diff --git a/apps/docs/content/docs/workflows/code/coding-agents.mdx b/apps/docs/content/docs/workflows/code/coding-agents.mdx index e96084c2b55..eb2f7736d00 100644 --- a/apps/docs/content/docs/workflows/code/coding-agents.mdx +++ b/apps/docs/content/docs/workflows/code/coding-agents.mdx @@ -7,7 +7,7 @@ Claude Code, Cursor, Codex and other coding agents work from a directory that `g ## What get gives an agent -- A **primer**, which opens `.sim/AGENTS.md`. `get` prints a short summary instead (the files written, the guide, and the `editLoop` commands to run); `get --primer` also prints the primer (in JSON output, its `primer` field). It covers the edit loop, how block identity, references and renames work, failures and retries, test runs, deletes, deploy, exit codes, and the params of each builder the workflow already uses. +- A **primer**, which opens `.sim/AGENTS.md`. `get` prints a short summary instead (the files written, the guide, and the `editLoop` command to run); `get --primer` also prints the primer (in JSON output, its `primer` field). It covers the edit loop, how block identity, references and renames work, failures and retries, test runs, deletes, deploy, exit codes, and the params of each builder the workflow already uses. - **`.sim/AGENTS.md`**: the primer followed by a reference, by task. A workspace directory also gets `.sim/GUIDE-advanced.md`. - **`.sim/examples/`**: one correct example of each common block to copy from. - **`.sim/sdk/`**: the type declarations, with `.sim/sdk/INDEX.md` listing the builders. @@ -17,10 +17,14 @@ Point the agent at `.sim/AGENTS.md` before it edits. ## The loop 1. `sim workflows source get --dir ` writes the workflow and the guide. -2. Edit `workflow.ts`. -3. `sim workflows source check --dir ` compiles it offline. -4. `sim workflows source status --dir ` shows what changed and what to run next. -5. `sim workflows source apply --dir --dry-run`, then `--yes`, saves the draft. +2. Write every file the change needs. +3. Run one chained command, then fix whatever it reports in the next step: + + ```bash + sim workflows source check --dir && sim workflows source apply --dir --yes && sim workflows run --manual --input '{...}' + ``` + + A non-zero exit code stops the chain at the first failure. `apply` compiles the source and compares it with the saved draft again, so an agent can skip `--dry-run`. People and CI use `apply --dry-run` to review the plan, and `status` shows what changed and what to run next. Add `bunx -p typescript@7.0.2 tsc -p ` after `check` to catch type errors. For a whole workspace, use `sim workspaces source` with the same steps; see [Manage a workspace as code](/workflows/code/workspace). diff --git a/apps/docs/content/docs/workflows/code/directory.mdx b/apps/docs/content/docs/workflows/code/directory.mdx index 7b363e138f8..ae2aec5f011 100644 --- a/apps/docs/content/docs/workflows/code/directory.mdx +++ b/apps/docs/content/docs/workflows/code/directory.mdx @@ -49,7 +49,7 @@ workflows/support/workflow.ts a workflow directory deployments/support.ts how workflows/support is deployed ``` -A resource's key is its file or folder name, and a workflow names it by that key. What each kind's file holds: +A resource's key is its file or folder name, and a workflow names it by that key. Every `.ts` file starts with the line `// @sim-sdk 1`, a deployment included; the one-line forms below show only the call. What each kind's file holds: {/* workflow-code-docs:directory-kinds:begin — generated by `bun run generate:workflow-code-docs`; do not edit between markers */} diff --git a/apps/sim/lib/workspace-source/application/files.integration.ts b/apps/sim/lib/workspace-source/application/files.integration.ts index abc65f62d1f..7c6dc1da5f7 100644 --- a/apps/sim/lib/workspace-source/application/files.integration.ts +++ b/apps/sim/lib/workspace-source/application/files.integration.ts @@ -642,6 +642,8 @@ describe('workspace source files', () => { const refused = await refusal(apply(workspaceId, dropped, { base: read.base })) expect(codes(refused.diagnostics)).toEqual(['E_APPLY_DELETE_NOT_ALLOWED']) + expect(refused.diagnostics[0].message).toContain('missing from the directory is a delete') + expect(refused.diagnostics[0].message).toContain('--allow-delete') expect((await storedFiles(workspaceId)).map((file) => file.id)).toContain(id) const deleted = await apply(workspaceId, dropped, { base: read.base, allowDelete: true }) diff --git a/apps/sim/lib/workspace-source/application/findings.ts b/apps/sim/lib/workspace-source/application/findings.ts index 8b967624682..20fb7fd5b40 100644 --- a/apps/sim/lib/workspace-source/application/findings.ts +++ b/apps/sim/lib/workspace-source/application/findings.ts @@ -463,12 +463,12 @@ export function planUndeclared( kind, key, 'E_APPLY_DELETE_NOT_ALLOWED', - `${where(kind, key)} is no longer declared; deleting "${resource.name}" needs --allow-delete.`, + `${where(kind, key)} is no longer declared: a resource missing from the directory is a delete, and deleting "${resource.name}" needs --allow-delete.`, { hint: kind === 'deployment' ? 'Pass --allow-delete to delete it, or restore its file to keep it.' - : 'Pass --allow-delete to delete it, or restore its file to keep it. Run with --allow-delete --dry-run to see which workflows use it.', + : 'Pass --allow-delete to delete it, or restore its file or folder to keep it. Run with --allow-delete --dry-run to see which workflows use it.', } ) : kindFinding( diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index df7c34bfc03..dfad37b24fd 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -34,12 +34,14 @@ export const WORKFLOW_SOURCE_LOOP_HELP = ` The loop: ${loopRows([ ['sim workflows source get --dir ./wf', 'write workflow.ts, functions/* and .sim/'], - ['edit ./wf/workflow.ts', ''], + ['edit ./wf/workflow.ts', 'every file first, then the one command below'], ['sim workflows source check --dir ./wf', 'offline: each error as file:line:column'], - [typecheckCommand('./wf'), 'type-check the edit'], - ['sim workflows source apply --dir ./wf --dry-run', 'the plan; nothing is written'], - ['sim workflows source apply --dir ./wf --yes', 'save the draft'], + [' && sim workflows source apply --dir ./wf --yes', 'save the draft (it re-checks)'], + [' && sim workflows run --manual', 'test the saved draft'], ])} +Run those three as one chained command: a non-zero exit stops it at the first failure, and the next +step fixes what it reported. For review, \`apply --dry-run\` prints the plan and writes nothing; +\`${typecheckCommand('./wf')}\` adds type errors. A new workflow: \`sim workflows source create --dir ./new --workspace \` writes a starter that records its workspace; edit and check it, then \`create --dir ./new --yes\` creates the workflow there, and the loop above goes on from there. @@ -56,12 +58,13 @@ export const WORKSPACE_SOURCE_LOOP_HELP = ` The loop: ${loopRows([ ['sim workspaces source get --dir ./ws', 'write tables/, workflows//, … and .sim/'], - ['edit the files', 'a new workflow: workflows//workflow.ts'], + ['edit the files', 'every file first; a new workflow: workflows//workflow.ts'], ['sim workspaces source check --dir ./ws', 'offline: each error as file:line:column'], - [typecheckCommand('./ws'), 'type-check the edit'], - ['sim workspaces source apply --dir ./ws --dry-run', 'the plan; nothing is written'], - ['sim workspaces source apply --dir ./ws --yes', 'write it to the workspace'], + [' && sim workspaces source apply --dir ./ws --yes', 'write it to the workspace (it re-checks)'], ])} +Run those two as one chained command: a non-zero exit stops it at the first failure, and the next +step fixes what it reported. For review, \`apply --dry-run\` prints the plan and writes nothing; +\`${typecheckCommand('./ws')}\` adds type errors. Promote dev to prod: \`sim workspaces source apply --dir ./ws --to --dry-run\`, then --yes. ${WORKSPACE_LINE} diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 347b1420201..759c1782421 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -10,6 +10,7 @@ import { builderSnippet, describeBuilder, referencedBuilders, + SDK_MAJOR, typecheckCommand, } from '@sim/workflow-sdk/codegen' import { @@ -40,21 +41,21 @@ const PARAMS_COMMAND = 'sim workflows source params' /** The rules every source directory shares, after the kind's own edit loop. */ function sharedRules(group: string, extraRenames = ''): string { - return `- **Identity**: a block is its entry in \`${SOURCE_LOCK_FILE}\`, which binds it by its const name or its display name. Change the display name (first argument) freely: references through the const follow it, and the apply rewrites every \`$ref.\` and \`\` for you (don't hand-edit). Renaming the const too keeps it when settings, neighbours or references still tie it to the old block; otherwise the apply refuses a delete (\`E_APPLY_BLOCK_DELETE\`). Safest: keep the const. + return `- **Identity**: a block is its entry in \`${SOURCE_LOCK_FILE}\`, which binds it by its const name or its display name. Change the display name (first argument) freely: references through the const follow it, and the apply rewrites every \`$ref.\` and \`\` for you. Renaming the const too keeps it when settings, neighbours or references still tie it to the old block; otherwise the apply refuses a delete (\`E_APPLY_BLOCK_DELETE\`). - **References**: in \`${SOURCE_ENTRY_FILE}\` read an output as \`x.content\`, a loop or parallel item as \`p.currentItem\` (\`p.index\`), text as \`\` t\`…\` \`\`, env as \`env.NAME\`. In a function file (\`codeFile('./functions/x.js')\`) read an output as \`$ref..\`, the key: the display name lowercased, whitespace and dots removed ("Triage Agent" → \`$ref.triageagent.content\`); in a loop body \`$ref.loop.currentItem\` / \`$ref.loop.index\`, in a parallel \`$ref.parallel.currentItem\` / \`$ref.parallel.index\`; env as \`$env.NAME\`. In \`.py\`/\`.sh\` files write \`\` and \`{{NAME}}\`, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`), after it its \`.results\`. A \`$ref\` naming no block is an error in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`). - **Renames**: one variable per apply (two at once read as a delete and an add).${extraRenames} - **Look up a builder**: \`${PARAMS_COMMAND} \` (a namespace like \`gmail\` lists them). - **Credentials**: \`sim credentials connect --name ""\`, give the owner its link, then \`credential('')\` (\`sim workflows source resources\`). - **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, reading the message as \`x.error\` (a Function's \`x.errorMessage\` drops the line and code: reply with it). Retry is block meta (third argument): \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })\`. A reference to a block that did not run is \`null\` (a whole value, function code, a condition) or \`''\` in text. Branches may rejoin; only branches that end separately each need a \`response\`. -- **Run and debug**: \`sim workflows run --manual --input '{…}'\` runs the saved draft (without it, the deployed version). Runs write real data (rows, emails): use test resources. With \`--dir \`, a failed run names the failing file and line; then \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list \`. -- **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (\`${group} get --dir \`, redo the edit there), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed. Every code: \`${SOURCE_AGENTS_FILE}\`.` +- **Run and debug**: \`--manual\` runs the saved draft, without it the deployed version. Runs write real data (rows, emails): use test resources. With \`--dir \`, a failed run names the failing file and line; then \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list
\`. +- **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (\`${group} get --dir \`, redo the edit there), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed.` } const WORKFLOW_PRIMER = `# Sim workflow source: primer \`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and nothing in it runs. Commands read the workflow id from \`${SOURCE_BASE_FILE}\`; run them from this directory. -**Edit loop**: edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`) → \`sim workflows source check --dir .\` (offline; it also adds new blocks to \`tsconfig.json\`) → \`${typecheckCommand()}\` → \`sim workflows source apply --dir . --dry-run\` → \`--yes\`. Rerun each step until it exits 0. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit. +**Edit loop**: write every file, then run one chained command and fix what it reports next: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --manual --input '{…}'\`. A non-zero exit stops the chain. Apply re-checks the source and its base, so \`apply --dry-run\` is only the review for people and CI. Add \`${typecheckCommand()}\` after \`check\` for type errors. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit. - **Deletes**: removing a block or a variable needs \`apply --allow-delete\` (\`E_APPLY_BLOCK_DELETE\` / \`E_APPLY_VARIABLE_DELETE\`). - **Deploy**: apply saves a draft; \`apply --deploy\` also deploys it, or \`sim workflows deploy \` publishes the saved draft later. @@ -67,13 +68,12 @@ const WORKSPACE_RENAMES = const WORKSPACE_PRIMER = `# Sim workspace source: primer -This directory is a Sim workspace as files (\`tables/\`, \`workflows//workflow.ts\`, …); nothing in it runs. Commands read the workspace id from \`${SOURCE_BASE_FILE}\`; run them from this directory. +This directory is a Sim workspace as files (\`tables/\`, \`workflows//workflow.ts\`, …); nothing in it runs. Commands read the workspace id from \`${SOURCE_BASE_FILE}\`; run them from this directory. Every \`.ts\` file, \`deployments/\` too, starts with \`// @sim-sdk ${SDK_MAJOR}\`. -**Edit loop**: edit the files → \`sim workspaces source check --dir .\` (offline; refreshes \`workspace.d.ts\` and \`tsconfig.json\`) → \`${typecheckCommand()}\` → \`sim workspaces source apply --dir . --dry-run\` → \`--yes\`. Rerun each step until it exits 0. Apply rewrites the directory: read a file again before the next edit. +**Edit loop**: write every file, then run one chained command and fix what it reports next: \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\` (add a \`sim workflows run\` to test). A non-zero exit stops the chain. Apply re-checks the source and its base, so \`apply --dry-run\` is only the review for people and CI. Add \`${typecheckCommand()}\` after \`check\` for type errors. Apply rewrites the directory: read a file again before the next edit. -- **Deletes**: a removed file, table column, workflow block or variable is deleted only with \`apply --allow-delete\` and cannot be undone. A kind is managed only when its folder exists. +- **Deletes**: a file or folder missing from a kind's folder, or a removed table column, workflow block or variable, is a delete: refused without \`apply --allow-delete\`, and it cannot be undone. - **Deploy**: \`deployments/.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys that workflow on apply; without one, apply never deploys. -- **Promote** (dev → prod): \`sim workspaces source apply --dir . --to --dry-run\`, then \`--yes\`. - **Exit ${SOURCE_HELD_EXIT_CODE}**: written in part; changes using an unset secret or unbound credential were held back: set it, apply again. ${sharedRules('sim workspaces source', WORKSPACE_RENAMES)} ` @@ -96,7 +96,7 @@ export function agentsPointer(kind: PrimerKind): string { ${kind === 'workflow' ? '`workflow.ts` is a Sim workflow as TypeScript that Sim compiles' : 'This directory is a Sim workspace as files that Sim applies'}; nothing in it runs. Read \`${SOURCE_AGENTS_FILE}\` before editing: the rules, the edit loop and every exit code. -Loop: edit, then \`${group} check --dir .\`, \`${typecheckCommand()}\`, \`${group} apply --dir . --dry-run\`, \`--yes\`. +Loop: write every file, then one chained command: \`${group} check --dir . && ${group} apply --dir . --yes\`; fix what it reports next. Exit codes: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (get a fresh copy and redo the edit), ${SOURCE_DRIFT_EXIT_CODE} \`status\`: the server changed. ` } diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index e591bb6aab5..6c1972785c6 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -27,7 +27,6 @@ import { SDK_MAJOR, SDK_MODELS_FILE, sdkIndexHeader, - typecheckCommand, type WorkspaceManifest, } from '@sim/workflow-sdk/codegen' import type { Command } from 'commander' @@ -601,17 +600,15 @@ export function primerOption(command: Command): void { } /** - * The commands of a directory's edit loop, in order, for a get's result: what the primer's loop - * says, runnable from anywhere because each names the directory. + * The edit loop of a directory for a get's result, as the one chained command the primer + * recommends: runnable from anywhere because it names the directory. Apply re-checks everything + * on the server, so a dry run is not a step of it. Still a list, so the JSON field keeps the shape + * earlier results had. */ export function editLoop(kind: PrimerKind, dir: string): string[] { const group = kind === 'workflow' ? 'sim workflows source' : 'sim workspaces source' const at = shellWord(dir) - return [ - `${group} check --dir ${at}`, - typecheckCommand(at), - `${group} apply --dir ${at} --dry-run`, - ] + return [`${group} check --dir ${at} && ${group} apply --dir ${at} --yes`] } /** What a directory's editable tree holds beside the printed source. */ diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index f724628b90c..ecb6f4d61e1 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -221,9 +221,11 @@ The primer above is enough to edit; read a section here when a step needs it. ## Edit loop in detail +Batch it: write every file first, then run steps 2 and 5 (and a test run) as one chained command, \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --manual --input '{…}'\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Steps 3, 4 and the dry run in step 5 are for a person, CI, or a change you want reviewed first. + 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`. 2. \`sim workflows source check --dir .\`: compiles offline with the server's compiler, in milliseconds. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block). It also adds the blocks the source now uses to \`tsconfig.json\`. -3. \`${typecheckCommand()}\`: about a second; catches what step 2 and the dry run do not (such as a reference to a start input the trigger does not declare). It runs the TypeScript release the declarations are built for (the directory has no \`package.json\`; plain \`bunx tsc\` would run whatever version it finds). \`tsconfig.json\` includes only the blocks the source used at the last check, get or apply: a builder from another block fails with \`has no exported member\` until you run step 2 (or use \`${typecheckCommand(TSCONFIG_FULL_FILE)}\`, every current block). The dry run is the authority: a printed line you did not edit that \`tsc\` flags and the dry run accepts is fine. +3. \`${typecheckCommand()}\` (chain it after step 2): about a second; catches what step 2 and the dry run do not (such as a reference to a start input the trigger does not declare). It runs the TypeScript release the declarations are built for (the directory has no \`package.json\`; plain \`bunx tsc\` would run whatever version it finds). \`tsconfig.json\` includes only the blocks the source used at the last check, get or apply: a builder from another block fails with \`has no exported member\` until you run step 2 (or use \`${typecheckCommand(TSCONFIG_FULL_FILE)}\`, every current block). The dry run is the authority: a printed line you did not edit that \`tsc\` flags and the dry run accepts is fine. 4. \`sim workflows source status --dir .\`: the files you changed (\`sim workflows source diff --dir .\` shows the edits), whether the workflow changed on the server since the get, and the command to run next (\`--offline\`: skip the server). Then \`sim workflows source apply --dir . --dry-run\` until it exits 0. 5. \`sim workflows source apply --dir . --yes\`: saves the draft, refusing errors, block deletions without \`--allow-delete\` and a stale directory, so it needs no separate dry run (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}). \`--deploy\` also deploys it; without it, a deployed workflow's next \`sim workflows deploy --expected-draft-fingerprint \` is printed, which deploys only the draft this apply saved. It then rewrites \`${SOURCE_ENTRY_FILE}\` in canonical form (order, quoting, defaults left out). 6. Exit ${SOURCE_STALE_EXIT_CODE} (\`SOURCE_STALE\`, HTTP 409, or \`E_APPLY_STALE\` on a dry run): the workflow changed and nothing was saved. Run \`sim workflows source get --dir \`, reapply your edit there, dry-run, apply. A get into this directory refuses to overwrite your unapplied edits unless you pass \`--force\`. Exit ${SOURCE_STALE_EXIT_CODE} right after an apply that ended without an answer (a timeout, a dropped connection) means the draft changed, by that apply or by someone else: get into a fresh directory and compare. Only when it holds your edit, run \`sim workflows source get --dir . --force\`; otherwise reapply your edit in the fresh directory. diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts index 91c0fe7a7bd..afabfff8220 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts @@ -196,9 +196,9 @@ describe('sim workflows source get --dir', () => { expect(printed).not.toHaveProperty('primer') expect(printed.guide).toBe('.sim/AGENTS.md') expect(printed.editLoop).toEqual([ - expect.stringMatching(/^sim workflows source check --dir /), - expect.stringMatching(/^bunx -p typescript@[\d.]+ tsc -p /), - expect.stringMatching(/^sim workflows source apply --dir .* --dry-run$/), + expect.stringMatching( + /^sim workflows source check --dir (\S+) && sim workflows source apply --dir \1 --yes$/ + ), ]) const agents = readFileSync(join(outDir, '.sim/AGENTS.md'), 'utf8') expect(agents).toContain('- `gmail.sendEmail` (Gmail: Send Email)') @@ -246,7 +246,7 @@ describe('sim workflows source get --dir', () => { const program = buildProgram() const named = [ ...`${sourcePrimer(kind)}${agentsPointer(kind)}`.matchAll(/`(sim [^`]+)`/g), - ].map((match) => match[1]) + ].flatMap((match) => match[1].split(' && ')) expect(named.length).toBeGreaterThan(0) for (const line of named) { let command: Command = program diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index 0f1c7b089d1..123e1c93d6c 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -10,6 +10,7 @@ import { compareStrings } from '@sim/utils/string' import type { WorkflowInput } from '@sim/workflow-code' import { SOURCE_CODE_DIR, SOURCE_ENTRY_FILE, SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { + SDK_MAJOR, SOURCE_COMPILER_OPTIONS, typecheckCommand, WORKSPACE_COOKBOOK, @@ -136,6 +137,8 @@ The primer above is enough to edit; read a section here when a step needs it. De A resource's key is its file or folder name (in \`${KIND_DIRS.secret}\` and \`${KIND_DIRS.credential}\`, the entry's name), and a workflow names it by that key. +Every \`.ts\` file below, a deployment included, starts with the line \`// @sim-sdk ${SDK_MAJOR}\` (without it: \`E_DECL_HEADER\`); a one-line form here shows only the call. + ${APPLY_ORDER.map((kind) => `- ${WORKSPACE_KIND_SPECS[kind].guide}`).join('\n')} One apply creates resources before the workflows that use them, so a workflow may name a key this directory declares before it exists. \`.sim/sdk/workspace.d.ts\` types the keys the server held at the last get and the ones this directory declares, with each workflow's inputs: \`sim workspaces source check\` (or \`sim workflows source check\` in a workflow folder) regenerates it from the files, so run it before \`tsc\` after adding a resource or a workflow input. The dry run is the authority. @@ -144,9 +147,11 @@ Secrets never appear in source: a workflow reads an environment variable as \`en ## Edit loop in detail +Batch it: write every file first, then run steps 2 and 5 (and any test run) as one chained command, \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\`, and fix what it reports in the next step. Each non-zero exit stops the chain. Steps 3 and 4, and the dry run, are for a person, CI, or a change you want reviewed first. + 1. Edit the files. 2. \`sim workspaces source check --dir .\`: compiles every workflow offline with the server's compiler, against what this directory declares: an unknown resource key (skills included) or table column, a child workflow's inputs, and an env name \`${KIND_DIRS.secret}\` lacks (a warning); and checks each \`${KIND_DIRS.table}/.rows.jsonl\` line against its table as the apply would. It fails (exit 1) on errors and on ${STRICT_FINDINGS_CLAUSE} in a block you added (\`--strict\`: in every block), regenerates \`.sim/sdk/workspace.d.ts\` and adds the blocks the workflows now use to \`tsconfig.json\`. In a workflow folder, \`sim workflows source check --dir .\` checks that one workflow the same way. Fix and rerun until it exits 0. -3. Run \`${typecheckCommand()}\` after every edit, before any dry run or apply, and fix what it reports: it takes about a second and catches what step 2 and the dry run do not (such as a reference to a start input the trigger does not declare). It type-checks the files with the TypeScript release the declarations are built for. \`tsconfig.json\` includes only the blocks the workflows used at the last check or get, which keeps it fast: a builder from another block fails with \`has no exported member\` until you run step 2 (or check with \`${typecheckCommand(TSCONFIG_FULL_FILE)}\`, every current block). \`sim workflows source params \` prints one builder's params and outputs; do not read the declarations whole. The dry run is the authority: a printed file you did not edit that \`tsc\` flags and the dry run accepts is fine, so leave it as it is. +3. Run \`${typecheckCommand()}\` after step 2 (chain it) and fix what it reports: it takes about a second and catches what step 2 and the dry run do not (such as a reference to a start input the trigger does not declare). It type-checks the files with the TypeScript release the declarations are built for. \`tsconfig.json\` includes only the blocks the workflows used at the last check or get, which keeps it fast: a builder from another block fails with \`has no exported member\` until you run step 2 (or check with \`${typecheckCommand(TSCONFIG_FULL_FILE)}\`, every current block). \`sim workflows source params \` prints one builder's params and outputs; do not read the declarations whole. The dry run is the authority: a printed file you did not edit that \`tsc\` flags and the dry run accepts is fine, so leave it as it is. 4. \`sim workspaces source status --dir .\` before applying: your changes by resource (\`sim workspaces source diff --dir .\` shows the edits), what changed on the server since the get (a workflow edited in the editor included), the conflicts, and the command to run next. Exit 0 nothing changed, ${SOURCE_LOCAL_CHANGES_EXIT_CODE} only your edits, ${SOURCE_DRIFT_EXIT_CODE} the server changed since (\`--offline\`: skip the server). Then \`sim workspaces source apply --dir . --dry-run\`: shows the plan (\`+\` create, \`~\` update, \`=\` adopt an existing resource of the same name, \`-\` delete) and every error; fix and rerun until it exits 0. 5. \`sim workspaces source apply --dir . --yes\`: writes it and rewrites this directory from what was stored; it prints the plan it applied (without \`--yes\` and a terminal it prints the plan and exits ${SOURCE_PLANNED_EXIT_CODE}, writing nothing). diff --git a/packages/workflow-sdk/cookbook/examples/cookbook.ts b/packages/workflow-sdk/cookbook/examples/cookbook.ts index b33b72df323..f13b1890758 100644 --- a/packages/workflow-sdk/cookbook/examples/cookbook.ts +++ b/packages/workflow-sdk/cookbook/examples/cookbook.ts @@ -72,10 +72,12 @@ export default workflow('Cookbook', { description: 'One example of each common b filterInput: { all: [{ field: 'status', op: 'eq', value: 'open' }] }, limit: 50, }) - // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else - // inserts one, so a second run for the same order updates it. table.insertRow takes the same - // data without conflictColumn and adds a row every run. data is keyed by column name: a column - // declared as `phone: column.string({ name: 'mobile' })` is written as { mobile: ... }. + // Upsert: replaces the row whose conflictColumn (a unique column, by name) matches data, else + // inserts one, so a second run for the same order rewrites it and a column missing from data + // is cleared (table.updateRowsByFilter changes only the columns it names). table.insertRow + // takes the same data without conflictColumn and adds a row every run. data is keyed by column + // name: a column declared as `phone: column.string({ name: 'mobile' })` is written as + // { mobile: ... }. const save = table.upsertRow('Save Order', { tableId: table('orders'), data: { orderId: start.orderId, status: 'open' }, diff --git a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts index e4749454eac..e183175d73c 100644 --- a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from cookbook/examples; do not edit. /** The example workflows, file name → text, written as `.sim/examples/`: together one correct example of each common block. */ -export const COOKBOOK_EXAMPLES: Readonly> = {"agents.ts":"// @sim-sdk 1\nimport {\n agent,\n childWorkflow,\n credential,\n customTool,\n env,\n mcp,\n parallel,\n response,\n router,\n runWorkflow,\n slack,\n t,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `lookup-order`, `linear`, `ops-slack`,\n// `enrich-lead` and ANTHROPIC_API_KEY stand in for this workspace\u0027s resources\n// (.sim/sdk/workspace.d.ts; `sim workflows source resources` lists the real keys).\nexport default workflow(\n \u0027Cookbook: agents and subflows\u0027,\n { description: \u0027Router, agent tools, a child workflow and a parallel fan-out.\u0027 },\n () => {\n const start = trigger.start(\u0027Start\u0027, {\n inputFormat: { message: \u0027string\u0027, email: \u0027string\u0027, domains: \u0027array\u0027 },\n })\n\n // Router: the model picks one route by its description; wire with triage..to(...).\n const triage = router(\u0027Triage\u0027, {\n context: start.message,\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n routes: {\n support: \u0027A customer asking about an existing order\u0027,\n sales: \u0027A prospect asking about pricing or a demo\u0027,\n },\n })\n\n // Agent tools: a workspace custom tool, one tool of an MCP server, an integration operation\n // (.tool.; the params given here are fixed, the model fills the rest) and\n // another workflow.\n const support = agent(\u0027Support Agent\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Answer the customer. Use your tools when they help.\u0027 },\n { role: \u0027user\u0027, content: start.message },\n ],\n tools: [\n customTool(\u0027lookup-order\u0027),\n mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027),\n slack.tool.sendMessage({ credential: credential(\u0027ops-slack\u0027), channel: \u0027support-urgent\u0027 }),\n childWorkflow(\u0027enrich-lead\u0027).asTool(),\n ],\n })\n\n // Child workflow: inputMapping is checked against the child\u0027s start inputs. Its output is\n // enrich.result (untyped JSON): the child\u0027s response block output, so a field of the child\u0027s\n // response body is enrich.result.data..\n const enrich = runWorkflow(\u0027Enrich Lead\u0027, {\n workflowId: childWorkflow(\u0027enrich-lead\u0027),\n inputMapping: { email: start.email },\n })\n\n // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its\n // position; each.results lists every branch\u0027s output once all finish. (loop.forEach is the\n // sequential form.) In a function code file inside the body, the same values are\n // $ref.parallel.currentItem and $ref.parallel.index.\n const each = parallel.collection(\u0027Each Domain\u0027, { collection: start.domains }, (p) => {\n const brief = agent(\u0027Company Brief\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Describe ${p.currentItem} in two sentences.` }],\n })\n p.to(brief)\n })\n\n const answer = response(\u0027Answer\u0027, { body: { answer: support.content } })\n const briefs = response(\u0027Briefs\u0027, {\n body: { lead: t`${enrich.result}`, briefs: t`${each.results}` },\n })\n\n start.to(triage)\n triage.support.to(support)\n support.to(answer)\n triage.sales.to(enrich)\n enrich.to(each)\n each.to(briefs)\n }\n)\n","cookbook.ts":"// @sim-sdk 1\nimport {\n agent,\n condition,\n credential,\n env,\n fn,\n human,\n js,\n knowledge,\n knowledgeBase,\n loop,\n response,\n slack,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `orders`, `policies`, `ops-slack` and\n// ANTHROPIC_API_KEY stand in for this workspace\u0027s resources. `sim workflows source resources`\n// lists the real keys, and .sim/sdk/workspace.d.ts types them.\nexport default workflow(\u0027Cookbook\u0027, { description: \u0027One example of each common block.\u0027 }, () => {\n // Triggers: trigger.start (API/manual input), trigger.schedule, trigger.webhook.\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, amount: \u0027number\u0027 } })\n const nightly = trigger.schedule(\u0027Nightly\u0027, {\n scheduleType: \u0027daily\u0027,\n dailyTime: \u002702:00\u0027,\n timezone: \u0027UTC\u0027,\n })\n\n // Agent: structured output via responseFormat; its fields become outputs (check.risk).\n // apiKey: needed on self-hosted Sim; hosted Sim supplies one.\n const check = agent(\u0027Check Order\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Rate the fraud risk of an order as low, med or high.\u0027 },\n { role: \u0027user\u0027, content: t`Order ${start.orderId} for ${start.amount}` },\n ],\n responseFormat: {\n name: \u0027risk\u0027,\n strict: true,\n schema: {\n type: \u0027object\u0027,\n properties: {\n risk: { type: \u0027string\u0027, enum: [\u0027low\u0027, \u0027med\u0027, \u0027high\u0027] },\n reason: { type: \u0027string\u0027 },\n },\n required: [\u0027risk\u0027, \u0027reason\u0027],\n additionalProperties: false,\n },\n },\n })\n\n // Condition: one branch per key, `else: true` last; wire with route..to(...).\n const route = condition(\u0027Route Risk\u0027, {\n high: js`${check.risk} === \u0027high\u0027`,\n med: js`${check.risk} === \u0027med\u0027`,\n else: true,\n })\n\n // Function: inline JavaScript; reference outputs with ${...}. Result is fn.result.\n const shape = fn(\u0027Shape\u0027, {\n code: js`return { id: ${start.orderId}, cents: Math.round(${start.amount} * 100) }`,\n })\n\n // Tables: query rows (each row is { id, data: { column } }) and write one.\n const recent = table.queryRows(\u0027Recent Orders\u0027, {\n tableId: table(\u0027orders\u0027),\n filterInput: { all: [{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027open\u0027 }] },\n limit: 50,\n })\n // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else\n // inserts one, so a second run for the same order updates it. table.insertRow takes the same\n // data without conflictColumn and adds a row every run. data is keyed by column name: a column\n // declared as `phone: column.string({ name: \u0027mobile\u0027 })` is written as { mobile: ... }.\n const save = table.upsertRow(\u0027Save Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n\n // Knowledge base search: results is the list of matching chunks.\n const docs = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: check.reason,\n topK: 3,\n })\n\n // Slack: a saved credential by key (see .sim/sdk/workspace.d.ts).\n const alert = slack.sendMessage(\u0027Alert Ops\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-alerts\u0027,\n messageFormat: \u0027text\u0027,\n text: t`High-risk order ${start.orderId}: ${check.reason}`,\n })\n\n // Human in the loop: inputFormat is the form; answers are approval.submission..\n const approval = human(\u0027Manager Review\u0027, {\n builderData: [{ name: \u0027orderId\u0027, type: \u0027string\u0027, value: start.orderId }],\n inputFormat: { approved: { type: \u0027boolean\u0027, required: true }, note: \u0027string\u0027 },\n })\n const decided = condition(\u0027Approved\u0027, {\n yes: js`${approval.submission.approved} === true`,\n else: true,\n })\n\n // Loop over a list: p.currentItem is one element and p.index its position; the loop\u0027s results\n // is the list of iteration outputs. In js`` code a reference is the value itself, not text\n // spliced in: write it where an expression goes, never inside quotes (\u0027${x}\u0027 would give the\n // JSON, quotes included). A function code file (code: codeFile(\u0027./functions/line.js\u0027)) reads\n // other blocks as $ref.. ($ref.recentorders.rows) and, inside the loop body,\n // the iteration as $ref.loop.currentItem and $ref.loop.index.\n const each = loop.forEach(\u0027Each Order\u0027, { collection: recent.rows }, (p) => {\n const line = fn(\u0027Line\u0027, {\n code: js`return ${p.currentItem.data.orderId} + \u0027: \u0027 + ${p.currentItem.data.status}`,\n })\n p.to(line)\n })\n const report = agent(\u0027Report\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Summarize these orders in 3 lines:\\n${each.results}` }],\n })\n const post = slack.sendMessage(\u0027Post Report\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-daily\u0027,\n messageFormat: \u0027text\u0027,\n text: report.content,\n })\n\n // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text.\n // body is the short form of the editor\u0027s JSON mode: { dataMode: \u0027json\u0027, data } as below.\n const reply = response(\u0027Respond\u0027, { body: { risk: check.risk, id: t`${shape.result.id}` } })\n const rejected = response(\u0027Respond Rejected\u0027, {\n dataMode: \u0027json\u0027,\n data: { status: \u0027rejected\u0027 },\n })\n // Error path: shape.onError(invalid) runs invalid when the code throws. shape.error leads with\n // the line and code that threw; shape.errorMessage is the thrown message alone, for the caller.\n const invalid = response(\u0027Respond Invalid\u0027, { body: { error: shape.errorMessage }, status: 422 })\n\n // Wiring: a.to(b) chains; a block can fan out to several targets.\n start.to(check)\n check.to(save)\n save.to(route)\n route.high.to(alert)\n alert.to(approval)\n approval.to(decided)\n decided.yes.to(shape)\n decided.else.to(rejected)\n route.med.to(docs)\n docs.to(shape)\n route.else.to(shape)\n shape.to(reply)\n shape.onError(invalid)\n nightly.to(recent)\n recent.to(each)\n each.to(report)\n report.to(post)\n})\n","integrations.ts":"// @sim-sdk 1\nimport {\n api,\n credential,\n env,\n gmail,\n response,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `leads`, `ops-gmail`, CLEARBIT_KEY and\n// LEADS_WEBHOOK_TOKEN stand in for this workspace\u0027s resources (.sim/sdk/workspace.d.ts).\n// Integration builders are named by service, not block type: `gmail_v2` is `gmail.*`, and a\n// hidden older version lives under `legacy.*`. .sim/sdk/INDEX.md lists every builder.\nexport default workflow(\n \u0027Cookbook: integrations\u0027,\n { description: \u0027Webhook, weekday schedule, HTTP with headers, table update, Gmail, error path.\u0027 },\n () => {\n // Webhook trigger: inputFormat types the posted JSON fields (hook.leadId). With requireAuth\n // the caller must send the token; keep it in an env var.\n const hook = trigger.webhook(\u0027Lead Webhook\u0027, {\n requireAuth: true,\n token: env.LEADS_WEBHOOK_TOKEN,\n inputFormat: { leadId: \u0027string\u0027, email: \u0027string\u0027, domain: \u0027string\u0027 },\n })\n\n // Schedule: no weekday preset exists, so scheduleType \u0027custom\u0027 takes a 5-field cron.\n const weekdays = trigger.schedule(\u0027Weekdays 8am\u0027, {\n scheduleType: \u0027custom\u0027,\n cronExpression: \u00270 8 * * 1-5\u0027,\n timezone: \u0027America/New_York\u0027,\n })\n\n // HTTP request: headers (and query params) are table rows, { cells: { Key, Value } }.\n const lookup = api(\u0027Company Lookup\u0027, {\n url: t`https://company.clearbit.com/v2/companies/find?domain=${hook.domain}`,\n method: \u0027GET\u0027,\n headers: [{ cells: { Key: \u0027Authorization\u0027, Value: t`Bearer ${env.CLEARBIT_KEY}` } }],\n })\n\n // Update one row by id: data holds only the columns to change. lookup.data is untyped JSON,\n // so a text field from it is wrapped in t``.\n const save = table.updateRowById(\u0027Save Company\u0027, {\n tableId: table(\u0027leads\u0027),\n rowId: hook.leadId,\n data: { company: t`${lookup.data.name}`, enriched: true },\n })\n\n // Gmail (gmail_v2): send one email with a saved Google credential.\n const welcome = gmail.sendEmail(\u0027Welcome Email\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: hook.email,\n subject: \u0027Welcome aboard\u0027,\n body: t`Thanks for signing up from ${hook.domain}.`,\n })\n\n // Query rows, then email them as one digest. A typed column filter: { field, op, value }.\n const pending = table.queryRows(\u0027Pending Leads\u0027, {\n tableId: table(\u0027leads\u0027),\n filterInput: { all: [{ field: \u0027enriched\u0027, op: \u0027eq\u0027, value: false }] },\n limit: 100,\n })\n const digest = gmail.sendEmail(\u0027Pending Digest\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: \u0027ops@example.com\u0027,\n subject: \u0027Leads still to enrich\u0027,\n body: t`${pending.rows}`,\n })\n\n // Error path: x.onError(y) runs y when x fails, instead of failing the run; y reads the\n // failure message as x.error.\n const failed = response(\u0027Lookup Failed\u0027, {\n body: { ok: false, error: lookup.error },\n status: 502,\n })\n const done = response(\u0027Done\u0027, { body: { ok: true, row: save.row } })\n\n hook.to(lookup)\n lookup.to(save)\n lookup.onError(failed)\n save.to(welcome)\n welcome.to(done)\n weekdays.to(pending)\n pending.to(digest)\n }\n)\n"} +export const COOKBOOK_EXAMPLES: Readonly> = {"agents.ts":"// @sim-sdk 1\nimport {\n agent,\n childWorkflow,\n credential,\n customTool,\n env,\n mcp,\n parallel,\n response,\n router,\n runWorkflow,\n slack,\n t,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `lookup-order`, `linear`, `ops-slack`,\n// `enrich-lead` and ANTHROPIC_API_KEY stand in for this workspace\u0027s resources\n// (.sim/sdk/workspace.d.ts; `sim workflows source resources` lists the real keys).\nexport default workflow(\n \u0027Cookbook: agents and subflows\u0027,\n { description: \u0027Router, agent tools, a child workflow and a parallel fan-out.\u0027 },\n () => {\n const start = trigger.start(\u0027Start\u0027, {\n inputFormat: { message: \u0027string\u0027, email: \u0027string\u0027, domains: \u0027array\u0027 },\n })\n\n // Router: the model picks one route by its description; wire with triage..to(...).\n const triage = router(\u0027Triage\u0027, {\n context: start.message,\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n routes: {\n support: \u0027A customer asking about an existing order\u0027,\n sales: \u0027A prospect asking about pricing or a demo\u0027,\n },\n })\n\n // Agent tools: a workspace custom tool, one tool of an MCP server, an integration operation\n // (.tool.; the params given here are fixed, the model fills the rest) and\n // another workflow.\n const support = agent(\u0027Support Agent\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Answer the customer. Use your tools when they help.\u0027 },\n { role: \u0027user\u0027, content: start.message },\n ],\n tools: [\n customTool(\u0027lookup-order\u0027),\n mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027),\n slack.tool.sendMessage({ credential: credential(\u0027ops-slack\u0027), channel: \u0027support-urgent\u0027 }),\n childWorkflow(\u0027enrich-lead\u0027).asTool(),\n ],\n })\n\n // Child workflow: inputMapping is checked against the child\u0027s start inputs. Its output is\n // enrich.result (untyped JSON): the child\u0027s response block output, so a field of the child\u0027s\n // response body is enrich.result.data..\n const enrich = runWorkflow(\u0027Enrich Lead\u0027, {\n workflowId: childWorkflow(\u0027enrich-lead\u0027),\n inputMapping: { email: start.email },\n })\n\n // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its\n // position; each.results lists every branch\u0027s output once all finish. (loop.forEach is the\n // sequential form.) In a function code file inside the body, the same values are\n // $ref.parallel.currentItem and $ref.parallel.index.\n const each = parallel.collection(\u0027Each Domain\u0027, { collection: start.domains }, (p) => {\n const brief = agent(\u0027Company Brief\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Describe ${p.currentItem} in two sentences.` }],\n })\n p.to(brief)\n })\n\n const answer = response(\u0027Answer\u0027, { body: { answer: support.content } })\n const briefs = response(\u0027Briefs\u0027, {\n body: { lead: t`${enrich.result}`, briefs: t`${each.results}` },\n })\n\n start.to(triage)\n triage.support.to(support)\n support.to(answer)\n triage.sales.to(enrich)\n enrich.to(each)\n each.to(briefs)\n }\n)\n","cookbook.ts":"// @sim-sdk 1\nimport {\n agent,\n condition,\n credential,\n env,\n fn,\n human,\n js,\n knowledge,\n knowledgeBase,\n loop,\n response,\n slack,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `orders`, `policies`, `ops-slack` and\n// ANTHROPIC_API_KEY stand in for this workspace\u0027s resources. `sim workflows source resources`\n// lists the real keys, and .sim/sdk/workspace.d.ts types them.\nexport default workflow(\u0027Cookbook\u0027, { description: \u0027One example of each common block.\u0027 }, () => {\n // Triggers: trigger.start (API/manual input), trigger.schedule, trigger.webhook.\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, amount: \u0027number\u0027 } })\n const nightly = trigger.schedule(\u0027Nightly\u0027, {\n scheduleType: \u0027daily\u0027,\n dailyTime: \u002702:00\u0027,\n timezone: \u0027UTC\u0027,\n })\n\n // Agent: structured output via responseFormat; its fields become outputs (check.risk).\n // apiKey: needed on self-hosted Sim; hosted Sim supplies one.\n const check = agent(\u0027Check Order\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Rate the fraud risk of an order as low, med or high.\u0027 },\n { role: \u0027user\u0027, content: t`Order ${start.orderId} for ${start.amount}` },\n ],\n responseFormat: {\n name: \u0027risk\u0027,\n strict: true,\n schema: {\n type: \u0027object\u0027,\n properties: {\n risk: { type: \u0027string\u0027, enum: [\u0027low\u0027, \u0027med\u0027, \u0027high\u0027] },\n reason: { type: \u0027string\u0027 },\n },\n required: [\u0027risk\u0027, \u0027reason\u0027],\n additionalProperties: false,\n },\n },\n })\n\n // Condition: one branch per key, `else: true` last; wire with route..to(...).\n const route = condition(\u0027Route Risk\u0027, {\n high: js`${check.risk} === \u0027high\u0027`,\n med: js`${check.risk} === \u0027med\u0027`,\n else: true,\n })\n\n // Function: inline JavaScript; reference outputs with ${...}. Result is fn.result.\n const shape = fn(\u0027Shape\u0027, {\n code: js`return { id: ${start.orderId}, cents: Math.round(${start.amount} * 100) }`,\n })\n\n // Tables: query rows (each row is { id, data: { column } }) and write one.\n const recent = table.queryRows(\u0027Recent Orders\u0027, {\n tableId: table(\u0027orders\u0027),\n filterInput: { all: [{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027open\u0027 }] },\n limit: 50,\n })\n // Upsert: replaces the row whose conflictColumn (a unique column, by name) matches data, else\n // inserts one, so a second run for the same order rewrites it and a column missing from data\n // is cleared (table.updateRowsByFilter changes only the columns it names). table.insertRow\n // takes the same data without conflictColumn and adds a row every run. data is keyed by column\n // name: a column declared as `phone: column.string({ name: \u0027mobile\u0027 })` is written as\n // { mobile: ... }.\n const save = table.upsertRow(\u0027Save Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n\n // Knowledge base search: results is the list of matching chunks.\n const docs = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: check.reason,\n topK: 3,\n })\n\n // Slack: a saved credential by key (see .sim/sdk/workspace.d.ts).\n const alert = slack.sendMessage(\u0027Alert Ops\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-alerts\u0027,\n messageFormat: \u0027text\u0027,\n text: t`High-risk order ${start.orderId}: ${check.reason}`,\n })\n\n // Human in the loop: inputFormat is the form; answers are approval.submission..\n const approval = human(\u0027Manager Review\u0027, {\n builderData: [{ name: \u0027orderId\u0027, type: \u0027string\u0027, value: start.orderId }],\n inputFormat: { approved: { type: \u0027boolean\u0027, required: true }, note: \u0027string\u0027 },\n })\n const decided = condition(\u0027Approved\u0027, {\n yes: js`${approval.submission.approved} === true`,\n else: true,\n })\n\n // Loop over a list: p.currentItem is one element and p.index its position; the loop\u0027s results\n // is the list of iteration outputs. In js`` code a reference is the value itself, not text\n // spliced in: write it where an expression goes, never inside quotes (\u0027${x}\u0027 would give the\n // JSON, quotes included). A function code file (code: codeFile(\u0027./functions/line.js\u0027)) reads\n // other blocks as $ref.. ($ref.recentorders.rows) and, inside the loop body,\n // the iteration as $ref.loop.currentItem and $ref.loop.index.\n const each = loop.forEach(\u0027Each Order\u0027, { collection: recent.rows }, (p) => {\n const line = fn(\u0027Line\u0027, {\n code: js`return ${p.currentItem.data.orderId} + \u0027: \u0027 + ${p.currentItem.data.status}`,\n })\n p.to(line)\n })\n const report = agent(\u0027Report\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Summarize these orders in 3 lines:\\n${each.results}` }],\n })\n const post = slack.sendMessage(\u0027Post Report\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-daily\u0027,\n messageFormat: \u0027text\u0027,\n text: report.content,\n })\n\n // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text.\n // body is the short form of the editor\u0027s JSON mode: { dataMode: \u0027json\u0027, data } as below.\n const reply = response(\u0027Respond\u0027, { body: { risk: check.risk, id: t`${shape.result.id}` } })\n const rejected = response(\u0027Respond Rejected\u0027, {\n dataMode: \u0027json\u0027,\n data: { status: \u0027rejected\u0027 },\n })\n // Error path: shape.onError(invalid) runs invalid when the code throws. shape.error leads with\n // the line and code that threw; shape.errorMessage is the thrown message alone, for the caller.\n const invalid = response(\u0027Respond Invalid\u0027, { body: { error: shape.errorMessage }, status: 422 })\n\n // Wiring: a.to(b) chains; a block can fan out to several targets.\n start.to(check)\n check.to(save)\n save.to(route)\n route.high.to(alert)\n alert.to(approval)\n approval.to(decided)\n decided.yes.to(shape)\n decided.else.to(rejected)\n route.med.to(docs)\n docs.to(shape)\n route.else.to(shape)\n shape.to(reply)\n shape.onError(invalid)\n nightly.to(recent)\n recent.to(each)\n each.to(report)\n report.to(post)\n})\n","integrations.ts":"// @sim-sdk 1\nimport {\n api,\n credential,\n env,\n gmail,\n response,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `leads`, `ops-gmail`, CLEARBIT_KEY and\n// LEADS_WEBHOOK_TOKEN stand in for this workspace\u0027s resources (.sim/sdk/workspace.d.ts).\n// Integration builders are named by service, not block type: `gmail_v2` is `gmail.*`, and a\n// hidden older version lives under `legacy.*`. .sim/sdk/INDEX.md lists every builder.\nexport default workflow(\n \u0027Cookbook: integrations\u0027,\n { description: \u0027Webhook, weekday schedule, HTTP with headers, table update, Gmail, error path.\u0027 },\n () => {\n // Webhook trigger: inputFormat types the posted JSON fields (hook.leadId). With requireAuth\n // the caller must send the token; keep it in an env var.\n const hook = trigger.webhook(\u0027Lead Webhook\u0027, {\n requireAuth: true,\n token: env.LEADS_WEBHOOK_TOKEN,\n inputFormat: { leadId: \u0027string\u0027, email: \u0027string\u0027, domain: \u0027string\u0027 },\n })\n\n // Schedule: no weekday preset exists, so scheduleType \u0027custom\u0027 takes a 5-field cron.\n const weekdays = trigger.schedule(\u0027Weekdays 8am\u0027, {\n scheduleType: \u0027custom\u0027,\n cronExpression: \u00270 8 * * 1-5\u0027,\n timezone: \u0027America/New_York\u0027,\n })\n\n // HTTP request: headers (and query params) are table rows, { cells: { Key, Value } }.\n const lookup = api(\u0027Company Lookup\u0027, {\n url: t`https://company.clearbit.com/v2/companies/find?domain=${hook.domain}`,\n method: \u0027GET\u0027,\n headers: [{ cells: { Key: \u0027Authorization\u0027, Value: t`Bearer ${env.CLEARBIT_KEY}` } }],\n })\n\n // Update one row by id: data holds only the columns to change. lookup.data is untyped JSON,\n // so a text field from it is wrapped in t``.\n const save = table.updateRowById(\u0027Save Company\u0027, {\n tableId: table(\u0027leads\u0027),\n rowId: hook.leadId,\n data: { company: t`${lookup.data.name}`, enriched: true },\n })\n\n // Gmail (gmail_v2): send one email with a saved Google credential.\n const welcome = gmail.sendEmail(\u0027Welcome Email\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: hook.email,\n subject: \u0027Welcome aboard\u0027,\n body: t`Thanks for signing up from ${hook.domain}.`,\n })\n\n // Query rows, then email them as one digest. A typed column filter: { field, op, value }.\n const pending = table.queryRows(\u0027Pending Leads\u0027, {\n tableId: table(\u0027leads\u0027),\n filterInput: { all: [{ field: \u0027enriched\u0027, op: \u0027eq\u0027, value: false }] },\n limit: 100,\n })\n const digest = gmail.sendEmail(\u0027Pending Digest\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: \u0027ops@example.com\u0027,\n subject: \u0027Leads still to enrich\u0027,\n body: t`${pending.rows}`,\n })\n\n // Error path: x.onError(y) runs y when x fails, instead of failing the run; y reads the\n // failure message as x.error.\n const failed = response(\u0027Lookup Failed\u0027, {\n body: { ok: false, error: lookup.error },\n status: 502,\n })\n const done = response(\u0027Done\u0027, { body: { ok: true, row: save.row } })\n\n hook.to(lookup)\n lookup.to(save)\n lookup.onError(failed)\n save.to(welcome)\n welcome.to(done)\n weekdays.to(pending)\n pending.to(digest)\n }\n)\n"} diff --git a/packages/workflow-sdk/src/codegen/generate.ts b/packages/workflow-sdk/src/codegen/generate.ts index cf2b767c3ea..33cfd2b7339 100644 --- a/packages/workflow-sdk/src/codegen/generate.ts +++ b/packages/workflow-sdk/src/codegen/generate.ts @@ -119,6 +119,22 @@ const CORE_TYPE_NAMES = [ const HEADER_PREFIX = '// @sim-sdk' +/** + * What a builder does at run time that its params cannot show, said in its doc comment and in + * `sim workflows source params`. `table.upsertRow`: `upsertRow` in + * `apps/sim/lib/table/rows/service.ts` writes the stored row's whole `data`, where the update + * builders merge cells (`jsonbMergePatch`). + */ +const BUILDER_NOTES: Readonly> = { + 'table.upsertRow': + 'Replaces the matched row: a column missing from `data` is cleared, not kept. To change some columns of existing rows, use `table.updateRowsByFilter` (or `table.updateRowById` for one row), which merge `data` into the stored row.', +} + +/** The note on builder `key`, when it has one. */ +export function builderNote(key: string): string | undefined { + return Object.hasOwn(BUILDER_NOTES, key) ? BUILDER_NOTES[key] : undefined +} + function header(sdkMajor: number): string { return `${HEADER_PREFIX} ${sdkMajor} · generated from the block catalog; do not edit` } @@ -498,10 +514,11 @@ export function builderTypes(catalog: BlockCatalog, entry: BuilderEntry): Builde ] .filter(Boolean) .join(' ') + const note = builderNote(entry.key) const signature = entry.special ? [] : [ - ...jsdoc([jsdocSummary], ''), + ...jsdoc(note ? [jsdocSummary, note] : [jsdocSummary], ''), `export function ${method}${typeParameterList(plan, true)}(name: string, params: ${paramsName}${genericArgs}, meta?: BlockMeta): Block<${outputType}${errorOutputs ? `, ${errorOutputs}` : ''}>`, ] const tool = diff --git a/packages/workflow-sdk/src/codegen/reference.test.ts b/packages/workflow-sdk/src/codegen/reference.test.ts index 98069665471..f787d5e6d55 100644 --- a/packages/workflow-sdk/src/codegen/reference.test.ts +++ b/packages/workflow-sdk/src/codegen/reference.test.ts @@ -11,6 +11,14 @@ const CATALOG = JSON.parse( ) as BlockCatalog describe('builder reference', () => { + it('says table.upsertRow replaces the row, and names update builders that exist', () => { + const upsert = describeBuilder(CATALOG, 'table.upsertRow') + expect(upsert?.doc).toContain('Replaces the matched row') + for (const [, name] of upsert?.doc?.matchAll(/`(table\.\w+)`/g) ?? []) { + expect(describeBuilder(CATALOG, name), name).not.toBeNull() + } + }) + it('gives each special builder the call core.d.ts declares, with its own params and return type', () => { expect(describeBuilder(CATALOG, 'condition')?.signature).toBe( "condition>(name: string, branches: B & ConditionBranches, meta?: BlockMeta): Block> & Branches>" diff --git a/packages/workflow-sdk/src/codegen/reference.ts b/packages/workflow-sdk/src/codegen/reference.ts index 6e1bc55626f..adf46520c01 100644 --- a/packages/workflow-sdk/src/codegen/reference.ts +++ b/packages/workflow-sdk/src/codegen/reference.ts @@ -16,7 +16,13 @@ import { } from '@sim/workflow-code/catalog/view' import { SDK_CORE_EXPORTS } from '@sim/workflow-code/sdk' import { CORE_DTS } from './core-text.generated' -import { builderTypes, operationLabel, type ParamFact, type ParamFacts } from './generate' +import { + builderNote, + builderTypes, + operationLabel, + type ParamFact, + type ParamFacts, +} from './generate' import { isLegacyBuilder } from './layout' import { builderEntry, TOOL_NAMESPACE } from './names' @@ -117,6 +123,8 @@ export function describeBuilder(catalog: BlockCatalog, key: string): BuilderRefe ? `${entry.path.slice(0, -1).join('.')}.${TOOL_NAMESPACE}.${(types.tool.at(-1) ?? '').replace(/^export function /, '')}` : null const replacement = replacementOf(catalog, entry.builder.type, entry.builder.operation) + const note = builderNote(key) + const noteDoc = note ? { doc: note } : {} return { key, blockType: entry.builder.type, @@ -124,7 +132,7 @@ export function describeBuilder(catalog: BlockCatalog, key: string): BuilderRefe ...(entry.builder.operation ? { operation: entry.builder.operation } : {}), legacy: isLegacyBuilder(key), ...(replacement ? { replacement } : {}), - ...(entry.special ? docOf(key) : {}), + ...(entry.special ? docOf(key) : noteDoc), signature, tool, paramsName: types.paramsName,