Skip to content

fix(agents): record Claude subscription rate-limit facts from the CLI stream - #129485

Closed
obviyus wants to merge 3 commits into
mainfrom
fix/claude-cli-rate-limit-facts
Closed

obviyus wants to merge 3 commits into
mainfrom
fix/claude-cli-rate-limit-facts

Conversation

@obviyus

@obviyus obviyus commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

A Claude CLI turn on a production gateway (Agent SDK 0.3.232, native claude login) failed with API Error: 400 Third-party apps now draw from your extra usage, not your plan limits…. OpenClaw classified it billing and recorded nothing else. The Claude stream-json output of every turn carries a rate_limit_event (SDK SDKRateLimitInfo: status, binding window, utilization, reset time, overage status/reason, error code) emitted right before the result, and OpenClaw discarded it — so there was no record of the subscription state at the moment of the failure, and no way to tell plan exhaustion from an Anthropic-side billing classification without re-running the turn.

Why This Change Was Made

Record the fact where it happens (Product Doctrine: recorded fact at the owning boundary, not multi-signal inference later).

  • src/agents/cli-output-contracts.ts: CliOutput.diagnostics.rateLimit (CliSubscriptionRateLimit): status, binding window id, a windows map of utilization/reset per wire window id, overage status/reason, isUsingOverage, errorCode.
  • src/agents/cli-output-records.ts: parseClaudeCliRateLimit, a zod schema over the whole rate_limit_event record, gated on the Claude stream-json dialect. The wire unifiedWindows map becomes windows verbatim; the SDK-typed shape (top-level rateLimitType/utilization/resetsAt, no unifiedWindows) folds into a one-entry map. A malformed optional field drops the whole diagnostic record rather than partially recording it (accepted tradeoff, commented).
  • src/agents/cli-output-stream.ts: the streaming parser keeps the last record and attaches it once in getOutput, so it survives both success and is_error results.
  • src/agents/cli-runner/log.ts: formatCliSubscriptionRateLimitDigest renders one compact line, e.g. rateLimit=allowed five_hour=36%→2026-08-25T17:50Z seven_day=28% overage=rejected(org_level_disabled); the reset time is shown only on the binding window.
  • src/agents/cli-runner/execute-process.ts: the cli turn: info line appends the digest.
  • src/agents/cli-runner/output-error.ts: billing / rate_limit FailoverError messages append Subscription rate limit: <digest>.; rawError stays the original CLI text.

No config, env, storage, or plugin-SDK surface. Not touched: extensions/, docs, CHANGELOG.

User Impact

  • Every Claude CLI turn logs its subscription window state on the existing cli turn: line (agent/cli-backend subsystem, info level).
  • A billing / rate-limit failure now carries the plan state in its error message, so the operator can tell "5h window exhausted" from "overage disabled at org level" from "credits required" without a second probe.
  • Non-Claude CLI backends and non-stream-json output are unchanged.

