Skip to content

fix: check "toolCall" instead of "toolUse" in stripDanglingAnthropicToolUses (closes #41571) - #46866

Closed
Br1an67 wants to merge 2 commits into
openclaw:mainfrom
Br1an67:fix/41571
Closed

Br1an67 wants to merge 2 commits into
openclaw:mainfrom
Br1an67:fix/41571

Conversation

@Br1an67

@Br1an67 Br1an67 commented Mar 15, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Problem: stripDanglingAnthropicToolUses checks block.type !== "toolUse" but pi-agent-core stores tool calls as type: "toolCall". Since "toolCall" !== "toolUse" is always true, the filter keeps all blocks, making the function a no-op.
  • Why it matters: Dangling tool call blocks are never removed after context truncation, causing "tool_use ids found without tool_result blocks" errors from the Anthropic API. This breaks long-running sessions that hit context limits.
  • What changed: Updated the type check in stripDanglingAnthropicToolUses from "toolUse" to "toolCall" in src/agents/pi-embedded-helpers/turns.ts. Also corrected the local AnthropicContentBlock type union.
  • What did NOT change (scope boundary): Bug 2 from the issue (empty assistant messages on LLM failure) is not addressed here — it is a separate concern. No other files were modified.

Change Type (select all)

  • Bug fix

Scope (select all touched areas)

  • Gateway / orchestration

Linked Issue/PR

User-visible / Behavior Changes

Long-running sessions that hit context truncation will now correctly strip dangling tool call blocks, preventing Anthropic API rejection errors.

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Repro + Verification

Environment

  • OS: Any
  • Runtime/container: Node.js
  • Model/provider: Anthropic (claude-sonnet-4-6 with thinking)
  • Integration/channel: Telegram DM (or any long session)

Steps

  1. Run a long session with thinking enabled until context window is nearly full
  2. Context truncation removes some messages, leaving orphaned tool_call blocks
  3. Next request sends orphaned tool_call blocks without matching tool_result
  4. Anthropic API rejects with "tool_use ids found without tool_result blocks"

Expected

  • stripDanglingAnthropicToolUses removes orphaned tool_call blocks before sending to API

Actual

  • The function was a no-op because it checked for the wrong type string, so orphaned blocks were never removed

Evidence

  • Failing test/log before + passing after

Type check (pnpm tsgo) passes with no new errors. Format and lint clean. No existing test file for turns.ts — the fix is a one-character type string correction with clear correctness.

Human Verification (required)

  • Verified scenarios: Confirmed pi-agent-core types.d.ts uses type: "toolCall" (not "toolUse"); verified openai.ts line 82 checks both types confirming both exist in codebase
  • Edge cases checked: The AnthropicContentBlock type union was also updated to match
  • What you did not verify: Runtime end-to-end testing with actual long-running session

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly: Revert this commit
  • Files/config to restore: src/agents/pi-embedded-helpers/turns.ts
  • Known bad symptoms reviewers should watch for: If tool_call blocks are incorrectly stripped, tool results may not match

Risks and Mitigations

None

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Mar 15, 2026
@greptile-apps

greptile-apps Bot commented Mar 15, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a real bug in stripDanglingAnthropicToolUses where the predicate checked for "toolUse" but pi-agent-core stores tool-call blocks as "toolCall", making the function a no-op and causing Anthropic API errors in long-running sessions that hit context truncation. The logic of the runtime fix is correct.

Key issue found:

  • The test file src/agents/pi-embedded-helpers.validate-turns.test.ts was not updated alongside the source change. All dangling-strip test fixtures (including the makeDualToolUseAssistantContent helper and individual test cases on lines 371, 392, 421, 470, etc.) still use type: "toolUse" for assistant content blocks. With the new predicate checking block.type !== "toolCall", a "toolUse" block satisfies the guard and is kept rather than stripped — the tests that assert stripping behaviour will now fail or silently pass for the wrong reason, providing no coverage of the actual fix.

Confidence Score: 2/5

  • The runtime fix is directionally correct but the test suite was not updated to match, leaving the fix uncovered by tests and breaking existing test expectations.
  • The two-line source change is the right fix for the described bug, and is consistent with how other parts of the codebase (e.g. openai.ts line 82) reference "toolCall". However, the companion test file was not updated: multiple test fixtures still use type: "toolUse", so the tests that are supposed to validate stripping will now either fail or no longer exercise the real code path. Until the tests are aligned with type: "toolCall", there is no automated assurance that the fix works correctly and regressions could go undetected.
  • src/agents/pi-embedded-helpers.validate-turns.test.ts — all dangling-strip test fixtures need type: "toolUse" changed to type: "toolCall"
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-helpers/turns.ts
Line: 68-69

Comment:
**Test fixtures out of sync with the fix**

The existing test suite in `src/agents/pi-embedded-helpers.validate-turns.test.ts` builds all its assistant-message fixtures using `type: "toolUse"` (e.g. lines 15–16, 371, 392, 421, 469, 471). After this change, the filter predicate only strips blocks whose `type === "toolCall"`, so a block typed `"toolUse"` satisfies `block.type !== "toolCall"` → `true` and is therefore **kept** rather than stripped.

This means several tests that rely on the stripping behaviour will now produce the wrong result:

- `"should strip tool_use blocks without matching tool_result"` — expects the `toolUse` block to be removed; it will be kept instead.
- `"should insert fallback text when all content would be removed"` — same issue; the fallback text path will never be reached.
- `"should handle multiple dangling tool_use blocks"` and `"should handle mixed tool_use with some having matching tool_result"` — both rely on `makeDualToolUseAssistantContent()` which emits `type: "toolUse"` blocks.

The test helpers and fixtures should be updated to use `type: "toolCall"` to match the runtime data produced by pi-agent-core, so the tests actually exercise the fixed code path.

How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: 9d03fca

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9d03fca5df

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

return false;
}
if (block.type !== "toolUse") {
if (block.type !== "toolCall") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Handle Anthropic toolUse blocks when stripping calls

Filtering only toolCall regresses the existing Anthropic toolUse shape that this repo still handles elsewhere (for example src/agents/session-transcript-repair.ts explicitly preserves toolUse.input for Anthropic, and src/agents/pi-embedded-helpers.validate-turns.test.ts covers toolUse assistant blocks). In sessions where assistant content uses toolUse, dangling tool calls are now left in place, so truncated histories can still trigger Anthropic's tool_use ids found without tool_result blocks rejection; the stripping logic should remain compatible with both toolCall and toolUse.

Useful? React with 👍 / 👎.

Comment on lines +68 to 69
if (block.type !== "toolCall") {
return true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test fixtures out of sync with the fix

The existing test suite in src/agents/pi-embedded-helpers.validate-turns.test.ts builds all its assistant-message fixtures using type: "toolUse" (e.g. lines 15–16, 371, 392, 421, 469, 471). After this change, the filter predicate only strips blocks whose type === "toolCall", so a block typed "toolUse" satisfies block.type !== "toolCall" → true and is therefore kept rather than stripped.

This means several tests that rely on the stripping behaviour will now produce the wrong result:

  • "should strip tool_use blocks without matching tool_result" — expects the toolUse block to be removed; it will be kept instead.
  • "should insert fallback text when all content would be removed" — same issue; the fallback text path will never be reached.
  • "should handle multiple dangling tool_use blocks" and "should handle mixed tool_use with some having matching tool_result" — both rely on makeDualToolUseAssistantContent() which emits type: "toolUse" blocks.

The test helpers and fixtures should be updated to use type: "toolCall" to match the runtime data produced by pi-agent-core, so the tests actually exercise the fixed code path.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-helpers/turns.ts
Line: 68-69

Comment:
**Test fixtures out of sync with the fix**

The existing test suite in `src/agents/pi-embedded-helpers.validate-turns.test.ts` builds all its assistant-message fixtures using `type: "toolUse"` (e.g. lines 15–16, 371, 392, 421, 469, 471). After this change, the filter predicate only strips blocks whose `type === "toolCall"`, so a block typed `"toolUse"` satisfies `block.type !== "toolCall"` → `true` and is therefore **kept** rather than stripped.

This means several tests that rely on the stripping behaviour will now produce the wrong result:

- `"should strip tool_use blocks without matching tool_result"` — expects the `toolUse` block to be removed; it will be kept instead.
- `"should insert fallback text when all content would be removed"` — same issue; the fallback text path will never be reached.
- `"should handle multiple dangling tool_use blocks"` and `"should handle mixed tool_use with some having matching tool_result"` — both rely on `makeDualToolUseAssistantContent()` which emits `type: "toolUse"` blocks.

The test helpers and fixtures should be updated to use `type: "toolCall"` to match the runtime data produced by pi-agent-core, so the tests actually exercise the fixed code path.

How can I resolve this? If you propose a fix, please make it concise.

@Br1an67
Br1an67 force-pushed the fix/41571 branch 3 times, most recently from 9d03fca to d6752e7 Compare March 15, 2026 21:56

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d6752e72c1

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +71 to +74
id === defaultSlotIdForKey("contextEngine") &&
normalizedOwner !== CORE_CONTEXT_ENGINE_OWNER
) {
return { ok: false, existingOwner: CORE_CONTEXT_ENGINE_OWNER };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Allow core to register the default context engine

This new owner gate blocks the default legacy context engine from ever being registered in normal startup: ensureContextEnginesInitialized() still calls registerLegacyContextEngine() (in src/context-engine/legacy.ts), which uses registerContextEngine() and therefore the hardcoded public-sdk owner, so this check returns { ok: false } for the default slot id and the result is ignored. In environments that keep the default plugins.slots.contextEngine unset, resolveContextEngine() then throws that legacy is not registered, breaking agent/compaction flows that rely on the built-in fallback.

Useful? React with 👍 / 👎.

@mike2024-dev

Copy link
Copy Markdown

We've verified this fix in production. The type mismatch ("toolUse" vs "toolCall") causes stripDanglingAnthropicToolUses() to be a complete no-op — it never strips anything because the condition block.type !== "toolUse" always evaluates to true when blocks are stored as "toolCall".

After patching this locally (adding && block.type !== "toolCall" to the filter), orphaned tool_use blocks from timed-out/crashed tool calls are now correctly stripped before reaching the Anthropic API.

This is a critical fix — without it, a single orphaned tool_use from a timeout permanently corrupts the session, causing an infinite retry loop that burns tokens until manual /new reset. We observed 164 failures across 10 corruption events over 11 days before applying the patch.

Would appreciate this getting merged. Happy to help with review if needed.

Br1an67 and others added 2 commits March 17, 2026 16:28
…oolUses (closes openclaw#41571)

pi-agent-core stores tool calls as type "toolCall" internally, but
stripDanglingAnthropicToolUses was checking for "toolUse". Since
"toolCall" !== "toolUse" is always true, the filter kept all blocks,
making the function a no-op. Dangling tool call blocks were never
removed, causing "tool_use ids found without tool_result blocks" errors
from the Anthropic API after context truncation.

Co-authored-by: Copilot <[email protected]>
Align test fixtures with the runtime type produced by pi-agent-core.
The existing tests used "toolUse" for assistant content blocks, but
pi-agent-core stores them as "toolCall". This ensures tests actually
exercise the fixed stripping code path.
@openclaw-barnacle openclaw-barnacle Bot added the r: too-many-prs Auto-close: author has more than twenty active PRs. label Mar 17, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing this PR because the author has more than 10 active PRs in this repo. Please reduce the active PR queue and reopen or resubmit once it is back under the limit. You can close your own PRs to get back under the limit.

@Br1an67

Br1an67 commented Mar 17, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the production validation, @mike2024-dev — the 164 failures / 10 corruption events data is very helpful in confirming the severity.

No worries about the closure — it was just the bot enforcing the active PR limit. I'm cleaning up my queue now and will reopen this PR shortly with the updated test fixtures (as flagged by the Greptile review). Should be back up soon.

Saw your #48888 as well — looks like a nice complementary fix for the error/aborted path. Once this one is reopened and merged, yours should be unblocked too. 🦞

mike2024-dev added a commit to mike2024-dev/openclaw that referenced this pull request Mar 18, 2026
…d of skipping

When repairToolUseResultPairing encounters an assistant message with
stopReason === 'error' or 'aborted', it previously skipped the message
entirely to avoid creating synthetic tool_results for incomplete tool
calls (see openclaw#4597).

However, skipping these messages preserves any orphaned tool_use blocks
inside them. Anthropic then rejects every subsequent API request with:
  'tool_use ids were found without tool_result blocks immediately after: <ID>'

This causes permanent session corruption — the same error fires on every
retry until a human manually resets the session (see openclaw#48354).

The fix: instead of skipping, strip the tool_use/toolCall blocks from
error/aborted messages. Text content (if any) is preserved. If the
message becomes empty after stripping, a placeholder text block is
inserted so the message remains structurally valid.

This avoids both failure modes:
- Does NOT create synthetic tool_results (preserves openclaw#4597 fix)
- Does NOT preserve orphaned tool_use blocks (fixes openclaw#48354)

Fixes openclaw#48354
Related: openclaw#4597 openclaw#46866 openclaw#45393
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling r: too-many-prs Auto-close: author has more than twenty active PRs. size: XS

Projects

None yet

2 participants