From 5e96fd5a6561e96d5f353aca764906c4e22cb822 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 03:48:21 -0800 Subject: [PATCH 01/37] fix(workflow-sdk): look a block type up as the builder written for it in source params --- .../protocol/workflow-source-params.test.ts | 20 +++++++++++++++++++ .../protocol/workflow-source-params.ts | 5 +++-- .../workflow-sdk/src/codegen/reference.ts | 15 ++++++++++++-- 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts index b5cf39a7a8c..1b3f69941dc 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts @@ -106,6 +106,26 @@ describe('sim workflows source params', () => { expect(stdoutJson()).toMatchObject({ builder: { key: 'slack.sendMessage' } }) }) + it('reads a block type as the builder written for it', async () => { + cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, FIXTURE_TEXT) + writeBase() + + await params('function') + + expect(stdoutJson()).toMatchObject({ builder: { key: 'fn', blockType: 'function' } }) + }) + + it('lists the builders of a block type that has several', async () => { + cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, FIXTURE_TEXT) + writeBase() + + await params('table_v2') + + const { kind, builders } = stdoutJson() as { kind: string; builders: Array<{ key: string }> } + expect(kind).toBe('namespace') + expect(builders.map((builder) => builder.key)).toContain('table.upsertRow') + }) + it('refuses a builder the catalog lacks, naming the closest one', async () => { cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, FIXTURE_TEXT) writeBase() diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts index c6fc048d5fc..491d774aa59 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts @@ -16,8 +16,9 @@ Prints a builder's params (required first, with enums and defaults), the gate fi which others apply, and its outputs, from the block catalog the last get, create or check cached. No request is made. is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A -namespace (gmail, trigger.gmail) lists its builders; a construct core.d.ts declares (loop, -parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, +namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for +it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, +env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no diff --git a/packages/workflow-sdk/src/codegen/reference.ts b/packages/workflow-sdk/src/codegen/reference.ts index 7d9ccb8b497..30a89c6e9f1 100644 --- a/packages/workflow-sdk/src/codegen/reference.ts +++ b/packages/workflow-sdk/src/codegen/reference.ts @@ -100,8 +100,9 @@ export function describeBuilder(catalog: BlockCatalog, key: string): BuilderRefe /** * Looks `query` up as a builder (`table.upsertRow`, `slack.tool.sendMessage`), a namespace - * (`gmail`, `trigger`: its builders listed), or a construct `core.d.ts` declares (`loop`, `t`); - * otherwise reports the closest builder or namespace as a hint. + * (`gmail`, `trigger`: its builders listed), a construct `core.d.ts` declares (`loop`, `t`), or a + * block type whose builder is named otherwise (`function` is `fn`; `table_v2` lists the `table.*` + * builders); otherwise reports the closest builder or namespace as a hint. */ export function lookupBuilder(catalog: BlockCatalog, query: string): BuilderLookup { const key = withoutToolSegment(query.trim()) @@ -116,6 +117,16 @@ export function lookupBuilder(catalog: BlockCatalog, query: string): BuilderLook if ((SDK_CORE_EXPORTS as readonly string[]).includes(root)) { return { kind: 'core', name: key, declaration: coreDeclaration(root) } } + const ofBlockType = paths.filter((path) => catalogBuilder(catalog, path)?.type === key) + const only = ofBlockType.length === 1 ? describeBuilder(catalog, ofBlockType[0]) : null + if (only) return { kind: 'builder', reference: only } + if (ofBlockType.length > 1) { + return { + kind: 'namespace', + namespace: key, + builders: ofBlockType.map((path) => ({ key: path, summary: summaryOf(catalog, path) })), + } + } const hint = suggestBuilder( key, paths.filter((path) => !isLegacyBuilder(path)) From 84d05da26077b5f2c1974dd6ccd321c53cc1e4f0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 03:49:41 -0800 Subject: [PATCH 02/37] fix(sim-cli): exit a workspace dry run that would hold changes back with 15, as the apply does --- .../commands/protocol/source-exit-codes.ts | 6 ++-- .../src/commands/protocol/source-write.ts | 7 ++++- .../protocol/workspace-source-apply.test.ts | 28 +++++++++++++++++++ .../protocol/workspace-source-apply.ts | 12 ++++++++ 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts index 2cba5e9c149..c34915129f7 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts @@ -80,7 +80,7 @@ function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRow[] { 'workflows source get': "the command failed, the directory is a workspace source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or it holds another workflow's source (SOURCE_WORKFLOW_MISMATCH) or edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force)", 'workspaces source apply': - 'the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run that would hold changes back exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed', + 'the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed', 'workspaces source get': 'the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written)', }, @@ -204,11 +204,11 @@ function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRow[] { { code: SOURCE_HELD_EXIT_CODE, meaning: - '`sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret the workspace has no value for, or a credential key nothing binds to', + '`sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret the workspace has no value for, or a credential key nothing binds to. Its dry run exits 15 too, so a script can tell beforehand that the apply would write only part', next: 'Set the secret (`sim secrets set`) or connect the credential, then apply again', help: { 'workspaces source apply': - 'written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again)', + 'written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing', }, }, { diff --git a/packages/sim-cli/src/commands/protocol/source-write.ts b/packages/sim-cli/src/commands/protocol/source-write.ts index f4bee3ac949..46e4151f60e 100644 --- a/packages/sim-cli/src/commands/protocol/source-write.ts +++ b/packages/sim-cli/src/commands/protocol/source-write.ts @@ -37,6 +37,11 @@ export interface SourceWriteFlow { show(preview: D): void /** Whether a preview's errors refuse the write, which is then reported and goes no further. */ refuses(preview: D): boolean + /** + * The exit status of a preview with errors, as the write it previews would exit: by default the + * refusal's ({@link refusedExitCode}). + */ + previewExitCode?(preview: D): number /** Prints what a preview that refuses nothing would write, before the plan stop or the question. */ explain?(preview: D): void /** Runs once the write may go ahead, before it is sent (the preview, or `null` with `--yes`). */ @@ -77,7 +82,7 @@ export async function runSourceWrite( preview = await flow.preview() flow.show(preview) if (preview.diagnostics.some((finding) => finding.severity === 'error')) { - setSoftExitCode(refusedExitCode(preview.diagnostics)) + setSoftExitCode(flow.previewExitCode?.(preview) ?? refusedExitCode(preview.diagnostics)) } if (flow.mode === 'dry-run' || flow.refuses(preview)) { flow.report(preview) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index 6f0a6a46b61..f4a90d77aad 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -1825,6 +1825,34 @@ describe('workspaces source apply', () => { expect(process.exitCode).toBe(1) }) + it.each([ + ['writes the rest', [{ kind: 'table', key: 'leads', action: 'create' }], 15], + ['writes nothing else', [], 1], + ])( + 'exits a dry run that holds a change back as the apply would: %s', + async (_case, others, exitCode) => { + request.mockResolvedValue( + answer({ + dryRun: true, + plan: [...others, { kind: 'workflow', key: 'ingest', action: 'create', held: true }], + diagnostics: [ + { + code: 'E_SECRET_MISSING', + severity: 'error', + message: 'workflows/ingest is held back: it reads the secret OPENAI_API_KEY.', + kind: 'workflow', + key: 'ingest', + }, + ], + }) + ) + + await apply('--dry-run') + + expect(process.exitCode).toBe(exitCode) + } + ) + it('saves the applied answer when the catalog of a workflow it reprinted cannot be fetched, and says its edges are unrecorded', async () => { const configDir = mkdtempSync(join(tmpdir(), 'sim-workspace-apply-config-')) vi.stubEnv('SIM_CONFIG_DIR', configDir) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 8eae6de1398..5535f2ef6ba 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -141,6 +141,17 @@ function refusesApply(data: ApplyData): boolean { ) } +/** + * The exit status of a dry run with errors, as the apply would exit: one that holds changes back + * and refuses nothing else writes the rest, so it exits 15 (`SOURCE_HELD_EXIT_CODE`) as that apply does, unless every + * change it would write is held (1, nothing written). + */ +function previewExitCode(data: ApplyData): number { + if (refusesApply(data)) return refusedExitCode(data.diagnostics) + const writesSome = data.plan.some((change) => change.action !== 'noop' && !change.held) + return writesSome ? SOURCE_HELD_EXIT_CODE : 1 +} + /** What an apply that wrote did, for the plan reprinted after it stopped part-way. */ type PlanOutcome = Pick @@ -869,6 +880,7 @@ export function attachWorkspaceSourceApply(source: Command): void { findings.print(preview.diagnostics) }, refuses: refusesApply, + previewExitCode, // Without a preview, stage the blobs the base does not hold as they are. beforeCommit: (preview) => stage(submission, preview ? new Set(preview.needBlobs) : blobsToStage(submission)), From b4a9021c5bc5c0f66009b6937283bcc1b0d94694 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 03:50:52 -0800 Subject: [PATCH 03/37] fix(sim-cli): return the output of the block a --stop-after run stopped after --- .../protocol/workflow-run-follow.test.ts | 25 +++++++++++++++++++ .../commands/protocol/workflow-run-follow.ts | 22 +++++++++++++++- .../src/commands/protocol/workflow-run-get.ts | 4 +-- 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index 7c0987ba354..05aacf04e23 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -348,6 +348,7 @@ describe('sim workflows run --follow', () => { entry: { type: 'block', blockId: 'agent-1', sourceRunId: 'run-1' }, stopAfterBlockId: 'agent-1', }, + selectedOutputs: ['agent-1'], }) }) @@ -359,6 +360,7 @@ describe('sim workflows run --follow', () => { expect(requestRaw.mock.calls[0][1].body).toEqual({ run: { source: 'manual', stopAfterBlockId: 'agent-1' }, + selectedOutputs: ['agent-1'], }) expect(requestRaw.mock.calls[1][1].body).toEqual({ run: { @@ -366,9 +368,32 @@ describe('sim workflows run --follow', () => { entry: { type: 'trigger', blockId: 'start' }, stopAfterBlockId: 'agent-1', }, + selectedOutputs: ['agent-1'], }) }) + it('selects the output of the block a --stop-after run stops after, by its key or id', async () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + const blockId = '3f2b7c1e-9a4d-4e8b-8c2a-1d5e6f7a8b9c' + + await run(WORKFLOW_ID, '--stop-after', 'Log v1.2 Total') + await run(WORKFLOW_ID, '--stop-after', blockId) + + expect(requestRaw.mock.calls[0][1].body).toMatchObject({ + run: { stopAfterBlockId: 'Log v1.2 Total' }, + selectedOutputs: ['logv12total'], + }) + expect(requestRaw.mock.calls[1][1].body.selectedOutputs).toEqual([blockId]) + }) + + it('keeps the outputs a --stop-after run selects itself', async () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await run(WORKFLOW_ID, '--stop-after', 'agent-1', '--select-output', 'start.input') + + expect(requestRaw.mock.calls[0][1].body.selectedOutputs).toEqual(['start.input']) + }) + it('refuses an empty --stop-after rather than running the whole draft', async () => { await expect(run(WORKFLOW_ID, '--stop-after', '')).rejects.toThrow( '--stop-after requires a block id, name or key' diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index 99f8c49313c..3e9c34faf55 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -15,6 +15,7 @@ import { buildRequest } from '../../runtime/request' import { renderResult } from '../../runtime/result' import type { OperationSpec } from '../../runtime/types' import { printRunFailureSite } from './run-source-location' +import { BLOCK_ID, normalizeBlockName } from './workflow-run-get' import { parseWaitTimeout, type RunSnapshot, @@ -487,6 +488,23 @@ async function followRun(workflowId: string, command: Command): Promise { } } +/** + * The selection a `--stop-after` run sends when the caller selected nothing: the stop block's + * whole output, so `blockOutputs` names the block the run stopped after and holds what it + * produced (the run's `output` stays empty: no Response block ran). The block is sent as the + * executor compares names ({@link normalizeBlockName}), so a display name with a dot is not read + * as a path; an id is sent as it is. + */ +function stopBlockSelection( + selection: WorkflowRunSelection | undefined, + flags: Record +): string[] | null { + const stopAfter = selection?.stopAfterBlockId + if (stopAfter === undefined) return null + if (Array.isArray(flags.selectOutput) && flags.selectOutput.length > 0) return null + return [BLOCK_ID.test(stopAfter) ? stopAfter : normalizeBlockName(stopAfter)] +} + /** * The handler Commander invokes for the generated `run` leaf, given the handler * it is replacing. @@ -544,6 +562,8 @@ function followOrDelegate(previous: ((args: unknown[]) => unknown) | null) { ) } if (flags.async !== true) { + const stopBlock = stopBlockSelection(selection, flags) + if (stopBlock) command.setOptionValue('selectOutput', stopBlock) await runWithResultStream(workflowId, command, waitTimeoutSeconds) return } @@ -608,7 +628,7 @@ export function attachWorkflowRunFollow(workflows: Command): void { ) .option( '--stop-after ', - 'Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual)' + 'Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). Unless --select-output names others, blockOutputs holds the output of that block under its key (or id); output stays empty' ) .option( '--dir ', diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-get.ts b/packages/sim-cli/src/commands/protocol/workflow-run-get.ts index d08ecb18a71..b5babc58768 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-get.ts @@ -19,7 +19,7 @@ import type { OperationSpec } from '../../runtime/types' * The same test the run resource applies (`isValidUuid`) before deciding a * selector head is a name it cannot resolve. */ -const BLOCK_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i +export const BLOCK_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i const SELECT_OUTPUT_FLAG = 'select-output' @@ -34,7 +34,7 @@ const SELECT_OUTPUT_FLAG = 'select-output' * imported because this package ships standalone and carries no workspace * dependency. */ -function normalizeBlockName(name: string): string { +export function normalizeBlockName(name: string): string { return name.toLowerCase().replace(/\s+/g, '').replace(/\./g, '') } From ba6b0d0511b6578bfc9e7232ac23ff28e9a20456 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 03:52:22 -0800 Subject: [PATCH 04/37] docs(sim-cli): say what workflows run prints and how it exits, and that draft runs need --manual --- .../src/commands/protocol/workflow-run-follow.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index 3e9c34faf55..18f4d8f7b26 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -4,6 +4,7 @@ import { writeStderr } from '#sim-cli/output/io' import { styles } from '#sim-cli/output/presentation' import { CLI_CONTRACT } from '../../contract/commands' import { embedStore } from '../../embed-context' +import { STILL_RUNNING_EXIT_CODE } from '../../exit-codes' import { V2_OPERATIONS } from '../../generated/v2-api' import { SimApiError } from '../../http/client' import { readNdjson } from '../../http/ndjson' @@ -597,6 +598,20 @@ function followOrDelegate(previous: ((args: unknown[]) => unknown) | null) { * handler is captured for async execution. Synchronous execution uses the same * generated request and result builders with a heartbeat-capable response. */ +/** `sim workflows run --help`, after the options: which version runs, what it prints, how it exits. */ +const RUN_HELP = ` +Without --manual (or a flag that implies it) this runs the active deployment; a workflow never +deployed has none. --manual runs the saved draft, as the source loop leaves it. + +The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the +workflow's final output) and blockOutputs (what --select-output named). It has no success field: +branch on status, or on the exit code. With --follow it is the stream's final frame +instead: success and output. + +Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed +first, then the error on stderr), or the command failed; ${STILL_RUNNING_EXIT_CODE} still running when --wait-timeout +elapsed.` + export function attachWorkflowRunFollow(workflows: Command): void { const run = workflows.commands.find((command) => command.name() === 'run') if (!run) { @@ -644,5 +659,6 @@ export function attachWorkflowRunFollow(workflows: Command): void { ) .option('--include-thinking', 'Show model reasoning while following (requires --follow)') .option('--include-tool-calls', 'Show tool calls while following (requires --follow)') + .addHelpText('after', RUN_HELP) .action(followOrDelegate(previous)) } From 5e3dff0ec8b882b9159b318daebb5cffe1115d4f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 03:55:18 -0800 Subject: [PATCH 05/37] fix(workflows): accept a block param's canonical name in workflow operations, as blocks get names it --- .../lib/workflows/editing/validation.test.ts | 30 +++++++++++ apps/sim/lib/workflows/editing/validation.ts | 51 ++++++++++++++++++- 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/apps/sim/lib/workflows/editing/validation.test.ts b/apps/sim/lib/workflows/editing/validation.test.ts index 4b67e3eddd8..bfc34bdfb26 100644 --- a/apps/sim/lib/workflows/editing/validation.test.ts +++ b/apps/sim/lib/workflows/editing/validation.test.ts @@ -382,6 +382,36 @@ describe('validateInputsForBlock', () => { }) }) + describe('canonical param names', () => { + it('writes a canonical name into the member it is stored in, as the catalog names it', () => { + const result = validateInputsForBlock('canonicalcred', { cred: 'cred_1' }, 'cred-1') + + expect(result.errors).toEqual([]) + expect(result.validInputs).toEqual({ manualCredential: 'cred_1' }) + }) + + it('refuses a canonical name beside one of its own members', () => { + const result = validateInputsForBlock( + 'canonicalcred', + { cred: 'cred_1', credential: 'cred_2' }, + 'cred-1' + ) + + expect(result.validInputs).toEqual({ credential: 'cred_2' }) + expect(result.errors).toEqual([ + expect.objectContaining({ field: 'cred', error: expect.stringContaining('"credential"') }), + ]) + }) + + it('still names a key that is neither a field nor a canonical param as unknown', () => { + const result = validateInputsForBlock('canonicalcred', { credKey: 'cred_1' }, 'cred-1') + + expect(result.errors).toEqual([ + expect.objectContaining({ field: 'credKey', error: expect.stringContaining('Unknown') }), + ]) + }) + }) + it('stores input-format rows with legacy or aliased types unchanged', () => { const rows = [ { name: 'payload', type: 'json' }, diff --git a/apps/sim/lib/workflows/editing/validation.ts b/apps/sim/lib/workflows/editing/validation.ts index 503e5173194..765e13770fc 100644 --- a/apps/sim/lib/workflows/editing/validation.ts +++ b/apps/sim/lib/workflows/editing/validation.ts @@ -104,6 +104,51 @@ function isContainerBlockType(blockType: string): blockType is 'loop' | 'paralle return blockType === 'loop' || blockType === 'parallel' } +/** + * `inputs` with each key that names a `canonicalParamId` instead of a subBlock (`tableId` for the + * table block's `tableSelector` / `manualTableId`) written under the member that param is stored + * in, as the catalog (`sim blocks get`) and source both name it. A param with one member is that + * member. For a basic/advanced pair, a string (an id, a `` reference) goes to the + * advanced member, the free-text field that takes either, and anything else to the basic one, as + * source compiles a literal; the caller then records the mode the written member implies. A + * canonical name written beside one of its own members is refused: the two would compete. + */ +function withCanonicalNamesResolved( + subBlocks: readonly SubBlockConfig[], + subBlockMap: ReadonlyMap, + inputs: Record, + refuse: (key: string, error: string) => void +): Record { + if (Object.keys(inputs).every((key) => subBlockMap.has(key))) return inputs + // canonical-index-unscoped: maps written names to member ids and reads no values. + const { groupsById } = buildCanonicalIndex(subBlocks) + const resolved: Record = {} + for (const [key, value] of Object.entries(inputs)) { + const group = subBlockMap.has(key) ? undefined : groupsById[key] + if (!group) { + resolved[key] = value + continue + } + const members = [group.basicId, ...group.advancedIds].filter( + (id): id is string => id !== undefined + ) + const written = members.filter((id) => Object.hasOwn(inputs, id)) + if (written.length > 0) { + refuse( + key, + `"${key}" is stored in ${written.map((id) => `"${id}"`).join(', ')}, which this edit also sets: write one of them` + ) + continue + } + const member = + typeof value === 'string' + ? (group.advancedIds[0] ?? group.basicId) + : (group.basicId ?? group.advancedIds[0]) + if (member !== undefined) resolved[member] = value + } + return resolved +} + /** * Validates and filters inputs against a block's subBlock configuration * Returns valid inputs and any validation errors encountered @@ -171,7 +216,6 @@ export function validateInputsForBlock( const validatedInputs: Record = {} const subBlockMap = new Map() - const conditionValues = { ...existingValues, ...inputs } for (const subBlock of blockConfig.subBlocks) { const variants = subBlockMap.get(subBlock.id) ?? [] @@ -179,6 +223,11 @@ export function validateInputsForBlock( subBlockMap.set(subBlock.id, variants) } + inputs = withCanonicalNamesResolved(blockConfig.subBlocks, subBlockMap, inputs, (key, error) => + errors.push({ blockId, blockType, field: key, value: inputs[key], error }) + ) + const conditionValues = { ...existingValues, ...inputs } + for (const [key, value] of Object.entries(inputs)) { // Skip runtime subblock IDs if (TRIGGER_RUNTIME_SUBBLOCK_IDS.includes(key)) { From 4584421275bbe011156d42450544dff47378918b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 03:57:31 -0800 Subject: [PATCH 06/37] fix(workspace-source): count the blocks and variables a workflow update removes as destructive --- .../application/apply.integration.ts | 32 +++++++++++++++++++ .../application/kinds/workflow/adapter.ts | 16 ++++++++++ 2 files changed, 48 insertions(+) diff --git a/apps/sim/lib/workspace-source/application/apply.integration.ts b/apps/sim/lib/workspace-source/application/apply.integration.ts index 9b55df147d5..1373086f664 100644 --- a/apps/sim/lib/workspace-source/application/apply.integration.ts +++ b/apps/sim/lib/workspace-source/application/apply.integration.ts @@ -2281,6 +2281,38 @@ export default workflow('Probe', {}, () => { expect(await tableSnapshot(workspaceId)).toEqual(before) }) + check( + 'counts the blocks an edited workflow removes as a delete, in the plan and its summary', + async () => { + const workspaceId = await newWorkspace() + await apply(workspaceId, STARTER) + const read = await get(workspaceId) + const entry = 'workflows/ingest/workflow.ts' + const files = { + ...read.files, + [entry]: `// @sim-sdk 1 +import { trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Ingest', {}, () => { + trigger.start('Start', { inputFormat: { email: 'string' } }) +}) +`, + } + + const planned = await apply(workspaceId, files, { + base: read.base, + dryRun: true, + allowDelete: true, + }) + + expect(planned.plan.find((change) => change.key === 'ingest')).toMatchObject({ + action: 'update', + fields: expect.arrayContaining(['blocks -1']), + destructive: { what: 'blocks', counts: { blocks: 1 } }, + }) + } + ) + check( 'renames a workflow its folder renames, and refuses a name another workflow holds', async () => { diff --git a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts index 8b12136e809..cdb4422df52 100644 --- a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts @@ -272,6 +272,21 @@ function diffFields(diff: SourceDiffSummary): string[] { return fields } +/** + * What an update deletes from the stored workflow: its removed blocks and variables, counted as a + * table update counts its dropped columns, so the plan, its summary and a status's next step all + * see a delete that needs `--allow-delete`. A removed block takes its stored identity with it + * (run history keyed to it, a trigger's webhook URL), which applying an older copy does not bring + * back. + */ +function deletedFrom(diff: SourceDiffSummary): Pick { + const counts: Record = {} + if (diff.blocks.removed.length > 0) counts.blocks = diff.blocks.removed.length + if (diff.variables.removed.length > 0) counts.variables = diff.variables.removed.length + if (Object.keys(counts).length === 0) return {} + return { destructive: { what: counts.blocks ? 'blocks' : 'variables', counts } } +} + /** The folder's lock, or the findings that refuse it, pinned to `.sim/lock.json`. */ function readLock( key: string, @@ -452,6 +467,7 @@ async function planUpdate( action: result.diff.noop && !metaOnly ? 'noop' : 'update', storedId: update.workflowId, fields: metaOnly ? ['names, order or comments'] : diffFields(result.diff), + ...deletedFrom(result.diff), refs: sourceRefs(result), ...blocksOf(result), detail: { From b876a0fd53151353c028d88513fdfc145afda745 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 03:58:15 -0800 Subject: [PATCH 07/37] fix(sim-cli): name --allow-delete in a workflow status's next apply when the edit removes a variable --- .../protocol/workflow-source-status.test.ts | 14 ++++++++++++++ .../commands/protocol/workflow-source-status.ts | 8 ++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts index 649fcdbb96e..c4291bda5f5 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts @@ -148,6 +148,7 @@ describe('workflows source status', () => { blocksModified: 0, edgesAdded: 0, edgesRemoved: 0, + variablesRemoved: 0, errors: 0, warnings: 0, }, @@ -245,6 +246,19 @@ describe('workflows source status', () => { expect(process.exitCode).toBe(11) }) + it('names --allow-delete in the apply it recommends when the edit removes a variable', async () => { + write(root, 'workflow.ts', `${ENTRY}// edited\n`) + const plan = dryRun([], 1) + plan.data.diff.variables.removed = ['threshold'] as never[] + mockRequest.mockResolvedValue(plan) + + await run(root, 'status') + + expect(printed().next).toMatchObject({ + command: `sim workflows source apply --dir ${root} --yes --allow-delete`, + }) + }) + it('leaves out a function file no codeFile() names, which applying never sends, and says so', async () => { write(root, 'functions/notes.js', 'return 3\n') mockRequest.mockResolvedValue(dryRun()) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts index 10c35bde107..501d92eb633 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts @@ -107,6 +107,8 @@ interface WorkflowPlanSummary { blocksModified: number edgesAdded: number edgesRemoved: number + /** Removed variables: like removed blocks, applying them needs `--allow-delete`. */ + variablesRemoved: number /** Errors other than `E_APPLY_STALE`, which the status lists as drift or a conflict. */ errors: number warnings: number @@ -127,13 +129,15 @@ function planSummary(data: PlanData): WorkflowPlanSummary { blocksModified: data.diff.blocks.modified.length, edgesAdded: data.diff.edges.added, edgesRemoved: data.diff.edges.removed, + variablesRemoved: data.diff.variables.removed.length, errors: findings('error'), warnings: findings('warning'), } } function planLine(plan: WorkflowPlanSummary): string { - return `Applying would: blocks +${plan.blocksAdded} -${plan.blocksRemoved} ~${plan.blocksModified}, connections +${plan.edgesAdded} -${plan.edgesRemoved}; ${plan.errors} error(s), ${plan.warnings} warning(s).` + const variables = plan.variablesRemoved > 0 ? `, variables -${plan.variablesRemoved}` : '' + return `Applying would: blocks +${plan.blocksAdded} -${plan.blocksRemoved} ~${plan.blocksModified}, connections +${plan.edgesAdded} -${plan.edgesRemoved}${variables}; ${plan.errors} error(s), ${plan.warnings} warning(s).` } interface StatusOptions { @@ -238,7 +242,7 @@ export function attachWorkflowSourceStatus(source: Command): void { getArgs: `${workflowId} `, server, errors: plan?.errors ?? 0, - deletes: (plan?.blocksRemoved ?? 0) > 0, + deletes: (plan?.blocksRemoved ?? 0) + (plan?.variablesRemoved ?? 0) > 0, scope: '', login, }), From 1744128adf880197dd5496ee2abfc183200375b1 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 03:59:52 -0800 Subject: [PATCH 08/37] fix(sim-cli): count a workspace status's errors and warnings as its dry run reports them --- .../src/commands/protocol/source-status.ts | 6 +++- .../protocol/workspace-source-status.test.ts | 8 +++-- .../protocol/workspace-source-status.ts | 29 +++++++++++++++---- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index 81a70f45900..f7e85c62740 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -68,8 +68,12 @@ export interface StatusReport extends SourceStatus { next: NextStep | null } -/** The status exit codes, each documented in the commands' help. */ +/** What a status prints and its exit codes, documented in the commands' help. */ export const STATUS_EXIT_CODES_HELP = ` +With --json, \`plan\` is what applying would do as \`apply --dry-run --allow-delete\` reports it +(its errors and warnings counted the same, a conflict as an error), and \`next\` the command to +run (with --allow-delete only when the plan deletes something). + Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); ${SOURCE_LOCAL_CHANGES_EXIT_CODE} local changes only (applying writes them); ${SOURCE_DRIFT_EXIT_CODE} the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts index 68b24862b39..4c1e7be4d48 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts @@ -535,7 +535,9 @@ describe('workspaces source status', () => { { kind: 'table', key: 'leads', server: 'changed' }, { kind: 'workflow', key: 'ingest', server: 'changed' }, ]) - expect(report.plan).toMatchObject({ errors: 0, warnings: 0 }) + // As its dry run counts them: the server changes left alone warn, and the stale workflow is + // one an apply sends by its base, so it refuses nothing. + expect(report.plan).toMatchObject({ errors: 0, warnings: 2 }) expect(report.next).toMatchObject({ command: `sim workspaces source get --dir ${dir}` }) expect(process.exitCode).toBe(12) }) @@ -675,7 +677,7 @@ describe('workspaces source status', () => { expect(report.next).toMatchObject({ command: 'sim workspaces source get --dir ', }) - expect(report.plan).toMatchObject({ conflicts: 1, errors: 0 }) + expect(report.plan).toMatchObject({ conflicts: 1, errors: 1 }) expect(process.exitCode).toBe(12) }) @@ -697,7 +699,7 @@ describe('workspaces source status', () => { const screen = String(vi.mocked(console.log).mock.calls.at(-1)?.[0]) expect(screen).toContain( - 'Applying would be refused as stale (exit 5): 1 conflict(s) above. Without them it would:' + 'Applying would be refused as stale (exit 5): the 1 conflict(s) above. Its dry run: 0 create, 0 update, 0 delete (1 unchanged); 1 error(s), 0 warning(s).' ) }) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts index ca6ea25b52d..61c588c836e 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -198,7 +198,11 @@ interface WorkspacePlanSummary { held: number /** Resources changed on both sides: while any stands, an apply is refused as stale. */ conflicts: number - /** Errors other than the server changes the status lists. */ + /** + * The errors and warnings its dry run reports (`apply --dry-run`, with `--allow-delete` when + * `next` names it), the server changes the status lists by resource included: a conflict is an + * error there (`E_APPLY_STALE`), a resource added on the server a warning (`W_UNDECLARED`). + */ errors: number warnings: number } @@ -249,8 +253,21 @@ function planAsApplied( * folder, such as one using a resource this apply deletes, still refuses the apply, so it stays. */ function workspacePlanFindings(data: PlanData, byBase: ReadonlySet): Diagnostic[] { - return planFindings(data.diagnostics, isServerChangeFinding).filter( - (finding) => !(aboutWorkflowSentByBase(finding, byBase) && isFolderEvaluationFinding(finding)) + return dryRunFindings(data, byBase).filter((finding) => !isServerChangeFinding(finding.code)) +} + +/** + * The findings an apply's dry run would report. A workflow folder the apply sends by its base is + * neither evaluated (no compile or lint findings) nor written, so a server edit to it is drift, + * never a stale refusal: the status sent it whole to see that edit. + */ +function dryRunFindings(data: PlanData, byBase: ReadonlySet): Diagnostic[] { + return planFindings(data.diagnostics, () => false).filter( + (finding) => + !( + aboutWorkflowSentByBase(finding, byBase) && + (isFolderEvaluationFinding(finding) || finding.code === 'E_APPLY_STALE') + ) ) } @@ -279,7 +296,7 @@ function planSummary( function planLine(plan: WorkspacePlanSummary): string { const counts = `${plan.create} create, ${plan.update} update, ${plan.delete} delete (${plan.unchanged} unchanged); ${plan.errors} error(s), ${plan.warnings} warning(s)` return plan.conflicts > 0 - ? `Applying would be refused as stale (exit ${SOURCE_STALE_EXIT_CODE}): ${plan.conflicts} conflict(s) above. Without them it would: ${counts}.` + ? `Applying would be refused as stale (exit ${SOURCE_STALE_EXIT_CODE}): the ${plan.conflicts} conflict(s) above. Its dry run: ${counts}.` : `Applying would: ${counts}.` } @@ -426,7 +443,9 @@ export function attachWorkspaceSourceStatus(source: Command): void { : [] ) const planned = data ? workspacePlanFindings(data, byBase) : [] - const plan = data ? planSummary(planned, applyPlan, status.conflicts.length) : null + const plan = data + ? planSummary(dryRunFindings(data, byBase), applyPlan, status.conflicts.length) + : null const report: StatusReport & { workspaceId: string | null } = { workspaceId, dir: options.dir, From 69f1bf6739d3bcc844eb1968860e9ecb951ab2c5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:02:27 -0800 Subject: [PATCH 09/37] docs(sim-cli): document input names, value shapes, retry and outputs on the operations path, and what export clears --- packages/sim-cli/src/contract/commands.ts | 36 +++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index ce47bbb4433..31f17156a4e 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -82,7 +82,35 @@ Source handles: parallel-start-source, parallel-end-source the same for a parallel Renames: An edit's {"name":"New name"} also rewrites every reference to the block, in - other blocks' inputs and in a loop's or parallel's collection and condition.` + other blocks' inputs and in a loop's or parallel's collection and condition. +Inputs: + inputs takes the field ids \`sim blocks get \` lists (inputSchema, operationInputSchema), + or the name a pair of them shares (inputDefinitions: tableId for tableSelector and + manualTableId; a string goes to the typed field). Add the type it answers with: \`blocks get + table\` answers table_v2, and an add of legacy table is refused. + conditions (condition): [{"title":"if","value":" > 3"},{"title":"else if","value":"…"}, + {"title":"else","value":""}]; the last entry is the else, and ids are assigned. + inputFormat (Start): [{"name":"email","type":"string"}]; types string, number, boolean, + object, array, file[]; an optional default "value" as text. +Block settings, beside inputs in an add's or edit's params: + "retry":{"enabled":true,"maxTries":3,"waitBetweenTriesMs":1000} retries a failed block; null + clears it. +Outputs: + A block that fails outputs {"error":""}: connect its error handle and read + there (without one, the run fails). A Workflow block's result is the child's + output; a child ending in a Response block gives {data, status, headers}, so read + .` +/** How to read `sim blocks get` for a `workflows operations apply` edit. */ +const BLOCK_DETAIL_GUIDE = ` +Reading it for \`sim workflows operations apply\`: + id the type to add: \`blocks get table\` answers table_v2 (an add of legacy + table is refused) + inputSchema the field ids inputs takes; operationInputSchema, an operation's own + inputDefinitions the block's inputs by name; one a pair of fields shares (tableId for + tableSelector and manualTableId) is accepted in place of the pair + outputs what it outputs on success; a failed block outputs {"error":"…"} + instead, read on its error path as +Block settings such as retry are not fields: \`sim workflows operations apply --help\`.` const WORKFLOW_SET_BLOCK_ENABLED_HELP = 'Blocks to enable or disable, applied after --operations: [{"block_id":"","enabled":false}]. Disabling a loop or parallel cascades to its unlocked descendants; enabling a block whose container is disabled is declined' const WORKFLOW_VARIABLE_OPERATIONS_HELP = @@ -697,6 +725,7 @@ export const CLI_CONTRACT: CliContract = { command: 'workflows state replace', confirm: 'This replaces the entire draft graph and cannot be undone.', }, + getBlock: { helpText: BLOCK_DETAIL_GUIDE }, applyWorkflowOperations: { command: 'workflows operations apply', describe: 'Edit a workflow’s blocks, connections and settings with a batch of operations', @@ -954,6 +983,8 @@ export const CLI_CONTRACT: CliContract = { flags: { folderPath: FOLDER_PATH_FLAG }, }, createWorkflow: { + describe: + 'Create a workflow whose draft holds one Start block (start_trigger, named Start); connect from it', flags: { folderPath: { ...FOLDER_PATH_FLAG, @@ -2272,7 +2303,8 @@ export const CLI_CONTRACT: CliContract = { // The payload is the artifact: `sim workflows export > wf.json` has to // produce something `sim workflows import` accepts back. exportWorkflow: { - describe: 'Print a workflow as a portable JSON document', + describe: + 'Print a workflow as a portable JSON document. Workspace bindings (a table, a child workflow, a knowledge base) print as null unless --include-workspace-bindings, and credentials always do: to read what a block is set to, use sim workflows state get', flags: { includeReferences: { boolean: true, From 21f95348f0ec6fe3e91784732de03ad05983d73a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:03:10 -0800 Subject: [PATCH 10/37] docs(sim-cli): document -w and SIM_WORKSPACE, and the quoting trap, in the top-level and source group help --- packages/sim-cli/src/commands/protocol/source-loop-help.ts | 7 +++++++ packages/sim-cli/src/program.ts | 5 +++++ 2 files changed, 12 insertions(+) diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index c3eb53fd988..5ffcaa97197 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -12,6 +12,11 @@ function loopRows(rows: ReadonlyArray): string { return rows.map(([command, what]) => ` ${command.padEnd(width)}${what}`.trimEnd()).join('\n') } +/** Where the commands of either group find their workspace. */ +const WORKSPACE_LINE = `Workspace: a command run on a directory reads it from .sim/base.json; any other takes -w +or SIM_WORKSPACE (export it once: a shell variable holding "--workspace " arrives as one +argument, which is refused).` + /** The status line both groups end with, for a directory at `dir`. */ function statusLine(group: string, dir: string): string { return `\`${group} status --dir ${dir}\` shows what applying would do and @@ -33,6 +38,7 @@ ${loopRows([ A new workflow: \`sim workflows source create --dir ./new --workspace \` writes a starter that records its workspace; edit and check it, then \`create --dir ./new --yes\` creates the workflow there, and the loop above goes on from there. +${WORKSPACE_LINE} Flags the loop needs: --allow-delete (apply: an edit that removes a block or variable is refused without it), --deploy (apply, create: also deploy the saved draft), --force (get: replace another @@ -52,6 +58,7 @@ ${loopRows([ ])} Promote dev to prod: \`sim workspaces source apply --dir ./ws --to --dry-run\`, then --yes. +${WORKSPACE_LINE} Flags the loop needs: --allow-delete (apply: removing a resource, a column, rows or a document, or a workflow's block or variable, is refused without it), --force (get: replace edits no apply diff --git a/packages/sim-cli/src/program.ts b/packages/sim-cli/src/program.ts index b5c7e0ecbe6..66d3f736b80 100644 --- a/packages/sim-cli/src/program.ts +++ b/packages/sim-cli/src/program.ts @@ -27,6 +27,11 @@ Profiles work like the AWS CLI: settings live in ~/.sim/config, keys in ~/.sim/credentials (0600), or under SIM_CONFIG_DIR when it is set. Select one with -P, --profile, or SIM_PROFILE. +A command targets the profile's workspace unless -w (--workspace ) or +SIM_WORKSPACE names another. In a script, export SIM_WORKSPACE= once, or +write -w "$WS": a variable holding "--workspace " reaches the CLI as one +argument, which it refuses. + Workflow, knowledge-base and workspace IDs are bare UUIDs. Table IDs carry a tbl_ prefix and file IDs a wf_ one, so wf_ never names a workflow. An audit-log or custom-tool ID can open with a dash, which reads as a flag; put -- in front From 61c8805507b4220373ab8e472d94dc0bc7e94925 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:07:15 -0800 Subject: [PATCH 11/37] docs(workflow-sdk): add upsertRow and the Response JSON form to the cookbook, and print a core builder's doc in source params --- .../cookbook/examples/cookbook.ts | 16 +++++++++++-- .../src/codegen/cookbook-text.generated.ts | 2 +- .../src/codegen/core-text.generated.ts | 2 +- .../workflow-sdk/src/codegen/reference.ts | 23 +++++++++++++++++++ .../workflow-sdk/src/codegen/semantics.ts | 9 ++++++-- packages/workflow-sdk/src/core.d.ts | 10 ++++---- 6 files changed, 52 insertions(+), 10 deletions(-) diff --git a/packages/workflow-sdk/cookbook/examples/cookbook.ts b/packages/workflow-sdk/cookbook/examples/cookbook.ts index 14ed8d9ed9f..ee8f86191e9 100644 --- a/packages/workflow-sdk/cookbook/examples/cookbook.ts +++ b/packages/workflow-sdk/cookbook/examples/cookbook.ts @@ -76,6 +76,13 @@ export default workflow('Cookbook', { description: 'One example of each common b tableId: table('orders'), data: { orderId: start.orderId, status: 'open', risk: check.risk }, }) + // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else + // inserts one. data is keyed by column name, as for insertRow. + const touch = table.upsertRow('Touch Order', { + tableId: table('orders'), + data: { orderId: start.orderId, status: 'seen' }, + conflictColumn: 'orderId', + }) // Knowledge base search: results is the list of matching chunks. const docs = knowledge.search('Policy Search', { @@ -129,13 +136,18 @@ export default workflow('Cookbook', { description: 'One example of each common b }) // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text. + // body is the short form of the editor's JSON mode: { dataMode: 'json', data } as below. const reply = response('Respond', { body: { risk: check.risk, id: t`${shape.result.id}` } }) - const rejected = response('Respond Rejected', { body: { status: 'rejected' } }) + const rejected = response('Respond Rejected', { + dataMode: 'json', + data: { status: 'rejected' }, + }) // Wiring: a.to(b) chains; a block can fan out to several targets. start.to(check) check.to(save) - save.to(route) + save.to(touch) + touch.to(route) route.high.to(alert) alert.to(approval) approval.to(decided) diff --git a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts index dfec30cef72..31c026f082d 100644 --- a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from cookbook/examples; do not edit. /** The example workflows, file name → text, written as `.sim/examples/`: together one correct example of each common block. */ -export const COOKBOOK_EXAMPLES: Readonly> = {"agents.ts":"// @sim-sdk 1\nimport {\n agent,\n childWorkflow,\n credential,\n customTool,\n env,\n mcp,\n parallel,\n response,\n router,\n runWorkflow,\n slack,\n t,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `lookup-order`, `linear`, `ops-slack`,\n// `enrich-lead` and ANTHROPIC_API_KEY stand in for this workspace\u0027s resources\n// (.sim/sdk/workspace.d.ts; `sim workflows source resources` lists the real keys).\nexport default workflow(\n \u0027Cookbook: agents and subflows\u0027,\n { description: \u0027Router, agent tools, a child workflow and a parallel fan-out.\u0027 },\n () => {\n const start = trigger.start(\u0027Start\u0027, {\n inputFormat: { message: \u0027string\u0027, email: \u0027string\u0027, domains: \u0027array\u0027 },\n })\n\n // Router: the model picks one route by its description; wire with triage..to(...).\n const triage = router(\u0027Triage\u0027, {\n context: start.message,\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n routes: {\n support: \u0027A customer asking about an existing order\u0027,\n sales: \u0027A prospect asking about pricing or a demo\u0027,\n },\n })\n\n // Agent tools: a workspace custom tool, one tool of an MCP server, an integration operation\n // (.tool.; the params given here are fixed, the model fills the rest) and\n // another workflow.\n const support = agent(\u0027Support Agent\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Answer the customer. Use your tools when they help.\u0027 },\n { role: \u0027user\u0027, content: start.message },\n ],\n tools: [\n customTool(\u0027lookup-order\u0027),\n mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027),\n slack.tool.sendMessage({ credential: credential(\u0027ops-slack\u0027), channel: \u0027support-urgent\u0027 }),\n childWorkflow(\u0027enrich-lead\u0027).asTool(),\n ],\n })\n\n // Child workflow: inputMapping is checked against the child\u0027s start inputs. Its output is\n // enrich.result (untyped JSON): the child\u0027s response block output, so a field of the child\u0027s\n // response body is enrich.result.data..\n const enrich = runWorkflow(\u0027Enrich Lead\u0027, {\n workflowId: childWorkflow(\u0027enrich-lead\u0027),\n inputMapping: { email: start.email },\n })\n\n // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its\n // position; each.results lists every branch\u0027s output once all finish. (loop.forEach is the\n // sequential form.) In a function code file inside the body, the same values are\n // $ref.parallel.currentItem and $ref.parallel.index.\n const each = parallel.collection(\u0027Each Domain\u0027, { collection: start.domains }, (p) => {\n const brief = agent(\u0027Company Brief\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Describe ${p.currentItem} in two sentences.` }],\n })\n p.to(brief)\n })\n\n const answer = response(\u0027Answer\u0027, { body: { answer: support.content } })\n const briefs = response(\u0027Briefs\u0027, {\n body: { lead: t`${enrich.result}`, briefs: t`${each.results}` },\n })\n\n start.to(triage)\n triage.support.to(support)\n support.to(answer)\n triage.sales.to(enrich)\n enrich.to(each)\n each.to(briefs)\n }\n)\n","cookbook.ts":"// @sim-sdk 1\nimport {\n agent,\n condition,\n credential,\n env,\n fn,\n human,\n js,\n knowledge,\n knowledgeBase,\n loop,\n response,\n slack,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `orders`, `policies`, `ops-slack` and\n// ANTHROPIC_API_KEY stand in for this workspace\u0027s resources. `sim workflows source resources`\n// lists the real keys, and .sim/sdk/workspace.d.ts types them.\nexport default workflow(\u0027Cookbook\u0027, { description: \u0027One example of each common block.\u0027 }, () => {\n // Triggers: trigger.start (API/manual input), trigger.schedule, trigger.webhook.\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, amount: \u0027number\u0027 } })\n const nightly = trigger.schedule(\u0027Nightly\u0027, {\n scheduleType: \u0027daily\u0027,\n dailyTime: \u002702:00\u0027,\n timezone: \u0027UTC\u0027,\n })\n\n // Agent: structured output via responseFormat; its fields become outputs (check.risk).\n // apiKey: needed on self-hosted Sim; hosted Sim supplies one.\n const check = agent(\u0027Check Order\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Rate the fraud risk of an order as low, med or high.\u0027 },\n { role: \u0027user\u0027, content: t`Order ${start.orderId} for ${start.amount}` },\n ],\n responseFormat: {\n name: \u0027risk\u0027,\n strict: true,\n schema: {\n type: \u0027object\u0027,\n properties: {\n risk: { type: \u0027string\u0027, enum: [\u0027low\u0027, \u0027med\u0027, \u0027high\u0027] },\n reason: { type: \u0027string\u0027 },\n },\n required: [\u0027risk\u0027, \u0027reason\u0027],\n additionalProperties: false,\n },\n },\n })\n\n // Condition: one branch per key, `else: true` last; wire with route..to(...).\n const route = condition(\u0027Route Risk\u0027, {\n high: js`${check.risk} === \u0027high\u0027`,\n med: js`${check.risk} === \u0027med\u0027`,\n else: true,\n })\n\n // Function: inline JavaScript; reference outputs with ${...}. Result is fn.result.\n const shape = fn(\u0027Shape\u0027, {\n code: js`return { id: ${start.orderId}, cents: Math.round(${start.amount} * 100) }`,\n })\n\n // Tables: query rows (each row is { id, data: { column } }) and insert a row.\n const recent = table.queryRows(\u0027Recent Orders\u0027, {\n tableId: table(\u0027orders\u0027),\n filterInput: { all: [{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027open\u0027 }] },\n limit: 50,\n })\n const save = table.insertRow(\u0027Save Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027, risk: check.risk },\n })\n\n // Knowledge base search: results is the list of matching chunks.\n const docs = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: check.reason,\n topK: 3,\n })\n\n // Slack: a saved credential by key (see .sim/sdk/workspace.d.ts).\n const alert = slack.sendMessage(\u0027Alert Ops\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-alerts\u0027,\n messageFormat: \u0027text\u0027,\n text: t`High-risk order ${start.orderId}: ${check.reason}`,\n })\n\n // Human in the loop: inputFormat is the form; answers are approval.submission..\n const approval = human(\u0027Manager Review\u0027, {\n builderData: [{ name: \u0027orderId\u0027, type: \u0027string\u0027, value: start.orderId }],\n inputFormat: { approved: { type: \u0027boolean\u0027, required: true }, note: \u0027string\u0027 },\n })\n const decided = condition(\u0027Approved\u0027, {\n yes: js`${approval.submission.approved} === true`,\n else: true,\n })\n\n // Loop over a list: p.currentItem is one element and p.index its position; the loop\u0027s results\n // is the list of iteration outputs. In js`` code a reference is the value itself, not text\n // spliced in: write it where an expression goes, never inside quotes (\u0027${x}\u0027 would give the\n // JSON, quotes included). A function code file (code: codeFile(\u0027./functions/line.js\u0027)) reads\n // other blocks as $ref.. ($ref.recentorders.rows) and, inside the loop body,\n // the iteration as $ref.loop.currentItem and $ref.loop.index.\n const each = loop.forEach(\u0027Each Order\u0027, { collection: recent.rows }, (p) => {\n const line = fn(\u0027Line\u0027, {\n code: js`return ${p.currentItem.data.orderId} + \u0027: \u0027 + ${p.currentItem.data.status}`,\n })\n p.to(line)\n })\n const report = agent(\u0027Report\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Summarize these orders in 3 lines:\\n${each.results}` }],\n })\n const post = slack.sendMessage(\u0027Post Report\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-daily\u0027,\n messageFormat: \u0027text\u0027,\n text: report.content,\n })\n\n // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text.\n const reply = response(\u0027Respond\u0027, { body: { risk: check.risk, id: t`${shape.result.id}` } })\n const rejected = response(\u0027Respond Rejected\u0027, { body: { status: \u0027rejected\u0027 } })\n\n // Wiring: a.to(b) chains; a block can fan out to several targets.\n start.to(check)\n check.to(save)\n save.to(route)\n route.high.to(alert)\n alert.to(approval)\n approval.to(decided)\n decided.yes.to(shape)\n decided.else.to(rejected)\n route.med.to(docs)\n docs.to(shape)\n route.else.to(shape)\n shape.to(reply)\n nightly.to(recent)\n recent.to(each)\n each.to(report)\n report.to(post)\n})\n","integrations.ts":"// @sim-sdk 1\nimport {\n api,\n credential,\n env,\n gmail,\n response,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `leads`, `ops-gmail`, CLEARBIT_KEY and\n// LEADS_WEBHOOK_TOKEN stand in for this workspace\u0027s resources (.sim/sdk/workspace.d.ts).\n// Integration builders are named by service, not block type: `gmail_v2` is `gmail.*`, and a\n// hidden older version lives under `legacy.*`. .sim/sdk/INDEX.md lists every builder.\nexport default workflow(\n \u0027Cookbook: integrations\u0027,\n { description: \u0027Webhook, weekday schedule, HTTP with headers, table update, Gmail, error path.\u0027 },\n () => {\n // Webhook trigger: inputFormat types the posted JSON fields (hook.leadId). With requireAuth\n // the caller must send the token; keep it in an env var.\n const hook = trigger.webhook(\u0027Lead Webhook\u0027, {\n requireAuth: true,\n token: env.LEADS_WEBHOOK_TOKEN,\n inputFormat: { leadId: \u0027string\u0027, email: \u0027string\u0027, domain: \u0027string\u0027 },\n })\n\n // Schedule: no weekday preset exists, so scheduleType \u0027custom\u0027 takes a 5-field cron.\n const weekdays = trigger.schedule(\u0027Weekdays 8am\u0027, {\n scheduleType: \u0027custom\u0027,\n cronExpression: \u00270 8 * * 1-5\u0027,\n timezone: \u0027America/New_York\u0027,\n })\n\n // HTTP request: headers (and query params) are table rows, { cells: { Key, Value } }.\n const lookup = api(\u0027Company Lookup\u0027, {\n url: t`https://company.clearbit.com/v2/companies/find?domain=${hook.domain}`,\n method: \u0027GET\u0027,\n headers: [{ cells: { Key: \u0027Authorization\u0027, Value: t`Bearer ${env.CLEARBIT_KEY}` } }],\n })\n\n // Update one row by id: data holds only the columns to change. lookup.data is untyped JSON,\n // so a text field from it is wrapped in t``.\n const save = table.updateRowById(\u0027Save Company\u0027, {\n tableId: table(\u0027leads\u0027),\n rowId: hook.leadId,\n data: { company: t`${lookup.data.name}`, enriched: true },\n })\n\n // Gmail (gmail_v2): send one email with a saved Google credential.\n const welcome = gmail.sendEmail(\u0027Welcome Email\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: hook.email,\n subject: \u0027Welcome aboard\u0027,\n body: t`Thanks for signing up from ${hook.domain}.`,\n })\n\n // Query rows, then email them as one digest. A typed column filter: { field, op, value }.\n const pending = table.queryRows(\u0027Pending Leads\u0027, {\n tableId: table(\u0027leads\u0027),\n filterInput: { all: [{ field: \u0027enriched\u0027, op: \u0027eq\u0027, value: false }] },\n limit: 100,\n })\n const digest = gmail.sendEmail(\u0027Pending Digest\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: \u0027ops@example.com\u0027,\n subject: \u0027Leads still to enrich\u0027,\n body: t`${pending.rows}`,\n })\n\n // Error path: x.onError(y) runs y when x fails, instead of failing the run; y reads the\n // failure message as x.error.\n const failed = response(\u0027Lookup Failed\u0027, {\n body: { ok: false, error: lookup.error },\n status: 502,\n })\n const done = response(\u0027Done\u0027, { body: { ok: true, row: save.row } })\n\n hook.to(lookup)\n lookup.to(save)\n lookup.onError(failed)\n save.to(welcome)\n welcome.to(done)\n weekdays.to(pending)\n pending.to(digest)\n }\n)\n"} +export const COOKBOOK_EXAMPLES: Readonly> = {"agents.ts":"// @sim-sdk 1\nimport {\n agent,\n childWorkflow,\n credential,\n customTool,\n env,\n mcp,\n parallel,\n response,\n router,\n runWorkflow,\n slack,\n t,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `lookup-order`, `linear`, `ops-slack`,\n// `enrich-lead` and ANTHROPIC_API_KEY stand in for this workspace\u0027s resources\n// (.sim/sdk/workspace.d.ts; `sim workflows source resources` lists the real keys).\nexport default workflow(\n \u0027Cookbook: agents and subflows\u0027,\n { description: \u0027Router, agent tools, a child workflow and a parallel fan-out.\u0027 },\n () => {\n const start = trigger.start(\u0027Start\u0027, {\n inputFormat: { message: \u0027string\u0027, email: \u0027string\u0027, domains: \u0027array\u0027 },\n })\n\n // Router: the model picks one route by its description; wire with triage..to(...).\n const triage = router(\u0027Triage\u0027, {\n context: start.message,\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n routes: {\n support: \u0027A customer asking about an existing order\u0027,\n sales: \u0027A prospect asking about pricing or a demo\u0027,\n },\n })\n\n // Agent tools: a workspace custom tool, one tool of an MCP server, an integration operation\n // (.tool.; the params given here are fixed, the model fills the rest) and\n // another workflow.\n const support = agent(\u0027Support Agent\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Answer the customer. Use your tools when they help.\u0027 },\n { role: \u0027user\u0027, content: start.message },\n ],\n tools: [\n customTool(\u0027lookup-order\u0027),\n mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027),\n slack.tool.sendMessage({ credential: credential(\u0027ops-slack\u0027), channel: \u0027support-urgent\u0027 }),\n childWorkflow(\u0027enrich-lead\u0027).asTool(),\n ],\n })\n\n // Child workflow: inputMapping is checked against the child\u0027s start inputs. Its output is\n // enrich.result (untyped JSON): the child\u0027s response block output, so a field of the child\u0027s\n // response body is enrich.result.data..\n const enrich = runWorkflow(\u0027Enrich Lead\u0027, {\n workflowId: childWorkflow(\u0027enrich-lead\u0027),\n inputMapping: { email: start.email },\n })\n\n // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its\n // position; each.results lists every branch\u0027s output once all finish. (loop.forEach is the\n // sequential form.) In a function code file inside the body, the same values are\n // $ref.parallel.currentItem and $ref.parallel.index.\n const each = parallel.collection(\u0027Each Domain\u0027, { collection: start.domains }, (p) => {\n const brief = agent(\u0027Company Brief\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Describe ${p.currentItem} in two sentences.` }],\n })\n p.to(brief)\n })\n\n const answer = response(\u0027Answer\u0027, { body: { answer: support.content } })\n const briefs = response(\u0027Briefs\u0027, {\n body: { lead: t`${enrich.result}`, briefs: t`${each.results}` },\n })\n\n start.to(triage)\n triage.support.to(support)\n support.to(answer)\n triage.sales.to(enrich)\n enrich.to(each)\n each.to(briefs)\n }\n)\n","cookbook.ts":"// @sim-sdk 1\nimport {\n agent,\n condition,\n credential,\n env,\n fn,\n human,\n js,\n knowledge,\n knowledgeBase,\n loop,\n response,\n slack,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `orders`, `policies`, `ops-slack` and\n// ANTHROPIC_API_KEY stand in for this workspace\u0027s resources. `sim workflows source resources`\n// lists the real keys, and .sim/sdk/workspace.d.ts types them.\nexport default workflow(\u0027Cookbook\u0027, { description: \u0027One example of each common block.\u0027 }, () => {\n // Triggers: trigger.start (API/manual input), trigger.schedule, trigger.webhook.\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, amount: \u0027number\u0027 } })\n const nightly = trigger.schedule(\u0027Nightly\u0027, {\n scheduleType: \u0027daily\u0027,\n dailyTime: \u002702:00\u0027,\n timezone: \u0027UTC\u0027,\n })\n\n // Agent: structured output via responseFormat; its fields become outputs (check.risk).\n // apiKey: needed on self-hosted Sim; hosted Sim supplies one.\n const check = agent(\u0027Check Order\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Rate the fraud risk of an order as low, med or high.\u0027 },\n { role: \u0027user\u0027, content: t`Order ${start.orderId} for ${start.amount}` },\n ],\n responseFormat: {\n name: \u0027risk\u0027,\n strict: true,\n schema: {\n type: \u0027object\u0027,\n properties: {\n risk: { type: \u0027string\u0027, enum: [\u0027low\u0027, \u0027med\u0027, \u0027high\u0027] },\n reason: { type: \u0027string\u0027 },\n },\n required: [\u0027risk\u0027, \u0027reason\u0027],\n additionalProperties: false,\n },\n },\n })\n\n // Condition: one branch per key, `else: true` last; wire with route..to(...).\n const route = condition(\u0027Route Risk\u0027, {\n high: js`${check.risk} === \u0027high\u0027`,\n med: js`${check.risk} === \u0027med\u0027`,\n else: true,\n })\n\n // Function: inline JavaScript; reference outputs with ${...}. Result is fn.result.\n const shape = fn(\u0027Shape\u0027, {\n code: js`return { id: ${start.orderId}, cents: Math.round(${start.amount} * 100) }`,\n })\n\n // Tables: query rows (each row is { id, data: { column } }) and insert a row.\n const recent = table.queryRows(\u0027Recent Orders\u0027, {\n tableId: table(\u0027orders\u0027),\n filterInput: { all: [{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027open\u0027 }] },\n limit: 50,\n })\n const save = table.insertRow(\u0027Save Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027, risk: check.risk },\n })\n // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else\n // inserts one. data is keyed by column name, as for insertRow.\n const touch = table.upsertRow(\u0027Touch Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027seen\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n\n // Knowledge base search: results is the list of matching chunks.\n const docs = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: check.reason,\n topK: 3,\n })\n\n // Slack: a saved credential by key (see .sim/sdk/workspace.d.ts).\n const alert = slack.sendMessage(\u0027Alert Ops\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-alerts\u0027,\n messageFormat: \u0027text\u0027,\n text: t`High-risk order ${start.orderId}: ${check.reason}`,\n })\n\n // Human in the loop: inputFormat is the form; answers are approval.submission..\n const approval = human(\u0027Manager Review\u0027, {\n builderData: [{ name: \u0027orderId\u0027, type: \u0027string\u0027, value: start.orderId }],\n inputFormat: { approved: { type: \u0027boolean\u0027, required: true }, note: \u0027string\u0027 },\n })\n const decided = condition(\u0027Approved\u0027, {\n yes: js`${approval.submission.approved} === true`,\n else: true,\n })\n\n // Loop over a list: p.currentItem is one element and p.index its position; the loop\u0027s results\n // is the list of iteration outputs. In js`` code a reference is the value itself, not text\n // spliced in: write it where an expression goes, never inside quotes (\u0027${x}\u0027 would give the\n // JSON, quotes included). A function code file (code: codeFile(\u0027./functions/line.js\u0027)) reads\n // other blocks as $ref.. ($ref.recentorders.rows) and, inside the loop body,\n // the iteration as $ref.loop.currentItem and $ref.loop.index.\n const each = loop.forEach(\u0027Each Order\u0027, { collection: recent.rows }, (p) => {\n const line = fn(\u0027Line\u0027, {\n code: js`return ${p.currentItem.data.orderId} + \u0027: \u0027 + ${p.currentItem.data.status}`,\n })\n p.to(line)\n })\n const report = agent(\u0027Report\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Summarize these orders in 3 lines:\\n${each.results}` }],\n })\n const post = slack.sendMessage(\u0027Post Report\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-daily\u0027,\n messageFormat: \u0027text\u0027,\n text: report.content,\n })\n\n // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text.\n // body is the short form of the editor\u0027s JSON mode: { dataMode: \u0027json\u0027, data } as below.\n const reply = response(\u0027Respond\u0027, { body: { risk: check.risk, id: t`${shape.result.id}` } })\n const rejected = response(\u0027Respond Rejected\u0027, {\n dataMode: \u0027json\u0027,\n data: { status: \u0027rejected\u0027 },\n })\n\n // Wiring: a.to(b) chains; a block can fan out to several targets.\n start.to(check)\n check.to(save)\n save.to(touch)\n touch.to(route)\n route.high.to(alert)\n alert.to(approval)\n approval.to(decided)\n decided.yes.to(shape)\n decided.else.to(rejected)\n route.med.to(docs)\n docs.to(shape)\n route.else.to(shape)\n shape.to(reply)\n nightly.to(recent)\n recent.to(each)\n each.to(report)\n report.to(post)\n})\n","integrations.ts":"// @sim-sdk 1\nimport {\n api,\n credential,\n env,\n gmail,\n response,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `leads`, `ops-gmail`, CLEARBIT_KEY and\n// LEADS_WEBHOOK_TOKEN stand in for this workspace\u0027s resources (.sim/sdk/workspace.d.ts).\n// Integration builders are named by service, not block type: `gmail_v2` is `gmail.*`, and a\n// hidden older version lives under `legacy.*`. .sim/sdk/INDEX.md lists every builder.\nexport default workflow(\n \u0027Cookbook: integrations\u0027,\n { description: \u0027Webhook, weekday schedule, HTTP with headers, table update, Gmail, error path.\u0027 },\n () => {\n // Webhook trigger: inputFormat types the posted JSON fields (hook.leadId). With requireAuth\n // the caller must send the token; keep it in an env var.\n const hook = trigger.webhook(\u0027Lead Webhook\u0027, {\n requireAuth: true,\n token: env.LEADS_WEBHOOK_TOKEN,\n inputFormat: { leadId: \u0027string\u0027, email: \u0027string\u0027, domain: \u0027string\u0027 },\n })\n\n // Schedule: no weekday preset exists, so scheduleType \u0027custom\u0027 takes a 5-field cron.\n const weekdays = trigger.schedule(\u0027Weekdays 8am\u0027, {\n scheduleType: \u0027custom\u0027,\n cronExpression: \u00270 8 * * 1-5\u0027,\n timezone: \u0027America/New_York\u0027,\n })\n\n // HTTP request: headers (and query params) are table rows, { cells: { Key, Value } }.\n const lookup = api(\u0027Company Lookup\u0027, {\n url: t`https://company.clearbit.com/v2/companies/find?domain=${hook.domain}`,\n method: \u0027GET\u0027,\n headers: [{ cells: { Key: \u0027Authorization\u0027, Value: t`Bearer ${env.CLEARBIT_KEY}` } }],\n })\n\n // Update one row by id: data holds only the columns to change. lookup.data is untyped JSON,\n // so a text field from it is wrapped in t``.\n const save = table.updateRowById(\u0027Save Company\u0027, {\n tableId: table(\u0027leads\u0027),\n rowId: hook.leadId,\n data: { company: t`${lookup.data.name}`, enriched: true },\n })\n\n // Gmail (gmail_v2): send one email with a saved Google credential.\n const welcome = gmail.sendEmail(\u0027Welcome Email\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: hook.email,\n subject: \u0027Welcome aboard\u0027,\n body: t`Thanks for signing up from ${hook.domain}.`,\n })\n\n // Query rows, then email them as one digest. A typed column filter: { field, op, value }.\n const pending = table.queryRows(\u0027Pending Leads\u0027, {\n tableId: table(\u0027leads\u0027),\n filterInput: { all: [{ field: \u0027enriched\u0027, op: \u0027eq\u0027, value: false }] },\n limit: 100,\n })\n const digest = gmail.sendEmail(\u0027Pending Digest\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: \u0027ops@example.com\u0027,\n subject: \u0027Leads still to enrich\u0027,\n body: t`${pending.rows}`,\n })\n\n // Error path: x.onError(y) runs y when x fails, instead of failing the run; y reads the\n // failure message as x.error.\n const failed = response(\u0027Lookup Failed\u0027, {\n body: { ok: false, error: lookup.error },\n status: 502,\n })\n const done = response(\u0027Done\u0027, { body: { ok: true, row: save.row } })\n\n hook.to(lookup)\n lookup.to(save)\n lookup.onError(failed)\n save.to(welcome)\n welcome.to(done)\n weekdays.to(pending)\n pending.to(digest)\n }\n)\n"} diff --git a/packages/workflow-sdk/src/codegen/core-text.generated.ts b/packages/workflow-sdk/src/codegen/core-text.generated.ts index 9e69817c8db..816f93ad3d5 100644 --- a/packages/workflow-sdk/src/codegen/core-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/core-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from src/core.d.ts; do not edit. /** The text of `core.d.ts`, the workflow SDK authoring declarations. */ -export const CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from \u0027@sim/workflow-sdk\u0027\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref; readonly length: Ref }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to ``.\n * Paths map exactly: `.seg`, `[\u0027seg\u0027]` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref = { readonly [REF]: T } & RefPaths\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue = [Extract] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo = ({ readonly [REF]: RefValue } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value = T | RefTo | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/** JavaScript code (condition expressions, inline function code). */\nexport declare const js: typeof t\n/** Python code. */\nexport declare const py: typeof t\n/** Shell code. */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value\u0027s type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref(\u0027Classify.content\u0027)`. */\nexport declare function ref(path: string): Ref\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field. Valid only on a param of a block the stored\n * workflow already has (same name and type) and holds a value for; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map\u0027s\n * values describe the resource: a table\u0027s row type, a credential\u0027s provider, a workflow\u0027s inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n\ntype KeyOf = keyof M extends never ? string : Extract\n\nexport type TableKey = KeyOf\nexport type KnowledgeBaseKey = KeyOf\nexport type CredentialKey = KeyOf\nexport type WorkflowKey = KeyOf\nexport type SkillKey = KeyOf\nexport type CustomToolKey = KeyOf\nexport type McpServerKey = KeyOf\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server\u0027s last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource\u0027s internal id. */\nexport interface ResourceRef {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential(\u0027support-slack\u0027)`. */\nexport type CredentialRef = ResourceRef<\u0027credential\u0027, Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential\u0027s provider; any key until it exists.\n */\nexport type CredentialKeyFor = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract]\nexport declare function credential(key: K): CredentialRef\n\n/**\n * The other form a credential field takes beside `credential(\u0027key\u0027)`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field\u0027s advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw(\u0027…\u0027)`.\n */\nexport type CredentialIdValue = RefTo | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow {\n id: string\n data: TableColumns\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column\u0027s type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns]-?: Exclude, null> } & {\n [C in Exclude>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column\u0027s type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table(\u0027leads\u0027)`. Table block operations live on `table.*`. */\nexport type TableRef = ResourceRef<\u0027table\u0027, Key>\nexport declare function table(key: K): TableRef\n\n/** A knowledge base: `knowledgeBase(\u0027docs\u0027)`. */\nexport type KnowledgeBaseRef = ResourceRef<\u0027knowledge-base\u0027, Key>\nexport declare function knowledgeBase(key: K): KnowledgeBaseRef\n\n/** A workspace skill: `skill(\u0027triage\u0027)`. */\nexport type SkillRef = ResourceRef<\u0027skill\u0027, Key>\nexport declare function skill(key: K): SkillRef\n\n/** A workspace folder: `folder(\u0027reports\u0027)`. */\nexport type FolderRef = ResourceRef<\u0027file-folder\u0027>\nexport declare function folder(key: string): FolderRef\n\n/** A workspace file: `file(\u0027contracts/acme.pdf\u0027)`. File block operations live on `file.*`. */\nexport type FileRef = ResourceRef<\u0027file\u0027>\nexport declare function file(path: string): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it: one uploaded in place, or a workspace\n * file chosen by `key` (written `file(\u0027path\u0027)` when the workspace resolves it).\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string | FileRef\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent\u0027s `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: \u0027auto\u0027 | \u0027force\u0027 | \u0027none\u0027\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool\u0027s params, which pick the member the agent reads. */\n modes?: Record\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool(\u0027lookup-order\u0027)`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick\n\n/** An MCP tool\u0027s arguments and the editor\u0027s snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record\n /**\n * What the editor saved about the server and the tool\u0027s input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp(\u0027linear\u0027)`. */\nexport interface McpServerRef extends ResourceRef<\u0027mcp-server\u0027, Key> {\n /** One of the server\u0027s tools, as an agent tool: `mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027)`. */\n tool(name: McpToolName, options?: McpToolOpts): Tool\n}\nexport declare function mcp(key: K): McpServerRef\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row\u0027s display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block\u0027s inputs, the\n * agent\u0027s legacy prompt fields, a container\u0027s stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record\n /**\n * A loop or parallel\u0027s `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record\n}\n\n/** A block\u0027s retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node\u0027s default port to each target. Returns the target, or a group of them. */\n to(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node\u0027s error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * The failure message a block outputs when an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`); a check refuses `x.error` on a block without one, which fails the run instead.\n */\ntype ErrorOutput = [O] extends [{ error: unknown }] ? unknown : { readonly error: Ref }\n\n/** A block: a node whose outputs can be referenced, and `error` after an `onError` edge. */\nexport type Block = Node & Ref & ErrorOutput\n\n/** The named ports of a condition or router. */\nexport type Branches = { readonly [P in K]: Node }\n\n/** Trigger builders (`trigger.start`, `trigger.gmail.poller`, ...), generated from the catalog. */\nexport declare namespace trigger {}\n\n/** Builders for hidden legacy block versions (`legacy.slack.send`), generated from the catalog. */\nexport declare namespace legacy {}\n\n/** A raw edge from a handle the SDK has no name for (a legacy or unknown port). */\nexport declare function edge(from: Node, handle: string, to: Target): void\n\n/** Any stored block type without a builder (legacy, unknown or custom), with untyped outputs. */\nexport declare function block(\n type: string,\n name: string,\n params: Record,\n meta?: BlockMeta\n): Block\n\n// Workflow and variables\n\nexport type VariableType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027plain\u0027\n\n/** A workflow variable declared in `workflow(name, { variables })`: its type and initial value. */\nexport interface VariableDeclaration {\n /**\n * The display name, written only when it differs from the key. It must normalize to the key\n * (lowercased, spaces and dots removed), as `\u0027Total Count\u0027` does to `totalcount`.\n */\n name?: string\n type: VariableType\n value: Json\n}\n\n/** The variables a workflow declares, by name. */\nexport type VariableDeclarations = Record\n\ndeclare const VAR: unique symbol\n\n/** A workflow variable, compiled to ``. */\nexport interface VarRef {\n readonly [VAR]: string\n}\n\ntype VariableValue = T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027string\u0027 | \u0027plain\u0027\n ? string\n : Json\n\n/** `vars` in the workflow body: one typed reference per declared variable. */\nexport type VarRefs = {\n readonly [K in keyof V]: VarRef & Ref>\n}\n\n/**\n * Workflow variables by name, untyped. Prefer the `vars` the `workflow()` body receives, which is\n * typed from the declared variables.\n */\nexport declare const vars: { readonly [name: string]: VarRef & Ref }\n\ndeclare const WORKFLOW_DEF: unique symbol\n\n/** The default export of a workflow file. */\nexport interface WorkflowDef {\n readonly [WORKFLOW_DEF]: true\n}\n\n/** A child workflow by key, for `runWorkflow` or as an agent tool. */\nexport interface WorkflowRef extends ResourceRef<\u0027workflow\u0027, Key> {\n /**\n * The workflow as an agent tool, as the editor\u0027s tool picker adds it:\n * `childWorkflow(\u0027enrich-lead\u0027).asTool()`. A tool with fixed inputs is written `raw(tool)`.\n */\n asTool(options?: ToolUsage): Tool\n}\n\n/**\n * Declares a workflow. The body wires blocks; it never runs. With no description or variables the\n * options may be left out: `workflow(\u0027Name\u0027, () => { ... })`.\n */\nexport declare function workflow>(\n name: string,\n options: { description?: string; variables?: V },\n body: (scope: { vars: VarRefs }) => void\n): WorkflowDef\nexport declare function workflow(\n name: string,\n body: (scope: { vars: VarRefs> }) => void\n): WorkflowDef\n/** A child workflow by key: `childWorkflow(\u0027enrich-lead\u0027)`. */\nexport declare function childWorkflow(key: K): WorkflowRef\n\n// Containers\n\ntype ItemOf = C extends { readonly [REF]: readonly (infer E)[] }\n ? E\n : C extends readonly (infer E)[]\n ? E\n : Json\n\n/** Inside a loop or parallel body. As a node it is the container\u0027s start port: `p.to(first)`. */\nexport interface SubflowScope extends Node {\n readonly index: Ref\n readonly currentItem: Ref\n readonly items: Ref\n}\n\n/**\n * A container\u0027s outputs, plus its iteration fields by name (`outer.index`), which a block inside\n * the container reads (in a nested container too: an outer loop\u0027s index or item). Outside the\n * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there.\n */\nexport interface SubflowOutput {\n results: Json[]\n index: number\n currentItem: Json\n items: Json[]\n}\n\n/** A loop or parallel container. Its `.to()` wires the port taken after it finishes. */\nexport type Container = Block\n\ntype Collection = AnyRef | Template | Json[] | string\n\nexport declare const loop: {\n for(\n name: string,\n params: { count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n forEach(\n name: string,\n params: { collection: C },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n while(\n name: string,\n params: { condition: Template | string },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n doWhile(\n name: string,\n params: { condition?: Template | string; count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n}\n\nexport declare const parallel: {\n /** A parallel with no stored type, which the loader runs as `count`. */\n (\n name: string,\n params: { count?: number; collection?: Collection; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n count(\n name: string,\n params: { count: number; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n collection(\n name: string,\n params: { collection: C; batchSize?: number },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n}\n\n// Blocks with a source form of their own\n\n/**\n * Params and outputs of the blocks below, generated from the catalog. Each entry is\n * `{ params; output }`; without generated types the params are loose.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface SpecialBuilderTypes {}\n\ntype SpecialParams = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { params: infer P }\n ? P\n : never\n : Record\n\ntype SpecialOutput = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { output: infer O }\n ? O\n : never\n : Json\n\n/** A condition expression, or `true` for the `else` branch. */\nexport type BranchExpression = Template | string | true\n\ndeclare const ONLY_ELSE: unique symbol\n\n/** What a branch other than `else` written as `true` must be, which no value is: the error names it. */\ninterface OnlyElseMayBeTrue {\n readonly [ONLY_ELSE]: true\n}\n\n/**\n * A condition\u0027s branches: every key holds an expression, and only `else` may be `true`. Another\n * branch written as `true` is checked against {@link OnlyElseMayBeTrue}, so the error names that\n * branch alone.\n */\ntype ConditionBranches = {\n [K in keyof B]: K extends \u0027else\u0027\n ? BranchExpression\n : B[K] extends true\n ? OnlyElseMayBeTrue\n : Template | string\n}\n\n/**\n * Keys of a condition written with no rows (`condition(\u0027Name\u0027, {})`, the source form of rows\n * that were never persisted): the implicit `if` and `else` ports stay addressable.\n */\ntype ConditionKeys = keyof B extends never ? \u0027if\u0027 | \u0027else\u0027 : Extract\ntype RouterKeys = keyof R extends never ? \u0027route0\u0027 : Extract\n\n/** A condition: named branches, the last one `else` when there are two or more. */\nexport declare function condition>(\n name: string,\n branches: B & ConditionBranches,\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A router: named routes described for the model. */\nexport declare function router>(\n name: string,\n params: SpecialParams<\u0027router\u0027> & { routes: R },\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A function block. `code` is inline (`` js`...` ``) or a code file (`codeFile(\u0027./functions/x.js\u0027)`). */\nexport declare function fn(\n name: string,\n params: SpecialParams<\u0027fn\u0027> & { code: Template | CodeFileRef | string },\n meta?: BlockMeta\n): Block>\n\n/**\n * The inputs of a child workflow by key, each checked against the input its start block\n * declares when `workspace.d.ts` knows the workflow; loose JSON otherwise.\n */\nexport type WorkflowInputMapping = K extends keyof WorkspaceWorkflows\n ? WorkspaceWorkflows[K] extends { inputs: infer I }\n ? { [N in keyof I]?: FieldValue }\n : InputMapping\n : InputMapping\n\n/**\n * Runs a child workflow. A `childWorkflow(\u0027key\u0027)` checks `inputMapping` against its inputs. Its\n * `result` is the child\u0027s output: its first response block\u0027s `{ data, status, headers }` (a body\n * field is `result.data.field`), else the output of the last block it ran.\n */\nexport declare function runWorkflow(\n name: string,\n params: Omit, \u0027workflowId\u0027 | \u0027inputMapping\u0027> & {\n workflowId: WorkflowRef | Exclude[\u0027workflowId\u0027], WorkflowRef>\n inputMapping?: WorkflowInputMapping\n },\n meta?: BlockMeta\n): Block>\n\n/**\n * Pauses for a person; the form in `inputFormat` types `submission`. A resumed block also holds\n * each form field at its top level (the runtime copies the submission up, over any output of the\n * same name), so `approval.approved` and `approval.submission.approved` both read it.\n */\nexport declare function human>(\n name: string,\n params: SpecialParams<\u0027human\u0027> & { inputFormat?: F },\n meta?: BlockMeta\n): Block<\n Omit, \u0027submission\u0027 | keyof F> & {\n submission: InputFieldsOutput\n } & InputFieldsOutput\n>\n\n/**\n * A response\u0027s body, status and headers: the editor\u0027s JSON mode. An object or array `body` is\n * JSON whose references keep their types; a template or reference is the body text as written.\n */\nexport interface ResponseBody {\n body: JsonWithRefs\n /** HTTP status; 200 when omitted. A template or reference must produce a number. */\n status?: number | RefTo | Template | EnvRef\n /** Response headers by name. */\n headers?: Record>\n}\n\n/**\n * Ends the workflow with an API response: `response(\u0027Reply\u0027, { body: { ok: true }, status: 201 })`,\n * or the block\u0027s own params (`dataMode`, `builderData`, ...) when the body is built field by field.\n */\nexport declare function response(\n name: string,\n params: ResponseBody,\n meta?: BlockMeta\n): Block>\nexport declare function response(\n name: string,\n params: SpecialParams<\u0027response\u0027>,\n meta?: BlockMeta\n): Block>\n\n/** Assigns workflow variables. */\nexport declare function setVariables(\n name: string,\n params: SpecialParams<\u0027setVariables\u0027>,\n meta?: BlockMeta\n): Block>\n\ndeclare const ANNOTATION: unique symbol\n\n/** A canvas note: no edges, no outputs. */\nexport interface Annotation {\n readonly [ANNOTATION]: true\n}\nexport declare function note(\n name: string,\n params: SpecialParams<\u0027note\u0027>,\n meta?: BlockMeta\n): Annotation\n\n// Structured param shapes\n\n/** Type names an input-format field may declare. */\nexport type InputFieldType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027file[]\u0027\n\n/** A structured input field: its type plus a default value, description or required flag. */\nexport interface InputFieldSpec {\n type: InputFieldType\n value?: JsonWithRefs\n description?: string\n required?: boolean\n}\n\n/** `input-format` fields by name: `{ subject: \u0027string\u0027, amount: { type: \u0027number\u0027, value: 0 } }`. */\nexport type InputFields = Record\n\ntype InputFieldValue = T extends \u0027string\u0027\n ? string\n : T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027array\u0027\n ? Json[]\n : T extends \u0027file[]\u0027\n ? SimFile[]\n : Json\n\n/** The outputs an `input-format` declares. */\nexport type InputFieldsOutput = {\n [K in keyof F]: F[K] extends { type: infer T } ? InputFieldValue : InputFieldValue\n}\n\n/**\n * One `response-format` field as the editor\u0027s builder stores it. An `object` or `array` field\u0027s\n * `value` may hold nested fields. A response is usually written with `body` instead.\n */\nexport interface ResponseField {\n id?: string\n name: string\n type: string\n value?: JsonWithRefs\n collapsed?: boolean\n}\n\n/** `response-format` fields: `[{ name: \u0027ok\u0027, type: \u0027boolean\u0027, value: true }]`. */\nexport type ResponseFields = ResponseField[]\n\n/** An agent message. */\nexport interface Message {\n role: \u0027system\u0027 | \u0027user\u0027 | \u0027assistant\u0027\n content: Value\n}\n\n/** One `variables-input` assignment, with any other stored keys kept. */\nexport interface VariableAssignment {\n variableId: VarRef\n value?: JsonWithRefs\n [key: string]: JsonWithRefs | VarRef | undefined\n}\n\n/** Child workflow inputs by name (`input-mapping`, `workflow-input-mapper`). */\nexport type InputMapping = Record\n\n/** An operator a table filter condition or builder rule can use. */\nexport type FilterOperator = LiteralUnion<\n | \u0027eq\u0027\n | \u0027ne\u0027\n | \u0027gt\u0027\n | \u0027gte\u0027\n | \u0027lt\u0027\n | \u0027lte\u0027\n | \u0027in\u0027\n | \u0027nin\u0027\n | \u0027like\u0027\n | \u0027ilike\u0027\n | \u0027nlike\u0027\n | \u0027nilike\u0027\n | \u0027contains\u0027\n | \u0027ncontains\u0027\n | \u0027startsWith\u0027\n | \u0027endsWith\u0027\n | \u0027isNull\u0027\n | \u0027isNotNull\u0027\n | \u0027isEmpty\u0027\n | \u0027isNotEmpty\u0027\n>\n\n/** One row of the editor\u0027s filter builder, as it stores it. */\nexport interface FilterRule {\n id?: string\n /** How this row joins the rows before it; `and` when omitted. */\n logicalOperator?: \u0027and\u0027 | \u0027or\u0027\n column: string\n operator: FilterOperator\n value: Value\n collapsed?: boolean\n}\n\n/** A filter-builder value: the editor\u0027s rows, `[{ column: \u0027status\u0027, operator: \u0027eq\u0027, value: \u0027new\u0027 }]`. */\nexport type Filter = FilterRule[]\n\n/** One table filter condition: `{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027new\u0027 }`. */\nexport interface TableCondition {\n field: string\n op: FilterOperator\n value?: JsonWithRefs\n}\n\n/**\n * A table predicate: a condition, or an `all` (and) / `any` (or) group of predicates. The\n * `{ status: { $eq: \u0027new\u0027 } }` operator-object grammar is not one: the runtime refuses it.\n */\nexport type TablePredicate = TableCondition | { all: TablePredicate[] } | { any: TablePredicate[] }\n\n/** A table sort by column: `{ createdAt: \u0027desc\u0027 }`. */\nexport type Sort =\n | Record\n | Array<{ column: string; direction: \u0027asc\u0027 | \u0027desc\u0027 }>\n\n/** One knowledge tag filter. */\nexport interface TagFilter {\n tagName: string\n tagValue: Value\n [key: string]: JsonWithRefs\n}\n\n/** One document tag. */\nexport interface DocumentTag {\n tagName: string\n value: Value\n [key: string]: JsonWithRefs\n}\n\n/** One `eval-input` metric. */\nexport interface EvalMetric {\n name: string\n description?: string\n range?: { min: number; max: number }\n [key: string]: JsonWithRefs | undefined\n}\n\n/** One `model-fallback-list` entry. */\nexport interface ModelFallback {\n model: LiteralUnion\n [key: string]: JsonWithRefs\n}\n\n/**\n * Model ids, generated into `models.d.ts` (which adds one member per model). Kept apart from the\n * block files so a model-list change touches one file.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface ModelIds {}\nexport type Model = Extract\n\n/** A JSON Schema `responseFormat`, or `{ name, strict, schema }` around one. */\nexport type ResponseFormat = JsonWithRefs\n\ntype Depth = [never, 0, 1, 2, 3, 4]\n\ntype FromSchema = [D] extends [never]\n ? Json\n : S extends { enum: readonly (infer E)[] }\n ? E\n : S extends { type: \u0027object\u0027; properties: infer P }\n ? { [K in keyof P]: FromSchema }\n : S extends { type: \u0027array\u0027; items: infer I }\n ? FromSchema[]\n : S extends { type: \u0027string\u0027 }\n ? string\n : S extends { type: \u0027number\u0027 | \u0027integer\u0027 }\n ? number\n : S extends { type: \u0027boolean\u0027 }\n ? boolean\n : Json\n\n/**\n * The outputs a literal `responseFormat` adds, read from its JSON Schema with recursion capped at\n * depth 4. A template or reference adds untyped JSON.\n */\nexport type ResponseFormatOutput = [RF] extends [undefined]\n ? unknown\n : RF extends { schema: infer S }\n ? FromSchema\n : RF extends { type: \u0027object\u0027; properties: object }\n ? FromSchema\n : { [key: string]: Json }\n" +export const CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from \u0027@sim/workflow-sdk\u0027\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref; readonly length: Ref }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to ``.\n * Paths map exactly: `.seg`, `[\u0027seg\u0027]` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref = { readonly [REF]: T } & RefPaths\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue = [Extract] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo = ({ readonly [REF]: RefValue } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value = T | RefTo | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/** JavaScript code (condition expressions, inline function code). */\nexport declare const js: typeof t\n/** Python code. */\nexport declare const py: typeof t\n/** Shell code. */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value\u0027s type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref(\u0027Classify.content\u0027)`. */\nexport declare function ref(path: string): Ref\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field. Valid only on a param of a block the stored\n * workflow already has (same name and type) and holds a value for; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map\u0027s\n * values describe the resource: a table\u0027s row type, a credential\u0027s provider, a workflow\u0027s inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n\ntype KeyOf = keyof M extends never ? string : Extract\n\nexport type TableKey = KeyOf\nexport type KnowledgeBaseKey = KeyOf\nexport type CredentialKey = KeyOf\nexport type WorkflowKey = KeyOf\nexport type SkillKey = KeyOf\nexport type CustomToolKey = KeyOf\nexport type McpServerKey = KeyOf\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server\u0027s last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource\u0027s internal id. */\nexport interface ResourceRef {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential(\u0027support-slack\u0027)`. */\nexport type CredentialRef = ResourceRef<\u0027credential\u0027, Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential\u0027s provider; any key until it exists.\n */\nexport type CredentialKeyFor = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract]\nexport declare function credential(key: K): CredentialRef\n\n/**\n * The other form a credential field takes beside `credential(\u0027key\u0027)`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field\u0027s advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw(\u0027…\u0027)`.\n */\nexport type CredentialIdValue = RefTo | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow {\n id: string\n data: TableColumns\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column\u0027s type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns]-?: Exclude, null> } & {\n [C in Exclude>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column\u0027s type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table(\u0027leads\u0027)`. Table block operations live on `table.*`. */\nexport type TableRef = ResourceRef<\u0027table\u0027, Key>\nexport declare function table(key: K): TableRef\n\n/** A knowledge base: `knowledgeBase(\u0027docs\u0027)`. */\nexport type KnowledgeBaseRef = ResourceRef<\u0027knowledge-base\u0027, Key>\nexport declare function knowledgeBase(key: K): KnowledgeBaseRef\n\n/** A workspace skill: `skill(\u0027triage\u0027)`. */\nexport type SkillRef = ResourceRef<\u0027skill\u0027, Key>\nexport declare function skill(key: K): SkillRef\n\n/** A workspace folder: `folder(\u0027reports\u0027)`. */\nexport type FolderRef = ResourceRef<\u0027file-folder\u0027>\nexport declare function folder(key: string): FolderRef\n\n/** A workspace file: `file(\u0027contracts/acme.pdf\u0027)`. File block operations live on `file.*`. */\nexport type FileRef = ResourceRef<\u0027file\u0027>\nexport declare function file(path: string): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it: one uploaded in place, or a workspace\n * file chosen by `key` (written `file(\u0027path\u0027)` when the workspace resolves it).\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string | FileRef\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent\u0027s `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: \u0027auto\u0027 | \u0027force\u0027 | \u0027none\u0027\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool\u0027s params, which pick the member the agent reads. */\n modes?: Record\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool(\u0027lookup-order\u0027)`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick\n\n/** An MCP tool\u0027s arguments and the editor\u0027s snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record\n /**\n * What the editor saved about the server and the tool\u0027s input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp(\u0027linear\u0027)`. */\nexport interface McpServerRef extends ResourceRef<\u0027mcp-server\u0027, Key> {\n /** One of the server\u0027s tools, as an agent tool: `mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027)`. */\n tool(name: McpToolName, options?: McpToolOpts): Tool\n}\nexport declare function mcp(key: K): McpServerRef\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row\u0027s display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block\u0027s inputs, the\n * agent\u0027s legacy prompt fields, a container\u0027s stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record\n /**\n * A loop or parallel\u0027s `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record\n}\n\n/** A block\u0027s retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node\u0027s default port to each target. Returns the target, or a group of them. */\n to(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node\u0027s error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * The failure message a block outputs when an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`); a check refuses `x.error` on a block without one, which fails the run instead.\n */\ntype ErrorOutput = [O] extends [{ error: unknown }] ? unknown : { readonly error: Ref }\n\n/** A block: a node whose outputs can be referenced, and `error` after an `onError` edge. */\nexport type Block = Node & Ref & ErrorOutput\n\n/** The named ports of a condition or router. */\nexport type Branches = { readonly [P in K]: Node }\n\n/** Trigger builders (`trigger.start`, `trigger.gmail.poller`, ...), generated from the catalog. */\nexport declare namespace trigger {}\n\n/** Builders for hidden legacy block versions (`legacy.slack.send`), generated from the catalog. */\nexport declare namespace legacy {}\n\n/** A raw edge from a handle the SDK has no name for (a legacy or unknown port). */\nexport declare function edge(from: Node, handle: string, to: Target): void\n\n/** Any stored block type without a builder (legacy, unknown or custom), with untyped outputs. */\nexport declare function block(\n type: string,\n name: string,\n params: Record,\n meta?: BlockMeta\n): Block\n\n// Workflow and variables\n\nexport type VariableType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027plain\u0027\n\n/** A workflow variable declared in `workflow(name, { variables })`: its type and initial value. */\nexport interface VariableDeclaration {\n /**\n * The display name, written only when it differs from the key. It must normalize to the key\n * (lowercased, spaces and dots removed), as `\u0027Total Count\u0027` does to `totalcount`.\n */\n name?: string\n type: VariableType\n value: Json\n}\n\n/** The variables a workflow declares, by name. */\nexport type VariableDeclarations = Record\n\ndeclare const VAR: unique symbol\n\n/** A workflow variable, compiled to ``. */\nexport interface VarRef {\n readonly [VAR]: string\n}\n\ntype VariableValue = T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027string\u0027 | \u0027plain\u0027\n ? string\n : Json\n\n/** `vars` in the workflow body: one typed reference per declared variable. */\nexport type VarRefs = {\n readonly [K in keyof V]: VarRef & Ref>\n}\n\n/**\n * Workflow variables by name, untyped. Prefer the `vars` the `workflow()` body receives, which is\n * typed from the declared variables.\n */\nexport declare const vars: { readonly [name: string]: VarRef & Ref }\n\ndeclare const WORKFLOW_DEF: unique symbol\n\n/** The default export of a workflow file. */\nexport interface WorkflowDef {\n readonly [WORKFLOW_DEF]: true\n}\n\n/** A child workflow by key, for `runWorkflow` or as an agent tool. */\nexport interface WorkflowRef extends ResourceRef<\u0027workflow\u0027, Key> {\n /**\n * The workflow as an agent tool, as the editor\u0027s tool picker adds it:\n * `childWorkflow(\u0027enrich-lead\u0027).asTool()`. A tool with fixed inputs is written `raw(tool)`.\n */\n asTool(options?: ToolUsage): Tool\n}\n\n/**\n * Declares a workflow. The body wires blocks; it never runs. With no description or variables the\n * options may be left out: `workflow(\u0027Name\u0027, () => { ... })`.\n */\nexport declare function workflow>(\n name: string,\n options: { description?: string; variables?: V },\n body: (scope: { vars: VarRefs }) => void\n): WorkflowDef\nexport declare function workflow(\n name: string,\n body: (scope: { vars: VarRefs> }) => void\n): WorkflowDef\n/** A child workflow by key: `childWorkflow(\u0027enrich-lead\u0027)`. */\nexport declare function childWorkflow(key: K): WorkflowRef\n\n// Containers\n\ntype ItemOf = C extends { readonly [REF]: readonly (infer E)[] }\n ? E\n : C extends readonly (infer E)[]\n ? E\n : Json\n\n/** Inside a loop or parallel body. As a node it is the container\u0027s start port: `p.to(first)`. */\nexport interface SubflowScope extends Node {\n readonly index: Ref\n readonly currentItem: Ref\n readonly items: Ref\n}\n\n/**\n * A container\u0027s outputs, plus its iteration fields by name (`outer.index`), which a block inside\n * the container reads (in a nested container too: an outer loop\u0027s index or item). Outside the\n * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there.\n */\nexport interface SubflowOutput {\n results: Json[]\n index: number\n currentItem: Json\n items: Json[]\n}\n\n/** A loop or parallel container. Its `.to()` wires the port taken after it finishes. */\nexport type Container = Block\n\ntype Collection = AnyRef | Template | Json[] | string\n\nexport declare const loop: {\n for(\n name: string,\n params: { count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n forEach(\n name: string,\n params: { collection: C },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n while(\n name: string,\n params: { condition: Template | string },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n doWhile(\n name: string,\n params: { condition?: Template | string; count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n}\n\nexport declare const parallel: {\n /** A parallel with no stored type, which the loader runs as `count`. */\n (\n name: string,\n params: { count?: number; collection?: Collection; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n count(\n name: string,\n params: { count: number; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n collection(\n name: string,\n params: { collection: C; batchSize?: number },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n}\n\n// Blocks with a source form of their own\n\n/**\n * Params and outputs of the blocks below, generated from the catalog. Each entry is\n * `{ params; output }`; without generated types the params are loose.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface SpecialBuilderTypes {}\n\ntype SpecialParams = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { params: infer P }\n ? P\n : never\n : Record\n\ntype SpecialOutput = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { output: infer O }\n ? O\n : never\n : Json\n\n/** A condition expression, or `true` for the `else` branch. */\nexport type BranchExpression = Template | string | true\n\ndeclare const ONLY_ELSE: unique symbol\n\n/** What a branch other than `else` written as `true` must be, which no value is: the error names it. */\ninterface OnlyElseMayBeTrue {\n readonly [ONLY_ELSE]: true\n}\n\n/**\n * A condition\u0027s branches: every key holds an expression, and only `else` may be `true`. Another\n * branch written as `true` is checked against {@link OnlyElseMayBeTrue}, so the error names that\n * branch alone.\n */\ntype ConditionBranches = {\n [K in keyof B]: K extends \u0027else\u0027\n ? BranchExpression\n : B[K] extends true\n ? OnlyElseMayBeTrue\n : Template | string\n}\n\n/**\n * Keys of a condition written with no rows (`condition(\u0027Name\u0027, {})`, the source form of rows\n * that were never persisted): the implicit `if` and `else` ports stay addressable.\n */\ntype ConditionKeys = keyof B extends never ? \u0027if\u0027 | \u0027else\u0027 : Extract\ntype RouterKeys = keyof R extends never ? \u0027route0\u0027 : Extract\n\n/** A condition: named branches, the last one `else` when there are two or more. */\nexport declare function condition>(\n name: string,\n branches: B & ConditionBranches,\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A router: named routes described for the model. */\nexport declare function router>(\n name: string,\n params: SpecialParams<\u0027router\u0027> & { routes: R },\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A function block. `code` is inline (`` js`...` ``) or a code file (`codeFile(\u0027./functions/x.js\u0027)`). */\nexport declare function fn(\n name: string,\n params: SpecialParams<\u0027fn\u0027> & { code: Template | CodeFileRef | string },\n meta?: BlockMeta\n): Block>\n\n/**\n * The inputs of a child workflow by key, each checked against the input its start block\n * declares when `workspace.d.ts` knows the workflow; loose JSON otherwise.\n */\nexport type WorkflowInputMapping = K extends keyof WorkspaceWorkflows\n ? WorkspaceWorkflows[K] extends { inputs: infer I }\n ? { [N in keyof I]?: FieldValue }\n : InputMapping\n : InputMapping\n\n/**\n * Runs a child workflow. A `childWorkflow(\u0027key\u0027)` checks `inputMapping` against its inputs. Its\n * `result` is the child\u0027s output: its first response block\u0027s `{ data, status, headers }` (a body\n * field is `result.data.field`), else the output of the last block it ran.\n */\nexport declare function runWorkflow(\n name: string,\n params: Omit, \u0027workflowId\u0027 | \u0027inputMapping\u0027> & {\n workflowId: WorkflowRef | Exclude[\u0027workflowId\u0027], WorkflowRef>\n inputMapping?: WorkflowInputMapping\n },\n meta?: BlockMeta\n): Block>\n\n/**\n * Pauses for a person; the form in `inputFormat` types `submission`. A resumed block also holds\n * each form field at its top level (the runtime copies the submission up, over any output of the\n * same name), so `approval.approved` and `approval.submission.approved` both read it.\n */\nexport declare function human>(\n name: string,\n params: SpecialParams<\u0027human\u0027> & { inputFormat?: F },\n meta?: BlockMeta\n): Block<\n Omit, \u0027submission\u0027 | keyof F> & {\n submission: InputFieldsOutput\n } & InputFieldsOutput\n>\n\n/**\n * A response\u0027s body, status and headers: the editor\u0027s JSON mode, `body` standing for\n * `{ dataMode: \u0027json\u0027, data }`. An object or array `body` is JSON whose references keep their\n * types; a template or reference is the body text as written.\n */\nexport interface ResponseBody {\n body: JsonWithRefs\n /** HTTP status; 200 when omitted. A template or reference must produce a number. */\n status?: number | RefTo | Template | EnvRef\n /** Response headers by name. */\n headers?: Record>\n}\n\n/**\n * Ends the workflow with an API response: `response(\u0027Reply\u0027, { body: { ok: true }, status: 201 })`\n * (`body` is short for `dataMode: \u0027json\u0027` with `data`), or the block\u0027s own params (`dataMode`,\n * `builderData`, ...) when the body is built field by field.\n */\nexport declare function response(\n name: string,\n params: ResponseBody,\n meta?: BlockMeta\n): Block>\nexport declare function response(\n name: string,\n params: SpecialParams<\u0027response\u0027>,\n meta?: BlockMeta\n): Block>\n\n/** Assigns workflow variables. */\nexport declare function setVariables(\n name: string,\n params: SpecialParams<\u0027setVariables\u0027>,\n meta?: BlockMeta\n): Block>\n\ndeclare const ANNOTATION: unique symbol\n\n/** A canvas note: no edges, no outputs. */\nexport interface Annotation {\n readonly [ANNOTATION]: true\n}\nexport declare function note(\n name: string,\n params: SpecialParams<\u0027note\u0027>,\n meta?: BlockMeta\n): Annotation\n\n// Structured param shapes\n\n/** Type names an input-format field may declare. */\nexport type InputFieldType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027file[]\u0027\n\n/** A structured input field: its type plus a default value, description or required flag. */\nexport interface InputFieldSpec {\n type: InputFieldType\n value?: JsonWithRefs\n description?: string\n required?: boolean\n}\n\n/** `input-format` fields by name: `{ subject: \u0027string\u0027, amount: { type: \u0027number\u0027, value: 0 } }`. */\nexport type InputFields = Record\n\ntype InputFieldValue = T extends \u0027string\u0027\n ? string\n : T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027array\u0027\n ? Json[]\n : T extends \u0027file[]\u0027\n ? SimFile[]\n : Json\n\n/** The outputs an `input-format` declares. */\nexport type InputFieldsOutput = {\n [K in keyof F]: F[K] extends { type: infer T } ? InputFieldValue : InputFieldValue\n}\n\n/**\n * One `response-format` field as the editor\u0027s builder stores it. An `object` or `array` field\u0027s\n * `value` may hold nested fields. A response is usually written with `body` instead.\n */\nexport interface ResponseField {\n id?: string\n name: string\n type: string\n value?: JsonWithRefs\n collapsed?: boolean\n}\n\n/** `response-format` fields: `[{ name: \u0027ok\u0027, type: \u0027boolean\u0027, value: true }]`. */\nexport type ResponseFields = ResponseField[]\n\n/** An agent message. */\nexport interface Message {\n role: \u0027system\u0027 | \u0027user\u0027 | \u0027assistant\u0027\n content: Value\n}\n\n/** One `variables-input` assignment, with any other stored keys kept. */\nexport interface VariableAssignment {\n variableId: VarRef\n value?: JsonWithRefs\n [key: string]: JsonWithRefs | VarRef | undefined\n}\n\n/** Child workflow inputs by name (`input-mapping`, `workflow-input-mapper`). */\nexport type InputMapping = Record\n\n/** An operator a table filter condition or builder rule can use. */\nexport type FilterOperator = LiteralUnion<\n | \u0027eq\u0027\n | \u0027ne\u0027\n | \u0027gt\u0027\n | \u0027gte\u0027\n | \u0027lt\u0027\n | \u0027lte\u0027\n | \u0027in\u0027\n | \u0027nin\u0027\n | \u0027like\u0027\n | \u0027ilike\u0027\n | \u0027nlike\u0027\n | \u0027nilike\u0027\n | \u0027contains\u0027\n | \u0027ncontains\u0027\n | \u0027startsWith\u0027\n | \u0027endsWith\u0027\n | \u0027isNull\u0027\n | \u0027isNotNull\u0027\n | \u0027isEmpty\u0027\n | \u0027isNotEmpty\u0027\n>\n\n/** One row of the editor\u0027s filter builder, as it stores it. */\nexport interface FilterRule {\n id?: string\n /** How this row joins the rows before it; `and` when omitted. */\n logicalOperator?: \u0027and\u0027 | \u0027or\u0027\n column: string\n operator: FilterOperator\n value: Value\n collapsed?: boolean\n}\n\n/** A filter-builder value: the editor\u0027s rows, `[{ column: \u0027status\u0027, operator: \u0027eq\u0027, value: \u0027new\u0027 }]`. */\nexport type Filter = FilterRule[]\n\n/** One table filter condition: `{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027new\u0027 }`. */\nexport interface TableCondition {\n field: string\n op: FilterOperator\n value?: JsonWithRefs\n}\n\n/**\n * A table predicate: a condition, or an `all` (and) / `any` (or) group of predicates. The\n * `{ status: { $eq: \u0027new\u0027 } }` operator-object grammar is not one: the runtime refuses it.\n */\nexport type TablePredicate = TableCondition | { all: TablePredicate[] } | { any: TablePredicate[] }\n\n/** A table sort by column: `{ createdAt: \u0027desc\u0027 }`. */\nexport type Sort =\n | Record\n | Array<{ column: string; direction: \u0027asc\u0027 | \u0027desc\u0027 }>\n\n/** One knowledge tag filter. */\nexport interface TagFilter {\n tagName: string\n tagValue: Value\n [key: string]: JsonWithRefs\n}\n\n/** One document tag. */\nexport interface DocumentTag {\n tagName: string\n value: Value\n [key: string]: JsonWithRefs\n}\n\n/** One `eval-input` metric. */\nexport interface EvalMetric {\n name: string\n description?: string\n range?: { min: number; max: number }\n [key: string]: JsonWithRefs | undefined\n}\n\n/** One `model-fallback-list` entry. */\nexport interface ModelFallback {\n model: LiteralUnion\n [key: string]: JsonWithRefs\n}\n\n/**\n * Model ids, generated into `models.d.ts` (which adds one member per model). Kept apart from the\n * block files so a model-list change touches one file.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface ModelIds {}\nexport type Model = Extract\n\n/** A JSON Schema `responseFormat`, or `{ name, strict, schema }` around one. */\nexport type ResponseFormat = JsonWithRefs\n\ntype Depth = [never, 0, 1, 2, 3, 4]\n\ntype FromSchema = [D] extends [never]\n ? Json\n : S extends { enum: readonly (infer E)[] }\n ? E\n : S extends { type: \u0027object\u0027; properties: infer P }\n ? { [K in keyof P]: FromSchema }\n : S extends { type: \u0027array\u0027; items: infer I }\n ? FromSchema[]\n : S extends { type: \u0027string\u0027 }\n ? string\n : S extends { type: \u0027number\u0027 | \u0027integer\u0027 }\n ? number\n : S extends { type: \u0027boolean\u0027 }\n ? boolean\n : Json\n\n/**\n * The outputs a literal `responseFormat` adds, read from its JSON Schema with recursion capped at\n * depth 4. A template or reference adds untyped JSON.\n */\nexport type ResponseFormatOutput = [RF] extends [undefined]\n ? unknown\n : RF extends { schema: infer S }\n ? FromSchema\n : RF extends { type: \u0027object\u0027; properties: object }\n ? FromSchema\n : { [key: string]: Json }\n" diff --git a/packages/workflow-sdk/src/codegen/reference.ts b/packages/workflow-sdk/src/codegen/reference.ts index 30a89c6e9f1..abff2b4cb08 100644 --- a/packages/workflow-sdk/src/codegen/reference.ts +++ b/packages/workflow-sdk/src/codegen/reference.ts @@ -25,6 +25,8 @@ export interface BuilderReference { operation?: string /** An older block version's builder, kept so stored workflows print; write the current one. */ legacy: boolean + /** What `core.d.ts` says of a builder it declares itself (`response`, `fn`), as prose. */ + doc?: string /** The call, as the declarations type it. */ signature: string /** The agent tool form (`slack.tool.sendMessage(…)`), when the builder has one. */ @@ -88,6 +90,7 @@ export function describeBuilder(catalog: BlockCatalog, key: string): BuilderRefe summary: types.summary, ...(entry.builder.operation ? { operation: entry.builder.operation } : {}), legacy: isLegacyBuilder(key), + ...(entry.special ? docOf(key) : {}), signature, tool, paramsName: types.paramsName, @@ -199,6 +202,25 @@ function coreDeclaration(name: string): string { return out.slice(0, MAX_CORE_LINES).join('\n') } +/** The doc comment above the first declaration of `name` in `core.d.ts`, as one paragraph. */ +function docOf(name: string): Pick { + const range = coreDeclarationRanges(name)[0] + if (!range) return {} + const lines = CORE_DTS.split('\n') + if (!lines[range.start - 1]?.trim().endsWith('*/')) return {} + const comment: string[] = [] + for (let index = range.start - 1; index >= 0; index--) { + comment.unshift(lines[index]) + if (lines[index].trim().startsWith('/**')) break + } + const doc = comment + .map((line) => line.trim().replace(/^\/\*\*\s?|\s?\*\/$|^\*\s?/g, '')) + .join(' ') + .replace(/\s+/g, ' ') + .trim() + return doc ? { doc } : {} +} + const MAX_SNIPPET_TYPE = 60 const MAX_SNIPPET_OPTIONAL = 12 @@ -300,6 +322,7 @@ export function renderBuilderReference(reference: BuilderReference): string { if (reference.legacy) { lines.push('Legacy: an older block version. Write the current builder instead.') } + if (reference.doc) lines.push('', reference.doc) lines.push('', reference.signature) if (reference.tool) lines.push(`${reference.tool} (as an agent tool)`) const required = reference.params.common.filter((param) => param.required) diff --git a/packages/workflow-sdk/src/codegen/semantics.ts b/packages/workflow-sdk/src/codegen/semantics.ts index 9ce78cdb4bd..f9c33d5aeac 100644 --- a/packages/workflow-sdk/src/codegen/semantics.ts +++ b/packages/workflow-sdk/src/codegen/semantics.ts @@ -8,7 +8,11 @@ * `apps/sim/lib/workflows/blocks/retry-eligibility.ts`; * - `onError`: `block-executor.ts` (`handleBlockError`), `executor/execution/edge-manager.ts` * (`shouldActivateEdge`), `executor/orchestrators/loop.ts` (`storeLoopNodeOutput`); - * - joins: `edge-manager.ts` (`processOutgoingEdges`, `isNodeReady`); + * - joins: `edge-manager.ts` (`processOutgoingEdges`, `isNodeReady`); a block that did not run: + * `executor/utils/block-reference.ts` (`resolveBlockReference`), `executor/variables/resolver.ts` + * (`RESOLVED_EMPTY`); + * - loop and parallel results: `executor/orchestrators/node.ts` (`handleLoopNodeCompletion`, + * `handleParallelNodeCompletion`), `orchestrators/loop.ts` and `parallel.ts` (`results`); * - outputs in function code: `executor/variables/resolver.ts` (`resolveCodeWithContextVars`, * `formatContextVariableReference`); * - child workflows: `executor/handlers/workflow/handler.ts` (`mapChildOutputToParent`, @@ -23,7 +27,8 @@ export const RUNTIME_SEMANTICS: readonly string[] = [ '', "- **Two retries, nested.** An `api` block's `retries`, `retryDelayMs` and `retryMaxDelayMs` repeat the HTTP request inside one run of the block: only after a timeout, a connection reset, a 429 or a 5xx, only for GET, HEAD, PUT and DELETE unless `retryNonIdempotent: true`, with jittered exponential backoff capped at `retryMaxDelayMs` (a `Retry-After` beyond the cap ends the retries). `meta.retry` (`{ enabled, maxTries, waitBetweenTriesMs }`) reruns the whole block, request retries included, after any failure but a stop or a failed child workflow; `maxTries` counts every try. So `retries: 2` under `maxTries: 3` sends up to 9 requests. Only the last try's failure reaches `onError`. Triggers and `human` never retry.", "- **`onError`.** `x.onError(y)` makes a failure of `x` an output, `{ error: '' }`, and runs `y` instead of `x`'s other targets; the run goes on. `y` reads the message as `x.error` (only a block with an `onError` edge has it). In a loop or parallel body (`y` must be in the same body) the iteration ends normally and the loop moves to the next item, with that error output as `x`'s entry for the iteration. Without `onError`, a failure in any iteration fails the run and stops the loop.", - '- **Joins run once.** A block with several incoming edges runs once, after every one of them has fired or been ruled out (a condition or router branch not taken, the normal edge of a block that failed into `onError`). `a.to(join)`, `b.to(join)`, `c.to(join)` wait for all three; behind a condition only the taken branch fires, and the join runs once after it. A block never runs once per incoming branch.', + "- **Joins run once.** A block with several incoming edges runs once, after every one of them has fired or been ruled out (a condition or router branch not taken, the normal edge of a block that failed into `onError`). `a.to(join)`, `b.to(join)`, `c.to(join)` wait for all three; behind a condition only the taken branch fires, and the join runs once after it. A block never runs once per incoming branch. A reference to a block that did not run (on the branch not taken) resolves empty: `null` as a whole value, in function code or in a condition, `''` inside text.", + '- **Loop and parallel results.** `x.results` holds one entry per iteration (a parallel: per branch), and each entry is the list of outputs of the body blocks that ran in it, in the order they finished. With one block in the body its output is `x.results[i][0]`; `x.results.flat()` lists every output.', "- **Outputs in function code.** In `fn` code, `\u0024{a.content}` inside js`` is not spliced in as text: it becomes an expression that evaluates to the output's value, a string as a string and an object as an object. Write it where an expression goes (`const reply = \u0024{a.content}`, `[\u0024{a.content}, \u0024{b.content}]`) and never wrap it in quotes. Written inside a JavaScript string or template literal it splices in as JSON, quotes included (`'Hi \u0024{a.content}'` gives `Hi \"hello\"`). Python code works the same way.", "- **Child workflows.** `const c = runWorkflow('C', { workflowId: childWorkflow('k'), inputMapping })` outputs the child's run as `c.result`: the output of the first `response` block the child reaches, `{ data, status, headers }` (a field of its `body` is `c.result.data.field`), or, with no `response` block, the output of the last block it ran. `c.result` is untyped: wrap a value that should become text in `t`. A deployed run of the parent (API, webhook, schedule, chat) runs the child's deployed version and fails while the child is not deployed; a run from the editor runs the child's draft. A failed child fails `c` (`c.onError(...)` catches it).", "- **MCP headers** (`mcp/.ts`). A header value is plain text in which `{{NAME}}` names an env variable anywhere (`Authorization: 'Bearer {{GITHUB_TOKEN}}'`), `env.NAME` for a whole value, or `stored()` to keep the value the server holds. A `t` template or a template literal with `\u0024{}` is refused. A credential header (`Authorization`, `Cookie`, or a name with `key`, `token`, `secret`, `auth`, `password`, `session`, `signature` or `credential`) holds nothing but an optional scheme word (`Bearer`, `Basic`, `Token`, `Bot`, `ApiKey`) and `{{NAME}}` references (`E_MCP_LITERAL_SECRET`). The variables resolve when the server connects, from the personal and workspace env (the workspace value wins); a missing one fails the connection.", diff --git a/packages/workflow-sdk/src/core.d.ts b/packages/workflow-sdk/src/core.d.ts index fdf7c69ae7b..31440540ffe 100644 --- a/packages/workflow-sdk/src/core.d.ts +++ b/packages/workflow-sdk/src/core.d.ts @@ -753,8 +753,9 @@ export declare function human > /** - * A response's body, status and headers: the editor's JSON mode. An object or array `body` is - * JSON whose references keep their types; a template or reference is the body text as written. + * A response's body, status and headers: the editor's JSON mode, `body` standing for + * `{ dataMode: 'json', data }`. An object or array `body` is JSON whose references keep their + * types; a template or reference is the body text as written. */ export interface ResponseBody { body: JsonWithRefs @@ -765,8 +766,9 @@ export interface ResponseBody { } /** - * Ends the workflow with an API response: `response('Reply', { body: { ok: true }, status: 201 })`, - * or the block's own params (`dataMode`, `builderData`, ...) when the body is built field by field. + * Ends the workflow with an API response: `response('Reply', { body: { ok: true }, status: 201 })` + * (`body` is short for `dataMode: 'json'` with `data`), or the block's own params (`dataMode`, + * `builderData`, ...) when the body is built field by field. */ export declare function response( name: string, From ff3af8404358ceeeceef2559bfd58396d2651c1e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:07:24 -0800 Subject: [PATCH 12/37] test(workflow-sdk): cover the core builder doc source params prints --- packages/workflow-sdk/src/codegen/reference.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/workflow-sdk/src/codegen/reference.test.ts b/packages/workflow-sdk/src/codegen/reference.test.ts index ef6f88fcb7d..0b29f448a20 100644 --- a/packages/workflow-sdk/src/codegen/reference.test.ts +++ b/packages/workflow-sdk/src/codegen/reference.test.ts @@ -24,6 +24,12 @@ describe('builder reference', () => { ]) }) + it('carries what core.d.ts says of a builder it declares, and nothing for a generated one', () => { + expect(describeBuilder(CATALOG, 'runWorkflow')?.doc).toContain('`result.data.field`') + expect(describeBuilder(CATALOG, 'response')?.doc).toContain("`dataMode: 'json'` with `data`") + expect(describeBuilder(CATALOG, 'agent')).not.toHaveProperty('doc') + }) + it('fills a text, number or boolean param of a snippet with an example value, not its type', () => { const snippets = catalogBuilderPaths(CATALOG).flatMap((key) => { const reference = describeBuilder(CATALOG, key) From 6762d75bfa31e7b33227b0405b50ed9aa611f116 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:08:28 -0800 Subject: [PATCH 13/37] docs: regenerate the CLI reference and document the held dry run, run results, status counts and block deletes --- apps/docs/content/docs/cli/blocks.mdx | 12 +++++ apps/docs/content/docs/cli/reference.mdx | 49 +++++++++++++++++-- apps/docs/content/docs/cli/scripting.mdx | 10 ++-- apps/docs/content/docs/cli/workflows.mdx | 33 +++++++++++-- apps/docs/content/docs/cli/workspaces.mdx | 4 +- .../content/docs/workflows/workspace-code.mdx | 4 +- 6 files changed, 95 insertions(+), 17 deletions(-) diff --git a/apps/docs/content/docs/cli/blocks.mdx b/apps/docs/content/docs/cli/blocks.mdx index fb1ffa07f71..95b796011c2 100644 --- a/apps/docs/content/docs/cli/blocks.mdx +++ b/apps/docs/content/docs/cli/blocks.mdx @@ -53,4 +53,16 @@ sim blocks get +```text +Reading it for `sim workflows operations apply`: + id the type to add: `blocks get table` answers table_v2 (an add of legacy + table is refused) + inputSchema the field ids inputs takes; operationInputSchema, an operation's own + inputDefinitions the block's inputs by name; one a pair of fields shares (tableId for + tableSelector and manualTableId) is accepted in place of the pair + outputs what it outputs on success; a failed block outputs {"error":"…"} + instead, read on its error path as +Block settings such as retry are not fields: `sim workflows operations apply --help`. +``` + API request and response schemas: [getBlock](/api-reference/catalog/getBlock). diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index f47db12440f..ee1ac1c81a7 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -426,6 +426,18 @@ sim blocks get +```text +Reading it for `sim workflows operations apply`: + id the type to add: `blocks get table` answers table_v2 (an add of legacy + table is refused) + inputSchema the field ids inputs takes; operationInputSchema, an operation's own + inputDefinitions the block's inputs by name; one a pair of fields shares (tableId for + tableSelector and manualTableId) is accepted in place of the pair + outputs what it outputs on success; a failed block outputs {"error":"…"} + instead, read on its error path as +Block settings such as retry are not fields: `sim workflows operations apply --help`. +``` + API request and response schemas: [getBlock](/api-reference/catalog/getBlock). ### sim blocks list @@ -7774,6 +7786,23 @@ Source handles: Renames: An edit's {"name":"New name"} also rewrites every reference to the block, in other blocks' inputs and in a loop's or parallel's collection and condition. +Inputs: + inputs takes the field ids `sim blocks get ` lists (inputSchema, operationInputSchema), + or the name a pair of them shares (inputDefinitions: tableId for tableSelector and + manualTableId; a string goes to the typed field). Add the type it answers with: `blocks get + table` answers table_v2, and an add of legacy table is refused. + conditions (condition): [{"title":"if","value":" > 3"},{"title":"else if","value":"…"}, + {"title":"else","value":""}]; the last entry is the else, and ids are assigned. + inputFormat (Start): [{"name":"email","type":"string"}]; types string, number, boolean, + object, array, file[]; an optional default "value" as text. +Block settings, beside inputs in an add's or edit's params: + "retry":{"enabled":true,"maxTries":3,"waitBetweenTriesMs":1000} retries a failed block; null + clears it. +Outputs: + A block that fails outputs {"error":""}: connect its error handle and read + there (without one, the run fails). A Workflow block's result is the child's + output; a child ending in a Response block gives {data, status, headers}, so read + . ``` API request and response schemas: [applyWorkflowOperations](/api-reference/workflows/applyWorkflowOperations). @@ -8112,7 +8141,7 @@ API request and response schemas: [updateWorkflowVersion](/api-reference/workflo ### sim workflows create -Create workflow +Create a workflow whose draft holds one start block (start_trigger, named Start); connect from it ```bash sim workflows create [options] @@ -8464,7 +8493,7 @@ sim workflows run [options] | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | | `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | -| `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). | +| `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). Unless --select-output names others, blockOutputs holds the output of that block under its key (or id); output stays empty. | | `--dir ` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. Not with --async or --follow, and not for a run --wait-timeout leaves running. | | `--wait-timeout ` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. | | `--follow` | No | Stream the run as it happens; progress on stderr, result on stdout. The stream reports only success and output, so the result omits the run id and timings a non-streaming run returns. | @@ -8473,11 +8502,17 @@ sim workflows run [options] +Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. + +The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. + +Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. + API request and response schemas: [executeWorkflow](/api-reference/workflows/executeWorkflowV2). ### sim workflows export -Print a workflow as a portable JSON document +Print a workflow as a portable JSON document. workspace bindings (a table, a child workflow, a knowledge base) print as null unless --include-workspace-bindings, and credentials always do: to read what a block is set to, use sim workflows state get The export clears credentials, passwords, and table sub-block values, but it is not a general secret scanner. Inspect literal variables and inline configuration before sharing the document. @@ -8685,6 +8720,8 @@ sim workflows source status [options] +With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). + Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). @@ -8751,7 +8788,7 @@ sim workflows source params [options] -Prints a builder's params (required first, with enums and defaults), the gate field that picks which others apply, and its outputs, from the block catalog the last get, create or check cached. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. +Prints a builder's params (required first, with enums and defaults), the gate field that picks which others apply, and its outputs, from the block catalog the last get, create or check cached. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no cached catalog (run a get once). @@ -10011,7 +10048,7 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run that would hold changes back exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing. Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). @@ -10067,6 +10104,8 @@ sim workspaces source status [options] +With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). + Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. diff --git a/apps/docs/content/docs/cli/scripting.mdx b/apps/docs/content/docs/cli/scripting.mdx index a6a494589e3..5391ed9864a 100644 --- a/apps/docs/content/docs/cli/scripting.mdx +++ b/apps/docs/content/docs/cli/scripting.mdx @@ -207,7 +207,7 @@ The CLI resends a request the API answers `429` only when sending it twice is sa | Code | `sim workspaces source apply` | | --- | --- | | `0` | Applied, or a dry run with no errors | -| `1` | The source has errors, every change it would write was held back for a secret or credential the workspace cannot satisfy (nothing was written), or command/request failure | +| `1` | The source has errors, every change it would write was held back for a secret or credential the workspace cannot satisfy (nothing was written; its dry run exits `1` too), or command/request failure | | `5` | A resource changed since the directory was read (`409 SOURCE_STALE`): get it again into a fresh directory, reapply the edit, and retry | | `6` | A resource (a workflow or its folder, a table) is locked (`423`); a locked block exits `1` (`E_APPLY_LOCKED_BLOCK`) | | `7` | The directory is over the size limits (`413`) | @@ -216,14 +216,14 @@ The CLI resends a request the API answers `429` only when sending it twice is sa | `10` | Busy, retry: another apply is writing the workspace (`409 SOURCE_BUSY`), or another `sim workspaces source` command is using the same directory (`SOURCE_DIR_BUSY`); nothing was written: run the command again once the other finished | | `13` | `AUTH_REQUIRED`: not logged in, or the server refused the credential; nothing was sent | | `14` | Run without `--yes` and with no terminal to ask: the plan was printed with no errors and nothing was written; run the same command with `--yes` | -| `15` | Written in part: changes that use a declared secret with no value, or a credential key nothing binds to, were held back and the rest was applied and saved; set the secret or connect the credential, then apply again (a promotion with `--to` too) | +| `15` | Written in part: changes that use a declared secret with no value, or a credential key nothing binds to, were held back and the rest was applied and saved; set the secret or connect the credential, then apply again (a promotion with `--to` too). A dry run that would do so exits `15` too, having written nothing | | `130` | Interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check | -Earlier CLI releases exited `1` when an apply held changes back, whether or not it wrote the rest. A script that reads `1` as "held back" should test for `15` too. +Earlier CLI releases exited `1` when an apply held changes back, whether or not it wrote the rest, and its dry run exited `1` in either case. A script that reads `1` as "held back" should test for `15` too. Both waits default to 3600 seconds; `--wait-timeout 0` waits indefinitely. `SIM_TIMEOUT_SECONDS` independently bounds one API request. A timeout does not cancel the underlying run or operation. -A synchronous or followed workflow run prints its result before exiting 1 for failure/cancellation. A paused run is not failed and can return 0; use `runs wait` or inspect status if your script requires completion. Fetching a failed run or listing runs only reports their state. +A synchronous or followed workflow run prints its result before exiting 1 for failure/cancellation. The result of a run that is not followed is the run record, whose `status` is `completed`, `failed`, `paused` or `cancelled`; it has no `success` field (a followed run's result is the stream's final frame, `success` and `output`), so branch on `status` or the exit code. A paused run is not failed and can return 0; use `runs wait` or inspect status if your script requires completion. Fetching a failed run or listing runs only reports their state. Capture a failure without losing its output: @@ -381,7 +381,7 @@ exit "$status" ## Workspace source in CI -Keep a [workspace source directory](/workflows/workspace-code) in a repository, `.sim/` included, and let CI plan each pull request and apply each merge. The dry run exits `1` on errors and `5` when the workspace changed since the committed base; `check` downloads the block catalog once on a fresh runner. On GitHub Actions (`GITHUB_ACTIONS=true`), every source command also annotates each error and warning at its file and line, so they show inline on the pull request, and `apply` (a dry run too) appends its plan and errors to the job's step summary. +Keep a [workspace source directory](/workflows/workspace-code) in a repository, `.sim/` included, and let CI plan each pull request and apply each merge. The dry run exits `1` on errors, `5` when the workspace changed since the committed base, and `15` when the apply would hold back changes that use a secret with no value or a credential nothing binds to; `check` downloads the block catalog once on a fresh runner. On GitHub Actions (`GITHUB_ACTIONS=true`), every source command also annotates each error and warning at its file and line, so they show inline on the pull request, and `apply` (a dry run too) appends its plan and errors to the job's step summary. ```yaml title=".github/workflows/sim-workspace.yml" on: diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 1f69d9ef0d8..2bbacfbeeb8 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -56,7 +56,7 @@ sim workflows get API request and response schemas: [getWorkflow](/api-reference/workflows/getWorkflow). -### Create workflow +### Create a workflow whose draft holds one start block (start_trigger, named Start); connect from it ```bash sim workflows create [options] @@ -354,6 +354,23 @@ Source handles: Renames: An edit's {"name":"New name"} also rewrites every reference to the block, in other blocks' inputs and in a loop's or parallel's collection and condition. +Inputs: + inputs takes the field ids `sim blocks get ` lists (inputSchema, operationInputSchema), + or the name a pair of them shares (inputDefinitions: tableId for tableSelector and + manualTableId; a string goes to the typed field). Add the type it answers with: `blocks get + table` answers table_v2, and an add of legacy table is refused. + conditions (condition): [{"title":"if","value":" > 3"},{"title":"else if","value":"…"}, + {"title":"else","value":""}]; the last entry is the else, and ids are assigned. + inputFormat (Start): [{"name":"email","type":"string"}]; types string, number, boolean, + object, array, file[]; an optional default "value" as text. +Block settings, beside inputs in an add's or edit's params: + "retry":{"enabled":true,"maxTries":3,"waitBetweenTriesMs":1000} retries a failed block; null + clears it. +Outputs: + A block that fails outputs {"error":""}: connect its error handle and read + there (without one, the run fails). A Workflow block's result is the child's + output; a child ending in a Response block gives {data, status, headers}, so read + . ``` API request and response schemas: [applyWorkflowOperations](/api-reference/workflows/applyWorkflowOperations). @@ -794,7 +811,7 @@ sim workflows run [options] | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | | `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | -| `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). | +| `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). Unless --select-output names others, blockOutputs holds the output of that block under its key (or id); output stays empty. | | `--dir ` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. Not with --async or --follow, and not for a run --wait-timeout leaves running. | | `--wait-timeout ` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. | | `--follow` | No | Stream the run as it happens; progress on stderr, result on stdout. The stream reports only success and output, so the result omits the run id and timings a non-streaming run returns. | @@ -803,6 +820,12 @@ sim workflows run [options] +Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. + +The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. + +Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. + API request and response schemas: [executeWorkflow](/api-reference/workflows/executeWorkflowV2). ### List runs for a workflow @@ -1083,7 +1106,7 @@ API request and response schemas: [deleteWorkflowChatDeployment](/api-reference/ ## Export and import -### Print a workflow as a portable JSON document +### Print a workflow as a portable JSON document. workspace bindings (a table, a child workflow, a knowledge base) print as null unless --include-workspace-bindings, and credentials always do: to read what a block is set to, use sim workflows state get The export clears credentials, passwords, and table sub-block values, but it is not a general secret scanner. Inspect literal variables and inline configuration before sharing the document. @@ -1361,6 +1384,8 @@ sim workflows source status [options] +With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). + Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). @@ -1529,7 +1554,7 @@ sim workflows source params [options] -Prints a builder's params (required first, with enums and defaults), the gate field that picks which others apply, and its outputs, from the block catalog the last get, create or check cached. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. +Prints a builder's params (required first, with enums and defaults), the gate field that picks which others apply, and its outputs, from the block catalog the last get, create or check cached. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no cached catalog (run a get once). diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 2bdf492eebf..496f1d18b53 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -731,6 +731,8 @@ sim workspaces source status [options] +With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). + Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. @@ -760,7 +762,7 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run that would hold changes back exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing. Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). diff --git a/apps/docs/content/docs/workflows/workspace-code.mdx b/apps/docs/content/docs/workflows/workspace-code.mdx index 343e84c0deb..e75a9f22189 100644 --- a/apps/docs/content/docs/workflows/workspace-code.mdx +++ b/apps/docs/content/docs/workflows/workspace-code.mdx @@ -66,7 +66,7 @@ The dry run prints the plan (`+` create, `~` update, `=` adopt an existing resou An apply adopts a resource it never read (one made in Sim under the name a new declaration gives) only when the declaration matches it, or only adds to it: a column, rows into an empty table, a document. An adopt that would change or remove anything the resource holds is refused with `E_APPLY_NO_BASE`, even with `--allow-delete`. Run `get` into a new directory to read the resource, then make your edit there, or give the declaration another name. -`status` shows what would happen if you applied, without writing anything: the files you created, edited, or deleted, grouped by resource; what changed in Sim since the `get` (a resource edited, added, or deleted there, a workflow edited in the editor included); the conflicts, where a resource changed on both sides; and the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unapplied, and `12` when something changed in Sim since the `get`, so a script or an agent can branch on it. Without a connection it shows your edits only and says so; `--offline` skips the server. `diff [paths or kind:key…]` prints the edits as unified diffs (a binary file by its sizes), and `diff --server` compares the directory with what Sim holds now. Both take `--json` (or `--output json`). +`status` shows what would happen if you applied, without writing anything: the files you created, edited, or deleted, grouped by resource; what changed in Sim since the `get` (a resource edited, added, or deleted there, a workflow edited in the editor included); the conflicts, where a resource changed on both sides; and the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unapplied, and `12` when something changed in Sim since the `get`, so a script or an agent can branch on it. Its JSON `plan` counts errors and warnings as the dry run of the apply it names next would, a conflict as an error. Without a connection it shows your edits only and says so; `--offline` skips the server. `diff [paths or kind:key…]` prints the edits as unified diffs (a binary file by its sizes), and `diff --server` compares the directory with what Sim holds now. Both take `--json` (or `--output json`). ## Workspace API keys [#workspace-api-keys] @@ -82,7 +82,7 @@ To apply the rest with a workspace key, such as in CI, narrow the apply to the k - Something deleted in Sim is not re-created by an unchanged directory, and an edit to it is refused as stale. - Table rows are part of the directory only when the table's `rows` opts in (`tables/.rows.jsonl`). Connector-synced documents and run history never are. - Seed rows (`rows: { mode: 'seed' }`) belong to the directory: `get` keeps the declaration and the rows file beside it, but Sim does not store them, so a get into a new directory has the declaration without the file. -- A delete cannot be undone by applying an older copy of the directory, such as a reverted commit. The resource stays deleted, and its rows, documents, run history, webhook URLs and schedules are gone. The dry run marks each change that deletes data and counts them as `destructive`. +- A delete cannot be undone by applying an older copy of the directory, such as a reverted commit. The resource stays deleted, and its rows, documents, run history, webhook URLs and schedules are gone. The dry run marks each change that deletes data and counts them as `destructive`, a workflow update that removes blocks or variables included. ## Promote to another workspace From ff6416e013479e1a5a88a95219310f3511f1dc29 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:11:03 -0800 Subject: [PATCH 14/37] refactor: compute a workspace status's dry-run findings once and share the core.d.ts doc-comment walk --- .../src/commands/protocol/source-status.ts | 2 +- .../commands/protocol/workflow-run-follow.ts | 24 +++++++------- .../protocol/workspace-source-status.ts | 28 ++++++----------- .../workflow-sdk/src/codegen/reference.ts | 31 +++++++++---------- 4 files changed, 38 insertions(+), 47 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index f7e85c62740..7382720f6c6 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -39,7 +39,7 @@ export type ServerCheck = 'checked' | 'unreachable' | 'offline' */ export function planFindings( diagnostics: readonly Diagnostic[], - listed: (code: Diagnostic['code']) => boolean + listed: (code: Diagnostic['code']) => boolean = () => false ): Diagnostic[] { return diagnostics.filter( (finding) => diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index 18f4d8f7b26..fe6776f142c 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -586,18 +586,6 @@ function followOrDelegate(previous: ((args: unknown[]) => unknown) | null) { } } -/** - * Teaches the generated `workflows run` leaf to stream. - * - * `--follow` rides on `run` rather than standing up a sibling command because - * it is the same operation with a different response encoding: the input, - * output-selection, and `--async` flags all still apply, and a second command - * would have to restate every one of them and then drift. - * - * Commander offers no way to read the action it already holds, so the existing - * handler is captured for async execution. Synchronous execution uses the same - * generated request and result builders with a heartbeat-capable response. - */ /** `sim workflows run --help`, after the options: which version runs, what it prints, how it exits. */ const RUN_HELP = ` Without --manual (or a flag that implies it) this runs the active deployment; a workflow never @@ -612,6 +600,18 @@ Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the first, then the error on stderr), or the command failed; ${STILL_RUNNING_EXIT_CODE} still running when --wait-timeout elapsed.` +/** + * Teaches the generated `workflows run` leaf to stream. + * + * `--follow` rides on `run` rather than standing up a sibling command because + * it is the same operation with a different response encoding: the input, + * output-selection, and `--async` flags all still apply, and a second command + * would have to restate every one of them and then drift. + * + * Commander offers no way to read the action it already holds, so the existing + * handler is captured for async execution. Synchronous execution uses the same + * generated request and result builders with a heartbeat-capable response. + */ export function attachWorkflowRunFollow(workflows: Command): void { const run = workflows.commands.find((command) => command.name() === 'run') if (!run) { diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts index 61c588c836e..55f71dda9b1 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -247,22 +247,14 @@ function planAsApplied( } /** - * The dry run's findings the plan counts, as an apply's dry run would report them: all but the - * server changes the status lists, and none from compiling or linting a workflow folder an apply - * sends by its base (the server evaluates only a folder sent whole). A plan check about such a - * folder, such as one using a resource this apply deletes, still refuses the apply, so it stays. - */ -function workspacePlanFindings(data: PlanData, byBase: ReadonlySet): Diagnostic[] { - return dryRunFindings(data, byBase).filter((finding) => !isServerChangeFinding(finding.code)) -} - -/** - * The findings an apply's dry run would report. A workflow folder the apply sends by its base is - * neither evaluated (no compile or lint findings) nor written, so a server edit to it is drift, - * never a stale refusal: the status sent it whole to see that edit. + * The findings an apply's dry run would report, which the plan counts. A workflow folder the apply + * sends by its base is neither evaluated (no compile or lint findings) nor written, so a server + * edit to it is drift, never a stale refusal: the status sent it whole to see that edit. A plan + * check about such a folder, such as one using a resource this apply deletes, still refuses the + * apply, so it stays. */ function dryRunFindings(data: PlanData, byBase: ReadonlySet): Diagnostic[] { - return planFindings(data.diagnostics, () => false).filter( + return planFindings(data.diagnostics).filter( (finding) => !( aboutWorkflowSentByBase(finding, byBase) && @@ -442,10 +434,10 @@ export function attachWorkspaceSourceStatus(source: Command): void { ) : [] ) - const planned = data ? workspacePlanFindings(data, byBase) : [] - const plan = data - ? planSummary(dryRunFindings(data, byBase), applyPlan, status.conflicts.length) - : null + const dryRun = data ? dryRunFindings(data, byBase) : [] + // The server changes are listed by resource, so only the rest are printed as findings. + const planned = dryRun.filter((finding) => !isServerChangeFinding(finding.code)) + const plan = data ? planSummary(dryRun, applyPlan, status.conflicts.length) : null const report: StatusReport & { workspaceId: string | null } = { workspaceId, dir: options.dir, diff --git a/packages/workflow-sdk/src/codegen/reference.ts b/packages/workflow-sdk/src/codegen/reference.ts index abff2b4cb08..3e2aec49610 100644 --- a/packages/workflow-sdk/src/codegen/reference.ts +++ b/packages/workflow-sdk/src/codegen/reference.ts @@ -140,8 +140,19 @@ export function lookupBuilder(catalog: BlockCatalog, query: string): BuilderLook const MAX_CORE_LINES = 80 /** Each top-level declaration of `name` in `core.d.ts` (overloads included): its line range. */ +/** `core.d.ts` by line. */ +const CORE_LINES = CORE_DTS.split('\n') + +/** The line the doc comment above line `start` opens on, or `start` when none is there. */ +function docCommentStart(start: number): number { + if (!CORE_LINES[start - 1]?.trim().endsWith('*/')) return start + let first = start - 1 + while (first > 0 && !CORE_LINES[first].trim().startsWith('/**')) first-- + return first +} + function coreDeclarationRanges(name: string): Array<{ start: number; end: number }> { - const lines = CORE_DTS.split('\n') + const lines = CORE_LINES const start = new RegExp( `^export (?:declare )?(?:const|function|namespace|interface|type) ${escapeRegExp(name)}\\b` ) @@ -169,7 +180,7 @@ function coreDeclarationRanges(name: string): Array<{ start: number; end: number * returns an `Annotation`), one line per overload. */ function coreSignatures(name: string): string { - const lines = CORE_DTS.split('\n') + const lines = CORE_LINES return coreDeclarationRanges(name) .map(({ start, end }) => lines @@ -189,15 +200,10 @@ function coreSignatures(name: string): string { * above it, as the file holds it: what a construct the catalog does not generate takes. */ function coreDeclaration(name: string): string { - const lines = CORE_DTS.split('\n') const out: string[] = [] for (const { start, end } of coreDeclarationRanges(name)) { - let first = start - if (lines[start - 1]?.trim().endsWith('*/')) { - while (first > 0 && !lines[first].trim().startsWith('/**')) first-- - } if (out.length > 0) out.push('') - out.push(...lines.slice(first, end)) + out.push(...CORE_LINES.slice(docCommentStart(start), end)) } return out.slice(0, MAX_CORE_LINES).join('\n') } @@ -206,14 +212,7 @@ function coreDeclaration(name: string): string { function docOf(name: string): Pick { const range = coreDeclarationRanges(name)[0] if (!range) return {} - const lines = CORE_DTS.split('\n') - if (!lines[range.start - 1]?.trim().endsWith('*/')) return {} - const comment: string[] = [] - for (let index = range.start - 1; index >= 0; index--) { - comment.unshift(lines[index]) - if (lines[index].trim().startsWith('/**')) break - } - const doc = comment + const doc = CORE_LINES.slice(docCommentStart(range.start), range.start) .map((line) => line.trim().replace(/^\/\*\*\s?|\s?\*\/$|^\*\s?/g, '')) .join(' ') .replace(/\s+/g, ' ') From 195e4e29b81f9a559610d19c8dab8af73f86f4a2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:12:38 -0800 Subject: [PATCH 15/37] refactor: type the canonical-name pass without any and tidy its neighbours' docs --- apps/sim/lib/workflows/editing/validation.ts | 6 +++--- .../sim-cli/src/commands/protocol/workspace-source-apply.ts | 4 ++-- packages/workflow-sdk/src/codegen/reference.ts | 3 +-- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/apps/sim/lib/workflows/editing/validation.ts b/apps/sim/lib/workflows/editing/validation.ts index 765e13770fc..1e2888e6006 100644 --- a/apps/sim/lib/workflows/editing/validation.ts +++ b/apps/sim/lib/workflows/editing/validation.ts @@ -116,13 +116,13 @@ function isContainerBlockType(blockType: string): blockType is 'loop' | 'paralle function withCanonicalNamesResolved( subBlocks: readonly SubBlockConfig[], subBlockMap: ReadonlyMap, - inputs: Record, + inputs: Record, refuse: (key: string, error: string) => void -): Record { +): Record { if (Object.keys(inputs).every((key) => subBlockMap.has(key))) return inputs // canonical-index-unscoped: maps written names to member ids and reads no values. const { groupsById } = buildCanonicalIndex(subBlocks) - const resolved: Record = {} + const resolved: Record = {} for (const [key, value] of Object.entries(inputs)) { const group = subBlockMap.has(key) ? undefined : groupsById[key] if (!group) { diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 5535f2ef6ba..8c5c562a536 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -143,8 +143,8 @@ function refusesApply(data: ApplyData): boolean { /** * The exit status of a dry run with errors, as the apply would exit: one that holds changes back - * and refuses nothing else writes the rest, so it exits 15 (`SOURCE_HELD_EXIT_CODE`) as that apply does, unless every - * change it would write is held (1, nothing written). + * and refuses nothing else writes the rest, so it exits `SOURCE_HELD_EXIT_CODE` as that apply + * does, unless every change it would write is held (1, nothing written). */ function previewExitCode(data: ApplyData): number { if (refusesApply(data)) return refusedExitCode(data.diagnostics) diff --git a/packages/workflow-sdk/src/codegen/reference.ts b/packages/workflow-sdk/src/codegen/reference.ts index 3e2aec49610..8cf1736be75 100644 --- a/packages/workflow-sdk/src/codegen/reference.ts +++ b/packages/workflow-sdk/src/codegen/reference.ts @@ -139,8 +139,6 @@ export function lookupBuilder(catalog: BlockCatalog, query: string): BuilderLook const MAX_CORE_LINES = 80 -/** Each top-level declaration of `name` in `core.d.ts` (overloads included): its line range. */ -/** `core.d.ts` by line. */ const CORE_LINES = CORE_DTS.split('\n') /** The line the doc comment above line `start` opens on, or `start` when none is there. */ @@ -151,6 +149,7 @@ function docCommentStart(start: number): number { return first } +/** Each top-level declaration of `name` in `core.d.ts` (overloads included): its line range. */ function coreDeclarationRanges(name: string): Array<{ start: number; end: number }> { const lines = CORE_LINES const start = new RegExp( From 5cae2c4f6dcf16a78bc360a0a42230501f617a3b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 03:52:05 -0800 Subject: [PATCH 16/37] fix(workflow-code): show a block's error output on in the outline when an error edge leaves it The executor takes an error edge whatever the stored errorEnabled flag says, and an operations edit that wires one leaves the flag false, so the outline reported the error output off while the path fired. The outline now reads the flag as the editor draws the port (flag or error edge). --- .../sanitization/json-sanitizer.test.ts | 37 +++++++++++++++++++ .../workflows/sanitization/json-sanitizer.ts | 8 +++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/apps/sim/lib/workflows/sanitization/json-sanitizer.test.ts b/apps/sim/lib/workflows/sanitization/json-sanitizer.test.ts index a83771e4f54..2c9c490ad29 100644 --- a/apps/sim/lib/workflows/sanitization/json-sanitizer.test.ts +++ b/apps/sim/lib/workflows/sanitization/json-sanitizer.test.ts @@ -161,6 +161,43 @@ describe('sanitizeForCopilot condition rows', () => { }) }) +describe('sanitizeForCopilot error output', () => { + // The executor takes an error edge whatever the stored flag says (an operations edit that wires + // one leaves the flag false), so the read view must not report the error output as off. + function blockWithFlag(errorEnabled: boolean | undefined, errorEdge: boolean) { + const fn = (id: string) => ({ + id, + type: 'function', + name: id, + position: { x: 0, y: 0 }, + enabled: true, + outputs: {}, + subBlocks: {}, + ...(id === 'risky' && errorEnabled !== undefined ? { errorEnabled } : {}), + }) + const state = { + blocks: { risky: fn('risky'), handler: fn('handler') }, + edges: errorEdge + ? [{ id: 'e1', source: 'risky', target: 'handler', sourceHandle: 'error' }] + : [], + loops: {}, + parallels: {}, + } as unknown as WorkflowState + return sanitizeForCopilot(state).blocks.risky.errorEnabled + } + + it('reports the error output on for a block an error edge leaves, whatever its flag', () => { + expect(blockWithFlag(false, true)).toBe(true) + expect(blockWithFlag(undefined, true)).toBe(true) + }) + + it('keeps the stored flag for a block no error edge leaves', () => { + expect(blockWithFlag(false, false)).toBe(false) + expect(blockWithFlag(true, false)).toBe(true) + expect(blockWithFlag(undefined, false)).toBeUndefined() + }) +}) + describe('sanitizeForCopilot server-only block inputs', () => { it('omits Sim Chat secret-mount policy while retaining model-visible inputs', () => { const result = sanitizeForCopilot( diff --git a/apps/sim/lib/workflows/sanitization/json-sanitizer.ts b/apps/sim/lib/workflows/sanitization/json-sanitizer.ts index 37538ad5fa3..02bb6a9e053 100644 --- a/apps/sim/lib/workflows/sanitization/json-sanitizer.ts +++ b/apps/sim/lib/workflows/sanitization/json-sanitizer.ts @@ -4,9 +4,11 @@ import { generateParallelBlocks, } from '@sim/workflow-persistence/subflow-helpers' import { + collectErrorSourceBlockIds, getWorkflowBranchHandleRowId, isSubflowType, normalizeWorkflowEdgeSourceHandle, + resolveEffectiveErrorEnabled, } from '@sim/workflow-types/workflow' import type { Edge } from '@xyflow/react' import { buildWebhookTriggerUrl } from '@/lib/webhooks/trigger-url' @@ -550,6 +552,7 @@ export function sanitizeForCopilot( ): CopilotWorkflowState { const sanitizedBlocks: Record = {} const processedBlocks = new Set() + const errorSourceBlockIds = collectErrorSourceBlockIds(state.edges) // Helper to find child blocks of a parent (loop/parallel container) const findChildBlocks = (parentId: string): string[] => { @@ -651,7 +654,10 @@ export function sanitizeForCopilot( if (connections) result.connections = connections if (Object.keys(nestedNodes).length > 0) result.nestedNodes = nestedNodes if (block.advancedMode !== undefined) result.advancedMode = block.advancedMode - if (block.errorEnabled !== undefined) result.errorEnabled = block.errorEnabled + // The executor takes the error path whenever an error edge leaves the block, whatever the + // flag says, so the flag is shown as the editor draws the port: on with such an edge. + const errorEnabled = resolveEffectiveErrorEnabled(block, blockId, errorSourceBlockIds) + if (block.errorEnabled !== undefined || errorEnabled) result.errorEnabled = errorEnabled if (block.retry !== undefined) result.retry = block.retry if (block.triggerMode !== undefined) result.triggerMode = block.triggerMode From ea0d6881494aa25a33f76a01bb8a1a8c22998b75 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 03:52:55 -0800 Subject: [PATCH 17/37] fix(executor): name the undeployed child a deployed run cannot call and say to deploy it A deployed parent calling a child with no active deployment failed with "" failed: Child workflow is not deployed. The failure now carries the child's name and id and says a deployed run calls each child's deployed version. --- .../handlers/workflow/handler.test.ts | 26 ++++++++++++++++ .../sim/executor/handlers/workflow/handler.ts | 31 ++++++++++++------- 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/apps/sim/executor/handlers/workflow/handler.test.ts b/apps/sim/executor/handlers/workflow/handler.test.ts index 140bad47f89..2f0cbad2274 100644 --- a/apps/sim/executor/handlers/workflow/handler.test.ts +++ b/apps/sim/executor/handlers/workflow/handler.test.ts @@ -332,6 +332,32 @@ describe('WorkflowBlockHandler', () => { }) }) + describe('deployed runs', () => { + it('names the undeployed child a deployed run cannot call, and says to deploy it', async () => { + mockReadWorkflowDefinitionAsExecutor.mockResolvedValueOnce({ + workflow: { id: 'child-workflow-id', name: 'Score', variables: {} }, + workspaceId: 'test-workspace-id', + state: null, + }) + + const failure = await handler + .execute({ ...mockContext, isDeployedContext: true }, mockBlock, { + workflowId: 'child-workflow-id', + }) + .then( + () => null, + (error: unknown) => error + ) + + expect(failure).toMatchObject({ + childWorkflowName: 'Score', + message: + '"Score" failed: Child workflow "Score" (child-workflow-id) is not deployed. A deployed run calls the deployed version of each child workflow: deploy "Score" (child-workflow-id), then run again.', + }) + expect(mockExecutorExecute).not.toHaveBeenCalled() + }) + }) + describe('workspace containment', () => { const inputs = { workflowId: 'child-workflow-id' } diff --git a/apps/sim/executor/handlers/workflow/handler.ts b/apps/sim/executor/handlers/workflow/handler.ts index ac17f6804e1..2236947cde1 100644 --- a/apps/sim/executor/handlers/workflow/handler.ts +++ b/apps/sim/executor/handlers/workflow/handler.ts @@ -385,7 +385,10 @@ export class WorkflowBlockHandler implements BlockHandler { // safe to cross the invocation boundary verbatim (it names no source // internals), so the catch forwards it instead of the generic failure. if (isCustomBlock) { - const deployed = await this.checkChildDeployment(workflowId, workflowReadDelegationOrigin) + const { deployed } = await this.readChildDeployment( + workflowId, + workflowReadDelegationOrigin + ) if (!deployed) { throw new BoundarySafeError({ errorType: 'not_deployed', @@ -395,13 +398,12 @@ export class WorkflowBlockHandler implements BlockHandler { } if (useDeployed && !isCustomBlock) { - const hasActiveDeployment = await this.checkChildDeployment( - workflowId, - workflowReadDelegationOrigin - ) - if (!hasActiveDeployment) { + const deployment = await this.readChildDeployment(workflowId, workflowReadDelegationOrigin) + if (!deployment.deployed) { + const child = deployment.name ? `"${deployment.name}" (${workflowId})` : workflowId + if (deployment.name) childWorkflowName = deployment.name throw new Error( - `Child workflow is not deployed. Please deploy the workflow before invoking it.` + `Child workflow ${child} is not deployed. A deployed run calls the deployed version of each child workflow: deploy ${child}, then run again.` ) } } @@ -1375,17 +1377,24 @@ export class WorkflowBlockHandler implements BlockHandler { } } - private async checkChildDeployment( + /** + * Whether the child has an active deployment, and its name when the read found the workflow, so + * a refusal can say which child to deploy. + */ + private async readChildDeployment( workflowId: string, origin: ExecutorDelegationOrigin - ): Promise { + ): Promise<{ deployed: boolean; name?: string }> { try { const definition = await readWorkflowDefinitionAsExecutor({ origin, workflowId, state: 'deployed', }) - return definition.state !== null + return { + deployed: definition.state !== null, + ...(definition.workflow.name ? { name: definition.workflow.name } : {}), + } } catch (error) { if (error instanceof DelegatedWorkspaceAuthorizationError) { throw childReadError(error, workflowId) @@ -1394,7 +1403,7 @@ export class WorkflowBlockHandler implements BlockHandler { errorName: toError(error).name, hasWorkflowId: workflowId.length > 0, }) - return false + return { deployed: false } } } From 5af85f2f7a1f461c2bf837c3d40841bf58b5cbe6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:04:33 -0800 Subject: [PATCH 18/37] fix(workflow-editing): name the fields that share a canonical param an operations edit writes beside one of them An operations edit now writes a canonical name (tableId) into its member field, so the only refusal left is a canonical name set beside one of its own members. That refusal now names every field sharing the name, with its mode, and the one the edit also set. --- apps/sim/lib/workflows/editing/validation.test.ts | 11 +++++++++-- apps/sim/lib/workflows/editing/validation.ts | 9 ++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/workflows/editing/validation.test.ts b/apps/sim/lib/workflows/editing/validation.test.ts index bfc34bdfb26..b9b0ad606dc 100644 --- a/apps/sim/lib/workflows/editing/validation.test.ts +++ b/apps/sim/lib/workflows/editing/validation.test.ts @@ -399,7 +399,11 @@ describe('validateInputsForBlock', () => { expect(result.validInputs).toEqual({ credential: 'cred_2' }) expect(result.errors).toEqual([ - expect.objectContaining({ field: 'cred', error: expect.stringContaining('"credential"') }), + expect.objectContaining({ + field: 'cred', + error: + '"cred" is the shared name of "credential" (basic mode) and "manualCredential" (advanced mode), and this edit also sets "credential": set one of them, not both', + }), ]) }) @@ -407,7 +411,10 @@ describe('validateInputsForBlock', () => { const result = validateInputsForBlock('canonicalcred', { credKey: 'cred_1' }, 'cred-1') expect(result.errors).toEqual([ - expect.objectContaining({ field: 'credKey', error: expect.stringContaining('Unknown') }), + expect.objectContaining({ + field: 'credKey', + error: 'Unknown input field "credKey" for block type "canonicalcred"', + }), ]) }) }) diff --git a/apps/sim/lib/workflows/editing/validation.ts b/apps/sim/lib/workflows/editing/validation.ts index 1e2888e6006..31da0d6ce43 100644 --- a/apps/sim/lib/workflows/editing/validation.ts +++ b/apps/sim/lib/workflows/editing/validation.ts @@ -134,9 +134,16 @@ function withCanonicalNamesResolved( ) const written = members.filter((id) => Object.hasOwn(inputs, id)) if (written.length > 0) { + const named = members.map((id) => + id === group.basicId + ? group.advancedIds.length > 0 + ? `"${id}" (basic mode)` + : `"${id}"` + : `"${id}" (advanced mode)` + ) refuse( key, - `"${key}" is stored in ${written.map((id) => `"${id}"`).join(', ')}, which this edit also sets: write one of them` + `"${key}" is the shared name of ${named.join(' and ')}, and this edit also sets ${written.map((id) => `"${id}"`).join(' and ')}: set one of them, not both` ) continue } From 1a10fda69fbaf81049ba74c2e3f25c9f432cb5df Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:04:34 -0800 Subject: [PATCH 19/37] fix(workflow-code): bring check to parity with the run for loop conditions, locks and child results - A while or do-while condition that is not a JavaScript expression once its references stand in as values is W_LOOP_CONDITION_SYNTAX, refused on an edited loop as E_APPLY_LOOP_CONDITION_SYNTAX: the run fails evaluating it. - A loop reading its own index by name in its condition is W_REF_OUT_OF_SCOPE with a hint: the condition is evaluated outside the loop's body. - check fails on a lock every apply and status refuses (a cap over its limit, bad JSON), and the lock refusal now says how to recover. - In a workspace directory, a reference to a child call's result. whose child responds is W_CHILD_RESULT_PATH, with result.data. as the hint. --- .../src/commands/protocol/source-check.ts | 155 ++++++++++++++++-- .../src/commands/protocol/workflow-dir.ts | 21 ++- .../protocol/workflow-source-check.test.ts | 51 ++++++ .../protocol/workflow-source-check.ts | 17 +- .../protocol/workspace-source-check.test.ts | 53 +++++- .../protocol/workspace-source-check.ts | 9 +- .../commands/protocol/workspace-source-dir.ts | 5 + packages/workflow-code/src/compile/SYNTAX.md | 2 + packages/workflow-code/src/compile/blocks.ts | 86 +++++++++- .../workflow-code/src/compile/checks.test.ts | 51 ++++++ .../workflow-code/src/diagnostics/codes.ts | 15 ++ .../workflow-code/src/diagnostics/refusals.ts | 8 +- 12 files changed, 438 insertions(+), 35 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index 70fede6d355..e2e695e31fa 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -35,7 +35,7 @@ import type { Command } from 'commander' import { setSoftExitCode } from '../../embed-context' import { SourceDirError } from './local-errors' import { printProtocolResult } from './result' -import { digest, readFolderWritten, readSourceJson, readSourceText } from './source-dir' +import { digest, readFolderWritten, readSourceText } from './source-dir' import { cachedCatalog, cachedSourceCatalog, @@ -44,7 +44,7 @@ import { } from './source-tree' import { type Diagnostic, findingsOutput } from './source-ui' import { blockDigest, readStoredBlockDigests, readStoredEdges } from './stored-edges' -import { readSourceFiles } from './workflow-dir' +import { lockRecoveryHint, readSourceFiles } from './workflow-dir' import { kindFolders, WORKSPACE_TREE, type WorkspaceDeclarations } from './workspace-source-dir' /** @@ -66,9 +66,11 @@ const STRICT_CODES: ReadonlySet = new Set([ 'W_LITERAL_SECRET', 'W_TABLE_UNKNOWN_COLUMN', 'W_CHILD_INPUT_UNKNOWN', + 'W_CHILD_RESULT_PATH', 'W_BRANCH_UNWIRED', 'W_UNRESOLVED_REF', 'W_REF_OUT_OF_SCOPE', + 'W_LOOP_CONDITION_SYNTAX', ]) /** @@ -286,6 +288,76 @@ function childInputFindings( })) } +/** The block type whose output a responding child workflow's run returns. */ +const RESPONSE_BLOCK_TYPE = 'response' + +/** The output of a Response block: what a responding child's `result` holds. */ +const RESPONSE_OUTPUTS: readonly string[] = ['data', 'status', 'headers'] + +/** A reference tag in canonical text, as the executor's resolver finds one. */ +const REFERENCE_TAG = /<([^<>]+)>/g + +/** The workflow a child workflow call names by key, or `null` for an id, a reference or none. */ +function calledWorkflowKey(canonical: CanonicalWorkflow['blocks'][string]): string | null { + const ref = canonical.params.workflowId + const child = ref?.kind === 'value' ? resourceNode(ref.value) : null + return child?.kind === 'workflow' ? child.key : null +} + +/** Every string inside a value, depth first. */ +function stringLeaves(value: unknown): string[] { + if (typeof value === 'string') return [value] + if (Array.isArray(value)) return value.flatMap(stringLeaves) + if (isRecordLike(value)) return Object.values(value).flatMap(stringLeaves) + return [] +} + +/** + * `W_CHILD_RESULT_PATH` for each reference to `>` whose call runs a workflow of + * this directory that responds, when `` is not one of the Response block's outputs: the + * child's `result` is then `{ data, status, headers }`, so the path reads nothing at run time. + */ +function childResultFindings( + workflow: CanonicalWorkflow, + declarations: WorkspaceDeclarations +): ParamFinding[] { + const responding = declarations.respondingWorkflows + if (!responding || responding.size === 0) return [] + const calls = new Map() + for (const [key, block] of Object.entries(workflow.blocks)) { + const child = calledWorkflowKey(block) + if (child !== null && responding.has(child)) calls.set(key, child) + } + if (calls.size === 0) return [] + const findings: ParamFinding[] = [] + for (const [block, canonical] of Object.entries(workflow.blocks)) { + for (const [param, value] of Object.entries(canonical.params)) { + if (value.kind !== 'value') continue + const reported = new Set() + for (const text of stringLeaves(value.value)) { + for (const [, inner] of text.matchAll(REFERENCE_TAG)) { + const [head = '', output, key, ...rest] = inner.split('.') + const child = calls.get(head) + const field = key?.replace(/\[.*$/, '') + if (child === undefined || output !== 'result' || !field) continue + if (RESPONSE_OUTPUTS.includes(field) || reported.has(inner)) continue + reported.add(inner) + const meant = [head, output, 'data', key, ...rest].join('.') + findings.push({ + code: 'W_CHILD_RESULT_PATH', + severity: 'warning', + message: `<${inner}> reads ${field} from the result of workflow "${child}", which responds: its result is the Response output ({ data, status, headers }), so the path reads nothing.`, + hint: `Did you mean <${meant}>? A field of the child's Response data is result.data.${field}.`, + block, + param, + }) + } + } + } + } + return findings +} + /** * The findings a compile cannot make without the workspace's declarations: a resource key the * directory does not declare (an apply fails on it), and a table row write naming a column, or a @@ -358,6 +430,7 @@ function declarationFindings( } } } + findings.push(...childResultFindings(workflow, declarations)) return findings } @@ -372,7 +445,9 @@ async function compileWorkflowDir( workspaceCatalog: BlockCatalog, declarations?: WorkspaceDeclarations ) { - const { lock } = parseWorkflowLock(await readSourceJson(dir, SOURCE_LOCK_FILE)) + const lockText = await readSourceText(dir, SOURCE_LOCK_FILE) + const parsedLock = lockText === null ? null : parseWorkflowLock(parseJsonText(lockText)) + const lock = parsedLock?.lock const [files, storedEdges, storedBlocks, printedWith] = await Promise.all([ readSourceFiles(dir, lock ?? null), readStoredEdges(dir), @@ -391,24 +466,58 @@ async function compileWorkflowDir( ...(storedEdges ? { storedUnreadEdges: storedEdges } : {}), ...(envNames ? { envNames, envDeclaredIn: KIND_DIRS.secret } : {}), }) - return { lock, files, compiled, storedBlocks, printedWith, catalog } + return { + lock, + lockProblems: parsedLock?.diagnostics ?? [], + files, + compiled, + storedBlocks, + printedWith, + catalog, + } } -/** - * The inputs of each workflow of the workspace directory `root` that compiles (`startInputs`, - * `null` for one without a Start trigger), by key: what a child workflow call is checked against - * and what `workspace.d.ts` types its `inputMapping` with. - */ -export async function workspaceWorkflowInputs( +/** Text parsed as JSON, or the text itself when it is not JSON, which the lock parser refuses. */ +function parseJsonText(text: string): unknown { + try { + return JSON.parse(text) + } catch { + return text + } +} + +/** What a child workflow call is checked against, for each workflow of a workspace directory. */ +export interface WorkspaceWorkflows { + /** + * The inputs of each workflow that compiles (`startInputs`, `null` for one without a Start + * trigger), by key: what a call's `inputMapping` is checked against and what `workspace.d.ts` + * types it with. + */ + inputs: Map + /** + * The keys of the workflows that compile holding an enabled Response block: a call's `result` + * is then that block's output, `{ data, status, headers }`. + */ + responding: Set +} + +/** Compiles each workflow of the workspace directory `root` for {@link WorkspaceWorkflows}. */ +export async function workspaceWorkflows( root: string, catalog: BlockCatalog -): Promise> { +): Promise { const inputs = new Map() + const responding = new Set() for (const key of await workspaceWorkflowKeys(root)) { const { compiled } = await compileWorkflowDir(join(root, KIND_DIRS.workflow, key), catalog) - if (compiled.workflow) inputs.set(key, startInputs(compiled.workflow)) + if (!compiled.workflow) continue + inputs.set(key, startInputs(compiled.workflow)) + const blocks = Object.values(compiled.workflow.blocks) + if (blocks.some((block) => block.type === RESPONSE_BLOCK_TYPE && block.enabled !== false)) { + responding.add(key) + } } - return inputs + return { inputs, responding } } /** @@ -439,7 +548,7 @@ export async function checkWorkflowDir( options: { declarations?: WorkspaceDeclarations; strict: StrictMode; prefix?: string } ): Promise<{ findings: CheckFinding[]; entry: string; unlisted: UnlistedCounts }> { const compiledDir = await compileWorkflowDir(dir, catalog, options.declarations) - const { lock, files, compiled, storedBlocks, printedWith } = compiledDir + const { lock, lockProblems, files, compiled, storedBlocks, printedWith } = compiledDir const entryText = files[SOURCE_ENTRY_FILE] const locate = (block: string, param: string, names: string | undefined) => { const prefix = encodeAnchor({ kind: 'param', block, param: '' }) @@ -577,6 +686,22 @@ export async function checkWorkflowDir( ), ...compiled.diagnostics.filter(exempt), ] + const prefixed = (file: string) => `${options.prefix ?? ''}${file}` + // A lock every apply and status refuses fails the check too, however clean the source is. + const lockFindings = lockProblems.map( + (problem): CheckFinding => ({ + code: problem.code, + severity: 'error', + message: `${problem.message} Every apply and status refuses this lock.`, + hint: lockRecoveryHint( + options.declarations + ? '`sim workspaces source get --dir `, from the workspace directory' + : undefined + ), + file: prefixed(SOURCE_LOCK_FILE), + ...(problem.path ? { path: problem.path } : {}), + }) + ) const findings = [ ...refused.filter((diagnostic) => reported(diagnostic.code, diagnostic.blockKey)), ...declared, @@ -629,7 +754,7 @@ export async function checkWorkflowDir( if (isRefused || (!varies && fails(code, blockKey))) unlisted.errors += count else unlisted.warnings += count } - return { findings, entry: entryText, unlisted } + return { findings: [...lockFindings, ...findings], entry: entryText, unlisted } } /** Findings a check counts but does not list: those the compile's caps left out. */ diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index c983e1ef687..28addb81069 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -130,15 +130,28 @@ export async function readBase( return base } +/** The command that writes a fresh copy of a workflow source directory, for {@link lockRecoveryHint}. */ +const WORKFLOW_GET = `\`sim workflows source get --dir \`, with the id from ${SOURCE_BASE_FILE}` + +/** + * How to recover from a lock no apply accepts: the CLI writes the lock, so the fix is a copy it + * wrote, not an edit. `get` is the command that writes a fresh directory. + */ +export function lockRecoveryHint(get: string = WORKFLOW_GET): string { + return `Restore ${SOURCE_LOCK_FILE} from version control, or write the source into a fresh directory (${get}) and carry your edits across.` +} + +/** A lock problem as one line: its path in the lock, then what is wrong. */ +function lockProblem(finding: { path?: string; message: string }): string { + return `${finding.path ? `${finding.path}: ` : ''}${finding.message}` +} + /** The directory's lock, refused with every problem the lock parser finds. */ export async function readLock(directory: string): Promise { const parsed = parseWorkflowLock(await readJson(directory, SOURCE_LOCK_FILE, GET_HINT)) if (parsed.lock) return parsed.lock - const problems = parsed.diagnostics.map( - (finding) => `${finding.path === '' ? '' : `${finding.path}: `}${finding.message}` - ) throw new SourceDirError( - `${SOURCE_LOCK_FILE} in ${directory} is not a valid lock: ${problems.join('; ')}` + `${SOURCE_LOCK_FILE} in ${directory} is not a valid lock: ${parsed.diagnostics.map(lockProblem).join('; ')}. ${lockRecoveryHint()}` ) } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts index 2bc359fe850..04065e0b1b0 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts @@ -284,6 +284,57 @@ describe('sim workflows source check', () => { expect(process.exitCode).toBe(1) }) + it('fails on a lock every apply refuses, a block cap over its limit included, saying how to recover', async () => { + cacheCatalog() + writeFileSync(join(dir, 'workflow.ts'), CLEAN) + const blocks = Object.fromEntries( + Array.from({ length: 2001 }, (_, index) => [ + `b${index}`, + { id: `id-${index}`, parent: null, ident: `b${index}`, order: index }, + ]) + ) + writeFileSync( + join(dir, '.sim/lock.json'), + JSON.stringify({ version: 1, blocks, variables: {} }) + ) + + await check() + + expect(result()).toMatchObject({ errors: 1 }) + expect(result().diagnostics).toEqual([ + expect.objectContaining({ + code: 'E_LOCK_SHAPE', + severity: 'error', + file: '.sim/lock.json', + path: '/blocks', + message: 'Expected at most 2000 entries. Every apply and status refuses this lock.', + hint: expect.stringContaining( + 'Restore .sim/lock.json from version control, or write the source into a fresh directory (`sim workflows source get --dir `' + ), + }), + ]) + expect(process.exitCode).toBe(1) + }) + + it('fails on a lock that is not JSON, and passes with no lock at all', async () => { + cacheCatalog() + writeFileSync(join(dir, 'workflow.ts'), CLEAN) + writeFileSync(join(dir, '.sim/lock.json'), '{ "version": 1,') + + await check() + + expect(result()).toMatchObject({ errors: 1 }) + expect(findingLines()).toContain('error E_LOCK_JSON') + expect(process.exitCode).toBe(1) + + process.exitCode = undefined + vi.mocked(console.log).mockClear() + rmSync(join(dir, '.sim/lock.json')) + await check() + expect(result()).toMatchObject({ errors: 0 }) + expect(process.exitCode).toBeUndefined() + }) + it('refuses a codeFile() path holding a NUL byte by its code, reading no such file', async () => { cacheCatalog() writeFileSync( diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts index f94cd15c58e..b82a8893129 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -13,7 +13,7 @@ import { strictFlags, strictMode, withWorkflowInputs, - workspaceWorkflowInputs, + workspaceWorkflows, } from './source-check' import { absoluteDirOption, @@ -96,12 +96,15 @@ export function attachWorkflowSourceCheck(source: Command): void { ? `\`sim workspaces source get --dir ${workspace.root}\`` : `\`sim workflows source get --dir ${options.dir}\` (or \`create\`)` ) - const declarations = workspace - ? { - ...(await readWorkspaceDeclarations(workspace.root)), - workflowInputs: await workspaceWorkflowInputs(workspace.root, catalog), - } - : undefined + const workflows = workspace ? await workspaceWorkflows(workspace.root, catalog) : undefined + const declarations = + workspace && workflows + ? { + ...(await readWorkspaceDeclarations(workspace.root)), + workflowInputs: workflows.inputs, + respondingWorkflows: workflows.responding, + } + : undefined const { findings, entry, unlisted } = await checkWorkflowDir(options.dir, catalog, { strict: strictMode(options), ...(declarations ? { declarations } : {}), diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts index 85fb144101a..5c012f69cc3 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts @@ -395,7 +395,7 @@ describe('sim workspaces source check', () => { function workflowFile(...lines: string[]): string { return [ '// @sim-sdk 1', - "import { agent, childWorkflow, env, runWorkflow, skill, trigger, workflow } from '@sim/workflow-sdk'", + "import { agent, childWorkflow, env, fn, js, response, runWorkflow, skill, t, trigger, workflow } from '@sim/workflow-sdk'", "export default workflow('W', {}, () => {", ...lines.map((line) => ` ${line}`), '})', @@ -471,6 +471,57 @@ describe('sim workspaces source check', () => { ]) }) + it("warns on a child call's result. when the child responds, naming result.data.", async () => { + writeFile( + 'workflows/responder/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { q: 'string' } })", + "const reply = response('Reply', { body: { mobile: start.q } })", + 'start.to(reply)' + ) + ) + writeFile( + 'workflows/silent/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { q: 'string' } })", + "const echo = fn('Echo', { code: js`return { mobile: ${start.q} }` })", + 'start.to(echo)' + ) + ) + writeFile( + 'workflows/parent/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { q: 'string' } })", + "const call = runWorkflow('Call', { workflowId: childWorkflow('responder'), inputMapping: { q: start.q } })", + "const other = runWorkflow('Other', { workflowId: childWorkflow('silent'), inputMapping: { q: start.q } })", + "const use = fn('Use', { code: js`return [${call.result.mobile}, ${call.result.data.mobile}, ${other.result.mobile}]` })", + "const reply = response('Reply', { body: { mobile: t`${call.result.mobile}`, ok: t`${call.result.status}` } })", + 'start.to(call)', + 'call.to(other)', + 'other.to(use)', + 'use.to(reply)' + ) + ) + + await check() + + const found = (stdoutJson().diagnostics as Array>).filter( + (finding) => finding.code === 'W_CHILD_RESULT_PATH' + ) + expect(found).toEqual([ + expect.objectContaining({ + code: 'W_CHILD_RESULT_PATH', + file: 'workflows/parent/workflow.ts', + line: 7, + message: expect.stringContaining( + ' reads mobile from the result of workflow "responder"' + ), + hint: expect.stringContaining('Did you mean ?'), + }), + expect.objectContaining({ code: 'W_CHILD_RESULT_PATH', line: 8 }), + ]) + }) + it('points an unknown env name at secrets.ts', async () => { writeFile( 'secrets.ts', diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts index 3bc84ae964d..3eef68366b3 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts @@ -17,8 +17,8 @@ import { strictFlags, strictMode, withWorkflowInputs, - workspaceWorkflowInputs, workspaceWorkflowKeys, + workspaceWorkflows, } from './source-check' import { absoluteDirOption, @@ -125,10 +125,11 @@ export function attachWorkspaceSourceCheck(source: Command): void { await withSourceDirLock(options.dir, async () => { const catalog = cachedCatalog(workspaceId) ?? (await fetchedCatalog(connect, workspaceId, options.dir)) - const workflowInputs = await workspaceWorkflowInputs(options.dir, catalog) + const workflows = await workspaceWorkflows(options.dir, catalog) const declarations = { ...(await readWorkspaceDeclarations(options.dir)), - workflowInputs, + workflowInputs: workflows.inputs, + respondingWorkflows: workflows.responding, } const keys = await workspaceWorkflowKeys(options.dir) const findings: CheckFinding[] = [] @@ -168,7 +169,7 @@ export function attachWorkspaceSourceCheck(source: Command): void { } await refreshWorkspaceTypes( options.dir, - withWorkflowInputs(declarations.local, workflowInputs) + withWorkflowInputs(declarations.local, workflows.inputs) ) await refreshWorkspaceTsconfigs(options.dir, workspaceId) reportCheck( diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index 7a98d1189f4..4808f660c0d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -314,6 +314,11 @@ export interface WorkspaceDeclarations { * key, for the workflows that compiled; set by a check, which compiles them. */ workflowInputs?: ReadonlyMap + /** + * The keys of the workflows that compiled holding an enabled Response block, whose `result` is + * that block's output; set by a check, which compiles them. + */ + respondingWorkflows?: ReadonlySet } /** diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index df584b1c3be..bbd89483ca2 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -403,6 +403,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `W_ENV_UNKNOWN` | `env.X`, or a code file `$env`, naming a variable the workspace does not hold (checked only when the env names are known); the hint has a did-you-mean. An offline check in a workspace directory knows only the names `secrets.ts` declares, so there the finding says `secrets.ts` does not declare it, and the hint points there. | | `W_CHILD_INPUT_UNKNOWN` | A child workflow call's `inputMapping` sets an input the child's Start trigger does not declare (`sim workspaces source check`, with the child in the same directory); the hint names the nearest input. | | `W_CHILD_NO_START` | A child workflow call names a workflow of the same directory that has no Start trigger (`sim workspaces source check`). | +| `W_CHILD_RESULT_PATH` | A reference to a child workflow call's `result.` whose child (in the same directory) holds a Response block, where `` is not `data`, `status` or `headers`: the child's result is its Response output, so the path reads nothing (`sim workspaces source check`); the hint names `result.data.`. The dry run reports the same reference as a `W_APPLY_LINT` warning. | | `E_UNKNOWN_SUBFLOW_PROPERTY` | `p.` that a loop or parallel does not have. | | `W_FORWARD_REF` | A ref to a block declared later; it resolves. | | `W_REF_NOT_NORMALIZED` | Hand-written `` text that is not in key form. | @@ -442,6 +443,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `W_UNKNOWN_OUTPUT_PATH` | A ref path the block's outputs do not have; the hint has a did-you-mean or lists the outputs. | | `W_OUTPUT_PATH_UNDECLARED` | A path the block does not declare that the run still accepts: an undeclared `inputFormat` input, or `x.error` with no error edge. Never refused. | | `W_JSON_REF_UNTYPED` | A bare ref in a JSON literal whose type nothing declares. | +| `W_LOOP_CONDITION_SYNTAX` | A while or do-while condition that is not a JavaScript expression once each reference stands in as a value, as the run evaluates it (`return Boolean()`): the run fails there. Refused as `E_APPLY_LOOP_CONDITION_SYNTAX` on a loop the edit added or changed. A loop reading its own `index` (or `currentItem`, `items`) by its name in its condition is `W_REF_OUT_OF_SCOPE`: the condition is evaluated outside the loop's body, so only `` reads the iteration there. | | `E_CODE_FILE_MISSING` | `codeFile()` names a file the request did not send. | | `E_CODE_FILE_PATH` | A code file path outside the directory, or with the wrong extension. | | `W_CODE_FILE_INLINED` | Print: the code could not round-trip through a file and was inlined. | diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 0404245d32f..a4dc40465b5 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -1,6 +1,10 @@ +import { parse } from '@babel/parser' import type { Node, ObjectExpression, ObjectProperty } from '@babel/types' import { isRecordLike } from '@sim/utils/object' -import { findWorkflowReferenceTokens } from '@sim/utils/workflow-references' +import { + findWorkflowReferenceTokens, + isLikelyWorkflowReferenceSegment, +} from '@sim/utils/workflow-references' import { BLOCK_RETRY_MAX_TRIES, BLOCK_RETRY_MAX_WAIT_MS, @@ -10,6 +14,7 @@ import { type WorkflowBranchKind, } from '@sim/workflow-types/workflow' import { encodeAnchor } from '../anchors' +import { babelErrorShape } from '../babel' import { isBranchExtraField } from '../canonicalize/branches' import { DEFAULT_LOOP_ITERATIONS, @@ -38,7 +43,7 @@ import { codeFileLanguage, fromCodeFile, } from '../code-files' -import { isIdentifierName, parseStoredPath } from '../code-files/ref-path' +import { isIdentifierName, LOOP_PROPERTIES, parseStoredPath } from '../code-files/ref-path' import { branchesAtTopLevel, ELSE_KEY, isElseTrue } from '../forms/condition' import { compileResponseParam, usesResponseForm } from '../forms/response' import { type ConfigField, type ContainerForm, loopForm, parallelForm } from '../forms/subflow' @@ -1867,6 +1872,78 @@ function jsonField(value: Value | undefined): Json | undefined { return isJson(value) ? value : undefined } +/** The executor's reference candidate pattern (`createReferencePattern`); each is then vetted. */ +const CONDITION_REFERENCE = /<([^<>]+)>/g + +/** + * A while or do-while condition checked as the run evaluates it (`LoopOrchestrator` + * `evaluateWhileCondition`): each reference is replaced by its value and the text runs as + * `return Boolean()`, outside every block. + * - `W_LOOP_CONDITION_SYNTAX` when that is not valid JavaScript, which fails the run: references + * stand in as `0`, so only the text the author wrote around them is judged. + * - `W_REF_OUT_OF_SCOPE` for the loop's own iteration field read by its name (``): the + * condition is evaluated outside the loop's body, where a named loop outputs only its results, + * so the run fails; only the bare `` reads the iteration there. + */ +function checkLoopCondition( + ctx: CompileContext, + decl: BlockDecl, + text: string, + property: ObjectProperty +): void { + if (text.trim() === '') return + const at = rangeOf(ctx, property.value) + const selfReads = new Set() + const runnable = text.replace(CONDITION_REFERENCE, (match: string, inner: string) => { + if (!isLikelyWorkflowReferenceSegment(match)) return match + const segments = parseStoredPath(inner) + const [head, field] = segments ?? [] + if ( + head?.kind === 'name' && + head.name === decl.key && + field?.kind === 'name' && + LOOP_PROPERTIES.includes(field.name) + ) { + selfReads.add(field.name) + } + return '0' + }) + for (const field of selfReads) { + ctx.reporter.report( + 'W_REF_OUT_OF_SCOPE', + `${decl.name}'s condition reads its own ${field} by the loop's name. The run evaluates the condition outside the loop's body, where the loop outputs only results, so the run fails.`, + at, + { + hint: `Write : the bare loop prefix reads the iteration the condition is evaluated for.`, + blockKey: decl.key, + } + ) + } + let failure: unknown = null + try { + const file = parse(`return Boolean(${runnable})`, { + sourceType: 'script', + allowReturnOutsideFunction: true, + errorRecovery: true, + }) + failure = file.errors?.[0] ?? null + } catch (error) { + failure = error + } + if (failure === null) return + const { message: raw } = babelErrorShape(failure) + const message = typeof raw === 'string' ? raw : 'Invalid JavaScript' + ctx.reporter.report( + 'W_LOOP_CONDITION_SYNTAX', + `${decl.name}'s condition is not a JavaScript expression (${message.replace(/\s*\(\d+:\d+\)$/, '')}), so the run fails when it evaluates it.`, + at, + { + hint: "Write one JavaScript expression the loop repeats while it is true, e.g. condition: ' < 3'.", + blockKey: decl.key, + } + ) +} + /** * `loop.(name, config, body, meta?)` / `parallel[.](...)`. Config holds the fields * the type uses; apply keeps the other types' fields from the stored workflow. `meta.extra` holds @@ -1910,6 +1987,11 @@ function compileContainer(ctx: CompileContext, decl: BlockDecl): CompiledBlock | ...(doWhileCondition !== undefined && { doWhileCondition }), } reportUnreadConfig(ctx, decl, form, written, loop) + for (const field of ['whileCondition', 'doWhileCondition'] as const) { + const text = loop[field] + const property = written.get(field) + if (text !== undefined && property) checkLoopCondition(ctx, decl, text, property) + } subflow = loop } else { const { fields } = compileConfig(ctx, site, 'parallel', parallelForm(builder.method), config) diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index 4b25f1daa01..e9a47f46a00 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -858,3 +858,54 @@ describe('an options object passed to .to()', () => { ) }) }) + +describe('loop conditions', () => { + /** A while (or do-while) loop around one block, its condition written as `condition`. */ + function whileLoop(condition: string, method: 'while' | 'doWhile' = 'while') { + return run( + [ + START, + `const w = loop.${method}('W', { condition: ${JSON.stringify(condition)} }, (p) => {`, + " const a = api('A', { url: 'https://x' })", + ' p.to(a)', + '})', + 'start.to(w)', + ].join('\n') + ) + } + + it('warns on a condition the run cannot evaluate as JavaScript, at the condition', () => { + for (const method of ['while', 'doWhile'] as const) { + const result = whileLoop(' < (3', method) + const [syntax] = findings(result, 'W_LOOP_CONDITION_SYNTAX') + expect(syntax?.message).toMatch( + /^W's condition is not a JavaScript expression \(.+\), so the run fails/ + ) + expect(syntax?.span.line).toBe(6) + expect(syntax?.blockKey).toBe('w') + } + }) + + it('judges only the text around references, which stand in as values', () => { + for (const condition of [ + ' < 3', + ' < && !== "x"', + 'true', + '', + ]) { + expect(findings(whileLoop(condition), 'W_LOOP_CONDITION_SYNTAX')).toEqual([]) + } + }) + + it("warns on the loop's own iteration field read by its name, naming ", () => { + const result = whileLoop(' < 3') + expect(findings(result, 'W_REF_OUT_OF_SCOPE')).toEqual([ + expect.objectContaining({ + message: expect.stringContaining("W's condition reads its own index by the loop's name"), + hint: expect.stringContaining('Write '), + blockKey: 'w', + }), + ]) + expect(findings(whileLoop(' < 3'), 'W_REF_OUT_OF_SCOPE')).toEqual([]) + }) +}) diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index 4b2b6574609..c725df3b8f5 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -106,6 +106,13 @@ const COMPILE_SCOPE_CODES = [ * directory), so it has no inputs to map and no entry point to run from. */ 'W_CHILD_NO_START', + /** + * A reference to a child workflow call's `result.` whose child holds a Response block (an + * offline check of a workspace directory), where `` is not `data`, `status` or `headers`: + * the child's result is its Response output, so the path reads nothing. The value meant is + * almost always `result.data.`. + */ + 'W_CHILD_RESULT_PATH', /** `p.` not in the loop/parallel resolvers' `KNOWN_PROPERTIES`. */ 'E_UNKNOWN_SUBFLOW_PROPERTY', /** A ref to a block declared later; it resolves, but the order is unusual. */ @@ -269,6 +276,12 @@ const COMPILE_CATALOG_CODES = [ * (typed), so a string value would break the JSON (`json-fields.ts`). */ 'W_JSON_REF_UNTYPED', + /** + * A while or do-while condition that is not a JavaScript expression once its references stand + * in as values, which fails the run when it evaluates it. Refused as + * `E_APPLY_LOOP_CONDITION_SYNTAX` on a loop the edit added or changed. + */ + 'W_LOOP_CONDITION_SYNTAX', ] as const /** Function-code files. */ @@ -520,6 +533,8 @@ const APPLY_DIAGNOSTIC_CODES = [ 'E_APPLY_REF_OUT_OF_SCOPE', /** A `W_CODE_FILE_REF_SYNTAX` in a code file the edit changed, which breaks the code at run time. */ 'E_APPLY_CODE_FILE_REF_SYNTAX', + /** A `W_LOOP_CONDITION_SYNTAX` on a loop the edit added or changed, which fails at run time. */ + 'E_APPLY_LOOP_CONDITION_SYNTAX', /** A non-blocking workflow lint finding, mapped to a source line. */ 'W_APPLY_LINT', /** A table row write (insert, upsert, update) with a key that is not a column of its table. */ diff --git a/packages/workflow-code/src/diagnostics/refusals.ts b/packages/workflow-code/src/diagnostics/refusals.ts index 3fde13e735a..45b85d3f1cf 100644 --- a/packages/workflow-code/src/diagnostics/refusals.ts +++ b/packages/workflow-code/src/diagnostics/refusals.ts @@ -64,6 +64,7 @@ export const refusalClass = refusalClassifier() export type EditRefusalCode = | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' + | 'E_APPLY_LOOP_CONDITION_SYNTAX' | 'E_APPLY_CODE_FILE_REF_SYNTAX' | 'E_APPLY_INVALID_SUBBLOCK_FIELD' | 'E_APPLY_INVALID_BLOCK_TYPE' @@ -88,11 +89,13 @@ export interface EditedBlocks { } /** - * An iteration field read outside its container (`W_REF_OUT_OF_SCOPE`), refused in any file on a - * block the edit changed, or in a code file the edit changed. + * An iteration field read outside its container (`W_REF_OUT_OF_SCOPE`), or a loop condition that + * is not a JavaScript expression (`W_LOOP_CONDITION_SYNTAX`), refused in any file on a block the + * edit changed, or in a code file the edit changed. */ const CHANGED_BLOCK_REFUSALS: ReadonlyMap = new Map([ ['W_REF_OUT_OF_SCOPE', 'E_APPLY_REF_OUT_OF_SCOPE'], + ['W_LOOP_CONDITION_SYNTAX', 'E_APPLY_LOOP_CONDITION_SYNTAX'], ]) /** @@ -139,6 +142,7 @@ const CODE_FILE_REFUSALS: ReadonlyMap = new Map([ export const REFUSABLE_WARNING_CODES: ReadonlySet = new Set([ 'W_UNKNOWN_OPTION', 'W_REF_OUT_OF_SCOPE', + 'W_LOOP_CONDITION_SYNTAX', 'W_UNKNOWN_OUTPUT_PATH', 'W_UNRESOLVED_REF', 'W_CODE_FILE_REF_SYNTAX', From 3369122803931e7487e867a3cf21d1bcda0749a6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:05:21 -0800 Subject: [PATCH 20/37] fix(workflow-code): report one error for a new block of an unknown type The source apply reported a new block of an unregistered type three times: the compile's E_APPLY_INVALID_BLOCK_TYPE at its line, the placement gate's in other words, and the state check's E_APPLY_INVALID_STATE. A gate refusal the compile already made for the same block, and the state check's repeat of it, are dropped. --- .../source-pipeline/evaluate/finalize.ts | 89 ++++++++++++++----- 1 file changed, 66 insertions(+), 23 deletions(-) diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts index 9ac87868483..179f91d8d64 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts @@ -1,4 +1,5 @@ import type { + Diagnostic, LocatedDiagnostic, LockIdentity, WorkflowLockBlock, @@ -135,6 +136,60 @@ function withoutCompiledReferences( } } +/** + * Refusals the compile makes at the source line, with its own wording and hint, that a server gate + * makes again for the same block: a field value (`E_APPLY_INVALID_SUBBLOCK_FIELD`, per field), and + * a block type the workspace cannot place (per block). + */ +const COMPILED_REFUSAL_CODES: ReadonlySet = new Set([ + 'E_APPLY_INVALID_SUBBLOCK_FIELD', + 'E_APPLY_INVALID_BLOCK_TYPE', + 'E_APPLY_TYPE_NOT_ADDABLE', +]) + +function refusalKey(code: string, blockKey: string, param: string | undefined): string { + const field = code === 'E_APPLY_INVALID_SUBBLOCK_FIELD' ? (param ?? '') : '' + return `${code}\u0000${blockKey}\u0000${field}` +} + +/** + * `findings` without the refusals that repeat one already made, so one mistake is one error: a + * {@link COMPILED_REFUSAL_CODES} refusal the compile made for the same block (and field), and the + * state check's `E_APPLY_INVALID_STATE` on a block whose type is refused as unregistered, which + * says only that again. + */ +function withoutRepeatedRefusals( + findings: readonly Diagnostic[], + compiled: readonly LocatedDiagnostic[], + keyOf: (id: string) => string | undefined +): Diagnostic[] { + const blockKeyOf = (finding: Diagnostic) => + finding.blockKey ?? (finding.blockId === undefined ? undefined : keyOf(finding.blockId)) + const compiledRefusals = new Set( + compiled.flatMap((finding) => + COMPILED_REFUSAL_CODES.has(finding.code) && finding.blockKey !== undefined + ? [refusalKey(finding.code, finding.blockKey, finding.param)] + : [] + ) + ) + const unregistered = new Set( + [...compiled, ...findings].flatMap((finding) => + finding.code === 'E_APPLY_INVALID_BLOCK_TYPE' ? (blockKeyOf(finding) ?? []) : [] + ) + ) + return findings.filter((finding) => { + const blockKey = blockKeyOf(finding) + if (finding.code === 'E_APPLY_INVALID_STATE') { + return blockKey === undefined || !unregistered.has(blockKey) + } + return ( + !COMPILED_REFUSAL_CODES.has(finding.code) || + blockKey === undefined || + !compiledRefusals.has(refusalKey(finding.code, blockKey, finding.param)) + ) + }) +} + /** * The post-materialize lock `mergeSourceMetaFromLock` re-keys onto: every bound key with its id, * and the submitted lock's ident and order for a block the file does not state them for. @@ -211,31 +266,19 @@ export async function finalizePlan( pending, keyOf: keyOfId, }) - // A field the compile already refused (with its span and options) needs no second refusal from - // the value gate. - const refusedFields = new Set( - compileDiagnostics.flatMap((finding) => - finding.code === 'E_APPLY_INVALID_SUBBLOCK_FIELD' - ? [`${finding.blockKey}\u0000${finding.param}`] - : [] - ) - ) - const refusedAgain = (finding: { code: string; blockId?: string; param?: string }) => - finding.code === 'E_APPLY_INVALID_SUBBLOCK_FIELD' && - finding.blockId !== undefined && - refusedFields.has(`${keyOfId(finding.blockId)}\u0000${finding.param}`) + const serverFindings = [ + ...resolved.keptDiagnostics, + ...resolved.materializeDiagnostics, + ...refusals.sourceRefusals, + ...refusals.renameWarnings, + ...gated.gateFindings, + ...normalized.diagnostics, + ...foreignIds, + ...lintDiagnostics(compiledLint, changedIds, keyOfId), + ] const diagnostics = [ ...compileDiagnostics, - ...[ - ...resolved.keptDiagnostics, - ...resolved.materializeDiagnostics, - ...refusals.sourceRefusals, - ...refusals.renameWarnings, - ...gated.gateFindings, - ...normalized.diagnostics, - ...foreignIds, - ...lintDiagnostics(compiledLint, changedIds, keyOfId), - ].filter((finding) => !refusedAgain(finding)), + ...withoutRepeatedRefusals(serverFindings, compileDiagnostics, keyOfId), ].map(locate) if (hasErrors(diagnostics)) { return { From ab5b228854cb4c5baf4c9b1f7c6cc3937d8c4137 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:05:22 -0800 Subject: [PATCH 21/37] feat(workflow-editing): lint a child's result. that reads nothing and an undeployed child at deploy - A reference to a Workflow block's result. whose child holds an enabled Response block, where is not data, status or headers, is a child-result lint finding naming result.data.. The source apply reports it as a W_APPLY_LINT warning, never a refusal. - A deploy's lint reports a called child with no deployment, which a deployed run of the parent cannot call. --- apps/sim/lib/api/contracts/v2/workflows.ts | 12 +- .../apply-workflow-source.integration.ts | 111 ++++++++++ .../lib/workflows/application/deployments.ts | 3 +- .../editing/lint-report.integration.ts | 209 ++++++++++++++++++ apps/sim/lib/workflows/editing/lint-report.ts | 77 +++++++ apps/sim/lib/workflows/editing/lint.ts | 140 +++++++++++- 6 files changed, 548 insertions(+), 4 deletions(-) create mode 100644 apps/sim/lib/workflows/editing/lint-report.integration.ts diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index fcff30dd9d9..48bd67376b9 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -459,13 +459,21 @@ const v2WorkflowLintSchema = z .union([z.string(), z.array(z.string())]) .describe('The reference, or references, that did not resolve.'), kind: z - .enum(['credential', 'resource', 'custom-tool', 'mcp-tool', 'skill', 'block-output']) + .enum([ + 'credential', + 'resource', + 'custom-tool', + 'mcp-tool', + 'skill', + 'block-output', + 'child-result', + ]) .describe('What kind of entity the reference was expected to name.'), reason: z.string().describe('Why the reference does not resolve.'), }) ) .describe( - 'Credential, resource, tool, and skill references that do not resolve; `block-output` references that will not work as written: a block that does not exist, or an output field the block does not have (reason `unknown-field`); and text outputs written unquoted in a JSON field (reason `unquoted-json-string`), which leave the field invalid JSON at run time unless the text is itself JSON. These values are still persisted; they are reported, not dropped.' + 'Credential, resource, tool, and skill references that do not resolve; `block-output` references that will not work as written: a block that does not exist, or an output field the block does not have (reason `unknown-field`); and text outputs written unquoted in a JSON field (reason `unquoted-json-string`), which leave the field invalid JSON at run time unless the text is itself JSON; `child-result` references to the `result.` of a Workflow block whose child responds, so its result is the Response output (`{ data, status, headers }`) and the key reads nothing (the value meant is `result.data.`). A deploy also reports, as `resource`, a called child workflow that is not deployed, which a deployed run cannot call. These values are still persisted; they are reported, not dropped.' ), tableFieldIssues: z .array( diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts index 7be8a678a59..d7f26d2bae7 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -1020,6 +1020,117 @@ check('a dry run with a compile error answers with line-pinned diagnostics', asy expect(result.diff.noop).toBe(false) }) +check( + "a responding child's result. is a warning naming result.data., not a refusal", + async () => { + const childId = generateId() + const childStartId = generateId() + const replyId = generateId() + const now = new Date() + await db.insert(workflow).values({ + id: childId, + userId: ownerId, + workspaceId, + name: `Responder ${childId}`, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + const child = await saveWorkflowToNormalizedTables(childId, { + blocks: { + [childStartId]: { + id: childStartId, + type: 'start_trigger', + name: 'Start', + position: { x: 0, y: 0 }, + subBlocks: {}, + outputs: {}, + enabled: true, + }, + [replyId]: { + id: replyId, + type: 'response', + name: 'Reply', + position: { x: 400, y: 0 }, + subBlocks: {}, + outputs: {}, + enabled: true, + }, + }, + edges: [{ id: generateId(), source: childStartId, target: replyId }], + loops: {}, + parallels: {}, + }) + if (!child.success) throw new Error(`Seeding the child failed: ${child.error}`) + const seeded = await seedWorkflow() + const callId = generateId() + const stored = await loadWorkflowFromNormalizedTables(seeded.workflowId) + if (!stored) throw new Error('The seeded workflow did not load') + const saved = await saveWorkflowToNormalizedTables(seeded.workflowId, { + ...stored, + blocks: { + ...stored.blocks, + [callId]: { + id: callId, + type: 'workflow_input', + name: 'Call', + position: { x: 200, y: 40 }, + subBlocks: { + workflowId: { id: 'workflowId', type: 'workflow-selector', value: childId }, + }, + outputs: {}, + enabled: true, + }, + }, + edges: [ + { id: generateId(), source: seeded.startId, target: callId }, + { id: seeded.edgeId, source: callId, target: seeded.scoreId }, + ], + }) + if (!saved.success) throw new Error(`Adding the call failed: ${saved.error}`) + const source = await getSource(seeded.workflowId) + + const result = await apply( + source, + edit(source.files, SCORE_CODE, 'return $ref.call.result.mobile'), + { + dryRun: true, + } + ) + + expect(result.diagnostics.filter((d) => d.severity === 'error')).toEqual([]) + expect(result.diagnostics).toContainEqual( + expect.objectContaining({ + code: 'W_APPLY_LINT', + blockKey: 'score', + message: expect.stringContaining('Did you mean ?'), + }) + ) + } +) + +check('a new block of an unknown type is one error, at its source line', async () => { + const seeded = await seedWorkflow() + const source = await getSource(seeded.workflowId) + const added = edit( + source.files, + ' start.to(score)', + " const ghost = block('qa_nonexistent_type', 'Ghost', {})\n start.to(score)\n score.to(ghost)" + ) + const files = { + ...added, + 'workflow.ts': added['workflow.ts'].replace(/import \{ /, 'import { block, '), + } + + const result = await apply(source, files, { dryRun: true }) + + const errors = result.diagnostics.filter((d) => d.severity === 'error') + expect(errors.map((d) => d.code)).toEqual(['E_APPLY_INVALID_BLOCK_TYPE']) + expect(errors[0]).toMatchObject({ file: 'workflow.ts', blockKey: 'ghost' }) + expect(errors[0]?.message).toContain('qa_nonexistent_type') + expect(result.applied).toBe(false) +}) + /** The realtime server's subblock write: one block's `sub_blocks` under the held row lock. */ async function canvasSubBlockWrite(tx: DbOrTx, blockId: string, code: string) { const [row] = await tx diff --git a/apps/sim/lib/workflows/application/deployments.ts b/apps/sim/lib/workflows/application/deployments.ts index 95c58f03d80..330e1b924fe 100644 --- a/apps/sim/lib/workflows/application/deployments.ts +++ b/apps/sim/lib/workflows/application/deployments.ts @@ -139,7 +139,8 @@ async function lintDeployedVersion( deploymentVersionId, context.workspaceId ), - { workflowId: context.workflowId, workspaceId: context.workspaceId, subjectUserId } + { workflowId: context.workflowId, workspaceId: context.workspaceId, subjectUserId }, + { deployed: true } ) ), Date.now() + DEPLOYED_VERSION_LINT_BUDGET_MS diff --git a/apps/sim/lib/workflows/editing/lint-report.integration.ts b/apps/sim/lib/workflows/editing/lint-report.integration.ts new file mode 100644 index 00000000000..18e82d965ce --- /dev/null +++ b/apps/sim/lib/workflows/editing/lint-report.integration.ts @@ -0,0 +1,209 @@ +/** + * Real PostgreSQL coverage for the lint's child workflow checks: the children a Workflow block + * calls are read from the workflow and block tables, and a graph is linted against them. A + * responding child's `result.` reads nothing unless `` is a Response output, and a + * deploy reports a called child with no deployment, which a deployed run cannot call. + */ +import { mkdir, writeFile } from 'node:fs/promises' +import { dirname, resolve } from 'node:path' +import { db } from '@sim/db' +import { user, workflow, workspace } from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { getErrorMessage } from '@sim/utils/errors' +import { generateId } from '@sim/utils/id' +import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' +import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, expect, it } from 'vitest' +import { buildWorkflowLintReport } from '@/lib/workflows/editing/lint-report' + +const ownerId = generateId() +const workspaceId = generateId() +const otherWorkspaceId = generateId() + +const checks: { name: string; status: string; durationMs: number; error?: string }[] = [] + +function check(name: string, run: () => Promise) { + it(name, async () => { + const started = performance.now() + try { + await run() + checks.push({ name, status: 'passed', durationMs: performance.now() - started }) + } catch (error) { + checks.push({ + name, + status: 'failed', + durationMs: performance.now() - started, + error: getErrorMessage(error), + }) + throw error + } + }) +} + +function block( + id: string, + type: string, + name: string, + subBlocks: Record = {}, + enabled = true +): BlockState { + return { + id, + type, + name, + position: { x: 0, y: 0 }, + subBlocks: Object.fromEntries( + Object.entries(subBlocks).map(([field, value]) => [ + field, + { id: field, type: 'short-input', value }, + ]) + ), + outputs: {}, + enabled, + } as BlockState +} + +/** Stores a child workflow whose only blocks are a Start and, when given, a Response block. */ +async function seedChild( + name: string, + options: { response?: 'enabled' | 'disabled'; deployed?: boolean; workspace?: string } = {} +): Promise { + const id = generateId() + const now = new Date() + await db.insert(workflow).values({ + id, + userId: ownerId, + workspaceId: options.workspace ?? workspaceId, + name, + isDeployed: options.deployed ?? false, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + const startId = generateId() + const blocks: Record = { [startId]: block(startId, 'start_trigger', 'Start') } + if (options.response) { + const replyId = generateId() + blocks[replyId] = block( + replyId, + 'response', + 'Reply', + { dataMode: 'json', data: '{"mobile": "1"}' }, + options.response === 'enabled' + ) + } + const state: WorkflowState = { blocks, edges: [], loops: {}, parallels: {} } + const saved = await saveWorkflowToNormalizedTables(id, state) + if (!saved.success) throw new Error(`Seeding the child failed: ${saved.error}`) + return id +} + +/** A parent graph whose Workflow block "Call" runs `childId` and whose function reads `code`. */ +function parent(childId: string, code: string) { + return { + blocks: { + start: block('start', 'start_trigger', 'Start'), + call: block('call', 'workflow_input', 'Call', { workflowId: childId }), + use: block('use', 'function', 'Use', { code }), + }, + edges: [ + { id: 'e1', source: 'start', target: 'call' }, + { id: 'e2', source: 'call', target: 'use' }, + ], + } +} + +function lint(graph: ReturnType, deployed = false) { + return buildWorkflowLintReport( + graph, + { workflowId: generateId(), workspaceId, subjectUserId: null }, + { deployed } + ) +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: ownerId, + name: 'Lint child fixture', + email: `${ownerId}@lint-child.invalid`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + for (const id of [workspaceId, otherWorkspaceId]) { + await insertWorkspaceFixture(db, { + id, + name: 'Lint child', + ownerId, + billedAccountUserId: ownerId, + }) + } +}) + +afterAll(async () => { + const reportPath = + process.env.WORKFLOW_LINT_CHILD_REPORT_PATH ?? resolve('test-results/workflow-lint-child.json') + await mkdir(dirname(reportPath), { recursive: true }) + await writeFile(reportPath, JSON.stringify({ checks }, null, 2)) + await deleteWorkspaceFixture(db, inArray(workspace.id, [workspaceId, otherWorkspaceId])) + await db.delete(user).where(eq(user.id, ownerId)) +}) + +check( + "a responding child's result. is reported with result.data. as the fix", + async () => { + const childId = await seedChild('Responder', { response: 'enabled', deployed: true }) + + const report = await lint( + parent( + childId, + 'return [, , ]' + ) + ) + + const found = report.unresolvedReferences.filter((ref) => ref.kind === 'child-result') + expect(found).toEqual([ + expect.objectContaining({ + blockId: 'use', + field: 'code', + value: [''], + reason: expect.stringContaining('Did you mean ?'), + }), + ]) + expect(found[0]?.reason).toContain('Workflow "Responder" responds') + } +) + +check( + 'a child with no enabled Response block, or in another workspace, is not judged', + async () => { + const silent = await seedChild('Silent') + const disabled = await seedChild('Disabled reply', { response: 'disabled' }) + const foreign = await seedChild('Foreign', { response: 'enabled', workspace: otherWorkspaceId }) + + for (const childId of [silent, disabled, foreign]) { + const report = await lint(parent(childId, 'return ')) + expect(report.unresolvedReferences.filter((ref) => ref.kind === 'child-result')).toEqual([]) + } + } +) + +check('a deploy reports a called child that is not deployed; a draft write does not', async () => { + const undeployed = await seedChild('Undeployed child') + const deployed = await seedChild('Deployed child', { deployed: true }) + const childFindings = (report: Awaited>) => + report.unresolvedReferences.filter((ref) => ref.field === 'workflowId') + + expect(childFindings(await lint(parent(undeployed, 'return 1'), true))).toEqual([ + expect.objectContaining({ + blockId: 'call', + kind: 'resource', + value: undeployed, + reason: expect.stringContaining('Workflow "Undeployed child" is not deployed.'), + }), + ]) + expect(childFindings(await lint(parent(undeployed, 'return 1')))).toEqual([]) + expect(childFindings(await lint(parent(deployed, 'return 1'), true))).toEqual([]) +}) diff --git a/apps/sim/lib/workflows/editing/lint-report.ts b/apps/sim/lib/workflows/editing/lint-report.ts index a0fa196628d..4c805e39683 100644 --- a/apps/sim/lib/workflows/editing/lint-report.ts +++ b/apps/sim/lib/workflows/editing/lint-report.ts @@ -1,8 +1,13 @@ +import { db } from '@sim/db' +import { workflow, workflowBlocks } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import type { WorkflowState } from '@sim/workflow-types/workflow' +import { and, eq, inArray, isNull } from 'drizzle-orm' import { getTableById } from '@/lib/table/service' import { + collectCalledWorkflowIds, + collectChildWorkflowFindings, collectDanglingBlockOutputReferences, collectTableBlockFieldIssues, collectUnquotedJsonStringReferences, @@ -10,6 +15,7 @@ import { collectWorkflowTableIds, hasWorkflowEntryBlock, lintEditedWorkflowState, + type WorkflowLintChildWorkflow, type WorkflowLintReport, type WorkflowLintTableFieldIssue, type WorkflowLintTableSchema, @@ -106,6 +112,57 @@ interface WorkflowLintReportOptions extends AgentToolReferenceValidationOptions * source line (a source apply). */ iterationScope?: boolean + /** + * The graph is a version a deploy admitted: each child workflow it calls must be deployed too, + * since a deployed run calls the child's deployed version. + */ + deployed?: boolean +} + +/** + * What the lint checks a call against for each workflow the graph's Workflow blocks call in this + * workspace, keyed by id: its name, whether it is deployed, and whether its draft holds an enabled + * Response block. A child in another workspace, or archived, is left out: the block's own + * reference check reports it. + */ +async function loadChildWorkflowsForLint( + blocks: Pick['blocks'], + workspaceId: string +): Promise> { + const ids = collectCalledWorkflowIds(blocks) + const children = new Map() + if (ids.length === 0) return children + const [rows, responders] = await Promise.all([ + db + .select({ id: workflow.id, name: workflow.name, isDeployed: workflow.isDeployed }) + .from(workflow) + .where( + and( + inArray(workflow.id, ids), + eq(workflow.workspaceId, workspaceId), + isNull(workflow.archivedAt) + ) + ), + db + .selectDistinct({ workflowId: workflowBlocks.workflowId }) + .from(workflowBlocks) + .where( + and( + inArray(workflowBlocks.workflowId, ids), + eq(workflowBlocks.type, 'response'), + eq(workflowBlocks.enabled, true) + ) + ), + ]) + const responding = new Set(responders.map((row) => row.workflowId)) + for (const row of rows) { + children.set(row.id, { + name: row.name, + deployed: row.isDeployed, + responds: responding.has(row.id), + }) + } + return children } /** @@ -205,6 +262,26 @@ export async function buildWorkflowLintReport( } } + try { + unresolvedReferences.push( + ...collectChildWorkflowFindings( + graph, + await loadChildWorkflowsForLint(graph.blocks, scope.workspaceId), + { deployed: options.deployed } + ) + ) + } catch (error) { + logger.warn('Child workflow lint failed', { + workflowId: scope.workflowId, + error: getErrorMessage(error), + }) + if (options.requireComplete) { + throw new Error( + 'Workflow child workflow checks could not complete; retry when lookup is available' + ) + } + } + /** Standalone diagnostics have already read tables under application authorization. */ let tableFieldIssues: WorkflowLintTableFieldIssue[] = options.tables?.tableFieldIssues ?? [] if (!options.tables) { diff --git a/apps/sim/lib/workflows/editing/lint.ts b/apps/sim/lib/workflows/editing/lint.ts index d5b54b4de15..512cb4b1fbf 100644 --- a/apps/sim/lib/workflows/editing/lint.ts +++ b/apps/sim/lib/workflows/editing/lint.ts @@ -18,6 +18,7 @@ import type { ManualRunEntryIssue } from '@/lib/workflows/triggers/manual-run' import { getBlock } from '@/blocks' import { isTriggerBlockType, + isWorkflowBlockType, normalizeName, REFERENCE, SPECIAL_REFERENCE_PREFIXES, @@ -95,7 +96,14 @@ export interface WorkflowLintFieldIssue extends WorkflowLintBlockRef { export interface WorkflowLintUnresolvedReference extends WorkflowLintBlockRef { field: string value: string | string[] - kind: 'credential' | 'resource' | 'custom-tool' | 'mcp-tool' | 'skill' | 'block-output' + kind: + | 'credential' + | 'resource' + | 'custom-tool' + | 'mcp-tool' + | 'skill' + | 'block-output' + | 'child-result' reason: string } @@ -590,6 +598,18 @@ function collectBlockingSections(lint: WorkflowLintIssueView): WorkflowLintSecti ), '; ' ), + lintSection( + 'Child workflow result paths that read nothing (a child that responds returns its Response output, { data, status, headers })', + unresolved + .filter((ref) => ref.kind === 'child-result') + .map( + (ref) => + `${blockLabel(ref)}.${ref.field} ${ + Array.isArray(ref.value) ? ref.value.join(', ') : ref.value + } (${ref.reason})` + ), + '; ' + ), lintSection( "Table filter/sort fields that are not columns of the referenced table (the run will fail in the block's error edge)", (lint.tableFieldIssues ?? []) @@ -1101,3 +1121,121 @@ export function collectUnquotedJsonStringReferences( } return findings } + +/** What the lint knows of a workflow a Workflow block calls. */ +export interface WorkflowLintChildWorkflow { + name: string + /** Whether the child has an active deployment, which a deployed run of the caller calls. */ + deployed: boolean + /** + * Whether the child holds an enabled Response block: its run then returns that block's output, + * `{ data, status, headers }`, as the caller's `result`. + */ + responds: boolean +} + +/** The workflow a Workflow block statically calls, or `undefined` for a reference or none. */ +function calledWorkflowId(block: BlockState): string | undefined { + if (!isWorkflowBlockType(block.type)) return undefined + let params: Record + try { + params = extractBlockParams(block as Parameters[0]) + } catch { + return undefined + } + const id = params.workflowId + return typeof id === 'string' && id.trim() !== '' && !id.includes('<') ? id.trim() : undefined +} + +/** Every workflow the graph's Workflow blocks statically call. */ +export function collectCalledWorkflowIds( + blocks: WorkflowState['blocks'] | Record | undefined +): string[] { + const ids = new Set() + for (const block of Object.values(blocks || {})) { + const id = calledWorkflowId(block as BlockState) + if (id) ids.add(id) + } + return [...ids] +} + +/** The output of a child's Response block, which a responding child's run returns. */ +const RESPONSE_OUTPUT_KEYS = ['data', 'status', 'headers'] as const + +/** The Workflow block output holding the child's run result. */ +const CHILD_RESULT_OUTPUT = 'result' + +/** + * Findings about the workflows the graph's Workflow blocks call, judged against what `children` + * (by workflow id) knows of each: + * - a reference to `>` whose key is not `data`, `status` or `headers` while the + * child responds (`child-result`): its result is the Response output, so the key reads nothing, + * and the value meant is almost always `>`; + * - with `deployed`, a child with no active deployment (`resource`): a deployed run of this + * workflow calls each child's deployed version, so it fails at the block. + */ +export function collectChildWorkflowFindings( + workflowState: Pick, + children: ReadonlyMap, + { deployed = false }: { deployed?: boolean } = {} +): WorkflowLintUnresolvedReference[] { + const blocks = (workflowState.blocks || {}) as Record + const childOf = new Map() + const findings: WorkflowLintUnresolvedReference[] = [] + for (const [blockId, block] of Object.entries(blocks)) { + const id = calledWorkflowId(block) + const child = id ? children.get(id) : undefined + if (!id || !child) continue + childOf.set(blockId, { ...child, id }) + if (deployed && !child.deployed) { + findings.push({ + ...blockRef(blockId, block), + field: 'workflowId', + value: id, + kind: 'resource', + reason: `Workflow "${child.name}" is not deployed. A deployed run calls the deployed version of each child workflow, so it fails at this block until "${child.name}" is deployed.`, + }) + } + } + if (childOf.size === 0) return findings + + const targetByKey = referenceTargetIndex(blocks) + for (const [blockId, block] of Object.entries(blocks)) { + for (const [subBlockId, subBlock] of Object.entries(block.subBlocks ?? {})) { + const leaves: string[] = [] + collectStringLeaves((subBlock as { value?: unknown })?.value, leaves) + const byTarget = new Map< + string, + { tokens: Set; keys: Set; meant: string[] } + >() + for (const leaf of leaves) { + for (const token of referenceCandidates(leaf, subBlockId === 'code')) { + if (!token || !REF_TOKEN_SHAPE.test(token)) continue + const targetId = referenceTarget(token, targetByKey) + if (!targetId || !childOf.get(targetId)?.responds) continue + const [head, output = '', next, ...rest] = token.split('.') + if (output !== CHILD_RESULT_OUTPUT || !next) continue + const key = splitLeadingBracketPath(next).property + if (!key || (RESPONSE_OUTPUT_KEYS as readonly string[]).includes(key)) continue + const group = byTarget.get(targetId) ?? { tokens: new Set(), keys: new Set(), meant: [] } + group.tokens.add(`<${token}>`) + group.keys.add(key) + group.meant.push(`<${[head, output, 'data', next, ...rest].join('.')}>`) + byTarget.set(targetId, group) + } + } + for (const [targetId, group] of byTarget) { + const target = blocks[targetId] + const child = childOf.get(targetId) + findings.push({ + ...blockRef(blockId, block), + field: subBlockId, + value: [...group.tokens], + kind: 'child-result', + reason: `Workflow "${child?.name}" responds, so "${target?.name || targetId}".result is its Response output ({ data, status, headers }) and ${quoteList(group.keys)} under result reads nothing. Did you mean ${[...new Set(group.meant)].join(', ')}?`, + }) + } + } + } + return findings +} From ab4e48204becff27a2e4d75bb3b33b51e0a2e19c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:05:22 -0800 Subject: [PATCH 22/37] chore(workflow-code): regenerate the OpenAPI document, CLI API types and CLI docs --- apps/docs/content/docs/cli/reference.mdx | 4 +- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- apps/docs/openapi-v2-workflows.json | 32 +++++++++++++- packages/sim-cli/src/generated/v2-api.ts | 54 +++++++++++++++++++++-- 5 files changed, 85 insertions(+), 9 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index ee1ac1c81a7..cfad9885a3e 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8698,7 +8698,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### sim workflows source status @@ -10077,7 +10077,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 2bbacfbeeb8..8aecb8b7313 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1492,7 +1492,7 @@ Compiles workflow.ts (and the function files it names) with the compiler the ser Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. ### Show the content of the changes in a workflow source directory diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 496f1d18b53..3f9f86374d0 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -789,7 +789,7 @@ Compiles every workflows/<key>/workflow.ts (and the function files each na Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 21388e46934..894c5b2c930 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -11309,7 +11309,8 @@ "custom-tool", "mcp-tool", "skill", - "block-output" + "block-output", + "child-result" ], "description": "What kind of entity the reference was expected to name." }, @@ -11321,7 +11322,7 @@ "required": ["blockId", "blockName", "blockType", "field", "value", "kind", "reason"], "additionalProperties": false }, - "description": "Credential, resource, tool, and skill references that do not resolve; `block-output` references that will not work as written: a block that does not exist, or an output field the block does not have (reason `unknown-field`); and text outputs written unquoted in a JSON field (reason `unquoted-json-string`), which leave the field invalid JSON at run time unless the text is itself JSON. These values are still persisted; they are reported, not dropped." + "description": "Credential, resource, tool, and skill references that do not resolve; `block-output` references that will not work as written: a block that does not exist, or an output field the block does not have (reason `unknown-field`); and text outputs written unquoted in a JSON field (reason `unquoted-json-string`), which leave the field invalid JSON at run time unless the text is itself JSON; `child-result` references to the `result.` of a Workflow block whose child responds, so its result is the Response output (`{ data, status, headers }`) and the key reads nothing (the value meant is `result.data.`). A deploy also reports, as `resource`, a called child workflow that is not deployed, which a deployed run cannot call. These values are still persisted; they are reported, not dropped." }, "tableFieldIssues": { "type": "array", @@ -19174,6 +19175,7 @@ "W_ENV_UNKNOWN", "W_CHILD_INPUT_UNKNOWN", "W_CHILD_NO_START", + "W_CHILD_RESULT_PATH", "E_UNKNOWN_SUBFLOW_PROPERTY", "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", @@ -19216,6 +19218,7 @@ "W_UNKNOWN_OUTPUT_PATH", "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", + "W_LOOP_CONDITION_SYNTAX", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", @@ -19295,6 +19298,7 @@ "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", "E_APPLY_CODE_FILE_REF_SYNTAX", + "E_APPLY_LOOP_CONDITION_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -19647,6 +19651,7 @@ "W_ENV_UNKNOWN", "W_CHILD_INPUT_UNKNOWN", "W_CHILD_NO_START", + "W_CHILD_RESULT_PATH", "E_UNKNOWN_SUBFLOW_PROPERTY", "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", @@ -19689,6 +19694,7 @@ "W_UNKNOWN_OUTPUT_PATH", "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", + "W_LOOP_CONDITION_SYNTAX", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", @@ -19768,6 +19774,7 @@ "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", "E_APPLY_CODE_FILE_REF_SYNTAX", + "E_APPLY_LOOP_CONDITION_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -20612,6 +20619,7 @@ "W_ENV_UNKNOWN", "W_CHILD_INPUT_UNKNOWN", "W_CHILD_NO_START", + "W_CHILD_RESULT_PATH", "E_UNKNOWN_SUBFLOW_PROPERTY", "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", @@ -20654,6 +20662,7 @@ "W_UNKNOWN_OUTPUT_PATH", "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", + "W_LOOP_CONDITION_SYNTAX", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", @@ -20733,6 +20742,7 @@ "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", "E_APPLY_CODE_FILE_REF_SYNTAX", + "E_APPLY_LOOP_CONDITION_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -21553,6 +21563,7 @@ "W_ENV_UNKNOWN", "W_CHILD_INPUT_UNKNOWN", "W_CHILD_NO_START", + "W_CHILD_RESULT_PATH", "E_UNKNOWN_SUBFLOW_PROPERTY", "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", @@ -21595,6 +21606,7 @@ "W_UNKNOWN_OUTPUT_PATH", "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", + "W_LOOP_CONDITION_SYNTAX", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", @@ -21674,6 +21686,7 @@ "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", "E_APPLY_CODE_FILE_REF_SYNTAX", + "E_APPLY_LOOP_CONDITION_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -26609,6 +26622,7 @@ "W_ENV_UNKNOWN", "W_CHILD_INPUT_UNKNOWN", "W_CHILD_NO_START", + "W_CHILD_RESULT_PATH", "E_UNKNOWN_SUBFLOW_PROPERTY", "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", @@ -26651,6 +26665,7 @@ "W_UNKNOWN_OUTPUT_PATH", "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", + "W_LOOP_CONDITION_SYNTAX", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", @@ -26729,6 +26744,7 @@ "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", "E_APPLY_CODE_FILE_REF_SYNTAX", + "E_APPLY_LOOP_CONDITION_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -27187,6 +27203,7 @@ "W_ENV_UNKNOWN", "W_CHILD_INPUT_UNKNOWN", "W_CHILD_NO_START", + "W_CHILD_RESULT_PATH", "E_UNKNOWN_SUBFLOW_PROPERTY", "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", @@ -27229,6 +27246,7 @@ "W_UNKNOWN_OUTPUT_PATH", "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", + "W_LOOP_CONDITION_SYNTAX", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", @@ -27307,6 +27325,7 @@ "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", "E_APPLY_CODE_FILE_REF_SYNTAX", + "E_APPLY_LOOP_CONDITION_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -27608,6 +27627,7 @@ "W_ENV_UNKNOWN", "W_CHILD_INPUT_UNKNOWN", "W_CHILD_NO_START", + "W_CHILD_RESULT_PATH", "E_UNKNOWN_SUBFLOW_PROPERTY", "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", @@ -27650,6 +27670,7 @@ "W_UNKNOWN_OUTPUT_PATH", "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", + "W_LOOP_CONDITION_SYNTAX", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", @@ -27728,6 +27749,7 @@ "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", "E_APPLY_CODE_FILE_REF_SYNTAX", + "E_APPLY_LOOP_CONDITION_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -28475,6 +28497,7 @@ "W_ENV_UNKNOWN", "W_CHILD_INPUT_UNKNOWN", "W_CHILD_NO_START", + "W_CHILD_RESULT_PATH", "E_UNKNOWN_SUBFLOW_PROPERTY", "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", @@ -28517,6 +28540,7 @@ "W_UNKNOWN_OUTPUT_PATH", "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", + "W_LOOP_CONDITION_SYNTAX", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", @@ -28595,6 +28619,7 @@ "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", "E_APPLY_CODE_FILE_REF_SYNTAX", + "E_APPLY_LOOP_CONDITION_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", @@ -28896,6 +28921,7 @@ "W_ENV_UNKNOWN", "W_CHILD_INPUT_UNKNOWN", "W_CHILD_NO_START", + "W_CHILD_RESULT_PATH", "E_UNKNOWN_SUBFLOW_PROPERTY", "W_FORWARD_REF", "W_REF_NOT_NORMALIZED", @@ -28938,6 +28964,7 @@ "W_UNKNOWN_OUTPUT_PATH", "W_OUTPUT_PATH_UNDECLARED", "W_JSON_REF_UNTYPED", + "W_LOOP_CONDITION_SYNTAX", "E_CODE_FILE_MISSING", "E_CODE_FILE_PATH", "W_CODE_FILE_INLINED", @@ -29016,6 +29043,7 @@ "E_APPLY_UNRESOLVED_REF", "E_APPLY_REF_OUT_OF_SCOPE", "E_APPLY_CODE_FILE_REF_SYNTAX", + "E_APPLY_LOOP_CONDITION_SYNTAX", "W_APPLY_LINT", "W_TABLE_UNKNOWN_COLUMN", "E_APPLY_INVALID_SCHEDULE", diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index bfe963dcebb..dda2ca15d4f 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -669,7 +669,14 @@ type ApplyWorkflowOperationsResponseRef2 = { blockType: string | null field: string value: string | Array - kind: 'credential' | 'resource' | 'custom-tool' | 'mcp-tool' | 'skill' | 'block-output' + kind: + | 'credential' + | 'resource' + | 'custom-tool' + | 'mcp-tool' + | 'skill' + | 'block-output' + | 'child-result' reason: string }> tableFieldIssues: Array<{ @@ -844,6 +851,7 @@ export type ApplyWorkflowSourceResponse = { | 'W_ENV_UNKNOWN' | 'W_CHILD_INPUT_UNKNOWN' | 'W_CHILD_NO_START' + | 'W_CHILD_RESULT_PATH' | 'E_UNKNOWN_SUBFLOW_PROPERTY' | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' @@ -886,6 +894,7 @@ export type ApplyWorkflowSourceResponse = { | 'W_UNKNOWN_OUTPUT_PATH' | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' + | 'W_LOOP_CONDITION_SYNTAX' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' @@ -965,6 +974,7 @@ export type ApplyWorkflowSourceResponse = { | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'E_APPLY_LOOP_CONDITION_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -1344,6 +1354,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_ENV_UNKNOWN' | 'W_CHILD_INPUT_UNKNOWN' | 'W_CHILD_NO_START' + | 'W_CHILD_RESULT_PATH' | 'E_UNKNOWN_SUBFLOW_PROPERTY' | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' @@ -1386,6 +1397,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_UNKNOWN_OUTPUT_PATH' | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' + | 'W_LOOP_CONDITION_SYNTAX' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' @@ -1464,6 +1476,7 @@ export type ApplyWorkspaceSourceResponse = { | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'E_APPLY_LOOP_CONDITION_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -1637,6 +1650,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_ENV_UNKNOWN' | 'W_CHILD_INPUT_UNKNOWN' | 'W_CHILD_NO_START' + | 'W_CHILD_RESULT_PATH' | 'E_UNKNOWN_SUBFLOW_PROPERTY' | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' @@ -1679,6 +1693,7 @@ export type ApplyWorkspaceSourceResponse = { | 'W_UNKNOWN_OUTPUT_PATH' | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' + | 'W_LOOP_CONDITION_SYNTAX' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' @@ -1757,6 +1772,7 @@ export type ApplyWorkspaceSourceResponse = { | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'E_APPLY_LOOP_CONDITION_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -5310,6 +5326,7 @@ export type CreateWorkflowFromSourceResponse = { | 'W_ENV_UNKNOWN' | 'W_CHILD_INPUT_UNKNOWN' | 'W_CHILD_NO_START' + | 'W_CHILD_RESULT_PATH' | 'E_UNKNOWN_SUBFLOW_PROPERTY' | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' @@ -5352,6 +5369,7 @@ export type CreateWorkflowFromSourceResponse = { | 'W_UNKNOWN_OUTPUT_PATH' | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' + | 'W_LOOP_CONDITION_SYNTAX' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' @@ -5431,6 +5449,7 @@ export type CreateWorkflowFromSourceResponse = { | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'E_APPLY_LOOP_CONDITION_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -6591,7 +6610,14 @@ type DeployWorkflowResponseRef4 = { blockType: string | null field: string value: string | Array - kind: 'credential' | 'resource' | 'custom-tool' | 'mcp-tool' | 'skill' | 'block-output' + kind: + | 'credential' + | 'resource' + | 'custom-tool' + | 'mcp-tool' + | 'skill' + | 'block-output' + | 'child-result' reason: string }> tableFieldIssues: Array<{ @@ -10418,6 +10444,7 @@ export type GetWorkflowSourceResponse = { | 'W_ENV_UNKNOWN' | 'W_CHILD_INPUT_UNKNOWN' | 'W_CHILD_NO_START' + | 'W_CHILD_RESULT_PATH' | 'E_UNKNOWN_SUBFLOW_PROPERTY' | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' @@ -10460,6 +10487,7 @@ export type GetWorkflowSourceResponse = { | 'W_UNKNOWN_OUTPUT_PATH' | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' + | 'W_LOOP_CONDITION_SYNTAX' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' @@ -10539,6 +10567,7 @@ export type GetWorkflowSourceResponse = { | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'E_APPLY_LOOP_CONDITION_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -11112,6 +11141,7 @@ export type GetWorkspaceSourceResponse = { | 'W_ENV_UNKNOWN' | 'W_CHILD_INPUT_UNKNOWN' | 'W_CHILD_NO_START' + | 'W_CHILD_RESULT_PATH' | 'E_UNKNOWN_SUBFLOW_PROPERTY' | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' @@ -11154,6 +11184,7 @@ export type GetWorkspaceSourceResponse = { | 'W_UNKNOWN_OUTPUT_PATH' | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' + | 'W_LOOP_CONDITION_SYNTAX' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' @@ -11232,6 +11263,7 @@ export type GetWorkspaceSourceResponse = { | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'E_APPLY_LOOP_CONDITION_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -14441,6 +14473,7 @@ export type PlanWorkflowSourceResponse = { | 'W_ENV_UNKNOWN' | 'W_CHILD_INPUT_UNKNOWN' | 'W_CHILD_NO_START' + | 'W_CHILD_RESULT_PATH' | 'E_UNKNOWN_SUBFLOW_PROPERTY' | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' @@ -14483,6 +14516,7 @@ export type PlanWorkflowSourceResponse = { | 'W_UNKNOWN_OUTPUT_PATH' | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' + | 'W_LOOP_CONDITION_SYNTAX' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' @@ -14562,6 +14596,7 @@ export type PlanWorkflowSourceResponse = { | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'E_APPLY_LOOP_CONDITION_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -14896,6 +14931,7 @@ export type PlanWorkspaceSourceResponse = { | 'W_ENV_UNKNOWN' | 'W_CHILD_INPUT_UNKNOWN' | 'W_CHILD_NO_START' + | 'W_CHILD_RESULT_PATH' | 'E_UNKNOWN_SUBFLOW_PROPERTY' | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' @@ -14938,6 +14974,7 @@ export type PlanWorkspaceSourceResponse = { | 'W_UNKNOWN_OUTPUT_PATH' | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' + | 'W_LOOP_CONDITION_SYNTAX' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' @@ -15016,6 +15053,7 @@ export type PlanWorkspaceSourceResponse = { | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'E_APPLY_LOOP_CONDITION_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -15189,6 +15227,7 @@ export type PlanWorkspaceSourceResponse = { | 'W_ENV_UNKNOWN' | 'W_CHILD_INPUT_UNKNOWN' | 'W_CHILD_NO_START' + | 'W_CHILD_RESULT_PATH' | 'E_UNKNOWN_SUBFLOW_PROPERTY' | 'W_FORWARD_REF' | 'W_REF_NOT_NORMALIZED' @@ -15231,6 +15270,7 @@ export type PlanWorkspaceSourceResponse = { | 'W_UNKNOWN_OUTPUT_PATH' | 'W_OUTPUT_PATH_UNDECLARED' | 'W_JSON_REF_UNTYPED' + | 'W_LOOP_CONDITION_SYNTAX' | 'E_CODE_FILE_MISSING' | 'E_CODE_FILE_PATH' | 'W_CODE_FILE_INLINED' @@ -15309,6 +15349,7 @@ export type PlanWorkspaceSourceResponse = { | 'E_APPLY_UNRESOLVED_REF' | 'E_APPLY_REF_OUT_OF_SCOPE' | 'E_APPLY_CODE_FILE_REF_SYNTAX' + | 'E_APPLY_LOOP_CONDITION_SYNTAX' | 'W_APPLY_LINT' | 'W_TABLE_UNKNOWN_COLUMN' | 'E_APPLY_INVALID_SCHEDULE' @@ -17243,7 +17284,14 @@ type ReplaceWorkflowStateResponseRef0 = { blockType: string | null field: string value: string | Array - kind: 'credential' | 'resource' | 'custom-tool' | 'mcp-tool' | 'skill' | 'block-output' + kind: + | 'credential' + | 'resource' + | 'custom-tool' + | 'mcp-tool' + | 'skill' + | 'block-output' + | 'child-result' reason: string }> tableFieldIssues: Array<{ From 90d341926949cd656db5e7857d6d7b9c15845b39 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:10:58 -0800 Subject: [PATCH 23/37] refactor(workflow-code): share the reference and response helpers the new checks use - The offline child-result check finds references with the shared tokenizer and splits paths with parseStoredPath, reads the response block type and outputs from @sim/workflow-code, and shares calledWorkflowKey with the child input check. - The loop condition check reuses the canonicalizer's reference pattern. - The lint reads a response block's outputs from the registry, looks children up alongside the reference collectors, and renders value findings with one helper. - check reads the workspace declarations and compiles its workflows at once. --- .../sim/executor/handlers/workflow/handler.ts | 2 +- apps/sim/lib/workflows/editing/lint-report.ts | 37 +++--- apps/sim/lib/workflows/editing/lint.ts | 61 ++++----- .../src/commands/protocol/source-check.ts | 121 ++++++++---------- .../protocol/workflow-source-check.ts | 16 +-- .../protocol/workspace-source-check.ts | 13 +- .../workflow-code/src/canonicalize/values.ts | 2 +- .../workflow-code/src/code-files/index.ts | 8 +- packages/workflow-code/src/compile/blocks.ts | 6 +- packages/workflow-code/src/index.ts | 4 +- packages/workflow-code/src/sdk.ts | 6 + 11 files changed, 131 insertions(+), 145 deletions(-) diff --git a/apps/sim/executor/handlers/workflow/handler.ts b/apps/sim/executor/handlers/workflow/handler.ts index 2236947cde1..33a69823f10 100644 --- a/apps/sim/executor/handlers/workflow/handler.ts +++ b/apps/sim/executor/handlers/workflow/handler.ts @@ -400,8 +400,8 @@ export class WorkflowBlockHandler implements BlockHandler { if (useDeployed && !isCustomBlock) { const deployment = await this.readChildDeployment(workflowId, workflowReadDelegationOrigin) if (!deployment.deployed) { - const child = deployment.name ? `"${deployment.name}" (${workflowId})` : workflowId if (deployment.name) childWorkflowName = deployment.name + const child = deployment.name ? `"${deployment.name}" (${workflowId})` : workflowId throw new Error( `Child workflow ${child} is not deployed. A deployed run calls the deployed version of each child workflow: deploy ${child}, then run again.` ) diff --git a/apps/sim/lib/workflows/editing/lint-report.ts b/apps/sim/lib/workflows/editing/lint-report.ts index 4c805e39683..2e3371c35a9 100644 --- a/apps/sim/lib/workflows/editing/lint-report.ts +++ b/apps/sim/lib/workflows/editing/lint-report.ts @@ -230,6 +230,23 @@ export async function buildWorkflowLintReport( ...collectUnquotedJsonStringReferences(graph) ) + // Started before the reference collectors so its lookup overlaps theirs. + const childFindings = loadChildWorkflowsForLint(graph.blocks, scope.workspaceId).then( + (children) => collectChildWorkflowFindings(graph, children, { deployed: options.deployed }), + (error: unknown) => { + logger.warn('Child workflow lint failed', { + workflowId: scope.workflowId, + error: getErrorMessage(error), + }) + if (options.requireComplete) { + throw new Error( + 'Workflow child workflow checks could not complete; retry when lookup is available' + ) + } + return [] + } + ) + if (scope.subjectUserId) { for (const collect of [collectUnresolvedReferences, collectUnresolvedAgentToolReferences]) { try { @@ -262,25 +279,7 @@ export async function buildWorkflowLintReport( } } - try { - unresolvedReferences.push( - ...collectChildWorkflowFindings( - graph, - await loadChildWorkflowsForLint(graph.blocks, scope.workspaceId), - { deployed: options.deployed } - ) - ) - } catch (error) { - logger.warn('Child workflow lint failed', { - workflowId: scope.workflowId, - error: getErrorMessage(error), - }) - if (options.requireComplete) { - throw new Error( - 'Workflow child workflow checks could not complete; retry when lookup is available' - ) - } - } + unresolvedReferences.push(...(await childFindings)) /** Standalone diagnostics have already read tables under application authorization. */ let tableFieldIssues: WorkflowLintTableFieldIssue[] = options.tables?.tableFieldIssues ?? [] diff --git a/apps/sim/lib/workflows/editing/lint.ts b/apps/sim/lib/workflows/editing/lint.ts index 512cb4b1fbf..308f3b1bc15 100644 --- a/apps/sim/lib/workflows/editing/lint.ts +++ b/apps/sim/lib/workflows/editing/lint.ts @@ -534,6 +534,10 @@ function collectBlockingSections(lint: WorkflowLintIssueView): WorkflowLintSecti const unresolved = lint.unresolvedReferences ?? [] const renderRef = (ref: WorkflowLintUnresolvedReference) => `${blockLabel(ref)}.${ref.field} (${ref.reason})` + const renderRefWithValue = (ref: WorkflowLintUnresolvedReference) => + `${blockLabel(ref)}.${ref.field} ${ + Array.isArray(ref.value) ? ref.value.join(', ') : ref.value + } (${ref.reason})` return [ lintSection( @@ -588,26 +592,12 @@ function collectBlockingSections(lint: WorkflowLintIssueView): WorkflowLintSecti ), lintSection( 'Block output references that will not work as written', - unresolved - .filter((ref) => ref.kind === 'block-output') - .map( - (ref) => - `${blockLabel(ref)}.${ref.field} ${ - Array.isArray(ref.value) ? ref.value.join(', ') : ref.value - } (${ref.reason})` - ), + unresolved.filter((ref) => ref.kind === 'block-output').map(renderRefWithValue), '; ' ), lintSection( 'Child workflow result paths that read nothing (a child that responds returns its Response output, { data, status, headers })', - unresolved - .filter((ref) => ref.kind === 'child-result') - .map( - (ref) => - `${blockLabel(ref)}.${ref.field} ${ - Array.isArray(ref.value) ? ref.value.join(', ') : ref.value - } (${ref.reason})` - ), + unresolved.filter((ref) => ref.kind === 'child-result').map(renderRefWithValue), '; ' ), lintSection( @@ -1148,22 +1138,19 @@ function calledWorkflowId(block: BlockState): string | undefined { } /** Every workflow the graph's Workflow blocks statically call. */ -export function collectCalledWorkflowIds( - blocks: WorkflowState['blocks'] | Record | undefined -): string[] { +export function collectCalledWorkflowIds(blocks: WorkflowState['blocks']): string[] { const ids = new Set() - for (const block of Object.values(blocks || {})) { - const id = calledWorkflowId(block as BlockState) + for (const block of Object.values(blocks)) { + const id = calledWorkflowId(block) if (id) ids.add(id) } return [...ids] } -/** The output of a child's Response block, which a responding child's run returns. */ -const RESPONSE_OUTPUT_KEYS = ['data', 'status', 'headers'] as const - -/** The Workflow block output holding the child's run result. */ -const CHILD_RESULT_OUTPUT = 'result' +/** The outputs of a Response block: what a responding child's run returns as `result`. */ +function responseOutputKeys(): ReadonlySet { + return new Set(Object.keys(getBlock('response')?.outputs ?? {})) +} /** * Findings about the workflows the graph's Workflow blocks call, judged against what `children` @@ -1180,13 +1167,13 @@ export function collectChildWorkflowFindings( { deployed = false }: { deployed?: boolean } = {} ): WorkflowLintUnresolvedReference[] { const blocks = (workflowState.blocks || {}) as Record - const childOf = new Map() + const childOf = new Map() const findings: WorkflowLintUnresolvedReference[] = [] for (const [blockId, block] of Object.entries(blocks)) { const id = calledWorkflowId(block) const child = id ? children.get(id) : undefined if (!id || !child) continue - childOf.set(blockId, { ...child, id }) + childOf.set(blockId, child) if (deployed && !child.deployed) { findings.push({ ...blockRef(blockId, block), @@ -1200,13 +1187,14 @@ export function collectChildWorkflowFindings( if (childOf.size === 0) return findings const targetByKey = referenceTargetIndex(blocks) + const responseKeys = responseOutputKeys() for (const [blockId, block] of Object.entries(blocks)) { for (const [subBlockId, subBlock] of Object.entries(block.subBlocks ?? {})) { const leaves: string[] = [] collectStringLeaves((subBlock as { value?: unknown })?.value, leaves) const byTarget = new Map< string, - { tokens: Set; keys: Set; meant: string[] } + { tokens: Set; keys: Set; meant: Set } >() for (const leaf of leaves) { for (const token of referenceCandidates(leaf, subBlockId === 'code')) { @@ -1214,25 +1202,30 @@ export function collectChildWorkflowFindings( const targetId = referenceTarget(token, targetByKey) if (!targetId || !childOf.get(targetId)?.responds) continue const [head, output = '', next, ...rest] = token.split('.') - if (output !== CHILD_RESULT_OUTPUT || !next) continue + if (output !== 'result' || !next) continue const key = splitLeadingBracketPath(next).property - if (!key || (RESPONSE_OUTPUT_KEYS as readonly string[]).includes(key)) continue - const group = byTarget.get(targetId) ?? { tokens: new Set(), keys: new Set(), meant: [] } + if (!key || responseKeys.has(key)) continue + const group = byTarget.get(targetId) ?? { + tokens: new Set(), + keys: new Set(), + meant: new Set(), + } group.tokens.add(`<${token}>`) group.keys.add(key) - group.meant.push(`<${[head, output, 'data', next, ...rest].join('.')}>`) + group.meant.add(`<${[head, output, 'data', next, ...rest].join('.')}>`) byTarget.set(targetId, group) } } for (const [targetId, group] of byTarget) { const target = blocks[targetId] const child = childOf.get(targetId) + if (!target || !child) continue findings.push({ ...blockRef(blockId, block), field: subBlockId, value: [...group.tokens], kind: 'child-result', - reason: `Workflow "${child?.name}" responds, so "${target?.name || targetId}".result is its Response output ({ data, status, headers }) and ${quoteList(group.keys)} under result reads nothing. Did you mean ${[...new Set(group.meant)].join(', ')}?`, + reason: `Workflow "${child.name}" responds, so "${target.name || targetId}".result is its Response output ({ data, status, headers }) and ${quoteList(group.keys)} under result reads nothing. Did you mean ${[...group.meant].join(', ')}?`, }) } } diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index e2e695e31fa..254aec40ca1 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -6,6 +6,7 @@ import { join } from 'node:path' import { isRecordLike, toRecord } from '@sim/utils/object' +import { findWorkflowReferenceTokens } from '@sim/utils/workflow-references' import { type BlockCatalog, type CanonicalWorkflow, @@ -16,9 +17,13 @@ import { didYouMean, EDIT_REFUSALS, encodeAnchor, + formatStoredPath, getOwn, parseJsonField, + parseStoredPath, parseWorkflowLock, + RESPONSE_BLOCK_TYPE, + RESPONSE_OUTPUTS, raisedMessage, refuseEditedFindings, refusesEdited, @@ -243,6 +248,13 @@ function inputMappingOf(canonical: CanonicalWorkflow['blocks'][string]): Record< return toRecord(value) } +/** The workflow a child workflow call names by key, or `null` for an id, a reference or none. */ +function calledWorkflowKey(canonical: CanonicalWorkflow['blocks'][string]): string | null { + const ref = canonical.params.workflowId + const child = ref?.kind === 'value' ? resourceNode(ref.value) : null + return child?.kind === 'workflow' ? child.key : null +} + /** * A child workflow call checked against the child's own `workflow.ts` in this directory: a child * without a Start trigger (`W_CHILD_NO_START`), and an `inputMapping` key its Start trigger does @@ -253,22 +265,21 @@ function childInputFindings( canonical: CanonicalWorkflow['blocks'][string], declarations: WorkspaceDeclarations ): ParamFinding[] { - const ref = canonical.params.workflowId - const child = ref?.kind === 'value' ? resourceNode(ref.value) : null - if (child?.kind !== 'workflow') return [] - const inputs = declarations.workflowInputs?.get(child.key) + const childKey = calledWorkflowKey(canonical) + if (childKey === null) return [] + const inputs = declarations.workflowInputs?.get(childKey) if (inputs === undefined) return [] - const entry = `${KIND_DIRS.workflow}/${child.key}/${SOURCE_ENTRY_FILE}` + const entry = `${KIND_DIRS.workflow}/${childKey}/${SOURCE_ENTRY_FILE}` if (inputs === null) { return [ { code: 'W_CHILD_NO_START', severity: 'warning', - message: `Workflow "${child.key}" has no Start trigger, so it takes no inputs and a call cannot run it.`, + message: `Workflow "${childKey}" has no Start trigger, so it takes no inputs and a call cannot run it.`, hint: `Add trigger.start('Start', { inputFormat: { … } }) to ${entry}, or call a workflow that has one.`, block, param: 'workflowId', - names: child.key, + names: childKey, }, ] } @@ -278,7 +289,7 @@ function childInputFindings( .map((field) => ({ code: 'W_CHILD_INPUT_UNKNOWN', severity: 'warning', - message: `inputMapping sets ${field}, which is not an input of workflow "${child.key}"; the child never receives it.`, + message: `inputMapping sets ${field}, which is not an input of workflow "${childKey}"; the child never receives it.`, hint: names.length > 0 ? `${didYouMean(field, names) ?? ''} Inputs (the Start trigger's inputFormat in ${entry}): ${listed(names)}.`.trimStart() @@ -288,22 +299,6 @@ function childInputFindings( })) } -/** The block type whose output a responding child workflow's run returns. */ -const RESPONSE_BLOCK_TYPE = 'response' - -/** The output of a Response block: what a responding child's `result` holds. */ -const RESPONSE_OUTPUTS: readonly string[] = ['data', 'status', 'headers'] - -/** A reference tag in canonical text, as the executor's resolver finds one. */ -const REFERENCE_TAG = /<([^<>]+)>/g - -/** The workflow a child workflow call names by key, or `null` for an id, a reference or none. */ -function calledWorkflowKey(canonical: CanonicalWorkflow['blocks'][string]): string | null { - const ref = canonical.params.workflowId - const child = ref?.kind === 'value' ? resourceNode(ref.value) : null - return child?.kind === 'workflow' ? child.key : null -} - /** Every string inside a value, depth first. */ function stringLeaves(value: unknown): string[] { if (typeof value === 'string') return [value] @@ -335,19 +330,26 @@ function childResultFindings( if (value.kind !== 'value') continue const reported = new Set() for (const text of stringLeaves(value.value)) { - for (const [, inner] of text.matchAll(REFERENCE_TAG)) { - const [head = '', output, key, ...rest] = inner.split('.') - const child = calls.get(head) - const field = key?.replace(/\[.*$/, '') - if (child === undefined || output !== 'result' || !field) continue - if (RESPONSE_OUTPUTS.includes(field) || reported.has(inner)) continue - reported.add(inner) - const meant = [head, output, 'data', key, ...rest].join('.') + for (const token of findWorkflowReferenceTokens(text)) { + if (token.kind !== 'workflow' || reported.has(token.value)) continue + const segments = parseStoredPath(token.value.slice(1, -1)) + const [head, output, field, ...rest] = segments ?? [] + const child = head?.kind === 'name' ? calls.get(head.name) : undefined + if (child === undefined || output?.kind !== 'name' || output.name !== 'result') continue + if (field?.kind !== 'name' || RESPONSE_OUTPUTS.includes(field.name)) continue + reported.add(token.value) + const meant = formatStoredPath([ + head, + output, + { kind: 'name', name: 'data' }, + field, + ...rest, + ]) findings.push({ code: 'W_CHILD_RESULT_PATH', severity: 'warning', - message: `<${inner}> reads ${field} from the result of workflow "${child}", which responds: its result is the Response output ({ data, status, headers }), so the path reads nothing.`, - hint: `Did you mean <${meant}>? A field of the child's Response data is result.data.${field}.`, + message: `${token.value} reads ${field.name} from the result of workflow "${child}", which responds: its result is the Response output ({ data, status, headers }), so the path reads nothing.`, + hint: `Did you mean <${meant}>? A field of the child's Response data is result.data.${field.name}.`, block, param, }) @@ -446,7 +448,7 @@ async function compileWorkflowDir( declarations?: WorkspaceDeclarations ) { const lockText = await readSourceText(dir, SOURCE_LOCK_FILE) - const parsedLock = lockText === null ? null : parseWorkflowLock(parseJsonText(lockText)) + const parsedLock = lockText === null ? null : parseWorkflowLock(lockText) const lock = parsedLock?.lock const [files, storedEdges, storedBlocks, printedWith] = await Promise.all([ readSourceFiles(dir, lock ?? null), @@ -477,47 +479,31 @@ async function compileWorkflowDir( } } -/** Text parsed as JSON, or the text itself when it is not JSON, which the lock parser refuses. */ -function parseJsonText(text: string): unknown { - try { - return JSON.parse(text) - } catch { - return text - } -} - -/** What a child workflow call is checked against, for each workflow of a workspace directory. */ -export interface WorkspaceWorkflows { - /** - * The inputs of each workflow that compiles (`startInputs`, `null` for one without a Start - * trigger), by key: what a call's `inputMapping` is checked against and what `workspace.d.ts` - * types it with. - */ - inputs: Map - /** - * The keys of the workflows that compile holding an enabled Response block: a call's `result` - * is then that block's output, `{ data, status, headers }`. - */ - responding: Set -} - -/** Compiles each workflow of the workspace directory `root` for {@link WorkspaceWorkflows}. */ +/** + * Compiles each workflow of the workspace directory `root` for what a child workflow call is + * checked against: the inputs of each workflow that compiles (`startInputs`, `null` without a + * Start trigger), which `workspace.d.ts` also types `inputMapping` with, and the keys of those + * holding an enabled response block, whose `result` is that block's output. + */ export async function workspaceWorkflows( root: string, catalog: BlockCatalog -): Promise { - const inputs = new Map() - const responding = new Set() +): Promise<{ + workflowInputs: Map + respondingWorkflows: Set +}> { + const workflowInputs = new Map() + const respondingWorkflows = new Set() for (const key of await workspaceWorkflowKeys(root)) { const { compiled } = await compileWorkflowDir(join(root, KIND_DIRS.workflow, key), catalog) if (!compiled.workflow) continue - inputs.set(key, startInputs(compiled.workflow)) + workflowInputs.set(key, startInputs(compiled.workflow)) const blocks = Object.values(compiled.workflow.blocks) if (blocks.some((block) => block.type === RESPONSE_BLOCK_TYPE && block.enabled !== false)) { - responding.add(key) + respondingWorkflows.add(key) } } - return { inputs, responding } + return { workflowInputs, respondingWorkflows } } /** @@ -686,7 +672,6 @@ export async function checkWorkflowDir( ), ...compiled.diagnostics.filter(exempt), ] - const prefixed = (file: string) => `${options.prefix ?? ''}${file}` // A lock every apply and status refuses fails the check too, however clean the source is. const lockFindings = lockProblems.map( (problem): CheckFinding => ({ @@ -698,7 +683,7 @@ export async function checkWorkflowDir( ? '`sim workspaces source get --dir `, from the workspace directory' : undefined ), - file: prefixed(SOURCE_LOCK_FILE), + file: `${prefix}${SOURCE_LOCK_FILE}`, ...(problem.path ? { path: problem.path } : {}), }) ) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts index b82a8893129..88664b3d2d6 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -96,15 +96,13 @@ export function attachWorkflowSourceCheck(source: Command): void { ? `\`sim workspaces source get --dir ${workspace.root}\`` : `\`sim workflows source get --dir ${options.dir}\` (or \`create\`)` ) - const workflows = workspace ? await workspaceWorkflows(workspace.root, catalog) : undefined - const declarations = - workspace && workflows - ? { - ...(await readWorkspaceDeclarations(workspace.root)), - workflowInputs: workflows.inputs, - respondingWorkflows: workflows.responding, - } - : undefined + const [declared, workflows] = workspace + ? await Promise.all([ + readWorkspaceDeclarations(workspace.root), + workspaceWorkflows(workspace.root, catalog), + ]) + : [] + const declarations = declared && workflows ? { ...declared, ...workflows } : undefined const { findings, entry, unlisted } = await checkWorkflowDir(options.dir, catalog, { strict: strictMode(options), ...(declarations ? { declarations } : {}), diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts index 3eef68366b3..b644b86e332 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts @@ -125,12 +125,11 @@ export function attachWorkspaceSourceCheck(source: Command): void { await withSourceDirLock(options.dir, async () => { const catalog = cachedCatalog(workspaceId) ?? (await fetchedCatalog(connect, workspaceId, options.dir)) - const workflows = await workspaceWorkflows(options.dir, catalog) - const declarations = { - ...(await readWorkspaceDeclarations(options.dir)), - workflowInputs: workflows.inputs, - respondingWorkflows: workflows.responding, - } + const [declared, workflows] = await Promise.all([ + readWorkspaceDeclarations(options.dir), + workspaceWorkflows(options.dir, catalog), + ]) + const declarations = { ...declared, ...workflows } const keys = await workspaceWorkflowKeys(options.dir) const findings: CheckFinding[] = [] const unlisted = { errors: 0, warnings: 0 } @@ -169,7 +168,7 @@ export function attachWorkspaceSourceCheck(source: Command): void { } await refreshWorkspaceTypes( options.dir, - withWorkflowInputs(declarations.local, workflows.inputs) + withWorkflowInputs(declarations.local, declarations.workflowInputs) ) await refreshWorkspaceTsconfigs(options.dir, workspaceId) reportCheck( diff --git a/packages/workflow-code/src/canonicalize/values.ts b/packages/workflow-code/src/canonicalize/values.ts index 06cfd27f754..f0afc08450d 100644 --- a/packages/workflow-code/src/canonicalize/values.ts +++ b/packages/workflow-code/src/canonicalize/values.ts @@ -13,7 +13,7 @@ import { setOwn } from '../records' import type { CanonContext } from './context' /** The executor's candidate pattern (`createReferencePattern`); each match is then vetted. */ -const REFERENCE_CANDIDATE = /<([^<>]+)>/g +export const REFERENCE_CANDIDATE = /<([^<>]+)>/g const VARIABLE_PREFIX = 'variable' /** diff --git a/packages/workflow-code/src/code-files/index.ts b/packages/workflow-code/src/code-files/index.ts index b1d16781a22..cf532131a2f 100644 --- a/packages/workflow-code/src/code-files/index.ts +++ b/packages/workflow-code/src/code-files/index.ts @@ -1,5 +1,11 @@ export { checkCodeFileBijection } from './bijection' export { type CodeFileRef, fromCodeFile } from './from-file' export { createJsContextScanner } from './lexer' -export { isIdentifierName, LOOP_PROPERTIES, PARALLEL_PROPERTIES } from './ref-path' +export { + formatStoredPath, + isIdentifierName, + LOOP_PROPERTIES, + PARALLEL_PROPERTIES, + parseStoredPath, +} from './ref-path' export { type CodeFileLanguage, codeFileLanguage, toCodeFile } from './to-file' diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index a4dc40465b5..afd4f8fc583 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -22,6 +22,7 @@ import { PARALLEL_BATCH_MAX, SUBFLOW_DATA_KEYS, } from '../canonicalize/subflows' +import { REFERENCE_CANDIDATE } from '../canonicalize/values' import { canonicalActivityInputs, isInactive, withStoredValue } from '../catalog/activity' import { editorDefaults } from '../catalog/defaults' import { @@ -1872,9 +1873,6 @@ function jsonField(value: Value | undefined): Json | undefined { return isJson(value) ? value : undefined } -/** The executor's reference candidate pattern (`createReferencePattern`); each is then vetted. */ -const CONDITION_REFERENCE = /<([^<>]+)>/g - /** * A while or do-while condition checked as the run evaluates it (`LoopOrchestrator` * `evaluateWhileCondition`): each reference is replaced by its value and the text runs as @@ -1894,7 +1892,7 @@ function checkLoopCondition( if (text.trim() === '') return const at = rangeOf(ctx, property.value) const selfReads = new Set() - const runnable = text.replace(CONDITION_REFERENCE, (match: string, inner: string) => { + const runnable = text.replace(REFERENCE_CANDIDATE, (match: string, inner: string) => { if (!isLikelyWorkflowReferenceSegment(match)) return match const segments = parseStoredPath(inner) const [head, field] = segments ?? [] diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index 8ac917625a4..5b900181a0a 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -33,8 +33,10 @@ export { export { checkCodeFileBijection, createJsContextScanner, + formatStoredPath, fromCodeFile, isIdentifierName, + parseStoredPath, } from './code-files' export { type CompileResult, compileWorkflow, type StoredEdgeRef } from './compile' export { codePointLabel, scriptName } from './compile/characters' @@ -115,7 +117,7 @@ export { isResourceKind } from './model' export { assignIdentifiers, printWorkflow } from './print' export { hasSuspiciousCharacter, printKey, quoteString } from './print/strings' export { getOwn, invertRecord, parseJsonContainer, setOrDelete, setOwn } from './records' -export { JS_RESERVED_WORDS, SDK_CORE_EXPORTS } from './sdk' +export { JS_RESERVED_WORDS, RESPONSE_BLOCK_TYPE, RESPONSE_OUTPUTS, SDK_CORE_EXPORTS } from './sdk' export { holdsSecret, withoutAuthScheme } from './secrets' export { mapAnchorIds, diff --git a/packages/workflow-code/src/sdk.ts b/packages/workflow-code/src/sdk.ts index 04bf90f6c8f..a3ec7b35186 100644 --- a/packages/workflow-code/src/sdk.ts +++ b/packages/workflow-code/src/sdk.ts @@ -29,6 +29,12 @@ export const RESPONSE_BLOCK_TYPE = 'response' */ export const RESPONSE_BODY_KEYS = ['body', 'status', 'headers'] as const +/** + * The outputs of a response block: what a child workflow call's `result` holds when the child + * responds, so a field of its body is `result.data.`. + */ +export const RESPONSE_OUTPUTS: readonly string[] = ['data', 'status', 'headers'] + /** * The SDK's tagged templates (`js\`...\``), each a core export. The printer and the * compiler's template check both read this list. From 12d491865b9f60237134425ffa06b31bb3c83254 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:13:28 -0800 Subject: [PATCH 24/37] test(workflow-code): cover the loop condition refusal on an edited loop; trim comment and test noise --- .../sanitization/json-sanitizer.test.ts | 1 - .../src/commands/protocol/source-check.ts | 1 - .../src/diagnostics/refusals.test.ts | 16 ++++++++++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/apps/sim/lib/workflows/sanitization/json-sanitizer.test.ts b/apps/sim/lib/workflows/sanitization/json-sanitizer.test.ts index 2c9c490ad29..38123ee9cde 100644 --- a/apps/sim/lib/workflows/sanitization/json-sanitizer.test.ts +++ b/apps/sim/lib/workflows/sanitization/json-sanitizer.test.ts @@ -193,7 +193,6 @@ describe('sanitizeForCopilot error output', () => { it('keeps the stored flag for a block no error edge leaves', () => { expect(blockWithFlag(false, false)).toBe(false) - expect(blockWithFlag(true, false)).toBe(true) expect(blockWithFlag(undefined, false)).toBeUndefined() }) }) diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index 254aec40ca1..b1fa7c68319 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -299,7 +299,6 @@ function childInputFindings( })) } -/** Every string inside a value, depth first. */ function stringLeaves(value: unknown): string[] { if (typeof value === 'string') return [value] if (Array.isArray(value)) return value.flatMap(stringLeaves) diff --git a/packages/workflow-code/src/diagnostics/refusals.test.ts b/packages/workflow-code/src/diagnostics/refusals.test.ts index 0c9a3b25cfe..cbe10c84c8b 100644 --- a/packages/workflow-code/src/diagnostics/refusals.test.ts +++ b/packages/workflow-code/src/diagnostics/refusals.test.ts @@ -198,6 +198,22 @@ describe('refuseEditedFindings', () => { expect(errors(refuseEditedFindings(compiled, edited('inner')))).toEqual([]) }) + it('refuses a loop condition the run cannot evaluate on an edited loop, and only there', () => { + const compiled = compile([ + START, + "const w = loop.while('W', { condition: ' < (3' }, (body) => {", + " const inner = fn('Inner', { code: 'return 1' })", + ' body.to(inner)', + '})', + 'start.to(w)', + ]) + + expect(errors(refuseEditedFindings(compiled, edited('w')))).toEqual([ + 'E_APPLY_LOOP_CONDITION_SYNTAX w', + ]) + expect(errors(refuseEditedFindings(compiled, edited('inner')))).toEqual([]) + }) + it('refuses a path no output has in an edited code file, and only there', () => { const compiled = compile( [ From 606959e305ee5d387a383ad317ecbdf2b424f52b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:29:42 -0800 Subject: [PATCH 25/37] refactor(workflow-code): reuse the shared child-call, string-leaf and Response-output helpers in the new checks The child lint reads the called workflow through getWorkflowInvocationTarget and the Response outputs through RESPONSE_OUTPUTS. collectStringLeaves moves to @sim/utils so the CLI check stops carrying a copy, and both source checks read their workspace declarations through one helper. --- .../sim/executor/handlers/workflow/handler.ts | 5 +- .../executor/utils/reference-validation.ts | 11 --- apps/sim/lib/workflows/editing/lint-report.ts | 11 +-- apps/sim/lib/workflows/editing/lint.ts | 67 +++++++------------ apps/sim/lib/workflows/editing/validation.ts | 12 ++-- .../src/commands/protocol/source-check.ts | 44 ++++++------ .../src/commands/protocol/source-status.ts | 17 ++--- .../protocol/workflow-source-check.ts | 13 ++-- .../protocol/workflow-source-status.ts | 2 +- .../protocol/workspace-source-check.ts | 10 +-- packages/utils/src/workflow-references.ts | 11 +++ .../workflow-sdk/src/codegen/reference.ts | 16 ++--- 12 files changed, 93 insertions(+), 126 deletions(-) diff --git a/apps/sim/executor/handlers/workflow/handler.ts b/apps/sim/executor/handlers/workflow/handler.ts index 33a69823f10..62b37772388 100644 --- a/apps/sim/executor/handlers/workflow/handler.ts +++ b/apps/sim/executor/handlers/workflow/handler.ts @@ -1391,10 +1391,7 @@ export class WorkflowBlockHandler implements BlockHandler { workflowId, state: 'deployed', }) - return { - deployed: definition.state !== null, - ...(definition.workflow.name ? { name: definition.workflow.name } : {}), - } + return { deployed: definition.state !== null, name: definition.workflow.name || undefined } } catch (error) { if (error instanceof DelegatedWorkspaceAuthorizationError) { throw childReadError(error, workflowId) diff --git a/apps/sim/executor/utils/reference-validation.ts b/apps/sim/executor/utils/reference-validation.ts index d0248289064..d348a6593cf 100644 --- a/apps/sim/executor/utils/reference-validation.ts +++ b/apps/sim/executor/utils/reference-validation.ts @@ -143,14 +143,3 @@ export function createWorkflowVariablePattern(): RegExp { 'g' ) } - -/** - * Collects every string leaf in a nested value — the shared walk for reference/env-token - * audits over block inputs (lint, deps, and the agent-cli mirrors each carried a copy). - */ -export function collectStringLeaves(value: unknown, out: string[]): void { - if (typeof value === 'string') out.push(value) - else if (Array.isArray(value)) for (const item of value) collectStringLeaves(item, out) - else if (typeof value === 'object' && value !== null) - for (const item of Object.values(value)) collectStringLeaves(item, out) -} diff --git a/apps/sim/lib/workflows/editing/lint-report.ts b/apps/sim/lib/workflows/editing/lint-report.ts index 2e3371c35a9..978fc5745c4 100644 --- a/apps/sim/lib/workflows/editing/lint-report.ts +++ b/apps/sim/lib/workflows/editing/lint-report.ts @@ -6,7 +6,6 @@ import type { WorkflowState } from '@sim/workflow-types/workflow' import { and, eq, inArray, isNull } from 'drizzle-orm' import { getTableById } from '@/lib/table/service' import { - collectCalledWorkflowIds, collectChildWorkflowFindings, collectDanglingBlockOutputReferences, collectTableBlockFieldIssues, @@ -27,6 +26,7 @@ import { collectUnresolvedReferences, UNRESOLVABLE_AT_LINT_NOTE, } from '@/lib/workflows/editing/validation' +import { collectReferencedWorkflowIds } from '@/lib/workflows/streaming/nested-output-options' import { type ManualRunEntryIssue, resolveManualRunEntry, @@ -126,10 +126,10 @@ interface WorkflowLintReportOptions extends AgentToolReferenceValidationOptions * reference check reports it. */ async function loadChildWorkflowsForLint( - blocks: Pick['blocks'], + graph: Pick, workspaceId: string ): Promise> { - const ids = collectCalledWorkflowIds(blocks) + const ids = collectReferencedWorkflowIds([graph]) const children = new Map() if (ids.length === 0) return children const [rows, responders] = await Promise.all([ @@ -231,8 +231,9 @@ export async function buildWorkflowLintReport( ) // Started before the reference collectors so its lookup overlaps theirs. - const childFindings = loadChildWorkflowsForLint(graph.blocks, scope.workspaceId).then( - (children) => collectChildWorkflowFindings(graph, children, { deployed: options.deployed }), + const childFindings = loadChildWorkflowsForLint(graph, scope.workspaceId).then( + (children) => + collectChildWorkflowFindings(graph, children, { deployed: options.deployed === true }), (error: unknown) => { logger.warn('Child workflow lint failed', { workflowId: scope.workflowId, diff --git a/apps/sim/lib/workflows/editing/lint.ts b/apps/sim/lib/workflows/editing/lint.ts index 308f3b1bc15..e7686418ef0 100644 --- a/apps/sim/lib/workflows/editing/lint.ts +++ b/apps/sim/lib/workflows/editing/lint.ts @@ -1,6 +1,11 @@ import { toRecordOrNull } from '@sim/utils/object' -import { findWorkflowReferenceTokens } from '@sim/utils/workflow-references' -import { didYouMean, readsIterationOutOfScope, type ScopeNode } from '@sim/workflow-code' +import { collectStringLeaves, findWorkflowReferenceTokens } from '@sim/utils/workflow-references' +import { + didYouMean, + RESPONSE_OUTPUTS, + readsIterationOutOfScope, + type ScopeNode, +} from '@sim/workflow-code' import type { CanonicalModeOverrides } from '@sim/workflow-code/catalog/canonical-index' import { MCP_STRUCTURED_CONTENT_OUTPUT } from '@/lib/mcp/output-schema' import { @@ -14,17 +19,16 @@ import { getResponseFormatOutputs, } from '@/lib/workflows/blocks/outputs' import { quotedBlockLabel } from '@/lib/workflows/labels' +import { getWorkflowInvocationTarget } from '@/lib/workflows/streaming/nested-output-options' import type { ManualRunEntryIssue } from '@/lib/workflows/triggers/manual-run' import { getBlock } from '@/blocks' import { isTriggerBlockType, - isWorkflowBlockType, normalizeName, REFERENCE, SPECIAL_REFERENCE_PREFIXES, } from '@/executor/constants' import { isPathInSchema } from '@/executor/utils/block-reference' -import { collectStringLeaves } from '@/executor/utils/reference-validation' import { splitLeadingBracketPath } from '@/executor/variables/resolvers/reference' import { collectBlockFieldIssues, @@ -1124,34 +1128,6 @@ export interface WorkflowLintChildWorkflow { responds: boolean } -/** The workflow a Workflow block statically calls, or `undefined` for a reference or none. */ -function calledWorkflowId(block: BlockState): string | undefined { - if (!isWorkflowBlockType(block.type)) return undefined - let params: Record - try { - params = extractBlockParams(block as Parameters[0]) - } catch { - return undefined - } - const id = params.workflowId - return typeof id === 'string' && id.trim() !== '' && !id.includes('<') ? id.trim() : undefined -} - -/** Every workflow the graph's Workflow blocks statically call. */ -export function collectCalledWorkflowIds(blocks: WorkflowState['blocks']): string[] { - const ids = new Set() - for (const block of Object.values(blocks)) { - const id = calledWorkflowId(block) - if (id) ids.add(id) - } - return [...ids] -} - -/** The outputs of a Response block: what a responding child's run returns as `result`. */ -function responseOutputKeys(): ReadonlySet { - return new Set(Object.keys(getBlock('response')?.outputs ?? {})) -} - /** * Findings about the workflows the graph's Workflow blocks call, judged against what `children` * (by workflow id) knows of each: @@ -1164,15 +1140,16 @@ function responseOutputKeys(): ReadonlySet { export function collectChildWorkflowFindings( workflowState: Pick, children: ReadonlyMap, - { deployed = false }: { deployed?: boolean } = {} + { deployed }: { deployed: boolean } ): WorkflowLintUnresolvedReference[] { const blocks = (workflowState.blocks || {}) as Record const childOf = new Map() const findings: WorkflowLintUnresolvedReference[] = [] - for (const [blockId, block] of Object.entries(blocks)) { - const id = calledWorkflowId(block) + for (const [blockId, stored] of Object.entries(workflowState.blocks || {})) { + const id = getWorkflowInvocationTarget(stored) const child = id ? children.get(id) : undefined if (!id || !child) continue + const block = blocks[blockId] childOf.set(blockId, child) if (deployed && !child.deployed) { findings.push({ @@ -1187,25 +1164,31 @@ export function collectChildWorkflowFindings( if (childOf.size === 0) return findings const targetByKey = referenceTargetIndex(blocks) - const responseKeys = responseOutputKeys() for (const [blockId, block] of Object.entries(blocks)) { for (const [subBlockId, subBlock] of Object.entries(block.subBlocks ?? {})) { const leaves: string[] = [] collectStringLeaves((subBlock as { value?: unknown })?.value, leaves) const byTarget = new Map< string, - { tokens: Set; keys: Set; meant: Set } + { + child: WorkflowLintChildWorkflow + tokens: Set + keys: Set + meant: Set + } >() for (const leaf of leaves) { for (const token of referenceCandidates(leaf, subBlockId === 'code')) { if (!token || !REF_TOKEN_SHAPE.test(token)) continue const targetId = referenceTarget(token, targetByKey) - if (!targetId || !childOf.get(targetId)?.responds) continue + const child = targetId ? childOf.get(targetId) : undefined + if (!targetId || !child?.responds) continue const [head, output = '', next, ...rest] = token.split('.') if (output !== 'result' || !next) continue const key = splitLeadingBracketPath(next).property - if (!key || responseKeys.has(key)) continue + if (!key || RESPONSE_OUTPUTS.includes(key)) continue const group = byTarget.get(targetId) ?? { + child, tokens: new Set(), keys: new Set(), meant: new Set(), @@ -1216,16 +1199,14 @@ export function collectChildWorkflowFindings( byTarget.set(targetId, group) } } - for (const [targetId, group] of byTarget) { + for (const [targetId, { child, ...group }] of byTarget) { const target = blocks[targetId] - const child = childOf.get(targetId) - if (!target || !child) continue findings.push({ ...blockRef(blockId, block), field: subBlockId, value: [...group.tokens], kind: 'child-result', - reason: `Workflow "${child.name}" responds, so "${target.name || targetId}".result is its Response output ({ data, status, headers }) and ${quoteList(group.keys)} under result reads nothing. Did you mean ${[...group.meant].join(', ')}?`, + reason: `Workflow "${child.name}" responds, so "${target?.name || targetId}".result is its Response output ({ data, status, headers }) and ${quoteList(group.keys)} under result reads nothing. Did you mean ${[...group.meant].join(', ')}?`, }) } } diff --git a/apps/sim/lib/workflows/editing/validation.ts b/apps/sim/lib/workflows/editing/validation.ts index 31da0d6ce43..26155b5e1bd 100644 --- a/apps/sim/lib/workflows/editing/validation.ts +++ b/apps/sim/lib/workflows/editing/validation.ts @@ -134,13 +134,11 @@ function withCanonicalNamesResolved( ) const written = members.filter((id) => Object.hasOwn(inputs, id)) if (written.length > 0) { - const named = members.map((id) => - id === group.basicId - ? group.advancedIds.length > 0 - ? `"${id}" (basic mode)` - : `"${id}"` - : `"${id}" (advanced mode)` - ) + const paired = isCanonicalPair(group) + const named = members.map((id) => { + if (!paired) return `"${id}"` + return `"${id}" (${id === group.basicId ? 'basic' : 'advanced'} mode)` + }) refuse( key, `"${key}" is the shared name of ${named.join(' and ')}, and this edit also sets ${written.map((id) => `"${id}"`).join(' and ')}: set one of them, not both` diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index b1fa7c68319..063c03a53e0 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { isRecordLike, toRecord } from '@sim/utils/object' -import { findWorkflowReferenceTokens } from '@sim/utils/workflow-references' +import { collectStringLeaves, findWorkflowReferenceTokens } from '@sim/utils/workflow-references' import { type BlockCatalog, type CanonicalWorkflow, @@ -50,7 +50,12 @@ import { import { type Diagnostic, findingsOutput } from './source-ui' import { blockDigest, readStoredBlockDigests, readStoredEdges } from './stored-edges' import { lockRecoveryHint, readSourceFiles } from './workflow-dir' -import { kindFolders, WORKSPACE_TREE, type WorkspaceDeclarations } from './workspace-source-dir' +import { + kindFolders, + readWorkspaceDeclarations, + WORKSPACE_TREE, + type WorkspaceDeclarations, +} from './workspace-source-dir' /** * A finding only the server can decide: `stored()` keeps a secret the stored workflow holds, and @@ -299,13 +304,6 @@ function childInputFindings( })) } -function stringLeaves(value: unknown): string[] { - if (typeof value === 'string') return [value] - if (Array.isArray(value)) return value.flatMap(stringLeaves) - if (isRecordLike(value)) return Object.values(value).flatMap(stringLeaves) - return [] -} - /** * `W_CHILD_RESULT_PATH` for each reference to `>` whose call runs a workflow of * this directory that responds, when `` is not one of the Response block's outputs: the @@ -328,7 +326,9 @@ function childResultFindings( for (const [param, value] of Object.entries(canonical.params)) { if (value.kind !== 'value') continue const reported = new Set() - for (const text of stringLeaves(value.value)) { + const leaves: string[] = [] + collectStringLeaves(value.value, leaves) + for (const text of leaves) { for (const token of findWorkflowReferenceTokens(text)) { if (token.kind !== 'workflow' || reported.has(token.value)) continue const segments = parseStoredPath(token.value.slice(1, -1)) @@ -479,18 +479,24 @@ async function compileWorkflowDir( } /** - * Compiles each workflow of the workspace directory `root` for what a child workflow call is - * checked against: the inputs of each workflow that compiles (`startInputs`, `null` without a - * Start trigger), which `workspace.d.ts` also types `inputMapping` with, and the keys of those - * holding an enabled response block, whose `result` is that block's output. + * The workspace directory `root`'s declarations, with what a child workflow call is checked + * against from compiling each of its workflows: the inputs of each workflow that compiles + * (`startInputs`, `null` without a Start trigger), which `workspace.d.ts` also types + * `inputMapping` with, and the keys of those holding an enabled response block, whose `result` is + * that block's output. */ -export async function workspaceWorkflows( +export async function readCheckDeclarations( root: string, catalog: BlockCatalog -): Promise<{ - workflowInputs: Map - respondingWorkflows: Set -}> { +): Promise>> { + const [declared, workflows] = await Promise.all([ + readWorkspaceDeclarations(root), + compileWorkspaceWorkflows(root, catalog), + ]) + return { ...declared, ...workflows } +} + +async function compileWorkspaceWorkflows(root: string, catalog: BlockCatalog) { const workflowInputs = new Map() const respondingWorkflows = new Set() for (const key of await workspaceWorkflowKeys(root)) { diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index 7382720f6c6..8c75733cdd5 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -33,20 +33,15 @@ type WorkspacePlanChange = ApplyWorkspaceSourceResponse['data']['plan'][number] export type ServerCheck = 'checked' | 'unreachable' | 'offline' /** - * The dry run's findings a status's plan shows: its errors and warnings, less those `listed` - * says the status reports as a change of its own (a stale base is drift or a conflict), and the - * info `I_FINDINGS_TRUNCATED` that says the list is incomplete (counted as neither). + * The dry run's findings a status's plan shows: its errors and warnings, and the info + * `I_FINDINGS_TRUNCATED` that says the list is incomplete (counted as neither). */ -export function planFindings( - diagnostics: readonly Diagnostic[], - listed: (code: Diagnostic['code']) => boolean = () => false -): Diagnostic[] { +export function planFindings(diagnostics: readonly Diagnostic[]): Diagnostic[] { return diagnostics.filter( (finding) => - (finding.severity === 'error' || - finding.severity === 'warning' || - finding.code === 'I_FINDINGS_TRUNCATED') && - !listed(finding.code) + finding.severity === 'error' || + finding.severity === 'warning' || + finding.code === 'I_FINDINGS_TRUNCATED' ) } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts index 88664b3d2d6..a25e07625be 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -6,6 +6,7 @@ import { CliUsageError } from './local-errors' import { cachedOrRefuse, checkWorkflowDir, + readCheckDeclarations, refreshWorkspaceTsconfigs, reportCheck, STRICT_HELP, @@ -13,7 +14,6 @@ import { strictFlags, strictMode, withWorkflowInputs, - workspaceWorkflows, } from './source-check' import { absoluteDirOption, @@ -31,7 +31,6 @@ import { } from './source-tree' import { verboseFlag } from './source-ui' import { requireEntry, WORKFLOW_TREE } from './workflow-dir' -import { readWorkspaceDeclarations } from './workspace-source-dir' const CHECK_HELP = ` Compiles workflow.ts (and the function files it names) with the compiler the server runs, against @@ -96,13 +95,9 @@ export function attachWorkflowSourceCheck(source: Command): void { ? `\`sim workspaces source get --dir ${workspace.root}\`` : `\`sim workflows source get --dir ${options.dir}\` (or \`create\`)` ) - const [declared, workflows] = workspace - ? await Promise.all([ - readWorkspaceDeclarations(workspace.root), - workspaceWorkflows(workspace.root, catalog), - ]) - : [] - const declarations = declared && workflows ? { ...declared, ...workflows } : undefined + const declarations = workspace + ? await readCheckDeclarations(workspace.root, catalog) + : undefined const { findings, entry, unlisted } = await checkWorkflowDir(options.dir, catalog, { strict: strictMode(options), ...(declarations ? { declarations } : {}), diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts index 501d92eb633..dd95840d73f 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts @@ -116,7 +116,7 @@ interface WorkflowPlanSummary { /** The dry run's findings the plan counts: all but `E_APPLY_STALE`, which the status lists. */ function workflowPlanFindings(data: PlanData): Diagnostic[] { - return planFindings(data.diagnostics, (code) => code === 'E_APPLY_STALE') + return planFindings(data.diagnostics).filter((finding) => finding.code !== 'E_APPLY_STALE') } function planSummary(data: PlanData): WorkflowPlanSummary { diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts index b644b86e332..4b50e6e7f60 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts @@ -9,6 +9,7 @@ import { CliUsageError, SourceDirError } from './local-errors' import { type CheckFinding, checkWorkflowDir, + readCheckDeclarations, refreshWorkspaceTsconfigs, reportCheck, requireCachedCatalog, @@ -18,7 +19,6 @@ import { strictMode, withWorkflowInputs, workspaceWorkflowKeys, - workspaceWorkflows, } from './source-check' import { absoluteDirOption, @@ -30,7 +30,7 @@ import { import { credentialRefused, unreachableReason } from './source-status' import { cachedCatalog, loadCatalog, refreshWorkspaceTypes } from './source-tree' import { verboseFlag } from './source-ui' -import { assertWorkspaceDir, readWorkspaceDeclarations } from './workspace-source-dir' +import { assertWorkspaceDir } from './workspace-source-dir' const CHECK_HELP = ` Compiles every workflows//workflow.ts (and the function files each names) with the compiler @@ -125,11 +125,7 @@ export function attachWorkspaceSourceCheck(source: Command): void { await withSourceDirLock(options.dir, async () => { const catalog = cachedCatalog(workspaceId) ?? (await fetchedCatalog(connect, workspaceId, options.dir)) - const [declared, workflows] = await Promise.all([ - readWorkspaceDeclarations(options.dir), - workspaceWorkflows(options.dir, catalog), - ]) - const declarations = { ...declared, ...workflows } + const declarations = await readCheckDeclarations(options.dir, catalog) const keys = await workspaceWorkflowKeys(options.dir) const findings: CheckFinding[] = [] const unlisted = { errors: 0, warnings: 0 } diff --git a/packages/utils/src/workflow-references.ts b/packages/utils/src/workflow-references.ts index 02e2aefc119..70f7d43e219 100644 --- a/packages/utils/src/workflow-references.ts +++ b/packages/utils/src/workflow-references.ts @@ -105,3 +105,14 @@ export function findWorkflowReferenceTokens(source: string): WorkflowReferenceTo return tokens.sort((left, right) => left.start - right.start) } + +/** + * Collects every string leaf in a nested value — the shared walk for reference/env-token + * audits over block inputs, shared by the server lint and the CLI's offline check. + */ +export function collectStringLeaves(value: unknown, out: string[]): void { + if (typeof value === 'string') out.push(value) + else if (Array.isArray(value)) for (const item of value) collectStringLeaves(item, out) + else if (typeof value === 'object' && value !== null) + for (const item of Object.values(value)) collectStringLeaves(item, out) +} diff --git a/packages/workflow-sdk/src/codegen/reference.ts b/packages/workflow-sdk/src/codegen/reference.ts index 8cf1736be75..bf83af41a17 100644 --- a/packages/workflow-sdk/src/codegen/reference.ts +++ b/packages/workflow-sdk/src/codegen/reference.ts @@ -151,21 +151,21 @@ function docCommentStart(start: number): number { /** Each top-level declaration of `name` in `core.d.ts` (overloads included): its line range. */ function coreDeclarationRanges(name: string): Array<{ start: number; end: number }> { - const lines = CORE_LINES const start = new RegExp( `^export (?:declare )?(?:const|function|namespace|interface|type) ${escapeRegExp(name)}\\b` ) const declarations: Array<{ start: number; end: number }> = [] - for (let index = 0; index < lines.length; index++) { - if (!start.test(lines[index])) continue + for (let index = 0; index < CORE_LINES.length; index++) { + if (!start.test(CORE_LINES[index])) continue let depth = 0 let end = index - for (; end < lines.length; end++) { - for (const char of lines[end]) { + for (; end < CORE_LINES.length; end++) { + for (const char of CORE_LINES[end]) { if ('({['.includes(char)) depth++ else if (')}]'.includes(char)) depth-- } - const continues = /[=:,|&]\s*$/.test(lines[end]) || /^\s+[?:|&]/.test(lines[end + 1] ?? '') + const continues = + /[=:,|&]\s*$/.test(CORE_LINES[end]) || /^\s+[?:|&]/.test(CORE_LINES[end + 1] ?? '') if (depth <= 0 && !continues) break } declarations.push({ start: index, end: end + 1 }) @@ -179,11 +179,9 @@ function coreDeclarationRanges(name: string): Array<{ start: number; end: number * returns an `Annotation`), one line per overload. */ function coreSignatures(name: string): string { - const lines = CORE_LINES return coreDeclarationRanges(name) .map(({ start, end }) => - lines - .slice(start, end) + CORE_LINES.slice(start, end) .join(' ') .replace(/^export (?:declare )?function /, '') .replace(/\s+/g, ' ') From 9afdc10bc55fababf925737806a029cfcd46df32 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 04:31:29 -0800 Subject: [PATCH 26/37] chore(workflow-code): trim restating comments and name the destructive-count test for what it checks --- .../application/apply.integration.ts | 43 +++++++++---------- .../src/commands/protocol/source-check.ts | 1 - .../src/commands/protocol/workflow-dir.ts | 1 - packages/utils/src/workflow-references.ts | 4 +- 4 files changed, 22 insertions(+), 27 deletions(-) diff --git a/apps/sim/lib/workspace-source/application/apply.integration.ts b/apps/sim/lib/workspace-source/application/apply.integration.ts index 1373086f664..e1495e0fa2a 100644 --- a/apps/sim/lib/workspace-source/application/apply.integration.ts +++ b/apps/sim/lib/workspace-source/application/apply.integration.ts @@ -2281,37 +2281,34 @@ export default workflow('Probe', {}, () => { expect(await tableSnapshot(workspaceId)).toEqual(before) }) - check( - 'counts the blocks an edited workflow removes as a delete, in the plan and its summary', - async () => { - const workspaceId = await newWorkspace() - await apply(workspaceId, STARTER) - const read = await get(workspaceId) - const entry = 'workflows/ingest/workflow.ts' - const files = { - ...read.files, - [entry]: `// @sim-sdk 1 + check('counts the blocks an edited workflow removes as a delete in its plan entry', async () => { + const workspaceId = await newWorkspace() + await apply(workspaceId, STARTER) + const read = await get(workspaceId) + const entry = 'workflows/ingest/workflow.ts' + const files = { + ...read.files, + [entry]: `// @sim-sdk 1 import { trigger, workflow } from '@sim/workflow-sdk' export default workflow('Ingest', {}, () => { trigger.start('Start', { inputFormat: { email: 'string' } }) }) `, - } + } - const planned = await apply(workspaceId, files, { - base: read.base, - dryRun: true, - allowDelete: true, - }) + const planned = await apply(workspaceId, files, { + base: read.base, + dryRun: true, + allowDelete: true, + }) - expect(planned.plan.find((change) => change.key === 'ingest')).toMatchObject({ - action: 'update', - fields: expect.arrayContaining(['blocks -1']), - destructive: { what: 'blocks', counts: { blocks: 1 } }, - }) - } - ) + expect(planned.plan.find((change) => change.key === 'ingest')).toMatchObject({ + action: 'update', + fields: expect.arrayContaining(['blocks -1']), + destructive: { what: 'blocks', counts: { blocks: 1 } }, + }) + }) check( 'renames a workflow its folder renames, and refuses a name another workflow holds', diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index 063c03a53e0..5192077d974 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -677,7 +677,6 @@ export async function checkWorkflowDir( ), ...compiled.diagnostics.filter(exempt), ] - // A lock every apply and status refuses fails the check too, however clean the source is. const lockFindings = lockProblems.map( (problem): CheckFinding => ({ code: problem.code, diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 28addb81069..786e9a25d99 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -141,7 +141,6 @@ export function lockRecoveryHint(get: string = WORKFLOW_GET): string { return `Restore ${SOURCE_LOCK_FILE} from version control, or write the source into a fresh directory (${get}) and carry your edits across.` } -/** A lock problem as one line: its path in the lock, then what is wrong. */ function lockProblem(finding: { path?: string; message: string }): string { return `${finding.path ? `${finding.path}: ` : ''}${finding.message}` } diff --git a/packages/utils/src/workflow-references.ts b/packages/utils/src/workflow-references.ts index 70f7d43e219..86934598108 100644 --- a/packages/utils/src/workflow-references.ts +++ b/packages/utils/src/workflow-references.ts @@ -107,8 +107,8 @@ export function findWorkflowReferenceTokens(source: string): WorkflowReferenceTo } /** - * Collects every string leaf in a nested value — the shared walk for reference/env-token - * audits over block inputs, shared by the server lint and the CLI's offline check. + * Collects every string leaf in a nested value: the walk the reference and env-token audits over + * block inputs share. */ export function collectStringLeaves(value: unknown, out: string[]): void { if (typeof value === 'string') out.push(value) From 3fdbc4eb41adc8fce33a37a62755ac73c25e25c7 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 05:00:55 -0800 Subject: [PATCH 27/37] docs(sim-cli): keep the create and export summaries short and move their detail into help The longer summaries renamed the CLI reference headings, so the #create-workflow and #print-a-workflow-as-a-portable-json-document anchors broke. The Start block and the cleared workspace bindings are now said in each command's help instead. --- apps/docs/content/docs/cli/reference.mdx | 8 ++++++-- apps/docs/content/docs/cli/workflows.mdx | 8 ++++++-- packages/sim-cli/src/contract/commands.ts | 12 ++++++++---- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index cfad9885a3e..ef21a2a94d2 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8141,7 +8141,7 @@ API request and response schemas: [updateWorkflowVersion](/api-reference/workflo ### sim workflows create -Create a workflow whose draft holds one start block (start_trigger, named Start); connect from it +Create workflow ```bash sim workflows create [options] @@ -8159,6 +8159,8 @@ sim workflows create [options] +The new workflow's draft holds one Start block (start_trigger, named Start): connect the blocks you add from it. + API request and response schemas: [createWorkflow](/api-reference/workflows/createWorkflowV2). ### sim workflows folders create @@ -8512,7 +8514,7 @@ API request and response schemas: [executeWorkflow](/api-reference/workflows/exe ### sim workflows export -Print a workflow as a portable JSON document. workspace bindings (a table, a child workflow, a knowledge base) print as null unless --include-workspace-bindings, and credentials always do: to read what a block is set to, use sim workflows state get +Print a workflow as a portable JSON document The export clears credentials, passwords, and table sub-block values, but it is not a general secret scanner. Inspect literal variables and inline configuration before sharing the document. @@ -8542,6 +8544,8 @@ sim workflows export [options] +Workspace bindings (a table, a child workflow, a knowledge base) print as null unless --include-workspace-bindings, and credentials always do: to read what a block is set to, use `sim workflows state get`. + API request and response schemas: [exportWorkflow](/api-reference/workflows/exportWorkflow). ### sim workflows source catalog diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 8aecb8b7313..2f270a48a89 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -56,7 +56,7 @@ sim workflows get API request and response schemas: [getWorkflow](/api-reference/workflows/getWorkflow). -### Create a workflow whose draft holds one start block (start_trigger, named Start); connect from it +### Create workflow ```bash sim workflows create [options] @@ -74,6 +74,8 @@ sim workflows create [options] +The new workflow's draft holds one Start block (start_trigger, named Start): connect the blocks you add from it. + API request and response schemas: [createWorkflow](/api-reference/workflows/createWorkflowV2). ### Update workflow @@ -1106,7 +1108,7 @@ API request and response schemas: [deleteWorkflowChatDeployment](/api-reference/ ## Export and import -### Print a workflow as a portable JSON document. workspace bindings (a table, a child workflow, a knowledge base) print as null unless --include-workspace-bindings, and credentials always do: to read what a block is set to, use sim workflows state get +### Print a workflow as a portable JSON document The export clears credentials, passwords, and table sub-block values, but it is not a general secret scanner. Inspect literal variables and inline configuration before sharing the document. @@ -1136,6 +1138,8 @@ sim workflows export [options] +Workspace bindings (a table, a child workflow, a knowledge base) print as null unless --include-workspace-bindings, and credentials always do: to read what a block is set to, use `sim workflows state get`. + API request and response schemas: [exportWorkflow](/api-reference/workflows/exportWorkflow). ### Preview workflow import diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 31f17156a4e..81c11d0183b 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -983,8 +983,9 @@ export const CLI_CONTRACT: CliContract = { flags: { folderPath: FOLDER_PATH_FLAG }, }, createWorkflow: { - describe: - 'Create a workflow whose draft holds one Start block (start_trigger, named Start); connect from it', + helpText: ` +The new workflow's draft holds one Start block (start_trigger, named Start): connect the +blocks you add from it.`, flags: { folderPath: { ...FOLDER_PATH_FLAG, @@ -2303,8 +2304,11 @@ export const CLI_CONTRACT: CliContract = { // The payload is the artifact: `sim workflows export > wf.json` has to // produce something `sim workflows import` accepts back. exportWorkflow: { - describe: - 'Print a workflow as a portable JSON document. Workspace bindings (a table, a child workflow, a knowledge base) print as null unless --include-workspace-bindings, and credentials always do: to read what a block is set to, use sim workflows state get', + describe: 'Print a workflow as a portable JSON document', + helpText: ` +Workspace bindings (a table, a child workflow, a knowledge base) print as null unless +--include-workspace-bindings, and credentials always do: to read what a block is set to, use +\`sim workflows state get\`.`, flags: { includeReferences: { boolean: true, From b16e020c383925f0f311ffcd1e024cc1c46f643c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 05:00:55 -0800 Subject: [PATCH 28/37] chore(docs): record the CLI reference code examples the help changes rewrote in the content baseline --- .../scripts/fixtures/content-baseline.json | 1674 +++++++++-------- 1 file changed, 844 insertions(+), 830 deletions(-) diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index aa47ad5c2c0..13bff03affc 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -2277,6 +2277,13 @@ "sha256": "575f3eca46c258a161e39e0bb8154f4e8ea02ed85bc48ba09e313bad08b2bdd7", "bytes": 24, "line": 38 + }, + { + "lang": "text", + "meta": null, + "sha256": "0a752f93f36e9515fd11690153150721f3286a0736d3da79f911bdaf2a3effcb", + "bytes": 710, + "line": 52 } ], "links": [ @@ -11051,2542 +11058,2549 @@ "lang": "bash", "meta": null, "sha256": "e89f5163bfcc02bcec8be44abb82d7807ccaeecc397ea8b3d8575e189f05a46a", - "bytes": null, - "line": null + "bytes": 19, + "line": 41 }, { "lang": "bash", "meta": null, "sha256": "3ce59639490b19f90613bf0b002f0d5f747ae6bf89110a31aaad132f4a5d56df", - "bytes": null, - "line": null + "bytes": 20, + "line": 64 }, { "lang": "bash", "meta": null, "sha256": "7be8dbf1bad323118735b5a0b4cdf49c653cc20508516225fe058776f0421e2e", - "bytes": null, - "line": null + "bytes": 20, + "line": 82 }, { "lang": "bash", "meta": null, "sha256": "5b13d0a219062e58827d50697e4cec707e48ebef466a5058abb6e524376cc18e", - "bytes": null, - "line": null + "bytes": 23, + "line": 102 }, { "lang": "bash", "meta": null, "sha256": "fac9741c4ccc5f0596cba54e6e2ecc4997e489032315eb4c80dd872c941dd0ae", - "bytes": null, - "line": null + "bytes": 20, + "line": 123 }, { "lang": "bash", "meta": null, "sha256": "cc2a546bb69dcb90170c414517e67c86b5a20c7918c28999cb06d15f19ad4774", - "bytes": null, - "line": null + "bytes": 28, + "line": 141 }, { "lang": "bash", "meta": null, "sha256": "f22525d91b0a915d24281bdac40a70c066449d9310582f844446e4fb2d9b347f", - "bytes": null, - "line": null + "bytes": 181, + "line": 169 }, { "lang": "bash", "meta": null, "sha256": "21d922f40e072101cbcfdfcd4ee3c6e9ca22fc35bc4828a37f79f57dafec8d02", - "bytes": null, - "line": null + "bytes": 17, + "line": 187 }, { "lang": "bash", "meta": null, "sha256": "56b302d091c4b589dde86d24739634d8f7d560873ca281d9962939aa6ff46ac1", - "bytes": null, - "line": null + "bytes": 33, + "line": 195 }, { "lang": "bash", "meta": null, "sha256": "ce318a355b5dabeedbde09c7ddeb4f9132a4a57501b15fd3c2d23b3b8c75fd7f", - "bytes": null, - "line": null + "bytes": 20, + "line": 229 }, { "lang": "bash", "meta": null, "sha256": "c74ad02c1945ec9c5cb8316f5ffeb64cc0b9dde01530570343e2dd2ee5c2ec23", - "bytes": null, - "line": null + "bytes": 20, + "line": 239 }, { "lang": "bash", "meta": null, "sha256": "abe19c862f574d48aa91f6a506496b6f6c414d03fab399a6c86e1c12b2f8302a", - "bytes": null, - "line": null + "bytes": 21, + "line": 247 }, { "lang": "bash", "meta": null, "sha256": "5c4299cf8aa6117a3a1a3c728d72c2a86f9627a5766d47be8ae1f03088642346", - "bytes": null, - "line": null + "bytes": 25, + "line": 259 }, { "lang": "bash", "meta": null, "sha256": "cf03b326f03d9bcb4260e2be1ca5bcb89551a8f7f2bb1ba85744f50a9a84b434", - "bytes": null, - "line": null + "bytes": 73, + "line": 277 }, { "lang": "bash", "meta": null, "sha256": "1350c2e26838e2b4a68726a51de8a06e2a5d32cc9714e0171c0dafd867db1d90", - "bytes": null, - "line": null + "bytes": 41, + "line": 294 }, { "lang": "bash", "meta": null, "sha256": "8b747ef16c178bb05ca7171ec48e801f20a250e774a44d2d3b9753bd69aa3ec2", - "bytes": null, - "line": null + "bytes": 29, + "line": 324 }, { "lang": "bash", "meta": null, "sha256": "88526e37fa1577427e6126306dc69d3afa94894d3dd313ae31286bff5eadafa4", - "bytes": null, - "line": null + "bytes": 28, + "line": 359 }, { "lang": "bash", "meta": null, "sha256": "437c1deab5031ec9ce664b5429f7b62c062fd592469411b7f61cc16a9e21aa15", - "bytes": null, - "line": null + "bytes": 26, + "line": 379 }, { "lang": "bash", "meta": null, "sha256": "575f3eca46c258a161e39e0bb8154f4e8ea02ed85bc48ba09e313bad08b2bdd7", - "bytes": null, - "line": null + "bytes": 24, + "line": 411 + }, + { + "lang": "text", + "meta": null, + "sha256": "0a752f93f36e9515fd11690153150721f3286a0736d3da79f911bdaf2a3effcb", + "bytes": 710, + "line": 425 }, { "lang": "bash", "meta": null, "sha256": "ecc11df2b60a4b0dc7d6b4e95f6fbee1f43554a8e32ee7232d50543a94e22273", - "bytes": null, - "line": null + "bytes": 25, + "line": 443 }, { "lang": "bash", "meta": null, "sha256": "451b8c0648b69af0d37673c7b6c4bd98eb8ce4baca0c902038fc1460938adf88", - "bytes": null, - "line": null + "bytes": 35, + "line": 475 }, { "lang": "bash", "meta": null, "sha256": "5037ed0778643f28636735f01bb24cd5f938bdc923f02abfacf6e37840a822f7", - "bytes": null, - "line": null + "bytes": 34, + "line": 506 }, { "lang": "bash", "meta": null, "sha256": "ef5100ffa39072ae2ba9bb021d546036b95ded8da431fad855f809550c8913fb", - "bytes": null, - "line": null + "bytes": 47, + "line": 539 }, { "lang": "bash", "meta": null, "sha256": "4051f5bb25072a25196ba8e847ab22b9d42aeb0cbb36186b5e7cc051d77c00e0", - "bytes": null, - "line": null + "bytes": 53, + "line": 569 }, { "lang": "bash", "meta": null, "sha256": "2b6d0db0f06b8f51733c7da29a0c183aab73a6da83b787db76e7c3064fc9c78c", - "bytes": null, - "line": null + "bytes": 64, + "line": 603 }, { "lang": "bash", "meta": null, "sha256": "a74b652635bc27ca58af7b080b78d983469558a2668f0b3f033a1b5b2f4cef10", - "bytes": null, - "line": null + "bytes": 55, + "line": 634 }, { "lang": "bash", "meta": null, "sha256": "e407b3388ac13c30e985d64e41a9fb8f68c52e6e7a020bc3db79ce9473944724", - "bytes": null, - "line": null + "bytes": 40, + "line": 665 }, { "lang": "bash", "meta": null, "sha256": "cb3d67be4a05a8cc95870cadb5ac682c16e80889db6606e388dd48651bfc4af4", - "bytes": null, - "line": null + "bytes": 30, + "line": 685 }, { "lang": "bash", "meta": null, "sha256": "f7e2cb3ed34992b91cdcbd2fa65eadb48134c31e0d295519421644ad0668f20e", - "bytes": null, - "line": null + "bytes": 47, + "line": 710 }, { "lang": "bash", "meta": null, "sha256": "3ce249d6b52442bdf5df53436bae6b9718064994b4b26ecf25372ce53606db08", - "bytes": null, - "line": null + "bytes": 45, + "line": 763 }, { "lang": "bash", "meta": null, "sha256": "48d4019bc1905094aec776873af1d5a4e94ec2f52d043c51bbbb559b6a876944", - "bytes": null, - "line": null + "bytes": 276, + "line": 806 }, { "lang": "bash", "meta": null, "sha256": "866eaf5e25ac2d6471b52118f082a507d5300b7c80cd82ecbe3cfbce598c5f6a", - "bytes": null, - "line": null + "bytes": 54, + "line": 818 }, { "lang": "bash", "meta": null, "sha256": "48d4019bc1905094aec776873af1d5a4e94ec2f52d043c51bbbb559b6a876944", - "bytes": null, - "line": null + "bytes": 276, + "line": 856 }, { "lang": "bash", "meta": null, "sha256": "e0ac83da55217195ac0ca3bd1a41314be433d0a62428f36eb9666df607e8322c", - "bytes": null, - "line": null + "bytes": 46, + "line": 868 }, { "lang": "bash", "meta": null, "sha256": "664dfa9d010be73d8c8d4c1b079e946a646cc4677891d5fd34df9e5817cabfed", - "bytes": null, - "line": null + "bytes": 40, + "line": 898 }, { "lang": "bash", "meta": null, "sha256": "55d8bb7d28001fafb0a76ccaf87863cb67f0150ffef73889e5c363ce3775131b", - "bytes": null, - "line": null + "bytes": 33, + "line": 924 }, { "lang": "bash", "meta": null, "sha256": "02ff8ad73ece2f21edb90fc1a69904f322032da6d90a23d28d2d490beb55ab53", - "bytes": null, - "line": null + "bytes": 48, + "line": 948 }, { "lang": "bash", "meta": null, "sha256": "06a7f6e71ab68db991126dcf2d660866aec7b89d27f751d082d2f90030a19b00", - "bytes": null, - "line": null + "bytes": 35, + "line": 978 }, { "lang": "bash", "meta": null, "sha256": "3c9e74b86271246976e186b32c311a50f367fcd701f0506a56c8c8150c01b400", - "bytes": null, - "line": null + "bytes": 31, + "line": 998 }, { "lang": "bash", "meta": null, "sha256": "c0bbfff139a69379e188cfe4bbd3393285fce565dd83f7098eb2d387356da9c4", - "bytes": null, - "line": null + "bytes": 48, + "line": 1021 }, { "lang": "bash", "meta": null, "sha256": "c569c5e38502a1c1e8f6078954bc90b559dd80adb577bb4cf7b63ec7bbdb3aa7", - "bytes": null, - "line": null + "bytes": 46, + "line": 1061 }, { "lang": "bash", "meta": null, "sha256": "939a624f32ea05ac4cddd6037a27cdc7829018f0ac8096e4afd85aa9fab93ea2", - "bytes": null, - "line": null + "bytes": 24, + "line": 1092 }, { "lang": "bash", "meta": null, "sha256": "428eca668e88f6323ab89a2e488c5fd403b8b04064b26b55a3b8ca7ddb966be5", - "bytes": null, - "line": null + "bytes": 26, + "line": 1111 }, { "lang": "bash", "meta": null, "sha256": "66b86826e7fbeb5cc1b35c54dcbf9727264c2b6d50528e8c21accaff3a708806", - "bytes": null, - "line": null + "bytes": 31, + "line": 1135 }, { "lang": "bash", "meta": null, "sha256": "a461b9c9fef3090d3367148a2a183410e81624e42e340c21a4138c30c6b4409c", - "bytes": null, - "line": null + "bytes": 41, + "line": 1157 }, { "lang": "bash", "meta": null, "sha256": "8c86de167a3b73c5430d2b15f558b7c0b2a82cd347b4e85907862196cf8e16bc", - "bytes": null, - "line": null + "bytes": 32, + "line": 1188 }, { "lang": "bash", "meta": null, "sha256": "8a9eb6688329292f21fecba059890d65dab0a136e86f26d38987c27d68013ad8", - "bytes": null, - "line": null + "bytes": 43, + "line": 1216 }, { "lang": "bash", "meta": null, "sha256": "be3c635d1b158a14e8e00c6e88d84e4126e29d89f0464ebf0b296f19b2bdf59b", - "bytes": null, - "line": null + "bytes": 32, + "line": 1239 }, { "lang": "bash", "meta": null, "sha256": "993262e619d4470867077b7a4e0c528f715be468511bf9e072e8a9429ef250a1", - "bytes": null, - "line": null + "bytes": 35, + "line": 1261 }, { "lang": "bash", "meta": null, "sha256": "adc4973b83b313bcaf5f9058297e030a9c272cb1b5612fe8465b02edf2ad1b73", - "bytes": null, - "line": null + "bytes": 54, + "line": 1293 }, { "lang": "bash", "meta": null, "sha256": "48fbd97b704f5e02a593cbf0020bc3c6600ff1b4d349ae80b3cba39225a4b9fc", - "bytes": null, - "line": null + "bytes": 46, + "line": 1324 }, { "lang": "bash", "meta": null, "sha256": "49e712965d1a8af321563bc382bb448e0b68067c3c68861f84896b5f97e70314", - "bytes": null, - "line": null + "bytes": 42, + "line": 1345 }, { "lang": "bash", "meta": null, "sha256": "e463cbe0c80554eaa7fe151c51523307240c2226a54924a3d984cdc0a84f529b", - "bytes": null, - "line": null + "bytes": 52, + "line": 1378 }, { "lang": "bash", "meta": null, "sha256": "23bede1f0d68221f4da857a62e0594d031e40e5a794bd96c79eba2de2924072a", - "bytes": null, - "line": null + "bytes": 54, + "line": 1411 }, { "lang": "bash", "meta": null, "sha256": "ad1df0d9a424569351d851507b674bb104654e1251d7bee11ebc6955e0f2be6c", - "bytes": null, - "line": null + "bytes": 56, + "line": 1443 }, { "lang": "bash", "meta": null, "sha256": "37cdd4ceab29424161734300286176b9971cd7d6c134022308d5b21e4fa9e714", - "bytes": null, - "line": null + "bytes": 33, + "line": 1475 }, { "lang": "bash", "meta": null, "sha256": "0bc8335422d07dfbc74c55102518d6d2965a5aa27be6994b8b4317478e13ef3d", - "bytes": null, - "line": null + "bytes": 37, + "line": 1506 }, { "lang": "bash", "meta": null, "sha256": "863b992687ec7121ef44d5680b290502052bfe51e7e43aa24376ddba51fc3841", - "bytes": null, - "line": null + "bytes": 28, + "line": 1536 }, { "lang": "bash", "meta": null, "sha256": "9d7e15ac24392a0771cf7857c3f110be1ede32e18427995923edc5978fdcaa31", - "bytes": null, - "line": null + "bytes": 38, + "line": 1556 }, { "lang": "bash", "meta": null, "sha256": "15849bbb5c9f4f1c0754c0c99d3048b910f6fdcbb02ab84a4e34d7ed1930cd15", - "bytes": null, - "line": null + "bytes": 24, + "line": 1589 }, { "lang": "bash", "meta": null, "sha256": "31cbe1979c2c645d78646d966ac83fd45e6b556d56ab0d8fc47a7abd281e524d", - "bytes": null, - "line": null + "bytes": 24, + "line": 1616 }, { "lang": "bash", "meta": null, "sha256": "1a728e81af7425e00df25a70a5819d272cbddcab487426cebc94de7834509999", - "bytes": null, - "line": null + "bytes": 33, + "line": 1639 }, { "lang": "bash", "meta": null, "sha256": "f7a8e9f75a2ea3d88d6d12b097f20a94e2b915741cc10f805b070c6ad4261a7e", - "bytes": null, - "line": null + "bytes": 35, + "line": 1671 }, { "lang": "bash", "meta": null, "sha256": "94537050876dfc16340c4db7965fcc2a098f09fcb9911d5e154c11721d212e6a", - "bytes": null, - "line": null + "bytes": 26, + "line": 1701 }, { "lang": "bash", "meta": null, "sha256": "cdee40f5dc3195f9db4462ddd0e5b7bc03b44f600a82f357d6b651ecee770840", - "bytes": null, - "line": null + "bytes": 26, + "line": 1721 }, { "lang": "bash", "meta": null, "sha256": "bda181f24ee73df10ced9c179ddb81b115d62b4da46eb64b63dd23e7f4c51a96", - "bytes": null, - "line": null + "bytes": 34, + "line": 1748 }, { "lang": "bash", "meta": null, "sha256": "14e217553dedf133ef014fd989058ee281844a55293e05a9dddf044947c058fe", - "bytes": null, - "line": null + "bytes": 40, + "line": 1778 }, { "lang": "bash", "meta": null, "sha256": "30f91370cbb0ddf76900ab363e83bb26c0a95cb81518de875885f66d4c9df4a3", - "bytes": null, - "line": null + "bytes": 33, + "line": 1810 }, { "lang": "bash", "meta": null, "sha256": "1c143b6c0cd2e76ce8c74504ecb5ee2560b147eb299d8f0d3d956854b706958c", - "bytes": null, - "line": null + "bytes": 32, + "line": 1841 }, { "lang": "bash", "meta": null, "sha256": "b36a5102aee98e664a1ca4cc19d91310af00b2a4afbb04c78589bb4c3a2936a9", - "bytes": null, - "line": null + "bytes": 29, + "line": 1872 }, { "lang": "bash", "meta": null, "sha256": "62a17f5231fba3f732cba025c16c8b6706411b9267e6abd58e4e51aff8777043", - "bytes": null, - "line": null + "bytes": 22, + "line": 1903 }, { "lang": "bash", "meta": null, "sha256": "760a88e6d91ed147f40d39808ae39d178b6c38b61a5c69dd37755079cff376c2", - "bytes": null, - "line": null + "bytes": 69, + "line": 1929 }, { "lang": "bash", "meta": null, "sha256": "e0173107cc10779c1b96d55c66a3bd628e9bc21b39234101e2f9d7519087780e", - "bytes": null, - "line": null + "bytes": 51, + "line": 1959 }, { "lang": "bash", "meta": null, "sha256": "71bb24f623f1958775fe0f9df499ad3f8241c3132ea8f8a40d5f26bd2041b65e", - "bytes": null, - "line": null + "bytes": 53, + "line": 1989 }, { "lang": "bash", "meta": null, "sha256": "51d1aa93ed9262fa8f275fbd24e805ad9a3a075ed2f5c3888d57ecf909426c3e", - "bytes": null, - "line": null + "bytes": 61, + "line": 2023 }, { "lang": "bash", "meta": null, "sha256": "4782c15ea248b0cb3a7cffa4242b54f9bea866ecf26f63ada4ed921455699cb3", - "bytes": null, - "line": null + "bytes": 54, + "line": 2056 }, { "lang": "bash", "meta": null, "sha256": "c8f14f40bbc787d13778c342211d73c9f0b118a8d37d3c82a87c72b42b9d5d93", - "bytes": null, - "line": null + "bytes": 56, + "line": 2088 }, { "lang": "bash", "meta": null, "sha256": "913db46a26314244a1e4c903adb6772a8e405da8cba64f7218ff3683d7daa72a", - "bytes": null, - "line": null + "bytes": 41, + "line": 2118 }, { "lang": "bash", "meta": null, "sha256": "7cda9f00d098a51943b10891142d7e6a8d4cb46d752e1cdae5825ab6c56b8aa9", - "bytes": null, - "line": null + "bytes": 42, + "line": 2138 }, { "lang": "bash", "meta": null, "sha256": "e09f666b66b4d7acdcd6aa26831c7f258ff49baa0fd762ea920b90fd39846582", - "bytes": null, - "line": null + "bytes": 61, + "line": 2158 }, { "lang": "bash", "meta": null, "sha256": "8b204243cf243c64557adb522d2bfd72be53400afab3c03f4c314117ed37655d", - "bytes": null, - "line": null + "bytes": 74, + "line": 2192 }, { "lang": "bash", "meta": null, "sha256": "cf87bc61bba385818ebc622f9b9f481213e1d86f65df7ab1a193749ab929a651", - "bytes": null, - "line": null + "bytes": 68, + "line": 2225 }, { "lang": "bash", "meta": null, "sha256": "2d57fee1358f9ce5a3f166aed1400940cbe737b04d8f487a16eb35bc3bb5a6d4", - "bytes": null, - "line": null + "bytes": 78, + "line": 2260 }, { "lang": "bash", "meta": null, "sha256": "7f02636a02ece5cd252aad171e251b18e1c29207d62dfcc962485052b799fdc4", - "bytes": null, - "line": null + "bytes": 65, + "line": 2292 }, { "lang": "bash", "meta": null, "sha256": "e6a2660057e8859cebd226a4420672f12beed4e274bdc57a4b70c96a0142b1b6", - "bytes": null, - "line": null + "bytes": 66, + "line": 2314 }, { "lang": "bash", "meta": null, "sha256": "54b00a2d3830092a8fe552bba29419710da6647ac3cc96d6a0a9ffbef596c440", - "bytes": null, - "line": null + "bytes": 78, + "line": 2350 }, { "lang": "bash", "meta": null, "sha256": "a0a28be794c70e6366719b49f3ad627faa087181960d287d6a17bc44d7a8bd9d", - "bytes": null, - "line": null + "bytes": 64, + "line": 2384 }, { "lang": "bash", "meta": null, "sha256": "2a48509e548ba0f0d2bb97bfc37ac1807f3b34cc5c44cbd1c5ca57735614fc24", - "bytes": null, - "line": null + "bytes": 71, + "line": 2419 }, { "lang": "bash", "meta": null, "sha256": "ea154f4a00845d5c60d54aff14d7173c8de383ec43e13454a8c326459ed7695f", - "bytes": null, - "line": null + "bytes": 58, + "line": 2450 }, { "lang": "bash", "meta": null, "sha256": "f14623530e7aeb20de131c59208269f9703e85ab6a89cd4368fb3c2ff7c36863", - "bytes": null, - "line": null + "bytes": 56, + "line": 2471 }, { "lang": "bash", "meta": null, "sha256": "cdf3ade3d9fa9f1f3a191265a2b0de8092eaaa49bd961d94eccb09355dfddb26", - "bytes": null, - "line": null + "bytes": 71, + "line": 2507 }, { "lang": "bash", "meta": null, "sha256": "2f509b586cc62ff6bb0b5c1ee7e5062689b1cfd987acc2c18dee6b10bc3a194f", - "bytes": null, - "line": null + "bytes": 65, + "line": 2561 }, { "lang": "bash", "meta": null, "sha256": "6546c4a95a217203c622f0e62f945cbe2863d42d02a5229621f43f12b68bc063", - "bytes": null, - "line": null + "bytes": 39, + "line": 2595 }, { "lang": "bash", "meta": null, "sha256": "e9f1685d2a50e4bd554c7daf19621a7704aa5b1aea3540af28884066ae413c69", - "bytes": null, - "line": null + "bytes": 36, + "line": 2615 }, { "lang": "bash", "meta": null, "sha256": "ad0c1107caee2427422e0a52a6da2df0a037010f93467fd957fb0136f938d675", - "bytes": null, - "line": null + "bytes": 30, + "line": 2635 }, { "lang": "bash", "meta": null, "sha256": "fae160a2cd7e296a9f9b00fa789ba95a2f1e507713a469902de21ed945d9eb25", - "bytes": null, - "line": null + "bytes": 59, + "line": 2658 }, { "lang": "bash", "meta": null, "sha256": "abdae7f49c77877550cfc2d7195132c12fb0117a0471faf1c525d44ad2de1321", - "bytes": null, - "line": null + "bytes": 73, + "line": 2694 }, { "lang": "bash", "meta": null, "sha256": "d11c4c59feac4345ba7dfb02edc2780adae89cf702e570f32e1ccc8555bdb169", - "bytes": null, - "line": null + "bytes": 60, + "line": 2727 }, { "lang": "bash", "meta": null, "sha256": "af533689c0b530ff902ae36c2cac7198f43ff6968d168a94da153d81fe8020fd", - "bytes": null, - "line": null + "bytes": 81, + "line": 2748 }, { "lang": "bash", "meta": null, "sha256": "f907eb4bee803d3f45d4abc9baae106aaec0249143dfd9cf56aa17285776a430", - "bytes": null, - "line": null + "bytes": 83, + "line": 2782 }, { "lang": "bash", "meta": null, "sha256": "28c4e709c778f27d924fbe49edb4bf198b7c73e9b65619e6fad43d1fb9e2cfb7", - "bytes": null, - "line": null + "bytes": 57, + "line": 2814 }, { "lang": "bash", "meta": null, "sha256": "0a7262cac83ce7c16b17a1364a123764e5fa8b645dd60fd5b394b3f74dd0e1fa", - "bytes": null, - "line": null + "bytes": 71, + "line": 2846 }, { "lang": "bash", "meta": null, "sha256": "a25c869b7add79bfe6f194ec72190bb6b4957bb303fe6b4c31c9455f4a2e11a9", - "bytes": null, - "line": null + "bytes": 73, + "line": 2878 }, { "lang": "bash", "meta": null, "sha256": "b3f9e190362420216749c9924e83a35c5a5c2414ab03ff89601a6b9501494bf9", - "bytes": null, - "line": null + "bytes": 35, + "line": 2911 }, { "lang": "bash", "meta": null, "sha256": "ae5dcbc80aeb125607ebd763669a1f335d6ddf087a6baf1853453867675ce865", - "bytes": null, - "line": null + "bytes": 45, + "line": 2933 }, { "lang": "bash", "meta": null, "sha256": "c91b2cb83c28571b965071d6643d955366931a6ca3dd340e54d8536ea90cefde", - "bytes": null, - "line": null + "bytes": 36, + "line": 2964 }, { "lang": "bash", "meta": null, "sha256": "de622393fa33cc9b0002c7d670d9f45c2bcd9fbfe3f0c99be71ae96969a005dd", - "bytes": null, - "line": null + "bytes": 47, + "line": 2989 }, { "lang": "bash", "meta": null, "sha256": "356cb12341ce90e24b765d02a997421c0469a3b26509c90e42a17af4dd3f9e95", - "bytes": null, - "line": null + "bytes": 48, + "line": 3014 }, { "lang": "bash", "meta": null, "sha256": "a611d4f425ac65781756225557a7e8f8559faccaa4c6466ef23fa78cd2a2226c", - "bytes": null, - "line": null + "bytes": 35, + "line": 3044 }, { "lang": "bash", "meta": null, "sha256": "8c7bab52ede04cca1dd71b466bd76c7f5b67c6b7f0fed08e14ee7656d6b2b160", - "bytes": null, - "line": null + "bytes": 28, + "line": 3064 }, { "lang": "bash", "meta": null, "sha256": "063e71c7485fe7d3657e692841a2f0629e6a31b48e8501282b0456202eefaa5d", - "bytes": null, - "line": null + "bytes": 39, + "line": 3089 }, { "lang": "bash", "meta": null, "sha256": "4f9e7b46b98628ddded377f3a73cb2e9b4751023b7b1fc90c1cefc90555c80c4", - "bytes": null, - "line": null + "bytes": 30, + "line": 3109 }, { "lang": "bash", "meta": null, "sha256": "efaaf65fd8057cd592d386d0e0c800eef4e71d649a1f011fd2f20495d8d942ab", - "bytes": null, - "line": null + "bytes": 48, + "line": 3137 }, { "lang": "bash", "meta": null, "sha256": "5303a1a6194097b3acc7546ccafb0faced44b084951b7e14ff1029cf0fdff957", - "bytes": null, - "line": null + "bytes": 43, + "line": 3170 }, { "lang": "bash", "meta": null, "sha256": "a9ba0ea93105e0f224ed0c3e661adf5fe706a875fb9741348134814d65c6d882", - "bytes": null, - "line": null + "bytes": 48, + "line": 3191 }, { "lang": "bash", "meta": null, "sha256": "a721f46390cb321c013b700b13f46f2e9833616be44a3ee8e0971c3e5c0f945b", - "bytes": null, - "line": null + "bytes": 37, + "line": 3223 }, { "lang": "bash", "meta": null, "sha256": "9f9b6ea8992e8fcd2bdb540857d42288ba0ecedb959ff5c1c56de708e65db79e", - "bytes": null, - "line": null + "bytes": 33, + "line": 3254 }, { "lang": "bash", "meta": null, "sha256": "1478c9884eb8c9bc2dd64170d3fb101030957399aab5da911d5f77d46b662c73", - "bytes": null, - "line": null + "bytes": 26, + "line": 3285 }, { "lang": "bash", "meta": null, "sha256": "51b81826c6f4b7933c1c802c82baca186c67efe8e59e69a6a7754360fe8675da", - "bytes": null, - "line": null + "bytes": 30, + "line": 3311 }, { "lang": "bash", "meta": null, "sha256": "8aeb5fc735c8037c480f3c8220149fb6f811de62c946584523d50d1cd1811a53", - "bytes": null, - "line": null + "bytes": 24, + "line": 3343 }, { "lang": "bash", "meta": null, "sha256": "a1bf4221604cc962c677313543850fe6cd140476ef52de3a9e29b305865ae8f0", - "bytes": null, - "line": null + "bytes": 23, + "line": 3372 }, { "lang": "bash", "meta": null, "sha256": "5215bc6f0c098350b8067dd283226f3444cf73599ab1989c5dfae5c563069a04", - "bytes": null, - "line": null + "bytes": 25, + "line": 3416 }, { "lang": "bash", "meta": null, "sha256": "98f84efeb01c77bc8c1aadb62fbd989c5ae41de97d07fd9b59e8b2b53cafe06f", - "bytes": null, - "line": null + "bytes": 145, + "line": 3440 }, { "lang": "bash", "meta": null, "sha256": "baad97733d922f4ef4c068577ef9f0f855c44f3b54e9b80a61733a4fecfd350d", - "bytes": null, - "line": null + "bytes": 32, + "line": 3460 }, { "lang": "bash", "meta": null, "sha256": "fdb563355cb89d0b6f534e825e70973c85326879a7d4f0adaee447ed78db5260", - "bytes": null, - "line": null + "bytes": 46, + "line": 3493 }, { "lang": "bash", "meta": null, "sha256": "8409df5d28808a04cbea45c4f0162a7a283a0d4eee0fc3391d82a8663121a495", - "bytes": null, - "line": null + "bytes": 33, + "line": 3523 }, { "lang": "bash", "meta": null, "sha256": "c3189f21b856e8c158f2a39d3260d7c0ac93ba2c0c73494c7e1374d45a51346f", - "bytes": null, - "line": null + "bytes": 30, + "line": 3543 }, { "lang": "bash", "meta": null, "sha256": "066839a4599d90ccd88f845122e61c608a8ea120e9f1476857f0a2eb8c723de7", - "bytes": null, - "line": null + "bytes": 50, + "line": 3566 }, { "lang": "bash", "meta": null, "sha256": "209da9ab7f502fbcaec3297113212d496eca57b124e273dc8080efa6c4e0de71", - "bytes": null, - "line": null + "bytes": 46, + "line": 3597 }, { "lang": "bash", "meta": null, "sha256": "c01ee6bd733ccd61abdb244baa88a17758166a1eacaa4456d3a8bbe56e6ff00f", - "bytes": null, - "line": null + "bytes": 15, + "line": 3642 }, { "lang": "bash", "meta": null, "sha256": "e2c2a5ffcc518a49f6cc038c691b068769101b4bf94905eb0a472299ab563620", - "bytes": null, - "line": null + "bytes": 39, + "line": 3656 }, { "lang": "bash", "meta": null, "sha256": "ccaaa978abfa31e70784eda567c50bec64a5cf485a205fa545e71f46c1821f3a", - "bytes": null, - "line": null + "bytes": 40, + "line": 3677 }, { "lang": "bash", "meta": null, "sha256": "7e6eac72f3011e3714d4eeb9914601dbe344ff899504c1324ff55c2b6eed60d5", - "bytes": null, - "line": null + "bytes": 53, + "line": 3702 }, { "lang": "bash", "meta": null, "sha256": "d557d9bb45aa7b4ee10d2d502d92710aafe9fcbc7b12d0a219c3eff49863e1f7", - "bytes": null, - "line": null + "bytes": 53, + "line": 3733 }, { "lang": "bash", "meta": null, "sha256": "6f4dc8213285da7c740b7f183f519a14d88e853125347cf4b3585c153f3d6c95", - "bytes": null, - "line": null + "bytes": 62, + "line": 3763 }, { "lang": "bash", "meta": null, "sha256": "c7934b9e19cf7a0ff636ecdb465b1a6727ad23d36b695eb0b08783efa08698d3", - "bytes": null, - "line": null + "bytes": 50, + "line": 3793 }, { "lang": "bash", "meta": null, "sha256": "c6c30823efb18475aef576f5eac37ab1a319e1de7b2462fccb62b249396e3d9f", - "bytes": null, - "line": null + "bytes": 52, + "line": 3815 }, { "lang": "bash", "meta": null, "sha256": "8567533e04160a832142ff673958ff2456ea163f86df91685ba5da691604a882", - "bytes": null, - "line": null + "bytes": 56, + "line": 3842 }, { "lang": "bash", "meta": null, "sha256": "f8809dfed9678563c959c376cf67dcc022eeee8e5e4384e8aa46ff6470838960", - "bytes": null, - "line": null + "bytes": 59, + "line": 3862 }, { "lang": "bash", "meta": null, "sha256": "c4202b9b75440588bb6562fce248037a4425448373f72f9ee3ad9ade135fab34", - "bytes": null, - "line": null + "bytes": 48, + "line": 3883 }, { "lang": "bash", "meta": null, "sha256": "711c4598e2329b7c5079f9cc2569196c4af7ebfa267e38ab904ff60e579e5169", - "bytes": null, - "line": null + "bytes": 48, + "line": 3908 }, { "lang": "bash", "meta": null, "sha256": "ef9a879b046809272052e1804f9ebe98b60cd0cdf476251b599ca44bb3ae1b11", - "bytes": null, - "line": null + "bytes": 63, + "line": 3934 }, { "lang": "bash", "meta": null, "sha256": "b07d1aa721f8a38cfc8e79bc68497e76240430fcc1fec0818294974f67755a1d", - "bytes": null, - "line": null + "bytes": 63, + "line": 3964 }, { "lang": "bash", "meta": null, "sha256": "48441bc81c5893bfd1567acf2a401eb191e4b7bef2862b8c29aa158a517adb82", "bytes": 93, - "line": 3988 + "line": 4000 }, { "lang": "bash", "meta": null, "sha256": "74d9b766eac6b565c6287e10884f95c2f74ecd8dd4947b488cda0ff1c1f16597", "bytes": 80, - "line": 4020 + "line": 4032 }, { "lang": "bash", "meta": null, "sha256": "4b74edf3d708c0fafd7bb8ba6a827644f65d6cd755a4cf1822b5308a45eb76c3", "bytes": 106, - "line": 4054 + "line": 4066 }, { "lang": "bash", "meta": null, "sha256": "229448ff3c47ffdfdd720fb88b38edcf58f51d063f7b7836d4f4fdc478f99b5c", "bytes": 69, - "line": 4088 + "line": 4100 }, { "lang": "bash", "meta": null, "sha256": "7863a0cbd4e2cb3715358cca55047765a210f9a42a3dd171e42f574185fe0ab9", "bytes": 73, - "line": 4120 + "line": 4132 }, { "lang": "bash", "meta": null, "sha256": "412f8bcf9151f7075294ba9e7cfcbb86581e91dbd1b217775e9fb6958df71a2e", "bytes": 72, - "line": 4153 + "line": 4165 }, { "lang": "bash", "meta": null, "sha256": "483447579062e117424ae72463645f166fea91b8a87fe6efcf48a24a3a8145f8", "bytes": 49, - "line": 4188 + "line": 4200 }, { "lang": "bash", "meta": null, "sha256": "e57bccfdde20412a95b0aeb601448b791eb566d28af3b17bbc16d1e62bbcfb4c", "bytes": 60, - "line": 4216 + "line": 4228 }, { "lang": "bash", "meta": null, "sha256": "34378bac1290005ec4e6a46fc968c097307dc2dd27dffd2ed275b885dcc8502b", "bytes": 57, - "line": 4247 + "line": 4259 }, { "lang": "bash", "meta": null, "sha256": "91c6910aa33b8d3c65dccd59a480a9d986eadf89d8d4974ade0c8cb47c7ac821", "bytes": 47, - "line": 4277 + "line": 4289 }, { "lang": "bash", "meta": null, "sha256": "303d009467865566416478bccdf9e95291862e222144f55ca61bae5d446fa9d5", "bytes": 50, - "line": 4301 + "line": 4313 }, { "lang": "bash", "meta": null, "sha256": "7deac995bc8ac114dae3500bb4792b73fdb39f5b666f4a2886428320e1ffbd00", "bytes": 60, - "line": 4325 + "line": 4337 }, { "lang": "bash", "meta": null, "sha256": "6231d67b8fca5d05ef85468209b86d04c0c016014f46f2f444da5321bd655941", - "bytes": null, - "line": null + "bytes": 46, + "line": 4372 }, { "lang": "bash", "meta": null, "sha256": "30a1944929f1b7cdc8d8866735022851ef133f4160fc018f736201f1531e7907", - "bytes": null, - "line": null + "bytes": 58, + "line": 4394 }, { "lang": "bash", "meta": null, "sha256": "6ce2fc39c89d2789f343b2590c28ff069d4bcf685241cdfd645d579b886625a5", - "bytes": null, - "line": null + "bytes": 44, + "line": 4424 }, { "lang": "bash", "meta": null, "sha256": "edbc6c008ae5039761ca84f5af6c63c15aab125fe0bc7b890362159598318cf6", - "bytes": null, - "line": null + "bytes": 65, + "line": 4450 }, { "lang": "bash", "meta": null, "sha256": "cdeb9be48212517be6994c625844b9761842bd3822c74e7d86970a022811a07d", - "bytes": null, - "line": null + "bytes": 61, + "line": 4485 }, { "lang": "bash", "meta": null, "sha256": "7f3233f2465f84ad271fbe67411e1651f83d9dd39e15128c477276a103443baa", - "bytes": null, - "line": null + "bytes": 61, + "line": 4517 }, { "lang": "bash", "meta": null, "sha256": "af80c56179adf35f94c4c1c3eb3676cf2ca68b61af3c1b43a9ac020c4205f4a2", - "bytes": null, - "line": null + "bytes": 61, + "line": 4550 }, { "lang": "bash", "meta": null, "sha256": "48fced6ea852f10aa3620044ca010c0bf50acfb3b743012f836a98be0d7cdf08", - "bytes": null, - "line": null + "bytes": 58, + "line": 4581 }, { "lang": "bash", "meta": null, "sha256": "6d9a078ab511579f7f7234fa28d72ae92f7df84c9f9957aff14951a2fe1b08f3", - "bytes": null, - "line": null + "bytes": 46, + "line": 4611 }, { "lang": "bash", "meta": null, "sha256": "88b2622d7dc41ea41543f26e4dd1b513c271cb0e0452b937033088f7ae80484f", - "bytes": null, - "line": null + "bytes": 46, + "line": 4636 }, { "lang": "bash", "meta": null, "sha256": "757036af4cd38ae573a0589ddcd08b179542a30bfa802f88ff3debb198baae47", - "bytes": null, - "line": null + "bytes": 62, + "line": 4684 }, { "lang": "bash", "meta": null, "sha256": "7311b5a978eda8140f8e314d709e565a535c76064199595eb139c015f16312d5", - "bytes": null, - "line": null + "bytes": 42, + "line": 4714 }, { "lang": "bash", "meta": null, "sha256": "c3410310e5eccb2e0a7440b8d3cbfc2508270890a08ec5a85c5b8cc5c5a3b8b8", - "bytes": null, - "line": null + "bytes": 45, + "line": 4734 }, { "lang": "bash", "meta": null, "sha256": "08f1a585205b784ac0527c4ffb9aae95a4d8bd1702abddb87d1aa25415de45d2", - "bytes": null, - "line": null + "bytes": 38, + "line": 4755 }, { "lang": "bash", "meta": null, "sha256": "e4502c5ec3c9643358cf434f3271f7f39ee39f899661c58e7af68b98f42cbcb1", - "bytes": null, - "line": null + "bytes": 60, + "line": 4775 }, { "lang": "bash", "meta": null, "sha256": "59e8699f41a3f06be75f1eb4addb041b762d100d6e15f61788e729a8a277f55f", - "bytes": null, - "line": null + "bytes": 63, + "line": 4805 }, { "lang": "bash", "meta": null, "sha256": "9a525f2d35624ea70a558a4081c20c98418fb371cce3ac2d70cb01462271f1c6", - "bytes": null, - "line": null + "bytes": 40, + "line": 4836 }, { "lang": "bash", "meta": null, "sha256": "5db8d4c149bb0b8378ac584947f1a8d037aa2375312e098338ee1566030988e4", - "bytes": null, - "line": null + "bytes": 51, + "line": 4862 }, { "lang": "bash", "meta": null, "sha256": "cba02b44f48f44f069fb55f48ec4e680a49b71ab99d8e7013ff4113236cd6e19", - "bytes": null, - "line": null + "bytes": 51, + "line": 4893 }, { "lang": "bash", "meta": null, "sha256": "1825feb4954c2f39280e98a8ab8f8784e097c9823d04cbccf616c28f24eeee4b", - "bytes": null, - "line": null + "bytes": 43, + "line": 4924 }, { "lang": "bash", "meta": null, "sha256": "0bd4be17187ea4870dfddcf74c03492e4ff3e4eb734d8e38fc710a0afd70e771", - "bytes": null, - "line": null + "bytes": 41, + "line": 4950 }, { "lang": "bash", "meta": null, "sha256": "e26b81a721ffd90b20b61be8168187fc20333274f6c3e537eb6cc44f87397f8b", - "bytes": null, - "line": null + "bytes": 40, + "line": 4974 }, { "lang": "bash", "meta": null, "sha256": "a85bb64841a5626286099eb6175af5f8d0b0c8f19d71275c41ba144d5ce6d75b", - "bytes": null, - "line": null + "bytes": 32, + "line": 5003 }, { "lang": "bash", "meta": null, "sha256": "c8500badf466ac4cddb64017931e69aedba037eb5c44d0be411f3e2368254f87", - "bytes": null, - "line": null + "bytes": 38, + "line": 5026 }, { "lang": "bash", "meta": null, "sha256": "c5da7d1cca60bf076fb11e3a830b1c639ae02b8b2413e4956b12b54d4af7869d", - "bytes": null, - "line": null + "bytes": 43, + "line": 5058 }, { "lang": "bash", "meta": null, "sha256": "ee42a8df21f3cb29767908892e907b58edc31fccac8414e646690b238373feac", - "bytes": null, - "line": null + "bytes": 49, + "line": 5080 }, { "lang": "bash", "meta": null, "sha256": "3aa75d103d8d87811ca0f13f238ef5bfc84debf02826b8883eb0a09b372b7230", - "bytes": null, - "line": null + "bytes": 44, + "line": 5103 }, { "lang": "bash", "meta": null, "sha256": "c97bf15cbec26edcc86e8e3a908361b4c12a7d4b5578d5ea685d4fc68993c3f9", - "bytes": null, - "line": null + "bytes": 55, + "line": 5129 }, { "lang": "bash", "meta": null, "sha256": "971979fe121168021fc32881c5e8807f271cbaee608d70cf22b709662e0aae21", - "bytes": null, - "line": null + "bytes": 38, + "line": 5161 }, { "lang": "bash", "meta": null, "sha256": "76f320882518b53d2a6055f48c06b0deba00efa8baa1c1932ec6f1c598868a82", - "bytes": null, - "line": null + "bytes": 48, + "line": 5189 }, { "lang": "bash", "meta": null, "sha256": "1c902a61277e58e20d330fd4f7510a922639122f3e26126aeff5a404579d210d", - "bytes": null, - "line": null + "bytes": 45, + "line": 5220 }, { "lang": "bash", "meta": null, "sha256": "3e09d80993bd2231d73817167d0a3e7d022d9bb5fadbf1563a854531a3c22ced", - "bytes": null, - "line": null + "bytes": 36, + "line": 5250 }, { "lang": "bash", "meta": null, "sha256": "39050b42d7a1e9da84fac3fa817aa0635c47c28f32bceabcaf8811283ad7d7ce", - "bytes": null, - "line": null + "bytes": 48, + "line": 5274 }, { "lang": "bash", "meta": null, "sha256": "a4d3e32ee5d44b474b2fe040b4be5d32c0ad725d1b3c3e4342dc2ca08fa0a157", - "bytes": null, - "line": null + "bytes": 30, + "line": 5316 }, { "lang": "bash", "meta": null, "sha256": "37f58f218a36b8141bd5c32fb2774d731631774d332ce2fe9f7a3af158f122c1", - "bytes": null, - "line": null + "bytes": 42, + "line": 5342 }, { "lang": "bash", "meta": null, "sha256": "992f83d520658780ee956610f7965ecaad8d3c782b452d78d619edccd3afa26f", - "bytes": null, - "line": null + "bytes": 29, + "line": 5372 }, { "lang": "bash", "meta": null, "sha256": "594f0358c607649151209b234a12f44d7a125fa9150668fbf46ad475c36e52c9", - "bytes": null, - "line": null + "bytes": 28, + "line": 5392 }, { "lang": "bash", "meta": null, "sha256": "1f2babf217eecbcd3edee20e939434b8b177c454ae3edad1ed0a79b24bf0929f", - "bytes": null, - "line": null + "bytes": 42, + "line": 5415 }, { "lang": "bash", "meta": null, "sha256": "d0f3737b421a98903f809a0b9e6dea5cd3bd96377b7dcc30fc5239e3aecf311d", - "bytes": null, - "line": null + "bytes": 28, + "line": 5457 }, { "lang": "bash", "meta": null, "sha256": "aa98bb7f2995f97bb02887ae3591ff0609686e634f9ad60068fbe12f38a4a026", - "bytes": null, - "line": null + "bytes": 35, + "line": 5490 }, { "lang": "bash", "meta": null, "sha256": "e421d326ab72354b8ec1d5711570d31868223c50da978b51961f9896acae5f35", - "bytes": null, - "line": null + "bytes": 26, + "line": 5521 }, { "lang": "bash", "meta": null, "sha256": "65c4b3a60ee39d43b253afd6818ed08dd93a5297f82b4648e4a3d5b0002731e4", - "bytes": null, - "line": null + "bytes": 32, + "line": 5545 }, { "lang": "bash", "meta": null, "sha256": "e2f60ffbb1bae7635a1e9ba79c228b19464a582144e1be50bfaba8d2c2db30c8", - "bytes": null, - "line": null + "bytes": 27, + "line": 5587 }, { "lang": "bash", "meta": null, "sha256": "afa0b971e60daad0dddc74b93f44fac1f51be91d47626ed4942b465fc6eba770", - "bytes": null, - "line": null + "bytes": 28, + "line": 5609 }, { "lang": "bash", "meta": null, "sha256": "4a0236d60519b55978f69d4eaa3ac6b8de2b354a7e63a14255abb64862d0456e", - "bytes": null, - "line": null + "bytes": 27, + "line": 5639 }, { "lang": "bash", "meta": null, "sha256": "ebd45772f099ce26c6315895068a1703d8e757f43daf35f6d3618c408319b37b", - "bytes": null, - "line": null + "bytes": 37, + "line": 5663 }, { "lang": "bash", "meta": null, "sha256": "e6e8ba88a5ede0c440346b124c101ccd53241c492f6dc28c3453fd23b8917cb3", - "bytes": null, - "line": null + "bytes": 24, + "line": 5693 }, { "lang": "bash", "meta": null, "sha256": "c19501e59583b680d6ce36b1133f3850ef1c96d05e7e5985b6cb8b1c5e19ff46", - "bytes": null, - "line": null + "bytes": 45, + "line": 5713 }, { "lang": "bash", "meta": null, "sha256": "4b84b742cd46fa81f9dc42d64c66c4b801b9fc6c381c1fda6690647d082639e3", - "bytes": null, - "line": null + "bytes": 43, + "line": 5743 }, { "lang": "bash", "meta": null, "sha256": "b9eefbf636684f9388fb43e708ad6dd2326b629f85a95e039f69e13651993c41", - "bytes": null, - "line": null + "bytes": 45, + "line": 5777 }, { "lang": "bash", "meta": null, "sha256": "bf2cc4f904e1d46c6ad5fb9c85a1a77b75062b61997add02c5c8d5b4cdcda262", - "bytes": null, - "line": null + "bytes": 25, + "line": 5808 }, { "lang": "bash", "meta": null, "sha256": "eef07048b814eb3b00f997c8b0907d1e21817abad072f7e8502087fdbe9a0188", - "bytes": null, - "line": null + "bytes": 37, + "line": 5831 }, { "lang": "bash", "meta": null, "sha256": "f35ce94c4d5abe5378ba2b6095a786d9989540caefe3b2248b43ec375b69d212", - "bytes": null, - "line": null + "bytes": 45, + "line": 5869 }, { "lang": "bash", "meta": null, "sha256": "f8a9f16a31241f7bed8f14a44cbc6ba4c13707b0bbc71f95abaded420f98cae8", - "bytes": null, - "line": null + "bytes": 45, + "line": 5901 }, { "lang": "bash", "meta": null, "sha256": "6eee9d069d9053a29e2bd61c5a85821fead20cc3af306f55e3597f9931588d32", - "bytes": null, - "line": null + "bytes": 45, + "line": 5932 }, { "lang": "bash", "meta": null, "sha256": "b0485a54f218265aaf8ef27b26af37e80603744b4cd13af804b9460ded6c769c", - "bytes": null, - "line": null + "bytes": 44, + "line": 5963 }, { "lang": "bash", "meta": null, "sha256": "eff43eafc0b5c9829de1e71e899e82b6db9bf5a3ba4da138fe2608ecf2ad96ea", - "bytes": null, - "line": null + "bytes": 44, + "line": 5998 }, { "lang": "bash", "meta": null, "sha256": "598ec0411dcfb12246c2ad819aeb9083cfd0dcf6a894aec2a0e908d82226e85f", - "bytes": null, - "line": null + "bytes": 32, + "line": 6029 }, { "lang": "bash", "meta": null, "sha256": "2869d4bb0b7552d346eca2e8bfe110dccdb3a13073c0e5a531ed34e8d111459f", - "bytes": null, - "line": null + "bytes": 44, + "line": 6049 }, { "lang": "bash", "meta": null, "sha256": "faa95847578604b50b3c020d50d94589351f7b1ec36e28cac7fe2140de6c4549", - "bytes": null, - "line": null + "bytes": 33, + "line": 6092 }, { "lang": "bash", "meta": null, "sha256": "25e24485a99181672176131b6ac2152347841a1a567430fbb98a553a929770f3", - "bytes": null, - "line": null + "bytes": 47, + "line": 6114 }, { "lang": "bash", "meta": null, "sha256": "9720d5ef881383f1c6da7a8a3a008f3afd615af99678d1bb81118511ff84dfcc", - "bytes": null, - "line": null + "bytes": 42, + "line": 6144 }, { "lang": "bash", "meta": null, "sha256": "3b9ac116c754c7e2bcf7f077f6061399dbfff4238408c4ef0d048fb442c3baf8", - "bytes": null, - "line": null + "bytes": 50, + "line": 6177 }, { "lang": "bash", "meta": null, "sha256": "3487041dfbdb03a03ebed0e308da4117442785d83c8158248fbad5df46f35fb2", - "bytes": null, - "line": null + "bytes": 48, + "line": 6210 }, { "lang": "bash", "meta": null, "sha256": "25f7e3715a24bd9657f90a5d9bc466cfe7b121a2660596c62c08a6ae0c4834f2", - "bytes": null, - "line": null + "bytes": 47, + "line": 6243 }, { "lang": "bash", "meta": null, "sha256": "8a310ebdd720a3d0e2fffb7db415873a53befe47ea4d638fca4ecd59ac27595e", - "bytes": null, - "line": null + "bytes": 40, + "line": 6275 }, { "lang": "bash", "meta": null, "sha256": "d3dba384fd5ce87e831b8454186e60d5e1cd6ae404b6324009adf4a961d85cfe", - "bytes": null, - "line": null + "bytes": 41, + "line": 6308 }, { "lang": "bash", "meta": null, "sha256": "4bec76dae83cf450410fd42df2a56ef2b20e69143f9631539a58f363631cb986", - "bytes": null, - "line": null + "bytes": 41, + "line": 6343 }, { "lang": "bash", "meta": null, "sha256": "ad373ebb46a54ef7fead24880468d70c4a415003db879817f5d78e717994573c", - "bytes": null, - "line": null + "bytes": 50, + "line": 6373 }, { "lang": "bash", "meta": null, "sha256": "9f85f14e7c0f00e23c82b9a097ab414df558c764e4171f8bdd6771386b02677c", - "bytes": null, - "line": null + "bytes": 42, + "line": 6395 }, { "lang": "bash", "meta": null, "sha256": "856a70bda3a296ed9e7d3de557191906106fd51da9fab3d2372bd4a3d0115ae1", - "bytes": null, - "line": null + "bytes": 48, + "line": 6429 }, { "lang": "bash", "meta": null, "sha256": "12b44782510d874df9900581914d66e8e8a0708ea6e1f8cab799c1187d4778f2", - "bytes": null, - "line": null + "bytes": 50, + "line": 6462 }, { "lang": "bash", "meta": null, "sha256": "908dcdcee6aa38f9ed48e63e5a70bba22dc7aaa603dfb8c62f0999259a1b9eb1", - "bytes": null, - "line": null + "bytes": 61, + "line": 6495 }, { "lang": "bash", "meta": null, "sha256": "55ea841db41ce49eb504636a54c29187e16b403b686059375abfa8aa51d01f7d", - "bytes": null, - "line": null + "bytes": 48, + "line": 6526 }, { "lang": "bash", "meta": null, "sha256": "c414854798bccb75c4b223fbed069ed445872158dbfb2b23093e140827d1e838", - "bytes": null, - "line": null + "bytes": 48, + "line": 6561 }, { "lang": "bash", "meta": null, "sha256": "9f45f6e6567f09f49ec40484721420a71a15d42f7ab92d3a3cfa1124ab8419fd", - "bytes": null, - "line": null + "bytes": 36, + "line": 6582 }, { "lang": "bash", "meta": null, "sha256": "862b4e873ebd70c303716275ebf30b3822c9c9e7f261a78e27b18f9585d798b0", - "bytes": null, - "line": null + "bytes": 46, + "line": 6602 }, { "lang": "bash", "meta": null, "sha256": "bb65d63f55930b4ea7b86e0475159b98a53e0525015508285c90425f28d53a55", - "bytes": null, - "line": null + "bytes": 45, + "line": 6623 }, { "lang": "bash", "meta": null, "sha256": "18d5a60f518896e595f00666ed45fdd624c789287809e18798e0d9f5610d48c8", - "bytes": null, - "line": null + "bytes": 43, + "line": 6653 }, { "lang": "bash", "meta": null, "sha256": "e44d003a6ba11690de0cc469320be892fae3b09033939a46724fccfb0aac4ab0", - "bytes": null, - "line": null + "bytes": 48, + "line": 6674 }, { "lang": "bash", "meta": null, "sha256": "bee16895751b8f386d2188e18ae402e521187d2bb7da9af709c2432ba9634209", - "bytes": null, - "line": null + "bytes": 46, + "line": 6697 }, { "lang": "bash", "meta": null, "sha256": "d3dede19db079b39e165a036fac3dd3376044ada7849f3ec70220ae188ac28e5", - "bytes": null, - "line": null + "bytes": 33, + "line": 6727 }, { "lang": "bash", "meta": null, "sha256": "0ac8381a83158432224d7b6bead7492d25f36e68eadc15c18e9bf84eddef77d0", - "bytes": null, - "line": null + "bytes": 42, + "line": 6749 }, { "lang": "bash", "meta": null, "sha256": "57308ec7b05d6b120ff6841edb51d8159d84444d6eaf36b3bccb9d1b2bb385e6", - "bytes": null, - "line": null + "bytes": 27, + "line": 6783 }, { "lang": "bash", "meta": null, "sha256": "90b5b274482044f6d036867177353233bf58d00f5dd345f76c0866a23be10343", - "bytes": null, - "line": null + "bytes": 32, + "line": 6806 }, { "lang": "bash", "meta": null, "sha256": "0636f27b84a87525a97146f65475905163efcae563920102110bdaef39d0cbe2", - "bytes": null, - "line": null + "bytes": 42, + "line": 6828 }, { "lang": "bash", "meta": null, "sha256": "36c08c95e7a531c73736416e90aea14eb199ad1746f90a4ecc78db9c037fd03e", - "bytes": null, - "line": null + "bytes": 33, + "line": 6859 }, { "lang": "bash", "meta": null, "sha256": "ab978cbdc23f7d851799251cfe01863187b2cd628b05c3c750ad1db2d26fb5fc", - "bytes": null, - "line": null + "bytes": 44, + "line": 6884 }, { "lang": "bash", "meta": null, "sha256": "2333fb674a47979dc56cf4e10c852516a7d179ddc234cc184130c6e82ae5811b", - "bytes": null, - "line": null + "bytes": 33, + "line": 6907 }, { "lang": "bash", "meta": null, "sha256": "d301cb24422359056dad68402e9f54a8ed15e21c0f183fb4c8eb937738f155dc", - "bytes": null, - "line": null + "bytes": 43, + "line": 6927 }, { "lang": "bash", "meta": null, "sha256": "bd3c423a63ecf70ee28e0c4aa2fe7b9e6078179ec2577ba80004cdfaf527843a", - "bytes": null, - "line": null + "bytes": 52, + "line": 6960 }, { "lang": "bash", "meta": null, "sha256": "a064ea603a971a2a3582988297d7293e6e0c6cabedfad714f2af97c0ff1884e7", - "bytes": null, - "line": null + "bytes": 39, + "line": 6991 }, { "lang": "bash", "meta": null, "sha256": "20d848044f1a1ac09fe6621d3e3f7fe7e2a6271c08e23f5eaea2c4c4b3f21c9d", - "bytes": null, - "line": null + "bytes": 31, + "line": 7012 }, { "lang": "bash", "meta": null, "sha256": "b19fe44255306f492be72ced4183894fe6ab47c5e87ab02cf909c5a6e89ab964", - "bytes": null, - "line": null + "bytes": 52, + "line": 7032 }, { "lang": "bash", "meta": null, "sha256": "0a8251333833585605881b98f9d121fa0e5669e58ba11cb583f69a333cea2ad6", - "bytes": null, - "line": null + "bytes": 37, + "line": 7069 }, { "lang": "bash", "meta": null, "sha256": "3f1de42768c4151cd364eb2534408179e93ca92dda918a493c9d05d4c8f03209", - "bytes": null, - "line": null + "bytes": 53, + "line": 7099 }, { "lang": "bash", "meta": null, "sha256": "60b57e472e506c0d6430f325c0e05c6cdfe9a62b4051a9f371929799ec7cfdef", - "bytes": null, - "line": null + "bytes": 24, + "line": 7121 }, { "lang": "bash", "meta": null, "sha256": "aeea8ffe933fcbb749950596d5c83192d1c42e2dac8f9532625c97afd7fe18a2", - "bytes": null, - "line": null + "bytes": 25, + "line": 7141 }, { "lang": "bash", "meta": null, "sha256": "3010a87af250eea55a7de4dcdda1fdcef515e73b7d2f5977d955f9d66ca4e130", - "bytes": null, - "line": null + "bytes": 25, + "line": 7166 }, { "lang": "bash", "meta": null, "sha256": "4cff190ec4b1d449d089493b45b00f986e3d17e563bca1816769ee3a1cfea2f2", - "bytes": null, - "line": null + "bytes": 28, + "line": 7188 }, { "lang": "bash", "meta": null, "sha256": "b7a3a8b8a114216dbdb506005496e5510feb227b0b6e39ba2b5145743e852577", - "bytes": null, - "line": null + "bytes": 37, + "line": 7208 }, { "lang": "bash", "meta": null, "sha256": "36e0677e842c003940707713b5334c6f2cabdfe6548790bc0c1b8546b0f820b6", - "bytes": null, - "line": null + "bytes": 32, + "line": 7240 }, { "lang": "bash", "meta": null, "sha256": "a9a07815e06f5bab4b2d1fc80a606227a8a617c105c56680c4bef68a520970c1", - "bytes": null, - "line": null + "bytes": 37, + "line": 7261 }, { "lang": "bash", "meta": null, "sha256": "79420742f040a499740d4b465a8e8fdbc628c275fbd2880182637c5917b67b9e", - "bytes": null, - "line": null + "bytes": 34, + "line": 7298 }, { "lang": "bash", "meta": null, "sha256": "a6b4fb5e2728894616f9d11df544879c4786b80458d5905a67ffc2224022ec1e", - "bytes": null, - "line": null + "bytes": 30, + "line": 7337 }, { "lang": "bash", "meta": null, "sha256": "1aa431dc5b8d1fdc3d54a77c56f15a1b9ac5896e343818d3d0ad2edbabc541db", - "bytes": null, - "line": null + "bytes": 23, + "line": 7368 }, { "lang": "bash", "meta": null, "sha256": "262692daffbb55d5cbbf1717fb2c8ff08bc009514bae8ff83ee756d4caba08d1", - "bytes": null, - "line": null + "bytes": 36, + "line": 7394 }, { "lang": "bash", "meta": null, "sha256": "1e9b19a7ea2fdbf0902ed74b48cecc710d7fa2272d4dbed9172af1ae0258310d", - "bytes": null, - "line": null + "bytes": 22, + "line": 7426 }, { "lang": "bash", "meta": null, "sha256": "734b96827127375d652bc125b1c9a243946cf5f8c251b43a7097656fcc2ce544", - "bytes": null, - "line": null + "bytes": 24, + "line": 7446 }, { "lang": "bash", "meta": null, "sha256": "c6544463a5be88fa1bb81e80633a6e4bf70e99d424d408c75930046e74c1dc5f", - "bytes": null, - "line": null + "bytes": 41, + "line": 7477 }, { "lang": "bash", "meta": null, - "sha256": "2ba0e68b06d7be939be3058e281cd495a16a41611ae4dadb91c97dea4b95fe29", - "bytes": null, - "line": null + "sha256": "2ba0e68b06d7be939be3058e281cd495a16a41611ae4dadb91c97dea4b95fe29", + "bytes": 52, + "line": 7503 }, { "lang": "bash", "meta": null, "sha256": "f0f241b97b09236a5fcdc9527cff2f76cf382270caf4315aa8ae11f8ca919932", - "bytes": null, - "line": null + "bytes": 58, + "line": 7533 }, { "lang": "bash", "meta": null, "sha256": "fde5893586a0c2c7cbd2ab3976d7d9ef35e861b56eab07191919891e09528bd4", - "bytes": null, - "line": null + "bytes": 46, + "line": 7566 }, { "lang": "bash", "meta": null, "sha256": "3d28258fd09b2c94b7cb24cb37035ce71d3777b58b2270998781761f8957081e", - "bytes": null, - "line": null + "bytes": 71, + "line": 7588 }, { "lang": "bash", "meta": null, "sha256": "45cdb94cf834d1950ab049a6a65c398b4917312897fdcaa3f25fa0081e707912", - "bytes": null, - "line": null + "bytes": 39, + "line": 7619 }, { "lang": "bash", "meta": null, "sha256": "ac7f120b7e8c39cb3de7b0936dfd2f6d8f38ece480b0523518883cef7b5b643c", - "bytes": null, - "line": null + "bytes": 39, + "line": 7639 }, { "lang": "bash", "meta": null, "sha256": "7994ad60b43332fb5bc583bf1ea5599fa2f659cd8ad811105837cf9e87fa28ed", - "bytes": null, - "line": null + "bytes": 52, + "line": 7661 }, { "lang": "bash", "meta": null, "sha256": "5ed096b4dcf0efad18c54d322d528b7bb0e80336d061ee7eaa5d39d3bd505a4d", - "bytes": null, - "line": null + "bytes": 62, + "line": 7702 }, { "lang": "bash", "meta": null, "sha256": "daf3ccbc5a308bc4c62d1a761e01fac3d40ff67cc256c4c9624d0cd00a0072c4", - "bytes": null, - "line": null + "bytes": 53, + "line": 7735 }, { "lang": "text", "meta": null, - "sha256": "48dd143dafc65a4f4c1cd5bfa0edc1ece98bec432d3e8d35b561c73cd3e3bfc2", - "bytes": 1109, - "line": 7754 + "sha256": "7ccb089303b6156668b4dee2b4783360c510107743f3ff3eae8a506720fcada9", + "bytes": 2256, + "line": 7766 }, { "lang": "bash", "meta": null, "sha256": "48ecf1013a285c0de3e23936d53a850d85af0564a7e089de2eba1ac7f8881a44", - "bytes": null, - "line": null + "bytes": 53, + "line": 7812 }, { "lang": "bash", "meta": null, "sha256": "653a412a8eeaffac8afbbbb2533375f02df67fe7ef882ca53fc7ca2755d0bcec", - "bytes": null, - "line": null + "bytes": 43, + "line": 7845 }, { "lang": "bash", "meta": null, "sha256": "bfb90a10455a59ef26068d176221816b9c374c4001d386ffdbb0140c4cfe40ca", - "bytes": null, - "line": null + "bytes": 40, + "line": 7875 }, { "lang": "bash", "meta": null, "sha256": "11658c406271a4f22a346aab51f697bc949342fbaaaabb2a786de824561bc4c3", - "bytes": null, - "line": null + "bytes": 35, + "line": 7910 }, { "lang": "bash", "meta": null, "sha256": "d683e8c6e5a1d063ea9f6c74fd9020d48aede0d5af7031f6f48bd5a173ad2d3d", - "bytes": null, - "line": null + "bytes": 33, + "line": 7935 }, { "lang": "bash", "meta": null, "sha256": "96abc89ee23cb4a7e2fc3caca2afbd2dd57d2734ca9e73816c412a71c5c5eb9d", - "bytes": null, - "line": null + "bytes": 43, + "line": 7962 }, { "lang": "bash", "meta": null, "sha256": "d63bf37625acc32ec1ee6e59a56f57469b9cb4dab03e23067a54d2f7d8abd3a3", - "bytes": null, - "line": null + "bytes": 41, + "line": 7994 }, { "lang": "bash", "meta": null, "sha256": "eb79c561c688b305a39f834bb39d74f65095db957e337d8e6081bbc00545bb08", - "bytes": null, - "line": null + "bytes": 53, + "line": 8027 }, { "lang": "bash", "meta": null, "sha256": "f30977b7b952e6a369b72b828256fac3f9ede78ce6e7c45560a8d09989bd4db5", - "bytes": null, - "line": null + "bytes": 49, + "line": 8058 }, { "lang": "bash", "meta": null, "sha256": "7d00d2a238c8794c5479e28ef14e6e104bcaff1aaaef70a094a2a51c55b6420c", - "bytes": null, - "line": null + "bytes": 50, + "line": 8079 }, { "lang": "bash", "meta": null, "sha256": "f34921d79bc4b608cb3e3c3f882729808afe1d8cf95ca45c63cbdf00ab494a3e", - "bytes": null, - "line": null + "bytes": 62, + "line": 8110 }, { "lang": "bash", "meta": null, "sha256": "ebfb60766394d803a01326b040ac37c5f122134555f1b968aeb6a79b10d74fc7", - "bytes": null, - "line": null + "bytes": 30, + "line": 8142 }, { "lang": "bash", "meta": null, "sha256": "432348582be57741628ca2b6a762c385ed57bbbfd4e4794b914409b7a89db582", - "bytes": null, - "line": null + "bytes": 35, + "line": 8166 }, { "lang": "bash", "meta": null, "sha256": "25d75743717b8e1c96f6b78e334e3e3cbc6dac5e395068308a4e358e06a0bac6", - "bytes": null, - "line": null + "bytes": 45, + "line": 8188 }, { "lang": "bash", "meta": null, "sha256": "2fc4fd97c2a62f635b42d646e481b18b0402ec0d051e7532988c026d838f0534", - "bytes": null, - "line": null + "bytes": 36, + "line": 8219 }, { "lang": "bash", "meta": null, "sha256": "3da31453cf86b97920f8d013f00122dee830af847c064e30ed3e158bd8f642cb", - "bytes": null, - "line": null + "bytes": 47, + "line": 8244 }, { "lang": "bash", "meta": null, "sha256": "d4de05e9142f532574133568e3fe2965c7fd82338e5b54ba0d8ae5713639eaca", - "bytes": null, - "line": null + "bytes": 43, + "line": 8269 }, { "lang": "bash", "meta": null, "sha256": "e63db5a4bab57e3229127bb086d0c5429dfe20de83eaf5097e8943f90520b9b3", - "bytes": null, - "line": null + "bytes": 51, + "line": 8301 }, { "lang": "bash", "meta": null, "sha256": "b130d4ed01c735074275b1505e7959e6dd3ae89c6b7ac159d17ccd495bec8f38", - "bytes": null, - "line": null + "bytes": 38, + "line": 8331 }, { "lang": "bash", "meta": null, "sha256": "32709306f0caabb4378fce9efba6b9c60a3985bb3500402d9a7f9e89fe35e00e", - "bytes": null, - "line": null + "bytes": 49, + "line": 8355 }, { "lang": "bash", "meta": null, "sha256": "a09f283134986b066a49a41c5ef250ff1502ae2adbc3316baacf92712112cc2d", - "bytes": null, - "line": null + "bytes": 43, + "line": 8397 }, { "lang": "bash", "meta": null, "sha256": "d941e4f91a379820ba5d640e7ceffd42c6fdd70b5b19da9c508c259b40ce14f7", - "bytes": null, - "line": null + "bytes": 53, + "line": 8430 }, { "lang": "bash", "meta": null, "sha256": "fb10d8958f9f1b03ab76713459abf552755dae3334103a451c387c9d1c7b3605", - "bytes": null, - "line": null + "bytes": 40, + "line": 8461 }, { "lang": "bash", "meta": null, "sha256": "b5dc1e771889fb1bf5f4d81d340cfd35d3a2263c87a725341d1d5c70405eb78d", - "bytes": null, - "line": null + "bytes": 43, + "line": 8517 }, { "lang": "bash", "meta": null, "sha256": "9065c4d4de3606f4362700b64aa3f856aa75214bebafe9334d48b9ff8466a80c", - "bytes": null, - "line": null + "bytes": 38, + "line": 8551 }, { "lang": "bash", "meta": null, "sha256": "face4eea006073000b49334d0a2bea7f15f9df86cb1f606ac8fe39004c754027", - "bytes": null, - "line": null + "bytes": 30, + "line": 8571 }, { "lang": "bash", "meta": null, "sha256": "29cc30facfddd548aa5873383ac3d90a6b392cf120894fd73a735f266196540d", - "bytes": null, - "line": null + "bytes": 47, + "line": 8581 }, { "lang": "bash", "meta": null, "sha256": "d58dd2280200d928a15de43483c5c709be8aedc38087ba95cbbe2a31a39466fa", - "bytes": null, - "line": null + "bytes": 49, + "line": 8615 }, { "lang": "bash", "meta": null, "sha256": "f43f6a034552660fdb745c0ac0cfe17c1af0c7a2995fd76ab45f79ebfd116bfb", - "bytes": null, - "line": null + "bytes": 37, + "line": 8652 }, { "lang": "bash", "meta": null, "sha256": "529d96c3ff160cf6393f3f7a1f69014d8f2f9f3f3ce5733fc11c58133accb7d7", - "bytes": null, - "line": null + "bytes": 36, + "line": 8680 }, { "lang": "bash", "meta": null, "sha256": "427c626ebed3055c690ff0dbbb3a20550a2daae5ae40f5f9e005f1eb47dd733a", - "bytes": null, - "line": null + "bytes": 37, + "line": 8707 }, { "lang": "bash", "meta": null, "sha256": "e61ba28ca4eef131ee1291f39b5cb583b2a1dd4436bde33a061ce27ac8af05af", - "bytes": null, - "line": null + "bytes": 46, + "line": 8733 }, { "lang": "bash", "meta": null, "sha256": "2b6c40dcef94f6188188d6369383e982f5a6dc88654b8ab76664c189f9af8ab0", - "bytes": null, - "line": null + "bytes": 47, + "line": 8767 }, { "lang": "bash", "meta": null, "sha256": "736889b5b5a59bc4fe7965922999b5cbec295acad8313c1e486d5668c7da961e", - "bytes": null, - "line": null + "bytes": 30, + "line": 8799 }, { "lang": "bash", "meta": null, "sha256": "4d6c0bc0130fd4a83c7b2fcac6f5b4b7bc2f275c05fa6101551ac61ce1405aca", - "bytes": null, - "line": null + "bytes": 44, + "line": 8819 }, { "lang": "bash", "meta": null, "sha256": "62d28b9be74c32c4ba00fefe878c492a6a5c671cc4a500373d7f2bdba9f7ef79", - "bytes": null, - "line": null + "bytes": 54, + "line": 8839 }, { "lang": "bash", "meta": null, "sha256": "185227ff19342ab461c3e652c4158d8ece85c079b2542b9243b7c7cf0b2dac2c", - "bytes": null, - "line": null + "bytes": 34, + "line": 8869 }, { "lang": "bash", "meta": null, "sha256": "7115696baaba8ca1ecd8f7cb22f215b7a53bf13d5757bd6932267644a0377807", - "bytes": null, - "line": null + "bytes": 36, + "line": 8889 }, { "lang": "bash", "meta": null, "sha256": "10330e610f59c2fb169fcff11cb8147563efbcc109f875222ecbfaaa48c05f31", - "bytes": null, - "line": null + "bytes": 50, + "line": 8911 }, { "lang": "bash", "meta": null, "sha256": "e88ab81833a4d529271c80e2cdf0e7ff5037a60066a918a9702a28ceca73a846", - "bytes": null, - "line": null + "bytes": 30, + "line": 8948 }, { "lang": "bash", "meta": null, "sha256": "f094df6732656b52792e5e766a69079c3e8bd929326bda7284e0bcb760bedd79", - "bytes": null, - "line": null + "bytes": 28, + "line": 8978 }, { "lang": "bash", "meta": null, "sha256": "7579bd6ac197afa0afa5f62d9b412a7e265725bd507c1c63b438a60fd72ce1d0", - "bytes": null, - "line": null + "bytes": 40, + "line": 9005 }, { "lang": "bash", "meta": null, "sha256": "63aac11606dc0eeb6cc452c20c405806840960425372cf2cf7c8b4b90a7de878", - "bytes": null, - "line": null + "bytes": 62, + "line": 9025 }, { "lang": "bash", "meta": null, "sha256": "52be4758f4289e9f75875d8401cf57fda54283b2df00e413921d07303e728638", - "bytes": null, - "line": null + "bytes": 28, + "line": 9056 }, { "lang": "bash", "meta": null, "sha256": "4c51312bac2ca9ea2dba0e7cf27f06d5e99502bab35ab569064057a85514cc38", - "bytes": null, - "line": null + "bytes": 38, + "line": 9077 }, { "lang": "bash", "meta": null, "sha256": "2b26aa6f404ab19bda2d846871eb04b732f6397d1899fc28d89a29706fc0a670", - "bytes": null, - "line": null + "bytes": 34, + "line": 9103 }, { "lang": "bash", "meta": null, "sha256": "47af2a240e0fa4bca92d786d1fea2d4b6cd7ee8810c4540b619271457739f829", - "bytes": null, - "line": null + "bytes": 60, + "line": 9125 }, { "lang": "bash", "meta": null, "sha256": "f4a5d9b54707e03cc845a3ffc99493f9990d7c0a0aa96a48a492b303ef1959b4", - "bytes": null, - "line": null + "bytes": 45, + "line": 9158 }, { "lang": "bash", "meta": null, "sha256": "4a4ff033e75c32373422638e4f8079487d9cc37fa2b250cc2907584e690e2699", - "bytes": null, - "line": null + "bytes": 45, + "line": 9191 }, { "lang": "bash", "meta": null, "sha256": "66d1f7b4fc772fcb1ac84bcba2c1aa0e1a26105dda64b564c40dec35fc5fdaf2", - "bytes": null, - "line": null + "bytes": 43, + "line": 9221 }, { "lang": "bash", "meta": null, "sha256": "5fc8d60c19e8e3fc1c640ea87e091d0b95642a210a7e1a7d9d19e527b6f11207", - "bytes": null, - "line": null + "bytes": 38, + "line": 9253 }, { "lang": "bash", "meta": null, "sha256": "a7acb92552eae9b29dd7b973751bb7f3c2f7eb1dc00f36e84c594cb88dd9fc1c", - "bytes": null, - "line": null + "bytes": 33, + "line": 9274 }, { "lang": "bash", "meta": null, "sha256": "bb84857c237d2bfae0c6f63653597fe55263147428a5e8d36ceacfcda6bd6246", - "bytes": null, - "line": null + "bytes": 26, + "line": 9305 }, { "lang": "bash", "meta": null, "sha256": "3e634421662d08fe73882dd6a0d428545c33597790333f83b4c5086c8d494a1e", - "bytes": null, - "line": null + "bytes": 49, + "line": 9331 }, { "lang": "bash", "meta": null, "sha256": "c48dfec9df0cebb16aa976f859770a8b5beb67e2cf01dc5472dd8b3727ea164d", - "bytes": null, - "line": null + "bytes": 47, + "line": 9351 }, { "lang": "bash", "meta": null, "sha256": "8fd3a890425cf05e630bcd969b2aff57b3993d6632d905cab5b23cfce60e425c", - "bytes": null, - "line": null + "bytes": 49, + "line": 9372 }, { "lang": "bash", "meta": null, "sha256": "bd32d826b077176044eabbf175d64a747ba1a826bb36c95efb46925525f75ba9", - "bytes": null, - "line": null + "bytes": 45, + "line": 9398 }, { "lang": "bash", "meta": null, "sha256": "ee94be8e7fcb3c1bdb0abd6991992563371ba113b80b433cce0c71ac499f1d48", - "bytes": null, - "line": null + "bytes": 43, + "line": 9422 }, { "lang": "bash", "meta": null, "sha256": "bbaecaea783d60d4e8cbaad1c6951d2aa5fde5772f050166a24415162d9de3bc", - "bytes": null, - "line": null + "bytes": 29, + "line": 9444 }, { "lang": "bash", "meta": null, "sha256": "627ab83bbee7d7a608e8771c98556a00cb9df200a40fe9b68d79f93c322de59d", - "bytes": null, - "line": null + "bytes": 18, + "line": 9469 }, { "lang": "bash", "meta": null, "sha256": "9396c5d2aba2c0ff0d484a0a778dc38368154eb19edca9372cf576f8abedac90", - "bytes": null, - "line": null + "bytes": 32, + "line": 9479 }, { "lang": "bash", "meta": null, "sha256": "456a3638df3f1208cc5620fe2f7744e60215930e90cdada8c6d3f3041844b81c", - "bytes": null, - "line": null + "bytes": 22, + "line": 9489 }, { "lang": "bash", "meta": null, "sha256": "80c6f38f04b6c653c8de67e79ba7b6ca1a5ec208e8765a036048fd0adc4b4522", - "bytes": null, - "line": null + "bytes": 37, + "line": 9499 }, { "lang": "bash", "meta": null, "sha256": "3be0a5bf2f996779b39f57c35c08a046709ad91ffbb1ecd700c2d0f8a1c9b554", - "bytes": null, - "line": null + "bytes": 40, + "line": 9524 }, { "lang": "bash", "meta": null, "sha256": "94cdaecf523029bf20f25cf278f76142041e4ad9ce6980a0de225f6dd0b93a8f", - "bytes": null, - "line": null + "bytes": 43, + "line": 9546 }, { "lang": "bash", "meta": null, "sha256": "1731734821194e9c9ab5d0e866031dff102eab3c67b81c83780dce706461c802", - "bytes": null, - "line": null + "bytes": 40, + "line": 9566 }, { "lang": "bash", "meta": null, "sha256": "466187fc1a5788ab09d7700cf7cd19c9c541a571d0bc86d70fe52a1eb831b851", - "bytes": null, - "line": null + "bytes": 54, + "line": 9588 }, { "lang": "bash", "meta": null, "sha256": "e10bc7e084ad3b9231262208e0ac216aee47dc0ec7b1507214690ea9c098d5c9", - "bytes": null, - "line": null + "bytes": 32, + "line": 9620 }, { "lang": "bash", "meta": null, "sha256": "6bb0cf09f6bd8ba02e1f24a5eed89b35c0226ec7eefce07502015a455520fd0f", - "bytes": null, - "line": null + "bytes": 33, + "line": 9630 }, { "lang": "bash", "meta": null, "sha256": "23acce8016e243ab651bcc860cd8f1b1d236e6a5b7951abc76282cd674b2a25e", - "bytes": null, - "line": null + "bytes": 39, + "line": 9653 }, { "lang": "bash", "meta": null, "sha256": "210e8ab3d8af173ce648501ca50c828325ac1f4452006ad4485cb7a24d760ae4", - "bytes": null, - "line": null + "bytes": 37, + "line": 9677 }, { "lang": "bash", "meta": null, "sha256": "cdff2d4272d5bc3a18729e63e5ece9053d33ac0f8faf35cfaa3a289baa2dccc1", - "bytes": null, - "line": null + "bytes": 48, + "line": 9699 }, { "lang": "bash", "meta": null, "sha256": "c307203dd609208b90cbc0372e3401a75e943421bdf77e4e10779ed2c89ca4ff", - "bytes": null, - "line": null + "bytes": 48, + "line": 9729 }, { "lang": "bash", "meta": null, "sha256": "f6340c3d5dc4eedb98435df593ff277d0e44fbcb4c61e71a05123267b5352e78", - "bytes": null, - "line": null + "bytes": 29, + "line": 9759 }, { "lang": "bash", "meta": null, - "sha256": "ca6e405dc70365db67ec66e6c2499fedf89ae3d7a90f4b5d044a2aab13bb8f37", - "bytes": null, - "line": null + "sha256": "ca6e405dc70365db67ec66e6c2499fedf89ae3d7a90f4b5d044a2aab13bb8f37", + "bytes": 37, + "line": 9781 }, { "lang": "bash", "meta": null, "sha256": "52918df5b4d4003d22322d5785d8a0202a2b66d39a3c71171f92a65545e28788", - "bytes": null, - "line": null + "bytes": 37, + "line": 9802 }, { "lang": "bash", "meta": null, "sha256": "28e77f2a35930390cc7de2fc5abdce7809311c33b10eb749941d5c44b9de0cfa", - "bytes": null, - "line": null + "bytes": 37, + "line": 9827 }, { "lang": "bash", "meta": null, "sha256": "088f9018d5639eac73c710bf1ef4fd134b0cd4c290587a161af1322b415a013f", - "bytes": null, - "line": null + "bytes": 29, + "line": 9854 }, { "lang": "bash", "meta": null, "sha256": "67384a12d7642ea8a82e807a58e42f921ea37cb496e2315ac87368ae0e297e4d", - "bytes": null, - "line": null + "bytes": 29, + "line": 9886 }, { "lang": "bash", "meta": null, "sha256": "4c9e46c0b1c48cb348bfb37e4c705e4dfe1cd5f221d667ebd02dd7325fce7e29", - "bytes": null, - "line": null + "bytes": 38, + "line": 9918 }, { "lang": "bash", "meta": null, "sha256": "20fbb381c0b4ef786f755f485789ecb9e76538ec6394956bb6153ee4a79547ca", - "bytes": null, - "line": null + "bytes": 31, + "line": 9941 }, { "lang": "bash", "meta": null, "sha256": "ec9baafc46bf3e7425a387e9d92083a610028b2f7bf477ccc203fee669796cf1", - "bytes": null, - "line": null + "bytes": 31, + "line": 9962 }, { "lang": "bash", "meta": null, "sha256": "54ffdfd98a1fc3aad38e602c1d02336a81fe97d48e6732402a7980d0f55cb20d", - "bytes": null, - "line": null + "bytes": 40, + "line": 9983 }, { "lang": "bash", "meta": null, "sha256": "1dbcb58a66005a55dccd94c633f3be04c7b462980746ce0bdfc7275bf728f009", "bytes": 35, - "line": 9963 + "line": 10004 }, { "lang": "bash", "meta": null, "sha256": "384da7ccbd87c00eba8c8301b7904ac71161b4faa0f51c208e833ddb1eba9a3c", "bytes": 37, - "line": 9989 + "line": 10030 }, { "lang": "bash", "meta": null, "sha256": "8fae3ef13c962a97565001ae3caa4625cb9df99e17686cf13c6142b0c324a5a6", - "bytes": null, - "line": null + "bytes": 37, + "line": 10059 }, { "lang": "bash", "meta": null, "sha256": "7dc2bd34c299748344eadb6569a96731086b27cc503f1bff70f63a05d41782fb", - "bytes": null, - "line": null + "bytes": 38, + "line": 10090 }, { "lang": "bash", "meta": null, "sha256": "625019ad388b3c98472aa65b7a683a970d0d0060496e89c547c3bbef85afc867", - "bytes": null, - "line": null + "bytes": 47, + "line": 10119 } ], "links": [ @@ -14341,8 +14355,8 @@ "lang": "bash", "meta": null, "sha256": "3b675df64318861fe48f8c955db2eaee667edaafd4389e2f4bb220fcf5445fee", - "bytes": null, - "line": null + "bytes": 75, + "line": 427 } ], "links": [ @@ -17415,393 +17429,393 @@ "lang": "bash", "meta": null, "sha256": "f094df6732656b52792e5e766a69079c3e8bd929326bda7284e0bcb760bedd79", - "bytes": null, - "line": null + "bytes": 28, + "line": 14 }, { "lang": "bash", "meta": null, "sha256": "736889b5b5a59bc4fe7965922999b5cbec295acad8313c1e486d5668c7da961e", - "bytes": null, - "line": null + "bytes": 30, + "line": 39 }, { "lang": "bash", "meta": null, "sha256": "ebfb60766394d803a01326b040ac37c5f122134555f1b968aeb6a79b10d74fc7", - "bytes": null, - "line": null + "bytes": 30, + "line": 57 }, { "lang": "bash", "meta": null, "sha256": "66d1f7b4fc772fcb1ac84bcba2c1aa0e1a26105dda64b564c40dec35fc5fdaf2", - "bytes": null, - "line": null + "bytes": 43, + "line": 79 }, { "lang": "bash", "meta": null, "sha256": "d941e4f91a379820ba5d640e7ceffd42c6fdd70b5b19da9c508c259b40ce14f7", - "bytes": null, - "line": null + "bytes": 53, + "line": 109 }, { "lang": "bash", "meta": null, "sha256": "52be4758f4289e9f75875d8401cf57fda54283b2df00e413921d07303e728638", - "bytes": null, - "line": null + "bytes": 28, + "line": 138 }, { "lang": "bash", "meta": null, "sha256": "5fc8d60c19e8e3fc1c640ea87e091d0b95642a210a7e1a7d9d19e527b6f11207", - "bytes": null, - "line": null + "bytes": 38, + "line": 157 }, { "lang": "bash", "meta": null, "sha256": "d4de05e9142f532574133568e3fe2965c7fd82338e5b54ba0d8ae5713639eaca", - "bytes": null, - "line": null + "bytes": 43, + "line": 178 }, { "lang": "bash", "meta": null, "sha256": "2b26aa6f404ab19bda2d846871eb04b732f6397d1899fc28d89a29706fc0a670", - "bytes": null, - "line": null + "bytes": 34, + "line": 206 }, { "lang": "bash", "meta": null, "sha256": "7115696baaba8ca1ecd8f7cb22f215b7a53bf13d5757bd6932267644a0377807", - "bytes": null, - "line": null + "bytes": 36, + "line": 226 }, { "lang": "bash", "meta": null, "sha256": "10330e610f59c2fb169fcff11cb8147563efbcc109f875222ecbfaaa48c05f31", - "bytes": null, - "line": null + "bytes": 50, + "line": 248 }, { "lang": "bash", "meta": null, "sha256": "185227ff19342ab461c3e652c4158d8ece85c079b2542b9243b7c7cf0b2dac2c", - "bytes": null, - "line": null + "bytes": 34, + "line": 283 }, { "lang": "bash", "meta": null, "sha256": "daf3ccbc5a308bc4c62d1a761e01fac3d40ff67cc256c4c9624d0cd00a0072c4", - "bytes": null, - "line": null + "bytes": 53, + "line": 305 }, { "lang": "text", "meta": null, - "sha256": "48dd143dafc65a4f4c1cd5bfa0edc1ece98bec432d3e8d35b561c73cd3e3bfc2", - "bytes": null, - "line": null + "sha256": "7ccb089303b6156668b4dee2b4783360c510107743f3ff3eae8a506720fcada9", + "bytes": 2256, + "line": 336 }, { "lang": "bash", "meta": null, "sha256": "48ecf1013a285c0de3e23936d53a850d85af0564a7e089de2eba1ac7f8881a44", - "bytes": null, - "line": null + "bytes": 53, + "line": 380 }, { "lang": "bash", "meta": null, "sha256": "a09f283134986b066a49a41c5ef250ff1502ae2adbc3316baacf92712112cc2d", - "bytes": null, - "line": null + "bytes": 43, + "line": 413 }, { "lang": "bash", "meta": null, "sha256": "4d6c0bc0130fd4a83c7b2fcac6f5b4b7bc2f275c05fa6101551ac61ce1405aca", - "bytes": null, - "line": null + "bytes": 44, + "line": 444 }, { "lang": "bash", "meta": null, "sha256": "62d28b9be74c32c4ba00fefe878c492a6a5c671cc4a500373d7f2bdba9f7ef79", - "bytes": null, - "line": null + "bytes": 54, + "line": 464 }, { "lang": "bash", "meta": null, "sha256": "7579bd6ac197afa0afa5f62d9b412a7e265725bd507c1c63b438a60fd72ce1d0", - "bytes": null, - "line": null + "bytes": 40, + "line": 492 }, { "lang": "bash", "meta": null, "sha256": "63aac11606dc0eeb6cc452c20c405806840960425372cf2cf7c8b4b90a7de878", - "bytes": null, - "line": null + "bytes": 62, + "line": 510 }, { "lang": "bash", "meta": null, "sha256": "7d00d2a238c8794c5479e28ef14e6e104bcaff1aaaef70a094a2a51c55b6420c", - "bytes": null, - "line": null + "bytes": 50, + "line": 539 }, { "lang": "bash", "meta": null, "sha256": "f30977b7b952e6a369b72b828256fac3f9ede78ce6e7c45560a8d09989bd4db5", - "bytes": null, - "line": null + "bytes": 49, + "line": 568 }, { "lang": "bash", "meta": null, "sha256": "f34921d79bc4b608cb3e3c3f882729808afe1d8cf95ca45c63cbdf00ab494a3e", - "bytes": null, - "line": null + "bytes": 62, + "line": 587 }, { "lang": "bash", "meta": null, "sha256": "eb79c561c688b305a39f834bb39d74f65095db957e337d8e6081bbc00545bb08", - "bytes": null, - "line": null + "bytes": 53, + "line": 617 }, { "lang": "bash", "meta": null, "sha256": "5ed096b4dcf0efad18c54d322d528b7bb0e80336d061ee7eaa5d39d3bd505a4d", - "bytes": null, - "line": null + "bytes": 62, + "line": 650 }, { "lang": "bash", "meta": null, "sha256": "47af2a240e0fa4bca92d786d1fea2d4b6cd7ee8810c4540b619271457739f829", - "bytes": null, - "line": null + "bytes": 60, + "line": 683 }, { "lang": "bash", "meta": null, "sha256": "f4a5d9b54707e03cc845a3ffc99493f9990d7c0a0aa96a48a492b303ef1959b4", - "bytes": null, - "line": null + "bytes": 45, + "line": 716 }, { "lang": "bash", "meta": null, "sha256": "4a4ff033e75c32373422638e4f8079487d9cc37fa2b250cc2907584e690e2699", - "bytes": null, - "line": null + "bytes": 45, + "line": 749 }, { "lang": "bash", "meta": null, "sha256": "fb10d8958f9f1b03ab76713459abf552755dae3334103a451c387c9d1c7b3605", - "bytes": null, - "line": null + "bytes": 40, + "line": 779 }, { "lang": "bash", "meta": null, "sha256": "d683e8c6e5a1d063ea9f6c74fd9020d48aede0d5af7031f6f48bd5a173ad2d3d", - "bytes": null, - "line": null + "bytes": 33, + "line": 831 }, { "lang": "bash", "meta": null, "sha256": "11658c406271a4f22a346aab51f697bc949342fbaaaabb2a786de824561bc4c3", - "bytes": null, - "line": null + "bytes": 35, + "line": 856 }, { "lang": "bash", "meta": null, "sha256": "bfb90a10455a59ef26068d176221816b9c374c4001d386ffdbb0140c4cfe40ca", - "bytes": null, - "line": null + "bytes": 40, + "line": 881 }, { "lang": "bash", "meta": null, "sha256": "d63bf37625acc32ec1ee6e59a56f57469b9cb4dab03e23067a54d2f7d8abd3a3", - "bytes": null, - "line": null + "bytes": 41, + "line": 914 }, { "lang": "bash", "meta": null, "sha256": "96abc89ee23cb4a7e2fc3caca2afbd2dd57d2734ca9e73816c412a71c5c5eb9d", - "bytes": null, - "line": null + "bytes": 43, + "line": 947 }, { "lang": "bash", "meta": null, "sha256": "653a412a8eeaffac8afbbbb2533375f02df67fe7ef882ca53fc7ca2755d0bcec", - "bytes": null, - "line": null + "bytes": 43, + "line": 979 }, { "lang": "bash", "meta": null, "sha256": "b130d4ed01c735074275b1505e7959e6dd3ae89c6b7ac159d17ccd495bec8f38", - "bytes": null, - "line": null + "bytes": 38, + "line": 1011 }, { "lang": "bash", "meta": null, "sha256": "32709306f0caabb4378fce9efba6b9c60a3985bb3500402d9a7f9e89fe35e00e", - "bytes": null, - "line": null + "bytes": 49, + "line": 1035 }, { "lang": "bash", "meta": null, "sha256": "e63db5a4bab57e3229127bb086d0c5429dfe20de83eaf5097e8943f90520b9b3", - "bytes": null, - "line": null + "bytes": 51, + "line": 1079 }, { "lang": "bash", "meta": null, "sha256": "b5dc1e771889fb1bf5f4d81d340cfd35d3a2263c87a725341d1d5c70405eb78d", - "bytes": null, - "line": null + "bytes": 43, + "line": 1111 }, { "lang": "bash", "meta": null, "sha256": "4c51312bac2ca9ea2dba0e7cf27f06d5e99502bab35ab569064057a85514cc38", - "bytes": null, - "line": null + "bytes": 38, + "line": 1143 }, { "lang": "bash", "meta": null, "sha256": "e88ab81833a4d529271c80e2cdf0e7ff5037a60066a918a9702a28ceca73a846", - "bytes": null, - "line": null + "bytes": 30, + "line": 1167 }, { "lang": "bash", "meta": null, "sha256": "a7acb92552eae9b29dd7b973751bb7f3c2f7eb1dc00f36e84c594cb88dd9fc1c", - "bytes": null, - "line": null + "bytes": 33, + "line": 1197 }, { "lang": "bash", "meta": null, "sha256": "2fc4fd97c2a62f635b42d646e481b18b0402ec0d051e7532988c026d838f0534", - "bytes": null, - "line": null + "bytes": 36, + "line": 1226 }, { "lang": "bash", "meta": null, "sha256": "432348582be57741628ca2b6a762c385ed57bbbfd4e4794b914409b7a89db582", - "bytes": null, - "line": null + "bytes": 35, + "line": 1249 }, { "lang": "bash", "meta": null, "sha256": "25d75743717b8e1c96f6b78e334e3e3cbc6dac5e395068308a4e358e06a0bac6", - "bytes": null, - "line": null + "bytes": 45, + "line": 1269 }, { "lang": "bash", "meta": null, "sha256": "3da31453cf86b97920f8d013f00122dee830af847c064e30ed3e158bd8f642cb", - "bytes": null, - "line": null + "bytes": 47, + "line": 1298 }, { "lang": "bash", "meta": null, "sha256": "bb84857c237d2bfae0c6f63653597fe55263147428a5e8d36ceacfcda6bd6246", - "bytes": null, - "line": null + "bytes": 26, + "line": 1319 }, { "lang": "bash", "meta": null, "sha256": "29cc30facfddd548aa5873383ac3d90a6b392cf120894fd73a735f266196540d", - "bytes": null, - "line": null + "bytes": 47, + "line": 1339 }, { "lang": "bash", "meta": null, "sha256": "427c626ebed3055c690ff0dbbb3a20550a2daae5ae40f5f9e005f1eb47dd733a", - "bytes": null, - "line": null + "bytes": 37, + "line": 1371 }, { "lang": "bash", "meta": null, "sha256": "f43f6a034552660fdb745c0ac0cfe17c1af0c7a2995fd76ab45f79ebfd116bfb", - "bytes": null, - "line": null + "bytes": 37, + "line": 1395 }, { "lang": "bash", "meta": null, "sha256": "d58dd2280200d928a15de43483c5c709be8aedc38087ba95cbbe2a31a39466fa", - "bytes": null, - "line": null + "bytes": 49, + "line": 1421 }, { "lang": "bash", "meta": null, "sha256": "9065c4d4de3606f4362700b64aa3f856aa75214bebafe9334d48b9ff8466a80c", - "bytes": null, - "line": null + "bytes": 38, + "line": 1456 }, { "lang": "bash", "meta": null, "sha256": "529d96c3ff160cf6393f3f7a1f69014d8f2f9f3f3ce5733fc11c58133accb7d7", - "bytes": null, - "line": null + "bytes": 36, + "line": 1474 }, { "lang": "bash", "meta": null, "sha256": "e61ba28ca4eef131ee1291f39b5cb583b2a1dd4436bde33a061ce27ac8af05af", - "bytes": null, - "line": null + "bytes": 46, + "line": 1499 }, { "lang": "bash", "meta": null, "sha256": "2b6c40dcef94f6188188d6369383e982f5a6dc88654b8ab76664c189f9af8ab0", - "bytes": null, - "line": null + "bytes": 47, + "line": 1533 }, { "lang": "bash", "meta": null, "sha256": "face4eea006073000b49334d0a2bea7f15f9df86cb1f606ac8fe39004c754027", - "bytes": null, - "line": null + "bytes": 30, + "line": 1563 } ], "links": [ From 5d777f9976900269386fd9a551a1a43a6b78c4b5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 06:13:45 -0800 Subject: [PATCH 29/37] fix(workflow-code): stand a loop condition's references in as (0) so member access after one parses A reference replaced by a bare 0 turned .length into 0.length, which is not JavaScript, so check warned (and apply refused) a condition the run evaluates fine. --- packages/workflow-code/src/compile/blocks.ts | 5 +++-- packages/workflow-code/src/compile/checks.test.ts | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index afd4f8fc583..2fcce95e645 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -1878,7 +1878,8 @@ function jsonField(value: Value | undefined): Json | undefined { * `evaluateWhileCondition`): each reference is replaced by its value and the text runs as * `return Boolean()`, outside every block. * - `W_LOOP_CONDITION_SYNTAX` when that is not valid JavaScript, which fails the run: references - * stand in as `0`, so only the text the author wrote around them is judged. + * stand in as `(0)`, a value that member access and calls can follow, so only the text the + * author wrote around them is judged. * - `W_REF_OUT_OF_SCOPE` for the loop's own iteration field read by its name (``): the * condition is evaluated outside the loop's body, where a named loop outputs only its results, * so the run fails; only the bare `` reads the iteration there. @@ -1904,7 +1905,7 @@ function checkLoopCondition( ) { selfReads.add(field.name) } - return '0' + return '(0)' }) for (const field of selfReads) { ctx.reporter.report( diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index e9a47f46a00..4bd0897206f 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -890,6 +890,7 @@ describe('loop conditions', () => { for (const condition of [ ' < 3', ' < && !== "x"', + '.length > 0 && [0] !== undefined', 'true', '', ]) { From 79ab6f4586655442aa04e7adcfafd594f2174397 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 06:14:01 -0800 Subject: [PATCH 30/37] fix(lint): judge a child's result. only when every run of the child ends at a Response block A child with a Response on one branch returns another block's output on the others, so W_CHILD_RESULT_PATH and the server's child-result lint now require every run to end at a root Response (alwaysEndsAtResponse in workflow-types, shared by the CLI check and the server). A deploy judges the child's active deployment, a draft write its draft, read in narrow batched queries; a failed child lookup no longer leaves an unhandled rejection. isElseConditionTitle and RESPONSE_BLOCK_TYPE move to workflow-types so every reader shares one rule. --- .../condition-input/condition-input.tsx | 2 +- .../executor/handlers/condition/handler.ts | 2 +- apps/sim/lib/workflows/conditions.test.ts | 20 --- apps/sim/lib/workflows/conditions.ts | 9 - .../lib/workflows/dynamic-handle-topology.ts | 33 ++++ .../editing/lint-report.integration.ts | 145 +++++++++++++--- .../lib/workflows/editing/lint-report.test.ts | 31 ++++ apps/sim/lib/workflows/editing/lint-report.ts | 156 ++++++++++++++---- apps/sim/lib/workflows/editing/lint.ts | 65 +++++++- .../src/commands/protocol/source-check.ts | 17 +- .../protocol/workspace-source-check.test.ts | 68 +++++++- .../commands/protocol/workspace-source-dir.ts | 4 +- .../src/canonicalize/branches.ts | 16 +- packages/workflow-code/src/compile/SYNTAX.md | 2 +- .../workflow-code/src/diagnostics/codes.ts | 8 +- packages/workflow-code/src/forms/response.ts | 3 +- packages/workflow-code/src/index.ts | 3 +- .../workflow-code/src/materialize/branches.ts | 6 +- packages/workflow-code/src/print/printer.ts | 9 +- packages/workflow-code/src/responds.ts | 55 ++++++ packages/workflow-code/src/sdk.ts | 3 - packages/workflow-types/src/workflow.ts | 74 +++++++++ scripts/check-unused-exports.baseline.json | 1 - 23 files changed, 610 insertions(+), 122 deletions(-) delete mode 100644 apps/sim/lib/workflows/conditions.test.ts delete mode 100644 apps/sim/lib/workflows/conditions.ts create mode 100644 packages/workflow-code/src/responds.ts diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/condition-input/condition-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/condition-input/condition-input.tsx index becc9bfb86d..c39b1af6df8 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/condition-input/condition-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/condition-input/condition-input.tsx @@ -13,8 +13,8 @@ import { } from '@sim/emcn' import { ChevronDown, ChevronsUpDown, ChevronUp, Plus, Trash } from '@sim/emcn/icons' import { createLogger } from '@sim/logger' +import { isElseConditionTitle } from '@sim/workflow-types/workflow' import Editor from 'react-simple-code-editor' -import { isElseConditionTitle } from '@/lib/workflows/conditions' import { isLikelyReferenceSegment, SYSTEM_REFERENCE_PREFIXES, diff --git a/apps/sim/executor/handlers/condition/handler.ts b/apps/sim/executor/handlers/condition/handler.ts index 52f4694676e..ef7a05e6fe9 100644 --- a/apps/sim/executor/handlers/condition/handler.ts +++ b/apps/sim/executor/handlers/condition/handler.ts @@ -1,12 +1,12 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' +import { isElseConditionTitle } from '@sim/workflow-types/workflow' import { adoptToolFailure, markFailureKind } from '@/lib/core/errors/failure-log' import { normalizeStringRecord, normalizeWorkflowVariables } from '@/lib/core/utils/records' import { isNonRetryableExecutionError, NonRetryableExecutionError, } from '@/lib/execution/non-retryable-error' -import { isElseConditionTitle } from '@/lib/workflows/conditions' import type { BlockOutput } from '@/blocks/types' import { BlockType, DEFAULTS, EDGE } from '@/executor/constants' import type { BlockHandler, ExecutionContext } from '@/executor/types' diff --git a/apps/sim/lib/workflows/conditions.test.ts b/apps/sim/lib/workflows/conditions.test.ts deleted file mode 100644 index 2db1d83590f..00000000000 --- a/apps/sim/lib/workflows/conditions.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { isElseConditionTitle } from '@/lib/workflows/conditions' - -describe('isElseConditionTitle', () => { - it.each(['else', 'Else', ' \t eLsE \n'])('recognizes "%s" as an else title', (title) => { - expect(isElseConditionTitle(title)).toBe(true) - }) - - it('rejects other condition titles', () => { - expect(isElseConditionTitle('else if')).toBe(false) - }) - - it('does not mutate legacy snapshot titles', () => { - const condition = { title: ' Else ' } - - isElseConditionTitle(condition.title) - - expect(condition.title).toBe(' Else ') - }) -}) diff --git a/apps/sim/lib/workflows/conditions.ts b/apps/sim/lib/workflows/conditions.ts deleted file mode 100644 index e1591fc3aa5..00000000000 --- a/apps/sim/lib/workflows/conditions.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Returns whether a condition title represents the fallback branch. - * - * @param title - Condition title from a workflow snapshot - * @returns Whether the normalized title is `else` - */ -export function isElseConditionTitle(title: unknown): boolean { - return typeof title === 'string' && title.trim().toLowerCase() === 'else' -} diff --git a/apps/sim/lib/workflows/dynamic-handle-topology.ts b/apps/sim/lib/workflows/dynamic-handle-topology.ts index 3a67bda44e1..2dd67c3e48c 100644 --- a/apps/sim/lib/workflows/dynamic-handle-topology.ts +++ b/apps/sim/lib/workflows/dynamic-handle-topology.ts @@ -1,3 +1,4 @@ +import { isElseConditionTitle, type WorkflowBranchKind } from '@sim/workflow-types/workflow' import type { BlockState } from '@/stores/workflows/workflow/types' export interface ConditionRow { @@ -39,6 +40,15 @@ export function getDynamicHandleSubblockId( return null } +/** The branch kind of a block whose branches are rows: `condition`, or `router` for router_v2. */ +export function getDynamicHandleBranchKind( + blockType: string | undefined +): WorkflowBranchKind | undefined { + if (blockType === 'condition') return 'condition' + if (blockType === 'router_v2') return 'router' + return undefined +} + export function getDynamicHandleSubblockType( blockType: string | undefined ): 'condition-input' | 'router-input' | null { @@ -122,6 +132,29 @@ export function getDynamicHandleRows( return [] } +/** + * The source handles of the branches `block` always takes one of (as `respondsOnEveryRun` reads + * canonical blocks): every route of a router, and every row of a condition with an else row (by + * stored title, as the executor finds it); none for branches never saved. `undefined` for a block + * without branches. + */ +export function getAlwaysTakenBranchHandles( + block: Pick & { subBlocks: Record } +): string[] | undefined { + const subBlockId = getDynamicHandleSubblockId(block.type) + if (subBlockId === null) return undefined + const stored = parseStructuredValue(block.subBlocks[subBlockId]?.value) ?? [] + if (block.type === 'condition') { + const hasElse = stored.some((row) => + isElseConditionTitle((row as { title?: unknown } | null)?.title) + ) + return stored.length > 0 && hasElse + ? getConditionRows(block.id, stored).map((row) => `condition-${row.id}`) + : [] + } + return stored.length > 0 ? getRouterRows(block.id, stored).map((row) => `router-${row.id}`) : [] +} + export function getDynamicHandleTopologySignature(block: BlockState): string | null { if (block.type === 'condition') { const rows = getConditionRows(block.id, block.subBlocks?.conditions?.value) diff --git a/apps/sim/lib/workflows/editing/lint-report.integration.ts b/apps/sim/lib/workflows/editing/lint-report.integration.ts index 18e82d965ce..229fa36f351 100644 --- a/apps/sim/lib/workflows/editing/lint-report.integration.ts +++ b/apps/sim/lib/workflows/editing/lint-report.integration.ts @@ -1,18 +1,20 @@ /** * Real PostgreSQL coverage for the lint's child workflow checks: the children a Workflow block - * calls are read from the workflow and block tables, and a graph is linted against them. A - * responding child's `result.` reads nothing unless `` is a Response output, and a - * deploy reports a called child with no deployment, which a deployed run cannot call. + * calls are read from the workflow, graph and deployment tables, and a graph is linted against + * them. The `result.` of a child whose every run ends at a Response block reads nothing + * unless `` is a Response output, judged on the version the caller's run calls, and a deploy + * reports a called child with no deployment, which a deployed run cannot call. */ import { mkdir, writeFile } from 'node:fs/promises' import { dirname, resolve } from 'node:path' import { db } from '@sim/db' -import { user, workflow, workspace } from '@sim/db/schema' +import { user, workflow, workflowDeploymentVersion, workspace } from '@sim/db/schema' import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow' +import type { Edge } from '@xyflow/react' import { eq, inArray } from 'drizzle-orm' import { afterAll, beforeAll, expect, it } from 'vitest' import { buildWorkflowLintReport } from '@/lib/workflows/editing/lint-report' @@ -64,10 +66,69 @@ function block( } as BlockState } -/** Stores a child workflow whose only blocks are a Start and, when given, a Response block. */ +function edge(source: string, target: string, sourceHandle = 'source'): Edge { + return { id: generateId(), source, target, sourceHandle, targetHandle: 'target' } +} + +/** + * A child graph: a Start trigger wired to a Response block "Reply" (disabled with `'disabled'`), + * or a Start trigger alone with `'none'`. Block ids are fresh, as stored block ids are global. + */ +function replyGraph(reply: 'enabled' | 'disabled' | 'none'): WorkflowState { + const startId = generateId() + const blocks: Record = { [startId]: block(startId, 'start_trigger', 'Start') } + const edges: Edge[] = [] + if (reply !== 'none') { + const replyId = generateId() + blocks[replyId] = block( + replyId, + 'response', + 'Reply', + { dataMode: 'json', data: '{"mobile": "1"}' }, + reply === 'enabled' + ) + edges.push(edge(startId, replyId)) + } + return { blocks, edges, loops: {}, parallels: {} } +} + +/** + * A child graph whose condition "Gate" sends its `if` branch to a Response block and its else + * branch to `elseTarget`: a second Response block, or a function that ends the run there. + */ +function gateGraph(elseTarget: 'response' | 'function'): WorkflowState { + const startId = generateId() + const gateId = generateId() + const replyId = generateId() + const otherId = generateId() + const conditions = JSON.stringify([ + { id: `${gateId}-if`, title: 'if', value: 'true' }, + { id: `${gateId}-else`, title: 'else', value: '' }, + ]) + const blocks: Record = { + [startId]: block(startId, 'start_trigger', 'Start'), + [gateId]: block(gateId, 'condition', 'Gate', { conditions }), + [replyId]: block(replyId, 'response', 'Reply', { dataMode: 'json', data: '{"mobile": "1"}' }), + [otherId]: + elseTarget === 'response' + ? block(otherId, 'response', 'Other', { dataMode: 'json', data: '{"mobile": "2"}' }) + : block(otherId, 'function', 'Other', { code: "return { mobile: '2' }" }), + } + const edges = [ + edge(startId, gateId), + edge(gateId, replyId, `condition-${gateId}-if`), + edge(gateId, otherId, `condition-${gateId}-else`), + ] + return { blocks, edges, loops: {}, parallels: {} } +} + +/** + * Stores a child workflow with draft `graph` (a Start trigger alone by default) and, with + * `deployed`, an active deployment of that graph (`true`) or of another one. + */ async function seedChild( name: string, - options: { response?: 'enabled' | 'disabled'; deployed?: boolean; workspace?: string } = {} + options: { graph?: WorkflowState; deployed?: boolean | WorkflowState; workspace?: string } = {} ): Promise { const id = generateId() const now = new Date() @@ -76,26 +137,23 @@ async function seedChild( userId: ownerId, workspaceId: options.workspace ?? workspaceId, name, - isDeployed: options.deployed ?? false, + isDeployed: Boolean(options.deployed), lastSynced: now, createdAt: now, updatedAt: now, }) - const startId = generateId() - const blocks: Record = { [startId]: block(startId, 'start_trigger', 'Start') } - if (options.response) { - const replyId = generateId() - blocks[replyId] = block( - replyId, - 'response', - 'Reply', - { dataMode: 'json', data: '{"mobile": "1"}' }, - options.response === 'enabled' - ) - } - const state: WorkflowState = { blocks, edges: [], loops: {}, parallels: {} } - const saved = await saveWorkflowToNormalizedTables(id, state) + const graph = options.graph ?? replyGraph('none') + const saved = await saveWorkflowToNormalizedTables(id, graph) if (!saved.success) throw new Error(`Seeding the child failed: ${saved.error}`) + if (options.deployed) { + await db.insert(workflowDeploymentVersion).values({ + id: generateId(), + workflowId: id, + version: 1, + state: options.deployed === true ? graph : options.deployed, + isActive: true, + }) + } return id } @@ -122,6 +180,14 @@ function lint(graph: ReturnType, deployed = false) { ) } +/** The references a parent reading `` from `childId` is told read nothing. */ +async function childResultValues(childId: string, deployed = false) { + const report = await lint(parent(childId, 'return '), deployed) + return report.unresolvedReferences + .filter((ref) => ref.kind === 'child-result') + .map((ref) => ref.value) +} + beforeAll(async () => { const now = new Date() await db.insert(user).values({ @@ -154,7 +220,7 @@ afterAll(async () => { check( "a responding child's result. is reported with result.data. as the fix", async () => { - const childId = await seedChild('Responder', { response: 'enabled', deployed: true }) + const childId = await seedChild('Responder', { graph: replyGraph('enabled'), deployed: true }) const report = await lint( parent( @@ -180,8 +246,11 @@ check( 'a child with no enabled Response block, or in another workspace, is not judged', async () => { const silent = await seedChild('Silent') - const disabled = await seedChild('Disabled reply', { response: 'disabled' }) - const foreign = await seedChild('Foreign', { response: 'enabled', workspace: otherWorkspaceId }) + const disabled = await seedChild('Disabled reply', { graph: replyGraph('disabled') }) + const foreign = await seedChild('Foreign', { + graph: replyGraph('enabled'), + workspace: otherWorkspaceId, + }) for (const childId of [silent, disabled, foreign]) { const report = await lint(parent(childId, 'return ')) @@ -207,3 +276,31 @@ check('a deploy reports a called child that is not deployed; a draft write does expect(childFindings(await lint(parent(undeployed, 'return 1')))).toEqual([]) expect(childFindings(await lint(parent(deployed, 'return 1'), true))).toEqual([]) }) + +check( + 'a child whose run can end outside a Response block is not judged; one that always responds is', + async () => { + const branchy = await seedChild('Branchy', { graph: gateGraph('function') }) + const covered = await seedChild('Covered', { graph: gateGraph('response') }) + expect(await childResultValues(branchy)).toEqual([]) + expect(await childResultValues(covered)).toEqual([['']]) + } +) + +check( + "a deploy judges a child's result by its active deployment; a draft write by its draft", + async () => { + const respondsInDraft = await seedChild('Draft responder', { + graph: replyGraph('enabled'), + deployed: replyGraph('none'), + }) + const respondsDeployed = await seedChild('Deployed responder', { + graph: replyGraph('none'), + deployed: replyGraph('enabled'), + }) + expect(await childResultValues(respondsInDraft)).toEqual([['']]) + expect(await childResultValues(respondsInDraft, true)).toEqual([]) + expect(await childResultValues(respondsDeployed)).toEqual([]) + expect(await childResultValues(respondsDeployed, true)).toEqual([['']]) + } +) diff --git a/apps/sim/lib/workflows/editing/lint-report.test.ts b/apps/sim/lib/workflows/editing/lint-report.test.ts index 6251733cfa9..5a120581731 100644 --- a/apps/sim/lib/workflows/editing/lint-report.test.ts +++ b/apps/sim/lib/workflows/editing/lint-report.test.ts @@ -1,3 +1,5 @@ +import { flushMacrotask } from '@sim/testing/helpers/async' +import { dbChainMockFns, resetDbChainMock } from '@sim/testing/mocks/database.mock' import { tableServiceMock, tableServiceMockFns } from '@sim/testing/mocks/table-service.mock' import type { Mock } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -95,6 +97,35 @@ describe('buildWorkflowLintReport notes', () => { } ) + it('a complete diagnostic whose reference and child workflow lookups both fail rejects once, leaving no rejection unhandled', async () => { + resetDbChainMock() + const unhandled: unknown[] = [] + const onUnhandled = (reason: unknown) => unhandled.push(reason) + process.on('unhandledRejection', onUnhandled) + try { + const call = block('call', 'workflow_input') + call.subBlocks = { workflowId: { id: 'workflowId', type: 'short-input', value: 'child-1' } } + mocks.collectUnresolvedReferences.mockRejectedValueOnce(new Error('lookup down')) + dbChainMockFns.where.mockImplementationOnce(() => { + throw new Error('child lookup down') + }) + + await expect( + buildWorkflowLintReport( + { blocks: { start: block('start', 'starter'), call }, edges: [edge('start', 'call')] }, + scope, + { requireComplete: true } + ) + ).rejects.toThrow('Workflow reference checks could not complete') + await flushMacrotask() + + expect(unhandled).toEqual([]) + } finally { + process.off('unhandledRejection', onUnhandled) + resetDbChainMock() + } + }) + /** * `--blocks '{}' --edges '[]'` used to lint perfectly clean, so a dry run gave * no hint that applying it would erase the workflow. diff --git a/apps/sim/lib/workflows/editing/lint-report.ts b/apps/sim/lib/workflows/editing/lint-report.ts index 978fc5745c4..dc90ae95e9f 100644 --- a/apps/sim/lib/workflows/editing/lint-report.ts +++ b/apps/sim/lib/workflows/editing/lint-report.ts @@ -1,11 +1,13 @@ import { db } from '@sim/db' -import { workflow, workflowBlocks } from '@sim/db/schema' +import { workflow, workflowBlocks, workflowDeploymentVersion, workflowEdges } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import type { WorkflowState } from '@sim/workflow-types/workflow' -import { and, eq, inArray, isNull } from 'drizzle-orm' +import { type AnyColumn, and, eq, inArray, isNull, sql } from 'drizzle-orm' import { getTableById } from '@/lib/table/service' +import { getDynamicHandleSubblockId } from '@/lib/workflows/dynamic-handle-topology' import { + alwaysEndsAtResponseBlock, collectChildWorkflowFindings, collectDanglingBlockOutputReferences, collectTableBlockFieldIssues, @@ -19,6 +21,7 @@ import { type WorkflowLintTableFieldIssue, type WorkflowLintTableSchema, type WorkflowLintUnresolvedReference, + type WorkflowResponseGraph, } from '@/lib/workflows/editing/lint' import { type AgentToolReferenceValidationOptions, @@ -119,20 +122,120 @@ interface WorkflowLintReportOptions extends AgentToolReferenceValidationOptions deployed?: boolean } +/** Joins a child's graph rows to its `workflow` row while that is live in `workspaceId`. */ +function liveChildOf(workflowIdColumn: AnyColumn, workspaceId: string) { + return and( + eq(workflow.id, workflowIdColumn), + eq(workflow.workspaceId, workspaceId), + isNull(workflow.archivedAt) + ) +} + +/** + * The draft graph of each child in `ids`, by workflow id: only what + * {@link alwaysEndsAtResponseBlock} reads (each block's type, flag, parent and branch rows, each + * edge's ends and handle), in one query per table. + */ +async function loadChildDraftGraphs( + ids: string[], + workspaceId: string +): Promise> { + const [blocks, edges] = await Promise.all([ + db + .select({ + workflowId: workflowBlocks.workflowId, + id: workflowBlocks.id, + type: workflowBlocks.type, + enabled: workflowBlocks.enabled, + parentId: sql`${workflowBlocks.data}->>'parentId'`, + branchRows: sql`coalesce(${workflowBlocks.subBlocks}->'conditions'->'value', ${workflowBlocks.subBlocks}->'routes'->'value')`, + }) + .from(workflowBlocks) + .innerJoin(workflow, liveChildOf(workflowBlocks.workflowId, workspaceId)) + .where(inArray(workflowBlocks.workflowId, ids)), + db + .select({ + workflowId: workflowEdges.workflowId, + source: workflowEdges.sourceBlockId, + target: workflowEdges.targetBlockId, + sourceHandle: workflowEdges.sourceHandle, + }) + .from(workflowEdges) + .innerJoin(workflow, liveChildOf(workflowEdges.workflowId, workspaceId)) + .where(inArray(workflowEdges.workflowId, ids)), + ]) + const graphs = new Map< + string, + { blocks: WorkflowResponseGraph['blocks']; edges: WorkflowResponseGraph['edges'][number][] } + >() + const graphOf = (workflowId: string) => { + const graph = graphs.get(workflowId) ?? { blocks: {}, edges: [] } + graphs.set(workflowId, graph) + return graph + } + for (const { workflowId, id, type, enabled, parentId, branchRows } of blocks) { + const branchField = getDynamicHandleSubblockId(type) + graphOf(workflowId).blocks[id] = { + type, + enabled, + data: { parentId }, + subBlocks: branchField ? { [branchField]: { value: branchRows } } : {}, + } + } + for (const { workflowId, ...edge } of edges) graphOf(workflowId).edges.push(edge) + return graphs +} + +/** + * The graph of each child in `ids` with an active deployment, by workflow id: the blocks and edges + * of that deployment's snapshot, which a deployed run of the caller calls, in one query. + */ +async function loadChildDeployedGraphs( + ids: string[], + workspaceId: string +): Promise> { + const versions = await db + .select({ + workflowId: workflowDeploymentVersion.workflowId, + blocks: sql< + WorkflowResponseGraph['blocks'] | null + >`${workflowDeploymentVersion.state}->'blocks'`, + edges: sql< + WorkflowResponseGraph['edges'] | null + >`${workflowDeploymentVersion.state}->'edges'`, + }) + .from(workflowDeploymentVersion) + .innerJoin(workflow, liveChildOf(workflowDeploymentVersion.workflowId, workspaceId)) + .where( + and( + inArray(workflowDeploymentVersion.workflowId, ids), + eq(workflowDeploymentVersion.isActive, true) + ) + ) + return new Map( + versions.map(({ workflowId, blocks, edges }) => [ + workflowId, + { blocks: blocks ?? {}, edges: edges ?? [] }, + ]) + ) +} + /** * What the lint checks a call against for each workflow the graph's Workflow blocks call in this - * workspace, keyed by id: its name, whether it is deployed, and whether its draft holds an enabled - * Response block. A child in another workspace, or archived, is left out: the block's own - * reference check reports it. + * workspace, keyed by id: its name, whether it is deployed, and whether every run of it ends at a + * Response block, judged on the version a run of the caller calls (`deployed`: the child's active + * deployment; else its draft). A child in another workspace, or archived, is left out: the block's + * own reference check reports it. */ async function loadChildWorkflowsForLint( graph: Pick, - workspaceId: string + workspaceId: string, + deployed: boolean ): Promise> { const ids = collectReferencedWorkflowIds([graph]) const children = new Map() if (ids.length === 0) return children - const [rows, responders] = await Promise.all([ + const [rows, graphs] = await Promise.all([ db .select({ id: workflow.id, name: workflow.name, isDeployed: workflow.isDeployed }) .from(workflow) @@ -143,23 +246,14 @@ async function loadChildWorkflowsForLint( isNull(workflow.archivedAt) ) ), - db - .selectDistinct({ workflowId: workflowBlocks.workflowId }) - .from(workflowBlocks) - .where( - and( - inArray(workflowBlocks.workflowId, ids), - eq(workflowBlocks.type, 'response'), - eq(workflowBlocks.enabled, true) - ) - ), + deployed ? loadChildDeployedGraphs(ids, workspaceId) : loadChildDraftGraphs(ids, workspaceId), ]) - const responding = new Set(responders.map((row) => row.workflowId)) for (const row of rows) { + const childGraph = graphs.get(row.id) children.set(row.id, { name: row.name, deployed: row.isDeployed, - responds: responding.has(row.id), + responds: childGraph !== undefined && alwaysEndsAtResponseBlock(childGraph), }) } return children @@ -230,21 +324,17 @@ export async function buildWorkflowLintReport( ...collectUnquotedJsonStringReferences(graph) ) - // Started before the reference collectors so its lookup overlaps theirs. - const childFindings = loadChildWorkflowsForLint(graph, scope.workspaceId).then( - (children) => - collectChildWorkflowFindings(graph, children, { deployed: options.deployed === true }), + // Started before the reference collectors so its lookup overlaps theirs. It settles to `null` + // rather than rejecting, so a collector below that throws first leaves no rejection unhandled. + const deployed = options.deployed === true + const childFindings = loadChildWorkflowsForLint(graph, scope.workspaceId, deployed).then( + (children) => collectChildWorkflowFindings(graph, children, { deployed }), (error: unknown) => { logger.warn('Child workflow lint failed', { workflowId: scope.workflowId, error: getErrorMessage(error), }) - if (options.requireComplete) { - throw new Error( - 'Workflow child workflow checks could not complete; retry when lookup is available' - ) - } - return [] + return null } ) @@ -280,7 +370,13 @@ export async function buildWorkflowLintReport( } } - unresolvedReferences.push(...(await childFindings)) + const children = await childFindings + if (children === null && options.requireComplete) { + throw new Error( + 'Workflow child workflow checks could not complete; retry when lookup is available' + ) + } + unresolvedReferences.push(...(children ?? [])) /** Standalone diagnostics have already read tables under application authorization. */ let tableFieldIssues: WorkflowLintTableFieldIssue[] = options.tables?.tableFieldIssues ?? [] diff --git a/apps/sim/lib/workflows/editing/lint.ts b/apps/sim/lib/workflows/editing/lint.ts index e7686418ef0..d97835dfe58 100644 --- a/apps/sim/lib/workflows/editing/lint.ts +++ b/apps/sim/lib/workflows/editing/lint.ts @@ -7,6 +7,12 @@ import { type ScopeNode, } from '@sim/workflow-code' import type { CanonicalModeOverrides } from '@sim/workflow-code/catalog/canonical-index' +import { + alwaysEndsAtResponse, + normalizeWorkflowEdgeSourceHandle, + parseWorkflowSourceHandle, + type ResponseGraphBlock, +} from '@sim/workflow-types/workflow' import { MCP_STRUCTURED_CONTENT_OUTPUT } from '@/lib/mcp/output-schema' import { collectPredicateFieldNames, @@ -18,6 +24,10 @@ import { getMcpStructuredContentOutputs, getResponseFormatOutputs, } from '@/lib/workflows/blocks/outputs' +import { + getAlwaysTakenBranchHandles, + getDynamicHandleBranchKind, +} from '@/lib/workflows/dynamic-handle-topology' import { quotedBlockLabel } from '@/lib/workflows/labels' import { getWorkflowInvocationTarget } from '@/lib/workflows/streaming/nested-output-options' import type { ManualRunEntryIssue } from '@/lib/workflows/triggers/manual-run' @@ -1122,12 +1132,65 @@ export interface WorkflowLintChildWorkflow { /** Whether the child has an active deployment, which a deployed run of the caller calls. */ deployed: boolean /** - * Whether the child holds an enabled Response block: its run then returns that block's output, + * Whether every run of the child ends at an enabled Response block + * ({@link alwaysEndsAtResponseBlock}): it then returns that block's output, * `{ data, status, headers }`, as the caller's `result`. */ responds: boolean } +/** The parts of a stored graph {@link alwaysEndsAtResponseBlock} reads. */ +export interface WorkflowResponseGraph { + blocks: Record< + string, + { + type: string + enabled?: boolean + data?: { parentId?: unknown } | null + subBlocks?: Record + } + > + edges: ReadonlyArray<{ source: string; target: string; sourceHandle?: string | null }> +} + +/** + * Whether every run of the stored graph ends at an enabled Response block at its root, so a + * Workflow block calling it reads that block's output as its `result` + * ({@link alwaysEndsAtResponse}). + */ +export function alwaysEndsAtResponseBlock(graph: WorkflowResponseGraph): boolean { + const blocks: Record = {} + for (const [id, block] of Object.entries(graph.blocks)) { + const branches = getAlwaysTakenBranchHandles({ + id, + type: block.type, + subBlocks: block.subBlocks ?? {}, + }) + const parentId = block.data?.parentId + blocks[id] = { + type: block.type, + enabled: block.enabled !== false, + parentId: typeof parentId === 'string' && parentId !== '' ? parentId : null, + ...(branches !== undefined && { branches }), + } + } + const edges = graph.edges.map((edge) => { + const sourceType = graph.blocks[edge.source]?.type + const handle = normalizeWorkflowEdgeSourceHandle(edge.sourceHandle) + const port = parseWorkflowSourceHandle( + handle, + sourceType, + getDynamicHandleBranchKind(sourceType) + ) + return { + source: edge.source, + target: edge.target, + port: port.kind === 'branch' ? `branch:${port.handle}` : port.kind, + } + }) + return alwaysEndsAtResponse(blocks, edges) +} + /** * Findings about the workflows the graph's Workflow blocks call, judged against what `children` * (by workflow id) knows of each: diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index 5192077d974..268dd3a0d06 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -22,11 +22,11 @@ import { parseJsonField, parseStoredPath, parseWorkflowLock, - RESPONSE_BLOCK_TYPE, RESPONSE_OUTPUTS, raisedMessage, refuseEditedFindings, refusesEdited, + respondsOnEveryRun, scriptName, startInputs, type Value, @@ -306,8 +306,10 @@ function childInputFindings( /** * `W_CHILD_RESULT_PATH` for each reference to `>` whose call runs a workflow of - * this directory that responds, when `` is not one of the Response block's outputs: the - * child's `result` is then `{ data, status, headers }`, so the path reads nothing at run time. + * this directory that ends at a Response block on every run, when `` is not one of the + * Response block's outputs: the child's `result` is then `{ data, status, headers }`, so the path + * reads nothing at run time. A child that can end elsewhere returns the output of the block it + * ends at, which the path may read, so its calls are not judged. */ function childResultFindings( workflow: CanonicalWorkflow, @@ -482,8 +484,8 @@ async function compileWorkflowDir( * The workspace directory `root`'s declarations, with what a child workflow call is checked * against from compiling each of its workflows: the inputs of each workflow that compiles * (`startInputs`, `null` without a Start trigger), which `workspace.d.ts` also types - * `inputMapping` with, and the keys of those holding an enabled response block, whose `result` is - * that block's output. + * `inputMapping` with, and the keys of those that end at a Response block on every run, whose + * `result` is that block's output. */ export async function readCheckDeclarations( root: string, @@ -503,10 +505,7 @@ async function compileWorkspaceWorkflows(root: string, catalog: BlockCatalog) { const { compiled } = await compileWorkflowDir(join(root, KIND_DIRS.workflow, key), catalog) if (!compiled.workflow) continue workflowInputs.set(key, startInputs(compiled.workflow)) - const blocks = Object.values(compiled.workflow.blocks) - if (blocks.some((block) => block.type === RESPONSE_BLOCK_TYPE && block.enabled !== false)) { - respondingWorkflows.add(key) - } + if (respondsOnEveryRun(compiled.workflow)) respondingWorkflows.add(key) } return { workflowInputs, respondingWorkflows } } diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts index 5c012f69cc3..4614af28b50 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts @@ -1,6 +1,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { COOKBOOK_EXAMPLES, WORKSPACE_COOKBOOK } from '@sim/workflow-sdk/codegen' import { Command } from 'commander' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { SimApiError } from '../../http/client' @@ -395,7 +396,7 @@ describe('sim workspaces source check', () => { function workflowFile(...lines: string[]): string { return [ '// @sim-sdk 1', - "import { agent, childWorkflow, env, fn, js, response, runWorkflow, skill, t, trigger, workflow } from '@sim/workflow-sdk'", + "import { agent, childWorkflow, condition, env, fn, js, response, runWorkflow, skill, t, trigger, workflow } from '@sim/workflow-sdk'", "export default workflow('W', {}, () => {", ...lines.map((line) => ` ${line}`), '})', @@ -522,6 +523,71 @@ describe('sim workspaces source check', () => { ]) }) + it("judges a child's result. only when every run of the child ends at a Response block", async () => { + // Gate.else ends the run at Echo, which returns { mobile }: result.mobile reads it then. + writeFile( + 'workflows/branchy/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { q: 'string' } })", + "const gate = condition('Gate', { yes: js`${start.q} === 'y'`, else: true })", + "const reply = response('Reply', { body: { mobile: start.q } })", + "const echo = fn('Echo', { code: js`return { mobile: ${start.q} }` })", + 'start.to(gate)', + 'gate.yes.to(reply)', + 'gate.else.to(echo)' + ) + ) + writeFile( + 'workflows/covered/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { q: 'string' } })", + "const gate = condition('Gate', { yes: js`${start.q} === 'y'`, else: true })", + "const reply = response('Reply', { body: { mobile: start.q } })", + "const other = response('Other', { body: { mobile: 'none' } })", + 'start.to(gate)', + 'gate.yes.to(reply)', + 'gate.else.to(other)' + ) + ) + writeFile( + 'workflows/parent/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { q: 'string' } })", + "const maybe = runWorkflow('Maybe', { workflowId: childWorkflow('branchy'), inputMapping: { q: start.q } })", + "const always = runWorkflow('Always', { workflowId: childWorkflow('covered'), inputMapping: { q: start.q } })", + "const use = fn('Use', { code: js`return [${maybe.result.mobile}, ${always.result.mobile}]` })", + 'start.to(maybe)', + 'maybe.to(always)', + 'always.to(use)' + ) + ) + + await check() + + const found = (stdoutJson().diagnostics as Array>).filter( + (finding) => finding.code === 'W_CHILD_RESULT_PATH' + ) + expect(found).toEqual([ + expect.objectContaining({ + message: expect.stringContaining(' reads mobile'), + }), + ]) + }) + + it("checks the cookbook example's table writes clean against the cookbook workspace's tables", async () => { + for (const [path, text] of Object.entries(WORKSPACE_COOKBOOK)) writeFile(path, text) + writeFile('workflows/cookbook/workflow.ts', COOKBOOK_EXAMPLES['cookbook.ts']) + + await check() + + const tableFindings = (stdoutJson().diagnostics as Array>).filter( + (finding) => + finding.file === 'workflows/cookbook/workflow.ts' && + ['W_TABLE_UNKNOWN_COLUMN', 'W_UNKNOWN_OPTION'].includes(String(finding.code)) + ) + expect(tableFindings).toEqual([]) + }) + it('points an unknown env name at secrets.ts', async () => { writeFile( 'secrets.ts', diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index 4808f660c0d..cbc29afb14b 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -315,8 +315,8 @@ export interface WorkspaceDeclarations { */ workflowInputs?: ReadonlyMap /** - * The keys of the workflows that compiled holding an enabled Response block, whose `result` is - * that block's output; set by a check, which compiles them. + * The keys of the workflows that compiled and end at a Response block on every run, whose + * `result` is that block's output; set by a check, which compiles them. */ respondingWorkflows?: ReadonlySet } diff --git a/packages/workflow-code/src/canonicalize/branches.ts b/packages/workflow-code/src/canonicalize/branches.ts index b6f1ba8302e..09802faccca 100644 --- a/packages/workflow-code/src/canonicalize/branches.ts +++ b/packages/workflow-code/src/canonicalize/branches.ts @@ -56,12 +56,22 @@ export function positionalKeys(kind: CanonicalBranches['kind'], count: number): }) } -/** The title the canvas shows (condition-input.tsx). */ -export function positionalTitle( +/** + * The title a branch row is stored with: its override, else the positional one, or none for a row + * stored without a title. + */ +export function storedTitle( kind: CanonicalBranches['kind'], + row: CanonicalBranchRow, index: number, count: number -): string { +): string | undefined { + if (row.titleOverride !== undefined) return row.titleOverride + return row.titleMissing ? undefined : positionalTitle(kind, index, count) +} + +/** The title the canvas shows (condition-input.tsx). */ +function positionalTitle(kind: CanonicalBranches['kind'], index: number, count: number): string { if (kind === 'router') return `Route ${index + 1}` if (index === 0) return 'if' if (index === count - 1) return 'else' diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index bbd89483ca2..9b453752e78 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -403,7 +403,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `W_ENV_UNKNOWN` | `env.X`, or a code file `$env`, naming a variable the workspace does not hold (checked only when the env names are known); the hint has a did-you-mean. An offline check in a workspace directory knows only the names `secrets.ts` declares, so there the finding says `secrets.ts` does not declare it, and the hint points there. | | `W_CHILD_INPUT_UNKNOWN` | A child workflow call's `inputMapping` sets an input the child's Start trigger does not declare (`sim workspaces source check`, with the child in the same directory); the hint names the nearest input. | | `W_CHILD_NO_START` | A child workflow call names a workflow of the same directory that has no Start trigger (`sim workspaces source check`). | -| `W_CHILD_RESULT_PATH` | A reference to a child workflow call's `result.` whose child (in the same directory) holds a Response block, where `` is not `data`, `status` or `headers`: the child's result is its Response output, so the path reads nothing (`sim workspaces source check`); the hint names `result.data.`. The dry run reports the same reference as a `W_APPLY_LINT` warning. | +| `W_CHILD_RESULT_PATH` | A reference to a child workflow call's `result.` whose child (in the same directory) ends at a Response block on every run, where `` is not `data`, `status` or `headers`: the child's result is its Response output, so the path reads nothing (`sim workspaces source check`); the hint names `result.data.`. The dry run reports the same reference as a `W_APPLY_LINT` warning. | | `E_UNKNOWN_SUBFLOW_PROPERTY` | `p.` that a loop or parallel does not have. | | `W_FORWARD_REF` | A ref to a block declared later; it resolves. | | `W_REF_NOT_NORMALIZED` | Hand-written `` text that is not in key form. | diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index c725df3b8f5..3a6f30ac337 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -107,10 +107,10 @@ const COMPILE_SCOPE_CODES = [ */ 'W_CHILD_NO_START', /** - * A reference to a child workflow call's `result.` whose child holds a Response block (an - * offline check of a workspace directory), where `` is not `data`, `status` or `headers`: - * the child's result is its Response output, so the path reads nothing. The value meant is - * almost always `result.data.`. + * A reference to a child workflow call's `result.` whose child ends at a Response block on + * every run (an offline check of a workspace directory), where `` is not `data`, `status` + * or `headers`: the child's result is its Response output, so the path reads nothing. The value + * meant is almost always `result.data.`. */ 'W_CHILD_RESULT_PATH', /** `p.` not in the loop/parallel resolvers' `KNOWN_PROPERTIES`. */ diff --git a/packages/workflow-code/src/forms/response.ts b/packages/workflow-code/src/forms/response.ts index 61775330197..64856348566 100644 --- a/packages/workflow-code/src/forms/response.ts +++ b/packages/workflow-code/src/forms/response.ts @@ -6,12 +6,13 @@ import type { Node, ObjectProperty } from '@babel/types' import { isRecordLike } from '@sim/utils/object' +import { RESPONSE_BLOCK_TYPE } from '@sim/workflow-types/workflow' import { type CompileContext, rangeOf, unsupported } from '../compile/context' import { didYouMean } from '../compile/hints' import { compileJsonField, compileValue, objectEntries, type ValueSite } from '../compile/values' import type { CanonicalBlock, CanonicalParam, SubBlockId, Value } from '../model' import { getOwn, setOwn } from '../records' -import { RESPONSE_BLOCK_TYPE, RESPONSE_BODY_KEYS } from '../sdk' +import { RESPONSE_BODY_KEYS } from '../sdk' import { holdsSecret } from '../secrets' /** The stored params the form carries: the editor's JSON mode and its three fields. */ diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index 5b900181a0a..ec06d063d2f 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -117,7 +117,8 @@ export { isResourceKind } from './model' export { assignIdentifiers, printWorkflow } from './print' export { hasSuspiciousCharacter, printKey, quoteString } from './print/strings' export { getOwn, invertRecord, parseJsonContainer, setOrDelete, setOwn } from './records' -export { JS_RESERVED_WORDS, RESPONSE_BLOCK_TYPE, RESPONSE_OUTPUTS, SDK_CORE_EXPORTS } from './sdk' +export { respondsOnEveryRun } from './responds' +export { JS_RESERVED_WORDS, RESPONSE_OUTPUTS, SDK_CORE_EXPORTS } from './sdk' export { holdsSecret, withoutAuthScheme } from './secrets' export { mapAnchorIds, diff --git a/packages/workflow-code/src/materialize/branches.ts b/packages/workflow-code/src/materialize/branches.ts index 8d4b7831c24..0b325deec83 100644 --- a/packages/workflow-code/src/materialize/branches.ts +++ b/packages/workflow-code/src/materialize/branches.ts @@ -1,4 +1,4 @@ -import { positionalKeys, positionalTitle } from '../canonicalize/branches' +import { positionalKeys, storedTitle } from '../canonicalize/branches' import type { BranchKey, CanonicalBranches, CanonicalBranchRow } from '../model' import { getOwn, setOwn } from '../records' import type { MaterializeContext } from './context' @@ -49,8 +49,8 @@ export function writeBranches( used.add(id) setOwn(ids, row.key, id) const entry: Record = { id } - if (row.titleOverride !== undefined) entry.title = row.titleOverride - else if (!row.titleMissing) entry.title = positionalTitle(branches.kind, index, rows.length) + const title = storedTitle(branches.kind, row, index, rows.length) + if (title !== undefined) entry.title = title entry.value = row.value if (row.key !== defaults[index]) entry.key = row.key for (const [field, value] of Object.entries(row.extra ?? {})) setOwn(entry, field, value) diff --git a/packages/workflow-code/src/print/printer.ts b/packages/workflow-code/src/print/printer.ts index b4d08a207d0..dc0f2a86612 100644 --- a/packages/workflow-code/src/print/printer.ts +++ b/packages/workflow-code/src/print/printer.ts @@ -10,6 +10,7 @@ import { compareStrings } from '@sim/utils/string' import { isReservedWorkflowBlockName, normalizeWorkflowBlockName, + RESPONSE_BLOCK_TYPE, } from '@sim/workflow-types/workflow' import { SUBFLOW_DATA_KEYS, SUPERSEDED_CONTAINER_PARAMS } from '../canonicalize/subflows' import { builderPins } from '../catalog/surface' @@ -23,13 +24,7 @@ import { SOURCE_ENTRY_FILE } from '../limits' import type { SourceHintBlock, SourceHints } from '../lock' import type { AnchorKey, BlockKey, CanonicalBlock, Json } from '../model' import { getOwn, setOwn } from '../records' -import { - type BlockMetaKey, - GENERIC_BUILDER, - RESPONSE_BLOCK_TYPE, - SDK_MODULE, - type TemplateTag, -} from '../sdk' +import { type BlockMetaKey, GENERIC_BUILDER, SDK_MODULE, type TemplateTag } from '../sdk' import { type AttachedComments, anchors, withComments } from './comments' import type { PrintContext } from './context' import { createPrintContext, type PrintInput } from './context' diff --git a/packages/workflow-code/src/responds.ts b/packages/workflow-code/src/responds.ts new file mode 100644 index 00000000000..94c6b776fbd --- /dev/null +++ b/packages/workflow-code/src/responds.ts @@ -0,0 +1,55 @@ +/** + * Whether a workflow, called as a child, always answers with its Response block's output. + */ +import { + alwaysEndsAtResponse, + isElseConditionTitle, + type ResponseGraphBlock, +} from '@sim/workflow-types/workflow' +import { storedTitle } from './canonicalize/branches' +import type { CanonicalBlock, CanonicalWorkflow, Port } from './model' + +/** + * The branches `block` always takes one of (as `getAlwaysTakenBranchHandles` reads stored + * blocks): every route of a router, and every row of a condition with an else row (by stored + * title, as the executor finds it); none for branches never saved. + */ +function alwaysTakenBranches(block: CanonicalBlock): ResponseGraphBlock['branches'] { + const branches = block.branches + if (!branches) return undefined + const rows = branches.rows ?? [] + const hasElse = rows.some((row, index) => + isElseConditionTitle(storedTitle(branches.kind, row, index, rows.length)) + ) + return branches.kind === 'condition' && !hasElse ? [] : rows.map((row) => row.key) +} + +function portName(port: Port): string { + return port.kind === 'branch' ? `branch:${port.key}` : port.kind +} + +/** + * Whether every run of `workflow` ends at an enabled Response block at its root, so a Workflow + * block calling it reads that block's output, `{ data, status, headers }`, as its `result` + * ({@link alwaysEndsAtResponse}). + */ +export function respondsOnEveryRun(workflow: CanonicalWorkflow): boolean { + const blocks: Record = {} + for (const [key, block] of Object.entries(workflow.blocks)) { + const branches = alwaysTakenBranches(block) + blocks[key] = { + type: block.type, + enabled: block.enabled, + parentId: block.parent, + ...(branches !== undefined && { branches }), + } + } + return alwaysEndsAtResponse( + blocks, + workflow.edges.map((edge) => ({ + source: edge.from, + target: edge.to, + port: portName(edge.port), + })) + ) +} diff --git a/packages/workflow-code/src/sdk.ts b/packages/workflow-code/src/sdk.ts index a3ec7b35186..08b084cadb5 100644 --- a/packages/workflow-code/src/sdk.ts +++ b/packages/workflow-code/src/sdk.ts @@ -20,9 +20,6 @@ export const GENERIC_BUILDER = 'block' /** The stored type of a workspace custom tool entry (the tool picker's `type: 'custom-tool'`). */ export const CUSTOM_TOOL_TYPE = 'custom-tool' -/** The response block type, which also takes the `response(name, { body, ... })` form. */ -export const RESPONSE_BLOCK_TYPE = 'response' - /** * The keys of the `response(name, { body, status?, headers? })` form. Writing `body` selects it; * without `body` the params are the block's own (`dataMode`, `builderData`, `data`, ...). diff --git a/packages/workflow-types/src/workflow.ts b/packages/workflow-types/src/workflow.ts index e925c63e0fd..e68faae560f 100644 --- a/packages/workflow-types/src/workflow.ts +++ b/packages/workflow-types/src/workflow.ts @@ -698,6 +698,80 @@ export function isKnownWorkflowTriggerBlock(block: WorkflowTriggerCapableBlock): return block.triggerMode === true || block.type === LEGACY_STARTER_BLOCK_TYPE } +/** The Response block's type: a run that reaches one returns its output. */ +export const RESPONSE_BLOCK_TYPE = 'response' + +/** Whether a stored condition title names the else branch, as the executor finds it. */ +export function isElseConditionTitle(title: unknown): boolean { + return typeof title === 'string' && title.trim().toLowerCase() === 'else' +} + +/** One block as {@link alwaysEndsAtResponse} reads it. */ +export interface ResponseGraphBlock { + type: string + enabled: boolean + /** The enclosing loop or parallel, or `null` at the root. */ + parentId: string | null + /** + * Set on a condition or router block: the branches a run always takes one of, empty when a run + * can take none (a condition without an else branch, or branches never saved). + */ + branches?: readonly string[] +} + +/** + * One edge as {@link alwaysEndsAtResponse} reads it, by the port it leaves through: `out`, + * `subflowEnd`, `branch:` for a condition or router branch, or any other port. + */ +export interface ResponseGraphEdge { + source: string + target: string + port: string +} + +/** + * Whether every run of a workflow ends at an enabled Response block at its root, so a caller's + * `result` is always that block's output (`{ data, status, headers }`) rather than the output of + * whichever block the run ended at. True when there is a root Response and every other root block + * that runs always goes on to one that runs (its out edge, a container's end edge, or an edge from + * every branch it always takes one of): the root graph is acyclic, so every run then ends at a + * Response. + */ +export function alwaysEndsAtResponse( + blocks: Readonly>, + edges: readonly ResponseGraphEdge[] +): boolean { + const runs = (id: string) => { + const block = Object.hasOwn(blocks, id) ? blocks[id] : undefined + return block?.enabled === true && !isWorkflowAnnotationOnlyBlockType(block.type) + } + const portsBySource = new Map>() + for (const edge of edges) { + if (!runs(edge.source) || !runs(edge.target)) continue + const ports = portsBySource.get(edge.source) ?? new Set() + ports.add(edge.port) + portsBySource.set(edge.source, ports) + } + let responds = false + for (const [id, block] of Object.entries(blocks)) { + if (!runs(id) || block.parentId !== null) continue + if (block.type === RESPONSE_BLOCK_TYPE) { + responds = true + continue + } + const ports = portsBySource.get(id) + if (block.branches !== undefined) { + const { branches } = block + if (branches.length === 0 || !branches.every((branch) => ports?.has(`branch:${branch}`))) { + return false + } + } else if (!ports?.has(isSubflowType(block.type) ? 'subflowEnd' : 'out')) { + return false + } + } + return responds +} + /** * Names reserved for reference-path prefixes (``, ``, * ``) — a block cannot take one of these as its (normalized) name. diff --git a/scripts/check-unused-exports.baseline.json b/scripts/check-unused-exports.baseline.json index 089075e8fd6..6d07c816224 100644 --- a/scripts/check-unused-exports.baseline.json +++ b/scripts/check-unused-exports.baseline.json @@ -5024,7 +5024,6 @@ "apps/sim/lib/workflows/deployment-outbox.ts#PrepareDeploymentWebhooksInput", "apps/sim/lib/workflows/diff/types.ts#EdgeDiffStatus", "apps/sim/lib/workflows/diff/types.ts#FieldDiffStatus", - "apps/sim/lib/workflows/dynamic-handle-topology.ts#getDynamicHandleSubblockId", "apps/sim/lib/workflows/editing/block-enablement.ts#findDescendants", "apps/sim/lib/workflows/editing/engine.ts#topologicalSortInserts", "apps/sim/lib/workflows/editing/lint.ts#WorkflowLintEmptyOutgoingPort", From 3ad3796cb8857b03d8b5eccdd94715a311009fec Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 06:14:14 -0800 Subject: [PATCH 31/37] fix(sim-cli): select the stop block of a --stop-after run that --follow streams --- .../protocol/workflow-run-follow.test.ts | 17 ++++++++++++++++- .../commands/protocol/workflow-run-follow.ts | 10 +++++----- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index 05aacf04e23..92e579cb213 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -54,7 +54,7 @@ function sse(...frames: unknown[]): ReadableStream { return bodyOf(frames.map((frame) => `data: ${JSON.stringify(frame)}\n\n`)) } -function _streamResponse(body: ReadableStream): Response { +function streamResponse(body: ReadableStream): Response { return { body, status: 200, @@ -386,6 +386,21 @@ describe('sim workflows run --follow', () => { expect(requestRaw.mock.calls[1][1].body.selectedOutputs).toEqual([blockId]) }) + it('selects the stop block of a --stop-after run it follows, so the final frame holds its output', async () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + requestRaw.mockResolvedValue( + streamResponse(sse({ event: 'final', data: { success: true, output: {} } })) + ) + + await run(WORKFLOW_ID, '--stop-after', 'agent-1', '--follow') + + expect(requestRaw.mock.calls[0][1].body).toMatchObject({ + run: { stopAfterBlockId: 'agent-1' }, + selectedOutputs: ['agent-1'], + stream: true, + }) + }) + it('keeps the outputs a --stop-after run selects itself', async () => { vi.spyOn(console, 'log').mockImplementation(() => {}) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index fe6776f142c..21ee1274d9b 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -491,9 +491,9 @@ async function followRun(workflowId: string, command: Command): Promise { /** * The selection a `--stop-after` run sends when the caller selected nothing: the stop block's - * whole output, so `blockOutputs` names the block the run stopped after and holds what it - * produced (the run's `output` stays empty: no Response block ran). The block is sent as the - * executor compares names ({@link normalizeBlockName}), so a display name with a dot is not read + * whole output, so `blockOutputs` (with `--follow`, the final frame's `output`) names the block + * the run stopped after and holds what it produced (no Response block ran). The block is sent as + * the executor compares names ({@link normalizeBlockName}), so a display name with a dot is not read * as a path; an id is sent as it is. */ function stopBlockSelection( @@ -541,6 +541,8 @@ function followOrDelegate(previous: ((args: unknown[]) => unknown) | null) { const selection = resolveWorkflowRunSelection(initialFlags) if (selection) command.setOptionValue('run', selection) const flags = command.optsWithGlobals() as Record + const stopBlock = stopBlockSelection(selection, flags) + if (stopBlock) command.setOptionValue('selectOutput', stopBlock) if (flags.follow !== true) { // A queued run has produced nothing to select from, so the server would @@ -563,8 +565,6 @@ function followOrDelegate(previous: ((args: unknown[]) => unknown) | null) { ) } if (flags.async !== true) { - const stopBlock = stopBlockSelection(selection, flags) - if (stopBlock) command.setOptionValue('selectOutput', stopBlock) await runWithResultStream(workflowId, command, waitTimeoutSeconds) return } From 15bc7dcacde89d26a204876b0d3cb9360bdfa46b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 06:14:15 -0800 Subject: [PATCH 32/37] fix(workspace-source): say on a dry run whether the apply would refuse The CLI guessed from each finding's kind/key whether it belonged to a held change, and E_PLAN_REF_DELETED names the held workflow while the server records it on the delete, so a dry run exited 15 for an apply that refuses. The dry run now carries refuses from the plan's own refusing list; the CLI falls back to the guess, minus that code, for older servers. --- apps/docs/openapi-v2-workflows.json | 8 +++ .../lib/api/contracts/v2/workspace-source.ts | 6 ++ .../application/apply-workspace-source.ts | 6 ++ .../application/references.integration.ts | 25 +++++--- .../protocol/workspace-source-apply.test.ts | 61 +++++++++++++++++++ .../protocol/workspace-source-apply.ts | 17 ++++-- packages/sim-cli/src/generated/v2-api.ts | 2 + 7 files changed, 112 insertions(+), 13 deletions(-) diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 894c5b2c930..51d4c8b04ff 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -26972,6 +26972,10 @@ }, "description": "Every planned change, no-ops included, in apply order." }, + "refuses": { + "description": "Set on a dry run: whether the apply would refuse. Errors of a change held back (`held`) refuse nothing else; any other error refuses. Absent on an apply.", + "type": "boolean" + }, "applied": { "type": "array", "items": { @@ -28266,6 +28270,10 @@ }, "description": "Every planned change, no-ops included, in apply order." }, + "refuses": { + "description": "Set on a dry run: whether the apply would refuse. Errors of a change held back (`held`) refuse nothing else; any other error refuses. Absent on an apply.", + "type": "boolean" + }, "applied": { "type": "array", "items": { diff --git a/apps/sim/lib/api/contracts/v2/workspace-source.ts b/apps/sim/lib/api/contracts/v2/workspace-source.ts index e948df35730..a7785a09215 100644 --- a/apps/sim/lib/api/contracts/v2/workspace-source.ts +++ b/apps/sim/lib/api/contracts/v2/workspace-source.ts @@ -301,6 +301,12 @@ const applyDataSchema = z workspaceId: z.string().describe('Workspace id.'), dryRun: z.boolean().describe('True when nothing was written because `dryRun` was set.'), plan: z.array(changeSchema).describe('Every planned change, no-ops included, in apply order.'), + refuses: z + .boolean() + .optional() + .describe( + 'Set on a dry run: whether the apply would refuse. Errors of a change held back (`held`) refuse nothing else; any other error refuses. Absent on an apply.' + ), applied: z.array(changeSchema).describe('The changes written, in order.'), failed: z .object({ diff --git a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts index 497161798a0..04134b3fb01 100644 --- a/apps/sim/lib/workspace-source/application/apply-workspace-source.ts +++ b/apps/sim/lib/workspace-source/application/apply-workspace-source.ts @@ -78,6 +78,11 @@ export interface ApplyWorkspaceSourceResult { dryRun: boolean /** Every change the apply plans, no-ops included, in apply order. */ plan: WorkspaceSourceChange[] + /** + * Set on a dry run: whether the apply would refuse, for an error outside the changes held back + * (those refuse nothing else). Absent on an apply, which a refusal throws instead. + */ + refuses?: boolean /** The changes written, in the order they were written. */ applied: WorkspaceSourceChange[] /** @@ -262,6 +267,7 @@ function planned( workspaceId, dryRun, plan: plan.changes.map((change) => summarize(change)), + ...(dryRun && { refuses: plan.refusing.length > 0 }), applied: [], needBlobs: plan.needBlobs, files: {}, diff --git a/apps/sim/lib/workspace-source/application/references.integration.ts b/apps/sim/lib/workspace-source/application/references.integration.ts index a728748fd2f..253ce48862b 100644 --- a/apps/sim/lib/workspace-source/application/references.integration.ts +++ b/apps/sim/lib/workspace-source/application/references.integration.ts @@ -324,11 +324,13 @@ describe('workspace source: secrets and credentials', () => { const missing = dryRun.diagnostics.find((finding) => finding.code === 'E_SECRET_MISSING') expect(missing?.hint).toContain('sim secrets set OPENAI_API_KEY --scope workspace') expect(held(dryRun.plan)).toEqual(['workflow:ask']) + expect(dryRun.refuses).toBe(false) const result = await apply(workspaceId, files) expect(result.failed).toBeUndefined() expect(actions(result.applied)).toEqual(['create workflow:plain']) expect(held(result.plan)).toEqual(['workflow:ask']) + expect(result.refuses).toBeUndefined() expect(await liveWorkflowNames(workspaceId)).toEqual(['Plain']) expect(result.base.resources['workflow:ask']).toBeUndefined() @@ -353,16 +355,21 @@ describe('workspace source: secrets and credentials', () => { ) // The edit drops the child for an agent reading a secret the workspace lacks: it is held. + const edited = { + ...withoutChild, + 'secrets.ts': SECRETS(), + 'workflows/parent/workflow.ts': ASK.replace("'Ask'", "'Parent'"), + } + // The dry run says the apply refuses, though the finding names the held workflow. + const preview = await apply(workspaceId, edited, { + base: created.base, + allowDelete: true, + dryRun: true, + }) + expect(held(preview.plan)).toEqual(['workflow:parent']) + expect(preview.refuses).toBe(true) const refused = await refusal( - apply( - workspaceId, - { - ...withoutChild, - 'secrets.ts': SECRETS(), - 'workflows/parent/workflow.ts': ASK.replace("'Ask'", "'Parent'"), - }, - { base: created.base, allowDelete: true } - ) + apply(workspaceId, edited, { base: created.base, allowDelete: true }) ) expect(findings(refused.diagnostics)).toContain('E_SECRET_MISSING workflow:parent') expect(findings(refused.diagnostics)).toContain('E_PLAN_REF_DELETED workflow:parent') diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index f4a90d77aad..d9daebdc487 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -1853,6 +1853,67 @@ describe('workspaces source apply', () => { } ) + it('exits a dry run as refused when the server says it refuses, though its only error names a held change', async () => { + request.mockResolvedValue( + answer({ + dryRun: true, + refuses: true, + plan: [ + { kind: 'table', key: 'leads', action: 'create' }, + { kind: 'workflow', key: 'ingest', action: 'create', held: true }, + ], + diagnostics: [ + { + code: 'E_SECRET_MISSING', + severity: 'error', + message: 'workflows/ingest is held back: it reads the secret OPENAI_API_KEY.', + kind: 'workflow', + key: 'ingest', + }, + ], + }) + ) + + await apply('--dry-run') + + expect(process.exitCode).toBe(1) + }) + + it('exits a dry run as refused when a delete breaks a workflow it holds back, for a server without refuses, as the apply refuses it', async () => { + // E_PLAN_REF_DELETED names the held workflow, but the server records it on the delete (or the + // plan), which no hold excuses: the apply would refuse, so the dry run cannot exit 15. + request.mockResolvedValue( + answer({ + dryRun: true, + plan: [ + { kind: 'table', key: 'leads', action: 'create' }, + { kind: 'workflow', key: 'parent', action: 'update', held: true }, + { kind: 'workflow', key: 'child', action: 'delete' }, + ], + diagnostics: [ + { + code: 'E_SECRET_MISSING', + severity: 'error', + message: 'workflows/parent is held back: it reads the secret OPENAI_API_KEY.', + kind: 'workflow', + key: 'parent', + }, + { + code: 'E_PLAN_REF_DELETED', + severity: 'error', + message: 'workflows/parent uses workflow "child", which this apply deletes.', + kind: 'workflow', + key: 'parent', + }, + ], + }) + ) + + await apply('--dry-run', '--allow-delete') + + expect(process.exitCode).toBe(1) + }) + it('saves the applied answer when the catalog of a workflow it reprinted cannot be fetched, and says its edges are unrecorded', async () => { const configDir = mkdtempSync(join(tmpdir(), 'sim-workspace-apply-config-')) vi.stubEnv('SIM_CONFIG_DIR', configDir) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 8c5c562a536..4a2077dfae6 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -124,18 +124,27 @@ function failedExitCode(failed: NonNullable): number { : refusedExitCode([{ code: failed.code, severity: 'error' }]) } -/** Whether `finding` is about a change the plan holds back, which refuses nothing else. */ +/** + * Whether `finding` is about a change the plan holds back, which refuses nothing else: one naming + * that change. For a server that predates `refuses` only; `E_PLAN_REF_DELETED` names the workflow + * that uses what a delete removes but sits on the delete or the plan, so no hold excuses it. + */ function isHeldFinding( plan: readonly Change[], finding: ApplyData['diagnostics'][number] ): boolean { - return plan.some( - (change) => change.held && change.kind === finding.kind && change.key === finding.key + return ( + finding.code !== 'E_PLAN_REF_DELETED' && + plan.some((change) => change.held && change.kind === finding.kind && change.key === finding.key) ) } -/** Whether a dry run's errors refuse the apply: any error but those of changes held back. */ +/** + * Whether a dry run's errors refuse the apply: the server's answer (`refuses`), or for a server + * that predates it, any error but those of changes held back. + */ function refusesApply(data: ApplyData): boolean { + if (data.refuses !== undefined) return data.refuses return data.diagnostics.some( (finding) => finding.severity === 'error' && !isHeldFinding(data.plan, finding) ) diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index dda2ca15d4f..b6207962a8d 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -1191,6 +1191,7 @@ export type ApplyWorkspaceSourceResponse = { id?: string held?: true }> + refuses?: boolean applied: Array<{ kind: | 'secret' @@ -14768,6 +14769,7 @@ export type PlanWorkspaceSourceResponse = { id?: string held?: true }> + refuses?: boolean applied: Array<{ kind: | 'secret' From e0d4d25617f524c9f257adf332784b43ee8ca95b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 06:14:16 -0800 Subject: [PATCH 33/37] fix(editing): resolve a canonical param name on the block's active surface On a trigger-mode block, a name shared by action and trigger fields (siteId) was written to the dormant action member. --- apps/sim/lib/workflows/editing/builders.ts | 11 ++++--- apps/sim/lib/workflows/editing/operations.ts | 9 ++++-- .../lib/workflows/editing/validation.test.ts | 29 +++++++++++++++++++ apps/sim/lib/workflows/editing/validation.ts | 25 +++++++++++----- 4 files changed, 57 insertions(+), 17 deletions(-) diff --git a/apps/sim/lib/workflows/editing/builders.ts b/apps/sim/lib/workflows/editing/builders.ts index 4efc86132f5..6d83044a862 100644 --- a/apps/sim/lib/workflows/editing/builders.ts +++ b/apps/sim/lib/workflows/editing/builders.ts @@ -157,6 +157,9 @@ export function createBlockFromParams( enforceToolBindingContract = false ): any { const blockConfig = getBlock(params.type) + const triggerMode = params.triggerMode || false + const isTriggerCapable = blockConfig ? hasTriggerCapability(blockConfig) : false + const effectiveTriggerMode = Boolean(triggerMode && isTriggerCapable) // Validate inputs against block configuration let validatedInputs: Record | undefined @@ -166,7 +169,8 @@ export function createBlockFromParams( params.inputs, blockId, {}, - enforceToolBindingContract + enforceToolBindingContract, + effectiveTriggerMode ) validatedInputs = result.validInputs if (errorsCollector && result.errors.length > 0) { @@ -174,11 +178,6 @@ export function createBlockFromParams( } } - // Determine outputs based on trigger mode - const triggerMode = params.triggerMode || false - const isTriggerCapable = blockConfig ? hasTriggerCapability(blockConfig) : false - const effectiveTriggerMode = Boolean(triggerMode && isTriggerCapable) - const blockState: any = { id: blockId, type: params.type, diff --git a/apps/sim/lib/workflows/editing/operations.ts b/apps/sim/lib/workflows/editing/operations.ts index 452dcec06cf..8acd21aca3b 100644 --- a/apps/sim/lib/workflows/editing/operations.ts +++ b/apps/sim/lib/workflows/editing/operations.ts @@ -340,7 +340,8 @@ function mergeNestedNodesForParent( childBlock.inputs, existingId, buildSubBlockValues(existingBlock.subBlocks), - ctx.enforceToolBindingContract + ctx.enforceToolBindingContract, + existingBlock.triggerMode === true ) validationErrors.push(...childValidation.errors) @@ -599,7 +600,8 @@ export function handleEditOperation(op: EditWorkflowOperation, ctx: OperationCon params.inputs, block_id, buildSubBlockValues(block.subBlocks), - ctx.enforceToolBindingContract + ctx.enforceToolBindingContract, + typeof params.triggerMode === 'boolean' ? params.triggerMode : block.triggerMode === true ) validationErrors.push(...validationResult.errors) @@ -1070,7 +1072,8 @@ export function handleInsertIntoSubflowOperation( params.inputs, block_id, buildSubBlockValues(existingBlock.subBlocks ?? {}), - ctx.enforceToolBindingContract + ctx.enforceToolBindingContract, + existingBlock.triggerMode === true ) validationErrors.push(...validationResult.errors) diff --git a/apps/sim/lib/workflows/editing/validation.test.ts b/apps/sim/lib/workflows/editing/validation.test.ts index b9b0ad606dc..c505a92b2e7 100644 --- a/apps/sim/lib/workflows/editing/validation.test.ts +++ b/apps/sim/lib/workflows/editing/validation.test.ts @@ -120,6 +120,18 @@ const canonicalCredBlockConfig = { ], } +// Mirrors webflow: the action pair and the trigger field share the canonical param siteId. +const dualSurfaceBlockConfig = { + type: 'dualsurface', + name: 'DualSurface', + outputs: {}, + subBlocks: [ + { id: 'siteSelector', type: 'project-selector', canonicalParamId: 'siteId', mode: 'basic' }, + { id: 'manualSiteId', type: 'short-input', canonicalParamId: 'siteId', mode: 'advanced' }, + { id: 'triggerSiteId', type: 'short-input', canonicalParamId: 'siteId', mode: 'trigger' }, + ], +} + // Mirrors video_generator_v3: routes provider -> tool; only video_falai has hosting. const videoBlockConfig = { type: 'video_generator_v3', @@ -244,6 +256,7 @@ const blockConfigsByType: Record = { huggingface: huggingfaceBlockConfig, knowledge: knowledgeBlockConfig, canonicalcred: canonicalCredBlockConfig, + dualsurface: dualSurfaceBlockConfig, video_generator_v3: videoBlockConfig, custom_key_block: customKeyBlockConfig, image_generator_v2: imageBlockConfig, @@ -407,6 +420,22 @@ describe('validateInputsForBlock', () => { ]) }) + it("writes a canonical name on a trigger-mode block into the trigger's member, not a dormant action one", () => { + const trigger = validateInputsForBlock( + 'dualsurface', + { siteId: 'site_1' }, + 'b', + {}, + false, + true + ) + const action = validateInputsForBlock('dualsurface', { siteId: 'site_1' }, 'b') + + expect(trigger.errors).toEqual([]) + expect(trigger.validInputs).toEqual({ triggerSiteId: 'site_1' }) + expect(action.validInputs).toEqual({ manualSiteId: 'site_1' }) + }) + it('still names a key that is neither a field nor a canonical param as unknown', () => { const result = validateInputsForBlock('canonicalcred', { credKey: 'cred_1' }, 'cred-1') diff --git a/apps/sim/lib/workflows/editing/validation.ts b/apps/sim/lib/workflows/editing/validation.ts index 26155b5e1bd..0d09db54328 100644 --- a/apps/sim/lib/workflows/editing/validation.ts +++ b/apps/sim/lib/workflows/editing/validation.ts @@ -33,6 +33,7 @@ import { import { containsReference } from '@/lib/workflows/sanitization/references' import { getSkillById } from '@/lib/workflows/skills/operations' import { + buildCanonicalIndexForSurface, buildSubBlockValues, getCanonicalSubBlocksForSurface, } from '@/lib/workflows/subblocks/visibility' @@ -111,17 +112,19 @@ function isContainerBlockType(blockType: string): blockType is 'loop' | 'paralle * member. For a basic/advanced pair, a string (an id, a `` reference) goes to the * advanced member, the free-text field that takes either, and anything else to the basic one, as * source compiles a literal; the caller then records the mode the written member implies. A - * canonical name written beside one of its own members is refused: the two would compete. + * canonical name written beside one of its own members is refused: the two would compete. Names + * resolve on the block's active surface (`triggerSurface`), so a trigger-mode block's name never + * lands on a dormant action member that shares it. */ function withCanonicalNamesResolved( - subBlocks: readonly SubBlockConfig[], + subBlocks: SubBlockConfig[], subBlockMap: ReadonlyMap, inputs: Record, + triggerSurface: boolean, refuse: (key: string, error: string) => void ): Record { if (Object.keys(inputs).every((key) => subBlockMap.has(key))) return inputs - // canonical-index-unscoped: maps written names to member ids and reads no values. - const { groupsById } = buildCanonicalIndex(subBlocks) + const { groupsById } = buildCanonicalIndexForSurface(subBlocks, triggerSurface) const resolved: Record = {} for (const [key, value] of Object.entries(inputs)) { const group = subBlockMap.has(key) ? undefined : groupsById[key] @@ -156,14 +159,16 @@ function withCanonicalNamesResolved( /** * Validates and filters inputs against a block's subBlock configuration - * Returns valid inputs and any validation errors encountered + * Returns valid inputs and any validation errors encountered. `triggerSurface` is whether the + * block runs in trigger mode, the surface a canonical param name resolves on. */ export function validateInputsForBlock( blockType: string, inputs: Record, blockId: string, existingValues: Record = {}, - enforceToolBindingContract = false + enforceToolBindingContract = false, + triggerSurface = false ): ValidationResult { const errors: ValidationError[] = [] @@ -228,8 +233,12 @@ export function validateInputsForBlock( subBlockMap.set(subBlock.id, variants) } - inputs = withCanonicalNamesResolved(blockConfig.subBlocks, subBlockMap, inputs, (key, error) => - errors.push({ blockId, blockType, field: key, value: inputs[key], error }) + inputs = withCanonicalNamesResolved( + blockConfig.subBlocks, + subBlockMap, + inputs, + triggerSurface, + (key, error) => errors.push({ blockId, blockType, field: key, value: inputs[key], error }) ) const conditionValues = { ...existingValues, ...inputs } From a3cd487d9a19067d5a9b5d28d90014031c085432 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 06:14:17 -0800 Subject: [PATCH 34/37] docs: fix the cookbook upsert and workspace help; pin the unknown-type error's line The cookbook wrote a status option and a column the orders table lacks and upserted on a column not declared unique; a check of the example against the cookbook workspace now guards it. The help says a source directory keeps its recorded workspace and what -w does with a variable holding the whole option. --- .../application/apply-workflow-source.integration.ts | 7 ++++++- apps/sim/lib/workflows/code/real-catalog.test.ts | 1 - .../sim-cli/src/commands/protocol/source-loop-help.ts | 4 ++-- packages/sim-cli/src/program.ts | 8 +++++--- packages/workflow-sdk/cookbook/examples/cookbook.ts | 4 ++-- packages/workflow-sdk/cookbook/workspace/tables/orders.ts | 2 +- .../workflow-sdk/src/codegen/cookbook-text.generated.ts | 2 +- .../src/codegen/workspace-cookbook-text.generated.ts | 2 +- 8 files changed, 18 insertions(+), 12 deletions(-) diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts index d7f26d2bae7..6fc2bb44d27 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -1126,7 +1126,12 @@ check('a new block of an unknown type is one error, at its source line', async ( const errors = result.diagnostics.filter((d) => d.severity === 'error') expect(errors.map((d) => d.code)).toEqual(['E_APPLY_INVALID_BLOCK_TYPE']) - expect(errors[0]).toMatchObject({ file: 'workflow.ts', blockKey: 'ghost' }) + const ghostLine = + files['workflow.ts'] + .split('\n') + .findIndex((line) => line.includes("block('qa_nonexistent_type'")) + 1 + expect(ghostLine).toBeGreaterThan(0) + expect(errors[0]).toMatchObject({ file: 'workflow.ts', line: ghostLine, blockKey: 'ghost' }) expect(errors[0]?.message).toContain('qa_nonexistent_type') expect(result.applied).toBe(false) }) diff --git a/apps/sim/lib/workflows/code/real-catalog.test.ts b/apps/sim/lib/workflows/code/real-catalog.test.ts index 0c55fba1485..984778f7bb6 100644 --- a/apps/sim/lib/workflows/code/real-catalog.test.ts +++ b/apps/sim/lib/workflows/code/real-catalog.test.ts @@ -56,7 +56,6 @@ const COOKBOOK_WORKSPACE: WorkspaceManifest = { columns: { orderId: { type: 'string' }, status: { type: 'string' }, - risk: { type: 'string' }, }, }, leads: { diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index 5ffcaa97197..9d1e35ce919 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -14,8 +14,8 @@ function loopRows(rows: ReadonlyArray): string { /** Where the commands of either group find their workspace. */ const WORKSPACE_LINE = `Workspace: a command run on a directory reads it from .sim/base.json; any other takes -w -or SIM_WORKSPACE (export it once: a shell variable holding "--workspace " arrives as one -argument, which is refused).` +or SIM_WORKSPACE (export it once, or keep only the ID in a variable: a variable holding +"--workspace " is one argument, an unknown option alone and the whole ID after -w).` /** The status line both groups end with, for a directory at `dir`. */ function statusLine(group: string, dir: string): string { diff --git a/packages/sim-cli/src/program.ts b/packages/sim-cli/src/program.ts index 66d3f736b80..5d55aad2938 100644 --- a/packages/sim-cli/src/program.ts +++ b/packages/sim-cli/src/program.ts @@ -28,9 +28,11 @@ Profiles work like the AWS CLI: settings live in ~/.sim/config, keys in with -P, --profile, or SIM_PROFILE. A command targets the profile's workspace unless -w (--workspace ) or -SIM_WORKSPACE names another. In a script, export SIM_WORKSPACE= once, or -write -w "$WS": a variable holding "--workspace " reaches the CLI as one -argument, which it refuses. +SIM_WORKSPACE names another; a source directory keeps to the workspace its +.sim/base.json records, and refuses a -w naming another. In a script, export +SIM_WORKSPACE= once, or keep only the ID in a variable and write -w "$WS". +A variable holding "--workspace " is one argument: alone it is an unknown +option, and after -w all of it is taken as the ID. Workflow, knowledge-base and workspace IDs are bare UUIDs. Table IDs carry a tbl_ prefix and file IDs a wf_ one, so wf_ never names a workflow. An audit-log diff --git a/packages/workflow-sdk/cookbook/examples/cookbook.ts b/packages/workflow-sdk/cookbook/examples/cookbook.ts index ee8f86191e9..af0065dca60 100644 --- a/packages/workflow-sdk/cookbook/examples/cookbook.ts +++ b/packages/workflow-sdk/cookbook/examples/cookbook.ts @@ -74,13 +74,13 @@ export default workflow('Cookbook', { description: 'One example of each common b }) const save = table.insertRow('Save Order', { tableId: table('orders'), - data: { orderId: start.orderId, status: 'open', risk: check.risk }, + data: { orderId: start.orderId, status: 'open' }, }) // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else // inserts one. data is keyed by column name, as for insertRow. const touch = table.upsertRow('Touch Order', { tableId: table('orders'), - data: { orderId: start.orderId, status: 'seen' }, + data: { orderId: start.orderId, status: 'answered' }, conflictColumn: 'orderId', }) diff --git a/packages/workflow-sdk/cookbook/workspace/tables/orders.ts b/packages/workflow-sdk/cookbook/workspace/tables/orders.ts index 0f74a03a1d7..855a536d7ad 100644 --- a/packages/workflow-sdk/cookbook/workspace/tables/orders.ts +++ b/packages/workflow-sdk/cookbook/workspace/tables/orders.ts @@ -7,7 +7,7 @@ export default defineTable({ name: 'orders', description: 'Order questions the support workflow answered', columns: { - orderId: column.string({ required: true }), + orderId: column.string({ required: true, unique: true }), status: column.select({ options: ['open', 'answered'] }), total: column.number(), }, diff --git a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts index 31c026f082d..1c02cd09fa8 100644 --- a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from cookbook/examples; do not edit. /** The example workflows, file name → text, written as `.sim/examples/`: together one correct example of each common block. */ -export const COOKBOOK_EXAMPLES: Readonly> = {"agents.ts":"// @sim-sdk 1\nimport {\n agent,\n childWorkflow,\n credential,\n customTool,\n env,\n mcp,\n parallel,\n response,\n router,\n runWorkflow,\n slack,\n t,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `lookup-order`, `linear`, `ops-slack`,\n// `enrich-lead` and ANTHROPIC_API_KEY stand in for this workspace\u0027s resources\n// (.sim/sdk/workspace.d.ts; `sim workflows source resources` lists the real keys).\nexport default workflow(\n \u0027Cookbook: agents and subflows\u0027,\n { description: \u0027Router, agent tools, a child workflow and a parallel fan-out.\u0027 },\n () => {\n const start = trigger.start(\u0027Start\u0027, {\n inputFormat: { message: \u0027string\u0027, email: \u0027string\u0027, domains: \u0027array\u0027 },\n })\n\n // Router: the model picks one route by its description; wire with triage..to(...).\n const triage = router(\u0027Triage\u0027, {\n context: start.message,\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n routes: {\n support: \u0027A customer asking about an existing order\u0027,\n sales: \u0027A prospect asking about pricing or a demo\u0027,\n },\n })\n\n // Agent tools: a workspace custom tool, one tool of an MCP server, an integration operation\n // (.tool.; the params given here are fixed, the model fills the rest) and\n // another workflow.\n const support = agent(\u0027Support Agent\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Answer the customer. Use your tools when they help.\u0027 },\n { role: \u0027user\u0027, content: start.message },\n ],\n tools: [\n customTool(\u0027lookup-order\u0027),\n mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027),\n slack.tool.sendMessage({ credential: credential(\u0027ops-slack\u0027), channel: \u0027support-urgent\u0027 }),\n childWorkflow(\u0027enrich-lead\u0027).asTool(),\n ],\n })\n\n // Child workflow: inputMapping is checked against the child\u0027s start inputs. Its output is\n // enrich.result (untyped JSON): the child\u0027s response block output, so a field of the child\u0027s\n // response body is enrich.result.data..\n const enrich = runWorkflow(\u0027Enrich Lead\u0027, {\n workflowId: childWorkflow(\u0027enrich-lead\u0027),\n inputMapping: { email: start.email },\n })\n\n // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its\n // position; each.results lists every branch\u0027s output once all finish. (loop.forEach is the\n // sequential form.) In a function code file inside the body, the same values are\n // $ref.parallel.currentItem and $ref.parallel.index.\n const each = parallel.collection(\u0027Each Domain\u0027, { collection: start.domains }, (p) => {\n const brief = agent(\u0027Company Brief\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Describe ${p.currentItem} in two sentences.` }],\n })\n p.to(brief)\n })\n\n const answer = response(\u0027Answer\u0027, { body: { answer: support.content } })\n const briefs = response(\u0027Briefs\u0027, {\n body: { lead: t`${enrich.result}`, briefs: t`${each.results}` },\n })\n\n start.to(triage)\n triage.support.to(support)\n support.to(answer)\n triage.sales.to(enrich)\n enrich.to(each)\n each.to(briefs)\n }\n)\n","cookbook.ts":"// @sim-sdk 1\nimport {\n agent,\n condition,\n credential,\n env,\n fn,\n human,\n js,\n knowledge,\n knowledgeBase,\n loop,\n response,\n slack,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `orders`, `policies`, `ops-slack` and\n// ANTHROPIC_API_KEY stand in for this workspace\u0027s resources. `sim workflows source resources`\n// lists the real keys, and .sim/sdk/workspace.d.ts types them.\nexport default workflow(\u0027Cookbook\u0027, { description: \u0027One example of each common block.\u0027 }, () => {\n // Triggers: trigger.start (API/manual input), trigger.schedule, trigger.webhook.\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, amount: \u0027number\u0027 } })\n const nightly = trigger.schedule(\u0027Nightly\u0027, {\n scheduleType: \u0027daily\u0027,\n dailyTime: \u002702:00\u0027,\n timezone: \u0027UTC\u0027,\n })\n\n // Agent: structured output via responseFormat; its fields become outputs (check.risk).\n // apiKey: needed on self-hosted Sim; hosted Sim supplies one.\n const check = agent(\u0027Check Order\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Rate the fraud risk of an order as low, med or high.\u0027 },\n { role: \u0027user\u0027, content: t`Order ${start.orderId} for ${start.amount}` },\n ],\n responseFormat: {\n name: \u0027risk\u0027,\n strict: true,\n schema: {\n type: \u0027object\u0027,\n properties: {\n risk: { type: \u0027string\u0027, enum: [\u0027low\u0027, \u0027med\u0027, \u0027high\u0027] },\n reason: { type: \u0027string\u0027 },\n },\n required: [\u0027risk\u0027, \u0027reason\u0027],\n additionalProperties: false,\n },\n },\n })\n\n // Condition: one branch per key, `else: true` last; wire with route..to(...).\n const route = condition(\u0027Route Risk\u0027, {\n high: js`${check.risk} === \u0027high\u0027`,\n med: js`${check.risk} === \u0027med\u0027`,\n else: true,\n })\n\n // Function: inline JavaScript; reference outputs with ${...}. Result is fn.result.\n const shape = fn(\u0027Shape\u0027, {\n code: js`return { id: ${start.orderId}, cents: Math.round(${start.amount} * 100) }`,\n })\n\n // Tables: query rows (each row is { id, data: { column } }) and insert a row.\n const recent = table.queryRows(\u0027Recent Orders\u0027, {\n tableId: table(\u0027orders\u0027),\n filterInput: { all: [{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027open\u0027 }] },\n limit: 50,\n })\n const save = table.insertRow(\u0027Save Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027, risk: check.risk },\n })\n // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else\n // inserts one. data is keyed by column name, as for insertRow.\n const touch = table.upsertRow(\u0027Touch Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027seen\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n\n // Knowledge base search: results is the list of matching chunks.\n const docs = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: check.reason,\n topK: 3,\n })\n\n // Slack: a saved credential by key (see .sim/sdk/workspace.d.ts).\n const alert = slack.sendMessage(\u0027Alert Ops\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-alerts\u0027,\n messageFormat: \u0027text\u0027,\n text: t`High-risk order ${start.orderId}: ${check.reason}`,\n })\n\n // Human in the loop: inputFormat is the form; answers are approval.submission..\n const approval = human(\u0027Manager Review\u0027, {\n builderData: [{ name: \u0027orderId\u0027, type: \u0027string\u0027, value: start.orderId }],\n inputFormat: { approved: { type: \u0027boolean\u0027, required: true }, note: \u0027string\u0027 },\n })\n const decided = condition(\u0027Approved\u0027, {\n yes: js`${approval.submission.approved} === true`,\n else: true,\n })\n\n // Loop over a list: p.currentItem is one element and p.index its position; the loop\u0027s results\n // is the list of iteration outputs. In js`` code a reference is the value itself, not text\n // spliced in: write it where an expression goes, never inside quotes (\u0027${x}\u0027 would give the\n // JSON, quotes included). A function code file (code: codeFile(\u0027./functions/line.js\u0027)) reads\n // other blocks as $ref.. ($ref.recentorders.rows) and, inside the loop body,\n // the iteration as $ref.loop.currentItem and $ref.loop.index.\n const each = loop.forEach(\u0027Each Order\u0027, { collection: recent.rows }, (p) => {\n const line = fn(\u0027Line\u0027, {\n code: js`return ${p.currentItem.data.orderId} + \u0027: \u0027 + ${p.currentItem.data.status}`,\n })\n p.to(line)\n })\n const report = agent(\u0027Report\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Summarize these orders in 3 lines:\\n${each.results}` }],\n })\n const post = slack.sendMessage(\u0027Post Report\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-daily\u0027,\n messageFormat: \u0027text\u0027,\n text: report.content,\n })\n\n // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text.\n // body is the short form of the editor\u0027s JSON mode: { dataMode: \u0027json\u0027, data } as below.\n const reply = response(\u0027Respond\u0027, { body: { risk: check.risk, id: t`${shape.result.id}` } })\n const rejected = response(\u0027Respond Rejected\u0027, {\n dataMode: \u0027json\u0027,\n data: { status: \u0027rejected\u0027 },\n })\n\n // Wiring: a.to(b) chains; a block can fan out to several targets.\n start.to(check)\n check.to(save)\n save.to(touch)\n touch.to(route)\n route.high.to(alert)\n alert.to(approval)\n approval.to(decided)\n decided.yes.to(shape)\n decided.else.to(rejected)\n route.med.to(docs)\n docs.to(shape)\n route.else.to(shape)\n shape.to(reply)\n nightly.to(recent)\n recent.to(each)\n each.to(report)\n report.to(post)\n})\n","integrations.ts":"// @sim-sdk 1\nimport {\n api,\n credential,\n env,\n gmail,\n response,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `leads`, `ops-gmail`, CLEARBIT_KEY and\n// LEADS_WEBHOOK_TOKEN stand in for this workspace\u0027s resources (.sim/sdk/workspace.d.ts).\n// Integration builders are named by service, not block type: `gmail_v2` is `gmail.*`, and a\n// hidden older version lives under `legacy.*`. .sim/sdk/INDEX.md lists every builder.\nexport default workflow(\n \u0027Cookbook: integrations\u0027,\n { description: \u0027Webhook, weekday schedule, HTTP with headers, table update, Gmail, error path.\u0027 },\n () => {\n // Webhook trigger: inputFormat types the posted JSON fields (hook.leadId). With requireAuth\n // the caller must send the token; keep it in an env var.\n const hook = trigger.webhook(\u0027Lead Webhook\u0027, {\n requireAuth: true,\n token: env.LEADS_WEBHOOK_TOKEN,\n inputFormat: { leadId: \u0027string\u0027, email: \u0027string\u0027, domain: \u0027string\u0027 },\n })\n\n // Schedule: no weekday preset exists, so scheduleType \u0027custom\u0027 takes a 5-field cron.\n const weekdays = trigger.schedule(\u0027Weekdays 8am\u0027, {\n scheduleType: \u0027custom\u0027,\n cronExpression: \u00270 8 * * 1-5\u0027,\n timezone: \u0027America/New_York\u0027,\n })\n\n // HTTP request: headers (and query params) are table rows, { cells: { Key, Value } }.\n const lookup = api(\u0027Company Lookup\u0027, {\n url: t`https://company.clearbit.com/v2/companies/find?domain=${hook.domain}`,\n method: \u0027GET\u0027,\n headers: [{ cells: { Key: \u0027Authorization\u0027, Value: t`Bearer ${env.CLEARBIT_KEY}` } }],\n })\n\n // Update one row by id: data holds only the columns to change. lookup.data is untyped JSON,\n // so a text field from it is wrapped in t``.\n const save = table.updateRowById(\u0027Save Company\u0027, {\n tableId: table(\u0027leads\u0027),\n rowId: hook.leadId,\n data: { company: t`${lookup.data.name}`, enriched: true },\n })\n\n // Gmail (gmail_v2): send one email with a saved Google credential.\n const welcome = gmail.sendEmail(\u0027Welcome Email\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: hook.email,\n subject: \u0027Welcome aboard\u0027,\n body: t`Thanks for signing up from ${hook.domain}.`,\n })\n\n // Query rows, then email them as one digest. A typed column filter: { field, op, value }.\n const pending = table.queryRows(\u0027Pending Leads\u0027, {\n tableId: table(\u0027leads\u0027),\n filterInput: { all: [{ field: \u0027enriched\u0027, op: \u0027eq\u0027, value: false }] },\n limit: 100,\n })\n const digest = gmail.sendEmail(\u0027Pending Digest\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: \u0027ops@example.com\u0027,\n subject: \u0027Leads still to enrich\u0027,\n body: t`${pending.rows}`,\n })\n\n // Error path: x.onError(y) runs y when x fails, instead of failing the run; y reads the\n // failure message as x.error.\n const failed = response(\u0027Lookup Failed\u0027, {\n body: { ok: false, error: lookup.error },\n status: 502,\n })\n const done = response(\u0027Done\u0027, { body: { ok: true, row: save.row } })\n\n hook.to(lookup)\n lookup.to(save)\n lookup.onError(failed)\n save.to(welcome)\n welcome.to(done)\n weekdays.to(pending)\n pending.to(digest)\n }\n)\n"} +export const COOKBOOK_EXAMPLES: Readonly> = {"agents.ts":"// @sim-sdk 1\nimport {\n agent,\n childWorkflow,\n credential,\n customTool,\n env,\n mcp,\n parallel,\n response,\n router,\n runWorkflow,\n slack,\n t,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `lookup-order`, `linear`, `ops-slack`,\n// `enrich-lead` and ANTHROPIC_API_KEY stand in for this workspace\u0027s resources\n// (.sim/sdk/workspace.d.ts; `sim workflows source resources` lists the real keys).\nexport default workflow(\n \u0027Cookbook: agents and subflows\u0027,\n { description: \u0027Router, agent tools, a child workflow and a parallel fan-out.\u0027 },\n () => {\n const start = trigger.start(\u0027Start\u0027, {\n inputFormat: { message: \u0027string\u0027, email: \u0027string\u0027, domains: \u0027array\u0027 },\n })\n\n // Router: the model picks one route by its description; wire with triage..to(...).\n const triage = router(\u0027Triage\u0027, {\n context: start.message,\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n routes: {\n support: \u0027A customer asking about an existing order\u0027,\n sales: \u0027A prospect asking about pricing or a demo\u0027,\n },\n })\n\n // Agent tools: a workspace custom tool, one tool of an MCP server, an integration operation\n // (.tool.; the params given here are fixed, the model fills the rest) and\n // another workflow.\n const support = agent(\u0027Support Agent\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Answer the customer. Use your tools when they help.\u0027 },\n { role: \u0027user\u0027, content: start.message },\n ],\n tools: [\n customTool(\u0027lookup-order\u0027),\n mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027),\n slack.tool.sendMessage({ credential: credential(\u0027ops-slack\u0027), channel: \u0027support-urgent\u0027 }),\n childWorkflow(\u0027enrich-lead\u0027).asTool(),\n ],\n })\n\n // Child workflow: inputMapping is checked against the child\u0027s start inputs. Its output is\n // enrich.result (untyped JSON): the child\u0027s response block output, so a field of the child\u0027s\n // response body is enrich.result.data..\n const enrich = runWorkflow(\u0027Enrich Lead\u0027, {\n workflowId: childWorkflow(\u0027enrich-lead\u0027),\n inputMapping: { email: start.email },\n })\n\n // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its\n // position; each.results lists every branch\u0027s output once all finish. (loop.forEach is the\n // sequential form.) In a function code file inside the body, the same values are\n // $ref.parallel.currentItem and $ref.parallel.index.\n const each = parallel.collection(\u0027Each Domain\u0027, { collection: start.domains }, (p) => {\n const brief = agent(\u0027Company Brief\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Describe ${p.currentItem} in two sentences.` }],\n })\n p.to(brief)\n })\n\n const answer = response(\u0027Answer\u0027, { body: { answer: support.content } })\n const briefs = response(\u0027Briefs\u0027, {\n body: { lead: t`${enrich.result}`, briefs: t`${each.results}` },\n })\n\n start.to(triage)\n triage.support.to(support)\n support.to(answer)\n triage.sales.to(enrich)\n enrich.to(each)\n each.to(briefs)\n }\n)\n","cookbook.ts":"// @sim-sdk 1\nimport {\n agent,\n condition,\n credential,\n env,\n fn,\n human,\n js,\n knowledge,\n knowledgeBase,\n loop,\n response,\n slack,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `orders`, `policies`, `ops-slack` and\n// ANTHROPIC_API_KEY stand in for this workspace\u0027s resources. `sim workflows source resources`\n// lists the real keys, and .sim/sdk/workspace.d.ts types them.\nexport default workflow(\u0027Cookbook\u0027, { description: \u0027One example of each common block.\u0027 }, () => {\n // Triggers: trigger.start (API/manual input), trigger.schedule, trigger.webhook.\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, amount: \u0027number\u0027 } })\n const nightly = trigger.schedule(\u0027Nightly\u0027, {\n scheduleType: \u0027daily\u0027,\n dailyTime: \u002702:00\u0027,\n timezone: \u0027UTC\u0027,\n })\n\n // Agent: structured output via responseFormat; its fields become outputs (check.risk).\n // apiKey: needed on self-hosted Sim; hosted Sim supplies one.\n const check = agent(\u0027Check Order\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Rate the fraud risk of an order as low, med or high.\u0027 },\n { role: \u0027user\u0027, content: t`Order ${start.orderId} for ${start.amount}` },\n ],\n responseFormat: {\n name: \u0027risk\u0027,\n strict: true,\n schema: {\n type: \u0027object\u0027,\n properties: {\n risk: { type: \u0027string\u0027, enum: [\u0027low\u0027, \u0027med\u0027, \u0027high\u0027] },\n reason: { type: \u0027string\u0027 },\n },\n required: [\u0027risk\u0027, \u0027reason\u0027],\n additionalProperties: false,\n },\n },\n })\n\n // Condition: one branch per key, `else: true` last; wire with route..to(...).\n const route = condition(\u0027Route Risk\u0027, {\n high: js`${check.risk} === \u0027high\u0027`,\n med: js`${check.risk} === \u0027med\u0027`,\n else: true,\n })\n\n // Function: inline JavaScript; reference outputs with ${...}. Result is fn.result.\n const shape = fn(\u0027Shape\u0027, {\n code: js`return { id: ${start.orderId}, cents: Math.round(${start.amount} * 100) }`,\n })\n\n // Tables: query rows (each row is { id, data: { column } }) and insert a row.\n const recent = table.queryRows(\u0027Recent Orders\u0027, {\n tableId: table(\u0027orders\u0027),\n filterInput: { all: [{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027open\u0027 }] },\n limit: 50,\n })\n const save = table.insertRow(\u0027Save Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027 },\n })\n // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else\n // inserts one. data is keyed by column name, as for insertRow.\n const touch = table.upsertRow(\u0027Touch Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027answered\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n\n // Knowledge base search: results is the list of matching chunks.\n const docs = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: check.reason,\n topK: 3,\n })\n\n // Slack: a saved credential by key (see .sim/sdk/workspace.d.ts).\n const alert = slack.sendMessage(\u0027Alert Ops\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-alerts\u0027,\n messageFormat: \u0027text\u0027,\n text: t`High-risk order ${start.orderId}: ${check.reason}`,\n })\n\n // Human in the loop: inputFormat is the form; answers are approval.submission..\n const approval = human(\u0027Manager Review\u0027, {\n builderData: [{ name: \u0027orderId\u0027, type: \u0027string\u0027, value: start.orderId }],\n inputFormat: { approved: { type: \u0027boolean\u0027, required: true }, note: \u0027string\u0027 },\n })\n const decided = condition(\u0027Approved\u0027, {\n yes: js`${approval.submission.approved} === true`,\n else: true,\n })\n\n // Loop over a list: p.currentItem is one element and p.index its position; the loop\u0027s results\n // is the list of iteration outputs. In js`` code a reference is the value itself, not text\n // spliced in: write it where an expression goes, never inside quotes (\u0027${x}\u0027 would give the\n // JSON, quotes included). A function code file (code: codeFile(\u0027./functions/line.js\u0027)) reads\n // other blocks as $ref.. ($ref.recentorders.rows) and, inside the loop body,\n // the iteration as $ref.loop.currentItem and $ref.loop.index.\n const each = loop.forEach(\u0027Each Order\u0027, { collection: recent.rows }, (p) => {\n const line = fn(\u0027Line\u0027, {\n code: js`return ${p.currentItem.data.orderId} + \u0027: \u0027 + ${p.currentItem.data.status}`,\n })\n p.to(line)\n })\n const report = agent(\u0027Report\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Summarize these orders in 3 lines:\\n${each.results}` }],\n })\n const post = slack.sendMessage(\u0027Post Report\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-daily\u0027,\n messageFormat: \u0027text\u0027,\n text: report.content,\n })\n\n // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text.\n // body is the short form of the editor\u0027s JSON mode: { dataMode: \u0027json\u0027, data } as below.\n const reply = response(\u0027Respond\u0027, { body: { risk: check.risk, id: t`${shape.result.id}` } })\n const rejected = response(\u0027Respond Rejected\u0027, {\n dataMode: \u0027json\u0027,\n data: { status: \u0027rejected\u0027 },\n })\n\n // Wiring: a.to(b) chains; a block can fan out to several targets.\n start.to(check)\n check.to(save)\n save.to(touch)\n touch.to(route)\n route.high.to(alert)\n alert.to(approval)\n approval.to(decided)\n decided.yes.to(shape)\n decided.else.to(rejected)\n route.med.to(docs)\n docs.to(shape)\n route.else.to(shape)\n shape.to(reply)\n nightly.to(recent)\n recent.to(each)\n each.to(report)\n report.to(post)\n})\n","integrations.ts":"// @sim-sdk 1\nimport {\n api,\n credential,\n env,\n gmail,\n response,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `leads`, `ops-gmail`, CLEARBIT_KEY and\n// LEADS_WEBHOOK_TOKEN stand in for this workspace\u0027s resources (.sim/sdk/workspace.d.ts).\n// Integration builders are named by service, not block type: `gmail_v2` is `gmail.*`, and a\n// hidden older version lives under `legacy.*`. .sim/sdk/INDEX.md lists every builder.\nexport default workflow(\n \u0027Cookbook: integrations\u0027,\n { description: \u0027Webhook, weekday schedule, HTTP with headers, table update, Gmail, error path.\u0027 },\n () => {\n // Webhook trigger: inputFormat types the posted JSON fields (hook.leadId). With requireAuth\n // the caller must send the token; keep it in an env var.\n const hook = trigger.webhook(\u0027Lead Webhook\u0027, {\n requireAuth: true,\n token: env.LEADS_WEBHOOK_TOKEN,\n inputFormat: { leadId: \u0027string\u0027, email: \u0027string\u0027, domain: \u0027string\u0027 },\n })\n\n // Schedule: no weekday preset exists, so scheduleType \u0027custom\u0027 takes a 5-field cron.\n const weekdays = trigger.schedule(\u0027Weekdays 8am\u0027, {\n scheduleType: \u0027custom\u0027,\n cronExpression: \u00270 8 * * 1-5\u0027,\n timezone: \u0027America/New_York\u0027,\n })\n\n // HTTP request: headers (and query params) are table rows, { cells: { Key, Value } }.\n const lookup = api(\u0027Company Lookup\u0027, {\n url: t`https://company.clearbit.com/v2/companies/find?domain=${hook.domain}`,\n method: \u0027GET\u0027,\n headers: [{ cells: { Key: \u0027Authorization\u0027, Value: t`Bearer ${env.CLEARBIT_KEY}` } }],\n })\n\n // Update one row by id: data holds only the columns to change. lookup.data is untyped JSON,\n // so a text field from it is wrapped in t``.\n const save = table.updateRowById(\u0027Save Company\u0027, {\n tableId: table(\u0027leads\u0027),\n rowId: hook.leadId,\n data: { company: t`${lookup.data.name}`, enriched: true },\n })\n\n // Gmail (gmail_v2): send one email with a saved Google credential.\n const welcome = gmail.sendEmail(\u0027Welcome Email\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: hook.email,\n subject: \u0027Welcome aboard\u0027,\n body: t`Thanks for signing up from ${hook.domain}.`,\n })\n\n // Query rows, then email them as one digest. A typed column filter: { field, op, value }.\n const pending = table.queryRows(\u0027Pending Leads\u0027, {\n tableId: table(\u0027leads\u0027),\n filterInput: { all: [{ field: \u0027enriched\u0027, op: \u0027eq\u0027, value: false }] },\n limit: 100,\n })\n const digest = gmail.sendEmail(\u0027Pending Digest\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: \u0027ops@example.com\u0027,\n subject: \u0027Leads still to enrich\u0027,\n body: t`${pending.rows}`,\n })\n\n // Error path: x.onError(y) runs y when x fails, instead of failing the run; y reads the\n // failure message as x.error.\n const failed = response(\u0027Lookup Failed\u0027, {\n body: { ok: false, error: lookup.error },\n status: 502,\n })\n const done = response(\u0027Done\u0027, { body: { ok: true, row: save.row } })\n\n hook.to(lookup)\n lookup.to(save)\n lookup.onError(failed)\n save.to(welcome)\n welcome.to(done)\n weekdays.to(pending)\n pending.to(digest)\n }\n)\n"} diff --git a/packages/workflow-sdk/src/codegen/workspace-cookbook-text.generated.ts b/packages/workflow-sdk/src/codegen/workspace-cookbook-text.generated.ts index 094ea0fec1e..cb5b9c99dc2 100644 --- a/packages/workflow-sdk/src/codegen/workspace-cookbook-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/workspace-cookbook-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from cookbook/workspace; do not edit. /** The example workspace directory, path → text: one resource of each kind and a workflow using them. */ -export const WORKSPACE_COOKBOOK: Readonly> = {"credentials.ts":"// @sim-sdk 1\nimport { defineCredentials } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// credentials.ts: the saved credentials workflows use as credential(\u0027\u0027), by provider only.\n// An apply binds each key to this workspace\u0027s credential of that provider. The provider is the\n// id `sim credentials connect ` takes (Gmail is \u0027google-email\u0027); a block\u0027s .d.ts names\n// the ones its credential accepts (CredentialKeyFor<\u0027google-email\u0027 | …>). `name` picks one of\n// several credentials of a provider by its display name.\nexport default defineCredentials({\n slack: { provider: \u0027slack\u0027 },\n gmail: { provider: \u0027google-email\u0027, name: \u0027Support inbox\u0027 },\n})\n","deployments/support.ts":"// @sim-sdk 1\nimport { defineDeployment } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// deployments/.ts deploys workflows// after the apply writes it.\n// \u0027draft\u0027 publishes the draft whenever it differs from the live version; \u0027pinned\u0027 never does.\nexport default defineDeployment({\n live: \u0027draft\u0027,\n api: { public: false },\n chat: {\n identifier: \u0027support-example\u0027,\n title: \u0027Support\u0027,\n // A password is a secret by name, never its value: auth: { password: env.CHAT_PASSWORD }.\n auth: { emails: [\u0027@example.com\u0027] },\n outputs: [{ block: \u0027Answer\u0027, path: \u0027content\u0027 }],\n },\n})\n","files/templates/reply.md":"Hi {{name}},\n\nThanks for reaching out about order {{orderId}}.\n","knowledge/policies/docs/refunds.md":"# Refunds\n\nOrders can be refunded within 30 days of delivery. Refunds go back to the original payment method.\n","knowledge/policies/knowledge.ts":"// @sim-sdk 1\nimport { defineKnowledgeBase } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// knowledge//knowledge.ts, with one file per document in knowledge//docs/ (flat, each\n// at most 10 MB). A workflow names it as knowledgeBase(\u0027policies\u0027).\nexport default defineKnowledgeBase({\n name: \u0027Policies\u0027,\n description: \u0027Refund and shipping policies\u0027,\n chunking: { maxSize: 1024, minSize: 100, overlap: 200 },\n})\n","mcp/docs.ts":"// @sim-sdk 1\nimport { defineMcpServer, env } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// mcp/.ts: an MCP server the workspace\u0027s agents call tools on. A workflow names it by key\n// and a tool by name: mcp(\u0027docs\u0027).tool(\u0027search_docs\u0027). A credential header holds an env reference,\n// never the secret itself; `stored()` keeps the value the server already holds. The server\u0027s id\n// derives from its URL, so a `url` with another host or path replaces the server; a new query\n// string updates it in place.\nexport default defineMcpServer({\n name: \u0027Docs\u0027,\n url: \u0027https://docs.example.com/mcp\u0027,\n headers: { Authorization: \u0027Bearer {{DOCS_MCP_TOKEN}}\u0027, \u0027X-Api-Key\u0027: env.DOCS_MCP_KEY },\n timeout: 10000,\n})\n","secrets.ts":"// @sim-sdk 1\nimport { defineSecrets } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// secrets.ts: the workspace secrets workflows read as env.NAME, by name and description only.\n// A value never appears here: set one with `sim secrets set NAME --scope workspace`.\nexport default defineSecrets({\n ANTHROPIC_API_KEY: { description: \u0027Model access for the support agent\u0027 },\n DOCS_MCP_KEY: { description: \u0027API key the docs MCP server checks\u0027 },\n DOCS_MCP_TOKEN: { description: \u0027Bearer token for the docs MCP server\u0027 },\n ORDERS_API_KEY: { description: \u0027API key the lookup-order tool sends to the orders service\u0027 },\n})\n","skills/tone.md":"---\nname: tone\ndescription: \"Answer in the support team\u0027s voice: short, warm, specific.\"\n---\nWrite like a person, not a policy. Lead with the answer, then the one detail that matters.\n","tables/orders.ts":"// @sim-sdk 1\nimport { column, defineTable } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// tables/.ts: the key (`orders`) is how a workflow names it: table(\u0027orders\u0027). Its rows stay\n// out of source (see plans.ts to opt in). To rename a column keep its key and set `name`.\nexport default defineTable({\n name: \u0027orders\u0027,\n description: \u0027Order questions the support workflow answered\u0027,\n columns: {\n orderId: column.string({ required: true }),\n status: column.select({ options: [\u0027open\u0027, \u0027answered\u0027] }),\n total: column.number(),\n },\n})\n","tables/plans.rows.jsonl":"{\"code\":\"solo\",\"seats\":1,\"tier\":\"basic\"}\n{\"code\":\"team\",\"seats\":10,\"tier\":\"pro\"}\n","tables/plans.ts":"// @sim-sdk 1\nimport { column, defineTable } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// Managed rows: tables/plans.rows.jsonl is the table\u0027s whole content, one row per line keyed by\n// column key, each matched to its stored row by the unique `code` column. Removing a line deletes\n// that row (with --allow-delete). Use `{ mode: \u0027seed\u0027 }` instead to write rows only when the table\n// is created.\nexport default defineTable({\n name: \u0027plans\u0027,\n description: \u0027Plans the billing workflow prices against\u0027,\n columns: {\n code: column.string({ required: true, unique: true }),\n seats: column.number(),\n tier: column.select({ options: [\u0027basic\u0027, \u0027pro\u0027] }),\n },\n rows: { mode: \u0027managed\u0027, key: \u0027code\u0027 },\n})\n","tools/lookup-order.js":"// Each schema parameter is a variable; $env.NAME reads an environment variable by name, so the\n// value never appears in source.\nconst response = await fetch(`https://orders.example.com/api/orders/${encodeURIComponent(orderId)}`, {\n headers: { Authorization: `Bearer ${$env.ORDERS_API_KEY}` },\n})\nreturn await response.json()\n","tools/lookup-order.ts":"// @sim-sdk 1\nimport { codeFile, defineTool } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// tools/.ts, with its code in tools/.js.\n// A workflow names it as customTool(\u0027lookup-order\u0027).\nexport default defineTool({\n title: \u0027Lookup order\u0027,\n schema: {\n type: \u0027function\u0027,\n function: {\n name: \u0027lookup_order\u0027,\n description: \u0027Find an order by id.\u0027,\n parameters: {\n type: \u0027object\u0027,\n properties: { orderId: { type: \u0027string\u0027 } },\n required: [\u0027orderId\u0027],\n },\n },\n },\n code: codeFile(\u0027./lookup-order.js\u0027),\n})\n","workflows/support/workflow.ts":"// @sim-sdk 1\nimport {\n agent,\n customTool,\n env,\n knowledge,\n knowledgeBase,\n skill,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// workflows//workflow.ts: a workflow source directory. It names the resources this\n// directory declares by key, and one apply creates them before the workflow that uses them.\nexport default workflow(\u0027Support\u0027, { description: \u0027Answers an order question.\u0027 }, () => {\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, question: \u0027string\u0027 } })\n const policy = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: start.question,\n topK: 3,\n })\n const answer = agent(\u0027Answer\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n // An environment variable by name; its value never appears in source.\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: t`Answer from these policies:\\n${policy.results}` },\n { role: \u0027user\u0027, content: t`Order ${start.orderId}: ${start.question}` },\n ],\n tools: [customTool(\u0027lookup-order\u0027)],\n skills: [skill(\u0027tone\u0027)],\n })\n const log = table.insertRow(\u0027Log Question\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027answered\u0027 },\n })\n\n start.to(policy)\n policy.to(answer)\n answer.to(log)\n})\n"} +export const WORKSPACE_COOKBOOK: Readonly> = {"credentials.ts":"// @sim-sdk 1\nimport { defineCredentials } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// credentials.ts: the saved credentials workflows use as credential(\u0027\u0027), by provider only.\n// An apply binds each key to this workspace\u0027s credential of that provider. The provider is the\n// id `sim credentials connect ` takes (Gmail is \u0027google-email\u0027); a block\u0027s .d.ts names\n// the ones its credential accepts (CredentialKeyFor<\u0027google-email\u0027 | …>). `name` picks one of\n// several credentials of a provider by its display name.\nexport default defineCredentials({\n slack: { provider: \u0027slack\u0027 },\n gmail: { provider: \u0027google-email\u0027, name: \u0027Support inbox\u0027 },\n})\n","deployments/support.ts":"// @sim-sdk 1\nimport { defineDeployment } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// deployments/.ts deploys workflows// after the apply writes it.\n// \u0027draft\u0027 publishes the draft whenever it differs from the live version; \u0027pinned\u0027 never does.\nexport default defineDeployment({\n live: \u0027draft\u0027,\n api: { public: false },\n chat: {\n identifier: \u0027support-example\u0027,\n title: \u0027Support\u0027,\n // A password is a secret by name, never its value: auth: { password: env.CHAT_PASSWORD }.\n auth: { emails: [\u0027@example.com\u0027] },\n outputs: [{ block: \u0027Answer\u0027, path: \u0027content\u0027 }],\n },\n})\n","files/templates/reply.md":"Hi {{name}},\n\nThanks for reaching out about order {{orderId}}.\n","knowledge/policies/docs/refunds.md":"# Refunds\n\nOrders can be refunded within 30 days of delivery. Refunds go back to the original payment method.\n","knowledge/policies/knowledge.ts":"// @sim-sdk 1\nimport { defineKnowledgeBase } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// knowledge//knowledge.ts, with one file per document in knowledge//docs/ (flat, each\n// at most 10 MB). A workflow names it as knowledgeBase(\u0027policies\u0027).\nexport default defineKnowledgeBase({\n name: \u0027Policies\u0027,\n description: \u0027Refund and shipping policies\u0027,\n chunking: { maxSize: 1024, minSize: 100, overlap: 200 },\n})\n","mcp/docs.ts":"// @sim-sdk 1\nimport { defineMcpServer, env } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// mcp/.ts: an MCP server the workspace\u0027s agents call tools on. A workflow names it by key\n// and a tool by name: mcp(\u0027docs\u0027).tool(\u0027search_docs\u0027). A credential header holds an env reference,\n// never the secret itself; `stored()` keeps the value the server already holds. The server\u0027s id\n// derives from its URL, so a `url` with another host or path replaces the server; a new query\n// string updates it in place.\nexport default defineMcpServer({\n name: \u0027Docs\u0027,\n url: \u0027https://docs.example.com/mcp\u0027,\n headers: { Authorization: \u0027Bearer {{DOCS_MCP_TOKEN}}\u0027, \u0027X-Api-Key\u0027: env.DOCS_MCP_KEY },\n timeout: 10000,\n})\n","secrets.ts":"// @sim-sdk 1\nimport { defineSecrets } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// secrets.ts: the workspace secrets workflows read as env.NAME, by name and description only.\n// A value never appears here: set one with `sim secrets set NAME --scope workspace`.\nexport default defineSecrets({\n ANTHROPIC_API_KEY: { description: \u0027Model access for the support agent\u0027 },\n DOCS_MCP_KEY: { description: \u0027API key the docs MCP server checks\u0027 },\n DOCS_MCP_TOKEN: { description: \u0027Bearer token for the docs MCP server\u0027 },\n ORDERS_API_KEY: { description: \u0027API key the lookup-order tool sends to the orders service\u0027 },\n})\n","skills/tone.md":"---\nname: tone\ndescription: \"Answer in the support team\u0027s voice: short, warm, specific.\"\n---\nWrite like a person, not a policy. Lead with the answer, then the one detail that matters.\n","tables/orders.ts":"// @sim-sdk 1\nimport { column, defineTable } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// tables/.ts: the key (`orders`) is how a workflow names it: table(\u0027orders\u0027). Its rows stay\n// out of source (see plans.ts to opt in). To rename a column keep its key and set `name`.\nexport default defineTable({\n name: \u0027orders\u0027,\n description: \u0027Order questions the support workflow answered\u0027,\n columns: {\n orderId: column.string({ required: true, unique: true }),\n status: column.select({ options: [\u0027open\u0027, \u0027answered\u0027] }),\n total: column.number(),\n },\n})\n","tables/plans.rows.jsonl":"{\"code\":\"solo\",\"seats\":1,\"tier\":\"basic\"}\n{\"code\":\"team\",\"seats\":10,\"tier\":\"pro\"}\n","tables/plans.ts":"// @sim-sdk 1\nimport { column, defineTable } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// Managed rows: tables/plans.rows.jsonl is the table\u0027s whole content, one row per line keyed by\n// column key, each matched to its stored row by the unique `code` column. Removing a line deletes\n// that row (with --allow-delete). Use `{ mode: \u0027seed\u0027 }` instead to write rows only when the table\n// is created.\nexport default defineTable({\n name: \u0027plans\u0027,\n description: \u0027Plans the billing workflow prices against\u0027,\n columns: {\n code: column.string({ required: true, unique: true }),\n seats: column.number(),\n tier: column.select({ options: [\u0027basic\u0027, \u0027pro\u0027] }),\n },\n rows: { mode: \u0027managed\u0027, key: \u0027code\u0027 },\n})\n","tools/lookup-order.js":"// Each schema parameter is a variable; $env.NAME reads an environment variable by name, so the\n// value never appears in source.\nconst response = await fetch(`https://orders.example.com/api/orders/${encodeURIComponent(orderId)}`, {\n headers: { Authorization: `Bearer ${$env.ORDERS_API_KEY}` },\n})\nreturn await response.json()\n","tools/lookup-order.ts":"// @sim-sdk 1\nimport { codeFile, defineTool } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// tools/.ts, with its code in tools/.js.\n// A workflow names it as customTool(\u0027lookup-order\u0027).\nexport default defineTool({\n title: \u0027Lookup order\u0027,\n schema: {\n type: \u0027function\u0027,\n function: {\n name: \u0027lookup_order\u0027,\n description: \u0027Find an order by id.\u0027,\n parameters: {\n type: \u0027object\u0027,\n properties: { orderId: { type: \u0027string\u0027 } },\n required: [\u0027orderId\u0027],\n },\n },\n },\n code: codeFile(\u0027./lookup-order.js\u0027),\n})\n","workflows/support/workflow.ts":"// @sim-sdk 1\nimport {\n agent,\n customTool,\n env,\n knowledge,\n knowledgeBase,\n skill,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// workflows//workflow.ts: a workflow source directory. It names the resources this\n// directory declares by key, and one apply creates them before the workflow that uses them.\nexport default workflow(\u0027Support\u0027, { description: \u0027Answers an order question.\u0027 }, () => {\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, question: \u0027string\u0027 } })\n const policy = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: start.question,\n topK: 3,\n })\n const answer = agent(\u0027Answer\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n // An environment variable by name; its value never appears in source.\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: t`Answer from these policies:\\n${policy.results}` },\n { role: \u0027user\u0027, content: t`Order ${start.orderId}: ${start.question}` },\n ],\n tools: [customTool(\u0027lookup-order\u0027)],\n skills: [skill(\u0027tone\u0027)],\n })\n const log = table.insertRow(\u0027Log Question\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027answered\u0027 },\n })\n\n start.to(policy)\n policy.to(answer)\n answer.to(log)\n})\n"} From 20f16f9a5ee588ca5261aed2507cd0a7c638acd6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 06:43:45 -0800 Subject: [PATCH 35/37] fix(workflow-code): flag a loop condition reading its own iteration by display name The run resolves to loop w by normalized name, so the self-reference check compares normalized names too. --- packages/workflow-code/src/compile/blocks.ts | 4 +++- packages/workflow-code/src/compile/checks.test.ts | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 2fcce95e645..aa906c0c742 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -11,6 +11,7 @@ import { BLOCK_RETRY_MIN_TRIES, BLOCK_RETRY_MIN_WAIT_MS, type BlockRetryConfig, + normalizeWorkflowBlockName, type WorkflowBranchKind, } from '@sim/workflow-types/workflow' import { encodeAnchor } from '../anchors' @@ -1893,13 +1894,14 @@ function checkLoopCondition( if (text.trim() === '') return const at = rangeOf(ctx, property.value) const selfReads = new Set() + const ownName = normalizeWorkflowBlockName(decl.name) const runnable = text.replace(REFERENCE_CANDIDATE, (match: string, inner: string) => { if (!isLikelyWorkflowReferenceSegment(match)) return match const segments = parseStoredPath(inner) const [head, field] = segments ?? [] if ( head?.kind === 'name' && - head.name === decl.key && + normalizeWorkflowBlockName(head.name) === ownName && field?.kind === 'name' && LOOP_PROPERTIES.includes(field.name) ) { diff --git a/packages/workflow-code/src/compile/checks.test.ts b/packages/workflow-code/src/compile/checks.test.ts index 4bd0897206f..4e2a0241894 100644 --- a/packages/workflow-code/src/compile/checks.test.ts +++ b/packages/workflow-code/src/compile/checks.test.ts @@ -909,4 +909,10 @@ describe('loop conditions', () => { ]) expect(findings(whileLoop(' < 3'), 'W_REF_OUT_OF_SCOPE')).toEqual([]) }) + + it("warns on the loop's own iteration field read by its display name, which the run resolves to the loop", () => { + expect(findings(whileLoop(' < 3'), 'W_REF_OUT_OF_SCOPE')).toEqual([ + expect.objectContaining({ blockKey: 'w' }), + ]) + }) }) From fb42142cc065a2322fc2bb5cc7d595de214335b9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 06:43:46 -0800 Subject: [PATCH 36/37] fix(lint): stop a child's response check at the first else row, on a root cycle, and for a __proto__ key Rows after a condition's first else never run, so only those up to it must be wired; a root cycle never runs to the Response block; and the canonical graph is built with own properties so a block keyed __proto__ is kept. --- .../lib/workflows/dynamic-handle-topology.ts | 15 +++--- apps/sim/lib/workflows/editing/lint.test.ts | 50 +++++++++++++++++++ .../protocol/workspace-source-check.test.ts | 17 ++++++- packages/workflow-code/src/responds.ts | 14 +++--- packages/workflow-types/src/workflow.ts | 32 ++++++++++-- 5 files changed, 111 insertions(+), 17 deletions(-) diff --git a/apps/sim/lib/workflows/dynamic-handle-topology.ts b/apps/sim/lib/workflows/dynamic-handle-topology.ts index 2dd67c3e48c..fed747de911 100644 --- a/apps/sim/lib/workflows/dynamic-handle-topology.ts +++ b/apps/sim/lib/workflows/dynamic-handle-topology.ts @@ -134,8 +134,9 @@ export function getDynamicHandleRows( /** * The source handles of the branches `block` always takes one of (as `respondsOnEveryRun` reads - * canonical blocks): every route of a router, and every row of a condition with an else row (by - * stored title, as the executor finds it); none for branches never saved. `undefined` for a block + * canonical blocks): every route of a router, and a condition's rows up to its first else row (by + * stored title, as the executor finds it), which runs when none before it matches; none for a + * condition without one or branches never saved. `undefined` for a block * without branches. */ export function getAlwaysTakenBranchHandles( @@ -145,12 +146,14 @@ export function getAlwaysTakenBranchHandles( if (subBlockId === null) return undefined const stored = parseStructuredValue(block.subBlocks[subBlockId]?.value) ?? [] if (block.type === 'condition') { - const hasElse = stored.some((row) => + const elseAt = stored.findIndex((row) => isElseConditionTitle((row as { title?: unknown } | null)?.title) ) - return stored.length > 0 && hasElse - ? getConditionRows(block.id, stored).map((row) => `condition-${row.id}`) - : [] + return elseAt === -1 + ? [] + : getConditionRows(block.id, stored) + .slice(0, elseAt + 1) + .map((row) => `condition-${row.id}`) } return stored.length > 0 ? getRouterRows(block.id, stored).map((row) => `router-${row.id}`) : [] } diff --git a/apps/sim/lib/workflows/editing/lint.test.ts b/apps/sim/lib/workflows/editing/lint.test.ts index 57daec10c39..c6323fb8ccc 100644 --- a/apps/sim/lib/workflows/editing/lint.test.ts +++ b/apps/sim/lib/workflows/editing/lint.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest' import { getBlock } from '@/blocks/registry' import { getToolParams } from '@/tools/metadata' import { + alwaysEndsAtResponseBlock, collectTableBlockFieldIssues, collectWorkflowFieldIssues, collectWorkflowTableIds, @@ -113,6 +114,55 @@ function baseBlock(id: string, type: string, name: string, subBlocks: Record { + const block = (type: string, subBlocks: Record = {}) => ({ + type, + subBlocks, + }) + const edge = (source: string, target: string, sourceHandle = 'source') => ({ + source, + target, + sourceHandle, + }) + + it('needs only the branches up to the first else row, the last a run can take', () => { + const conditions = JSON.stringify([ + { id: 'g-if', title: 'if', value: 'true' }, + { id: 'g-else', title: 'else', value: '' }, + { id: 'g-after', title: 'else if', value: 'true' }, + ]) + const graph = { + blocks: { + start: block('start_trigger'), + gate: block('condition', { conditions: { value: conditions } }), + yes: block('response'), + no: block('response'), + }, + edges: [ + edge('start', 'gate'), + edge('gate', 'yes', 'condition-g-if'), + edge('gate', 'no', 'condition-g-else'), + ], + } + + expect(alwaysEndsAtResponseBlock(graph)).toBe(true) + }) + + it('is false for a root cycle, whose blocks never run to the Response block', () => { + const graph = { + blocks: { + start: block('start_trigger'), + a: block('function'), + b: block('function'), + reply: block('response'), + }, + edges: [edge('start', 'a'), edge('a', 'b'), edge('b', 'a')], + } + + expect(alwaysEndsAtResponseBlock(graph)).toBe(false) + }) +}) + describe('lintEditedWorkflowState', () => { it('reports orphan blocks but allows unconnected condition/router branches', () => { const workflowState = { diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts index 4614af28b50..7aa7b5e0441 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts @@ -549,16 +549,26 @@ describe('sim workspaces source check', () => { 'gate.else.to(other)' ) ) + writeFile( + 'workflows/proto/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { q: 'string' } })", + "const reply = response('__proto__', { body: { mobile: start.q } })", + 'start.to(reply)' + ) + ) writeFile( 'workflows/parent/workflow.ts', workflowFile( "const start = trigger.start('Start', { inputFormat: { q: 'string' } })", "const maybe = runWorkflow('Maybe', { workflowId: childWorkflow('branchy'), inputMapping: { q: start.q } })", "const always = runWorkflow('Always', { workflowId: childWorkflow('covered'), inputMapping: { q: start.q } })", - "const use = fn('Use', { code: js`return [${maybe.result.mobile}, ${always.result.mobile}]` })", + "const named = runWorkflow('Named', { workflowId: childWorkflow('proto'), inputMapping: { q: start.q } })", + "const use = fn('Use', { code: js`return [${maybe.result.mobile}, ${always.result.mobile}, ${named.result.mobile}]` })", 'start.to(maybe)', 'maybe.to(always)', - 'always.to(use)' + 'always.to(named)', + 'named.to(use)' ) ) @@ -571,6 +581,9 @@ describe('sim workspaces source check', () => { expect.objectContaining({ message: expect.stringContaining(' reads mobile'), }), + expect.objectContaining({ + message: expect.stringContaining(' reads mobile'), + }), ]) }) diff --git a/packages/workflow-code/src/responds.ts b/packages/workflow-code/src/responds.ts index 94c6b776fbd..d49676bb766 100644 --- a/packages/workflow-code/src/responds.ts +++ b/packages/workflow-code/src/responds.ts @@ -8,20 +8,22 @@ import { } from '@sim/workflow-types/workflow' import { storedTitle } from './canonicalize/branches' import type { CanonicalBlock, CanonicalWorkflow, Port } from './model' +import { setOwn } from './records' /** * The branches `block` always takes one of (as `getAlwaysTakenBranchHandles` reads stored - * blocks): every route of a router, and every row of a condition with an else row (by stored - * title, as the executor finds it); none for branches never saved. + * blocks): every route of a router, and a condition's rows up to its first else row (by stored + * title, as the executor finds it); none for a condition without one or branches never saved. */ function alwaysTakenBranches(block: CanonicalBlock): ResponseGraphBlock['branches'] { const branches = block.branches if (!branches) return undefined const rows = branches.rows ?? [] - const hasElse = rows.some((row, index) => + if (branches.kind === 'router') return rows.map((row) => row.key) + const elseAt = rows.findIndex((row, index) => isElseConditionTitle(storedTitle(branches.kind, row, index, rows.length)) ) - return branches.kind === 'condition' && !hasElse ? [] : rows.map((row) => row.key) + return elseAt === -1 ? [] : rows.slice(0, elseAt + 1).map((row) => row.key) } function portName(port: Port): string { @@ -37,12 +39,12 @@ export function respondsOnEveryRun(workflow: CanonicalWorkflow): boolean { const blocks: Record = {} for (const [key, block] of Object.entries(workflow.blocks)) { const branches = alwaysTakenBranches(block) - blocks[key] = { + setOwn(blocks, key, { type: block.type, enabled: block.enabled, parentId: block.parent, ...(branches !== undefined && { branches }), - } + }) } return alwaysEndsAtResponse( blocks, diff --git a/packages/workflow-types/src/workflow.ts b/packages/workflow-types/src/workflow.ts index e68faae560f..0d2b858a685 100644 --- a/packages/workflow-types/src/workflow.ts +++ b/packages/workflow-types/src/workflow.ts @@ -714,7 +714,8 @@ export interface ResponseGraphBlock { parentId: string | null /** * Set on a condition or router block: the branches a run always takes one of, empty when a run - * can take none (a condition without an else branch, or branches never saved). + * can take none (a condition without an else branch, or branches never saved). A condition's + * end at its first else row: the rows after it never run. */ branches?: readonly string[] } @@ -729,13 +730,29 @@ export interface ResponseGraphEdge { port: string } +/** Whether the graph of `successors` (with each target's incoming count in `pending`) has a cycle. */ +function hasCycle(successors: Map, pending: Map): boolean { + const ready = [...successors.keys()].filter((id) => !pending.has(id)) + let visited = 0 + for (let id = ready.pop(); id !== undefined; id = ready.pop()) { + visited += 1 + for (const next of successors.get(id) ?? []) { + const left = (pending.get(next) ?? 0) - 1 + pending.set(next, left) + if (left === 0) ready.push(next) + } + } + const nodes = new Set([...successors.keys(), ...pending.keys()]) + return visited < nodes.size +} + /** * Whether every run of a workflow ends at an enabled Response block at its root, so a caller's * `result` is always that block's output (`{ data, status, headers }`) rather than the output of * whichever block the run ended at. True when there is a root Response and every other root block * that runs always goes on to one that runs (its out edge, a container's end edge, or an edge from - * every branch it always takes one of): the root graph is acyclic, so every run then ends at a - * Response. + * every branch it always takes one of), and the root graph is acyclic: every run then ends at a + * Response. A root cycle never runs (its blocks wait on each other), so it makes this false. */ export function alwaysEndsAtResponse( blocks: Readonly>, @@ -745,13 +762,22 @@ export function alwaysEndsAtResponse( const block = Object.hasOwn(blocks, id) ? blocks[id] : undefined return block?.enabled === true && !isWorkflowAnnotationOnlyBlockType(block.type) } + const isRoot = (id: string) => blocks[id]?.parentId === null const portsBySource = new Map>() + const successors = new Map() + const pending = new Map() for (const edge of edges) { if (!runs(edge.source) || !runs(edge.target)) continue const ports = portsBySource.get(edge.source) ?? new Set() ports.add(edge.port) portsBySource.set(edge.source, ports) + if (!isRoot(edge.source) || !isRoot(edge.target)) continue + const next = successors.get(edge.source) ?? [] + next.push(edge.target) + successors.set(edge.source, next) + pending.set(edge.target, (pending.get(edge.target) ?? 0) + 1) } + if (hasCycle(successors, pending)) return false let responds = false for (const [id, block] of Object.entries(blocks)) { if (!runs(id) || block.parentId !== null) continue From eaf21ff5589e8a42302d0946354faf42603c93fc Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sun, 22 Nov 2026 06:43:47 -0800 Subject: [PATCH 37/37] docs: make the cookbook's order writes repeatable and say where each source directory takes its workspace The orders table's orderId is unique, so the cookbook and the Support workflow upsert on it instead of inserting a second row for the same order. --- .../src/commands/protocol/source-loop-help.ts | 7 ++++--- .../src/commands/protocol/workflow-dir.ts | 2 +- packages/sim-cli/src/program.ts | 6 ++++-- .../workflow-sdk/cookbook/examples/cookbook.ts | 16 ++++++---------- .../workspace/workflows/support/workflow.ts | 3 ++- .../src/codegen/cookbook-text.generated.ts | 2 +- .../codegen/workspace-cookbook-text.generated.ts | 2 +- 7 files changed, 19 insertions(+), 19 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index 9d1e35ce919..5f75ed958cb 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -13,9 +13,10 @@ function loopRows(rows: ReadonlyArray): string { } /** Where the commands of either group find their workspace. */ -const WORKSPACE_LINE = `Workspace: a command run on a directory reads it from .sim/base.json; any other takes -w -or SIM_WORKSPACE (export it once, or keep only the ID in a variable: a variable holding -"--workspace " is one argument, an unknown option alone and the whole ID after -w).` +const WORKSPACE_LINE = `Workspace: a directory records it (.sim/base.json, or a starter's .sim/starter.json); any other +command takes -w , SIM_WORKSPACE or the profile's (export SIM_WORKSPACE once, or keep only the +ID in a variable: one holding "--workspace " is one argument, an unknown option alone and the +whole ID after -w).` /** The status line both groups end with, for a directory at `dir`. */ function statusLine(group: string, dir: string): string { diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 786e9a25d99..18ddafa169a 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -220,7 +220,7 @@ The primer above is enough to edit; read a section here when a step needs it. ## Edit loop in detail -1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and insert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. +1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. 2. \`sim workflows source check --dir .\`: compiles offline with the server's compiler, in milliseconds. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on a missing required field, an unknown option or output path, a wrong value kind, an out-of-range value, an unwired condition or router branch or a literal secret in a block you added (\`--strict\`: in every block). It also adds the blocks the source now uses to \`tsconfig.json\`. 3. \`${typecheckCommand()}\`: about a second; catches what step 2 and the dry run do not (such as a reference to a start input the trigger does not declare). It runs the TypeScript release the declarations are built for (the directory has no \`package.json\`; plain \`bunx tsc\` would run whatever version it finds). \`tsconfig.json\` includes only the blocks the source used at the last check, get or apply: a builder from another block fails with \`has no exported member\` until you run step 2 (or use \`${typecheckCommand(TSCONFIG_FULL_FILE)}\`, every current block). The dry run is the authority: a printed line you did not edit that \`tsc\` flags and the dry run accepts is fine. 4. \`sim workflows source status --dir .\`: the files you changed (\`sim workflows source diff --dir .\` shows the edits), whether the workflow changed on the server since the get, and the command to run next (\`--offline\`: skip the server). Then \`sim workflows source apply --dir . --dry-run\` until it exits 0. diff --git a/packages/sim-cli/src/program.ts b/packages/sim-cli/src/program.ts index 5d55aad2938..2ea6725298b 100644 --- a/packages/sim-cli/src/program.ts +++ b/packages/sim-cli/src/program.ts @@ -28,8 +28,10 @@ Profiles work like the AWS CLI: settings live in ~/.sim/config, keys in with -P, --profile, or SIM_PROFILE. A command targets the profile's workspace unless -w (--workspace ) or -SIM_WORKSPACE names another; a source directory keeps to the workspace its -.sim/base.json records, and refuses a -w naming another. In a script, export +SIM_WORKSPACE names another. A source directory records its own: a workflow +directory acts on the workflow its .sim/base.json names, a workspace directory +on the workspace its base names (refusing a -w naming another), and a starter +on the one .sim/starter.json names unless -w names another. In a script, export SIM_WORKSPACE= once, or keep only the ID in a variable and write -w "$WS". A variable holding "--workspace " is one argument: alone it is an unknown option, and after -w all of it is taken as the ID. diff --git a/packages/workflow-sdk/cookbook/examples/cookbook.ts b/packages/workflow-sdk/cookbook/examples/cookbook.ts index af0065dca60..bdc48be3b86 100644 --- a/packages/workflow-sdk/cookbook/examples/cookbook.ts +++ b/packages/workflow-sdk/cookbook/examples/cookbook.ts @@ -66,21 +66,18 @@ export default workflow('Cookbook', { description: 'One example of each common b code: js`return { id: ${start.orderId}, cents: Math.round(${start.amount} * 100) }`, }) - // Tables: query rows (each row is { id, data: { column } }) and insert a row. + // Tables: query rows (each row is { id, data: { column } }) and write one. const recent = table.queryRows('Recent Orders', { tableId: table('orders'), filterInput: { all: [{ field: 'status', op: 'eq', value: 'open' }] }, limit: 50, }) - const save = table.insertRow('Save Order', { - tableId: table('orders'), - data: { orderId: start.orderId, status: 'open' }, - }) // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else - // inserts one. data is keyed by column name, as for insertRow. - const touch = table.upsertRow('Touch Order', { + // inserts one, so a second run for the same order updates it. table.insertRow takes the same + // data without conflictColumn and adds a row every run. + const save = table.upsertRow('Save Order', { tableId: table('orders'), - data: { orderId: start.orderId, status: 'answered' }, + data: { orderId: start.orderId, status: 'open' }, conflictColumn: 'orderId', }) @@ -146,8 +143,7 @@ export default workflow('Cookbook', { description: 'One example of each common b // Wiring: a.to(b) chains; a block can fan out to several targets. start.to(check) check.to(save) - save.to(touch) - touch.to(route) + save.to(route) route.high.to(alert) alert.to(approval) approval.to(decided) diff --git a/packages/workflow-sdk/cookbook/workspace/workflows/support/workflow.ts b/packages/workflow-sdk/cookbook/workspace/workflows/support/workflow.ts index 4be18ed1fb2..fdf7b146cd9 100644 --- a/packages/workflow-sdk/cookbook/workspace/workflows/support/workflow.ts +++ b/packages/workflow-sdk/cookbook/workspace/workflows/support/workflow.ts @@ -32,9 +32,10 @@ export default workflow('Support', { description: 'Answers an order question.' } tools: [customTool('lookup-order')], skills: [skill('tone')], }) - const log = table.insertRow('Log Question', { + const log = table.upsertRow('Log Question', { tableId: table('orders'), data: { orderId: start.orderId, status: 'answered' }, + conflictColumn: 'orderId', }) start.to(policy) diff --git a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts index 1c02cd09fa8..87c2154327c 100644 --- a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from cookbook/examples; do not edit. /** The example workflows, file name → text, written as `.sim/examples/`: together one correct example of each common block. */ -export const COOKBOOK_EXAMPLES: Readonly> = {"agents.ts":"// @sim-sdk 1\nimport {\n agent,\n childWorkflow,\n credential,\n customTool,\n env,\n mcp,\n parallel,\n response,\n router,\n runWorkflow,\n slack,\n t,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `lookup-order`, `linear`, `ops-slack`,\n// `enrich-lead` and ANTHROPIC_API_KEY stand in for this workspace\u0027s resources\n// (.sim/sdk/workspace.d.ts; `sim workflows source resources` lists the real keys).\nexport default workflow(\n \u0027Cookbook: agents and subflows\u0027,\n { description: \u0027Router, agent tools, a child workflow and a parallel fan-out.\u0027 },\n () => {\n const start = trigger.start(\u0027Start\u0027, {\n inputFormat: { message: \u0027string\u0027, email: \u0027string\u0027, domains: \u0027array\u0027 },\n })\n\n // Router: the model picks one route by its description; wire with triage..to(...).\n const triage = router(\u0027Triage\u0027, {\n context: start.message,\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n routes: {\n support: \u0027A customer asking about an existing order\u0027,\n sales: \u0027A prospect asking about pricing or a demo\u0027,\n },\n })\n\n // Agent tools: a workspace custom tool, one tool of an MCP server, an integration operation\n // (.tool.; the params given here are fixed, the model fills the rest) and\n // another workflow.\n const support = agent(\u0027Support Agent\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Answer the customer. Use your tools when they help.\u0027 },\n { role: \u0027user\u0027, content: start.message },\n ],\n tools: [\n customTool(\u0027lookup-order\u0027),\n mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027),\n slack.tool.sendMessage({ credential: credential(\u0027ops-slack\u0027), channel: \u0027support-urgent\u0027 }),\n childWorkflow(\u0027enrich-lead\u0027).asTool(),\n ],\n })\n\n // Child workflow: inputMapping is checked against the child\u0027s start inputs. Its output is\n // enrich.result (untyped JSON): the child\u0027s response block output, so a field of the child\u0027s\n // response body is enrich.result.data..\n const enrich = runWorkflow(\u0027Enrich Lead\u0027, {\n workflowId: childWorkflow(\u0027enrich-lead\u0027),\n inputMapping: { email: start.email },\n })\n\n // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its\n // position; each.results lists every branch\u0027s output once all finish. (loop.forEach is the\n // sequential form.) In a function code file inside the body, the same values are\n // $ref.parallel.currentItem and $ref.parallel.index.\n const each = parallel.collection(\u0027Each Domain\u0027, { collection: start.domains }, (p) => {\n const brief = agent(\u0027Company Brief\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Describe ${p.currentItem} in two sentences.` }],\n })\n p.to(brief)\n })\n\n const answer = response(\u0027Answer\u0027, { body: { answer: support.content } })\n const briefs = response(\u0027Briefs\u0027, {\n body: { lead: t`${enrich.result}`, briefs: t`${each.results}` },\n })\n\n start.to(triage)\n triage.support.to(support)\n support.to(answer)\n triage.sales.to(enrich)\n enrich.to(each)\n each.to(briefs)\n }\n)\n","cookbook.ts":"// @sim-sdk 1\nimport {\n agent,\n condition,\n credential,\n env,\n fn,\n human,\n js,\n knowledge,\n knowledgeBase,\n loop,\n response,\n slack,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `orders`, `policies`, `ops-slack` and\n// ANTHROPIC_API_KEY stand in for this workspace\u0027s resources. `sim workflows source resources`\n// lists the real keys, and .sim/sdk/workspace.d.ts types them.\nexport default workflow(\u0027Cookbook\u0027, { description: \u0027One example of each common block.\u0027 }, () => {\n // Triggers: trigger.start (API/manual input), trigger.schedule, trigger.webhook.\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, amount: \u0027number\u0027 } })\n const nightly = trigger.schedule(\u0027Nightly\u0027, {\n scheduleType: \u0027daily\u0027,\n dailyTime: \u002702:00\u0027,\n timezone: \u0027UTC\u0027,\n })\n\n // Agent: structured output via responseFormat; its fields become outputs (check.risk).\n // apiKey: needed on self-hosted Sim; hosted Sim supplies one.\n const check = agent(\u0027Check Order\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Rate the fraud risk of an order as low, med or high.\u0027 },\n { role: \u0027user\u0027, content: t`Order ${start.orderId} for ${start.amount}` },\n ],\n responseFormat: {\n name: \u0027risk\u0027,\n strict: true,\n schema: {\n type: \u0027object\u0027,\n properties: {\n risk: { type: \u0027string\u0027, enum: [\u0027low\u0027, \u0027med\u0027, \u0027high\u0027] },\n reason: { type: \u0027string\u0027 },\n },\n required: [\u0027risk\u0027, \u0027reason\u0027],\n additionalProperties: false,\n },\n },\n })\n\n // Condition: one branch per key, `else: true` last; wire with route..to(...).\n const route = condition(\u0027Route Risk\u0027, {\n high: js`${check.risk} === \u0027high\u0027`,\n med: js`${check.risk} === \u0027med\u0027`,\n else: true,\n })\n\n // Function: inline JavaScript; reference outputs with ${...}. Result is fn.result.\n const shape = fn(\u0027Shape\u0027, {\n code: js`return { id: ${start.orderId}, cents: Math.round(${start.amount} * 100) }`,\n })\n\n // Tables: query rows (each row is { id, data: { column } }) and insert a row.\n const recent = table.queryRows(\u0027Recent Orders\u0027, {\n tableId: table(\u0027orders\u0027),\n filterInput: { all: [{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027open\u0027 }] },\n limit: 50,\n })\n const save = table.insertRow(\u0027Save Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027 },\n })\n // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else\n // inserts one. data is keyed by column name, as for insertRow.\n const touch = table.upsertRow(\u0027Touch Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027answered\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n\n // Knowledge base search: results is the list of matching chunks.\n const docs = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: check.reason,\n topK: 3,\n })\n\n // Slack: a saved credential by key (see .sim/sdk/workspace.d.ts).\n const alert = slack.sendMessage(\u0027Alert Ops\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-alerts\u0027,\n messageFormat: \u0027text\u0027,\n text: t`High-risk order ${start.orderId}: ${check.reason}`,\n })\n\n // Human in the loop: inputFormat is the form; answers are approval.submission..\n const approval = human(\u0027Manager Review\u0027, {\n builderData: [{ name: \u0027orderId\u0027, type: \u0027string\u0027, value: start.orderId }],\n inputFormat: { approved: { type: \u0027boolean\u0027, required: true }, note: \u0027string\u0027 },\n })\n const decided = condition(\u0027Approved\u0027, {\n yes: js`${approval.submission.approved} === true`,\n else: true,\n })\n\n // Loop over a list: p.currentItem is one element and p.index its position; the loop\u0027s results\n // is the list of iteration outputs. In js`` code a reference is the value itself, not text\n // spliced in: write it where an expression goes, never inside quotes (\u0027${x}\u0027 would give the\n // JSON, quotes included). A function code file (code: codeFile(\u0027./functions/line.js\u0027)) reads\n // other blocks as $ref.. ($ref.recentorders.rows) and, inside the loop body,\n // the iteration as $ref.loop.currentItem and $ref.loop.index.\n const each = loop.forEach(\u0027Each Order\u0027, { collection: recent.rows }, (p) => {\n const line = fn(\u0027Line\u0027, {\n code: js`return ${p.currentItem.data.orderId} + \u0027: \u0027 + ${p.currentItem.data.status}`,\n })\n p.to(line)\n })\n const report = agent(\u0027Report\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Summarize these orders in 3 lines:\\n${each.results}` }],\n })\n const post = slack.sendMessage(\u0027Post Report\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-daily\u0027,\n messageFormat: \u0027text\u0027,\n text: report.content,\n })\n\n // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text.\n // body is the short form of the editor\u0027s JSON mode: { dataMode: \u0027json\u0027, data } as below.\n const reply = response(\u0027Respond\u0027, { body: { risk: check.risk, id: t`${shape.result.id}` } })\n const rejected = response(\u0027Respond Rejected\u0027, {\n dataMode: \u0027json\u0027,\n data: { status: \u0027rejected\u0027 },\n })\n\n // Wiring: a.to(b) chains; a block can fan out to several targets.\n start.to(check)\n check.to(save)\n save.to(touch)\n touch.to(route)\n route.high.to(alert)\n alert.to(approval)\n approval.to(decided)\n decided.yes.to(shape)\n decided.else.to(rejected)\n route.med.to(docs)\n docs.to(shape)\n route.else.to(shape)\n shape.to(reply)\n nightly.to(recent)\n recent.to(each)\n each.to(report)\n report.to(post)\n})\n","integrations.ts":"// @sim-sdk 1\nimport {\n api,\n credential,\n env,\n gmail,\n response,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `leads`, `ops-gmail`, CLEARBIT_KEY and\n// LEADS_WEBHOOK_TOKEN stand in for this workspace\u0027s resources (.sim/sdk/workspace.d.ts).\n// Integration builders are named by service, not block type: `gmail_v2` is `gmail.*`, and a\n// hidden older version lives under `legacy.*`. .sim/sdk/INDEX.md lists every builder.\nexport default workflow(\n \u0027Cookbook: integrations\u0027,\n { description: \u0027Webhook, weekday schedule, HTTP with headers, table update, Gmail, error path.\u0027 },\n () => {\n // Webhook trigger: inputFormat types the posted JSON fields (hook.leadId). With requireAuth\n // the caller must send the token; keep it in an env var.\n const hook = trigger.webhook(\u0027Lead Webhook\u0027, {\n requireAuth: true,\n token: env.LEADS_WEBHOOK_TOKEN,\n inputFormat: { leadId: \u0027string\u0027, email: \u0027string\u0027, domain: \u0027string\u0027 },\n })\n\n // Schedule: no weekday preset exists, so scheduleType \u0027custom\u0027 takes a 5-field cron.\n const weekdays = trigger.schedule(\u0027Weekdays 8am\u0027, {\n scheduleType: \u0027custom\u0027,\n cronExpression: \u00270 8 * * 1-5\u0027,\n timezone: \u0027America/New_York\u0027,\n })\n\n // HTTP request: headers (and query params) are table rows, { cells: { Key, Value } }.\n const lookup = api(\u0027Company Lookup\u0027, {\n url: t`https://company.clearbit.com/v2/companies/find?domain=${hook.domain}`,\n method: \u0027GET\u0027,\n headers: [{ cells: { Key: \u0027Authorization\u0027, Value: t`Bearer ${env.CLEARBIT_KEY}` } }],\n })\n\n // Update one row by id: data holds only the columns to change. lookup.data is untyped JSON,\n // so a text field from it is wrapped in t``.\n const save = table.updateRowById(\u0027Save Company\u0027, {\n tableId: table(\u0027leads\u0027),\n rowId: hook.leadId,\n data: { company: t`${lookup.data.name}`, enriched: true },\n })\n\n // Gmail (gmail_v2): send one email with a saved Google credential.\n const welcome = gmail.sendEmail(\u0027Welcome Email\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: hook.email,\n subject: \u0027Welcome aboard\u0027,\n body: t`Thanks for signing up from ${hook.domain}.`,\n })\n\n // Query rows, then email them as one digest. A typed column filter: { field, op, value }.\n const pending = table.queryRows(\u0027Pending Leads\u0027, {\n tableId: table(\u0027leads\u0027),\n filterInput: { all: [{ field: \u0027enriched\u0027, op: \u0027eq\u0027, value: false }] },\n limit: 100,\n })\n const digest = gmail.sendEmail(\u0027Pending Digest\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: \u0027ops@example.com\u0027,\n subject: \u0027Leads still to enrich\u0027,\n body: t`${pending.rows}`,\n })\n\n // Error path: x.onError(y) runs y when x fails, instead of failing the run; y reads the\n // failure message as x.error.\n const failed = response(\u0027Lookup Failed\u0027, {\n body: { ok: false, error: lookup.error },\n status: 502,\n })\n const done = response(\u0027Done\u0027, { body: { ok: true, row: save.row } })\n\n hook.to(lookup)\n lookup.to(save)\n lookup.onError(failed)\n save.to(welcome)\n welcome.to(done)\n weekdays.to(pending)\n pending.to(digest)\n }\n)\n"} +export const COOKBOOK_EXAMPLES: Readonly> = {"agents.ts":"// @sim-sdk 1\nimport {\n agent,\n childWorkflow,\n credential,\n customTool,\n env,\n mcp,\n parallel,\n response,\n router,\n runWorkflow,\n slack,\n t,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `lookup-order`, `linear`, `ops-slack`,\n// `enrich-lead` and ANTHROPIC_API_KEY stand in for this workspace\u0027s resources\n// (.sim/sdk/workspace.d.ts; `sim workflows source resources` lists the real keys).\nexport default workflow(\n \u0027Cookbook: agents and subflows\u0027,\n { description: \u0027Router, agent tools, a child workflow and a parallel fan-out.\u0027 },\n () => {\n const start = trigger.start(\u0027Start\u0027, {\n inputFormat: { message: \u0027string\u0027, email: \u0027string\u0027, domains: \u0027array\u0027 },\n })\n\n // Router: the model picks one route by its description; wire with triage..to(...).\n const triage = router(\u0027Triage\u0027, {\n context: start.message,\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n routes: {\n support: \u0027A customer asking about an existing order\u0027,\n sales: \u0027A prospect asking about pricing or a demo\u0027,\n },\n })\n\n // Agent tools: a workspace custom tool, one tool of an MCP server, an integration operation\n // (.tool.; the params given here are fixed, the model fills the rest) and\n // another workflow.\n const support = agent(\u0027Support Agent\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Answer the customer. Use your tools when they help.\u0027 },\n { role: \u0027user\u0027, content: start.message },\n ],\n tools: [\n customTool(\u0027lookup-order\u0027),\n mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027),\n slack.tool.sendMessage({ credential: credential(\u0027ops-slack\u0027), channel: \u0027support-urgent\u0027 }),\n childWorkflow(\u0027enrich-lead\u0027).asTool(),\n ],\n })\n\n // Child workflow: inputMapping is checked against the child\u0027s start inputs. Its output is\n // enrich.result (untyped JSON): the child\u0027s response block output, so a field of the child\u0027s\n // response body is enrich.result.data..\n const enrich = runWorkflow(\u0027Enrich Lead\u0027, {\n workflowId: childWorkflow(\u0027enrich-lead\u0027),\n inputMapping: { email: start.email },\n })\n\n // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its\n // position; each.results lists every branch\u0027s output once all finish. (loop.forEach is the\n // sequential form.) In a function code file inside the body, the same values are\n // $ref.parallel.currentItem and $ref.parallel.index.\n const each = parallel.collection(\u0027Each Domain\u0027, { collection: start.domains }, (p) => {\n const brief = agent(\u0027Company Brief\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Describe ${p.currentItem} in two sentences.` }],\n })\n p.to(brief)\n })\n\n const answer = response(\u0027Answer\u0027, { body: { answer: support.content } })\n const briefs = response(\u0027Briefs\u0027, {\n body: { lead: t`${enrich.result}`, briefs: t`${each.results}` },\n })\n\n start.to(triage)\n triage.support.to(support)\n support.to(answer)\n triage.sales.to(enrich)\n enrich.to(each)\n each.to(briefs)\n }\n)\n","cookbook.ts":"// @sim-sdk 1\nimport {\n agent,\n condition,\n credential,\n env,\n fn,\n human,\n js,\n knowledge,\n knowledgeBase,\n loop,\n response,\n slack,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `orders`, `policies`, `ops-slack` and\n// ANTHROPIC_API_KEY stand in for this workspace\u0027s resources. `sim workflows source resources`\n// lists the real keys, and .sim/sdk/workspace.d.ts types them.\nexport default workflow(\u0027Cookbook\u0027, { description: \u0027One example of each common block.\u0027 }, () => {\n // Triggers: trigger.start (API/manual input), trigger.schedule, trigger.webhook.\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, amount: \u0027number\u0027 } })\n const nightly = trigger.schedule(\u0027Nightly\u0027, {\n scheduleType: \u0027daily\u0027,\n dailyTime: \u002702:00\u0027,\n timezone: \u0027UTC\u0027,\n })\n\n // Agent: structured output via responseFormat; its fields become outputs (check.risk).\n // apiKey: needed on self-hosted Sim; hosted Sim supplies one.\n const check = agent(\u0027Check Order\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Rate the fraud risk of an order as low, med or high.\u0027 },\n { role: \u0027user\u0027, content: t`Order ${start.orderId} for ${start.amount}` },\n ],\n responseFormat: {\n name: \u0027risk\u0027,\n strict: true,\n schema: {\n type: \u0027object\u0027,\n properties: {\n risk: { type: \u0027string\u0027, enum: [\u0027low\u0027, \u0027med\u0027, \u0027high\u0027] },\n reason: { type: \u0027string\u0027 },\n },\n required: [\u0027risk\u0027, \u0027reason\u0027],\n additionalProperties: false,\n },\n },\n })\n\n // Condition: one branch per key, `else: true` last; wire with route..to(...).\n const route = condition(\u0027Route Risk\u0027, {\n high: js`${check.risk} === \u0027high\u0027`,\n med: js`${check.risk} === \u0027med\u0027`,\n else: true,\n })\n\n // Function: inline JavaScript; reference outputs with ${...}. Result is fn.result.\n const shape = fn(\u0027Shape\u0027, {\n code: js`return { id: ${start.orderId}, cents: Math.round(${start.amount} * 100) }`,\n })\n\n // Tables: query rows (each row is { id, data: { column } }) and write one.\n const recent = table.queryRows(\u0027Recent Orders\u0027, {\n tableId: table(\u0027orders\u0027),\n filterInput: { all: [{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027open\u0027 }] },\n limit: 50,\n })\n // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else\n // inserts one, so a second run for the same order updates it. table.insertRow takes the same\n // data without conflictColumn and adds a row every run.\n const save = table.upsertRow(\u0027Save Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n\n // Knowledge base search: results is the list of matching chunks.\n const docs = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: check.reason,\n topK: 3,\n })\n\n // Slack: a saved credential by key (see .sim/sdk/workspace.d.ts).\n const alert = slack.sendMessage(\u0027Alert Ops\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-alerts\u0027,\n messageFormat: \u0027text\u0027,\n text: t`High-risk order ${start.orderId}: ${check.reason}`,\n })\n\n // Human in the loop: inputFormat is the form; answers are approval.submission..\n const approval = human(\u0027Manager Review\u0027, {\n builderData: [{ name: \u0027orderId\u0027, type: \u0027string\u0027, value: start.orderId }],\n inputFormat: { approved: { type: \u0027boolean\u0027, required: true }, note: \u0027string\u0027 },\n })\n const decided = condition(\u0027Approved\u0027, {\n yes: js`${approval.submission.approved} === true`,\n else: true,\n })\n\n // Loop over a list: p.currentItem is one element and p.index its position; the loop\u0027s results\n // is the list of iteration outputs. In js`` code a reference is the value itself, not text\n // spliced in: write it where an expression goes, never inside quotes (\u0027${x}\u0027 would give the\n // JSON, quotes included). A function code file (code: codeFile(\u0027./functions/line.js\u0027)) reads\n // other blocks as $ref.. ($ref.recentorders.rows) and, inside the loop body,\n // the iteration as $ref.loop.currentItem and $ref.loop.index.\n const each = loop.forEach(\u0027Each Order\u0027, { collection: recent.rows }, (p) => {\n const line = fn(\u0027Line\u0027, {\n code: js`return ${p.currentItem.data.orderId} + \u0027: \u0027 + ${p.currentItem.data.status}`,\n })\n p.to(line)\n })\n const report = agent(\u0027Report\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Summarize these orders in 3 lines:\\n${each.results}` }],\n })\n const post = slack.sendMessage(\u0027Post Report\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-daily\u0027,\n messageFormat: \u0027text\u0027,\n text: report.content,\n })\n\n // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text.\n // body is the short form of the editor\u0027s JSON mode: { dataMode: \u0027json\u0027, data } as below.\n const reply = response(\u0027Respond\u0027, { body: { risk: check.risk, id: t`${shape.result.id}` } })\n const rejected = response(\u0027Respond Rejected\u0027, {\n dataMode: \u0027json\u0027,\n data: { status: \u0027rejected\u0027 },\n })\n\n // Wiring: a.to(b) chains; a block can fan out to several targets.\n start.to(check)\n check.to(save)\n save.to(route)\n route.high.to(alert)\n alert.to(approval)\n approval.to(decided)\n decided.yes.to(shape)\n decided.else.to(rejected)\n route.med.to(docs)\n docs.to(shape)\n route.else.to(shape)\n shape.to(reply)\n nightly.to(recent)\n recent.to(each)\n each.to(report)\n report.to(post)\n})\n","integrations.ts":"// @sim-sdk 1\nimport {\n api,\n credential,\n env,\n gmail,\n response,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `leads`, `ops-gmail`, CLEARBIT_KEY and\n// LEADS_WEBHOOK_TOKEN stand in for this workspace\u0027s resources (.sim/sdk/workspace.d.ts).\n// Integration builders are named by service, not block type: `gmail_v2` is `gmail.*`, and a\n// hidden older version lives under `legacy.*`. .sim/sdk/INDEX.md lists every builder.\nexport default workflow(\n \u0027Cookbook: integrations\u0027,\n { description: \u0027Webhook, weekday schedule, HTTP with headers, table update, Gmail, error path.\u0027 },\n () => {\n // Webhook trigger: inputFormat types the posted JSON fields (hook.leadId). With requireAuth\n // the caller must send the token; keep it in an env var.\n const hook = trigger.webhook(\u0027Lead Webhook\u0027, {\n requireAuth: true,\n token: env.LEADS_WEBHOOK_TOKEN,\n inputFormat: { leadId: \u0027string\u0027, email: \u0027string\u0027, domain: \u0027string\u0027 },\n })\n\n // Schedule: no weekday preset exists, so scheduleType \u0027custom\u0027 takes a 5-field cron.\n const weekdays = trigger.schedule(\u0027Weekdays 8am\u0027, {\n scheduleType: \u0027custom\u0027,\n cronExpression: \u00270 8 * * 1-5\u0027,\n timezone: \u0027America/New_York\u0027,\n })\n\n // HTTP request: headers (and query params) are table rows, { cells: { Key, Value } }.\n const lookup = api(\u0027Company Lookup\u0027, {\n url: t`https://company.clearbit.com/v2/companies/find?domain=${hook.domain}`,\n method: \u0027GET\u0027,\n headers: [{ cells: { Key: \u0027Authorization\u0027, Value: t`Bearer ${env.CLEARBIT_KEY}` } }],\n })\n\n // Update one row by id: data holds only the columns to change. lookup.data is untyped JSON,\n // so a text field from it is wrapped in t``.\n const save = table.updateRowById(\u0027Save Company\u0027, {\n tableId: table(\u0027leads\u0027),\n rowId: hook.leadId,\n data: { company: t`${lookup.data.name}`, enriched: true },\n })\n\n // Gmail (gmail_v2): send one email with a saved Google credential.\n const welcome = gmail.sendEmail(\u0027Welcome Email\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: hook.email,\n subject: \u0027Welcome aboard\u0027,\n body: t`Thanks for signing up from ${hook.domain}.`,\n })\n\n // Query rows, then email them as one digest. A typed column filter: { field, op, value }.\n const pending = table.queryRows(\u0027Pending Leads\u0027, {\n tableId: table(\u0027leads\u0027),\n filterInput: { all: [{ field: \u0027enriched\u0027, op: \u0027eq\u0027, value: false }] },\n limit: 100,\n })\n const digest = gmail.sendEmail(\u0027Pending Digest\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: \u0027ops@example.com\u0027,\n subject: \u0027Leads still to enrich\u0027,\n body: t`${pending.rows}`,\n })\n\n // Error path: x.onError(y) runs y when x fails, instead of failing the run; y reads the\n // failure message as x.error.\n const failed = response(\u0027Lookup Failed\u0027, {\n body: { ok: false, error: lookup.error },\n status: 502,\n })\n const done = response(\u0027Done\u0027, { body: { ok: true, row: save.row } })\n\n hook.to(lookup)\n lookup.to(save)\n lookup.onError(failed)\n save.to(welcome)\n welcome.to(done)\n weekdays.to(pending)\n pending.to(digest)\n }\n)\n"} diff --git a/packages/workflow-sdk/src/codegen/workspace-cookbook-text.generated.ts b/packages/workflow-sdk/src/codegen/workspace-cookbook-text.generated.ts index cb5b9c99dc2..933d4c18fd9 100644 --- a/packages/workflow-sdk/src/codegen/workspace-cookbook-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/workspace-cookbook-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from cookbook/workspace; do not edit. /** The example workspace directory, path → text: one resource of each kind and a workflow using them. */ -export const WORKSPACE_COOKBOOK: Readonly> = {"credentials.ts":"// @sim-sdk 1\nimport { defineCredentials } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// credentials.ts: the saved credentials workflows use as credential(\u0027\u0027), by provider only.\n// An apply binds each key to this workspace\u0027s credential of that provider. The provider is the\n// id `sim credentials connect ` takes (Gmail is \u0027google-email\u0027); a block\u0027s .d.ts names\n// the ones its credential accepts (CredentialKeyFor<\u0027google-email\u0027 | …>). `name` picks one of\n// several credentials of a provider by its display name.\nexport default defineCredentials({\n slack: { provider: \u0027slack\u0027 },\n gmail: { provider: \u0027google-email\u0027, name: \u0027Support inbox\u0027 },\n})\n","deployments/support.ts":"// @sim-sdk 1\nimport { defineDeployment } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// deployments/.ts deploys workflows// after the apply writes it.\n// \u0027draft\u0027 publishes the draft whenever it differs from the live version; \u0027pinned\u0027 never does.\nexport default defineDeployment({\n live: \u0027draft\u0027,\n api: { public: false },\n chat: {\n identifier: \u0027support-example\u0027,\n title: \u0027Support\u0027,\n // A password is a secret by name, never its value: auth: { password: env.CHAT_PASSWORD }.\n auth: { emails: [\u0027@example.com\u0027] },\n outputs: [{ block: \u0027Answer\u0027, path: \u0027content\u0027 }],\n },\n})\n","files/templates/reply.md":"Hi {{name}},\n\nThanks for reaching out about order {{orderId}}.\n","knowledge/policies/docs/refunds.md":"# Refunds\n\nOrders can be refunded within 30 days of delivery. Refunds go back to the original payment method.\n","knowledge/policies/knowledge.ts":"// @sim-sdk 1\nimport { defineKnowledgeBase } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// knowledge//knowledge.ts, with one file per document in knowledge//docs/ (flat, each\n// at most 10 MB). A workflow names it as knowledgeBase(\u0027policies\u0027).\nexport default defineKnowledgeBase({\n name: \u0027Policies\u0027,\n description: \u0027Refund and shipping policies\u0027,\n chunking: { maxSize: 1024, minSize: 100, overlap: 200 },\n})\n","mcp/docs.ts":"// @sim-sdk 1\nimport { defineMcpServer, env } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// mcp/.ts: an MCP server the workspace\u0027s agents call tools on. A workflow names it by key\n// and a tool by name: mcp(\u0027docs\u0027).tool(\u0027search_docs\u0027). A credential header holds an env reference,\n// never the secret itself; `stored()` keeps the value the server already holds. The server\u0027s id\n// derives from its URL, so a `url` with another host or path replaces the server; a new query\n// string updates it in place.\nexport default defineMcpServer({\n name: \u0027Docs\u0027,\n url: \u0027https://docs.example.com/mcp\u0027,\n headers: { Authorization: \u0027Bearer {{DOCS_MCP_TOKEN}}\u0027, \u0027X-Api-Key\u0027: env.DOCS_MCP_KEY },\n timeout: 10000,\n})\n","secrets.ts":"// @sim-sdk 1\nimport { defineSecrets } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// secrets.ts: the workspace secrets workflows read as env.NAME, by name and description only.\n// A value never appears here: set one with `sim secrets set NAME --scope workspace`.\nexport default defineSecrets({\n ANTHROPIC_API_KEY: { description: \u0027Model access for the support agent\u0027 },\n DOCS_MCP_KEY: { description: \u0027API key the docs MCP server checks\u0027 },\n DOCS_MCP_TOKEN: { description: \u0027Bearer token for the docs MCP server\u0027 },\n ORDERS_API_KEY: { description: \u0027API key the lookup-order tool sends to the orders service\u0027 },\n})\n","skills/tone.md":"---\nname: tone\ndescription: \"Answer in the support team\u0027s voice: short, warm, specific.\"\n---\nWrite like a person, not a policy. Lead with the answer, then the one detail that matters.\n","tables/orders.ts":"// @sim-sdk 1\nimport { column, defineTable } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// tables/.ts: the key (`orders`) is how a workflow names it: table(\u0027orders\u0027). Its rows stay\n// out of source (see plans.ts to opt in). To rename a column keep its key and set `name`.\nexport default defineTable({\n name: \u0027orders\u0027,\n description: \u0027Order questions the support workflow answered\u0027,\n columns: {\n orderId: column.string({ required: true, unique: true }),\n status: column.select({ options: [\u0027open\u0027, \u0027answered\u0027] }),\n total: column.number(),\n },\n})\n","tables/plans.rows.jsonl":"{\"code\":\"solo\",\"seats\":1,\"tier\":\"basic\"}\n{\"code\":\"team\",\"seats\":10,\"tier\":\"pro\"}\n","tables/plans.ts":"// @sim-sdk 1\nimport { column, defineTable } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// Managed rows: tables/plans.rows.jsonl is the table\u0027s whole content, one row per line keyed by\n// column key, each matched to its stored row by the unique `code` column. Removing a line deletes\n// that row (with --allow-delete). Use `{ mode: \u0027seed\u0027 }` instead to write rows only when the table\n// is created.\nexport default defineTable({\n name: \u0027plans\u0027,\n description: \u0027Plans the billing workflow prices against\u0027,\n columns: {\n code: column.string({ required: true, unique: true }),\n seats: column.number(),\n tier: column.select({ options: [\u0027basic\u0027, \u0027pro\u0027] }),\n },\n rows: { mode: \u0027managed\u0027, key: \u0027code\u0027 },\n})\n","tools/lookup-order.js":"// Each schema parameter is a variable; $env.NAME reads an environment variable by name, so the\n// value never appears in source.\nconst response = await fetch(`https://orders.example.com/api/orders/${encodeURIComponent(orderId)}`, {\n headers: { Authorization: `Bearer ${$env.ORDERS_API_KEY}` },\n})\nreturn await response.json()\n","tools/lookup-order.ts":"// @sim-sdk 1\nimport { codeFile, defineTool } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// tools/.ts, with its code in tools/.js.\n// A workflow names it as customTool(\u0027lookup-order\u0027).\nexport default defineTool({\n title: \u0027Lookup order\u0027,\n schema: {\n type: \u0027function\u0027,\n function: {\n name: \u0027lookup_order\u0027,\n description: \u0027Find an order by id.\u0027,\n parameters: {\n type: \u0027object\u0027,\n properties: { orderId: { type: \u0027string\u0027 } },\n required: [\u0027orderId\u0027],\n },\n },\n },\n code: codeFile(\u0027./lookup-order.js\u0027),\n})\n","workflows/support/workflow.ts":"// @sim-sdk 1\nimport {\n agent,\n customTool,\n env,\n knowledge,\n knowledgeBase,\n skill,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// workflows//workflow.ts: a workflow source directory. It names the resources this\n// directory declares by key, and one apply creates them before the workflow that uses them.\nexport default workflow(\u0027Support\u0027, { description: \u0027Answers an order question.\u0027 }, () => {\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, question: \u0027string\u0027 } })\n const policy = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: start.question,\n topK: 3,\n })\n const answer = agent(\u0027Answer\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n // An environment variable by name; its value never appears in source.\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: t`Answer from these policies:\\n${policy.results}` },\n { role: \u0027user\u0027, content: t`Order ${start.orderId}: ${start.question}` },\n ],\n tools: [customTool(\u0027lookup-order\u0027)],\n skills: [skill(\u0027tone\u0027)],\n })\n const log = table.insertRow(\u0027Log Question\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027answered\u0027 },\n })\n\n start.to(policy)\n policy.to(answer)\n answer.to(log)\n})\n"} +export const WORKSPACE_COOKBOOK: Readonly> = {"credentials.ts":"// @sim-sdk 1\nimport { defineCredentials } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// credentials.ts: the saved credentials workflows use as credential(\u0027\u0027), by provider only.\n// An apply binds each key to this workspace\u0027s credential of that provider. The provider is the\n// id `sim credentials connect ` takes (Gmail is \u0027google-email\u0027); a block\u0027s .d.ts names\n// the ones its credential accepts (CredentialKeyFor<\u0027google-email\u0027 | …>). `name` picks one of\n// several credentials of a provider by its display name.\nexport default defineCredentials({\n slack: { provider: \u0027slack\u0027 },\n gmail: { provider: \u0027google-email\u0027, name: \u0027Support inbox\u0027 },\n})\n","deployments/support.ts":"// @sim-sdk 1\nimport { defineDeployment } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// deployments/.ts deploys workflows// after the apply writes it.\n// \u0027draft\u0027 publishes the draft whenever it differs from the live version; \u0027pinned\u0027 never does.\nexport default defineDeployment({\n live: \u0027draft\u0027,\n api: { public: false },\n chat: {\n identifier: \u0027support-example\u0027,\n title: \u0027Support\u0027,\n // A password is a secret by name, never its value: auth: { password: env.CHAT_PASSWORD }.\n auth: { emails: [\u0027@example.com\u0027] },\n outputs: [{ block: \u0027Answer\u0027, path: \u0027content\u0027 }],\n },\n})\n","files/templates/reply.md":"Hi {{name}},\n\nThanks for reaching out about order {{orderId}}.\n","knowledge/policies/docs/refunds.md":"# Refunds\n\nOrders can be refunded within 30 days of delivery. Refunds go back to the original payment method.\n","knowledge/policies/knowledge.ts":"// @sim-sdk 1\nimport { defineKnowledgeBase } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// knowledge//knowledge.ts, with one file per document in knowledge//docs/ (flat, each\n// at most 10 MB). A workflow names it as knowledgeBase(\u0027policies\u0027).\nexport default defineKnowledgeBase({\n name: \u0027Policies\u0027,\n description: \u0027Refund and shipping policies\u0027,\n chunking: { maxSize: 1024, minSize: 100, overlap: 200 },\n})\n","mcp/docs.ts":"// @sim-sdk 1\nimport { defineMcpServer, env } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// mcp/.ts: an MCP server the workspace\u0027s agents call tools on. A workflow names it by key\n// and a tool by name: mcp(\u0027docs\u0027).tool(\u0027search_docs\u0027). A credential header holds an env reference,\n// never the secret itself; `stored()` keeps the value the server already holds. The server\u0027s id\n// derives from its URL, so a `url` with another host or path replaces the server; a new query\n// string updates it in place.\nexport default defineMcpServer({\n name: \u0027Docs\u0027,\n url: \u0027https://docs.example.com/mcp\u0027,\n headers: { Authorization: \u0027Bearer {{DOCS_MCP_TOKEN}}\u0027, \u0027X-Api-Key\u0027: env.DOCS_MCP_KEY },\n timeout: 10000,\n})\n","secrets.ts":"// @sim-sdk 1\nimport { defineSecrets } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// secrets.ts: the workspace secrets workflows read as env.NAME, by name and description only.\n// A value never appears here: set one with `sim secrets set NAME --scope workspace`.\nexport default defineSecrets({\n ANTHROPIC_API_KEY: { description: \u0027Model access for the support agent\u0027 },\n DOCS_MCP_KEY: { description: \u0027API key the docs MCP server checks\u0027 },\n DOCS_MCP_TOKEN: { description: \u0027Bearer token for the docs MCP server\u0027 },\n ORDERS_API_KEY: { description: \u0027API key the lookup-order tool sends to the orders service\u0027 },\n})\n","skills/tone.md":"---\nname: tone\ndescription: \"Answer in the support team\u0027s voice: short, warm, specific.\"\n---\nWrite like a person, not a policy. Lead with the answer, then the one detail that matters.\n","tables/orders.ts":"// @sim-sdk 1\nimport { column, defineTable } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// tables/.ts: the key (`orders`) is how a workflow names it: table(\u0027orders\u0027). Its rows stay\n// out of source (see plans.ts to opt in). To rename a column keep its key and set `name`.\nexport default defineTable({\n name: \u0027orders\u0027,\n description: \u0027Order questions the support workflow answered\u0027,\n columns: {\n orderId: column.string({ required: true, unique: true }),\n status: column.select({ options: [\u0027open\u0027, \u0027answered\u0027] }),\n total: column.number(),\n },\n})\n","tables/plans.rows.jsonl":"{\"code\":\"solo\",\"seats\":1,\"tier\":\"basic\"}\n{\"code\":\"team\",\"seats\":10,\"tier\":\"pro\"}\n","tables/plans.ts":"// @sim-sdk 1\nimport { column, defineTable } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// Managed rows: tables/plans.rows.jsonl is the table\u0027s whole content, one row per line keyed by\n// column key, each matched to its stored row by the unique `code` column. Removing a line deletes\n// that row (with --allow-delete). Use `{ mode: \u0027seed\u0027 }` instead to write rows only when the table\n// is created.\nexport default defineTable({\n name: \u0027plans\u0027,\n description: \u0027Plans the billing workflow prices against\u0027,\n columns: {\n code: column.string({ required: true, unique: true }),\n seats: column.number(),\n tier: column.select({ options: [\u0027basic\u0027, \u0027pro\u0027] }),\n },\n rows: { mode: \u0027managed\u0027, key: \u0027code\u0027 },\n})\n","tools/lookup-order.js":"// Each schema parameter is a variable; $env.NAME reads an environment variable by name, so the\n// value never appears in source.\nconst response = await fetch(`https://orders.example.com/api/orders/${encodeURIComponent(orderId)}`, {\n headers: { Authorization: `Bearer ${$env.ORDERS_API_KEY}` },\n})\nreturn await response.json()\n","tools/lookup-order.ts":"// @sim-sdk 1\nimport { codeFile, defineTool } from \u0027@sim/workflow-sdk/workspace\u0027\n\n// tools/.ts, with its code in tools/.js.\n// A workflow names it as customTool(\u0027lookup-order\u0027).\nexport default defineTool({\n title: \u0027Lookup order\u0027,\n schema: {\n type: \u0027function\u0027,\n function: {\n name: \u0027lookup_order\u0027,\n description: \u0027Find an order by id.\u0027,\n parameters: {\n type: \u0027object\u0027,\n properties: { orderId: { type: \u0027string\u0027 } },\n required: [\u0027orderId\u0027],\n },\n },\n },\n code: codeFile(\u0027./lookup-order.js\u0027),\n})\n","workflows/support/workflow.ts":"// @sim-sdk 1\nimport {\n agent,\n customTool,\n env,\n knowledge,\n knowledgeBase,\n skill,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// workflows//workflow.ts: a workflow source directory. It names the resources this\n// directory declares by key, and one apply creates them before the workflow that uses them.\nexport default workflow(\u0027Support\u0027, { description: \u0027Answers an order question.\u0027 }, () => {\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, question: \u0027string\u0027 } })\n const policy = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: start.question,\n topK: 3,\n })\n const answer = agent(\u0027Answer\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n // An environment variable by name; its value never appears in source.\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: t`Answer from these policies:\\n${policy.results}` },\n { role: \u0027user\u0027, content: t`Order ${start.orderId}: ${start.question}` },\n ],\n tools: [customTool(\u0027lookup-order\u0027)],\n skills: [skill(\u0027tone\u0027)],\n })\n const log = table.upsertRow(\u0027Log Question\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027answered\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n\n start.to(policy)\n policy.to(answer)\n answer.to(log)\n})\n"}