Skip to content

Commit 7341fe7

Browse files
committed
fix(agents): sanitize rejected tool call ids on retry
1 parent 5e41074 commit 7341fe7

7 files changed

Lines changed: 174 additions & 4 deletions

File tree

‎src/agents/embedded-agent-runner/run-loop.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ import { prepareAndDispatchEmbeddedRunAttempt } from "./run/attempt-dispatch-pre
2929
import { normalizeEmbeddedRunAttempt } from "./run/attempt-normalization.js";
3030
import { recoverEmbeddedRunAttempt } from "./run/attempt-recovery.js";
3131
import { forgetPromptBuildDrainCacheForRun } from "./run/attempt.prompt-helpers.js";
32+
import {
33+
shouldForceToolCallIdSanitization,
34+
shouldRetryWithForcedToolCallIdSanitization,
35+
} from "./run/attempt.transcript-policy.js";
3236
import { hasCodexAppServerRecoveryRetryBudget } from "./run/codex-app-server-recovery.js";
3337
import { createEmbeddedRunCompactionRuntime } from "./run/compaction-runtime.js";
3438
import { createEmbeddedRunContextRecoveryState } from "./run/context-recovery-state.js";
@@ -269,6 +273,7 @@ export async function runPreparedEmbeddedLoop(
269273
sessionPromptState,
270274
});
271275
let authRetryPending = false;
276+
let forceToolCallIdSanitizationApi: string | undefined;
272277
let accumulatedReplayState = createEmbeddedRunReplayState();
273278
// Hoisted so the retry-limit error path can use the most recent API total.
274279
let lastTurnTotal: number | undefined;
@@ -313,6 +318,10 @@ export async function runPreparedEmbeddedLoop(
313318
const runtimeAuthRetry: boolean = authRetryPending;
314319
authRetryPending = false;
315320
attemptedThinking.add(thinkLevel);
321+
const forceToolCallIdSanitization = shouldForceToolCallIdSanitization({
322+
forceToolCallIdSanitizationApi,
323+
modelApi: effectiveModel.api,
324+
});
316325
const codexAppServerRecoveryRetryAvailable = hasCodexAppServerRecoveryRetryBudget({
317326
alreadyRetried: codexAppServerRecoveryRetries > 0,
318327
runLoopIterations,
@@ -327,6 +336,7 @@ export async function runPreparedEmbeddedLoop(
327336
replayState: accumulatedReplayState,
328337
provider,
329338
modelId,
339+
forceToolCallIdSanitization,
330340
startupStagesEmitted,
331341
bootstrapPromptWarningSignaturesSeen,
332342
resolveRuntimeFallbackReason,
@@ -436,6 +446,19 @@ export async function runPreparedEmbeddedLoop(
436446
}
437447
const { shouldSurfaceCodexCompletionTimeout } = recovery;
438448

449+
if (
450+
shouldRetryWithForcedToolCallIdSanitization({
451+
cloudCodeAssistFormatError: attempt.cloudCodeAssistFormatError,
452+
errorMessage: attemptAssistant?.errorMessage,
453+
forceToolCallIdSanitizationApi,
454+
modelApi: effectiveModel.api,
455+
})
456+
) {
457+
forceToolCallIdSanitizationApi = effectiveModel.api;
458+
lastRetryFailoverReason = "format";
459+
continue;
460+
}
461+
439462
const assistantFailureOutcome = await handleEmbeddedAssistantFailure({
440463
runParams: params,
441464
attempt,

‎src/agents/embedded-agent-runner/run/attempt-dispatch-preparation.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ export async function prepareAndDispatchEmbeddedRunAttempt(input: {
3232
replayState: ReturnType<typeof createEmbeddedRunReplayState>;
3333
provider: string;
3434
modelId: string;
35+
forceToolCallIdSanitization: boolean;
3536
startupStagesEmitted: boolean;
3637
bootstrapPromptWarningSignaturesSeen: string[];
3738
resolveRuntimeFallbackReason: () => string | null;
@@ -188,6 +189,7 @@ export async function prepareAndDispatchEmbeddedRunAttempt(input: {
188189
agentHarnessId: runtime.agentHarness.id,
189190
expectedRuntimeArtifact: expectedHarnessArtifact?.artifact,
190191
runtimePlan,
192+
forceToolCallIdSanitization: input.forceToolCallIdSanitization,
191193
model: runtime.effectiveModel,
192194
resolvedApiKey: resolvedStreamApiKey,
193195
authProfileId: runtime.lastProfileId,

‎src/agents/embedded-agent-runner/run/attempt-session-manager-prepare.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ export async function prepareEmbeddedAttemptSessionManager(input: {
7272
},
7373
provider: attempt.provider,
7474
modelId: attempt.modelId,
75+
forceToolCallIdSanitization: attempt.forceToolCallIdSanitization,
7576
config: attempt.config,
7677
env: process.env,
7778
});

‎src/agents/embedded-agent-runner/run/attempt.transcript-policy.test.ts‎

Lines changed: 105 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22
import { beforeEach, describe, expect, it, vi } from "vitest";
33
import type { ProviderRuntimeModel } from "../../../plugins/provider-runtime-model.types.js";
44
import type { AgentRuntimePlan } from "../../runtime-plan/types.js";
5-
import { resolveAttemptTranscriptPolicy } from "./attempt.transcript-policy.js";
5+
import {
6+
resolveAttemptTranscriptPolicy,
7+
shouldForceToolCallIdSanitization,
8+
shouldRetryWithForcedToolCallIdSanitization,
9+
} from "./attempt.transcript-policy.js";
610

711
const resolveProviderRuntimePluginMock = vi.hoisted(() => vi.fn());
812

@@ -66,6 +70,106 @@ describe("resolveAttemptTranscriptPolicy", () => {
6670
expect(resolvePolicy).toHaveBeenCalledWith(runtimePlanModelContext);
6771
});
6872

73+
it("forces strict tool call id sanitization after a provider format retry", () => {
74+
const plannedPolicy = {
75+
sanitizeMode: "images-only",
76+
sanitizeToolCallIds: false,
77+
toolCallIdMode: "strict9",
78+
preserveNativeAnthropicToolUseIds: false,
79+
repairToolUseResultPairing: true,
80+
preserveSignatures: false,
81+
dropThinkingBlocks: false,
82+
applyGoogleTurnOrdering: false,
83+
validateGeminiTurns: false,
84+
validateAnthropicTurns: false,
85+
allowSyntheticToolResults: false,
86+
} as const;
87+
const runtimePlan = {
88+
transcript: {
89+
resolvePolicy: vi.fn(() => plannedPolicy),
90+
},
91+
} as unknown as AgentRuntimePlan;
92+
93+
const policy = resolveAttemptTranscriptPolicy({
94+
runtimePlan,
95+
runtimePlanModelContext: {
96+
workspaceDir: ".",
97+
modelApi: "anthropic-messages",
98+
},
99+
provider: "github-copilot",
100+
modelId: "claude-sonnet-4",
101+
forceToolCallIdSanitization: true,
102+
});
103+
104+
expect(policy).toEqual({
105+
...plannedPolicy,
106+
sanitizeToolCallIds: true,
107+
toolCallIdMode: "strict",
108+
});
109+
});
110+
111+
it("allows exactly one forced sanitization retry for a provider format error", () => {
112+
expect(
113+
shouldRetryWithForcedToolCallIdSanitization({
114+
cloudCodeAssistFormatError: true,
115+
errorMessage: "messages.17.content.0.tool_use.id: String should match pattern",
116+
modelApi: "anthropic-messages",
117+
}),
118+
).toBe(true);
119+
expect(
120+
shouldRetryWithForcedToolCallIdSanitization({
121+
cloudCodeAssistFormatError: true,
122+
errorMessage: "tool call id was invalid and must match the required pattern",
123+
modelApi: "anthropic-messages",
124+
}),
125+
).toBe(true);
126+
expect(
127+
shouldRetryWithForcedToolCallIdSanitization({
128+
cloudCodeAssistFormatError: true,
129+
errorMessage: "messages.17.content.0.tool_use.id: String should match pattern",
130+
forceToolCallIdSanitizationApi: "anthropic-messages",
131+
modelApi: "anthropic-messages",
132+
}),
133+
).toBe(false);
134+
expect(
135+
shouldRetryWithForcedToolCallIdSanitization({
136+
cloudCodeAssistFormatError: true,
137+
errorMessage: "invalid request format",
138+
modelApi: "anthropic-messages",
139+
}),
140+
).toBe(false);
141+
expect(
142+
shouldRetryWithForcedToolCallIdSanitization({
143+
cloudCodeAssistFormatError: true,
144+
errorMessage: "messages.17.content.0.tool_use.id: String should match pattern",
145+
modelApi: "openai-responses",
146+
}),
147+
).toBe(false);
148+
expect(
149+
shouldRetryWithForcedToolCallIdSanitization({
150+
cloudCodeAssistFormatError: true,
151+
errorMessage: "messages.17.content.0.tool_use.id: String should match pattern",
152+
forceToolCallIdSanitizationApi: "anthropic-messages",
153+
modelApi: "openai-responses",
154+
}),
155+
).toBe(false);
156+
});
157+
158+
it("limits forced sanitization to the API that rejected the transcript", () => {
159+
expect(
160+
shouldForceToolCallIdSanitization({
161+
forceToolCallIdSanitizationApi: "anthropic-messages",
162+
modelApi: "anthropic-messages",
163+
}),
164+
).toBe(true);
165+
expect(
166+
shouldForceToolCallIdSanitization({
167+
forceToolCallIdSanitizationApi: "anthropic-messages",
168+
modelApi: "openai-responses",
169+
}),
170+
).toBe(false);
171+
});
172+
69173
it("keeps the legacy provider transcript fallback when no RuntimePlan is available", () => {
70174
// Legacy fallback remains for older runner paths and tests provider runtime
71175
// plugin discovery with the same workspace/env context.

‎src/agents/embedded-agent-runner/run/attempt.transcript-policy.ts‎

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,34 @@ type AttemptRuntimeModelContext = NonNullable<
1010
Parameters<AgentRuntimePlan["transcript"]["resolvePolicy"]>[0]
1111
>;
1212

13+
export function shouldForceToolCallIdSanitization(params: {
14+
forceToolCallIdSanitizationApi?: string;
15+
modelApi?: string;
16+
}): boolean {
17+
return (
18+
params.forceToolCallIdSanitizationApi !== undefined &&
19+
params.forceToolCallIdSanitizationApi === params.modelApi
20+
);
21+
}
22+
23+
export function shouldRetryWithForcedToolCallIdSanitization(params: {
24+
cloudCodeAssistFormatError: boolean;
25+
errorMessage?: string;
26+
forceToolCallIdSanitizationApi?: string;
27+
modelApi?: string;
28+
}): boolean {
29+
const isOpenAIResponsesApi =
30+
params.modelApi === "openai-responses" ||
31+
params.modelApi === "openai-chatgpt-responses" ||
32+
params.modelApi === "azure-openai-responses";
33+
return (
34+
params.cloudCodeAssistFormatError &&
35+
!shouldForceToolCallIdSanitization(params) &&
36+
!isOpenAIResponsesApi &&
37+
/tool[._\s-]+(?:use|call)[._\s-]+id/i.test(params.errorMessage ?? "")
38+
);
39+
}
40+
1341
/**
1442
* Adapts the RuntimePlan model context to the legacy provider-runtime model
1543
* shape used by transcript-policy fallbacks.
@@ -30,10 +58,11 @@ export function resolveAttemptTranscriptPolicy(params: {
3058
runtimePlanModelContext: AttemptRuntimeModelContext;
3159
provider: string;
3260
modelId: string;
61+
forceToolCallIdSanitization?: boolean;
3362
config?: OpenClawConfig;
3463
env?: NodeJS.ProcessEnv;
3564
}): TranscriptPolicy {
36-
return (
65+
const policy =
3766
params.runtimePlan?.transcript.resolvePolicy(params.runtimePlanModelContext) ??
3867
resolveTranscriptPolicy({
3968
modelApi: params.runtimePlanModelContext.modelApi,
@@ -43,6 +72,13 @@ export function resolveAttemptTranscriptPolicy(params: {
4372
workspaceDir: params.runtimePlanModelContext.workspaceDir,
4473
env: params.env ?? process.env,
4574
model: asProviderRuntimeModel(params.runtimePlanModelContext.model),
46-
})
47-
);
75+
});
76+
if (!params.forceToolCallIdSanitization) {
77+
return policy;
78+
}
79+
return {
80+
...policy,
81+
sanitizeToolCallIds: true,
82+
toolCallIdMode: "strict",
83+
};
4884
}

‎src/agents/embedded-agent-runner/run/run-attempt-dispatch.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ type AttemptRuntime = {
4444
agentHarnessId: string;
4545
expectedRuntimeArtifact?: AgentHarnessRuntimeArtifactBinding;
4646
runtimePlan: AgentRuntimePlan;
47+
forceToolCallIdSanitization: boolean;
4748
model: EmbeddedRunAttemptParams["model"];
4849
resolvedApiKey?: string;
4950
authProfileId?: string;
@@ -249,6 +250,7 @@ export async function dispatchEmbeddedRunAttempt(input: {
249250
: {}),
250251
runtimePlan: runtime.runtimePlan,
251252
observeToolTerminal,
253+
forceToolCallIdSanitization: runtime.forceToolCallIdSanitization,
252254
model: applyAuthHeaderOverride(
253255
applyLocalNoAuthHeaderOverride(runtime.model, runtime.apiKeyInfo),
254256
runtime.runtimeAuthActive ? null : runtime.apiKeyInfo,

‎src/agents/embedded-agent-runner/run/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,8 @@ export type EmbeddedRunAttemptParams = EmbeddedRunAttemptBase & {
128128
runtimePlan?: AgentRuntimePlan;
129129
/** Reports terminal tool facts to the host-owned attempt outcome accumulator. */
130130
observeToolTerminal?: EmbeddedRunAttemptToolTerminalObserver;
131+
/** Force replay-safe tool call IDs after a provider rejects the prior transcript format. */
132+
forceToolCallIdSanitization?: boolean;
131133
/** Host-issued scope for harnesses that mirror native child runs into task state. */
132134
agentHarnessTaskRuntimeScope?: AgentHarnessTaskRuntimeScope;
133135
/** Storage-neutral trajectory target for harness-owned runtime trace artifacts. */

0 commit comments

Comments
 (0)