Repository navigation
Description
Summary
Bumping @anthropic-ai/claude-agent-sdk to 0.3.181 (PR #731) prompted a fan-out review of how sequant consumes the SDK message stream. The review surfaced one high-value gap unrelated to the bump itself: sequant silently discards the structured rate-limit / billing signals the SDK already emits, and instead guesses rate limits via regex-on-stderr. This directly worsens the known #592 fallback-noise problem.
This issue scopes that fix (primary), records a deliberately-deferred UX idea (tool_use_meta), and captures a housekeeping flag (local SDK drift).
Part 1 — Structured rate-limit / credits error handling (PRIMARY)
Problem
Today sequant infers rate limits by regex-matching stderr text:
src/lib/workflow/error-classifier.ts:84-99—/rate.?limit/i,/\b429\b/,/overloaded/isrc/lib/workflow/phase-executor.ts:863— feedsclassifyError(lastResult.stderrTail, exitCode); never sees structured SDK data- On retry exhaustion the user gets the noisy, misleading
! Phase failed with MCP enabled, retrying without MCP...(phase-executor.ts:912) — the fix(run): pre-flight guard misses in_progress issues already merged on GitHub (gap in #305/#423) #592 fallback noise.
Meanwhile, the SDK message stream — consumed at a single clean chokepoint, src/lib/workflow/drivers/claude-code.ts:122 (for await (const message of queryInstance)) — already emits, and sequant drops on the floor:
rate_limit_event→SDKRateLimitInfo(status,resetsAt,overageDisabledReason: 'out_of_credits' | ...)assistant.error: 'rate_limit' | 'billing_error' | ...api_retrymessages (error_status,error)
The assistant handler (claude-code.ts:127-144) filters content to type === "text" only; every other message type falls through silently.
Important: these three message types exist in the currently installed 0.3.158 — this fix is viable today and does not depend on the 0.3.181 bump. The 0.3.181 additions (
errorCode,canUserPurchaseCredits,hasChargeableSavedPaymentMethodonSDKRateLimitInfo) are incremental polish layered on top once we're on 0.3.181.
Proposed approach
- In the
claude-code.ts:122stream loop, handlemessage.type === 'rate_limit_event'and theassistant.errorfield (and optionallyapi_retry), extracting the structured info. - Add a
RateLimitError(and/orBillingError) subclass insrc/lib/errors.ts(alongside the existingApiError) carryingresetsAt,overageDisabledReason, and — when on ≥0.3.181 —canUserPurchaseCredits/hasChargeableSavedPaymentMethod. - Propagate it through
AgentPhaseResultsophase-executorsurfaces an accurate message ("Out of credits" / "Rate limited — resets at HH:MM") instead of the generic fix(run): pre-flight guard misses in_progress issues already merged on GitHub (gap in #305/#423) #592 fallback noise, and skips the pointless MCP-disabled retry when the failure is billing/credits (a no-MCP retry won't fix being out of credits). - Keep the existing stderr-regex classifier as a fallback for non-SDK error paths (subprocess runs via
src/mcp/tools/run.ts).
Acceptance Criteria
- The
claude-code.tsstream loop readsrate_limit_eventand assistanterrorfields rather than discarding them. - A dedicated error type (
RateLimitError/BillingError) exists insrc/lib/errors.tsand carries at minimumresetsAtandoverageDisabledReason. - When a phase fails due to rate-limit/credits, the user-facing message names the real cause (e.g. "Out of credits" or "Rate limited, resets at ") — verified against a captured/mocked
rate_limit_event. - A credits/billing failure does not trigger the misleading "retrying without MCP" fallback path (fix(run): pre-flight guard misses in_progress issues already merged on GitHub (gap in #305/#423) #592).
- Existing stderr-regex classification still works for the subprocess path (
run.ts) — no regression inerror-classifiertests. - Unit coverage in
src/lib/workflow/drivers/claude-code.test.ts(or a sibling) drives the new message types through the loop. - When the codebase is on ≥0.3.181, the message is enriched with
canUserPurchaseCredits/hasChargeableSavedPaymentMethod(e.g. "Out of credits — purchasable" vs "hard limit"). Gate gracefully if the field is absent.
Evidence / references
- Chokepoint & dropped messages:
claude-code.ts:122,:127-144 - SDK types already present in 0.3.158:
node_modules/@anthropic-ai/claude-agent-sdk/sdk.d.ts—SDKRateLimitEvent/SDKRateLimitInfo(:3432-3455),SDKAssistantMessage.error(:2604),SDKAPIRetryMessage(~:2590) - Regex fallback:
error-classifier.ts:84-99; consumerphase-executor.ts:863, fallback noise:912 - Related: fix(run): pre-flight guard misses in_progress issues already merged on GitHub (gap in #305/#423) #592 (fallback-noise / pre-flight miss)
Part 2 — tool_use_meta human-readable tool labels (DEFERRED — out of scope here)
The 0.3.181 bump also added a tool_use_meta sidecar (display-friendly tool names + icon_url). Investigated and deliberately deferred — recorded here so it isn't re-discovered cold:
- Sequant never renders tool calls. The driver (
claude-code.ts:132) filters assistant content totype:"text"and discardstool_useblocks; the renderer (src/lib/cli-ui/run-renderer.ts) shows phase status only; the TUI activity row (src/ui/tui/IssueBox.tsx) surfaces agent prose, not tool calls. - So there is no raw-wire-name UX problem to fix — this would be a new tool-activity rendering path, not a label swap.
icon_urlis unusable in a terminal TUI. - Benefit: LOW. Revisit only if a per-tool activity surface is independently wanted (cf. closed feat(tui): enrich
nowLinewith per-file / log-tail activity #543 "enrich nowLine"). Requires ≥0.3.181 first.
No ACs — tracked as a note, not a deliverable. Split into its own issue if/when prioritized.
Part 3 — Housekeeping flag: local SDK / lockfile drift
During the review, the local working tree was found 3 commits behind origin/main (the just-merged dependabot PRs #728/#730/#731). Consequently:
- Local
package-lock.jsonandnode_modules/@anthropic-ai/claude-agent-sdkare both still 0.3.158, whileorigin/mainpins 0.3.181. - This is not a code bug — just stale local state. Anyone picking up Part 1 (or testing the 0.3.181 fields) must first:
git pull origin main && npm ciengines.nodeis>=22.12.0onorigin/main; all bumps were in-range patch/minor — no engine-floor conflict.
Acceptance Criteria
- Working tree synced to
origin/mainandnpm cirun sonode_modulesreflects 0.3.181 before validating the ≥0.3.181 enrichment AC in Part 1.
Scope note
The behavioral background/remote/-p fixes in the 0.3.158→0.3.181 range (print-mode background-notification timing, stream-json idle reporting, remote-control file_attachments) were checked and are behavior-neutral for sequant — it embeds the SDK in-process as a foreground query() with a string prompt, with no -p/headless CLI, stream-json, remote control, or file_attachments. No action needed; documented so it isn't re-investigated.
Activity
admarble commentedon Jun 20, 2026
Complexity: Standard (8 ACs, 2 directories)
AC Quality Check
All ACs are measurable with concrete verification targets. Notes:
origin/mainandnode_modules/@anthropic-ai/claude-agent-sdkis already 0.3.181. No work required; AC-8 should be checked as a precondition, not implemented.Scope Assessment
Non-Goals: Present and explicit — Part 2 (
tool_use_metatool-label rendering) is deliberately deferred (no ACs); the 0.3.158→0.3.181 background/remote/-pbehaviors are documented as behavior-neutral for sequant.src/lib/workflow/*,src/lib)Verdict:⚠️ SCOPE_WARNING (AC count ≥6) → auto-enables quality loop. Cohesive single feature; no split recommended.
Acceptance Criteria
AC-1: Stream loop reads
rate_limit_event+ assistanterrorinstead of discardingVerification: Unit Test —
claude-code.test.tsScenario: Given a mocked
queryInstanceasync-iterable emitting arate_limit_eventand anassistantmessage witherror: 'rate_limit'→ When the driver consumes the stream → Then both are captured (not silently dropped at thetype === "text"filter, claude-code.ts:127-144).Assumptions:
rate_limit_infolives onmessage.rate_limit_info; assistant error onmessage.message.error.AC-2:
RateLimitError/BillingErrorinsrc/lib/errors.tsVerification: Unit Test
Scenario: Given the new subclasses → When constructed → Then they extend
SequantError, carryresetsAt+overageDisabledReasoninmetadata, and setisRetryablecorrectly (rate-limit retryable; billing/credits NOT retryable).Assumptions: Follows the existing
ApiErrorsubclass pattern.AC-3: User-facing message names the real cause
Verification: Integration Test (phase-executor) + Unit Test (formatter)
Scenario: Given a captured/mocked
rate_limit_event→ When a phase fails → Then the message reads e.g. "Out of credits" or "Rate limited — resets at HH:MM", not the generic #592 fallback.AC-4: Credits/billing failure does NOT trigger "retrying without MCP" (#592)
Verification: Integration Test —
phase-executor.test.tsScenario: Given a phase fails with a
BillingError(out_of_credits) → When the executor reaches the MCP-fallback guard (phase-executor.ts:912) → Then the no-MCP retry is skipped (it cannot fix being out of credits).AC-5: stderr-regex classifier still works for subprocess path — no regression
Verification: Unit Test —
error-classifier.test.tsScenario: Given
run.tssubprocess stderr (no structured SDK data) → WhenclassifyErrorruns → Then api_error/429/overloaded patterns classify as before. Existing tests unchanged + green.AC-6: Unit coverage drives the new message types through the loop
Verification: Unit Test
Scenario: Given mock messages for
rate_limit_event,assistant.error, and (optionally)api_retry→ When fed through the driver loop → Then each path is asserted.AC-7: ≥0.3.181 enrichment (
canUserPurchaseCredits/hasChargeableSavedPaymentMethod)Verification: Unit Test
Scenario: Given
rate_limit_infowith the 0.3.181 fields → Then message distinguishes "Out of credits — purchasable" vs "hard limit". Given the fields absent → Then gate gracefully (no crash, generic billing message).Assumptions: Fields are optional on
SDKRateLimitInfo(confirmed present in installed 0.3.181sdk.d.ts:3832-3834).AC-8: Working tree synced to
origin/main,npm cirun (Part 3)Verification: Manual / precondition — ALREADY MET (tree at origin/main 0/0; SDK 0.3.181 installed).
Implementation Plan
Phase 1: Error types (
src/lib/errors.ts)RateLimitError extends SequantError(isRetryable: true) andBillingError extends SequantError(isRetryable: false), each declaring a typedmetadata(resetsAt?,overageDisabledReason?,rateLimitType?,canUserPurchaseCredits?,hasChargeableSavedPaymentMethod?).formatRateLimitMessage(info)helper that mapsoverageDisabledReason === 'out_of_credits'/errorCode === 'credits_required'→ BillingError text, else rate-limit-with-reset text; enrich with purchasable flag when present.Phase 2: Capture in driver (
drivers/claude-code.ts:122loop)message.type === 'rate_limit_event'→ latestrate_limit_info; in the existingassistantbranch, readmessage.message.error(and optionally handleapi_retry). Keep these in loop-scoped vars.Phase 3: Propagate via
AgentPhaseResult(drivers/agent-driver.ts:58)structuredError?: SequantErrortoAgentPhaseResult. Driver populates it; other drivers (aider) leave it undefined.phase-executor.ts: preferlastResult.structuredErrorover re-classifyError(stderrTail)for the user-facing message; guard the MCP fallback (:912) so aBillingError(and non-retryable credits case) skips the no-MCP retry. Retain the stderr-regex classifier as the fallback whenstructuredErroris absent (subprocess/run.tspath → AC-5).Phase 4: Tests
claude-code.test.ts(AC-1/6/7),phase-executor.test.ts(AC-3/4), confirmerror-classifier.test.tsunchanged + green (AC-5).Design Review
errors.ts; the retry/message decision inphase-executor. Clean separation matching the existing "driver captures, executor decides" contract (agent-driver.ts:81-83).if. Rejected: a new event-bus or refactoring the message loop into a typed dispatcher — overkill for 2-3 message types.ApiErrorsubclassing ofSequantError; reuses theclassifyError→isRetryabledecision flow already wired at phase-executor.ts:861-880.structuredErrorfield instead of reusingerror: string?" — because the executor needs the type (billing vs rate-limit) to gate the MCP retry, not just text. "Is billing non-retryable correct?" — yes; a no-MCP retry can't refill credits.Feature Quality Planning
All standard checks pass. Notable items:
AgentPhaseResultfield is optional; aider driver and subprocess path unaffected.error-classifier.ts:84-99regex stays as the subprocess fallback by design (AC-5) — not a duplicate to consolidate.Open Questions
AgentPhaseResult). Impact if wrong: executor would have to re-parse text, defeating the purpose.RateLimitErrorvsBillingError? — Recommendation: yes, two types.out_of_credits/credits_required→BillingError(non-retryable, drives the fix(run): pre-flight guard misses in_progress issues already merged on GitHub (gap in #305/#423) #592 skip); transientrate_limit/overloaded→RateLimitError(retryable). Impact if collapsed to one: harder to gate the MCP-fallback skip cleanly (AC-4).api_retrynow or defer? — Recommendation: capture it opportunistically for diagnostics but don't block AC on it (issue marks it "optionally"). Low impact.Recommended Workflow
Phases: spec → testgen → exec → qa
Quality Loop: enabled (SCOPE_WARNING auto-enable; touches retry/error control flow)
Reasoning: ACs are Unit/Integration with clear input/output → testgen stubs first. No UI → no
testphase. Not security-sensitive → nosecurity-review.Label Review
Current:
enhancement,cli,dependenciesRecommended: keep
enhancement,cli; addplanned.dependenciesis borderline — the actual SDK bump already merged (#731); this is feature work consuming the SDK, not a dep bump. Keep only if you want the SDK-coupling traceable, otherwise drop.Quality Loop: Will auto-enable (SCOPE_WARNING).
→
gh issue edit 732 --add-label plannedadmarble commentedon Jun 20, 2026
Implementation Update (/exec)
All 8 ACs satisfied. PR: #735
AC Coverage
rate_limit_event+ assistanterrordrivers/claude-code.tscapture varsRateLimitError/BillingErrortyped subclassessrc/lib/errors.tserror: structuredError.messageBillingErrorguard inphase-executor.tserror-types/error-capturetests unchanged & greenclaude-code.test.tsformatRateLimitMessage+ testsKey files changed
src/lib/errors.ts—RateLimitError,BillingError,formatRateLimitMessage,createRateLimitError, predicatessrc/lib/workflow/drivers/claude-code.ts— capturerate_limit_event/assistant.error/api_retry, build typed errorsrc/lib/workflow/drivers/agent-driver.ts+types.ts—structuredError?onAgentPhaseResult/PhaseResultsrc/lib/workflow/phase-executor.ts— preferstructuredError; guard MCP fallback againstBillingError__tests__/rate-limit-errors.test.ts(new),claude-code.test.ts,phase-executor.test.tsQuality Plan Alignment
errors.tsstays SDK-free (structuralRateLimitInfoLike); driver owns SDK importstructuredErrorfield optional; aider/subprocess paths unaffectedChecks
npm run build✅ ·npm run lint✅ (0 warnings) · targeted tests 218 ✅ · workflow sweep 1003 ✅Note: Restored an unrelated pre-existing
package-lock.jsondrift (npm droppinglibcmetadata) to keep the commit focused.admarble commentedon Jun 20, 2026
QA Review for Issue #732
AC Coverage
rate_limit_event+ assistanterrorinstead of discardingclaude-code.ts:148-165captures both (guarded byisRateLimitFailureInfo); driven through the loop inclaude-code.test.tsRateLimitError/BillingErrorextendSequantError, carryresetsAt+overageDisabledReason, correctisRetryableerrors.ts: RateLimit retryable=true, Billing retryable=false; metadata verified inrate-limit-errors.test.tserror: structuredError?.message ?? error;phase-executor.test.tsassertsresult.error === "Out of credits"; formatter unit-testedinstanceof BillingErrorguard atphase-executor.ts:918-924; two integration tests (genuine-failure + cold-start range) assert no mcp-disabled callerror-classifier.tsuntouched;error-types.test.ts+error-capture.test.tsunchanged & greenclaude-code.test.tscoversrate_limit_event,assistant.error,api_retry, allowed_warning (no false positive), successformatRateLimitMessagehandlescanUserPurchaseCreditstrue/false/undefined → "purchasable"/"hard limit"/generic; testedsdk.d.tsexposes the 0.3.181 fields; build consumes themCoverage: 8/8 AC items met (8 original, 0 derived)
CI Status
build (22.x)typecheckvalidate-skillsvalidate-pluginCI Summary: 4 passed, 0 pending, 0 failed
Quality Metrics
any)Local gates:
npm run build✅ ·npm run lint✅ (0 warnings) · affected suites 218 ✅ · workflow sweep (exec) 1003 ✅Test Coverage Analysis
src/lib/errors.ts__tests__/rate-limit-errors.test.tssrc/lib/workflow/drivers/claude-code.tsdrivers/claude-code.test.tssrc/lib/workflow/phase-executor.tsphase-executor.test.tssrc/lib/workflow/drivers/agent-driver.tssrc/lib/workflow/types.tsCoverage: 3/3 changed logic files have corresponding tests. Critical path (retry/MCP-fallback control flow) covered.
Code Review
Strengths:
errors.tsstays SDK-free via the structuralRateLimitInfoLiketype; only the driver imports the SDK. Matches the existing "driver captures, executor decides" contract.isRateLimitFailureInfo) correctly prevents a benignallowed_warningevent from being mis-attributed to an unrelated phase failure — explicitly tested.return lastResult!), and the no-result path. Traced manually;originalErroroverwrite only happens inside the now-skipped MCP-fallback block.instanceof BillingErroris safe here — single internalerrors.jsmodule, no dual-package hazard.ApiError/SequantErrorsubclass pattern;isRetryabledrives the existing retry decision flow.Issues: None blocking.
Suggestions (non-blocking):
structuredError(claude-code.ts:263-290). The capturedrateLimitInfo/assistantErrorare function-scoped and available, but thecatchreturns without building the typed error. Low-probability — rate-limit/billing failures arrive as result/assistant-error messages, not thrown exceptions (the catch is for timeout/abort/unexpected SDK throws). Could callbuildStructuredErrorin the catch for completeness as a follow-up.resetsAtunit heuristic (<1e12→ seconds, else ms): the SDK type doesn't document the unit. The heuristic is reasonable and documented, but if the SDK ever emits a small ms value the time would be wrong. Acceptable given the constraint.const isBillingFailureinphase-executor.ts:918shares a name with the exportedisBillingFailure(info)predicate (not imported here, so no compiler collision) — a different local name would read slightly clearer.Test Quality Review
isRetryable, surfaced message string), not internalsqueryis mocked (external dep) via a clean async-iterable helper/\d{2}:\d{2}/regex so TZ-independentAnti-Pattern Detection
No N+1 loops, empty catches, hardcoded secrets, or uncleared timers introduced.
package.jsonunchanged → no dependency audit. Call-site review: all 6 new exports (RateLimitError,BillingError,createRateLimitError,isRateLimitFailureInfo,isBillingFailure,formatRateLimitMessage) have live call sites — no dead exports.Risk Assessment
rate_limit_event→ catch path loses the structured cause and falls back to the raw error string (see suggestion feat: Complete remaining v1.0 features (AC-10, AC-13, AC-14) #1). Or the SDK changesresetsAtunits (heuristic could misformat).catch).run.ts) is intentionally left on the stderr-regex classifier per AC-5. No cross-file sibling requires action.structuredError; thecatchreturn is the one sibling that does not (flagged above as a non-blocking follow-up).Adversarial Re-Read
Findings: Traced every failure return path for message preservation (genuine-failure, cold-start exhaustion, no-result) — structured message survives in all three;
originalErroroverwrite is confined to the MCP-fallback block that billing now skips. Ran the build/lint/affected-suite gates fresh (all green) rather than trusting exec's claims. Verifiedinstanceofworks across the AgentPhaseResult→PhaseResult boundary (single module). Confirmed no Non-Goal expansion: Part 2 (tool_use_metarendering) is untouched; subprocess regex path retained per AC-5. One genuine gap surfaced: thecatchpath does not propagatestructuredError(low-probability, non-blocking).Status: Gaps Found
Verdict: AC_MET_BUT_NOT_A_PLUS
All 8 acceptance criteria are MET with strong test coverage, clean layering, and green CI. Downgraded from READY_FOR_MERGE only by the adversarial re-read surfacing one non-blocking gap (catch-path
structuredErrorpropagation) plus two minor suggestions. None block merge — these are follow-up polish items. Safe to merge; optionally address suggestion #1 first.Documentation
[Unreleased] → Addedentry present for feat(driver): surface structured rate-limit/credits errors from SDK message stream (replaces #592 fallback noise) #732Documentation: Before merging, optionally run
/docs 732(low value here — no user-facing config/CLI surface).Next Steps
structuredErrorin thecatchblock ofclaude-code.tsfor completeness, or file as a follow-up.git merge origin/mainbefore merging is fine).refactor(driver): propagate structuredError on catch-path; rename bil…
admarble commentedon Jun 20, 2026
QA Review for Issue #732 (re-run on
1dc6e15)Incremental review of commit
1dc6e15(the QA-suggestion follow-up) on top of the previously-reviewedd98061b. Delta: +69 lines acrossclaude-code.ts(catch-path),phase-executor.ts(rename),claude-code.test.ts(+2 tests).AC Coverage
rate_limit_event+ assistanterrorRateLimitError/BillingErrortyped subclasses, correctisRetryableCoverage: 8/8 AC items MET.
Prior-round findings — resolution
structuredErrorclaude-code.ts:277-303builds the typed error from captured signals; abort/timeout still returns first (tested both branches)isBillingFailurevar overlapped exported predicatefailureIsBillingresetsAtseconds/ms heuristicCI Status (commit
1dc6e15)typecheckbuild (22.x)validate-skillsvalidate-pluginCI Summary: 4 passed, 0 pending, 0 failed (waited for
build (22.x)to settle before verdict).Quality Metrics
anytypesLocal gates (on
1dc6e15): build ✅ · lint ✅ (0 warnings) · affected suites 220/220 ✅ · workflow sweep 934 passed / 2 skipped ✅Code Review (delta)
buildStructuredError, so a genuine timeout is never masked by a stale rate-limit signal — explicitly covered by the "abort-wins" test.structuredError?.message ?? error + stderrSuffixparses as?? (error + stderrSuffix)— correct fallback.buildStructuredErroronly attaches a cause when a failure-grade (rejected/billing) event was captured (isRateLimitFailureInfoguard), so an unrelated throw isn't mislabelled.Risk Assessment
resetsAtunit drift if the SDK emits an unexpected magnitude (mitigated by the<1e12heuristic).structuredError; the abort early-return intentionally does not (timeout is the real cause).Adversarial Re-Read
Findings: Traced the new catch-path against both branches (throw-after-rejection → typed cause surfaced; abort → timeout preserved); re-ran build/lint/tests fresh on
1dc6e15and waited for CIbuild (22.x)to go green rather than assuming; verified??/+precedence; confirmed no Non-Goal expansion (Part 2 untouched, subprocess regex path retained). No remaining gaps — the prior round's actionable items are resolved and the one accepted item is a documented engineering choice.Status: Clean
Verdict: READY_FOR_MERGE
All 8 ACs MET, all gates and CI green, prior-round suggestions resolved, adversarial re-read clean. This is an A+ implementation. Ready to merge PR #735.
Documentation
[Unreleased] → Addedentry present (feat(driver): surface structured rate-limit/credits errors from SDK message stream (replaces #592 fallback noise) #732)Documentation: Optionally run
/docs 732before merge (low value — no user-facing CLI/config surface).Next Steps
origin/mainby the dependabot commit — a cleangit merge origin/mainbefore merge keeps it tidy).admarble commentedon Jun 20, 2026
QA Review for Issue #732 (re-review @
d404ca4)Re-QA after the follow-up commit
d404ca4(catch-pathstructuredErrorpropagation + billing-guard rename) landed on top of the previously-approved1dc6e15. PR #735.AC Coverage
rate_limit_event+ assistanterrorclaude-code.ts:149-172captures both; api_retry also captured. Discriminants verified against SDKsdk.d.ts(type:'system'/subtype:'api_retry',assistant.error?).RateLimitError/BillingErrorinerrors.tsw/resetsAt+overageDisabledReasonSequantError;RateLimitMetadatacarries both fields.BillingError.isRetryable=false,RateLimitError=true.formatRateLimitMessage→ "Out of credits…" / "Rate limited — resets at HH:MM"; driven by mockedrate_limit_eventinclaude-code.test.ts.failureIsBillinggate atphase-executor.ts:913; tested incl. cold-start-window edge case (no 4th mcp-disabled call).error-classifier.tsandrun.tsuntouched; still invoked viastructuredError ?? classifyError(...). No regression.canUserPurchaseCredits…) w/ graceful gatingorigin/main+npm ci(0.3.181)Coverage: 8/8 met.
CI Status (PR #735)
mergeable: CLEAN. 149/149 relevant unit tests pass locally (
rate-limit-errors,claude-code,phase-executor).Quality Metrics
any)Code Review
Strengths:
errors.tsstays SDK-free via theRateLimitInfoLikesubset; only the driver imports the SDK.status,resetsAt,overageDisabledReason,errorCode:'credits_required',canUserPurchaseCredits) matchesSDKRateLimitInfoexactly (camelCase confirmed, not snake_case).isRateLimitFailureInfocorrectly excludesallowed/allowed_warningso a benign warning event can't poison an unrelated failure.d404ca4closed the one gap from the prior pass — catch-path now propagatesstructuredErrortoo, so all three error return sites are consistent whilesuccesscorrectly omits it.Issues: None blocking.
Suggestions (non-blocking, follow-up at most):
apiRetryErroris the lowest-precedence fallback; if the SDK does an api_retry (e.g. overloaded) and then fails for an unrelated reason, "API overloaded" could be surfaced as the cause. Low risk — rate_limit_event/assistant.error take precedence and an api_retry-then-fail is usually genuinely rate-limit-adjacent.RateLimitInfoLikeis a hand-maintained subset ofSDKRateLimitInfo; a future SDK field rename would silently stop populating (no compile error, since the driver passes the raw SDK object). Inherent to the deliberate decoupling; acceptable.Risk Assessment
SDKRateLimitInfoin a future bump → structured capture silently no-ops and behavior reverts to the stderr-regex fallback (safe degradation, not a crash).aider.ts(otherAgentDriver) andrun.ts(subprocess) — both correctly leave the optionalstructuredErrorundefined and use the unchanged stderr-regex classifier, exactly as the issue scopes. No sibling fix needed.structuredError; the success site correctly omits it. Consistent.Adversarial Re-Read
Findings: No gaps found because: ran all 8 driver + 3 executor + AC-2/3/7 error tests (149 pass); verified every SDK discriminant and field name against
node_modules/.../sdk.d.ts(not just code review); confirmed theformatResetTimeseconds-vs-ms heuristic boundary (1e12) holds for realistic epochs; confirmed abort-masking guard ordering; confirmed both fallback paths (error-classifier.ts,run.ts) are untouched so AC-5 has no regression surface; Part 2 (tool_use_meta) is explicitly a Non-Goal and correctly not implemented; noanyintroduced.Status: Clean
Verdict: READY_FOR_MERGE
A+ implementation. All 8 ACs met, CI green, mergeable CLEAN, comprehensive edge-case test coverage, clean SDK/error-module decoupling, and the follow-up commit closed the only prior gap.
Documentation
[Unreleased]entry present (feat(driver): surface structured rate-limit/credits errors from SDK message stream (replaces #592 fallback noise) #732)Next Steps
fix(driver): date-qualify multi-day rate-limit resets; prefer billing…
admarble commentedon Jun 20, 2026
Gap-fill follow-up (commit
0af8872, PR #735)Filled the two concrete gaps surfaced in the re-review, directly on the PR:
1. Multi-day reset times were misleading.
SDKRateLimitInfo.rateLimitTypecan beseven_day*, whereresetsAtis days out — butformatResetTimerendered only bare localHH:MM, which reads as "later today." Now: bareHH:MMwhen the reset is on the current calendar day, date-qualifiedMM-DD HH:MMotherwise. Added same-day and multi-day tests.2. Billing could be downgraded to retryable. If a transient
rate_limit_event(no billing reason) co-occurred withassistant.error: "billing_error",buildStructuredErrorreturned a retryableRateLimitError— which would wrongly re-enable the retry / MCP-fallback path for a non-retryable billing failure. Thebilling_errorsignal now wins over a transient throttle event; when therate_limit_eventis itself billing, its richercanUserPurchaseCreditsmetadata is preserved. Added a billing-precedence driver test.Not changed (deliberate):
rate_limit_event/assistant.errortake precedence and an api_retry-then-fail is usually genuinely rate-limit-adjacent.RateLimitInfoLikehand-maintained SDK subset — kept; importing the SDK type intoerrors.tsto guard against drift would defeat the SDK-free decoupling that module was written to preserve. Drift degrades safely to the stderr-regex fallback.Local: typecheck clean, 151/151 unit tests pass (
rate-limit-errors,claude-code,phase-executor). CI re-running on0af8872.feat(driver): surface structured rate-limit/credits errors from SDK m…
feat(#739): preserve partial output for turn-capped phases in phase-e…
fix(#860): close the residual gaps — status guard, drift telemetry, M…
fix(#860): classify live five-hour windows as waitable, not terminal …
feat(driver): surface structured rate-limit/credits errors from SDK s…
refactor(driver): propagate structuredError on catch-path; rename bil…
fix(driver): date-qualify multi-day rate-limit resets; prefer billing…