diff --git a/.agents/skills/add-tools/SKILL.md b/.agents/skills/add-tools/SKILL.md index 955ff96b57c..9c2bdb437c9 100644 --- a/.agents/skills/add-tools/SKILL.md +++ b/.agents/skills/add-tools/SKILL.md @@ -234,6 +234,14 @@ 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 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 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..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 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 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 03a17dd3910..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 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 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 21ef948cd3a..b4d0189c191 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 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 } /** 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..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 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 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 ff8a15150f8..4c020bcc989 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -206,6 +206,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 +485,217 @@ 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}}', + reset_token: 'a', + }), + }), + notify('notify'), + block('read', 'function', { + language: 'javascript', + code: 'return { id: , 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([]) + expect(result.blockOutputs?.['read.result']).toEqual({ + id: 'dry_run_row_1', + score: 82, + email: 'a@b.co', + note: 'key={{DRY_SECRET}}', + notified: 42, + }) + expect(JSON.stringify(result)).not.toContain(SECRET) + const [save, sent] = result.sideEffects?.stubbed ?? [] + const written = { + email: 'a@b.co', + score: 82, + 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', + }) + }) + 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) @@ -746,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}}', }), ], @@ -758,7 +970,13 @@ 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: { + 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) const content = Buffer.from(fileUrl.slice(fileUrl.indexOf(',') + 1), 'base64').toString('utf8') @@ -767,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 77d22bf68d6..ec9b6f23789 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,61 @@ 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 { +/** 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 +} + +/** + * `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 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 echoed.map((entry) => overlay(output.items, item, 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`, 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) - return outputs ? generateMockPayloadFromOutputsDefinition(outputs) : {} + if (!outputs) return {} + const sample = generateMockPayloadFromOutputsDefinition(outputs) + return echoed ? overlayFields(outputs, sample, echoed) : sample } 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..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 { @@ -92,6 +93,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, 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 : utf8ByteLength(params.content), + }), + 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..261735c30af 100644 --- a/apps/sim/tools/knowledge/create_document.ts +++ b/apps/sim/tools/knowledge/create_document.ts @@ -117,6 +117,11 @@ export const knowledgeCreateDocumentTool: InternalToolConfig ({ + data: { documentName: inferDocumentFileInfo(params.name.trim()).filename }, + }), + 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..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, @@ -259,10 +296,13 @@ 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}). 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, @@ -270,6 +310,7 @@ export async function answerUnsentWrite( params: Record registry: ResolvedSecretTraceRegistry | undefined describe: (maskedParams: Record) => unknown + echo?: (maskedParams: Record) => Record } ): Promise { const { call } = write @@ -283,33 +324,47 @@ export async function answerUnsentWrite( 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, - }) + ? buildFromMaskedParams(call.toolId, input.describe, maskedParams) : null - return { success: true, output: write.policy.stubWrite({ ...call, request }) } + 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, + }), + } } /** - * 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..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,6 +55,13 @@ export const tableBatchInsertRowsTool: InternalToolConfig< }, }, + /** A dry run's placeholder holds the rows the call writes, each with its own placeholder id. */ + dryRunOutput: (params) => ({ + rows: params.rows.map((data, index) => ({ ...placeholderRow(data, index), executions: {} })), + insertedCount: params.rows.length, + ignoredColumns: [], + }), + 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..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,6 +52,12 @@ export const tableInsertRowTool: InternalToolConfig ({ + row: { ...placeholderRow(params.data, 0), executions: {} }, + ignoredColumns: [], + }), + transformResponse: async (response): Promise => { const result = await response.json() const data = result.data || result 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 612b64ca59b..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,6 +59,15 @@ export const tableUpdateRowTool: InternalToolConfig ({ + row: placeholderRow(params.data, 0, params.rowId), + ignoredColumns: [], + }), + 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..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,6 +60,12 @@ export const tableUpsertRowTool: InternalToolConfig ({ row: placeholderRow(params.data, 0), ignoredColumns: [] }), + 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..3c1322a9399 100644 --- a/apps/sim/tools/types.ts +++ b/apps/sim/tools/types.ts @@ -279,6 +279,17 @@ export interface ToolConfig

{ > // Output schema - what this tool produces outputs?: Record + /** + * 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 // OAuth configuration for this tool (if it requires authentication) oauth?: OAuthConfig