From c907775a111ae9df51a8b7524a67d029d567f54c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 11:02:09 -0800 Subject: [PATCH 1/7] improvement(workflow-code): clean slate for workflows and workspace as code Remove the feature's own compatibility paths now that nothing depends on them: version-less bases and the lock/base upgrade seams, numeric blob revs, the SDK-major floor (E_SDK_MAJOR_OLD), the plan-read dry-run fallback, the client-side refuses fallback, older-CLI catalog caches and folder records, old-server resource defaults, and get --primer. Declare mayBeText on block outputs (Function result, API data) and read it through the catalog in place of TEXT_CAPABLE_OUTPUTS. Name the run a pause is recorded under in paused.runId on execute, resume and run reads, and build the CLI resume command from it instead of searching output markers. Fix the stale lookup-order sample. --- .claude/rules/sim-workflow-code.md | 2 +- .cursor/rules/sim-workflow-code.mdc | 2 +- apps/docs/content/docs/cli/reference.mdx | 2 - apps/docs/content/docs/cli/workflows.mdx | 1 - apps/docs/content/docs/cli/workspaces.mdx | 1 - .../docs/workflows/code/coding-agents.mdx | 2 +- .../docs/workflows/code/diagnostics.mdx | 3 +- .../content/docs/workflows/code/syntax.mdx | 2 +- .../content/docs/workflows/code/workspace.mdx | 2 +- apps/docs/openapi-v2-resources.json | 15 ++ apps/docs/openapi-v2-workflows.json | 210 ++++++++++------- .../[workflowId]/execute/route.test.ts | 33 +++ .../workflows/[workflowId]/execute/route.ts | 6 +- .../runs/[runId]/resume/route.test.ts | 31 +++ .../[workflowId]/runs/[runId]/resume/route.ts | 5 +- .../[workflowId]/runs/[runId]/route.test.ts | 2 + .../[workflowId]/runs/[runId]/route.ts | 1 + .../workflows/source/resources/route.test.ts | 2 +- apps/sim/blocks/blocks/api.ts | 6 +- apps/sim/blocks/blocks/function.ts | 6 +- .../contracts/v2/openapi/source-resources.ts | 2 +- .../lib/api/contracts/v2/openapi/workflows.ts | 3 +- .../lib/api/contracts/v2/source-catalog.ts | 4 + apps/sim/lib/api/contracts/v2/workflows.ts | 212 ++++++++++-------- .../lib/api/contracts/v2/workspace-source.ts | 2 +- apps/sim/lib/api/contracts/workflow-source.ts | 5 +- .../lib/api/mcp/generated/v2-operations.ts | 2 +- apps/sim/lib/workflows/api/index.ts | 1 + apps/sim/lib/workflows/api/run-pause.ts | 20 ++ .../application/read-workflow-run.ts | 2 +- .../sim/lib/workflows/code/catalog/project.ts | 2 + .../workflows/code/json-field-refs.test.ts | 35 +++ .../lib/workflows/executor/execute-service.ts | 5 +- .../executor/human-in-the-loop-manager.ts | 10 +- .../workflows/executor/resume-execution.ts | 16 +- .../protocol/source-apply-interrupt.test.ts | 1 + .../protocol/source-dir/write-back.ts | 15 +- .../commands/protocol/source-dir/written.ts | 15 +- .../src/commands/protocol/source-status.ts | 14 -- .../src/commands/protocol/source-tree.ts | 40 +--- .../src/commands/protocol/stored-edges.ts | 4 +- .../protocol/workflow-run-wait.test.ts | 23 +- .../commands/protocol/workflow-run-wait.ts | 2 +- .../protocol/workflow-source-apply.test.ts | 7 + .../protocol/workflow-source-check.test.ts | 1 + .../protocol/workflow-source-get.test.ts | 12 +- .../commands/protocol/workflow-source-get.ts | 10 +- .../protocol/workflow-source-params.test.ts | 1 + .../workflow-source-roundtrip.test.ts | 24 +- .../protocol/workflow-source-status.test.ts | 39 +--- .../protocol/workflow-source-status.ts | 23 +- .../protocol/workspace-source-apply.test.ts | 71 +++--- .../protocol/workspace-source-apply.ts | 25 +-- .../protocol/workspace-source-get.test.ts | 14 +- .../commands/protocol/workspace-source-get.ts | 5 +- .../protocol/workspace-source-status.test.ts | 2 +- .../protocol/workspace-source-status.ts | 18 +- packages/sim-cli/src/generated/v2-api.ts | 43 ++-- .../sim-cli/src/runtime/paused-run.test.ts | 99 +++----- packages/sim-cli/src/runtime/paused-run.ts | 73 ++---- packages/workflow-code/src/catalog/types.ts | 2 + packages/workflow-code/src/compile/SYNTAX.md | 6 +- .../src/compile/ergonomics.test.ts | 8 +- packages/workflow-code/src/compile/index.ts | 18 +- .../workflow-code/src/diagnostics/codes.ts | 4 +- packages/workflow-code/src/json-fields.ts | 32 +-- packages/workflow-code/src/lock.test.ts | 27 ++- packages/workflow-code/src/lock.ts | 43 +--- packages/workflow-code/src/sdk.ts | 6 - .../workflow-sdk/test/fixtures/catalog.json | 6 +- packages/workflow-types/src/blocks.ts | 6 + packages/workspace-code/DESIGN.md | 5 +- packages/workspace-code/src/base.test.ts | 18 +- packages/workspace-code/src/base.ts | 27 +-- 74 files changed, 724 insertions(+), 720 deletions(-) create mode 100644 apps/sim/lib/workflows/api/run-pause.ts diff --git a/.claude/rules/sim-workflow-code.md b/.claude/rules/sim-workflow-code.md index 7a170078358..24d4b87b2d8 100644 --- a/.claude/rules/sim-workflow-code.md +++ b/.claude/rules/sim-workflow-code.md @@ -209,7 +209,7 @@ changed. | `.sim/base.json` (workspace) | `version: 1` | Same policy | | `workflow_source_meta` | `version: 1` | Same policy; a bump needs a data migration | | Fingerprints | `sf1:` (workflow), `rf1:` (resource) | Any change to canonicalize or a kind's `canonical()` output changes every stored fingerprint and makes every checkout stale; treat it as a format change | -| SDK surface | `// @sim-sdk 1`, `SDK_MAJOR`, `OLDEST_SDK_MAJOR` | Compile refuses a newer major and reads down to the floor | +| SDK surface | `// @sim-sdk 1`, `SDK_MAJOR` | Compile refuses any major but the server's | | `apps/sim/blocks/sdk-names/` | append-only | Never rename or remove a name | Nothing upgrades an old version: a bump is a hard refusal until a migration exists. A lock or base diff --git a/.cursor/rules/sim-workflow-code.mdc b/.cursor/rules/sim-workflow-code.mdc index b55a0e7ed5e..100c3bdefe5 100644 --- a/.cursor/rules/sim-workflow-code.mdc +++ b/.cursor/rules/sim-workflow-code.mdc @@ -189,7 +189,7 @@ changed. | `.sim/base.json` (workspace) | `version: 1` | Same policy | | `workflow_source_meta` | `version: 1` | Same policy; a bump needs a data migration | | Fingerprints | `sf1:` (workflow), `rf1:` (resource) | Any change to canonicalize or a kind's `canonical()` output changes every stored fingerprint and makes every checkout stale; treat it as a format change | -| SDK surface | `// @sim-sdk 1`, `SDK_MAJOR`, `OLDEST_SDK_MAJOR` | Compile refuses a newer major and reads down to the floor | +| SDK surface | `// @sim-sdk 1`, `SDK_MAJOR` | Compile refuses any major but the server's | | `apps/sim/blocks/sdk-names/` | append-only | Never rename or remove a name | Nothing upgrades an old version: a bump is a hard refusal until a migration exists. A lock or base diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 059624a490b..4ee702d3374 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8622,7 +8622,6 @@ sim workflows source get [options] | `--function-code ` | No | Where function-block code goes: `files` (default) writes it to `functions/*` files referenced with `codeFile()`; `inline` prints it in tagged templates. Accepted values: `inline`, `files`. | | `--dir ` | No | Write the source, its lock and SDK type declarations into this directory instead of printing them. | | `--force` | No | With --dir: replace another workflow's source or edits no apply has saved. | -| `--primer` | No | Also print the primer written atop .sim/AGENTS.md (a `primer` field in JSON). | @@ -10037,7 +10036,6 @@ sim workspaces source get [options] | Option | Required | Description | | --- | --- | --- | -| `--primer` | No | Also print the primer written atop .sim/AGENTS.md (a `primer` field in JSON). | | `--dir ` | Yes | Directory to write the workspace source into. | | `--only ` | No | Read only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--force` | No | Replace files with edits no apply has saved. | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 8760141181e..ed4df922b58 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1379,7 +1379,6 @@ sim workflows source get [options] | `--function-code ` | No | Where function-block code goes: `files` (default) writes it to `functions/*` files referenced with `codeFile()`; `inline` prints it in tagged templates. Accepted values: `inline`, `files`. | | `--dir ` | No | Write the source, its lock and SDK type declarations into this directory instead of printing them. | | `--force` | No | With --dir: replace another workflow's source or edits no apply has saved. | -| `--primer` | No | Also print the primer written atop .sim/AGENTS.md (a `primer` field in JSON). | diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 619562b560f..ccaae1e1758 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -700,7 +700,6 @@ sim workspaces source get [options] | Option | Required | Description | | --- | --- | --- | -| `--primer` | No | Also print the primer written atop .sim/AGENTS.md (a `primer` field in JSON). | | `--dir ` | Yes | Directory to write the workspace source into. | | `--only ` | No | Read only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--force` | No | Replace files with edits no apply has saved. | diff --git a/apps/docs/content/docs/workflows/code/coding-agents.mdx b/apps/docs/content/docs/workflows/code/coding-agents.mdx index eb2f7736d00..91cfe685573 100644 --- a/apps/docs/content/docs/workflows/code/coding-agents.mdx +++ b/apps/docs/content/docs/workflows/code/coding-agents.mdx @@ -7,7 +7,7 @@ Claude Code, Cursor, Codex and other coding agents work from a directory that `g ## What get gives an agent -- A **primer**, which opens `.sim/AGENTS.md`. `get` prints a short summary instead (the files written, the guide, and the `editLoop` command to run); `get --primer` also prints the primer (in JSON output, its `primer` field). It covers the edit loop, how block identity, references and renames work, failures and retries, test runs, deletes, deploy, exit codes, and the params of each builder the workflow already uses. +- A **primer**, which opens `.sim/AGENTS.md`. `get` prints a short summary instead (the files written, the guide, and the `editLoop` command to run). 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. diff --git a/apps/docs/content/docs/workflows/code/diagnostics.mdx b/apps/docs/content/docs/workflows/code/diagnostics.mdx index 554a7a9a0f7..c9b8bbf92c0 100644 --- a/apps/docs/content/docs/workflows/code/diagnostics.mdx +++ b/apps/docs/content/docs/workflows/code/diagnostics.mdx @@ -22,8 +22,7 @@ Reading and writing `workflow.ts`. | `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_SDK_MAJOR` | The header's major is not the one 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. | diff --git a/apps/docs/content/docs/workflows/code/syntax.mdx b/apps/docs/content/docs/workflows/code/syntax.mdx index e75b027d727..cc3849dc81c 100644 --- a/apps/docs/content/docs/workflows/code/syntax.mdx +++ b/apps/docs/content/docs/workflows/code/syntax.mdx @@ -107,7 +107,7 @@ export default workflow('Name', { description: '…', variables: { /* … */ } } }) ``` -- Line 1 is `// @sim-sdk N`. Without it the file is refused with `E_SDK_HEADER`; a number newer or older than the server reads is `E_SDK_MAJOR` or `E_SDK_MAJOR_OLD`. +- Line 1 is `// @sim-sdk N`. Without it the file is refused with `E_SDK_HEADER`; a number other than the one the server reads is `E_SDK_MAJOR`. - Imports are named imports from `'@sim/workflow-sdk'` only. Aliases are allowed. - The file has exactly one `export default workflow(name, options?, body)` (`E_WORKFLOW_EXPORT`). `options` is `{ description?, variables? }`. `body` is `() => { … }` or `({ vars }) => { … }`. - Variables are `variables: { : { name?, type, value } }`. `type` is `string`, `number`, `boolean`, `object`, `array` or `plain`, and both `type` and `value` are required; `value` is plain JSON. The key is the variable's key: lowercased, with spaces and dots removed. `name` is written only when it differs, and must normalize to the key (`E_VARIABLE_NAME_MISMATCH`). Read one as `vars.`. diff --git a/apps/docs/content/docs/workflows/code/workspace.mdx b/apps/docs/content/docs/workflows/code/workspace.mdx index 20b2e3ae0d0..09c356241ed 100644 --- a/apps/docs/content/docs/workflows/code/workspace.mdx +++ b/apps/docs/content/docs/workflows/code/workspace.mdx @@ -32,7 +32,7 @@ const log = table.insertRow('Log Question', { }) ``` -`get` writes a short primer for coding agents atop `.sim/AGENTS.md` (`get --primer` also prints it, in JSON output as its `primer` field), 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. +`get` writes a short primer for coding agents 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 diff --git a/apps/docs/openapi-v2-resources.json b/apps/docs/openapi-v2-resources.json index fc3d8e4965f..a627022e4f1 100644 --- a/apps/docs/openapi-v2-resources.json +++ b/apps/docs/openapi-v2-resources.json @@ -32795,6 +32795,11 @@ "description": "Hidden from the output picker.", "type": "boolean" }, + "mayBeText": { + "description": "A `json` or `any` output whose value can still be text at run time.", + "type": "boolean", + "const": true + }, "properties": { "description": "Nested outputs by name, each of this same shape.", "type": "object", @@ -33838,6 +33843,11 @@ "description": "Hidden from the output picker.", "type": "boolean" }, + "mayBeText": { + "description": "A `json` or `any` output whose value can still be text at run time.", + "type": "boolean", + "const": true + }, "properties": { "description": "Nested outputs by name, each of this same shape.", "type": "object", @@ -34697,6 +34707,11 @@ "description": "Hidden from the output picker.", "type": "boolean" }, + "mayBeText": { + "description": "A `json` or `any` output whose value can still be text at run time.", + "type": "boolean", + "const": true + }, "properties": { "description": "Nested outputs by name, each of this same shape.", "type": "object", diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 51d4c8b04ff..9e23599839a 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -4394,6 +4394,7 @@ "startedAt": "2026-08-09T18:04:10.000Z", "endedAt": "2026-08-09T18:04:11.000Z", "durationMs": 1000, + "paused": null, "executionTimeoutSeconds": 3000 } } @@ -5131,7 +5132,7 @@ "post": { "operationId": "resumeWorkflowRunV2", "summary": "Resume workflow run", - "description": "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.\n\nOAuth scope: `api:write`.", + "description": "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt; when it pauses again, `paused.runId` names the run to resume next. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.\n\nOAuth scope: `api:write`.", "x-sim-operation": "workflows.runs.resume", "x-oauth-scope": "api:write", "tags": ["Workflow Runs"], @@ -5229,7 +5230,8 @@ "error": null, "startedAt": "2026-08-09T18:04:10.000Z", "endedAt": "2026-08-09T18:04:11.000Z", - "durationMs": 1000 + "durationMs": 1000, + "paused": null } } } @@ -6736,7 +6738,7 @@ { "key": "lookup-order", "id": "ctl_2b8d6f03", - "name": "lookup_order" + "name": "Lookup order" } ], "mcpServers": [ @@ -17275,6 +17277,50 @@ } ], "description": "Execution timeout applied to this run, in seconds: the plan's timeout, lowered by `executionTimeoutSeconds` when one was requested. Null when the run has no execution timeout." + }, + "paused": { + "anyOf": [ + { + "type": "object", + "properties": { + "runId": { + "type": "string", + "description": "Run to name in Resume workflow run: the run this pause is recorded under, which for a resumed run that paused again is the run it resumed." + }, + "points": { + "type": "array", + "items": { + "type": "object", + "properties": { + "contextId": { + "type": "string", + "description": "Pause context to name in `contextId` when resuming this point." + }, + "kind": { + "type": "string", + "enum": ["human", "time"], + "description": "`human` waits for a resume request; `time` resumes automatically at `resumeAt`." + }, + "status": { + "type": "string", + "enum": ["paused", "queued", "resuming", "resumed", "failed"], + "description": "Resume state of this point: waiting, queued behind another resume, resuming, resumed, or a failed resume attempt." + } + }, + "required": ["contextId", "kind", "status"], + "additionalProperties": false + }, + "description": "Every point the run is paused at. Resume one with Resume workflow run, naming `runId` and its `contextId`." + } + }, + "required": ["runId", "points"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "Where the run waits when `status` is `paused`; null otherwise." } }, "required": [ @@ -17284,7 +17330,8 @@ "output", "blockOutputs", "error", - "executionTimeoutSeconds" + "executionTimeoutSeconds", + "paused" ], "additionalProperties": false, "title": "Workflow run result", @@ -17316,6 +17363,7 @@ "startedAt": "2026-08-09T18:04:10.000Z", "endedAt": "2026-08-09T18:04:11.000Z", "durationMs": 1000, + "paused": null, "executionTimeoutSeconds": 3000 } } @@ -18248,6 +18296,10 @@ "type": "number", "description": "Number of pause points that have resumed." }, + "runId": { + "type": "string", + "description": "Run to name in Resume workflow run: the run this pause is recorded under, which for a resumed run that paused again is the run it resumed." + }, "points": { "type": "array", "items": { @@ -18265,6 +18317,7 @@ "automaticResumeWaitingReason", "pausePointCount", "resumedCount", + "runId", "points" ], "additionalProperties": false @@ -18479,9 +18532,53 @@ "description": "Execution duration in milliseconds.", "type": "number", "minimum": 0 + }, + "paused": { + "anyOf": [ + { + "type": "object", + "properties": { + "runId": { + "type": "string", + "description": "Run to name in Resume workflow run: the run this pause is recorded under, which for a resumed run that paused again is the run it resumed." + }, + "points": { + "type": "array", + "items": { + "type": "object", + "properties": { + "contextId": { + "type": "string", + "description": "Pause context to name in `contextId` when resuming this point." + }, + "kind": { + "type": "string", + "enum": ["human", "time"], + "description": "`human` waits for a resume request; `time` resumes automatically at `resumeAt`." + }, + "status": { + "type": "string", + "enum": ["paused", "queued", "resuming", "resumed", "failed"], + "description": "Resume state of this point: waiting, queued behind another resume, resuming, resumed, or a failed resume attempt." + } + }, + "required": ["contextId", "kind", "status"], + "additionalProperties": false + }, + "description": "Every point the run is paused at. Resume one with Resume workflow run, naming `runId` and its `contextId`." + } + }, + "required": ["runId", "points"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "Where the run waits when `status` is `paused`; null otherwise." } }, - "required": ["runId", "workflowId", "status", "output", "blockOutputs", "error"], + "required": ["runId", "workflowId", "status", "output", "blockOutputs", "error", "paused"], "additionalProperties": false, "title": "Workflow resume result", "description": "Synchronous resumed run output and in-band execution status. Run failures are reported in band, not as HTTP errors, so branch on `status`." @@ -18511,7 +18608,8 @@ "error": null, "startedAt": "2026-08-09T18:04:10.000Z", "endedAt": "2026-08-09T18:04:11.000Z", - "durationMs": 1000 + "durationMs": 1000, + "paused": null } } ] @@ -19090,10 +19188,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -19149,7 +19246,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_LIMIT_EXCEEDED", @@ -19625,7 +19721,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_LIMIT_EXCEEDED", @@ -20008,10 +20103,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -20299,10 +20393,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -20324,7 +20417,7 @@ "description": "Hash of the block catalog the source was printed against." } }, - "required": ["workflowId", "workspaceId", "fingerprint", "catalogHash"], + "required": ["version", "workflowId", "workspaceId", "fingerprint", "catalogHash"], "additionalProperties": { "description": "An `x-` extension field, kept verbatim." }, @@ -20593,7 +20686,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_LIMIT_EXCEEDED", @@ -20976,10 +21068,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -21267,10 +21358,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -21292,7 +21382,7 @@ "description": "Hash of the block catalog the source was printed against." } }, - "required": ["workflowId", "workspaceId", "fingerprint", "catalogHash"], + "required": ["version", "workflowId", "workspaceId", "fingerprint", "catalogHash"], "additionalProperties": { "description": "An `x-` extension field, kept verbatim." }, @@ -21537,7 +21627,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_LIMIT_EXCEEDED", @@ -21920,10 +22009,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -22469,7 +22557,7 @@ { "key": "lookup-order", "id": "ctl_2b8d6f03", - "name": "lookup_order" + "name": "Lookup order" } ], "mcpServers": [ @@ -26394,16 +26482,7 @@ "description": "Stored id of the binary file." }, "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], + "type": "string", "description": "Content revision as last read." }, "sha256": { @@ -26598,7 +26677,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_INVALID_CHARACTER", @@ -27183,7 +27261,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_INVALID_CHARACTER", @@ -27438,16 +27515,7 @@ "description": "Stored id of the binary file." }, "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], + "type": "string", "description": "Content revision as last read." }, "sha256": { @@ -27607,7 +27675,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_INVALID_CHARACTER", @@ -28010,16 +28077,7 @@ "description": "Stored id of the binary file." }, "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], + "type": "string", "description": "Content revision as last read." }, "sha256": { @@ -28481,7 +28539,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_INVALID_CHARACTER", @@ -28736,16 +28793,7 @@ "description": "Stored id of the binary file." }, "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], + "type": "string", "description": "Content revision as last read." }, "sha256": { @@ -28905,7 +28953,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_INVALID_CHARACTER", @@ -29308,16 +29355,7 @@ "description": "Stored id of the binary file." }, "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], + "type": "string", "description": "Content revision as last read." }, "sha256": { diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts index 0f8ecd035de..6d49625fb81 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts @@ -333,6 +333,38 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => { }) }) + it('names where a paused run waits: the run to resume and each pause point', async () => { + mockExecuteWorkflowCore.mockResolvedValueOnce({ + success: true, + status: 'paused', + output: {}, + pausePoints: [ + { contextId: 'ctx-1', pauseKind: 'human', resumeStatus: 'paused' }, + { contextId: 'ctx-2', pauseKind: 'time', resumeStatus: 'paused' }, + ], + metadata: { duration: 5 }, + }) + + const body = await (await callExecute({ input: {} })).json() + + expect(body.data).toMatchObject({ + status: 'paused', + paused: { + runId: 'execution-123', + points: [ + { contextId: 'ctx-1', kind: 'human', status: 'paused' }, + { contextId: 'ctx-2', kind: 'time', status: 'paused' }, + ], + }, + }) + }) + + it('reports no pause for a run that finished', async () => { + const body = await (await callExecute({ input: {} })).json() + + expect(body.data.paused).toBeNull() + }) + it('streams an immediate heartbeat and the same sync result when NDJSON is accepted', async () => { vi.useFakeTimers() try { @@ -382,6 +414,7 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => { status: 'completed', output: { result: 'done' }, blockOutputs: null, + paused: null, error: null, startedAt: '2026-07-31T00:00:00.000Z', endedAt: '2026-07-31T00:00:01.000Z', diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts index ab53f25617b..a2f8723779c 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts @@ -36,7 +36,7 @@ import { SIM_VIA_HEADER, validateCallChain, } from '@/lib/execution/call-chain' -import { v2WorkflowErrorPolicies } from '@/lib/workflows/api' +import { presentV2RunPause, v2WorkflowErrorPolicies } from '@/lib/workflows/api' import { executeManualWorkflowFromBlockOperation, executeManualWorkflowOperation, @@ -140,6 +140,10 @@ function presentRun(result: ExecuteWorkflowServiceRun) { executionTimeoutSeconds: executionTimeoutSeconds(result.executionTimeoutMs), output: result.output ?? null, blockOutputs: result.blockOutputs ?? null, + paused: + result.status === 'paused' + ? presentV2RunPause(result.executionId, result.pausePoints ?? []) + : null, } } diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts index 9e8e18d0c12..e1857d01c47 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts @@ -137,6 +137,35 @@ describe('POST /api/v2/workflows/[workflowId]/runs/[runId]/resume', () => { expect(v2ResumeWorkflowContract.response.schema.parse(body)).toEqual(body) }) + it('names the run a resume that paused again waits under, which is the run it resumed', async () => { + mocks.resume.mockResolvedValueOnce({ + kind: 'sync', + success: true, + status: 'paused', + executionId: 'resume-execution-4', + output: {}, + error: undefined, + structuredError: null, + paused: { + runId: 'run-1', + points: [{ contextId: 'context-4', pauseKind: 'human', resumeStatus: 'paused' }], + }, + }) + const { request, context } = makeRequest(JSON.stringify({ contextId: 'context-3' })) + + const body = await (await POST(request, context)).json() + + expect(body.data).toMatchObject({ + runId: 'resume-execution-4', + status: 'paused', + paused: { + runId: 'run-1', + points: [{ contextId: 'context-4', kind: 'human', status: 'paused' }], + }, + }) + expect(v2ResumeWorkflowContract.response.schema.parse(body)).toEqual(body) + }) + it('wraps synchronous resume results in the canonical v2 run shape', async () => { mocks.resume.mockResolvedValueOnce({ kind: 'sync', @@ -165,6 +194,7 @@ describe('POST /api/v2/workflows/[workflowId]/runs/[runId]/resume', () => { status: 'completed', output: { approved: true }, blockOutputs: null, + paused: null, error: null, startedAt: '2026-08-05T00:00:00.000Z', endedAt: '2026-08-05T00:00:01.000Z', @@ -208,6 +238,7 @@ describe('POST /api/v2/workflows/[workflowId]/runs/[runId]/resume', () => { status: 'failed', output: { partial: true }, blockOutputs: null, + paused: null, error: { message: 'Condition evaluation failed', code: 'BLOCK_EXECUTION_FAILED', diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts index e34f27d2bcb..6f81489ce78 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts @@ -18,7 +18,7 @@ import { } from '@/lib/api/server/routes' import { getBaseUrl } from '@/lib/core/utils/urls' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' -import { v2WorkflowErrorPolicies } from '@/lib/workflows/api' +import { presentV2RunPause, v2WorkflowErrorPolicies } from '@/lib/workflows/api' import { workflowOperations } from '@/lib/workflows/application/operations' import { resumeWorkflowRun } from '@/lib/workflows/application/resume-run' import { ResumeWorkflowExecutionError } from '@/lib/workflows/executor/resume-execution' @@ -118,6 +118,9 @@ export const POST = withRouteHandler( output: result.output ?? null, // Resume has no request body to name selectors in, so selection never applies here. blockOutputs: null, + paused: result.paused + ? presentV2RunPause(result.paused.runId, result.paused.points) + : null, }, { headers } ) diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts index 54c0fc63784..e1b301f5761 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts @@ -150,11 +150,13 @@ describe('v2 run detail and cancel adapters', () => { pausePointCount: 1, resumedCount: 0, }, + pausedRunId: 'run-parent', }) const body = await (await callStatus()).json() expect(body.data.paused.contextId).toBe('context-1') + expect(body.data.paused.runId).toBe('run-parent') expect(body.data.paused).not.toHaveProperty('pausedExecutionId') }) diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts index dffdb4e639a..35465bcdfb7 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts @@ -49,6 +49,7 @@ export const GET = defineV2JsonRoute({ paused: status.paused ? v2WorkflowRunStatusSchema.shape.paused.parse({ ...status.paused, + runId: status.pausedRunId, points: status.pausePoints ?? [], }) : null, diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts index dcb32f2e1be..b9ed2d1ee11 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts @@ -60,7 +60,7 @@ const manifest = { }, ], skills: [{ key: 'triage', id: 'skl_1', name: 'Triage' }], - customTools: [{ key: 'lookup-order', id: 'ctl_1', name: 'lookup_order' }], + customTools: [{ key: 'lookup-order', id: 'ctl_1', name: 'Lookup order' }], mcpServers: [{ key: 'github', id: 'mcp-1', name: 'GitHub', tools: ['create_issue'] }], env: ['CRM_KEY'], truncated: false, diff --git a/apps/sim/blocks/blocks/api.ts b/apps/sim/blocks/blocks/api.ts index 9c0f51140b2..a3859d628fb 100644 --- a/apps/sim/blocks/blocks/api.ts +++ b/apps/sim/blocks/blocks/api.ts @@ -193,7 +193,11 @@ Example: }, }, outputs: { - data: { type: 'json', description: 'API response data (JSON, text, or other formats)' }, + data: { + type: 'json', + description: 'API response data (JSON, text, or other formats)', + mayBeText: true, + }, status: { type: 'number', description: 'HTTP status code (200, 404, 500, etc.)' }, headers: { type: 'json', description: 'HTTP response headers as key-value pairs' }, }, diff --git a/apps/sim/blocks/blocks/function.ts b/apps/sim/blocks/blocks/function.ts index 57fdbd45279..3dde96bf241 100644 --- a/apps/sim/blocks/blocks/function.ts +++ b/apps/sim/blocks/blocks/function.ts @@ -172,7 +172,11 @@ try { }, }, outputs: { - result: { type: 'json', description: 'Structured result emitted by the executed code' }, + result: { + type: 'json', + description: 'Structured result emitted by the executed code', + mayBeText: true, + }, stdout: { type: 'string', description: 'Console log output and debug messages from function execution', diff --git a/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts b/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts index d7145cfba48..32e839a6206 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts @@ -36,7 +36,7 @@ const SOURCE_RESOURCES_EXAMPLE = { }, ], skills: [{ key: 'triage', id: 'skl_7e2a4c19', name: 'Triage' }], - customTools: [{ key: 'lookup-order', id: 'ctl_2b8d6f03', name: 'lookup_order' }], + customTools: [{ key: 'lookup-order', id: 'ctl_2b8d6f03', name: 'Lookup order' }], mcpServers: [ { key: 'github', id: 'mcp-1a2b3c4d', name: 'GitHub', tools: ['create_issue', 'list_issues'] }, ], diff --git a/apps/sim/lib/api/contracts/v2/openapi/workflows.ts b/apps/sim/lib/api/contracts/v2/openapi/workflows.ts index 2568f74eca0..32077cd08dc 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workflows.ts @@ -210,6 +210,7 @@ const RUN_RESULT_EXAMPLE = { startedAt: '2026-08-09T18:04:10.000Z', endedAt: '2026-08-09T18:04:11.000Z', durationMs: 1_000, + paused: null, }, } as const @@ -1590,7 +1591,7 @@ const declaredRoutes = [ operationId: 'resumeWorkflowRunV2', summary: 'Resume workflow run', description: - "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.", + "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt; when it pauses again, `paused.runId` names the run to resume next. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.", errors: [...RESOURCE_ERRORS, 'UsageLimitExceeded', 'Conflict', 'PayloadTooLarge'], success: { byStatus: { diff --git a/apps/sim/lib/api/contracts/v2/source-catalog.ts b/apps/sim/lib/api/contracts/v2/source-catalog.ts index e8ead2205e9..226e57aed92 100644 --- a/apps/sim/lib/api/contracts/v2/source-catalog.ts +++ b/apps/sim/lib/api/contracts/v2/source-catalog.ts @@ -242,6 +242,10 @@ const catalogOutputSchema = z .optional() .describe('When the output is present: `{ field, value, not?, and? }`.'), hiddenFromDisplay: z.boolean().optional().describe('Hidden from the output picker.'), + mayBeText: z + .literal(true) + .optional() + .describe('A `json` or `any` output whose value can still be text at run time.'), properties: z .record(z.string(), z.unknown().describe('A nested output, of this same shape.')) .optional() diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 48bd67376b9..823df6043a6 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -86,6 +86,16 @@ export const v2WorkflowRunIdSchema = runIdSchema .describe('Unique workflow run identifier.') .meta({ examples: ['run_8f14e45f-ceea-467f-a'] }) +/** + * The run a pause is recorded under, which Resume workflow run names. A resumed run that pauses + * again records the pause under the run it resumed, not under the resume attempt's own id. + */ +const v2PausedRunIdSchema = z + .string() + .describe( + 'Run to name in Resume workflow run: the run this pause is recorded under, which for a resumed run that paused again is the run it resumed.' + ) + /** * `X-Run-Id` reserves an execution ID without guaranteeing a retrievable run. * Claims can survive uncertain execution outcomes; a missing run does not make @@ -1839,6 +1849,101 @@ const v2AppliedExecutionTimeoutSchema = z "Execution timeout applied to this run, in seconds: the plan's timeout, lowered by `executionTimeoutSeconds` when one was requested. Null when the run has no execution timeout." ) +const v2PauseInputFieldSchema = z + .object({ + name: z.string().describe('Key to supply this field under in the resume `input`.'), + label: z.string().describe('Display label for the field.'), + type: z.string().describe('Declared value type, such as `string`, `number`, or `boolean`.'), + description: z.string().optional().describe('Field help text, when configured.'), + placeholder: z.string().optional().describe('Placeholder text, when configured.'), + required: z.boolean().describe('Whether the field is marked required.'), + options: z + .array(z.unknown().describe('One selectable option.')) + .optional() + .describe('Selectable options, when the field offers a fixed set.'), + }) + .meta({ + id: 'WorkflowRunPauseInputField', + title: 'Pause input field', + description: 'One field a human pause asks the resumer to fill.', + }) + +const v2WorkflowRunPausePointSchema = z + .object({ + contextId: z + .string() + .describe('Pause context to name in `contextId` when resuming this point.'), + blockId: z.string().describe('Workflow block that paused.'), + blockName: z + .string() + .nullable() + .describe( + 'Name of the block as the run executed it. Null only for a point paused before names were recorded whose run was manual or whose deployment version no longer exists.' + ), + kind: z + .enum(['human', 'time']) + .describe('`human` waits for a resume request; `time` resumes automatically at `resumeAt`.'), + status: z + .enum(['paused', 'queued', 'resuming', 'resumed', 'failed']) + .describe( + 'Resume state of this point: waiting, queued behind another resume, resuming, resumed, or a failed resume attempt.' + ), + registeredAt: z + .string() + .nullable() + .describe( + 'ISO 8601 timestamp when the run paused at this point, or null for a point recorded without one.' + ) + .meta({ format: 'date-time' }), + resumeAt: z + .string() + .nullable() + .describe('ISO 8601 automatic-resume timestamp for a time pause, otherwise null.') + .meta({ format: 'date-time' }), + parallel: z + .object({ + parallelId: z.string().describe('Parallel block containing the pause.'), + branchIndex: z.number().int().describe('Zero-based branch that paused.'), + branchTotal: z + .number() + .int() + .nullable() + .describe('Number of branches, or null when unrecorded.'), + }) + .nullable() + .describe('Parallel branch of the pause, or null outside a parallel.'), + loop: z + .object({ + loopId: z.string().describe('Loop block containing the pause.'), + iteration: z.number().int().describe('Zero-based iteration that paused.'), + }) + .nullable() + .describe('Loop iteration of the pause, or null outside a loop.'), + inputFields: z + .array(v2PauseInputFieldSchema) + .nullable() + .describe( + 'Fields a human pause asks for, without default values. Labels and descriptions are resolved, so they are withheld when organization permission groups hide execution data. Null then, for a time pause, a pause with no declared form, fields over 64 KiB or not provably free of secrets, or one recorded before pause details were captured.' + ), + display: z + .unknown() + .describe('Reviewer content value.') + .nullable() + .describe( + "Content the pause presents to its reviewer, with the run's resolved secrets redacted. Null unless `includeOutput=true`, when hidden by organization permission groups, for a time pause, for content over 64 KiB or not provably free of secrets, or for a pause recorded before pause details were captured." + ), + queuePosition: z + .number() + .int() + .nullable() + .describe('Position among pending resume requests for this run, or null when none waits.'), + }) + .meta({ + id: 'WorkflowRunPausePoint', + title: 'Workflow run pause point', + description: 'One point at which a paused run waits.', + }) + /** * The run result resource. In-band run failures are `status: 'failed'` * with a structured `error` — never an HTTP error: **a `runId` means 200/202 + @@ -1874,6 +1979,17 @@ export const v2ExecuteWorkflowDataSchema = z .meta({ format: 'date-time' }), durationMs: z.number().nonnegative().optional().describe('Execution duration in milliseconds.'), executionTimeoutSeconds: v2AppliedExecutionTimeoutSchema, + paused: z + .object({ + runId: v2PausedRunIdSchema, + points: z + .array(v2WorkflowRunPausePointSchema.pick({ contextId: true, kind: true, status: true })) + .describe( + 'Every point the run is paused at. Resume one with Resume workflow run, naming `runId` and its `contextId`.' + ), + }) + .nullable() + .describe('Where the run waits when `status` is `paused`; null otherwise.'), }) .meta({ id: 'WorkflowRunResult', @@ -2166,101 +2282,6 @@ export const v2RunFileSchema = z }) export type V2RunFile = z.output -const v2PauseInputFieldSchema = z - .object({ - name: z.string().describe('Key to supply this field under in the resume `input`.'), - label: z.string().describe('Display label for the field.'), - type: z.string().describe('Declared value type, such as `string`, `number`, or `boolean`.'), - description: z.string().optional().describe('Field help text, when configured.'), - placeholder: z.string().optional().describe('Placeholder text, when configured.'), - required: z.boolean().describe('Whether the field is marked required.'), - options: z - .array(z.unknown().describe('One selectable option.')) - .optional() - .describe('Selectable options, when the field offers a fixed set.'), - }) - .meta({ - id: 'WorkflowRunPauseInputField', - title: 'Pause input field', - description: 'One field a human pause asks the resumer to fill.', - }) - -const v2WorkflowRunPausePointSchema = z - .object({ - contextId: z - .string() - .describe('Pause context to name in `contextId` when resuming this point.'), - blockId: z.string().describe('Workflow block that paused.'), - blockName: z - .string() - .nullable() - .describe( - 'Name of the block as the run executed it. Null only for a point paused before names were recorded whose run was manual or whose deployment version no longer exists.' - ), - kind: z - .enum(['human', 'time']) - .describe('`human` waits for a resume request; `time` resumes automatically at `resumeAt`.'), - status: z - .enum(['paused', 'queued', 'resuming', 'resumed', 'failed']) - .describe( - 'Resume state of this point: waiting, queued behind another resume, resuming, resumed, or a failed resume attempt.' - ), - registeredAt: z - .string() - .nullable() - .describe( - 'ISO 8601 timestamp when the run paused at this point, or null for a point recorded without one.' - ) - .meta({ format: 'date-time' }), - resumeAt: z - .string() - .nullable() - .describe('ISO 8601 automatic-resume timestamp for a time pause, otherwise null.') - .meta({ format: 'date-time' }), - parallel: z - .object({ - parallelId: z.string().describe('Parallel block containing the pause.'), - branchIndex: z.number().int().describe('Zero-based branch that paused.'), - branchTotal: z - .number() - .int() - .nullable() - .describe('Number of branches, or null when unrecorded.'), - }) - .nullable() - .describe('Parallel branch of the pause, or null outside a parallel.'), - loop: z - .object({ - loopId: z.string().describe('Loop block containing the pause.'), - iteration: z.number().int().describe('Zero-based iteration that paused.'), - }) - .nullable() - .describe('Loop iteration of the pause, or null outside a loop.'), - inputFields: z - .array(v2PauseInputFieldSchema) - .nullable() - .describe( - 'Fields a human pause asks for, without default values. Labels and descriptions are resolved, so they are withheld when organization permission groups hide execution data. Null then, for a time pause, a pause with no declared form, fields over 64 KiB or not provably free of secrets, or one recorded before pause details were captured.' - ), - display: z - .unknown() - .describe('Reviewer content value.') - .nullable() - .describe( - "Content the pause presents to its reviewer, with the run's resolved secrets redacted. Null unless `includeOutput=true`, when hidden by organization permission groups, for a time pause, for content over 64 KiB or not provably free of secrets, or for a pause recorded before pause details were captured." - ), - queuePosition: z - .number() - .int() - .nullable() - .describe('Position among pending resume requests for this run, or null when none waits.'), - }) - .meta({ - id: 'WorkflowRunPausePoint', - title: 'Workflow run pause point', - description: 'One point at which a paused run waits.', - }) - /** * The polled run resource. `queued` is backfilled from the async job * queue before the worker writes the durable log row — v1's jobs endpoint 404 @@ -2314,6 +2335,7 @@ export const v2WorkflowRunStatusSchema = z paused: workflowExecutionPausedDetailSchema .omit({ pausedExecutionId: true }) .extend({ + runId: v2PausedRunIdSchema, points: z .array(v2WorkflowRunPausePointSchema) .describe( diff --git a/apps/sim/lib/api/contracts/v2/workspace-source.ts b/apps/sim/lib/api/contracts/v2/workspace-source.ts index a7785a09215..cbc1dbd005a 100644 --- a/apps/sim/lib/api/contracts/v2/workspace-source.ts +++ b/apps/sim/lib/api/contracts/v2/workspace-source.ts @@ -115,7 +115,7 @@ const baseResourceSchema = z z.string(), z.object({ id: z.string().describe('Stored id of the binary file.'), - rev: z.union([z.number().int(), z.string()]).describe('Content revision as last read.'), + rev: z.string().describe('Content revision as last read.'), sha256: sha256Schema, }) ) diff --git a/apps/sim/lib/api/contracts/workflow-source.ts b/apps/sim/lib/api/contracts/workflow-source.ts index c44227b4d8a..39f43eedae9 100644 --- a/apps/sim/lib/api/contracts/workflow-source.ts +++ b/apps/sim/lib/api/contracts/workflow-source.ts @@ -144,10 +144,7 @@ export function sourceFingerprintSchema(field: string) { } export const sourceBaseSchema = withExtensions({ - version: z - .literal(1) - .default(1) - .describe('Base format version; a base written before it existed reads as 1.'), + version: z.literal(1).describe('Base format version.'), workflowId: z .string() .min(1, 'base.workflowId cannot be empty') diff --git a/apps/sim/lib/api/mcp/generated/v2-operations.ts b/apps/sim/lib/api/mcp/generated/v2-operations.ts index 17226db8242..ee6a66d1b0f 100644 --- a/apps/sim/lib/api/mcp/generated/v2-operations.ts +++ b/apps/sim/lib/api/mcp/generated/v2-operations.ts @@ -2812,7 +2812,7 @@ export const V2_MCP_OPERATIONS = { contract: v2ResumeWorkflowContract, summary: 'Resume workflow run', description: - "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.\n\nOAuth scope: `api:write`.", + "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt; when it pauses again, `paused.runId` names the run to resume next. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.\n\nOAuth scope: `api:write`.", handler: () => import('@/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route').then( (route) => route.POST diff --git a/apps/sim/lib/workflows/api/index.ts b/apps/sim/lib/workflows/api/index.ts index 45bf083bdb5..0acd93e54d1 100644 --- a/apps/sim/lib/workflows/api/index.ts +++ b/apps/sim/lib/workflows/api/index.ts @@ -7,6 +7,7 @@ export { v2WorkflowErrorPolicies, WORKFLOW_NOT_FOUND_MESSAGE, } from '@/lib/workflows/api/route-policies' +export { presentV2RunPause } from '@/lib/workflows/api/run-pause' export { withBoundSourceFindings } from '@/lib/workflows/api/source-findings' export { presentSourceOutcome } from '@/lib/workflows/api/source-presenters' export { applyOrDryRunLane, withSourceSlot } from '@/lib/workflows/api/source-slots' diff --git a/apps/sim/lib/workflows/api/run-pause.ts b/apps/sim/lib/workflows/api/run-pause.ts new file mode 100644 index 00000000000..d214a2c7ab2 --- /dev/null +++ b/apps/sim/lib/workflows/api/run-pause.ts @@ -0,0 +1,20 @@ +import type { V2ExecuteWorkflowData } from '@/lib/api/contracts/v2/workflows' +import type { PausePoint } from '@/executor/types' + +/** + * The v2 wire shape of where a run waits, shared by the execute and resume results: the run the + * pause is recorded under (which Resume workflow run names) and each of its points. + */ +export function presentV2RunPause( + runId: string, + points: readonly PausePoint[] +): NonNullable { + return { + runId, + points: points.map((point) => ({ + contextId: point.contextId, + kind: point.pauseKind, + status: point.resumeStatus, + })), + } +} diff --git a/apps/sim/lib/workflows/application/read-workflow-run.ts b/apps/sim/lib/workflows/application/read-workflow-run.ts index d0f1dc53767..ade832c08bf 100644 --- a/apps/sim/lib/workflows/application/read-workflow-run.ts +++ b/apps/sim/lib/workflows/application/read-workflow-run.ts @@ -175,7 +175,7 @@ export const readWorkflowRun = defineAuthorizedWorkflowUseCase({ ) : null - return { ...status, files, pausePoints, failedBlock } + return { ...status, files, pausePoints, pausedRunId: stateExecutionId, failedBlock } } catch (error) { if (error instanceof FunctionalOutputsUnavailableError) { throw new OrchestrationError('conflict', FUNCTIONAL_OUTPUTS_UNAVAILABLE_MESSAGE) diff --git a/apps/sim/lib/workflows/code/catalog/project.ts b/apps/sim/lib/workflows/code/catalog/project.ts index ca7a99051cb..ab070760398 100644 --- a/apps/sim/lib/workflows/code/catalog/project.ts +++ b/apps/sim/lib/workflows/code/catalog/project.ts @@ -404,6 +404,7 @@ const OUTPUT_META_KEYS = new Set([ 'description', 'condition', 'hiddenFromDisplay', + 'mayBeText', 'nullable', 'properties', 'items', @@ -447,6 +448,7 @@ function projectOutput(definition: unknown): CatalogOutput | undefined { output.condition = copyOutputCondition(record.condition as OutputCondition) } if (typed && record.hiddenFromDisplay === true) output.hiddenFromDisplay = true + if (typed && record.mayBeText === true) output.mayBeText = true const nested: Record = {} if (record.properties && typeof record.properties === 'object') { diff --git a/apps/sim/lib/workflows/code/json-field-refs.test.ts b/apps/sim/lib/workflows/code/json-field-refs.test.ts index 2e591b2d8e4..4f03e80640d 100644 --- a/apps/sim/lib/workflows/code/json-field-refs.test.ts +++ b/apps/sim/lib/workflows/code/json-field-refs.test.ts @@ -109,3 +109,38 @@ describe('JSON field literals against the real resolver', () => { }) }) }) + +describe('JSON field references to an output that may be text', () => { + /** The `W_JSON_REF_UNTYPED` tokens of a row whose JSON `data` holds `fields` bare. */ + function untypedTokens(fields: string): string[] { + const compiled = compileWorkflow({ + entry: { + path: 'workflow.ts', + text: `// @sim-sdk 1 +import { api, table, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Text outputs', {}, () => { + const start = trigger.start('Start') + const fetchTicket = api('Fetch ticket', { url: 'https://example.com', method: 'GET' }) + const logTicket = table.insertRow('Log ticket', { tableId: table('tickets'), data: { ${fields} } }) + start.to(fetchTicket).to(logTicket) +}) +`, + }, + files: new Map(), + catalog, + sdkMajor: catalog.sdkMajor, + }) + return compiled.diagnostics + .filter((diagnostic) => diagnostic.code === 'W_JSON_REF_UNTYPED') + .map((diagnostic) => diagnostic.message.match(/<[^>]+>/)?.[0] ?? diagnostic.message) + } + + it('flags a bare HTTP body, which a text response splices in unquoted', () => { + expect(untypedTokens('body: fetchTicket.data')).toEqual(['']) + }) + + it('stores a bare JSON output that is never text without a warning', () => { + expect(untypedTokens('headers: fetchTicket.headers, status: fetchTicket.status')).toEqual([]) + }) +}) diff --git a/apps/sim/lib/workflows/executor/execute-service.ts b/apps/sim/lib/workflows/executor/execute-service.ts index d79453a28a1..8bd2407c3b0 100644 --- a/apps/sim/lib/workflows/executor/execute-service.ts +++ b/apps/sim/lib/workflows/executor/execute-service.ts @@ -52,7 +52,7 @@ import { workflowHasResponseBlock } from '@/lib/workflows/utils' import { normalizeName } from '@/executor/constants' import { ExecutionSnapshot } from '@/executor/execution/snapshot' import type { ExecutionMetadata, SerializableExecutionState } from '@/executor/execution/types' -import type { BlockLog, NormalizedBlockOutput } from '@/executor/types' +import type { BlockLog, NormalizedBlockOutput, PausePoint } from '@/executor/types' import { classifyExecutionError, hasExecutionResult, @@ -183,6 +183,8 @@ export interface ExecuteWorkflowServiceRun { durationMs?: number /** The execution timeout applied to the run in milliseconds; `0` means untimed. */ executionTimeoutMs: number + /** Where a `paused` run waits, recorded under its `executionId`. */ + pausePoints?: PausePoint[] } /** A run's result before the applied timeout is stamped onto it. */ @@ -864,6 +866,7 @@ export async function executeWorkflowService( startedAt: result.metadata?.startTime, endedAt: result.metadata?.endTime, durationMs: result.metadata?.duration, + ...(status === 'paused' ? { pausePoints: result.pausePoints ?? [] } : {}), } } catch (error: unknown) { const errorMessage = getErrorMessage(error, 'Unknown error') diff --git a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts index 77c30588b6b..08d9acc71a8 100644 --- a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts +++ b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts @@ -175,6 +175,14 @@ class ResumeAdmissionError extends Error { export type FailedResumeOutcome = 'pause_retained' | 'execution_failed' | 'execution_completed' /** Matches the paused execution mode to the deployment recorded on its durable root log. */ +/** + * The run a resumed attempt's pause is recorded under: the execution the resumed engine ran as, + * else the attempt's own id. Resume workflow run names this run to resume the pause. + */ +export function pausedRunIdOf(result: ExecutionResult, resumeExecutionId: string): string { + return result.metadata?.executionId ?? resumeExecutionId +} + export function requireResumeDeploymentVersion( useDraftState: unknown, deploymentVersionId: string | null @@ -997,7 +1005,7 @@ export class PauseResumeManager { * reason, then throw so the attempt settles as failed below. The thrown * message stays stable; the underlying error rides on `cause`. */ - const effectiveExecutionId = result.metadata?.executionId ?? resumeExecutionId + const effectiveExecutionId = pausedRunIdOf(result, resumeExecutionId) const failPause = async (reason: string, cause?: unknown): Promise => { logger.error( reason, diff --git a/apps/sim/lib/workflows/executor/resume-execution.ts b/apps/sim/lib/workflows/executor/resume-execution.ts index 2ba5d6e4d06..484d605e7a2 100644 --- a/apps/sim/lib/workflows/executor/resume-execution.ts +++ b/apps/sim/lib/workflows/executor/resume-execution.ts @@ -14,11 +14,14 @@ import type { OrchestrationRequestContext } from '@/lib/core/orchestration/types import { generateRequestId } from '@/lib/core/utils/request' import { preprocessExecution } from '@/lib/execution/preprocessing' import { RESUME_EXECUTION_JOB_ID_PREFIX } from '@/lib/workflows/executor/enqueue-execution' -import { PauseResumeManager } from '@/lib/workflows/executor/human-in-the-loop-manager' +import { + PauseResumeManager, + pausedRunIdOf, +} from '@/lib/workflows/executor/human-in-the-loop-manager' import { createStreamingResponse } from '@/lib/workflows/streaming/streaming' import { executeResumeJob, type ResumeExecutionPayload } from '@/background/resume-execution' import { ExecutionSnapshot } from '@/executor/execution/snapshot' -import type { ExecutionResult } from '@/executor/types' +import type { ExecutionResult, PausePoint } from '@/executor/types' import { classifyExecutionError, hasExecutionResult, @@ -87,6 +90,8 @@ export type ResumeWorkflowExecutionResult = startTime?: string endTime?: string } + /** Where a run that paused again waits: the run the pause is recorded under, and its points. */ + paused: { runId: string; points: PausePoint[] } | null } | { kind: 'async' @@ -353,6 +358,13 @@ export async function executeResumeWorkflow({ endTime: result.metadata.endTime, } : undefined, + paused: + status === 'paused' + ? { + runId: pausedRunIdOf(result, enqueueResult.resumeExecutionId), + points: result.pausePoints ?? [], + } + : null, } } diff --git a/packages/sim-cli/src/commands/protocol/source-apply-interrupt.test.ts b/packages/sim-cli/src/commands/protocol/source-apply-interrupt.test.ts index 825607bb8e6..4738c91be95 100644 --- a/packages/sim-cli/src/commands/protocol/source-apply-interrupt.test.ts +++ b/packages/sim-cli/src/commands/protocol/source-apply-interrupt.test.ts @@ -9,6 +9,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' const WORKFLOW_ID = '00000000-0000-4000-8000-00000000000a' const WORKSPACE_ID = 'ws_local' const BASE = { + version: 1, workflowId: WORKFLOW_ID, workspaceId: WORKSPACE_ID, fingerprint: 'sf1:a', diff --git a/packages/sim-cli/src/commands/protocol/source-dir/write-back.ts b/packages/sim-cli/src/commands/protocol/source-dir/write-back.ts index bba48bcac50..5824db7a80c 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/write-back.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/write-back.ts @@ -16,13 +16,7 @@ import { fingerprintOf } from '@sim/workspace-code' import { printError } from '#sim-cli/output/io' import { type WorkspaceFolder, workspaceFolderOf } from './dir-kind' import { readSourceJson, readSourceText, type SourceDirChange, updateSourceDir } from './files' -import { - lockCodeFiles, - orphanedCodeFiles, - SOURCE_WRITTEN_FILE, - sourceRelativePath, - writableFiles, -} from './layout' +import { lockCodeFiles, orphanedCodeFiles, sourceRelativePath, writableFiles } from './layout' import { digest, inWorkspace, @@ -104,12 +98,7 @@ export async function writeBack( const unnamed = await unnamedCodeFiles(dir, previousLock, answer, orphaned) await updateSourceDir(dir, { write, - remove: [ - ...orphaned, - ...(extra.remove ?? []), - // A record of the folder's own, from before, would shadow the workspace's. - ...(folder ? [SOURCE_WRITTEN_FILE] : []), - ], + remove: [...orphaned, ...(extra.remove ?? [])], }) if (folder) await recordFolderWrite(folder, Object.fromEntries(printed), orphaned, answer.base) if (unnamed.length > 0) { diff --git a/packages/sim-cli/src/commands/protocol/source-dir/written.ts b/packages/sim-cli/src/commands/protocol/source-dir/written.ts index 4823a24b9cc..604926b9e04 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/written.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/written.ts @@ -8,7 +8,6 @@ import { createHash } from 'node:crypto' import { mapWithConcurrency } from '@sim/utils/concurrency' import { toRecord } from '@sim/utils/object' import { compareStrings } from '@sim/utils/string' -import { SOURCE_BASE_FILE } from '@sim/workflow-code/limits' import { KIND_DIRS } from '@sim/workspace-code' import { workspaceFolderOf } from './dir-kind' import { FILE_CONCURRENCY, normalizeSourceText, readSourceJson, readSourceText } from './files' @@ -229,22 +228,12 @@ export function inWorkspace(key: string, path: string): string { /** * What the CLI last wrote into the workflow directory `dir`: its own `.sim/written.json`, or for a * workflow folder of a workspace directory, the workspace record's entries for the folder (its - * `.sim/` records left out). A write into such a folder records there and never in the folder, but - * a CLI from before that left a record of the folder's own. That record wins only when it is the - * later one: when the workspace record's digest of the folder's `.sim/base.json` is not the base on - * disk, a single-workflow write replaced the base after the workspace record was taken. Otherwise - * the folder's own record is stale and ignored. + * `.sim/` records left out). A write into such a folder records there and never in the folder. */ export async function readFolderWritten(dir: string): Promise { - const own = await readWritten(dir) const folder = await workspaceFolderOf(dir) - if (!folder) return own + if (!folder) return readWritten(dir) const record = await readWritten(folder.root) - if (Object.keys(own.digests).length > 0) { - const base = await readSourceText(dir, SOURCE_BASE_FILE) - const recorded = record.digests[inWorkspace(folder.key, SOURCE_BASE_FILE)] - if (base !== null && recorded !== digest(base)) return own - } const prefix = inWorkspace(folder.key, '') const inFolder = (entries: Record) => Object.fromEntries( diff --git a/packages/sim-cli/src/commands/protocol/source-status.ts b/packages/sim-cli/src/commands/protocol/source-status.ts index ee87b021f3f..27421281ccf 100644 --- a/packages/sim-cli/src/commands/protocol/source-status.ts +++ b/packages/sim-cli/src/commands/protocol/source-status.ts @@ -553,20 +553,6 @@ export function nextStep(status: SourceStatus, input: NextStepInput): NextStep | } } -/** - * A status's plan: the plan read, or, from a server that predates it (its route answers `404`), - * the apply dry run it replaced, which spends the source-write budget. A `404` the dry run also - * answers is the resource's own, and is thrown. - */ -export async function readPlan(plan: () => Promise, dryRun: () => Promise): Promise { - try { - return await plan() - } catch (error) { - if (!(error instanceof SimApiError) || error.status !== 404) throw error - return dryRun() - } -} - /** The changes that delete something (a resource, rows, documents, columns, a deployment). */ export function destructiveChanges( changes: ReadonlyArray> diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index 6c1972785c6..cba59952a8f 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -5,7 +5,6 @@ * the agent guide and the LF lines. */ import { createHash } from 'node:crypto' -import { rmSync } from 'node:fs' import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { mapWithConcurrency } from '@sim/utils/concurrency' @@ -29,7 +28,6 @@ import { sdkIndexHeader, type WorkspaceManifest, } from '@sim/workflow-sdk/codegen' -import type { Command } from 'commander' import { printError, printLine } from '#sim-cli/output/io' import type { OutputFormat } from '../../config/index' import { readJsonFile, writeJsonFile } from '../../config/json-file' @@ -178,19 +176,10 @@ function writeCachedCatalog(catalog: BlockCatalog): void { writeJsonFile(catalogCachePath(catalog.hash), catalog) } -/** - * Records `hash` as the workspace's catalog, dropping the per-workspace copy and the - * per-workflow copies an older CLI cached under the workspace id. - */ +/** Records `hash` as the workspace's catalog. */ function writeWorkspaceCatalogPointer(workspaceId: string, hash: string): void { if (embedStore.getStore() || !CACHE_KEY.test(workspaceId)) return writeJsonFile(workspaceCatalogPointerPath(workspaceId), { hash }) - for (const legacy of [`${workspaceId}.json`, workspaceId]) { - if (legacy === `${hash}.json`) continue - try { - rmSync(join(catalogCacheDir(), legacy), { recursive: true, force: true }) - } catch {} - } } /** @@ -258,18 +247,15 @@ export async function loadCatalog( return loadWorkflowCatalog(client, source.workspaceId, source.workflowId) } -/** - * The resource manifest as `generateWorkspaceTypes` reads it. A server older than the skills, - * custom tools and MCP servers sections omits them, which leaves those keys plain strings. - */ +/** The resource manifest as `generateWorkspaceTypes` reads it. */ function workspaceManifestFrom({ tables, knowledgeBases, credentials, workflows, - skills = [], - customTools = [], - mcpServers = [], + skills, + customTools, + mcpServers, env, }: GetSourceResourcesResponse['data']): WorkspaceManifest { return { @@ -365,7 +351,7 @@ function workspaceTypesFrom( /** * The workspace's resources as `workspace.d.ts` ({@link workspaceTypesFrom}), read from the * server. When the resources cannot be listed (a `403` for a caller the manifest does not admit, a - * `404` from a server that predates the route) only the declared resources are typed, or `null` + * `404` for a workspace it cannot see) only the declared resources are typed, or `null` * without any: the source still writes and type-checks, with every other key a plain string. */ export async function loadWorkspaceTypes( @@ -391,7 +377,7 @@ export async function loadWorkspaceTypes( /** * Regenerates `workspace.d.ts` from the stored manifest the last get kept beside it and what the * directory declares now (`local`), so `tsc` types a key added since without a request. A - * directory with no kept manifest (written by an older CLI) is left as it is. + * directory with no kept manifest (no get has written its types) is left as it is. */ export async function refreshWorkspaceTypes(dir: string, local: LocalDeclarations): Promise { const [manifest, current] = await Promise.all([ @@ -575,8 +561,8 @@ export function finishTree( /** * Prints a tree write's result: the fields, then the primer as text when the result carries one - * (in JSON or YAML it is the document's `primer` field). A get leaves the primer out unless - * `--primer` asks for it: it is already the top of `.sim/AGENTS.md`. + * (in JSON or YAML it is the document's `primer` field). A get leaves the primer out: it is + * already the top of `.sim/AGENTS.md`. */ export function printTreeResult( format: OutputFormat, @@ -591,14 +577,6 @@ export function printTreeResult( if (primer !== undefined) printLine(`\n${primer}`) } -/** Adds `--primer` to a get command: it prints the primer the get writes atop `.sim/AGENTS.md`. */ -export function primerOption(command: Command): void { - command.option( - '--primer', - 'Also print the primer written atop .sim/AGENTS.md (a `primer` field in JSON)' - ) -} - /** * The edit loop of a directory for a get's result, as the one chained command the primer * recommends: runnable from anywhere because it names the directory. Apply re-checks everything diff --git a/packages/sim-cli/src/commands/protocol/stored-edges.ts b/packages/sim-cli/src/commands/protocol/stored-edges.ts index aedb5cd0ceb..5df1625a9f7 100644 --- a/packages/sim-cli/src/commands/protocol/stored-edges.ts +++ b/packages/sim-cli/src/commands/protocol/stored-edges.ts @@ -172,7 +172,7 @@ function isStoredEdge(value: unknown): value is StoredEdgeRef { /** * The stored edges recorded for the base `dir` holds now, or `undefined` when none are: no - * record, one an older CLI or another base wrote, or a malformed one. + * record, one another base wrote, or a malformed one. */ export async function readStoredEdges(dir: string): Promise { const [record, base] = await Promise.all([ @@ -195,7 +195,7 @@ export async function readStoredEdges(dir: string): Promise } | null } @@ -149,7 +151,15 @@ describe('workflows runs wait', () => { }) it('stops on a pause that is waiting for a human, and says how to resume it', async () => { - respondWith({ status: 'paused', paused: { pauseKind: 'human', contextId: 'ctx_9' } }) + respondWith({ + status: 'paused', + paused: { + pauseKind: 'human', + contextId: 'ctx_9', + runId: 'run_1', + points: [{ contextId: 'ctx_9', status: 'paused' }], + }, + }) await wait() @@ -160,11 +170,16 @@ describe('workflows runs wait', () => { ) }) - it('names the same resume command the run record prints in next, from the output links', async () => { + it('names the run the server records the pause under, not the run it waited on', async () => { respondWith({ status: 'paused', - output: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } }, - paused: { pauseKind: 'human', contextId: 'ctx_other' }, + output: { data: { _resume: { contextId: 'decoy', executionId: 'decoy_run' } } }, + paused: { + pauseKind: 'human', + contextId: 'ctx_9', + runId: 'exec_9', + points: [{ contextId: 'ctx_9', status: 'paused' }], + }, }) await wait() diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts b/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts index 0942fc29e2b..5e90c89f5be 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts @@ -196,7 +196,7 @@ function explain( if (outcome === 'completed') return null if (outcome === 'failed') return `Run ${runId} failed.` if (outcome === 'cancelled') return `Run ${runId} was cancelled.` - const next = resumeCommandFor(toRecord(run), { runId, workflowId }) + const next = resumeCommandFor(toRecord(run), { workflowId }) return `Run ${runId} is paused waiting for input.${next ? ` Resume it: ${next}` : ''}` } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts index 23a468b5521..7a6bdf08467 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts @@ -52,6 +52,7 @@ const WORKFLOW_ID = '00000000-0000-4000-8000-00000000000a' const WORKSPACE_ID = 'ws_local' const APPLY_PATH = `/api/v2/workflows/${WORKFLOW_ID}/source` const BASE = { + version: 1, workflowId: WORKFLOW_ID, workspaceId: WORKSPACE_ID, fingerprint: 'sf1:a', @@ -950,6 +951,9 @@ describe('sim workflows source apply', () => { knowledgeBases: [], credentials: [], workflows: [], + skills: [], + customTools: [], + mcpServers: [], env: [], truncated: false, }, @@ -1480,6 +1484,9 @@ describe('sim workflows source create on a directory with no workflow.ts', () => knowledgeBases: [], credentials: [], workflows: [], + skills: [], + customTools: [], + mcpServers: [], env: ['OPENAI_API_KEY'], truncated: false, }, diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts index f8ec2bf80c7..ba073a04761 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts @@ -44,6 +44,7 @@ function printedWithFixture(): void { writeFileSync( join(dir, '.sim/base.json'), JSON.stringify({ + version: 1, workflowId: 'wf', workspaceId: WORKSPACE_ID, fingerprint: 'sf1:a', diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts index afabfff8220..20c2b886019 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts @@ -53,6 +53,7 @@ function source( files, lock: { version: 1, blocks: {}, variables: {} }, base: { + version: 1, workflowId: WORKFLOW_ID, workspaceId: WORKSPACE_ID, fingerprint: 'sf1:x', @@ -124,7 +125,8 @@ const MANIFEST = { credentials: [], workflows: [], skills: [{ key: 'triage', id: 'skill-1', name: 'Triage' }], - customTools: [{ key: 'lookup-order', id: 'tool-1', name: 'lookup_order' }], + customTools: [{ key: 'lookup-order', id: 'tool-1', name: 'Lookup order' }], + mcpServers: [], env: [], truncated: false, }, @@ -184,7 +186,7 @@ describe('sim workflows source get --dir', () => { expect(callsTo(CATALOG_PATH)[0][1].query).toBeUndefined() }) - it('writes the primer atop the guide with a snippet for each builder the source calls and no other, printing it only with --primer', async () => { + it('writes the primer atop the guide with a snippet for each builder the source calls and no other, without printing it', async () => { serve({ [SOURCE_PATH]: () => source({ 'workflow.ts': "// @sim-sdk 1\nconst mail = gmail.sendEmail('Mail', {})\n" }), @@ -203,12 +205,6 @@ describe('sim workflows source get --dir', () => { const agents = readFileSync(join(outDir, '.sim/AGENTS.md'), 'utf8') expect(agents).toContain('- `gmail.sendEmail` (Gmail: Send Email)') expect(agents).not.toContain('`slack.sendMessage`') - - vi.mocked(console.log).mockClear() - await get('--dir', outDir, '--primer') - - const { primer } = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') - expect(agents.startsWith(primer)).toBe(true) }) it('writes a root AGENTS.md pointing at the guide, and never replaces one it did not write', async () => { diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts index 4a9d147e2d3..b9aba27c52a 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -15,7 +15,7 @@ import { withSourceCommandLock, } from './source-dir' import { sourceExitCodesHelp } from './source-exit-codes' -import { editLoop, primerOption, printTreeResult, withSourceExitCode } from './source-tree' +import { editLoop, printTreeResult, withSourceExitCode } from './source-tree' import { findingsOutput } from './source-ui' import { type PrintedSource, writeSourceDirectory } from './workflow-dir' @@ -60,8 +60,8 @@ async function assertNoLocalEdits(dir: string, source: PrintedSource): Promise => { @@ -124,7 +123,7 @@ export function attachWorkflowSourceGet(source: Command): void { ) assertPrintedSourcePaths(workflowSource.files) if (!force) await assertNoLocalEdits(dir, workflowSource) - const { primer, ...tree } = await writeSourceDirectory( + const { primer: _, ...tree } = await writeSourceDirectory( client, dir, workflowSource, @@ -137,7 +136,6 @@ export function attachWorkflowSourceGet(source: Command): void { dir, ...tree, editLoop: editLoop('workflow', dir), - ...(flags.primer === true ? { primer } : {}), fingerprint: workflowSource.base.fingerprint, ...findings.result(workflowSource.diagnostics), }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts index e0b6ff5fc86..2dcc4a2067d 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts @@ -52,6 +52,7 @@ function writeBase(catalogHash?: string): void { writeFileSync( join(dir, '.sim/base.json'), JSON.stringify({ + version: 1, workflowId: 'wf', workspaceId: WORKSPACE_ID, fingerprint: 'sf1:a', diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts index 3c2e9ac19ee..5c7d6238dab 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts @@ -1,4 +1,3 @@ -import { createHash } from 'node:crypto' import { existsSync, mkdirSync, @@ -181,6 +180,9 @@ const MANIFEST = { knowledgeBases: [], credentials: [{ key: 'support-slack', id: 'c-1', name: 'Support Slack', provider: 'slack' }], workflows: [], + skills: [], + customTools: [], + mcpServers: [], env: ['CRM_KEY'], truncated: false, } @@ -673,24 +675,6 @@ describe('a get into a directory that already holds source', () => { expect(read('functions/score.js')).toBe('return 2\r\n') }) - it('replaces unedited CRLF function code an older CLI recorded with its raw digest', async () => { - const crlf = { ...FILES, 'functions/score.js': 'return 1\r\n' } - server.source = () => json(sourceResponse(crlf)) - await get() - const sha256 = (text: string) => createHash('sha256').update(text, 'utf8').digest('hex') - writeFileSync( - join(dir, '.sim/written.json'), - JSON.stringify({ - version: 1, - files: Object.fromEntries(Object.entries(crlf).map(([path, text]) => [path, sha256(text)])), - }) - ) - - await get() - - expect(read('functions/score.js')).toBe('return 1\r\n') - }) - it('refuses to overwrite an unapplied edit, such as the one a stale apply refused', async () => { await get() writeFileSync(join(dir, 'workflow.ts'), EDITED) @@ -1068,8 +1052,6 @@ describe('checking a workflow holding a type the workspace catalog withholds', ( it('caches each catalog once by its hash, fetching the workflow catalog only while uncached', async () => { const cacheDir = join(root, 'config/cache/source-catalog') - mkdirSync(join(cacheDir, WORKSPACE_ID), { recursive: true }) - writeFileSync(join(cacheDir, `${WORKSPACE_ID}.json`), '{}') serve(TICKET_ROUTER) const queries: string[] = [] const answer = server.catalog diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts index d76df0e22dd..0bd0c3afd64 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts @@ -15,6 +15,7 @@ const { mockRequest, mockProfileFrom } = contextMockFns const WORKFLOW_ID = '00000000-0000-4000-8000-00000000000a' const WORKSPACE_ID = 'ws_local' const BASE = { + version: 1, workflowId: WORKFLOW_ID, workspaceId: WORKSPACE_ID, fingerprint: 'sf1:a', @@ -393,26 +394,14 @@ describe('workflows source status', () => { expect(process.exitCode).toBe(12) }) - it('falls back to the apply dry run on a server without the plan read', async () => { - mockRequest - .mockRejectedValueOnce(new SimApiError('Not found', 404, 'NOT_FOUND')) - .mockResolvedValueOnce(dryRun()) + it('reports a workflow the server no longer has as deleted there', async () => { + mockRequest.mockRejectedValue(new SimApiError('Workflow not found', 404, 'NOT_FOUND')) await run(root, 'status') expect(mockRequest.mock.calls.map(([path]) => path)).toEqual([ `/api/v2/workflows/${WORKFLOW_ID}/source/plan`, - `/api/v2/workflows/${WORKFLOW_ID}/source`, ]) - expect(mockRequest.mock.calls[1][1].query).toEqual({ dryRun: true, allowDelete: true }) - expect(printed()).toMatchObject({ state: 'clean', server: 'checked' }) - }) - - it('reports a workflow the server no longer has as deleted there', async () => { - mockRequest.mockRejectedValue(new SimApiError('Workflow not found', 404, 'NOT_FOUND')) - - await run(root, 'status') - expect(printed()).toMatchObject({ state: 'drift', drift: [{ kind: 'workflow', key: WORKFLOW_ID, server: 'deleted' }], @@ -528,18 +517,8 @@ describe('workflows source status', () => { local: [{ files: [{ path: 'functions/score.js', change: 'edited' }] }], }) }) - it.each([ - [ - 'the workspace record, which records the folder base on disk, over a stale record of its own', - true, - [], - ], - [ - 'a record of its own when the workspace record predates the folder base (an older CLI wrote it)', - false, - [{ path: 'functions/score.js', change: 'edited' }], - ], - ])('in a workspace folder, reads %s', async (_label, rootCurrent, files) => { + + it("ignores a written record in a workspace folder, reading only the workspace directory's", async () => { const ws = join(root, 'ws') const folder = join(ws, 'workflows/score') write( @@ -549,11 +528,8 @@ describe('workflows source status', () => { ) writeWorkflowDir(folder, { at: ws, prefix: 'workflows/score/' }) const rootRecord = JSON.parse(readFileSync(join(ws, '.sim/written.json'), 'utf8')) - rootRecord.files['workflows/score/.sim/base.json'] = rootCurrent - ? digest(JSON.stringify(BASE)) - : digest('an older base') + rootRecord.files['workflows/score/.sim/base.json'] = digest('another base') write(ws, '.sim/written.json', JSON.stringify(rootRecord)) - // A nested record an older CLI left: score.js as it was before the last write. write( folder, '.sim/written.json', @@ -565,9 +541,8 @@ describe('workflows source status', () => { await run(folder, 'status', '--offline') - expect(printed()).toMatchObject({ server: 'offline' }) const local = (printed().local ?? []) as Array<{ files: unknown[] }> - expect(local.flatMap((entry) => entry.files)).toEqual(files) + expect(local.flatMap((entry) => entry.files)).toEqual([]) }) }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts index 386ebd0e6ca..188d5b2efe6 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.ts @@ -42,7 +42,6 @@ import { planFindings, printDiffReport, printStatusReport, - readPlan, type ServerCheck, STATUS_EXIT_CODES_HELP, type StatusReport, @@ -193,22 +192,12 @@ export function attachWorkflowSourceStatus(source: Command): void { const files = await readSourceFiles(options.dir, lock) try { const body = { files, lock, base: local.base } - const response = await readPlan( - () => - client.request('planWorkflowSource', { - params: { workflowId }, - query: { allowDelete: true }, - body, - retryRateLimited: true, - }), - () => - client.request('applyWorkflowSource', { - params: { workflowId }, - query: { dryRun: true, allowDelete: true }, - body: { ...body, provenance: { client: 'cli' } }, - retryRateLimited: true, - }) - ) + const response = await client.request('planWorkflowSource', { + params: { workflowId }, + query: { allowDelete: true }, + body, + retryRateLimited: true, + }) data = response.data await refreshWorkflowWorkspaceTypes(client, options.dir, local.base.workspaceId) if (data.diagnostics.some((finding) => finding.code === 'E_APPLY_STALE')) { diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index 2e0f1aed8be..c3c8797eae3 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -68,7 +68,13 @@ const LEADS = "// @sim-sdk 1\nexport default defineTable({ name: 'leads', column const INGEST = "// @sim-sdk 1\nexport default workflow('Ingest', {}, () => {})\n" /** A workflow folder's base, as a get in `workspaceId` writes it. */ const folderBase = (workspaceId: string) => - JSON.stringify({ workflowId: 'wf_1', workspaceId, fingerprint: 'sf1:a', catalogHash: 'c' }) + JSON.stringify({ + version: 1, + workflowId: 'wf_1', + workspaceId, + fingerprint: 'sf1:a', + catalogHash: 'c', + }) const INGEST_BASE = folderBase('ws_local') function answer(overrides: Record = {}) { @@ -1028,7 +1034,7 @@ describe('workspaces source apply', () => { resources: { 'file:a.bin': { id: 'f1', - blobs: { 'files/a.bin': { id: 'f1', rev: 1, sha256: sha(Buffer.from([1, 2, 3])) } }, + blobs: { 'files/a.bin': { id: 'f1', rev: '1', sha256: sha(Buffer.from([1, 2, 3])) } }, }, }, }) @@ -1070,7 +1076,7 @@ describe('workspaces source apply', () => { resources: { 'file:a.bin': { id: 'f1', - blobs: { 'files/a.bin': { id: 'f1', rev: 1, sha256: sha(Buffer.from([1, 2, 3])) } }, + blobs: { 'files/a.bin': { id: 'f1', rev: '1', sha256: sha(Buffer.from([1, 2, 3])) } }, }, }, }) @@ -1333,10 +1339,10 @@ describe('workspaces source apply', () => { JSON.stringify({ ...BASE, resources: { - 'file:a.bin': { id: 'f1', blobs: { 'files/a.bin': { id: 'f1', rev: 1, sha256 } } }, + 'file:a.bin': { id: 'f1', blobs: { 'files/a.bin': { id: 'f1', rev: '1', sha256 } } }, 'knowledge-base:docs': { id: 'kb1', - blobs: { 'guide.pdf': { id: 'd1', rev: 1, sha256 } }, + blobs: { 'guide.pdf': { id: 'd1', rev: '1', sha256 } }, }, }, }) @@ -1369,8 +1375,8 @@ describe('workspaces source apply', () => { JSON.stringify({ ...BASE, resources: { - 'file:a.txt': { id: 'f1', blobs: { 'files/a.txt': { id: 'f1', rev: 1, sha256 } } }, - 'file:b.txt': { id: 'f2', blobs: { 'files/b.txt': { id: 'f2', rev: 1, sha256 } } }, + 'file:a.txt': { id: 'f1', blobs: { 'files/a.txt': { id: 'f1', rev: '1', sha256 } } }, + 'file:b.txt': { id: 'f2', blobs: { 'files/b.txt': { id: 'f2', rev: '1', sha256 } } }, }, }) ) @@ -1405,6 +1411,7 @@ describe('workspaces source apply', () => { request.mockResolvedValue( answer({ dryRun: true, + refuses: true, diagnostics: [ { code: 'E_APPLY_STALE', @@ -1504,6 +1511,7 @@ describe('workspaces source apply', () => { request.mockResolvedValue( answer({ dryRun: true, + refuses: true, diagnostics: codes.map((code) => ({ code, severity: 'error', message: code })), }) ) @@ -1513,6 +1521,20 @@ describe('workspaces source apply', () => { expect(process.exitCode).toBe(exitCode) }) + it("takes a dry run's refusal from the server's answer alone, never from its findings", async () => { + request.mockResolvedValue( + answer({ + dryRun: true, + plan: [{ kind: 'table', key: 'leads', action: 'create', held: true }], + diagnostics: [{ code: 'E_APPLY_LOCKED', severity: 'error', message: 'locked' }], + }) + ) + + await apply('--dry-run') + + expect(process.exitCode).toBe(1) + }) + it('refuses a local blob over the size limit before reading it, and exits 7', async () => { write('files/huge.bin', '') truncateSync(join(dir, 'files/huge.bin'), WORKSPACE_SOURCE_LIMITS.maxBlobBytes + 1) @@ -1919,41 +1941,6 @@ describe('workspaces source apply', () => { expect(process.exitCode).toBe(1) }) - it('exits a dry run as refused when a delete breaks a workflow it holds back, for a server without refuses, as the apply refuses it', async () => { - // E_PLAN_REF_DELETED names the held workflow, but the server records it on the delete (or the - // plan), which no hold excuses: the apply would refuse, so the dry run cannot exit 15. - request.mockResolvedValue( - answer({ - dryRun: true, - plan: [ - { kind: 'table', key: 'leads', action: 'create' }, - { kind: 'workflow', key: 'parent', action: 'update', held: true }, - { kind: 'workflow', key: 'child', action: 'delete' }, - ], - diagnostics: [ - { - code: 'E_SECRET_MISSING', - severity: 'error', - message: 'workflows/parent is held back: it reads the secret OPENAI_API_KEY.', - kind: 'workflow', - key: 'parent', - }, - { - code: 'E_PLAN_REF_DELETED', - severity: 'error', - message: 'workflows/parent uses workflow "child", which this apply deletes.', - kind: 'workflow', - key: 'parent', - }, - ], - }) - ) - - await apply('--dry-run', '--allow-delete') - - expect(process.exitCode).toBe(1) - }) - it('saves the applied answer when the catalog of a workflow it reprinted cannot be fetched, and says its edges are unrecorded', async () => { const configDir = mkdtempSync(join(tmpdir(), 'sim-workspace-apply-config-')) vi.stubEnv('SIM_CONFIG_DIR', configDir) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index c908eac98f8..7a3fcbfa9cb 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -130,30 +130,9 @@ function failedExitCode(failed: NonNullable): number { : refusedExitCode([{ code: failed.code, severity: 'error' }]) } -/** - * Whether `finding` is about a change the plan holds back, which refuses nothing else: one naming - * that change. For a server that predates `refuses` only; `E_PLAN_REF_DELETED` names the workflow - * that uses what a delete removes but sits on the delete or the plan, so no hold excuses it. - */ -function isHeldFinding( - plan: readonly Change[], - finding: ApplyData['diagnostics'][number] -): boolean { - return ( - finding.code !== 'E_PLAN_REF_DELETED' && - plan.some((change) => change.held && change.kind === finding.kind && change.key === finding.key) - ) -} - -/** - * Whether a dry run's errors refuse the apply: the server's answer (`refuses`), or for a server - * that predates it, any error but those of changes held back. - */ +/** Whether a dry run's errors refuse the apply, as the server answers (`refuses`). */ function refusesApply(data: ApplyData): boolean { - if (data.refuses !== undefined) return data.refuses - return data.diagnostics.some( - (finding) => finding.severity === 'error' && !isHeldFinding(data.plan, finding) - ) + return data.refuses === true } /** diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts index a63e7fbb08d..bb42350a716 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts @@ -131,6 +131,7 @@ describe('workspaces source get', () => { it('refuses a workflow source directory, --force included, keeping its base and unapplied edits', async () => { const base = JSON.stringify({ + version: 1, workflowId: 'wf-1', workspaceId: 'ws_local', fingerprint: 'sf1:x', @@ -186,7 +187,7 @@ describe('workspaces source get', () => { expect(readFileSync(join(dir, 'AGENTS.md'), 'utf8')).toBe('# Our rules\n') }) - it('names the edit loop instead of printing the primer, which --primer prints', async () => { + it('names the edit loop instead of printing the primer', async () => { serve({ 'tables/leads.ts': LEADS }) await get() @@ -194,12 +195,6 @@ describe('workspaces source get', () => { const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') expect(printed).not.toHaveProperty('primer') expect(printed.editLoop[0]).toMatch(/^sim workspaces source check --dir /) - - vi.mocked(console.log).mockClear() - await get('--primer') - - const { primer } = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') - expect(readFileSync(join(dir, '.sim/AGENTS.md'), 'utf8').startsWith(primer)).toBe(true) }) it('writes the workspace primer atop the guide, and the deep dives to the advanced guide it names', async () => { @@ -295,7 +290,7 @@ describe('workspaces source get', () => { const fileResource = { 'file:report.bin': { id: 'file_1', - blobs: { 'files/report.bin': { id: 'file_1', rev: 1, sha256: listed().sha256 } }, + blobs: { 'files/report.bin': { id: 'file_1', rev: '1', sha256: listed().sha256 } }, }, } @@ -725,6 +720,7 @@ describe('workspaces source get', () => { workflows: [], skills: [{ key: 'stored', id: 'skill-1', name: 'stored' }], customTools: [], + mcpServers: [], env: [], truncated: false, }, @@ -774,6 +770,7 @@ describe('workspaces source get', () => { workflows: [{ key: 'enrich', inputs: [{ name: 'email', type: 'string' }] }], skills: [], customTools: [], + mcpServers: [], env: [], truncated: false, }, @@ -827,6 +824,7 @@ describe('workspaces source get', () => { workflows: [{ key: 'enrich', inputs: [{ name: 'email', type: 'string' }] }], skills: [], customTools: [], + mcpServers: [], env: [], truncated: false, }, diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts index 601ee73deb8..131280d32bb 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts @@ -37,7 +37,6 @@ import { finishTree, loadCatalog, loadWorkspaceTypes, - primerOption, printTreeResult, sourceTreeChange, withSourceExitCode, @@ -335,7 +334,6 @@ export function attachWorkspaceSourceGet(source: Command): void { 'downloadKnowledgeDocument', ]) absoluteDirOption(command) - primerOption(command) searchTasks(command, [ 'change the model in every agent block', 'bulk edit every workflow in the workspace', @@ -348,7 +346,7 @@ export function attachWorkspaceSourceGet(source: Command): void { .allowExcessArguments(false) .description('Write a workspace as a source directory') .addHelpText('after', GET_HELP) - .action(async (options: { dir: string; only?: string; force?: boolean; primer?: boolean }) => { + .action(async (options: { dir: string; only?: string; force?: boolean }) => { const kinds = parseKinds(options.only) const { client, profile } = connect() await withSourceDirLock(options.dir, async () => { @@ -392,7 +390,6 @@ export function attachWorkspaceSourceGet(source: Command): void { skipped: data.skipped.length, guide: result.guide, editLoop: editLoop('workspace', options.dir), - ...(options.primer === true ? { primer: result.primer } : {}), ...findings.result(data.diagnostics), }) }) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts index 1bbc4ac767a..9c55fac2a0b 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.test.ts @@ -26,7 +26,7 @@ const BASE = { version: 1, workspaceId: WORKSPACE_ID, resources: {} } const LEADS = "// @sim-sdk 1\nexport default defineTable({ name: 'leads', columns: {} })\n" const DEALS = "// @sim-sdk 1\nexport default defineTable({ name: 'deals', columns: {} })\n" const INGEST = "// @sim-sdk 1\nexport default workflow('Ingest', {}, () => {})\n" -const INGEST_BASE = `${JSON.stringify({ workflowId: 'wf_1', workspaceId: WORKSPACE_ID, fingerprint: 'sf1:a', catalogHash: 'c' })}\n` +const INGEST_BASE = `${JSON.stringify({ version: 1, workflowId: 'wf_1', workspaceId: WORKSPACE_ID, fingerprint: 'sf1:a', catalogHash: 'c' })}\n` const NOTES = Buffer.from('binary notes, version one') /** The files a get wrote, by path: what `.sim/written.json` records. */ diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts index a6ba3335c22..c6868cde10f 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -61,7 +61,6 @@ import { planFindings, printDiffReport, printStatusReport, - readPlan, type ServerCheck, STATUS_EXIT_CODES_HELP, type StatusReport, @@ -401,20 +400,9 @@ export function attachWorkspaceSourceStatus(source: Command): void { options: { allowDelete: true, ...(only ? { only } : {}) }, } try { - const response = await readPlan( - () => - connection.client.request('planWorkspaceSource', { - params: { workspaceId: target }, - body, - retryRateLimited: true, - }), - () => - connection.client.request('applyWorkspaceSource', { - params: { workspaceId: target }, - query: { dryRun: true }, - body: { ...body, provenance: { client: 'cli' } }, - retryRateLimited: true, - }) + const response = await connection.client.request( + 'planWorkspaceSource', + { params: { workspaceId: target }, body, retryRateLimited: true } ) data = response.data byBase = workflowsSentByBase(local, target) diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 3f5750b0710..3bc9f3f8a53 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -760,7 +760,7 @@ export type ApplyWorkflowSourceBody = { [key: string]: unknown } base: { - version?: 1 + version: 1 workflowId: string workspaceId: string fingerprint: string @@ -825,7 +825,6 @@ export type ApplyWorkflowSourceResponse = { | 'E_SYNTAX' | 'E_SDK_HEADER' | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' | 'E_UNSUPPORTED_SYNTAX' | 'E_WORKFLOW_EXPORT' | 'E_LIMIT_EXCEEDED' @@ -1117,7 +1116,7 @@ export type ApplyWorkspaceSourceBody = { string, { id: string - rev: number | string + rev: string sha256: string } > @@ -1331,7 +1330,6 @@ export type ApplyWorkspaceSourceResponse = { | 'E_SYNTAX' | 'E_SDK_HEADER' | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' | 'E_UNSUPPORTED_SYNTAX' | 'E_WORKFLOW_EXPORT' | 'E_INVALID_CHARACTER' @@ -1508,7 +1506,7 @@ export type ApplyWorkspaceSourceResponse = { string, { id: string - rev: number | string + rev: string sha256: string } > @@ -1627,7 +1625,6 @@ export type ApplyWorkspaceSourceResponse = { | 'E_SYNTAX' | 'E_SDK_HEADER' | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' | 'E_UNSUPPORTED_SYNTAX' | 'E_WORKFLOW_EXPORT' | 'E_INVALID_CHARACTER' @@ -5301,7 +5298,6 @@ export type CreateWorkflowFromSourceResponse = { | 'E_SYNTAX' | 'E_SDK_HEADER' | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' | 'E_UNSUPPORTED_SYNTAX' | 'E_WORKFLOW_EXPORT' | 'E_LIMIT_EXCEEDED' @@ -7161,6 +7157,14 @@ type ExecuteWorkflowResponseRef1 = { endedAt?: string durationMs?: number executionTimeoutSeconds: number | null + paused: { + runId: string + points: Array<{ + contextId: string + kind: 'human' | 'time' + status: 'paused' | 'queued' | 'resuming' | 'resumed' | 'failed' + }> + } | null } type ExecuteWorkflowResponseRef2 = { @@ -9218,6 +9222,7 @@ export type GetSourceCatalogResponse = { description?: string condition?: unknown hiddenFromDisplay?: boolean + mayBeText?: true properties?: Record sharedProperties?: number items?: unknown @@ -9448,6 +9453,7 @@ export type GetSourceCatalogResponse = { description?: string condition?: unknown hiddenFromDisplay?: boolean + mayBeText?: true properties?: Record sharedProperties?: number items?: unknown @@ -9631,6 +9637,7 @@ export type GetSourceCatalogResponse = { description?: string condition?: unknown hiddenFromDisplay?: boolean + mayBeText?: true properties?: Record sharedProperties?: number items?: unknown @@ -10349,6 +10356,7 @@ type GetWorkflowRunResponseRef4 = { automaticResumeWaitingReason: string | null pausePointCount: number resumedCount: number + runId: string points: Array } | null cost: { @@ -10427,7 +10435,6 @@ export type GetWorkflowSourceResponse = { | 'E_SYNTAX' | 'E_SDK_HEADER' | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' | 'E_UNSUPPORTED_SYNTAX' | 'E_WORKFLOW_EXPORT' | 'E_LIMIT_EXCEEDED' @@ -10992,7 +10999,7 @@ export type GetWorkspaceSourceResponse = { string, { id: string - rev: number | string + rev: string sha256: string } > @@ -11126,7 +11133,6 @@ export type GetWorkspaceSourceResponse = { | 'E_SYNTAX' | 'E_SDK_HEADER' | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' | 'E_UNSUPPORTED_SYNTAX' | 'E_WORKFLOW_EXPORT' | 'E_INVALID_CHARACTER' @@ -14396,7 +14402,7 @@ export type PlanWorkflowSourceBody = { [key: string]: unknown } base: { - version?: 1 + version: 1 workflowId: string workspaceId: string fingerprint: string @@ -14456,7 +14462,6 @@ export type PlanWorkflowSourceResponse = { | 'E_SYNTAX' | 'E_SDK_HEADER' | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' | 'E_UNSUPPORTED_SYNTAX' | 'E_WORKFLOW_EXPORT' | 'E_LIMIT_EXCEEDED' @@ -14708,7 +14713,7 @@ export type PlanWorkspaceSourceBody = { string, { id: string - rev: number | string + rev: string sha256: string } > @@ -14917,7 +14922,6 @@ export type PlanWorkspaceSourceResponse = { | 'E_SYNTAX' | 'E_SDK_HEADER' | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' | 'E_UNSUPPORTED_SYNTAX' | 'E_WORKFLOW_EXPORT' | 'E_INVALID_CHARACTER' @@ -15094,7 +15098,7 @@ export type PlanWorkspaceSourceResponse = { string, { id: string - rev: number | string + rev: string sha256: string } > @@ -15213,7 +15217,6 @@ export type PlanWorkspaceSourceResponse = { | 'E_SYNTAX' | 'E_SDK_HEADER' | 'E_SDK_MAJOR' - | 'E_SDK_MAJOR_OLD' | 'E_UNSUPPORTED_SYNTAX' | 'E_WORKFLOW_EXPORT' | 'E_INVALID_CHARACTER' @@ -17798,6 +17801,14 @@ type ResumeWorkflowResponseRef1 = { startedAt?: string endedAt?: string durationMs?: number + paused: { + runId: string + points: Array<{ + contextId: string + kind: 'human' | 'time' + status: 'paused' | 'queued' | 'resuming' | 'resumed' | 'failed' + }> + } | null } type ResumeWorkflowResponseRef2 = { diff --git a/packages/sim-cli/src/runtime/paused-run.test.ts b/packages/sim-cli/src/runtime/paused-run.test.ts index e0383cabd81..c920d5db2bc 100644 --- a/packages/sim-cli/src/runtime/paused-run.test.ts +++ b/packages/sim-cli/src/runtime/paused-run.test.ts @@ -1,91 +1,66 @@ import { describe, expect, it } from 'vitest' import { withResumeNext } from './paused-run' +const point = (contextId: string, status = 'paused') => ({ contextId, kind: 'human', status }) + const paused = { - runId: 'run_top', + runId: 'run_attempt', workflowId: 'wf_1', status: 'paused', - output: { data: { _resume: { contextId: 'ctx_9', executionId: 'exec_9' } } }, + output: { data: { _resume: { contextId: 'decoy', executionId: 'decoy_run' } } }, + paused: { runId: 'run_top', points: [point('ctx_9')] }, } describe('withResumeNext', () => { - it('names the exact resume command, with the pause context and the execution its links name', () => { + it('names the run the server says the pause is recorded under, not the record run id', () => { expect(withResumeNext('executeWorkflow', paused)).toEqual({ ...paused, - next: 'sim workflows runs resume exec_9 --workflow wf_1 --context ctx_9', - }) - }) - - it('falls back to the run id, and to the paused record context, when the output names none', () => { - expect(withResumeNext('executeWorkflow', { ...paused, output: null })).toMatchObject({ - next: 'sim workflows runs resume run_top --workflow wf_1', + next: 'sim workflows runs resume run_top --workflow wf_1 --context ctx_9', }) - expect( - withResumeNext('getWorkflowRun', { ...paused, output: undefined, paused: { contextId: 'c' } }) - ).toMatchObject({ next: 'sim workflows runs resume run_top --workflow wf_1 --context c' }) }) - it('leaves a run that is not paused, another operation and an existing next as they were', () => { - const done = { ...paused, status: 'completed' } - expect(withResumeNext('executeWorkflow', done)).toBe(done) - expect(withResumeNext('listWorkflowRuns', paused)).toBe(paused) - const hinted = { ...paused, next: 'x' } - expect(withResumeNext('executeWorkflow', hinted)).toBe(hinted) - expect(withResumeNext('executeWorkflow', null)).toBeNull() - }) - - it('reads only the links the server writes, never a record that data or an API response carries', () => { - const decoy = { contextId: 'x; rm -rf ~', executionId: 'y' } + it('reads the paused field of a run resource, naming only the points still waiting', () => { const run = { ...paused, - output: { - data: { - rows: [decoy], - body: { contextId: 'evil', executionId: 'evil_run' }, - _resume: paused.output.data._resume, - }, - }, - } - expect(withResumeNext('executeWorkflow', run)).toMatchObject({ - next: 'sim workflows runs resume exec_9 --workflow wf_1 --context ctx_9', - }) - expect( - withResumeNext('executeWorkflow', { - ...paused, - output: { data: { rows: [{ contextId: 'evil', executionId: 'evil_run' }] } }, - }) - ).toMatchObject({ next: 'sim workflows runs resume run_top --workflow wf_1' }) - }) - - it('never prints an id outside the format the server issues', () => { - const hostile = { - ...paused, - output: { data: { _resume: { contextId: 'x; rm -rf ~', executionId: '$(id)' } } }, + output: undefined, + paused: { contextId: 'b', runId: 'run_top', points: [point('a', 'resumed'), point('b')] }, } - expect(withResumeNext('executeWorkflow', hostile)).toMatchObject({ - next: 'sim workflows runs resume run_top --workflow wf_1', + expect(withResumeNext('getWorkflowRun', run)).toMatchObject({ + next: 'sim workflows runs resume run_top --workflow wf_1 --context b', }) - expect( - withResumeNext('executeWorkflow', { ...paused, workflowId: 'wf; id' }) - ).not.toHaveProperty('next') }) - it('names one command per pause when several blocks pause together', () => { + it('names one command per waiting point, quoting a branch context', () => { const several = { ...paused, - output: { - pausedBlocks: [ - { data: { _resume: { contextId: 'a\u208D0\u208E', executionId: 'exec_9' } } }, - { data: { _resume: { contextId: 'b', executionId: 'exec_9' } } }, - ], - pauseCount: 2, - }, + paused: { runId: 'run_top', points: [point('a₍0₎'), point('b')] }, } expect(withResumeNext('executeWorkflow', several)).toMatchObject({ next: [ - "sim workflows runs resume exec_9 --workflow wf_1 --context 'a\u208D0\u208E'", - 'sim workflows runs resume exec_9 --workflow wf_1 --context b', + "sim workflows runs resume run_top --workflow wf_1 --context 'a₍0₎'", + 'sim workflows runs resume run_top --workflow wf_1 --context b', ].join('\n'), }) }) + + it('leaves a run that is not paused, another operation, an existing next and no paused field as they were', () => { + const done = { ...paused, status: 'completed' } + expect(withResumeNext('executeWorkflow', done)).toBe(done) + expect(withResumeNext('listWorkflowRuns', paused)).toBe(paused) + const hinted = { ...paused, next: 'x' } + expect(withResumeNext('executeWorkflow', hinted)).toBe(hinted) + expect(withResumeNext('executeWorkflow', null)).toBeNull() + const unnamed = { ...paused, paused: null } + expect(withResumeNext('executeWorkflow', unnamed)).toBe(unnamed) + }) + + it('never prints an id outside the format the server issues', () => { + for (const hostile of [ + { ...paused, paused: { runId: '$(id)', points: [point('ctx_9')] } }, + { ...paused, paused: { runId: 'run_top', points: [point('x; rm -rf ~')] } }, + { ...paused, workflowId: 'wf; id' }, + ]) { + expect(withResumeNext('executeWorkflow', hostile)).not.toHaveProperty('next') + } + }) }) diff --git a/packages/sim-cli/src/runtime/paused-run.ts b/packages/sim-cli/src/runtime/paused-run.ts index 60ab934dad7..a09387646cc 100644 --- a/packages/sim-cli/src/runtime/paused-run.ts +++ b/packages/sim-cli/src/runtime/paused-run.ts @@ -4,11 +4,6 @@ import type { V2OperationName } from '../generated/v2-api' /** Operations whose payload is a run record that may be paused. */ const RUN_OPERATIONS: ReadonlySet = new Set(['executeWorkflow', 'getWorkflowRun']) -interface ResumeLinks { - contextId: string - executionId: string -} - /** What the server issues for an id: letters, digits and `_ . : -` plus the `₍ ₎` of a branch id. */ const ISSUED_ID = /^[\p{L}\p{N}_.:\u208D\u208E-]{1,256}$/u @@ -16,69 +11,39 @@ function issuedId(value: unknown): value is string { return typeof value === 'string' && ISSUED_ID.test(value) } -function readLinks(value: unknown): ResumeLinks | null { - if (!isRecordLike(value)) return null - const { contextId, executionId } = value - return issuedId(contextId) && issuedId(executionId) ? { contextId, executionId } : null -} - -/** - * The resume links of every pause in a run's output: `resume` beside a pause response, or - * `_resume` inside its `data`; the response is the output itself (or its `response`) for one - * pause, and each entry of `pausedBlocks` when several blocks pause together. Only those fixed - * places are read, never data a block or an API response carries, and a link whose ids are not - * in the format the server issues is skipped. - */ -function findResumeLinks(output: unknown): ResumeLinks[] { - if (!isRecordLike(output)) return [] - const found = new Map() - for (const root of [output, output.response]) { - if (!isRecordLike(root)) continue - const responses = Array.isArray(root.pausedBlocks) ? root.pausedBlocks : [root] - for (const response of responses) { - if (!isRecordLike(response)) continue - const links = readLinks(response.resume) ?? readLinks(toRecordOrNull(response.data)?._resume) - if (links) found.set(`${links.executionId}\n${links.contextId}`, links) - } - } - return [...found.values()] -} - const SAFE_ARGUMENT = /^[A-Za-z0-9_.:-]+$/ function shellArgument(value: string): string { return SAFE_ARGUMENT.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'` } -/** The command that resumes a paused run, with the pause's context when it is known. */ -function resumeCommand(runId: string, workflowId: string, contextId: string | null): string { - const context = contextId ? ` --context ${shellArgument(contextId)}` : '' - return `sim workflows runs resume ${shellArgument(runId)} --workflow ${shellArgument(workflowId)}${context}` +/** The command that resumes one pause of a paused run. */ +function resumeCommand(runId: string, workflowId: string, contextId: string): string { + return `sim workflows runs resume ${shellArgument(runId)} --workflow ${shellArgument(workflowId)} --context ${shellArgument(contextId)}` } /** - * The exact `runs resume` command for a paused run record, one line per waiting pause, since the - * record carries two ids (`runId` and the output's `_resume.executionId`) and a context a reader - * would otherwise have to pair up. `runs resume` takes the run the pause belongs to, which is the - * links' `executionId`. A record whose output names no links falls back to its own ids and the - * `paused.contextId`; null when an id is not in the format the server issues, so no untrusted - * text reaches a printed command. `fallback` supplies the ids a record omits. + * The exact `runs resume` command for a paused run record, one line per point still waiting. The + * server names the run to resume in `paused.runId` (for a resumed run that paused again, the run + * it resumed, not the record's own `runId`) and each point's `contextId`. Null when nothing waits + * or an id is not in the format the server issues, so no untrusted text reaches a printed + * command. `workflowId` is used when the record omits its own. */ export function resumeCommandFor( record: Record, - fallback: { runId: string; workflowId: string } + fallback: { workflowId: string } ): string | null { - const runId = typeof record.runId === 'string' ? record.runId : fallback.runId const workflowId = typeof record.workflowId === 'string' ? record.workflowId : fallback.workflowId + const paused = toRecordOrNull(record.paused) + const runId = paused?.runId if (!issuedId(runId) || !issuedId(workflowId)) return null - const links = findResumeLinks(record.output) - if (links.length > 0) { - return links - .map((link) => resumeCommand(link.executionId, workflowId, link.contextId)) - .join('\n') + const commands: string[] = [] + for (const point of Array.isArray(paused?.points) ? paused.points : []) { + if (!isRecordLike(point) || point.status !== 'paused') continue + if (!issuedId(point.contextId)) return null + commands.push(resumeCommand(runId, workflowId, point.contextId)) } - const contextId = toRecordOrNull(record.paused)?.contextId - return resumeCommand(runId, workflowId, issuedId(contextId) ? contextId : null) + return commands.length > 0 ? commands.join('\n') : null } /** @@ -88,7 +53,7 @@ export function resumeCommandFor( export function withResumeNext(operation: V2OperationName, payload: unknown): unknown { if (!RUN_OPERATIONS.has(operation) || !isRecordLike(payload)) return payload if (payload.status !== 'paused' || 'next' in payload) return payload - if (typeof payload.runId !== 'string' || typeof payload.workflowId !== 'string') return payload - const next = resumeCommandFor(payload, { runId: payload.runId, workflowId: payload.workflowId }) + if (typeof payload.workflowId !== 'string') return payload + const next = resumeCommandFor(payload, { workflowId: payload.workflowId }) return next ? { ...payload, next } : payload } diff --git a/packages/workflow-code/src/catalog/types.ts b/packages/workflow-code/src/catalog/types.ts index 9dee644ba90..e103e034d7c 100644 --- a/packages/workflow-code/src/catalog/types.ts +++ b/packages/workflow-code/src/catalog/types.ts @@ -200,6 +200,8 @@ export interface CatalogOutput { description?: string condition?: OutputCondition hiddenFromDisplay?: boolean + /** A `json` or `any` output whose value can still be text at run time. */ + mayBeText?: true properties?: Record items?: CatalogOutput } diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index d7f91f6512e..1f1f16353e8 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -30,8 +30,7 @@ export default workflow('Name', { description: '…', variables: { … } }, ({ v }) ``` -- Line 1 is `// @sim-sdk N`. Missing: `E_SDK_HEADER`. `N` above the server's major: `E_SDK_MAJOR`. - `N` below `OLDEST_SDK_MAJOR` (`sdk.ts`): `E_SDK_MAJOR_OLD`. +- Line 1 is `// @sim-sdk N`. Missing: `E_SDK_HEADER`. `N` other than the server's major: `E_SDK_MAJOR`. - Imports: named imports from `'@sim/workflow-sdk'` only (aliases allowed). Anything else is `E_UNSUPPORTED_SYNTAX`. - Exactly one `export default workflow(name, options?, body)` (`E_WORKFLOW_EXPORT`). `options` is @@ -384,8 +383,7 @@ Errors refuse the whole apply. Warnings are saved as written; info is informatio | `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_SDK_MAJOR` | The header's major is not the one 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. | diff --git a/packages/workflow-code/src/compile/ergonomics.test.ts b/packages/workflow-code/src/compile/ergonomics.test.ts index 0bceee7331f..c82d891effb 100644 --- a/packages/workflow-code/src/compile/ergonomics.test.ts +++ b/packages/workflow-code/src/compile/ergonomics.test.ts @@ -412,10 +412,10 @@ describe('a raw edge into a container child', () => { }) describe('header, names and hand-written references', () => { - it('refuses a header major below the oldest the server reads', () => { - expect(codes(run(source(" api('A', { url: 'x' })", '// @sim-sdk 0')))).toEqual([ - 'E_SDK_MAJOR_OLD', - ]) + it('refuses a header major other than the one the server reads', () => { + for (const header of ['// @sim-sdk 0', '// @sim-sdk 2']) { + expect(codes(run(source(" api('A', { url: 'x' })", header)))).toEqual(['E_SDK_MAJOR']) + } }) it('warns on an invisible bidi or zero-width character in a block name, and prints it escaped', () => { diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index 3850a53547f..91558307d64 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -27,7 +27,7 @@ import type { VarKey, } from '../model' import { getOwn, setOwn } from '../records' -import { OLDEST_SDK_MAJOR, SDK_MODULE } from '../sdk' +import { SDK_MODULE } from '../sdk' import { compileBlock } from './blocks' import { checkStorableLiterals, checkStorableText } from './characters' import { CommentCollector } from './comments' @@ -539,20 +539,16 @@ function compileEntry( hint: `Start the file with // @sim-sdk ${input.sdkMajor}.`, } ) - } else if (parsed.sdkMajor > input.sdkMajor) { + } else if (parsed.sdkMajor !== input.sdkMajor) { reporter.report( 'E_SDK_MAJOR', - `This file targets SDK ${parsed.sdkMajor}; this server supports up to ${input.sdkMajor}.`, - { file, start: 0, end: parsed.headerEnd }, - { hint: `Write // @sim-sdk ${input.sdkMajor}, or update Sim.` } - ) - } else if (parsed.sdkMajor < OLDEST_SDK_MAJOR) { - reporter.report( - 'E_SDK_MAJOR_OLD', - `This file targets SDK ${parsed.sdkMajor}; this server supports SDK ${OLDEST_SDK_MAJOR} to ${input.sdkMajor}.`, + `This file targets SDK ${parsed.sdkMajor}; this server reads SDK ${input.sdkMajor}.`, { file, start: 0, end: parsed.headerEnd }, { - hint: `Rewrite the file for SDK ${input.sdkMajor}: run sim workflows source get to print it again.`, + hint: + parsed.sdkMajor > input.sdkMajor + ? `Write // @sim-sdk ${input.sdkMajor}, or update Sim.` + : `Write // @sim-sdk ${input.sdkMajor}: run sim workflows source get to print the file again.`, } ) } diff --git a/packages/workflow-code/src/diagnostics/codes.ts b/packages/workflow-code/src/diagnostics/codes.ts index 3a6f30ac337..4a222f03af0 100644 --- a/packages/workflow-code/src/diagnostics/codes.ts +++ b/packages/workflow-code/src/diagnostics/codes.ts @@ -22,10 +22,8 @@ const COMPILE_SYNTAX_CODES = [ 'E_SYNTAX', /** The first line is not `// @sim-sdk N`. */ 'E_SDK_HEADER', - /** The header's major is above the server's supported major. */ + /** The header's major is not the one the server reads. */ 'E_SDK_MAJOR', - /** The header's major is below the oldest major the server reads (`OLDEST_SDK_MAJOR`). */ - 'E_SDK_MAJOR_OLD', /** A construct outside the accepted grammar; `hint` names the supported form. */ 'E_UNSUPPORTED_SYNTAX', /** Not exactly one `export default workflow(...)`. */ diff --git a/packages/workflow-code/src/json-fields.ts b/packages/workflow-code/src/json-fields.ts index 6b6513d04aa..dd7f704d51f 100644 --- a/packages/workflow-code/src/json-fields.ts +++ b/packages/workflow-code/src/json-fields.ts @@ -62,32 +62,6 @@ export interface RefTypeScope { const STRING_VARIABLE_TYPES: ReadonlySet = new Set(['string', 'plain']) -/** - * Outputs the catalog types `json` whose value can still be text: a Function returns whatever its - * code does, and an HTTP response is parsed only when it says it is JSON. A reference to the whole - * of one is `untyped` unless the Function's code says what it returns. A path inside one is - * never declared, so it is `untyped` already. - */ -const TEXT_CAPABLE_OUTPUTS: ReadonlyMap = new Map([ - ['function', 'result'], - ['api', 'data'], -]) - -/** Whether the declared output `segments` of a `blockType` block may hold text at run time. */ -function mayHoldText( - blockType: string, - declared: CatalogOutput, - segments: readonly RefSegment[] -): boolean { - if (declared.type === 'any') return true - const [first] = segments - return ( - segments.length === 1 && - first?.kind === 'name' && - TEXT_CAPABLE_OUTPUTS.get(blockType) === first.name - ) -} - function outputAt( outputs: Record, segments: RefSegment[] @@ -207,8 +181,8 @@ export function responseFormatFields(param: CanonicalParam | undefined): string[ * declares it (a path into untyped JSON, a loop item, an unknown block). An environment variable * is a string; a variable goes by its type; a block output by its declared output type, else by * the field its dynamic outputs declare, or for a Function's `result` by what its JavaScript - * certainly returns there. An output that can hold text though the catalog types it `json` or - * `any` (a Function's `result`, an HTTP `data`) is `untyped` unless the code says otherwise. + * certainly returns there. An `any` output, or one the catalog marks `mayBeText` (a Function's + * `result`, an HTTP `data`), is `untyped` unless the code says otherwise. */ export function refValueKind(token: string, scope: RefTypeScope): RefValueKind { if (token.startsWith('{{')) return 'string' @@ -247,7 +221,7 @@ export function refValueKind(token: string, scope: RefTypeScope): RefValueKind { if (returned) return returned if (found) { if (found.type === 'string') return 'string' - return mayHoldText(block.type, found, segments) ? 'untyped' : 'typed' + return found.type === 'any' || found.mayBeText ? 'untyped' : 'typed' } if (declared.dynamicOutputs) { const { source, param } = declared.dynamicOutputs diff --git a/packages/workflow-code/src/lock.test.ts b/packages/workflow-code/src/lock.test.ts index 51b4241f3a1..4c8eba57f18 100644 --- a/packages/workflow-code/src/lock.test.ts +++ b/packages/workflow-code/src/lock.test.ts @@ -260,21 +260,30 @@ describe('parseWorkflowLock', () => { }) describe('parseSourceBase', () => { - const base = { workflowId: 'wf-1', workspaceId: 'ws-1', fingerprint: 'sf1:a', catalogHash: 'c' } + const base = { + version: 1, + workflowId: 'wf-1', + workspaceId: 'ws-1', + fingerprint: 'sf1:a', + catalogHash: 'c', + } - it('reads a base written before it carried a version as version 1', () => { - expect(parseSourceBase(JSON.stringify(base))).toEqual({ base: { version: 1, ...base } }) + it('reads a version 1 base', () => { + expect(parseSourceBase(JSON.stringify(base))).toEqual({ base }) }) - it('refuses a version this build cannot read', () => { - expect(parseSourceBase({ ...base, version: 2 })).toEqual({ - problem: 'Unsupported base version; expected 1.', - }) + it('refuses a base with no version or a version this build cannot read', () => { + const { version: _, ...unversioned } = base + for (const input of [unversioned, { ...base, version: 2 }]) { + expect(parseSourceBase(input)).toEqual({ + problem: 'Unsupported base version; expected 1.', + }) + } }) it('keeps an x- extension and refuses any other unknown field', () => { expect(parseSourceBase({ ...base, 'x-tool': { pinned: true } })).toEqual({ - base: { version: 1, ...base, 'x-tool': { pinned: true } }, + base: { ...base, 'x-tool': { pinned: true } }, }) expect(parseSourceBase({ ...base, branch: 'main' })).toEqual({ problem: 'Unknown base field "branch".', @@ -282,7 +291,7 @@ describe('parseSourceBase', () => { }) it('names every missing or malformed field at once', () => { - expect(parseSourceBase({ workspaceId: 1, fingerprint: 'x'.repeat(257) })).toEqual({ + expect(parseSourceBase({ version: 1, workspaceId: 1, fingerprint: 'x'.repeat(257) })).toEqual({ problem: '"workflowId" must be a non-empty string. "workspaceId" must be a string. "fingerprint" must be a non-empty string of at most 256 characters. "catalogHash" must be a string.', }) diff --git a/packages/workflow-code/src/lock.ts b/packages/workflow-code/src/lock.ts index 5b868ccad0d..8747b22369e 100644 --- a/packages/workflow-code/src/lock.ts +++ b/packages/workflow-code/src/lock.ts @@ -11,9 +11,7 @@ * Version policy: adding an optional field does not bump `version`. Validators learn a field * before writers emit it; until every reader knows a field, data goes under an `x-` key, which * every validator tolerates and preserves. Removing or changing the meaning of a field bumps it, - * and the new format adds its step to {@link upgradeWorkflowLock} or {@link upgradeSourceBase}: - * every reader goes through them, so a file written in any version this build reads parses as - * the current one. + * and a reader refuses any version but its own. */ import { isRecordLike } from '@sim/utils/object' @@ -29,7 +27,7 @@ import { SDK_RESERVED_IDENTIFIERS } from './sdk' /** * `sf1:` + lowercase hex SHA-256 (`sourceFingerprint`). Checkouts in the field hold it in their * base, so a change to canonicalize's output or to the hashing is a format change: it bumps the - * prefix (`sf2:`) and accepts the old one for a release. `equivalence/pinned.test.ts` pins it. + * prefix (`sf2:`), and a checkout read before it re-runs get. `equivalence/pinned.test.ts` pins it. */ export type SourceFingerprint = `sf1:${string}` @@ -111,7 +109,7 @@ export type WorkflowLockV1 = { /** One environment's freshness facts for a lock, `.sim/base.json` (see the module comment). */ export type SourceBase = { [extension: LockExtensionKey]: Json - /** Base format version; a base written before it existed reads as 1. */ + /** Base format version. */ version: 1 /** The workflow the source was read from; apply refuses a base read from another workflow. */ workflowId: string @@ -540,35 +538,14 @@ function blocksOnParentCycles(blocks: Record): Set< } /** - * A lock object of any version this build reads, as the current version (1) holds it, or `null` - * for a version it cannot read. The one seam a lock format change goes through: v1 is current, - * so it passes through unchanged. - */ -function upgradeWorkflowLock( - json: Record -): (Record & { version: 1 }) | null { - return json.version === 1 ? { ...json, version: 1 } : null -} - -/** - * A base object of any version this build reads, as the current version (1) holds it, or `null` - * for a version it cannot read. A base written before `version` existed is version 1. - */ -function upgradeSourceBase( - json: Record -): (Record & { version: 1 }) | null { - return json.version === undefined || json.version === 1 ? { ...json, version: 1 } : null -} - -/** - * Validates a source base (`.sim/base.json`), given as parsed JSON or as JSON text, through - * {@link upgradeSourceBase}. Unknown fields are refused except `x-` extensions, which are kept. + * Validates a source base (`.sim/base.json`), given as parsed JSON or as JSON text. Only version 1 + * is read. Unknown fields are refused except `x-` extensions, which are kept. */ export function parseSourceBase(input: unknown): { base: SourceBase } | { problem: string } { const parsed = jsonInput(input) if (!parsed || !isRecordLike(parsed.json)) return { problem: 'The base is not a JSON object.' } - const json = upgradeSourceBase(parsed.json) - if (!json) return { problem: 'Unsupported base version; expected 1.' } + const json = parsed.json + if (json.version !== 1) return { problem: 'Unsupported base version; expected 1.' } const problems: string[] = [] const extensions = readExtensions(json, BASE_FIELDS, (field, problem) => problems.push( @@ -607,7 +584,7 @@ export function parseSourceBase(input: unknown): { base: SourceBase } | { proble } /** - * Validates a lock, given as parsed JSON or as JSON text, through {@link upgradeWorkflowLock}. + * Validates a lock, given as parsed JSON or as JSON text; only version 1 is read. * Every problem is reported at once, each with an RFC 6901 `path`; a lock with any problem is * rejected whole. Unknown fields are errors, so a typo never silently drops identity, except `x-` * extension fields, which are preserved. A version this build cannot read stops validation there. @@ -623,8 +600,8 @@ export function parseWorkflowLock(input: unknown): ParseWorkflowLockResult { reader.report('E_LOCK_SHAPE', [], 'The lock must be a JSON object.') return { diagnostics: reader.diagnostics } } - const json = upgradeWorkflowLock(parsed.json) - if (!json) { + const json = parsed.json + if (json.version !== 1) { reader.report('E_LOCK_VERSION', ['version'], 'Unsupported lock version; expected 1.') return { diagnostics: reader.diagnostics } } diff --git a/packages/workflow-code/src/sdk.ts b/packages/workflow-code/src/sdk.ts index 08b084cadb5..41258878f63 100644 --- a/packages/workflow-code/src/sdk.ts +++ b/packages/workflow-code/src/sdk.ts @@ -87,12 +87,6 @@ export const SDK_RESOURCE_CALLS = { 'file-folder': 'folder', } as const satisfies Partial> -/** - * The oldest SDK major the compiler reads. A header below it is `E_SDK_MAJOR_OLD`: no - * down-migration exists, so such a file must be printed again for a supported major. - */ -export const OLDEST_SDK_MAJOR = 1 - /** How the SDK treats one core export. An export with no traits is a value constructor or const. */ interface SdkCoreExportTraits { /** diff --git a/packages/workflow-sdk/test/fixtures/catalog.json b/packages/workflow-sdk/test/fixtures/catalog.json index 41ea99a8943..b91ab6aa8f8 100644 --- a/packages/workflow-sdk/test/fixtures/catalog.json +++ b/packages/workflow-sdk/test/fixtures/catalog.json @@ -6805,7 +6805,8 @@ "outputs": { "data": { "type": "json", - "description": "API response data (JSON, text, or other formats)" + "description": "API response data (JSON, text, or other formats)", + "mayBeText": true }, "status": { "type": "number", @@ -6972,7 +6973,8 @@ "outputs": { "result": { "type": "json", - "description": "Structured result emitted by the executed code" + "description": "Structured result emitted by the executed code", + "mayBeText": true }, "stdout": { "type": "string", diff --git a/packages/workflow-types/src/blocks.ts b/packages/workflow-types/src/blocks.ts index 25dc8f56c6f..32fbe39d20d 100644 --- a/packages/workflow-types/src/blocks.ts +++ b/packages/workflow-types/src/blocks.ts @@ -84,6 +84,12 @@ export type OutputFieldDefinition = description?: string condition?: OutputCondition hiddenFromDisplay?: boolean + /** + * A `json` or `any` output whose value can still be text at run time (a Function's `result` + * is whatever its code returns; an HTTP body is parsed only when it says it is JSON). + * Workflow source stores a bare reference to it in JSON text as untyped. + */ + mayBeText?: boolean } export function isHiddenFromDisplay(def: unknown): boolean { diff --git a/packages/workspace-code/DESIGN.md b/packages/workspace-code/DESIGN.md index 6ab1a06c3a9..cfd68ec347b 100644 --- a/packages/workspace-code/DESIGN.md +++ b/packages/workspace-code/DESIGN.md @@ -116,7 +116,7 @@ skill's `content` are handled by hand. A fixture in the kind's test must set eve **Changing canonical output breaks every checkout.** Any change to a kind's `canonical()` (or to `@sim/workflow-code` canonicalize, for workflows) changes stored fingerprints, so every directory in the field reads as changed or stale after the deploy. Treat it as a format change: bump the -`rf`/`sf` prefix and accept the old one for a release, or ship it with a note to re-run get. +`rf`/`sf` prefix, and a directory read before the change re-runs get. ### The workflow kind @@ -396,8 +396,7 @@ unchanged. One workflow keeps its own `SOURCE_LIMITS` (`@sim/workflow-code/limit `.sim/base.json` carries `version: 1`. As with the workflow lock, adding an optional field does not bump the version: validators learn a field before writers emit it, and data waits under an `x-` key, -which the parser tolerates and preserves. Nothing upgrades an older version yet; a bump is a hard -refusal until a migration is written. +which the parser tolerates and preserves. A reader refuses any other version. ## SDK and CLI diff --git a/packages/workspace-code/src/base.test.ts b/packages/workspace-code/src/base.test.ts index 977e884459d..34da21003d9 100644 --- a/packages/workspace-code/src/base.test.ts +++ b/packages/workspace-code/src/base.test.ts @@ -80,7 +80,7 @@ describe('parseWorkspaceBase', () => { "__proto__": { "id": "col_evil", "options": { "__proto__": "opt_evil" } }, "email": { "id": "col_1" } }, - "blobs": { "__proto__": { "id": "b", "rev": 1, "sha256": "${'a'.repeat(64)}" } } + "blobs": { "__proto__": { "id": "b", "rev": "1", "sha256": "${'a'.repeat(64)}" } } } } }`) @@ -95,4 +95,20 @@ describe('parseWorkspaceBase', () => { ).toEqual(['__proto__']) expect(Object.keys(resource?.blobs ?? {})).toEqual(['__proto__']) }) + + it('refuses a blob whose rev is not a string', () => { + const parsed = parseWorkspaceBase({ + version: 1, + workspaceId: 'ws', + resources: { + 'file:a.png': { + id: 'f', + blobs: { 'files/a.png': { id: 'f', rev: 3, sha256: 'a'.repeat(64) } }, + }, + }, + }) + expect(parsed.diagnostics?.map((finding) => `${finding.code} ${finding.path}`)).toEqual([ + 'E_BASE_SHAPE /resources/file:a.png/blobs/files~1a.png', + ]) + }) }) diff --git a/packages/workspace-code/src/base.ts b/packages/workspace-code/src/base.ts index 66fd3ad5b9a..ac12185f54f 100644 --- a/packages/workspace-code/src/base.ts +++ b/packages/workspace-code/src/base.ts @@ -6,8 +6,8 @@ * base; the root only records each workflow's id. * * Version policy as the lock's: adding an optional field does not bump `version`, and unknown - * data goes under an `x-` key, which the parser tolerates and preserves. A format change adds its - * step to {@link upgradeWorkspaceBase}, which every read goes through. + * data goes under an `x-` key, which the parser tolerates and preserves. A format change bumps + * `version`, and the parser refuses any version but its own. */ import { isRecordLike } from '@sim/utils/object' import { @@ -143,18 +143,9 @@ function isStringRecord(value: unknown): value is Record { } /** - * A base object of any version this build reads, as the current version (1) holds it, or `null` - * for a version it cannot read. v1 is current, so it passes through unchanged. - */ -function upgradeWorkspaceBase( - json: Record -): (Record & { version: 1 }) | null { - return json.version === 1 ? { ...json, version: 1 } : null -} - -/** - * Validates a base (an object, or its JSON text), through {@link upgradeWorkspaceBase}. Unknown fields are refused unless they are `x-` - * extensions, which are kept; every problem is reported, each with its JSON Pointer in `path`. + * Validates a base (an object, or its JSON text); only version 1 is read. Unknown fields are + * refused unless they are `x-` extensions, which are kept; every problem is reported, each with + * its JSON Pointer in `path`. */ export function parseWorkspaceBase( input: unknown @@ -186,8 +177,8 @@ export function parseWorkspaceBase( shape('', 'The base must be an object.') return { diagnostics } } - const value = upgradeWorkspaceBase(parsed.json) - if (!value) { + const value = parsed.json + if (value.version !== 1) { return { diagnostics: [ diagnostic('E_BASE_VERSION', 'The base version must be 1.', { path: '/version' }), @@ -272,7 +263,7 @@ function parseResource( if ( !isRecordLike(blob) || !isNonEmptyString(blob.id) || - !(typeof rev === 'number' || isNonEmptyString(rev)) || + !isNonEmptyString(rev) || typeof blob.sha256 !== 'string' || !SHA256_HEX.test(blob.sha256) ) { @@ -282,7 +273,7 @@ function parseResource( blobs[name] = { ...extensionsOf(blob, BLOB_FIELDS, blobPath), id: blob.id, - rev: String(rev), + rev, sha256: blob.sha256, } } From d5ad786ac13a1ba5c3ec90cfdcbff70998c42fc0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 11:10:32 -0800 Subject: [PATCH 2/7] improvement(workflow-code): one pause shape for execute and resume, and simplify the clean-slate removals Execute and resume both return the run's pause through runPauseOf, the one rule for the run a pause is recorded under, and present it through one presenter. The primer rides only on the create scaffold, refusesApply is inlined, and the remaining unversioned base fixtures carry version 1. --- .../workflows/[workflowId]/execute/route.ts | 5 +---- .../[workflowId]/runs/[runId]/resume/route.ts | 4 +--- .../sim/hooks/queries/workflow-source.test.ts | 8 ++++++- apps/sim/lib/api/contracts/v2/workflows.ts | 4 ---- apps/sim/lib/workflows/api/run-pause.ts | 16 +++++++------- .../lib/workflows/executor/execute-service.ts | 9 ++++---- .../executor/human-in-the-loop-manager.ts | 9 +------- .../workflows/executor/resume-execution.ts | 19 +++++----------- apps/sim/lib/workflows/executor/run-pause.ts | 22 +++++++++++++++++++ .../src/commands/protocol/source-tree.ts | 9 +++----- .../src/commands/protocol/workflow-dir.ts | 4 ++-- .../protocol/workflow-run-get.test.ts | 7 +++++- .../commands/protocol/workflow-run-wait.ts | 2 +- .../commands/protocol/workflow-source-get.ts | 2 +- .../protocol/workspace-source-apply.ts | 9 ++------ .../commands/protocol/workspace-source-get.ts | 3 +-- packages/sim-cli/src/runtime/paused-run.ts | 7 +++--- packages/sim-cli/src/terminal.test.ts | 8 ++++++- .../src/compile/catalog.test-helpers.ts | 5 +++-- .../workspace-code/src/kinds/workflow.test.ts | 5 +++-- 20 files changed, 83 insertions(+), 74 deletions(-) create mode 100644 apps/sim/lib/workflows/executor/run-pause.ts diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts index a2f8723779c..e15e4e10e89 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts @@ -140,10 +140,7 @@ function presentRun(result: ExecuteWorkflowServiceRun) { executionTimeoutSeconds: executionTimeoutSeconds(result.executionTimeoutMs), output: result.output ?? null, blockOutputs: result.blockOutputs ?? null, - paused: - result.status === 'paused' - ? presentV2RunPause(result.executionId, result.pausePoints ?? []) - : null, + paused: presentV2RunPause(result.paused), } } diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts index 6f81489ce78..5608c1364ee 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts @@ -118,9 +118,7 @@ export const POST = withRouteHandler( output: result.output ?? null, // Resume has no request body to name selectors in, so selection never applies here. blockOutputs: null, - paused: result.paused - ? presentV2RunPause(result.paused.runId, result.paused.points) - : null, + paused: presentV2RunPause(result.paused), }, { headers } ) diff --git a/apps/sim/hooks/queries/workflow-source.test.ts b/apps/sim/hooks/queries/workflow-source.test.ts index c9b20117fc5..e5dd998070d 100644 --- a/apps/sim/hooks/queries/workflow-source.test.ts +++ b/apps/sim/hooks/queries/workflow-source.test.ts @@ -21,7 +21,13 @@ function sourceServer() { workspaceId: 'ws-1', files: { 'workflow.ts': state.text }, lock: { version: 1, blocks: {}, variables: {} }, - base: { workflowId: WORKFLOW_ID, workspaceId: 'ws-1', fingerprint: 'f', catalogHash: 'c' }, + base: { + version: 1, + workflowId: WORKFLOW_ID, + workspaceId: 'ws-1', + fingerprint: 'f', + catalogHash: 'c', + }, canonicalHash: 'h', sdkMajor: 1, blockTypes: [], diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 823df6043a6..d048362b245 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -86,10 +86,6 @@ export const v2WorkflowRunIdSchema = runIdSchema .describe('Unique workflow run identifier.') .meta({ examples: ['run_8f14e45f-ceea-467f-a'] }) -/** - * The run a pause is recorded under, which Resume workflow run names. A resumed run that pauses - * again records the pause under the run it resumed, not under the resume attempt's own id. - */ const v2PausedRunIdSchema = z .string() .describe( diff --git a/apps/sim/lib/workflows/api/run-pause.ts b/apps/sim/lib/workflows/api/run-pause.ts index d214a2c7ab2..3856e724b15 100644 --- a/apps/sim/lib/workflows/api/run-pause.ts +++ b/apps/sim/lib/workflows/api/run-pause.ts @@ -1,17 +1,17 @@ import type { V2ExecuteWorkflowData } from '@/lib/api/contracts/v2/workflows' -import type { PausePoint } from '@/executor/types' +import type { RunPause } from '@/lib/workflows/executor/run-pause' /** - * The v2 wire shape of where a run waits, shared by the execute and resume results: the run the - * pause is recorded under (which Resume workflow run names) and each of its points. + * The v2 wire shape of where a run waits, shared by the execute and resume results; null when it + * is not paused. */ export function presentV2RunPause( - runId: string, - points: readonly PausePoint[] -): NonNullable { + pause: RunPause | null | undefined +): V2ExecuteWorkflowData['paused'] { + if (!pause) return null return { - runId, - points: points.map((point) => ({ + runId: pause.runId, + points: pause.points.map((point) => ({ contextId: point.contextId, kind: point.pauseKind, status: point.resumeStatus, diff --git a/apps/sim/lib/workflows/executor/execute-service.ts b/apps/sim/lib/workflows/executor/execute-service.ts index 8bd2407c3b0..fa52cfa85d3 100644 --- a/apps/sim/lib/workflows/executor/execute-service.ts +++ b/apps/sim/lib/workflows/executor/execute-service.ts @@ -32,6 +32,7 @@ import { releaseExecutionIdClaim, } from '@/lib/workflows/executor/execution-id-claim' import { handlePostExecutionPauseState } from '@/lib/workflows/executor/pause-persistence' +import { type RunPause, runPauseOf } from '@/lib/workflows/executor/run-pause' import { loadDeployedWorkflowState, loadWorkflowDeploymentVersionState, @@ -52,7 +53,7 @@ import { workflowHasResponseBlock } from '@/lib/workflows/utils' import { normalizeName } from '@/executor/constants' import { ExecutionSnapshot } from '@/executor/execution/snapshot' import type { ExecutionMetadata, SerializableExecutionState } from '@/executor/execution/types' -import type { BlockLog, NormalizedBlockOutput, PausePoint } from '@/executor/types' +import type { BlockLog, NormalizedBlockOutput } from '@/executor/types' import { classifyExecutionError, hasExecutionResult, @@ -183,8 +184,8 @@ export interface ExecuteWorkflowServiceRun { durationMs?: number /** The execution timeout applied to the run in milliseconds; `0` means untimed. */ executionTimeoutMs: number - /** Where a `paused` run waits, recorded under its `executionId`. */ - pausePoints?: PausePoint[] + /** Where a `paused` run waits; absent otherwise. */ + paused?: RunPause | null } /** A run's result before the applied timeout is stamped onto it. */ @@ -866,7 +867,7 @@ export async function executeWorkflowService( startedAt: result.metadata?.startTime, endedAt: result.metadata?.endTime, durationMs: result.metadata?.duration, - ...(status === 'paused' ? { pausePoints: result.pausePoints ?? [] } : {}), + paused: runPauseOf(result, executionId), } } catch (error: unknown) { const errorMessage = getErrorMessage(error, 'Unknown error') diff --git a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts index 08d9acc71a8..d0e124aaa75 100644 --- a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts +++ b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts @@ -59,6 +59,7 @@ import { normalizeAutomaticResumeWaitingReason, resolveAutomaticResumeAdmissionFailure, } from '@/lib/workflows/executor/resume-policy' +import { pausedRunIdOf } from '@/lib/workflows/executor/run-pause' import { forwardAgentStreamToExecutionEvents, shouldForwardAnswerTextFromSink, @@ -175,14 +176,6 @@ class ResumeAdmissionError extends Error { export type FailedResumeOutcome = 'pause_retained' | 'execution_failed' | 'execution_completed' /** Matches the paused execution mode to the deployment recorded on its durable root log. */ -/** - * The run a resumed attempt's pause is recorded under: the execution the resumed engine ran as, - * else the attempt's own id. Resume workflow run names this run to resume the pause. - */ -export function pausedRunIdOf(result: ExecutionResult, resumeExecutionId: string): string { - return result.metadata?.executionId ?? resumeExecutionId -} - export function requireResumeDeploymentVersion( useDraftState: unknown, deploymentVersionId: string | null diff --git a/apps/sim/lib/workflows/executor/resume-execution.ts b/apps/sim/lib/workflows/executor/resume-execution.ts index 484d605e7a2..9d1b16b9f0d 100644 --- a/apps/sim/lib/workflows/executor/resume-execution.ts +++ b/apps/sim/lib/workflows/executor/resume-execution.ts @@ -14,14 +14,12 @@ import type { OrchestrationRequestContext } from '@/lib/core/orchestration/types import { generateRequestId } from '@/lib/core/utils/request' import { preprocessExecution } from '@/lib/execution/preprocessing' import { RESUME_EXECUTION_JOB_ID_PREFIX } from '@/lib/workflows/executor/enqueue-execution' -import { - PauseResumeManager, - pausedRunIdOf, -} from '@/lib/workflows/executor/human-in-the-loop-manager' +import { PauseResumeManager } from '@/lib/workflows/executor/human-in-the-loop-manager' +import { type RunPause, runPauseOf } from '@/lib/workflows/executor/run-pause' import { createStreamingResponse } from '@/lib/workflows/streaming/streaming' import { executeResumeJob, type ResumeExecutionPayload } from '@/background/resume-execution' import { ExecutionSnapshot } from '@/executor/execution/snapshot' -import type { ExecutionResult, PausePoint } from '@/executor/types' +import type { ExecutionResult } from '@/executor/types' import { classifyExecutionError, hasExecutionResult, @@ -90,8 +88,8 @@ export type ResumeWorkflowExecutionResult = startTime?: string endTime?: string } - /** Where a run that paused again waits: the run the pause is recorded under, and its points. */ - paused: { runId: string; points: PausePoint[] } | null + /** Where a run that paused again waits. */ + paused: RunPause | null } | { kind: 'async' @@ -359,12 +357,7 @@ export async function executeResumeWorkflow({ } : undefined, paused: - status === 'paused' - ? { - runId: pausedRunIdOf(result, enqueueResult.resumeExecutionId), - points: result.pausePoints ?? [], - } - : null, + runFailure === undefined ? runPauseOf(result, enqueueResult.resumeExecutionId) : null, } } diff --git a/apps/sim/lib/workflows/executor/run-pause.ts b/apps/sim/lib/workflows/executor/run-pause.ts new file mode 100644 index 00000000000..a4caecbd5ab --- /dev/null +++ b/apps/sim/lib/workflows/executor/run-pause.ts @@ -0,0 +1,22 @@ +import type { ExecutionResult, PausePoint } from '@/executor/types' + +/** Where a paused run waits: the run its pause is recorded under, and each pause point. */ +export interface RunPause { + runId: string + points: PausePoint[] +} + +/** + * The run a pause is recorded under, which Resume workflow run names: the execution the engine ran + * as, else `runId`, the id the run was started or resumed with. A resumed run that pauses again + * records the pause under the run it resumed, not the resume attempt's own id. + */ +export function pausedRunIdOf(result: ExecutionResult, runId: string): string { + return result.metadata?.executionId ?? runId +} + +/** Where `result` waits when it paused, else null. */ +export function runPauseOf(result: ExecutionResult, runId: string): RunPause | null { + if (result.status !== 'paused') return null + return { runId: pausedRunIdOf(result, runId), points: result.pausePoints ?? [] } +} diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index cba59952a8f..6b07fc855fa 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -535,8 +535,6 @@ export interface SourceTree { workspaceTypes: boolean /** The agent guide to read before editing. */ guide: typeof SOURCE_AGENTS_FILE - /** The primer atop the guide (`source-primer.ts`), printed so an agent needs no other read. */ - primer: string } /** Reports a `tsconfig.json` the CLI left alone and summarizes a tree write. */ @@ -544,7 +542,7 @@ export function finishTree( dir: string, written: number, workspaceTypes: WorkspaceTypes | null, - tree: { ownsTsconfig: boolean; primer: string } + tree: { ownsTsconfig: boolean } ): SourceTree { if (!tree.ownsTsconfig) { printError( @@ -555,14 +553,13 @@ export function finishTree( files: written, workspaceTypes: workspaceTypes !== null, guide: SOURCE_AGENTS_FILE, - primer: tree.primer, } } /** * Prints a tree write's result: the fields, then the primer as text when the result carries one - * (in JSON or YAML it is the document's `primer` field). A get leaves the primer out: it is - * already the top of `.sim/AGENTS.md`. + * (in JSON or YAML it is the document's `primer` field). Only a new directory's starter prints + * it; a get leaves it at the top of `.sim/AGENTS.md`. */ export function printTreeResult( format: OutputFormat, diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index ecb6f4d61e1..65726eb842f 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -343,7 +343,7 @@ export async function writeSourceScaffold( client: OperationClient<'getSourceCatalog' | 'getSourceResources'>, dir: string, workspaceId: string -): Promise { +): Promise { const [catalog, workspaceTypes] = await Promise.all([ loadCatalog(client, { workspaceId, blockTypes: [] }), loadWorkspaceTypes(client, workspaceId), @@ -358,7 +358,7 @@ export async function writeSourceScaffold( ...tree.change.write, ] await updateSourceDir(dir, { ...tree.change, write }) - return finishTree(dir, write.length, workspaceTypes, tree) + return { ...finishTree(dir, write.length, workspaceTypes, tree), primer: tree.primer } } /** diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts index 8e19ee28677..e1675570ab9 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts @@ -119,7 +119,12 @@ describe('sim workflows runs get on a paused run', () => { runId: RUN_ID, workflowId: WORKFLOW_ID, status: 'paused', - paused: { contextId: 'ctx_1', pauseKind: 'human' }, + paused: { + contextId: 'ctx_1', + pauseKind: 'human', + runId: RUN_ID, + points: [{ contextId: 'ctx_1', status: 'paused' }], + }, } answer({ data: run }) const out = stdout() diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts b/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts index 5e90c89f5be..c1fc987fd8a 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-wait.ts @@ -196,7 +196,7 @@ function explain( if (outcome === 'completed') return null if (outcome === 'failed') return `Run ${runId} failed.` if (outcome === 'cancelled') return `Run ${runId} was cancelled.` - const next = resumeCommandFor(toRecord(run), { workflowId }) + const next = resumeCommandFor(toRecord(run), workflowId) return `Run ${runId} is paused waiting for input.${next ? ` Resume it: ${next}` : ''}` } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts index b9aba27c52a..10a5bcd783e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -123,7 +123,7 @@ export function attachWorkflowSourceGet(source: Command): void { ) assertPrintedSourcePaths(workflowSource.files) if (!force) await assertNoLocalEdits(dir, workflowSource) - const { primer: _, ...tree } = await writeSourceDirectory( + const tree = await writeSourceDirectory( client, dir, workflowSource, diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 7a3fcbfa9cb..34788744ba6 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -130,18 +130,13 @@ function failedExitCode(failed: NonNullable): number { : refusedExitCode([{ code: failed.code, severity: 'error' }]) } -/** Whether a dry run's errors refuse the apply, as the server answers (`refuses`). */ -function refusesApply(data: ApplyData): boolean { - return data.refuses === true -} - /** * The exit status of a dry run with errors, as the apply would exit: one that holds changes back * and refuses nothing else writes the rest, so it exits `SOURCE_HELD_EXIT_CODE` as that apply * does, unless every change it would write is held (1, nothing written). */ function previewExitCode(data: ApplyData): number { - if (refusesApply(data)) return refusedExitCode(data.diagnostics) + if (data.refuses === true) return refusedExitCode(data.diagnostics) const writesSome = data.plan.some((change) => change.action !== 'noop' && !change.held) return writesSome ? SOURCE_HELD_EXIT_CODE : 1 } @@ -875,7 +870,7 @@ export function attachWorkspaceSourceApply(source: Command): void { printPlan(preview.plan, preview.diagnostics) findings.print(preview.diagnostics) }, - refuses: refusesApply, + refuses: (preview) => preview.refuses === true, previewExitCode, // Without a preview, stage the blobs the base does not hold as they are. beforeCommit: (preview) => diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts index 131280d32bb..ba5996b29a3 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts @@ -131,7 +131,7 @@ async function writeWorkspaceSource( dir: string, source: WorkspaceSource, force: boolean -): Promise<{ written: number; removed: number; guide: string; primer: string }> { +): Promise<{ written: number; removed: number; guide: string }> { assertWorkspacePaths(Object.keys(source.files)) assertListedBlobs(source.blobs) const blobs = new Map(source.blobs.map((blob) => [blob.path, blob])) @@ -277,7 +277,6 @@ async function writeWorkspaceSource( written: summary.files, removed: gone.size, guide: summary.guide, - primer: summary.primer, } } finally { if (partial) await rm(partial, { recursive: true, force: true }) diff --git a/packages/sim-cli/src/runtime/paused-run.ts b/packages/sim-cli/src/runtime/paused-run.ts index a09387646cc..c0bdf8cf3c6 100644 --- a/packages/sim-cli/src/runtime/paused-run.ts +++ b/packages/sim-cli/src/runtime/paused-run.ts @@ -27,13 +27,12 @@ function resumeCommand(runId: string, workflowId: string, contextId: string): st * server names the run to resume in `paused.runId` (for a resumed run that paused again, the run * it resumed, not the record's own `runId`) and each point's `contextId`. Null when nothing waits * or an id is not in the format the server issues, so no untrusted text reaches a printed - * command. `workflowId` is used when the record omits its own. + * command. */ export function resumeCommandFor( record: Record, - fallback: { workflowId: string } + workflowId: string ): string | null { - const workflowId = typeof record.workflowId === 'string' ? record.workflowId : fallback.workflowId const paused = toRecordOrNull(record.paused) const runId = paused?.runId if (!issuedId(runId) || !issuedId(workflowId)) return null @@ -54,6 +53,6 @@ export function withResumeNext(operation: V2OperationName, payload: unknown): un if (!RUN_OPERATIONS.has(operation) || !isRecordLike(payload)) return payload if (payload.status !== 'paused' || 'next' in payload) return payload if (typeof payload.workflowId !== 'string') return payload - const next = resumeCommandFor(payload, { workflowId: payload.workflowId }) + const next = resumeCommandFor(payload, payload.workflowId) return next ? { ...payload, next } : payload } diff --git a/packages/sim-cli/src/terminal.test.ts b/packages/sim-cli/src/terminal.test.ts index 97817c2f549..387a4b84baf 100644 --- a/packages/sim-cli/src/terminal.test.ts +++ b/packages/sim-cli/src/terminal.test.ts @@ -135,7 +135,13 @@ describe('a refused source write in JSON output', () => { ) writeFileSync( join(dir, '.sim/base.json'), - JSON.stringify({ workflowId, workspaceId: 'ws_1', fingerprint: 'sf1:a', catalogHash: 'h' }) + JSON.stringify({ + version: 1, + workflowId, + workspaceId: 'ws_1', + fingerprint: 'sf1:a', + catalogHash: 'h', + }) ) const finding = { code: 'E_APPLY_STALE', diff --git a/packages/workflow-code/src/compile/catalog.test-helpers.ts b/packages/workflow-code/src/compile/catalog.test-helpers.ts index dd20526619b..3fb77e1cd79 100644 --- a/packages/workflow-code/src/compile/catalog.test-helpers.ts +++ b/packages/workflow-code/src/compile/catalog.test-helpers.ts @@ -31,6 +31,7 @@ function sub( const ANY: CatalogOutput = { type: 'json' } const TEXT: CatalogOutput = { type: 'string' } +const MAY_BE_TEXT: CatalogOutput = { type: 'json', mayBeText: true } function graph(extra: Partial = {}): CatalogBlockGraph { return { @@ -121,7 +122,7 @@ export const TEST_CATALOG: BlockCatalog = { sub('body', 'code', 'json', { language: 'json' }), ], { - data: ANY, + data: MAY_BE_TEXT, status: { type: 'number' }, headers: { type: 'json', properties: { contentType: TEXT } }, } @@ -160,7 +161,7 @@ export const TEST_CATALOG: BlockCatalog = { }), sub('code', 'code', 'code', { required: true }), ], - { result: ANY, stdout: TEXT }, + { result: MAY_BE_TEXT, stdout: TEXT }, { errorOutputs: ['errorMessage'] } ), note: block( diff --git a/packages/workspace-code/src/kinds/workflow.test.ts b/packages/workspace-code/src/kinds/workflow.test.ts index 6685722cb1c..a2c0b24e50a 100644 --- a/packages/workspace-code/src/kinds/workflow.test.ts +++ b/packages/workspace-code/src/kinds/workflow.test.ts @@ -33,7 +33,7 @@ describe('workflowCodec', () => { expect(parsed.diagnostics.map((finding) => finding.code)).toEqual(['E_DECL_SHAPE']) }) - it('reads a base written before bases carried a version', () => { + it('refuses a base with no version', () => { const base = { workflowId: 'wf_1', workspaceId: 'ws', fingerprint: 'sf1:a', catalogHash: 'c' } const parsed = workflowCodec.parse( 'ingest', @@ -44,6 +44,7 @@ describe('workflowCodec', () => { [] ) - expect(parsed.decl?.base).toEqual({ version: 1, ...base }) + expect(parsed.decl?.base).toBeUndefined() + expect(parsed.diagnostics.map((finding) => finding.code)).toEqual(['E_DECL_SHAPE']) }) }) From fa9099f7d3d409b7db5c672155143d3a4ea2d80c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 11:24:10 -0800 Subject: [PATCH 3/7] test(workflow-code): prove a resumed run that pauses again names the run it resumed Extend the runtime integration with a second human block, and tighten the cleanup-audited tests so each can fail. --- .../[workflowId]/execute/route.test.ts | 6 -- .../runs/[runId]/resume/route.test.ts | 2 +- ...ply-workflow-source.runtime.integration.ts | 59 +++++++++++++++++-- .../src/commands/protocol/source-tree.ts | 1 - .../protocol/workflow-source-status.test.ts | 1 + .../protocol/workspace-source-apply.test.ts | 7 ++- packages/sim-cli/src/runtime/paused-run.ts | 1 - .../workspace-code/src/kinds/workflow.test.ts | 15 ----- 8 files changed, 62 insertions(+), 30 deletions(-) diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts index 6d49625fb81..b6e70d1d042 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts @@ -359,12 +359,6 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => { }) }) - it('reports no pause for a run that finished', async () => { - const body = await (await callExecute({ input: {} })).json() - - expect(body.data.paused).toBeNull() - }) - it('streams an immediate heartbeat and the same sync result when NDJSON is accepted', async () => { vi.useFakeTimers() try { diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts index e1857d01c47..53322ddd5c5 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts @@ -137,7 +137,7 @@ describe('POST /api/v2/workflows/[workflowId]/runs/[runId]/resume', () => { expect(v2ResumeWorkflowContract.response.schema.parse(body)).toEqual(body) }) - it('names the run a resume that paused again waits under, which is the run it resumed', async () => { + it("presents the pause the resume reports, not the resume attempt's own run id", async () => { mocks.resume.mockResolvedValueOnce({ kind: 'sync', success: true, diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.runtime.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-source.runtime.integration.ts index fcdf008a0fe..7c3bbc9c3b4 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.runtime.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.runtime.integration.ts @@ -3,7 +3,8 @@ * PostgreSQL, while workflow source is applied to the draft. The apply renames the paused block; * the run then resumes from its execution snapshot. Source apply writes the draft only, so the * snapshot and the deployed version must come through it byte-identical, and the renamed block - * must keep its id so the pause point still names a block the draft holds. + * must keep its id so the pause point still names a block the draft holds. The resumed run then + * pauses at a second block under the run it resumed, which the resume names in `paused.runId`. */ import { mkdir, writeFile } from 'node:fs/promises' import { dirname, resolve } from 'node:path' @@ -50,6 +51,7 @@ const workspaceId = generateId() const workflowId = generateId() const startId = generateId() const approvalId = generateId() +const signoffId = generateId() const owner = createSessionPrincipal({ userId: ownerId, sessionId: generateId() }) const ownerKey = createPersonalApiKeyPrincipal({ userId: ownerId, keyId: generateId() }) @@ -168,8 +170,24 @@ beforeAll(async () => { }, }, }), + [signoffId]: createBlock({ + id: signoffId, + type: 'human_in_the_loop', + name: 'Signoff', + position: { x: 600, y: 0 }, + subBlocks: { + inputFormat: { + id: 'inputFormat', + type: 'input-format', + value: [{ id: 'signed', name: 'signed', type: 'boolean', required: true }], + }, + }, + }), }, - edges: [{ id: generateId(), source: startId, target: approvalId }], + edges: [ + { id: generateId(), source: startId, target: approvalId }, + { id: generateId(), source: approvalId, target: signoffId }, + ], loops: {}, parallels: {}, }) @@ -266,7 +284,40 @@ check( }, }) - expect(resumed).toMatchObject({ kind: 'sync', success: true }) - expect(resumed).not.toMatchObject({ status: 'failed' }) + expect(resumed).toMatchObject({ kind: 'sync', success: true, status: 'paused' }) + if (resumed.kind !== 'sync' || !resumed.paused) + throw new Error('Expected the run to pause again') + // The resume attempt runs under its own id, but the pause it reaches is recorded under the run + // it resumed, and that is the run the next resume names. + expect(resumed.executionId).not.toBe(runId) + expect(resumed.paused.runId).toBe(runId) + const [waiting] = resumed.paused.points.filter((point) => point.resumeStatus === 'paused') + if (!waiting) throw new Error('Expected a waiting pause point') + expect(waiting.blockId).toBe(signoffId) + await vi.waitFor( + async () => { + const row = await pausedRow(runId) + const points = Object.values( + (row?.pausePoints ?? {}) as Record + ) + if (!points.some((point) => point.contextId === waiting.contextId)) { + throw new Error('Second pause not yet published') + } + }, + { timeout: 20_000, interval: 250 } + ) + + const signed = await resumeWorkflowRun.execute({ + principal: ownerKey, + input: { + workflowId, + runId: resumed.paused.runId, + contextId: waiting.contextId, + resumeInput: { signed: true }, + surface: 'v2', + }, + }) + + expect(signed).toMatchObject({ kind: 'sync', success: true, status: 'completed', paused: null }) } ) diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index 6b07fc855fa..7e47cffaf73 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -176,7 +176,6 @@ function writeCachedCatalog(catalog: BlockCatalog): void { writeJsonFile(catalogCachePath(catalog.hash), catalog) } -/** Records `hash` as the workspace's catalog. */ function writeWorkspaceCatalogPointer(workspaceId: string, hash: string): void { if (embedStore.getStore() || !CACHE_KEY.test(workspaceId)) return writeJsonFile(workspaceCatalogPointerPath(workspaceId), { hash }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts index 0bd0c3afd64..38a3d3f81ee 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-status.test.ts @@ -541,6 +541,7 @@ describe('workflows source status', () => { await run(folder, 'status', '--offline') + expect(printed()).toMatchObject({ server: 'offline' }) const local = (printed().local ?? []) as Array<{ files: unknown[] }> expect(local.flatMap((entry) => entry.files)).toEqual([]) }) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index c3c8797eae3..a678826462e 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -1525,14 +1525,17 @@ describe('workspaces source apply', () => { request.mockResolvedValue( answer({ dryRun: true, - plan: [{ kind: 'table', key: 'leads', action: 'create', held: true }], + plan: [ + { kind: 'table', key: 'leads', action: 'create', held: true }, + { kind: 'table', key: 'other', action: 'create' }, + ], diagnostics: [{ code: 'E_APPLY_LOCKED', severity: 'error', message: 'locked' }], }) ) await apply('--dry-run') - expect(process.exitCode).toBe(1) + expect(process.exitCode).toBe(15) }) it('refuses a local blob over the size limit before reading it, and exits 7', async () => { diff --git a/packages/sim-cli/src/runtime/paused-run.ts b/packages/sim-cli/src/runtime/paused-run.ts index c0bdf8cf3c6..40427e2fb23 100644 --- a/packages/sim-cli/src/runtime/paused-run.ts +++ b/packages/sim-cli/src/runtime/paused-run.ts @@ -17,7 +17,6 @@ function shellArgument(value: string): string { return SAFE_ARGUMENT.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'` } -/** The command that resumes one pause of a paused run. */ function resumeCommand(runId: string, workflowId: string, contextId: string): string { return `sim workflows runs resume ${shellArgument(runId)} --workflow ${shellArgument(workflowId)} --context ${shellArgument(contextId)}` } diff --git a/packages/workspace-code/src/kinds/workflow.test.ts b/packages/workspace-code/src/kinds/workflow.test.ts index a2c0b24e50a..f0844ab735a 100644 --- a/packages/workspace-code/src/kinds/workflow.test.ts +++ b/packages/workspace-code/src/kinds/workflow.test.ts @@ -32,19 +32,4 @@ describe('workflowCodec', () => { expect(parsed.decl).toBeUndefined() expect(parsed.diagnostics.map((finding) => finding.code)).toEqual(['E_DECL_SHAPE']) }) - - it('refuses a base with no version', () => { - const base = { workflowId: 'wf_1', workspaceId: 'ws', fingerprint: 'sf1:a', catalogHash: 'c' } - const parsed = workflowCodec.parse( - 'ingest', - { - 'workflows/ingest/workflow.ts': 'export default 1\n', - 'workflows/ingest/.sim/base.json': JSON.stringify(base), - }, - [] - ) - - expect(parsed.decl?.base).toBeUndefined() - expect(parsed.diagnostics.map((finding) => finding.code)).toEqual(['E_DECL_SHAPE']) - }) }) From dadf320644001b014da46608abaf1aec4d08879b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 11:54:35 -0800 Subject: [PATCH 4/7] fix(sim-cli): name no resume command for a timed pause, which the resume route refuses --- .../src/commands/protocol/workflow-run-get.test.ts | 2 +- .../src/commands/protocol/workflow-run-wait.test.ts | 6 +++--- packages/sim-cli/src/runtime/paused-run.test.ts | 12 ++++++++++++ packages/sim-cli/src/runtime/paused-run.ts | 12 ++++++------ 4 files changed, 22 insertions(+), 10 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts index e1675570ab9..666e60dac8e 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-get.test.ts @@ -123,7 +123,7 @@ describe('sim workflows runs get on a paused run', () => { contextId: 'ctx_1', pauseKind: 'human', runId: RUN_ID, - points: [{ contextId: 'ctx_1', status: 'paused' }], + points: [{ contextId: 'ctx_1', kind: 'human', status: 'paused' }], }, } answer({ data: run }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-wait.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-wait.test.ts index 96c506554e8..a1edb326c62 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-wait.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-wait.test.ts @@ -78,7 +78,7 @@ interface RunPayload { pauseKind?: string | null resumeAt?: string | null runId?: string - points?: Array<{ contextId: string; status: string }> + points?: Array<{ contextId: string; kind: string; status: string }> } | null } @@ -157,7 +157,7 @@ describe('workflows runs wait', () => { pauseKind: 'human', contextId: 'ctx_9', runId: 'run_1', - points: [{ contextId: 'ctx_9', status: 'paused' }], + points: [{ contextId: 'ctx_9', kind: 'human', status: 'paused' }], }, }) @@ -178,7 +178,7 @@ describe('workflows runs wait', () => { pauseKind: 'human', contextId: 'ctx_9', runId: 'exec_9', - points: [{ contextId: 'ctx_9', status: 'paused' }], + points: [{ contextId: 'ctx_9', kind: 'human', status: 'paused' }], }, }) diff --git a/packages/sim-cli/src/runtime/paused-run.test.ts b/packages/sim-cli/src/runtime/paused-run.test.ts index c920d5db2bc..327a0eb4c06 100644 --- a/packages/sim-cli/src/runtime/paused-run.test.ts +++ b/packages/sim-cli/src/runtime/paused-run.test.ts @@ -30,6 +30,18 @@ describe('withResumeNext', () => { }) }) + it('names no command for a timed pause, which resumes on its own', () => { + const timed = { contextId: 'later', kind: 'time', status: 'paused' } + expect( + withResumeNext('executeWorkflow', { + ...paused, + paused: { runId: 'run_top', points: [timed, point('ctx_9')] }, + }) + ).toMatchObject({ next: 'sim workflows runs resume run_top --workflow wf_1 --context ctx_9' }) + const onlyTimed = { ...paused, paused: { runId: 'run_top', points: [timed] } } + expect(withResumeNext('executeWorkflow', onlyTimed)).toBe(onlyTimed) + }) + it('names one command per waiting point, quoting a branch context', () => { const several = { ...paused, diff --git a/packages/sim-cli/src/runtime/paused-run.ts b/packages/sim-cli/src/runtime/paused-run.ts index 40427e2fb23..7af902a35c2 100644 --- a/packages/sim-cli/src/runtime/paused-run.ts +++ b/packages/sim-cli/src/runtime/paused-run.ts @@ -22,11 +22,11 @@ function resumeCommand(runId: string, workflowId: string, contextId: string): st } /** - * The exact `runs resume` command for a paused run record, one line per point still waiting. The - * server names the run to resume in `paused.runId` (for a resumed run that paused again, the run - * it resumed, not the record's own `runId`) and each point's `contextId`. Null when nothing waits - * or an id is not in the format the server issues, so no untrusted text reaches a printed - * command. + * The exact `runs resume` command for a paused run record, one line per human pause still waiting + * (a timed pause resumes on its own, and the resume route refuses it). The server names the run to + * resume in `paused.runId` (for a resumed run that paused again, the run it resumed, not the + * record's own `runId`) and each point's `contextId`. Null when nothing waits or an id is not in + * the format the server issues, so no untrusted text reaches a printed command. */ export function resumeCommandFor( record: Record, @@ -37,7 +37,7 @@ export function resumeCommandFor( if (!issuedId(runId) || !issuedId(workflowId)) return null const commands: string[] = [] for (const point of Array.isArray(paused?.points) ? paused.points : []) { - if (!isRecordLike(point) || point.status !== 'paused') continue + if (!isRecordLike(point) || point.status !== 'paused' || point.kind !== 'human') continue if (!issuedId(point.contextId)) return null commands.push(resumeCommand(runId, workflowId, point.contextId)) } From e7fc6724e4cf9a8fefe39ae552ad93326e1b6777 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 12:03:28 -0800 Subject: [PATCH 5/7] docs(workflow-code): status asks with a plan read, and a paused v2 run names the run to resume in paused --- .../content/docs/workflows/blocks/human-in-the-loop.mdx | 7 ++++--- apps/docs/content/docs/workflows/code/edit.mdx | 2 +- apps/docs/content/docs/workflows/code/how-it-works.mdx | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/apps/docs/content/docs/workflows/blocks/human-in-the-loop.mdx b/apps/docs/content/docs/workflows/blocks/human-in-the-loop.mdx index 15eb134623c..15fb1ec23e1 100644 --- a/apps/docs/content/docs/workflows/blocks/human-in-the-loop.mdx +++ b/apps/docs/content/docs/workflows/blocks/human-in-the-loop.mdx @@ -76,7 +76,7 @@ HITL blocks are excluded from the selected-output picker because pause data is i ## Resume with the v2 API -A v2 execute call can return `data.status: "paused"`. Read `contextId` from `data.output.data._resume` and the paused run's ID from `data.runId`: +A v2 execute call can return `data.status: "paused"`. Read the run to resume from `data.paused.runId`, and the `contextId` of a waiting `human` point from `data.paused.points`: ```bash curl -X POST 'https://www.sim.ai/api/v2/workflows/WORKFLOW_ID/runs/RUN_ID/resume' \ @@ -102,12 +102,13 @@ For an originally synchronous run, the response waits for the resumed execution "error": null, "startedAt": "2026-10-13T10:00:00.000Z", "endedAt": "2026-10-13T10:00:01.234Z", - "durationMs": 1234 + "durationMs": 1234, + "paused": null } } ``` -A later Human block can pause the resumed run again, returning new pause data. The resumed attempt has its own `runId`. +A later Human block can pause the resumed run again. The response then has `status: "paused"` and new `paused.points`, and `paused.runId` names the run to resume next: the run you resumed, not the attempt's own `runId`. ### Asynchronous and originally streaming runs diff --git a/apps/docs/content/docs/workflows/code/edit.mdx b/apps/docs/content/docs/workflows/code/edit.mdx index 69625fd3440..7aa8d8c57dd 100644 --- a/apps/docs/content/docs/workflows/code/edit.mdx +++ b/apps/docs/content/docs/workflows/code/edit.mdx @@ -46,7 +46,7 @@ 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`). +`status` lists the files you created, edited, or deleted, asks the server (with a plan read 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 diff --git a/apps/docs/content/docs/workflows/code/how-it-works.mdx b/apps/docs/content/docs/workflows/code/how-it-works.mdx index e3144b2c3d3..9da6506e437 100644 --- a/apps/docs/content/docs/workflows/code/how-it-works.mdx +++ b/apps/docs/content/docs/workflows/code/how-it-works.mdx @@ -57,7 +57,7 @@ Sim also stores each block's `const` name, its order in the file and its comment - the same: the apply goes ahead; - different: someone saved the workflow since you read it. The apply is refused as stale with exit `5`, on a dry run too, and nothing is written; [Troubleshooting](/workflows/code/troubleshooting#exit-5) has the steps. -The check is made again inside the write's transaction, so two applies that race cannot both win. `status` asks the same question with a dry run and reports it as drift (exit `12`) before you apply. +The check is made again inside the write's transaction, so two applies that race cannot both win. `status` asks the same question with a plan read that saves nothing and reports it as drift (exit `12`) before you apply. The base also records the block catalog you read against. When a compile fails and the catalog changed since, for example after a block gained a setting, the apply adds `W_APPLY_CATALOG_MOVED`: run `get` again to pick up the new types. From db535649fd7c6fd26ab45713cce42ddf6714ea78 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 12:05:47 -0800 Subject: [PATCH 6/7] docs(workflow-code): record the resumed-run example's paused field in the docs compatibility baseline --- apps/docs/scripts/fixtures/content-baseline.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index a86af7ad782..2a4f4f63954 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -180362,8 +180362,8 @@ { "lang": "json", "meta": null, - "sha256": "a58b8caec4a62b60998e6e861527913aa75c729a95b8772f0bea51b5947f98c3", - "bytes": 302, + "sha256": "2a7fc012d9a65e44b43b9d3a71fc338005cb118dccc142cb009006420d9d329d", + "bytes": 322, "line": 90 }, { @@ -180371,7 +180371,7 @@ "meta": null, "sha256": "202789edbaae3ec51e3c5209888b456b40142eb9151fa7b2a56387b92205b373", "bytes": 135, - "line": 112 + "line": 113 } ], "links": [ From c2b644b9b9cdf22c84f768473ca0668d5d58afd8 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 12:29:59 -0800 Subject: [PATCH 7/7] test(workflow-code): version the Code tab's base fixture and expect paused on the internal resume result --- .../resume/[workflowId]/[executionId]/[contextId]/route.test.ts | 1 + .../[workflowId]/components/panel/components/code/code.test.tsx | 1 + 2 files changed, 2 insertions(+) diff --git a/apps/sim/app/api/resume/[workflowId]/[executionId]/[contextId]/route.test.ts b/apps/sim/app/api/resume/[workflowId]/[executionId]/[contextId]/route.test.ts index 54f3a68e6e1..8d06460b71e 100644 --- a/apps/sim/app/api/resume/[workflowId]/[executionId]/[contextId]/route.test.ts +++ b/apps/sim/app/api/resume/[workflowId]/[executionId]/[contextId]/route.test.ts @@ -480,6 +480,7 @@ describe('POST /api/resume/[workflowId]/[executionId]/[contextId]', () => { success: false, status: 'failed', output: { partial: true }, + paused: null, error: 'Route: Condition evaluation failed', structuredError: { message: 'Condition evaluation failed', diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/code/code.test.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/code/code.test.tsx index da05646819e..5e761625e42 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/code/code.test.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/code/code.test.tsx @@ -50,6 +50,7 @@ describe('Code tab', () => { files: { 'workflow.ts': `// read ${sourceReads.length}` }, lock: { version: 1, blocks: {}, variables: {} }, base: { + version: 1, workflowId: WORKFLOW_ID, workspaceId: WORKSPACE_ID, fingerprint: `f${sourceReads.length}`,