diff --git a/.agents/skills/add-integration/SKILL.md b/.agents/skills/add-integration/SKILL.md index 6f15c8e6eef..7bcb1c8739c 100644 --- a/.agents/skills/add-integration/SKILL.md +++ b/.agents/skills/add-integration/SKILL.md @@ -606,6 +606,7 @@ If creating V2 versions (API-aligned outputs): - [ ] Verified `tools.config.params` correctly maps and coerces all param types - [ ] Verified every tool output and `transformResponse` path against documented or live-verified JSON responses - [ ] If any response schema remained unknown, explicitly told the user instead of guessing +- [ ] Ran the block in a workflow with `sim workflows run --dry`: each write is in `sideEffects.stubbed` (at most 50 entries; the rest are counted in `sideEffects.omitted.stubbed`) with the documented request where `request` is not `null` (null: the run could not vouch it was free of secrets, or could not build it once they were masked), and each read ran for real; a write absent from `stubbed` counts only if its block ran (not on an untaken branch or `--mock`ed) (send one write for real only with `--allow ` against a test resource) - [ ] `{Service}BlockMeta` exported with at least 7 templates, each having `icon`, `title`, `prompt`, `modules`, `category`, and `tags` ## File Handling diff --git a/.agents/skills/add-tools/SKILL.md b/.agents/skills/add-tools/SKILL.md index 7f45f81e0f7..955ff96b57c 100644 --- a/.agents/skills/add-tools/SKILL.md +++ b/.agents/skills/add-tools/SKILL.md @@ -220,6 +220,20 @@ search that returns no email or phone, and an email verifier. `read`, fails the audit unless the `effect` line carries `// tool-effect: ` on one of the two lines above it; use it only for a genuine exception such as a GET that writes in `postProcess`. - A factory that builds tools from definitions takes `effect` per definition and passes it through. +- Prove the labels with a dry run, against a test account or test resource (a `read` runs for real, + so a write mislabelled `read` is sent): put the block in a workflow and run + `sim workflows run --dry --input '{…}'`. Each `write` call must appear in the result's + `sideEffects.stubbed` with the request you expect (an HTTP tool's `method`, `url` and `body`, or an + in-process operation's input, credentials redacted), and each `read` must run for real and return + live data; a read listed there is labelled `write`. A write missing from `stubbed` may not have + been reached (an untaken branch, or a block answered by `--mock`), so first confirm its block ran + in the trace: a reached write is absent only when its block was `--allow`ed and sent it for real, + so a reached, unallowed write missing from `stubbed` is labelled `read`. `stubbed` keeps at most + 50 entries and counts the rest in `sideEffects.omitted.stubbed`, so a write past the cap is + counted, not missing: test one tool per run, or few enough to fit. An entry's `request` is `null` + when the run cannot vouch that no secret remains in it, or cannot build it once secrets are + masked (a URL that is wholly a secret); then check the tool label alone and compare the request + fields only on entries that carry one. ## Critical Rules for Parameters diff --git a/.agents/skills/validate-integration/SKILL.md b/.agents/skills/validate-integration/SKILL.md index a9d69a3823e..4f4d178f178 100644 --- a/.agents/skills/validate-integration/SKILL.md +++ b/.agents/skills/validate-integration/SKILL.md @@ -82,6 +82,12 @@ For **every** tool file, check: `add-tools` → Declaring the effect) - [ ] Any `// tool-effect: ` sits on a genuine verb/label exception, and `bun run check:tool-effects` passes +- [ ] A dry run (`sim workflows run --dry --input '{…}'` on a workflow using the + block) lists every write operation in `sideEffects.stubbed` (at most 50 entries; the rest + are counted in `sideEffects.omitted.stubbed`) with the request the API docs expect where + `request` is not `null`, and every read runs for real; a write absent from `stubbed` counts + only if its block ran (not on an untaken branch or `--mock`ed) (rules: `add-tools` → + Declaring the effect) ### Params - [ ] All required API params are marked `required: true` diff --git a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx index 5d1768a9ca6..7636413fc99 100644 --- a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx +++ b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx @@ -166,7 +166,7 @@ Apply without `dryRun`. Set `atomic: true` in the body to write nothing when any ## 7. Test the draft [#test-run] -Run the saved draft with `run.source: "manual"`. Manual runs are synchronous or streamed, never `async`. +Run the saved draft with `run.source: "manual"` and `run.dry: true`. A dry run sends no writes: every tool call not declared `read` (table writes, sends, HTTP calls, custom and MCP tools) returns a placeholder shaped like the tool's output, and the result lists it under `sideEffects.stubbed` with the request it would have sent, credentials, secrets and password fields redacted. Check those payloads instead of cleaning up test data. Reads and model calls run for real, child workflows run dry too, and custom blocks are answered whole. Code runs for real (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) and is listed under `sideEffects.unchecked`. A dry run keeps nothing beyond its own log, which is under the `test` trigger: Agents read their memory but write none, and it raises no workspace event and does not count as a run of the workflow. Human in the loop and Wait blocks are answered whole, so a dry run never pauses, and a test run is never resumed. A failed dry run still returns its `sideEffects`, and only another dry run can use it, or a workflow test's run, as `run.entry.sourceRunId`. Allowing an Agent with `run.allowBlocks` sends only its own tool calls, not a workflow or custom block it calls. A mock is data: it cannot replace a locked block or set a field the run's execution, trace or billing reads (such as `cost`, `tokens`, `model` or a field starting with `_`), and the run records only which blocks were mocked, so a rerun passes `run.mocks` again, while the run's log shows a mocked block's output like any other block's. `run.mocks` names at most 50 blocks. Manual runs are synchronous or streamed, never `async`; a dry run is synchronous only. @@ -174,12 +174,12 @@ Run the saved draft with `run.source: "manual"`. Manual runs are synchronous or curl -sS --fail-with-body -X POST \ "$BASE_URL/api/v2/workflows/$WORKFLOW_ID/execute" \ -H "X-API-Key: $SIM_API_KEY" -H 'Content-Type: application/json' \ - -d '{"run": {"source": "manual"}, "input": {"ticketId": "T-123"}}' + -d '{"run": {"source": "manual", "dry": true}, "input": {"ticketId": "T-123"}}' ``` ```bash - sim workflows run "$WORKFLOW_ID" --manual --input '{"ticketId": "T-123"}' + sim workflows run "$WORKFLOW_ID" --dry --input '{"ticketId": "T-123"}' ``` @@ -193,6 +193,9 @@ Narrow a test run with these options: | Stop after one block | `run.stopAfterBlockId` | `--stop-after ` | | Rerun from a block, reusing an earlier run's upstream outputs | `run.entry: {type: "block", blockId, sourceRunId}` | `--from-block --source-run ` | | Rerun one block only | Block entry plus `stopAfterBlockId` naming the same block | `--from-block` and `--stop-after` with the same block | +| Send one block's writes for real during a dry run | `run.allowBlocks: [""]` | `--allow ` | +| Answer a block with a fixed output during a dry run, to steer a branch | `run.mocks: {"": {...}}` | `--mock ='{...}'` | +| Run everything for real | omit `run.dry` | `--manual` | `stopAfterBlockId` cannot name a block inside a loop or parallel. A run that routes away from the stop block fails as soon as that is decided. diff --git a/apps/docs/content/docs/cli/index.mdx b/apps/docs/content/docs/cli/index.mdx index d44f4e9b9ee..f8e60ffd8b6 100644 --- a/apps/docs/content/docs/cli/index.mdx +++ b/apps/docs/content/docs/cli/index.mdx @@ -77,7 +77,7 @@ b8c0d247-9e13-4a86-97f5-2ad4e1638c09 Weekly digest /Reporting no 18 sim workflows run 3a9e21d8-5f47-4c0b-b2ea-91d7c6034ef8 --input '{"ticketId":"T-4821"}' ``` -Ordinary execution runs the active deployment. Deploy from the workflow builder or with `sim workflows deploy `. To execute the current saved workflow state, use `sim workflows run --manual`. +Ordinary execution runs the active deployment. Deploy from the workflow builder or with `sim workflows deploy `. To execute the current saved workflow state, use `sim workflows run --manual`. To test it without sending its writes, use `--dry`: each write is answered with a placeholder and listed with its request under `sideEffects` in the result. ## How commands are shaped diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 9d740bd6ba2..edbee1d5ca8 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8516,6 +8516,9 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | +| `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | +| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, so a rerun passes it again (its log shows the output like any other block’s); repeatable. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -8531,9 +8534,11 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. + The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. -A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. +A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry and --allow. The run records only which blocks were mocked, so pass each --mock again; its log shows a mocked block's output like any other. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 2db4c32aecb..d87fd3e7cf6 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -833,6 +833,9 @@ sim workflows run [options] | `--base64-max-bytes ` | No | Maximum total bytes of file content to inline as base64, lowering but never raising the server limit of 16 MiB. Rejected when `async` is true. | | `--run-id ` | No | One-shot identifier for this run; NOT an idempotency key — reusing a claimed value fails with RUN_ID_CONFLICT instead of replaying the first result, and a fresh value starts another run. | | `--manual` | No | Run the current saved workflow state instead of the active deployment. | +| `--dry` | No | Dry run of the saved draft (implies --manual): writes are not sent but answered with placeholders and listed with their request payloads in sideEffects; reads, model calls and code run for real. Logged as a test run. Not with --follow, --async or --wait-timeout. | +| `--allow ` | No | Send this block's writes for real during a --dry run (its id, display name or key); for an Agent, only its own tool calls, not a workflow or custom block it calls; repeatable. | +| `--mock =` | No | Answer this block with the given JSON object instead of running it during a --dry run (its id, display name or key), to steer a branch or give a stubbed write a realistic result. Not a locked block; data only, so no cost, tokens, model or other field the run’s trace or billing reads, and no field starting with _. The run records only which blocks were mocked, so a rerun passes it again (its log shows the output like any other block’s); repeatable. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | | `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | @@ -848,9 +851,11 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --manual runs the saved draft, as the source loop leaves it. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs and is listed in sideEffects.unchecked. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. + The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. -A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. +A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again; a dry run's keeps --dry and --allow. The run records only which blocks were mocked, so pass each --mock again; its log shows a mocked block's output like any other. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. diff --git a/apps/docs/content/docs/workflows/code/coding-agents.mdx b/apps/docs/content/docs/workflows/code/coding-agents.mdx index 42ec35a8469..fd82d6293a7 100644 --- a/apps/docs/content/docs/workflows/code/coding-agents.mdx +++ b/apps/docs/content/docs/workflows/code/coding-agents.mdx @@ -21,11 +21,13 @@ Point the agent at `.sim/AGENTS.md` before it edits. 3. Run one chained command, then fix whatever it reports in the next step: ```bash - sim workflows source check --dir && sim workflows source apply --dir --yes && sim workflows run --manual --input '{...}' + sim workflows source check --dir && sim workflows source apply --dir --yes && sim workflows run --dry --input '{...}' ``` A non-zero exit code stops the chain at the first failure. `apply` compiles the source and compares it with the saved draft again, so an agent can skip `--dry-run`. `check` also type-checks the directory, so the chain needs no separate `tsc`. People and CI use `apply --dry-run` to review the plan, and `status` shows what changed and what to run next. + `run --dry` tests the saved draft without sending its writes: each write returns a placeholder and is listed under `sideEffects` with the request it would have sent, so the agent checks payloads instead of cleaning up rows or messages. `--allow ` sends one block's writes for real against a test resource, and `--manual` runs everything for real. + For a whole workspace, use `sim workspaces source` with the same steps; see [Manage a workspace as code](/workflows/code/workspace). ## Look things up diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index e1f7b4cc243..03a17dd3910 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -4976,7 +4976,8 @@ "downloadPath": "/api/v2/workflows/3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36/runs/run_8f14e45f-ceea-467f-a/files/file_1a2b3c", "base64": null } - ] + ], + "dryRun": null } } } @@ -17204,6 +17205,230 @@ "title": "Execution error", "description": "Structured in-band failure details for a workflow run." }, + "WorkflowRunSideEffects": { + "type": "object", + "properties": { + "stubbed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "description": "Workflow whose block it was: the run workflow, or a child workflow it called." + }, + "blockId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block id in that workflow; null when the call named no block." + }, + "block": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block display name; null when the call named no block." + }, + "tool": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Tool the block (or an Agent) called; null when the whole block was answered instead of run." + }, + "request": { + "anyOf": [ + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Request field." + } + }, + { + "type": "null" + } + ], + "description": "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never headers), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain, or could not build the request once they were masked (such as a URL that is wholly a secret)." + }, + "returned": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Placeholder field." + }, + "description": "Placeholder output the block or tool call returned to the run instead." + } + }, + "required": ["workflowId", "blockId", "block", "tool", "request", "returned"], + "additionalProperties": false + }, + "description": "Writes that were not sent, in the order the run reached them." + }, + "allowed": { + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "description": "Workflow whose block it was: the run workflow, or a child workflow it called." + }, + "blockId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block id in that workflow; null when the call named no block." + }, + "block": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block display name; null when the call named no block." + }, + "tool": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Tool sent; null when the whole block ran." + } + }, + "required": ["workflowId", "blockId", "block", "tool"], + "additionalProperties": false + }, + "description": "Writes sent for real because `run.allowBlocks` named their block, once per block and tool." + }, + "unchecked": { + "type": "array", + "items": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "description": "Workflow whose block it was: the run workflow, or a child workflow it called." + }, + "blockId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block id in that workflow; null when the call named no block." + }, + "block": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Block display name; null when the call named no block." + }, + "reason": { + "type": "string", + "description": "Why the run cannot see what this code changed." + } + }, + "required": ["workflowId", "blockId", "block", "reason"], + "additionalProperties": false + }, + "description": "Blocks whose code ran for real, once per block: a Function block's code, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model wrote, which may make network calls the run cannot see." + }, + "omitted": { + "type": "object", + "properties": { + "stubbed": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Writes left out of `stubbed`." + }, + "allowed": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Writes left out of `allowed`." + }, + "unchecked": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991, + "description": "Blocks left out of `unchecked`." + } + }, + "required": ["stubbed", "allowed", "unchecked"], + "additionalProperties": false, + "description": "Entries each list left out once it held 50." + } + }, + "required": ["stubbed", "allowed", "unchecked", "omitted"], + "additionalProperties": false, + "title": "Workflow run side effects", + "description": "What a dry run did with each write it reached." + }, + "WorkflowDryRun": { + "type": "object", + "properties": { + "allowBlocks": { + "type": "array", + "items": { + "type": "string", + "description": "Block id." + }, + "description": "Blocks whose writes the run sent (`run.allowBlocks`), by id." + }, + "mockedBlocks": { + "type": "array", + "items": { + "type": "string", + "description": "Block id." + }, + "description": "Blocks the run answered with fixed outputs (`run.mocks`), by id. Only the ids are recorded, so a rerun passes the outputs again." + } + }, + "required": ["allowBlocks", "mockedBlocks"], + "additionalProperties": false, + "title": "Workflow dry run", + "description": "The blocks a dry run sent and mocked, by id, which a rerun of it names again; never a mock output." + }, "WorkflowRunResult": { "type": "object", "properties": { @@ -17325,6 +17550,14 @@ } ], "description": "Where the run waits when `status` is `paused`; null otherwise." + }, + "sideEffects": { + "description": "What a dry run (`run.dry`) did with each write it reached, whatever its status; absent otherwise.", + "$ref": "#/components/schemas/WorkflowRunSideEffects" + }, + "dryRun": { + "description": "A dry run's allowed and mocked blocks (`run.dry`); absent for any other run.", + "$ref": "#/components/schemas/WorkflowDryRun" } }, "required": [ @@ -17511,7 +17744,7 @@ "sourceRunId": { "type": "string", "minLength": 1, - "description": "Run in this workflow whose persisted execution state supplies upstream block results. Missing or expired state returns 404." + "description": "Run in this workflow whose persisted execution state supplies upstream block results. Missing or expired state returns 404. A test run (a dry run, or a workflow test) holds placeholders for the writes it did not send, so it is the source only of a `dry` run." } }, "required": ["type", "blockId", "sourceRunId"], @@ -17523,6 +17756,37 @@ "description": "Saved workflow block after which the run stops (its id, display name or reference key); downstream blocks do not execute. Must not be inside a loop or parallel. If a router, condition, or untaken error path routes the run away from the block, the run fails as soon as that is decided; no further block starts, though blocks already running finish. With a block entry naming the same block, re-runs only that block against the source run.", "type": "string", "minLength": 1 + }, + "dry": { + "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes), listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`.", + "type": "boolean" + }, + "allowBlocks": { + "description": "Blocks (id, display name or reference key) of this workflow whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block, or a block that runs another workflow (a Workflow or custom block), cannot be allowed. Allowing an Agent sends only its own tool calls: a workflow or custom block it calls stays stubbed.", + "maxItems": 50, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + }, + "mocks": { + "description": "Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`. A locked block (or one inside a locked loop or parallel) cannot be mocked. A mock is data: it cannot set a field the run’s execution, trace or billing reads (`cost`, `tokens`, `model`, `providerTiming`, `toolCalls`, `executionData`, `childTraceSpans`, `childWorkflowId`, `childWorkflowSnapshotId`, `childDeploymentVersionId`, or any field starting with `_`). The run records only which blocks were mocked, so a rerun passes the outputs again; its log shows a mocked block’s output like any other block’s.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Output field." + }, + "description": "Output object that answers the block instead of its handler." + }, + "maxProperties": 50 } }, "required": ["source"], @@ -18403,6 +18667,17 @@ } ], "description": "Run-produced files when `includeOutput=true`, or null when not requested or execution data is hidden by organization permission groups." + }, + "dryRun": { + "anyOf": [ + { + "$ref": "#/components/schemas/WorkflowDryRun" + }, + { + "type": "null" + } + ], + "description": "A failed dry run's allowed and mocked blocks, by id, which a rerun of it names again; null for any other run, or when execution data is hidden by organization permission groups." } }, "required": [ @@ -18419,7 +18694,8 @@ "error", "output", "blockOutputs", - "files" + "files", + "dryRun" ], "additionalProperties": false, "title": "Workflow run status", @@ -18466,7 +18742,8 @@ "downloadPath": "/api/v2/workflows/3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36/runs/run_8f14e45f-ceea-467f-a/files/file_1a2b3c", "base64": null } - ] + ], + "dryRun": null } } ] 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 2d54ea85391..027e08ddc3e 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts @@ -138,6 +138,8 @@ function presentRun(result: ExecuteWorkflowServiceRun) { endedAt: result.endedAt, durationMs: result.durationMs, executionTimeoutSeconds: executionTimeoutSeconds(result.executionTimeoutMs), + sideEffects: result.sideEffects, + dryRun: result.dryRun, output: result.output ?? null, blockOutputs: result.blockOutputs ?? null, paused: presentV2RunPause(result.paused), @@ -549,6 +551,9 @@ export const POST = withRouteHandler( blockId: manualRun.entry.blockId, sourceRunId: manualRun.entry.sourceRunId, stopAfterBlockId: manualRun.stopAfterBlockId, + dry: manualRun.dry, + allowBlocks: manualRun.allowBlocks, + mocks: manualRun.mocks, }, request: req, }) @@ -562,6 +567,9 @@ export const POST = withRouteHandler( triggerBlockId: manualRun.entry?.blockId, useMockPayload: manualRun.entry?.useMockPayload === true, stopAfterBlockId: manualRun.stopAfterBlockId, + dry: manualRun.dry, + allowBlocks: manualRun.allowBlocks, + mocks: manualRun.mocks, }, request: req, }) 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 7e2e5b9aa16..ea14a294680 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 @@ -66,6 +66,7 @@ const baseStatus = { finalOutput: null, blockOutputs: null, files: null, + dryRun: null, } describe('v2 run detail and cancel adapters', () => { 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 fcaf4a3e6cd..c38294bb99c 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 @@ -61,6 +61,7 @@ export const GET = defineV2JsonRoute({ output: status.finalOutput, blockOutputs: status.blockOutputs, files: status.files, + dryRun: status.dryRun, }, }), }) diff --git a/apps/sim/app/api/workflows/[id]/execute/route.ts b/apps/sim/app/api/workflows/[id]/execute/route.ts index 31ca931b575..dc735847632 100644 --- a/apps/sim/app/api/workflows/[id]/execute/route.ts +++ b/apps/sim/app/api/workflows/[id]/execute/route.ts @@ -37,6 +37,7 @@ import { isTimeoutAbortReason, isTimeoutError, } from '@/lib/core/execution-limits' +import { OrchestrationError, statusForOrchestrationError } from '@/lib/core/orchestration/types' import { isCrossSiteSessionRequest } from '@/lib/core/security/same-origin' import { generateRequestId } from '@/lib/core/utils/request' import { SSE_HEADERS } from '@/lib/core/utils/sse' @@ -859,15 +860,23 @@ async function handleExecutePost( if (rawRunFromBlock.executionId) { const { getExecutionStateForWorkflow, getLatestExecutionStateWithExecutionId } = await import('@/lib/workflows/executor/execution-state') - const sourceExecution = - rawRunFromBlock.executionId === 'latest' - ? await getLatestExecutionStateWithExecutionId(workflowId) - : { - executionId: rawRunFromBlock.executionId, - state: await getExecutionStateForWorkflow(rawRunFromBlock.executionId, workflowId), - } - const snapshot = sourceExecution?.state - if (!snapshot) { + let sourceExecution: { executionId: string; state: SerializableExecutionState } | null + if (rawRunFromBlock.executionId === 'latest') { + sourceExecution = await getLatestExecutionStateWithExecutionId(workflowId) + } else { + let state: SerializableExecutionState | null + try { + state = await getExecutionStateForWorkflow(rawRunFromBlock.executionId, workflowId) + } catch (error) { + if (!(error instanceof OrchestrationError)) throw error + return NextResponse.json( + { error: error.message }, + { status: statusForOrchestrationError(error.code) } + ) + } + sourceExecution = state ? { executionId: rawRunFromBlock.executionId, state } : null + } + if (!sourceExecution) { if (rawRunFromBlock.sourceSnapshot && !isPublicApiAccess) { resolvedRunFromBlock = { startBlockId: rawRunFromBlock.startBlockId, @@ -891,7 +900,7 @@ async function handleExecutePost( } else { resolvedRunFromBlock = { startBlockId: rawRunFromBlock.startBlockId, - sourceSnapshot: snapshot, + sourceSnapshot: sourceExecution.state, sourceExecutionId: sourceExecution.executionId, } } diff --git a/apps/sim/blocks/registry.ts b/apps/sim/blocks/registry.ts index 4708c8fdf3e..2ecc739c25c 100644 --- a/apps/sim/blocks/registry.ts +++ b/apps/sim/blocks/registry.ts @@ -165,9 +165,19 @@ function versionCandidates(type: string): BlockConfig[] { return candidates } -/** Find the block whose `tools.access` contains the given tool id. */ +let blockByTool: Map | undefined + +/** Find the first block, in registry order, whose `tools.access` contains the given tool id. */ export function getBlockByToolName(toolName: string): BlockConfig | undefined { - return Object.values(BLOCK_REGISTRY).find((b) => b.tools?.access?.includes(toolName)) + if (!blockByTool) { + blockByTool = new Map() + for (const block of Object.values(BLOCK_REGISTRY)) { + for (const toolId of block.tools?.access ?? []) { + if (!blockByTool.has(toolId)) blockByTool.set(toolId, block) + } + } + } + return blockByTool.get(toolName) } /** diff --git a/apps/sim/executor/execution/block-executor.ts b/apps/sim/executor/execution/block-executor.ts index 96dcc1f1061..1279af29851 100644 --- a/apps/sim/executor/execution/block-executor.ts +++ b/apps/sim/executor/execution/block-executor.ts @@ -74,6 +74,7 @@ import { getIterationContext, } from '@/executor/utils/iteration-context' import { isJSONString } from '@/executor/utils/json' +import { mockOutputRefusal } from '@/executor/utils/mock-output' import { filterOutputForLog } from '@/executor/utils/output-filter' import { projectResolvedSecretDiagnosticError } from '@/executor/utils/resolved-secret-content-projection' import type { @@ -93,6 +94,7 @@ import { import { createAgentStreamPump } from '@/providers/stream-pump' import { isRunAbortError } from '@/providers/streaming-tool-loop-shared' import type { SerializedBlock } from '@/serializer/types' +import { redactSideEffectPayload } from '@/tools/side-effects' const logger = createLogger('BlockExecutor') @@ -285,6 +287,14 @@ export class BlockExecutor { const testHooks = this.contextExtensions.testHooks const mockedBlockId = node.metadata.originalBlockId ?? block.id const isMocked = !isSentinel && testHooks?.mocksBlock(mockedBlockId) === true + const sideEffects = isSentinel || isMocked ? undefined : this.contextExtensions.sideEffects + const site = sideEffects && { + workflowId: blockCtx.workflowId, + blockId: mockedBlockId, + blockName: block.metadata?.name ?? mockedBlockId, + blockType: block.metadata?.id ?? '', + } + const answeredBy = site && sideEffects?.answersBlock(site) ? sideEffects : undefined try { /** * Only the handler call is retried. A streaming handler returns before any @@ -303,6 +313,19 @@ export class BlockExecutor { inputDisplayRegistry ) } + if (answeredBy && site) { + return answeredBy.answerBlock({ + ...site, + input: () => + redactSideEffectPayload({ + payload: blockLog?.input ?? {}, + params: inputsForLog, + blockTypes: [site.blockType], + executionContext: blockCtx, + registry: inputDisplayRegistry, + }), + }) + } const invocationMetadata = retry ? { ...nodeMetadata, retry } : nodeMetadata return handler.executeWithNode ? handler.executeWithNode(blockCtx, block, resolvedInputs, invocationMetadata) @@ -982,8 +1005,11 @@ export class BlockExecutor { return { result: output } } - /** A test mock sees exactly what the block's execution log shows, never raw resolved secrets. */ - private resolveMockedBlock( + /** + * A test mock sees exactly what the block's execution log shows, never raw resolved secrets, + * and answers with data only ({@link mockOutputRefusal}). + */ + private async resolveMockedBlock( ctx: ExecutionContext, node: DAGNode, block: SerializedBlock, @@ -997,7 +1023,7 @@ export class BlockExecutor { if (projection && !projection.complete) { throw new Error(`Mocked block "${blockName}" has inputs whose secrets cannot be redacted`) } - return testHooks.resolveMock( + const output = await testHooks.resolveMock( { blockId, blockName, @@ -1009,6 +1035,9 @@ export class BlockExecutor { }, ctx.abortSignal ) + const refusal = mockOutputRefusal(`Mocked block "${blockName}"`, output) + if (refusal) throw new Error(refusal) + return output } /** Builds the log-facing input copy from resolver-recorded projections only. */ diff --git a/apps/sim/executor/execution/executor.ts b/apps/sim/executor/execution/executor.ts index b2f20695c85..da887cd2a68 100644 --- a/apps/sim/executor/execution/executor.ts +++ b/apps/sim/executor/execution/executor.ts @@ -470,6 +470,7 @@ export class DAGExecutor { enforceCredentialAccess: this.contextExtensions.enforceCredentialAccess, piiBlockOutputRedaction: this.contextExtensions.piiBlockOutputRedaction, testHooks: this.contextExtensions.testHooks, + sideEffects: this.contextExtensions.sideEffects, blockStates: state.getBlockStates(), blockLogs: restoredBlockLogs, /* diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index 36265be745e..21ef948cd3a 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -87,6 +87,8 @@ export interface ExecutionMetadata { allowLargeValueWorkflowScope?: boolean callChain?: string[] correlation?: AsyncExecutionCorrelation + /** A dry run's allowed and mocked blocks, recorded on its log so a rerun can name them again. */ + dryRun?: DryRunOptions executionMode?: 'sync' | 'stream' | 'async' /** * Deployed-chat thinking policy half of the SSE dual gate. Persisted so HITL @@ -318,6 +320,72 @@ export interface ExecutionTestHooks { recordSpy(call: { blockId: string; input: unknown; output: unknown }): void } +/** A dry run's allowed and mocked blocks of the workflow it started, by id; never a mock's output. */ +export interface DryRunOptions { + allowBlocks: string[] + mockedBlocks: string[] +} + +/** Where a call that may change state outside the run was made: a block of one executing workflow. */ +export interface SideEffectSite { + workflowId: string + /** The workflow block id, never a parallel-branch clone id; null when the caller named none. */ + blockId: string | null + blockName: string | null + blockType: string | null +} + +/** A block of one executing workflow, which the block executor always knows. */ +export interface SideEffectBlockSite extends SideEffectSite { + blockId: string + blockName: string + blockType: string +} + +/** A write tool call the run answers instead of sending, with the request it would have sent. */ +export interface StubbedToolCall extends SideEffectSite { + toolId: string + /** The request with credentials, secrets and PII redacted; null when that cannot be vouched for. */ + request: Record | null +} + +/** A block the run answers instead of running its handler. */ +export interface AnsweredBlockCall extends SideEffectBlockSite { + /** + * The inputs its log shows, redacted like a stubbed write's request (null when that cannot be + * vouched for); built only when the block is recorded as stubbed rather than mocked. + */ + input: () => Promise | null> +} + +/** + * How a run treats work that may change state outside it: a dry run, or a workflow test's + * unmocked writes. Unlike {@link ExecutionTestHooks}, every child execution inherits it, including + * a workflow an Agent calls as a tool, so a child's writes follow the run that started it. Tool + * calls meet it in `tools/side-effects.ts`; the block executor consults it before each block's + * handler. Its presence alone also means the run keeps nothing beyond its log: an Agent writes no + * memory, and files uploaded to a provider's Files API are deleted once the call settles. Where + * only the log is at hand, the `test` trigger says the same. + */ +export interface SideEffectPolicy { + /** + * Whether this write tool call is sent or answered with {@link stubWrite}. Records a sent call + * the run should report: an allowed block's write, or code that runs unchecked. + */ + decideWrite(call: SideEffectSite & { toolId: string }): 'send' | 'stub' + /** + * Records code that ran for real, which can make network calls the run cannot see: code run + * through `function_execute`, or a While or Do While loop's condition. + */ + ranCode(site: SideEffectSite): void + /** Records a write that was not sent and returns the placeholder output answering it. */ + stubWrite(call: StubbedToolCall): Record + /** Whether this block is answered with {@link answerBlock} instead of running its handler. */ + answersBlock(block: SideEffectBlockSite): boolean + /** The output answering a block that does not run: its mock, or a recorded placeholder. */ + answerBlock(call: AnsweredBlockCall): Promise +} + export interface ContextExtensions { workspaceId?: string executionId?: string @@ -418,6 +486,7 @@ export interface ContextExtensions { stopAfterBlockId?: string testHooks?: ExecutionTestHooks + sideEffects?: SideEffectPolicy /** * Ordered list of workflow IDs in the current call chain, used for cycle detection. diff --git a/apps/sim/executor/handlers/agent/handler.ts b/apps/sim/executor/handlers/agent/handler.ts index 90c44d3e588..b509d30499f 100644 --- a/apps/sim/executor/handlers/agent/handler.ts +++ b/apps/sim/executor/handlers/agent/handler.ts @@ -22,7 +22,11 @@ import { assertValidMcpServerToolBindings, MCP_SERVER_ADVANCED_TOOL_TYPE } from import { resolveMcpToolBinding } from '@/lib/mcp/tool-binding' import type { McpToolSchema } from '@/lib/mcp/types' import { createMcpToolId } from '@/lib/mcp/utils' -import { type AgentTurnSession, openAgentTurnSession } from '@/lib/memory/agent-turn-session' +import { + type AgentTurnSession, + findStoredAgentConversation, + openAgentTurnSession, +} from '@/lib/memory/agent-turn-session' import { MEMORY } from '@/lib/memory/constants' import { createAgentMemoryRetrievalTool } from '@/lib/memory/retrieval-tool' import { @@ -182,6 +186,18 @@ interface IndexedToolInput { toolIndex: number } +/** + * Whether this Agent writes its turn to memory. Under a run's side-effect policy (a dry run, or a + * workflow test) it writes nothing, so a conversation is left as the run found it, but it reads + * the conversation as a live run would: its history, and the memory retrieval tool. + */ +function persistsMemory(ctx: ExecutionContext, inputs: AgentInputs): boolean { + return Boolean(inputs.memoryType && inputs.memoryType !== 'none' && !ctx.sideEffects) +} + +/** A stored conversation an Agent reads without opening a turn in it. */ +type StoredAgentConversation = Awaited> + /** * Removes the sim-auto identity preamble from the system messages built for a * routed primary. A fallback the builder named is not a pool model, so it must @@ -230,6 +246,8 @@ interface ExecuteAcrossModelsConfig { resultRegistry: ResolvedSecretTraceRegistry | undefined providerErrorRegistry: ResolvedSecretTraceRegistry | undefined agentConversation?: AgentTurnSession + /** The stored conversation a run that writes no memory reads ({@link findStoredAgentConversation}). */ + storedConversation?: StoredAgentConversation } interface FormattedAgentTools { @@ -518,9 +536,9 @@ export class AgentBlockHandler implements BlockHandler { } const streamingConfig = this.getStreamingConfig(ctx, block) + const writesMemory = persistsMemory(ctx, filteredInputs) const agentConversation = - filteredInputs.memoryType && - filteredInputs.memoryType !== 'none' && + writesMemory && filteredInputs.conversationId && nodeMetadata && nodeMetadata.executionOrder !== undefined @@ -532,13 +550,25 @@ export class AgentBlockHandler implements BlockHandler { conversationId: filteredInputs.conversationId, }) : undefined + const storedConversation = + !writesMemory && + filteredInputs.memoryType && + filteredInputs.memoryType !== 'none' && + filteredInputs.conversationId + ? await findStoredAgentConversation({ + ctx, + conversationId: filteredInputs.conversationId, + }) + : undefined const messagesWithInputFiles = await this.buildMessages( ctx, filteredInputs, modelInputs, skillMetadata, fileProjection, - agentConversation + writesMemory, + agentConversation, + storedConversation ) /** * The primary hydrates before the registries settle and fork, as it always @@ -623,6 +653,7 @@ export class AgentBlockHandler implements BlockHandler { resultRegistry, providerErrorRegistry, agentConversation, + storedConversation, }) if (servedRegistry) ctx.resolvedSecretTraceRegistry = servedRegistry @@ -641,7 +672,7 @@ export class AgentBlockHandler implements BlockHandler { if (this.isStreamingExecution(result)) { const streamingResult = result as StreamingExecution streamingResult.diagnosticResolvedSecretTraceRegistry = providerErrorRegistry - if (filteredInputs.memoryType && filteredInputs.memoryType !== 'none') { + if (writesMemory) { return this.wrapStreamForMemoryPersistence( ctx, filteredInputs, @@ -653,7 +684,7 @@ export class AgentBlockHandler implements BlockHandler { return streamingResult } - if (filteredInputs.memoryType && filteredInputs.memoryType !== 'none') { + if (writesMemory) { await this.persistResponseToMemory( ctx, filteredInputs, @@ -1442,7 +1473,10 @@ export class AgentBlockHandler implements BlockHandler { modelInputs: AgentInputs, skillMetadata: Array<{ name: string; description: string }>, fileProjection: ReturnType, - agentConversation?: AgentTurnSession + /** Whether this turn is written to memory ({@link persistsMemory}). */ + writesMemory: boolean, + agentConversation?: AgentTurnSession, + storedConversation?: StoredAgentConversation ): Promise { const messages: Message[] = [] const memoryEnabled = inputs.memoryType && inputs.memoryType !== 'none' @@ -1464,9 +1498,9 @@ export class AgentBlockHandler implements BlockHandler { inputs, fileProjection.projectedNameByFile, { - richHistory: Boolean(agentConversation), + richHistory: Boolean(agentConversation ?? storedConversation), excludeTurnId: agentConversation?.turnId, - memoryId: agentConversation?.memoryId, + memoryId: agentConversation?.memoryId ?? storedConversation?.memoryId, } ) const hasExisting = memoryMessages.length > 0 @@ -1600,6 +1634,7 @@ export class AgentBlockHandler implements BlockHandler { fileProjection.projectedNameByFile, fileProjection.directNameInputPaths ) + if (!writesMemory) return messagesWithFiles /** Persist the complete turn before provider hydration adds bytes or transient handles. */ const lastUserMessage = messages @@ -2684,7 +2719,8 @@ export class AgentBlockHandler implements BlockHandler { resultRegistry, config.providerErrorRegistry, savedCredentials?.(), - config.agentConversation + config.agentConversation, + config.storedConversation ) if ((hasNext || config.retryPrimaryOnStreamStart) && this.isStreamingExecution(result)) { result = await this.primeStreamingExecution(result as StreamingExecution) @@ -2888,7 +2924,8 @@ export class AgentBlockHandler implements BlockHandler { modelRuntimeRegistry: ResolvedSecretTraceRegistry | undefined, providerErrorRegistry: ResolvedSecretTraceRegistry | undefined, savedCredentials: Promise | undefined, - agentConversation?: AgentTurnSession + agentConversation?: AgentTurnSession, + storedConversation?: StoredAgentConversation ): Promise { const providerId = providerRequest.provider const model = providerRequest.model @@ -2897,11 +2934,9 @@ export class AgentBlockHandler implements BlockHandler { const credentials: BlockModelCredentials = (await savedCredentials) ?? {} const { blockData, blockNameMapping } = collectBlockData(ctx) - const agentMemoryRetrieval = agentConversation?.memoryId - ? createAgentMemoryRetrievalTool({ - executionContext: ctx, - memoryId: agentConversation.memoryId, - }) + const memoryId = agentConversation?.memoryId ?? storedConversation?.memoryId + const agentMemoryRetrieval = memoryId + ? createAgentMemoryRetrievalTool({ executionContext: ctx, memoryId }) : undefined const response = await executeProviderRequest( @@ -2957,9 +2992,10 @@ export class AgentBlockHandler implements BlockHandler { executionContext: ctx, agentConversation, agentMemoryRetrieval, - agentMemoryContext: agentConversation - ? { historyTokens: providerRequest.memoryHistoryTokens } - : undefined, + agentMemoryContext: + agentConversation || storedConversation + ? { historyTokens: providerRequest.memoryHistoryTokens } + : undefined, } ) diff --git a/apps/sim/executor/handlers/agent/memory-harness.integration.ts b/apps/sim/executor/handlers/agent/memory-harness.integration.ts index 896737de95d..7c18d0b19cc 100644 --- a/apps/sim/executor/handlers/agent/memory-harness.integration.ts +++ b/apps/sim/executor/handlers/agent/memory-harness.integration.ts @@ -532,7 +532,7 @@ describe('Agent memory through PostgreSQL, storage, and provider transports', () return Response.json({ id: 'file-harness' }) }) vi.stubGlobal('fetch', upload) - await uploadLargeFilesToProvider(largeRequest, provider, firstContext) + await uploadLargeFilesToProvider(largeRequest, provider, firstContext, []) expect(upload).toHaveBeenCalledOnce() expect(largeFile.providerFileId).toBe('file-harness') } diff --git a/apps/sim/executor/handlers/pi/handler.test.ts b/apps/sim/executor/handlers/pi/handler.test.ts index b5493f04d72..0a70ed35cfb 100644 --- a/apps/sim/executor/handlers/pi/handler.test.ts +++ b/apps/sim/executor/handlers/pi/handler.test.ts @@ -229,7 +229,12 @@ describe('PiBlockHandler', () => { it('adds successful Function tool cost once to a non-streaming Local Dev result', async () => { mockBuildSimToolSpecs.mockImplementation( - async (_ctx: unknown, _tools: unknown, functionToolCost: { total: number }) => { + async ( + _ctx: unknown, + _blockId: string, + _tools: unknown, + functionToolCost: { total: number } + ) => { functionToolCost.total += 0.125 return [] } @@ -553,7 +558,12 @@ describe('PiBlockHandler', () => { it('streams text when the block is selected for streaming output', async () => { mockBuildSimToolSpecs.mockImplementation( - async (_ctx: unknown, _tools: unknown, functionToolCost: { total: number }) => { + async ( + _ctx: unknown, + _blockId: string, + _tools: unknown, + functionToolCost: { total: number } + ) => { functionToolCost.total += 0.25 return [] } diff --git a/apps/sim/executor/handlers/pi/handler.ts b/apps/sim/executor/handlers/pi/handler.ts index 13eff86979b..a66c9c97ad3 100644 --- a/apps/sim/executor/handlers/pi/handler.ts +++ b/apps/sim/executor/handlers/pi/handler.ts @@ -301,7 +301,7 @@ export class PiBlockHandler implements BlockHandler { const usePrivateKey = inputs.authMethod === 'privateKey' const port = parseOptionalNumberInput(inputs.port, 'port', { integer: true, min: 1 }) ?? 22 const sandboxCost: SandboxCostSink = { total: 0 } - const tools = await buildSimToolSpecs(ctx, inputs.tools, sandboxCost) + const tools = await buildSimToolSpecs(ctx, block.id, inputs.tools, sandboxCost) const params: PiLocalRunParams = { ...contextualBase, mode: 'local', diff --git a/apps/sim/executor/handlers/pi/local/sim-tools.test.ts b/apps/sim/executor/handlers/pi/local/sim-tools.test.ts index 62de6856b0e..a175940bb00 100644 --- a/apps/sim/executor/handlers/pi/local/sim-tools.test.ts +++ b/apps/sim/executor/handlers/pi/local/sim-tools.test.ts @@ -60,7 +60,7 @@ describe('buildSimToolSpecs', () => { }) mockExecuteTool.mockResolvedValue({ success: true, output: 'sent' }) - const specs = await buildSimToolSpecs(executionContext(undefined), [ + const specs = await buildSimToolSpecs(executionContext(undefined), 'pi-1', [ { type: 'gmail', operation: 'send', usageControl: 'auto' }, { type: 'gmail', operation: 'send', usageControl: 'auto' }, ]) @@ -95,7 +95,7 @@ describe('buildSimToolSpecs', () => { resolvedSecretTraceRegistry: new ResolvedSecretTraceRegistry(), } as ExecutionContext - const [spec] = await buildSimToolSpecs(trustedCtx, [ + const [spec] = await buildSimToolSpecs(trustedCtx, 'pi-1', [ { type: 'exa', operation: 'exa_search', usageControl: 'auto' }, ]) // An attacker-influenced tool arg tries to spoof the execution context. @@ -127,6 +127,7 @@ describe('buildSimToolSpecs', () => { const functionToolCost = { total: 0 } const [functionSpec, searchSpec] = await buildSimToolSpecs( executionContext(undefined), + 'pi-1', [ { type: 'function', operation: 'execute', usageControl: 'auto' }, { type: 'exa', operation: 'exa_search', usageControl: 'auto' }, @@ -179,7 +180,7 @@ describe('buildSimToolSpecs', () => { ]) registry.recordResolved('API_KEY', 'secret-value') - const [spec] = await buildSimToolSpecs(executionContext(registry), toolInput) + const [spec] = await buildSimToolSpecs(executionContext(registry), 'pi-1', toolInput) await expect(spec.execute({})).resolves.toEqual({ text: JSON.stringify({ authorization: 'Bearer {{API_KEY}}' }), @@ -216,7 +217,7 @@ describe('buildSimToolSpecs', () => { registry.recordResolvedAtInputPath('UNRELATED', 'Test', ['task']) registry.recordResolvedInputProjection(['task'], 'Test', '{{UNRELATED}}') - const [spec] = await buildSimToolSpecs(executionContext(registry), tools) + const [spec] = await buildSimToolSpecs(executionContext(registry), 'pi-1', tools) await expect(spec.execute({ query: 'pi' })).resolves.toEqual({ text: JSON.stringify({ selected: '{{API_KEY}}', unrelated: 'Test' }), @@ -236,7 +237,7 @@ describe('buildSimToolSpecs', () => { const registry = new ResolvedSecretTraceRegistry([ { name: 'API_KEY', plaintext: 'secret-value', encryptedValue: 'ciphertext' }, ]) - const [spec] = await buildSimToolSpecs(executionContext(registry), toolInput) + const [spec] = await buildSimToolSpecs(executionContext(registry), 'pi-1', toolInput) mockExecuteTool.mockImplementationOnce(async (_toolId, _params, options) => { await options.resolvedSecretTraceRegistry.importProvenance( @@ -283,7 +284,7 @@ describe('buildSimToolSpecs', () => { }) const registry = new ResolvedSecretTraceRegistry() registry.markIncomplete('unspecified') - const [spec] = await buildSimToolSpecs(executionContext(registry), toolInput) + const [spec] = await buildSimToolSpecs(executionContext(registry), 'pi-1', toolInput) const result = await spec.execute({}) diff --git a/apps/sim/executor/handlers/pi/local/sim-tools.ts b/apps/sim/executor/handlers/pi/local/sim-tools.ts index bcfab3229a8..6f3d44eb587 100644 --- a/apps/sim/executor/handlers/pi/local/sim-tools.ts +++ b/apps/sim/executor/handlers/pi/local/sim-tools.ts @@ -107,6 +107,7 @@ function projectToolResult( function buildSimToolSpec( ctx: ExecutionContext, + blockId: string, inputTools: ToolInput[], provider: ProviderToolConfig, toolIndex: number, @@ -211,6 +212,7 @@ function buildSimToolSpec( // Trusted execution context is written last so model arguments cannot override it. _context: { workflowId: ctx.workflowId, + blockId, workspaceId: ctx.workspaceId, executionId: ctx.executionId, userId: ctx.userId, @@ -267,6 +269,8 @@ function buildSimToolSpec( */ export async function buildSimToolSpecs( ctx: ExecutionContext, + /** The Pi block, the block its tool calls act for. */ + blockId: string, inputTools: unknown, sandboxCost?: SandboxCostSink ): Promise { @@ -312,6 +316,6 @@ export async function buildSimToolSpecs( await annotateDuplicateToolBindings(ctx, providers) assignProviderToolIdentities(providers) return configuredTools.map(({ provider, toolIndex }) => - buildSimToolSpec(ctx, inputTools, provider, toolIndex, sandboxCost) + buildSimToolSpec(ctx, blockId, inputTools, provider, toolIndex, sandboxCost) ) } diff --git a/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts b/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts index 407b64e5f5d..ea8a9e7e8a2 100644 --- a/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts +++ b/apps/sim/executor/handlers/workflow/custom-block-tool-runner.ts @@ -4,7 +4,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' import { isPlainRecord, isRecordLike } from '@sim/utils/object' import type { BillingAttributionSnapshot } from '@/lib/billing/core/attribution' -import type { PiiBlockOutputRedaction } from '@/executor/execution/types' +import type { PiiBlockOutputRedaction, SideEffectPolicy } from '@/executor/execution/types' import { WorkflowBlockHandler } from '@/executor/handlers/workflow/handler' import type { ExecutionContext, @@ -82,6 +82,8 @@ export function buildCustomBlockExecutionContext( piiBlockOutputRedaction?: PiiBlockOutputRedaction /** The invoking run's unrecorded model spend, which a child billed on its log adds to. */ unrecordedModelCost?: UnrecordedModelCost + /** The invoking run's side-effect policy, which the child's writes follow. */ + sideEffects?: SideEffectPolicy } ): ExecutionContext { // Prefer the invoking agent run's ids so correlation and cancellation both @@ -105,6 +107,7 @@ export function buildCustomBlockExecutionContext( environmentVariables: options.environmentVariables, piiBlockOutputRedaction: options.piiBlockOutputRedaction, unrecordedModelCost: options.unrecordedModelCost, + sideEffects: options.sideEffects, blockStates: new Map(), executedBlocks: new Set(), blockLogs: [], diff --git a/apps/sim/executor/handlers/workflow/handler.ts b/apps/sim/executor/handlers/workflow/handler.ts index a2d8bc4cf4c..baa82628589 100644 --- a/apps/sim/executor/handlers/workflow/handler.ts +++ b/apps/sim/executor/handlers/workflow/handler.ts @@ -931,6 +931,9 @@ export class WorkflowBlockHandler implements BlockHandler { // A workflow test's mocks and spies reach every child it runs, except a custom // block's: that workflow is the publisher's, so the test mocks the block whole. testHooks: isCustomBlock ? undefined : ctx.testHooks, + // Every child inherits the run's side-effect policy, a custom block's included: the + // policy answers a custom block whole, so its child never runs under it. + sideEffects: ctx.sideEffects, callChain: childCallChain, // A custom block's own session markers and the parent's live stream, fanned // out together — see `childCallbacks` above for why this is not two spreads. diff --git a/apps/sim/executor/handlers/workflow/tool-runner.ts b/apps/sim/executor/handlers/workflow/tool-runner.ts index c506fc97f92..25a09d367ba 100644 --- a/apps/sim/executor/handlers/workflow/tool-runner.ts +++ b/apps/sim/executor/handlers/workflow/tool-runner.ts @@ -6,7 +6,7 @@ import { isRecordLike } from '@sim/utils/object' import { calculateCostSummary } from '@/lib/logs/execution/logging-factory' import type { TraceSpan } from '@/lib/logs/types' import { ChildWorkflowError } from '@/executor/errors/child-workflow-error' -import type { PiiBlockOutputRedaction } from '@/executor/execution/types' +import type { PiiBlockOutputRedaction, SideEffectPolicy } from '@/executor/execution/types' import { buildCustomBlockExecutionContext, type CustomBlockExecutorContext, @@ -100,6 +100,7 @@ export async function runWorkflowTool( principal?: WorkflowExecutionPrincipal piiBlockOutputRedaction?: PiiBlockOutputRedaction unrecordedModelCost?: UnrecordedModelCost + sideEffects?: SideEffectPolicy } ): Promise { if (!params.workflowId) { diff --git a/apps/sim/executor/orchestrators/loop.ts b/apps/sim/executor/orchestrators/loop.ts index d2507fadec0..ee12c24c1af 100644 --- a/apps/sim/executor/orchestrators/loop.ts +++ b/apps/sim/executor/orchestrators/loop.ts @@ -10,7 +10,13 @@ import { generateRequestId } from '@/lib/core/utils/request' import { executeInIsolatedVM } from '@/lib/execution/isolated-vm' import { compactSubflowResults } from '@/lib/execution/payloads/serializer' import { isLikelyReferenceSegment } from '@/lib/workflows/sanitization/references' -import { CONTROL_BACK_EDGE_HANDLES, DEFAULTS, EDGE, PARALLEL } from '@/executor/constants' +import { + BlockType, + CONTROL_BACK_EDGE_HANDLES, + DEFAULTS, + EDGE, + PARALLEL, +} from '@/executor/constants' import type { DAG } from '@/executor/dag/builder' import type { EdgeManager } from '@/executor/execution/edge-manager' import type { LoopScope } from '@/executor/execution/state' @@ -28,6 +34,7 @@ import { extractBaseBlockId, extractLoopIdFromSentinel, extractParallelIdFromSentinel, + stripOuterBranchSuffix, } from '@/executor/utils/subflow-node-id-codec' import { mergeSubflowSecretProvenance } from '@/executor/utils/subflow-secret-provenance' import type { VariableResolver } from '@/executor/variables/resolver' @@ -805,6 +812,15 @@ export class LoopOrchestrator { return match }) + const workflowLoopId = stripOuterBranchSuffix(loopId) + ctx.sideEffects?.ranCode({ + workflowId: ctx.workflowId, + blockId: workflowLoopId, + blockName: + ctx.workflow?.blocks.find((block) => block.id === workflowLoopId)?.metadata?.name ?? + workflowLoopId, + blockType: BlockType.LOOP, + }) vmResult = await executeInIsolatedVM({ code: `return Boolean(${evaluatedCondition})`, params: {}, diff --git a/apps/sim/executor/types.ts b/apps/sim/executor/types.ts index 75cc34c5811..c589d8b7e6a 100644 --- a/apps/sim/executor/types.ts +++ b/apps/sim/executor/types.ts @@ -11,6 +11,7 @@ import type { ParentIteration, PiiBlockOutputRedaction, SerializableExecutionState, + SideEffectPolicy, } from '@/executor/execution/types' import type { ResolvedSecretTraceProvenanceV1, @@ -451,6 +452,8 @@ export interface ExecutionContext { workflowId: string /** Set during a workflow test run; Agent tool calls consult it before calling the tool. */ testHooks?: ExecutionTestHooks + /** Set during a dry run or workflow test; inherited by every child execution. */ + sideEffects?: SideEffectPolicy workspaceId?: string executionId?: string largeValueExecutionIds?: string[] diff --git a/apps/sim/executor/utils/mock-output.ts b/apps/sim/executor/utils/mock-output.ts new file mode 100644 index 00000000000..6e9e6211e60 --- /dev/null +++ b/apps/sim/executor/utils/mock-output.ts @@ -0,0 +1,20 @@ +import { SPAN_SOURCE_OUTPUT_FIELDS } from '@/lib/logs/execution/trace-spans/factory' + +/** + * Whether a block's own handler alone may set this top-level output field: a `_` field steers + * the executor (a pause, a child-run link), and the run's trace and bill are built from the + * {@link SPAN_SOURCE_OUTPUT_FIELDS}. + */ +export function isRunControlledOutputField(field: string): boolean { + return field.startsWith('_') || SPAN_SOURCE_OUTPUT_FIELDS.has(field) +} + +/** + * Why a mocked output, named by `label`, is refused; null when it sets only data. A mock (a dry + * run's `run.mocks`, or a workflow test's `mockBlock`) is data, never run control or billing. + */ +export function mockOutputRefusal(label: string, output: Record): string | null { + const fields = Object.keys(output).filter(isRunControlledOutputField) + if (fields.length === 0) return null + return `${label} sets ${fields.join(', ')}: a mock is data, so it cannot set a field the run's execution, trace or billing reads (${[...SPAN_SOURCE_OUTPUT_FIELDS].join(', ')}, or any field starting with "_").` +} diff --git a/apps/sim/lib/api/contracts/mothership-management-tools.ts b/apps/sim/lib/api/contracts/mothership-management-tools.ts index e4d60e2a1a2..9951634043e 100644 --- a/apps/sim/lib/api/contracts/mothership-management-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-management-tools.ts @@ -25,7 +25,7 @@ export const managementToolContracts = [ route: 'sim', scope: 'all', description: - 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs; mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', + 'Create and run the selected workspace\u2019s workflow tests. create takes a name, a one-line title for the concern, and an optional description, and returns tests/.test.js; write the cases into that file with the file tools. A test file is plain vitest: import { describe, it, expect, vi } from "vitest" and { runWorkflow, mockBlock, mockTool, spyOnBlock } from "sim:test", one top-level describe, an it per case. runWorkflow(name, input) runs a workflow and returns { output } (pass { trigger: \"Trigger block name\" } as a third argument when it has several triggers); mockBlock(blockName) returns a vi.fn whose value replaces that block\u2019s output and records its inputs (data only: no cost, tokens, model, providerTiming, toolCalls or field starting with _, which the run\u2019s trace and billing read); mockTool(toolId) or mockTool(agentBlockName, toolId) answers an Agent\u2019s calls to that tool the same way while the model still runs, naming built-in tools by id (slack_message), MCP tools by server as mockTool({ mcp: "Server name", tool: "tool_name" }), and custom tools by title as mockTool({ customTool: "Title" }); .mockSampleOutput({ ...overrides }) on either mock makes it answer with a placeholder output shaped like the real one, with your fields merged in; a write tool call no mock answers is not sent but answered with such a placeholder, as in a dry run (a custom block no mock answers is answered whole), while reads run for real; await expect(value).toMatchRubric(rubric) asks a model judge for pass or fail. Every write is checked and refused if the file does not load. run takes a version (draft while editing, deployed before shipping), waits, and returns each file\u2019s failures with line numbers and messages. list and get report status; update changes title or description.', inputSchema: mothershipTestsInputSchema, }, { diff --git a/apps/sim/lib/api/contracts/v2/openapi/workflows.ts b/apps/sim/lib/api/contracts/v2/openapi/workflows.ts index 32077cd08dc..d2390d7a0e6 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workflows.ts @@ -1559,6 +1559,7 @@ const declaredRoutes = [ base64: null, }, ], + dryRun: null, }, }, ] diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 29e3ded0daa..b5786408496 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1635,6 +1635,9 @@ export type V2ExecutionError = z.output export const EXECUTE_OPTION_CONSTRAINTS = 'Input descriptions specify compatible modes; invalid combinations return `400`.' +/** Blocks one run's `run.mocks` may answer. */ +const MAX_RUN_MOCKS = 50 + export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ z .object({ @@ -1686,7 +1689,7 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .string() .min(1, 'run.entry.sourceRunId cannot be empty') .describe( - 'Run in this workflow whose persisted execution state supplies upstream block results. Missing or expired state returns 404.' + 'Run in this workflow whose persisted execution state supplies upstream block results. Missing or expired state returns 404. A test run (a dry run, or a workflow test) holds placeholders for the writes it did not send, so it is the source only of a `dry` run.' ), }) .strict(), @@ -1702,6 +1705,34 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .describe( 'Saved workflow block after which the run stops (its id, display name or reference key); downstream blocks do not execute. Must not be inside a loop or parallel. If a router, condition, or untaken error path routes the run away from the block, the run fails as soon as that is decided; no further block starts, though blocks already running finish. With a block entry naming the same block, re-runs only that block against the source run.' ), + dry: z + .boolean() + .optional() + .describe( + "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a placeholder shaped like the tool's output and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes), listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`." + ), + allowBlocks: z + .array(z.string().min(1, 'run.allowBlocks entries cannot be empty')) + .max(50) + .optional() + .describe( + 'Blocks (id, display name or reference key) of this workflow whose writes a dry run sends for real, listed in `sideEffects.allowed`. Requires `dry`. A Human in the loop or Wait block, or a block that runs another workflow (a Workflow or custom block), cannot be allowed. Allowing an Agent sends only its own tool calls: a workflow or custom block it calls stays stubbed.' + ), + mocks: z + .record( + z.string(), + z + .record(z.string(), z.unknown().describe('Output field.')) + .describe('Output object that answers the block instead of its handler.') + ) + .refine((mocks) => Object.keys(mocks).length <= MAX_RUN_MOCKS, { + message: `run.mocks names at most ${MAX_RUN_MOCKS} blocks`, + }) + .meta({ maxProperties: MAX_RUN_MOCKS }) + .optional() + .describe( + 'Blocks of this workflow (keyed by id, display name or reference key) answered with this output object instead of running, to steer branches or give a stubbed write a realistic result. Requires `dry`. A locked block (or one inside a locked loop or parallel) cannot be mocked. A mock is data: it cannot set a field the run’s execution, trace or billing reads (`cost`, `tokens`, `model`, `providerTiming`, `toolCalls`, `executionData`, `childTraceSpans`, `childWorkflowId`, `childWorkflowSnapshotId`, `childDeploymentVersionId`, or any field starting with `_`). The run records only which blocks were mocked, so a rerun passes the outputs again; its log shows a mocked block’s output like any other block’s.' + ), }) .strict(), ]) @@ -1951,6 +1982,93 @@ const v2WorkflowRunPausePointSchema = z description: 'One point at which a paused run waits.', }) +const sideEffectBlockFields = { + workflowId: z + .string() + .describe('Workflow whose block it was: the run workflow, or a child workflow it called.'), + blockId: z + .string() + .nullable() + .describe('Block id in that workflow; null when the call named no block.'), + block: z.string().nullable().describe('Block display name; null when the call named no block.'), +} + +const v2RunSideEffectsSchema = z + .object({ + stubbed: z + .array( + z.object({ + ...sideEffectBlockFields, + tool: z + .string() + .nullable() + .describe( + 'Tool the block (or an Agent) called; null when the whole block was answered instead of run.' + ), + request: z + .record(z.string(), z.unknown().describe('Request field.')) + .nullable() + .describe( + "What the call would have sent: an in-process operation's input, an HTTP call's `method`, `url` and `body` (never headers), or a custom or MCP tool's `arguments`. For a block answered whole, its logged inputs. Credentials, secrets, password fields and (when the workspace redacts it) PII are redacted; null when the run could not prove none remain, or could not build the request once they were masked (such as a URL that is wholly a secret)." + ), + returned: z + .record(z.string(), z.unknown().describe('Placeholder field.')) + .describe('Placeholder output the block or tool call returned to the run instead.'), + }) + ) + .describe('Writes that were not sent, in the order the run reached them.'), + allowed: z + .array( + z.object({ + ...sideEffectBlockFields, + tool: z.string().nullable().describe('Tool sent; null when the whole block ran.'), + }) + ) + .describe( + 'Writes sent for real because `run.allowBlocks` named their block, once per block and tool.' + ), + unchecked: z + .array( + z.object({ + ...sideEffectBlockFields, + reason: z.string().describe('Why the run cannot see what this code changed.'), + }) + ) + .describe( + "Blocks whose code ran for real, once per block: a Function block's code, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model wrote, which may make network calls the run cannot see." + ), + omitted: z + .object({ + stubbed: z.number().int().nonnegative().describe('Writes left out of `stubbed`.'), + allowed: z.number().int().nonnegative().describe('Writes left out of `allowed`.'), + unchecked: z.number().int().nonnegative().describe('Blocks left out of `unchecked`.'), + }) + .describe('Entries each list left out once it held 50.'), + }) + .meta({ + id: 'WorkflowRunSideEffects', + title: 'Workflow run side effects', + description: 'What a dry run did with each write it reached.', + }) + +export const v2RunDryRunSchema = z + .object({ + allowBlocks: z + .array(z.string().describe('Block id.')) + .describe('Blocks whose writes the run sent (`run.allowBlocks`), by id.'), + mockedBlocks: z + .array(z.string().describe('Block id.')) + .describe( + 'Blocks the run answered with fixed outputs (`run.mocks`), by id. Only the ids are recorded, so a rerun passes the outputs again.' + ), + }) + .meta({ + id: 'WorkflowDryRun', + title: 'Workflow dry run', + description: + 'The blocks a dry run sent and mocked, by id, which a rerun of it names again; never a mock output.', + }) + /** * The run result resource. In-band run failures are `status: 'failed'` * with a structured `error` — never an HTTP error: **a `runId` means 200/202 + @@ -1997,6 +2115,14 @@ export const v2ExecuteWorkflowDataSchema = z }) .nullable() .describe('Where the run waits when `status` is `paused`; null otherwise.'), + sideEffects: v2RunSideEffectsSchema + .optional() + .describe( + 'What a dry run (`run.dry`) did with each write it reached, whatever its status; absent otherwise.' + ), + dryRun: v2RunDryRunSchema + .optional() + .describe("A dry run's allowed and mocked blocks (`run.dry`); absent for any other run."), }) .meta({ id: 'WorkflowRunResult', @@ -2090,7 +2216,7 @@ export const v2ResumeWorkflowQueuedSchema = v2ExecuteWorkflowQueuedSchema export type V2ResumeWorkflowQueued = z.output export const v2ResumeWorkflowDataSchema = v2ExecuteWorkflowDataSchema - .omit({ executionTimeoutSeconds: true }) + .omit({ executionTimeoutSeconds: true, sideEffects: true, dryRun: true }) .extend({ error: v2ExecutionErrorSchema .omit({ rerunFromBlockId: true }) @@ -2388,6 +2514,11 @@ export const v2WorkflowRunStatusSchema = z .describe( 'Run-produced files when `includeOutput=true`, or null when not requested or execution data is hidden by organization permission groups.' ), + dryRun: v2RunDryRunSchema + .nullable() + .describe( + "A failed dry run's allowed and mocked blocks, by id, which a rerun of it names again; null for any other run, or when execution data is hidden by organization permission groups." + ), }) .meta({ id: 'WorkflowRunStatus', diff --git a/apps/sim/lib/internal/mcp/execute-tool.ts b/apps/sim/lib/internal/mcp/execute-tool.ts index 22c733328bb..73be8b83101 100644 --- a/apps/sim/lib/internal/mcp/execute-tool.ts +++ b/apps/sim/lib/internal/mcp/execute-tool.ts @@ -27,6 +27,7 @@ import { McpToolsNotAllowedError, } from '@/lib/mcp/application/execute-tool' import { McpOauthRedirectRequired } from '@/lib/mcp/oauth' +import { parseMcpToolArguments } from '@/lib/mcp/tool-arguments' import { McpOauthAuthorizationRequiredError } from '@/lib/mcp/types' import { categorizeError, @@ -46,42 +47,6 @@ import { const logger = createLogger('McpInternalOperation') -const MCP_SYSTEM_PARAMETERS = new Set([ - 'operationPolicy', - 'serverId', - 'serverUrl', - 'toolName', - 'serverName', - '_context', - 'envVars', - 'workflowVariables', - 'blockData', - 'blockNameMapping', - '_toolSchema', -]) - -function parseArguments(input: unknown): Record | null { - if (!isPlainRecord(input)) return null - if (!Object.hasOwn(input, 'arguments')) { - return Object.fromEntries( - Object.entries(input).filter(([name]) => !MCP_SYSTEM_PARAMETERS.has(name)) - ) - } - - const value = input.arguments - if (typeof value !== 'string') return isPlainRecord(value) ? value : null - try { - const parsed: unknown = JSON.parse(value) - return isPlainRecord(parsed) ? parsed : null - } catch (error) { - logger.warn('Failed to parse MCP arguments JSON', { - errorName: error instanceof Error ? error.name : 'UnknownError', - argumentsLength: value.length, - }) - return null - } -} - async function createResponse( body: Record, status: number, @@ -157,7 +122,7 @@ export const executeMcpTool: InternalToolOperationHandler = async (request) => { { status: 400 } ) } - const args = parseArguments(request.input) + const args = parseMcpToolArguments(request.input) if (!args) return Response.json({ success: false, error: 'Invalid request format' }, { status: 400 }) @@ -211,6 +176,7 @@ export const executeMcpTool: InternalToolOperationHandler = async (request) => { callChain: request.context.callChain, timeoutMs, signal: request.signal, + checkOnly: request.context.checkOnly, } let result: ExecuteMcpToolResult if (target.kind === 'shared_server') { @@ -231,7 +197,7 @@ export const executeMcpTool: InternalToolOperationHandler = async (request) => { } request.signal?.throwIfAborted() const body = - request.toolId === 'mcp_run_operation' + request.toolId === 'mcp_run_operation' || 'checked' in result ? result : result.success ? { success: true, data: { success: true, output: result.output } } diff --git a/apps/sim/lib/internal/tool-operations/types.ts b/apps/sim/lib/internal/tool-operations/types.ts index bad836cdbd5..0e2a0654b70 100644 --- a/apps/sim/lib/internal/tool-operations/types.ts +++ b/apps/sim/lib/internal/tool-operations/types.ts @@ -35,6 +35,11 @@ export interface InternalToolOperationContext { authorizedServiceAccountCredential?: AuthorizedServiceAccountCredential /** Trusted source block for saved MCP operation restrictions. */ mcpBlockId?: string + /** + * Authorize and validate the call as a live one would, then answer without sending it: set by + * the executor for an MCP write the run's side-effect policy holds back, never from tool input. + */ + checkOnly?: boolean /** * Authenticated direct caller, supplied by an authorized use case, never tool input. A * delegated principal carries that use case's audience; rebind it before another use case. diff --git a/apps/sim/lib/logs/execution/logging-session.ts b/apps/sim/lib/logs/execution/logging-session.ts index e6721a971a4..5139e90dffd 100644 --- a/apps/sim/lib/logs/execution/logging-session.ts +++ b/apps/sim/lib/logs/execution/logging-session.ts @@ -937,6 +937,11 @@ export class LoggingSession { return this.deletedScope } + /** The trigger the run is logged under. */ + getTriggerType(): ExecutionTrigger['type'] { + return this.triggerType + } + private async releaseAdmissionSlot(): Promise { try { await releaseExecutionSlot(this.reservationId) diff --git a/apps/sim/lib/logs/execution/trace-spans/factory.ts b/apps/sim/lib/logs/execution/trace-spans/factory.ts index 63e3f1849a1..66da7ac5f9f 100644 --- a/apps/sim/lib/logs/execution/trace-spans/factory.ts +++ b/apps/sim/lib/logs/execution/trace-spans/factory.ts @@ -62,6 +62,24 @@ function liftChildTraceHandle(output: Record | undefined): { } } +/** + * The top-level block output fields {@link createSpanFromLog} reads beyond the displayed output: + * provider timing, cost, tokens and model become the span's usage, which the run is billed by, + * and the rest build its tool and child-workflow spans. Only a block's own handler sets them. + */ +export const SPAN_SOURCE_OUTPUT_FIELDS: ReadonlySet = new Set([ + 'cost', + 'tokens', + 'model', + 'providerTiming', + 'toolCalls', + 'executionData', + 'childTraceSpans', + 'childWorkflowId', + 'childWorkflowSnapshotId', + 'childDeploymentVersionId', +]) + /** * Creates a TraceSpan from a BlockLog. Returns null for invalid logs. * diff --git a/apps/sim/lib/mcp/application/execute-managed-tool.test.ts b/apps/sim/lib/mcp/application/execute-managed-tool.test.ts index 5ba7deeb835..550cabb9777 100644 --- a/apps/sim/lib/mcp/application/execute-managed-tool.test.ts +++ b/apps/sim/lib/mcp/application/execute-managed-tool.test.ts @@ -4,6 +4,7 @@ import { createExecutorPrincipal, createSessionPrincipal, } from '@sim/testing/factories/principal.factory' +import { auditMock, auditMockFns } from '@sim/testing/mocks/audit.mock' import { mcpOauthMock } from '@sim/testing/mocks/mcp-oauth.mock' import { mcpServiceMock, mcpServiceMockFns } from '@sim/testing/mocks/mcp-service.mock' import { workspaceAuthzMock, workspaceAuthzMockFns } from '@sim/testing/mocks/workspace-authz.mock' @@ -42,6 +43,8 @@ vi.mock('@/lib/mcp/application/managed-auth-provider', () => ({ vi.mock('@sim/platform-authz/workspace', () => workspaceAuthzMock) +vi.mock('@sim/audit', () => auditMock) + import { executeManagedMcpToolUseCase } from '@/lib/mcp/application/execute-managed-tool' import { createCopilotApplicationPrincipal } from '@/lib/mothership/auth/application-delegation' @@ -52,6 +55,12 @@ const mocks = { resolvePermission: workspaceAuthzMockFns.mockResolveEffectiveWorkspacePermission, } +const auditWrites = [ + auditMockFns.mockRecordAudit, + auditMockFns.mockRecordAuditOnce, + auditMockFns.mockRecordAuditRollup, +] + const context = { credentialId: 'mcp-cg-123456789012345678901', credentialGroupId: 'group-1', @@ -304,4 +313,32 @@ describe('executeManagedMcpToolUseCase', () => { ).rejects.toThrow('Workspace access revoked') expect(mocks.executeTool).not.toHaveBeenCalled() }) + + it('checks a held-back call without sending it, saving a tool snapshot or auditing it', async () => { + mocks.discoverTools.mockResolvedValue([ + { name: 'search_transcripts', inputSchema: { type: 'object', properties: {} } }, + ]) + const input = { + workspaceId: context.workspaceId, + credentialId: context.credentialId, + toolName: 'search_transcripts', + } + + await expect( + executeManagedMcpToolUseCase.execute({ principal, input: { ...input, checkOnly: true } }) + ).resolves.toEqual({ success: true, checked: true }) + + expect(mocks.executeTool).not.toHaveBeenCalled() + expect(mocks.saveToolSnapshot).not.toHaveBeenCalled() + for (const write of auditWrites) expect(write).not.toHaveBeenCalled() + + const savedWorkflow = await mocks.loadWorkflow() + queueTableRows(schemaMock.workflowDeploymentVersion, [{ state: savedWorkflow }]) + queueTableRows(schemaMock.workflowDeploymentVersion, [{ state: savedWorkflow }]) + await executeManagedMcpToolUseCase.execute({ principal, input }) + + expect(mocks.executeTool).toHaveBeenCalledOnce() + expect(mocks.saveToolSnapshot).toHaveBeenCalledOnce() + expect(auditWrites.some((write) => write.mock.calls.length > 0)).toBe(true) + }) }) diff --git a/apps/sim/lib/mcp/application/execute-managed-tool.ts b/apps/sim/lib/mcp/application/execute-managed-tool.ts index 5ff24632d37..fca62c5bedf 100644 --- a/apps/sim/lib/mcp/application/execute-managed-tool.ts +++ b/apps/sim/lib/mcp/application/execute-managed-tool.ts @@ -36,6 +36,11 @@ export interface ExecuteManagedMcpToolInput { callChain?: string[] timeoutMs?: number signal?: AbortSignal + /** + * Authorize, discover and validate the call as a live one would, then stop before sending it, + * writing nothing a live call reads: no server health, tool cache or tool snapshot. + */ + checkOnly?: boolean } function requireToolSchema(value: unknown): McpToolSchema { @@ -99,12 +104,13 @@ export const executeManagedMcpToolUseCase = defineAuthorizedWorkspaceUseCase({ input.signal, { requireComplete: true } ) - await saveManagedMcpToolSnapshot( - runtime.credentialId, - toManagedMcpToolSnapshots(tools), - runtime.oauthConfigVersion, - runtime.grantedAt - ) + if (!input.checkOnly) + await saveManagedMcpToolSnapshot( + runtime.credentialId, + toManagedMcpToolSnapshots(tools), + runtime.oauthConfigVersion, + runtime.grantedAt + ) const discovered = tools.find((tool) => tool.name === input.toolName) if (!discovered) { throw new OrchestrationError('not_found', 'Tool not found on the managed MCP connection') @@ -150,6 +156,7 @@ export const executeManagedMcpToolUseCase = defineAuthorizedWorkspaceUseCase({ context, credentialOperations.useManagedMcp.resourcePolicy ) + if (input.checkOnly) return { success: true, checked: true } const providerResult = await mcpService.executeManagedMcpTool({ connectionId: runtime.credentialId, serverId: runtime.mcpServerId, @@ -163,15 +170,18 @@ export const executeManagedMcpToolUseCase = defineAuthorizedWorkspaceUseCase({ input.signal?.throwIfAborted() return transformToolResult(providerResult) }, - projectAudit: ({ input, context }) => ({ - action: AuditAction.CREDENTIAL_ACCESSED, - resourceType: AuditResourceType.CREDENTIAL, - resourceId: context.credentialId, - description: `Executed managed MCP tool ${input.toolName}`, - metadata: { - credentialType: 'managed_mcp', - mcpServerId: context.mcpServerId, - toolName: input.toolName, - }, - }), + projectAudit: ({ input, context }) => + input.checkOnly + ? [] + : { + action: AuditAction.CREDENTIAL_ACCESSED, + resourceType: AuditResourceType.CREDENTIAL, + resourceId: context.credentialId, + description: `Executed managed MCP tool ${input.toolName}`, + metadata: { + credentialType: 'managed_mcp', + mcpServerId: context.mcpServerId, + toolName: input.toolName, + }, + }, }) diff --git a/apps/sim/lib/mcp/application/execute-tool.test.ts b/apps/sim/lib/mcp/application/execute-tool.test.ts index d4870e2a3f8..82baea986da 100644 --- a/apps/sim/lib/mcp/application/execute-tool.test.ts +++ b/apps/sim/lib/mcp/application/execute-tool.test.ts @@ -307,6 +307,28 @@ describe('executeMcpToolUseCase', () => { expect(mocks.executeTool).toHaveBeenCalledOnce() }) + it('checks a held-back call against the server’s tools without sending it', async () => { + const input = { + workspaceId: WORKSPACE.workspaceId, + serverId: SERVER.id, + toolName: 'lookup', + checkOnly: true, + } + + await expect( + executeMcpToolUseCase.execute({ principal: PRINCIPAL, input: { ...input, arguments: {} } }) + ).rejects.toMatchObject({ code: 'validation' }) + await expect( + executeMcpToolUseCase.execute({ + principal: PRINCIPAL, + input: { ...input, arguments: { count: 1 } }, + }) + ).resolves.toEqual({ success: true, checked: true }) + + expect(mocks.discoverServerTools).toHaveBeenCalledTimes(2) + expect(mocks.executeTool).not.toHaveBeenCalled() + }) + it('rechecks a saved block restriction changed during discovery', async () => { mocks.loadWorkflow.mockResolvedValueOnce(await mocks.loadWorkflow()).mockResolvedValue({ workspaceId: WORKSPACE.workspaceId, diff --git a/apps/sim/lib/mcp/application/execute-tool.ts b/apps/sim/lib/mcp/application/execute-tool.ts index 538fa445a8b..cb318632e21 100644 --- a/apps/sim/lib/mcp/application/execute-tool.ts +++ b/apps/sim/lib/mcp/application/execute-tool.ts @@ -38,11 +38,18 @@ export interface ExecuteMcpToolInput { timeoutMs?: number signal?: AbortSignal onResolvedSecretTraceProvenance?: (provenance: ResolvedSecretTraceProvenanceV1) => void + /** + * Authorize, discover and validate the call as a live one would, then stop before sending it, + * writing nothing a live call reads: no server health, tool cache or tool snapshot. + */ + checkOnly?: boolean } export type ExecuteMcpToolResult = | { success: true; output: McpToolResult } | { success: false; error: string } + /** A `checkOnly` call that would have been sent. */ + | { success: true; checked: true } function hasType(value: unknown): value is SchemaProperty { return typeof value === 'object' && value !== null && 'type' in value @@ -164,7 +171,7 @@ export const executeMcpToolUseCase = defineAuthorizedWorkspaceUseCase({ context.workspaceId, 'skip-cache', input.onResolvedSecretTraceProvenance, - { signal: input.signal, requireComplete: true } + { signal: input.signal, requireComplete: true, readOnly: input.checkOnly } ) const tool = tools.find((candidate) => candidate.name === input.toolName) if (!tool) throw new OrchestrationError('not_found', 'Tool not found on the specified server') @@ -190,6 +197,7 @@ export const executeMcpToolUseCase = defineAuthorizedWorkspaceUseCase({ ), input.toolName ) + if (input.checkOnly) return { success: true, checked: true } const providerResult = await mcpService.executeTool( userId, context.server.id, diff --git a/apps/sim/lib/mcp/service.test.ts b/apps/sim/lib/mcp/service.test.ts index 25dbd999137..995f1ba4986 100644 --- a/apps/sim/lib/mcp/service.test.ts +++ b/apps/sim/lib/mcp/service.test.ts @@ -591,43 +591,65 @@ describe('McpService best-effort discovery', () => { expect(tools.map((t) => t.name)).toEqual(['a1']) }) - it('skips an OAuth server nobody authorized without creating its OAuth row or marking it pending', async () => { - mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A', { authType: 'oauth' })]) - mcpOauthMockFns.mockHasDecryptableOauthTokens.mockResolvedValue(false) + it.each([ + ['a best-effort', { bestEffort: true }], + ['a read-only', { readOnly: true }], + ])( + 'skips an OAuth server nobody authorized in %s discovery without creating its OAuth row or marking it pending', + async (_kind, options) => { + mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A', { authType: 'oauth' })]) + mcpOauthMockFns.mockHasDecryptableOauthTokens.mockResolvedValue(false) + + await expect( + mcpService.discoverServerTools( + MEMBER_B, + 'mcp-a', + WORKSPACE_ID, + 'cache-aside', + undefined, + options + ) + ).rejects.toBeInstanceOf(McpOauthAuthorizationRequiredError) + expect(mcpOauthMockFns.mockGetOrCreateOauthRow).not.toHaveBeenCalled() + // loadOauthRow clears a column it cannot decrypt; the gate must not risk that. + expect(mcpOauthMockFns.mockLoadOauthRow).not.toHaveBeenCalled() + expect(mockConnect).not.toHaveBeenCalled() + expectNoSharedStateWrites() + } + ) - await expect( - mcpService.discoverServerTools(MEMBER_B, 'mcp-a', WORKSPACE_ID, 'cache-aside', undefined, { - bestEffort: true, + it.each([ + ['a best-effort', { bestEffort: true }], + ['a read-only', { readOnly: true }], + ])( + 'connects an authorized OAuth server in %s discovery with a grant-preserving provider and writes nothing when it is rejected', + async (_kind, options) => { + mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A', { authType: 'oauth' })]) + mcpOauthMockFns.mockHasDecryptableOauthTokens.mockResolvedValue(true) + mcpOauthMockFns.mockGetOrCreateOauthRow.mockResolvedValue({ + id: 'oauth-row-1', + tokens: { access_token: 'expired', token_type: 'bearer' }, }) - ).rejects.toBeInstanceOf(McpOauthAuthorizationRequiredError) - expect(mcpOauthMockFns.mockGetOrCreateOauthRow).not.toHaveBeenCalled() - // loadOauthRow clears a column it cannot decrypt; the gate must not risk that. - expect(mcpOauthMockFns.mockLoadOauthRow).not.toHaveBeenCalled() - expect(mockConnect).not.toHaveBeenCalled() - expectNoSharedStateWrites() - }) - - it('connects an authorized OAuth server with a grant-preserving provider and writes nothing when it is rejected', async () => { - mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A', { authType: 'oauth' })]) - mcpOauthMockFns.mockHasDecryptableOauthTokens.mockResolvedValue(true) - mcpOauthMockFns.mockGetOrCreateOauthRow.mockResolvedValue({ - id: 'oauth-row-1', - tokens: { access_token: 'expired', token_type: 'bearer' }, - }) - mockListTools.mockRejectedValueOnce(new UnauthorizedError('refresh rejected')) - MockMcpClient.mockClear() - - await expect( - mcpService.discoverServerTools(MEMBER_B, 'mcp-a', WORKSPACE_ID, 'cache-aside', undefined, { - bestEffort: true, + mockListTools.mockRejectedValueOnce(new UnauthorizedError('refresh rejected')) + MockMcpClient.mockClear() + + await expect( + mcpService.discoverServerTools( + MEMBER_B, + 'mcp-a', + WORKSPACE_ID, + 'cache-aside', + undefined, + options + ) + ).rejects.toThrow('refresh rejected') + + expect(MockMcpClient.mock.calls[0]?.[0]).toMatchObject({ + oauthCredentials: { initialProvider: { preserveGrant: true } }, }) - ).rejects.toThrow('refresh rejected') - - expect(MockMcpClient.mock.calls[0]?.[0]).toMatchObject({ - oauthCredentials: { initialProvider: { preserveGrant: true } }, - }) - expectNoSharedStateWrites() - }) + expectNoSharedStateWrites() + } + ) it('warms the shared tool cache on success without stamping status', async () => { mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A')]) @@ -651,4 +673,50 @@ describe('McpService best-effort discovery', () => { expect.any(Number) ) }) + + describe('read-only, as a dry run checks a call', () => { + it('leaves status, cooldown and the cached tools as they were when discovery fails', async () => { + mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A')]) + mockListTools.mockResolvedValueOnce([tool('a1', 'mcp-a')]) + await mcpService.discoverServerTools(USER_ID, 'mcp-a', WORKSPACE_ID) + resetDbChainMock() + wireSelectsToWorkspaceRows() + mockCacheAdapter.set.mockClear() + mockCacheAdapter.delete.mockClear() + mockListTools.mockReset() + mockListTools.mockRejectedValueOnce(new Error('Connection refused')) + + await expect( + mcpService.discoverServerTools(USER_ID, 'mcp-a', WORKSPACE_ID, 'skip-cache', undefined, { + requireComplete: true, + readOnly: true, + }) + ).rejects.toThrow('Connection refused') + + expectNoSharedStateWrites() + const cached = await mcpService.discoverServerTools(USER_ID, 'mcp-a', WORKSPACE_ID) + expect(cached.map((t) => t.name)).toEqual(['a1']) + expect(mockListTools).toHaveBeenCalledOnce() + }) + + it('neither caches the tools it finds nor stamps status', async () => { + mockGetWorkspaceServersRows.mockResolvedValue([dbRow('mcp-a', 'A')]) + mockListTools.mockResolvedValueOnce([tool('a1', 'mcp-a')]) + + await mcpService.discoverServerTools( + USER_ID, + 'mcp-a', + WORKSPACE_ID, + 'skip-cache', + undefined, + { + requireComplete: true, + readOnly: true, + } + ) + + expect(dbChainMockFns.set).not.toHaveBeenCalled() + expect(mockCacheAdapter.set).not.toHaveBeenCalled() + }) + }) }) diff --git a/apps/sim/lib/mcp/service.ts b/apps/sim/lib/mcp/service.ts index 468f0a6bbd4..f5828309afe 100644 --- a/apps/sim/lib/mcp/service.ts +++ b/apps/sim/lib/mcp/service.ts @@ -83,6 +83,12 @@ interface McpRequestOptions { * discovery left its tools cached, without connecting. */ bestEffort?: boolean + /** + * A discovery that checks a call without making it (a dry run's MCP write): it reads the cooldown + * as a live call would, but writes none of the server's shared state, so a check never changes + * what live calls see. No status, failure count, cooldown, or tool cache write or eviction. + */ + readOnly?: boolean } interface McpToolExecutionOptions extends McpRequestOptions { @@ -1192,7 +1198,12 @@ class McpService { onResolvedSecretTraceProvenance?: ResolvedSecretTraceProvenanceCallback, options: McpRequestOptions = {} ): Promise { - if (onResolvedSecretTraceProvenance || options.signal || options.requireComplete) { + if ( + onResolvedSecretTraceProvenance || + options.signal || + options.requireComplete || + options.readOnly + ) { return this.discoverServerToolsImpl( userId, serverId, @@ -1231,15 +1242,22 @@ class McpService { workspaceId: string, refresh: McpDiscoveryRefresh, onResolvedSecretTraceProvenance?: ResolvedSecretTraceProvenanceCallback, - { signal, requireComplete = false, bestEffort = false }: McpRequestOptions = {} + { + signal, + requireComplete = false, + bestEffort = false, + readOnly = false, + }: McpRequestOptions = {} ): Promise { signal?.throwIfAborted() const requestId = generateRequestId() const discoveryStartedAt = new Date() const maxRetries = 2 + // Best-effort and read-only discoveries both leave the server's shared state as they found it. + const preservesSharedState = bestEffort || readOnly // Before the cache: another member's cached tools never reach a requester who cannot call them. - const requesterConfig = bestEffort + const requesterConfig = preservesSharedState ? await this.loadAuthenticatableServerConfig(serverId, userId, workspaceId) : undefined @@ -1282,9 +1300,10 @@ class McpService { onResolvedSecretTraceProvenance, signal, requireComplete, - bestEffort + preservesSharedState ) logger.info(`Discovered ${tools.length} tools from server ${config.name}`, { requestId }) + if (readOnly) return tools const cacheWrite = this.cacheAdapter .set(serverCacheKey(workspaceId, serverId), tools, this.cacheTimeout) .catch((err) => logger.warn(`Cache write failed for ${config.name}:`, err, { requestId })) @@ -1317,7 +1336,7 @@ class McpService { signal?.throwIfAborted() continue } - if (bestEffort) throw error + if (preservesSharedState) throw error // Drop positive cache so a follow-up doesn't return stale tools. const statusApplied = isOauthAuthorizationError(error, authType) ? await this.markServerOauthPending(serverId, workspaceId, discoveryStartedAt) diff --git a/apps/sim/lib/mcp/tool-arguments.ts b/apps/sim/lib/mcp/tool-arguments.ts new file mode 100644 index 00000000000..31146271b5e --- /dev/null +++ b/apps/sim/lib/mcp/tool-arguments.ts @@ -0,0 +1,54 @@ +import { createLogger } from '@sim/logger' +import { isPlainRecord } from '@sim/utils/object' + +const logger = createLogger('McpToolArguments') + +/** + * Params an Agent's tool call carries for the run itself (every env var, workflow variable and + * block output), which no tool sends: neither an MCP server's arguments nor a stubbed write's + * recorded request may show them. + */ +export const RUN_CONTEXT_PARAMS: ReadonlySet = new Set([ + 'envVars', + 'workflowVariables', + 'blockData', + 'blockNameMapping', +]) + +/** Params an MCP tool call carries for the run, never sent to the server as arguments. */ +const MCP_SYSTEM_PARAMETERS: ReadonlySet = new Set([ + ...RUN_CONTEXT_PARAMS, + 'operationPolicy', + 'serverId', + 'serverUrl', + 'toolName', + 'serverName', + '_context', + '_toolSchema', +]) + +/** + * The arguments an MCP tool call sends its server: an explicit `arguments` object (or JSON + * string), else every param that is not the run's own. Null when they cannot be read. + */ +export function parseMcpToolArguments(input: unknown): Record | null { + if (!isPlainRecord(input)) return null + if (!Object.hasOwn(input, 'arguments')) { + return Object.fromEntries( + Object.entries(input).filter(([name]) => !MCP_SYSTEM_PARAMETERS.has(name)) + ) + } + + const value = input.arguments + if (typeof value !== 'string') return isPlainRecord(value) ? value : null + try { + const parsed: unknown = JSON.parse(value) + return isPlainRecord(parsed) ? parsed : null + } catch (error) { + logger.warn('Failed to parse MCP arguments JSON', { + errorName: error instanceof Error ? error.name : 'UnknownError', + argumentsLength: value.length, + }) + return null + } +} diff --git a/apps/sim/lib/memory/agent-turn-session.ts b/apps/sim/lib/memory/agent-turn-session.ts index 04e8234931e..871d59ddd09 100644 --- a/apps/sim/lib/memory/agent-turn-session.ts +++ b/apps/sim/lib/memory/agent-turn-session.ts @@ -20,6 +20,7 @@ import { redactObjectStrings } from '@/lib/logs/execution/pii-redaction' import { openAgentMemoryTurnUseCase, readAgentMemoryArtifactUseCase, + readAgentMemoryPrefixUseCase, saveAgentMemoryTurnUseCase, storeAgentMemoryArtifactUseCase, } from '@/lib/memory/application/agent-turns' @@ -362,6 +363,44 @@ export class AgentTurnSession extends AgentTurnStateMachine { } } +/** Whether a workspace's Agents keep durable turn history (the `agent-memory-history` rollout). */ +async function keepsAgentMemoryHistory(workspaceId: string): Promise { + try { + return await isFeatureEnabled('agent-memory-history', { workspaceId }) + } catch { + logger.warn('Agent memory rollout configuration unavailable') + return false + } +} + +/** + * The stored conversation an Agent reads without opening a turn in it, for a run that writes no + * memory (a dry run or a workflow test): the same rich history and retrieval an + * {@link openAgentTurnSession} turn reads, and nothing written. Undefined when the conversation + * is not stored, the workspace keeps no turn history, or it cannot be read. + */ +export async function findStoredAgentConversation(input: { + ctx: ExecutionContext + conversationId: string +}): Promise<{ memoryId: string } | undefined> { + const { ctx, conversationId } = input + if (!ctx.workspaceId || !conversationId) return undefined + if (!(await keepsAgentMemoryHistory(ctx.workspaceId))) return undefined + try { + const stored = await readAgentMemoryPrefixUseCase.execute({ + principal: await createExecutorPrincipalFromExecutionContext({ + context: ctx, + audience: MEMORY_DELEGATION_AUDIENCE, + }), + input: { workspaceId: ctx.workspaceId, conversationId }, + }) + return stored ? { memoryId: stored.id } : undefined + } catch { + logger.warn('Agent memory history unavailable', { executionId: ctx.executionId }) + return undefined + } +} + /** Durability errors are isolated; authorization for model/tool execution remains with the executor. */ export async function openAgentTurnSession( input: OpenAgentTurnSessionInput @@ -375,13 +414,7 @@ export async function openAgentTurnSession( !input.conversationId ) return undefined - try { - if (!(await isFeatureEnabled('agent-memory-history', { workspaceId: ctx.workspaceId }))) - return undefined - } catch { - logger.warn('Agent memory rollout configuration unavailable') - return undefined - } + if (!(await keepsAgentMemoryHistory(ctx.workspaceId))) return undefined const identity: AgentMemoryTurnIdentity = { workspaceId: ctx.workspaceId, workflowId: ctx.workflowId, diff --git a/apps/sim/lib/mothership/__integration__/content-delivery-compat.baseline.json b/apps/sim/lib/mothership/__integration__/content-delivery-compat.baseline.json index a9dcd23f9db..497804bf07b 100644 --- a/apps/sim/lib/mothership/__integration__/content-delivery-compat.baseline.json +++ b/apps/sim/lib/mothership/__integration__/content-delivery-compat.baseline.json @@ -790,6 +790,7 @@ "data": { "blockOutputs": null, "cost": null, + "dryRun": null, "durationMs": null, "endedAt": "