diff --git a/.claude/rules/sim-workflow-code.md b/.claude/rules/sim-workflow-code.md index d7435063c05..e93c164628a 100644 --- a/.claude/rules/sim-workflow-code.md +++ b/.claude/rules/sim-workflow-code.md @@ -48,6 +48,14 @@ workspace directory). | `apps/sim/blocks/sdk-names/.json` | Frozen SDK builder names, one file per block type | | `apps/sim/app/workspace/**/panel/components/code/` | The read-only Code tab | +Public docs live in `apps/docs/content/docs/workflows/code/`. The exit-code, diagnostic-code, limit +and per-kind layout tables of `exit-codes.mdx`, `diagnostics.mdx`, `limits.mdx` and `directory.mdx` sit between +`workflow-code-docs` markers and come from their owners (`source-exit-codes.ts`, SYNTAX.md and `workspace-code`'s +`diagnostics/codes.ts` TSDoc, the `*_LIMITS` constants, `WORKSPACE_KIND_SPECS`): edit the owner, then run +`bun run generate:workflow-code-docs` (`check:workflow-code-docs` fails on drift, a diagnostic code a page names that +no engine emits, a limit or diagnostic code with no docs entry, and a `typescript@x.y.z` pin other than the CLI's). +A limit also needs a label in the generator's `WORKFLOW_LIMIT_LABELS` or `WORKSPACE_LIMIT_LABELS`. + Dependencies point one way: `packages/workflow-types` → `packages/workflow-code` → `packages/workspace-code` and `packages/workflow-sdk` → the CLI and `apps/sim`. `check:boundaries` keeps both engines and `packages/table-cells` pure (no Node built-ins, `eval`, `globalThis`, dynamic import): they run in the browser, the CLI and the diff --git a/.cursor/rules/sim-workflow-code.mdc b/.cursor/rules/sim-workflow-code.mdc index 77d1474b0f1..9ea97adf333 100644 --- a/.cursor/rules/sim-workflow-code.mdc +++ b/.cursor/rules/sim-workflow-code.mdc @@ -28,6 +28,14 @@ workspace directory). | `apps/sim/blocks/sdk-names/.json` | Frozen SDK builder names, one file per block type | | `apps/sim/app/workspace/**/panel/components/code/` | The read-only Code tab | +Public docs live in `apps/docs/content/docs/workflows/code/`. The exit-code, diagnostic-code, limit +and per-kind layout tables of `exit-codes.mdx`, `diagnostics.mdx`, `limits.mdx` and `directory.mdx` sit between +`workflow-code-docs` markers and come from their owners (`source-exit-codes.ts`, SYNTAX.md and `workspace-code`'s +`diagnostics/codes.ts` TSDoc, the `*_LIMITS` constants, `WORKSPACE_KIND_SPECS`): edit the owner, then run +`bun run generate:workflow-code-docs` (`check:workflow-code-docs` fails on drift, a diagnostic code a page names that +no engine emits, a limit or diagnostic code with no docs entry, and a `typescript@x.y.z` pin other than the CLI's). +A limit also needs a label in the generator's `WORKFLOW_LIMIT_LABELS` or `WORKSPACE_LIMIT_LABELS`. + Dependencies point one way: `packages/workflow-types` → `packages/workflow-code` → `packages/workspace-code` and `packages/workflow-sdk` → the CLI and `apps/sim`. `check:boundaries` keeps both engines and `packages/table-cells` pure (no Node built-ins, `eval`, `globalThis`, dynamic import): they run in the browser, the CLI and the diff --git a/apps/docs/content/docs/cli/index.mdx b/apps/docs/content/docs/cli/index.mdx index cccca7766cb..0af5ca3871a 100644 --- a/apps/docs/content/docs/cli/index.mdx +++ b/apps/docs/content/docs/cli/index.mdx @@ -140,7 +140,7 @@ sim tables rows query --help | [`workflow-mcp-servers`](/cli/workflow-mcp-servers) | Expose deployed workflows as MCP tools | | [`meta`](/cli/meta) | Inspect API availability and credential status | -To edit a workflow as a TypeScript file, or a whole workspace as a directory, use `sim workflows source` and `sim workspaces source` (in preview). See [Workflows as code](/workflows/code) and [Workspace as code](/workflows/workspace-code). +To edit a workflow as a TypeScript file, or a whole workspace as a directory, use `sim workflows source` and `sim workspaces source` (in preview). See [Workflows as code](/workflows/code) and [Manage a workspace as code](/workflows/code/workspace). The [command overview](/cli/commands) lists global options and root commands. The [complete reference](/cli/reference) contains every subcommand, argument, and option on one page. Both are generated from the CLI. @@ -177,7 +177,7 @@ The repository is also a native Claude Code and Codex plugin, which exposes the The skills assume `sim` is installed and signed in, so complete [Your first command](#your-first-command) first. They never store or print API keys. These agent skills are separate from the workspace skills you manage with [`sim skills`](/cli/skills). -To have a coding agent edit workflow files directly, see [Workflows as code for coding agents](/workflows/code#for-coding-agents). +To have a coding agent edit workflow files directly, see [Use workflows as code with coding agents](/workflows/code/coding-agents). ## Related docs diff --git a/apps/docs/content/docs/cli/scripting.mdx b/apps/docs/content/docs/cli/scripting.mdx index 5391ed9864a..f14a6f229df 100644 --- a/apps/docs/content/docs/cli/scripting.mdx +++ b/apps/docs/content/docs/cli/scripting.mdx @@ -165,61 +165,7 @@ The CLI resends a request the API answers `429` only when sending it twice is sa | `3` | Committed operation requires configuration | | `4` | Wait timed out | -| Code | `sim workflows source apply` or `create` | -| --- | --- | -| `0` | Applied or created, or a dry run with no errors | -| `1` | The source has errors (each printed as `file:line:column` with its frame and hint), `create`'s workflow name is taken (`SOURCE_NAME_TAKEN`: pass `--name`), or command/request failure | -| `5` | The workflow changed since the directory was read (`409 SOURCE_STALE`): get it again, reapply the edit, and retry | -| `6` | The workflow or its folder is locked (`423`, `E_APPLY_LOCKED`); a locked block exits `1` (`E_APPLY_LOCKED_BLOCK`) | -| `7` | The source is over the size limits (`413`) | -| `9` | Still rate limited (`429`) after the CLI's retries; nothing was written | -| `10` | Busy, retry: another `sim` command is using `--dir`, or the workspace directory it is a workflow folder of (`SOURCE_DIR_BUSY`); nothing was read or written: run it again once the other finished | -| `13` | `AUTH_REQUIRED`: not logged in, or the server refused the credential; nothing was sent | -| `14` | Run without `--yes` and with no terminal to ask: the plan was printed with no errors and nothing was written; run the same command with `--yes` | -| `130` | Interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check | - -| Code | `sim workflows source status` or `sim workspaces source status` | -| --- | --- | -| `0` | Clean: nothing to apply, and the server changed nothing since the directory was read | -| `1` | Command/request failure | -| `7` | The source is too large for the server to read in one dry run | -| `10` | `sim workspaces source status` only: another `sim workspaces source` command is using the directory (`SOURCE_DIR_BUSY`); nothing was read: run it again once the other finished | -| `11` | Local changes only: applying writes them | -| `12` | The server changed since the directory was read (drift, or a conflict with local changes) | -| `13` | `AUTH_REQUIRED`: not logged in, or the server refused the credential; the local changes are still shown | - -| Code | `sim workflows source check` or `sim workspaces source check` | -| --- | --- | -| `0` | No errors (warnings may still print) | -| `1` | The source has errors, or a warning that fails the check on a block the edit added (see `--strict`), or no block catalog is cached: run the get once | -| `10` | `sim workspaces source check` only: another `sim workspaces source` command is using the directory (`SOURCE_DIR_BUSY`); nothing was read: run it again once the other finished | - -| Code | `sim workflows source get --dir` or `sim workspaces source get` | -| --- | --- | -| `0` | Written | -| `1` | The directory holds edits no apply has saved (`SOURCE_LOCAL_EDITS`) or another workflow's source (`SOURCE_WORKFLOW_MISMATCH`): apply them, get into another directory, or pass `--force`; it is the other kind of source directory (`SOURCE_DIR_KIND_MISMATCH`, even with `--force`); for a workspace, `--workspace` names another workspace than the one the directory was read from (`SOURCE_OTHER_WORKSPACE`) or a downloaded binary file does not match its listing (`SOURCE_BLOB_MISMATCH`); or command/request failure | -| `7` | The workflow, or a kind of resource, is too large for one directory | -| `9` | Still rate limited (`429`) after the CLI's retries; nothing was written | -| `10` | Busy, retry: another `sim` command is using the directory (or, for a workflow folder, its workspace directory) (`SOURCE_DIR_BUSY`); nothing was read or written: run it again once the other finished | -| `13` | `AUTH_REQUIRED`: not logged in, the login expired, or the server refused the credential; nothing was read or written: run `sim login` and the get again | -| `130` | Interrupted (Ctrl-C): run the get again | - -| Code | `sim workspaces source apply` | -| --- | --- | -| `0` | Applied, or a dry run with no errors | -| `1` | The source has errors, every change it would write was held back for a secret or credential the workspace cannot satisfy (nothing was written; its dry run exits `1` too), or command/request failure | -| `5` | A resource changed since the directory was read (`409 SOURCE_STALE`): get it again into a fresh directory, reapply the edit, and retry | -| `6` | A resource (a workflow or its folder, a table) is locked (`423`); a locked block exits `1` (`E_APPLY_LOCKED_BLOCK`) | -| `7` | The directory is over the size limits (`413`) | -| `8` | The apply stopped part-way: what was written is saved into the directory; apply again | -| `9` | Still rate limited (`429`) after the CLI's retries; nothing was written | -| `10` | Busy, retry: another apply is writing the workspace (`409 SOURCE_BUSY`), or another `sim workspaces source` command is using the same directory (`SOURCE_DIR_BUSY`); nothing was written: run the command again once the other finished | -| `13` | `AUTH_REQUIRED`: not logged in, or the server refused the credential; nothing was sent | -| `14` | Run without `--yes` and with no terminal to ask: the plan was printed with no errors and nothing was written; run the same command with `--yes` | -| `15` | Written in part: changes that use a declared secret with no value, or a credential key nothing binds to, were held back and the rest was applied and saved; set the secret or connect the credential, then apply again (a promotion with `--to` too). A dry run that would do so exits `15` too, having written nothing | -| `130` | Interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check | - -Earlier CLI releases exited `1` when an apply held changes back, whether or not it wrote the rest, and its dry run exited `1` in either case. A script that reads `1` as "held back" should test for `15` too. +The source commands (`sim workflows source` and `sim workspaces source`) have codes of their own, among them `5` stale, `10` busy, `11` and `12` for `status`, `14` for an apply without `--yes`, and `15` for an apply that held changes back. [Exit codes](/workflows/code/exit-codes) lists each one with what to do next. Both waits default to 3600 seconds; `--wait-timeout 0` waits indefinitely. `SIM_TIMEOUT_SECONDS` independently bounds one API request. A timeout does not cancel the underlying run or operation. @@ -381,63 +327,14 @@ exit "$status" ## Workspace source in CI -Keep a [workspace source directory](/workflows/workspace-code) in a repository, `.sim/` included, and let CI plan each pull request and apply each merge. The dry run exits `1` on errors, `5` when the workspace changed since the committed base, and `15` when the apply would hold back changes that use a secret with no value or a credential nothing binds to; `check` downloads the block catalog once on a fresh runner. On GitHub Actions (`GITHUB_ACTIONS=true`), every source command also annotates each error and warning at its file and line, so they show inline on the pull request, and `apply` (a dry run too) appends its plan and errors to the job's step summary. - -```yaml title=".github/workflows/sim-workspace.yml" -on: - pull_request: - paths: ['workspace/**'] - push: - branches: [main] - paths: ['workspace/**'] - -concurrency: sim-workspace - -permissions: - contents: write - -jobs: - workspace: - runs-on: ubuntu-latest - env: - SIM_API_KEY: ${{ secrets.SIM_API_KEY }} - SIM_WORKSPACE: ${{ vars.SIM_WORKSPACE }} - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: '20' - - uses: oven-sh/setup-bun@v2 - - run: bun add -g sim - - run: sim workspaces source check --dir workspace - - run: bunx -p typescript@7.0.2 tsc -p workspace - - run: sim workspaces source apply --dir workspace --dry-run - - if: github.event_name == 'push' - run: sim workspaces source apply --dir workspace --yes - - if: ${{ !cancelled() && github.event_name == 'push' }} - run: | - git add -A workspace - if ! git diff --cached --quiet; then - git -c user.name=sim-bot -c user.email=sim-bot@users.noreply.github.com \ - commit -m "chore(workspace): files the apply rewrote [skip ci]" - git push - fi -``` - -`check` runs first because it is offline and fast, and it regenerates `.sim/sdk/workspace.d.ts`, so the `tsc` step after it types resources the pull request adds. A workspace API key can apply tables, rows, knowledge bases, files, custom tools, MCP servers and credential bindings. Workflows, skills, secrets and deployments need a member's personal API key, and deployments need an admin. Apply rewrites files under the directory (each `.sim/base.json`, ids it allocated, values the server normalized), and the next apply compares with them, so the last step commits them back to the branch; `[skip ci]` keeps that commit from running the job again. That step runs even when the apply failed (`!cancelled()`), because an apply can fail having written part of its plan: exit `15` means it held back changes that use a secret with no value or a credential nothing binds to and applied the rest, and exit `8` means it stopped part-way. Either way the directory records what was written, so committing it keeps the next run from being refused as stale (exit `5`) for resources this run wrote; the job still fails, so set the secret, connect the credential or fix the failure, and push again. Where the branch is protected, run `sim workspaces source get --dir workspace` on a new branch instead and open a pull request. After merging two branches that each applied, a dry run with no changes means the files match the workspace. Exit `5` means a resource changed since this branch's base: get the workspace into a fresh directory and carry the edit over. Exit `10` means another apply is writing the workspace (or another command is using the directory), so retry; the `concurrency` key keeps two runs of this job from overlapping. - -To promote the same directory to a second workspace, add a step with `--to` before the step that commits the files back: - -```bash -sim workspaces source apply --dir workspace --to "$PROD_WORKSPACE_ID" --yes -``` - -The promotion writes `workspace/.sim/targets/.json`, what it left in that workspace. Committing it lets the next run tell a change made in that workspace since (kept, or exit `5` when the directory changed the same resource) from one to promote. +Dry-run source on pull requests, apply on merge, comment the plan and detect drift on a schedule: see [Run in CI](/workflows/code/ci) for GitHub Actions recipes. ## Related docs - [Output formats](/cli/output) - [Workflow commands](/cli/workflows) +- [Workflows as code: run in CI](/workflows/code/ci) +- [Workflows as code: exit codes](/workflows/code/exit-codes) - [Workflow imports and workspace sync](/cli/workflow-sync) - [Organization commands](/cli/organizations) - [Troubleshooting](/cli/troubleshooting) diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index bfcf603f083..a2e3bf22ef9 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1340,7 +1340,7 @@ sim workflows mkdir API request and response schemas: [createWorkflowFolder](/api-reference/workflows/createWorkflowsFolder). -## Other commands +## Workflows as code ### Show a workflow’s draft as TypeScript source with its identity lock diff --git a/apps/docs/content/docs/meta.json b/apps/docs/content/docs/meta.json index 4a9220fc06b..46999555c52 100644 --- a/apps/docs/content/docs/meta.json +++ b/apps/docs/content/docs/meta.json @@ -11,6 +11,7 @@ "---Build---", "chat", "workflows", + "workflows/code", "agents", "---Workspace---", "knowledgebase", diff --git a/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx b/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx index 72e006b327b..4108e2c07d3 100644 --- a/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx +++ b/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx @@ -199,7 +199,7 @@ Plain JavaScript without imports runs in isolated-vm within Node child workers i | Variable | Description | |----------|-------------| -| `WORKFLOW_CODE` | Set to `true` to enable [workflows as code](/workflows/code) and [workspace as code](/workflows/workspace-code): the read-only **Code** tab in the workflow builder, and the source API and MCP operations that the `sim workflows source` and `sim workspaces source` CLI commands call. Off when unset; while off, those operations answer `403` | +| `WORKFLOW_CODE` | Set to `true` to enable [workflows as code](/workflows/code) and [workspace as code](/workflows/code/workspace): the read-only **Code** tab in the workflow builder, and the source API and MCP operations that the `sim workflows source` and `sim workspaces source` CLI commands call. Off when unset; while off, those operations answer `403` | ## Chat and PII [#chat--pii] diff --git a/apps/docs/content/docs/workflows/code.mdx b/apps/docs/content/docs/workflows/code.mdx deleted file mode 100644 index 81d14deb04d..00000000000 --- a/apps/docs/content/docs/workflows/code.mdx +++ /dev/null @@ -1,224 +0,0 @@ ---- -title: Workflows as code -description: Read and edit a workflow as one TypeScript file, check it before saving, and review changes as diffs. ---- - -import { Callout } from '@/components/ui/callout' - -Every workflow can be read and written as a TypeScript file. The file and the workflow builder show the same workflow: edit either one and the other follows. Use it to review agent changes as a diff, keep workflows in git, or let a coding agent such as Claude Code build and change them for you. - - -Workflows as code is in preview. When it is [enabled on your Sim deployment](/platform/self-hosting/environment-variables#preview-features), the workflow builder shows a read-only **Code** tab and the [CLI](/cli) gains the `sim workflows source` commands. - - -## For coding agents [#for-coding-agents] - -Claude Code, Cursor, Codex and other coding agents work from a directory that `get` writes. `get` prints a short primer (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; in JSON output, its `primer` field), and the same primer opens `.sim/AGENTS.md`, the full guide. 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. - -To write a block the workflow does not use yet, `sim workflows source params ` (for example `table.upsertRow` or `trigger.schedule`) prints its params, required ones first with their options and defaults, and its outputs, from the cached block catalog without a request. A namespace such as `gmail` lists its builders. - -For a whole workspace, use `sim workspaces source` with the same steps; see [Workspace as code](/workflows/workspace-code). - -## What the file holds - -The file states what the workflow runs: its blocks, their settings, the connections between them, branches, loops, and variables. Layout and other builder-only details stay in the stored workflow, so the file stays short and a change to one setting is a one-line diff. - -Nothing in the file runs on your machine. Sim reads it statically, checks it against your workspace, and saves it as the workflow draft. Deploying stays a separate step. - -## Edit a workflow from the CLI - -1. Write the workflow into a directory: - - ```bash - sim workflows source get --dir ./support-triage - ``` - - This writes `workflow.ts`, any function code under `functions/`, and type declarations for the blocks the workflow uses and for your workspace's tables, credentials, knowledge bases, and environment variable names, with `.sim/sdk/INDEX.md` listing those blocks' builders. The declarations of every block are generated once per block catalog into the CLI's cache (`~/.sim/cache/source-catalog/`) and shared by every directory. It also writes a `tsconfig.json` that resolves them and type-checks the blocks the workflow uses, and a `tsconfig.full.json` that type-checks every block through that cache, unless the directory already has files of those names, which are left as they are. For coding agents it writes `.sim/AGENTS.md`, the primer `get` prints followed by a reference, and example workflows under `.sim/examples/` with one correct example of each common block to copy from. The examples name placeholder resources, so the tsconfig files leave them out of the type-check. - - `get` into a directory that already holds source refuses to overwrite edits you have not applied, and refuses a directory that holds a different workflow. Pass `--force` to replace them. A workspace source directory is always refused, `--force` included (and `sim workspaces source get` refuses a workflow directory the same way). - -2. Edit `workflow.ts`, then compile it on your machine with Sim's compiler, without a request: - - ```bash - sim workflows source check --dir ./support-triage - ``` - - It exits 1 on an error, and on the warnings `sim workflows source check --help` lists (a missing required field, an unknown option, an unwired condition or router branch, a literal secret and more) in a block you added since the get (`--strict` fails on these in every block, except an unwired branch on a block the get printed, which the stored workflow may hold; `--no-strict` never fails on a warning). It also adds the blocks the workflow now uses to `tsconfig.json`. Your editor type-checks the file against the generated declarations, and `bunx -p typescript@7.0.2 tsc -p ./support-triage` checks it from the command line with the TypeScript release the declarations are built for; `-p ./support-triage/tsconfig.full.json` type-checks against every block. - -3. See what changed, and whether someone changed the workflow since your `get`: - - ```bash - sim workflows source status --dir ./support-triage - sim workflows source diff --dir ./support-triage - ``` - - `status` lists the files you created, edited, or deleted, asks the server (with a dry run that saves nothing) whether the workflow changed since the `get`, and ends with the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unsaved, and `12` when the workflow changed in the editor since the `get` (a conflict, if you edited it too). Without a connection it shows your edits only and says so; `--offline` skips the server. `diff` prints each edit as a unified diff, and `diff --server` compares the directory with the workflow as it is saved now. Both take `--json` (or `--output json`). - -4. Check the change without saving it: - - ```bash - sim workflows source apply --dir ./support-triage --dry-run - ``` - - `apply` reads the workflow ID from `.sim/base.json`. Pass it as `apply --dir …` to have the CLI confirm the directory holds that workflow. Every command that reads a source directory (`check`, `status`, `diff`, `params`, `apply`, and their `sim workspaces source` counterparts) defaults `--dir` to the current directory; `get` and `create`, which write one, always need `--dir`. - - Sim compiles the file and runs every check a save would run: unknown settings, missing required fields, broken references, permissions, and locked blocks. Each problem prints with its line, the code around it, and a hint: - - ``` - workflow.ts:56:7 error E_UNKNOWN_PARAM: Slack has no param chanel. - 54 | const notify = slack.sendMessage('Notify', { - 55 | credential: credential('support-slack'), - > 56 | chanel: 'C0SUPPORT', - | ^^^^^^^^^^^^^^^^^^^ - 57 | text: t`New ${classify.category} ticket: ${ticketIn.subject}`, - hint: Did you mean channel? - ``` - -5. Save the draft: - - ```bash - sim workflows source apply --dir ./support-triage --yes - ``` - - The workflow builder updates for anyone who has the workflow open. Deploy when you are ready, or add `--deploy` to deploy right after the save, which also prints the URL of each webhook the workflow now serves; without it, a deployed workflow whose draft now differs prints the `sim workflows deploy` command to run. `--yes` refuses everything a dry run would, so step 4 is optional: without `--yes`, and with no terminal to ask, `apply` prints the plan, writes nothing and exits `14`. The save rewrites `workflow.ts` in canonical form, so read it again before the next edit. - - Editing the name or description in `workflow('…')` renames or redescribes the workflow; a name another workflow in its folder already has is refused with `E_NAME_TAKEN`. Lines starting with `note:` report something the save did beyond what the file says; read them. - - A save that removes a block (its declaration is gone from `workflow.ts`) is refused with `E_APPLY_BLOCK_DELETE`, naming the blocks, and one that removes a workflow variable with `E_APPLY_VARIABLE_DELETE`. Pass `--allow-delete` when the deletion is intended. - -To create a new workflow, run `sim workflows source create --dir --workspace ` on an empty directory: without `--dry-run` or `--yes` it creates nothing and writes a starter `workflow.ts` with that workspace's type declarations, `tsconfig.json` and `.sim/AGENTS.md`, and records the workspace in `.sim/starter.json`. Edit the starter, check it, then run `sim workflows source create --dir --workspace --dry-run` and `--yes` (the starter prints both). A create goes to the starter's workspace whatever your default workspace, unless `--workspace` names another. Until the workflow is created the directory has no `.sim/base.json`, so `status`, `diff` and `apply` refuse it. The file starts with the `// @sim-sdk 1` line and default-exports one `workflow('Name', {}, () => { ... })`. The command prints the new workflow ID and writes the same type declarations, `tsconfig.json`, and `.sim/` files that `get` writes, so you can continue editing with `apply`. If another workflow already has that name, the command exits `1`; pass `--name` to choose another. - -Keep the `.sim/` folder the commands write. `.sim/lock.json` ties each block in the file to the stored block, so renaming a block keeps the same block, with its webhook URL, schedules and run history. Changing its name string keeps it through the lock; renaming the variable too keeps it when the block's type, parent and connections are unchanged, and the dry run reports that as `W_MAT_INFERRED_RENAME`. Renaming two blocks of the same type in the same place in one save is ambiguous, so do those one save at a time. `.sim/base.json` records the version you read. - -## Example: support triage - -A webhook receives a ticket, an agent classifies it, billing tickets are logged to a table, and the team hears about every ticket in Slack. This is the file `sim workflows source get` prints for it: - -```ts title="workflow.ts" -// @sim-sdk 1 -import { - agent, - condition, - credential, - env, - js, - slack, - t, - table, - trigger, - workflow, -} from '@sim/workflow-sdk' - -export default workflow( - 'Support triage', - { variables: { escalations: { type: 'number', value: 0 } } }, - () => { - const ticketIn = trigger.webhook('Ticket in', { - requireAuth: true, - token: env.TICKETS_WEBHOOK_TOKEN, - inputFormat: { subject: 'string', body: 'string', contacts: 'array' }, - responseMode: 'custom', - responseStatusCode: 202, - responseBody: { ok: true }, - }) - const classify = agent('Classify', { - messages: [ - { role: 'system', content: 'Classify support tickets.' }, - { - role: 'user', - content: t`${ticketIn.subject} - -${ticketIn.body}`, - }, - ], - model: 'claude-sonnet-5-5', - responseFormat: { - name: 'ticket', - strict: true, - schema: { - type: 'object', - additionalProperties: false, - required: ['category', 'urgent'], - properties: { - category: { type: 'string', enum: ['billing', 'bug', 'other'] }, - urgent: { type: 'boolean' }, - }, - }, - }, - }) - const byCategory = condition('By category', { - billing: js`${classify.category} === 'billing'`, - else: true, - }) - const logTicket = table.insertRow('Log ticket', { - tableId: table('tickets'), - data: { subject: ticketIn.subject, category: classify.category }, - }) - const notify = slack.sendMessage('Notify', { - credential: credential('support-slack'), - channel: 'C0SUPPORT', - text: t`New ${classify.category} ticket (urgent: ${classify.urgent}): ${ticketIn.subject}`, - }) - - ticketIn.to(classify) - classify.to(byCategory) - byCategory.billing.to(logTicket) - byCategory.else.to(notify) - logTicket.to(notify) - logTicket.onError(notify) - } -) -``` - -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. -- `.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. - -## Function code - -Code that does not fit a block goes in a Function block, kept in its own file: - -```ts -const score = fn('Score lead', { code: codeFile('./functions/score-lead.js') }) -``` - -In the file, `$ref.block.path` reads another block's output and `$env.NAME` reads an environment variable. `block` is the block's key: its name lowercased with all whitespace and every `.` removed (`$ref.triageagent.content` for "Triage Agent", `$ref.v2result.text` for "V2. Result"). Inside a loop body, `$ref.loop.currentItem` and `$ref.loop.index` read the iteration's item and position; inside a parallel body, `$ref.parallel.currentItem` and `$ref.parallel.index`. A `$ref` that names no block is refused in a file you edited, because it would not resolve when the workflow runs. Python and shell files are saved as written, so `$ref` and `$env` mean nothing there: read an output as `` (``) and an environment variable as `{{NAME}}`. - -## Use it in CI - -Run `sim workflows source apply --dir --dry-run` in CI to catch a broken workflow before it is saved. It exits `0` when the workflow is valid and `1` when it has errors, so a failing check blocks the merge. It exits `5` when the workflow was changed in the editor after you committed the directory; run `get` again and reapply your edit. - -- **Commit** `workflow.ts`, `functions/`, `.sim/lock.json`, `.sim/base.json`, `.sim/written.json`, `tsconfig.json` and `.gitattributes`. CI finds the workflow from `workflowId` in `.sim/base.json`, and `status` and `get` use `.sim/written.json` to tell your edits apart from what the CLI last wrote. -- **Optionally gitignore** `.sim/sdk/`, the generated type declarations of the blocks in use (a few dozen files); `get` and `check` write them again. Gitignore `tsconfig.full.json`, which names the CLI's cache on your machine; `check` writes it again. A single-workflow directory gets no `.gitignore`, so add the lines yourself. -- **A whole workspace** in one repository, with dry runs on pull requests, apply on merge and promotion from one workspace to another, is covered in [Git and CI](/workflows/workspace-code#git-and-ci) and [Promote to another workspace](/workflows/workspace-code#promote-to-another-workspace). -- **Git provenance:** in a git repository, `apply` and `create` send the commit checked out (`HEAD`) and the `origin` remote URL, with any credentials, query or fragment removed, as `provenance.gitSha` and `provenance.repo`, each only when `git` can read it (a repository with no `origin` sends only the commit). A saved write records what was sent in its [audit log](/platform/enterprise/audit-logs) entry (`workflow.updated` or `workflow.created`). A directory outside a repository sends neither. -- **Credentials:** use a personal API key (**Settings → Sim API keys**, passed as `SIM_API_KEY`) or an OAuth login, not a workspace API key. Saving and dry-running source act as a person, so a workspace key is refused with `403`. Set `SIM_WORKSPACE` unless you pass `--workspace`, and `SIM_ENDPOINT` if you use a self-hosted Sim. See [Authenticating CI](/cli/authentication#authenticating-ci). - -## Working with other people - -- If someone changes the workflow after you read it, the save (or `--dry-run`) is refused with exit code `5` and nothing is overwritten. Run `get` into a new directory, reapply your edit, and save. -- Locked blocks cannot be changed from the file. Unlock them in the workflow builder first. -- Removing a block that serves a live webhook, schedule, chat, or MCP tool warns you: the deployed version keeps serving it until the next deploy. - -## Limits and known gaps - -- The file holds block declarations and connections only. Helper functions, loops that create blocks, and imports are refused; use Loop, Condition, and Workflow blocks instead. -- Function code is one file per block, with no imports between files. -- A change anyone makes while you edit means reading the workflow again; there is no automatic merge. -- Workflows run in Sim, not locally. `--dry-run` checks everything a save checks, without running the workflow. -- A workflow can have up to 2,000 blocks and 2,000 variables, and its source up to 4 MB across `workflow.ts` and its function files together. A larger workflow is refused when you read or save it, and the CLI exits with code `7`. - -To keep the tables, knowledge bases, tools and skills a workflow uses in the same directory, see [Workspace as code](/workflows/workspace-code). - -See [CLI workflow commands](/cli/workflows) for every flag. diff --git a/apps/docs/content/docs/workflows/code/ci.mdx b/apps/docs/content/docs/workflows/code/ci.mdx new file mode 100644 index 00000000000..0f13dd25415 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/ci.mdx @@ -0,0 +1,184 @@ +--- +title: Run in CI +description: Dry-run source on pull requests, apply on merge, comment the plan, detect drift on a schedule, and promote, with GitHub Actions recipes. +--- + +Result: a pull request that shows what an apply would change, an apply on merge, and a scheduled check that tells you when someone edited the workspace in Sim. + +## Credentials + +Saving and dry-running source act as a person. Use a personal API key (**Settings → Sim API keys**, passed as `SIM_API_KEY`) or an OAuth login. A workspace API key is refused with `403` for workflows, and for a workspace directory it can apply only the kinds it can write; see [Workspace API keys](/workflows/code/workspace#workspace-api-keys). Set `SIM_WORKSPACE` unless you pass `--workspace`, and `SIM_ENDPOINT` if you use a self-hosted Sim. See [Authenticating CI](/cli/authentication#authenticating-ci). + +## What to commit + +- **A workflow directory:** commit `workflow.ts`, `functions/`, `.sim/lock.json`, `.sim/base.json`, `.sim/written.json`, `.sim/stored-edges.json`, `tsconfig.json` and `.gitattributes`. CI finds the workflow from `workflowId` in `.sim/base.json`, and `status` and `get` use `.sim/written.json` to tell your edits apart from what the CLI last wrote. Gitignore `tsconfig.full.json`; `.sim/sdk/` is optional. +- **A workspace directory:** commit everything, including `.sim/`. Its generated `.gitignore` leaves out only temporary files. + +[Directory layout](/workflows/code/directory) lists every file. + +## One workflow + +Run `sim workflows source apply --dir --dry-run` on pull requests. It exits `0` when the workflow is valid, `1` when it has errors, and `5` when the workflow was changed in the workflow builder after you committed the directory, so a failing check blocks the merge. `check` is not needed: the dry run runs every check a save runs, and `check` fails on a fresh runner that has no cached block catalog. + +```yaml title=".github/workflows/sim-workflow.yml" +on: + pull_request: + paths: ['support-triage/**'] + +permissions: + contents: read + +jobs: + dry-run: + runs-on: ubuntu-latest + env: + SIM_API_KEY: ${{ secrets.SIM_API_KEY }} + SIM_WORKSPACE: ${{ vars.SIM_WORKSPACE }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + - uses: oven-sh/setup-bun@v2 + - run: bun add -g sim + - run: sim workflows source apply --dir support-triage --dry-run +``` + +## A workspace + +Keep a [workspace directory](/workflows/code/workspace) in a repository, `.sim/` included, and let CI plan each pull request and apply each merge. The dry run exits `1` on errors, `5` when the workspace changed since the committed base, and `15` when the apply would hold back changes that use a secret with no value or a credential nothing binds to. `check` downloads the block catalog once on a fresh runner. On GitHub Actions (`GITHUB_ACTIONS=true`), every source command also annotates each error and warning at its file and line, so they show inline on the pull request, and a workspace `apply` (a dry run too) appends its plan and errors to the job's step summary. + +```yaml title=".github/workflows/sim-workspace.yml" +on: + pull_request: + paths: ['workspace/**'] + push: + branches: [main] + paths: ['workspace/**'] + +concurrency: sim-workspace + +permissions: + contents: write + +jobs: + workspace: + runs-on: ubuntu-latest + env: + SIM_API_KEY: ${{ secrets.SIM_API_KEY }} + SIM_WORKSPACE: ${{ vars.SIM_WORKSPACE }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + - uses: oven-sh/setup-bun@v2 + - run: bun add -g sim + - run: sim workspaces source check --dir workspace + - run: bunx -p typescript@7.0.2 tsc -p workspace + - run: sim workspaces source apply --dir workspace --dry-run + - if: github.event_name == 'push' + run: sim workspaces source apply --dir workspace --yes + - if: ${{ !cancelled() && github.event_name == 'push' }} + run: | + git add -A workspace + if ! git diff --cached --quiet; then + git -c user.name=sim-bot -c user.email=sim-bot@users.noreply.github.com \ + commit -m "chore(workspace): files the apply rewrote [skip ci]" + git push + fi +``` + +`check` runs first because it is offline and fast, and it regenerates `.sim/sdk/workspace.d.ts`, so the `tsc` step after it types resources the pull request adds. Apply rewrites files under the directory (each `.sim/base.json`, ids it allocated, values the server normalized), and the next apply compares with them, so the last step commits them back to the branch; `[skip ci]` keeps that commit from running the job again. That step runs even when the apply failed (`!cancelled()`), because an apply can fail having written part of its plan: exit `15` means it held back changes that use a secret with no value or a credential nothing binds to and applied the rest, and exit `8` means it stopped part-way. Either way the directory records what was written, so committing it keeps the next run from being refused as stale (exit `5`) for resources this run wrote; the job still fails, so set the secret, connect the credential or fix the failure, and push again. Where the branch is protected, run `sim workspaces source get --dir workspace` on a new branch instead and open a pull request. + +After merging two branches that each applied, a dry run with no changes means the files match the workspace. Exit `5` means a resource changed since this branch's base: get the workspace into a fresh directory and carry the edit over. Exit `10` means another apply is writing the workspace (or another command is using the directory), so retry; the `concurrency` key keeps two runs of this job from overlapping. Pull requests from forks do not receive repository secrets, so the dry run needs a branch in the same repository. + +### Comment the plan on the pull request + +The step summary appears on the run page, not in the pull request. To post the plan as one comment that later pushes edit instead of adding another, copy the summary file in the same step that runs the dry run, with `pull-requests: write` in `permissions`: + +```yaml + - if: github.event_name == 'pull_request' + env: + GH_TOKEN: ${{ github.token }} + run: | + status=0 + sim workspaces source apply --dir workspace --dry-run || status=$? + gh pr comment "${{ github.event.pull_request.number }}" --edit-last --create-if-none --body-file "$GITHUB_STEP_SUMMARY" + exit "$status" +``` + +Use this step in place of the plain dry-run step for pull requests. The comment lists the first 50 changes and errors and counts the rest. `--edit-last` edits the last comment from the same account, which is the Actions bot here, so do not post other comments from this token on the pull request. + +### Detect drift on a schedule + +A change made in Sim, such as a hotfix in the workflow builder, makes the next apply exit `5`. A scheduled job finds it first: `status` exits `12` when the server changed since the directory was read, and `11` when the committed directory holds edits no apply has saved, for example after a merge whose apply failed. + +```yaml title=".github/workflows/sim-drift.yml" +on: + schedule: + - cron: '17 6 * * 1-5' + workflow_dispatch: + +permissions: + contents: read + issues: write + +jobs: + drift: + runs-on: ubuntu-latest + env: + SIM_API_KEY: ${{ secrets.SIM_API_KEY }} + SIM_WORKSPACE: ${{ vars.SIM_WORKSPACE }} + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + - uses: oven-sh/setup-bun@v2 + - run: bun add -g sim + - run: | + status=0 + sim workspaces source status --dir workspace --output json > status.json || status=$? + if [ "$status" -eq 0 ] || [ "$status" -eq 11 ] || [ "$status" -eq 12 ]; then + [ "$(jq -r .server status.json)" = checked ] || { echo "Sim was not checked: $(jq -r .note status.json)"; exit 1; } + fi + case "$status" in + 0) exit 0 ;; + 11|12) ;; + *) exit "$status" ;; + esac + run_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + body="sim workspaces source status exited $status ($run_url). Run it locally for the changes and the next command." + gh label create sim-drift --force + number=$(gh issue list --label sim-drift --state open --json number --jq '.[0].number // empty') + if [ -n "$number" ]; then + gh issue comment "$number" --body "$body" + else + gh issue create --label sim-drift --title "Sim workspace drift" --body "$body" + fi +``` + +`status` exits `0` or `11` without asking Sim when the server is unreachable, so the job reads the `server` field of its JSON output and fails unless it is `checked`. To bring the change into git instead, run `sim workspaces source get --dir workspace` on a new branch and open a pull request. + +### Promote in CI + +To promote the same directory to a second workspace, add a step with `--to` before the step that commits the files back: + +```bash +sim workspaces source apply --dir workspace --to "$PROD_WORKSPACE_ID" --yes +``` + +The promotion writes `workspace/.sim/targets/.json`, what it left in that workspace. Committing it lets the next run tell a change made in that workspace since (kept, or exit `5` when the directory changed the same resource) from one to promote. See [Promote to another workspace](/workflows/code/promote). + +## Git provenance + +In a git repository, `apply` and `create` send the commit checked out (`HEAD`) and the `origin` remote URL, with any credentials, query or fragment removed, as `provenance.gitSha` and `provenance.repo`, each only when `git` can read it (a repository with no `origin` sends only the commit). A saved write records what was sent in its [audit log](/platform/enterprise/audit-logs) entry (`workflow.updated` or `workflow.created` for a workflow, `workspace.updated` for a workspace apply). A directory outside a repository sends neither. + +## Related docs + +- [Exit codes](/workflows/code/exit-codes) +- [Promote to another workspace](/workflows/code/promote) +- [Scripting](/cli/scripting) +- [Authenticating CI](/cli/authentication#authenticating-ci) diff --git a/apps/docs/content/docs/workflows/code/coding-agents.mdx b/apps/docs/content/docs/workflows/code/coding-agents.mdx new file mode 100644 index 00000000000..77dd28d4c37 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/coding-agents.mdx @@ -0,0 +1,45 @@ +--- +title: Use with coding agents +description: What get gives a coding agent, how it edits and saves a workflow, and the MCP and API paths for the same operations. +--- + +Claude Code, Cursor, Codex and other coding agents work from a directory that `get` writes. + +## What get gives an agent + +- A **primer**: `get` prints it (in JSON output, its `primer` field), and it opens `.sim/AGENTS.md`. 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. + +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. + +For a whole workspace, use `sim workspaces source` with the same steps; see [Manage a workspace as code](/workflows/code/workspace). + +## Look things up + +- `sim workflows source params ` prints a builder's params and outputs from the cached block catalog without a request. A namespace such as `gmail` lists its builders. +- `sim workflows source resources` lists the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and environment variable names the file can name. +- `sim workflows source catalog` shows the block catalog the source is checked against. + +## Exit codes and retries + +An agent can branch on the exit code: `5` means the workflow changed and it must `get` into a fresh directory, `14` means it forgot `--yes`, and `9` means wait a minute. See [Exit codes](/workflows/code/exit-codes). + +## Over MCP and the API + +`getWorkflowSource` returns a workflow as TypeScript source files with its `lock` and `base`. Edit the files and send them back, with the same `lock` and `base`, through `applyWorkflowSource`, first with `query: {"dryRun": true}`. One call replaces a batch of graph operations. See [MCP tools](/mcp/tools#workflow-source) and [Build and run workflows](/api-reference/build-and-run-workflows). + +## Related docs + +- [Edit a workflow](/workflows/code/edit) +- [File syntax](/workflows/code/syntax) +- [Directory layout](/workflows/code/directory) diff --git a/apps/docs/content/docs/workflows/code/create.mdx b/apps/docs/content/docs/workflows/code/create.mdx new file mode 100644 index 00000000000..eb571abb483 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/create.mdx @@ -0,0 +1,45 @@ +--- +title: Create a workflow +description: Start a new workflow from a starter file, check it, and create it from a directory. +--- + +Result: a new workflow created from a file, in the workspace you choose. + +## Steps + +1. Write a starter into an empty directory: + + ```bash + sim workflows source create --dir ./lead-intake --workspace + ``` + + Without `--dry-run` or `--yes` this creates nothing. It writes a starter `workflow.ts` with that workspace's type declarations, `tsconfig.json` and `.sim/AGENTS.md`, and records the workspace in `.sim/starter.json`. The file starts with the `// @sim-sdk 1` line and default-exports one `workflow('Name', {}, () => { ... })`. + +2. Edit the starter and check it as in [Edit a workflow](/workflows/code/edit). + +3. Create the workflow: + + ```bash + sim workflows source create --dir ./lead-intake --workspace --dry-run + sim workflows source create --dir ./lead-intake --workspace --yes + ``` + + The starter prints both commands with its workspace filled in. The command prints the new workflow ID and writes the same type declarations, `tsconfig.json`, and `.sim/` files that `get` writes, so you can continue editing with `apply`. + +A create goes to the starter's workspace whatever your default workspace, unless `--workspace` names another. Until the workflow is created the directory has no `.sim/base.json`, so `status`, `diff` and `apply` refuse it. + +If another workflow already has that name, the command exits `1` with `SOURCE_NAME_TAKEN`; pass `--name` to choose another. Without `--yes` and with no terminal to ask, `create` prints the plan, writes nothing and exits `14`. + +## Fork a workflow + +Copy its directory, delete the copy's `.sim/`, and create it under a new name. A copy has no stored workflow to take a saved secret from, so replace each `stored()` in the file, which `get` printed for a value it does not show, with `env.NAME` or the value; otherwise the create fails with `E_STORED_VALUE_MISSING`. + +```bash +sim workflows source create --dir ./copy --workspace --name "New name" --yes +``` + +## Related docs + +- [Get started](/workflows/code/get-started) +- [Edit a workflow](/workflows/code/edit) +- [Exit codes](/workflows/code/exit-codes) diff --git a/apps/docs/content/docs/workflows/code/diagnostics.mdx b/apps/docs/content/docs/workflows/code/diagnostics.mdx new file mode 100644 index 00000000000..554a7a9a0f7 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/diagnostics.mdx @@ -0,0 +1,371 @@ +--- +title: Diagnostic codes +description: Every error, warning and info code that workflow and workspace source report, grouped by where it comes from. +--- + +Every finding that `check`, `status` and `apply` print has a code. The first letter is its severity: `E_` is an error, `W_` a warning and `I_` information. An error refuses the apply and makes `check` exit `1`. A warning is reported and the apply saves the source as written, except where a row below says the apply refuses it as the matching `E_APPLY_…` error. Information never blocks anything. + +A finding prints as `file:line:column` with the code around it and a hint; in `--output json` it is an entry of `diagnostics` (see [Scripting](/cli/scripting#exit-codes) for the shape). The codes are frozen at release, so a script can match on them. + +{/* workflow-code-docs:diagnostics:begin — generated by `bun run generate:workflow-code-docs`; do not edit between markers */} + +### Workflow source + +#### Compile and print + +Reading and writing `workflow.ts`. + +| Code | Meaning | +| --- | --- | +| `E_SYNTAX` | Babel could not parse the file. | +| `E_INVALID_CHARACTER` | A NUL or an unpaired UTF-16 surrogate, raw or escaped in a string, in the file or a code file: a workflow cannot store either. | +| `E_NUMBER_NOT_FINITE` | A number literal too large to store (`1e999` reads as `Infinity`). | +| `W_NUMBER_PRECISION` | A number literal whose digits a number cannot hold; write it as a string. | +| `E_SDK_HEADER` | Line 1 is not `// @sim-sdk N`. | +| `E_SDK_MAJOR` | The header's major is newer than the server supports. | +| `E_SDK_MAJOR_OLD` | The header's major is older than the oldest the server reads. | +| `E_UNSUPPORTED_SYNTAX` | A construct outside this grammar; the hint names the supported form. | +| `E_WORKFLOW_EXPORT` | Not exactly one `export default workflow(…)`. | +| `E_LIMIT_EXCEEDED` | Over the block, edge, total-byte, depth or `codeFile()` reference cap (`SOURCE_LIMITS`). Apply answers 413. | +| `E_TOO_MANY_ERRORS` | The compile stopped after 100 errors; fix those and compile again to see the rest. | +| `I_FINDINGS_TRUNCATED` | 100 warnings, or 20 of one code, were listed and the rest omitted, so a flood of one finding never hides another. A finding repeated at the same place is listed once. Infos are capped apart (100, the rest dropped), so they never displace a warning, and errors are never displaced by either. An answer that merges findings from several stages is capped the same way as a whole; when that cuts it, it ends in one `I_FINDINGS_TRUNCATED` counting what it left out, in place of the stages' own. | +| `E_DUPLICATE_NAME` | Two blocks normalize to one key. | +| `E_RESERVED_NAME` | A block name normalizes to `loop`, `parallel` or `variable`. | +| `E_KEY_OVERRIDE` | A `meta.key` that is not a legacy key the stored workflow already has. | +| `E_EMPTY_NAME` | An empty block name. | +| `E_NAME_NOT_LITERAL` | A block or workflow name that is not a string literal. | +| `E_LOOKALIKE_NAME` | Two block names whose keys differ only by Unicode normalization (NFC vs NFD), or a block name with a word that mixes Latin letters with Cyrillic, Greek, Armenian or Cherokee ones (`Сlaude`); the message names the code point. | +| `W_LOOKALIKE_NAME` | A look-alike pair the stored workflow already holds, kept so it round-trips. | +| `W_SUSPICIOUS_CHARACTER` | A block or workflow name holds a bidi control or zero-width character. | +| `E_UNKNOWN_IDENTIFIER` | An identifier that names nothing in scope; the hint has a did-you-mean, says to write the value for a const refused for holding one, and points `process.env` at `env.NAME`. | +| `E_OUT_OF_SCOPE` | A ref or wiring into a sibling subflow's child. | +| `E_UNKNOWN_VARIABLE` | `vars.x` names no declared variable. | +| `E_DUPLICATE_VARIABLE` | Two variables with one key. | +| `E_VARIABLE_NAME_MISMATCH` | A variable's `name` does not normalize to its key. | +| `E_INVALID_ENV_NAME` | `env.X` with an invalid name. | +| `W_ENV_UNKNOWN` | `env.X`, or a code file `$env`, naming a variable the workspace does not hold (checked only when the env names are known); the hint has a did-you-mean. An offline check in a workspace directory knows only the names `secrets.ts` declares, so there the finding says `secrets.ts` does not declare it, and the hint points there. | +| `W_CHILD_INPUT_UNKNOWN` | A child workflow call's `inputMapping` sets an input the child's Start trigger does not declare (`sim workspaces source check`, with the child in the same directory); the hint names the nearest input. | +| `W_CHILD_NO_START` | A child workflow call names a workflow of the same directory that has no Start trigger (`sim workspaces source check`). | +| `W_CHILD_RESULT_PATH` | A reference to a child workflow call's `result.` whose child (in the same directory) ends at a Response block on every run, where `` is not `data`, `status` or `headers`: the child's result is its Response output, so the path reads nothing (`sim workspaces source check`); the hint names `result.data.`. The dry run reports the same reference as a `W_APPLY_LINT` warning. | +| `E_UNKNOWN_SUBFLOW_PROPERTY` | `p.` that a loop or parallel does not have. | +| `W_FORWARD_REF` | A ref to a block declared later; it resolves. | +| `W_REF_NOT_NORMALIZED` | Hand-written `` text that is not in key form. | +| `E_REF_UNREPRESENTABLE` | A reference to a block whose key holds a character a reference cannot carry (`Q&A`, `x>y`); rename the block. | +| `E_EDGE_SCOPE` | An edge across subflow scopes. | +| `E_EDGE_NOTE` | An edge to or from a note. | +| `E_TARGET_TRIGGER` | An edge into a trigger. | +| `E_NO_DEFAULT_OUTPUT` | `.to()` on a condition or router; wire a branch. | +| `E_DUPLICATE_EDGE` | The same edge twice. | +| `E_ERROR_PORT_UNSUPPORTED` | `onError` on a block with no error port. | +| `W_ERROR_PORT_STORED` | `onError` on a block with no error port (a loop or parallel) that the stored workflow already wires; kept so it round-trips. An offline check, which cannot read the stored workflow, reports it for any such edge between two blocks the lock binds: an apply keeps it only if the stored workflow holds it. | +| `E_UNKNOWN_BRANCH` | `x.key.to()` where `key` is not a branch of `x`. | +| `E_DUPLICATE_BRANCH_KEY` | Two rows with one key. | +| `E_BRANCH_KEY_COLLIDES` | A branch key equal to an output name, `to` or `onError`. | +| `E_BRANCH_ELSE_LAST` | Two or more condition rows that do not end with `else`. | +| `W_RAW_HANDLE` | `edge()` with a handle kept verbatim. | +| `W_SUBFLOW_HANDLE_SCOPE` | `edge()` from a loop or parallel's start handle to a block outside it (the executor runs it as the container's exit), or from another of its handles into its own child. The canvas never draws one; stored ones print this way so they round-trip. | +| `E_EDGE_CYCLE` | Wiring that closes a cycle among enabled blocks, a self-loop included: no block on it ever runs. Framed at the edge back to a block declared earlier, the one to remove; repeat work with `loop()`/`parallel()`. | +| `W_EDGE_CYCLE` | A cycle the stored workflow already holds, kept so it round-trips; none of it runs. An offline check reports it for a cycle among blocks the lock binds, which an apply keeps only if the stored workflow holds every edge of it. | +| `W_BRANCH_UNWIRED` | A condition or router branch no edge leaves, so a run that takes it ends there; the hint names the wiring. Not reported for a branch the stored workflow already leaves unwired. | +| `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_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`. | +| `W_UNKNOWN_MODEL` | A `model` the catalog does not list (kept: custom models are free text). | +| `W_LEGACY_BLOCK_TYPE` | A new block of a legacy or deprecated type; `hint` names the replacement's builders. | +| `I_SCHEDULE_UTC` | A schedule created from source with no `timezone`, which runs in UTC (the editor would have seeded the viewer's zone). | +| `E_STORED_VALUE_MISSING` | `stored()` where the stored workflow holds no value. | +| `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_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. | +| `W_JSON_REF_UNTYPED` | A bare ref in a JSON literal whose type nothing declares. | +| `W_LOOP_CONDITION_SYNTAX` | A while or do-while condition that is not a JavaScript expression once each reference stands in as a value, as the run evaluates it (`return Boolean()`): the run fails there. Refused as `E_APPLY_LOOP_CONDITION_SYNTAX` on a loop the edit added or changed. A loop reading its own `index` (or `currentItem`, `items`) by its name in its condition is `W_REF_OUT_OF_SCOPE`: the condition is evaluated outside the loop's body, so only `` reads the iteration there. | +| `W_REF_OUT_OF_SCOPE` | A loop or parallel iteration field (`index`, `currentItem`, `items`) read from a block outside that container: `lp.index` after the loop, `$ref.loop.index` or `` in a block in no loop. The run fails (or reads nothing) there. Refused as `E_APPLY_REF_OUT_OF_SCOPE` on a block the edit changed. | +| `W_UNKNOWN_BLOCK_TYPE` | A new block of a type the catalog does not hold; refused as `E_APPLY_INVALID_BLOCK_TYPE`. A block the stored workflow or the lock already holds keeps its type quietly. | +| `W_TYPE_NOT_ADDABLE` | A new block of a type the catalog keeps only for blocks already using it; refused as `E_APPLY_TYPE_NOT_ADDABLE`. | +| `E_CODE_FILE_MISSING` | `codeFile()` names a file the request did not send. | +| `E_CODE_FILE_PATH` | A code file path outside the directory, or with the wrong extension. | +| `W_CODE_FILE_INLINED` | Print: the code could not round-trip through a file and was inlined. | +| `W_CODE_FILE_REF_SYNTAX` | `$ref.key.path` or `$env.NAME` in a Python or shell code file, which runs as text; the hint names the `` or `{{NAME}}` form. Refused as `E_APPLY_CODE_FILE_REF_SYNTAX` in a file the edit changed. | +| `W_UNRESOLVED_REF` | Print: a stored `` token that resolves to nothing. Compile: a code file `$ref` chain that does. Either is kept as text. | +| `W_FORWARD_REF_LITERALIZED` | Print: a ref in a cycle printed as text. | +| `W_COMMENT_MOVED` | A comment hoisted to the nearest anchor. | +| `W_COMMENT_DROPPED` | A comment whose block no longer exists. | + +#### Lock and source meta + +Reading `.sim/lock.json`. Each finding names a JSON `path`. + +| Code | Meaning | +| --- | --- | +| `E_LOCK_JSON`, `E_SOURCE_META_JSON` | Not valid JSON. | +| `E_LOCK_VERSION`, `E_SOURCE_META_VERSION` | `version` missing or not `1`. | +| `E_LOCK_SHAPE`, `E_SOURCE_META_SHAPE` | A required field missing or of the wrong type or format. | +| `E_LOCK_UNKNOWN_FIELD`, `E_SOURCE_META_UNKNOWN_FIELD` | A field the schema does not define (`x-` keys are allowed). | +| `E_LOCK_KEY` | A block or variable key not in normalized form. | +| `E_LOCK_IDENT`, `E_SOURCE_META_IDENT` | An ident that is not a JS identifier, or is reserved. | +| `E_LOCK_DUPLICATE_IDENT`, `E_SOURCE_META_DUPLICATE_IDENT` | Two blocks with one ident. | +| `E_LOCK_DUPLICATE_ID` | One block, variable or branch id under two keys. | +| `E_LOCK_PARENT` | A parent naming no block, itself, or forming a cycle. | +| `E_LOCK_BRANCH` | A branch key that is not a JS identifier. | +| `E_LOCK_CODE_FILE_PATH` | A `codeFile` that is absolute, escapes the directory, or uses backslashes. | +| `E_SOURCE_META_ANCHOR` | A comment key that is not a valid anchor. | + +#### Canonicalize + +Reading the stored workflow in a get. + +| Code | Meaning | +| --- | --- | +| `E_CANON_LEGACY_NAME_COLLISION` | Two stored names normalize alike; the loser is keyed `key~n`. | +| `E_CANON_EDGE_SCOPE` | A stored edge crosses subflow scopes. | +| `W_CANON_RESERVED_NAME` | A stored name normalizes to a reserved key. | +| `W_CANON_DANGLING_EDGE` | A stored edge to a missing block; dropped. | +| `W_CANON_DANGLING_PARENT` | A parent that does not exist; the block is placed at the root and the raw parent kept. | +| `W_CANON_RAW_HANDLE` | An unknown edge handle, kept as a raw port. | +| `W_CANON_UNKNOWN_BLOCK_TYPE` | A type the catalog does not have; params kept. | +| `W_CANON_UNRESOLVED_ID` | A resource id with no key; kept verbatim. | +| `W_CANON_TITLE_OVERRIDE` | A branch title that differs from its positional title. | +| `W_CANON_SUBFLOW_REPAIRED` | A loop or parallel config the loader would repair. | +| `W_CANON_SUBBLOCK_TYPE_DRIFT` | A stored subBlock type differs from the catalog's. | +| `W_CANON_UNDECODABLE_JSON` | A stored JSON-text field that does not parse, kept as text; or a branch list that is not rows with distinct ids, kept verbatim. | + +#### Materialize + +Matching the compiled file to the stored blocks. + +| Code | Meaning | +| --- | --- | +| `E_MAT_DUPLICATE_LOCK_ID` | Two lock keys carry one block id. | +| `E_MAT_UNKNOWN_RESOURCE` | A resource key with no live resource in this workspace. | +| `E_MAT_UNKNOWN_VARIABLE` | A `vars.x` reference to a variable the workflow does not declare. | +| `W_MAT_DELETED_SINCE_PULL` | A lock entry whose block was deleted since the read; re-created. | +| `W_MAT_INFERRED_RENAME` | A rename inferred from type, parent and edges (the key and the ident both changed). | +| `W_MAT_RETYPE_RECREATED` | A key kept with a new type: delete plus create, so webhook URLs and schedules change. | +| `W_MAT_LOCK_ID_CLAIMED` | A lock id another workflow holds, ignored: the block binds to the stored block it matches, or gets a new id. | +| `I_MAT_NEEDS_LAYOUT` | A new block with no position, or one moved into or out of a loop or parallel; placed by autolayout. | + +#### Apply + +Saving the workflow draft. + +| Code | Meaning | +| --- | --- | +| `E_APPLY_STALE` | The workflow changed since the source was read (HTTP 409). | +| `E_APPLY_WORKFLOW_MISMATCH` | `base.workflowId` names another workflow (HTTP 400). | +| `E_APPLY_LOCKED_BLOCK` | The change touches a locked block or a child of a locked container. | +| `E_APPLY_TYPE_NOT_ADDABLE` | A new block of a type that may stay but not be added. | +| `E_APPLY_INVALID_STATE` | The resulting graph fails validation. | +| `E_APPLY_BLOCK_NOT_FOUND`, `E_APPLY_INVALID_BLOCK_TYPE` | A block or type the engine cannot place. | +| `E_APPLY_BLOCK_NOT_ALLOWED`, `E_APPLY_MODEL_NOT_ALLOWED`, `E_APPLY_TOOL_NOT_ALLOWED` | Refused by the workspace's permission group. | +| `E_APPLY_INVALID_EDGE_SOURCE`, `E_APPLY_INVALID_EDGE_SCOPE`, `E_APPLY_INVALID_SOURCE_HANDLE`, `E_APPLY_INVALID_TARGET_HANDLE` | An edge the engine refuses. | +| `E_APPLY_INVALID_SUBBLOCK_FIELD`, `E_APPLY_MISSING_REQUIRED_PARAMS` | A field the engine refuses, or required params missing. | +| `E_APPLY_RETRY_NOT_SUPPORTED` | A new or changed retry policy on a block that always runs once (triggers, human-in-the-loop, containers). | +| `E_APPLY_DUPLICATE_TRIGGER`, `E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK` | A second trigger or single-instance block. | +| `E_APPLY_DISABLED_ANCESTOR` | An enabled block inside a disabled container. | +| `E_APPLY_CREDENTIAL_UNREACHABLE` | A credential the acting user cannot use. | +| `W_APPLY_CREDENTIAL_KEPT` | A credential key the caller cannot resolve stands where the workflow stores a credential the caller cannot see; the stored one is kept, whatever the key. | +| `E_APPLY_SANDBOX_PLAN_REQUIRED` | The sandbox needs a plan the workspace does not have. | +| `W_APPLY_HOSTED_KEY_DROPPED` | A hosted key that does not apply was cleared. | +| `W_APPLY_VALUE_NORMALIZED` | Validation rewrote a value; the returned files show it. | +| `W_APPLY_TYPE_CHANGED` | A block's type changed; its id, webhook URL and schedules are replaced. | +| `W_APPLY_TRIGGER_REMOVED` | A deleted or retyped block still serves a live webhook, schedule, chat output or MCP tool until the next deploy. | +| `W_APPLY_CATALOG_MOVED` | Compile failed and the block catalog changed since the read: get the source again. | +| `E_APPLY_LINT`, `W_APPLY_LINT` | A workflow lint finding, mapped to a source line. | +| `E_APPLY_UNRESOLVED_REF` | A `$ref` naming no block or variable, or a path no output has, in code or a block the edit changed (`W_UNRESOLVED_REF`, `W_UNKNOWN_OUTPUT_PATH` elsewhere). | +| `E_APPLY_REF_OUT_OF_SCOPE` | A `W_REF_OUT_OF_SCOPE` iteration reference on a block the edit added, changed or moved. | +| `E_APPLY_CODE_FILE_REF_SYNTAX` | A `W_CODE_FILE_REF_SYNTAX` in a code file the edit changed. | +| `E_APPLY_LOOP_CONDITION_SYNTAX` | A `W_LOOP_CONDITION_SYNTAX` on a loop the edit added or changed. | +| `E_APPLY_BLOCK_DELETE` | The apply deletes blocks the source no longer declares; pass `--allow-delete`. When it also adds blocks of a deleted one's type, it names them as possible renames and says how to keep the ids. | +| `E_APPLY_VARIABLE_DELETE` | The apply removes workflow variables the source no longer declares; pass `--allow-delete`, as for blocks. | +| `W_APPLY_PROBABLE_RENAME` | With `--allow-delete`, a deleted block and an added one share a type and parent: a probable rename that gets a new id. | +| `E_NAME_TAKEN` | The `workflow('…')` name renames the workflow to one another workflow in its folder holds. | +| `E_WORKFLOW_META_INVALID` | The `workflow('…')` name is empty or over 255 characters, or its description is over 50,000 characters: limits the workflow API holds every workflow to. | +| `E_APPLY_INVALID_SCHEDULE` | An added or changed schedule whose cron, timezone or interval deploy would refuse. | +| `W_TABLE_UNKNOWN_COLUMN` | A table row write whose data names a key that is not a column of the table; the run drops it. The hint names the nearest column. | + +### Workspace source + +Workspace source reports every workflow code above for the files of `workflows//`, with that path as the file, and these codes for the rest of the directory. + +#### Declaration files and the directory layout + +| Code | Meaning | +| --- | --- | +| `E_DECL_SYNTAX` | A Babel parse error, re-coded. | +| `E_DECL_HEADER` | The first line is not `// @sim-sdk 1`. | +| `E_DECL_IMPORT` | An import from anything but `@sim/workflow-sdk/workspace`, or a non-named import. | +| `E_DECL_EXPORT` | Not exactly one `export default defineX({ … })` with the kind's `defineX`. | +| `E_DECL_UNSUPPORTED` | A construct outside the declaration grammar: JSON literals, the kind's helper calls. | +| `E_DECL_DUPLICATE_KEY` | An object key declared twice. | +| `E_DECL_SHAPE` | A required field is missing, or a field has the wrong type. | +| `E_DECL_UNKNOWN_FIELD` | A field the kind does not define. | +| `E_DECL_UNKNOWN_FILE` | A path inside a kind's folder that no resource owns. | +| `W_PATH_NOT_SENT` | A file under a kind's folder whose path no workspace holds (a hidden name such as `.env`, or a character such as `:` or `?`): the CLI does not send it, so an apply neither writes nor deletes anything for it. | +| `E_BLOB_MANIFEST` | A blob manifest entry listed twice, or at a path that holds no binary file: the apply writes nothing. | +| `E_BLOB_MISSING` | A binary file a write needs whose bytes are not staged (or were staged at another size): the apply writes nothing. Stage it, then apply again. | +| `E_KEY_INVALID` | A resource key outside `^[a-z][a-z0-9_-]{0,63}$`. | +| `W_DECL_SUSPICIOUS_CHARACTER` | A resource name, a skill name, a workspace file path or a knowledge document name holds a bidi control or zero-width character, so it reads differently from what it stores. The workflow-file counterpart is `W_SUSPICIOUS_CHARACTER`. | + +#### `.sim/base.json` + +| Code | Meaning | +| --- | --- | +| `E_BASE_JSON` | The base is not valid JSON. | +| `E_BASE_VERSION` | `version` is missing or not `1`. | +| `E_BASE_SHAPE` | A required field is missing or of the wrong type or format. | +| `E_BASE_UNKNOWN_FIELD` | A field the base does not define (`x-` keys are allowed). | + +#### Secrets (`secrets.ts`) + +| Code | Meaning | +| --- | --- | +| `E_SECRET_NAME` | A declared name outside the secret name format. | +| `E_SECRET_MISSING` | A workflow uses a declared secret the workspace holds no value for: it is held back. | +| `W_SECRET_MISSING` | A declared secret the workspace holds no value for. | + +#### Credentials (`credentials.ts`) + +| Code | Meaning | +| --- | --- | +| `E_CREDENTIAL_MISSING` | A workflow uses a declared key no credential of its provider binds to: it is held back. | +| `E_CREDENTIAL_AMBIGUOUS` | A workflow uses a declared key several credentials could bind to: it is held back. | +| `W_CREDENTIAL_MISSING` | A declared key no credential of its provider binds to. | +| `W_CREDENTIAL_AMBIGUOUS` | A declared key several credentials could bind to. | + +#### Tables + +| Code | Meaning | +| --- | --- | +| `E_TABLE_COLUMN_NAME` | A column key or name outside the table name pattern. | +| `E_TABLE_DUPLICATE_COLUMN` | Two columns resolve to one name. | +| `E_TABLE_TOO_MANY_COLUMNS` | More columns than a table may hold: a size limit, classed like `E_LIMIT_EXCEEDED`. | +| `E_TABLE_OPTIONS` | A select column without options, an option declared twice, or options on another type. | +| `E_TABLE_TYPE_CONVERSION` | A type change the stored cells cannot convert to. | +| `E_TABLE_FOLDER` | A table folder that does not exist in the workspace. | +| `E_TABLE_ROWS` | The declaration's `rows` or its `tables/.rows.jsonl`: a bad mode or key column, a line that is not a row of declared columns, a managed row without its key or repeating one. | +| `I_TABLE_SEED_SKIPPED` | Seed rows declared for a table that already holds rows: only a new or empty table is seeded. | +| `I_TABLE_ROWS_UNKEYED` | Managed rows whose key cell is empty (a row the table's "add row" made and nobody keyed): no file line can name them, so a get leaves them out and an apply keeps them as they are. | +| `W_LIKELY_RENAME` | A column dropped and one of the same type added: probably a rename, which loses the cells. | + +#### Custom tools + +| Code | Meaning | +| --- | --- | +| `E_TOOL_SCHEMA` | The schema is not a function declaration a custom tool may store. | +| `E_TOOL_CODE` | `code` is not `codeFile('./.js')`, a string or `stored()`, or its code file is missing or does not parse. | +| `E_TOOL_STORED_MISSING` | `code: stored()` for a tool the server holds no code of (none stored under the key or title). | +| `W_TOOL_LITERAL_SECRET` | The code holds what looks like a literal credential (`holdsSecret`, as for function code): a get prints it as `stored()`, and code a directory writes with one applies with this warning. | + +#### Skills + +| Code | Meaning | +| --- | --- | +| `E_SKILL_FRONTMATTER` | `skills/.md` does not open with a frontmatter block of `name` and `description`. | + +#### MCP servers + +| Code | Meaning | +| --- | --- | +| `E_MCP_LITERAL_SECRET` | A credential header (`Authorization`, `X-Api-Key`, …) holds literal text, not an env reference. | +| `E_MCP_STORED_MISSING` | `stored()` names a header the stored server holds no value for. | +| `E_MCP_TOOL_UNKNOWN` | A workflow names a tool the MCP server does not list. | +| `W_MCP_REPLACE` | A changed URL replaces the server: a new server id, the old one deleted. | +| `W_MCP_TOOLS_UNCHECKED` | The server's tools could not be listed, so the tool names workflows use are not checked. | + +#### Workspace files + +| Code | Meaning | +| --- | --- | +| `E_FILE_PATH` | A path no workspace file may have: a dot or empty segment, a reserved name or character. | +| `E_FILE_PATH_COLLISION` | Two paths that differ only in letter case, or a path that is both a file and a folder. | +| `E_FILE_NAME` | A name the server would store differently (trimmed, whitespace collapsed, NFC). | +| `E_FILE_TOO_LARGE` | A file over the per-blob cap: a get skips it and an apply never writes it. | +| `E_FILE_CONTENT` | A workspace file sent as text, or listed without a valid SHA-256 and size. | + +#### Knowledge bases + +| Code | Meaning | +| --- | --- | +| `E_KB_EMBEDDING_IMMUTABLE` | A declared embedding model that differs from the stored one: it is fixed at creation. | +| `E_KB_EMBEDDING_MODEL` | A new knowledge base declares a model this server does not create knowledge bases with. | +| `E_KB_DOC_AMBIGUOUS` | The server holds several documents under one declared file name. | +| `E_KB_DOC_NAME` | A document file name or type the knowledge base cannot hold. | +| `E_KB_DOC_EMPTY` | An empty document, which a knowledge base cannot index. | +| `E_KB_CHUNKING` | Chunking settings outside what a knowledge base accepts. | +| `E_KB_FOLDER` | A knowledge base folder that does not exist in the workspace. | +| `W_KB_DOC_UNCHECKED` | A stored document whose bytes this request had no budget left to download and compare. | +| `W_KB_DOC_FAILED` | Documents whose indexing failed: search does not find them until they are indexed again. | +| `I_KB_REEMBED` | How many documents the apply indexes (embeds) after it writes them. | +| `I_KB_CHUNKING` | Changed chunking applies to documents indexed from now on; stored ones keep their chunks. | +| `I_KB_PROCESSING` | Documents still waiting to be indexed or being indexed: search finds them once that ends. | +| `I_KB_DOCS_UNHASHED` | Documents a get lists without a hash: it had no budget left to download them. | +| `I_KB_UNMANAGED_DOCS` | Documents source leaves alone: connector-synced, too large, or not a plain file name. | +| `I_KB_REPLACE_UNFINISHED` | A replace that stopped partway left a replacement document (under its upload name): the next apply that changes the knowledge base finishes the replace, or removes the replacement. | + +#### Deployments + +| Code | Meaning | +| --- | --- | +| `E_DEPLOY_WORKFLOW` | `deployments/.ts` names no workflow this workspace holds or this directory declares. | +| `E_DEPLOY_SECRET` | A chat password written as a value instead of `env.NAME`, an unset variable, or `stored()` where no password is stored. | +| `E_DEPLOY_CHAT_OUTPUT` | A chat output names a block the workflow does not have. | +| `E_DEPLOY_CHAT_IDENTIFIER` | A chat identifier another live chat already holds. | +| `E_DEPLOY_PINNED_CHAT` | A chat change on a pinned deployment whose draft differs: deploying a chat publishes it. | +| `W_DEPLOYED_DRAFT_CHANGED` | An apply edits a deployed workflow that no `live: 'draft'` deployment republishes. | +| `W_DEPLOY_DRAFT_NOT_SOURCE` | A `live: 'draft'` deployment whose draft holds edits the directory does not declare (made in the editor, say): the apply does not publish it. | +| `E_DEPLOY_DRAFT_NOT_SOURCE_CHAT` | A chat change while the draft holds edits the directory does not: deploying a chat publishes it. | +| `I_DEPLOY_DRAFT_NOT_LIVE` | A pinned deployment's draft differs from its live version, which keeps running. | + +#### Plan and apply + +| Code | Meaning | +| --- | --- | +| `E_APPLY_NO_BASE` | The server holds the resource but the directory has no base for it: get it first. | +| `E_APPLY_FORBIDDEN` | The caller may not make this change. | +| `E_APPLY_DELETE_NOT_ALLOWED` | The change deletes a resource or data and `--allow-delete` was not given. | +| `E_APPLY_LOCKED` | The resource is locked against this change (HTTP 423). | +| `E_APPLY_REFUSED` | A change a child operation refused, with its message. | +| `E_APPLY_FAILED` | A write failed for a reason that is not the source's (logged on the server). | +| `E_PLAN_TOO_LARGE` | The apply would make more changes or touch more workflows than one request may. | +| `E_PLAN_REF_DELETED` | A declared resource references one this apply deletes. | +| `E_PLAN_REF_HELD` | A declared resource references one this apply holds back, so it is held back too. | +| `W_RESOURCE_IN_USE` | A resource this apply deletes is still used by stored workflows. | +| `W_TABLE_COLUMN_RENAMED_IN_USE` | A table column this apply renames is still written, filtered or sorted by its old name in a stored workflow's Table block, which the run then drops. | +| `E_WORKFLOW_FILES_MISSING` | A workflow folder sent without its files whose base names no workflow of this workspace. | +| `E_WORKFLOW_FOLDER_COPIED` | A workflow folder holding the base of another declared folder's workflow: a copy. | +| `W_UNDECLARED` | A resource the server holds that the directory does not declare (kept without `--allow-delete`). | +| `W_BASE_OTHER_WORKSPACE` | The directory's base was read from another workspace: every resource is created anew. | +| `W_PROMOTE_TARGET_DELETED` | A promotion (`apply --to`) keeps deleted a resource the directory declares that the target deleted since the last promotion: the target no longer holds it. | +| `W_PROMOTE_DELETES_TARGET_ONLY` | A promotion with `--allow-delete` deletes a resource only the target holds (the directory does not declare it). | +| `W_SERVER_CHANGED` | The server changed a resource the directory leaves alone; the apply keeps it. | +| `W_SERVER_DELETED` | The server deleted a resource the directory leaves as it was; it is not created again. | +| `W_SERVER_MOVED` | The server moved a resource the directory leaves as it was; it is not created again. | +| `I_KEY_REBOUND` | A key bound to a deleted resource was bound to the one this apply wrote. | +| `E_KEY_RENAMED` | A declaration under a new key for a resource the base read under another: keys never move. | + +#### Shared with workflow source + +A workspace finding with the same meaning as a workflow finding uses its code. + +| Code | Meaning | +| --- | --- | +| `E_APPLY_STALE` | The workflow changed since the source was read (HTTP 409). | +| `E_LIMIT_EXCEEDED` | Over the block, edge, total-byte, depth or `codeFile()` reference cap (`SOURCE_LIMITS`). Apply answers 413. | +| `E_NAME_TAKEN` | The `workflow('…')` name renames the workflow to one another workflow in its folder holds. | +| `I_FINDINGS_TRUNCATED` | 100 warnings, or 20 of one code, were listed and the rest omitted, so a flood of one finding never hides another. A finding repeated at the same place is listed once. Infos are capped apart (100, the rest dropped), so they never displace a warning, and errors are never displaced by either. An answer that merges findings from several stages is capped the same way as a whole; when that cuts it, it ends in one `I_FINDINGS_TRUNCATED` counting what it left out, in place of the stages' own. | + +{/* workflow-code-docs:diagnostics:end */} + +## Related docs + +- [File syntax](/workflows/code/syntax) +- [Exit codes](/workflows/code/exit-codes) +- [Limits](/workflows/code/limits) diff --git a/apps/docs/content/docs/workflows/code/directory.mdx b/apps/docs/content/docs/workflows/code/directory.mdx new file mode 100644 index 00000000000..321679afdb3 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/directory.mdx @@ -0,0 +1,88 @@ +--- +title: Directory layout +description: Every file a workflow directory and a workspace directory holds, who writes it, and what to commit. +--- + +`get` writes a directory, and every later command reads and rewrites it. Keep the `.sim/` folder: it is how Sim recognizes each block and resource again, and how an apply knows what version you read. + +## Workflow directory + +`sim workflows source get --dir ` writes: + +| Path | What it is | In git | +| --- | --- | --- | +| `workflow.ts` | The workflow, in [file syntax](/workflows/code/syntax) | Commit | +| `functions/` | One file per Function block's code | Commit | +| `.sim/lock.json` | Ties each block in the file to the stored block, so renaming a block keeps its webhook URL, schedules and run history | Commit | +| `.sim/base.json` | The workflow ID and the version you read | Commit | +| `.sim/written.json` | A digest of each file as the CLI last wrote it, so `status` and `get` tell your edits from the CLI's | Commit | +| `.sim/stored-edges.json` | The connections the stored workflow held when it was printed, so an offline `check` tells them from connections you added. The CLI's own record, never sent | Commit | +| `.sim/starter.json` | The workspace a starter was written for, before `create` | Not kept: removed once the workflow exists | +| `.sim/AGENTS.md` | The guide for coding agents: the primer `get` prints, then a reference | Optional, written again by `get` | +| `.sim/examples/` | Example workflows to copy from | Optional, written again by `get` | +| `.sim/sdk/` | Type declarations for the blocks the workflow uses, and your workspace's tables, credentials, knowledge bases and environment variable names. `.sim/sdk/INDEX.md` lists the builders | Optional, written again by `get` and `check` | +| `tsconfig.json` | Resolves the declarations and type-checks the blocks the workflow uses. Left as it is if you already have one | Commit | +| `tsconfig.full.json` | Type-checks every block through the CLI's cache | Ignore: it names the cache on your machine, and `check` writes it again | +| `.gitattributes` | Keeps the source files on LF line endings | Commit | + +The declarations of every block are generated once per block catalog into the CLI's cache, `~/.sim/cache/source-catalog/`, and shared by every directory. A workflow directory gets no `.gitignore`, so add the lines for what you ignore. + +While a command runs it holds `.sim/command.lock/`, so two commands on one directory never interleave. A second one exits `10`. + +## Workspace directory + +`sim workspaces source get --dir ` writes one folder per kind of resource. A kind is managed only when its folder or file exists. + +``` +secrets.ts the env variable names workflows read (never a value) +credentials.ts the saved credentials workflows use, by provider +tables/orders.ts a table: name, description, columns +tables/plans.rows.jsonl a table's rows, one JSON object per line (only when the table opts in) +knowledge/policies/knowledge.ts a knowledge base: name, chunking +knowledge/policies/docs/*.md one file per document +files/templates/reply.md a workspace file, at its folder path +tools/lookup-order.ts a custom tool: title and schema +tools/lookup-order.js the tool's code +skills/tone.md a skill: name and description, then its content +mcp/docs.ts an MCP server: url, headers +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: + +{/* workflow-code-docs:directory-kinds:begin — generated by `bun run generate:workflow-code-docs`; do not edit between markers */} + +- `secrets.ts`: `export default defineSecrets({ NAME: { description? } })`, the workspace secrets workflows read, by name and description only (never a value: set one with `sim secrets set NAME --scope workspace`). A workflow: `env.NAME`; one using a declared secret the workspace has no value for is held back, and the rest apply. +- `credentials.ts`: `export default defineCredentials({ : { provider, name? } })`, binding each key to this workspace's credential for that provider (never a token): the one bound already, else the only one, else the one whose display name is `name`. A workflow: `credential('')`; one using a key no credential binds to is held back, and the rest apply. +- `tools/.ts` (`defineTool({ title, schema, code: codeFile('./.js') })`) and its code in `tools/.js`, where each schema parameter is a variable. Code holding a literal credential prints as `code: stored()`, which keeps the stored code. A workflow: `customTool('')`. +- `skills/.md`: a frontmatter block of `name` and `description`, then the content. A workflow: `skills: [skill('')]` on an agent. +- `mcp/.ts`: `export default defineMcpServer({ name?, url, headers?, auth?, timeout?, retries?, enabled? })`. A credential header holds `env.NAME` or `'Bearer {{NAME}}'`, never a literal secret; `stored()` keeps the value the server holds. A changed `url` replaces the server. A workflow: `mcp('').tool('')`. +- `tables/.ts`: `export default defineTable({ name, description?, folder?, columns: { … } })` with `column.string()`, `column.number()`, `column.select({ options: [...] })`, … from `@sim/workflow-sdk/workspace`. Rows stay out of source unless `rows` opts in: `{ mode: 'managed', key: '' }` keeps the rows equal to `tables/.rows.jsonl` (one JSON object per line, keyed by column key), `{ mode: 'seed' }` writes them once into a new table. A workflow: `table('')`. +- `knowledge//knowledge.ts` (`defineKnowledgeBase({ name, description?, folder?, chunking?, embeddingModel? })`) and `knowledge//docs/`, one file per document, flat. A workflow: `knowledgeBase('')`. Connector-synced documents are never part of source. +- `files/`: every file is one workspace file at that folder path; no declaration. +- `workflows//`: one workflow each, exactly a `sim workflows source get --dir` directory (`workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`). +- `deployments/.ts`: `defineDeployment({ live: 'draft' | 'pinned', api?: { public? }, chat? })` deploys `workflows//`, so its schedule, webhook, API and chat triggers run. `live: 'draft'` publishes the draft whenever it differs from the live version; `'pinned'` never redeploys and says when the draft differs. A chat password is `env.NAME` (or `stored()` to keep the stored one); chat outputs name a block by its name. Removing the file undeploys the workflow (needs `--allow-delete`). Deploying needs workspace admin, never a workspace API key. MCP publishing is not part of source. + +{/* workflow-code-docs:directory-kinds:end */} + +Beside the resources: + +| Path | What it is | In git | +| --- | --- | --- | +| `.sim/base.json` | The workspace the directory was read from and the version of every resource | Commit | +| `workflows//.sim/` | Each workflow's `lock.json`, `base.json` and `written.json`, as above | Commit | +| `.sim/targets/.json` | What each [promotion](/workflows/code/promote) left in that workspace | Commit | +| `.sim/skipped.json` | Documents and files a get left out, with the reason | Optional | +| `.sim/AGENTS.md`, `.sim/GUIDE-advanced.md`, `.sim/examples/`, `.sim/sdk/` | The agent guide with deletes, Git and CI, and promotion in depth; examples of every kind; type declarations including `.sim/sdk/workspace.d.ts` | Optional, written again by `get` | +| `.sim/cache/` | This machine's file stats. It ignores itself | Not committed | +| `tsconfig.json`, `tsconfig.full.json`, `.gitattributes`, `.gitignore` | As for a workflow directory. `.gitattributes` also keeps workspace files and knowledge base documents byte for byte | Commit all but `tsconfig.full.json` | + +The generated `.gitignore` leaves out only what a command keeps while it runs (`.sim/downloads/`, `.sim/command.lock/`, `.sim-staging-*`) and `tsconfig.full.json`. Commit the rest, including `.sim/`: a fresh clone can then run `check`, `apply --dry-run` and `apply`. + +## Related docs + +- [Edit a workflow](/workflows/code/edit) +- [Manage a workspace as code](/workflows/code/workspace) +- [Run in CI](/workflows/code/ci) +- [Limits](/workflows/code/limits) diff --git a/apps/docs/content/docs/workflows/code/edit.mdx b/apps/docs/content/docs/workflows/code/edit.mdx new file mode 100644 index 00000000000..5a9fb5d89c5 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/edit.mdx @@ -0,0 +1,110 @@ +--- +title: Edit a workflow +description: Read a workflow into a directory, edit it, check it, and save it, including renames, deletes and deploys. +--- + +Result: a workflow saved from a file you edited, with the problems found before the save. + +## Prerequisites + +The Sim CLI, signed in, with [workflows as code enabled](/workflows/code). Run every command on the same `--dir`; commands that read a directory (`check`, `status`, `diff`, `params`, `apply`) default it to the current directory, while `get` and `create`, which write one, always need `--dir`. + +## 1. Read the workflow + +```bash +sim workflows source get --dir ./support-triage +``` + +This writes `workflow.ts`, any function code under `functions/`, type declarations for the blocks the workflow uses and for your workspace's resources, and the `.sim/` folder. See [Directory layout](/workflows/code/directory) for each file. For coding agents it writes `.sim/AGENTS.md` and example workflows under `.sim/examples/`. + +`get` into a directory that already holds source refuses to overwrite edits you have not applied, and refuses a directory that holds a different workflow. Pass `--force` to replace them. A workspace directory is always refused, `--force` included. + +To write a block the workflow does not use yet, `sim workflows source params ` (for example `table.upsertRow` or `trigger.schedule`) prints its params, required ones first with their options and defaults, and its outputs, from the cached block catalog without a request. A namespace such as `gmail` lists its builders. + +## 2. Edit and check + +Edit `workflow.ts`, then compile it on your machine with Sim's compiler: + +```bash +sim workflows source check --dir ./support-triage +``` + +`check` makes no request. It needs the block catalog the last `get` cached in `~/.sim/cache/source-catalog/`; with none cached it exits `1` and tells you to run `get` once. It exits `1` on an error, and on the warnings `sim workflows source check --help` lists (a missing required field, an unknown option, an unwired condition or router branch, a literal secret and more) in a block you added since the get. `--strict` fails on these in every block, except an unwired branch on a block the get printed; `--no-strict` never fails on a warning. It also adds the blocks the workflow now uses to `tsconfig.json`. + +Your editor type-checks the file against the generated declarations, and this checks it from the command line with the TypeScript release the declarations are built for: + +```bash +bunx -p typescript@7.0.2 tsc -p ./support-triage +``` + +Use `-p ./support-triage/tsconfig.full.json` to type-check against every block. + +## 3. See what changed + +```bash +sim workflows source status --dir ./support-triage +sim workflows source diff --dir ./support-triage +``` + +`status` lists the files you created, edited, or deleted, asks the server (with a dry run that saves nothing) whether the workflow changed since the `get`, and ends with the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unsaved, and `12` when the workflow changed in the workflow builder since the `get` (a conflict, if you edited it too). Without a connection it shows your edits only and says so; `--offline` skips the server. `diff` prints each edit as a unified diff, and `diff --server` compares the directory with the workflow as it is saved now. Both take `--json` (or `--output json`). + +## 4. Dry run + +```bash +sim workflows source apply --dir ./support-triage --dry-run +``` + +`apply` reads the workflow ID from `.sim/base.json`. Pass it as `apply --dir …` to have the CLI confirm the directory holds that workflow. + +Sim compiles the file and runs every check a save would run: unknown settings, missing required fields, broken references, permissions, and locked blocks. Each problem prints with its line, the code around it, and a hint: + +``` +workflow.ts:56:7 error E_UNKNOWN_PARAM: Slack has no param chanel. + 54 | const notify = slack.sendMessage('Notify', { + 55 | credential: credential('support-slack'), +> 56 | chanel: 'C0SUPPORT', + | ^^^^^^^^^^^^^^^^^^^ + 57 | text: t`New ${classify.category} ticket: ${ticketIn.subject}`, + hint: Did you mean channel? +``` + +Every code is in [Diagnostic codes](/workflows/code/diagnostics). + +## 5. Save the draft + +```bash +sim workflows source apply --dir ./support-triage --yes +``` + +The workflow builder updates for anyone who has the workflow open. `--yes` refuses everything a dry run would, so step 4 is optional: without `--yes`, and with no terminal to ask, `apply` prints the plan, writes nothing and exits `14`. The save rewrites `workflow.ts` in canonical form, so read it again before the next edit. + +Editing the name or description in `workflow('…')` renames or redescribes the workflow; a name another workflow in its folder already has is refused with `E_NAME_TAKEN`. Lines starting with `note:` report something the save did beyond what the file says; read them. + +### Deploy + +Saving writes the draft. Add `--deploy` to deploy right after the save, which also prints the URL of each webhook the workflow now serves. Without it, a deployed workflow whose draft now differs prints the `sim workflows deploy` command to run. + +### Deletes + +A save that removes a block (its declaration is gone from `workflow.ts`) is refused with `E_APPLY_BLOCK_DELETE`, naming the blocks, and one that removes a workflow variable with `E_APPLY_VARIABLE_DELETE`. Pass `--allow-delete` when the deletion is intended. Removing a block that serves a live webhook, schedule, chat, or MCP tool warns you: the deployed version keeps serving it until the next deploy. + +### Renames + +Keep the `.sim/` folder the commands write. `.sim/lock.json` ties each block in the file to the stored block, so renaming a block keeps the same block, with its webhook URL, schedules and run history. Changing its name string keeps it through the lock; renaming the variable too keeps it when the block's type, parent and connections are unchanged, and the dry run reports that as `W_MAT_INFERRED_RENAME`. Renaming two blocks of the same type in the same place in one save is ambiguous, so do those one save at a time. `.sim/base.json` records the version you read. + +## Working with other people + +- If someone changes the workflow after you read it, the save (or `--dry-run`) is refused with exit code `5` and nothing is overwritten. Run `get` into a new directory, reapply your edit, and save. There is no automatic merge. +- Locked blocks cannot be changed from the file. Unlock them in the workflow builder first. + +## Limits + +The file holds block declarations and connections only: helpers, loops that create blocks, and imports are refused. Function code is one file per block, with no imports between files. Workflows run in Sim, not locally, and `--dry-run` checks everything a save checks without running the workflow. Size caps are in [Limits](/workflows/code/limits). + +## Related docs + +- [File syntax](/workflows/code/syntax) +- [Create a workflow](/workflows/code/create) +- [Run in CI](/workflows/code/ci) +- [Exit codes](/workflows/code/exit-codes) +- [CLI workflow commands](/cli/workflows#workflows-as-code) diff --git a/apps/docs/content/docs/workflows/code/exit-codes.mdx b/apps/docs/content/docs/workflows/code/exit-codes.mdx new file mode 100644 index 00000000000..fb20995b618 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/exit-codes.mdx @@ -0,0 +1,83 @@ +--- +title: Exit codes +description: What the sim workflows source and sim workspaces source commands exit with, and what to run next. +--- + +import { Tab, Tabs } from '@/components/ui/tabs' + +The `sim workflows source` and `sim workspaces source` commands exit with a code a script or CI job can branch on. Findings print on stderr, and the result of a command goes to stdout. A code of its own is set aside for each outcome a script handles differently, so test for the code you act on, not for any non-zero status. + +`status` is the command to branch on: it exits `0` when nothing differs, `11` when only your edits are unsaved, and `12` when the server changed since the directory was read. + +```bash +sim workspaces source status --dir workspace --output json > status.json +case $? in + 0) echo "in sync" ;; + 11) echo "local edits to apply" ;; + 12) echo "the workspace changed in Sim since the get" ;; + *) echo "status failed"; exit 1 ;; +esac +``` + +## Codes + +The table for the kind of directory you work in. Both are built from the table `--help`, the generated [CLI reference](/cli/workflows#workflows-as-code) and `.sim/AGENTS.md` print, so they cannot disagree with the CLI. + +{/* workflow-code-docs:exit-codes:begin — generated by `bun run generate:workflow-code-docs`; do not edit between markers */} + + + + + | Code | Meaning | What to do | + | --- | --- | --- | + | `0` | Applied or created, a dry run or check with no errors, or a clean status | Go on | + | `1` | The source has errors (each printed as `file:line:column` with a hint), a locked block (`E_APPLY_LOCKED_BLOCK`), a name another workflow holds (`SOURCE_NAME_TAKEN`), a cancelled prompt, or the command failed | Fix what it printed and run it again | + | `5` | Stale (`SOURCE_STALE`, or `E_APPLY_STALE` on a dry run): the server changed what this directory was read from, and nothing was written | `sim workflows source get --dir `, reapply your edit there, dry-run, apply | + | `6` | A workflow or its folder is locked (`E_APPLY_LOCKED`); a locked block exits 1 instead | Ask someone to unlock it in the workflow builder | + | `7` | The source is over the size limits (on a get, status or diff too) | Split function code, or remove blocks or resources | + | `8` | `sim workspaces source apply` stopped part-way: what was written is saved into the directory | Apply again until it exits 0 | + | `9` | Still rate limited (HTTP 429) after the CLI's retries (up to 6, at most a minute apart); nothing more was written | Wait a minute and run the same command again | + | `10` | Busy: another apply is writing the workspace (`SOURCE_BUSY`), or another sim command is using this directory (`SOURCE_DIR_BUSY`); nothing was written | Run it again once the other finished | + | `11` | `status`: only your edits, which applying writes | Dry-run, then apply | + | `12` | `status`: the server changed since the get (drift, or a conflict with your edits) | Follow the `Next:` line it prints | + | `13` | Not logged in, the login expired, or the server refused the credential (`AUTH_REQUIRED`); nothing was sent | `sim login`, or fix or unset `SIM_API_KEY` when the key comes from it; then the same command again | + | `14` | `apply` or `create` without `--yes` and no terminal to ask: it printed the plan, found no errors, and wrote nothing | Run the same command with `--yes` | + | `15` | `sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret the workspace has no value for, or a credential key nothing binds to. Its dry run exits 15 too, so a script can tell beforehand that the apply would write only part | Set the secret (`sim secrets set`) or connect the credential, then apply again | + | `130` | Interrupted (Ctrl-C). An apply or create already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written | `sim workflows source status --dir .` | + + + + + | Code | Meaning | What to do | + | --- | --- | --- | + | `0` | Applied or created, a dry run or check with no errors, or a clean status | Go on | + | `1` | The source has errors (each printed as `file:line:column` with a hint), a locked block (`E_APPLY_LOCKED_BLOCK`), a name another resource holds (`E_NAME_TAKEN`), a cancelled prompt, or the command failed | Fix what it printed and run it again | + | `5` | Stale (`SOURCE_STALE`, or `E_APPLY_STALE` on a dry run): the server changed what this directory was read from, and nothing was written | `sim workspaces source get --dir `, reapply your edit there, dry-run, apply | + | `6` | A workflow or its folder is locked (`E_APPLY_LOCKED`); a locked block exits 1 instead | Ask someone to unlock it in the workflow builder | + | `7` | The source is over the size limits (on a get, status or diff too) | Split function code, or remove blocks or resources | + | `8` | `sim workspaces source apply` stopped part-way: what was written is saved into the directory | Apply again until it exits 0 | + | `9` | Still rate limited (HTTP 429) after the CLI's retries (up to 6, at most a minute apart); nothing more was written | Wait a minute and run the same command again | + | `10` | Busy: another apply is writing the workspace (`SOURCE_BUSY`), or another sim command is using this directory (`SOURCE_DIR_BUSY`); nothing was written | Run it again once the other finished | + | `11` | `status`: only your edits, which applying writes | Dry-run, then apply | + | `12` | `status`: the server changed since the get (drift, or a conflict with your edits) | Follow the `Next:` line it prints | + | `13` | Not logged in, the login expired, or the server refused the credential (`AUTH_REQUIRED`); nothing was sent | `sim login`, or fix or unset `SIM_API_KEY` when the key comes from it; then the same command again | + | `14` | `apply` or `create` without `--yes` and no terminal to ask: it printed the plan, found no errors, and wrote nothing | Run the same command with `--yes` | + | `15` | `sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret the workspace has no value for, or a credential key nothing binds to. Its dry run exits 15 too, so a script can tell beforehand that the apply would write only part | Set the secret (`sim secrets set`) or connect the credential, then apply again | + | `130` | Interrupted (Ctrl-C). An apply or create already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written | `sim workspaces source status --dir .` | + + + + +{/* workflow-code-docs:exit-codes:end */} + +Earlier CLI releases exited `1` when an apply held changes back, whether or not it wrote the rest, and its dry run exited `1` in either case. A script that reads `1` as "held back" should test for `15` too. + +Exit `9` follows the CLI's retries: it resends a request the API answered `429` only when sending it twice is safe, which includes every `GET`, a source `apply` and a `create`. See [Scripting](/cli/scripting#exit-codes) for the retry schedule and the codes every command shares (`13` and `9`). + +## Related docs + +- [Run in CI](/workflows/code/ci) +- [Diagnostic codes](/workflows/code/diagnostics) +- [Limits](/workflows/code/limits) +- [Scripting: exit codes](/cli/scripting#exit-codes) +- [CLI workflow commands](/cli/workflows#workflows-as-code) and [workspace commands](/cli/workspaces#workspace-as-code) diff --git a/apps/docs/content/docs/workflows/code/get-started.mdx b/apps/docs/content/docs/workflows/code/get-started.mdx new file mode 100644 index 00000000000..0e592f79b55 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/get-started.mdx @@ -0,0 +1,75 @@ +--- +title: Get started +description: Change one setting of a workflow from your terminal, save it, and see it in the workflow builder. +--- + +This walks through one change end to end: read a workflow as a file, edit it, check it, save it, and see the result in the workflow builder. + +## Before you start + +- Workflows as code is [enabled](/workflows/code) for your workspace. Where it is not, step 2 answers `403`. +- The Sim CLI is installed and you are signed in with a default workspace. See [Your first command](/cli#your-first-command). +- Optional: Bun, for the type-check in step 4. + +## 1. Find the workflow ID + +```bash +sim workflows list --search "support" +``` + +## 2. Read it as a file + +```bash +sim workflows source get --dir ./support-triage +``` + +This writes `workflow.ts`, the type declarations, and `.sim/`, which records which block is which. See [Directory layout](/workflows/code/directory). + +## 3. Change one setting + +Open `workflow.ts` and change one value, such as an agent's `model` or a message's `text`. Each `const` is a block, and a change to one setting is a one-line diff. The forms you can write are in [File syntax](/workflows/code/syntax). + +## 4. Check it + +```bash +sim workflows source check --dir ./support-triage +bunx -p typescript@7.0.2 tsc -p ./support-triage +``` + +`check` compiles the file on your machine, and `tsc` type-checks it. Each problem prints with its line, the code around it, and a hint. + +## 5. See what changed + +```bash +sim workflows source status --dir ./support-triage +sim workflows source diff --dir ./support-triage +``` + +`status` lists your edits, asks the server whether the workflow changed since the `get`, and ends with the one command to run next. + +## 6. Save the draft + +```bash +sim workflows source apply --dir ./support-triage --dry-run +sim workflows source apply --dir ./support-triage --yes +``` + +The dry run runs every check a save runs and writes nothing. `--yes` saves the draft and rewrites `workflow.ts` in canonical form, so read it again before the next edit. + +## 7. See it in the builder + +Open the workflow in the workflow builder. It shows your change, and updates for anyone who has the workflow open. The **Code** tab shows the same workflow as read-only source. Saving writes the draft only: deploy it when you are ready. + +## Create a new workflow + +```bash +sim workflows source create --dir ./new-workflow --workspace +``` + +See [Create a workflow](/workflows/code/create). + +## Related docs + +- [Edit a workflow](/workflows/code/edit) +- [Use with coding agents](/workflows/code/coding-agents) +- [Exit codes](/workflows/code/exit-codes) diff --git a/apps/docs/content/docs/workflows/code/index.mdx b/apps/docs/content/docs/workflows/code/index.mdx new file mode 100644 index 00000000000..2a7cb5bc8d7 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/index.mdx @@ -0,0 +1,57 @@ +--- +title: Workflows as code +description: Read and edit workflows and whole workspaces as TypeScript files, check them before saving, and review changes as diffs. +--- + +import { Callout } from '@/components/ui/callout' + +Every workflow can be read and written as one TypeScript file, and a whole workspace as a directory of files. The file and the workflow builder show the same workflow: edit either one and the other follows. Use it to review agent changes as a diff, keep workflows in git, or let a coding agent such as Claude Code build and change them for you. + + +Workflows as code is in preview. When it is enabled, the workflow builder shows a read-only **Code** tab and the [CLI](/cli) gains the `sim workflows source` and `sim workspaces source` commands. On a self-hosted deployment, set [`WORKFLOW_CODE`](/platform/self-hosting/environment-variables#preview-features). On Sim Cloud it is enabled per organization, workspace or user. Where it is off, the **Code** tab is not shown and a source command answers `403` with "Workflows as code is in preview and not enabled for this workspace". + + +## Workflow or workspace + +- **A workflow** is one `workflow.ts` plus its function code files. Use `sim workflows source`. +- **A workspace** is a directory with a folder for each kind of resource: tables, knowledge bases, files, custom tools, skills, MCP servers, secrets and credential bindings, deployments and workflows. Each workflow is written exactly as above. One apply creates the resources before the workflows that use them, so a coding agent can build a working setup from scratch. Use `sim workspaces source`. + +The file states what the workflow runs: its blocks, their settings, the connections between them, branches, loops, and variables. Layout and other builder-only details stay in the stored workflow, so the file stays short and a change to one setting is a one-line diff. Nothing in the file runs on your machine: Sim reads it statically, checks it against your workspace, and saves it as the workflow draft. Deploying stays a separate step. + +## The loop + +Both commands follow the same five steps: + +```bash +sim workflows source get --dir ./support-triage +# edit ./support-triage/workflow.ts +sim workflows source check --dir ./support-triage +sim workflows source status --dir ./support-triage +sim workflows source apply --dir ./support-triage --dry-run +sim workflows source apply --dir ./support-triage --yes +``` + +`get` writes the directory, `check` compiles it on your machine, `status` shows what changed and what to run next, a dry run checks everything a save checks, and `apply --yes` saves the draft. + +## Terms + +- **As code** names the feature; **source** names its files and commands. +- A **workflow directory** is the directory `sim workflows source get` writes; a **workspace directory** is the one `sim workspaces source get` writes. +- **Get** reads from Sim and **apply** writes to Sim. Neither is a sync: [fork, push and pull](/cli/workflow-sync) are a different feature. +- **Check** compiles offline. A **dry run** asks the server and saves nothing. The **plan** is what a dry run prints. +- **Stale** means an apply was refused because the server changed what you read (exit `5`). **Drift** means the server changed since the get (`status` exits `12`). A **conflict** is a resource changed on both sides. +- A **resource key** is the file or folder name of a table, skill or other resource. A **block key** is a block's name lowercased with whitespace and dots removed, as in `$ref.triageagent.content`. + +## For coding agents [#for-coding-agents] + +Claude Code, Cursor, Codex and other coding agents work from a directory that `get` writes. `get` prints a primer and writes the full guide to `.sim/AGENTS.md`. See [Use with coding agents](/workflows/code/coding-agents). + +## Related docs + +- [Get started](/workflows/code/get-started): change one setting and see it in the builder +- [Edit a workflow](/workflows/code/edit) +- [Manage a workspace as code](/workflows/code/workspace) +- [Run in CI](/workflows/code/ci) +- [File syntax](/workflows/code/syntax) +- [Exit codes](/workflows/code/exit-codes), [diagnostic codes](/workflows/code/diagnostics) and [limits](/workflows/code/limits) +- [CLI workflow commands](/cli/workflows#workflows-as-code) and [workspace commands](/cli/workspaces#workspace-as-code) diff --git a/apps/docs/content/docs/workflows/code/limits.mdx b/apps/docs/content/docs/workflows/code/limits.mdx new file mode 100644 index 00000000000..6f08e50e88b --- /dev/null +++ b/apps/docs/content/docs/workflows/code/limits.mdx @@ -0,0 +1,61 @@ +--- +title: Limits +description: The size limits of workflow source and workspace source, and what happens when a directory goes over one. +--- + +A get leaves out what an apply would refuse, so anything a get writes can be applied back unchanged. The numbers below are hard limits, read from the same constants the CLI and the server enforce. + +## What happens over a limit + +- **A workflow** over a limit is refused when you read or save it (`E_LIMIT_EXCEEDED`), and the CLI exits `7`. +- **An apply of a workspace directory** that would make more changes than the limit, send more edited workflows, or hold more resources of a kind is refused before anything is written, and the CLI exits `7`. +- **A get of a workspace** that holds more resources of a kind than one directory takes exits `7`. +- **A workspace file or knowledge base document** over its limit, or whose name a directory cannot hold, is left out of the get and listed in `.sim/skipped.json`. An apply never writes or deletes it. + +{/* workflow-code-docs:limits:begin — generated by `bun run generate:workflow-code-docs`; do not edit between markers */} + +### One workflow + +| Limit | Value | +| --- | --- | +| Blocks in one workflow | 2,000 | +| Connections (edges) in one workflow | 10,000 | +| Variables in one workflow | 2,000 | +| Files in one source: `workflow.ts` plus one function file per block | 2,001 | +| Bytes of all files together, `workflow.ts` and function files | 4,000,000 bytes | +| Nesting depth of `workflow.ts`, and of each JavaScript function file | 200 | + +### A workspace directory + +| Limit | Value | +| --- | --- | +| Resources of one kind in one directory | 500 | +| Bytes of every declaration file together, workflow files excluded | 2,000,000 bytes | +| Edited workflows one apply sends | 100 | +| Bytes of every workflow file one apply sends | 8,000,000 bytes | +| Bytes of every workflow file one get writes; a workflow past it is left out | 32,000,000 bytes | +| Changes one apply makes, no-ops excluded | 1,000 | +| Rows in one `tables/.rows.jsonl` | 10,000 | +| Bytes of every rows file together | 16,000,000 bytes | +| Columns in one table | 1,000 | +| Bytes of one workspace file or knowledge base document | 10,000,000 bytes | +| Workspace files and knowledge base documents together in one directory | 20,000 | +| Nesting depth of a declaration file | 200 | + +### Uploading and downloading files + +| Limit | Value | +| --- | --- | +| Bytes of files one upload request carries; a larger file goes in a request of its own | 8,000,000 bytes | +| Files in one upload request | 1,000 | +| Bytes of stored files one get or apply downloads to compare | 24,000,000 bytes | +| Files one caller may hold staged in one workspace at once | 20,000 | +| Bytes one caller may hold staged in one workspace at once | 4,000,000,000 bytes | + +{/* workflow-code-docs:limits:end */} + +## Related docs + +- [Exit codes](/workflows/code/exit-codes) +- [Diagnostic codes](/workflows/code/diagnostics) +- [Manage a workspace as code](/workflows/code/workspace) diff --git a/apps/docs/content/docs/workflows/code/meta.json b/apps/docs/content/docs/workflows/code/meta.json new file mode 100644 index 00000000000..bca32e90566 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/meta.json @@ -0,0 +1,20 @@ +{ + "title": "Workflows as code", + "pages": [ + "index", + "get-started", + "---How-to guides---", + "edit", + "create", + "workspace", + "promote", + "ci", + "coding-agents", + "---Reference---", + "syntax", + "directory", + "exit-codes", + "diagnostics", + "limits" + ] +} diff --git a/apps/docs/content/docs/workflows/code/promote.mdx b/apps/docs/content/docs/workflows/code/promote.mdx new file mode 100644 index 00000000000..4dd1ba68ded --- /dev/null +++ b/apps/docs/content/docs/workflows/code/promote.mdx @@ -0,0 +1,51 @@ +--- +title: Promote to another workspace +description: Apply a workspace directory read from one workspace to another with --to, such as dev to prod, and how the target record works. +--- + +Result: the resources of a directory created or updated in a second workspace, with changes made there since the last promotion kept or refused. + +## Promote or fork? + +- Use **promote** (`--to`) when the directory, usually in git, is the source of truth and the target workspace need not be linked to the source. +- Use **fork, push and pull** when two workspaces should stay linked as parent and child and exchange reviewed changes. They need an Admin on both workspaces, and Enterprise on billing-enabled deployments. See [Workflow imports and workspace sync](/cli/workflow-sync). + +## Before the first promotion + +Set the target's secrets (`sim secrets set NAME --scope workspace -w `) and connect its credentials, or the workflows that use them are held back and the apply exits `15`. + +## Promote + +Apply a directory read from one workspace (dev) to another (prod) with `--to`: + +```bash +sim workspaces source apply --dir ./my-workspace --to "$PROD_WORKSPACE_ID" --dry-run +sim workspaces source apply --dir ./my-workspace --to "$PROD_WORKSPACE_ID" --yes +``` + +Each resource binds by key to the target's own. One the target holds under the same key is updated in place, so a workflow keeps its id and its webhook URLs. A key the target lacks is created. Secrets and credentials bind by name to the target's own, and no value is copied. The directory stays bound to the workspace it was read from. Without `--to`, `check`, `status`, `diff` and `apply` act on the workspace the directory was read from, whatever your default workspace; a `--workspace` naming another one is refused. + +## Deletes + +A resource you deleted from the directory since the last promotion is deleted in the target too, and like any delete it needs `--allow-delete`. Resources only the target holds, such as a table created in prod and the rows its runs wrote, are kept, with or without `--allow-delete`: the plan names each with a `W_UNDECLARED` warning. To delete them as well, pass `--delete-target-only` beside `--allow-delete`; the plan then names each with a `W_PROMOTE_DELETES_TARGET_ONLY` warning, so run it with `--dry-run` first. + +## The target record + +Each promotion records what it left in the target in `.sim/targets/.json`, and the next promotion compares with that record: + +- A resource changed in the target since the last promotion, such as a hotfix made in Sim, is kept when the directory left it alone. +- When the directory changed it too, the promotion is refused as stale and exits `5`. Carry the target's change into the source workspace, or undo it in the target, then promote again. +- A resource deleted in the target since the last promotion stays deleted, with a `W_PROMOTE_TARGET_DELETED` warning. Remove its entry from the record to create it again. +- The first promotion, and any resource the record does not hold (one created in the target since), updates the target to match the directory. Review the dry run first. + +Commit the record with the rest of the directory, so a promotion from CI or another clone compares with it. Don't delete it to get past a stale refusal: without it, the next promotion overwrites every change made in the target since, including rows its workflows wrote. + +## In CI + +To promote after each merge, add the step after the apply to the source workspace and before the step that commits the files back; see [Run in CI](/workflows/code/ci#promote-in-ci). + +## Related docs + +- [Manage a workspace as code](/workflows/code/workspace) +- [Run in CI](/workflows/code/ci) +- [Exit codes](/workflows/code/exit-codes) diff --git a/apps/docs/content/docs/workflows/code/syntax.mdx b/apps/docs/content/docs/workflows/code/syntax.mdx new file mode 100644 index 00000000000..42bf9e2a800 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/syntax.mdx @@ -0,0 +1,268 @@ +--- +title: File syntax +description: The TypeScript subset a workflow file accepts, from builders, values, references, wiring, branches, loops and function code. +--- + +A workflow file is a declaration of blocks and connections, not a program. Sim reads it statically and never runs it, so the file holds a fixed set of forms. This page lists them. A form outside it is refused with `E_UNSUPPORTED_SYNTAX` and a hint that names the supported form. The types for every builder are in `.sim/sdk/` after a `get`, and `sim workflows source params ` prints one builder's params. + +## An example + +A webhook receives a ticket, an agent classifies it, billing tickets are logged to a table, and the team hears about every ticket in Slack. This is the file `sim workflows source get` prints for it: + +```ts title="workflow.ts" +// @sim-sdk 1 +import { + agent, + condition, + credential, + env, + js, + slack, + t, + table, + trigger, + workflow, +} from '@sim/workflow-sdk' + +export default workflow( + 'Support triage', + { variables: { escalations: { type: 'number', value: 0 } } }, + () => { + const ticketIn = trigger.webhook('Ticket in', { + requireAuth: true, + token: env.TICKETS_WEBHOOK_TOKEN, + inputFormat: { subject: 'string', body: 'string', contacts: 'array' }, + responseMode: 'custom', + responseStatusCode: 202, + responseBody: { ok: true }, + }) + const classify = agent('Classify', { + messages: [ + { role: 'system', content: 'Classify support tickets.' }, + { + role: 'user', + content: t`${ticketIn.subject} + +${ticketIn.body}`, + }, + ], + model: 'claude-sonnet-5-5', + responseFormat: { + name: 'ticket', + strict: true, + schema: { + type: 'object', + additionalProperties: false, + required: ['category', 'urgent'], + properties: { + category: { type: 'string', enum: ['billing', 'bug', 'other'] }, + urgent: { type: 'boolean' }, + }, + }, + }, + }) + const byCategory = condition('By category', { + billing: js`${classify.category} === 'billing'`, + else: true, + }) + const logTicket = table.insertRow('Log ticket', { + tableId: table('tickets'), + data: { subject: ticketIn.subject, category: classify.category }, + }) + const notify = slack.sendMessage('Notify', { + credential: credential('support-slack'), + channel: 'C0SUPPORT', + text: t`New ${classify.category} ticket (urgent: ${classify.urgent}): ${ticketIn.subject}`, + }) + + ticketIn.to(classify) + classify.to(byCategory) + byCategory.billing.to(logTicket) + byCategory.else.to(notify) + logTicket.to(notify) + logTicket.onError(notify) + } +) +``` + +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. +- `.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. + +## The file + +```ts +// @sim-sdk 1 +import { agent, t, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Name', { description: '…', variables: { /* … */ } }, ({ vars }) => { + const start = trigger.start('Start', { inputFormat: { question: 'string' } }) + const answer = agent('Answer', { model: 'claude-sonnet-5-5', messages: [ /* … */ ] }) + start.to(answer) +}) +``` + +- Line 1 is `// @sim-sdk N`. Without it the file is refused with `E_SDK_HEADER`; a number newer or older than the server reads is `E_SDK_MAJOR` or `E_SDK_MAJOR_OLD`. +- 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.`. +- 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 + +- `const x = builder('Name', params?, meta?)` declares a block; a bare `builder(…)` statement does too. The builder is the block's dotted path in the catalog: `agent`, `slack.sendMessage`, `table.insertRow`, `trigger.gmail.poller`. An unknown path is `E_UNKNOWN_BUILDER`, with a did-you-mean. Builders under `legacy.` are old block versions a workflow may already hold; do not write new ones. +- `block(type, 'Name', params?, meta?)` writes any block type, including a custom or legacy one that no builder fits. Params are checked against the catalog when it knows the type, and kept as written when it does not. +- A name is a non-empty string literal (`E_NAME_NOT_LITERAL`, `E_EMPTY_NAME`), unique once normalized (`E_DUPLICATE_NAME`), and not `loop`, `parallel` or `variable` (`E_RESERVED_NAME`). A name with a look-alike character, such as a Cyrillic letter inside a Latin word, is `E_LOOKALIKE_NAME`, and one with a bidirectional control or zero-width character is `W_SUSPICIOUS_CHARACTER`. +- `response(name, { body, status?, headers? })` is the Response block. Any other key is `E_UNKNOWN_PARAM`. + +### Params + +- 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 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 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 + +For a field that offers a selector in the builder, a resource helper (`credential('key')`, `table('key')` and the others in the next section) or a non-empty array of them selects the resource. Anything else, such as `channel: 'C0123'`, is the value typed into the field. The kind of value alone decides which one you mean. + +### `meta` + +The optional third argument holds what belongs to the block, not to its settings. + +| Key | Meaning | +| --- | --- | +| `disabled: true` | The block is disabled. | +| `locked: true` | An apply refuses any change to this block. | +| `errorPort: boolean` | Exposes the error port. A block with an `onError` edge has one without this. | +| `retry: { enabled, maxTries, waitBetweenTriesMs }` | The block's retry policy, written whole. `maxTries` is a whole number from 2 to 5 and `waitBetweenTriesMs` from 0 to 5000; anything else is `E_UNSUPPORTED_SYNTAX`. | +| `advancedMode: boolean` | The block's advanced toggle, which changes what it sends. | +| `triggerMode: boolean` | Runs the block as a trigger. Trigger builders set it. | +| `branches: { : { title? } }` | The display title of a condition or router row. | +| `key: ''` | A legacy block key the name cannot produce. A `get` writes it for a stored block that needs it; any other value is `E_KEY_OVERRIDE`. | + +## Values + +- Literals, objects, arrays and negative numbers are written as in TypeScript. A number too large to store is `E_NUMBER_NOT_FINITE`, and one whose digits a number cannot hold is `W_NUMBER_PRECISION`: write it as a string. +- A string is `'…'`, an untagged template without `${}`, or a tagged template: + + | Tag | For | + | --- | --- | + | `` t`…` `` | Text with references or `env.X` in it | + | `` js`…` `` | JavaScript: a condition expression, or function code inline | + | `` py`…` ``, `` sh`…` `` | Python and shell code | + | `` json`…` `` | JSON text kept as written | + | `` md`…` `` | Markdown, such as a note's content | + +### Resource helpers + +A key is the resource's stable key in the workspace; `.sim/sdk/workspace.d.ts` lists them. A key with no live resource is `E_MAT_UNKNOWN_RESOURCE` on apply. + +| Form | Stands for | +| --- | --- | +| `credential('key')` | A saved credential | +| `table('key')` | A workspace table | +| `knowledgeBase('key')` | A knowledge base | +| `file('path')` | A workspace file | +| `folder('key')` | A workspace folder | +| `childWorkflow('key')` | A workflow, for `runWorkflow`; `.asTool()` in a `tools` list | +| `customTool('key')` | A custom tool, in a `tools` list | +| `mcp('key')` | An MCP server; `.tool(name)` in a `tools` list | +| `skill('key')` | A workspace skill | +| `codeFile('./functions/x.js')` | Function code kept in its own file | +| `stored()` | The value already stored for this param, which is not printed | +| `todo()` | No value yet | +| `env.X` | The environment variable `X`, which a block reads as `{{X}}`. The name must match `[A-Za-z_][A-Za-z0-9_]*` (`E_INVALID_ENV_NAME`) | + +In a workspace directory, `sim workspaces source check` reports a key the directory does not declare; see [Manage a workspace as code](/workflows/code/workspace). + +### 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`. + +### References + +- `block.output`, `block['x-y']` and `block.items[0]` read another block's output; they are stored as ``, `` and ``. The path is typed from the block's outputs. A path no output has is `W_UNKNOWN_OUTPUT_PATH`, which the apply refuses as an error on a block the edit changed. +- An agent's declared `responseFormat` fields and a Start, API or Input trigger's declared `inputFormat` fields count as outputs. An input the trigger does not declare, and `x.error` on a block with no error edge, are `W_OUTPUT_PATH_UNDECLARED`: a warning the apply never refuses, because a caller may still pass the input. +- A reference to a block declared later is `W_FORWARD_REF` and still resolves. A reference into a sibling loop or parallel's child is `E_OUT_OF_SCOPE`. An identifier that names nothing is `E_UNKNOWN_IDENTIFIER`, with a did-you-mean. +- `vars.x` reads a workflow variable; an undeclared one is `E_UNKNOWN_VARIABLE`. +- `ref('Raw.path')` writes the reference text `` as you gave it. Hand-written `` text whose head is not a block key is `W_REF_NOT_NORMALIZED`. + +### JSON fields + +A field that holds JSON text, such as `responseFormat`, a table row's `data` or a response body, takes an object or array literal and stores it as formatted JSON. Each bare reference inside is quoted when the output is a string and left bare otherwise, because the run splices a string raw and any other value as JSON. A reference no output type is known for is stored bare with `W_JSON_REF_UNTYPED`. A template is a JSON string, which is how a value becomes text on purpose. A resource helper inside the literal is `E_UNSUPPORTED_SYNTAX`. + +### Input formats and tools + +- `inputFormat` is a record: `name: 'string'` declares a string input, and `name: { type, … }` declares one with options. An entry with no type, such as `count: 5`, is refused. +- An agent's `tools` is an array of: + - `slack.tool.sendMessage(params)`: an integration operation, written as the block's namespace, `tool`, and the operation; + - `customTool('key')`: a workspace custom tool; + - `mcp('key').tool('name', { args? })`: one tool of an MCP server, with the arguments the workflow fixes; + - `childWorkflow('key').asTool()`: a child workflow; + - `raw(tool)`: any other stored tool, which a `get` writes when a tool does not fit the forms above. +- A tool's secret prints as `params: { key: stored() }`, resolved like a block's `stored()`. A tool that no rule matches to a stored one is `E_STORED_VALUE_MISSING`, so a deleted or reordered tool never takes another tool's secret. + +## Function code + +Code that does not fit a block goes in a Function block, kept in its own file: + +```ts +const score = fn('Score lead', { code: codeFile('./functions/score-lead.js') }) +``` + +The path is `./functions/.`, relative to `workflow.ts`, and the extension matches the block's `language`: `js` for JavaScript (the default), `py` for Python, `sh` for shell. Any other path is `E_CODE_FILE_PATH`, and a file that was not sent is `E_CODE_FILE_MISSING`. When code cannot be kept in a file, a `get` writes it inline as `` js`…` `` and reports `W_CODE_FILE_INLINED`. + +In a JavaScript file, `$ref.block.path` reads another block's output and `$env.NAME` reads an environment variable. `block` is the block's key: its name lowercased with all whitespace and every `.` removed (`$ref.triageagent.content` for "Triage Agent", `$ref.v2result.text` for "V2. Result"). Inside a loop body, `$ref.loop.currentItem` and `$ref.loop.index` read the iteration's item and position; inside a parallel body, `$ref.parallel.currentItem` and `$ref.parallel.index`. A `$ref` that names no block is refused in a file you edited, because it would not resolve when the workflow runs. Python and shell files are saved as written, so `$ref` and `$env` mean nothing there: read an output as `` (``) and an environment variable as `{{NAME}}`; a `$ref` in one is `W_CODE_FILE_REF_SYNTAX`. + +## Branches + +- A condition's params object lists its rows in order, each a string or template. Write `else: true` last for the empty else. Two or more rows must end with `else` (`E_BRANCH_ELSE_LAST`). +- A router's rows are `routes: { key: text }`. +- A branch key is unique (`E_DUPLICATE_BRANCH_KEY`) and may not be an output name, `to` or `onError` (`E_BRANCH_KEY_COLLIDES`). +- A branch that no edge leaves ends the run on that path; `check` reports it as `W_BRANCH_UNWIRED`. + +## Loops and parallel blocks + +| Form | Runs | +| --- | --- | +| `loop.for('Name', { count }, body)` | `count` times; a loop with no `count` runs 5 | +| `loop.forEach('Name', { collection }, body)` | once per item | +| `loop.while('Name', { condition }, body)` | while the condition holds | +| `loop.doWhile('Name', { condition, count }, body)` | until the condition stops it; with no condition, `count` times | +| `parallel.count('Name', { count, batchSize }, body)` | `count` branches | +| `parallel.collection('Name', { collection, batchSize }, body)` | one branch per item | + +- `body` is `(p) => { … }`, where `p.to(x)` connects the container's start to a block inside it, or `(p) => block(…)`, which does the same for one block. +- `p.index`, `p.currentItem` and `p.items` read the iteration; any other property is `E_UNKNOWN_SUBFLOW_PROPERTY`. They are stored as `` or ``. +- A `count` that is not a whole number of at least 1, or a `batchSize` outside 1 to 20, is `W_SUBFLOW_COUNT`: the run replaces or clamps it. + +## Wiring + +| Form | Connects | +| --- | --- | +| `a.to(b, c)` | `a` to `b` and `a` to `c` | +| `a.to(b).to(c)` | a chain | +| `a.to(b, c).to(d)` | `b` to `d` and `c` to `d` | +| `a.onError(b)` | the error path of `a` | +| `cond.key.to(x)` | one branch of a condition or router | +| `container.to(x)` | what runs after the loop or parallel finishes | + +Refused: `.to()` on a condition or router itself (`E_NO_DEFAULT_OUTPUT`; wire a branch), a branch that does not exist (`E_UNKNOWN_BRANCH`), an edge into a trigger (`E_TARGET_TRIGGER`), `onError` on a block with no error port (`E_ERROR_PORT_UNSUPPORTED`), an edge to or from a note (`E_EDGE_NOTE`), an edge across loop or parallel scopes (`E_EDGE_SCOPE`), a repeated edge (`E_DUPLICATE_EDGE`) and a cycle (`E_EDGE_CYCLE`). Repeat work with a `loop` instead. + +## Comments + +Comments you write are kept and written back where they were. One inside an expression moves to the statement it belongs to (`W_COMMENT_MOVED`). One whose block no longer exists is dropped (`W_COMMENT_DROPPED`). + +## Related docs + +- [Diagnostic codes](/workflows/code/diagnostics) +- [Edit a workflow](/workflows/code/edit) +- [Directory layout](/workflows/code/directory) +- [Limits](/workflows/code/limits) diff --git a/apps/docs/content/docs/workflows/code/workspace.mdx b/apps/docs/content/docs/workflows/code/workspace.mdx new file mode 100644 index 00000000000..be03a344d3f --- /dev/null +++ b/apps/docs/content/docs/workflows/code/workspace.mdx @@ -0,0 +1,88 @@ +--- +title: Manage a workspace as code +description: Keep a workspace's tables, knowledge bases, files, custom tools, skills and workflows in one directory, and apply it in one step. +--- + +import { Callout } from '@/components/ui/callout' + +A whole workspace can be read and written as a directory: one folder per kind of resource, with each workflow written exactly as [workflows as code](/workflows/code) writes it. One apply creates the resources before the workflows that use them, so a coding agent can build a working setup from scratch. + + +Workspace as code is in preview, behind the [same setting](/workflows/code) as workflows as code. It adds the `sim workspaces source` commands to the [CLI](/cli/workspaces#workspace-as-code). + + +## The directory + +The layout of every kind and each file's role is in [Directory layout](/workflows/code/directory). A resource's key is its file or folder name, and a workflow names it by that key: + +```ts title="workflows/support/workflow.ts" +const policy = knowledge.search('Policy Search', { + knowledgeBaseId: knowledgeBase('policies'), + query: start.question, +}) +const answer = agent('Answer', { + model: 'claude-sonnet-4-6', + messages: [{ role: 'user', content: t`${policy.results}\n\n${start.question}` }], + tools: [customTool('lookup-order')], + skills: [skill('tone')], +}) +const log = table.insertRow('Log Question', { + tableId: table('orders'), + data: { orderId: start.orderId, status: 'answered' }, +}) +``` + +`get` prints a short primer for coding agents (in JSON output, its `primer` field) and writes it atop `.sim/AGENTS.md`, the guide, with deletes in depth, Git and CI, and promoting to another workspace in `.sim/GUIDE-advanced.md`. It also writes `.sim/examples/workspace/`, a complete example of every kind and the workflow that uses them. + +## Edit a workspace + +```bash +sim workspaces source get --dir ./my-workspace +sim workspaces source check --dir ./my-workspace +sim workspaces source status --dir ./my-workspace +sim workspaces source apply --dir ./my-workspace --dry-run +sim workspaces source apply --dir ./my-workspace --yes +``` + +`check` compiles every workflow on your machine against what the directory declares: an unknown table, credential, knowledge base, skill, custom tool, MCP server or workflow key, a table row write naming a column the table does not declare, and a child workflow call whose `inputMapping` names an input the child's Start trigger does not declare, are reported, and an env name `secrets.ts` lacks is a warning. It checks each `tables/.rows.jsonl` line against its table the way an apply writes it (a required cell, a unique value, a column's type and select options), so the dry run's `E_TABLE_ROWS` shows up offline at its line. It exits 1 on errors and, as `sim workflows source check` does, on a broken block you added. + +Unlike a workflow directory's `check`, it needs the block catalog but fetches it for you: on a fresh clone with none cached it downloads the catalog once with the profile's credentials, and without credentials it exits `1` and tells you to run `get`. It also regenerates `.sim/sdk/workspace.d.ts` from the declarations, so run `bunx -p typescript@7.0.2 tsc -p ./my-workspace` after it to type-check every file, keys added since the get included. Run in a `workflows/` folder, `sim workflows source check --dir .` checks that one workflow the same way. + +The dry run prints the plan (`+` create, `~` update, `=` adopt an existing resource with the same name, `-` delete) and every error with its file and line. `--only tables,workflows` limits a get or an apply to some kinds. + +An apply adopts a resource it never read (one made in Sim under the name a new declaration gives) only when the declaration matches it, or only adds to it: a column, rows into an empty table, a document. An adopt that would change or remove anything the resource holds is refused with `E_APPLY_NO_BASE`, even with `--allow-delete`. Run `get` into a new directory to read the resource, then make your edit there, or give the declaration another name. + +`status` shows what would happen if you applied, without writing anything: the files you created, edited, or deleted, grouped by resource; what changed in Sim since the `get` (a resource edited, added, or deleted there, a workflow edited in the workflow builder included); the conflicts, where a resource changed on both sides; and the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unapplied, and `12` when something changed in Sim since the `get`, so a script or an agent can branch on it. Its JSON `plan` counts errors and warnings as the dry run of the apply it names next would, a conflict as an error. Without a connection it shows your edits only and says so; `--offline` skips the server. `diff [paths or kind:key…]` prints the edits as unified diffs (a binary file by its sizes), and `diff --server` compares the directory with what Sim holds now. Both take `--json` (or `--output json`). + +## Workspace API keys [#workspace-api-keys] + +A personal API key or an OAuth login can apply every kind its workspace role allows. A workspace API key cannot create or change workflows, skills, secrets or deployments. An apply with one that would is refused with `E_APPLY_FORBIDDEN`, naming each resource, before anything is written. A `get` with a workspace key leaves out the kinds it cannot read, such as `secrets.ts`, and names them with the same code. + +To apply the rest with a workspace key, such as in CI, narrow the apply to the kinds it can write: `sim workspaces source apply --dir ./my-workspace --only tables,knowledge,files,tools,mcp,credentials.ts --yes`. Deployments need an admin's personal key. + +## Deletes + +- A kind is managed only when its folder exists. A directory without `skills/` never touches a skill. +- Removing the file of a resource the directory manages deletes it only with `--allow-delete`; without the flag the apply is refused. The flag also covers a removed table column, managed table row, knowledge base document, workspace file, workflow block or workflow variable. +- A resource the directory never managed is kept, and the apply names it in a warning. +- Something deleted in Sim is not re-created by an unchanged directory, and an edit to it is refused as stale. +- Table rows are part of the directory only when the table's `rows` opts in (`tables/.rows.jsonl`). Connector-synced documents and run history never are. +- Seed rows (`rows: { mode: 'seed' }`) belong to the directory: `get` keeps the declaration and the rows file beside it, but Sim does not store them, so a get into a new directory has the declaration without the file. +- A delete cannot be undone by applying an older copy of the directory, such as a reverted commit. The resource stays deleted, and its rows, documents, run history, webhook URLs and schedules are gone. The dry run marks each change that deletes data and counts them as `destructive`, a workflow update that removes blocks or variables included. + +## Good to know + +- Secret values never appear. Workflows read environment variables as `env.NAME`, tool code as `$env.NAME`, and credentials by key. +- Renaming a skill does not rewrite the workflows that use it: each agent keeps the name it stored until its skills list is next edited. +- Hidden files (a name starting with a dot, such as `files/.env`) and names with a character no workspace path holds (such as `:` or `?`) are never sent. An apply names each one in a `W_PATH_NOT_SENT` warning. +- A knowledge base's `embeddingModel` is fixed when it is created. An apply that changes it is refused. +- An apply that stops part-way exits `8`, prints the plan again with each change marked written or not written (`notWritten` in JSON), and saves what it wrote into the directory. Run the same apply again until it exits `0`. The dry run checks an MCP server's URL as the write does, so an unresolvable host is refused before anything is written. +- An apply exits `5` when a resource changed in Sim after you read it. Run `get` into a new directory and reapply your edit. +- Size caps, and what is left out of a get, are in [Limits](/workflows/code/limits). + +## Related docs + +- [Promote to another workspace](/workflows/code/promote) +- [Run in CI](/workflows/code/ci) +- [Directory layout](/workflows/code/directory) +- [CLI workspace commands](/cli/workspaces#workspace-as-code) diff --git a/apps/docs/content/docs/workflows/meta.json b/apps/docs/content/docs/workflows/meta.json index 8762490d5cb..bfbd3c07fdc 100644 --- a/apps/docs/content/docs/workflows/meta.json +++ b/apps/docs/content/docs/workflows/meta.json @@ -6,8 +6,6 @@ "connections", "variables", "large-data", - "code", - "workspace-code", "deployment", "triggers", "blocks" diff --git a/apps/docs/content/docs/workflows/workspace-code.mdx b/apps/docs/content/docs/workflows/workspace-code.mdx deleted file mode 100644 index e75a9f22189..00000000000 --- a/apps/docs/content/docs/workflows/workspace-code.mdx +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Workspace as code -description: Keep a workspace's tables, knowledge bases, files, custom tools, skills and workflows in one directory, and apply it in one step. ---- - -import { Callout } from '@/components/ui/callout' - -A whole workspace can be read and written as a directory: one folder per kind of resource, with each workflow written exactly as [workflows as code](/workflows/code) writes it. One apply creates the resources before the workflows that use them, so a coding agent can build a working setup from scratch. - - -Workspace as code is in preview, behind the [same setting](/platform/self-hosting/environment-variables#preview-features) as workflows as code. It adds the `sim workspaces source` commands to the [CLI](/cli/workspaces). - - -## The directory - -``` -secrets.ts the env variable names workflows read (never a value) -credentials.ts the saved credentials workflows use, by provider -tables/orders.ts a table: name, description, columns -tables/plans.rows.jsonl a table's rows, one JSON object per line (only when the table opts in) -knowledge/policies/knowledge.ts a knowledge base: name, chunking -knowledge/policies/docs/*.md one file per document -files/templates/reply.md a workspace file, at its folder path -tools/lookup-order.ts a custom tool: title and schema -tools/lookup-order.js the tool's code -skills/tone.md a skill: name and description, then its content -mcp/docs.ts an MCP server: url, headers -workflows/support/workflow.ts a workflow source 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: - -```ts title="workflows/support/workflow.ts" -const policy = knowledge.search('Policy Search', { - knowledgeBaseId: knowledgeBase('policies'), - query: start.question, -}) -const answer = agent('Answer', { - model: 'claude-sonnet-4-6', - messages: [{ role: 'user', content: t`${policy.results}\n\n${start.question}` }], - tools: [customTool('lookup-order')], - skills: [skill('tone')], -}) -const log = table.insertRow('Log Question', { - tableId: table('orders'), - data: { orderId: start.orderId, status: 'answered' }, -}) -``` - -`get` prints a short primer for coding agents (in JSON output, its `primer` field) and writes it atop `.sim/AGENTS.md`, the guide, with deletes in depth, Git and CI, and promoting to another workspace in `.sim/GUIDE-advanced.md`. It also writes `.sim/examples/workspace/`, a complete example of every kind and the workflow that uses them. - -## Edit a workspace from the CLI - -```bash -sim workspaces source get --dir ./my-workspace -sim workspaces source check --dir ./my-workspace -sim workspaces source status --dir ./my-workspace -sim workspaces source apply --dir ./my-workspace --dry-run -sim workspaces source apply --dir ./my-workspace --yes -``` - -`check` compiles every workflow on your machine, without a request, against what the directory declares: an unknown table, credential, knowledge base, skill, custom tool, MCP server or workflow key, a table row write naming a column the table does not declare, and a child workflow call whose `inputMapping` names an input the child's Start trigger does not declare, are reported, and an env name `secrets.ts` lacks is a warning. It checks each `tables/.rows.jsonl` line against its table the way an apply writes it (a required cell, a unique value, a column's type and select options), so the dry run's `E_TABLE_ROWS` shows up offline at its line. It exits 1 on errors and, as `sim workflows source check` does, on a broken block you added. It also regenerates `.sim/sdk/workspace.d.ts` from the declarations, so run `bunx -p typescript@7.0.2 tsc -p ./my-workspace` after it to type-check every file, keys added since the get included. Run in a `workflows/` folder, `sim workflows source check --dir .` checks that one workflow the same way. - -The dry run prints the plan (`+` create, `~` update, `=` adopt an existing resource with the same name, `-` delete) and every error with its file and line. `--only tables,workflows` limits a get or an apply to some kinds. - -An apply adopts a resource it never read (one made in Sim under the name a new declaration gives) only when the declaration matches it, or only adds to it: a column, rows into an empty table, a document. An adopt that would change or remove anything the resource holds is refused with `E_APPLY_NO_BASE`, even with `--allow-delete`. Run `get` into a new directory to read the resource, then make your edit there, or give the declaration another name. - -`status` shows what would happen if you applied, without writing anything: the files you created, edited, or deleted, grouped by resource; what changed in Sim since the `get` (a resource edited, added, or deleted there, a workflow edited in the editor included); the conflicts, where a resource changed on both sides; and the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unapplied, and `12` when something changed in Sim since the `get`, so a script or an agent can branch on it. Its JSON `plan` counts errors and warnings as the dry run of the apply it names next would, a conflict as an error. Without a connection it shows your edits only and says so; `--offline` skips the server. `diff [paths or kind:key…]` prints the edits as unified diffs (a binary file by its sizes), and `diff --server` compares the directory with what Sim holds now. Both take `--json` (or `--output json`). - -## Workspace API keys [#workspace-api-keys] - -A personal API key or an OAuth login can apply every kind its workspace role allows. A workspace API key cannot create or change workflows, skills, secrets or deployments. An apply with one that would is refused with `E_APPLY_FORBIDDEN`, naming each resource, before anything is written. A `get` with a workspace key leaves out the kinds it cannot read, such as `secrets.ts`, and names them with the same code. - -To apply the rest with a workspace key, such as in CI, narrow the apply to the kinds it can write: `sim workspaces source apply --dir ./my-workspace --only tables,knowledge,files,tools,mcp --yes`. - -## Deletes - -- A kind is managed only when its folder exists. A directory without `skills/` never touches a skill. -- Removing the file of a resource the directory manages deletes it only with `--allow-delete`; without the flag the apply is refused. The flag also covers a removed table column, managed table row, knowledge base document, workspace file, workflow block or workflow variable. -- A resource the directory never managed is kept, and the apply names it in a warning. -- Something deleted in Sim is not re-created by an unchanged directory, and an edit to it is refused as stale. -- Table rows are part of the directory only when the table's `rows` opts in (`tables/.rows.jsonl`). Connector-synced documents and run history never are. -- Seed rows (`rows: { mode: 'seed' }`) belong to the directory: `get` keeps the declaration and the rows file beside it, but Sim does not store them, so a get into a new directory has the declaration without the file. -- A delete cannot be undone by applying an older copy of the directory, such as a reverted commit. The resource stays deleted, and its rows, documents, run history, webhook URLs and schedules are gone. The dry run marks each change that deletes data and counts them as `destructive`, a workflow update that removes blocks or variables included. - -## Promote to another workspace - -Apply a directory read from one workspace (dev) to another (prod) with `--to`: - -```bash -sim workspaces source apply --dir ./my-workspace --to "$PROD_WORKSPACE_ID" --dry-run -sim workspaces source apply --dir ./my-workspace --to "$PROD_WORKSPACE_ID" --yes -``` - -Each resource binds by key to the target's own. One the target holds under the same key is updated in place, so a workflow keeps its id and its webhook URLs. A key the target lacks is created. Secrets and credentials bind by name to the target's own, and no value is copied. A resource you deleted from the directory since the last promotion is deleted in the target too, and like any delete it needs `--allow-delete`. Resources only the target holds, such as a table created in prod and the rows its runs wrote, are kept, with or without `--allow-delete`: the plan names each with a `W_UNDECLARED` warning. To delete them as well, pass `--delete-target-only` beside `--allow-delete`; the plan then names each with a `W_PROMOTE_DELETES_TARGET_ONLY` warning, so run it with `--dry-run` first. The directory stays bound to the workspace it was read from. Without `--to`, `check`, `status`, `diff` and `apply` act on the workspace the directory was read from, whatever your default workspace; a `--workspace` naming another one is refused. - -Each promotion records what it left in the target in `.sim/targets/.json`, and the next promotion compares with that record: - -- A resource changed in the target since the last promotion, such as a hotfix made in Sim, is kept when the directory left it alone. -- When the directory changed it too, the promotion is refused as stale and exits `5`. Carry the target's change into the source workspace, or undo it in the target, then promote again. -- A resource deleted in the target since the last promotion stays deleted, with a `W_PROMOTE_TARGET_DELETED` warning. Remove its entry from the record to create it again. -- The first promotion, and any resource the record does not hold (one created in the target since), updates the target to match the directory. Review the dry run first. - -Commit the record with the rest of the directory, so a promotion from CI or another clone compares with it. Don't delete it to get past a stale refusal: without it, the next promotion overwrites every change made in the target since, including rows its workflows wrote. - -## Git and CI - -Commit the whole directory, including `.sim/`: its base files are what an apply compares with, from any clone. The generated `.gitignore` leaves out only temporary files. A fresh clone can run `check`, `apply --dry-run` and `apply` with nothing else. See [Workspace source in CI](/cli/scripting#workspace-source-in-ci) for a GitHub Actions setup. - -In a git repository, `apply` sends the commit checked out (`HEAD`) and the `origin` remote URL, with any credentials, query or fragment removed, as `provenance.gitSha` and `provenance.repo`, each only when `git` can read it (a repository with no `origin` sends only the commit). An apply that writes records what was sent in its `workspace.updated` [audit log](/platform/enterprise/audit-logs) entry. A directory outside a repository sends neither. - -## Good to know - -- Secret values never appear. Workflows read environment variables as `env.NAME`, tool code as `$env.NAME`, and credentials by key. -- Renaming a skill does not rewrite the workflows that use it: each agent keeps the name it stored until its skills list is next edited. -- One apply sends at most 100 edited workflows and makes at most 1,000 changes; a directory holds at most 500 resources of a kind, and a `tables/.rows.jsonl` at most 10,000 rows. An apply over a limit is refused before anything is written. -- A document or file over 10 MB, or whose name a directory cannot hold, is left out of `get` and listed in `.sim/skipped.json`. An apply never writes or deletes it. -- Hidden files (a name starting with a dot, such as `files/.env`) and names with a character no workspace path holds (such as `:` or `?`) are never sent. An apply names each one in a `W_PATH_NOT_SENT` warning. -- A knowledge base's `embeddingModel` is fixed when it is created. An apply that changes it is refused. -- An apply that stops part-way exits `8`, prints the plan again with each change marked written or not written (`notWritten` in JSON), and saves what it wrote into the directory. Run the same apply again until it exits `0`. The dry run checks an MCP server's URL as the write does, so an unresolvable host is refused before anything is written. -- An apply exits `5` when a resource changed in Sim after you read it. Run `get` into a new directory and reapply your edit. - -See [CLI workspace commands](/cli/workspaces) for every flag. diff --git a/apps/docs/lib/redirects.ts b/apps/docs/lib/redirects.ts index be04cce4921..cbc6cc8008f 100644 --- a/apps/docs/lib/redirects.ts +++ b/apps/docs/lib/redirects.ts @@ -110,6 +110,12 @@ const PATH_REDIRECTS: DocsRedirect[] = [ { source: '/building-agents/agents', destination: '/agents', permanent: true }, // form deployment removed { source: '/deployment/form', destination: '/workflows/deployment', permanent: true }, + // workspace as code moved into the workflows-as-code section + { + source: '/workflows/workspace-code', + destination: '/workflows/code/workspace', + permanent: true, + }, // copilot deprecated and removed { source: '/copilot', destination: '/chat', permanent: true }, { source: '/copilot/:path*', destination: '/chat', permanent: true }, diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index 23d8c5a0136..f032813c59e 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -14188,175 +14188,161 @@ "meta": null, "sha256": "b9179e0bca4639a77dbc99a0802c9c18305b65cce5c37ce114b8e215f26070a0", "bytes": 134, - "line": 6 + "line": 10 }, { "lang": "bash", "meta": null, "sha256": "6367a903928d88d568ec633957ade0b5f874989ac59a1cf31c58287830c6c777", "bytes": 170, - "line": 19 + "line": 23 }, { "lang": "bash", "meta": null, "sha256": "61a29fb19683034ec35a9a6cb6caa3a94bbb9b4fd1e8c545fbbd933478ad0844", "bytes": 241, - "line": 33 + "line": 37 }, { "lang": "bash", "meta": null, "sha256": "bc4f2b365fb6d27a0afb6b8ebcdd56e94301c40741300e10ba249e11708274fd", "bytes": 172, - "line": 45 + "line": 49 }, { "lang": "bash", "meta": null, "sha256": "dc652d6ae196b4ad1d37da8dcdee9ae36e1798498e10f94882a117410d43e45f", "bytes": 202, - "line": 56 + "line": 60 }, { "lang": "bash", "meta": null, "sha256": "5e0490835e43a237fec4df37f9bab2c053f332d26b38ae42ea710c1958d66fba", "bytes": 110, - "line": 67 + "line": 71 }, { "lang": "bash", "meta": null, "sha256": "2017d76c972d478c166fc271da149acdf01f3c5906a6b068e07d91b684fc2e24", "bytes": 65, - "line": 75 + "line": 79 }, { "lang": "bash", "meta": null, "sha256": "8237f3c905a4fed316c3cabae5b8cddd72c57d8e3e3abe712ebce4116246f82a", "bytes": 53, - "line": 84 + "line": 88 }, { "lang": "bash", "meta": null, "sha256": "abad6fbd8c82c1eb28d7a7f4b49f8cce9754472b20ffb2613a6a69ae8c2823b4", "bytes": 51, - "line": 92 + "line": 96 }, { "lang": "bash", "meta": null, "sha256": "7f0dad13a24bafce09cf14f505da3d6d956a0431e24845a80cd01b1a775e8374", "bytes": 263, - "line": 98 + "line": 102 }, { "lang": "json", "meta": null, "sha256": "a19ec054796bc74549f7dbe83949c9eb6c5ae1f54cda5b5c9f8a7e1db5f99d80", "bytes": 349, - "line": 113 + "line": 117 }, { "lang": "bash", "meta": null, "sha256": "068b9eadd1fcffae232855024fdb4ff017b0f010ced2273c53f3b3fd2e898de2", "bytes": 236, - "line": 226 + "line": 176 }, { "lang": "bash", "meta": null, "sha256": "21d6503ee5e2f4362d6d086a74d41704bded199dd6f1a7a2f5760d4c06a78dab", "bytes": 260, - "line": 238 + "line": 188 }, { "lang": "bash", "meta": null, "sha256": "774f1a6b1c5e4ad85fa5551fba8a5faed7d82b3bb25e7d46336fb0b65e1e9522", "bytes": 220, - "line": 257 + "line": 207 }, { "lang": "bash", "meta": null, "sha256": "736d071516b05af975232c48c7e23065fc0334fc07c541ada21a806ea43f84e7", "bytes": 109, - "line": 270 + "line": 220 }, { "lang": "bash", "meta": null, "sha256": "019796d6002868ad852ec9b9bba75bff42f7f8f6eb2073dfb897aa359065721a", "bytes": 159, - "line": 276 + "line": 226 }, { "lang": "bash", "meta": null, "sha256": "3a91f6de422f9407871de6fa5bac996f2337001079def7f966bd0068086d7c63", "bytes": 199, - "line": 285 + "line": 235 }, { "lang": "bash", "meta": null, "sha256": "cdbd2c99596ad694d9ebd9eca43740e8c7371fabba9eca7cc580c16ae96bc800", "bytes": 166, - "line": 302 + "line": 252 }, { "lang": "bash", "meta": null, "sha256": "3edb250258fdf417424a8f185dd601a1a6374ce8b93dd553276cfef39875f959", "bytes": 323, - "line": 317 + "line": 267 }, { "lang": "bash", "meta": null, "sha256": "1d949072a36a628c98e3d17961acc9c59f07edcc89f63413f212adc3baec879e", "bytes": 290, - "line": 326 + "line": 276 }, { "lang": "bash", "meta": null, "sha256": "4cc080decc18686ffbbfe9c5c51c621d23d2b8de9f189ed8145973189681900b", "bytes": 219, - "line": 336 + "line": 286 }, { "lang": "bash", "meta": null, "sha256": "ab8b2eb4638d04f81b66e3eba3d9acfe49e6ae2531094ed48d0d3468537c188b", "bytes": 160, - "line": 343 + "line": 293 }, { "lang": "bash", "meta": "title=\"nightly-digest.sh\"", "sha256": "25d588b87d9f49723f0b1e41edadedfb33ec1eb28460b9b8574d2dfef87a7870", "bytes": 747, - "line": 352 - }, - { - "lang": "yaml", - "meta": "title=\".github/workflows/sim-workspace.yml\"", - "sha256": "9e7ef199fcc3626b482f4377b15d500c8cf417675cdf19fbdcf9188cce424963", - "bytes": 1136, - "line": 382 - }, - { - "lang": "bash", - "meta": null, - "sha256": "3b675df64318861fe48f8c955db2eaee667edaafd4389e2f4bb220fcf5445fee", - "bytes": 75, - "line": 427 + "line": 302 } ], "links": [ diff --git a/apps/sim/lib/mothership/generated/docs-manifest.ts b/apps/sim/lib/mothership/generated/docs-manifest.ts index cb6256a2947..b365dff58b2 100644 --- a/apps/sim/lib/mothership/generated/docs-manifest.ts +++ b/apps/sim/lib/mothership/generated/docs-manifest.ts @@ -500,6 +500,18 @@ export const DOCS_MANIFEST: readonly string[] = [ 'workflows/blocks/webhook.mdx', 'workflows/blocks/workflow.mdx', 'workflows/code.mdx', + 'workflows/code/ci.mdx', + 'workflows/code/coding-agents.mdx', + 'workflows/code/create.mdx', + 'workflows/code/diagnostics.mdx', + 'workflows/code/directory.mdx', + 'workflows/code/edit.mdx', + 'workflows/code/exit-codes.mdx', + 'workflows/code/get-started.mdx', + 'workflows/code/limits.mdx', + 'workflows/code/promote.mdx', + 'workflows/code/syntax.mdx', + 'workflows/code/workspace.mdx', 'workflows/connections.mdx', 'workflows/data-flow.mdx', 'workflows/deployment.mdx', @@ -516,5 +528,4 @@ export const DOCS_MANIFEST: readonly string[] = [ 'workflows/triggers/table.mdx', 'workflows/triggers/webhook.mdx', 'workflows/variables.mdx', - 'workflows/workspace-code.mdx', ] diff --git a/package.json b/package.json index eda9b13af7c..67bb934aec4 100644 --- a/package.json +++ b/package.json @@ -126,6 +126,8 @@ "sim-setup": "bun run packages/sim-setup/src/index.ts", "generate:agent-stream-docs": "bun run scripts/sync-agent-stream-docs.ts", "check:agent-stream-docs": "bun run scripts/sync-agent-stream-docs.ts --check", + "generate:workflow-code-docs": "bun run scripts/sync-workflow-code-docs.ts", + "check:workflow-code-docs": "bun run scripts/sync-workflow-code-docs.ts --check", "prepare": "bun husky", "test:workflow-sync": "bun --no-env-file scripts/test-integration.ts lib/workspaces/__integration__", "type-check": "bun run type-check:scripts:esm && turbo run type-check", diff --git a/packages/sim-cli/README.md b/packages/sim-cli/README.md index ae9bc8c691c..752eb70050b 100644 --- a/packages/sim-cli/README.md +++ b/packages/sim-cli/README.md @@ -356,7 +356,7 @@ use a personal API key or an OAuth login, since a workspace API key cannot save workflows. See [Workflows as code](https://docs.sim.ai/workflows/code) and -[Workspace as code](https://docs.sim.ai/workflows/workspace-code). +[Workspace as code](https://docs.sim.ai/workflows/code/workspace). ## CI and automation @@ -369,7 +369,7 @@ export SIM_WORKSPACE="" sim workflows run --input @input.json --output json ``` -Create and revoke API keys in Sim under **Settings → API keys**, and store them +Create and revoke API keys in Sim under **Settings → Sim API keys**, and store them in your CI provider's secret store. `sim logout` only removes a stored key from the current machine; it does not revoke the key. diff --git a/packages/sim-cli/src/commands/auth.test.ts b/packages/sim-cli/src/commands/auth.test.ts index c19a122dcff..027b402e7f6 100644 --- a/packages/sim-cli/src/commands/auth.test.ts +++ b/packages/sim-cli/src/commands/auth.test.ts @@ -354,7 +354,7 @@ describe('login command', () => { expect(mocks.writeCredentialsProfile).not.toHaveBeenCalled() const output = vi.mocked(console.log).mock.calls.flat().join('\n') expect(output).toContain('API key key-id was created on your account') - expect(output).toContain('Revoke "CLI (2026-11-11 09:30:00Z)" in Settings → API keys.') + expect(output).toContain('Revoke "CLI (2026-11-11 09:30:00Z)" in Settings → Sim API keys.') }) it('stores nothing when the issued expiry is not the one requested', async () => { diff --git a/packages/sim-cli/src/commands/auth.ts b/packages/sim-cli/src/commands/auth.ts index 0641916a2bd..ce945ee507f 100644 --- a/packages/sim-cli/src/commands/auth.ts +++ b/packages/sim-cli/src/commands/auth.ts @@ -755,7 +755,7 @@ async function loginWithHandoff( : `the newest key named "CLI (…Z)", created at about ${new Date().toISOString().slice(0, 19).replace('T', ' ')}Z,` printLine( styles().yellow( - `API key ${keyId} was created on your account but could not be stored safely. Revoke ${listedAs} in Settings → API keys.` + `API key ${keyId} was created on your account but could not be stored safely. Revoke ${listedAs} in Settings → Sim API keys.` ) ) throw error @@ -851,7 +851,7 @@ export function logoutCommand(): Command { printLine(styles().green(`✓ Removed profile "${safeOneLine(profileName)}".`)) if (credential?.kind === 'api_key') { printLine( - styles().dim(' The key itself is still active — revoke it in Settings → API keys.') + styles().dim(' The key itself is still active — revoke it in Settings → Sim API keys.') ) } return @@ -886,7 +886,7 @@ export function logoutCommand(): Command { if (credential.kind === 'api_key') { /** Local API-key removal cannot revoke the server-side key. */ printLine( - styles().dim(' The key itself is still active — revoke it in Settings → API keys.') + styles().dim(' The key itself is still active — revoke it in Settings → Sim API keys.') ) } }) diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts index c159398d877..06cf8d8e4c9 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.test.ts @@ -24,27 +24,6 @@ const WORKFLOW_SDK_README = readFileSync( 'utf8' ) -const SCRIPTING_DOCS = readFileSync( - join(import.meta.dirname, '../../../../../apps/docs/content/docs/cli/scripting.mdx'), - 'utf8' -) - -/** The codes of each `| Code | |` table in the scripting docs, by its header cell. */ -const DOCS_TABLES = new Map( - SCRIPTING_DOCS.split(/\n\s*\n/).flatMap((block) => { - const header = block.match(/^\| Code \| (.+) \|$/m) - if (!header) return [] - const codes = [...block.matchAll(/^\| `(\d+)` \|/gm)].map((match) => Number(match[1])) - return [[header[1], codes] as const] - }) -) - -function docsTable(heading: string): number[] { - const codes = DOCS_TABLES.get(heading) - if (!codes) throw new Error(`scripting.mdx has no exit-code table headed ${heading}`) - return codes -} - describe('the exit-code tables an agent or a reader relies on', () => { it.each([ ['the workflow directory guide', WORKFLOW_TREE.agents], @@ -56,28 +35,6 @@ describe('the exit-code tables an agent or a reader relies on', () => { }) }) -describe('the exit-code tables of the CLI scripting docs', () => { - it.each([ - ['workflows source apply', '`sim workflows source apply` or `create`'], - ['workflows source create', '`sim workflows source apply` or `create`'], - ['workflows source get', '`sim workflows source get --dir` or `sim workspaces source get`'], - ['workspaces source get', '`sim workflows source get --dir` or `sim workspaces source get`'], - ['workspaces source apply', '`sim workspaces source apply`'], - ] as const)('list every code %s names in its --help', (command, heading) => { - const help = sourceExitCodesHelp(command).replace(/\s+/g, ' ') - const named = [...help.matchAll(/(?:: |; )(\d+) /g)].map((match) => Number(match[1])) - expect(named.length).toBeGreaterThan(0) - expect(docsTable(heading)).toEqual(expect.arrayContaining(named)) - }) - - it('name only codes a source command exits with', () => { - const sourceTables = [...DOCS_TABLES].filter(([heading]) => heading.includes(' source ')) - expect(sourceTables.length).toBeGreaterThanOrEqual(5) - for (const [, codes] of sourceTables) - expect(SOURCE_EXIT_CODES).toEqual(expect.arrayContaining(codes)) - }) -}) - describe('the exit codes a get names in its --help', () => { it.each(['workflows source get', 'workspaces source get'] as const)( '%s names exit 13 for a missing or refused login', diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts index c34915129f7..9ecdbb61c59 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts @@ -20,7 +20,7 @@ const INTERRUPTED_EXIT_CODE = 130 const DEFERRED_SECONDS = DEFERRED_INTERRUPT_BOUND_MS / 1000 /** The command group a directory guide's exit-code table is for. */ -type SourceCommandGroup = 'sim workflows source' | 'sim workspaces source' +export type SourceCommandGroup = 'sim workflows source' | 'sim workspaces source' /** A source command whose `--help` lists its exit codes from {@link sourceExitCodeRows}. */ export type SourceHelpCommand = @@ -54,7 +54,7 @@ const WORKFLOW_DIR_BUSY = * one table the directory guides and each command's `--help` are built from, so neither can * drift from the codes the CLI exits with. `prefix` is the command group a guide is for. */ -function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRow[] { +export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRow[] { return [ { code: 0, @@ -101,7 +101,7 @@ function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRow[] { code: SOURCE_LOCKED_EXIT_CODE, meaning: 'A workflow or its folder is locked (`E_APPLY_LOCKED`); a locked block exits 1 instead', - next: 'Ask someone to unlock it in the editor', + next: 'Ask someone to unlock it in the workflow builder', help: { 'workflows source apply': 'the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK)', diff --git a/packages/workspace-code/src/diagnostics/codes.ts b/packages/workspace-code/src/diagnostics/codes.ts index c35be3967e7..b0bc94ad38a 100644 --- a/packages/workspace-code/src/diagnostics/codes.ts +++ b/packages/workspace-code/src/diagnostics/codes.ts @@ -7,6 +7,9 @@ * workflow code already says ({@link SHARED_CODES}) use that code, and every other workspace code * is one the workflow vocabulary does not hold ({@link WorkspaceDiagnosticCode} is `never` if it * does). + * + * The TSDoc above each code is its meaning in the public docs: `bun run generate:workflow-code-docs` + * reads it, and fails on a code without one. */ import { @@ -60,9 +63,13 @@ const DECLARATION_CODES = [ /** `.sim/base.json`. */ const BASE_CODES = [ + /** The base is not valid JSON. */ 'E_BASE_JSON', + /** `version` is missing or not `1`. */ 'E_BASE_VERSION', + /** A required field is missing or of the wrong type or format. */ 'E_BASE_SHAPE', + /** A field the base does not define (`x-` keys are allowed). */ 'E_BASE_UNKNOWN_FIELD', ] as const diff --git a/scripts/generate-cli-docs.ts b/scripts/generate-cli-docs.ts index 6c83eaefafd..822c1f9a3a4 100644 --- a/scripts/generate-cli-docs.ts +++ b/scripts/generate-cli-docs.ts @@ -425,6 +425,7 @@ const GROUP_SECTIONS: Record = { { title: 'Chat deployments', prefixes: ['chat status', 'chat publish', 'chat unpublish'] }, { title: 'Export and import', prefixes: ['export', 'import-preview', 'import'] }, { title: 'Folders', prefixes: ['ls', 'folders', 'mkdir'] }, + { title: 'Workflows as code', prefixes: ['source'] }, ], workspaces: [ { diff --git a/scripts/sync-workflow-code-docs.ts b/scripts/sync-workflow-code-docs.ts new file mode 100644 index 00000000000..708bcbfedbc --- /dev/null +++ b/scripts/sync-workflow-code-docs.ts @@ -0,0 +1,535 @@ +/** + * Generates the reference tables of the workflows-as-code docs from the code that owns them, so + * the exit codes, diagnostic codes and limits a reader looks up can never drift from the CLI and + * the engines: + * + * - `exit-codes`: `sourceExitCodeRows` (`packages/sim-cli/.../source-exit-codes.ts`), the one + * table `--help`, the generated CLI pages and `.sim/AGENTS.md` are already built from. + * - `diagnostics`: the Diagnostics tables of `packages/workflow-code/src/compile/SYNTAX.md` + * (workflow codes) and the TSDoc of each code in `packages/workspace-code/src/diagnostics/codes.ts` + * (workspace codes), each set required to equal the code list the engines export. + * - `directory-kinds`: the one line per resource kind (`WORKSPACE_KIND_SPECS[kind].guide`) that the + * workspace directory's `.sim/AGENTS.md` prints. + * - `limits`: `SOURCE_LIMITS` and `WORKSPACE_SOURCE_LIMITS`. The values come from code; the label of + * each limit is authored here, and every limit must have one. + * + * Content is rewritten between the `workflow-code-docs:` markers of the pages under + * `apps/docs/content/docs/workflows/code/`. The check also fails on a diagnostic code a page + * names that no engine emits, and on a `typescript@x.y.z` pin in the docs other than the release + * the CLI type-checks a directory with. + * + * Usage: + * bun run scripts/sync-workflow-code-docs.ts # write + * bun run scripts/sync-workflow-code-docs.ts --check # fail on drift + */ + +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { compareStrings } from '@sim/utils/string' +import { + type SourceCommandGroup, + sourceExitCodeRows, +} from '../packages/sim-cli/src/commands/protocol/source-exit-codes' +import { DIAGNOSTIC_CODES } from '../packages/workflow-code/src/diagnostics/codes' +import { SOURCE_LIMITS } from '../packages/workflow-code/src/limits' +import { typecheckCommand } from '../packages/workflow-sdk/src/codegen/tsconfig' +import { WORKSPACE_DIAGNOSTIC_CODES } from '../packages/workspace-code/src/diagnostics/codes' +import { APPLY_ORDER } from '../packages/workspace-code/src/kind' +import { WORKSPACE_SOURCE_LIMITS } from '../packages/workspace-code/src/limits' +import { WORKSPACE_KIND_SPECS } from '../packages/workspace-code/src/specs' + +const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') +const DOCS_DIR = path.join(rootDir, 'apps/docs/content/docs') +const PAGES_DIR = path.join(DOCS_DIR, 'workflows/code') +const SYNTAX_PATH = path.join(rootDir, 'packages/workflow-code/src/compile/SYNTAX.md') +const WORKSPACE_CODES_PATH = path.join(rootDir, 'packages/workspace-code/src/diagnostics/codes.ts') + +const REGIONS = { + 'exit-codes': 'exit-codes.mdx', + diagnostics: 'diagnostics.mdx', + limits: 'limits.mdx', + 'directory-kinds': 'directory.mdx', +} as const +type Region = keyof typeof REGIONS + +const beginMarker = (region: Region) => + `{/* workflow-code-docs:${region}:begin — generated by \`bun run generate:workflow-code-docs\`; do not edit between markers */}` +const endMarker = (region: Region) => `{/* workflow-code-docs:${region}:end */}` + +/** Text safe for MDX prose: braces and angle brackets escaped outside code spans. */ +function mdx(text: string): string { + return text + .split(/(`[^`]*`)/) + .map((part, index) => + index % 2 === 1 + ? part + : part.replaceAll('{', '\\{').replaceAll('}', '\\}').replaceAll('<', '<') + ) + .join('') +} + +/** A TSDoc body as one line of prose: `{@link X}` becomes `X`, a hard wrap becomes a space. */ +function tsdocText(lines: string[]): string { + return lines + .map((line) => line.replace(/^\s*\*\s?/, '').trim()) + .filter(Boolean) + .join(' ') + .replace(/\{@link ([^}]+)\}/g, '`$1`') + .trim() +} + +function cell(text: string): string { + return mdx(text.replaceAll('\n', ' ')).replaceAll('|', '\\|') +} + +const indent = (block: string, spaces: number) => + block + .split('\n') + .map((line) => (line ? ' '.repeat(spaces) + line : line)) + .join('\n') + +function exitCodeTable(group: SourceCommandGroup): string { + return [ + '| Code | Meaning | What to do |', + '| --- | --- | --- |', + ...sourceExitCodeRows(group).map( + ({ code, meaning, next }) => `| \`${code}\` | ${cell(meaning)} | ${cell(next)} |` + ), + ].join('\n') +} + +function buildExitCodes(): string { + return [ + '', + "", + ' ', + '', + indent(exitCodeTable('sim workflows source'), 4), + '', + ' ', + ' ', + '', + indent(exitCodeTable('sim workspaces source'), 4), + '', + ' ', + '', + '', + ].join('\n') +} + +interface DiagnosticRow { + codes: string[] + meaning: string +} +interface DiagnosticGroup { + title: string + note: string + rows: DiagnosticRow[] +} + +/** The groups of the Diagnostics section of SYNTAX.md: a bold title, then a table of code rows. */ +function parseWorkflowDiagnostics(): DiagnosticGroup[] { + const syntax = fs.readFileSync(SYNTAX_PATH, 'utf8') + const start = syntax.indexOf('\n## Diagnostics') + if (start === -1) throw new Error('SYNTAX.md has no "## Diagnostics" section') + const groups: DiagnosticGroup[] = [] + let heading: string[] | null = null + let current: DiagnosticGroup | null = null + for (const line of syntax.slice(start).split('\n').slice(2)) { + if (line.startsWith('**')) { + heading = [line] + continue + } + if (heading && line.trim() !== '') { + heading.push(line) + continue + } + if (heading) { + const text = heading.join(' ') + const match = /^\*\*(.+?)\*\*\s*(.*)$/.exec(text) + if (!match) throw new Error(`Cannot read the SYNTAX.md diagnostics heading: ${text}`) + current = { title: match[1], note: match[2].replace(/^\((.*)\)$/, '$1'), rows: [] } + groups.push(current) + heading = null + continue + } + const row = /^\| (`[EWI]_[A-Z0-9_]+`(?:, `[EWI]_[A-Z0-9_]+`)*) \| (.*) \|$/.exec(line) + if (row && current) { + current.rows.push({ + codes: row[1].split(', ').map((code) => code.slice(1, -1)), + meaning: row[2].replaceAll('\\|', '|'), + }) + } + } + return groups +} + +interface WorkspaceCodeGroup { + title: string + rows: DiagnosticRow[] +} + +/** + * The `const X_CODES = [...]` arrays of the workspace codes file: the TSDoc above an array is the + * group's title and the TSDoc above each string is that code's meaning. + */ +function parseWorkspaceDiagnostics(): { groups: WorkspaceCodeGroup[]; undocumented: string[] } { + const lines = fs.readFileSync(WORKSPACE_CODES_PATH, 'utf8').split('\n') + const groups: WorkspaceCodeGroup[] = [] + const undocumented: string[] = [] + let doc: string[] = [] + let inDoc = false + let groupTitle: string | null = null + let current: WorkspaceCodeGroup | null = null + let sharedLine = false + for (const line of lines) { + const trimmed = line.trim() + if (inDoc) { + if (trimmed.endsWith('*/')) { + inDoc = false + const body = trimmed.replace(/\*\/$/, '').trim() + if (body && body !== '*') doc.push(body) + } else doc.push(trimmed) + continue + } + if (trimmed.startsWith('/**')) { + doc = [] + const rest = trimmed.replace(/^\/\*\*/, '') + if (rest.endsWith('*/')) doc.push(rest.replace(/\*\/$/, '').trim()) + else { + inDoc = true + if (rest.trim()) doc.push(rest.trim()) + } + continue + } + const arrayStart = /^const ([A-Z_]+_CODES) = \[/.exec(trimmed) + if (arrayStart) { + sharedLine = arrayStart[1] === 'SHARED_CODES' || arrayStart[1] === 'OWN_CODES' + current = null + if (!sharedLine) { + groupTitle = tsdocText(doc).replace(/\.$/, '') + current = { title: groupTitle, rows: [] } + groups.push(current) + } + doc = [] + continue + } + if (trimmed.startsWith(']')) { + current = null + continue + } + const code = /^'([EWI]_[A-Z0-9_]+)',?$/.exec(trimmed) + if (code && current) { + const meaning = tsdocText(doc) + if (!meaning) undocumented.push(code[1]) + current.rows.push({ codes: [code[1]], meaning }) + doc = [] + } else if (trimmed !== '' && !trimmed.startsWith('//')) { + doc = [] + } + } + return { groups, undocumented } +} + +const codeCell = (codes: string[]) => codes.map((code) => `\`${code}\``).join(', ') + +function diagnosticTable(rows: DiagnosticRow[]): string { + return [ + '| Code | Meaning |', + '| --- | --- |', + ...rows.map(({ codes, meaning }) => `| ${codeCell(codes)} | ${cell(meaning)} |`), + ].join('\n') +} + +const WORKFLOW_GROUP_LEAD: Record = { + 'Compile and print': 'Reading and writing `workflow.ts`.', + 'Lock and source meta': 'Reading `.sim/lock.json`. Each finding names a JSON `path`.', + Canonicalize: 'Reading the stored workflow in a get.', + Materialize: 'Matching the compiled file to the stored blocks.', + Apply: 'Saving the workflow draft.', +} + +/** One error per code `documented` names that `exported` does not hold, and per code it lacks. */ +function codeDiff( + what: string, + documented: readonly string[], + exported: readonly string[] +): string[] { + const have = new Set(documented) + const want = new Set(exported) + const extra = documented.filter((code) => !want.has(code)) + const missing = exported.filter((code) => !have.has(code)) + return [ + ...(extra.length ? [`${what} names codes no engine emits: ${extra.join(', ')}`] : []), + ...(missing.length ? [`${what} has no entry for: ${missing.join(', ')}`] : []), + ] +} + +function buildDiagnostics(errors: string[]): string { + const workflow = parseWorkflowDiagnostics() + const workflowRows = workflow.flatMap((group) => group.rows) + const workflowMeaning = new Map( + workflowRows.flatMap((row) => row.codes.map((code) => [code, row.meaning])) + ) + for (const [what, documented, exported] of [ + ['SYNTAX.md Diagnostics', [...workflowMeaning.keys()], DIAGNOSTIC_CODES], + ] as const) { + errors.push(...codeDiff(what, documented, exported)) + } + + const { groups: workspace, undocumented } = parseWorkspaceDiagnostics() + if (undocumented.length) + errors.push( + `workspace-code/src/diagnostics/codes.ts has no TSDoc for: ${undocumented.join(', ')}` + ) + const ownCodes = new Set(workspace.flatMap((group) => group.rows.flatMap((row) => row.codes))) + const exportedWorkspace: readonly string[] = WORKSPACE_DIAGNOSTIC_CODES + errors.push( + ...codeDiff( + 'workspace-code code arrays', + [...ownCodes], + exportedWorkspace.filter((code) => ownCodes.has(code) || !workflowMeaning.has(code)) + ) + ) + const shared: DiagnosticRow[] = exportedWorkspace + .filter((code) => !ownCodes.has(code)) + .map((code) => ({ codes: [code], meaning: workflowMeaning.get(code) ?? '' })) + + const lines: string[] = ['', '### Workflow source', ''] + for (const group of workflow) { + lines.push(`#### ${group.title}`, '') + const lead = WORKFLOW_GROUP_LEAD[group.title] + const note = lead ?? (group.note ? `${group.note}.` : '') + if (!lead) errors.push(`No lead sentence for the diagnostics group "${group.title}"`) + if (note) lines.push(mdx(note), '') + lines.push(diagnosticTable(group.rows), '') + } + lines.push('### Workspace source', '') + lines.push( + 'Workspace source reports every workflow code above for the files of `workflows//`, with that path as the file, and these codes for the rest of the directory.', + '' + ) + for (const group of workspace) { + lines.push(`#### ${mdx(group.title)}`, '', diagnosticTable(group.rows), '') + } + lines.push( + '#### Shared with workflow source', + '', + 'A workspace finding with the same meaning as a workflow finding uses its code.', + '', + diagnosticTable(shared), + '' + ) + return lines.join('\n') +} + +function buildDirectoryKinds(): string { + return ['', ...APPLY_ORDER.map((kind) => `- ${mdx(WORKSPACE_KIND_SPECS[kind].guide)}`), ''].join( + '\n' + ) +} + +/** The label of each limit in the docs. A limit added to code without one fails the check. */ +const WORKFLOW_LIMIT_LABELS: Record = { + maxBlocks: 'Blocks in one workflow', + maxEdges: 'Connections (edges) in one workflow', + maxVariables: 'Variables in one workflow', + maxFiles: 'Files in one source: `workflow.ts` plus one function file per block', + maxTotalBytes: 'Bytes of all files together, `workflow.ts` and function files', + maxDepth: 'Nesting depth of `workflow.ts`, and of each JavaScript function file', +} + +const WORKSPACE_LIMIT_LABELS: Record = { + maxResourcesPerKind: 'Resources of one kind in one directory', + maxDeclarationBytes: 'Bytes of every declaration file together, workflow files excluded', + maxWorkflows: 'Edited workflows one apply sends', + maxWorkflowBytes: 'Bytes of every workflow file one apply sends', + maxDirectoryWorkflowBytes: + 'Bytes of every workflow file one get writes; a workflow past it is left out', + maxChanges: 'Changes one apply makes, no-ops excluded', + maxTableRows: 'Rows in one `tables/.rows.jsonl`', + maxRowsBytes: 'Bytes of every rows file together', + maxColumns: 'Columns in one table', + maxBlobBytes: 'Bytes of one workspace file or knowledge base document', + maxBlobs: 'Workspace files and knowledge base documents together in one directory', + maxBlobBytesPerRequest: + 'Bytes of files one upload request carries; a larger file goes in a request of its own', + maxBlobsPerRequest: 'Files in one upload request', + maxHashBytesPerRequest: 'Bytes of stored files one get or apply downloads to compare', + maxStagedBlobs: 'Files one caller may hold staged in one workspace at once', + maxStagedBytes: 'Bytes one caller may hold staged in one workspace at once', + maxDepth: 'Nesting depth of a declaration file', +} + +const LIMIT_GROUPS: Array<{ + title: string + limits: Record + labels: Record + keys: string[] +}> = [ + { + title: 'One workflow', + limits: SOURCE_LIMITS, + labels: WORKFLOW_LIMIT_LABELS, + keys: Object.keys(WORKFLOW_LIMIT_LABELS), + }, + { + title: 'A workspace directory', + limits: WORKSPACE_SOURCE_LIMITS, + labels: WORKSPACE_LIMIT_LABELS, + keys: [ + 'maxResourcesPerKind', + 'maxDeclarationBytes', + 'maxWorkflows', + 'maxWorkflowBytes', + 'maxDirectoryWorkflowBytes', + 'maxChanges', + 'maxTableRows', + 'maxRowsBytes', + 'maxColumns', + 'maxBlobBytes', + 'maxBlobs', + 'maxDepth', + ], + }, + { + title: 'Uploading and downloading files', + limits: WORKSPACE_SOURCE_LIMITS, + labels: WORKSPACE_LIMIT_LABELS, + keys: [ + 'maxBlobBytesPerRequest', + 'maxBlobsPerRequest', + 'maxHashBytesPerRequest', + 'maxStagedBlobs', + 'maxStagedBytes', + ], + }, +] + +/** A limit whose label starts with "Bytes" is a byte count. */ +function formatLimit(label: string, value: number): string { + const formatted = value.toLocaleString('en-US') + return label.startsWith('Bytes') ? `${formatted} bytes` : formatted +} + +function buildLimits(errors: string[]): string { + for (const [name, limits, labels] of [ + ['SOURCE_LIMITS', SOURCE_LIMITS, WORKFLOW_LIMIT_LABELS], + ['WORKSPACE_SOURCE_LIMITS', WORKSPACE_SOURCE_LIMITS, WORKSPACE_LIMIT_LABELS], + ] as const) { + const unlabeled = Object.keys(limits).filter((key) => !(key in labels)) + if (unlabeled.length) + errors.push(`${name} has limits with no docs label: ${unlabeled.join(', ')}`) + } + for (const key of Object.keys(WORKSPACE_SOURCE_LIMITS)) { + const placed = LIMIT_GROUPS.slice(1).filter((group) => group.keys.includes(key)).length + if (placed !== 1) + errors.push(`WORKSPACE_SOURCE_LIMITS.${key} is in ${placed} limits groups, not 1`) + } + + const lines: string[] = [''] + for (const group of LIMIT_GROUPS) { + lines.push(`### ${group.title}`, '', '| Limit | Value |', '| --- | --- |') + for (const key of group.keys) { + lines.push( + `| ${cell(group.labels[key])} | ${formatLimit(group.labels[key], group.limits[key])} |` + ) + } + lines.push('') + } + return lines.join('\n') +} + +function rewrite(region: Region, doc: string, content: string, file: string): string { + const begin = doc.indexOf(beginMarker(region)) + const end = doc.indexOf(endMarker(region)) + if (begin === -1 || end === -1 || end < begin) { + throw new Error(`workflow-code-docs: ${region} markers not found in ${file}`) + } + return `${doc.slice(0, begin + beginMarker(region).length)}\n${content}\n${doc.slice(end)}` +} + +function walkMdx(dir: string): string[] { + return fs + .readdirSync(dir, { recursive: true, encoding: 'utf8' }) + .filter((entry) => entry.endsWith('.mdx')) + .map((entry) => path.join(dir, entry)) +} + +/** A generated region, which the owners already check, so stale rows never block regenerating it. */ +const GENERATED_REGION = + /\{\/\* workflow-code-docs:[\w-]+:begin[\s\S]*?\{\/\* workflow-code-docs:[\w-]+:end \*\/\}/g + +function checkProse(errors: string[]): void { + const known = new Set([...DIAGNOSTIC_CODES, ...WORKSPACE_DIAGNOSTIC_CODES]) + for (const file of walkMdx(PAGES_DIR)) { + const rel = path.relative(rootDir, file) + const text = fs.readFileSync(file, 'utf8') + const prose = text.replace(GENERATED_REGION, '') + for (const match of prose.matchAll(/`([EWI]_[A-Z0-9_]+)`/g)) { + if (!known.has(match[1])) errors.push(`${rel} names ${match[1]}, which no engine emits`) + } + } + const pinned = /typescript@(\d+\.\d+\.\d+)/.exec(typecheckCommand())?.[1] + if (!pinned) { + errors.push('typecheckCommand() no longer names a typescript@x.y.z release') + return + } + for (const file of walkMdx(DOCS_DIR)) { + for (const match of fs.readFileSync(file, 'utf8').matchAll(/typescript@(\d+\.\d+\.\d+)/g)) { + if (match[1] !== pinned) { + errors.push( + `${path.relative(rootDir, file)} pins typescript@${match[1]}, but the CLI type-checks with ${pinned}` + ) + } + } + } +} + +function main(): void { + const checkMode = process.argv.includes('--check') + const errors: string[] = [] + const generated: Record = { + 'exit-codes': buildExitCodes(), + diagnostics: buildDiagnostics(errors), + limits: buildLimits(errors), + 'directory-kinds': buildDirectoryKinds(), + } + checkProse(errors) + + const writes: Array<{ rel: string; file: string; next: string }> = [] + for (const region of Object.keys(REGIONS) as Region[]) { + const file = path.join(PAGES_DIR, REGIONS[region]) + const rel = path.relative(rootDir, file) + if (!fs.existsSync(file)) { + errors.push(`${rel} does not exist`) + continue + } + const doc = fs.readFileSync(file, 'utf8') + const next = rewrite(region, doc, generated[region], rel) + if (next !== doc) writes.push({ rel, file, next }) + } + + if (errors.length > 0) { + console.error('workflow-code-docs:') + for (const error of [...new Set(errors)].sort(compareStrings)) console.error(` - ${error}`) + process.exit(1) + } + if (checkMode) { + if (writes.length > 0) { + console.error( + `workflow-code-docs: out of date: ${writes.map((write) => write.rel).join(', ')}. Run \`bun run generate:workflow-code-docs\`.` + ) + process.exit(1) + } + console.log('workflow-code-docs: up to date.') + return + } + for (const { rel, file, next } of writes) { + fs.writeFileSync(file, next) + console.log(`workflow-code-docs: updated ${rel}`) + } +} + +main()