From dadf5a76f31dc3a23170fa452bb668f249fd374a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 07:46:23 -0800 Subject: [PATCH 1/2] improvement(workflow-code): remove agent traps from table keys, Function results, resume ids and builder names --- .../content/docs/workflows/code/syntax.mdx | 2 +- ...pply-workflow-source.skills.integration.ts | 4 +- .../read-source-resources.integration.ts | 2 +- .../workspaces/resource-keys.integration.ts | 29 ++++ apps/sim/lib/workspaces/resource-keys.test.ts | 6 + apps/sim/lib/workspaces/resource-keys.ts | 28 +++- .../protocol/workflow-run-get.test.ts | 20 +++ .../commands/protocol/workflow-run-wait.ts | 4 +- packages/sim-cli/src/contract/commands.ts | 1 + .../sim-cli/src/runtime/paused-run.test.ts | 36 +++++ packages/sim-cli/src/runtime/paused-run.ts | 62 +++++++++ packages/sim-cli/src/runtime/result.ts | 11 +- packages/workflow-code/DESIGN.md | 6 +- packages/workflow-code/src/compile/SYNTAX.md | 6 +- .../workflow-code/src/compile/checks.test.ts | 14 ++ .../src/compile/function-returns.ts | 83 ++++++++---- packages/workflow-code/src/compile/hints.ts | 62 ++++++++- packages/workflow-code/src/compile/scope.ts | 15 ++- packages/workflow-code/src/compile/tools.ts | 3 +- .../workflow-code/src/json-fields.test.ts | 126 ++++++++++++++++++ packages/workflow-code/src/json-fields.ts | 38 +++++- .../src/codegen/reference.test.ts | 25 +++- .../workflow-sdk/src/codegen/reference.ts | 3 +- 23 files changed, 531 insertions(+), 55 deletions(-) create mode 100644 packages/sim-cli/src/runtime/paused-run.test.ts create mode 100644 packages/sim-cli/src/runtime/paused-run.ts diff --git a/apps/docs/content/docs/workflows/code/syntax.mdx b/apps/docs/content/docs/workflows/code/syntax.mdx index a4776d4dfe2..e75b027d727 100644 --- a/apps/docs/content/docs/workflows/code/syntax.mdx +++ b/apps/docs/content/docs/workflows/code/syntax.mdx @@ -196,7 +196,7 @@ A secret is never printed. A literal value in a password field prints as `stored ### JSON fields -A field that holds JSON text, such as `responseFormat`, a table row's `data` or a response body, takes an object or array literal and stores it as formatted JSON. Each bare reference inside is quoted when the output is a string and left bare otherwise, because the run splices a string raw and any other value as JSON. A field of a Function's `result` has the type its JavaScript certainly returns there (a string literal, `String(…)`, `.toISOString().slice(…)` and the like are text; arithmetic, comparisons and literals are not). A reference no output type is known for is stored bare with `W_JSON_REF_UNTYPED`. A template is a JSON string, which is how a value becomes text on purpose. A resource helper inside the literal is `E_UNSUPPORTED_SYNTAX`. +A field that holds JSON text, such as `responseFormat`, a table row's `data` or a response body, takes an object or array literal and stores it as formatted JSON. Each bare reference inside is quoted when the output is a string and left bare otherwise, because the run splices a string raw and any other value as JSON. A Function's `result`, or a field of it, has the type its JavaScript certainly returns there (a string literal, `String(…)`, `.toISOString().slice(…)` and the like are text; arithmetic, comparisons and literals are not); a Function `result` or an API `data` whose code or response may be text is untyped unless the code says. A reference no output type is known for is stored bare with `W_JSON_REF_UNTYPED`. A template is a JSON string, which is how a value becomes text on purpose. A resource helper inside the literal is `E_UNSUPPORTED_SYNTAX`. ### Input formats and tools diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.skills.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-source.skills.integration.ts index ca1f0c26c33..ee04254a263 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.skills.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.skills.integration.ts @@ -297,7 +297,7 @@ check( const written = edit( edit(source.files, 'skills: []', "skills: [skill('listed-only')]"), 'tools: []', - "tools: [customTool('listed-lookup')]" + "tools: [customTool('listed_lookup')]" ) written['workflow.ts'] = written['workflow.ts'].replace( /^import \{ /m, @@ -313,7 +313,7 @@ check( ]) expect(manifest.skills).toContainEqual({ key: 'listed-only', id: skillId, name: 'Listed only' }) expect(manifest.customTools).toContainEqual({ - key: 'listed-lookup', + key: 'listed_lookup', id: toolId, name: 'listed_lookup', }) diff --git a/apps/sim/lib/workflows/application/read-source-resources.integration.ts b/apps/sim/lib/workflows/application/read-source-resources.integration.ts index db6572560e7..1f343161659 100644 --- a/apps/sim/lib/workflows/application/read-source-resources.integration.ts +++ b/apps/sim/lib/workflows/application/read-source-resources.integration.ts @@ -401,7 +401,7 @@ describe('source resources manifest', () => { { key: 'tone', id: ids.laterSkill, name: 'Tone' }, ]) expect(manifest.customTools).toEqual([ - { key: 'lookup-order', id: ids.customTool, name: 'lookup_order' }, + { key: 'lookup_order', id: ids.customTool, name: 'lookup_order' }, ]) }) diff --git a/apps/sim/lib/workspaces/resource-keys.integration.ts b/apps/sim/lib/workspaces/resource-keys.integration.ts index 9a95fc5604a..3b3797f3ccd 100644 --- a/apps/sim/lib/workspaces/resource-keys.integration.ts +++ b/apps/sim/lib/workspaces/resource-keys.integration.ts @@ -181,6 +181,35 @@ describe('workspace resource keys against PostgreSQL', () => { expect(new Set(keys)).toEqual(new Set(['invoices', 'invoices-2', 'invoices-3'])) }) + it('keys a name with underscores by its own spelling, apart from the hyphenated one', async () => { + const underscored = generateId() + const hyphenated = generateId() + await insertTable(underscored, workspaceId, 'daily_totals', at(40)) + await insertTable(hyphenated, workspaceId, 'daily-totals', at(41)) + + expect(await keyOf('table', hyphenated)).toBe('daily-totals') + expect(await keyOf('table', underscored)).toBe('daily_totals') + expect(await idOf('table', 'daily_totals')).toBe(underscored) + }) + + it('suffixes an underscored name whose key is taken, and leaves a persisted hyphen key alone', async () => { + const legacy = generateId() + const first = generateId() + const second = generateId() + await insertTable(legacy, workspaceId, 'weekly-totals', at(42)) + expect(await keyOf('table', legacy)).toBe('weekly-totals') + await db + .update(userTableDefinitions) + .set({ name: 'weekly_totals' }) + .where(eq(userTableDefinitions.id, legacy)) + await insertTable(first, workspaceId, 'monthly_totals', at(43)) + await insertTable(second, workspaceId, 'Monthly_Totals!', at(44)) + + expect(await keyOf('table', legacy)).toBe('weekly-totals') + expect(await keyOf('table', first)).toBe('monthly_totals') + expect(await keyOf('table', second)).toBe('monthly_totals-2') + }) + it('keeps every kind’s key through a rename', async () => { const ids = { table: generateId(), diff --git a/apps/sim/lib/workspaces/resource-keys.test.ts b/apps/sim/lib/workspaces/resource-keys.test.ts index 0624a987a1b..b14bcc64e29 100644 --- a/apps/sim/lib/workspaces/resource-keys.test.ts +++ b/apps/sim/lib/workspaces/resource-keys.test.ts @@ -8,6 +8,12 @@ describe('resourceKeyBase', () => { expect(resourceKeyBase('table', 'Leads (EU)!')).toBe('leads-eu') }) + it('keeps the underscores of a name, the spelling its author types', () => { + expect(resourceKeyBase('table', 'daily_totals')).toBe('daily_totals') + expect(resourceKeyBase('table', 'Daily_Totals (v2)')).toBe('daily_totals-v2') + expect(resourceKeyBase('table', '_scratch_')).toBe('scratch') + }) + it('keys a name with no slug characters by its kind', () => { expect(resourceKeyBase('knowledge-base', '***')).toBe('knowledge-base') expect(resourceKeyBase('credential', '')).toBe('credential') diff --git a/apps/sim/lib/workspaces/resource-keys.ts b/apps/sim/lib/workspaces/resource-keys.ts index c2a4ce40495..160c1c0a5c6 100644 --- a/apps/sim/lib/workspaces/resource-keys.ts +++ b/apps/sim/lib/workspaces/resource-keys.ts @@ -13,7 +13,7 @@ import { } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { generateId } from '@sim/utils/id' -import { compareStrings, slugify } from '@sim/utils/string' +import { compareStrings, escapeLikePattern } from '@sim/utils/string' import type { ResourceKind } from '@sim/workflow-code' import { and, asc, eq, inArray, isNull, like, or } from 'drizzle-orm' import { OrchestrationError } from '@/lib/core/orchestration/types' @@ -203,12 +203,24 @@ function trimKey(value: string, maxLength: number): string { } /** - * The key a resource is first offered: its name's slug, or the kind when the name has no slug - * characters; prefixed with the kind when the slug starts with a digit, and cut to the key - * length. Always matches the stored key format `^[a-z][a-z0-9_-]{0,63}$`. + * A name's key characters: lowercased, with every run of other characters one hyphen and no + * leading or trailing separator. Underscores stay, so a table named `daily_totals` is keyed + * `daily_totals`, the spelling its author will type. + */ +function keySlug(name: string): string { + return name + .toLowerCase() + .replace(/[^a-z0-9_]+/g, '-') + .replace(/^[-_]+|[-_]+$/g, '') +} + +/** + * The key a resource is first offered: its name's slug (underscores kept), or the kind when the + * name has no slug characters; prefixed with the kind when the slug starts with a digit, and cut + * to the key length. Always matches the stored key format `^[a-z][a-z0-9_-]{0,63}$`. */ export function resourceKeyBase(kind: ResourceKind, name: string): string { - const slug = slugify(name) + const slug = keySlug(name) const base = slug === '' ? kind : /^[a-z]/.test(slug) ? slug : `${kind}-${slug}` return trimKey(base, MAX_KEY_LENGTH) } @@ -309,7 +321,11 @@ async function readTakenKeys( and( eq(workspaceResourceKey.workspaceId, workspaceId), eq(workspaceResourceKey.kind, kind), - or(...prefixes.map((prefix) => like(workspaceResourceKey.key, `${prefix}%`))) + or( + ...prefixes.map((prefix) => + like(workspaceResourceKey.key, `${escapeLikePattern(prefix)}%`) + ) + ) ) ) return new Set(rows.map((row) => row.key)) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts index 766f7e8d86a..8e19ee28677 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts @@ -112,3 +112,23 @@ describe('sim workflows runs get --select-output', () => { expect(request.mock.calls.map(([path]) => path)).toEqual([STATE_PATH]) }) }) + +describe('sim workflows runs get on a paused run', () => { + it('prints the exact resume command beside the run, additively', async () => { + const run = { + runId: RUN_ID, + workflowId: WORKFLOW_ID, + status: 'paused', + paused: { contextId: 'ctx_1', pauseKind: 'human' }, + } + answer({ data: run }) + const out = stdout() + + await get() + + expect(JSON.parse(out())).toEqual({ + ...run, + next: `sim workflows runs resume ${RUN_ID} --workflow ${WORKFLOW_ID} --context ctx_1`, + }) + }) +}) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts b/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts index c6bdd2f07e2..b3bf3546156 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts @@ -10,6 +10,7 @@ import { STILL_RUNNING_EXIT_CODE } from '../../exit-codes' import { V2_OPERATIONS } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { apiCommand, type Connection } from '../../runtime/called-operations' +import { resumeCommand } from '../../runtime/paused-run' import { renderResult } from '../../runtime/result' /** @@ -197,8 +198,7 @@ function explain( if (outcome === 'completed') return null if (outcome === 'failed') return `Run ${runId} failed.` if (outcome === 'cancelled') return `Run ${runId} was cancelled.` - const context = snapshot.contextId ? ` --context ${snapshot.contextId}` : '' - return `Run ${runId} is paused waiting for input. Resume it: sim workflows runs resume ${runId} --workflow ${workflowId}${context}` + return `Run ${runId} is paused waiting for input. Resume it: ${resumeCommand(runId, workflowId, snapshot.contextId)}` } /** diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 025a641df5b..d9c5efd99f5 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -2459,6 +2459,7 @@ To read what a block is set to, use \`sim workflows outline\` or \`sim workflows { header: 'resume at', path: 'paused.resumeAt', format: 'timestamp' }, { header: 'blocked on', path: 'paused.blockedOnBlockId' }, { header: 'pause points', path: 'paused.pausePointCount' }, + { header: 'next', path: 'next' }, { header: 'error', path: 'error.message' }, ], }, diff --git a/packages/sim-cli/src/runtime/paused-run.test.ts b/packages/sim-cli/src/runtime/paused-run.test.ts new file mode 100644 index 00000000000..19bf10b2ab3 --- /dev/null +++ b/packages/sim-cli/src/runtime/paused-run.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import { withResumeNext } from './paused-run' + +const paused = { + runId: 'run_top', + workflowId: 'wf_1', + status: 'paused', + output: { response: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } } }, +} + +describe('withResumeNext', () => { + it('names the exact resume command, with the pause context and the execution its links name', () => { + expect(withResumeNext('executeWorkflow', paused)).toEqual({ + ...paused, + next: 'sim workflows runs resume exec_9 --workflow wf_1 --context ctx_9', + }) + }) + + it('falls back to the run id, and to the paused record context, when the output names none', () => { + expect(withResumeNext('executeWorkflow', { ...paused, output: null })).toMatchObject({ + next: 'sim workflows runs resume run_top --workflow wf_1', + }) + expect( + withResumeNext('getWorkflowRun', { ...paused, output: undefined, paused: { contextId: 'c' } }) + ).toMatchObject({ next: 'sim workflows runs resume run_top --workflow wf_1 --context c' }) + }) + + it('leaves a run that is not paused, another operation and an existing next as they were', () => { + const done = { ...paused, status: 'completed' } + expect(withResumeNext('executeWorkflow', done)).toBe(done) + expect(withResumeNext('listWorkflowRuns', paused)).toBe(paused) + const hinted = { ...paused, next: 'x' } + expect(withResumeNext('executeWorkflow', hinted)).toBe(hinted) + expect(withResumeNext('executeWorkflow', null)).toBeNull() + }) +}) diff --git a/packages/sim-cli/src/runtime/paused-run.ts b/packages/sim-cli/src/runtime/paused-run.ts new file mode 100644 index 00000000000..d36329f2ebc --- /dev/null +++ b/packages/sim-cli/src/runtime/paused-run.ts @@ -0,0 +1,62 @@ +import { isRecordLike, toRecordOrNull } from '@sim/utils/object' +import type { V2OperationName } from '../generated/v2-api' + +/** Operations whose payload is a run record that may be paused. */ +const RUN_OPERATIONS: ReadonlySet = new Set(['executeWorkflow', 'getWorkflowRun']) + +/** Records visited in a paused run's output while looking for its resume links. */ +const SEARCH_BUDGET = 500 +const SEARCH_DEPTH = 6 + +interface ResumeLinks { + contextId: string + executionId: string +} + +/** + * The resume links a human-in-the-loop pause leaves in a run's output (`_resume`, or `resume` + * beside the response): the record holding both the pause's `contextId` and the `executionId` + * `runs resume` takes as its run. + */ +function findResumeLinks(output: unknown): ResumeLinks | null { + let visited = 0 + const search = (value: unknown, depth: number): ResumeLinks | null => { + if (!isRecordLike(value) || depth > SEARCH_DEPTH || visited++ >= SEARCH_BUDGET) return null + if (typeof value.contextId === 'string' && typeof value.executionId === 'string') { + return { contextId: value.contextId, executionId: value.executionId } + } + for (const child of Object.values(value)) { + const found = search(child, depth + 1) + if (found) return found + } + return null + } + return search(output, 0) +} + +/** The command that resumes a paused run, with the pause's context when it is known. */ +export function resumeCommand(runId: string, workflowId: string, contextId: string | null): string { + const context = contextId ? ` --context ${contextId}` : '' + return `sim workflows runs resume ${runId} --workflow ${workflowId}${context}` +} + +/** + * A run record with `next` added when it is paused for input: the exact `runs resume` command, + * since the record carries two ids (`runId` and the output's `_resume.executionId`) and a context + * a reader would otherwise have to pair up. `runs resume` takes the run the pause belongs to, + * which is `_resume.executionId` when the output names one. Any other payload comes back as it + * was, and so does one that already has a `next`. + */ +export function withResumeNext(operation: V2OperationName, payload: unknown): unknown { + if (!RUN_OPERATIONS.has(operation) || !isRecordLike(payload)) return payload + if (payload.status !== 'paused' || 'next' in payload) return payload + if (typeof payload.runId !== 'string' || typeof payload.workflowId !== 'string') return payload + const links = findResumeLinks(payload.output) + const paused = toRecordOrNull(payload.paused) + const contextId = + links?.contextId ?? (typeof paused?.contextId === 'string' ? paused.contextId : null) + return { + ...payload, + next: resumeCommand(links?.executionId ?? payload.runId, payload.workflowId, contextId), + } +} diff --git a/packages/sim-cli/src/runtime/result.ts b/packages/sim-cli/src/runtime/result.ts index bc05e727868..9b6f16ff541 100644 --- a/packages/sim-cli/src/runtime/result.ts +++ b/packages/sim-cli/src/runtime/result.ts @@ -17,6 +17,10 @@ import { timestamp, } from '../output/render' import { printTraceSpans } from '../output/trace' +import { withResumeNext } from './paused-run' + +/** Result fields holding a command to run, printed whole (a clipped flag would make it wrong). */ +const RUN_COMMAND_FIELDS: ReadonlySet = new Set(['next']) interface RenderResultOptions { expandedTrace?: boolean @@ -437,7 +441,10 @@ export function renderResult( // The single-key unwrap exists for the human table: `{ mcpServer: {...} }` rendered as-is // printed nothing. Machine formats print the API's data verbatim, so `--output json` // matches the OpenAPI shape the docs and the agent reference card are generated from. - const data = format === 'json' || format === 'yaml' ? raw : unwrapResource(raw) + const data = withResumeNext( + operation, + format === 'json' || format === 'yaml' ? raw : unwrapResource(raw) + ) if (spec.itemsPath) { const items = at(data, spec.itemsPath) if (!Array.isArray(items)) { @@ -467,7 +474,7 @@ export function renderResult( ? inferredFields(data, spec.dataKeys === true) : [] - printRecord(format, fields, data) + printRecord(format, fields, data, RUN_COMMAND_FIELDS) if (spec.expandedTrace && options.expandedTrace) { const traceSpans = at(data, 'traceSpans') if (!Array.isArray(traceSpans)) { diff --git a/packages/workflow-code/DESIGN.md b/packages/workflow-code/DESIGN.md index a3463565c12..4637f9c8a4b 100644 --- a/packages/workflow-code/DESIGN.md +++ b/packages/workflow-code/DESIGN.md @@ -401,8 +401,10 @@ A JSON code field (a `code` subBlock holding JSON text: an agent's `responseForm splices a reference's value into such text raw for a string and as JSON otherwise, so a bare reference in a literal is stored by its output type: quoted (`""`) when the catalog or the workflow types it `string`, bare (``) otherwise, and bare with `W_JSON_REF_UNTYPED` when -nothing types it. A Function's `result.` is typed by what its JavaScript certainly returns -there (`refValueKind` reads `function-returns.ts`), so a text field is quoted at compile and +nothing types it. An output the catalog types `json` or `any` that can hold text (a Function's +`result`, an HTTP `data`) is untyped unless the code says otherwise. A Function's `result` and +`result.` are typed by what its JavaScript certainly returns there (`refValueKind` reads +`function-returns.ts`), so a text field is quoted at compile and printed back as the bare reference. The runtime splice is not changed: a bare token outside a string is spliced raw by design (a string holding JSON text is nested on purpose), and the text is not valid JSON until the splice, so the resolver cannot tell where a value should be encoded. A string in the literal (a template or plain string) is always a JSON string. The diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index d9ab8226974..d7f91f6512e 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -224,8 +224,10 @@ written as an object or array literal compiles to `JSON.stringify(value, null, 2 reference is stored by its output type: quoted (`""`) when the catalog or the workflow types it `string`, bare (``) otherwise, because the executor splices a string raw and any other value as JSON. A Function `result` field its JavaScript certainly returns as text (`return { tier: 'gold' }`) is -quoted too, and one it returns as a non-string (`return { total: a + b }`) is bare. A reference -nothing types is stored bare with `W_JSON_REF_UNTYPED`, which is not raised for those, +quoted too, and one it returns as a non-string (`return { total: a + b }`) is bare; so is the whole +`result` when every `return` is text (`return new Date().toISOString()`) or none is. A reference +nothing types, including a whole Function `result` or HTTP `data` its code or response may make +text, is stored bare with `W_JSON_REF_UNTYPED`, which is not raised for those, nor, against a stored workflow, for a field the source left as stored. A template is a JSON string, which is how a value becomes text on purpose. A resource (`table('x')`, `credential()`, `file()`) or `raw(node)` is not data, so inside the literal it is `E_UNSUPPORTED_SYNTAX`. The printer writes a field's text back as the diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index 1727df19f64..0bf9c401d57 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -549,6 +549,20 @@ describe('an SDK export the file did not import', () => { }) }) +describe('a builder written as its block type', () => { + it('names the builder for a bare call and a namespaced one', () => { + const bare = run("const h = humanInTheLoop('Review', {})") + expect(findings(bare, 'E_UNKNOWN_BUILDER')[0]?.hint).toBe('Did you mean human?') + const dotted = run("const h = slack.send_message('Tell', {})") + expect(findings(dotted, 'E_UNKNOWN_BUILDER')[0]?.hint).toBe('Did you mean slack.sendMessage?') + }) + + it('leaves a call that is no builder an unsupported call', () => { + const result = run("const h = fetch('https://x')") + expect(findings(result, 'E_UNKNOWN_BUILDER')).toEqual([]) + }) +}) + describe('a misspelled required param', () => { it('reports the unknown param once, without a second W_REQUIRED_MISSING for its suggestion', () => { const result = run("const a = api('A', { urll: 'https://x' })") diff --git a/packages/workflow-code/src/compile/function-returns.ts b/packages/workflow-code/src/compile/function-returns.ts index e52e5ce30f2..37c98d83d38 100644 --- a/packages/workflow-code/src/compile/function-returns.ts +++ b/packages/workflow-code/src/compile/function-returns.ts @@ -1,12 +1,14 @@ /** - * What a Function block's `result` fields hold, read from the object literal its JavaScript code - * returns (`return { total: subtotal + tax, tier: 'gold' }`), so a bare reference to one in a JSON - * field is not reported as untyped when the code says it is a number, boolean, array or object. + * What a Function block's `result` holds, read from the JavaScript code: the whole value + * (`return new Date().toISOString()` is text, `return [1, 2]` is not), and the fields of the object + * literal it returns (`return { total: subtotal + tax, tier: 'gold' }`), so a bare reference to + * either in a JSON field is typed when the code says whether it is text. * - * The reading is deliberately narrow: every `return` outside a nested function must return an - * object literal, and a field counts only when each of them sets it to an expression whose kind - * is certain (a literal, arithmetic, a comparison, `String(…)`, the `.length` of a string or an - * array, a local variable never + * The reading is deliberately narrow. The whole value counts only when every `return` outside a + * nested function yields an expression of one kind and the code ends in a `return` or `throw` + * (falling off the end returns nothing). A field counts only when every `return` is an object + * literal and each sets it to an expression whose kind is certain (a literal, arithmetic, a + * comparison, `String(…)`, the `.length` of a string or an array, a local variable never * reassigned to another kind, …). Anything else stays unknown, and the reference keeps its * warning: a wrong "typed" would store a string bare and break the JSON at run time. */ @@ -109,8 +111,16 @@ const COMPARISON: ReadonlySet = new Set([ 'instanceof', ]) -/** Each function block's returned field kinds, read once per compiled block object. */ -const cache = new WeakMap | null>() +/** What a Function's code returns: the whole value's kind, and the kinds of an object's fields. */ +interface ReturnedKinds { + /** The kind of `result` itself, when every `return` agrees on one and none can be skipped. */ + whole: ReturnedKind | undefined + /** The fields every `return` sets, when each returns an object literal; empty otherwise. */ + fields: ReadonlyMap +} + +/** Each function block's returned kinds, read once per compiled block object. */ +const cache = new WeakMap() function isFunctionNode(node: Node): boolean { return ( @@ -435,8 +445,29 @@ function returnedFields( return fields } -/** The field kinds a function body's returns agree on, or `null` when any return is no literal. */ -function readReturns(code: string): ReadonlyMap | null { +/** + * The kind of the whole returned value: what every `return` yields, when they agree and the code + * cannot finish without one (it ends in a `return` or `throw`), since falling off the end returns + * nothing. + */ +function wholeKind( + program: Node, + returns: ReadonlyArray, + inference: Inference +): ReturnedKind | undefined { + const last = program.type === 'Program' ? program.body.at(-1) : undefined + if (last?.type !== 'ReturnStatement' && last?.type !== 'ThrowStatement') return undefined + let agreed: JsKind | undefined + for (const [index, argument] of returns.entries()) { + const kind = inference.kind(argument) + agreed = index === 0 ? kind : merge(agreed, kind) + if (agreed === undefined) return undefined + } + return agreed === undefined ? undefined : agreed === 'string' ? 'string' : 'typed' +} + +/** The field kinds a function body's returns agree on, or none when any return is no literal. */ +function readReturns(code: string): ReturnedKinds | null { let program: Node try { const file = parse(toCodeFile(code, 'javascript'), { @@ -456,9 +487,13 @@ function readReturns(code: string): ReadonlyMap | null { }) if (returns.length === 0) return null const inference = new Inference(collectBindings(program)) + const whole = wholeKind(program, returns, inference) + const objects = returns.filter((argument) => argument?.type === 'ObjectExpression') + const kinds = new Map() + if (objects.length !== returns.length) return { whole, fields: kinds } let agreed: Map | null = null - for (const argument of returns) { - if (argument?.type !== 'ObjectExpression') return null + for (const argument of objects) { + if (argument?.type !== 'ObjectExpression') continue const fields = returnedFields(argument, inference) if (agreed === null) { agreed = fields @@ -468,36 +503,38 @@ function readReturns(code: string): ReadonlyMap | null { agreed.set(key, fields.has(key) ? merge(kind, fields.get(key)) : undefined) } } - const kinds = new Map() for (const [key, kind] of agreed ?? []) { if (kind !== undefined) kinds.set(key, kind === 'string' ? 'string' : 'typed') } - return kinds + return { whole, fields: kinds } } /** - * The kind of `result.` of a JavaScript Function block, from the object literal its code - * returns; `undefined` for any other block, path or language, or when the code does not say. + * The kind of a JavaScript Function block's `result` (path `['result']`), from what every + * `return` yields, or of `result.`, from the object literal its code returns; `undefined` + * for any other block, path or language, or when the code does not say. */ function functionResultKind( block: CanonicalBlock, path: readonly string[] ): ReturnedKind | undefined { - if (block.type !== FUNCTION_TYPE || path.length !== 2 || path[0] !== 'result') return undefined - let fields = cache.get(block) - if (fields === undefined) { + if (block.type !== FUNCTION_TYPE || path.length < 1 || path.length > 2 || path[0] !== 'result') { + return undefined + } + let kinds = cache.get(block) + if (kinds === undefined) { const code = getOwn(block.params, 'code') const language = getOwn(block.params, 'language') const javascript = language === undefined || (language.kind === 'value' && (language.value === 'javascript' || language.value === '')) - fields = + kinds = javascript && code?.kind === 'value' && typeof code.value === 'string' ? readReturns(code.value) : null - cache.set(block, fields) + cache.set(block, kinds) } - return fields?.get(path[1]) + return path.length === 1 ? kinds?.whole : kinds?.fields.get(path[1] ?? '') } /** diff --git a/packages/workflow-code/src/compile/hints.ts b/packages/workflow-code/src/compile/hints.ts index f2d838d6a1c..5f0abc6bcb4 100644 --- a/packages/workflow-code/src/compile/hints.ts +++ b/packages/workflow-code/src/compile/hints.ts @@ -1,4 +1,7 @@ import type { Node } from '@babel/types' +import { stripVersionSuffix } from '@sim/utils/string' +import type { BlockCatalog } from '../catalog/types' +import { catalogBlock, catalogBlockTypes, catalogBuildersOfType } from '../catalog/view' /** * The supported form for each rejected construct. Tests assert @@ -223,16 +226,71 @@ const BUILDER_ALIASES: Readonly> = { code: 'fn', } +/** A name as its letters only, so `humanInTheLoop`, `human_in_the_loop` and `Human in the Loop` agree. */ +function spelling(name: string): string { + return name.toLowerCase().replace(/[^a-z0-9]+/g, '') +} + +/** Replacement hops followed from a legacy block type to the one that supersedes it. */ +const MAX_REPLACEMENT_HOPS = 3 + +/** + * The builders `written` names under another spelling: a builder path in other letter case or + * separators (`table_upsert_row` for `table.upsertRow`), or a block type or display name whose + * builder is named otherwise (`humanInTheLoop`, `human_in_the_loop_v2` or "Human in the Loop" for + * `human`), following a legacy block to the one that replaces it. `paths` bounds the answer to + * builders the caller may write; empty when nothing matches. + */ +export function builderNamedLike( + catalog: BlockCatalog, + written: string, + paths: readonly string[] +): string[] { + const wanted = spelling(written) + if (wanted === '') return [] + const allowed = new Set(paths) + const sameSpelling = paths.filter((path) => spelling(path) === wanted) + if (sameSpelling.length > 0) return sameSpelling + const types = catalogBlockTypes(catalog).filter((type) => { + const block = catalogBlock(catalog, type) + return [type, stripVersionSuffix(type), block?.name ?? ''].some( + (name) => spelling(name) === wanted + ) + }) + const builders = new Set() + for (const found of types) { + let type = found + for (let hop = 0; hop < MAX_REPLACEMENT_HOPS; hop++) { + const replacedBy = catalogBlock(catalog, type)?.lifecycle?.sunset?.replacedBy + if (!replacedBy || !catalogBlock(catalog, replacedBy)) break + type = replacedBy + } + for (const [path] of catalogBuildersOfType(catalog, type)) { + if (allowed.has(path)) builders.add(path) + } + } + return [...builders] +} + /** How many builder paths a hint lists when nothing is close. */ const LISTED_BUILDERS = 15 /** * The hint for a builder path no catalog builder has, from most to least specific: the builder a - * common other name stands for (`http.request` → `api`), a builder of the same namespace whose method differs only by a synonymous verb (`postMessage` → `sendMessage`), + * block's or builder's other spelling names (`humanInTheLoop` → `human`, with a `catalog`), the + * builder a common other name stands for (`http.request` → `api`), a builder of the same namespace whose method differs only by a synonymous verb (`postMessage` → `sendMessage`), * the closest path by edit distance, the one builder of the namespace whose method starts with the * written one, the namespace's builders listed (those it starts first), else the closest namespace. */ -export function suggestBuilder(written: string, paths: readonly string[]): string | undefined { +export function suggestBuilder( + written: string, + paths: readonly string[], + catalog?: BlockCatalog +): string | undefined { + const named = catalog ? builderNamedLike(catalog, written, paths) : [] + if (named.length > 0) { + return `Did you mean ${named.length === 1 ? named[0] : `one of ${named.slice(0, LISTED_BUILDERS).join(', ')}`}?` + } const alias = BUILDER_ALIASES[(written.split('.')[0] ?? written).toLowerCase()] if (alias !== undefined && paths.includes(alias)) return `Did you mean ${alias}?` const dot = written.lastIndexOf('.') diff --git a/packages/workflow-code/src/compile/scope.ts b/packages/workflow-code/src/compile/scope.ts index 3e9e95cb7f2..750aeaf8f1c 100644 --- a/packages/workflow-code/src/compile/scope.ts +++ b/packages/workflow-code/src/compile/scope.ts @@ -30,7 +30,7 @@ import { type Scope, unsupported, } from './context' -import { closest, HINTS, hintForNode, nodeLabel, suggestBuilder } from './hints' +import { builderNamedLike, closest, HINTS, hintForNode, nodeLabel, suggestBuilder } from './hints' import { calleePath, SDK_VALUE_FUNCTIONS } from './values' type CallClass = @@ -71,7 +71,7 @@ function classifyCall(ctx: CompileContext, scope: Scope, call: CallExpression): 'E_UNKNOWN_BUILDER', `${dotted} is not a block builder: ${path.root} is not an SDK namespace.`, rangeOf(ctx, call.callee), - { hint: suggestBuilder(dotted, catalogBuilderPaths(ctx.catalog)) } + { hint: suggestBuilder(dotted, catalogBuilderPaths(ctx.catalog), ctx.catalog) } ) } return { kind: 'builder', path: dotted, builder: { kind: 'unknown' } } @@ -82,7 +82,12 @@ function classifyCall(ctx: CompileContext, scope: Scope, call: CallExpression): ? [...catalogBuilderPaths(ctx.catalog), GENERIC_BUILDER, 'parallel'] : null const imported = bareBuilderPaths?.includes(path.root) === true - if (bareBuilderPaths && (imported || closest(path.root, bareBuilderPaths) !== null)) { + if ( + bareBuilderPaths && + (imported || + closest(path.root, bareBuilderPaths) !== null || + builderNamedLike(ctx.catalog, path.root, bareBuilderPaths).length > 0) + ) { // `apii('Call', { ... })`: a bare, builder-shaped call nothing binds, naming a builder or close // to one (`fetch('x')` stays an unsupported call). It classifies as an unknown builder so the // const still binds and its wiring raises no E_UNKNOWN_IDENTIFIER. @@ -93,7 +98,7 @@ function classifyCall(ctx: CompileContext, scope: Scope, call: CallExpression): 'E_UNKNOWN_BUILDER', `${path.root} is not a block builder.`, rangeOf(ctx, call.callee), - { hint: suggestBuilder(path.root, bareBuilderPaths) } + { hint: suggestBuilder(path.root, bareBuilderPaths, ctx.catalog) } ) } return { kind: 'builder', path: path.root, builder: { kind: 'unknown' } } @@ -150,7 +155,7 @@ function classifyCall(ctx: CompileContext, scope: Scope, call: CallExpression): 'E_UNKNOWN_BUILDER', `${dotted} is not a block builder.`, rangeOf(ctx, call.callee), - { hint: suggestBuilder(dotted, candidates) } + { hint: suggestBuilder(dotted, candidates, ctx.catalog) } ) return { kind: 'builder', path: dotted, builder: { kind: 'unknown' } } } diff --git a/packages/workflow-code/src/compile/tools.ts b/packages/workflow-code/src/compile/tools.ts index 3e2babde666..e3c27bf0132 100644 --- a/packages/workflow-code/src/compile/tools.ts +++ b/packages/workflow-code/src/compile/tools.ts @@ -233,7 +233,8 @@ function compileToolCall( hint: suggestBuilder( [path.root, ...path.rest].filter((segment) => segment !== 'tool').join('.'), - catalogBuilderPaths(ctx.catalog) + catalogBuilderPaths(ctx.catalog), + ctx.catalog ) ?? 'Write namespace.tool.method(params, options), or raw(tool).', }), blockKey: site.decl.key, diff --git a/packages/workflow-code/src/json-fields.test.ts b/packages/workflow-code/src/json-fields.test.ts index 96db98018aa..52d5718c0eb 100644 --- a/packages/workflow-code/src/json-fields.test.ts +++ b/packages/workflow-code/src/json-fields.test.ts @@ -317,3 +317,129 @@ describe('W_JSON_REF_UNTYPED on a Function block output', () => { expect(untyped("return { v: 'one' }", 'v', printed)).toEqual([]) }) }) + +describe('W_JSON_REF_UNTYPED on the whole of an output that can hold text', () => { + const WHOLE_IMPORTS = "import { api, fn, trigger, workflow } from '@sim/workflow-sdk'" + + /** Compiles a Function block with `code` whose whole `result` a JSON body uses bare. */ + function compile(code: string, ref = 'score.result', stored?: CanonicalWorkflow) { + const text = `// @sim-sdk 1\n${WHOLE_IMPORTS}\n\nexport default workflow('Test', {}, () => { + const start = trigger.start('Start') + const score = fn('Score', { code: ${JSON.stringify(code)} }) + const next = api('Next', { url: 'https://x', body: { v: ${ref} } }) + start.to(score) + score.to(next) +})\n` + return compileWorkflow({ + entry: { path: 'workflow.ts', text }, + files: new Map(), + catalog: TEST_CATALOG, + sdkMajor: 1, + ...(stored ? { stored } : {}), + }) + } + + const untyped = (code: string, ref?: string, stored?: CanonicalWorkflow) => + compile(code, ref, stored).diagnostics.filter((d) => d.code === 'W_JSON_REF_UNTYPED') + + const body = (code: string) => compile(code).workflow?.blocks.next?.params.body + + it('quotes a result every return makes text, so the string cannot break the JSON', () => { + const code = 'return new Date().toISOString().slice(0, 10)' + expect(untyped(code)).toEqual([]) + expect(body(code)).toEqual({ kind: 'value', value: '{\n "v": ""\n}' }) + expect(untyped("if ($ref.start.x) return 'a'\nreturn `b${1}`")).toEqual([]) + }) + + it('leaves bare a result every return makes a number, boolean, array or object', () => { + for (const code of [ + 'return 1 + 2', + 'return $ref.start.n > 3', + 'return [1, 2]', + "return { a: 'x' }", + 'if ($ref.start.x) return 1\nreturn true', + ]) { + expect(untyped(code), code).toEqual([]) + expect(body(code), code).toEqual({ kind: 'value', value: '{\n "v": \n}' }) + } + }) + + it('warns when nothing certain says whether the result is text', () => { + // An unread value, text in one return and not another, a path that returns nothing, and no return. + expect(untyped('return $ref.start.v')).toHaveLength(1) + expect(untyped("if ($ref.start.x) return 'a'\nreturn 1")).toHaveLength(1) + expect(untyped("if ($ref.start.x) return 'a'\nconst y = 2")).toHaveLength(1) + expect(untyped('if ($ref.start.x) return\nreturn 1')).toHaveLength(1) + expect(untyped('const y = 2')).toHaveLength(1) + expect(untyped('return { v: 1 ', 'score.result')).toHaveLength(1) + }) + + it('warns on an HTTP response body, which is text unless the response says it is JSON', () => { + const text = `// @sim-sdk 1\nimport { api, trigger, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Test', {}, () => { + const start = trigger.start('Start') + const get = api('Get', { url: 'https://x' }) + const next = api('Next', { url: 'https://x', body: { v: get.data, s: get.status } }) + start.to(get) + get.to(next) +})\n` + const result = compileWorkflow({ + entry: { path: 'workflow.ts', text }, + files: new Map(), + catalog: TEST_CATALOG, + sdkMajor: 1, + }) + expect( + result.diagnostics.filter((d) => d.code === 'W_JSON_REF_UNTYPED').map((d) => d.message) + ).toEqual([expect.stringContaining('')]) + }) + + it('on an apply, stays quiet on an unchanged JSON field, and warns once the code stops saying', () => { + const read = 'return $ref.start.v' + const printed = compile(read).workflow + if (!printed) throw new Error('the source did not compile') + expect(untyped(read, 'score.result', printed)).toEqual([]) + + const typed = compile('return 1').workflow + if (!typed) throw new Error('the source did not compile') + expect(untyped(read, 'score.result', typed)).toHaveLength(1) + }) + + describe('an output the catalog types any', () => { + const catalog: BlockCatalog = { + ...TEST_CATALOG, + blocks: { + ...TEST_CATALOG.blocks, + service: { + ...TEST_CATALOG.blocks.function, + type: 'service', + outputs: { id: { type: 'any' }, tags: { type: 'json' } }, + } as CatalogBlock, + }, + } + const service: CanonicalBlock = { + key: 'svc', + name: 'Svc', + type: 'service', + parent: null, + enabled: true, + locked: false, + triggerMode: false, + advancedMode: false, + errorPort: false, + retry: null, + params: {}, + modes: {}, + } + const kind = (token: string) => + refValueKind(token, { + catalog, + block: (key) => (key === 'svc' ? service : undefined), + variable: () => undefined, + }) + + it('is untyped, since it may be text, while a json output stays typed', () => { + expect(kind('')).toBe('untyped') + expect(kind('')).toBe('typed') + }) + }) +}) diff --git a/packages/workflow-code/src/json-fields.ts b/packages/workflow-code/src/json-fields.ts index 471ca3e2e57..6b6513d04aa 100644 --- a/packages/workflow-code/src/json-fields.ts +++ b/packages/workflow-code/src/json-fields.ts @@ -62,6 +62,32 @@ export interface RefTypeScope { const STRING_VARIABLE_TYPES: ReadonlySet = new Set(['string', 'plain']) +/** + * Outputs the catalog types `json` whose value can still be text: a Function returns whatever its + * code does, and an HTTP response is parsed only when it says it is JSON. A reference to the whole + * of one is `untyped` unless the Function's code says what it returns. A path inside one is + * never declared, so it is `untyped` already. + */ +const TEXT_CAPABLE_OUTPUTS: ReadonlyMap = new Map([ + ['function', 'result'], + ['api', 'data'], +]) + +/** Whether the declared output `segments` of a `blockType` block may hold text at run time. */ +function mayHoldText( + blockType: string, + declared: CatalogOutput, + segments: readonly RefSegment[] +): boolean { + if (declared.type === 'any') return true + const [first] = segments + return ( + segments.length === 1 && + first?.kind === 'name' && + TEXT_CAPABLE_OUTPUTS.get(blockType) === first.name + ) +} + function outputAt( outputs: Record, segments: RefSegment[] @@ -180,8 +206,9 @@ export function responseFormatFields(param: CanonicalParam | undefined): string[ * and the workflow say: `string`, `typed` (any other declared type), or `untyped` when nothing * declares it (a path into untyped JSON, a loop item, an unknown block). An environment variable * is a string; a variable goes by its type; a block output by its declared output type, else by - * the field its dynamic outputs declare, or for a Function's `result.` by what its - * JavaScript certainly returns there. + * the field its dynamic outputs declare, or for a Function's `result` by what its JavaScript + * certainly returns there. An output that can hold text though the catalog types it `json` or + * `any` (a Function's `result`, an HTTP `data`) is `untyped` unless the code says otherwise. */ export function refValueKind(token: string, scope: RefTypeScope): RefValueKind { if (token.startsWith('{{')) return 'string' @@ -215,10 +242,13 @@ export function refValueKind(token: string, scope: RefTypeScope): RefValueKind { }, }) const found = outputAt(outputs, segments) - if (found) return found.type === 'string' ? 'string' : 'typed' - // A Function's `result.` is typed by the object literal its JavaScript returns. + // A Function's `result`, or `result.`, is typed by what its JavaScript returns. const returned = referencedResultKind(token, scope.block) if (returned) return returned + if (found) { + if (found.type === 'string') return 'string' + return mayHoldText(block.type, found, segments) ? 'untyped' : 'typed' + } if (declared.dynamicOutputs) { const { source, param } = declared.dynamicOutputs const field = dynamicFieldName(source, segments) diff --git a/packages/workflow-sdk/src/codegen/reference.test.ts b/packages/workflow-sdk/src/codegen/reference.test.ts index 0b29f448a20..98069665471 100644 --- a/packages/workflow-sdk/src/codegen/reference.test.ts +++ b/packages/workflow-sdk/src/codegen/reference.test.ts @@ -3,7 +3,7 @@ import { join } from 'node:path' import type { BlockCatalog } from '@sim/workflow-code' import { catalogBuilderPaths } from '@sim/workflow-code/catalog/view' import { describe, expect, it } from 'vitest' -import { builderSnippet, describeBuilder } from './reference' +import { builderSnippet, describeBuilder, lookupBuilder } from './reference' /** A real catalog projected from registry blocks, shared with the SDK's own type checks. */ const CATALOG = JSON.parse( @@ -41,3 +41,26 @@ describe('builder reference', () => { } }) }) + +describe('lookupBuilder for a name the SDK spells differently', () => { + const hint = (query: string) => { + const found = lookupBuilder(CATALOG, query) + return found.kind === 'missing' ? found.hint : found.kind + } + + it('names the builder written for a block type in another spelling', () => { + for (const query of ['humanInTheLoop', 'human_in_the_loop', 'Human-In-The-Loop']) { + expect(hint(query), query).toBe('Did you mean human?') + } + expect(lookupBuilder(CATALOG, 'human_in_the_loop_v2').kind).toBe('builder') + }) + + it('names a builder path written in another case or with other separators', () => { + expect(hint('table_upsert_row')).toBe('Did you mean table.upsertRow?') + expect(hint('Table.UpsertRow')).toBe('Did you mean table.upsertRow?') + }) + + it('still reports nothing for a name that is neither', () => { + expect(hint('humanOutOfTheLoop')).not.toBe('Did you mean human?') + }) +}) diff --git a/packages/workflow-sdk/src/codegen/reference.ts b/packages/workflow-sdk/src/codegen/reference.ts index b451a489276..6e1bc55626f 100644 --- a/packages/workflow-sdk/src/codegen/reference.ts +++ b/packages/workflow-sdk/src/codegen/reference.ts @@ -166,7 +166,8 @@ export function lookupBuilder(catalog: BlockCatalog, query: string): BuilderLook } const hint = suggestBuilder( key, - paths.filter((path) => !isLegacyBuilder(path)) + paths.filter((path) => !isLegacyBuilder(path)), + catalog ) return hint ? { kind: 'missing', hint } : { kind: 'missing' } } From edd1b40f70f483d4538fa563abcbefb6bc34520b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 08:35:31 -0800 Subject: [PATCH 2/2] fix(sim-cli): read resume links only from the server's marker locations and quote the printed resume command --- .../protocol/workflow-run-wait.test.ts | 15 +++ .../commands/protocol/workflow-run-wait.ts | 13 ++- .../sim-cli/src/runtime/paused-run.test.ts | 57 +++++++++- packages/sim-cli/src/runtime/paused-run.ts | 100 ++++++++++++------ 4 files changed, 143 insertions(+), 42 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-wait.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-wait.test.ts index 0a9fb14ffa3..a8d37bf7a0c 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-wait.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-wait.test.ts @@ -72,6 +72,7 @@ afterEach(() => { interface RunPayload { status: string + output?: unknown paused?: { contextId?: string | null pauseKind?: string | null @@ -159,6 +160,20 @@ describe('workflows runs wait', () => { ) }) + it('names the same resume command the run record prints in next, from the output links', async () => { + respondWith({ + status: 'paused', + output: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } }, + paused: { pauseKind: 'human', contextId: 'ctx_other' }, + }) + + await wait() + + expect(errored.join('\n')).toContain( + 'sim workflows runs resume exec_9 --workflow 00000000-0000-4000-8000-00000000000a --context ctx_9' + ) + }) + it('stops on a pause whose kind the server did not name', async () => { respondWith({ status: 'paused', paused: { pauseKind: null } }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts b/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts index b3bf3546156..0942fc29e2b 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts @@ -1,5 +1,5 @@ import { sleep } from '@sim/utils/helpers' -import { isRecordLike, toRecordOrNull } from '@sim/utils/object' +import { isRecordLike, toRecord, toRecordOrNull } from '@sim/utils/object' import { type Command, Option } from 'commander' import { printError, writeStderr } from '#sim-cli/output/io' import { hasProgressTerminal, styles } from '#sim-cli/output/presentation' @@ -10,7 +10,7 @@ import { STILL_RUNNING_EXIT_CODE } from '../../exit-codes' import { V2_OPERATIONS } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { apiCommand, type Connection } from '../../runtime/called-operations' -import { resumeCommand } from '../../runtime/paused-run' +import { resumeCommandFor } from '../../runtime/paused-run' import { renderResult } from '../../runtime/result' /** @@ -87,7 +87,6 @@ export interface RunSnapshot { /** `time` resumes itself; `human` and null wait for a person. */ pauseKind: string | null resumeAt: string | null - contextId: string | null } function optionalString(value: unknown): string | null { @@ -116,7 +115,6 @@ function readRun(raw: unknown): RunSnapshot { status: run.status, pauseKind: paused ? optionalString(paused.pauseKind) : null, resumeAt: paused ? optionalString(paused.resumeAt) : null, - contextId: paused ? optionalString(paused.contextId) : null, } } @@ -193,12 +191,13 @@ function explain( outcome: WaitOutcome, runId: string, workflowId: string, - snapshot: RunSnapshot + run: unknown ): string | null { if (outcome === 'completed') return null if (outcome === 'failed') return `Run ${runId} failed.` if (outcome === 'cancelled') return `Run ${runId} was cancelled.` - return `Run ${runId} is paused waiting for input. Resume it: ${resumeCommand(runId, workflowId, snapshot.contextId)}` + const next = resumeCommandFor(toRecord(run), { runId, workflowId }) + return `Run ${runId} is paused waiting for input.${next ? ` Resume it: ${next}` : ''}` } /** @@ -254,7 +253,7 @@ export async function waitForRun( if (outcome) { progress.finish() renderResult('getWorkflowRun', profile.output, runData(raw), runSpec()) - const message = explain(outcome, wait.runId, wait.workflowId, snapshot) + const message = explain(outcome, wait.runId, wait.workflowId, runData(raw)) if (message) printError(styles().red(message)) setSoftExitCode(WAIT_EXIT_CODES[outcome]) return diff --git a/packages/sim-cli/src/runtime/paused-run.test.ts b/packages/sim-cli/src/runtime/paused-run.test.ts index 19bf10b2ab3..e0383cabd81 100644 --- a/packages/sim-cli/src/runtime/paused-run.test.ts +++ b/packages/sim-cli/src/runtime/paused-run.test.ts @@ -5,7 +5,7 @@ const paused = { runId: 'run_top', workflowId: 'wf_1', status: 'paused', - output: { response: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } } }, + output: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } }, } describe('withResumeNext', () => { @@ -33,4 +33,59 @@ describe('withResumeNext', () => { expect(withResumeNext('executeWorkflow', hinted)).toBe(hinted) expect(withResumeNext('executeWorkflow', null)).toBeNull() }) + + it('reads only the links the server writes, never a record that data or an API response carries', () => { + const decoy = { contextId: 'x; rm -rf ~', executionId: 'y' } + const run = { + ...paused, + output: { + data: { + rows: [decoy], + body: { contextId: 'evil', executionId: 'evil_run' }, + _resume: paused.output.data._resume, + }, + }, + } + expect(withResumeNext('executeWorkflow', run)).toMatchObject({ + next: 'sim workflows runs resume exec_9 --workflow wf_1 --context ctx_9', + }) + expect( + withResumeNext('executeWorkflow', { + ...paused, + output: { data: { rows: [{ contextId: 'evil', executionId: 'evil_run' }] } }, + }) + ).toMatchObject({ next: 'sim workflows runs resume run_top --workflow wf_1' }) + }) + + it('never prints an id outside the format the server issues', () => { + const hostile = { + ...paused, + output: { data: { _resume: { contextId: 'x; rm -rf ~', executionId: '$(id)' } } }, + } + expect(withResumeNext('executeWorkflow', hostile)).toMatchObject({ + next: 'sim workflows runs resume run_top --workflow wf_1', + }) + expect( + withResumeNext('executeWorkflow', { ...paused, workflowId: 'wf; id' }) + ).not.toHaveProperty('next') + }) + + it('names one command per pause when several blocks pause together', () => { + const several = { + ...paused, + output: { + pausedBlocks: [ + { data: { _resume: { contextId: 'a\u208D0\u208E', executionId: 'exec_9' } } }, + { data: { _resume: { contextId: 'b', executionId: 'exec_9' } } }, + ], + pauseCount: 2, + }, + } + expect(withResumeNext('executeWorkflow', several)).toMatchObject({ + next: [ + "sim workflows runs resume exec_9 --workflow wf_1 --context 'a\u208D0\u208E'", + 'sim workflows runs resume exec_9 --workflow wf_1 --context b', + ].join('\n'), + }) + }) }) diff --git a/packages/sim-cli/src/runtime/paused-run.ts b/packages/sim-cli/src/runtime/paused-run.ts index d36329f2ebc..60ab934dad7 100644 --- a/packages/sim-cli/src/runtime/paused-run.ts +++ b/packages/sim-cli/src/runtime/paused-run.ts @@ -4,59 +4,91 @@ import type { V2OperationName } from '../generated/v2-api' /** Operations whose payload is a run record that may be paused. */ const RUN_OPERATIONS: ReadonlySet = new Set(['executeWorkflow', 'getWorkflowRun']) -/** Records visited in a paused run's output while looking for its resume links. */ -const SEARCH_BUDGET = 500 -const SEARCH_DEPTH = 6 - interface ResumeLinks { contextId: string executionId: string } +/** What the server issues for an id: letters, digits and `_ . : -` plus the `₍ ₎` of a branch id. */ +const ISSUED_ID = /^[\p{L}\p{N}_.:\u208D\u208E-]{1,256}$/u + +function issuedId(value: unknown): value is string { + return typeof value === 'string' && ISSUED_ID.test(value) +} + +function readLinks(value: unknown): ResumeLinks | null { + if (!isRecordLike(value)) return null + const { contextId, executionId } = value + return issuedId(contextId) && issuedId(executionId) ? { contextId, executionId } : null +} + /** - * The resume links a human-in-the-loop pause leaves in a run's output (`_resume`, or `resume` - * beside the response): the record holding both the pause's `contextId` and the `executionId` - * `runs resume` takes as its run. + * The resume links of every pause in a run's output: `resume` beside a pause response, or + * `_resume` inside its `data`; the response is the output itself (or its `response`) for one + * pause, and each entry of `pausedBlocks` when several blocks pause together. Only those fixed + * places are read, never data a block or an API response carries, and a link whose ids are not + * in the format the server issues is skipped. */ -function findResumeLinks(output: unknown): ResumeLinks | null { - let visited = 0 - const search = (value: unknown, depth: number): ResumeLinks | null => { - if (!isRecordLike(value) || depth > SEARCH_DEPTH || visited++ >= SEARCH_BUDGET) return null - if (typeof value.contextId === 'string' && typeof value.executionId === 'string') { - return { contextId: value.contextId, executionId: value.executionId } +function findResumeLinks(output: unknown): ResumeLinks[] { + if (!isRecordLike(output)) return [] + const found = new Map() + for (const root of [output, output.response]) { + if (!isRecordLike(root)) continue + const responses = Array.isArray(root.pausedBlocks) ? root.pausedBlocks : [root] + for (const response of responses) { + if (!isRecordLike(response)) continue + const links = readLinks(response.resume) ?? readLinks(toRecordOrNull(response.data)?._resume) + if (links) found.set(`${links.executionId}\n${links.contextId}`, links) } - for (const child of Object.values(value)) { - const found = search(child, depth + 1) - if (found) return found - } - return null } - return search(output, 0) + return [...found.values()] +} + +const SAFE_ARGUMENT = /^[A-Za-z0-9_.:-]+$/ + +function shellArgument(value: string): string { + return SAFE_ARGUMENT.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'` } /** The command that resumes a paused run, with the pause's context when it is known. */ -export function resumeCommand(runId: string, workflowId: string, contextId: string | null): string { - const context = contextId ? ` --context ${contextId}` : '' - return `sim workflows runs resume ${runId} --workflow ${workflowId}${context}` +function resumeCommand(runId: string, workflowId: string, contextId: string | null): string { + const context = contextId ? ` --context ${shellArgument(contextId)}` : '' + return `sim workflows runs resume ${shellArgument(runId)} --workflow ${shellArgument(workflowId)}${context}` +} + +/** + * The exact `runs resume` command for a paused run record, one line per waiting pause, since the + * record carries two ids (`runId` and the output's `_resume.executionId`) and a context a reader + * would otherwise have to pair up. `runs resume` takes the run the pause belongs to, which is the + * links' `executionId`. A record whose output names no links falls back to its own ids and the + * `paused.contextId`; null when an id is not in the format the server issues, so no untrusted + * text reaches a printed command. `fallback` supplies the ids a record omits. + */ +export function resumeCommandFor( + record: Record, + fallback: { runId: string; workflowId: string } +): string | null { + const runId = typeof record.runId === 'string' ? record.runId : fallback.runId + const workflowId = typeof record.workflowId === 'string' ? record.workflowId : fallback.workflowId + if (!issuedId(runId) || !issuedId(workflowId)) return null + const links = findResumeLinks(record.output) + if (links.length > 0) { + return links + .map((link) => resumeCommand(link.executionId, workflowId, link.contextId)) + .join('\n') + } + const contextId = toRecordOrNull(record.paused)?.contextId + return resumeCommand(runId, workflowId, issuedId(contextId) ? contextId : null) } /** - * A run record with `next` added when it is paused for input: the exact `runs resume` command, - * since the record carries two ids (`runId` and the output's `_resume.executionId`) and a context - * a reader would otherwise have to pair up. `runs resume` takes the run the pause belongs to, - * which is `_resume.executionId` when the output names one. Any other payload comes back as it + * A run record with `next` added when it is paused for input. Any other payload comes back as it * was, and so does one that already has a `next`. */ export function withResumeNext(operation: V2OperationName, payload: unknown): unknown { if (!RUN_OPERATIONS.has(operation) || !isRecordLike(payload)) return payload if (payload.status !== 'paused' || 'next' in payload) return payload if (typeof payload.runId !== 'string' || typeof payload.workflowId !== 'string') return payload - const links = findResumeLinks(payload.output) - const paused = toRecordOrNull(payload.paused) - const contextId = - links?.contextId ?? (typeof paused?.contextId === 'string' ? paused.contextId : null) - return { - ...payload, - next: resumeCommand(links?.executionId ?? payload.runId, payload.workflowId, contextId), - } + const next = resumeCommandFor(payload, { runId: payload.runId, workflowId: payload.workflowId }) + return next ? { ...payload, next } : payload }