Skip to content

Commit 58d3c35

Browse files
committed
fix: preserve client tool source order (#75580)
1 parent 54f01a8 commit 58d3c35

3 files changed

Lines changed: 203 additions & 28 deletions

File tree

‎src/agents/pi-embedded-runner/run/attempt.ts‎

Lines changed: 58 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1524,13 +1524,27 @@ export async function runEmbeddedAttempt(
15241524
});
15251525

15261526
// Add client tools (OpenResponses hosted tools) to customTools.
1527-
// Accumulate every detected call in arrival order; the LLM may invoke
1528-
// multiple client tools in a single turn and earlier callers were
1529-
// silently dropped by a last-write-wins variable.
1530-
const clientToolCallsDetected: Array<{
1527+
// Reserve slots synchronously at tool execution entry, before async
1528+
// before_tool_call hooks run, so parallel client-tool batches preserve
1529+
// assistant source order even when later hooks finish first.
1530+
const clientToolCallSlots: Array<{
1531+
toolCallId: string;
15311532
name: string;
1532-
params: Record<string, unknown>;
1533+
params?: Record<string, unknown>;
1534+
completed: boolean;
15331535
}> = [];
1536+
const clientToolCallSlotIndexes = new Map<string, number>();
1537+
const reserveClientToolCallSlot = (toolCallId: string, toolName: string) => {
1538+
if (clientToolCallSlotIndexes.has(toolCallId)) {
1539+
return;
1540+
}
1541+
clientToolCallSlotIndexes.set(toolCallId, clientToolCallSlots.length);
1542+
clientToolCallSlots.push({
1543+
toolCallId,
1544+
name: toolName,
1545+
completed: false,
1546+
});
1547+
};
15341548
const clientToolLoopDetection = resolveToolLoopDetectionConfig({
15351549
cfg: params.config,
15361550
agentId: sessionAgentId,
@@ -1569,8 +1583,33 @@ export async function runEmbeddedAttempt(
15691583
const clientToolDefs = clientTools
15701584
? toClientToolDefinitions(
15711585
clientTools,
1572-
(toolName, toolParams) => {
1573-
clientToolCallsDetected.push({ name: toolName, params: toolParams });
1586+
{
1587+
reserve: reserveClientToolCallSlot,
1588+
complete: (toolCallId, toolName, toolParams) => {
1589+
reserveClientToolCallSlot(toolCallId, toolName);
1590+
const slotIndex = clientToolCallSlotIndexes.get(toolCallId);
1591+
if (slotIndex === undefined) {
1592+
return;
1593+
}
1594+
const slot = clientToolCallSlots[slotIndex];
1595+
if (!slot) {
1596+
return;
1597+
}
1598+
slot.name = toolName;
1599+
slot.params = toolParams;
1600+
slot.completed = true;
1601+
},
1602+
discard: (toolCallId) => {
1603+
const slotIndex = clientToolCallSlotIndexes.get(toolCallId);
1604+
if (slotIndex === undefined) {
1605+
return;
1606+
}
1607+
const slot = clientToolCallSlots[slotIndex];
1608+
if (slot) {
1609+
slot.completed = false;
1610+
slot.params = undefined;
1611+
}
1612+
},
15741613
},
15751614
{
15761615
agentId: sessionAgentId,
@@ -3532,6 +3571,17 @@ export async function runEmbeddedAttempt(
35323571
});
35333572
trajectoryEndRecorded = true;
35343573

3574+
const completedClientToolCalls = clientToolCallSlots.flatMap((slot) =>
3575+
slot.completed && slot.params
3576+
? [
3577+
{
3578+
name: slot.name,
3579+
params: slot.params,
3580+
},
3581+
]
3582+
: [],
3583+
);
3584+
35353585
return {
35363586
replayMetadata,
35373587
itemLifecycle: getItemLifecycle(),
@@ -3576,7 +3626,7 @@ export async function runEmbeddedAttempt(
35763626
// Client tool calls detected (OpenResponses hosted tools).
35773627
// Stay `undefined` (not `[]`) when none were detected so downstream
35783628
// truthiness predicates keep working without a `.length` check.
3579-
clientToolCalls: clientToolCallsDetected.length > 0 ? clientToolCallsDetected : undefined,
3629+
clientToolCalls: completedClientToolCalls.length > 0 ? completedClientToolCalls : undefined,
35803630
yieldDetected: yieldDetected || undefined,
35813631
};
35823632
} finally {

‎src/agents/pi-tool-definition-adapter.ts‎

Lines changed: 45 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,14 @@ type ToolExecuteArgs = ToolDefinition["execute"] extends (...args: infer P) => u
4141
type ToolExecuteArgsAny = ToolExecuteArgs | ToolExecuteArgsLegacy | ToolExecuteArgsCurrent;
4242
const TOOL_ERROR_PARAM_PREVIEW_MAX_CHARS = 600;
4343

44+
export type ClientToolCallRecorder =
45+
| ((toolName: string, params: Record<string, unknown>) => void)
46+
| {
47+
reserve?: (toolCallId: string, toolName: string) => void;
48+
complete: (toolCallId: string, toolName: string, params: Record<string, unknown>) => void;
49+
discard?: (toolCallId: string, toolName: string) => void;
50+
};
51+
4452
function isAbortSignal(value: unknown): value is AbortSignal {
4553
return typeof value === "object" && value !== null && "aborted" in value;
4654
}
@@ -318,7 +326,7 @@ function coerceParamsRecord(value: unknown): Record<string, unknown> {
318326
// These tools are intercepted to return a "pending" result instead of executing
319327
export function toClientToolDefinitions(
320328
tools: ClientToolDefinition[],
321-
onClientToolCall?: (toolName: string, params: Record<string, unknown>) => void,
329+
onClientToolCall?: ClientToolCallRecorder,
322330
hookContext?: HookContext,
323331
): ToolDefinition[] {
324332
return tools.map((tool) => {
@@ -330,27 +338,44 @@ export function toClientToolDefinitions(
330338
parameters: func.parameters as ToolDefinition["parameters"],
331339
execute: async (...args: ToolExecuteArgs): Promise<AgentToolResult<unknown>> => {
332340
const { toolCallId, params } = splitToolExecuteArgs(args);
341+
if (onClientToolCall && typeof onClientToolCall !== "function") {
342+
onClientToolCall.reserve?.(toolCallId, func.name);
343+
}
333344
const initialParamsRecord = coerceParamsRecord(params);
334-
const outcome = await runBeforeToolCallHook({
335-
toolName: func.name,
336-
params: initialParamsRecord,
337-
toolCallId,
338-
ctx: hookContext,
339-
});
340-
if (outcome.blocked) {
341-
if (outcome.kind === "veto") {
342-
return buildBlockedToolResult({
343-
reason: outcome.reason,
344-
deniedReason: outcome.deniedReason,
345-
});
345+
try {
346+
const outcome = await runBeforeToolCallHook({
347+
toolName: func.name,
348+
params: initialParamsRecord,
349+
toolCallId,
350+
ctx: hookContext,
351+
});
352+
if (outcome.blocked) {
353+
if (onClientToolCall && typeof onClientToolCall !== "function") {
354+
onClientToolCall.discard?.(toolCallId, func.name);
355+
}
356+
if (outcome.kind === "veto") {
357+
return buildBlockedToolResult({
358+
reason: outcome.reason,
359+
deniedReason: outcome.deniedReason,
360+
});
361+
}
362+
throw new Error(outcome.reason);
346363
}
347-
throw new Error(outcome.reason);
348-
}
349-
const adjustedParams = outcome.params;
350-
const paramsRecord = coerceParamsRecord(adjustedParams);
351-
// Notify handler that a client tool was called
352-
if (onClientToolCall) {
353-
onClientToolCall(func.name, paramsRecord);
364+
const adjustedParams = outcome.params;
365+
const paramsRecord = coerceParamsRecord(adjustedParams);
366+
// Notify handler that a client tool was called.
367+
if (onClientToolCall) {
368+
if (typeof onClientToolCall === "function") {
369+
onClientToolCall(func.name, paramsRecord);
370+
} else {
371+
onClientToolCall.complete(toolCallId, func.name, paramsRecord);
372+
}
373+
}
374+
} catch (err) {
375+
if (onClientToolCall && typeof onClientToolCall !== "function") {
376+
onClientToolCall.discard?.(toolCallId, func.name);
377+
}
378+
throw err;
354379
}
355380
// Return a pending result - the client will execute this tool
356381
return jsonResult({

‎src/agents/pi-tools.before-tool-call.integration.e2e.test.ts‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,4 +351,104 @@ describe("before_tool_call hook integration for client tools", () => {
351351
extra: true,
352352
});
353353
});
354+
355+
it("preserves client tool source order when hooks resolve out of order", async () => {
356+
let releaseFirstHook!: () => void;
357+
const firstHookGate = new Promise<void>((resolve) => {
358+
releaseFirstHook = resolve;
359+
});
360+
installBeforeToolCallHook({
361+
runBeforeToolCallImpl: async (event: unknown) => {
362+
const toolName = (event as { toolName?: string }).toolName;
363+
if (toolName === "first_tool") {
364+
await firstHookGate;
365+
}
366+
return { params: { marker: toolName } };
367+
},
368+
});
369+
370+
const slots: Array<{
371+
toolCallId: string;
372+
name: string;
373+
params?: Record<string, unknown>;
374+
completed: boolean;
375+
}> = [];
376+
const indexes = new Map<string, number>();
377+
const reserve = (toolCallId: string, name: string) => {
378+
indexes.set(toolCallId, slots.length);
379+
slots.push({ toolCallId, name, completed: false });
380+
};
381+
const complete = (toolCallId: string, name: string, params: Record<string, unknown>) => {
382+
const index = indexes.get(toolCallId);
383+
if (index === undefined) {
384+
throw new Error(`missing reserved client tool slot for ${toolCallId}`);
385+
}
386+
const slot = slots[index];
387+
if (!slot) {
388+
throw new Error(`missing client tool slot at ${index}`);
389+
}
390+
slot.name = name;
391+
slot.params = params;
392+
slot.completed = true;
393+
};
394+
const [firstTool, secondTool] = toClientToolDefinitions(
395+
[
396+
{
397+
type: "function",
398+
function: {
399+
name: "first_tool",
400+
description: "First client tool",
401+
parameters: { type: "object", properties: { value: { type: "string" } } },
402+
},
403+
},
404+
{
405+
type: "function",
406+
function: {
407+
name: "second_tool",
408+
description: "Second client tool",
409+
parameters: { type: "object", properties: { value: { type: "string" } } },
410+
},
411+
},
412+
],
413+
{ reserve, complete },
414+
{ agentId: "main", sessionKey: "main" },
415+
);
416+
if (!firstTool || !secondTool) {
417+
throw new Error("missing client tool definitions");
418+
}
419+
const extensionContext = {} as Parameters<typeof firstTool.execute>[4];
420+
421+
const firstRun = firstTool.execute(
422+
"client-call-1",
423+
{ value: "first" },
424+
undefined,
425+
undefined,
426+
extensionContext,
427+
);
428+
const secondRun = secondTool.execute(
429+
"client-call-2",
430+
{ value: "second" },
431+
undefined,
432+
undefined,
433+
extensionContext,
434+
);
435+
436+
await secondRun;
437+
expect(slots.map((slot) => ({ name: slot.name, completed: slot.completed }))).toEqual([
438+
{ name: "first_tool", completed: false },
439+
{ name: "second_tool", completed: true },
440+
]);
441+
442+
releaseFirstHook();
443+
await firstRun;
444+
445+
expect(slots.filter((slot) => slot.completed).map((slot) => slot.name)).toEqual([
446+
"first_tool",
447+
"second_tool",
448+
]);
449+
expect(slots.map((slot) => slot.params)).toEqual([
450+
{ value: "first", marker: "first_tool" },
451+
{ value: "second", marker: "second_tool" },
452+
]);
453+
});
354454
});

0 commit comments

Comments
 (0)