Evidence

  • Live proof on a Linux gateway host, isolated OPENCLAW_STATE_DIR and dist built from this head, one openclaw agent --local turn through the Agent SDK path (anthropic/claude-fable-5):
    cli turn: provider=claude-cli model=claude-fable-5 durationMs=3742 outBytes=46 outHash=0ac7a7b49da7 rateLimit=allowed five_hour=54%→2026-08-25T17:50Z seven_day=31% seven_day_overage_included=46% overage=rejected(org_level_disabled)
    
    The same turn on the pre-change dist logs cli turn: … outBytes=2 outHash=2689367b205c with no rate-limit facts. Note the third wire window (seven_day_overage_included) that the SDK type does not declare — the window map is keyed by wire id for that reason.
  • Rejection path (error=credits_required, message enrichment) is covered by unit test only: 160 live probe turns on the same account (80 with the stock Claude Code prompt, 80 with OpenClaw's appended system prompt) all returned status=allowed, so the 400 could not be reproduced on demand.
  • node scripts/run-vitest.mjs src/agents/cli-output-stream.test.ts src/agents/cli-output-records.test.ts src/agents/cli-runner/output-error.test.ts — green (new: retain on success/error result, malformed record dropped, SDK-typed shape folds to one window, observed-record digest, minimal digest, billing failover enrichment, unrelated failure untouched). The new tests fail on pre-change code for the intended reasons (missing diagnostics.rateLimit, missing digest export, unenriched billing message).
  • oxfmt, scripts/run-oxlint.mjs on changed files, git diff --check — clean. pnpm build — clean (the two INEFFECTIVE_DYNAMIC_IMPORT warnings are pre-existing UI-side).
  • Local ClawSweeper review (gpt-5.6-terra, high) on 3ced009 raised one P2: a finite resetsAt above Date range would throw in the digest formatter and fail a successful turn. Fixed in b28d410 by bounding the reset at the schema (record dropped), with a regression test.
  • Production LOC: +108 / −4 raw numstat; cli-output-stream.ts 54/41 is a re-indent of the unchanged getOutput body into buildOutput (pure move), so net new production ≈ +95. Justified by a new recorded fact at its owning boundary. Tests +187.

… stream

Claude CLI stream-json emits a rate_limit_event after every response (Agent SDK SDKRateLimitInfo). OpenClaw discarded it, so a subscription 400 ("Third-party apps now draw from your extra usage") was classified billing with no record of the plan state at that moment.

- Parse the record into CliOutput.diagnostics.rateLimit (closed type, zod-validated, retained on the error path).
- Append a compact digest to the "cli turn:" log line.
- Append "Subscription rate limit: <digest>." to billing/rate_limit FailoverError messages.
@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@obviyus
obviyus marked this pull request as ready for review August 25, 2026 17:09
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M maintainer Maintainer-authored PR labels Aug 25, 2026
A finite reset value above Date range would throw in the digest formatter and fail an otherwise successful turn; reject the record in the schema instead.
…imit digest

The pinned Agent SDK adds canUserPurchaseCredits and
hasChargeableSavedPaymentMethod to rate_limit_event for
credits_required rejections. Keep both so a billing failure tells the
operator whether buying credits or a saved card can recover the turn.
@clawsweeper

clawsweeper Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 25, 2026, 1:33 PM ET / 17:33 UTC.

ClawSweeper review

What this changes

This PR captures Claude CLI rate_limit_event records, preserves them in CLI output diagnostics, and surfaces a compact digest in turn logs and relevant failover errors.

Merge readiness

⚠️ Needs maintainer review before merge - 4 items remain

The patch cleanly records a previously discarded Claude stream fact through the parser, log, and billing-error paths. It remains open for maintainer review because the pinned Agent SDK event contract could not be directly inspected in this checkout, and the PR carries the protected maintainer label.

Priority: P2
Reviewed head: f8f59b49ee7dbaeadac81af7f0086851f85636d2
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation and live success-path proof are useful, but direct verification of the pinned SDK event contract remains outstanding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR body provides a head-built live Claude CLI run whose turn log contains the new rate-limit digest; focused tests supplement the error-enrichment path.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides a head-built live Claude CLI run whose turn log contains the new rate-limit digest; focused tests supplement the error-enrichment path.
Evidence reviewed 7 items Current main lacks this diagnostic: Current main’s parsed-record handler updates session, usage, and terminal output but has no rate-limit-event parser or output diagnostic attachment.
PR owner-boundary implementation: The PR validates Claude stream records at the shared parser boundary and attaches the retained fact only to a built CLI output.
Caller and failure consumer: The runner creates the streaming parser for JSONL executions, then uses normalized diagnostics in the log path and appends them only after failure classification is billing or rate_limit.
Findings None None.
Security None None.

Live Verification

Command: pnpm openclaw --help

Result: PASS (completed)

$ node scripts/run-node.mjs --help
[openclaw] Building TypeScript (dist is stale: missing_build_stamp - build stamp missing).
[openclaw] Building bundled plugin assets.
[canvas] build: node scripts/bundle-a2ui.mjs
[log] ‹DIR›/a2ui.bundle.js  chunk │ size: 399.96 kB
[log] ‹DIR›/a2ui-v0.9.bundle.js  chunk │ size: 615.66 kB
[log]
[success] rolldown v1.2.0 Finished in 97.36 ms
[diffs] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts curated
[diffs-language-pack] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts full
[discord] build: node --import tsx ../../scripts/build-discord-activity-sdk.mts
[tsdown-build] invocation 1/2 finished in 0.7s
node_modules/playwright-core/lib/coreBundle.js (65821:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65821:29 ]
       │
 65821 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/playwright-core/lib/coreBundle.js (65828:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65828:29 ]
       │
 65828 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2343:30) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2343:31 ]
      │
 2343 │           ASM_CONSTS[start] = eval(func);
      │                               ──┬─
      │                                 ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2366:32) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2366:33 ]
      │
 2366 │           moduleExports[name] = eval(func);
      │                                 ──┬─
      │                                   ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

