Skip to content

fix(agents): preserve Anthropic thinking-token usage - #116993

Merged
steipete merged 1 commit into
mainfrom
codex/qa300-anthropic-usage-thinking-tokens
Jul 31, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/qa300-anthropic-usage-thinking-tokens

Conversation

@steipete

Copy link
Copy Markdown
Contributor

fix(agents): preserve Anthropic thinking token usage

What Problem This Solves

Anthropic reports thinking usage in output_tokens_details.thinking_tokens, while OpenAI reports the same normalized concept in output_tokens_details.reasoning_tokens. The shared provider-agnostic usage owner understood only the OpenAI spelling, so every Claude thinking-token count silently disappeared before existing agent, session, Gateway, and accounting consumers received it.

Why This Change Was Made

Recognize the official Anthropic field at the existing canonical normalization boundary. Preserve the existing OpenAI spelling as the higher-priority value and use nullish selection so explicitly reported zero thinking tokens remain observable.

The installed Anthropic SDK defines the field for both streamed message-delta usage and final response usage in node_modules/@anthropic-ai/sdk/src/resources/messages/messages.ts:1189-1199, :1292-1303, and :2382-2395. The installed OpenAI SDK retains its existing reasoning_tokens contract in node_modules/openai/src/resources/responses/responses.ts:7275-7282.

User Impact

Claude thinking-token counts now reach the same existing reasoning-token metrics and reporting paths already used by OpenAI. Existing token totals, cache counts, OpenAI precedence, public configuration, plugin SDK, authentication, persistence, and protocol behavior do not change.

Evidence

  • Frozen baseline: 36b80ada3ceae2de21b3d8710b883d778e4c4578.
  • Reviewed candidate: 63ddaa2d1bb23131b2d0cb73ec0a8f0e83afb86d.
  • node scripts/run-vitest.mjs src/agents/usage.test.ts: 47 tests passed.
  • Authentic before/after probe: Anthropic thinking_tokens: 17 previously produced no reasoningTokens; the candidate reports 17, preserves explicit zero, preserves OpenAI 17, and retains OpenAI precedence when both fields are present.
  • Independently reviewed against the actual installed Anthropic and OpenAI SDK source, canonical callers, sibling aliases, and the complete two-file diff: clean.
  • Genuine exact full-branch structured Codex gpt-5.6-sol / high / P3 autoreview: clean, confidence 0.95, no actionable P0/P1/P2/P3 findings; TruffleHog preflight clean.
  • Production delta: +1 line; focused regression coverage: +19 lines.
  • No public configuration, public SDK, protocol, security, authentication, SQLite, schema, or persistent-state changes.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS maintainer Maintainer-authored PR labels Jul 31, 2026
@steipete
steipete marked this pull request as ready for review July 31, 2026 18:58
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels Jul 31, 2026
@clawsweeper

clawsweeper Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 31, 2026, 3:05 PM ET / 19:05 UTC.

ClawSweeper review

What this changes

This PR recognizes Anthropic thinking_tokens inside provider output details so the existing normalized reasoningTokens field retains Claude thinking usage.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 4 items remain

Keep this PR open for protected-label maintainer review and redacted real-provider evidence. Current main still drops the Anthropic spelling at the shared normalization owner, and the patch is the right narrow shape; likely related people are steipete (high confidence) and Vincent Koc (medium confidence).

Priority: P2
Reviewed head: 63ddaa2d1bb23131b2d0cb73ec0a8f0e83afb86d

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The implementation is focused and internally consistent, but it lacks independently inspectable real-provider behavior proof.
Proof confidence 🦪 silver shellfish (2/6) Needs stronger real behavior proof before merge: The PR body asserts an authentic probe but contains no visible after-fix terminal/live output or artifact; add redacted real Anthropic output showing the normalized result, then update the body for a fresh review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The PR body asserts an authentic probe but contains no visible after-fix terminal/live output or artifact; add redacted real Anthropic output showing the normalized result, then update the body for a fresh review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Current-main omission: Current main accepts only output_tokens_details.reasoning_tokens; it has no Anthropic thinking_tokens alias, so the central behavior remains unfixed.
Canonical owner and consumers: The shared normalizer is applied to raw agent/message candidates before emitting run usage, and the same normalized representation is read by session cost/reporting code; adding the alias there avoids a provider-specific downstream workaround.
Existing normalization contract: The current focused tests already establish the analogous OpenAI Responses output_tokens_details.reasoning_tokens behavior, making the proposed Anthropic alias and precedence coverage a focused extension of the existing contract.
Findings None None.
Security None None.

How this fits together

Provider and stream adapters supply raw token-usage payloads to the agent runtime. The shared usage normalizer turns those payloads into agent events, transcript data, Gateway-compatible usage, and session cost/reporting inputs.

