diff --git a/docs/job-trigger-context.md b/docs/job-trigger-context.md index deccbb31..d716b54f 100644 --- a/docs/job-trigger-context.md +++ b/docs/job-trigger-context.md @@ -14,7 +14,7 @@ The available value beneath a slug is: | Trigger | Fields | | --- | --- | -| Manual | `prompt` | +| Manual | `prompt`, `data` | | Schedule | `scheduled_at`, `cron`, `timezone` | | Linear webhook | Complete Linear delivery, plus `provider`, `event`, `delivery_id` | | GitHub webhook | Complete GitHub delivery, plus `provider`, `event`, `delivery_id` | @@ -30,3 +30,5 @@ Run inspection returns `context` as the complete persisted object and `invocatio Every webhook trigger may also define `handlerCode` containing one synchronous `function handler(webhook)` declaration. Factorize runs it only after provider authentication and trigger scoping, inside an isolated Worker with no bindings or outbound network access. Returning `false` rejects the delivery, `true` retains the default value above, and a JSON-compatible object replaces that value beneath the stable trigger slug. Timeouts, exceptions, and invalid return values are recorded in webhook activity and never create a run. REST `POST /api/v1/job-handlers/test` and MCP `test_job_webhook_handler` exercise the same isolation boundary without creating an invocation. Prompt and run-name templates render plain text: double-brace substitutions preserve URLs, quotes, Markdown, and code without HTML entity escaping. Triple-brace substitutions remain supported. Literal entity text in job context is preserved, not decoded. The web UI escapes rendered values when displaying them. This applies to new runs; existing persisted prompts are unchanged. + +Object and array substitutions insert compact JSON, including nested values: `{{trigger-1}}` inserts the complete trigger context and `{{trigger-1.data}}` inserts the complete manual data object. Object keys are sorted recursively (integer keys follow JSON's numeric ordering); array order is preserved. Nested nulls render as JSON `null`; a directly interpolated null or missing value remains empty, as in Mustache. Primitive values remain raw text. Sections still use the original context for truthiness, object scopes, and array iteration. diff --git a/packages/app/src/text-template.ts b/packages/app/src/text-template.ts index aaf5d79e..e55b9637 100644 --- a/packages/app/src/text-template.ts +++ b/packages/app/src/text-template.ts @@ -1,6 +1,32 @@ import Mustache from "mustache"; +/** + * Compact JSON with recursively sorted object keys (integer keys retain JSON's + * numeric ordering), array order preserved, and nested nulls retained. + * Other values follow JSON.stringify's standard JSON conversion rules. + */ +function interpolationText(value: unknown): string { + if (value == null) return ""; + if (typeof value !== "object") return String(value); + return JSON.stringify(value, (_key, entry) => { + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return entry; + return Object.fromEntries(Object.keys(entry).sort().map(key => [key, entry[key]])); + }); +} + +// Normalize only interpolations: section truthiness, iteration, and dotted +// lookups must continue to operate on the original structured context. +class TextWriter extends Mustache.Writer { + override unescapedValue(token: string[], context: Mustache.Context): string { + return interpolationText(context.lookup(token[1])); + } + + override escapedValue(token: string[], context: Mustache.Context): string { + return this.unescapedValue(token, context); + } +} + /** Agent input and display names are plain text; HTML escaping belongs at the UI boundary. */ export function renderTextTemplate(template: string, context: Record): string { - return Mustache.render(template, context, undefined, { escape: (value: string) => value }); + return new TextWriter().render(template, context); } diff --git a/packages/app/src/trigger-context.ts b/packages/app/src/trigger-context.ts index 10868a36..aa939649 100644 --- a/packages/app/src/trigger-context.ts +++ b/packages/app/src/trigger-context.ts @@ -11,7 +11,7 @@ const commonWebhook: ContextPath[] = [ export const triggerContextCatalog: Record = { manual: [ { path: "prompt", type: "string", description: "Prompt supplied by the manual invocation.", example: "Review the failing build" }, - { path: "data", type: "object", description: "JSON data supplied by the manual invocation." }, + { path: "data", type: "object", description: "Complete manual JSON data; interpolate this path to insert the full object as JSON." }, ], schedule: [ { path: "scheduled_at", type: "string", description: "Scheduled occurrence as an ISO 8601 timestamp.", example: "2026-09-16T09:00:00.000Z" }, diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 4828418f..64ffab7b 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -39,7 +39,7 @@ export const loginPage = (marketingOrigin = "https://factorize.sh") => `Optional Mustache template; inactive triggers are false in conditional sections.';jobForm.querySelector('[name="promptTemplate"]')?.parentElement?.before(label)} +const jobForm=document.querySelector('#job');if(jobForm&&!jobForm.elements.namedItem('runNameTemplate')){const label=document.createElement('label');label.className='label relative mt-5 min-w-0';label.innerHTML='Run name templateOptional Mustache template; objects and arrays insert JSON. Inactive triggers are false in conditional sections.';jobForm.querySelector('[name="promptTemplate"]')?.parentElement?.before(label)} if(jobForm){const nativeFetch=window.fetch.bind(window);window.fetch=async(input,init)=>{if(init?.body&&new RegExp('^/api/v1/jobs(?:/|$)').test(String(input))){try{const body=JSON.parse(String(init.body));body.runNameTemplate=jobForm.elements.namedItem('runNameTemplate')?.value||'';init={...init,body:JSON.stringify(body)}}catch{}}return nativeFetch(input,init)}} const syncThemeButton=()=>{const dark=document.documentElement.classList.contains('dark');themeIcon.textContent=dark?'☀':'☾';themeToggle.setAttribute('aria-label',dark?'Use light mode':'Use dark mode')}; themeToggle.addEventListener('click',()=>{const dark=!document.documentElement.classList.contains('dark');document.documentElement.classList.toggle('dark',dark);try{localStorage.setItem('factorize-theme',dark?'dark':'light')}catch{}syncThemeButton()});syncThemeButton(); @@ -131,8 +131,8 @@ let slugEdited=Boolean(jobId);const jobSlug=value=>value.trim().toLowerCase().re const kinds={manual:'Manual',schedule:'Schedule',linear:'Linear',clickup:'ClickUp',github:'GitHub Issues',cloudflareTail:'Cloudflare Tail',jobLifecycle:'Job lifecycle'}; const providerKind=t=>t.kind==='webhook'?t.config.provider:t.kind; const reflection=t=>t.reflection?.paths||contextCatalog[providerKind(t)]||[]; -const triggerHints=()=>triggers.map(t=>({path:t.slug+'.*',type:'context',description:kinds[providerKind(t)]+' trigger context'})); -const contextPaths=()=>triggers.flatMap(t=>[{path:t.slug+'.*',type:'context',description:kinds[providerKind(t)]+' trigger context'},...reflection(t).filter(x=>x.path!=='*').map(x=>({path:t.slug+'.'+x.path,type:x.type,description:x.description}))]); +const triggerHints=()=>triggers.map(t=>({path:t.slug,type:'object',description:'Complete '+kinds[providerKind(t)]+' trigger context as JSON'})); +const contextPaths=()=>triggers.flatMap(t=>[{path:t.slug,type:'object',description:'Complete '+kinds[providerKind(t)]+' trigger context as JSON'},...reflection(t).filter(x=>x.path!=='*').map(x=>({path:t.slug+'.'+x.path,type:x.type,description:x.description}))]); const nameOf=(items,id)=>items.find(x=>String(x.id)===String(id))?.name||String(id||'Not selected'); const simpleSchedule=c=>{if(c.timezone!=='UTC')return null;const cron=(c.cron||'').trim(),minutes=cron.match(/^\\*\\/(\\d+) \\* \\* \\* \\*$/),hours=cron.match(/^0 \\*\\/(\\d+) \\* \\* \\*$/);if(cron==='* * * * *')return {unit:'minutes',value:1};if(cron==='0 * * * *')return {unit:'hours',value:1};if(minutes&&Number(minutes[1])>=1&&Number(minutes[1])<=59)return {unit:'minutes',value:Number(minutes[1])};if(hours&&Number(hours[1])>=1&&Number(hours[1])<=23)return {unit:'hours',value:Number(hours[1])};return null}; function simpleCron(){const unit=triggerForm.elements.intervalUnit.value,value=Number(triggerForm.elements.intervalValue.value),max=unit==='minutes'?59:23;if(!Number.isInteger(value)||value<1||value>max)throw new Error('Enter an interval from 1 to '+max+' '+unit+'.');return unit==='minutes'?'*/'+value+' * * * *':'0 */'+value+' * * *'} diff --git a/packages/app/test/job-domain.test.ts b/packages/app/test/job-domain.test.ts index 197e05a8..68504cfc 100644 --- a/packages/app/test/job-domain.test.ts +++ b/packages/app/test/job-domain.test.ts @@ -32,6 +32,44 @@ describe("job invocation domain", () => { expect(Mustache.render("{{value}}", { value: "