[tsdown-build] invocation 2/2 finished in 13.2s
[plugin-control-plane-loads] verified 35 built modules with native require and checked doctor closures
runtime-postbuild: 11 phases completed in 4148ms (slowest: built plugin control-plane loads 3391ms)

OpenClaw 2026.8.1 (f8f59b4) — All your chats, one OpenClaw.

Usage: openclaw [options] [command]

Options:
  --container ‹name›   Run the CLI inside a running Podman/Docker container named ‹name› (default: env OPENCLAW_CONTAINER)
  --dev                Dev profile: isolate state under ~/.openclaw-dev, default gateway port 19001, and shift derived ports (browser/canvas)
  -h, --help           Display help for command
  --log-level ‹level›  Global log level override for file + console (silent|fatal|error|warn|info|debug|trace)
  --no-color           Disable ANSI colors
  --profile ‹name›     Use a named profile (isol
… output truncated …

Assertions:

  • PASS expect_output: Usage: openclaw

How this fits together

Claude CLI stream-json records enter OpenClaw’s shared CLI parser, which returns normalized agent output to the CLI runner. The runner then emits operator diagnostics or turns terminal failures into failover errors.

flowchart LR
A[Claude CLI stream-json] --> B[CLI stream parser]
B --> C[Rate-limit diagnostic]
C --> D[Normalized CLI output]
D --> E[Turn log]
D --> F[Billing or rate-limit error]
Loading

Decision needed

Question Recommendation
Does the agent-runtime owner accept the exact Agent SDK 0.3.232 rate-limit record schema and the resulting operator-visible digest? Verify contract and proceed: Inspect the pinned SDK type/source against the accepted fields, then land once exact-head checks are green.

Why: The dependency contract is material to this parser, but cannot be independently checked from the local dependency cache or network in this review environment.

Before merge

  • Resolve merge risk (P1) - The schema depends on the pinned Agent SDK’s rate_limit_event contract, but its source/types were unavailable locally and DNS prevented direct retrieval; a mismatch would silently omit diagnostics.
  • Resolve merge risk (P1) - Production code is net +126 lines for a bug fix; the growth is plausibly justified by the new normalized fact, validation, and rendering boundary, but should remain single-path.
  • Complete next step (P2) - The protected maintainer label and unresolved direct dependency-contract check require normal owner review; no mechanical repair is identified.
Agent review details

Security

None.

PR surface

Source +126, Tests +229. Total +355 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 6 171 45 +126
Tests 3 229 0 +229
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 400 45 +355

Review metrics

Metric Value Why it matters
Production versus test LOC production +171/-45 (net +126); tests +229/-0 The added parser, normalized diagnostic contract, and rendering path are meaningful production growth for a diagnostics bug fix.

Merge-risk options

Maintainer options:

  1. Verify the pinned stream contract (recommended)
    Confirm the SDK 0.3.232 event definition covers the parsed fields before merging this new diagnostic interpretation.
  2. Accept the observed-wire risk
    Land based on the supplied live event evidence while accepting that future or undocumented field variation may omit the diagnostic.

Technical review

Best possible solution:

Keep one Claude stream-json parser boundary that validates, retains, and renders the diagnostic fact after the pinned SDK contract is directly verified.

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

No live current-main reproduction of the billing 400 is available; source inspection shows that current main discards the event, and the PR body supplies a real after-fix success-path record.

Is this the best way to solve the issue?

Yes, subject to direct SDK-contract verification: preserving the fact at the stream parser before logs and error classification is the narrowest owner-boundary repair.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This improves bounded operator diagnosis for Claude CLI billing and rate-limit failures without changing delivery or authorization behavior.
  • add merge-risk: 🚨 other: The new diagnostic parser interprets an external CLI/SDK wire record whose pinned contract could not be directly verified in this review environment.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides a head-built live Claude CLI run whose turn log contains the new rate-limit digest; focused tests supplement the error-enrichment path.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides a head-built live Claude CLI run whose turn log contains the new rate-limit digest; focused tests supplement the error-enrichment path.

Label justifications:

  • P2: This improves bounded operator diagnosis for Claude CLI billing and rate-limit failures without changing delivery or authorization behavior.
  • merge-risk: 🚨 other: The new diagnostic parser interprets an external CLI/SDK wire record whose pinned contract could not be directly verified in this review environment.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides a head-built live Claude CLI run whose turn log contains the new rate-limit digest; focused tests supplement the error-enrichment path.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides a head-built live Claude CLI run whose turn log contains the new rate-limit digest; focused tests supplement the error-enrichment path.

Evidence

What I checked:

  • Current main lacks this diagnostic: Current main’s parsed-record handler updates session, usage, and terminal output but has no rate-limit-event parser or output diagnostic attachment. (src/agents/cli-output-stream.ts:301, a2ef21e43369)
  • PR owner-boundary implementation: The PR validates Claude stream records at the shared parser boundary and attaches the retained fact only to a built CLI output. (src/agents/cli-output-records.ts:537, f8f59b49ee7d)
  • Caller and failure consumer: The runner creates the streaming parser for JSONL executions, then uses normalized diagnostics in the log path and appends them only after failure classification is billing or rate_limit. (src/agents/cli-runner/execute-process.ts:112, f8f59b49ee7d)
  • Dependency-contract signal and gap: The Anthropic plugin invokes claude --output-format stream-json and pins @anthropic-ai/claude-agent-sdk 0.3.232, so the SDK event shape is an applicable dependency contract. No installed SDK source was present and DNS prevented fetching the package types. (extensions/anthropic/package.json:8, f8f59b49ee7d)
  • Focused behavior coverage: Added tests cover retention for success and error terminal results, invalid reset rejection, SDK-style single-window normalization, digest rendering, billing enrichment, and unrelated-error preservation. (src/agents/cli-runner/output-error.test.ts:22, f8f59b49ee7d)
  • Feature provenance: Main blame attributes the stream parser and runner output boundary to the recent refactor commit, while prior merged Agent SDK session work provides adjacent ownership history. (src/agents/cli-output-records.ts:31, 3506a5521853)

Likely related people:

  • Peter Steinberger: Current-main blame attributes the stream-dialect and CLI-turn logging boundary to the recent refactor commit. (role: recent CLI parser and runner contributor; confidence: high; commits: 3506a5521853, 4e099689c075; files: src/agents/cli-output-records.ts, src/agents/cli-output-stream.ts, src/agents/cli-runner/execute-process.ts)
  • obviyus: A prior merged Agent SDK session-runtime fix and this PR both cover the Claude CLI/SDK boundary. (role: recent Anthropic Agent SDK contributor; confidence: high; commits: 1af9b07e30df; files: extensions/anthropic/cli-backend.ts, extensions/anthropic/package.json)

Rank-up moves

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

  • Inspect or cite the SDK 0.3.232 type/source for every retained rate-limit field, then confirm exact-head CI.

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.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 25, 2026
@obviyus

obviyus commented Aug 26, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: not planned.

Decision: the reported API Error: 400 Third-party apps now draw from your extra usage is not caused by anything OpenClaw sends, so a recorded-facts/message-only change is not a fix and adds surface without changing the outcome.

Why (proof, one operator host, live gateway untouched):

  • 1 failure in 228 Claude Code turns on the same claude 2.1.245 / Agent SDK binary and the same native subscription login.
  • Spawned CLI carried no OpenClaw-forwarded credential (no CLAUDE_CODE_OAUTH_TOKEN*, no credential file descriptor).
  • 200 SDK runs across stock preset, the real OpenClaw system-prompt append, the append plus a 20 KB AGENTS.md bootstrap, a 20 KB size control, and the bootstrap alone: 0 failures.
  • 15 turns through an isolated OpenClaw gateway on the real cli-backend path (workspace bootstrap, mcp__openclaw__* tools, fresh sessions): 15/15 ok.
  • Live gateway kept completing Claude turns after the event; no cooldown or routing change resulted, and the failed turn fell back to the configured secondary model.

Supported path: keep using the claude-cli agent runtime with the CLI's own login; on this 400, retry the turn. Stale copied anthropic:claude-cli profiles are cleaned by openclaw doctor --fix (#129052).

What would reopen this: a reproducible case where the same turn fails repeatedly on retry while a plain claude -p with the same prompt succeeds, with the isolated-gateway log attached.

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 merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant