From 414b7432f840fcbd8d0c9a55f98934a2869fa3c3 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 05:41:02 -0800 Subject: [PATCH 1/3] improvement(workflows): dry-run placeholders echo the writes they stand in for A stubbed write was answered with a generic sample of the tool's outputs, so a Function reading a dry-run table upsert's row.data. got null and an agent testing its workflow concluded its logic was wrong. A tool may now declare a pure dryRunOutput(params) on its config: the outputs the request alone determines. It receives the params with every secret masked (as sideEffects.stubbed[].request is built), its result is redacted like that request, and the sample of the declared outputs fills whatever it leaves out (ids, nested fields, each array item from the sample's first). Tools without it keep the sample. Declared for table insert/upsert/update row (row.data echoes the written data; update keeps the named row id) and batch insert (rows and insertedCount), file write (requested name, text byte size), and knowledge create document (the document name as stored). Filter updates and deletes are left out: their outputs depend on stored state. --- .agents/skills/add-tools/SKILL.md | 4 ++ .../api-reference/build-and-run-workflows.mdx | 2 +- apps/docs/openapi-v2-workflows.json | 2 +- apps/sim/executor/execution/types.ts | 5 ++ apps/sim/lib/api/contracts/v2/workflows.ts | 2 +- .../application/dry-run.integration.ts | 53 +++++++++++++++++- apps/sim/lib/workflows/dry-run/samples.ts | 41 ++++++++++++-- .../sim/lib/workflows/dry-run/side-effects.ts | 5 +- apps/sim/tools/file/write.ts | 10 ++++ apps/sim/tools/index.ts | 1 + apps/sim/tools/knowledge/create_document.ts | 10 ++++ apps/sim/tools/side-effects.ts | 54 +++++++++++-------- apps/sim/tools/table/batch_insert_rows.ts | 6 +++ apps/sim/tools/table/insert_row.ts | 3 ++ apps/sim/tools/table/update_row.ts | 3 ++ apps/sim/tools/table/upsert_row.ts | 3 ++ apps/sim/tools/types.ts | 8 +++ 17 files changed, 180 insertions(+), 32 deletions(-) diff --git a/.agents/skills/add-tools/SKILL.md b/.agents/skills/add-tools/SKILL.md index 955ff96b57c..b0843e588e8 100644 --- a/.agents/skills/add-tools/SKILL.md +++ b/.agents/skills/add-tools/SKILL.md @@ -234,6 +234,10 @@ search that returns no email or phone, and an email verifier. 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. +- A dry run answers a `write` with a sample of its `outputs`. When downstream blocks read output the + request alone determines (a table write's `row.data`, a created file's `name`), declare a pure + `dryRunOutput(params)` returning just those fields; it gets params with secrets masked, and the + sample fills ids and everything else. Never guess at what the provider would add. ## Critical Rules for Parameters 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 7636413fc99..df9b7459683 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"` 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. +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 correctly shaped placeholder (a table write echoes the row it would have written, secrets masked, so a block reading `row.data` gets the values it wrote), 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. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 03a17dd3910..3b88ed05db6 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -17758,7 +17758,7 @@ "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`.", + "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table write echoes the row it would have written, secrets masked) 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": { diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index 21ef948cd3a..4e95433aa4b 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -347,6 +347,11 @@ 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 + /** + * The output the tool's `dryRunOutput` derives from that request, redacted like it; null when + * the tool declares none or that cannot be vouched for, so the placeholder is the sample alone. + */ + echoed: Record | null } /** A block the run answers instead of running its handler. */ diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index b5786408496..a0b9a5a2ae8 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1709,7 +1709,7 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .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`." + "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table write echoes the row it would have written, secrets masked) 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')) diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index ff8a15150f8..086fe2a3933 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -98,6 +98,7 @@ import { import { readWorkflowRun } from '@/lib/workflows/application/read-workflow-run' import { resumeWorkflowRun } from '@/lib/workflows/application/resume-run' import { runFromBlockFromCopilot } from '@/lib/workflows/application/run-workflow-from-copilot' +import { sampleToolOutput } from '@/lib/workflows/dry-run' import type { ExecuteWorkflowServiceRun } from '@/lib/workflows/executor/execute-service' import { getWorkflowExecutionLogStatus } from '@/lib/workflows/executor/execution-state' import { POST as v2Execute } from '@/app/api/v2/workflows/[workflowId]/execute/route' @@ -206,6 +207,7 @@ async function createTable(): Promise { columns: [ { id: 'col_email', name: 'email', type: 'string', required: true, unique: true }, { id: 'col_score', name: 'score', type: 'number' }, + { id: 'col_note', name: 'note', type: 'string' }, ], }, }) @@ -484,6 +486,52 @@ describe('a dry run', () => { expect(stubbed[2].request).toMatchObject({ data: { email: 'child@b.co' } }) }) + it('answers a table write with the row it would have written, its secrets masked', async () => { + const tableId = await createTable() + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('save', 'table', { + operation: 'upsert_row', + tableSelector: tableId, + data: JSON.stringify({ email: 'a@b.co', score: 82, note: 'key={{DRY_SECRET}}' }), + }), + notify('notify'), + block('read', 'function', { + language: 'javascript', + code: 'return { score: , email: , note: , notified: }', + }), + ], + [ + ['start', 'save'], + ['save', 'notify'], + ['notify', 'read'], + ] + ).state + ) + + const result = await run(workflowId, { dry: true, selectedOutputs: ['read.result'] }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(await tableRows(tableId)).toEqual([]) + const read = toRecord(result.blockOutputs?.['read.result']) + expect(read).toMatchObject({ + score: 82, + email: 'a@b.co', + note: expect.stringContaining('key='), + }) + expect(JSON.stringify(result)).not.toContain(SECRET) + const [save, sent] = result.sideEffects?.stubbed ?? [] + expect(toRecord(save.returned.row).data).toEqual({ + email: 'a@b.co', + score: 82, + note: read.note, + }) + expect(sent).toMatchObject({ tool: 'http_request', returned: sampleToolOutput('http_request') }) + expect(read.notified).toBe(sampleToolOutput('http_request').status) + }) + it('keeps nothing beyond its own log: no run count and no workspace event', async () => { const { parentId } = await parentFixture() const subscriber = await saveWorkflow(graph([block('start', 'start_trigger')], []).state) @@ -758,7 +806,10 @@ describe('a dry run', () => { expect(result.status, JSON.stringify(result.error)).toBe('completed') const [write] = result.sideEffects?.stubbed ?? [] - expect(write).toMatchObject({ tool: 'knowledge_create_document' }) + expect(write).toMatchObject({ + tool: 'knowledge_create_document', + returned: { data: { documentName: 'notes.txt' } }, + }) const [document] = toArray(toRecord(write.request).documents) const fileUrl = String(toRecord(document).fileUrl) const content = Buffer.from(fileUrl.slice(fileUrl.indexOf(',') + 1), 'base64').toString('utf8') diff --git a/apps/sim/lib/workflows/dry-run/samples.ts b/apps/sim/lib/workflows/dry-run/samples.ts index 77d22bf68d6..89cba38e75f 100644 --- a/apps/sim/lib/workflows/dry-run/samples.ts +++ b/apps/sim/lib/workflows/dry-run/samples.ts @@ -1,3 +1,4 @@ +import { isPlainRecord } from '@sim/utils/object' import { getEffectiveBlockOutputs } from '@/lib/workflows/blocks/outputs' import { generateMockPayloadFromOutputsDefinition } from '@/lib/workflows/triggers/mock-payload' import { isRunControlledOutputField } from '@/executor/utils/mock-output' @@ -21,8 +22,42 @@ export function sampleBlockOutput(block: { ) } -/** Placeholder output shaped like a tool's declared outputs; empty for a tool that declares none. */ -export function sampleToolOutput(toolId: string): Record { +/** + * `value` with what it leaves out taken from `sample`: a record field by field, and each item of + * an array from the sample's first item. + */ +function fillFromSample(sample: unknown, value: unknown): unknown { + if (value === undefined) return sample + if (Array.isArray(value)) { + const item = Array.isArray(sample) ? sample[0] : undefined + return value.map((entry) => fillFromSample(item, entry)) + } + if (!isPlainRecord(value) || !isPlainRecord(sample)) return value + return Object.fromEntries([ + ...Object.entries(sample), + ...Object.entries(value).map(([key, entry]) => [ + key, + fillFromSample(Object.hasOwn(sample, key) ? sample[key] : undefined, entry), + ]), + ]) +} + +/** + * Placeholder output shaped like a tool's declared outputs; empty for a tool that declares none. + * `echoed`, what the tool's `dryRunOutput` derived from the request it would have sent, fills each + * declared output it names, and the sample everything else. + */ +export function sampleToolOutput( + toolId: string, + echoed: Record | null = null +): Record { const outputs = getToolOutputsMetadata(toolId) - return outputs ? generateMockPayloadFromOutputsDefinition(outputs) : {} + const sample = outputs ? generateMockPayloadFromOutputsDefinition(outputs) : {} + if (!echoed) return sample + return Object.fromEntries( + Object.entries(sample).map(([field, value]) => [ + field, + Object.hasOwn(echoed, field) ? fillFromSample(value, echoed[field]) : value, + ]) + ) } diff --git a/apps/sim/lib/workflows/dry-run/side-effects.ts b/apps/sim/lib/workflows/dry-run/side-effects.ts index 89fd69c7de3..dc5f75fbb71 100644 --- a/apps/sim/lib/workflows/dry-run/side-effects.ts +++ b/apps/sim/lib/workflows/dry-run/side-effects.ts @@ -114,7 +114,8 @@ class RecordedList { /** * The side-effect policy of a dry run (`run.dry`) and of a workflow test's unmocked writes: every - * write tool call is answered with a placeholder shaped like the tool's output and recorded with + * write tool call is answered with a placeholder shaped like the tool's output, holding what the + * request determines where the tool declares it (`dryRunOutput`), and recorded with * the request it would have sent, except an allowed block's, which are sent and recorded once per * block and tool. Reads always run, and code runs and is listed unchecked. Custom blocks and * {@link PAUSING_BLOCK_TYPES} are answered whole, as is a block that acts outside the tool seam @@ -192,7 +193,7 @@ export class WriteStubPolicy implements SideEffectPolicy { } stubWrite(call: StubbedToolCall): Record { - const returned = sampleToolOutput(call.toolId) + const returned = sampleToolOutput(call.toolId, call.echoed) this.stubbed.add({ ...recordedSite(call), tool: call.toolId, request: call.request, returned }) return returned } diff --git a/apps/sim/tools/file/write.ts b/apps/sim/tools/file/write.ts index 80a776bf4c6..153a424c215 100644 --- a/apps/sim/tools/file/write.ts +++ b/apps/sim/tools/file/write.ts @@ -92,6 +92,16 @@ export const fileWriteTool: InternalToolConfig = }, }, + /** + * A dry run's placeholder names the file the call asks for (a write that would collide is + * suffixed live) and sizes the text it writes; a stored file's name and size stay placeholders. + */ + dryRunOutput: (params) => ({ + name: params.fileName, + size: + params.content === undefined ? undefined : new TextEncoder().encode(params.content).length, + }), + transformResponse: async (response) => { const data = await response.json() if (!response.ok || !data.success) { diff --git a/apps/sim/tools/index.ts b/apps/sim/tools/index.ts index e0a75eb04c6..b71740af5b1 100644 --- a/apps/sim/tools/index.ts +++ b/apps/sim/tools/index.ts @@ -2269,6 +2269,7 @@ async function executeToolImplementation( registry: resolvedSecretTraceRegistry, describe: (maskedParams: Record) => describeToolRequest(unsentTool, maskedParams), + echo: unsentTool.dryRunOutput, } if (normalizedToolId !== mcpRunOperationTool.id || !tool.operation) { return await answerUnsentWrite(unsentWrite, unsent) diff --git a/apps/sim/tools/knowledge/create_document.ts b/apps/sim/tools/knowledge/create_document.ts index d41fdc8cca8..dcf7b594bd7 100644 --- a/apps/sim/tools/knowledge/create_document.ts +++ b/apps/sim/tools/knowledge/create_document.ts @@ -117,6 +117,16 @@ export const knowledgeCreateDocumentTool: InternalToolConfig ({ + message: 'Successfully created document in knowledge base', + data: { + documentName: inferDocumentFileInfo(params.name.trim()).filename, + type: 'document', + enabled: true, + }, + }), + transformResponse: async (response): Promise => { const result = await response.json() const data = result.data || result diff --git a/apps/sim/tools/side-effects.ts b/apps/sim/tools/side-effects.ts index 2a88117c46b..538e307da0b 100644 --- a/apps/sim/tools/side-effects.ts +++ b/apps/sim/tools/side-effects.ts @@ -259,10 +259,11 @@ export async function redactSideEffectPayload(input: { /** * The response answering a write tool call the run's side-effect policy does not send, after the - * policy recorded the request it would have sent: `describe` builds it from params whose secrets - * are already masked ({@link maskRequestParams}), and the result is redacted again as a payload - * ({@link redactSideEffectPayload}). The request is null when either step cannot vouch that no - * secret remains, or it cannot be built from the masked params; the write is answered either way. + * policy recorded the request it would have sent: `describe` builds it, and `echo` (a tool's + * `dryRunOutput`) the output that request determines, both from params whose secrets are already + * masked ({@link maskRequestParams}), and each result is redacted again as a payload + * ({@link redactSideEffectPayload}). Either is null when a step cannot vouch that no secret remains, + * or it cannot be built from the masked params; the write is answered either way. */ export async function answerUnsentWrite( write: UnsentWrite, @@ -270,6 +271,7 @@ export async function answerUnsentWrite( params: Record registry: ResolvedSecretTraceRegistry | undefined describe: (maskedParams: Record) => unknown + echo?: (maskedParams: Record) => Record } ): Promise { const { call } = write @@ -282,34 +284,40 @@ export async function answerUnsentWrite( if (!(error instanceof SecretScanDepthError)) throw error maskedParams = null } - const described = maskedParams - ? describeMaskedRequest(call.toolId, input.describe, maskedParams) - : null - const request = described - ? await redactSideEffectPayload({ - payload: described.payload, - params: input.params, - blockTypes, - executionContext: write.executionContext, - registry: input.registry, - }) - : null - return { success: true, output: write.policy.stubWrite({ ...call, request }) } + const fromMaskedParams = async ( + build: ((maskedParams: Record) => unknown) | undefined + ): Promise | null> => { + const built = + maskedParams && build ? buildFromMaskedParams(call.toolId, build, maskedParams) : null + return built + ? redactSideEffectPayload({ + payload: built.payload, + params: input.params, + blockTypes, + executionContext: write.executionContext, + registry: input.registry, + }) + : null + } + const request = await fromMaskedParams(input.describe) + const echoed = await fromMaskedParams(input.echo) + return { success: true, output: write.policy.stubWrite({ ...call, request, echoed }) } } /** - * The request a write would send, or null when it cannot be built from masked params (a URL that is - * wholly a masked secret fails URL validation): describing an unsent write never fails the run. + * What `build` makes of a write's masked params (its request, or the output it determines), or + * null when it cannot be built from them (a URL that is wholly a masked secret fails URL + * validation): answering an unsent write never fails the run. */ -function describeMaskedRequest( +function buildFromMaskedParams( toolId: string, - describe: (maskedParams: Record) => unknown, + build: (maskedParams: Record) => unknown, maskedParams: Record ): { payload: unknown } | null { try { - return { payload: describe(maskedParams) } + return { payload: build(maskedParams) } } catch (error) { - logger.warn('Could not describe an unsent write from its masked params; recording no request', { + logger.warn('Could not build from the masked params of an unsent write; recording none', { toolId, errorName: error instanceof Error ? error.name : 'UnknownError', }) diff --git a/apps/sim/tools/table/batch_insert_rows.ts b/apps/sim/tools/table/batch_insert_rows.ts index 7205f08780e..0031507ea71 100644 --- a/apps/sim/tools/table/batch_insert_rows.ts +++ b/apps/sim/tools/table/batch_insert_rows.ts @@ -55,6 +55,12 @@ export const tableBatchInsertRowsTool: InternalToolConfig< }, }, + /** A dry run's placeholder rows hold the data the call writes; their ids stay placeholders. */ + dryRunOutput: (params) => ({ + rows: params.rows.map((data) => ({ data })), + insertedCount: params.rows.length, + }), + transformResponse: async (response): Promise => { const result = await response.json() const data = result.data || result diff --git a/apps/sim/tools/table/insert_row.ts b/apps/sim/tools/table/insert_row.ts index 1f2e00b9814..411e171adb0 100644 --- a/apps/sim/tools/table/insert_row.ts +++ b/apps/sim/tools/table/insert_row.ts @@ -52,6 +52,9 @@ export const tableInsertRowTool: InternalToolConfig ({ row: { data: params.data } }), + transformResponse: async (response): Promise => { const result = await response.json() const data = result.data || result diff --git a/apps/sim/tools/table/update_row.ts b/apps/sim/tools/table/update_row.ts index 612b64ca59b..1f8c2dba94f 100644 --- a/apps/sim/tools/table/update_row.ts +++ b/apps/sim/tools/table/update_row.ts @@ -59,6 +59,9 @@ export const tableUpdateRowTool: InternalToolConfig ({ row: { id: params.rowId, data: params.data } }), + transformResponse: async (response): Promise => { const result = await response.json() const data = result.data || result diff --git a/apps/sim/tools/table/upsert_row.ts b/apps/sim/tools/table/upsert_row.ts index 161b91c32b1..4d9307ec83e 100644 --- a/apps/sim/tools/table/upsert_row.ts +++ b/apps/sim/tools/table/upsert_row.ts @@ -60,6 +60,9 @@ export const tableUpsertRowTool: InternalToolConfig ({ row: { data: params.data } }), + transformResponse: async (response): Promise => { const result = await response.json() const data = result.data || result diff --git a/apps/sim/tools/types.ts b/apps/sim/tools/types.ts index 5f1f6a6cc04..7b1c6a8e607 100644 --- a/apps/sim/tools/types.ts +++ b/apps/sim/tools/types.ts @@ -279,6 +279,14 @@ export interface ToolConfig

{ > // Output schema - what this tool produces outputs?: Record + /** + * How a dry run answers this write without sending it: the outputs the request alone determines, + * never a guess at what the provider or stored state would add. Pure. `params` have every secret + * masked, and the result is redacted like `sideEffects.stubbed[].request`, since it feeds + * downstream blocks. Whatever it leaves out (an id, a field nested in a declared output) comes + * from the sample of {@link outputs}, which alone answers a tool without it. + */ + dryRunOutput?: (params: P) => Record // OAuth configuration for this tool (if it requires authentication) oauth?: OAuthConfig From 02de1d09122e89793e42cf682e63e09b1b40ec4c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 06:09:15 -0800 Subject: [PATCH 2/3] improvement(workflows): placeholders follow the declared output schema and redact once A dry-run echo was merged into the sample by the sample's value shape, so a table row declared as bare json came back with the generic sample keys (name: 'Sample Object', status: 'active') beside its data, and every batch row shared the id 'item_1'. The echo is now laid over the sample by the declared schema: field by field where an output declares properties, item by item where it declares array items, and whole anywhere else (an undeclared field is dropped). The table hooks return the row as the routes emit it (data, and placeholder id, position and timestamps, distinct per batch row) with no ignored columns; update's row holds only the fields it patches. Knowledge create echoes only the document name, and file write sizes its text with utf8ByteLength. Value-based masking replaced every occurrence of any string under a secret-named field, however short, so a one-letter reset_token column turned 'a@b.co' into '[REDACTED]@b.co' in the request and in what downstream blocks read; worse, a value masked inside a run secret left the rest of that secret unmatched by the registry. Values shorter than the repo's identifying-literal floor (isNonIdentifyingSecretLiteral) are now masked only by their field, password fields are masked by name like credential-named ones, and the registry projection runs before key and value masking. A stubbed write's request and echo are redacted in one pass, one PII call per write; when that pass cannot vouch for the pair, both are null. --- .agents/skills/add-tools/SKILL.md | 6 +- .../api-reference/build-and-run-workflows.mdx | 2 +- apps/docs/openapi-v2-workflows.json | 2 +- apps/sim/executor/execution/types.ts | 4 +- apps/sim/lib/api/contracts/v2/workflows.ts | 2 +- .../application/dry-run.integration.ts | 254 +++++++++++++++--- apps/sim/lib/workflows/dry-run/samples.ts | 67 +++-- apps/sim/tools/file/write.ts | 7 +- apps/sim/tools/knowledge/create_document.ts | 7 +- apps/sim/tools/side-effects.ts | 135 +++++++--- apps/sim/tools/table/batch_insert_rows.ts | 7 +- apps/sim/tools/table/insert_row.ts | 9 +- apps/sim/tools/table/response.ts | 18 ++ apps/sim/tools/table/update_row.ts | 12 +- apps/sim/tools/table/upsert_row.ts | 9 +- apps/sim/tools/types.ts | 13 +- 16 files changed, 412 insertions(+), 142 deletions(-) diff --git a/.agents/skills/add-tools/SKILL.md b/.agents/skills/add-tools/SKILL.md index b0843e588e8..3c1fe2191b6 100644 --- a/.agents/skills/add-tools/SKILL.md +++ b/.agents/skills/add-tools/SKILL.md @@ -236,8 +236,10 @@ search that returns no email or phone, and an email verifier. fields only on entries that carry one. - A dry run answers a `write` with a sample of its `outputs`. When downstream blocks read output the request alone determines (a table write's `row.data`, a created file's `name`), declare a pure - `dryRunOutput(params)` returning just those fields; it gets params with secrets masked, and the - sample fills ids and everything else. Never guess at what the provider would add. + `dryRunOutput(params)` returning just those fields; it gets params with secrets masked. It is laid + over the sample by the declared schema: field by field where an output declares `properties`, + whole anywhere else, so return an undeclared shape (a `json` row) complete, with placeholders for + what the request cannot know. Never guess at what the provider would add. ## Critical Rules for Parameters 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 df9b7459683..ebfefe57d91 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"` 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 correctly shaped placeholder (a table write echoes the row it would have written, secrets masked, so a block reading `row.data` gets the values it wrote), 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. +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 correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written before the table coerces it, secrets masked, so a block reading `row.data` gets the values it wrote), 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. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 3b88ed05db6..49c481780de 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -17758,7 +17758,7 @@ "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 correctly shaped placeholder (a table write echoes the row it would have written, secrets masked) 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`.", + "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written, secrets masked) 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": { diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index 4e95433aa4b..b4d0189c191 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -348,8 +348,8 @@ export interface StubbedToolCall extends SideEffectSite { /** The request with credentials, secrets and PII redacted; null when that cannot be vouched for. */ request: Record | null /** - * The output the tool's `dryRunOutput` derives from that request, redacted like it; null when - * the tool declares none or that cannot be vouched for, so the placeholder is the sample alone. + * The tool's `dryRunOutput` of the masked params, redacted with `request`; null when the tool + * declares none or it cannot be built or vouched for, leaving the placeholder the sample alone. */ echoed: Record | null } diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index a0b9a5a2ae8..5dec74a85ee 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1709,7 +1709,7 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .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 correctly shaped placeholder (a table write echoes the row it would have written, secrets masked) 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`." + "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written, secrets masked) 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')) diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index 086fe2a3933..4c020bcc989 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -98,7 +98,6 @@ import { import { readWorkflowRun } from '@/lib/workflows/application/read-workflow-run' import { resumeWorkflowRun } from '@/lib/workflows/application/resume-run' import { runFromBlockFromCopilot } from '@/lib/workflows/application/run-workflow-from-copilot' -import { sampleToolOutput } from '@/lib/workflows/dry-run' import type { ExecuteWorkflowServiceRun } from '@/lib/workflows/executor/execute-service' import { getWorkflowExecutionLogStatus } from '@/lib/workflows/executor/execution-state' import { POST as v2Execute } from '@/app/api/v2/workflows/[workflowId]/execute/route' @@ -495,12 +494,17 @@ describe('a dry run', () => { block('save', 'table', { operation: 'upsert_row', tableSelector: tableId, - data: JSON.stringify({ email: 'a@b.co', score: 82, note: 'key={{DRY_SECRET}}' }), + data: JSON.stringify({ + email: 'a@b.co', + score: 82, + note: 'key={{DRY_SECRET}}', + reset_token: 'a', + }), }), notify('notify'), block('read', 'function', { language: 'javascript', - code: 'return { score: , email: , note: , notified: }', + code: 'return { id: , score: , email: , note: , notified: }', }), ], [ @@ -515,21 +519,181 @@ describe('a dry run', () => { expect(result.status, JSON.stringify(result.error)).toBe('completed') expect(await tableRows(tableId)).toEqual([]) - const read = toRecord(result.blockOutputs?.['read.result']) - expect(read).toMatchObject({ + expect(result.blockOutputs?.['read.result']).toEqual({ + id: 'dry_run_row_1', score: 82, email: 'a@b.co', - note: expect.stringContaining('key='), + note: 'key={{DRY_SECRET}}', + notified: 42, }) expect(JSON.stringify(result)).not.toContain(SECRET) const [save, sent] = result.sideEffects?.stubbed ?? [] - expect(toRecord(save.returned.row).data).toEqual({ + const written = { email: 'a@b.co', score: 82, - note: read.note, + note: 'key={{DRY_SECRET}}', + reset_token: '[REDACTED]', + } + expect(save.request).toMatchObject({ data: written }) + expect(save.returned).toEqual({ + success: true, + row: { + id: 'dry_run_row_1', + data: written, + position: 0, + createdAt: '1970-01-01T00:00:00.000Z', + updatedAt: '1970-01-01T00:00:00.000Z', + }, + operation: 'mock_operation', + ignoredColumns: [], + message: 'mock_message', + }) + expect(sent).toMatchObject({ tool: 'http_request', returned: { status: 42 } }) + }) + + it('masks a run secret wherever it appears, though a secret-named column holds part of it', async () => { + const tableId = await createTable() + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('save', 'table', { + operation: 'upsert_row', + tableSelector: tableId, + data: JSON.stringify({ + email: 'a@b.co', + note: 'key={{DRY_SECRET}}', + session_token: SECRET.slice(0, 16), + }), + }), + ], + [['start', 'save']] + ).state + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + const written = { email: 'a@b.co', note: 'key={{DRY_SECRET}}', session_token: '[REDACTED]' } + const [save] = result.sideEffects?.stubbed ?? [] + expect(save.request).toMatchObject({ data: written }) + expect(toRecord(save.returned.row).data).toEqual(written) + expect(JSON.stringify(result)).not.toContain(SECRET.slice(16)) + }) + + it('answers each write that declares it with the output its request determines', async () => { + const tableId = await createTable() + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('add', 'table', { + operation: 'insert_row', + tableSelector: tableId, + data: JSON.stringify({ email: 'a@b.co' }), + }), + block('batch', 'table', { + operation: 'batch_insert_rows', + tableSelector: tableId, + rows: JSON.stringify([{ email: 'b@b.co' }, { email: 'c@d.co', score: 3 }]), + }), + block('edit', 'table', { + operation: 'update_row', + tableSelector: tableId, + rowId: 'row_named', + data: JSON.stringify({ score: 7 }), + }), + block('report', 'file_v4', { + operation: 'file_write', + fileName: 'report.txt', + content: 'héllo', + }), + ], + [ + ['start', 'add'], + ['add', 'batch'], + ['batch', 'edit'], + ['edit', 'report'], + ] + ).state + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(await tableRows(tableId)).toEqual([]) + const placeholderRow = (id: string, data: Record, position: number) => ({ + id, + data, + position, + createdAt: '1970-01-01T00:00:00.000Z', + updatedAt: '1970-01-01T00:00:00.000Z', + }) + const returned = Object.fromEntries( + (result.sideEffects?.stubbed ?? []).map((entry) => [entry.tool, entry.returned]) + ) + expect(returned).toEqual({ + table_insert_row: { + success: true, + row: { ...placeholderRow('dry_run_row_1', { email: 'a@b.co' }, 0), executions: {} }, + ignoredColumns: [], + message: 'mock_message', + }, + table_batch_insert_rows: { + success: true, + rows: [ + { ...placeholderRow('dry_run_row_1', { email: 'b@b.co' }, 0), executions: {} }, + { ...placeholderRow('dry_run_row_2', { email: 'c@d.co', score: 3 }, 1), executions: {} }, + ], + insertedCount: 2, + ignoredColumns: [], + message: 'mock_message', + }, + table_update_row: { + success: true, + row: placeholderRow('row_named', { score: 7 }, 0), + ignoredColumns: [], + message: 'mock_message', + }, + file_write: { + id: 'mock_id', + name: 'report.txt', + size: 6, + url: 'mock_url', + version: 42, + revision: 'mock_revision', + }, + }) + }) + + it('answers a write with the sample alone when its output cannot be derived from the request', async () => { + const tableId = await createTable() + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('batch', 'table', { + operation: 'batch_insert_rows', + tableSelector: tableId, + rows: JSON.stringify({ email: 'a@b.co' }), + }), + ], + [['start', 'batch']] + ).state + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + const [batch] = result.sideEffects?.stubbed ?? [] + expect(batch.request).toMatchObject({ rows: { email: 'a@b.co' } }) + expect(batch.returned).toEqual({ + success: true, + rows: [{ id: 'item_1', name: 'Sample Item', value: 'Sample Value' }], + insertedCount: 42, + ignoredColumns: ['mock_ignoredColumns_item'], + message: 'mock_message', }) - expect(sent).toMatchObject({ tool: 'http_request', returned: sampleToolOutput('http_request') }) - expect(read.notified).toBe(sampleToolOutput('http_request').status) }) it('keeps nothing beyond its own log: no run count and no workspace event', async () => { @@ -794,7 +958,7 @@ describe('a dry run', () => { operation: 'create_document', knowledgeBaseSelector: knowledgeBaseId, manualKnowledgeBaseId: knowledgeBaseId, - name: 'notes.txt', + name: 'notes', content: 'The deploy key is {{DRY_SECRET}}', }), ], @@ -808,7 +972,10 @@ describe('a dry run', () => { const [write] = result.sideEffects?.stubbed ?? [] expect(write).toMatchObject({ tool: 'knowledge_create_document', - returned: { data: { documentName: 'notes.txt' } }, + returned: { + message: 'mock_message', + data: { documentId: 'mock_documentId', documentName: 'notes.txt', type: 'mock_type' }, + }, }) const [document] = toArray(toRecord(write.request).documents) const fileUrl = String(toRecord(document).fileUrl) @@ -818,38 +985,43 @@ describe('a dry run', () => { expect(JSON.stringify(result.sideEffects)).not.toContain(SECRET) }) - it('masks a secret typed into a password field, whatever the field is called', async () => { - const routingKey = `routing-${generateId()}` - const workflowId = await saveWorkflow( - graph( - [ - block('start', 'start_trigger'), - block('page', 'pagerduty', { - operation: 'send_event', - routingKey, - eventAction: 'trigger', - eventSummary: 'Disk full', - eventSource: 'db-1', - eventSeverity: 'critical', - }), - ], - [['start', 'page']] - ).state - ) + it.each([ + ['a', `routing-${generateId()}`], + ['a short', 'rk-7Q'], + ])( + 'masks %s secret typed into a password field, whatever the field is called', + async (_, routingKey) => { + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('page', 'pagerduty', { + operation: 'send_event', + routingKey, + eventAction: 'trigger', + eventSummary: 'Disk full', + eventSource: 'db-1', + eventSeverity: 'critical', + }), + ], + [['start', 'page']] + ).state + ) - const result = await run(workflowId, { dry: true }) + const result = await run(workflowId, { dry: true }) - expect(result.status, JSON.stringify(result.error)).toBe('completed') - expect(result.sideEffects?.stubbed).toEqual([ - expect.objectContaining({ - tool: 'pagerduty_send_event', - request: expect.objectContaining({ - body: expect.objectContaining({ event_action: 'trigger' }), + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.stubbed).toEqual([ + expect.objectContaining({ + tool: 'pagerduty_send_event', + request: expect.objectContaining({ + body: expect.objectContaining({ event_action: 'trigger', routing_key: '[REDACTED]' }), + }), }), - }), - ]) - expect(JSON.stringify(result.sideEffects)).not.toContain(routingKey) - }) + ]) + expect(JSON.stringify(result.sideEffects)).not.toContain(routingKey) + } + ) it('answers a write whose request it cannot build once masked, so the run goes on', async () => { const workflowId = await saveWorkflow( diff --git a/apps/sim/lib/workflows/dry-run/samples.ts b/apps/sim/lib/workflows/dry-run/samples.ts index 89cba38e75f..ec9b6f23789 100644 --- a/apps/sim/lib/workflows/dry-run/samples.ts +++ b/apps/sim/lib/workflows/dry-run/samples.ts @@ -22,42 +22,61 @@ export function sampleBlockOutput(block: { ) } +/** The fields a declared output lays out: its `properties`, or a nested map of fields. */ +function declaredFields(output: unknown): Record | null { + if (!isPlainRecord(output)) return null + if (typeof output.type !== 'string') return output + return (output.type === 'object' || output.type === 'json') && isPlainRecord(output.properties) + ? output.properties + : null +} + /** - * `value` with what it leaves out taken from `sample`: a record field by field, and each item of - * an array from the sample's first item. + * `echoed` laid over `sample` by the declared `output`: field by field where it declares fields, + * item by item where it declares an array's `items`, and anywhere else `echoed` replaces the sample + * whole. */ -function fillFromSample(sample: unknown, value: unknown): unknown { - if (value === undefined) return sample - if (Array.isArray(value)) { +function overlay(output: unknown, sample: unknown, echoed: unknown): unknown { + if (echoed === undefined) return sample + const fields = declaredFields(output) + if (fields) { + return isPlainRecord(echoed) && isPlainRecord(sample) + ? overlayFields(fields, sample, echoed) + : echoed + } + if (isPlainRecord(output) && output.type === 'array' && isPlainRecord(output.items)) { + if (!Array.isArray(echoed)) return echoed const item = Array.isArray(sample) ? sample[0] : undefined - return value.map((entry) => fillFromSample(item, entry)) + return echoed.map((entry) => overlay(output.items, item, entry)) } - if (!isPlainRecord(value) || !isPlainRecord(sample)) return value - return Object.fromEntries([ - ...Object.entries(sample), - ...Object.entries(value).map(([key, entry]) => [ - key, - fillFromSample(Object.hasOwn(sample, key) ? sample[key] : undefined, entry), - ]), - ]) + return echoed +} + +/** The sample's declared fields, each with what `echoed` holds for it laid over it. */ +function overlayFields( + fields: Record, + sample: Record, + echoed: Record +): Record { + return Object.fromEntries( + Object.entries(sample).map(([field, value]) => [ + field, + Object.hasOwn(echoed, field) ? overlay(fields[field], value, echoed[field]) : value, + ]) + ) } /** * Placeholder output shaped like a tool's declared outputs; empty for a tool that declares none. - * `echoed`, what the tool's `dryRunOutput` derived from the request it would have sent, fills each - * declared output it names, and the sample everything else. + * `echoed`, the tool's `dryRunOutput`, is laid over the sample by the declared schema (see + * `ToolConfig.dryRunOutput`). */ export function sampleToolOutput( toolId: string, echoed: Record | null = null ): Record { const outputs = getToolOutputsMetadata(toolId) - const sample = outputs ? generateMockPayloadFromOutputsDefinition(outputs) : {} - if (!echoed) return sample - return Object.fromEntries( - Object.entries(sample).map(([field, value]) => [ - field, - Object.hasOwn(echoed, field) ? fillFromSample(value, echoed[field]) : value, - ]) - ) + if (!outputs) return {} + const sample = generateMockPayloadFromOutputsDefinition(outputs) + return echoed ? overlayFields(outputs, sample, echoed) : sample } diff --git a/apps/sim/tools/file/write.ts b/apps/sim/tools/file/write.ts index 153a424c215..b453bca1ccf 100644 --- a/apps/sim/tools/file/write.ts +++ b/apps/sim/tools/file/write.ts @@ -1,3 +1,4 @@ +import { utf8ByteLength } from '@sim/utils/paste' import type { InternalToolConfig, ToolResponse } from '@/tools/types' interface FileWriteParams { @@ -94,12 +95,12 @@ export const fileWriteTool: InternalToolConfig = /** * A dry run's placeholder names the file the call asks for (a write that would collide is - * suffixed live) and sizes the text it writes; a stored file's name and size stay placeholders. + * suffixed live) and sizes the text it writes, as masked; a stored file's size, and its name + * unless `fileName` overrides it, stay placeholders. */ dryRunOutput: (params) => ({ name: params.fileName, - size: - params.content === undefined ? undefined : new TextEncoder().encode(params.content).length, + size: params.content === undefined ? undefined : utf8ByteLength(params.content), }), transformResponse: async (response) => { diff --git a/apps/sim/tools/knowledge/create_document.ts b/apps/sim/tools/knowledge/create_document.ts index dcf7b594bd7..261735c30af 100644 --- a/apps/sim/tools/knowledge/create_document.ts +++ b/apps/sim/tools/knowledge/create_document.ts @@ -119,12 +119,7 @@ export const knowledgeCreateDocumentTool: InternalToolConfig ({ - message: 'Successfully created document in knowledge base', - data: { - documentName: inferDocumentFileInfo(params.name.trim()).filename, - type: 'document', - enabled: true, - }, + data: { documentName: inferDocumentFileInfo(params.name.trim()).filename }, }), transformResponse: async (response): Promise => { diff --git a/apps/sim/tools/side-effects.ts b/apps/sim/tools/side-effects.ts index 538e307da0b..7c7dc5ac3a5 100644 --- a/apps/sim/tools/side-effects.ts +++ b/apps/sim/tools/side-effects.ts @@ -19,6 +19,7 @@ import { isCustomTool } from '@/executor/constants' import type { SideEffectPolicy, SideEffectSite } from '@/executor/execution/types' import type { ExecutionContext } from '@/executor/types' import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' +import { isNonIdentifyingSecretLiteral } from '@/executor/utils/resolved-secret-match-policy' import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' import { stripCloneSuffixes } from '@/executor/utils/subflow-node-id-codec' import { prepareToolRequest } from '@/tools/request-transport' @@ -120,18 +121,28 @@ function checkScanDepth(depth: number): void { if (depth > MAX_SCAN_DEPTH) throw new SecretScanDepthError() } -/** Every credential-named field masked, and each credential value masked wherever it reappears. */ -function redactCredentials(value: unknown, credentials: string[], depth = 0): unknown { +/** The secrets a call's params carry, as {@link callSecrets} finds them. */ +interface CallSecrets { + /** Values masked wherever they reappear. */ + values: string[] + /** Password fields of the calling blocks, masked by name like a credential-named field. */ + passwordFields: ReadonlySet +} + +/** Every credential-named or password field masked, and each secret value wherever it reappears. */ +function redactCredentials(value: unknown, secrets: CallSecrets, depth = 0): unknown { checkScanDepth(depth) - if (typeof value === 'string') return redactExactSensitiveValues(value, credentials) + if (typeof value === 'string') return redactExactSensitiveValues(value, secrets.values) if (Array.isArray(value)) { - return value.map((item) => redactCredentials(item, credentials, depth + 1)) + return value.map((item) => redactCredentials(item, secrets, depth + 1)) } if (!isPlainRecord(value)) return value return Object.fromEntries( Object.entries(value).map(([key, item]) => [ key, - isSensitiveKey(key) ? REDACTED_MARKER : redactCredentials(item, credentials, depth + 1), + isSensitiveKey(key) || secrets.passwordFields.has(key) + ? REDACTED_MARKER + : redactCredentials(item, secrets, depth + 1), ]) ) } @@ -160,17 +171,19 @@ function passwordParamsFor(blockType: string): ReadonlySet { } /** - * The values in `params` that are secrets: every string under a credential-named field at any - * depth (an access token, a hosted key, an MCP argument named `apiKey`), and whatever was typed - * into a password field of the blocks `blockTypes` names, whatever the field is called. + * The secrets in `params`: every string under a credential-named field at any depth (an access + * token, a hosted key, an MCP argument named `apiKey`), and whatever was typed into a password + * field of the blocks `blockTypes` names, whatever the field is called. A value too short to + * identify a secret ({@link isNonIdentifyingSecretLiteral}) is masked only by its field, so a + * one-letter `reset_token` column never rewrites the rest of a row. */ -function secretValues(params: Record, blockTypes: string[]): string[] { +function callSecrets(params: Record, blockTypes: string[]): CallSecrets { const passwordParams = blockTypes.map(passwordParamsFor) const found = new Set() const collectStrings = (value: unknown, depth: number): void => { checkScanDepth(depth) if (typeof value === 'string') { - if (value !== '') found.add(value) + if (!isNonIdentifyingSecretLiteral(value)) found.add(value) } else if (Array.isArray(value)) { for (const item of value) collectStrings(item, depth + 1) } else if (isPlainRecord(value)) { @@ -191,15 +204,35 @@ function secretValues(params: Record, blockTypes: string[]): st } } visit(params, 0) - return [...found] + return { + values: [...found], + passwordFields: new Set(passwordParams.flatMap((fields) => [...fields])), + } +} + +/** + * `value` with every secret the run resolved masked by its registry, then the secrets `params` + * carry ({@link callSecrets}) by field and by value. The registry goes first: a value masked inside + * a resolved secret would leave the rest of it unmatched. Null when the registry cannot vouch that + * no secret remains. + */ +function maskSecrets( + value: Record, + params: Record, + blockTypes: string[], + registry: ResolvedSecretTraceRegistry | undefined +): Record | null { + const projection = projectResolvedSecretModelContent(value, registry) + if (!projection.safe || !isPlainRecord(projection.value)) return null + const masked = redactCredentials(projection.value, callSecrets(params, blockTypes)) + return isPlainRecord(masked) ? masked : null } /** * The params a tool call's request is described from: the run-context params no tool sends - * dropped, and each secret masked before any request builder sees it ({@link secretValues} by - * field and by value, then every secret the run resolved by its registry), so no transformation a - * builder applies (base64 file content, URL encoding, hashing) can carry a secret past redaction. - * Null when the registry cannot vouch that none remains. + * dropped, and each secret masked ({@link maskSecrets}) before any request builder sees it, so no + * transformation a builder applies (base64 file content, URL encoding, hashing) can carry a secret + * past redaction. Null when the registry cannot vouch that none remains. */ function maskRequestParams( params: Record, @@ -209,16 +242,19 @@ function maskRequestParams( const sent = Object.fromEntries( Object.entries(params).filter(([key]) => !RUN_CONTEXT_PARAMS.has(key)) ) - const masked = redactCredentials(sent, secretValues(sent, blockTypes)) - const projection = projectResolvedSecretModelContent(masked, registry) - return projection.safe && isPlainRecord(projection.value) ? projection.value : null + return maskSecrets(sent, sent, blockTypes, registry) +} + +/** A payload as a record: one that is not is reported under `input`. */ +function asPayloadRecord(payload: unknown): Record { + return isPlainRecord(payload) ? payload : { input: payload } } /** - * A side effect's payload (a stubbed write's request, or an answered block's inputs) as a run may - * report it: the secrets in `params` masked by field and by value, every secret the run resolved - * masked by its registry, then the run's PII redaction applied as it is to a block's output. Null - * when the registry cannot vouch that no secret remains, or the PII redaction fails. + * A side effect's payload (a stubbed write's request and placeholder, or an answered block's + * inputs) as a run may report it: its secrets masked ({@link maskSecrets}), then the run's PII + * redaction applied as it is to a block's output. Null when the registry cannot vouch that no + * secret remains, or the PII redaction fails. */ export async function redactSideEffectPayload(input: { payload: unknown @@ -228,22 +264,23 @@ export async function redactSideEffectPayload(input: { executionContext: ExecutionContext registry: ResolvedSecretTraceRegistry | undefined }): Promise | null> { - let redacted: unknown + let masked: Record | null try { - redacted = redactCredentials( - isPlainRecord(input.payload) ? input.payload : { input: input.payload }, - secretValues(input.params, input.blockTypes) + masked = maskSecrets( + asPayloadRecord(input.payload), + input.params, + input.blockTypes, + input.registry ) } catch (error) { if (error instanceof SecretScanDepthError) return null throw error } - const projection = projectResolvedSecretModelContent(redacted, input.registry) - if (!projection.safe || !isPlainRecord(projection.value)) return null + if (!masked) return null const pii = input.executionContext.piiBlockOutputRedaction - if (!pii?.enabled) return projection.value + if (!pii?.enabled) return masked try { - return await redactObjectStrings(projection.value, { + return await redactObjectStrings(masked, { entityTypes: pii.entityTypes, language: pii.language, customPatterns: pii.customPatterns, @@ -261,9 +298,11 @@ export async function redactSideEffectPayload(input: { * The response answering a write tool call the run's side-effect policy does not send, after the * policy recorded the request it would have sent: `describe` builds it, and `echo` (a tool's * `dryRunOutput`) the output that request determines, both from params whose secrets are already - * masked ({@link maskRequestParams}), and each result is redacted again as a payload - * ({@link redactSideEffectPayload}). Either is null when a step cannot vouch that no secret remains, - * or it cannot be built from the masked params; the write is answered either way. + * masked ({@link maskRequestParams}). Both are redacted again in one {@link redactSideEffectPayload} + * call, so a workspace that redacts PII makes one call per write; the price is that when that + * pass cannot vouch for the pair, both are null. Each is also null when it cannot be built from the + * masked params. The write is answered either way, its placeholder the sample alone without an + * echo. */ export async function answerUnsentWrite( write: UnsentWrite, @@ -284,24 +323,32 @@ export async function answerUnsentWrite( if (!(error instanceof SecretScanDepthError)) throw error maskedParams = null } - const fromMaskedParams = async ( - build: ((maskedParams: Record) => unknown) | undefined - ): Promise | null> => { - const built = - maskedParams && build ? buildFromMaskedParams(call.toolId, build, maskedParams) : null - return built - ? redactSideEffectPayload({ - payload: built.payload, + const described = maskedParams + ? buildFromMaskedParams(call.toolId, input.describe, maskedParams) + : null + const echoed = + maskedParams && input.echo ? buildFromMaskedParams(call.toolId, input.echo, maskedParams) : null + const redacted = + described || echoed + ? await redactSideEffectPayload({ + payload: { + ...(described ? { request: asPayloadRecord(described.payload) } : {}), + ...(echoed ? { echoed: echoed.payload } : {}), + }, params: input.params, blockTypes, executionContext: write.executionContext, registry: input.registry, }) : null + return { + success: true, + output: write.policy.stubWrite({ + ...call, + request: isPlainRecord(redacted?.request) ? redacted.request : null, + echoed: isPlainRecord(redacted?.echoed) ? redacted.echoed : null, + }), } - const request = await fromMaskedParams(input.describe) - const echoed = await fromMaskedParams(input.echo) - return { success: true, output: write.policy.stubWrite({ ...call, request, echoed }) } } /** diff --git a/apps/sim/tools/table/batch_insert_rows.ts b/apps/sim/tools/table/batch_insert_rows.ts index 0031507ea71..983e4892838 100644 --- a/apps/sim/tools/table/batch_insert_rows.ts +++ b/apps/sim/tools/table/batch_insert_rows.ts @@ -2,7 +2,7 @@ import { TABLE_LIMITS } from '@/lib/table/constants' import { selectTableRowSecretProvenance } from '@/lib/table/secret-provenance-selection' import { enrichTableToolSchema } from '@/tools/schema-enrichers' import { TABLE_ID_PARAM } from '@/tools/table/params' -import { tableSuccess } from '@/tools/table/response' +import { placeholderRow, tableSuccess } from '@/tools/table/response' import { IGNORED_COLUMNS_OUTPUT, type TableBatchInsertParams, @@ -55,10 +55,11 @@ export const tableBatchInsertRowsTool: InternalToolConfig< }, }, - /** A dry run's placeholder rows hold the data the call writes; their ids stay placeholders. */ + /** A dry run's placeholder holds the rows the call writes, each with its own placeholder id. */ dryRunOutput: (params) => ({ - rows: params.rows.map((data) => ({ data })), + rows: params.rows.map((data, index) => ({ ...placeholderRow(data, index), executions: {} })), insertedCount: params.rows.length, + ignoredColumns: [], }), transformResponse: async (response): Promise => { diff --git a/apps/sim/tools/table/insert_row.ts b/apps/sim/tools/table/insert_row.ts index 411e171adb0..cd95d08893a 100644 --- a/apps/sim/tools/table/insert_row.ts +++ b/apps/sim/tools/table/insert_row.ts @@ -1,7 +1,7 @@ import { selectTableRowSecretProvenance } from '@/lib/table/secret-provenance-selection' import { enrichTableToolSchema } from '@/tools/schema-enrichers' import { TABLE_ID_PARAM } from '@/tools/table/params' -import { tableSuccess } from '@/tools/table/response' +import { placeholderRow, tableSuccess } from '@/tools/table/response' import { IGNORED_COLUMNS_OUTPUT, type TableRowInsertParams, @@ -52,8 +52,11 @@ export const tableInsertRowTool: InternalToolConfig ({ row: { data: params.data } }), + /** A dry run's placeholder holds the row the call writes, its id and position placeholders. */ + dryRunOutput: (params) => ({ + row: { ...placeholderRow(params.data, 0), executions: {} }, + ignoredColumns: [], + }), transformResponse: async (response): Promise => { const result = await response.json() diff --git a/apps/sim/tools/table/response.ts b/apps/sim/tools/table/response.ts index 659975e9268..82a046af668 100644 --- a/apps/sim/tools/table/response.ts +++ b/apps/sim/tools/table/response.ts @@ -4,3 +4,21 @@ export function tableSuccess>( ): { success: true; output: T & { success: true } } { return { success: true, output: { ...output, success: true } } } + +/** The timestamp a dry run's placeholder row carries: the request cannot know when it is written. */ +const PLACEHOLDER_ROW_TIMESTAMP = '1970-01-01T00:00:00.000Z' + +/** + * A dry run's placeholder for a row a table write returns: the data the call writes (before schema + * coercion, every key kept), and placeholders for the id, position and timestamps the table would + * assign. + */ +export function placeholderRow(data: unknown, position: number, id?: string) { + return { + id: id ?? `dry_run_row_${position + 1}`, + data, + position, + createdAt: PLACEHOLDER_ROW_TIMESTAMP, + updatedAt: PLACEHOLDER_ROW_TIMESTAMP, + } +} diff --git a/apps/sim/tools/table/update_row.ts b/apps/sim/tools/table/update_row.ts index 1f8c2dba94f..27a44e794ec 100644 --- a/apps/sim/tools/table/update_row.ts +++ b/apps/sim/tools/table/update_row.ts @@ -1,7 +1,7 @@ import { selectTableRowSecretProvenance } from '@/lib/table/secret-provenance-selection' import { enrichTableToolSchema } from '@/tools/schema-enrichers' import { TABLE_ID_PARAM } from '@/tools/table/params' -import { tableSuccess } from '@/tools/table/response' +import { placeholderRow, tableSuccess } from '@/tools/table/response' import { IGNORED_COLUMNS_OUTPUT, type TableRowUpdateParams, @@ -59,8 +59,14 @@ export const tableUpdateRowTool: InternalToolConfig ({ row: { id: params.rowId, data: params.data } }), + /** + * A dry run's placeholder is the row named, holding only the fields the call patches: its other + * columns are stored state the request cannot know. + */ + dryRunOutput: (params) => ({ + row: placeholderRow(params.data, 0, params.rowId), + ignoredColumns: [], + }), transformResponse: async (response): Promise => { const result = await response.json() diff --git a/apps/sim/tools/table/upsert_row.ts b/apps/sim/tools/table/upsert_row.ts index 4d9307ec83e..3a4122098a5 100644 --- a/apps/sim/tools/table/upsert_row.ts +++ b/apps/sim/tools/table/upsert_row.ts @@ -1,7 +1,7 @@ import { selectTableRowSecretProvenance } from '@/lib/table/secret-provenance-selection' import { enrichTableToolSchema } from '@/tools/schema-enrichers' import { TABLE_ID_PARAM } from '@/tools/table/params' -import { tableSuccess } from '@/tools/table/response' +import { placeholderRow, tableSuccess } from '@/tools/table/response' import { IGNORED_COLUMNS_OUTPUT, type TableRowInsertParams, @@ -60,8 +60,11 @@ export const tableUpsertRowTool: InternalToolConfig ({ row: { data: params.data } }), + /** + * A dry run's placeholder holds the row the call writes, its id and position placeholders; whether + * it inserts or updates is stored state. + */ + dryRunOutput: (params) => ({ row: placeholderRow(params.data, 0), ignoredColumns: [] }), transformResponse: async (response): Promise => { const result = await response.json() diff --git a/apps/sim/tools/types.ts b/apps/sim/tools/types.ts index 7b1c6a8e607..3c1322a9399 100644 --- a/apps/sim/tools/types.ts +++ b/apps/sim/tools/types.ts @@ -280,11 +280,14 @@ export interface ToolConfig

{ // Output schema - what this tool produces outputs?: Record /** - * How a dry run answers this write without sending it: the outputs the request alone determines, - * never a guess at what the provider or stored state would add. Pure. `params` have every secret - * masked, and the result is redacted like `sideEffects.stubbed[].request`, since it feeds - * downstream blocks. Whatever it leaves out (an id, a field nested in a declared output) comes - * from the sample of {@link outputs}, which alone answers a tool without it. + * Pure: the outputs a dry run's unsent write derives from its request alone, never a guess at + * what the provider or stored state would add. `params` have every secret masked, and the result + * is redacted like `sideEffects.stubbed[].request`. It is laid over the sample of {@link outputs} + * by their declared schema, one rule at every level: field by field where an output declares + * `properties` (a field it does not declare is dropped), item by item where it declares array + * `items`, and anywhere else the value replaces the sample whole, so a hook returns an undeclared + * shape (a `json` row) complete, with placeholders for what the request cannot know. Whatever it + * leaves out keeps the sample. */ dryRunOutput?: (params: P) => Record From 0e46c368d3a8e6b5693150ceb040a2148a37eaa4 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 06:16:03 -0800 Subject: [PATCH 3/3] docs(skills): describe the placeholder overlay for arrays and requested file names --- .agents/skills/add-tools/SKILL.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/.agents/skills/add-tools/SKILL.md b/.agents/skills/add-tools/SKILL.md index 3c1fe2191b6..9c2bdb437c9 100644 --- a/.agents/skills/add-tools/SKILL.md +++ b/.agents/skills/add-tools/SKILL.md @@ -235,11 +235,13 @@ search that returns no email or phone, and an email verifier. 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. - A dry run answers a `write` with a sample of its `outputs`. When downstream blocks read output the - request alone determines (a table write's `row.data`, a created file's `name`), declare a pure - `dryRunOutput(params)` returning just those fields; it gets params with secrets masked. It is laid - over the sample by the declared schema: field by field where an output declares `properties`, - whole anywhere else, so return an undeclared shape (a `json` row) complete, with placeholders for - what the request cannot know. Never guess at what the provider would add. + request alone determines (a table write's `row.data`, a file write's requested name), declare a + pure `dryRunOutput(params)` returning just those fields; it gets params with secrets masked. It is + laid over the sample by the declared schema: field by field where an output declares `properties`, + item by item where an array declares `items` (undeclared fields are dropped), and whole anywhere + else, so return an undeclared shape (a `json` row) complete, with placeholders for what the request + cannot know. Never guess at what the provider or stored state would add (a collision suffix on a + file name, an id). ## Critical Rules for Parameters