flowchart LR
  A[Provider usage payload] --> B[Agent stream and subscription]
  B --> C[Shared usage normalizer]
  C --> D[Agent run usage events]
  C --> E[Session transcript usage]
  D --> F[Gateway and API consumers]
  E --> G[Cost and usage reporting]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The PR body asserts an authentic probe but contains no visible after-fix terminal/live output or artifact; add redacted real Anthropic output showing the normalized result, then update the body for a fresh review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - The exact Anthropic SDK declaration was not independently inspectable in this read-only checkout, so the provider field still needs visible real-response confirmation before merge.
  • Resolve merge risk (P1) - The PR body describes a before/after probe but supplies no redacted terminal output, log, recording, or linked artifact that directly shows the after-fix normalized value.
  • Complete next step (P2) - The protected maintainer label and missing real-provider proof require explicit maintainer handling; there is no concrete automated repair beyond requesting evidence.
Agent review details

Security

None.

PR surface

Source +1, Tests +19. Total +20 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 3 2 +1
Tests 1 19 0 +19
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 22 2 +20

Review metrics

None.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep the provider spelling at the shared usage-normalization boundary, retaining reasoning_tokens precedence, and merge only after a redacted real Anthropic response visibly proves thinking_tokens reaches normalized reasoningTokens.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep the provider spelling at the shared usage-normalization boundary, retaining reasoning_tokens precedence, and merge only after a redacted real Anthropic response visibly proves thinking_tokens reaches normalized reasoningTokens.

Do we have a high-confidence way to reproduce the issue?

No high-confidence live reproduction is available in this read-only checkout: current source clearly omits the fallback, but the installed Anthropic SDK type and a redacted real response were unavailable for independent verification.

Is this the best way to solve the issue?

Unclear pending provider-payload proof: the shared normalizer is the best owner boundary and the precedence order is correct, but the exact Anthropic wire shape still needs direct confirmation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 38d53e324d78.

Labels

Label changes:

  • add P2: This is a bounded existing-behavior provider-usage accounting defect with a limited but real reporting and observability impact.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR body asserts an authentic probe but contains no visible after-fix terminal/live output or artifact; add redacted real Anthropic output showing the normalized result, then update the body for a fresh review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Label justifications:

  • P2: This is a bounded existing-behavior provider-usage accounting defect with a limited but real reporting and observability impact.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR body asserts an authentic probe but contains no visible after-fix terminal/live output or artifact; add redacted real Anthropic output showing the normalized result, then update the body for a fresh review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Current-main omission: Current main accepts only output_tokens_details.reasoning_tokens; it has no Anthropic thinking_tokens alias, so the central behavior remains unfixed. (src/agents/usage.ts:33, 38d53e324d78)
  • Canonical owner and consumers: The shared normalizer is applied to raw agent/message candidates before emitting run usage, and the same normalized representation is read by session cost/reporting code; adding the alias there avoids a provider-specific downstream workaround. (src/agents/embedded-agent-subscribe.ts:635, 38d53e324d78)
  • Existing normalization contract: The current focused tests already establish the analogous OpenAI Responses output_tokens_details.reasoning_tokens behavior, making the proposed Anthropic alias and precedence coverage a focused extension of the existing contract. (src/agents/usage.test.ts:121, 38d53e324d78)
  • Feature-history provenance: History identifies steipete's May 22, 2026 OpenAI reasoning-token preservation fix as the source of the existing spelling; the proposed fallback extends that same provider-agnostic normalization seam. (src/agents/usage.ts:200, 0ddf51cf7106)
  • Release and current-main check: The latest supplied release is v2026.7.1 at 2d2ddc43, which predates the current-main commit inspected here; current main still lacks the alias, so this PR is not obsolete or already implemented. (src/agents/usage.ts:204, 38d53e324d78)
  • Dependency-inspection gap: The repository pins @anthropic-ai/sdk 0.115.0, but this read-only checkout has no installed SDK sources and the promisor/GitHub fetch path could not resolve DNS; the exact upstream field declaration therefore was not independently confirmed locally. (package.json:1937, 38d53e324d78)

Likely related people:

  • steipete: History attributes the original OpenAI reasoning-token preservation work in this shared normalization path to steipete, and this PR extends that established contract. (role: feature owner; confidence: high; commits: 0ddf51cf7106, 2f24ea492bcc; files: src/agents/usage.ts, src/agents/usage.test.ts)
  • Vincent Koc: The current grafted usage helper and focused test file trace to Vincent Koc's recent repository snapshot commit, making them a useful adjacent routing contact for the present implementation. (role: recent area contributor; confidence: medium; commits: a133f63488a3; files: src/agents/usage.ts, src/agents/usage.test.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Add redacted terminal or live-output evidence from a real Anthropic response showing thinking_tokens becomes reasoningTokens.
  • Include the claimed zero-value and OpenAI-precedence results in that proof or in a linked reproducible validation transcript.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete
steipete merged commit 629d3c2 into main Jul 31, 2026
186 of 195 checks passed
@steipete
steipete deleted the codex/qa300-anthropic-usage-thinking-tokens branch July 31, 2026 19:17
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XS status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant