Skip to content

Commit 414278a

Browse files
lanclawclaude
authored andcommitted
fix(repair): honor erroredAssistantResultPolicy + strip id-less tool blocks
Co-Authored-By: Claude Opus 4.6 <[email protected]>
1 parent 063b2df commit 414278a

4 files changed

Lines changed: 170 additions & 33 deletions

File tree

‎PR_FIX_TASK.md‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Task: Fix PR #48888 and rebase onto main
2+
3+
## Context
4+
5+
This is PR https://github.com/openclaw/openclaw/pull/48888
6+
Branch: fix/repair-tool-use-error-aborted
7+
Target: main
8+
9+
The PR fixes `repairToolUseResultPairing()` to strip orphaned tool_use blocks from
10+
error/aborted assistant messages instead of passing them through unchanged.
11+
The core idea is correct. There are 4 bugs to fix, plus a rebase conflict to resolve.
12+
13+
## Files to modify
14+
15+
- `src/agents/session-transcript-repair.ts`
16+
- `src/agents/session-transcript-repair.test.ts`
17+
18+
## The 4 bugs (from Greptile review)
19+
20+
### Bug 1: Type-incorrect `added` push
21+
22+
In session-transcript-repair.ts, find where strings like `"stripped-error-<id>"`
23+
are pushed into the `added` array. The `added` array is typed as
24+
`Array<Extract<AgentMessage, { role: "toolResult" }>>`.
25+
Fix: just set `changed = true` instead of pushing to `added`.
26+
27+
### Bug 2: `result.changed` doesn't exist on return type
28+
29+
In session-transcript-repair.test.ts, find `expect(result.changed).toBe(true)`.
30+
`ToolUseRepairReport` has no `changed` field — only `messages`, `added`,
31+
`droppedDuplicateCount`, `droppedOrphanCount`, and `moved`.
32+
Fix: replace `expect(result.changed).toBe(true)` with
33+
`expect(result.moved).toBeTruthy()` or check that `result.messages` changed.
34+
Actually the best fix: add `changed: boolean` to `ToolUseRepairReport` and return it.
35+
36+
### Bug 3: `functionCall` blocks not stripped
37+
38+
In session-transcript-repair.ts, find the filter that strips tool blocks.
39+
It likely says `b.type !== "toolCall" && b.type !== "toolUse"`.
40+
Fix: also add `&& b.type !== "functionCall"` to the filter.
41+
42+
### Bug 4: Existing test broken by new `added` push
43+
44+
In session-transcript-repair.test.ts, find a test that expects
45+
`result.added.toHaveLength(0)` after an aborted message.
46+
Fix: update the assertion after fixing Bug 1 (since we won't push to `added` anymore,
47+
the original assertion of toHaveLength(0) may still be correct — verify).
48+
49+
## Rebase approach
50+
51+
The current branch (fix/repair-tool-use-error-aborted) has a conflict when
52+
cherry-picking onto main. The conflict is in session-transcript-repair.ts around
53+
line 496 — the PR removes the old `stopReason === "error" || stopReason === "aborted"`
54+
skip block, but main has updated that same area.
55+
56+
Steps:
57+
58+
1. First understand both the PR diff and the current main version of the file
59+
2. Apply the PR's logic (strip tool_use from error/aborted messages) on top of main
60+
3. Fix the 4 bugs above
61+
4. Run: pnpm install && pnpm check && pnpm test -- --testPathPattern session-transcript-repair
62+
5. If tests pass, commit with message: "fix(repair): strip tool_use blocks from error/aborted messages (fixes #48354)"
63+
64+
## Important
65+
66+
- Work on branch fix-48888-v2 (already created, currently pointing to main HEAD)
67+
- Do NOT push — just get to a clean commit with passing tests
68+
- Report which bugs you fixed and test results
69+
70+
When completely finished, run:
71+
openclaw system event --text "PR #48888 fix complete: ready to review and push" --mode now

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1197,6 +1197,7 @@
11971197
"node-edge-tts": "^1.2.10",
11981198
"osc-progress": "^0.3.0",
11991199
"pdfjs-dist": "^5.6.205",
1200+
"picomatch": "^4.0.4",
12001201
"playwright-core": "1.58.2",
12011202
"qrcode-terminal": "^0.12.0",
12021203
"sharp": "^0.34.5",

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/agents/session-transcript-repair.ts‎

Lines changed: 95 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -349,9 +349,16 @@ export type ToolUseRepairReport = {
349349
changed: boolean;
350350
};
351351

352+
function shouldPreserveErroredAssistantResults(options?: ToolUseResultPairingOptions): boolean {
353+
return (
354+
options?.erroredAssistantResultPolicy !== undefined &&
355+
options.erroredAssistantResultPolicy !== "drop"
356+
);
357+
}
358+
352359
export function repairToolUseResultPairing(
353360
messages: AgentMessage[],
354-
_options?: ToolUseResultPairingOptions,
361+
options?: ToolUseResultPairingOptions,
355362
): ToolUseRepairReport {
356363
// Anthropic (and Cloud Code Assist) reject transcripts where assistant tool calls are not
357364
// immediately followed by matching tool results. Session files can end up with results
@@ -403,6 +410,93 @@ export function repairToolUseResultPairing(
403410

404411
const assistant = msg as Extract<AgentMessage, { role: "assistant" }>;
405412

413+
// Check for error/aborted stop reason early, before extractToolCallsFromAssistant,
414+
// because that function skips blocks without a non-empty id. For error/aborted
415+
// messages we need to strip ALL tool-like blocks regardless of id presence.
416+
const stopReason = (assistant as { stopReason?: string }).stopReason;
417+
if (stopReason === "error" || stopReason === "aborted") {
418+
// If the caller explicitly set erroredAssistantResultPolicy to "preserve",
419+
// fall back to the old behavior: push the message through unchanged and
420+
// optionally retain matching tool results for surviving tool calls.
421+
if (shouldPreserveErroredAssistantResults(options)) {
422+
const toolCalls = extractToolCallsFromAssistant(assistant);
423+
out.push(msg);
424+
if (toolCalls.length > 0) {
425+
const toolCallIds = new Set(toolCalls.map((t) => t.id));
426+
const toolCallNamesById = new Map(toolCalls.map((t) => [t.id, t.name] as const));
427+
let j = i + 1;
428+
for (; j < messages.length; j += 1) {
429+
const next = messages[j];
430+
if (!next || typeof next !== "object") {
431+
continue;
432+
}
433+
const nextRole = (next as { role?: unknown }).role;
434+
if (nextRole === "assistant") {
435+
break;
436+
}
437+
if (nextRole === "toolResult") {
438+
const toolResult = next as Extract<AgentMessage, { role: "toolResult" }>;
439+
const id = extractToolResultId(toolResult);
440+
if (id && toolCallIds.has(id)) {
441+
const normalizedToolResult = normalizeToolResultName(
442+
toolResult,
443+
toolCallNamesById.get(id),
444+
);
445+
pushToolResult(normalizedToolResult);
446+
}
447+
}
448+
}
449+
i = j - 1;
450+
}
451+
continue;
452+
}
453+
454+
// Default behavior: strip orphaned tool_use/toolCall/functionCall blocks from
455+
// the assistant message instead of passing them through unchanged.
456+
// Previously we skipped synthesis to avoid creating synthetic tool_results for
457+
// incomplete tool calls (#4597), but preserving orphaned blocks causes permanent
458+
// session corruption — Anthropic rejects every subsequent request with
459+
// "tool_use ids were found without tool_result blocks" (#48354).
460+
const content = Array.isArray(assistant.content) ? assistant.content : [];
461+
const stripped = content.filter(
462+
(b: { type?: string }) =>
463+
b && b.type !== "toolCall" && b.type !== "toolUse" && b.type !== "functionCall",
464+
);
465+
if (stripped.length < content.length) {
466+
changed = true;
467+
out.push({
468+
...assistant,
469+
content:
470+
stripped.length > 0
471+
? stripped
472+
: [{ type: "text" as const, text: "[tool calls from errored turn stripped]" }],
473+
} as typeof assistant);
474+
} else {
475+
out.push(msg);
476+
}
477+
// Skip past any trailing messages up to the next assistant turn
478+
let j = i + 1;
479+
for (; j < messages.length; j += 1) {
480+
const next = messages[j];
481+
if (!next || typeof next !== "object") {
482+
out.push(next);
483+
continue;
484+
}
485+
const nextRole = (next as { role?: unknown }).role;
486+
if (nextRole === "assistant") {
487+
break;
488+
}
489+
if (nextRole !== "toolResult") {
490+
out.push(next);
491+
} else {
492+
// Drop orphaned tool results for the stripped tool calls
493+
changed = true;
494+
}
495+
}
496+
i = j - 1;
497+
continue;
498+
}
499+
406500
const toolCalls = extractToolCallsFromAssistant(assistant);
407501
if (toolCalls.length === 0) {
408502
out.push(msg);
@@ -460,38 +554,6 @@ export function repairToolUseResultPairing(
460554
}
461555
}
462556

463-
// Aborted/errored assistant turns: strip orphaned tool_use/toolCall/functionCall
464-
// blocks from the assistant message instead of passing them through unchanged.
465-
// Previously we skipped synthesis to avoid creating synthetic tool_results for
466-
// incomplete tool calls (#4597), but preserving orphaned blocks causes permanent
467-
// session corruption — Anthropic rejects every subsequent request with
468-
// "tool_use ids were found without tool_result blocks" (#48354).
469-
const stopReason = (assistant as { stopReason?: string }).stopReason;
470-
if (stopReason === "error" || stopReason === "aborted") {
471-
const content = Array.isArray(assistant.content) ? assistant.content : [];
472-
const stripped = content.filter(
473-
(b: { type?: string }) =>
474-
b && b.type !== "toolCall" && b.type !== "toolUse" && b.type !== "functionCall",
475-
);
476-
if (stripped.length < content.length) {
477-
changed = true;
478-
out.push({
479-
...assistant,
480-
content:
481-
stripped.length > 0
482-
? stripped
483-
: [{ type: "text" as const, text: "[tool calls from errored turn stripped]" }],
484-
} as typeof assistant);
485-
} else {
486-
out.push(msg);
487-
}
488-
for (const rem of remainder) {
489-
out.push(rem);
490-
}
491-
i = j - 1;
492-
continue;
493-
}
494-
495557
out.push(msg);
496558

497559
if (spanResultsById.size > 0 && remainder.length > 0) {

0 commit comments

Comments
 (0)