Skip to content

fix(claude): confirm resume readiness before opening - #287

Merged
xxchan merged 2 commits into
mainfrom
fix/claude-resume-initialize
Oct 9, 2026
Merged

xxchan merged 2 commits into
mainfrom
fix/claude-resume-initialize

Conversation

@xxchan

@xxchan xxchan commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

Resuming a missing Claude session previously returned a Session that immediately exited, leaving the host to discover the failure on its first prompt. Resumes now wait for the native initialize response within the existing 30-second readback bound. A native result/error_during_execution, control refusal, exit, or deadline rejects the opening call and releases the process. Native failures retain the redacted error text and cause: { method: "initialize", native }.

Requested service tier uses the same initialization response; effort readback follows it. Fresh opens without settings readback keep the existing immediate path. Initialization and settings readbacks are private: their replies never enter records, including duplicate replies after opening, and successful answers are never attached to errors. This also fixes the existing service-tier opening path exposing account email, organization, subscription, process ID and home-directory information.

Consumer impact: opening still confirms the requested service tier, but no longer emits a service_tier event from the private initialization answer. Claude's Session.serviceTier() is null until a native system/init or result reports it during a turn. The runtime page and record-stream specification document this behavior and distinguish initialization readiness from restored-history continuity.

Validation:

  • Recorded-frame regressions cover early failure, a matching initialization response, unrelated responses, native refusal, exit, deadline, combined settings, and the fresh-open path. An initialization fixture based on Claude 2.1.295, with synthetic account details, verifies that resume, service-tier opens, replay and opening errors never expose those fields.
  • Real Claude 2.1.295 with a local scripted provider: missing-ID resume fails before any model request; valid resume initializes and can run another turn. The full Claude vendor suite and behavior suite pass. No real account was used.
  • Full CI=1 pnpm run check and package builds pass on the code combined with the credential-redaction change in fix: redact known session credentials from records and errors #286.

Closes #285.

@xxchan
xxchan merged commit c21dfe6 into main Oct 9, 2026
17 checks passed
@xxchan
xxchan deleted the fix/claude-resume-initialize branch October 9, 2026 18:17
xxchan pushed a commit that referenced this pull request Oct 9, 2026
…sAt) (#280)

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:

```ts
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` (#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](docs/spec/runtime-matrix.md#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](https://claude.com/claude-code)

---------

Co-authored-by: Ferryman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@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]>
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.

claude: resuming a missing session opens anyway and fails on the first prompt

2 participants