From 3e1d65b9515d2a9c57cf956d2fa4eff73be128fa Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:45:46 -0800 Subject: [PATCH 1/2] fix(workflow-code): agent-facing semantics copy for guardrails failures, loop results, and params --full - guardrails block, docs and previews: a failed check leaves through the error port, so handle it there (onError in workflow code), not with a Condition on passed - loop/parallel results typed Json[][] with the per-iteration wording in core.d.ts, cookbook, primer and json-fields - source params JSON brief names the --full lookup as next --- .../components/workflow-preview/examples.ts | 117 +++++++----------- .../docs/workflows/blocks/guardrails.mdx | 25 ++-- apps/sim/blocks/blocks/guardrails.ts | 10 +- .../src/commands/protocol/source-primer.ts | 2 +- .../protocol/workflow-source-params.test.ts | 30 ++++- .../protocol/workflow-source-params.ts | 17 ++- packages/workflow-code/src/json-fields.ts | 2 +- .../workflow-sdk/cookbook/examples/agents.ts | 8 +- .../cookbook/examples/cookbook.ts | 4 +- .../src/codegen/cookbook-text.generated.ts | 2 +- .../src/codegen/core-text.generated.ts | 2 +- packages/workflow-sdk/src/core.d.ts | 11 +- .../workflow-sdk/test/negative/rejected.ts | 8 ++ 13 files changed, 137 insertions(+), 101 deletions(-) diff --git a/apps/docs/components/workflow-preview/examples.ts b/apps/docs/components/workflow-preview/examples.ts index 21864d4b529..33a640b403b 100644 --- a/apps/docs/components/workflow-preview/examples.ts +++ b/apps/docs/components/workflow-preview/examples.ts @@ -1445,14 +1445,28 @@ const GUARDRAILS_START = { position: { x: 0, y: 0 }, } as const -const GUARDRAILS_GATE = { - id: 'condition', - name: 'Condition', - type: 'condition', - typeLabel: 'Condition', - bgColor: '#FF752F', - position: { x: 640, y: 0 }, -} as const +/** A Function block in a guardrails example: the passing path (top) or the error path (bottom). */ +function guardrailsFunction(id: string, name: string, code: string, path: 'pass' | 'error') { + return { + id, + name, + type: 'function', + typeLabel: 'Function', + sentence: ['Run', { subBlockId: 'Code', noun: 'code' }], + bgColor: '#FF402F', + position: { x: 640, y: path === 'pass' ? -60 : 140 }, + rows: [{ title: 'Code', value: code }], + } +} + +/** A guardrails example's edges: the check passes to `passId`, and fails through its error port to `errorId`. */ +function guardrailsEdges(passId: string, errorId: string): PreviewWorkflow['edges'] { + return [ + { id: 'start-guardrails', source: 'start', target: 'guardrails' }, + { id: `guardrails-${passId}`, source: 'guardrails', target: passId }, + { id: `guardrails-${errorId}`, source: 'guardrails', target: errorId, sourceHandle: 'error' }, + ] +} /** Guardrails example: validate JSON before parsing it. */ export const GUARDRAILS_JSON_WORKFLOW: PreviewWorkflow = { @@ -1473,46 +1487,15 @@ export const GUARDRAILS_JSON_WORKFLOW: PreviewWorkflow = { { title: 'Validation', value: 'Valid JSON' }, ], }, - { - ...GUARDRAILS_GATE, - rows: [], - branches: [ - { id: 'condition-if', label: 'If', value: '' }, - { id: 'condition-else', label: 'else' }, - ], - }, - { - id: 'parse', - name: 'Parse', - type: 'function', - typeLabel: 'Function', - sentence: ['Run', { subBlockId: 'Code', noun: 'code' }], - bgColor: '#FF402F', - position: { x: 960, y: -60 }, - rows: [{ title: 'Code', value: 'return JSON.parse();' }], - }, - { - id: 'reject', - name: 'Reject', - type: 'function', - typeLabel: 'Function', - sentence: ['Run', { subBlockId: 'Code', noun: 'code' }], - bgColor: '#FF402F', - position: { x: 960, y: 140 }, - rows: [{ title: 'Code', value: 'return { valid: false, error: };' }], - }, - ], - edges: [ - { id: 'start-guardrails', source: 'start', target: 'guardrails' }, - { id: 'guardrails-condition', source: 'guardrails', target: 'condition' }, - { id: 'condition-parse', source: 'condition', target: 'parse', sourceHandle: 'condition-if' }, - { - id: 'condition-reject', - source: 'condition', - target: 'reject', - sourceHandle: 'condition-else', - }, + guardrailsFunction('parse', 'Parse', 'return JSON.parse();', 'pass'), + guardrailsFunction( + 'reject', + 'Reject', + 'return { valid: false, error: };', + 'error' + ), ], + edges: guardrailsEdges('parse', 'reject'), } /** Guardrails example: check an answer is grounded in the knowledge base. */ @@ -1541,19 +1524,15 @@ export const GUARDRAILS_HALLUCINATION_WORKFLOW: PreviewWorkflow = { { title: 'Model', value: 'claude-sonnet-5-5' }, ], }, - { - ...GUARDRAILS_GATE, - rows: [], - branches: [ - { id: 'condition-if', label: 'If', value: ' >= 3' }, - { id: 'condition-else', label: 'else' }, - ], - }, - ], - edges: [ - { id: 'start-guardrails', source: 'start', target: 'guardrails' }, - { id: 'guardrails-condition', source: 'guardrails', target: 'condition' }, + guardrailsFunction('answer', 'Answer', 'return ;', 'pass'), + guardrailsFunction( + 'flag', + 'Flag', + 'return { grounded: false, score: , reason: };', + 'error' + ), ], + edges: guardrailsEdges('answer', 'flag'), } /** Guardrails example: block user input that contains PII. */ @@ -1586,19 +1565,15 @@ export const GUARDRAILS_PII_WORKFLOW: PreviewWorkflow = { { title: 'Action', value: 'Block Request' }, ], }, - { - ...GUARDRAILS_GATE, - rows: [], - branches: [ - { id: 'condition-if', label: 'If', value: '' }, - { id: 'condition-else', label: 'else' }, - ], - }, - ], - edges: [ - { id: 'start-guardrails', source: 'start', target: 'guardrails' }, - { id: 'guardrails-condition', source: 'guardrails', target: 'condition' }, + guardrailsFunction('process', 'Process', 'return ;', 'pass'), + guardrailsFunction( + 'reject', + 'Reject', + 'return { rejected: true, found: };', + 'error' + ), ], + edges: guardrailsEdges('process', 'reject'), } /** HITL example: a human approves AI content before it ships. */ diff --git a/apps/docs/content/docs/workflows/blocks/guardrails.mdx b/apps/docs/content/docs/workflows/blocks/guardrails.mdx index 2ed94172872..56994d3422e 100644 --- a/apps/docs/content/docs/workflows/blocks/guardrails.mdx +++ b/apps/docs/content/docs/workflows/blocks/guardrails.mdx @@ -6,7 +6,11 @@ description: Validate JSON, match a pattern, assess grounding, or detect PII. import { Callout } from '@/components/ui/callout' import { BlockPreview, WorkflowPreview, GUARDRAILS_JSON_WORKFLOW, GUARDRAILS_HALLUCINATION_WORKFLOW, GUARDRAILS_PII_WORKFLOW } from '@/components/workflow-preview' -The **Guardrails block** checks content and returns a result. Each block runs one validation type; chain blocks for multiple checks. Validation alone does not choose the next path—connect a Condition to act on it. +The **Guardrails block** checks content. Each block runs one validation type; chain blocks for multiple checks. A passing check continues along the normal output. A failed check leaves through the block's **error port**, so connect the error port to handle it. + + +Do not branch on `` with a Condition. A failed check never reaches the Condition, and with nothing on the error port the run completes without output. In workflow code, wire the failure with `onError`: `check.onError(reject)`. + @@ -14,7 +18,7 @@ The **Guardrails block** checks content and returns a result. Each block runs on -Select **Valid JSON**, check ``, and branch on `` before parsing it in Function. This checks JSON syntax, not a schema's required fields or types. +Select **Valid JSON** and check ``. Valid JSON continues to the Function that parses it; invalid JSON takes the error port to **Reject**, which reads the parse error as ``. This checks JSON syntax, not a schema's required fields or types. ## Configuration @@ -22,7 +26,7 @@ Set **Content to Validate** to text or an earlier output, then select **Validati ### Valid JSON -Passes when the content parses as JSON. Invalid content returns `passed: false` and a parse error. Use a Function after this check if you also need schema validation. +Passes when the content parses as JSON. Invalid content fails the check with a parse error in `error`. Use a Function after this check if you also need schema validation. ### Regex match @@ -32,7 +36,7 @@ Enter **Regex Pattern**, for example an email pattern: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ``` -Patterns use RE2's linear-time engine. Lookahead, lookbehind, and backreferences are unsupported and fail validation. To require that content does not contain a pattern, match the pattern and invert `passed` in a Condition. +Patterns use RE2's linear-time engine. Lookahead, lookbehind, and backreferences are unsupported and fail validation. To require that content does not contain a pattern, use a Condition or Function instead: a Regex Match that fails always takes the error port. ### Hallucination check @@ -71,8 +75,8 @@ The picker groups these regional identifiers. Availability depends on the select | Action | Result when PII is found | | --- | --- | -| **Block Request** (default) | `passed: false`, detected entities, and an error summary | -| **Mask PII** | Replaced text in `maskedText`; `passed: true` when masking succeeds | +| **Block Request** (default) | Fails the check through the error port, with the detected entities and an error summary | +| **Mask PII** | Passes, with replaced text in `maskedText` | With no PII found, Mask returns the original text. Read `detectedEntities` to distinguish no detection from successful masking. @@ -84,10 +88,10 @@ Use `` downstream in Mask mode. The original content is s | Reference | Value | | --- | --- | -| `` | Validation outcome; for Mask, whether masking succeeded | +| `` | `true` after a passing check; a failed check takes the error port instead | | `` | Check that ran | | `` | Original checked content | -| `` | Failure message, when present | +| `` | Why the check failed, for the block on the error port | | `` / `` | Grounding score and explanation for Hallucination Check | | `` | PII entities with type, location, detected text, and confidence | | `` | Masked text in Mask mode | @@ -96,16 +100,17 @@ Use `` downstream in Mask mode. The original content is s -Use `passed` for the configured threshold, or `score` for an explicit downstream comparison. Hallucination checks run synchronously; choose the model and chunk count according to the latency your workflow allows. +A score below **Confidence** fails the check through the error port, where `` and `` say why. A grounded answer continues along the normal output. Hallucination checks run synchronously; choose the model and chunk count according to the latency your workflow allows. ## Block PII in input -Branch on `passed` to process clean input or reject detected PII. Selecting only the types relevant to your task keeps the check focused. +Clean input continues along the normal output; detected PII takes the error port to **Reject**. Selecting only the types relevant to your task keeps the check focused. ## Related docs +- [Connections and error paths](/workflows/connections) - [Condition](/workflows/blocks/condition) - [Function](/workflows/blocks/function) - [Credentials and execution-log protection](/platform/credentials) diff --git a/apps/sim/blocks/blocks/guardrails.ts b/apps/sim/blocks/blocks/guardrails.ts index 7680b2fa109..31d779150ca 100644 --- a/apps/sim/blocks/blocks/guardrails.ts +++ b/apps/sim/blocks/blocks/guardrails.ts @@ -31,10 +31,10 @@ export const GuardrailsBlock: BlockConfig = { - Use regex validation for format checking (emails, phone numbers, URLs, etc.) - Use hallucination check to validate LLM outputs against knowledge base content - Use PII detection to block or mask sensitive personal information - - Access validation result with (true/false) + - A failed check leaves through the error port, not the normal output: connect the error port to handle it (in workflow code, check.onError(handler)); the handler reads why as + - Do not branch on with a Condition: on a failed check the Condition never runs, and the run ends with no output - For hallucination check, access (0-10 confidence) and - For PII detection, access and - - Chain with Condition block to handle validation failures `, docsLink: 'https://docs.sim.ai/workflows/blocks/guardrails', category: 'blocks', @@ -309,7 +309,8 @@ Return ONLY the regex pattern - no explanations, no quotes, no forward slashes, }, passed: { type: 'boolean', - description: 'Whether validation passed (true/false)', + description: + 'Whether validation passed. A failed check leaves through the error port, so the normal output only sees true', }, score: { type: 'number', @@ -326,7 +327,8 @@ Return ONLY the regex pattern - no explanations, no quotes, no forward slashes, }, error: { type: 'string', - description: 'Error message if validation failed', + description: + 'Why validation failed, read by the block connected to the error port (onError in workflow code)', }, }, } diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index f4ca6710ade..2319e24a6f1 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -61,7 +61,7 @@ function sharedRules(extra: { renames?: string; patterns?: string; debug?: strin - **References**: \`${SOURCE_ENTRY_FILE}\` reads \`x.content\`, text as \`\` t\`…\` \`\`, env as \`env.NAME\`. A function file (\`codeFile('./functions/x.js')\`) reads \`$ref..\` (key: display name lowercased, no spaces or dots), \`$ref.loop.currentItem\` / \`.index\` in a body (\`parallel\` too), \`$env.NAME\`; \`.py\`/\`.sh\` files \`\`, \`{{NAME}}\`. A block that never ran reads \`null\` (\`''\` in text). ${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any builder: \`${PARAMS_COMMAND} \`): - Condition: keys test in order, first true wins, \`else: true\` last; wire \`route.high.to(alert)\`. - - Loop: \`const each = loop.forEach('Each Order', { collection: recent.rows }, (p) => {\`; inside, \`p.currentItem.data.orderId\` and \`p.index\`; after, \`each.results\`. + - Loop: \`const each = loop.forEach('Each Order', { collection: recent.rows }, (p) => {\`; inside \`p.currentItem.data.orderId\`, \`p.index\`; after \`each.results[i][0]\`. - Failure: \`lookup.onError(failed)\`; \`failed\` reads its message as \`lookup.error\` (any block; a Function's adds the line: \`.errorMessage\` doesn't). - Retry: an \`api\` block resends with \`retries: 3\`, \`retryDelayMs: 500\`; any block's Retry on fail: 3rd argument, \`{ retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } }\`. - Child: \`const enrich = runWorkflow('Enrich Lead', {\` with \`workflowId: childWorkflow('enrich-lead')\`, \`inputMapping: { email: start.email }\`; read \`enrich.result.data.\`. 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 3b46a1447a4..6f6168828ef 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 @@ -180,7 +180,35 @@ describe('sim workflows source params', () => { await params('table.upsertRow', '--full') const full = stdoutJson() as { builder: { params: { common: unknown[] } } } expect(full.builder.params.common.length).toBeGreaterThan(brief.builder.required.length) - expect(JSON.stringify(full).length).toBeGreaterThan(JSON.stringify(brief).length * 2) + expect(JSON.stringify(full.builder).length).toBeGreaterThan( + JSON.stringify(brief.builder).length * 2 + ) + }) + + it('names the --full lookup in the JSON brief, and that lookup types the optional params', async () => { + cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, FIXTURE_TEXT) + writeBase() + + await params('slack.tool.sendMessage') + const { builder, next } = stdoutJson() as { + builder: { optional: string[] } + next?: { command: string; reason: string } + } + const prefix = 'sim workflows source params ' + expect(next?.command.startsWith(prefix)).toBe(true) + + vi.mocked(console.log).mockClear() + const source = new Command('source') + attachWorkflowSourceParams(source) + source.commands.forEach((command) => command.exitOverride()) + const argv = (next?.command ?? '').slice(prefix.length).split(' ') + await source.parseAsync(['node', 'source', 'params', ...argv]) + const full = stdoutJson() as { + builder: { key: string; params: { common: Array<{ key: string; type: string }> } } + } + expect(full.builder.key).toBe('slack.sendMessage') + const typed = full.builder.params.common.map((param) => param.key) + expect(builder.optional.every((key) => typed.includes(key))).toBe(true) }) it('keeps the call signature of a builder whose required params core.d.ts types', async () => { 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 1eb43699744..fec1bcfc2ab 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts @@ -7,12 +7,14 @@ import { } from '@sim/workflow-sdk/codegen' import type { Command } from 'commander' import { printLine } from '#sim-cli/output/io' +import { simInvocation } from '#sim-cli/runtime/run-next' import { isMachineFormat, type ResolvedProfile } from '../../config/index' import { actingProfileFrom } from '../../context' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' import { recordedWorkspace } from './source-dir' import { cachedCatalog, cachedSourceCatalog } from './source-tree' +import { shellWord } from './source-ui' const PARAMS_HELP = ` Prints a builder in brief (an example call, the required params with types, the optional ones by @@ -72,8 +74,19 @@ export function attachWorkflowSourceParams(source: Command): void { switch (found.kind) { case 'builder': if (machine) { - const builder = options.full ? found.reference : compactBuilder(found.reference) - printProtocolResult(profile.output, { builder }) + printProtocolResult( + profile.output, + options.full + ? { builder: found.reference } + : { + builder: compactBuilder(found.reference), + next: { + command: `${simInvocation(command)} workflows source params ${found.reference.key} --dir ${shellWord(options.dir)} --full`, + reason: + "Every param's type, enum, default and doc: the brief names the optional ones only.", + }, + } + ) } else { printLine( (options.full ? renderBuilderReference : renderCompactBuilder)(found.reference) diff --git a/packages/workflow-code/src/json-fields.ts b/packages/workflow-code/src/json-fields.ts index 542a4498399..7b69a7e4195 100644 --- a/packages/workflow-code/src/json-fields.ts +++ b/packages/workflow-code/src/json-fields.ts @@ -229,7 +229,7 @@ export function refValueKind( } const block = scope.block(head.name) if (!block || segments.length === 0) return 'untyped' - // A loop or parallel's `results` is the array of every iteration's output. + // A loop or parallel's `results` holds one list per iteration, of its body blocks' outputs. if (block.subflow) { const [first] = segments return segments.length === 1 && first?.kind === 'name' && first.name === 'results' diff --git a/packages/workflow-sdk/cookbook/examples/agents.ts b/packages/workflow-sdk/cookbook/examples/agents.ts index 2fbeb5e7030..d77e5e75663 100644 --- a/packages/workflow-sdk/cookbook/examples/agents.ts +++ b/packages/workflow-sdk/cookbook/examples/agents.ts @@ -66,10 +66,10 @@ export default workflow( inputMapping: { email: start.email }, }) - // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its - // position; each.results lists every branch's output once all finish. (loop.forEach is the - // sequential form.) In a function code file inside the body, the same values are - // $ref.parallel.currentItem and $ref.parallel.index. + // Parallel: one branch per item, run at once (loop.forEach is the sequential form). + // p.currentItem is the item and p.index its position; once all finish, each.results[i] lists + // branch i's body-block outputs (one block: each.results[i][0]). In a function code file + // inside the body, the same values are $ref.parallel.currentItem and $ref.parallel.index. const each = parallel.collection('Each Domain', { collection: start.domains }, (p) => { const brief = agent('Company Brief', { model: 'claude-sonnet-4-6', diff --git a/packages/workflow-sdk/cookbook/examples/cookbook.ts b/packages/workflow-sdk/cookbook/examples/cookbook.ts index 4bfb92c9607..adf79ce20c9 100644 --- a/packages/workflow-sdk/cookbook/examples/cookbook.ts +++ b/packages/workflow-sdk/cookbook/examples/cookbook.ts @@ -138,8 +138,8 @@ export default workflow('Cookbook', { description: 'One example of each common b else: true, }) - // Loop over a list: p.currentItem is one element and p.index its position; the loop's results - // is the list of iteration outputs. In js`` code a reference is the value itself, not text + // Loop over a list: p.currentItem is one element and p.index its position; each.results[i] is + // iteration i's body-block outputs (one block: [i][0]). In js`` code a reference is the value itself, not text // spliced in: write it where an expression goes, never inside quotes ('${x}' would give the // JSON, quotes included). A function code file (code: codeFile('./functions/line.js')) reads // other blocks as $ref.. ($ref.recentorders.rows) and, inside the loop body, diff --git a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts index 04ac9f761e6..2c962f01a06 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 table,\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 types 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 or built-in\n // operation (.tool., also table.tool.*, knowledge.tool.*, file.tool.*; the\n // params given here are fixed, the model fills the rest) and 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 table.tool.queryRows({ tableId: table(\u0027orders\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// Index: file:line, a name on that line, what it shows (the comment above each line explains it).\n// cookbook.ts:50 trigger.schedule: daily schedule (trigger.start just above)\n// cookbook.ts:59 agent: structured output (responseFormat), retry as block meta\n// cookbook.ts:86 condition: keys tested in order, first true wins, else: true last\n// cookbook.ts:93 fn: inline JavaScript in js``\n// cookbook.ts:98 table.queryRows: outputs rows, each row { id, data }\n// cookbook.ts:109 table.upsertRow: conflictColumn; insertRow, updateRowsByFilter\n// cookbook.ts:116 knowledge.search: knowledge base search\n// cookbook.ts:132 human: human in the loop: approval.submission.\n// cookbook.ts:147 loop.forEach: p.currentItem, p.index, each.results; $ref.loop in code files\n// cookbook.ts:180 fn: branches that rejoin: ?? picks the one that ran\n// cookbook.ts:186 response: body and status\n// cookbook.ts:215 onError: error path: x.error, a Function\u0027s x.errorMessage\n// integrations.ts:24 trigger.webhook: webhook with a token\n// integrations.ts:31 trigger.schedule: cron schedule\n// integrations.ts:40 api: HTTP request: headers, retries, retryDelayMs\n// integrations.ts:50 table.updateRowById: update one row by id\n// integrations.ts:87 onError: error path to a response\n// agents.ts:32 router: routes the model picks from\n// agents.ts:52 tools: agent tools: custom, MCP, integration, table, child workflow\n// agents.ts:64 runWorkflow: child workflow: inputMapping, enrich.result.data.\n// agents.ts:73 parallel.collection: parallel fan-out\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. Retry is block meta, the third\n // argument (not on a trigger, human, loop or parallel): a failed run is tried up to maxTries.\n const check = agent(\n \u0027Check Order\u0027,\n {\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 { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } }\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 }: recent.rows[0].data.status) 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: replaces the row whose conflictColumn (a unique column, by name) matches data, else\n // inserts one, so a second run for the same order rewrites it and a column missing from data\n // is cleared (table.updateRowsByFilter changes only the columns it names). table.insertRow\n // takes the same data without conflictColumn and adds a row every run. data is keyed by column\n // name: a column declared as `phone: column.string({ name: \u0027mobile\u0027 })` is written as\n // { mobile: ... }.\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 // Branches that rejoin: a block both lead to runs once, after whichever branch ran. A block\n // that did not run reads as null in js`` code and as \u0027\u0027 in t`` text, so a function picks the\n // branch\u0027s value with ?? and one response replies for both.\n const size = condition(\u0027Order Size\u0027, { large: js`${shape.result.cents} >= 100000`, else: true })\n const review = table.upsertRow(\u0027Keep Open\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n const accept = table.upsertRow(\u0027Mark Answered\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027answered\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n const status = fn(\u0027Pick Status\u0027, {\n code: js`return ${review.row.data.status} ?? ${accept.row.data.status}`,\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, {\n body: { risk: check.risk, id: t`${shape.result.id}`, status: t`${status.result}` },\n })\n const rejected = response(\u0027Respond Rejected\u0027, {\n dataMode: \u0027json\u0027,\n data: { status: \u0027rejected\u0027 },\n })\n // Error path: shape.onError(invalid) runs invalid when the code throws. shape.error leads with\n // the line and code that threw; shape.errorMessage is the thrown message alone, for the caller.\n const invalid = response(\u0027Respond Invalid\u0027, { body: { error: shape.errorMessage }, status: 422 })\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(size)\n size.large.to(review)\n size.else.to(accept)\n review.to(status)\n accept.to(status)\n status.to(reply)\n shape.onError(invalid)\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 // retries resend only the request, after a timeout, a reset, a 429 or a 5xx, before the\n // block fails (block meta retry reruns the whole block).\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 retries: 3,\n retryDelayMs: 500,\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 table,\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 types 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 or built-in\n // operation (.tool., also table.tool.*, knowledge.tool.*, file.tool.*; the\n // params given here are fixed, the model fills the rest) and 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 table.tool.queryRows({ tableId: table(\u0027orders\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 (loop.forEach is the sequential form).\n // p.currentItem is the item and p.index its position; once all finish, each.results[i] lists\n // branch i\u0027s body-block outputs (one block: each.results[i][0]). In a function code file\n // inside the body, the same values are $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// Index: file:line, a name on that line, what it shows (the comment above each line explains it).\n// cookbook.ts:50 trigger.schedule: daily schedule (trigger.start just above)\n// cookbook.ts:59 agent: structured output (responseFormat), retry as block meta\n// cookbook.ts:86 condition: keys tested in order, first true wins, else: true last\n// cookbook.ts:93 fn: inline JavaScript in js``\n// cookbook.ts:98 table.queryRows: outputs rows, each row { id, data }\n// cookbook.ts:109 table.upsertRow: conflictColumn; insertRow, updateRowsByFilter\n// cookbook.ts:116 knowledge.search: knowledge base search\n// cookbook.ts:132 human: human in the loop: approval.submission.\n// cookbook.ts:147 loop.forEach: p.currentItem, p.index, each.results; $ref.loop in code files\n// cookbook.ts:180 fn: branches that rejoin: ?? picks the one that ran\n// cookbook.ts:186 response: body and status\n// cookbook.ts:215 onError: error path: x.error, a Function\u0027s x.errorMessage\n// integrations.ts:24 trigger.webhook: webhook with a token\n// integrations.ts:31 trigger.schedule: cron schedule\n// integrations.ts:40 api: HTTP request: headers, retries, retryDelayMs\n// integrations.ts:50 table.updateRowById: update one row by id\n// integrations.ts:87 onError: error path to a response\n// agents.ts:32 router: routes the model picks from\n// agents.ts:52 tools: agent tools: custom, MCP, integration, table, child workflow\n// agents.ts:64 runWorkflow: child workflow: inputMapping, enrich.result.data.\n// agents.ts:73 parallel.collection: parallel fan-out\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. Retry is block meta, the third\n // argument (not on a trigger, human, loop or parallel): a failed run is tried up to maxTries.\n const check = agent(\n \u0027Check Order\u0027,\n {\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 { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } }\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 }: recent.rows[0].data.status) 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: replaces the row whose conflictColumn (a unique column, by name) matches data, else\n // inserts one, so a second run for the same order rewrites it and a column missing from data\n // is cleared (table.updateRowsByFilter changes only the columns it names). table.insertRow\n // takes the same data without conflictColumn and adds a row every run. data is keyed by column\n // name: a column declared as `phone: column.string({ name: \u0027mobile\u0027 })` is written as\n // { mobile: ... }.\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; each.results[i] is\n // iteration i\u0027s body-block outputs (one block: [i][0]). 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 // Branches that rejoin: a block both lead to runs once, after whichever branch ran. A block\n // that did not run reads as null in js`` code and as \u0027\u0027 in t`` text, so a function picks the\n // branch\u0027s value with ?? and one response replies for both.\n const size = condition(\u0027Order Size\u0027, { large: js`${shape.result.cents} >= 100000`, else: true })\n const review = table.upsertRow(\u0027Keep Open\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n const accept = table.upsertRow(\u0027Mark Answered\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027answered\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n const status = fn(\u0027Pick Status\u0027, {\n code: js`return ${review.row.data.status} ?? ${accept.row.data.status}`,\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, {\n body: { risk: check.risk, id: t`${shape.result.id}`, status: t`${status.result}` },\n })\n const rejected = response(\u0027Respond Rejected\u0027, {\n dataMode: \u0027json\u0027,\n data: { status: \u0027rejected\u0027 },\n })\n // Error path: shape.onError(invalid) runs invalid when the code throws. shape.error leads with\n // the line and code that threw; shape.errorMessage is the thrown message alone, for the caller.\n const invalid = response(\u0027Respond Invalid\u0027, { body: { error: shape.errorMessage }, status: 422 })\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(size)\n size.large.to(review)\n size.else.to(accept)\n review.to(status)\n accept.to(status)\n status.to(reply)\n shape.onError(invalid)\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 // retries resend only the request, after a timeout, a reset, a 429 or a 5xx, before the\n // block fails (block meta retry reruns the whole block).\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 retries: 3,\n retryDelayMs: 500,\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 0a40df3fc47..9e9ef9311be 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/**\n * JavaScript code (condition expressions, inline function code), kept exactly as written: like\n * `String.raw`, `` js`/\\s+/` `` is `/\\s+/`. Only `` \\` `` and `\\${` are escapes, for a backtick\n * and a literal `${`. So are `py`, `sh`, `json` and `md`; `t` text reads like a JS string.\n */\nexport declare const js: typeof t\n/** Python code, kept exactly as written (see {@link js}). */\nexport declare const py: typeof t\n/** Shell code, kept exactly as written (see {@link js}). */\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 or a value that looks like a credential. Valid only\n * on a param of a block the stored workflow already has (same name and type) and holds a value\n * for, or as the `value` of a variable the stored workflow declares; 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 * What a block outputs when it fails and an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`): the failure message `error` on every block, plus the error outputs `E` its catalog\n * entry declares (a Function\u0027s `errorMessage`, the thrown message without its line and code). A\n * check refuses each on a block without an error edge, which fails the run instead. An output the\n * block declares under the same name keeps its declared type.\n */\ntype ErrorOutputs = {\n readonly [K in \u0027error\u0027 | E as [O] extends [Record] ? never : K]: Ref\n}\n\n/** A block: a node whose outputs can be referenced, and its error outputs after an `onError` edge. */\nexport type Block = Node & Ref & ErrorOutputs\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\n/**\n * A loop container: `forEach` over a list, `for` a count, `while` or `doWhile` a condition. The\n * body callback declares the blocks each iteration runs and wires the first from the scope\n * (`p.to(first)`), which reads the iteration as `p.currentItem` and `p.index` (a code file:\n * `$ref.loop.currentItem`). After it, `each.results` lists every iteration\u0027s output, and\n * `each.to(next)` wires what runs once all finish.\n * @example const each = loop.forEach(\u0027Each Order\u0027, { collection: orders.rows }, (p) => { const line = fn(\u0027Line\u0027, { code: js`return ${p.currentItem.data.id}` }); p.to(line) })\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 }`, with `errorOutputs` when the block declares any; without generated types\n * 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/** The error outputs a special builder\u0027s block declares; a builder whose block has any passes them. */\ntype SpecialErrorOutputs = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { errorOutputs: infer E extends string }\n ? E\n : never\n : never\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/**\n * A condition: named branches tested in order, top to bottom; the first whose expression holds\n * runs, and `else` (last, written `true`) runs when none does. Wire each as `x..to(block)`.\n * @example condition(\u0027Route\u0027, { big: js`${order.total} >= 500`, small: js`${order.total} < 50`, else: true })\n */\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, SpecialErrorOutputs<\u0027fn\u0027>>\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" +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/**\n * JavaScript code (condition expressions, inline function code), kept exactly as written: like\n * `String.raw`, `` js`/\\s+/` `` is `/\\s+/`. Only `` \\` `` and `\\${` are escapes, for a backtick\n * and a literal `${`. So are `py`, `sh`, `json` and `md`; `t` text reads like a JS string.\n */\nexport declare const js: typeof t\n/** Python code, kept exactly as written (see {@link js}). */\nexport declare const py: typeof t\n/** Shell code, kept exactly as written (see {@link js}). */\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 or a value that looks like a credential. Valid only\n * on a param of a block the stored workflow already has (same name and type) and holds a value\n * for, or as the `value` of a variable the stored workflow declares; 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 * What a block outputs when it fails and an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`): the failure message `error` on every block, plus the error outputs `E` its catalog\n * entry declares (a Function\u0027s `errorMessage`, the thrown message without its line and code). A\n * check refuses each on a block without an error edge, which fails the run instead. An output the\n * block declares under the same name keeps its declared type.\n */\ntype ErrorOutputs = {\n readonly [K in \u0027error\u0027 | E as [O] extends [Record] ? never : K]: Ref\n}\n\n/** A block: a node whose outputs can be referenced, and its error outputs after an `onError` edge. */\nexport type Block = Node & Ref & ErrorOutputs\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 /**\n * One entry per iteration (a parallel: per branch), each the list of outputs of the body blocks\n * that ran in it, in the order they finished. With one block in the body its output is\n * `results[i][0]`; in code, `results.flat()` lists every output.\n */\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\n/**\n * A loop container: `forEach` over a list, `for` a count, `while` or `doWhile` a condition. The\n * body callback declares the blocks each iteration runs and wires the first from the scope\n * (`p.to(first)`), which reads the iteration as `p.currentItem` and `p.index` (a code file:\n * `$ref.loop.currentItem`). After it, `each.results[i]` lists iteration `i`\u0027s body-block outputs\n * (one block: `each.results[i][0]`), and `each.to(next)` wires what runs once all finish.\n * @example const each = loop.forEach(\u0027Each Order\u0027, { collection: orders.rows }, (p) => { const line = fn(\u0027Line\u0027, { code: js`return ${p.currentItem.data.id}` }); p.to(line) })\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 }`, with `errorOutputs` when the block declares any; without generated types\n * 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/** The error outputs a special builder\u0027s block declares; a builder whose block has any passes them. */\ntype SpecialErrorOutputs = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { errorOutputs: infer E extends string }\n ? E\n : never\n : never\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/**\n * A condition: named branches tested in order, top to bottom; the first whose expression holds\n * runs, and `else` (last, written `true`) runs when none does. Wire each as `x..to(block)`.\n * @example condition(\u0027Route\u0027, { big: js`${order.total} >= 500`, small: js`${order.total} < 50`, else: true })\n */\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, SpecialErrorOutputs<\u0027fn\u0027>>\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/core.d.ts b/packages/workflow-sdk/src/core.d.ts index ab4495f948e..e78c54bb623 100644 --- a/packages/workflow-sdk/src/core.d.ts +++ b/packages/workflow-sdk/src/core.d.ts @@ -591,7 +591,12 @@ export interface SubflowScope extends Node { * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there. */ export interface SubflowOutput { - results: Json[] + /** + * One entry per iteration (a parallel: per branch), each 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 + * `results[i][0]`; in code, `results.flat()` lists every output. + */ + results: Json[][] index: number currentItem: Json items: Json[] @@ -606,8 +611,8 @@ type Collection = AnyRef | Template | Json[] | string * A loop container: `forEach` over a list, `for` a count, `while` or `doWhile` a condition. The * body callback declares the blocks each iteration runs and wires the first from the scope * (`p.to(first)`), which reads the iteration as `p.currentItem` and `p.index` (a code file: - * `$ref.loop.currentItem`). After it, `each.results` lists every iteration's output, and - * `each.to(next)` wires what runs once all finish. + * `$ref.loop.currentItem`). After it, `each.results[i]` lists iteration `i`'s body-block outputs + * (one block: `each.results[i][0]`), and `each.to(next)` wires what runs once all finish. * @example const each = loop.forEach('Each Order', { collection: orders.rows }, (p) => { const line = fn('Line', { code: js`return ${p.currentItem.data.id}` }); p.to(line) }) */ export declare const loop: { diff --git a/packages/workflow-sdk/test/negative/rejected.ts b/packages/workflow-sdk/test/negative/rejected.ts index e89365fe4ed..da1d2bdf765 100644 --- a/packages/workflow-sdk/test/negative/rejected.ts +++ b/packages/workflow-sdk/test/negative/rejected.ts @@ -124,6 +124,14 @@ export default workflow('Rejected', {}, () => { }) }) + // A loop's `results[i]` is the list of iteration `i`'s body-block outputs, not one output. + const perLead = loop.forEach('Each lead brief', { collection: leads.rows }, (p) => { + p.to(agent('Brief', { model: 'claude-sonnet-5-5', messages: [] })) + }) + t`${perLead.results[0][0].content}` + // @ts-expect-error `results[0]` lists the first iteration's outputs: read one as `results[0][0]` + t`${perLead.results[0].content}` + // A Function also outputs `errorMessage` on failure; a block that declares no such output does not. const parse = fn('Parse', { code: js`return 1` }) parse.error satisfies Ref From 3adffa05638dcfb604465721675cda1e87031715 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:10:34 -0800 Subject: [PATCH 2/2] fix(sim-cli): keep the typed workspace and options in the params --full next step --- .../protocol/workflow-source-params.test.ts | 32 +++++++++++++------ .../protocol/workflow-source-params.ts | 5 ++- 2 files changed, 25 insertions(+), 12 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 6f6168828ef..0a58c8fa950 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 @@ -185,24 +185,38 @@ describe('sim workflows source params', () => { ) }) - it('names the --full lookup in the JSON brief, and that lookup types the optional params', async () => { + it('names the --full lookup in the JSON brief as typed, and that lookup types the optional params', async () => { cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, FIXTURE_TEXT) writeBase() + /** The CLI from its root, so a printed command line runs as typed. */ + const sim = async (...argv: string[]) => { + const root = new Command('sim').option('--workspace ') + const source = root.command('workflows').command('source') + attachWorkflowSourceParams(source) + source.commands.forEach((command) => command.exitOverride()) + await root.parseAsync(['node', 'sim', ...argv]) + } - await params('slack.tool.sendMessage') + await sim( + '--workspace', + WORKSPACE_ID, + 'workflows', + 'source', + 'params', + 'slack.tool.sendMessage', + '--dir', + dir + ) const { builder, next } = stdoutJson() as { builder: { optional: string[] } next?: { command: string; reason: string } } - const prefix = 'sim workflows source params ' - expect(next?.command.startsWith(prefix)).toBe(true) + const words = (next?.command ?? '').split(' ').map((word) => word.replace(/^'(.*)'$/, '$1')) + expect(words.slice(0, 3)).toEqual(['sim', '--workspace', WORKSPACE_ID]) + expect(words).toContain('--full') vi.mocked(console.log).mockClear() - const source = new Command('source') - attachWorkflowSourceParams(source) - source.commands.forEach((command) => command.exitOverride()) - const argv = (next?.command ?? '').slice(prefix.length).split(' ') - await source.parseAsync(['node', 'source', 'params', ...argv]) + await sim(...words.slice(1)) const full = stdoutJson() as { builder: { key: string; params: { common: Array<{ key: string; type: string }> } } } 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 fec1bcfc2ab..f637f497629 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts @@ -7,14 +7,13 @@ import { } from '@sim/workflow-sdk/codegen' import type { Command } from 'commander' import { printLine } from '#sim-cli/output/io' -import { simInvocation } from '#sim-cli/runtime/run-next' +import { typedCommandLine } from '#sim-cli/runtime/run-next' import { isMachineFormat, type ResolvedProfile } from '../../config/index' import { actingProfileFrom } from '../../context' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' import { recordedWorkspace } from './source-dir' import { cachedCatalog, cachedSourceCatalog } from './source-tree' -import { shellWord } from './source-ui' const PARAMS_HELP = ` Prints a builder in brief (an example call, the required params with types, the optional ones by @@ -81,7 +80,7 @@ export function attachWorkflowSourceParams(source: Command): void { : { builder: compactBuilder(found.reference), next: { - command: `${simInvocation(command)} workflows source params ${found.reference.key} --dir ${shellWord(options.dir)} --full`, + command: `${typedCommandLine(command, [found.reference.key])} --full`, reason: "Every param's type, enum, default and doc: the brief names the optional ones only.", },