Skip to content

Commit cef1b65

Browse files
authored
fix(table): apply filter and sort builder rules pinned on agent tool rows (#10083)
* fix(table): apply filter and sort builder rules pinned on agent tool rows Agent tool rows store filter-builder and sort-builder values as JSON text, but the tool param decoder treated both as plain strings. Table v2 then threw on the parsed rules and the tool ran on the raw params with the model's own filter in place of the pinned one (bulk update/delete included); sort rules went out unconverted, and Table v1 ignored pinned builder rules entirely. - decode filter-builder and sort-builder values as JSON - pick the active canonical member from decoded values, so an emptied builder ('[]') no longer hides the model's filter - ToolCallParamsError: Table mapper failures on a tool call fail the call instead of falling back to raw params (agent and Pi local tools) - keep tool-row builder rules as raw text for search/replace * fix(table): fail a tool call whose v1 builder rules are corrupt A pinned v1 builder value that does not decode to an array iterated as a string, built nothing, and fell back to the model's filter. On a tool call it now fails the call; an empty rule list keeps its model fallback. Also types the new test helper params. * fix(agent): record or skip a tool call whose block mapper rejects its params A pending-call retry now records a ToolCallParamsError as a failed tool call instead of aborting the continuation (other preparation refusals still abort), and a Human-in-the-loop v2 notification whose mapper rejects its params is skipped rather than sent with raw params. * fix(agent): keep rejected argument values out of the tool-call error ToolCallParamsError reaches the model before tool-result secret redaction, and a mapper's message can quote the value it rejected after a {{SECRET}} placeholder was resolved. The model now gets a static message; the original error stays on cause for server logs.
1 parent f584949 commit cef1b65

14 files changed

Lines changed: 381 additions & 30 deletions

File tree

‎apps/sim/blocks/blocks/table.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { TABLE_LIMITS } from '@/lib/table/constants'
44
import { filterRulesToFilter, sortRulesToSort } from '@/lib/table/query-builder/converters'
55
import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types'
66
import {
7+
failToolCallOnError,
78
isToolCall,
89
mapperOperation,
910
parseOptionalNumberInput,
@@ -94,15 +95,21 @@ interface ParsedParams {
9495
* list) falls back to the model's `filter`/`sort` arg instead of discarding it; the canvas keeps
9596
* the builder's result.
9697
*/
97-
function resolveBuilderOrJson(
98+
function resolveBuilderOrJson<TRule>(
9899
builderActive: boolean,
99-
fromBuilder: () => unknown,
100+
builderValue: unknown,
101+
fromBuilder: (rules: TRule[]) => unknown,
100102
json: unknown,
101103
fieldName: string,
102104
context: BlockToolParamsContext | undefined
103105
): unknown {
104106
if (builderActive) {
105-
const built = fromBuilder() || undefined
107+
// A tool row's rules that did not decode to an array are corrupt, not empty: falling back
108+
// would run the operation on the model's filter instead of the one the user pinned.
109+
if (isToolCall(context) && !Array.isArray(builderValue)) {
110+
throw new Error(`Invalid ${fieldName} builder rules: expected a list of conditions.`)
111+
}
112+
const built = fromBuilder(builderValue as TRule[]) || undefined
106113
if (built !== undefined || !isToolCall(context) || !json) return built
107114
} else if (!json) {
108115
return undefined
@@ -116,8 +123,8 @@ function resolveBulkFilter(
116123
): unknown {
117124
return resolveBuilderOrJson(
118125
params.bulkFilterMode === 'builder' && Boolean(params.bulkFilterBuilder),
119-
() =>
120-
filterRulesToFilter(params.bulkFilterBuilder as Parameters<typeof filterRulesToFilter>[0]),
126+
params.bulkFilterBuilder,
127+
filterRulesToFilter,
121128
params.filter,
122129
'Filter',
123130
context
@@ -195,14 +202,16 @@ const paramTransformers: Record<
195202
const builderMode = params.builderMode === 'builder'
196203
const filter = resolveBuilderOrJson(
197204
builderMode && Boolean(params.filterBuilder),
198-
() => filterRulesToFilter(params.filterBuilder as Parameters<typeof filterRulesToFilter>[0]),
205+
params.filterBuilder,
206+
filterRulesToFilter,
199207
params.filter,
200208
'Filter',
201209
context
202210
)
203211
const sort = resolveBuilderOrJson(
204212
builderMode && Boolean(params.sortBuilder),
205-
() => sortRulesToSort(params.sortBuilder as Parameters<typeof sortRulesToSort>[0]),
213+
params.sortBuilder,
214+
sortRulesToSort,
206215
params.sort,
207216
'Sort',
208217
context
@@ -760,7 +769,7 @@ Return ONLY the sort JSON:`,
760769
const transformer = paramTransformers[mapperOperation(params, context)]
761770

762771
if (transformer) {
763-
return transformer(rest as TableBlockParams, context)
772+
return failToolCallOnError(context, () => transformer(rest as TableBlockParams, context))
764773
}
765774

766775
return rest

‎apps/sim/blocks/blocks/table_v2.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import type {
1313
} from '@/lib/table/types'
1414
import type { BlockConfig, BlockToolParamsContext } from '@/blocks/types'
1515
import {
16+
failToolCallOnError,
1617
mapperOperation,
1718
resolveTableColumnSelection,
1819
TABLE_OUTPUT_COLUMNS_INPUT,
@@ -570,7 +571,7 @@ Return ONLY the JSON object:`,
570571
const { operation, ...rest } = params
571572
const transformer = paramTransformers[mapperOperation(params, context)]
572573
if (transformer) {
573-
return transformer(rest as TableBlockParams, context)
574+
return failToolCallOnError(context, () => transformer(rest as TableBlockParams, context))
574575
}
575576
return rest
576577
},

‎apps/sim/blocks/utils.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
SIM_AUTO_MODEL_ID,
2424
} from '@/providers/models'
2525
import { isPiSupportedModel } from '@/providers/pi-providers'
26+
import { ToolCallParamsError } from '@/providers/tool-params-error'
2627
import type { ProviderId } from '@/providers/types'
2728
import { getProviderFromModel } from '@/providers/utils'
2829
import { useProvidersStore } from '@/stores/providers/store'
@@ -948,6 +949,33 @@ export function toolCallArg<T>(
948949
return isToolCall(context) ? value : undefined
949950
}
950951

952+
/**
953+
* What the model is told when a block rejects a tool call's params. Deliberately static: a
954+
* mapper's own message can quote the value it rejected (`Invalid Limit "…"`, a JSON parse
955+
* snippet), and by then a model-written `{{SECRET}}` placeholder has been resolved to plaintext.
956+
*/
957+
const TOOL_CALL_PARAMS_REJECTED_MESSAGE =
958+
'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.'
959+
960+
/**
961+
* Runs a mapper body, and on a tool call turns any failure into a {@link ToolCallParamsError} so
962+
* the call fails instead of running on the raw merged params. Use it where those raw params are
963+
* unsafe: a pinned value under a block-only key (a filter builder) drops out of them, leaving the
964+
* model's own argument for the same tool param in its place. The original error stays on `cause`
965+
* for server logs; the canvas rethrows it unchanged.
966+
*/
967+
export function failToolCallOnError<T>(
968+
context: BlockToolParamsContext | undefined,
969+
map: () => T
970+
): T {
971+
try {
972+
return map()
973+
} catch (error) {
974+
if (!isToolCall(context) || error instanceof ToolCallParamsError) throw error
975+
throw new ToolCallParamsError(TOOL_CALL_PARAMS_REJECTED_MESSAGE, { cause: error })
976+
}
977+
}
978+
951979
/**
952980
* The operation a block's `tools.config.params` mapper runs for. A tool call passes it only in
953981
* `context`: a stored tool row keeps its operation outside its params, and a tool that declares its

‎apps/sim/executor/handlers/human-in-the-loop/handler.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import type { BlockHandler, ExecutionContext, PauseMetadata } from '@/executor/t
2828
import { collectBlockData } from '@/executor/utils/block-data'
2929
import { convertBuilderDataToJson, convertPropertyValue } from '@/executor/utils/builder-data'
3030
import { parseObjectStrings } from '@/executor/utils/json'
31+
import { ToolCallParamsError } from '@/providers/tool-params-error'
3132
import { buildBlockToolParamsTransform } from '@/providers/utils'
3233
import type { SerializedBlock } from '@/serializer/types'
3334
import { executeTool } from '@/tools'
@@ -449,7 +450,9 @@ export class HumanInTheLoopBlockHandler implements BlockHandler {
449450
return paramsTransform(visibleParams)
450451
} catch (error) {
451452
// Mirrors `prepareToolExecution`: a transform that throws must not take the
452-
// notification down with it, so the raw params still go out.
453+
// notification down with it, so the raw params still go out — except a
454+
// `ToolCallParamsError`, whose raw params are unsafe to send.
455+
if (error instanceof ToolCallParamsError) throw error
453456
logger.warn('Notification tool params transform failed, using raw params', {
454457
toolId,
455458
error,

‎apps/sim/executor/handlers/human-in-the-loop/notification-params.test.ts‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,22 +27,38 @@ const notifierBlock = {
2727
outputs: {},
2828
}
2929

30+
/** A notifier whose mapper rejects its stored params, as Table's does for a corrupt filter. */
31+
const rejectingNotifierBlock = {
32+
...notifierBlock,
33+
tools: {
34+
...notifierBlock.tools,
35+
config: {
36+
params: () => {
37+
throw new ToolCallParamsError('Invalid JSON in Filter')
38+
},
39+
},
40+
},
41+
}
42+
3043
vi.mock('@/tools/utils', () => toolsUtilsMock)
3144

3245
vi.mock('@/tools', () => toolsMock)
3346

3447
import { getBlock } from '@/blocks/registry'
3548
import { PAUSE_RESUME } from '@/executor/constants'
3649
import { HumanInTheLoopBlockHandler } from '@/executor/handlers/human-in-the-loop/handler'
50+
import { ToolCallParamsError } from '@/providers/tool-params-error'
3751

3852
toolsUtilsMockFns.mockGetTool.mockReturnValue({
3953
id: 'notifier_send',
4054
params: { channel: { type: 'string' }, silent: { type: 'boolean' } },
4155
})
4256

43-
vi.mocked(getBlock).mockImplementation((type: string) =>
44-
type === 'notifier' ? (notifierBlock as never) : undefined
45-
)
57+
vi.mocked(getBlock).mockImplementation((type: string) => {
58+
if (type === 'notifier') return notifierBlock as never
59+
if (type === 'rejecting_notifier') return rejectingNotifierBlock as never
60+
return undefined
61+
})
4662

4763
const executed: Array<Record<string, unknown>> = []
4864
toolsMockFns.mockExecuteTool.mockImplementation(
@@ -53,7 +69,10 @@ toolsMockFns.mockExecuteTool.mockImplementation(
5369
)
5470

5571
/** Runs one notification whose channel was configured in ADVANCED mode. */
56-
async function runNotification(blockTypeId: string): Promise<Record<string, unknown>> {
72+
async function runNotification(
73+
blockTypeId: string,
74+
notifierType = 'notifier'
75+
): Promise<Record<string, unknown>> {
5776
executed.length = 0
5877

5978
const block = {
@@ -74,7 +93,7 @@ async function runNotification(blockTypeId: string): Promise<Record<string, unkn
7493
operation: PAUSE_RESUME.OPERATION.HUMAN,
7594
notification: [
7695
{
77-
type: 'notifier',
96+
type: notifierType,
7897
toolId: 'notifier_send',
7998
title: 'Notify',
8099
params: { channel: '', manualChannel: 'C123', silent: 'false' },
@@ -103,6 +122,11 @@ describe('Human block notification params', () => {
103122
})
104123
})
105124

125+
it('v2 skips a notification whose mapper rejects its params instead of sending raw ones', async () => {
126+
await runNotification('human_in_the_loop_v2', 'rejecting_notifier')
127+
expect(executed).toEqual([])
128+
})
129+
106130
it('v1 keeps handing the tool its raw stored values', async () => {
107131
// Deliberately unchanged: altering what an already-configured v1 notification sends
108132
// is exactly the break v2 exists to avoid.

‎apps/sim/executor/handlers/pi/local/sim-tools.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-sec
2323
import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
2424
import { annotateDuplicateToolBindings } from '@/executor/utils/tool-binding-labels'
2525
import { assignProviderToolIdentities } from '@/providers/tool-identity'
26+
import { ToolCallParamsError } from '@/providers/tool-params-error'
2627
import type { ProviderToolConfig } from '@/providers/types'
2728
import { transformBlockTool } from '@/providers/utils'
2829
import { executeTool } from '@/tools'
@@ -129,8 +130,9 @@ function buildSimToolSpec(
129130
* declares. Skipping it here left Pi local tools receiving a raw selector id
130131
* where the tool expected a resolved one, and `'false'` where it expected `false`.
131132
*
132-
* A failure keeps the raw params, matching `prepareToolExecution`. The projected
133-
* copy is only transformed when the raw one was, so the two stay comparable.
133+
* A failure keeps the raw params, matching `prepareToolExecution`, except a
134+
* `ToolCallParamsError`, which fails the call. The projected copy is only
135+
* transformed when the raw one was, so the two stay comparable.
134136
*/
135137
let transformApplied = false
136138
const applyParamsTransform = (input: Record<string, unknown>): Record<string, unknown> => {
@@ -140,6 +142,7 @@ function buildSimToolSpec(
140142
transformApplied = true
141143
return transformed
142144
} catch (error) {
145+
if (error instanceof ToolCallParamsError) throw error
143146
logger.warn('paramsTransform failed for Pi local tool, using raw params', { error })
144147
return input
145148
}

‎apps/sim/lib/workflows/search-replace/json-value-fields.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,18 @@ export function isSearchableJsonValueSubBlock(
110110
)
111111
}
112112

113+
/**
114+
* Rule builders stay as their stored JSON text in a tool row: the replacer edits a tool param's
115+
* raw text, and has no path into a builder's rule array the way it does for `table` cells.
116+
*/
117+
const RAW_TEXT_TOOL_PARAM_SUBBLOCK_TYPES = new Set<SubBlockType>(['filter-builder', 'sort-builder'])
118+
113119
export function shouldParseSerializedSubBlockValue(
114120
subBlockType: SubBlockType | undefined
115121
): subBlockType is SubBlockType {
116122
return Boolean(
117123
subBlockType &&
124+
!RAW_TEXT_TOOL_PARAM_SUBBLOCK_TYPES.has(subBlockType) &&
118125
(isSearchableJsonValueSubBlock(subBlockType) || holdsObjectValue({ type: subBlockType }))
119126
)
120127
}

‎apps/sim/lib/workflows/search-replace/replacements.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
SEARCH_REPLACE_BLOCK_CONFIGS,
77
} from '@/lib/workflows/search-replace/search-replace.fixtures'
88
import { WORKFLOW_SEARCH_SUBFLOW_FIELD_IDS } from '@/lib/workflows/search-replace/subflow-fields'
9+
import { TableV2Block } from '@/blocks/blocks/table_v2'
910

1011
/**
1112
* Asserts real tool params and outputs, which the global `@/tools/metadata`
@@ -417,6 +418,64 @@ describe('buildWorkflowSearchReplacePlan', () => {
417418
])
418419
})
419420

421+
it('replaces a value inside filter builder rules stored as a serialized tool input param', () => {
422+
const workflow = createSearchReplaceWorkflowFixture()
423+
const rule = { id: 'r1', logicalOperator: 'and', column: 'status', operator: 'eq' }
424+
workflow.blocks['tool-input-1'] = {
425+
id: 'tool-input-1',
426+
type: 'custom',
427+
name: 'Tool Input Block',
428+
position: { x: 0, y: 0 },
429+
enabled: true,
430+
outputs: {},
431+
subBlocks: {
432+
tools: {
433+
id: 'tools',
434+
type: 'tool-input',
435+
value: [
436+
{
437+
type: 'table_v2',
438+
toolId: 'table_query_rows_v2',
439+
operation: 'query_rows',
440+
title: 'Table',
441+
params: {
442+
tableId: 'tbl_1',
443+
filterBuilder: JSON.stringify([{ ...rule, value: 'pending' }]),
444+
},
445+
},
446+
],
447+
},
448+
},
449+
}
450+
const matches = indexWorkflowSearchMatches({
451+
workflow,
452+
query: 'pending',
453+
mode: 'text',
454+
blockConfigs: {
455+
...SEARCH_REPLACE_BLOCK_CONFIGS,
456+
custom: { subBlocks: [{ id: 'tools', title: 'Tools', type: 'tool-input' }] },
457+
table_v2: TableV2Block,
458+
},
459+
}).filter((match) => match.blockId === 'tool-input-1' && match.editable)
460+
461+
const plan = buildWorkflowSearchReplacePlan({
462+
blocks: workflow.blocks,
463+
matches,
464+
selectedMatchIds: new Set(matches.map((match) => match.id)),
465+
defaultReplacement: 'approved',
466+
})
467+
468+
expect(plan.conflicts).toEqual([])
469+
expect(plan.updates).toHaveLength(1)
470+
expect(plan.updates[0].nextValue).toEqual([
471+
expect.objectContaining({
472+
params: expect.objectContaining({
473+
filterBuilder: JSON.stringify([{ ...rule, value: 'approved' }]),
474+
}),
475+
}),
476+
])
477+
})
478+
420479
it('conflicts when a selected duplicate file occurrence is removed', () => {
421480
const workflow = createSearchReplaceWorkflowFixture()
422481
const files = [

‎apps/sim/providers/conversation-continuation.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
setEncryptedConversationMessage,
2121
} from '@/providers/conversation-metadata'
2222
import { executeProviderTool } from '@/providers/runtime-context'
23+
import { ToolCallParamsError } from '@/providers/tool-params-error'
2324
import type { Message, ProviderRequest } from '@/providers/types'
2425
import { prepareToolExecution } from '@/providers/utils'
2526

@@ -137,6 +138,19 @@ describe('durable conversation restoration and continuation', () => {
137138
).rejects.toBe(refused)
138139
})
139140

141+
it('records a block mapper rejection as a failed tool call without dispatching it', async () => {
142+
vi.mocked(prepareToolExecution).mockImplementationOnce(() => {
143+
throw new ToolCallParamsError('Invalid JSON in Filter')
144+
})
145+
const session = await pendingSession()
146+
await continuePendingConversationCalls(toolRequest, session)
147+
expect(session.getPendingCalls()).toEqual([])
148+
expect(session.getMessages('openai', 'model-a', 'binding-a')[1].content).toContain(
149+
'Invalid JSON in Filter'
150+
)
151+
expect(executeProviderTool).not.toHaveBeenCalled()
152+
})
153+
140154
it('clears a previously restored native message when the next fallback binding changes', async () => {
141155
const messages = toolGroup()
142156
const native = {

0 commit comments

Comments
 (0)