diff --git a/.github/workflows/workflow-code-corpus.yml b/.github/workflows/workflow-code-corpus.yml new file mode 100644 index 00000000000..7779a823c7d --- /dev/null +++ b/.github/workflows/workflow-code-corpus.yml @@ -0,0 +1,45 @@ +name: workflow-code-corpus + +# The workflow-code corpus suites over the whole generated corpus. The PR test job samples a few +# cases per block type (`corpusSubjects`) to stay inside its budget, so a property that fails only +# on an unsampled case never shows there. This runs every case nightly, and on a change to itself. + +on: + pull_request: + paths: + - '.github/workflows/workflow-code-corpus.yml' + schedule: + - cron: '17 8 * * *' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: workflow-code-corpus-${{ github.ref }} + cancel-in-progress: true + +jobs: + corpus: + name: corpus (full) + runs-on: ${{ (vars.CI_PROVIDER == '' || vars.CI_PROVIDER == 'blacksmith') && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} + timeout-minutes: 60 + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + + - name: Setup workspace + uses: ./.github/actions/setup + with: + provider: ${{ vars.CI_PROVIDER }} + + - name: Run the corpus suites over every case + working-directory: apps/sim + env: + ROUNDTRIP_CORPUS_FULL: '1' + NODE_OPTIONS: '--no-warnings --max-old-space-size=8192' + NEXT_PUBLIC_APP_URL: 'https://www.sim.ai' + DATABASE_URL: 'postgresql://postgres:postgres@localhost:5432/simstudio' + ENCRYPTION_KEY: '0000000000000000000000000000000000000000000000000000000000000000' # dummy key for CI only + run: bunx vitest run lib/workflows/code/corpus/ + diff --git a/apps/docs/content/docs/workflows/code/diagnostics.mdx b/apps/docs/content/docs/workflows/code/diagnostics.mdx index 680fbaf6100..a6e30ebc5be 100644 --- a/apps/docs/content/docs/workflows/code/diagnostics.mdx +++ b/apps/docs/content/docs/workflows/code/diagnostics.mdx @@ -69,7 +69,7 @@ Reading and writing `workflow.ts`. | `E_UNKNOWN_BUILDER` | A builder path the catalog does not have, a bare builder-shaped call (`apii('Name', …)`) nothing binds, or a namespace the SDK lacks or the file did not import; `hint` names the builder a common other name stands for (`http.request` → `api`), then prefers a synonymous verb (`postMessage` → `sendMessage`), then the closest path, then the namespace's builders. | | `E_UNKNOWN_PARAM` | A param the block does not have; the hint has a did-you-mean, or for block meta written there (`retry`, `disabled`, `locked`, `errorPort`) the third argument that takes it. | | `E_FIXED_PARAM` | A param the builder already pins. | -| `W_FIELD_NOT_APPLICABLE` | A param not visible under the block's values; apply keeps the stored value and the written-back source drops it. | +| `W_FIELD_NOT_APPLICABLE` | A param not visible under the block's values, or a basic-only field on a block with `advancedMode`; apply keeps the stored value and the written-back source drops it. | | `W_REQUIRED_MISSING` | A required field left empty, including `todo()`; not repeated for a field an `E_UNKNOWN_PARAM` did-you-mean names, or one written with a value that failed to compile. | | `W_UNKNOWN_OPTION` | A dropdown value none of its options names; `hint` lists them. | | `E_UNKNOWN_OPERATION` | An `operation` the block does not offer; `hint` lists them. A retired one the stored block holds is `W_UNKNOWN_OPTION`. | @@ -80,7 +80,7 @@ Reading and writing `workflow.ts`. | `W_VALUE_KIND` | A value whose JSON type differs from the field's. | | `W_OUT_OF_RANGE` | A literal slider value outside the catalog `min`/`max`, off its `step`, or fractional where it takes whole numbers; kept as written, and the executor forwards it unclamped. | | `W_TABLE_FILTER_SHAPE` | A literal table filter the runtime refuses: the legacy `$` operator grammar, or predicate and builder rows mixed. | -| `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. For a literal token in a credential field, the hint says `credential('')`. | +| `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field or workflow variable holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. A value Sim minted at creation (a webhook token) is not reported. For a literal token in a credential field, the hint says `credential('')`. | | `W_SUBFLOW_COUNT` | A loop or parallel count, or a parallel batch size, the runtime replaces or clamps. | | `W_UNKNOWN_OUTPUT_PATH` | A ref path the block's outputs do not have; the hint has a did-you-mean or lists the outputs. | | `W_OUTPUT_PATH_UNDECLARED` | A path the block does not declare that the run still accepts: an undeclared `inputFormat` input, or `x.error` with no error edge. Never refused. | diff --git a/apps/docs/content/docs/workflows/code/syntax.mdx b/apps/docs/content/docs/workflows/code/syntax.mdx index c3fc3c08730..49a81eabd26 100644 --- a/apps/docs/content/docs/workflows/code/syntax.mdx +++ b/apps/docs/content/docs/workflows/code/syntax.mdx @@ -90,7 +90,7 @@ How to read it: - Each `const` is a block. `agent`, `condition`, `table.insertRow`, and `slack.sendMessage` are the blocks you know from the workflow builder, with the same settings. - `classify.category` is a typed reference to another block's output, the same as `` in the builder. `t` writes text with references in it; `js` writes code. - `table('tickets')` and `credential('support-slack')` name workspace resources by a stable key. Renaming the table in Sim keeps the key. -- `env.TICKETS_WEBHOOK_TOKEN` reads an environment variable. Secret values are never printed: a key pasted into a password field prints as `stored()`, which keeps the saved value. +- `env.TICKETS_WEBHOOK_TOKEN` reads an environment variable. A key pasted into a password field, or a value that looks like a credential, prints as `stored()`, which keeps the saved value. - `.to()` connects blocks, `byCategory.billing` is one branch of the condition, and `.onError()` follows the error path. `notify` has three incoming edges and runs once, after the branch that was taken. - A webhook answers its caller as soon as the request is accepted and runs the workflow in the background, so the caller never sees a `response` block's output. `responseMode: 'custom'` sets that fixed answer (here `202` with `{ "ok": true }`; without it, `200` with `{ "message": "Webhook processed" }`). To answer with values the run computes, start the workflow with `trigger.start` and call it through the API; a `response` block then sets what the caller receives. @@ -110,7 +110,7 @@ export default workflow('Name', { description: '…', variables: { /* … */ } } - Line 1 is `// @sim-sdk N`. Without it the file is refused with `E_SDK_HEADER`; a number other than the one the server reads is `E_SDK_MAJOR`. - Imports are named imports from `'@sim/workflow-sdk'` only. Aliases are allowed. - The file has exactly one `export default workflow(name, options?, body)` (`E_WORKFLOW_EXPORT`). `options` is `{ description?, variables? }`. `body` is `() => { … }` or `({ vars }) => { … }`. -- Variables are `variables: { : { name?, type, value } }`. `type` is `string`, `number`, `boolean`, `object`, `array` or `plain`, and both `type` and `value` are required; `value` is plain JSON. The key is the variable's key: lowercased, with spaces and dots removed. `name` is written only when it differs, and must normalize to the key (`E_VARIABLE_NAME_MISMATCH`). Read one as `vars.`. +- Variables are `variables: { : { name?, type, value } }`. `type` is `string`, `number`, `boolean`, `object`, `array` or `plain`, and both `type` and `value` are required; `value` is plain JSON, or `stored()` for a value that looks like a credential. The key is the variable's key: lowercased, with spaces and dots removed. `name` is written only when it differs, and must normalize to the key (`E_VARIABLE_NAME_MISMATCH`). Read one as `vars.`. - The body holds block declarations and wiring statements. Helpers, loops, conditionals and imports of your own have no stored form and are refused. Use `loop`, `parallel`, `condition` and `runWorkflow` blocks instead. ## Blocks @@ -124,8 +124,9 @@ export default workflow('Name', { description: '…', variables: { /* … */ } } - A param is a setting of the block, named as `sim workflows source params ` lists it. For a setting the builder shows as a basic or advanced pair, you write the shared name, not either member. Writing a member by its own name is `E_UNKNOWN_PARAM`, and the hint names the right one. - An omitted param is the default the workflow builder fills in, so a block with no params is stored like one made in the builder. `null` for a whole param stores it as absent. +- A value Sim creates with the block, such as a webhook token, is kept when the source leaves it out. Write `null` to clear it; on a new block, `null` creates the block without one. - A param the builder already fixes, such as `operation`, is `E_FIXED_PARAM`. -- A param that is not visible under the block's other settings is `W_FIELD_NOT_APPLICABLE`. It never runs, so the apply keeps the stored value and the next `get` leaves the line out. +- A param that is not visible under the block's other settings is `W_FIELD_NOT_APPLICABLE`, as is a basic-only field on a block with `advancedMode: true`. It never runs, so the apply keeps the stored value and the next `get` leaves the line out. - A required field left empty, or written as `todo()`, is `W_REQUIRED_MISSING`. A value of the wrong JSON type is `W_VALUE_KIND`; it is never converted. ### Selecting a resource or typing an ID @@ -186,7 +187,7 @@ In a workspace directory, `sim workspaces source check` reports a key the direct ### Secrets and `stored()` -A secret is never printed. A literal value in a password field prints as `stored()`, which compiles to the value the stored workflow already holds for the same block and param. A new block, another block type or an empty field has nothing stored: `stored()` there is `E_STORED_VALUE_MISSING`. To set a secret, write `env.NAME` and keep the value in the workspace's environment variables. A literal key in the file is `W_LITERAL_SECRET`. +A literal value in a password field prints as `stored()`, and so does any param, tool param or variable value that looks like a credential: a known token format, an `Authorization` header or a credential-named property. `stored()` compiles to the value the stored workflow already holds for the same block and param, or for a variable, the same variable. A secret that matches none of these patterns outside a password field prints as written. A new block, another block type or an empty field has nothing stored: `stored()` there is `E_STORED_VALUE_MISSING`. To set a secret, write `env.NAME` and keep the value in the workspace's environment variables. A literal key in the file is `W_LITERAL_SECRET`. ### References diff --git a/apps/sim/lib/workflows/code/hand-written.test.ts b/apps/sim/lib/workflows/code/hand-written.test.ts index d196d9ae7bd..f9895de0b43 100644 --- a/apps/sim/lib/workflows/code/hand-written.test.ts +++ b/apps/sim/lib/workflows/code/hand-written.test.ts @@ -105,12 +105,16 @@ function applyTwice(text: string) { } /** One stored block canonicalized, printed and compiled back against what it continues. */ -function printAndCompile(type: string, values: Record) { +function printAndCompile( + type: string, + values: Record, + options: { advancedMode?: boolean } = {} +) { const subBlocks = Object.fromEntries( Object.entries(values).map(([id, value]) => [id, { id, type: 'short-input', value }]) ) const state: WorkflowState = { - blocks: { b1: createBlock({ id: 'b1', type, name: 'Block', subBlocks } as never) }, + blocks: { b1: createBlock({ id: 'b1', type, name: 'Block', subBlocks, ...options } as never) }, edges: [], loops: {}, parallels: {}, @@ -122,7 +126,12 @@ function printAndCompile(type: string, values: Record) { }).workflow const text = printWorkflow({ workflow: canonical, catalog, options: { functionCode: 'inline' } }) .files[0].text - return { text, diagnostics: compile(text, canonical).diagnostics } + return { text, canonical, diagnostics: compile(text, canonical).diagnostics } +} + +/** The params a compile's diagnostics of `code` name. */ +function paramsOf(diagnostics: ReadonlyArray<{ code: string; param?: string }>, code: string) { + return diagnostics.filter((d) => d.code === code).map((d) => d.param) } describe('hand-written source over the real catalog', () => { @@ -234,6 +243,70 @@ export default workflow('Chat', {}, () => { expect(compile(text).diagnostics).toEqual([]) }, 120_000) + it('treats a basic-only field as never running on a block in advanced mode', () => { + const { text, canonical, diagnostics } = printAndCompile( + 'sailpoint_v2', + { operation: 'sailpoint_search_aggregate', aggregationType: 'SAILPOINT' }, + { advancedMode: true } + ) + expect(text).not.toContain('aggregations:') + expect(paramsOf(diagnostics, 'W_REQUIRED_MISSING')).not.toContain('aggregations') + const written = text.replace( + "aggregationType: 'SAILPOINT',", + "aggregationType: 'SAILPOINT',\n aggregations: { name: 'department' }," + ) + expect(written).not.toBe(text) + expect(paramsOf(compile(written, canonical).diagnostics, 'W_FIELD_NOT_APPLICABLE')).toEqual([ + 'aggregations', + ]) + }, 120_000) + + it('keeps a credential in a workflow variable out of the file and compiles it back', () => { + const key = ['sk-proj-', 'abcdefghijklmnopqrstuvwxyz', '123456'].join('') + const text = `${HEADER}import { trigger, workflow } from '@sim/workflow-sdk' +export default workflow('Keys', { variables: { apiKey: { type: 'string', value: '${key}' } } }, () => { + trigger.start('Start', {}) +}) +` + const run = applyTwice(text) + expect(run.first.diagnostics.map((d) => d.code)).toEqual(['W_LITERAL_SECRET']) + expect(run.readBack).not.toContain(key) + expect(run.readBack).toContain('value: stored()') + const again = compile(run.readBack, run.canonical) + expect(again.diagnostics.filter((d) => d.severity === 'error')).toEqual([]) + expect(again.workflow?.variables).toEqual(run.canonical.variables) + expect(compile(run.readBack).diagnostics.map((d) => d.code)).toContain('E_STORED_VALUE_MISSING') + const offline = (variables: Record) => + compileWorkflow({ + entry: { path: 'workflow.ts', text: run.readBack }, + files: new Map(), + catalog, + sdkMajor: catalog.sdkMajor, + storedUnread: { version: 1, blocks: {}, variables }, + }).diagnostics.filter((d) => d.code === 'E_STORED_VALUE_MISSING') + expect(offline({ apikey: 'var-1' })).toEqual([]) + expect(offline({ other: 'var-1' })).toHaveLength(1) + }, 120_000) + + it('never warns about the webhook token Sim mints, on apply or read-back', () => { + const text = `${HEADER}import { trigger, workflow } from '@sim/workflow-sdk' +export default workflow('Hook', {}, () => { + trigger.webhook('Hook', {}) +}) +` + const run = applyTwice(text) + expect(run.readBack).toContain('token: stored()') + const printed = printWorkflow({ + workflow: run.canonical, + catalog, + options: { functionCode: 'inline' }, + }) + expect(paramsOf(printed.diagnostics, 'W_LITERAL_SECRET')).toEqual([]) + expect(paramsOf(compile(run.readBack, run.canonical).diagnostics, 'W_LITERAL_SECRET')).toEqual( + [] + ) + }, 120_000) + it('reads a stored uploaded file back as source that type-checks and compiles clean', () => { const file = { name: 'a.txt', path: '/api/files/serve/a.txt', size: 3, type: 'text/plain' } const { text, diagnostics } = printAndCompile('agent', { diff --git a/packages/workflow-code/DESIGN.md b/packages/workflow-code/DESIGN.md index dca5b69e8f7..966e8950905 100644 --- a/packages/workflow-code/DESIGN.md +++ b/packages/workflow-code/DESIGN.md @@ -426,7 +426,7 @@ as written (`table_v2`'s filter builder). ## Secrets -A secret is never printed. `secrets.ts` holds the one predicate print and compile share +A detected secret is never printed. `secrets.ts` holds the one predicate print and compile share (`holdsSecret`): literal text in a `password` subBlock, or in any other field a high-confidence credential (`holdsDetectedSecret`): a known token format (`sk-…`, `ghp_…`, `xoxb-…`, `AKIA…`, a JWT, a private key, `Bearer `), a credential header row (`Authorization`, `X-Api-Key`), a @@ -437,7 +437,9 @@ credential-named property, code assignment or URL query parameter (`api_key`, `c Such a param (block params, agent tool params and MCP tool arguments alike) prints as `stored()`, meaning "keep the stored value", with `W_LITERAL_SECRET`; compile warns the same way where source -writes one literally. A custom tool snapshot's code has no `stored()` form, so a credential there +writes one literally. A workflow variable value holding a detected credential does the same, its +`stored()` resolved by variable key. A value creation mints (`mintsFreshValue`, a webhook token) +prints as `stored()` without the warning: Sim wrote it, not the source. A custom tool snapshot's code has no `stored()` form, so a credential there only warns. Compile resolves `stored()` to the value `CompileInput.stored` (the stored workflow, canonicalized under the submitted lock) holds for the same block key, type and param, a pair's members and mode included, so a get followed by an unchanged apply keeps the value. A new block, diff --git a/packages/workflow-code/src/catalog/activity.ts b/packages/workflow-code/src/catalog/activity.ts index ad9cd3bacfc..17b22dde001 100644 --- a/packages/workflow-code/src/catalog/activity.ts +++ b/packages/workflow-code/src/catalog/activity.ts @@ -254,10 +254,20 @@ function serializes(subBlock: CatalogSubBlock, inputs: ActivityInputs): boolean } if (subBlock.mode === 'advanced' && !advancedMode) return isNonEmptyValue(values[subBlock.id]) - if (subBlock.mode === 'basic' && advancedMode) return false + if (basicOnlyHidden(subBlock, advancedMode)) return false return conditionHolds(subBlock, values) } +/** + * Whether the block's `advancedMode` keeps a standalone field (one outside any `canonicalParamId` + * group) from ever running: the serializer never sends a basic-only field from a block in advanced + * mode, whatever it holds. Compile and print ask here before treating such a field as applicable + * or required, so neither asks for a value the run would drop. + */ +export function basicOnlyHidden(subBlock: CatalogSubBlock, advancedMode: boolean): boolean { + return advancedMode && subBlock.mode === 'basic' && subBlock.canonicalParamId === undefined +} + /** * Whether a stored param is inactive: stored, but neither forwarded by the serializer nor read by * deploy (`deployReadIds`) under the block's current values. Mirrors the include rule in diff --git a/packages/workflow-code/src/catalog/defaults.ts b/packages/workflow-code/src/catalog/defaults.ts index 0cd4d512e88..94c89a58ed4 100644 --- a/packages/workflow-code/src/catalog/defaults.ts +++ b/packages/workflow-code/src/catalog/defaults.ts @@ -46,7 +46,9 @@ export function subBlockEditorDefault(subBlock: CatalogSubBlock): EditorDefault * state it, and a block created from source keeps the value `MaterializeHooks.initBlock` computed, * exactly as a canvas-created block does. */ -export function mintsFreshValue(subBlock: CatalogSubBlock): boolean { +export function mintsFreshValue( + subBlock: Pick +): boolean { if (subBlock.hidden || subBlock.readOnly) return false const thunk = subBlock.valueDefault return thunk !== undefined && 'computed' in thunk && thunk.initial === undefined diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index 580068f7aee..24343120274 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -14,8 +14,10 @@ workflow. **Defaults.** An omitted param is the editor default canvas creation writes, so a block written with no params is stored as a canvas-created one. `null` as a whole param means stored-absent (no -default fills it). The printer omits a value equal to the default and writes `null` for an active -field that has a default but no stored value. +default fills it). A value Sim mints when the block is created (`mintsFreshValue`: a webhook +token) is kept when source leaves it out; `null` clears it, and on a new block creates it without +one. The printer omits a value equal to the default and writes `null` for an active field that has +a default but no stored value. ## File @@ -39,7 +41,8 @@ export default workflow('Name', { description: '…', variables: { … } }, ({ v - Variables: `variables: { : { name?, type, value } }`. The property key is the variable key; `name` is written only when it differs, and must normalize to the key (`E_VARIABLE_NAME_MISMATCH`). `type` is `string | number | boolean | object | array | plain`; - `value` is plain JSON. Both are required. The stored key is the property key normalized + `value` is plain JSON, or `stored()` for a value holding a detected credential (see `stored()`). + Both are required. The stored key is the property key normalized (lowercased, spaces and dots removed), and `vars.` resolves through it. - The body holds block declarations and wiring statements. No other statements, no helpers, no loops, no conditionals, no imports of your own. @@ -84,9 +87,10 @@ export default workflow('Name', { description: '…', variables: { … } }, ({ v - A pinned param (`operation`, or a builder's `fixed` entry) is `E_FIXED_PARAM`; the compiler adds pinned values. - A param not visible under the block's values is `W_FIELD_NOT_APPLICABLE`, naming the value that - hides it: it never runs, so apply keeps the stored value (preserved state) and the written-back - source drops the line. A required field left - empty (or `todo()`) is `W_REQUIRED_MISSING`. A value whose JSON type differs from the field's is + hides it, as is a basic-only field (`mode: 'basic'`, no canonical pair) on a block with + `advancedMode`, which the serializer never sends: it never runs, so apply keeps the stored value + (preserved state) and the written-back source drops the line. A required field left empty (or + `todo()`) is `W_REQUIRED_MISSING`. A value whose JSON type differs from the field's is `W_VALUE_KIND`; it is never coerced. ### Pair mode @@ -176,11 +180,15 @@ no live resource is `E_MAT_UNKNOWN_RESOURCE` on apply. ### `stored()` -The printer writes `stored()` for literal text in a `password` field (a secret is never printed; -`{{ENV}}` and references print as themselves), in params and tool params alike. It compiles to the +The printer writes `stored()` for literal text in a `password` field and for a value holding a +detected credential (`secrets.ts`; `{{ENV}}` and references print as themselves), in params, tool +params and workflow variable values alike. A secret the detector does not recognize outside a +password field prints as written. It compiles to the value `CompileInput.stored` (the stored workflow the file continues) holds for the same block key, type and param, a pair's members and mode included. A new block, another type or an empty field is -`E_STORED_VALUE_MISSING`; inside a value it is `E_UNSUPPORTED_SYNTAX`. +`E_STORED_VALUE_MISSING`; inside a value it is `E_UNSUPPORTED_SYNTAX`. A variable's +`value: stored()` compiles to the stored workflow's variable of the same key, and is +`E_STORED_VALUE_MISSING` when there is none. A tool's `stored()` takes the value of the stored tool it continues, matched by identity: the one stored tool of the same type and operation whose params agree with every param the source writes. @@ -441,7 +449,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `E_UNKNOWN_BUILDER` | A builder path the catalog does not have, a bare builder-shaped call (`apii('Name', …)`) nothing binds, or a namespace the SDK lacks or the file did not import; `hint` names the builder a common other name stands for (`http.request` → `api`), then prefers a synonymous verb (`postMessage` → `sendMessage`), then the closest path, then the namespace's builders. | | `E_UNKNOWN_PARAM` | A param the block does not have; the hint has a did-you-mean, or for block meta written there (`retry`, `disabled`, `locked`, `errorPort`) the third argument that takes it. | | `E_FIXED_PARAM` | A param the builder already pins. | -| `W_FIELD_NOT_APPLICABLE` | A param not visible under the block's values; apply keeps the stored value and the written-back source drops it. | +| `W_FIELD_NOT_APPLICABLE` | A param not visible under the block's values, or a basic-only field on a block with `advancedMode`; apply keeps the stored value and the written-back source drops it. | | `W_REQUIRED_MISSING` | A required field left empty, including `todo()`; not repeated for a field an `E_UNKNOWN_PARAM` did-you-mean names, or one written with a value that failed to compile. | | `W_UNKNOWN_OPTION` | A dropdown value none of its options names; `hint` lists them. | | `E_UNKNOWN_OPERATION` | An `operation` the block does not offer; `hint` lists them. A retired one the stored block holds is `W_UNKNOWN_OPTION`. | @@ -452,7 +460,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `W_VALUE_KIND` | A value whose JSON type differs from the field's. | | `W_OUT_OF_RANGE` | A literal slider value outside the catalog `min`/`max`, off its `step`, or fractional where it takes whole numbers; kept as written, and the executor forwards it unclamped. | | `W_TABLE_FILTER_SHAPE` | A literal table filter the runtime refuses: the legacy `$` operator grammar, or predicate and builder rows mixed. | -| `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. For a literal token in a credential field, the hint says `credential('')`. | +| `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field or workflow variable holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. A value Sim minted at creation (a webhook token) is not reported. For a literal token in a credential field, the hint says `credential('')`. | | `W_SUBFLOW_COUNT` | A loop or parallel count, or a parallel batch size, the runtime replaces or clamps. | | `W_UNKNOWN_OUTPUT_PATH` | A ref path the block's outputs do not have; the hint has a did-you-mean or lists the outputs. | | `W_OUTPUT_PATH_UNDECLARED` | A path the block does not declare that the run still accepts: an undeclared `inputFormat` input, or `x.error` with no error edge. Never refused. | diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 133d77f7d52..a210e0a2ced 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -26,7 +26,12 @@ import { SUBFLOW_DATA_KEYS, } from '../canonicalize/subflows' import { REFERENCE_CANDIDATE } from '../canonicalize/values' -import { canonicalActivityInputs, isInactive, withStoredValue } from '../catalog/activity' +import { + basicOnlyHidden, + canonicalActivityInputs, + isInactive, + withStoredValue, +} from '../catalog/activity' import { editorDefaults, mintsFreshValue } from '../catalog/defaults' import { builderPins, @@ -432,9 +437,10 @@ function parseCodeFile( if (ctx.codeFiles.bytes > limits.maxTotalBytes) { // Reported once, on the file that crosses the cap; each file after it is skipped silently. if (before > limits.maxTotalBytes) return null + const total = before + utf8ByteLength(text) ctx.reporter.report( 'E_LIMIT_EXCEEDED', - `The workflow and its code files total more than ${limits.maxTotalBytes} bytes.`, + `The workflow and its code files total ${total} bytes with ${path}; the limit is ${limits.maxTotalBytes}.`, at, { hint: 'Share one code file between blocks, or shorten the code.', blockKey: decl.key } ) @@ -797,18 +803,26 @@ function pairMode(field: Extract, value: Compile return derivedMember?.type === 'code' && otherMember.type !== 'code' ? other : derived } +/** What `keepStored` reads of a member: its id, and the traits that decide `W_LITERAL_SECRET`. */ +type StoredMember = Pick< + CatalogSubBlock, + 'id' | 'password' | 'hidden' | 'readOnly' | 'valueDefault' +> + /** * `stored()`: the param keeps what the stored block holds (`CompileInput.stored`), a pair its * members and mode, without the value ever appearing in source. Only a block the stored workflow * already has under this key and type, holding a value for the param, can keep one. Under * `CompileInput.storedUnread` a block the lock binds may be such a block, which only the server - * can tell, so its param is left out unread (neither refused nor defaulted, nor required). + * can tell, so its param is left out unread (neither refused nor defaulted, nor required). A kept + * value creation minted (`mintsFreshValue`: a webhook token) is no `W_LITERAL_SECRET`: Sim wrote + * it, not the source. */ function keepStored( ctx: CompileContext, state: Pick & Partial>, - members: ReadonlyArray<{ id: SubBlockId; password?: boolean }>, + members: ReadonlyArray, property: ObjectProperty, field: CatalogField | null ): void { @@ -841,7 +855,7 @@ function keepStored( const param = getOwn(stored.params, member.id) if (param) setOwn(params, member.id, param) else state.unset.add(member.id) - if (param?.kind === 'value' && holdsSecret(member, param.value)) { + if (param?.kind === 'value' && !mintsFreshValue(member) && holdsSecret(member, param.value)) { reportLiteralSecret(ctx, decl.key, { property, param: name }, member) } } @@ -1717,7 +1731,18 @@ function checkFields(ctx: CompileContext, index: FieldIndex, state: BlockState): for (const entry of state.written) { const sub = declarationFor(index, entry.target, lookup) if (!sub) continue - if (!isVisible(sub, values)) { + if (basicOnlyHidden(sub, state.meta.advancedMode)) { + ctx.reporter.report( + 'W_FIELD_NOT_APPLICABLE', + notApplicableMessage(entry.param, 'basic mode only, and the block sets advancedMode'), + rangeOf(ctx, entry.property), + { + hint: `Remove ${entry.param}, or drop advancedMode so it runs.`, + blockKey: decl.key, + param: entry.param, + } + ) + } else if (!isVisible(sub, values)) { ctx.reporter.report( 'W_FIELD_NOT_APPLICABLE', notApplicableMessage(entry.param, hiddenReason(sub, values)), @@ -1764,7 +1789,8 @@ function checkFields(ctx: CompileContext, index: FieldIndex, state: BlockState): ) } } - for (const field of missingRequiredFields(index, values, (id) => Object.hasOwn(params, id))) { + const isWritten = (id: SubBlockId) => Object.hasOwn(params, id) + for (const field of missingRequiredFields(index, values, isWritten, state.meta.advancedMode)) { if (state.explained.has(field.name)) continue const todo = state.todos.get(field.name) ctx.reporter.report( diff --git a/packages/workflow-code/src/compile/context.ts b/packages/workflow-code/src/compile/context.ts index 4f28367608d..4673e4a7893 100644 --- a/packages/workflow-code/src/compile/context.ts +++ b/packages/workflow-code/src/compile/context.ts @@ -282,6 +282,13 @@ export function lookup(scope: Scope, name: string): Binding | null { return null } +/** Whether `node` is the SDK's `stored()` as `scope` binds it, called with no arguments. */ +export function isStoredCall(scope: Scope, node: Node): boolean { + if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier') return false + const binding = lookup(scope, node.callee.name) + return binding?.kind === 'sdk' && binding.name === 'stored' && node.arguments.length === 0 +} + /** Every identifier visible from `scope`, innermost first, for did-you-mean. */ function visibleNames(scope: Scope): string[] { const names: string[] = [] diff --git a/packages/workflow-code/src/compile/hostile.test.ts b/packages/workflow-code/src/compile/hostile.test.ts index 252512d56d0..17197c8528c 100644 --- a/packages/workflow-code/src/compile/hostile.test.ts +++ b/packages/workflow-code/src/compile/hostile.test.ts @@ -409,6 +409,11 @@ describe('hostile sources produce diagnostics only', () => { ) const limits = result.diagnostics.filter((d) => d.code === 'E_LIMIT_EXCEEDED') expect(limits.map((d) => d.blockKey)).toEqual(['f2']) + const measured = + /total (\d+) bytes with workflows\/functions\/f2\.js; the limit is 2000\./.exec( + limits[0]?.message ?? '' + ) + expect(Number(measured?.[1])).toBeGreaterThan(2_000) expect(result.workflow).toBeNull() }) diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index 7aaecb3ff52..f5484c60e1e 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -36,10 +36,18 @@ import type { import { getOwn, setOwn } from '../records' import { childResultScope } from '../responds' import { SDK_MODULE } from '../sdk' +import { holdsDetectedSecret, variableSecretFinding } from '../secrets' import { compileBlock } from './blocks' import { checkStorableLiterals, checkStorableText } from './characters' import { CommentCollector } from './comments' -import { type CompileContext, rangeOf, recordSpan, type Scope, unsupported } from './context' +import { + type CompileContext, + isStoredCall, + rangeOf, + recordSpan, + type Scope, + unsupported, +} from './context' import { EdgeCollector } from './edges' import { referencedResultKind } from './function-returns' import { didYouMean, HINTS, hintForNode, nodeLabel } from './hints' @@ -239,7 +247,33 @@ function namesVariableKey(name: string, key: VarKey): boolean { return normalized === key || collisionSuffix(key, normalized) } -function compileVariables(ctx: CompileContext, node: Node): void { +/** + * A variable's `value: stored()`, which get prints for a value holding a credential: the value the + * stored workflow's variable `key` holds. With only the lock of the stored workflow + * (`storedUnread`) a variable the lock records cannot be read, so it is `null` unread, as an + * offline check needs nothing more. `undefined` after `E_STORED_VALUE_MISSING`. + */ +function storedVariableValue( + ctx: CompileContext, + key: VarKey, + node: Node +): CanonicalVariable['value'] | undefined { + const unread = ctx.stored ? undefined : ctx.storedUnread + if (unread && Object.hasOwn(unread.variables, key)) return null + const stored = ctx.stored && getOwn(ctx.stored.variables, key) + if (stored) return stored.value + ctx.reporter.report( + 'E_STORED_VALUE_MISSING', + ctx.stored || unread + ? `stored() keeps the value of variable ${key}, but the stored workflow has no such variable.` + : `stored() keeps the value of variable ${key}, but there is no stored workflow to keep it from.`, + rangeOf(ctx, node), + { hint: `Write the value of ${key}.` } + ) + return undefined +} + +function compileVariables(ctx: CompileContext, node: Node, scope: Scope): void { if (node.type !== 'ObjectExpression') { unsupported( ctx, @@ -339,7 +373,16 @@ function compileVariables(ctx: CompileContext, node: Node): void { } } else if (field === 'value') { valueWritten = true - value = compileJsonLiteral(ctx, fieldProperty.value) + value = isStoredCall(scope, fieldProperty.value) + ? storedVariableValue(ctx, key, fieldProperty.value) + : compileJsonLiteral(ctx, fieldProperty.value) + // Written or kept stored, as for a param: a credential in a variable travels with every copy. + if (value !== undefined && holdsDetectedSecret(value)) { + const { message, hint } = variableSecretFinding(key) + ctx.reporter.report('W_LITERAL_SECRET', message, rangeOf(ctx, fieldProperty.value), { + hint, + }) + } } else { unsupported( ctx, @@ -410,7 +453,7 @@ function compileWorkflowCall( "Write description: '...'." ) } else if (key === 'variables') { - compileVariables(ctx, property.value) + compileVariables(ctx, property.value, moduleScope) } else { ctx.reporter.report( 'E_UNKNOWN_PARAM', diff --git a/packages/workflow-code/src/compile/tools.ts b/packages/workflow-code/src/compile/tools.ts index a354ca6df77..e965c4c547b 100644 --- a/packages/workflow-code/src/compile/tools.ts +++ b/packages/workflow-code/src/compile/tools.ts @@ -32,7 +32,14 @@ import { import { deepEqual, getOwn, setOwn } from '../records' import { CUSTOM_TOOL_TYPE, hasToolForm } from '../sdk' import { holdsSecret, literalSecretFinding } from '../secrets' -import { type CompileContext, lockBinds, lookup, rangeOf, unsupported } from './context' +import { + type CompileContext, + isStoredCall, + lockBinds, + lookup, + rangeOf, + unsupported, +} from './context' import { didYouMean, hintForNode, nodeLabel, suggestBuilder } from './hints' import { calleePath, @@ -661,7 +668,7 @@ function compileMcpTool( site.decl.key ) } - if (isStoredCall(site, argProperty.value)) { + if (isStoredCall(site.scope, argProperty.value)) { // Holds the argument's place; `resolveStoredParams` fills in the stored value. setOwn(form.args, arg, null) pending.push({ param: arg, key: arg, node: argProperty.value }) @@ -786,12 +793,6 @@ function literalKey(property: ObjectProperty): string | null { return null } -function isStoredCall(site: ValueSite, node: Node): boolean { - if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier') return false - const binding = lookup(site.scope, node.callee.name) - return binding?.kind === 'sdk' && binding.name === 'stored' && node.arguments.length === 0 -} - /** * `raw(tool)`, the canonical tool verbatim. The printer writes a password param holding literal * text as `params: { key: stored() }`, so a direct `stored()` entry of `params` is taken out of @@ -823,7 +824,7 @@ function compileRawTool( if ( key !== null && property.type === 'ObjectProperty' && - isStoredCall(site, property.value) + isStoredCall(site.scope, property.value) ) { pending.push({ param: key, key, node: property.value }) } else kept.push(property) diff --git a/packages/workflow-code/src/compile/validate-catalog.ts b/packages/workflow-code/src/compile/validate-catalog.ts index 6b9429b0919..f7d4c3c0dcf 100644 --- a/packages/workflow-code/src/compile/validate-catalog.ts +++ b/packages/workflow-code/src/compile/validate-catalog.ts @@ -1,3 +1,4 @@ +import { basicOnlyHidden } from '../catalog/activity' import { type ConditionClause, type ConditionLookup, @@ -81,13 +82,15 @@ export function hiddenReason( * canvas writes. A field counts when no member holds a value and some member is certainly visible * and certainly required under those values: a provider's credential fields never count for a * model of another provider, and the half of a channel/DM switch the block does not use never - * counts. The server's lint, which runs the registry's own conditions, still reports what this + * counts, nor does a basic-only field of a block in advanced mode (`basicOnlyHidden`), which never + * runs. The server's lint, which runs the registry's own conditions, still reports what this * static check cannot decide. */ export function missingRequiredFields( index: FieldIndex, values: ReadonlyMap, - isWritten: (subBlockId: SubBlockId) => boolean + isWritten: (subBlockId: SubBlockId) => boolean, + advancedMode: boolean ): CatalogField[] { const missing: CatalogField[] = [] for (const field of index.fields.values()) { @@ -96,7 +99,12 @@ export function missingRequiredFields( const lookup = paramLookup(values) const declared = members.flatMap((sub) => index.declarations.get(sub.id) ?? [sub]) if ( - declared.some((sub) => evaluateCondition(sub, lookup) === true && isRequired(sub, values)) + declared.some( + (sub) => + !basicOnlyHidden(sub, advancedMode) && + evaluateCondition(sub, lookup) === true && + isRequired(sub, values) + ) ) { missing.push(field) } diff --git a/packages/workflow-code/src/print/params.ts b/packages/workflow-code/src/print/params.ts index d715b65c97f..74b97174362 100644 --- a/packages/workflow-code/src/print/params.ts +++ b/packages/workflow-code/src/print/params.ts @@ -6,13 +6,14 @@ import { compareStrings } from '@sim/utils/string' import { type ActivityInputs, + basicOnlyHidden, canonicalActivityInputs, executableInactiveParams, isInactive, withStoredValue, } from '../catalog/activity' import { recordLookup } from '../catalog/conditions' -import { type EditorDefault, editorDefaults } from '../catalog/defaults' +import { type EditorDefault, editorDefaults, mintsFreshValue } from '../catalog/defaults' import { buildFieldIndex, declarationFor, @@ -138,6 +139,8 @@ function printParamValue( if (!param) return null if (param.kind === 'tools') return printTools(ctx, block, param.tools) if (holdsSecret(sb, param.value)) { + // A value creation minted (a webhook token) stays out of the file, but source never wrote it. + if (sb && mintsFreshValue(sb)) return ctx.values.call('stored', []) return storedSecret(ctx, block, sb?.id ?? id, sb?.password === true) } if ( @@ -456,6 +459,7 @@ export function responseFormParams( * A field that prints `todo()` when it holds no stored value: one the builder's type requires * (`requiredForBuilder`) or requires in the variant the block's values select * (`requiredForValues`), or a required, always-shown field with no condition, default or not. + * Never a basic-only field of a block in advanced mode (`basicOnlyHidden`), which no value runs. */ function needsTodo( block: CanonicalBlock, @@ -465,6 +469,7 @@ function needsTodo( pinned: Readonly>, values: Readonly> ): boolean { + if (basicOnlyHidden(sb, block.advancedMode)) return false if (requiredForBuilder(declarations, pinned)) return true if (requiredForValues(declared, declarations, values)) return true if (sb.required !== true || sb.condition !== undefined || sb.hidden || sb.readOnly) return false diff --git a/packages/workflow-code/src/print/printer.ts b/packages/workflow-code/src/print/printer.ts index 8803f62262d..56a0d22b606 100644 --- a/packages/workflow-code/src/print/printer.ts +++ b/packages/workflow-code/src/print/printer.ts @@ -16,15 +16,17 @@ import { SUBFLOW_DATA_KEYS, SUPERSEDED_CONTAINER_PARAMS } from '../canonicalize/ import { builderPins } from '../catalog/surface' import { catalogBlock } from '../catalog/view' import type { PrintDiagnosticCode } from '../diagnostics/codes' +import { diagnostic } from '../diagnostics/factory' import type { Diagnostic } from '../diagnostics/frame' import { branchesAtTopLevel, printsAsElseTrue } from '../forms/condition' import { readResponseForm } from '../forms/response' import { printedConfig } from '../forms/subflow' import { SOURCE_ENTRY_FILE } from '../limits' import { isJson, type SourceHintBlock, type SourceHints } from '../lock' -import type { AnchorKey, BlockKey, CanonicalBlock, Json } from '../model' +import type { AnchorKey, BlockKey, CanonicalBlock, CanonicalVariable, Json } from '../model' import { getOwn, pushTo, setOwn } from '../records' import { type BlockMetaKey, GENERIC_BUILDER, SDK_MODULE, type TemplateTag } from '../sdk' +import { holdsDetectedSecret, variableSecretFinding } from '../secrets' import { type AttachedComments, anchors, withComments } from './comments' import type { PrintContext } from './context' import { createPrintContext, type PrintInput } from './context' @@ -311,6 +313,17 @@ function scopeStatements(ctx: PrintContext, scope: BlockKey | null): StatementLi return { docs, depth } } +/** + * A variable's value, or `stored()` with `W_LITERAL_SECRET` when it holds a detected credential, + * so `source get` never writes the key into a file; compile reads it back from the stored variable. + */ +function printVariableValue(ctx: PrintContext, variable: CanonicalVariable): Expr { + if (!holdsDetectedSecret(variable.value)) return ctx.values.json(variable.value) + const { message, hint } = variableSecretFinding(variable.key) + ctx.diagnostics.push(diagnostic('W_LITERAL_SECRET', message, { hint })) + return ctx.values.call('stored', []) +} + function printSource(ctx: PrintContext): PrintResult { orderDeclarations(ctx) const body = scopeStatements(ctx, null) @@ -331,7 +344,7 @@ function printSource(ctx: PrintContext): PrintResult { fields.push({ key: 'name', value: ctx.values.string(variable.name) }) } fields.push({ key: 'type', value: ctx.values.string(variable.type) }) - fields.push({ key: 'value', value: ctx.values.json(variable.value) }) + fields.push({ key: 'value', value: printVariableValue(ctx, variable) }) const attached = ctx.comments.take(anchors.variable(variable.key)) return { key: printKey(variable.key), value: objectExpr(fields), ...attached } }) diff --git a/packages/workflow-code/src/secrets.ts b/packages/workflow-code/src/secrets.ts index d29a1114090..0bf8aa73a51 100644 --- a/packages/workflow-code/src/secrets.ts +++ b/packages/workflow-code/src/secrets.ts @@ -235,3 +235,14 @@ export function literalSecretFinding( hint: 'Store the credential as a workspace or personal env variable and interpolate env.NAME into the value in a t template, so the key never sits in the workflow.', } } + +/** + * The message and hint of `W_LITERAL_SECRET` for workflow variable `name` holding a detected + * credential: get prints its value as `stored()`, which compile resolves from the stored variable. + */ +export function variableSecretFinding(name: string): { message: string; hint: string } { + return { + message: `Variable ${name} holds what looks like a literal credential; get prints its value as stored() so it never lands in a file.`, + hint: 'Store the credential as a workspace or personal env variable and read env.NAME in the blocks that use it, so the key never sits in the workflow.', + } +} diff --git a/packages/workflow-sdk/src/codegen/core-text.generated.ts b/packages/workflow-sdk/src/codegen/core-text.generated.ts index 3a52cbec8fd..0a40df3fc47 100644 --- a/packages/workflow-sdk/src/codegen/core-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/core-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from src/core.d.ts; do not edit. /** The text of `core.d.ts`, the workflow SDK authoring declarations. */ -export const CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from \u0027@sim/workflow-sdk\u0027\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref; readonly length: Ref }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to ``.\n * Paths map exactly: `.seg`, `[\u0027seg\u0027]` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref = { readonly [REF]: T } & RefPaths\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue = [Extract] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo = ({ readonly [REF]: RefValue } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value = T | RefTo | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/**\n * JavaScript code (condition expressions, inline function code), kept exactly as written: like\n * `String.raw`, `` js`/\\s+/` `` is `/\\s+/`. Only `` \\` `` and `\\${` are escapes, for a backtick\n * and a literal `${`. So are `py`, `sh`, `json` and `md`; `t` text reads like a JS string.\n */\nexport declare const js: typeof t\n/** Python code, kept exactly as written (see {@link js}). */\nexport declare const py: typeof t\n/** Shell code, kept exactly as written (see {@link js}). */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value\u0027s type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref(\u0027Classify.content\u0027)`. */\nexport declare function ref(path: string): Ref\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field. 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 or a value that looks like a credential. Valid only\n * on a param of a block the stored workflow already has (same name and type) and holds a value\n * for, or as the `value` of a variable the stored workflow declares; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map\u0027s\n * values describe the resource: a table\u0027s row type, a credential\u0027s provider, a workflow\u0027s inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n\ntype KeyOf = keyof M extends never ? string : Extract\n\nexport type TableKey = KeyOf\nexport type KnowledgeBaseKey = KeyOf\nexport type CredentialKey = KeyOf\nexport type WorkflowKey = KeyOf\nexport type SkillKey = KeyOf\nexport type CustomToolKey = KeyOf\nexport type McpServerKey = KeyOf\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server\u0027s last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource\u0027s internal id. */\nexport interface ResourceRef {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential(\u0027support-slack\u0027)`. */\nexport type CredentialRef = ResourceRef<\u0027credential\u0027, Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential\u0027s provider; any key until it exists.\n */\nexport type CredentialKeyFor = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract]\nexport declare function credential(key: K): CredentialRef\n\n/**\n * The other form a credential field takes beside `credential(\u0027key\u0027)`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field\u0027s advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw(\u0027…\u0027)`.\n */\nexport type CredentialIdValue = RefTo | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow {\n id: string\n data: TableColumns\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column\u0027s type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns]-?: Exclude, null> } & {\n [C in Exclude>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column\u0027s type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table(\u0027leads\u0027)`. Table block operations live on `table.*`. */\nexport type TableRef = ResourceRef<\u0027table\u0027, Key>\nexport declare function table(key: K): TableRef\n\n/** A knowledge base: `knowledgeBase(\u0027docs\u0027)`. */\nexport type KnowledgeBaseRef = ResourceRef<\u0027knowledge-base\u0027, Key>\nexport declare function knowledgeBase(key: K): KnowledgeBaseRef\n\n/** A workspace skill: `skill(\u0027triage\u0027)`. */\nexport type SkillRef = ResourceRef<\u0027skill\u0027, Key>\nexport declare function skill(key: K): SkillRef\n\n/** A workspace folder: `folder(\u0027reports\u0027)`. */\nexport type FolderRef = ResourceRef<\u0027file-folder\u0027>\nexport declare function folder(key: string): FolderRef\n\n/** A workspace file: `file(\u0027contracts/acme.pdf\u0027)`. File block operations live on `file.*`. */\nexport type FileRef = ResourceRef<\u0027file\u0027>\nexport declare function file(path: string): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it: one uploaded in place, or a workspace\n * file chosen by `key` (written `file(\u0027path\u0027)` when the workspace resolves it).\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string | FileRef\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent\u0027s `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: \u0027auto\u0027 | \u0027force\u0027 | \u0027none\u0027\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool\u0027s params, which pick the member the agent reads. */\n modes?: Record\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool(\u0027lookup-order\u0027)`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick\n\n/** An MCP tool\u0027s arguments and the editor\u0027s snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record\n /**\n * What the editor saved about the server and the tool\u0027s input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp(\u0027linear\u0027)`. */\nexport interface McpServerRef extends ResourceRef<\u0027mcp-server\u0027, Key> {\n /** One of the server\u0027s tools, as an agent tool: `mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027)`. */\n tool(name: McpToolName, options?: McpToolOpts): Tool\n}\nexport declare function mcp(key: K): McpServerRef\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row\u0027s display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block\u0027s inputs, the\n * agent\u0027s legacy prompt fields, a container\u0027s stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record\n /**\n * A loop or parallel\u0027s `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record\n}\n\n/** A block\u0027s retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node\u0027s default port to each target. Returns the target, or a group of them. */\n to(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node\u0027s error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * What a block outputs when it fails and an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`): the failure message `error` on every block, plus the error outputs `E` its catalog\n * entry declares (a Function\u0027s `errorMessage`, the thrown message without its line and code). A\n * check refuses each on a block without an error edge, which fails the run instead. An output the\n * block declares under the same name keeps its declared type.\n */\ntype ErrorOutputs = {\n readonly [K in \u0027error\u0027 | E as [O] extends [Record] ? never : K]: Ref\n}\n\n/** A block: a node whose outputs can be referenced, and its error outputs after an `onError` edge. */\nexport type Block = Node & Ref & ErrorOutputs\n\n/** The named ports of a condition or router. */\nexport type Branches = { readonly [P in K]: Node }\n\n/** Trigger builders (`trigger.start`, `trigger.gmail.poller`, ...), generated from the catalog. */\nexport declare namespace trigger {}\n\n/** Builders for hidden legacy block versions (`legacy.slack.send`), generated from the catalog. */\nexport declare namespace legacy {}\n\n/** A raw edge from a handle the SDK has no name for (a legacy or unknown port). */\nexport declare function edge(from: Node, handle: string, to: Target): void\n\n/** Any stored block type without a builder (legacy, unknown or custom), with untyped outputs. */\nexport declare function block(\n type: string,\n name: string,\n params: Record,\n meta?: BlockMeta\n): Block\n\n// Workflow and variables\n\nexport type VariableType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027plain\u0027\n\n/** A workflow variable declared in `workflow(name, { variables })`: its type and initial value. */\nexport interface VariableDeclaration {\n /**\n * The display name, written only when it differs from the key. It must normalize to the key\n * (lowercased, spaces and dots removed), as `\u0027Total Count\u0027` does to `totalcount`.\n */\n name?: string\n type: VariableType\n value: Json\n}\n\n/** The variables a workflow declares, by name. */\nexport type VariableDeclarations = Record\n\ndeclare const VAR: unique symbol\n\n/** A workflow variable, compiled to ``. */\nexport interface VarRef {\n readonly [VAR]: string\n}\n\ntype VariableValue = T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027string\u0027 | \u0027plain\u0027\n ? string\n : Json\n\n/** `vars` in the workflow body: one typed reference per declared variable. */\nexport type VarRefs = {\n readonly [K in keyof V]: VarRef & Ref>\n}\n\n/**\n * Workflow variables by name, untyped. Prefer the `vars` the `workflow()` body receives, which is\n * typed from the declared variables.\n */\nexport declare const vars: { readonly [name: string]: VarRef & Ref }\n\ndeclare const WORKFLOW_DEF: unique symbol\n\n/** The default export of a workflow file. */\nexport interface WorkflowDef {\n readonly [WORKFLOW_DEF]: true\n}\n\n/** A child workflow by key, for `runWorkflow` or as an agent tool. */\nexport interface WorkflowRef extends ResourceRef<\u0027workflow\u0027, Key> {\n /**\n * The workflow as an agent tool, as the editor\u0027s tool picker adds it:\n * `childWorkflow(\u0027enrich-lead\u0027).asTool()`. A tool with fixed inputs is written `raw(tool)`.\n */\n asTool(options?: ToolUsage): Tool\n}\n\n/**\n * Declares a workflow. The body wires blocks; it never runs. With no description or variables the\n * options may be left out: `workflow(\u0027Name\u0027, () => { ... })`.\n */\nexport declare function workflow>(\n name: string,\n options: { description?: string; variables?: V },\n body: (scope: { vars: VarRefs }) => void\n): WorkflowDef\nexport declare function workflow(\n name: string,\n body: (scope: { vars: VarRefs> }) => void\n): WorkflowDef\n/** A child workflow by key: `childWorkflow(\u0027enrich-lead\u0027)`. */\nexport declare function childWorkflow(key: K): WorkflowRef\n\n// Containers\n\ntype ItemOf = C extends { readonly [REF]: readonly (infer E)[] }\n ? E\n : C extends readonly (infer E)[]\n ? E\n : Json\n\n/** Inside a loop or parallel body. As a node it is the container\u0027s start port: `p.to(first)`. */\nexport interface SubflowScope extends Node {\n readonly index: Ref\n readonly currentItem: Ref\n readonly items: Ref\n}\n\n/**\n * A container\u0027s outputs, plus its iteration fields by name (`outer.index`), which a block inside\n * the container reads (in a nested container too: an outer loop\u0027s index or item). Outside the\n * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there.\n */\nexport interface SubflowOutput {\n results: Json[]\n index: number\n currentItem: Json\n items: Json[]\n}\n\n/** A loop or parallel container. Its `.to()` wires the port taken after it finishes. */\nexport type Container = Block\n\ntype Collection = AnyRef | Template | Json[] | string\n\n/**\n * A loop container: `forEach` over a list, `for` a count, `while` or `doWhile` a condition. The\n * body callback declares the blocks each iteration runs and wires the first from the scope\n * (`p.to(first)`), which reads the iteration as `p.currentItem` and `p.index` (a code file:\n * `$ref.loop.currentItem`). After it, `each.results` lists every iteration\u0027s output, and\n * `each.to(next)` wires what runs once all finish.\n * @example const each = loop.forEach(\u0027Each Order\u0027, { collection: orders.rows }, (p) => { const line = fn(\u0027Line\u0027, { code: js`return ${p.currentItem.data.id}` }); p.to(line) })\n */\nexport declare const loop: {\n for(\n name: string,\n params: { count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n forEach(\n name: string,\n params: { collection: C },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n while(\n name: string,\n params: { condition: Template | string },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n doWhile(\n name: string,\n params: { condition?: Template | string; count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n}\n\nexport declare const parallel: {\n /** A parallel with no stored type, which the loader runs as `count`. */\n (\n name: string,\n params: { count?: number; collection?: Collection; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n count(\n name: string,\n params: { count: number; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n collection(\n name: string,\n params: { collection: C; batchSize?: number },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n}\n\n// Blocks with a source form of their own\n\n/**\n * Params and outputs of the blocks below, generated from the catalog. Each entry is\n * `{ params; output }`, with `errorOutputs` when the block declares any; without generated types\n * the params are loose.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface SpecialBuilderTypes {}\n\ntype SpecialParams = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { params: infer P }\n ? P\n : never\n : Record\n\ntype SpecialOutput = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { output: infer O }\n ? O\n : never\n : Json\n\n/** The error outputs a special builder\u0027s block declares; a builder whose block has any passes them. */\ntype SpecialErrorOutputs = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { errorOutputs: infer E extends string }\n ? E\n : never\n : never\n\n/** A condition expression, or `true` for the `else` branch. */\nexport type BranchExpression = Template | string | true\n\ndeclare const ONLY_ELSE: unique symbol\n\n/** What a branch other than `else` written as `true` must be, which no value is: the error names it. */\ninterface OnlyElseMayBeTrue {\n readonly [ONLY_ELSE]: true\n}\n\n/**\n * A condition\u0027s branches: every key holds an expression, and only `else` may be `true`. Another\n * branch written as `true` is checked against {@link OnlyElseMayBeTrue}, so the error names that\n * branch alone.\n */\ntype ConditionBranches = {\n [K in keyof B]: K extends \u0027else\u0027\n ? BranchExpression\n : B[K] extends true\n ? OnlyElseMayBeTrue\n : Template | string\n}\n\n/**\n * Keys of a condition written with no rows (`condition(\u0027Name\u0027, {})`, the source form of rows\n * that were never persisted): the implicit `if` and `else` ports stay addressable.\n */\ntype ConditionKeys = keyof B extends never ? \u0027if\u0027 | \u0027else\u0027 : Extract\ntype RouterKeys = keyof R extends never ? \u0027route0\u0027 : Extract\n\n/**\n * A condition: named branches tested in order, top to bottom; the first whose expression holds\n * runs, and `else` (last, written `true`) runs when none does. Wire each as `x..to(block)`.\n * @example condition(\u0027Route\u0027, { big: js`${order.total} >= 500`, small: js`${order.total} < 50`, else: true })\n */\nexport declare function condition>(\n name: string,\n branches: B & ConditionBranches,\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A router: named routes described for the model. */\nexport declare function router>(\n name: string,\n params: SpecialParams<\u0027router\u0027> & { routes: R },\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A function block. `code` is inline (`` js`...` ``) or a code file (`codeFile(\u0027./functions/x.js\u0027)`). */\nexport declare function fn(\n name: string,\n params: SpecialParams<\u0027fn\u0027> & { code: Template | CodeFileRef | string },\n meta?: BlockMeta\n): Block, SpecialErrorOutputs<\u0027fn\u0027>>\n\n/**\n * The inputs of a child workflow by key, each checked against the input its start block\n * declares when `workspace.d.ts` knows the workflow; loose JSON otherwise.\n */\nexport type WorkflowInputMapping = K extends keyof WorkspaceWorkflows\n ? WorkspaceWorkflows[K] extends { inputs: infer I }\n ? { [N in keyof I]?: FieldValue }\n : InputMapping\n : InputMapping\n\n/**\n * Runs a child workflow. A `childWorkflow(\u0027key\u0027)` checks `inputMapping` against its inputs. Its\n * `result` is the child\u0027s output: its first response block\u0027s `{ data, status, headers }` (a body\n * field is `result.data.field`), else the output of the last block it ran.\n */\nexport declare function runWorkflow(\n name: string,\n params: Omit, \u0027workflowId\u0027 | \u0027inputMapping\u0027> & {\n workflowId: WorkflowRef | Exclude[\u0027workflowId\u0027], WorkflowRef>\n inputMapping?: WorkflowInputMapping\n },\n meta?: BlockMeta\n): Block>\n\n/**\n * Pauses for a person; the form in `inputFormat` types `submission`. A resumed block also holds\n * each form field at its top level (the runtime copies the submission up, over any output of the\n * same name), so `approval.approved` and `approval.submission.approved` both read it.\n */\nexport declare function human>(\n name: string,\n params: SpecialParams<\u0027human\u0027> & { inputFormat?: F },\n meta?: BlockMeta\n): Block<\n Omit, \u0027submission\u0027 | keyof F> & {\n submission: InputFieldsOutput\n } & InputFieldsOutput\n>\n\n/**\n * A response\u0027s body, status and headers: the editor\u0027s JSON mode, `body` standing for\n * `{ dataMode: \u0027json\u0027, data }`. An object or array `body` is JSON whose references keep their\n * types; a template or reference is the body text as written.\n */\nexport interface ResponseBody {\n body: JsonWithRefs\n /** HTTP status; 200 when omitted. A template or reference must produce a number. */\n status?: number | RefTo | Template | EnvRef\n /** Response headers by name. */\n headers?: Record>\n}\n\n/**\n * Ends the workflow with an API response: `response(\u0027Reply\u0027, { body: { ok: true }, status: 201 })`\n * (`body` is short for `dataMode: \u0027json\u0027` with `data`), or the block\u0027s own params (`dataMode`,\n * `builderData`, ...) when the body is built field by field.\n */\nexport declare function response(\n name: string,\n params: ResponseBody,\n meta?: BlockMeta\n): Block>\nexport declare function response(\n name: string,\n params: SpecialParams<\u0027response\u0027>,\n meta?: BlockMeta\n): Block>\n\n/** Assigns workflow variables. */\nexport declare function setVariables(\n name: string,\n params: SpecialParams<\u0027setVariables\u0027>,\n meta?: BlockMeta\n): Block>\n\ndeclare const ANNOTATION: unique symbol\n\n/** A canvas note: no edges, no outputs. */\nexport interface Annotation {\n readonly [ANNOTATION]: true\n}\nexport declare function note(\n name: string,\n params: SpecialParams<\u0027note\u0027>,\n meta?: BlockMeta\n): Annotation\n\n// Structured param shapes\n\n/** Type names an input-format field may declare. */\nexport type InputFieldType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027file[]\u0027\n\n/** A structured input field: its type plus a default value, description or required flag. */\nexport interface InputFieldSpec {\n type: InputFieldType\n value?: JsonWithRefs\n description?: string\n required?: boolean\n}\n\n/** `input-format` fields by name: `{ subject: \u0027string\u0027, amount: { type: \u0027number\u0027, value: 0 } }`. */\nexport type InputFields = Record\n\ntype InputFieldValue = T extends \u0027string\u0027\n ? string\n : T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027array\u0027\n ? Json[]\n : T extends \u0027file[]\u0027\n ? SimFile[]\n : Json\n\n/** The outputs an `input-format` declares. */\nexport type InputFieldsOutput = {\n [K in keyof F]: F[K] extends { type: infer T } ? InputFieldValue : InputFieldValue\n}\n\n/**\n * One `response-format` field as the editor\u0027s builder stores it. An `object` or `array` field\u0027s\n * `value` may hold nested fields. A response is usually written with `body` instead.\n */\nexport interface ResponseField {\n id?: string\n name: string\n type: string\n value?: JsonWithRefs\n collapsed?: boolean\n}\n\n/** `response-format` fields: `[{ name: \u0027ok\u0027, type: \u0027boolean\u0027, value: true }]`. */\nexport type ResponseFields = ResponseField[]\n\n/** An agent message. */\nexport interface Message {\n role: \u0027system\u0027 | \u0027user\u0027 | \u0027assistant\u0027\n content: Value\n}\n\n/** One `variables-input` assignment, with any other stored keys kept. */\nexport interface VariableAssignment {\n variableId: VarRef\n value?: JsonWithRefs\n [key: string]: JsonWithRefs | VarRef | undefined\n}\n\n/** Child workflow inputs by name (`input-mapping`, `workflow-input-mapper`). */\nexport type InputMapping = Record\n\n/** An operator a table filter condition or builder rule can use. */\nexport type FilterOperator = LiteralUnion<\n | \u0027eq\u0027\n | \u0027ne\u0027\n | \u0027gt\u0027\n | \u0027gte\u0027\n | \u0027lt\u0027\n | \u0027lte\u0027\n | \u0027in\u0027\n | \u0027nin\u0027\n | \u0027like\u0027\n | \u0027ilike\u0027\n | \u0027nlike\u0027\n | \u0027nilike\u0027\n | \u0027contains\u0027\n | \u0027ncontains\u0027\n | \u0027startsWith\u0027\n | \u0027endsWith\u0027\n | \u0027isNull\u0027\n | \u0027isNotNull\u0027\n | \u0027isEmpty\u0027\n | \u0027isNotEmpty\u0027\n>\n\n/** One row of the editor\u0027s filter builder, as it stores it. */\nexport interface FilterRule {\n id?: string\n /** How this row joins the rows before it; `and` when omitted. */\n logicalOperator?: \u0027and\u0027 | \u0027or\u0027\n column: string\n operator: FilterOperator\n value: Value\n collapsed?: boolean\n}\n\n/** A filter-builder value: the editor\u0027s rows, `[{ column: \u0027status\u0027, operator: \u0027eq\u0027, value: \u0027new\u0027 }]`. */\nexport type Filter = FilterRule[]\n\n/** One table filter condition: `{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027new\u0027 }`. */\nexport interface TableCondition {\n field: string\n op: FilterOperator\n value?: JsonWithRefs\n}\n\n/**\n * A table predicate: a condition, or an `all` (and) / `any` (or) group of predicates. The\n * `{ status: { $eq: \u0027new\u0027 } }` operator-object grammar is not one: the runtime refuses it.\n */\nexport type TablePredicate = TableCondition | { all: TablePredicate[] } | { any: TablePredicate[] }\n\n/** A table sort by column: `{ createdAt: \u0027desc\u0027 }`. */\nexport type Sort =\n | Record\n | Array<{ column: string; direction: \u0027asc\u0027 | \u0027desc\u0027 }>\n\n/** One knowledge tag filter. */\nexport interface TagFilter {\n tagName: string\n tagValue: Value\n [key: string]: JsonWithRefs\n}\n\n/** One document tag. */\nexport interface DocumentTag {\n tagName: string\n value: Value\n [key: string]: JsonWithRefs\n}\n\n/** One `eval-input` metric. */\nexport interface EvalMetric {\n name: string\n description?: string\n range?: { min: number; max: number }\n [key: string]: JsonWithRefs | undefined\n}\n\n/** One `model-fallback-list` entry. */\nexport interface ModelFallback {\n model: LiteralUnion\n [key: string]: JsonWithRefs\n}\n\n/**\n * Model ids, generated into `models.d.ts` (which adds one member per model). Kept apart from the\n * block files so a model-list change touches one file.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface ModelIds {}\nexport type Model = Extract\n\n/** A JSON Schema `responseFormat`, or `{ name, strict, schema }` around one. */\nexport type ResponseFormat = JsonWithRefs\n\ntype Depth = [never, 0, 1, 2, 3, 4]\n\ntype FromSchema = [D] extends [never]\n ? Json\n : S extends { enum: readonly (infer E)[] }\n ? E\n : S extends { type: \u0027object\u0027; properties: infer P }\n ? { [K in keyof P]: FromSchema }\n : S extends { type: \u0027array\u0027; items: infer I }\n ? FromSchema[]\n : S extends { type: \u0027string\u0027 }\n ? string\n : S extends { type: \u0027number\u0027 | \u0027integer\u0027 }\n ? number\n : S extends { type: \u0027boolean\u0027 }\n ? boolean\n : Json\n\n/**\n * The outputs a literal `responseFormat` adds, read from its JSON Schema with recursion capped at\n * depth 4. A template or reference adds untyped JSON.\n */\nexport type ResponseFormatOutput = [RF] extends [undefined]\n ? unknown\n : RF extends { schema: infer S }\n ? FromSchema\n : RF extends { type: \u0027object\u0027; properties: object }\n ? FromSchema\n : { [key: string]: Json }\n" diff --git a/packages/workflow-sdk/src/core.d.ts b/packages/workflow-sdk/src/core.d.ts index 32fa6a032ac..ab4495f948e 100644 --- a/packages/workflow-sdk/src/core.d.ts +++ b/packages/workflow-sdk/src/core.d.ts @@ -148,8 +148,9 @@ export declare function todo(): never /** * Keeps the value the stored workflow holds for this param, without showing it: the printer writes - * it for a secret pasted into a password field. Valid only on a param of a block the stored - * workflow already has (same name and type) and holds a value for; anything else is + * it for a secret pasted into a password field or a value that looks like a credential. Valid only + * on a param of a block the stored workflow already has (same name and type) and holds a value + * for, or as the `value` of a variable the stored workflow declares; anything else is * `E_STORED_VALUE_MISSING`. */ export declare function stored(): never