diff --git a/apps/sim/blocks/blocks/table.ts b/apps/sim/blocks/blocks/table.ts index affb9ae5f1b..cee3e621c26 100644 --- a/apps/sim/blocks/blocks/table.ts +++ b/apps/sim/blocks/blocks/table.ts @@ -4,6 +4,7 @@ import { TABLE_LIMITS } from '@/lib/table/constants' import { filterRulesToFilter, sortRulesToSort } from '@/lib/table/query-builder/converters' import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types' import { + failToolCallOnError, isToolCall, mapperOperation, parseOptionalNumberInput, @@ -94,15 +95,21 @@ interface ParsedParams { * list) falls back to the model's `filter`/`sort` arg instead of discarding it; the canvas keeps * the builder's result. */ -function resolveBuilderOrJson( +function resolveBuilderOrJson( builderActive: boolean, - fromBuilder: () => unknown, + builderValue: unknown, + fromBuilder: (rules: TRule[]) => unknown, json: unknown, fieldName: string, context: BlockToolParamsContext | undefined ): unknown { if (builderActive) { - const built = fromBuilder() || undefined + // A tool row's rules that did not decode to an array are corrupt, not empty: falling back + // would run the operation on the model's filter instead of the one the user pinned. + if (isToolCall(context) && !Array.isArray(builderValue)) { + throw new Error(`Invalid ${fieldName} builder rules: expected a list of conditions.`) + } + const built = fromBuilder(builderValue as TRule[]) || undefined if (built !== undefined || !isToolCall(context) || !json) return built } else if (!json) { return undefined @@ -116,8 +123,8 @@ function resolveBulkFilter( ): unknown { return resolveBuilderOrJson( params.bulkFilterMode === 'builder' && Boolean(params.bulkFilterBuilder), - () => - filterRulesToFilter(params.bulkFilterBuilder as Parameters[0]), + params.bulkFilterBuilder, + filterRulesToFilter, params.filter, 'Filter', context @@ -195,14 +202,16 @@ const paramTransformers: Record< const builderMode = params.builderMode === 'builder' const filter = resolveBuilderOrJson( builderMode && Boolean(params.filterBuilder), - () => filterRulesToFilter(params.filterBuilder as Parameters[0]), + params.filterBuilder, + filterRulesToFilter, params.filter, 'Filter', context ) const sort = resolveBuilderOrJson( builderMode && Boolean(params.sortBuilder), - () => sortRulesToSort(params.sortBuilder as Parameters[0]), + params.sortBuilder, + sortRulesToSort, params.sort, 'Sort', context @@ -760,7 +769,7 @@ Return ONLY the sort JSON:`, const transformer = paramTransformers[mapperOperation(params, context)] if (transformer) { - return transformer(rest as TableBlockParams, context) + return failToolCallOnError(context, () => transformer(rest as TableBlockParams, context)) } return rest diff --git a/apps/sim/blocks/blocks/table_v2.ts b/apps/sim/blocks/blocks/table_v2.ts index 2f340ee80f3..e7e303b2934 100644 --- a/apps/sim/blocks/blocks/table_v2.ts +++ b/apps/sim/blocks/blocks/table_v2.ts @@ -13,6 +13,7 @@ import type { } from '@/lib/table/types' import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types' import { + failToolCallOnError, mapperOperation, resolveTableColumnSelection, TABLE_OUTPUT_COLUMNS_INPUT, @@ -570,7 +571,7 @@ Return ONLY the JSON object:`, const { operation, ...rest } = params const transformer = paramTransformers[mapperOperation(params, context)] if (transformer) { - return transformer(rest as TableBlockParams, context) + return failToolCallOnError(context, () => transformer(rest as TableBlockParams, context)) } return rest }, diff --git a/apps/sim/blocks/utils.ts b/apps/sim/blocks/utils.ts index 7e554c256da..c9a0fb240dd 100644 --- a/apps/sim/blocks/utils.ts +++ b/apps/sim/blocks/utils.ts @@ -23,6 +23,7 @@ import { SIM_AUTO_MODEL_ID, } from '@/providers/models' import { isPiSupportedModel } from '@/providers/pi-providers' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { ProviderId } from '@/providers/types' import { getProviderFromModel } from '@/providers/utils' import { useProvidersStore } from '@/stores/providers/store' @@ -948,6 +949,33 @@ export function toolCallArg( return isToolCall(context) ? value : undefined } +/** + * What the model is told when a block rejects a tool call's params. Deliberately static: a + * mapper's own message can quote the value it rejected (`Invalid Limit "…"`, a JSON parse + * snippet), and by then a model-written `{{SECRET}}` placeholder has been resolved to plaintext. + */ +const TOOL_CALL_PARAMS_REJECTED_MESSAGE = + 'The tool was not run: its arguments could not be mapped to the tool inputs. Check the argument values (filters, sort, row data, limit) and try again.' + +/** + * Runs a mapper body, and on a tool call turns any failure into a {@link ToolCallParamsError} so + * the call fails instead of running on the raw merged params. Use it where those raw params are + * unsafe: a pinned value under a block-only key (a filter builder) drops out of them, leaving the + * model's own argument for the same tool param in its place. The original error stays on `cause` + * for server logs; the canvas rethrows it unchanged. + */ +export function failToolCallOnError( + context: BlockToolParamsContext | undefined, + map: () => T +): T { + try { + return map() + } catch (error) { + if (!isToolCall(context) || error instanceof ToolCallParamsError) throw error + throw new ToolCallParamsError(TOOL_CALL_PARAMS_REJECTED_MESSAGE, { cause: error }) + } +} + /** * The operation a block's `tools.config.params` mapper runs for. A tool call passes it only in * `context`: a stored tool row keeps its operation outside its params, and a tool that declares its diff --git a/apps/sim/executor/handlers/human-in-the-loop/handler.ts b/apps/sim/executor/handlers/human-in-the-loop/handler.ts index c20676f8e8c..29573871eda 100644 --- a/apps/sim/executor/handlers/human-in-the-loop/handler.ts +++ b/apps/sim/executor/handlers/human-in-the-loop/handler.ts @@ -28,6 +28,7 @@ import type { BlockHandler, ExecutionContext, PauseMetadata } from '@/executor/t import { collectBlockData } from '@/executor/utils/block-data' import { convertBuilderDataToJson, convertPropertyValue } from '@/executor/utils/builder-data' import { parseObjectStrings } from '@/executor/utils/json' +import { ToolCallParamsError } from '@/providers/tool-params-error' import { buildBlockToolParamsTransform } from '@/providers/utils' import type { SerializedBlock } from '@/serializer/types' import { executeTool } from '@/tools' @@ -449,7 +450,9 @@ export class HumanInTheLoopBlockHandler implements BlockHandler { return paramsTransform(visibleParams) } catch (error) { // Mirrors `prepareToolExecution`: a transform that throws must not take the - // notification down with it, so the raw params still go out. + // notification down with it, so the raw params still go out — except a + // `ToolCallParamsError`, whose raw params are unsafe to send. + if (error instanceof ToolCallParamsError) throw error logger.warn('Notification tool params transform failed, using raw params', { toolId, error, diff --git a/apps/sim/executor/handlers/human-in-the-loop/notification-params.test.ts b/apps/sim/executor/handlers/human-in-the-loop/notification-params.test.ts index dc4bd9d32a4..57066d13dab 100644 --- a/apps/sim/executor/handlers/human-in-the-loop/notification-params.test.ts +++ b/apps/sim/executor/handlers/human-in-the-loop/notification-params.test.ts @@ -27,6 +27,19 @@ const notifierBlock = { outputs: {}, } +/** A notifier whose mapper rejects its stored params, as Table's does for a corrupt filter. */ +const rejectingNotifierBlock = { + ...notifierBlock, + tools: { + ...notifierBlock.tools, + config: { + params: () => { + throw new ToolCallParamsError('Invalid JSON in Filter') + }, + }, + }, +} + vi.mock('@/tools/utils', () => toolsUtilsMock) vi.mock('@/tools', () => toolsMock) @@ -34,15 +47,18 @@ vi.mock('@/tools', () => toolsMock) import { getBlock } from '@/blocks/registry' import { PAUSE_RESUME } from '@/executor/constants' import { HumanInTheLoopBlockHandler } from '@/executor/handlers/human-in-the-loop/handler' +import { ToolCallParamsError } from '@/providers/tool-params-error' toolsUtilsMockFns.mockGetTool.mockReturnValue({ id: 'notifier_send', params: { channel: { type: 'string' }, silent: { type: 'boolean' } }, }) -vi.mocked(getBlock).mockImplementation((type: string) => - type === 'notifier' ? (notifierBlock as never) : undefined -) +vi.mocked(getBlock).mockImplementation((type: string) => { + if (type === 'notifier') return notifierBlock as never + if (type === 'rejecting_notifier') return rejectingNotifierBlock as never + return undefined +}) const executed: Array> = [] toolsMockFns.mockExecuteTool.mockImplementation( @@ -53,7 +69,10 @@ toolsMockFns.mockExecuteTool.mockImplementation( ) /** Runs one notification whose channel was configured in ADVANCED mode. */ -async function runNotification(blockTypeId: string): Promise> { +async function runNotification( + blockTypeId: string, + notifierType = 'notifier' +): Promise> { executed.length = 0 const block = { @@ -74,7 +93,7 @@ async function runNotification(blockTypeId: string): Promise { }) }) + it('v2 skips a notification whose mapper rejects its params instead of sending raw ones', async () => { + await runNotification('human_in_the_loop_v2', 'rejecting_notifier') + expect(executed).toEqual([]) + }) + it('v1 keeps handing the tool its raw stored values', async () => { // Deliberately unchanged: altering what an already-configured v1 notification sends // is exactly the break v2 exists to avoid. diff --git a/apps/sim/executor/handlers/pi/local/sim-tools.ts b/apps/sim/executor/handlers/pi/local/sim-tools.ts index ff27d7fd9b4..bcfab3229a8 100644 --- a/apps/sim/executor/handlers/pi/local/sim-tools.ts +++ b/apps/sim/executor/handlers/pi/local/sim-tools.ts @@ -23,6 +23,7 @@ import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-sec import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' import { annotateDuplicateToolBindings } from '@/executor/utils/tool-binding-labels' import { assignProviderToolIdentities } from '@/providers/tool-identity' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { ProviderToolConfig } from '@/providers/types' import { transformBlockTool } from '@/providers/utils' import { executeTool } from '@/tools' @@ -129,8 +130,9 @@ function buildSimToolSpec( * declares. Skipping it here left Pi local tools receiving a raw selector id * where the tool expected a resolved one, and `'false'` where it expected `false`. * - * A failure keeps the raw params, matching `prepareToolExecution`. The projected - * copy is only transformed when the raw one was, so the two stay comparable. + * A failure keeps the raw params, matching `prepareToolExecution`, except a + * `ToolCallParamsError`, which fails the call. The projected copy is only + * transformed when the raw one was, so the two stay comparable. */ let transformApplied = false const applyParamsTransform = (input: Record): Record => { @@ -140,6 +142,7 @@ function buildSimToolSpec( transformApplied = true return transformed } catch (error) { + if (error instanceof ToolCallParamsError) throw error logger.warn('paramsTransform failed for Pi local tool, using raw params', { error }) return input } diff --git a/apps/sim/lib/workflows/search-replace/json-value-fields.ts b/apps/sim/lib/workflows/search-replace/json-value-fields.ts index 37b78cc08f7..05c36473544 100644 --- a/apps/sim/lib/workflows/search-replace/json-value-fields.ts +++ b/apps/sim/lib/workflows/search-replace/json-value-fields.ts @@ -110,11 +110,18 @@ export function isSearchableJsonValueSubBlock( ) } +/** + * Rule builders stay as their stored JSON text in a tool row: the replacer edits a tool param's + * raw text, and has no path into a builder's rule array the way it does for `table` cells. + */ +const RAW_TEXT_TOOL_PARAM_SUBBLOCK_TYPES = new Set(['filter-builder', 'sort-builder']) + export function shouldParseSerializedSubBlockValue( subBlockType: SubBlockType | undefined ): subBlockType is SubBlockType { return Boolean( subBlockType && + !RAW_TEXT_TOOL_PARAM_SUBBLOCK_TYPES.has(subBlockType) && (isSearchableJsonValueSubBlock(subBlockType) || holdsObjectValue({ type: subBlockType })) ) } diff --git a/apps/sim/lib/workflows/search-replace/replacements.test.ts b/apps/sim/lib/workflows/search-replace/replacements.test.ts index 3ed26d831c4..bd8c99c7d62 100644 --- a/apps/sim/lib/workflows/search-replace/replacements.test.ts +++ b/apps/sim/lib/workflows/search-replace/replacements.test.ts @@ -6,6 +6,7 @@ import { SEARCH_REPLACE_BLOCK_CONFIGS, } from '@/lib/workflows/search-replace/search-replace.fixtures' import { WORKFLOW_SEARCH_SUBFLOW_FIELD_IDS } from '@/lib/workflows/search-replace/subflow-fields' +import { TableV2Block } from '@/blocks/blocks/table_v2' /** * Asserts real tool params and outputs, which the global `@/tools/metadata` @@ -417,6 +418,64 @@ describe('buildWorkflowSearchReplacePlan', () => { ]) }) + it('replaces a value inside filter builder rules stored as a serialized tool input param', () => { + const workflow = createSearchReplaceWorkflowFixture() + const rule = { id: 'r1', logicalOperator: 'and', column: 'status', operator: 'eq' } + workflow.blocks['tool-input-1'] = { + id: 'tool-input-1', + type: 'custom', + name: 'Tool Input Block', + position: { x: 0, y: 0 }, + enabled: true, + outputs: {}, + subBlocks: { + tools: { + id: 'tools', + type: 'tool-input', + value: [ + { + type: 'table_v2', + toolId: 'table_query_rows_v2', + operation: 'query_rows', + title: 'Table', + params: { + tableId: 'tbl_1', + filterBuilder: JSON.stringify([{ ...rule, value: 'pending' }]), + }, + }, + ], + }, + }, + } + const matches = indexWorkflowSearchMatches({ + workflow, + query: 'pending', + mode: 'text', + blockConfigs: { + ...SEARCH_REPLACE_BLOCK_CONFIGS, + custom: { subBlocks: [{ id: 'tools', title: 'Tools', type: 'tool-input' }] }, + table_v2: TableV2Block, + }, + }).filter((match) => match.blockId === 'tool-input-1' && match.editable) + + const plan = buildWorkflowSearchReplacePlan({ + blocks: workflow.blocks, + matches, + selectedMatchIds: new Set(matches.map((match) => match.id)), + defaultReplacement: 'approved', + }) + + expect(plan.conflicts).toEqual([]) + expect(plan.updates).toHaveLength(1) + expect(plan.updates[0].nextValue).toEqual([ + expect.objectContaining({ + params: expect.objectContaining({ + filterBuilder: JSON.stringify([{ ...rule, value: 'approved' }]), + }), + }), + ]) + }) + it('conflicts when a selected duplicate file occurrence is removed', () => { const workflow = createSearchReplaceWorkflowFixture() const files = [ diff --git a/apps/sim/providers/conversation-continuation.test.ts b/apps/sim/providers/conversation-continuation.test.ts index 0c1575b39f6..41976abe745 100644 --- a/apps/sim/providers/conversation-continuation.test.ts +++ b/apps/sim/providers/conversation-continuation.test.ts @@ -20,6 +20,7 @@ import { setEncryptedConversationMessage, } from '@/providers/conversation-metadata' import { executeProviderTool } from '@/providers/runtime-context' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { Message, ProviderRequest } from '@/providers/types' import { prepareToolExecution } from '@/providers/utils' @@ -137,6 +138,19 @@ describe('durable conversation restoration and continuation', () => { ).rejects.toBe(refused) }) + it('records a block mapper rejection as a failed tool call without dispatching it', async () => { + vi.mocked(prepareToolExecution).mockImplementationOnce(() => { + throw new ToolCallParamsError('Invalid JSON in Filter') + }) + const session = await pendingSession() + await continuePendingConversationCalls(toolRequest, session) + expect(session.getPendingCalls()).toEqual([]) + expect(session.getMessages('openai', 'model-a', 'binding-a')[1].content).toContain( + 'Invalid JSON in Filter' + ) + expect(executeProviderTool).not.toHaveBeenCalled() + }) + it('clears a previously restored native message when the next fallback binding changes', async () => { const messages = toolGroup() const native = { diff --git a/apps/sim/providers/conversation-continuation.ts b/apps/sim/providers/conversation-continuation.ts index f8e06c1ffaf..117d604cb2b 100644 --- a/apps/sim/providers/conversation-continuation.ts +++ b/apps/sim/providers/conversation-continuation.ts @@ -16,6 +16,7 @@ import { import { getProviderHistoryProtocol, requiresNativeToolHistory } from '@/providers/history-adapters' import { executeProviderTool } from '@/providers/runtime-context' import { isAbortError } from '@/providers/streaming-tool-loop-shared' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { Message, ProviderId, ProviderRequest } from '@/providers/types' import { prepareToolExecution } from '@/providers/utils' @@ -78,15 +79,29 @@ export async function continuePendingConversationCalls( }) continue } - const { executionParams } = prepareToolExecution( - tool, - args, - { - ...request, - resolveToolInvocationId: () => call.invocationId, - }, - call.providerCallId - ) + let executionParams: ReturnType['executionParams'] + try { + executionParams = prepareToolExecution( + tool, + args, + { + ...request, + resolveToolInvocationId: () => call.invocationId, + }, + call.providerCallId + ).executionParams + } catch (error) { + // Any other preparation refusal aborts the continuation; a block mapper rejecting the + // arguments is a failed tool call, recorded as the original attempt would have reported it. + if (!(error instanceof ToolCallParamsError)) throw error + const result = { success: false, output: {}, error: getErrorMessage(error) } + await session.recordToolResult({ + invocationId: call.invocationId, + rawResponse: result, + modelResponse: result, + }) + continue + } try { logger.info('Retrying an Agent tool with an unrecorded outcome') await executeProviderTool(tool.id, executionParams) diff --git a/apps/sim/providers/tool-params-error.ts b/apps/sim/providers/tool-params-error.ts new file mode 100644 index 00000000000..73ec4b30a56 --- /dev/null +++ b/apps/sim/providers/tool-params-error.ts @@ -0,0 +1,20 @@ +/** + * Thrown by a block's `tools.config.params` mapper when a tool call must not run at all. + * + * A mapper failure on a tool call is normally logged and the tool runs with the raw merged + * params instead (`prepareToolExecution`, Pi's local tools, Human-in-the-loop v2 notifications). + * That fallback drops the canonical collapse along with everything else, so a model-supplied + * argument the user's pinned value had hidden comes back: a Table bulk delete would run with the + * model's `filter` rather than the filter the user configured. This error is rethrown instead, + * and the call is reported as failed, so its message reaches the model unredacted and must + * never quote an argument value. + * + * Deliberately a leaf module: blocks import it, and `@/blocks/utils` already imports + * `@/providers/utils`. + */ +export class ToolCallParamsError extends Error { + constructor(message: string, options?: { cause?: unknown }) { + super(message, options) + this.name = 'ToolCallParamsError' + } +} diff --git a/apps/sim/providers/utils.test.ts b/apps/sim/providers/utils.test.ts index fc00bfb146e..953cae3fb4b 100644 --- a/apps/sim/providers/utils.test.ts +++ b/apps/sim/providers/utils.test.ts @@ -1,4 +1,5 @@ import { resetEnvFlagsMock, setEnvFlags } from '@sim/testing' +import { omit } from '@sim/utils/object' import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const workflowMetadataMocks = vi.hoisted(() => ({ @@ -11,6 +12,13 @@ vi.mock('@/lib/internal/workflows/read-tool-enrichment', () => ({ readWorkflowMetadataForTool: workflowMetadataMocks.readWorkflowMetadataForTool, })) +import { + filterRulesToFilter, + filterRulesToPredicate, + sortRulesToSort, +} from '@/lib/table/query-builder/converters' +import { normalizeTablePredicate } from '@/lib/table/query-builder/predicate' +import type { FilterRule, Predicate, SortRule } from '@/lib/table/types' import { getParamsForToolOperation } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/param-dependents' import { CbInsightsV2Block } from '@/blocks/blocks/cbinsights' import { CheckrV2Block } from '@/blocks/blocks/checkr' @@ -22,6 +30,8 @@ import { RampBlock } from '@/blocks/blocks/ramp' import { ResendV2Block } from '@/blocks/blocks/resend' import { RevenueCatBlock } from '@/blocks/blocks/revenuecat' import { SharepointV2Block } from '@/blocks/blocks/sharepoint' +import { TableBlock } from '@/blocks/blocks/table' +import { TableV2Block } from '@/blocks/blocks/table_v2' import { TrelloBlock } from '@/blocks/blocks/trello' import { VideoGeneratorV3Block } from '@/blocks/blocks/video_generator' import * as blockRegistry from '@/blocks/registry' @@ -33,6 +43,7 @@ import { supportsTemperature, } from '@/providers/models' import { assignProviderToolIdentities } from '@/providers/tool-identity' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { ProviderToolConfig } from '@/providers/types' import { buildBlockToolParamsTransform, @@ -97,6 +108,10 @@ import { resendCreateBroadcastTool } from '@/tools/resend/create_broadcast' import type { CreateBroadcastParams } from '@/tools/resend/types' import { revenuecatGetCustomerTool } from '@/tools/revenuecat/get_customer' import { getListTool as sharepointGetListTool } from '@/tools/sharepoint/get_list' +import { tableDeleteRowsByFilterTool } from '@/tools/table/delete_rows_by_filter' +import { tableQueryRowsTool } from '@/tools/table/query_rows' +import { tableQueryRowsV2Tool } from '@/tools/table/query_rows_v2' +import { tableUpdateRowsByFilterTool } from '@/tools/table/update_rows_by_filter' import { trelloListListsTool } from '@/tools/trello/list_lists' import { trelloUpdateListTool } from '@/tools/trello/update_list' import { falaiVideoTool } from '@/tools/video/falai' @@ -924,6 +939,142 @@ describe('Resend broadcast recipient on a tool row', () => { }) }) +describe('Table builder rules pinned on an agent tool row', () => { + const pinnedRules: FilterRule[] = [ + { id: 'r1', logicalOperator: 'and', column: 'status', operator: 'eq', value: 'active' }, + ] + const modelFilter: Predicate = { field: 'status', op: 'eq', value: 'archived' } + + async function runTableTool( + block: typeof TableBlock, + operation: string, + tool: { toolEnrichment?: unknown }, + stored: Record, + modelArgs: Record + ) { + const providerTool = await transformBlockTool( + { type: block.type, operation, params: { tableId: 'tbl_1', ...stored } }, + { + selectedOperation: operation, + getAllBlocks: () => [block], + // Schema enrichment reads the live table; what reaches the tool does not depend on it. + getTool: () => omit(tool, ['toolEnrichment']), + } + ) + if (!providerTool) throw new Error('Table agent tool was not created') + return prepareToolExecution(providerTool, modelArgs, {}, undefined).executionParams + } + + it.each([ + { operation: 'update_rows_by_filter', tool: tableUpdateRowsByFilterTool }, + { operation: 'delete_rows_by_filter', tool: tableDeleteRowsByFilterTool }, + ])( + 'runs v2 $operation on the pinned filter, not the model filter', + async ({ operation, tool }) => { + const params = await runTableTool( + TableV2Block, + operation, + tool, + { filterBuilder: JSON.stringify(pinnedRules), data: '{"status":"done"}' }, + { filter: modelFilter } + ) + expect(params.filter).toEqual(filterRulesToPredicate(pinnedRules)) + } + ) + + it('lets the model filter through an emptied v2 filter builder', async () => { + const params = await runTableTool( + TableV2Block, + 'delete_rows_by_filter', + tableDeleteRowsByFilterTool, + { filterBuilder: '[]' }, + { filter: modelFilter } + ) + expect(params.filter).toEqual(normalizeTablePredicate(modelFilter)) + }) + + it('fails the call instead of running a v2 bulk delete on the model filter', async () => { + await expect( + runTableTool( + TableV2Block, + 'delete_rows_by_filter', + tableDeleteRowsByFilterTool, + { filterBuilder: '[{"column":' }, + { filter: modelFilter } + ) + ).rejects.toThrow(ToolCallParamsError) + }) + + it('never quotes a rejected argument back to the model', async () => { + const resolvedSecret = 'sk-live-fixture-value' + const rejection = runTableTool( + TableV2Block, + 'query_rows', + tableQueryRowsV2Tool, + {}, + { limit: resolvedSecret } + ) + await expect(rejection).rejects.toThrow(ToolCallParamsError) + await expect(rejection).rejects.not.toThrow(resolvedSecret) + }) + + it('sends the pinned v2 sort builder as a sort spec', async () => { + const sortRules: SortRule[] = [{ id: 's1', column: 'wins', direction: 'desc' }] + const params = await runTableTool( + TableV2Block, + 'query_rows', + tableQueryRowsV2Tool, + { sortBuilder: JSON.stringify(sortRules) }, + {} + ) + expect(params.order).toEqual([{ field: 'wins', direction: 'desc' }]) + }) + + it('runs a v1 bulk update on the pinned filter, not the model filter', async () => { + const params = await runTableTool( + TableBlock, + 'update_rows_by_filter', + tableUpdateRowsByFilterTool, + { + bulkFilterMode: 'builder', + bulkFilterBuilder: JSON.stringify(pinnedRules), + data: '{"status":"done"}', + }, + { filter: { status: 'archived' } } + ) + expect(params.filter).toEqual(filterRulesToFilter(pinnedRules)) + }) + + it('fails the call instead of running a v1 bulk delete on the model filter', async () => { + await expect( + runTableTool( + TableBlock, + 'delete_rows_by_filter', + tableDeleteRowsByFilterTool, + { bulkFilterMode: 'builder', bulkFilterBuilder: '[{"column":"status","value":"a"b"}]' }, + { filter: { status: 'archived' } } + ) + ).rejects.toThrow(ToolCallParamsError) + }) + + it('applies the pinned v1 query filter and sort builders', async () => { + const sortRules: SortRule[] = [{ id: 's1', column: 'wins', direction: 'desc' }] + const params = await runTableTool( + TableBlock, + 'query_rows', + tableQueryRowsTool, + { + builderMode: 'builder', + filterBuilder: JSON.stringify(pinnedRules), + sortBuilder: JSON.stringify(sortRules), + }, + { filter: { status: 'archived' }, sort: { name: 'asc' } } + ) + expect(params.filter).toEqual(filterRulesToFilter(pinnedRules)) + expect(params.sort).toEqual(sortRulesToSort(sortRules)) + }) +}) + describe('Excel targets through agent execution', () => { it.each(['model', 'configured'] as const)( 'clears the %s range after canonical argument mapping', diff --git a/apps/sim/providers/utils.ts b/apps/sim/providers/utils.ts index 955a96b865f..ecac17d3338 100644 --- a/apps/sim/providers/utils.ts +++ b/apps/sim/providers/utils.ts @@ -17,8 +17,10 @@ import { buildCanonicalIndex, type CanonicalGroup, type CanonicalModeOverrides, + getCanonicalValues, isCanonicalPair, resolveActiveCanonicalValue, + resolveCanonicalMode, scopeCanonicalModesForTool, } from '@/lib/workflows/subblocks/visibility' import { omitConditionHiddenParams } from '@/lib/workflows/tool-input/hidden-params' @@ -52,6 +54,7 @@ import { getProviderToolModelInputRegistry, registerPreparedProviderToolInputProvenance, } from '@/providers/tool-input-provenance' +import { ToolCallParamsError } from '@/providers/tool-params-error' import type { ModelPricing, ProviderId, ProviderToolConfig } from '@/providers/types' import { isNonEmpty, mergeToolParameters } from '@/tools/merge-params' import { buildToolParamShapes, decodeToolParams } from '@/tools/param-shape' @@ -537,7 +540,10 @@ type BlockToolParamsFn = ( * Four steps, in an order each of which is load-bearing: * * 1. Collapse canonical basic/advanced pairs onto the canonical id, so a value stored - * under `manualChannel` becomes the `channel` the tool declares. + * under `manualChannel` becomes the `channel` the tool declares. The active member is + * picked from the decoded values, as the canvas sees them: a builder the user emptied + * is stored as `'[]'`, which reads as filled until it decodes to `[]`, and would + * otherwise hide the model's argument for the other member. * 2. Decode the stringified values back to their real shapes, and expand a * `checkbox-list` onto its option params. After the collapse so a pair is decoded * once under its canonical id, and BEFORE the block's `params` function because @@ -595,16 +601,19 @@ export function buildBlockToolParamsTransform(config: { const paramsTransform = needsTransform ? (params: Record): Record => { let result = { ...params } + const decodedMembers = decodeToolParams(params, paramShapes) for (const group of canonicalGroups) { // Route through the canonical SOT: an explicit scoped override wins, else the value // heuristic - no `?? 'basic'` (which dropped an advanced-only value when basic was empty). const explicitMode = scopedCanonicalModes?.[group.canonicalId] - const chosen = resolveActiveCanonicalValue( + const mode = resolveCanonicalMode( group, - result, + decodedMembers, explicitMode ? { [group.canonicalId]: explicitMode } : undefined ) + const { basicValue, advancedValue } = getCanonicalValues(group, result) + const chosen = mode === 'advanced' ? advancedValue : basicValue const sourceIds = [group.basicId, ...group.advancedIds].filter(Boolean) as string[] result = omit(result, sourceIds) @@ -1626,6 +1635,7 @@ export function prepareToolExecution( toolParams = tool.paramsTransform(toolParams) transformed = true } catch (err) { + if (err instanceof ToolCallParamsError) throw err logger.warn('paramsTransform failed, using raw params', { error: err }) } diff --git a/apps/sim/tools/param-shape.ts b/apps/sim/tools/param-shape.ts index 2a4509d2daf..3ca3ea4e621 100644 --- a/apps/sim/tools/param-shape.ts +++ b/apps/sim/tools/param-shape.ts @@ -59,11 +59,18 @@ const SUBBLOCK_TYPE_BY_VALUE_TYPE: Record = { any: 'short-input', } -/** Sub-block types whose store value is an object or array rather than a scalar. */ +/** + * Sub-block types whose store value is an object or array rather than a scalar. + * + * `filter-builder` and `sort-builder` hold rule arrays, and both the Table mappers and the + * tool-row builders only read an array: a tool row's rules left as JSON text are ignored. + */ const OBJECT_VALUED_SUBBLOCK_TYPES = new Set([ 'checkbox-list', 'file-upload', + 'filter-builder', 'grouped-checkbox-list', + 'sort-builder', 'table', ])