Skip to content

feat: a failed turn says when the limit that refused it resets (resetsAt) - #280

Merged
xxchan merged 3 commits into
mainfrom
feat/limit-resets-at
Oct 9, 2026
Merged

xxchan merged 3 commits into
mainfrom
feat/limit-resets-at

Conversation

@TennyZhuang

@TennyZhuang TennyZhuang commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

A failed turn now says when the limit that refused it resets, where the runtime reports that time for the failure; a claude subscription limit's refusal is classed quota; and the failed turn is a union tagged by failure, so each field exists only on the failure it means something for:

export type TurnOutcome = { kind: "completed" } | { kind: "aborted" } | FailedTurn;

export type FailedTurn = // exported
  | { kind: "failed"; failure: "auth"; reason: string; status?: number; credential?: CredentialProblem }
  | { kind: "failed"; failure: "quota"; reason: string; status?: number; resetsAt?: UtcInstant } // same type as AccountUsageWindow.resetsAt
  | { kind: "failed"; failure: Exclude<FailureClass, "auth" | "quota">; reason: string; status?: number };

resetsAt exists only on quota: rate_limited never carries one (retry delays are not oar's). Reading credential or resetsAt without checking failure first does not compile.

Why: a host that continues a session once a usage limit resets (Ferry's auto-continue, like Claude Code's interactive autoContinueAtUsageLimit) needs the reset time of the limit that stopped the turn. Before this, such a turn said only failure: "quota" or "rate_limited", and a claude subscription limit was rate_limited, so failureAdvice said to retry now.

It is a fact only: absent when the runtime gives no time, never derived from an account-usage read, a usage snapshot, a retry delay or prose. It is the runtime's last report, so it may already be past when a turn fails; a past time means the host should treat the reset as unknown (the projection reads no clock). oar does not retry or continue. No new event kind, no limit/window field (account usage covers the windows).

Per runtime

Runtime Source Outcome
claude rate_limit_event {rate_limit_info: {status, resetsAt (unix s), rateLimitType, overageStatus, …}}, sent whenever claude's view of a claude.ai subscription's limits changes, a refused 429 included, before the turn's error assistant frame (error: "rate_limit") and result (api_error_status: 429) rate_limit while the latest event says rejected, overage does not take the requests (overageStatus absent or rejected) and it names resetsAt: quota with that resetsAt. Otherwise rate_limited with none
codex usageLimitExceeded carries no data; the time is only in the message, in local time ("Try again at 3:05 PM.") none: oar does not parse the text, and matching an account/rateLimits/updated snapshot to the failure would be inference
pi, pi-durable provider text; pi-ai words a ChatGPT plan's reset "Try again in ~N min." none
opencode, kimi, grok, antigravity nothing in the failure-evidence runs none
cursor RateLimitError has code, status, isRetryable, no time none

claude: the projection keeps the latest event across turns until another replaces it (claude reports a change, and re-sends an unchanged rejection at most every 30 s behind a default-on flag), so a second refused turn may have no event of its own. An allowed / allowed_warning event, or a rejection overage covers, clears it. A rejection naming no reset stays rate_limited: claude also marks a subscriber's 429 without limit headers rejected with no reset, and words that one a temporary capacity issue. Only a rate_limit failure is reclassified; a 529 after a rejection is not. RuntimeFailureError is unchanged: no open makes a model request.

Release notes (0.50.0)

Behavior changes

  • A failed TurnOutcome is now FailedTurn, a union tagged by failure. Hosts that read outcome.credential directly must first check outcome.failure === "auth" (and failure === "quota" before resetsAt); otherwise it no longer compiles. Values at runtime are unchanged apart from the next item.
  • A claude turn refused by a claude.ai subscription's usage limit (a rate_limit failure after a rejected rate_limit_event naming a reset) now fails with failure: "quota" and resetsAt, where it was rate_limited. failureAdvice says retry: "later" for it instead of "now". Hosts that branch on rate_limited to catch claude subscription limits now see quota. Throttling with no such event (an API key, a gateway) is still rate_limited.

Added

  • FailedTurn, exported.
  • resetsAt?: UtcInstant on a quota failure (claude only). A time already past means unknown.

Evidence

  • claude: Agent SDK 0.3.295 sdk.d.ts (SDKRateLimitEvent, SDKRateLimitInfo, "emitted when rate limit info changes"; bundles claude 2.1.295) and the claude 2.1.289 binary, read only: the rate_limit_info zod schema (same fields and enums), the print-mode listener that writes the frame on every limits change, the 429 handler that updates the limits from the anthropic-ratelimit-unified-* headers before the rate_limit error message is built, the headerless 429 marked rejected without a reset, and the 30 s re-send of an unchanged rejection.
  • No live verification: oar never deliberately triggers an error on a real account, and only a subscription at its limit makes claude send a rejected event (a scripted provider cannot: claude reads these headers only on a claude.ai login). This is the one failure mapping resting on [src]/[sym]; runtime-matrix says so. The recorded fixtures' rate_limit_event frames are scrubbed to {type}.
  • codex: codex app-server generate-json-schema (0.148.0) CodexErrorInfo / TurnError; codex-rs protocol/src/error.rs (UsageLimitReachedError.resets_at only formatted into the message).
  • pi-ai 1.1.0 openai-codex-responses.js; @cursor/sdk 1.0.37 errors.d.ts.

Type-check plumbing: the root tsconfig.json maps @botiverse/oar (and its subpaths) to packages/oar/src. Tests hand src-typed sessions to CLI functions that import @botiverse/oar, i.e. the built dist; UtcInstant's unique symbol brand is a different type in each copy, so once Event reaches a UtcInstant the root tsc rejected cli-progress, cli-mcp and cli-each-runtime. Consumers see one copy and are unaffected; the CLI's own typecheck still runs against dist.

Tests

  • tests/claude/claude-limit-reset.test.ts: a rate_limit after a rejected, uncovered event naming a reset is quota with resetsAt; a rate_limit with no event stays rate_limited with none. Through claudeSession on a fake process: the refused turn ends quota with the reset, the frame is recorded verbatim with no event, and a second refusal with no new event keeps claude's last report. On the projection: rate_limited with no reset after allowed, allowed_warning, a rejection overage covers, a rejection with no reset (with or without rateLimitType, or a non-number), or a rejection a later allowed replaced; a 529 after a rejection, a billing_error and an auth failure keep their classes. Mutation-checked: leaving the class rate_limited, dropping the rate_limit gate, the overage check or the carry across turns, or keeping a stale reset when a non-refusing event arrives, each fails a test.
  • tests/failed-turn.test.ts: type-level. Reading credential or resetsAt on an unnarrowed FailedTurn, and building a rate_limited with resetsAt, a quota with credential or an auth with resetsAt, are each @ts-expect-error. Against a flat failed type all five lines compile (TS2578), so each one is load-bearing. Reading after checking failure compiles and returns the values.
  • tests/failure-mapping.test.ts: the claude table passes limitResetsAt: null. The vendor failure tests (sea-trial/vendor/failure-classes*.vendor.test.ts) read credential after narrowing.
  • pnpm run check (typecheck, lint, tests, mock sea trial) and pnpm run build on faa5323, rebased on c21dfe6 (fix(claude): confirm resume readiness before opening #287): typecheck, lint and build green; 1420 tests passed, 159 skipped, 1 failed: acp-process (an ACP request timing out at 500 ms), with machine load around 52; it passes alone. Mock sea trial 19/19. The aimock vendor tests were not run locally: no real runtime turns, and a scripted provider cannot make claude send the frame (CI runs the behavior backends).

Docs: FailedTurn, TurnOutcome and failureAdvice comments, record-stream (the TurnOutcome shape), runtime-matrix (when a limit resets, the mapping rules, the claude table), claude page (usage limits), codex page, conversation spec (beside failureAdvice), roadmap.

🤖 Generated with Claude Code

TennyZhuang pushed a commit that referenced this pull request Oct 9, 2026
Review of #280. claude's `rate_limit` category covers throttling and a
claude.ai subscription's usage limit alike, so the refusal stayed
`rate_limited` and `failureAdvice` told hosts to retry now while the
limit might be hours from resetting. When claude's latest
`rate_limit_event` says `rejected`, overage does not take the requests
and it names `resetsAt`, the failure is a usage limit until it resets:
`quota`, with that `resetsAt`. Without such an event (an API key's
throttling, a subscriber's 429 without limit headers, which claude marks
rejected with no reset and words a capacity issue) it stays
`rate_limited`.

The kept event is claude's last report, so the time may already be past
when a later turn fails; the contract now says a past time means unknown,
and the projection still reads no clock. The docs state that this mapping
rests on the SDK types and the binary only (oar never triggers an error
on a real account), and that codex's prose time and rate-limit snapshots
are not read for the failure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Ferryman and others added 3 commits October 9, 2026 16:34
…sAt)

A host that continues a session once a usage limit resets (auto-continue,
like Claude Code's interactive autoContinueAtUsageLimit) needs the reset
time of the limit that stopped the turn; a limit failure said only
`quota` or `rate_limited`.

TurnOutcome's failed variant gets `resetsAt?: UtcInstant`, the type
account usage already uses, set only where the runtime reports that time
for the failure. It is a fact: never derived from an account-usage read,
a usage snapshot, a retry delay or prose, and oar does not retry.

Only claude reports one. Its `rate_limit_event` frames (Agent SDK
0.3.295 SDKRateLimitInfo, the 2.1.289 binary) carry each change of a
claude.ai subscription's limits, a refused 429 included, before the
turn's error frame. The projection keeps the latest event's `resetsAt`
(unix seconds) while it says `rejected` and overage does not take the
requests, and gives it to a failure claude categorizes `rate_limit`. The
frame still carries no event. codex says the time only as local-time
prose; pi, the ACP runtimes and cursor report none.

The root tsconfig maps @botiverse/oar to its sources: tests hand
src-typed sessions to CLI functions typed against the built dist, and
UtcInstant's unique-symbol brand differs between the two copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of #280. claude's `rate_limit` category covers throttling and a
claude.ai subscription's usage limit alike, so the refusal stayed
`rate_limited` and `failureAdvice` told hosts to retry now while the
limit might be hours from resetting. When claude's latest
`rate_limit_event` says `rejected`, overage does not take the requests
and it names `resetsAt`, the failure is a usage limit until it resets:
`quota`, with that `resetsAt`. Without such an event (an API key's
throttling, a subscriber's 429 without limit headers, which claude marks
rejected with no reset and words a capacity issue) it stays
`rate_limited`.

The kept event is claude's last report, so the time may already be past
when a later turn fails; the contract now says a past time means unknown,
and the projection still reads no clock. The docs state that this mapping
rests on the SDK types and the binary only (oar never triggers an error
on a real account), and that codex's prose time and rate-limit snapshots
are not read for the failure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of #280. A failed TurnOutcome carried `credential` and `resetsAt`
on every class, so a host could read a quota's `credential` or a
throttle's `resetsAt` and get a silent undefined. The failed variant is
now `FailedTurn`, tagged by `failure`: `credential` exists only on
`auth`, `resetsAt` only on `quota` (`rate_limited` never carries it;
retry delays are not oar's), `status` on every class. Reading either
field without checking `failure` first no longer compiles.

`FailedTurn` is exported. The adapters build it per class (claude's
auth and quota branches explicitly; codex, pi, grok and ACP through the
class alone), `Classified` drops the `credential` no caller set, the
vendor failure tests read `credential` after narrowing, and
`failureAdvice` documents that a `quota` failure's `resetsAt` says when.
tests/failed-turn.test.ts pins the shape with `@ts-expect-error`: all
five lines compile against a flat type, so each one is load-bearing.

BREAKING CHANGE: code that reads `outcome.credential` (or `resetsAt`)
on a failed turn must check `outcome.failure` first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@TennyZhuang
TennyZhuang force-pushed the feat/limit-resets-at branch from 5468435 to faa5323 Compare October 9, 2026 20:47
@xxchan
xxchan merged commit 17410ff into main Oct 9, 2026
33 of 34 checks passed
@xxchan
xxchan deleted the feat/limit-resets-at branch October 9, 2026 21:10
@xxchan xxchan mentioned this pull request Oct 9, 2026
xxchan added a commit that referenced this pull request Oct 9, 2026
Release OAR and CLI 0.50.0. This PR changes only the two package version
fields.

**Breaking: a failed turn is a union tagged by `failure`** (#280)
- `TurnOutcome` `failed` is now `FailedTurn`, exported: `credential`
exists only on `failure: "auth"`, `resetsAt` only on `failure: "quota"`,
`status` on every class. A host that reads `outcome.credential` must
check `failure === "auth"` first, or it no longer compiles.

**Added**
- **`resetsAt` on a quota failure** (#280): when the limit that refused
the turn resets, where the runtime reports it. Only claude does: a
`rate_limit` failure while claude's latest `rate_limit_event` says a
subscription limit is `rejected`, overage does not take the requests,
and a reset is named. It is the runtime's last report; a time already
past means unknown. Codex's reset time exists only in its prose and is
not parsed.
- **Claude token totals include subagents and compaction** (#282, #292):
`usage().total` is claude's own running total (`result.modelUsage`),
which counts the main loop, Task subagents, sidechains and compaction.
Before, it was the main loop only (`result.usage`).
- **`SessionUsage.unattributed`**: what the total includes that no
`byAgent` entry accounts for (claude's subagents and compaction, which
its stream does not attribute per agent). `byAgent` plus `unattributed`
sums to `total`.
- **`SessionUsage.withChildren`**: the total plus the total of every
session derived from this one in `graph()` (codex child threads, grok
child sessions, OpenCode v2 children), each counted once.
- **Open errors keep their native cause** (#284): a failed codex, ACP or
claude open carries `cause: { method, native }` (redacted), so a host
can diagnose a failure even when no Session was returned.

**Fixed**
- **Known session credentials are redacted from every record and error**
(#286), not only from error text: session env and MCP env values chosen
by name, MCP credential headers, password-bearing connection URLs, and
pi's resolved model key. Original runtime input is unchanged. Limit: a
key the model repeats back across several streamed text deltas is not
caught, so SessionView text and coalesced events can still show it.
- **ACP error `data` is redacted** (#284); it used to bypass MCP
credential redaction.
- **Claude resume of a missing session fails at open** (#285, #287) with
claude's own text ("No conversation found with session ID: …") and
`cause: { method: "initialize", native }`, instead of returning a
Session that exits before its first prompt. A normal resume now waits
for claude's `initialize` answer (about 1 s observed).
- **Claude's `initialize` answer is no longer recorded** (#287): it
carries the account's email, organization and subscription. This
affected every open with `serviceTier` since that option shipped.
- **pi provider auth and model catalog use the agent dir sessions use**
(#289, #290): with `OAR_PI_AGENT_DIR` set, `createPiProviderAuth()` and
`createPiModelCatalog()` read and write that dir's `auth.json` and
`models.json` instead of pi's own. An empty `OAR_PI_AGENT_DIR` now
counts as unset everywhere, instead of becoming a relative path.

**Behavior changes**
- Narrow on `failure` before reading `credential` or `resetsAt` (see
above).
- Some claude rate-limit failures are now `quota` (with `resetsAt`)
instead of `rate_limited`; `failureAdvice` says `retry: "later"` for
them.
- Claude totals grow: they now include subagent and compaction tokens. A
resumed claude Session asks `get_usage` once at open for its baseline
(consumed privately, never recorded); if that answer does not come,
`usage().total` stays null for the Session rather than reporting the
lifetime figure.
- After a claude open with `serviceTier`, `serviceTier()` is null until
the first turn reports it; no `service_tier` event is emitted at open.
- Redaction now applies to every record, so a host comparing raw records
with what it sent may see `[redacted]` where a known credential
appeared.

**Known issues**
- `createPiModelCatalog().providers()[].configured` is false for a
stored credential until `refresh()` (#291). Use
`createPiProviderAuth().status(id)`.
- A Windows CI flake in the credential-redaction vendor test (#288);
tests only.

Validation: every PR passed all 17 checks on its final head. #284, #286,
#287, #280 and #290 merged with trees equal to their CI trees. #292 was
checked on its base, so its combination with #290 (disjoint files) was
verified locally (typecheck, lint, full tests: 1446 passed), and the
merged tree equals that verified tree. Lookout verified #286, #287, #290
and #292 against real binaries. After this PR passes CI and merges, tag
its exact squash commit as `v0.50.0` to trigger npm trusted publishing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: exe.dev user <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
xxchan added a commit that referenced this pull request Oct 9, 2026
Closes #288.

`sea-trial/vendor/credential-redaction.vendor.test.ts` failed on
`behavior (windows-latest, claude-aimock)` with `EBUSY: resource busy or
locked, rmdir …\oar-claude-credential-test-…` during CI for #280 and
again for #295. The claude case points `CLAUDE_CONFIG_DIR` into the
test's temp dir. On Windows, claude's files can still be held for a
moment after `dispose()`.

The three `rm` calls in the file now retry (`maxRetries: 10, retryDelay:
300`), as `mcp-servers.vendor.test.ts` and the aimock harness already do
for a runtime's config dir. Test-only; no release.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: exe.dev user <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants