From 87936a030d31ea6c6a816077e010adc69d253816 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 18:32:11 -0800 Subject: [PATCH 1/3] fix(workflow-code): keep js template escapes verbatim, add table/knowledge/file agent tool forms, pin create fingerprint - js/py/sh/json/md tagged templates now store the raw text written between the backticks (only \` and \${ are escapes), so js`/\s+/` stores /\s+/ instead of silently dropping the backslash. The printer writes code back so compile reads exactly the stored text, using ${'...'} for what raw text cannot hold. - The catalog marks the built-in blocks the agent tool picker offers (agentTool), so table.tool.queryRows(...), knowledge.tool.search(...) and file.tool.read(...) compile and print instead of requiring raw(). - A source write now prints its answer with the workspace's resource keys for any resource the source wrote by id, so the returned fingerprint matches the next read and a pinned deploy (create --deploy no longer fails with a draft-changed conflict). --- .../content/docs/workflows/code/syntax.mdx | 2 + apps/docs/openapi-v2-resources.json | 5 + .../components/tool-input/tool-input.tsx | 2 +- .../sub-block/components/tool-input/utils.ts | 26 +--- apps/sim/blocks/agent-tools.ts | 27 ++++ .../lib/api/contracts/v2/source-catalog.ts | 6 + .../apply-workflow-source.integration.ts | 65 +++++++++ .../application/source-pipeline/commit.ts | 2 +- .../source-pipeline/evaluate/resolve.ts | 2 +- .../application/source-pipeline/outcome.ts | 71 +++++++--- .../application/source-pipeline/plan.ts | 4 +- .../sim/lib/workflows/code/catalog/project.ts | 2 + apps/sim/lib/workflows/code/corpus/values.ts | 7 +- .../lib/workflows/code/real-catalog.test.ts | 55 ++++++++ packages/sim-cli/src/generated/v2-api.ts | 1 + .../src/canonicalize/index.test.ts | 11 +- packages/workflow-code/src/catalog/types.ts | 5 + packages/workflow-code/src/compile/SYNTAX.md | 11 +- .../workflow-code/src/compile/characters.ts | 20 ++- packages/workflow-code/src/compile/tools.ts | 2 +- packages/workflow-code/src/compile/values.ts | 38 +++++- packages/workflow-code/src/print/strings.ts | 99 ++++++++++++-- packages/workflow-code/src/print/values.ts | 22 +++- .../src/print/verbatim-templates.test.ts | 124 ++++++++++++++++++ .../workflow-code/src/random.test-helpers.ts | 10 ++ packages/workflow-code/src/sdk.ts | 26 +++- .../src/codegen/core-text.generated.ts | 2 +- packages/workflow-sdk/src/core.d.ts | 10 +- .../workflow-sdk/test/fixtures/catalog.json | 11 +- 29 files changed, 573 insertions(+), 95 deletions(-) create mode 100644 apps/sim/blocks/agent-tools.ts create mode 100644 packages/workflow-code/src/print/verbatim-templates.test.ts create mode 100644 packages/workflow-code/src/random.test-helpers.ts diff --git a/apps/docs/content/docs/workflows/code/syntax.mdx b/apps/docs/content/docs/workflows/code/syntax.mdx index c21b0153694..c3fc3c08730 100644 --- a/apps/docs/content/docs/workflows/code/syntax.mdx +++ b/apps/docs/content/docs/workflows/code/syntax.mdx @@ -160,6 +160,8 @@ The optional third argument holds what belongs to the block, not to its settings | `` json`…` `` | JSON text kept as written | | `` md`…` `` | Markdown, such as a note's content | + Code and markup (`js`, `py`, `sh`, `json`, `md`) are stored exactly as written between the backticks, like `String.raw`: `` js`/\s+/.test(x)` `` stores `/\s+/.test(x)`. Only `` \` `` and `\${` are escapes, for a backtick and a literal `${` in the code. A `t` template is text and reads like a JavaScript string, so `\n` in it is a newline. + ### Resource helpers A key is the resource's stable key in the workspace; `.sim/sdk/workspace.d.ts` lists them. A key with no live resource is `E_MAT_UNKNOWN_RESOURCE` on apply. diff --git a/apps/docs/openapi-v2-resources.json b/apps/docs/openapi-v2-resources.json index 44b2270bf19..2cc043e6c77 100644 --- a/apps/docs/openapi-v2-resources.json +++ b/apps/docs/openapi-v2-resources.json @@ -32073,6 +32073,11 @@ "description": "At most one per workflow.", "type": "boolean" }, + "agentTool": { + "description": "A built-in block the agent tool picker offers beside integrations, so its operations have an agent-tool form.", + "type": "boolean", + "const": true + }, "subBlocks": { "type": "array", "items": { diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx index 7f007010acc..87e67ab3618 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx @@ -68,7 +68,6 @@ import { import type { StoredTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/types' import { isAgentToolBlock, - isCoreAgentToolBlock, isCustomToolAlreadySelected, isMcpToolAlreadySelected, isWorkflowAlreadySelected, @@ -81,6 +80,7 @@ import { useActiveSearchTarget, } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/providers/active-search-target-provider' import { getAllBlocks, getBlock } from '@/blocks' +import { isCoreAgentToolBlock } from '@/blocks/agent-tools' import { isCustomBlockType } from '@/blocks/custom/build-config' import { useCustomBlockOverlayVersion } from '@/blocks/custom/client-overlay' import { getTileIconColorClass } from '@/blocks/icon-color' diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts index 710674aeea2..3f3f6ed0522 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts @@ -1,25 +1,9 @@ -import { stripVersionSuffix } from '@sim/utils/string' import type { StoredTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/types' +import { isCoreAgentToolBlock } from '@/blocks/agent-tools' import type { BlockConfig } from '@/blocks/types' import { resolveModelProviderId } from '@/blocks/utils' import { supportsToolUsageControl } from '@/providers/models' -/** - * Core blocks the agent tool picker offers even though they are not - * `category: 'tools'`. Stored as BASE types and matched after stripping the - * `_vN` suffix, so a new version never has to be re-listed here. - */ -const CORE_AGENT_TOOL_TYPES = new Set([ - 'api', - 'webhook_request', - 'workflow', - 'workflow_input', - 'knowledge', - 'function', - 'table', - 'file', -]) - /** * Checks whether a registered block should appear in the agent tool picker. * @@ -35,14 +19,6 @@ export function isAgentToolBlock( return isCoreAgentToolBlock(block) } -/** - * Checks whether a block is one of the platform's core agent tools, which the - * picker lists under "Built-in Tools" rather than "Integrations". - */ -export function isCoreAgentToolBlock(block: Pick): boolean { - return CORE_AGENT_TOOL_TYPES.has(stripVersionSuffix(block.type)) -} - /** * Checks if an MCP tool is already selected. */ diff --git a/apps/sim/blocks/agent-tools.ts b/apps/sim/blocks/agent-tools.ts new file mode 100644 index 00000000000..c34ec17870a --- /dev/null +++ b/apps/sim/blocks/agent-tools.ts @@ -0,0 +1,27 @@ +import { stripVersionSuffix } from '@sim/utils/string' +import type { BlockConfig } from '@/blocks/types' + +/** + * Core blocks the agent tool picker offers even though they are not + * `category: 'tools'`. Stored as BASE types and matched after stripping the + * `_vN` suffix, so a new version never has to be re-listed here. + */ +const CORE_AGENT_TOOL_TYPES = new Set([ + 'api', + 'webhook_request', + 'workflow', + 'workflow_input', + 'knowledge', + 'function', + 'table', + 'file', +]) + +/** + * Checks whether a block is one of the platform's core agent tools, which the + * picker lists under "Built-in Tools" rather than "Integrations" and the + * workflow source catalog marks `agentTool`. + */ +export function isCoreAgentToolBlock(block: Pick): boolean { + return CORE_AGENT_TOOL_TYPES.has(stripVersionSuffix(block.type)) +} diff --git a/apps/sim/lib/api/contracts/v2/source-catalog.ts b/apps/sim/lib/api/contracts/v2/source-catalog.ts index 57a63b68c0f..32e70d7aa9a 100644 --- a/apps/sim/lib/api/contracts/v2/source-catalog.ts +++ b/apps/sim/lib/api/contracts/v2/source-catalog.ts @@ -318,6 +318,12 @@ const catalogBlockSchema = z .optional() .describe('Trigger mode support.'), singleInstance: z.boolean().optional().describe('At most one per workflow.'), + agentTool: z + .literal(true) + .optional() + .describe( + 'A built-in block the agent tool picker offers beside integrations, so its operations have an agent-tool form.' + ), subBlocks: z .array(z.union([catalogSubBlockSchema, sharedSubBlockRefSchema, triggerSubBlocksRefSchema])) .describe('Configuration fields in declared order, inline or by reference.'), diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts index a9f74eac30c..470220a4a1a 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.integration.ts @@ -57,6 +57,7 @@ import { createWorkflowFromSource, planWorkflowSource, } from '@/lib/workflows/application/apply-workflow-source' +import { deployWorkflow } from '@/lib/workflows/application/deployments' import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' import { WorkflowSourceRejectedError } from '@/lib/workflows/application/source-error' import { @@ -356,6 +357,70 @@ export default workflow('Each item', {}, () => { expect(result.diff.noop).toBe(true) }) +check( + 'a create naming tables by id answers with the fingerprint its next read and a pinned deploy see', + async () => { + const tableNamed = async (keyed: boolean) => { + const name = `tool_rows_${generateId().slice(0, 8)}` + const created = await createTableUseCase.execute({ + principal, + input: { workspaceId, name, schema: { columns: [{ name: 'email', type: 'string' }] } }, + }) + if (keyed) { + await claimResourceKey({ + workspaceId, + kind: 'table', + key: name, + resourceId: created.table.id, + origin: 'adopted', + createdBy: ownerId, + }) + } + return created.table.id + } + const keyed = await tableNamed(true) + const unkeyed = await tableNamed(false) + const tableTool = (tableId: string) => + `raw({ type: 'table_v2', toolId: 'table_query_rows', operation: 'query_rows', modes: {}, params: { tableId: '${tableId}' } })` + const created = await withPermissionGroupScope(() => + createWorkflowFromSource.execute({ + principal, + input: { + workspaceId, + name: `Source create ${generateId()}`, + files: { + 'workflow.ts': `// @sim-sdk 1 +import { agent, raw, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Table tools ${generateId().slice(0, 8)}', {}, () => { + const start = trigger.start('Start', { inputFormat: { q: 'string' } }) + const lookup = agent('Lookup', { + model: 'claude-sonnet-4-5', + messages: [{ role: 'user', content: start.q }], + tools: [${tableTool(keyed)}, ${tableTool(unkeyed)}], + }) + start.to(lookup) +}) +`, + }, + }, + }) + ) + expect(created.applied).toBe(true) + + const deployed = await deployWorkflow.execute({ + principal, + input: { + workflowId: created.workflowId, + requestId: generateId(), + expectedDraftFingerprint: created.base.fingerprint, + }, + }) + expect(deployed.success).toBe(true) + expect((await getSource(created.workflowId)).base.fingerprint).toBe(created.base.fingerprint) + } +) + check('create keeps the function file name the source wrote', async () => { const created = await withPermissionGroupScope(() => createWorkflowFromSource.execute({ diff --git a/apps/sim/lib/workflows/application/source-pipeline/commit.ts b/apps/sim/lib/workflows/application/source-pipeline/commit.ts index 251b05fe908..dac11cb5ec7 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/commit.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/commit.ts @@ -87,7 +87,7 @@ export async function commitSource( target.kind === 'new' ? 'Created workflow from source' : 'Applied workflow source', logContext ) - return shapeOutcome(frame, printWritten(planned, committed.state), { + return shapeOutcome(frame, await printWritten(planned, committed.state, { allocate: true }), { applied: true, wroteSourceMeta: true, diff: plan.diff, diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts index 7e744f3a846..e57fb190a9d 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts @@ -36,7 +36,7 @@ import { loadAvailableResourceKeys, loadResourceKeyResolver } from '@/lib/workfl * `primary`, falling back to `fallback` for a key, id or name it does not resolve. Whether an id * is built in is `primary`'s answer alone. */ -function withFallback( +export function withFallback( primary: ResourceKeyResolver, fallback: Pick ): ResourceKeyResolver { diff --git a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts index 70f529afb93..09932a45354 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts @@ -1,20 +1,24 @@ import type { Principal } from '@sim/auth/principal' import { createLogger } from '@sim/logger' -import type { - BlockCatalog, - CanonicalizeResult, - SourceBase, - WorkflowLockV1, - WorkflowSourceMetaV1, +import { + type BlockCatalog, + type CanonicalizeResult, + canonicalize, + type ResourceKeyResolver, + type SourceBase, + type WorkflowLockV1, + type WorkflowSourceMetaV1, } from '@sim/workflow-code' import type { WorkflowState } from '@sim/workflow-types/workflow' import { withCatalogBlockScope } from '@/lib/catalog/application/context' import { previewSourceCommit } from '@/lib/workflows/application/source-commit' import { emptyDiffSummary, type SourceDiffSummary } from '@/lib/workflows/application/source-diff' import type { WorkflowSourceDiagnostic } from '@/lib/workflows/application/source-error' +import { withFallback } from '@/lib/workflows/application/source-pipeline/evaluate/resolve' import { type CommitTarget, targetIds } from '@/lib/workflows/application/source-pipeline/load' import type { PlannedSource, RefusedSource } from '@/lib/workflows/application/source-pipeline/plan' import { type PrintedSource, printStoredSource } from '@/lib/workflows/code/print-stored' +import { loadResourceKeyResolver, type ResourceReferences } from '@/lib/workflows/code/resources' import { type DeploymentDrift, readDeploymentDrift, @@ -102,7 +106,10 @@ export function printPlanned( { plan, loaded }: Pick, state: WorkflowState, sourceMeta: WorkflowSourceMetaV1 | null, - lockless?: CanonicalizeResult + { + lockless, + resources = plan.resources, + }: { lockless?: CanonicalizeResult; resources?: ResourceKeyResolver } = {} ): PrintedSource { /** The function files the submission named, kept so a write never renames the author's. */ const codeFiles: Record = {} @@ -113,7 +120,7 @@ export function printPlanned( state, meta: plan.meta, catalog: loaded.catalog, - resources: plan.resources, + resources, sourceMeta, functionCode: plan.functionCode, identity: plan.identity, @@ -123,16 +130,46 @@ export function printPlanned( }) } -/** Prints the blocks and edges a write stores with the plan's variables and source meta. */ -export function printWritten( +/** + * Prints the blocks and edges a write stores, or a dry run would, with the plan's variables and + * source meta, as the next read prints them. The plan's resolver knows the resources the source + * named by key; one the source wrote by id (a `raw()` tool's literal `tableId`) resolves through + * the workspace's resource keys, allocating a missing key when `allocate` (a commit) as that read + * does. With the plan's resolver alone such a resource would print, and fingerprint, unlike every + * later read and a pinned deploy's draft check. + */ +export async function printWritten( planned: Pick, - written: Omit -): PrintedSource { - return printPlanned( - planned, - { ...written, variables: planned.plan.storedVariables }, - planned.plan.sourceMeta + written: Omit, + { allocate }: { allocate: boolean } +): Promise { + const { plan, loaded } = planned + const state = { ...written, variables: plan.storedVariables } + const unresolved: ResourceReferences['ids'] = [] + const recording: ResourceKeyResolver = { + toKey(kind, id) { + const key = plan.resources.toKey(kind, id) + if (key === null) unresolved.push({ kind, id }) + return key + }, + toId: (kind, key) => plan.resources.toId(kind, key), + nameOf: (kind, id) => plan.resources.nameOf?.(kind, id) ?? null, + isBuiltin: plan.resources.isBuiltin, + } + const lockless = canonicalize(state, { + catalog: loaded.catalog, + meta: plan.meta, + resources: recording, + }) + if (unresolved.length === 0) return printPlanned(planned, state, plan.sourceMeta, { lockless }) + const byId = await loadResourceKeyResolver( + loaded.scope.workspaceId, + { ids: unresolved }, + { actorUserId: loaded.scope.subjectUserId, allocate } ) + return printPlanned(planned, state, plan.sourceMeta, { + resources: withFallback(plan.resources, byId), + }) } /** @@ -177,7 +214,7 @@ export async function previewSource( workspaceId: loaded.scope.workspaceId, principalKind: principal.kind, }) - return shapeOutcome(frame, printWritten(planned, preview.state), { + return shapeOutcome(frame, await printWritten(planned, preview.state, { allocate: false }), { applied: false, ...(isNew ? UNDEPLOYED diff --git a/apps/sim/lib/workflows/application/source-pipeline/plan.ts b/apps/sim/lib/workflows/application/source-pipeline/plan.ts index adf25a781f3..48f4b10b48a 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/plan.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/plan.ts @@ -336,10 +336,10 @@ function printNoop(planned: PlannedSource): NonNullable { workflow: { ...storedCanonical.canonical.workflow, meta: plan.meta }, } : storedCanonical.canonical - const printed = printPlanned(planned, stored.state, plan.sourceMeta, lockless) + const printed = printPlanned(planned, stored.state, plan.sourceMeta, { lockless }) const before = isEqual(plan.sourceMeta, storedSourceMeta) ? printed - : printPlanned(planned, stored.state, storedSourceMeta, lockless) + : printPlanned(planned, stored.state, storedSourceMeta, { lockless }) return { printed, sourceMetaChanged: !isEqual(printed.files, before.files) || !isEqual(printed.lock, before.lock), diff --git a/apps/sim/lib/workflows/code/catalog/project.ts b/apps/sim/lib/workflows/code/catalog/project.ts index 43fc4a102b5..7b9624da727 100644 --- a/apps/sim/lib/workflows/code/catalog/project.ts +++ b/apps/sim/lib/workflows/code/catalog/project.ts @@ -21,6 +21,7 @@ import { operationOptions } from '@/lib/workflows/code/catalog/sdk-names' import { deriveValueShape } from '@/lib/workflows/code/catalog/value-kind' import { TRIGGER_TYPES } from '@/lib/workflows/triggers/types' import { accessIdEffect, blockEffect } from '@/blocks/access-effect' +import { isCoreAgentToolBlock } from '@/blocks/agent-tools' import type { BlockConfig, SubBlockConfig } from '@/blocks/types' import { isHumanInTheLoopBlock, @@ -660,6 +661,7 @@ export function projectBlock(block: BlockConfig): CatalogBlock { } } assign(projected, 'singleInstance', block.singleInstance) + if (block.category !== 'tools' && isCoreAgentToolBlock(block)) projected.agentTool = true const dynamicOutputs = projectDynamicOutputs(block) if (dynamicOutputs) projected.dynamicOutputs = dynamicOutputs if (block.errorOutputs) projected.errorOutputs = Object.keys(block.errorOutputs) diff --git a/apps/sim/lib/workflows/code/corpus/values.ts b/apps/sim/lib/workflows/code/corpus/values.ts index 6cdbef193ac..699ad66a475 100644 --- a/apps/sim/lib/workflows/code/corpus/values.ts +++ b/apps/sim/lib/workflows/code/corpus/values.ts @@ -23,7 +23,7 @@ export const CORPUS_VARIABLE_NAME = 'corpusNote' */ export const CORPUS_SKILL = { id: 'corpus-skill', key: 'corpus-skill', name: 'Corpus skill' } -/** The six markers every free-text corpus string carries. */ +/** The markers every free-text corpus string carries. */ export const CORPUS_TEXT_MARKERS = [ '', "''", @@ -31,18 +31,21 @@ export const CORPUS_TEXT_MARKERS = [ '\n', '`', '${', + '\\', ] as const export const CORPUS_TEXT = [ 'Reply to as', "'' using {{API_KEY}} and ", 'second line with a `backtick` and a literal \u0024{notInterpolated} and <3 hearts', + String.raw`a pattern /^\d+\s\w*$/ and a path C:\temp\file`, ].join('\n') const JS_CODE = [ 'const input = ', "const label = ' {{API_KEY}}'", 'const note = `tick \u0024{label}` // \u0024{', + String.raw`const pattern = /^\d+\s[\w.]*\\$/ // "\n" '\\' \u0041 \x`, 'return { input, label, note, key: {{API_KEY}} }', ].join('\n') @@ -50,6 +53,7 @@ const PYTHON_CODE = [ 'value = ', "label = ' {{API_KEY}}'", 'note = f"`tick` \u0024{label}"', + String.raw`pattern = r"^\d+\s\w*$" + "\n"`, 'return {"value": value, "label": label}', ].join('\n') @@ -57,6 +61,7 @@ const SHELL_CODE = [ 'INPUT=', "echo ' {{API_KEY}}'", 'echo "`date` \u0024{HOME}"', + String.raw`printf '%s\n' "a\tb" | sed 's/\s\+/ /g'`, ].join('\n') /** JSON code fields must stay parseable, so the payload lives inside JSON strings. */ diff --git a/apps/sim/lib/workflows/code/real-catalog.test.ts b/apps/sim/lib/workflows/code/real-catalog.test.ts index 257fab9e2d8..d6213514318 100644 --- a/apps/sim/lib/workflows/code/real-catalog.test.ts +++ b/apps/sim/lib/workflows/code/real-catalog.test.ts @@ -257,6 +257,61 @@ describe('canonicalize and codegen over the real block catalog', () => { } }, 120_000) + it('prints a Table tool the agent tool picker stored as table.tool.queryRows that type-checks and compiles back', () => { + sdkTypesOnce() + const tables: ResourceKeyResolver = { + toKey: (kind, id) => (kind === 'table' && id === 'tbl_orders' ? 'orders' : null), + toId: (kind, key) => (kind === 'table' && key === 'orders' ? 'tbl_orders' : null), + } + const picked = { + type: 'table_v2', + title: 'Table', + toolId: 'table_query_rows', + operation: 'query_rows', + usageControl: 'auto', + params: { tableId: 'tbl_orders' }, + } + const state: WorkflowState = { + blocks: { + a1: createBlock({ + id: 'a1', + type: 'agent', + name: 'Agent', + subBlocks: { + model: { id: 'model', type: 'combobox', value: 'claude-sonnet-4-5' }, + tools: { id: 'tools', type: 'tool-input', value: [picked] }, + }, + }), + }, + edges: [], + loops: {}, + parallels: {}, + } + const meta = { name: 'Table tool', description: null } + const canonical = canonicalize(state, { catalog, meta, resources: tables }).workflow + const [entry] = printWorkflow({ + workflow: canonical, + catalog, + options: { functionCode: 'inline' }, + }).files + expect(entry.text).toMatch(/table\.tool\.queryRows\(\s*\{ tableId: table\('orders'\) \}/) + const dir = path.join(workDir, 'table-tool') + mkdirSync(dir, { recursive: true }) + writeFileSync(path.join(dir, 'table-tool.ts'), entry.text) + expect(typeCheckAgainstSdk(workDir, 'table-tool', [path.join(dir, '*.ts')])).toBe('') + + const compiled = compileWorkflow({ + entry, + files: new Map(), + catalog, + sdkMajor: catalog.sdkMajor, + knownKeys: new Set(Object.keys(canonical.blocks)), + stored: canonical, + }) + expect(compiled.diagnostics.filter((d) => d.severity === 'error')).toEqual([]) + expect(compiled.workflow && canonicalEquals(compiled.workflow, canonical)).toBe(true) + }, 120_000) + it('keeps a built-in skill entry verbatim with no unresolved-id warning, and round-trips it', () => { sdkTypesOnce() const [builtin] = BUILTIN_SKILLS diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 0f5cb641fb4..3cbf028dd5a 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -9146,6 +9146,7 @@ export type GetSourceCatalogResponse = { available: Array } singleInstance?: boolean + agentTool?: true subBlocks: Array< | { id: string diff --git a/packages/workflow-code/src/canonicalize/index.test.ts b/packages/workflow-code/src/canonicalize/index.test.ts index ab9fb3f9b40..95795ade1dd 100644 --- a/packages/workflow-code/src/canonicalize/index.test.ts +++ b/packages/workflow-code/src/canonicalize/index.test.ts @@ -12,6 +12,7 @@ import type { SubBlockId, Value, } from '../model' +import { mulberry32 } from '../random.test-helpers' import type { CanonicalizeOptions } from '.' import { canonicalize } from '.' @@ -1390,16 +1391,6 @@ describe('canonicalize: block fields', () => { /** A runtime global (Node 17+, browsers); this package type-checks with `types: []`. */ declare function structuredClone(value: T): T -function mulberry32(seed: number): () => number { - let state = seed - return () => { - state = (state + 0x6d2b79f5) | 0 - let t = Math.imul(state ^ (state >>> 15), 1 | state) - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t - return ((t ^ (t >>> 14)) >>> 0) / 4294967296 - } -} - function shuffleKeys(value: unknown, random: () => number): unknown { if (Array.isArray(value)) return value.map((item) => shuffleKeys(item, random)) if (value === null || typeof value !== 'object') return value diff --git a/packages/workflow-code/src/catalog/types.ts b/packages/workflow-code/src/catalog/types.ts index e4c2c1a2707..2c3b0792460 100644 --- a/packages/workflow-code/src/catalog/types.ts +++ b/packages/workflow-code/src/catalog/types.ts @@ -266,6 +266,11 @@ export interface CatalogBlock { triggers?: { enabled: boolean; available: string[] } /** Only one instance per workflow (`duplicate_single_instance_block` gate). */ singleInstance?: boolean + /** + * A built-in block the agent tool picker offers beside integrations. Like a `tools`-category + * block, its namespaced operations have an agent-tool form (`hasToolForm` in `sdk.ts`). + */ + agentTool?: true /** Declared order (the printer's param order), duplicates kept. */ subBlocks: CatalogSubBlock[] /** diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index 4a898db5ac6..580068f7aee 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -135,7 +135,10 @@ round-trip such a block but never introduce one; renaming the block retires the - Literals, objects, arrays, `-number`. Nested `null` is kept. A plain object with a `$sim` key is data and compiles to `{ $sim: 'literal', value }`. -- Strings: `'…'`, untagged templates without `${}`, and tagged templates (cooked text): +- Strings: `'…'`, untagged templates without `${}`, and tagged templates. A `t` template reads + like a JS string (cooked: `\n` is a newline); the code and markup tags read their text as + written (raw), unescaping only `` \` `` and `\${`, so `` js`/\s+/` `` stores `/\s+/`. The printer + writes what raw text cannot hold (CR, invisible characters) as `${'…'}`: | Tag | For | |---|---| @@ -244,8 +247,10 @@ changes how an unedited field stores it. pass through. The printer writes a list the record cannot carry (an integer-like or repeated name, an unknown key) as `raw([…])`. - Tools (`valueKind: 'tools'`): an array of - - `ns.tool.method(params, options?)` (`slack.tool.sendMessage(…)`): an integration operation (a - `tools`-category block's namespaced builder, outside trigger mode). Any other builder as a tool + - `ns.tool.method(params, options?)` (`slack.tool.sendMessage(…)`, `table.tool.queryRows(…)`): + an operation the agent tool picker offers (the namespaced builder, outside trigger mode, of a + `tools`-category block or a built-in one the catalog marks `agentTool`: Table, Knowledge, + File). Any other builder as a tool (`api.tool(…)`, `trigger.gmail.tool.poller(…)`) is `E_UNKNOWN_BUILDER`. Params are checked like a block's: one the tool type does not have is `E_UNKNOWN_PARAM`, one of another operation `W_FIELD_NOT_APPLICABLE`, a literal secret `W_LITERAL_SECRET`; diff --git a/packages/workflow-code/src/compile/characters.ts b/packages/workflow-code/src/compile/characters.ts index af2e0963da2..fdd27f4347d 100644 --- a/packages/workflow-code/src/compile/characters.ts +++ b/packages/workflow-code/src/compile/characters.ts @@ -9,10 +9,11 @@ * which JSON stores as `null`, and `12345678901234567890` reads as the nearest double, losing digits. */ -import type { File, Node, NumericLiteral } from '@babel/types' +import type { File, Node, NumericLiteral, TaggedTemplateExpression } from '@babel/types' import { containsNulCharacter, sanitizeForJsonb } from '@sim/utils/string' import { childNodes } from '../babel' import type { BlockKey } from '../model' +import { VERBATIM_TEMPLATE_TAGS } from '../sdk' import type { Reporter } from './report' /** The index of the first character `sanitizeForJsonb` would replace, or `-1`. */ @@ -54,6 +55,18 @@ export function checkStorableText( return false } +/** + * A template under a {@link VERBATIM_TEMPLATE_TAGS} tag, whose text compile reads raw. Matched by + * name: this pass runs before scope, and a renamed import only costs a cooked-text check. + */ +function isVerbatimTemplate(node: Node): node is TaggedTemplateExpression { + return ( + node.type === 'TaggedTemplateExpression' && + node.tag.type === 'Identifier' && + VERBATIM_TEMPLATE_TAGS.has(node.tag.name) + ) +} + /** The value a literal node reads as: a string literal's, a template quasi's cooked text. */ function literalValue(node: Node): string | null { if (node.type === 'StringLiteral') return node.value @@ -128,6 +141,11 @@ export function checkStorableLiterals( checkNumber(file, node, reporter) continue } + if (isVerbatimTemplate(node)) { + // Its text is the raw source, which holds no escape to read: only interpolations remain. + stack.push(...node.quasi.expressions) + continue + } const value = literalValue(node) if (value !== null) { const index = firstUnstorable(value) diff --git a/packages/workflow-code/src/compile/tools.ts b/packages/workflow-code/src/compile/tools.ts index ea25867f79c..a354ca6df77 100644 --- a/packages/workflow-code/src/compile/tools.ts +++ b/packages/workflow-code/src/compile/tools.ts @@ -247,7 +247,7 @@ function compileToolCall( if (!block || !hasToolForm(named.path, builder, block)) { ctx.reporter.report( 'E_UNKNOWN_BUILDER', - `${named.path} is not an agent tool: only an integration operation has a tool form.`, + `${named.path} is not an agent tool: only an integration, Table, Knowledge or File operation has a tool form.`, rangeOf(ctx, call.callee), { hint: "Write an integration operation as namespace.tool.method(params), a child workflow as childWorkflow('key').asTool(), or any other stored tool as raw(tool).", diff --git a/packages/workflow-code/src/compile/values.ts b/packages/workflow-code/src/compile/values.ts index 9f8f1b7475b..201a43c9e7a 100644 --- a/packages/workflow-code/src/compile/values.ts +++ b/packages/workflow-code/src/compile/values.ts @@ -48,7 +48,14 @@ import { type VarNode, } from '../model' import { getOwn, setOwn } from '../records' -import { isTemplateTag, SDK_RESOURCE_CALLS, type SdkCoreExport, TEMPLATE_TAGS } from '../sdk' +import { + isTemplateTag, + SDK_RESOURCE_CALLS, + type SdkCoreExport, + TEMPLATE_TAGS, + type TemplateTag, + VERBATIM_TEMPLATE_TAGS, +} from '../sdk' import { inputFormatFields } from '../start-inputs' import { type BlockDecl, @@ -1139,15 +1146,40 @@ function subflowScopeRef( return blockRefToken(ctx, node, container, [{ kind: 'name', name: container.key }, ...path], site) } +/** + * A verbatim template's text between interpolations ({@link VERBATIM_TEMPLATE_TAGS}): the raw + * source text with only `` \` `` and `\${` unescaped, so every other backslash stays as written. + * The printer's `verbatimTemplateParts` is its inverse. + */ +function readVerbatimText(raw: string): string { + let text = '' + for (let index = 0; index < raw.length; index += 1) { + const char = raw[index] + const next = raw[index + 1] ?? '' + if (char !== '\\') { + text += char + } else if (next === '`' || (next === '$' && raw[index + 2] === '{')) { + text += next + index += 1 + } else { + text += char + next + index += 1 + } + } + return text +} + function templateText( ctx: CompileContext, node: TaggedTemplateExpression, + tag: TemplateTag, site: ValueSite ): string | null { const { quasis, expressions } = node.quasi + const verbatim = VERBATIM_TEMPLATE_TAGS.has(tag) let text = '' for (const [index, quasi] of quasis.entries()) { - const cooked = quasi.value.cooked + const cooked = verbatim ? readVerbatimText(quasi.value.raw) : quasi.value.cooked if (cooked == null) { return unsupported( ctx, @@ -1397,7 +1429,7 @@ export function compileValue( ) } if (!tag || tag.kind !== 'sdk' || !isTemplateTag(tag.name)) return rejectNode(ctx, node, site) - const text = templateText(ctx, node, site) + const text = templateText(ctx, node, tag.name, site) return text === null ? null : { kind: 'value', value: text, form: 'template' } } case 'Identifier': diff --git a/packages/workflow-code/src/print/strings.ts b/packages/workflow-code/src/print/strings.ts index d029ea37f04..06f6423e398 100644 --- a/packages/workflow-code/src/print/strings.ts +++ b/packages/workflow-code/src/print/strings.ts @@ -1,9 +1,10 @@ /** - * Literal escaping for printed source. Every function returns text whose cooked JS value is - * exactly the input: the compiler reads cooked values, so `\`, quotes, `${`, CR, + * Literal escaping for printed source. Every function returns text the compiler reads back as + * exactly the input. Quoted strings and `t` templates are read cooked, so `\`, quotes, `${`, CR, * U+2028/2029, other control characters, lone surrogates and the characters that reorder or hide * text in review ({@link isSuspiciousCharacter}) are escaped, while LF stays raw inside templates - * so multi-line text reads naturally. Template content is never re-indented. + * so multi-line text reads naturally. Verbatim templates (`js`, `py`, ...) are read raw instead + * ({@link verbatimTemplateParts}). Template content is never re-indented. */ import { isIdentifierName } from '../code-files/ref-path' @@ -34,6 +35,17 @@ export function hasSuspiciousCharacter(text: string): boolean { return false } +/** A control character or one {@link isSuspiciousCharacter} names: never printed bare. */ +function isControlOrHidden(code: number): boolean { + return code < 0x20 || code === 0x7f || isSuspiciousCharacter(code) +} + +function isSurrogatePairAt(text: string, index: number): boolean { + const code = text.charCodeAt(index) + const next = text.charCodeAt(index + 1) + return code >= 0xd800 && code <= 0xdbff && next >= 0xdc00 && next <= 0xdfff +} + function hex4(code: number): string { return `\\u${code.toString(16).toUpperCase().padStart(4, '0')}` } @@ -47,17 +59,12 @@ function escapeText(text: string, mode: 'single' | 'double' | 'template'): strin for (let i = 0; i < text.length; i += 1) { const code = text.charCodeAt(i) const char = text[i] ?? '' - if (code >= 0xd800 && code <= 0xdbff) { - const next = text.charCodeAt(i + 1) - if (next >= 0xdc00 && next <= 0xdfff) { - out += char + (text[i + 1] ?? '') - i += 1 - } else { - out += hex4(code) - } + if (isSurrogatePairAt(text, i)) { + out += char + (text[i + 1] ?? '') + i += 1 continue } - if (code >= 0xdc00 && code <= 0xdfff) { + if (code >= 0xd800 && code <= 0xdfff) { out += hex4(code) continue } @@ -91,7 +98,7 @@ function escapeText(text: string, mode: 'single' | 'double' | 'template'): strin out += mode === 'template' && text[i + 1] === '{' ? '\\$' : '$' continue } - if (code < 0x20 || code === 0x7f || isSuspiciousCharacter(code)) { + if (isControlOrHidden(code)) { out += hex4(code) continue } @@ -120,6 +127,72 @@ export function escapeTemplateText(text: string): string { return escapeText(text, 'template') } +/** + * Whether a verbatim template prints `code` as a string-literal interpolation rather than raw: CR + * (raw template text reads it as LF), a lone surrogate (no file can hold one), and what + * {@link escapeText} escapes in a template for review (other controls, U+2028/U+2029, + * {@link isSuspiciousCharacter}). + */ +function verbatimNeedsLiteral(code: number): boolean { + return ( + (isControlOrHidden(code) && code !== 0x0a && code !== 0x09) || + code === 0x2028 || + code === 0x2029 || + (code >= 0xd800 && code <= 0xdfff) + ) +} + +/** One piece of a verbatim template's body: raw template text, or a `${'…'}` interpolation. */ +export type VerbatimPart = { raw: string } | { literal: string } + +/** + * A verbatim template's text (`js`, `py`, `sh`, `json`, `md`) as the pieces between its + * backticks. Compile reads raw text and unescapes only `` \` `` and `\${`, so the text prints as + * written except that a backtick and `${` take a backslash, and what raw text cannot hold prints + * as a string-literal interpolation ({@link verbatimNeedsLiteral}). A backslash run that would + * otherwise escape a backtick, `${`, an interpolation or the template's end loses its last + * backslash to an interpolation (`${'\\'}`), so compile reads back exactly `text`. + */ +export function verbatimTemplateParts(text: string): VerbatimPart[] { + const parts: VerbatimPart[] = [] + let raw = '' + const pushLiteral = (piece: string) => { + const last = parts.at(-1) + if (raw === '' && last && 'literal' in last) { + last.literal += piece + return + } + if (raw !== '') parts.push({ raw }) + raw = '' + parts.push({ literal: piece }) + } + const needsLiteralAt = (index: number) => + !isSurrogatePairAt(text, index) && verbatimNeedsLiteral(text.charCodeAt(index)) + const opensSyntaxAt = (index: number) => + text[index] === '`' || (text[index] === '$' && text[index + 1] === '{') + for (let index = 0; index < text.length; index += 1) { + const char = text[index] ?? '' + if (isSurrogatePairAt(text, index)) { + raw += char + (text[index + 1] ?? '') + index += 1 + } else if (needsLiteralAt(index)) { + pushLiteral(char) + } else if (char === '\\') { + let end = index + while (text[end] === '\\') end += 1 + const run = end - index + const escapesNext = end >= text.length || opensSyntaxAt(end) || needsLiteralAt(end) + raw += '\\'.repeat(run % 2 === 1 && escapesNext ? run - 1 : run) + if (run % 2 === 1 && escapesNext) pushLiteral('\\') + index = end - 1 + } else { + raw += opensSyntaxAt(index) ? `\\${char}` : char + } + } + if (raw !== '') parts.push({ raw }) + return parts +} + /** An object key: bare when it is an identifier name, quoted otherwise (`quoteProperties: asNeeded`). */ export function printKey(key: string): string { return isIdentifierName(key) ? key : quoteString(key) diff --git a/packages/workflow-code/src/print/values.ts b/packages/workflow-code/src/print/values.ts index b93d941cb85..9d70a5c9831 100644 --- a/packages/workflow-code/src/print/values.ts +++ b/packages/workflow-code/src/print/values.ts @@ -9,10 +9,17 @@ import type { CatalogSubBlock } from '../catalog/types' import { parseJsonContainer } from '../json-text' import { type BlockKey, isSimNode, type Json, type SimNode, type Value } from '../model' import { getOwn } from '../records' -import { SDK_RESOURCE_CALLS, type TemplateTag } from '../sdk' +import { SDK_RESOURCE_CALLS, type TemplateTag, VERBATIM_TEMPLATE_TAGS } from '../sdk' import { type Doc, literalText } from './doc' import type { RefPrinter } from './refs' -import { escapeTemplateText, printKey, printMember, printNumber, quoteString } from './strings' +import { + escapeTemplateText, + printKey, + printMember, + printNumber, + quoteString, + verbatimTemplateParts, +} from './strings' import { arrayExpr, callExpr, type Expr, objectExpr, type Property, pathDepth } from './syntax' export interface FieldContext { @@ -156,9 +163,14 @@ export class ValuePrinter { if (!tagged) return rawPlain ? this.call('raw', [this.string(text)]) : this.string(text) const tag = context.tag this.use(tag) - const body: Doc[] = parts.map((part) => - part.kind === 'text' ? literalText(escapeTemplateText(part.text)) : ['${', part.expr, '}'] - ) + const verbatim = VERBATIM_TEMPLATE_TAGS.has(tag) + const body: Doc[] = parts.map((part) => { + if (part.kind === 'ref') return ['${', part.expr, '}'] + if (!verbatim) return literalText(escapeTemplateText(part.text)) + return verbatimTemplateParts(part.text).map((piece) => + 'raw' in piece ? literalText(piece.raw) : ['${', quoteString(piece.literal), '}'] + ) + }) let refDepth = 1 for (const part of parts) { if (part.kind === 'ref') refDepth = Math.max(refDepth, pathDepth(part.expr)) diff --git a/packages/workflow-code/src/print/verbatim-templates.test.ts b/packages/workflow-code/src/print/verbatim-templates.test.ts new file mode 100644 index 00000000000..2879e5f8ab0 --- /dev/null +++ b/packages/workflow-code/src/print/verbatim-templates.test.ts @@ -0,0 +1,124 @@ +/** + * Code in a `js`/`py`/`sh`/`json`/`md` template is stored exactly as written between the + * backticks, and printed so that compiling it gives back the same code. + */ +import { describe, expect, it } from 'vitest' +import { compileWorkflow } from '../compile' +import { TEST_CATALOG } from '../compile/catalog.test-helpers' +import type { CanonicalWorkflow } from '../model' +import { mulberry32 } from '../random.test-helpers' +import { printWorkflow } from './printer' + +const HEADER = "// @sim-sdk 1\nimport { fn, js, workflow } from '@sim/workflow-sdk'\n\n" + +function compile(text: string) { + return compileWorkflow({ + entry: { path: 'workflow.ts', text }, + files: new Map(), + catalog: TEST_CATALOG, + sdkMajor: 1, + }) +} + +function compiled(body: string): CanonicalWorkflow { + const result = compile(`${HEADER}export default workflow('Test', {}, () => {\n${body}\n})\n`) + expect(result.diagnostics.filter((d) => d.severity === 'error')).toEqual([]) + if (!result.workflow) throw new Error('expected a workflow') + return result.workflow +} + +function codeOf(workflow: CanonicalWorkflow | undefined): unknown { + return workflow?.blocks.f?.params.code +} + +/** Prints `workflow` with function code inline (a `js` template) and compiles the print. */ +function reprinted(workflow: CanonicalWorkflow): { text: string; again: CanonicalWorkflow } { + const output = printWorkflow({ + workflow, + catalog: TEST_CATALOG, + options: { functionCode: 'inline' }, + }) + const text = output.files[0]?.text ?? '' + expect(text).not.toContain('\r') + const result = compile(text) + expect(result.diagnostics.filter((d) => d.severity === 'error')).toEqual([]) + if (!result.workflow) throw new Error(`the print did not compile:\n${text}`) + return { text, again: result.workflow } +} + +/** A Function block holding `code` exactly, written as a quoted string. */ +function storing(code: string): CanonicalWorkflow { + return compiled(` const f = fn('F', { code: ${JSON.stringify(code)} })`) +} + +describe('a js template', () => { + it('stores the backslashes written between its backticks', () => { + const workflow = compiled( + " const f = fn('F', { code: js`return /^\\d+\\s\\w+$/.test('12 ab') && '\\\\'.length === 1` })" + ) + const code = codeOf(workflow) + expect(code).toEqual({ + kind: 'value', + value: "return /^\\d+\\s\\w+$/.test('12 ab') && '\\\\'.length === 1", + }) + const value = (code as { value: string }).value + expect(new Function(value)()).toBe(true) + }) + + it('reads an escaped backtick and ${ as the characters, and keeps an invalid escape', () => { + const workflow = compiled( + " const f = fn('F', { code: js`const s = \\`a \\${b}\\`; const u = '\\u{zz}' \\x` })" + ) + expect(codeOf(workflow)).toEqual({ + kind: 'value', + value: "const s = `a ${b}`; const u = '\\u{zz}' \\x", + }) + }) + + it('keeps a NUL escape as text rather than refusing an unstorable character', () => { + const workflow = compiled(" const f = fn('F', { code: js`return '\\u0000'` })") + expect(codeOf(workflow)).toEqual({ kind: 'value', value: "return '\\u0000'" }) + }) +}) + +const EDGE_CODES: ReadonlyArray<[string, string]> = [ + ['regex classes', String.raw`return /^\d+\s\w*$/.test("1 a")`], + ['escaped backslash in a string', String.raw`return 'a\\b'.split('\\')`], + ['escapes inside strings', String.raw`return "line\nnext\t\u0041"`], + ['a nested template', 'const s = `x ${y} \\` z`'], + ['an escaped ${', 'const s = `\\${not}`'], + ['a literal $ and {', 'cost: $5 { x } $'], +] + +/** Characters that mix the template's own syntax with backslashes. */ +const ALPHABET = ['\\', '`', '$', '{', '}', 'a', 's', 'n', '\n', '\r', '\t', "'", '\u200b', '😀'] + +describe('printing verbatim code', () => { + it.each(EDGE_CODES)('compiles back %s byte for byte', (_name, code) => { + const workflow = storing(code) + const { text, again } = reprinted(workflow) + expect(text).toContain('js`') + expect(codeOf(again)).toEqual(codeOf(workflow)) + }) + + it('prints a regex as written, not doubled', () => { + const { text } = reprinted(storing(String.raw`return /\s+/.test(x)`)) + expect(text).toContain(String.raw`js${'`'}return /\s+/.test(x)${'`'}`) + }) + + it('compiles back every generated string over the template syntax alphabet', () => { + const random = mulberry32(7) + for (let round = 0; round < 300; round += 1) { + const length = 1 + Math.floor(random() * 12) + let code = '' + for (let index = 0; index < length; index += 1) { + code += ALPHABET[Math.floor(random() * ALPHABET.length)] + } + const workflow = storing(code) + expect({ code, again: codeOf(reprinted(workflow).again) }).toEqual({ + code, + again: codeOf(workflow), + }) + } + }) +}) diff --git a/packages/workflow-code/src/random.test-helpers.ts b/packages/workflow-code/src/random.test-helpers.ts new file mode 100644 index 00000000000..ab1f1d31dd5 --- /dev/null +++ b/packages/workflow-code/src/random.test-helpers.ts @@ -0,0 +1,10 @@ +/** A deterministic pseudo-random generator (mulberry32) for seeded property tests. */ +export function mulberry32(seed: number): () => number { + let state = seed + return () => { + state = (state + 0x6d2b79f5) | 0 + let t = Math.imul(state ^ (state >>> 15), 1 | state) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} diff --git a/packages/workflow-code/src/sdk.ts b/packages/workflow-code/src/sdk.ts index eac04fe1b18..b7b5d47b446 100644 --- a/packages/workflow-code/src/sdk.ts +++ b/packages/workflow-code/src/sdk.ts @@ -55,6 +55,19 @@ export const TEMPLATE_TAGS = [ export type TemplateTag = (typeof TEMPLATE_TAGS)[number] +/** + * The {@link TEMPLATE_TAGS} whose text is code or markup, kept as written: compile reads the raw + * text between the backticks and unescapes only `` \` `` and `\${`, so `` js`/\s+/` `` stores + * `/\s+/`. A `t` template is text and reads like a JS string (`\n` is a newline). + */ +export const VERBATIM_TEMPLATE_TAGS: ReadonlySet = new Set([ + 'js', + 'py', + 'sh', + 'json', + 'md', +]) + /** Whether a name is one of the {@link TEMPLATE_TAGS}. */ export function isTemplateTag(name: string): name is TemplateTag { return TEMPLATE_TAGS.some((tag) => tag === name) @@ -248,13 +261,18 @@ export const SDK_RESERVED_IDENTIFIERS: ReadonlySet = new Set([ /** * Whether the SDK declares a builder's agent-tool form, `namespace.tool.method(params, options)`: - * a namespaced builder of a tools-category block outside trigger mode. SDK codegen emits exactly - * these, and the printer writes any other tool as `raw(tool)`. + * a namespaced builder outside trigger mode of a block the agent tool picker offers (a + * tools-category block, or a built-in one marked `agentTool`). SDK codegen emits exactly these, + * and the printer writes any other tool as `raw(tool)`. */ export function hasToolForm( path: string, builder: Pick, - block: Pick + block: Pick ): boolean { - return block.category === 'tools' && builder.triggerMode !== true && path.includes('.') + return ( + (block.category === 'tools' || block.agentTool === true) && + builder.triggerMode !== true && + path.includes('.') + ) } diff --git a/packages/workflow-sdk/src/codegen/core-text.generated.ts b/packages/workflow-sdk/src/codegen/core-text.generated.ts index f74cf120da9..3a52cbec8fd 100644 --- a/packages/workflow-sdk/src/codegen/core-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/core-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from src/core.d.ts; do not edit. /** The text of `core.d.ts`, the workflow SDK authoring declarations. */ -export const CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from \u0027@sim/workflow-sdk\u0027\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref; readonly length: Ref }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to ``.\n * Paths map exactly: `.seg`, `[\u0027seg\u0027]` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref = { readonly [REF]: T } & RefPaths\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue = [Extract] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo = ({ readonly [REF]: RefValue } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value = T | RefTo | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/** JavaScript code (condition expressions, inline function code). */\nexport declare const js: typeof t\n/** Python code. */\nexport declare const py: typeof t\n/** Shell code. */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value\u0027s type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref(\u0027Classify.content\u0027)`. */\nexport declare function ref(path: string): Ref\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field. Valid only on a param of a block the stored\n * workflow already has (same name and type) and holds a value for; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map\u0027s\n * values describe the resource: a table\u0027s row type, a credential\u0027s provider, a workflow\u0027s inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n\ntype KeyOf = keyof M extends never ? string : Extract\n\nexport type TableKey = KeyOf\nexport type KnowledgeBaseKey = KeyOf\nexport type CredentialKey = KeyOf\nexport type WorkflowKey = KeyOf\nexport type SkillKey = KeyOf\nexport type CustomToolKey = KeyOf\nexport type McpServerKey = KeyOf\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server\u0027s last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource\u0027s internal id. */\nexport interface ResourceRef {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential(\u0027support-slack\u0027)`. */\nexport type CredentialRef = ResourceRef<\u0027credential\u0027, Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential\u0027s provider; any key until it exists.\n */\nexport type CredentialKeyFor = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract]\nexport declare function credential(key: K): CredentialRef\n\n/**\n * The other form a credential field takes beside `credential(\u0027key\u0027)`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field\u0027s advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw(\u0027…\u0027)`.\n */\nexport type CredentialIdValue = RefTo | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow {\n id: string\n data: TableColumns\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column\u0027s type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns]-?: Exclude, null> } & {\n [C in Exclude>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column\u0027s type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table(\u0027leads\u0027)`. Table block operations live on `table.*`. */\nexport type TableRef = ResourceRef<\u0027table\u0027, Key>\nexport declare function table(key: K): TableRef\n\n/** A knowledge base: `knowledgeBase(\u0027docs\u0027)`. */\nexport type KnowledgeBaseRef = ResourceRef<\u0027knowledge-base\u0027, Key>\nexport declare function knowledgeBase(key: K): KnowledgeBaseRef\n\n/** A workspace skill: `skill(\u0027triage\u0027)`. */\nexport type SkillRef = ResourceRef<\u0027skill\u0027, Key>\nexport declare function skill(key: K): SkillRef\n\n/** A workspace folder: `folder(\u0027reports\u0027)`. */\nexport type FolderRef = ResourceRef<\u0027file-folder\u0027>\nexport declare function folder(key: string): FolderRef\n\n/** A workspace file: `file(\u0027contracts/acme.pdf\u0027)`. File block operations live on `file.*`. */\nexport type FileRef = ResourceRef<\u0027file\u0027>\nexport declare function file(path: string): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it: one uploaded in place, or a workspace\n * file chosen by `key` (written `file(\u0027path\u0027)` when the workspace resolves it).\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string | FileRef\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent\u0027s `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: \u0027auto\u0027 | \u0027force\u0027 | \u0027none\u0027\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool\u0027s params, which pick the member the agent reads. */\n modes?: Record\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool(\u0027lookup-order\u0027)`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick\n\n/** An MCP tool\u0027s arguments and the editor\u0027s snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record\n /**\n * What the editor saved about the server and the tool\u0027s input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp(\u0027linear\u0027)`. */\nexport interface McpServerRef extends ResourceRef<\u0027mcp-server\u0027, Key> {\n /** One of the server\u0027s tools, as an agent tool: `mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027)`. */\n tool(name: McpToolName, options?: McpToolOpts): Tool\n}\nexport declare function mcp(key: K): McpServerRef\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row\u0027s display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block\u0027s inputs, the\n * agent\u0027s legacy prompt fields, a container\u0027s stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record\n /**\n * A loop or parallel\u0027s `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record\n}\n\n/** A block\u0027s retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node\u0027s default port to each target. Returns the target, or a group of them. */\n to(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node\u0027s error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * 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. Valid only on a param of a block the stored\n * workflow already has (same name and type) and holds a value for; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map\u0027s\n * values describe the resource: a table\u0027s row type, a credential\u0027s provider, a workflow\u0027s inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n\ntype KeyOf = keyof M extends never ? string : Extract\n\nexport type TableKey = KeyOf\nexport type KnowledgeBaseKey = KeyOf\nexport type CredentialKey = KeyOf\nexport type WorkflowKey = KeyOf\nexport type SkillKey = KeyOf\nexport type CustomToolKey = KeyOf\nexport type McpServerKey = KeyOf\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server\u0027s last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource\u0027s internal id. */\nexport interface ResourceRef {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential(\u0027support-slack\u0027)`. */\nexport type CredentialRef = ResourceRef<\u0027credential\u0027, Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential\u0027s provider; any key until it exists.\n */\nexport type CredentialKeyFor = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract]\nexport declare function credential(key: K): CredentialRef\n\n/**\n * The other form a credential field takes beside `credential(\u0027key\u0027)`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field\u0027s advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw(\u0027…\u0027)`.\n */\nexport type CredentialIdValue = RefTo | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow {\n id: string\n data: TableColumns\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column\u0027s type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns]-?: Exclude, null> } & {\n [C in Exclude>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column\u0027s type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table(\u0027leads\u0027)`. Table block operations live on `table.*`. */\nexport type TableRef = ResourceRef<\u0027table\u0027, Key>\nexport declare function table(key: K): TableRef\n\n/** A knowledge base: `knowledgeBase(\u0027docs\u0027)`. */\nexport type KnowledgeBaseRef = ResourceRef<\u0027knowledge-base\u0027, Key>\nexport declare function knowledgeBase(key: K): KnowledgeBaseRef\n\n/** A workspace skill: `skill(\u0027triage\u0027)`. */\nexport type SkillRef = ResourceRef<\u0027skill\u0027, Key>\nexport declare function skill(key: K): SkillRef\n\n/** A workspace folder: `folder(\u0027reports\u0027)`. */\nexport type FolderRef = ResourceRef<\u0027file-folder\u0027>\nexport declare function folder(key: string): FolderRef\n\n/** A workspace file: `file(\u0027contracts/acme.pdf\u0027)`. File block operations live on `file.*`. */\nexport type FileRef = ResourceRef<\u0027file\u0027>\nexport declare function file(path: string): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it: one uploaded in place, or a workspace\n * file chosen by `key` (written `file(\u0027path\u0027)` when the workspace resolves it).\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string | FileRef\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent\u0027s `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: \u0027auto\u0027 | \u0027force\u0027 | \u0027none\u0027\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool\u0027s params, which pick the member the agent reads. */\n modes?: Record\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool(\u0027lookup-order\u0027)`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick\n\n/** An MCP tool\u0027s arguments and the editor\u0027s snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record\n /**\n * What the editor saved about the server and the tool\u0027s input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp(\u0027linear\u0027)`. */\nexport interface McpServerRef extends ResourceRef<\u0027mcp-server\u0027, Key> {\n /** One of the server\u0027s tools, as an agent tool: `mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027)`. */\n tool(name: McpToolName, options?: McpToolOpts): Tool\n}\nexport declare function mcp(key: K): McpServerRef\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row\u0027s display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block\u0027s inputs, the\n * agent\u0027s legacy prompt fields, a container\u0027s stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record\n /**\n * A loop or parallel\u0027s `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record\n}\n\n/** A block\u0027s retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node\u0027s default port to each target. Returns the target, or a group of them. */\n to(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node\u0027s error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * 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" diff --git a/packages/workflow-sdk/src/core.d.ts b/packages/workflow-sdk/src/core.d.ts index 0bb4e9f9fa9..32fa6a032ac 100644 --- a/packages/workflow-sdk/src/core.d.ts +++ b/packages/workflow-sdk/src/core.d.ts @@ -118,11 +118,15 @@ type Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boole /** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */ export declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template -/** JavaScript code (condition expressions, inline function code). */ +/** + * JavaScript code (condition expressions, inline function code), kept exactly as written: like + * `String.raw`, `` js`/\s+/` `` is `/\s+/`. Only `` \` `` and `\${` are escapes, for a backtick + * and a literal `${`. So are `py`, `sh`, `json` and `md`; `t` text reads like a JS string. + */ export declare const js: typeof t -/** Python code. */ +/** Python code, kept exactly as written (see {@link js}). */ export declare const py: typeof t -/** Shell code. */ +/** Shell code, kept exactly as written (see {@link js}). */ export declare const sh: typeof t /** * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON diff --git a/packages/workflow-sdk/test/fixtures/catalog.json b/packages/workflow-sdk/test/fixtures/catalog.json index 9dbd2f8b60f..043cecf5d4f 100644 --- a/packages/workflow-sdk/test/fixtures/catalog.json +++ b/packages/workflow-sdk/test/fixtures/catalog.json @@ -6818,7 +6818,8 @@ "container": null, "annotationOnly": false }, - "effect": "write" + "effect": "write", + "agentTool": true }, "condition": { "type": "condition", @@ -6988,6 +6989,7 @@ "annotationOnly": false }, "effect": "write", + "agentTool": true, "errorOutputs": [ "errorMessage" ] @@ -10909,7 +10911,8 @@ "list_tags": "read", "list_connectors": "read", "get_connector": "read" - } + }, + "agentTool": true }, "loop": { "type": "loop", @@ -32422,6 +32425,7 @@ "table_new_row" ] }, + "agentTool": true, "dynamicOutputs": { "source": "tableRows", "param": "tableId" @@ -32538,7 +32542,8 @@ "container": null, "annotationOnly": false }, - "effect": "write" + "effect": "write", + "agentTool": true } }, "triggers": { From 8698ef7a13dd367aac939bb1124e8ecc2b65b999 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 19:34:58 -0800 Subject: [PATCH 2/3] fix(workflow-code): read verbatim tags through the file's SDK imports in the character check A cooked t imported as js skipped the NUL/lone-surrogate check while compile still read it cooked. Also documents that agentTool marks hidden legacy versions. --- .../sim/lib/workflows/code/catalog/project.ts | 1 + packages/workflow-code/src/catalog/types.ts | 6 ++-- .../workflow-code/src/compile/characters.ts | 33 ++++++++++++------- .../src/print/verbatim-templates.test.ts | 7 ++++ 4 files changed, 34 insertions(+), 13 deletions(-) diff --git a/apps/sim/lib/workflows/code/catalog/project.ts b/apps/sim/lib/workflows/code/catalog/project.ts index 7b9624da727..ab5907ebc75 100644 --- a/apps/sim/lib/workflows/code/catalog/project.ts +++ b/apps/sim/lib/workflows/code/catalog/project.ts @@ -661,6 +661,7 @@ export function projectBlock(block: BlockConfig): CatalogBlock { } } assign(projected, 'singleInstance', block.singleInstance) + // Hidden legacy versions too: an agent tool stored from one still prints through its builder. if (block.category !== 'tools' && isCoreAgentToolBlock(block)) projected.agentTool = true const dynamicOutputs = projectDynamicOutputs(block) if (dynamicOutputs) projected.dynamicOutputs = dynamicOutputs diff --git a/packages/workflow-code/src/catalog/types.ts b/packages/workflow-code/src/catalog/types.ts index 2c3b0792460..ef8878e962b 100644 --- a/packages/workflow-code/src/catalog/types.ts +++ b/packages/workflow-code/src/catalog/types.ts @@ -267,8 +267,10 @@ export interface CatalogBlock { /** Only one instance per workflow (`duplicate_single_instance_block` gate). */ singleInstance?: boolean /** - * A built-in block the agent tool picker offers beside integrations. Like a `tools`-category - * block, its namespaced operations have an agent-tool form (`hasToolForm` in `sdk.ts`). + * A built-in block type the agent tool picker offers beside integrations, in any version: a + * hidden legacy version is marked too, as a hidden `tools`-category version keeps its category, + * so a tool stored from it prints through its builder. Its namespaced operations have an + * agent-tool form (`hasToolForm` in `sdk.ts`). */ agentTool?: true /** Declared order (the printer's param order), duplicates kept. */ diff --git a/packages/workflow-code/src/compile/characters.ts b/packages/workflow-code/src/compile/characters.ts index fdd27f4347d..c8339ad95e1 100644 --- a/packages/workflow-code/src/compile/characters.ts +++ b/packages/workflow-code/src/compile/characters.ts @@ -9,11 +9,11 @@ * which JSON stores as `null`, and `12345678901234567890` reads as the nearest double, losing digits. */ -import type { File, Node, NumericLiteral, TaggedTemplateExpression } from '@babel/types' +import type { File, Node, NumericLiteral } from '@babel/types' import { containsNulCharacter, sanitizeForJsonb } from '@sim/utils/string' import { childNodes } from '../babel' import type { BlockKey } from '../model' -import { VERBATIM_TEMPLATE_TAGS } from '../sdk' +import { SDK_MODULE, VERBATIM_TEMPLATE_TAGS } from '../sdk' import type { Reporter } from './report' /** The index of the first character `sanitizeForJsonb` would replace, or `-1`. */ @@ -56,15 +56,21 @@ export function checkStorableText( } /** - * A template under a {@link VERBATIM_TEMPLATE_TAGS} tag, whose text compile reads raw. Matched by - * name: this pass runs before scope, and a renamed import only costs a cooked-text check. + * The local names the file imports a {@link VERBATIM_TEMPLATE_TAGS} tag under, read from its SDK + * imports as compile binds them, so `import { t as js }` stays a cooked `t`. */ -function isVerbatimTemplate(node: Node): node is TaggedTemplateExpression { - return ( - node.type === 'TaggedTemplateExpression' && - node.tag.type === 'Identifier' && - VERBATIM_TEMPLATE_TAGS.has(node.tag.name) - ) +function verbatimTagNames(ast: File): ReadonlySet { + const names = new Set() + for (const statement of ast.program.body) { + if (statement.type !== 'ImportDeclaration' || statement.source.value !== SDK_MODULE) continue + for (const specifier of statement.specifiers) { + if (specifier.type !== 'ImportSpecifier') continue + const { imported } = specifier + const name = imported.type === 'Identifier' ? imported.name : imported.value + if (VERBATIM_TEMPLATE_TAGS.has(name)) names.add(specifier.local.name) + } + } + return names } /** The value a literal node reads as: a string literal's, a template quasi's cooked text. */ @@ -135,13 +141,18 @@ export function checkStorableLiterals( ast: File, reporter: Reporter ): void { + const verbatimTags = verbatimTagNames(ast) const stack: Node[] = [ast.program] for (let node = stack.pop(); node !== undefined; node = stack.pop()) { if (node.type === 'NumericLiteral') { checkNumber(file, node, reporter) continue } - if (isVerbatimTemplate(node)) { + if ( + node.type === 'TaggedTemplateExpression' && + node.tag.type === 'Identifier' && + verbatimTags.has(node.tag.name) + ) { // Its text is the raw source, which holds no escape to read: only interpolations remain. stack.push(...node.quasi.expressions) continue diff --git a/packages/workflow-code/src/print/verbatim-templates.test.ts b/packages/workflow-code/src/print/verbatim-templates.test.ts index 2879e5f8ab0..e608e42c77a 100644 --- a/packages/workflow-code/src/print/verbatim-templates.test.ts +++ b/packages/workflow-code/src/print/verbatim-templates.test.ts @@ -75,6 +75,13 @@ describe('a js template', () => { }) }) + it('still refuses a NUL escape in a cooked tag imported under a verbatim name', () => { + const result = compile( + "// @sim-sdk 1\nimport { fn, t as js, workflow } from '@sim/workflow-sdk'\n\nexport default workflow('Test', {}, () => {\n const f = fn('F', { code: js`return '\\u0000'` })\n})\n" + ) + expect(result.diagnostics.map((d) => d.code)).toContain('E_INVALID_CHARACTER') + }) + it('keeps a NUL escape as text rather than refusing an unstorable character', () => { const workflow = compiled(" const f = fn('F', { code: js`return '\\u0000'` })") expect(codeOf(workflow)).toEqual({ kind: 'value', value: "return '\\u0000'" }) From e077248f2bb3bac5115d599c48f5abab3722fa86 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 19:41:44 -0800 Subject: [PATCH 3/3] docs(workflow-sdk): show a table operation as an agent tool in the agents cookbook --- packages/workflow-sdk/cookbook/examples/agents.ts | 8 +++++--- packages/workflow-sdk/cookbook/examples/cookbook.ts | 8 ++++---- .../workflow-sdk/src/codegen/cookbook-text.generated.ts | 2 +- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/workflow-sdk/cookbook/examples/agents.ts b/packages/workflow-sdk/cookbook/examples/agents.ts index ec62d32842d..2fbeb5e7030 100644 --- a/packages/workflow-sdk/cookbook/examples/agents.ts +++ b/packages/workflow-sdk/cookbook/examples/agents.ts @@ -12,6 +12,7 @@ import { runWorkflow, slack, t, + table, trigger, workflow, } from '@sim/workflow-sdk' @@ -38,9 +39,9 @@ export default workflow( }, }) - // Agent tools: a workspace custom tool, one tool of an MCP server, an integration operation - // (.tool.; the params given here are fixed, the model fills the rest) and - // another workflow. + // Agent tools: a workspace custom tool, one tool of an MCP server, an integration or built-in + // operation (.tool., also table.tool.*, knowledge.tool.*, file.tool.*; the + // params given here are fixed, the model fills the rest) and another workflow. const support = agent('Support Agent', { model: 'claude-sonnet-4-6', apiKey: env.ANTHROPIC_API_KEY, @@ -52,6 +53,7 @@ export default workflow( customTool('lookup-order'), mcp('linear').tool('create_issue'), slack.tool.sendMessage({ credential: credential('ops-slack'), channel: 'support-urgent' }), + table.tool.queryRows({ tableId: table('orders') }), childWorkflow('enrich-lead').asTool(), ], }) diff --git a/packages/workflow-sdk/cookbook/examples/cookbook.ts b/packages/workflow-sdk/cookbook/examples/cookbook.ts index 02f6d27d432..4bfb92c9607 100644 --- a/packages/workflow-sdk/cookbook/examples/cookbook.ts +++ b/packages/workflow-sdk/cookbook/examples/cookbook.ts @@ -36,10 +36,10 @@ import { // integrations.ts:40 api: HTTP request: headers, retries, retryDelayMs // integrations.ts:50 table.updateRowById: update one row by id // integrations.ts:87 onError: error path to a response -// agents.ts:31 router: routes the model picks from -// agents.ts:51 tools: agent tools: custom, MCP, integration, child workflow -// agents.ts:62 runWorkflow: child workflow: inputMapping, enrich.result.data. -// agents.ts:71 parallel.collection: parallel fan-out +// agents.ts:32 router: routes the model picks from +// agents.ts:52 tools: agent tools: custom, MCP, integration, table, child workflow +// agents.ts:64 runWorkflow: child workflow: inputMapping, enrich.result.data. +// agents.ts:73 parallel.collection: parallel fan-out // An example to copy from, not a workflow of yours: `orders`, `policies`, `ops-slack` and // ANTHROPIC_API_KEY stand in for this workspace's resources. `sim workflows source resources` diff --git a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts index 42e1fcfb7cd..04ac9f761e6 100644 --- a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from cookbook/examples; do not edit. /** The example workflows, file name → text, written as `.sim/examples/`: together one correct example of each common block. */ -export const COOKBOOK_EXAMPLES: Readonly> = {"agents.ts":"// @sim-sdk 1\nimport {\n agent,\n childWorkflow,\n credential,\n customTool,\n env,\n mcp,\n parallel,\n response,\n router,\n runWorkflow,\n slack,\n t,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `lookup-order`, `linear`, `ops-slack`,\n// `enrich-lead` and ANTHROPIC_API_KEY stand in for this workspace\u0027s resources\n// (.sim/sdk/workspace.d.ts 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 operation\n // (.tool.; the params given here are fixed, the model fills the rest) and\n // another workflow.\n const support = agent(\u0027Support Agent\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Answer the customer. Use your tools when they help.\u0027 },\n { role: \u0027user\u0027, content: start.message },\n ],\n tools: [\n customTool(\u0027lookup-order\u0027),\n mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027),\n slack.tool.sendMessage({ credential: credential(\u0027ops-slack\u0027), channel: \u0027support-urgent\u0027 }),\n childWorkflow(\u0027enrich-lead\u0027).asTool(),\n ],\n })\n\n // Child workflow: inputMapping is checked against the child\u0027s start inputs. Its output is\n // enrich.result (untyped JSON): the child\u0027s response block output, so a field of the child\u0027s\n // response body is enrich.result.data..\n const enrich = runWorkflow(\u0027Enrich Lead\u0027, {\n workflowId: childWorkflow(\u0027enrich-lead\u0027),\n inputMapping: { email: start.email },\n })\n\n // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its\n // position; each.results lists every branch\u0027s output once all finish. (loop.forEach is the\n // sequential form.) In a function code file inside the body, the same values are\n // $ref.parallel.currentItem and $ref.parallel.index.\n const each = parallel.collection(\u0027Each Domain\u0027, { collection: start.domains }, (p) => {\n const brief = agent(\u0027Company Brief\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Describe ${p.currentItem} in two sentences.` }],\n })\n p.to(brief)\n })\n\n const answer = response(\u0027Answer\u0027, { body: { answer: support.content } })\n const briefs = response(\u0027Briefs\u0027, {\n body: { lead: t`${enrich.result}`, briefs: t`${each.results}` },\n })\n\n start.to(triage)\n triage.support.to(support)\n support.to(answer)\n triage.sales.to(enrich)\n enrich.to(each)\n each.to(briefs)\n }\n)\n","cookbook.ts":"// @sim-sdk 1\nimport {\n agent,\n condition,\n credential,\n env,\n fn,\n human,\n js,\n knowledge,\n knowledgeBase,\n loop,\n response,\n slack,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// 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:31 router: routes the model picks from\n// agents.ts:51 tools: agent tools: custom, MCP, integration, child workflow\n// agents.ts:62 runWorkflow: child workflow: inputMapping, enrich.result.data.\n// agents.ts:71 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. 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"}