Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
wip(recovery): Tier-1 retry ladder, tests not yet updated
Jack Rudenko9bd7af738d23
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.tsindex 6c7f1300..dba1a128 100644--- a/packages/cli/src/config.ts+++ b/packages/cli/src/config.ts@@ -61,6 +61,17 @@ export const ENV = {// Classifier passthrough (auto-mode permission classifier → native Anthropic)CLAUDISH_CLASSIFIER_PROVIDER: "CLAUDISH_CLASSIFIER_PROVIDER", // "anthropic" enables classifier passthroughCLAUDISH_CLASSIFIER_MODEL: "CLAUDISH_CLASSIFIER_MODEL", // native Claude model to rewrite the classifier onto (also enables)+ // Connection-recovery switches. CLAUDISH_RECOVERY turns the retry ladder+ // itself off (the CI / scripted `-p` escape: without it an unreachable+ // endpoint is held for the whole tier-1 deadline instead of failing at once).+ // CLAUDISH_RECOVERY_UI says whether claudish may own a surface on which the+ // reason is legible. Both accept 1/true and 0/false, like CLAUDISH_DEBUG.+ CLAUDISH_RECOVERY: "CLAUDISH_RECOVERY",+ CLAUDISH_RECOVERY_UI: "CLAUDISH_RECOVERY_UI",+ // Claude Code's own per-request client timeout. NOT claudish's variable — it+ // is READ, never written, because it is the hard ceiling any in-request hold+ // must land inside. See recovery/settings.ts's resolveTier1DeadlineMs.+ API_TIMEOUT_MS: "API_TIMEOUT_MS",} as const;// OpenRouter API Configurationdiff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.tsindex ee4f3f23..4b3fb181 100644--- a/packages/cli/src/handlers/composed-handler.ts+++ b/packages/cli/src/handlers/composed-handler.ts@@ -38,6 +38,8 @@ import { GeminiThoughtSignatureMiddleware, MiddlewareManager } from "../middlewaimport { deepMergeParams } from "../model-params.js";import { describeSiblingKeys, getProviderByName } from "../providers/provider-definitions.js";import { isTerminal429 } from "../providers/transport/openai.js";+import { recoveryClock } from "../recovery/clock.js";+import { resolveRecoveryEnabled } from "../recovery/settings.js";import {type OpenAIImageBlock,type VisionProxyAuthHeaders,@@ -75,6 +77,14 @@ import { createOllamaJsonlStream } from "./shared/stream-parsers/ollama-jsonl.jsimport { createResponsesStreamHandler } from "./shared/stream-parsers/openai-responses-sse.js";import { createStreamingResponseHandler } from "./shared/stream-parsers/openai-sse.js";import { TokenTracker, type UsageCacheDetail } from "./shared/token-tracker.js";+import {+ type ConnectionErrorInfo,+ MIN_ATTEMPT_SLOT_MS,+ mergeSignalIntoInit,+ refreshDeadlineAt,+ tier1DeadlineAt,+ withConnectionRetry,+} from "./shared/transient-retry.js";import { captureUpstreamError } from "./shared/upstream-error-capture.js";/**@@ -410,6 +420,184 @@ export class ComposedHandler implements ModelHandler {return c.json(wrapAnthropicError(400, msg, "connection_error"), 400 as any);}+ /**+ * The inbound client's abort signal, or one that never fires.+ *+ * It fires sub-millisecond when Claude Code goes away — measured at+ * 0.49–0.86 ms across twelve trials, in the HELD shape (handler awaiting, no+ * headers sent) as well as the streaming one. Nothing in this codebase read+ * it before recovery existed, which is also why a fallback matters: a caller+ * that builds a Context without a real `Request` must get a signal that never+ * aborts rather than a crash.+ */+ private clientSignal(c: Context): AbortSignal {+ try {+ const signal = c.req?.raw?.signal;+ if (signal) return signal;+ } catch {+ // A synthesised Context. Fall through.+ }+ return new AbortController().signal;+ }++ /**+ * Should the retry ladder be skipped entirely, answering today's immediate+ * 400? Returns the REASON, or null to proceed.+ *+ * THREE GATES, AND DELIBERATELY NO FOURTH. Each is a fact available at this+ * instant — a request header, configuration, and the clock.+ *+ * There is NO special case for a refused loopback address, and that absence+ * is a decision rather than an omission. An earlier design skipped the ladder+ * for `refused` + loopback when the recovery UI was off, on the reasoning+ * that a stopped local server will not start itself. It was cut for two+ * reasons. The narrow one: the predicate was a regression generator — every+ * revision of it either fired universally (skipping recovery everywhere) or+ * fired never, and both times the defect was invisible because the SAME rule+ * decided the tests. The broad one, which is the real one: this is not a+ * feature for Ollama. It is the general answer to "claudish could not reach+ * the host", and a general rule that carves out one address family stops+ * being general. A user who restarts their server mid-ladder gets their turn+ * back, exactly as a user whose VPN reconnects does.+ */+ private shouldSkipTier1(c: Context, deadlineAt: number): string | null {+ // Probes MUST fail fast. Every probe POSTs through this handler, so+ // without this gate `--probe` and the config TUI's Test All would each+ // hold an unreachable link open for the full deadline and then misreport+ // it as a timeout — breaking the two tools that diagnose this exact fault.+ if (c.req.header("x-claudish-no-recovery") === "1") return "probe";+ // The CI / scripted-`-p` master switch. Off restores today's behaviour+ // everywhere, byte for byte.+ if (!resolveRecoveryEnabled()) return "recovery-disabled";+ // Attempt 1 already spent the budget. A guard, not a hope.+ if (recoveryClock().now() + MIN_ATTEMPT_SLOT_MS > deadlineAt) return "no-budget";+ return null;+ }++ /**+ * Run tier-1 recovery for one classified connection failure.+ *+ * Callers reach this from inside their own `catch`, never before, and only+ * after `classifyConnectionError` returned non-null. `value` means the+ * operation eventually succeeded and the caller carries on with it;+ * `respond` means the caller returns that Response immediately. An+ * unclassifiable failure on a LATER attempt is rethrown from here, exactly as+ * an unclassifiable first failure is rethrown by the caller.+ */+ private async recoverConnection<T>(+ c: Context,+ first: unknown,+ conn: ConnectionErrorInfo,+ endpoint: string,+ op: (signal: AbortSignal) => Promise<T>,+ ctx: {+ startTime: number;+ deadlineAt: number;+ fallbackMeta?: { chain: string[]; attempts: number };+ retryAttempted?: boolean;+ authType?: "api-key" | "oauth" | "none";+ site: string;+ }+ ): Promise<{ kind: "value"; value: T } | { kind: "respond"; response: Response }> {+ const skip = this.shouldSkipTier1(c, ctx.deadlineAt);+ if (skip) {+ log(+ `[Recovery] skipped (${skip}) — ${this.provider.displayName} at ${endpoint}, site=${ctx.site}`+ );+ return {+ kind: "respond",+ response: this.respondConnectionError(c, first, conn, endpoint, ctx),+ };+ }++ // Lift Bun's per-request idle timeout so the hold is bounded by OUR+ // deadline rather than by the server's. `c.env` IS the Bun `Server` and+ // `c.env.timeout` is a real two-arity function — measured: a request given+ // `0` survived SIX times its `idleTimeout` where the un-disarmed control+ // died at 1.6×. Called HERE, inside the catch, and never on a healthy+ // request.+ try {+ (c.env as { timeout?: (req: Request, seconds: number) => void } | undefined)?.timeout?.(+ c.req.raw,+ 0+ );+ } catch {+ // An older Bun, or a synthesised Context. The deadline still holds; only+ // the server's own ceiling might cut it short, and that is today's+ // behaviour rather than a regression.+ }++ const result = await withConnectionRetry(op, first, {+ providerName: this.provider.name,+ providerDisplayName: this.provider.displayName,+ resolveEndpoint: (err) => this.connectionEndpointFor(err, endpoint),+ deadlineAt: ctx.deadlineAt,+ signal: this.clientSignal(c),+ });++ switch (result.kind) {+ case "ok":+ return { kind: "value", value: result.value };+ case "threw":+ // Classification runs on every attempt. Something that is not a+ // connection failure must keep its own route out of here.+ throw result.error;+ case "client_gone":+ this.recordClientGone(ctx.startTime, ctx.fallbackMeta, result.episodeId, result.attempts);+ // Nobody reads this. It exists so Hono has an object to return for a+ // socket that is already gone.+ return { kind: "respond", response: new Response(null, { status: 499 }) };+ default: {+ log(+ `[Recovery] ${this.provider.displayName} exhausted after ${result.attempts} attempts ` ++ `in ${result.recoveryMs}ms (episode ${result.episodeId}, outcome ${result.kind}) — ` ++ "answering connection_error"+ );+ return {+ kind: "respond",+ response: this.respondConnectionError(c, result.error, result.conn, result.endpoint, {+ ...ctx,+ retryAttempted: true,+ }),+ };+ }+ }+ }++ /** Stats for a request whose client went away mid-recovery. */+ private recordClientGone(+ startTime: number,+ fallbackMeta: { chain: string[]; attempts: number } | undefined,+ episodeId: string,+ attempts: number+ ): void {+ log(+ `[Recovery] client disconnected after ${attempts} attempts (episode ${episodeId}) — ` ++ "releasing the request"+ );+ try {+ recordStats({+ model_id: this.targetModel,+ provider_name: this.provider.name,+ stream_format: this.provider.streamFormat,+ latency_ms: Math.round(performance.now() - startTime),+ success: false,+ http_status: 0,+ error_class: "network",+ error_code: "client_disconnected",+ token_strategy: this.options.tokenStrategy ?? "standard",+ adapter_name: this.getActiveAdapterName(),+ middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),+ fallback_used: fallbackMeta !== undefined,+ fallback_chain: fallbackMeta?.chain,+ fallback_attempts: fallbackMeta?.attempts,+ invocation_mode: this.options.invocationMode ?? "auto-route",+ });+ } catch {+ // Stats must never crash claudish+ }+ }+async handle(c: Context, payload: any): Promise<Response> {const startTime = performance.now();// latency_ms = time-to-first-byte (from request send to successful response).@@ -645,10 +833,6 @@ export class ComposedHandler implements ModelHandler {if (this.provider.refreshAuth) {try {await this.provider.refreshAuth();- // Update display name in case auth resolved it (e.g., Gemini tier detection)- if (this.provider.displayName) {- this.tokenTracker.setProviderDisplayName(this.provider.displayName);- }// Quota is DELIBERATELY not fetched here.//// This used to await getQuotaRemaining with a 2s cap on every single@@ -670,44 +854,71 @@ export class ComposedHandler implements ModelHandler {// user across every provider in the chain — off a subscription onto// metered billing — for an outage on their own machine.//- // No retry ladder here yet: this phase only stops the misclassification.const conn = classifyConnectionError(err);if (conn) {- return this.respondConnectionError(c, err, conn, this.connectionEndpointFor(err), {- startTime,- fallbackMeta,+ // The refresh path's deadline is DELIBERATELY earlier than the fetch+ // path's. Both live in the same request and share one budget; if a+ // refresh recovers at the very end of it and then succeeds, the flow+ // proceeds to the primary fetch — byte-identical to today's+ // expression and therefore unclamped — and a maximal connect hang+ // would land the response write a whole connect timeout past the+ // deadline.+ const outcome = await this.recoverConnection(+ c,+ err,+ conn,+ this.connectionEndpointFor(err),+ () => this.provider.refreshAuth!(),+ {+ startTime,+ deadlineAt: refreshDeadlineAt(tier1DeadlineAt(c)),+ fallbackMeta,+ authType: "oauth",+ site: "refreshAuth",+ }+ );+ if (outcome.kind === "respond") return outcome.response;+ // Recovered: fall through as if the first refresh had succeeded.+ } else {+ log(`[${this.provider.displayName}] Auth/health check failed: ${err.message}`);+ logStderr(+ `Error [${this.provider.displayName}]: Auth/health check failed — ${err.message}. Check credentials and server.`+ );+ reportError({+ error: err,+ providerName: this.provider.name,+ providerDisplayName: this.provider.displayName,+ streamFormat: this.provider.streamFormat,+ modelId: this.targetModel,+ httpStatus: 401,+ isStreaming: false,+ retryAttempted: false,+ isInteractive: this.isInteractive,authType: "oauth",- site: "refreshAuth",});+ // A terminal setup failure (misconfiguration, revoked entitlement) can+ // never succeed on retry. Answering 401 sent the client into ~11 retries+ // over two minutes of backoff, with the actionable message hidden behind+ // "API error · Retrying". 400 is not retryable, so the explanation lands+ // inline on the first attempt.+ if (err?.terminal) {+ return c.json(+ wrapAnthropicError(400, err.message, "invalid_request_error"),+ 400 as any+ );+ }+ // Return 401 (auth failure) so FallbackHandler treats this as retryable and+ // moves to the next provider in the chain. 503 (connection error) would stop+ // the fallback chain since it is not retryable by design.+ return c.json(wrapAnthropicError(401, err.message, "authentication_error"), 401 as any);}- log(`[${this.provider.displayName}] Auth/health check failed: ${err.message}`);- logStderr(- `Error [${this.provider.displayName}]: Auth/health check failed — ${err.message}. Check credentials and server.`- );- reportError({- error: err,- providerName: this.provider.name,- providerDisplayName: this.provider.displayName,- streamFormat: this.provider.streamFormat,- modelId: this.targetModel,- httpStatus: 401,- isStreaming: false,- retryAttempted: false,- isInteractive: this.isInteractive,- authType: "oauth",- });- // A terminal setup failure (misconfiguration, revoked entitlement) can- // never succeed on retry. Answering 401 sent the client into ~11 retries- // over two minutes of backoff, with the actionable message hidden behind- // "API error · Retrying". 400 is not retryable, so the explanation lands- // inline on the first attempt.- if (err?.terminal) {- return c.json(wrapAnthropicError(400, err.message, "invalid_request_error"), 400 as any);- }- // Return 401 (auth failure) so FallbackHandler treats this as retryable and- // moves to the next provider in the chain. 503 (connection error) would stop- // the fallback chain since it is not retryable by design.- return c.json(wrapAnthropicError(401, err.message, "authentication_error"), 401 as any);+ }+ // Update display name in case auth resolved it (e.g., Gemini tier+ // detection). Moved out of the `try` so it runs after a RECOVERED+ // refresh too — a refresh that only succeeded on attempt four resolved+ // the same names as one that succeeded on attempt one.+ if (this.provider.displayName) {+ this.tokenTracker.setProviderDisplayName(this.provider.displayName);}}// Update context window if provider dynamically discovered it@@ -755,17 +966,28 @@ export class ComposedHandler implements ModelHandler {headers = await this.provider.getHeaders(payload);} catch (err: any) {const conn = classifyConnectionError(err);- if (conn) {- return this.respondConnectionError(- c,- err,- conn,- this.connectionEndpointFor(err, endpoint),- { startTime, fallbackMeta, authType: "oauth", site: "getHeaders" }- );+ if (!conn) {+ // Anything else keeps its existing route out of here untouched.+ throw err;}- // Anything else keeps its existing route out of here untouched.- throw err;+ const outcome = await this.recoverConnection<Record<string, string>>(+ c,+ err,+ conn,+ this.connectionEndpointFor(err, endpoint),+ () => this.provider.getHeaders(),+ {+ startTime,+ // An auth site with the unclamped primary fetch still ahead of it —+ // same reservation as the refreshAuth catch, same reason.+ deadlineAt: refreshDeadlineAt(tier1DeadlineAt(c)),+ fallbackMeta,+ authType: "oauth",+ site: "getHeaders",+ }+ );+ if (outcome.kind === "respond") return outcome.response;+ headers = outcome.value;}// 6a. The body is NOT necessarily JSON. A transport may serialize the@@ -802,16 +1024,49 @@ export class ComposedHandler implements ModelHandler {// host — check your network/DNS" instead of a mystifying 500. (A Tailscale// MagicDNS outage making chatgpt.com unresolvable is what motivated this.)const conn = classifyConnectionError(error);- if (conn) {- // Status 400, NOT 503, and every field below is shared with the four- // other sites that can fail this way — see respondConnectionError.- return this.respondConnectionError(c, error, conn, endpoint, {- startTime,- fallbackMeta,- site: "fetch",- });- }- throw error;+ if (!conn) throw error;++ // Every construct below is built HERE, inside the catch, after+ // classification returned non-null. A successful request never executes+ // one line of it, and the expression above is byte-identical to what it+ // was before recovery existed — including its `enqueueRequest` ternary.+ //+ // The re-issue must go through that SAME ternary. Six transports+ // implement `enqueueRequest`, and what they implement is not decoration:+ // a bounded 429 loop with `Retry-After`, a served-set model-fallback+ // chain, and the local concurrency gate that stops `[email protected]:3`+ // running four inferences at once. Skipping it would make the attempt+ // that finally CONNECTS behave differently from the one that failed —+ // and at the moment a network returns, N woken waiters would stampede+ // unqueued into a provider that has just come back.+ const doFetchWith = (sig: AbortSignal) =>+ fetch(+ endpoint,+ mergeSignalIntoInit(+ {+ method: "POST",+ headers,+ body: serialized?.body ?? JSON.stringify(requestPayload),+ ...requestInit,+ },+ sig+ )+ );+ const reissue = (sig: AbortSignal) => {+ const attempt = () => doFetchWith(sig);+ return this.provider.enqueueRequest+ ? this.provider.enqueueRequest(attempt, { signal: sig })+ : attempt();+ };++ const outcome = await this.recoverConnection<Response>(c, error, conn, endpoint, reissue, {+ startTime,+ deadlineAt: tier1DeadlineAt(c),+ fallbackMeta,+ site: "fetch",+ });+ if (outcome.kind === "respond") return outcome.response;+ response = outcome.value;}// Check if the transport fell back to a different model (e.g., capacity exhaustion)@@ -892,28 +1147,46 @@ export class ComposedHandler implements ModelHandler {// for a provider that accepts it while the machine is offline. An// UNCLASSIFIED throw is rethrown unchanged, so the existing 500 route// out of here is untouched.- let retryResp: Response;- try {+ const doParamRetry = async (sig?: AbortSignal): Promise<Response> => {const retryHeaders = await this.provider.getHeaders(payload);retryHeaders["Content-Type"] = retrySerialized?.contentType ?? "application/json";- retryResp = await fetch(endpoint, {- method: "POST",- headers: retryHeaders,- body: retrySerialized?.body ?? JSON.stringify(requestPayload),- ...(this.provider.getRequestInit?.() || {}),- });+ return fetch(+ endpoint,+ mergeSignalIntoInit(+ {+ method: "POST",+ headers: retryHeaders,+ body: retrySerialized?.body ?? JSON.stringify(requestPayload),+ ...(this.provider.getRequestInit?.() || {}),+ },+ sig+ )+ );+ };+ let retryResp: Response;+ try {+ retryResp = await doParamRetry();} catch (err: any) {const conn = classifyConnectionError(err);- if (conn) {- return this.respondConnectionError(- c,- err,- conn,- this.connectionEndpointFor(err, endpoint),- { startTime, fallbackMeta, retryAttempted: true, site: "parameter-recovery" }- );- }- throw err;+ if (!conn) throw err;+ const outcome = await this.recoverConnection<Response>(+ c,+ err,+ conn,+ this.connectionEndpointFor(err, endpoint),+ doParamRetry,+ {+ startTime,+ // The full budget: this site runs AFTER the primary fetch, so+ // there is no unclamped attempt left ahead of it to reserve for.+ deadlineAt: tier1DeadlineAt(c),+ fallbackMeta,+ retryAttempted: true,+ site: "parameter-recovery",+ }+ );+ if (outcome.kind === "respond") return outcome.response;+ retryResp = outcome.value;}if (retryResp.ok) {response = retryResp;@@ -934,20 +1207,33 @@ export class ComposedHandler implements ModelHandler {// 401: retry with forced auth refresh (OAuth token expiry)if (response.status === 401 && this.provider.forceRefreshAuth) {log(`[${this.provider.displayName}] Got 401, forcing auth refresh and retrying`);- try {- await this.provider.forceRefreshAuth();+ // The forced refresh AND the retry fetch that follows it, as one+ // re-issuable operation. Both are network calls and either can fail+ // transiently, so a ladder that could only re-run one of them would+ // leave the other exactly as exposed as it was.+ const doAuthRetry = async (sig?: AbortSignal): Promise<Response> => {+ await this.provider.forceRefreshAuth!();const retryHeaders = await this.provider.getHeaders(payload);// Same serialization as the primary request — this is a separate call// site and the easy one to forget, which is why both are pinned by// the same assertion.retryHeaders["Content-Type"] = serialized?.contentType ?? "application/json";const retryInit = this.provider.getRequestInit?.() || {};- const retryResp = await fetch(endpoint, {- method: "POST",- headers: retryHeaders,- body: serialized?.body ?? JSON.stringify(requestPayload),- ...retryInit,- });+ return fetch(+ endpoint,+ mergeSignalIntoInit(+ {+ method: "POST",+ headers: retryHeaders,+ body: serialized?.body ?? JSON.stringify(requestPayload),+ ...retryInit,+ },+ sig+ )+ );+ };+ /** Returns a Response to answer with, or null to carry on streaming. */+ const settleAuthRetry = async (retryResp: Response): Promise<Response | null> => {if (retryResp.ok) {response = retryResp; // fall through to stream handling below} else {@@ -996,9 +1282,14 @@ export class ComposedHandler implements ModelHandler {}return c.json(wrapAnthropicError(retryResp.status, errorText), retryResp.status as any);}+ return null;+ };+ try {+ const answered = await settleAuthRetry(await doAuthRetry());+ if (answered) return answered;} catch (err: any) {// CLASSIFY FIRST, exactly as in the refreshAuth catch above, and for a- // sharper reason: this `try` wraps BOTH `forceRefreshAuth()` AND the+ // sharper reason: this path covers BOTH `forceRefreshAuth()` AND the// raw retry `fetch` that follows it, so "the network dropped while we// were re-signing a request" arrives here and left as an unconditional// `authentication_error` 401. `isRetryableError` reads 401 as@@ -1008,59 +1299,67 @@ export class ComposedHandler implements ModelHandler {// this whole area exists to prevent.const conn = classifyConnectionError(err);if (conn) {- return this.respondConnectionError(+ const outcome = await this.recoverConnection<Response>(c,err,conn,this.connectionEndpointFor(err, endpoint),+ doAuthRetry,{startTime,+ deadlineAt: tier1DeadlineAt(c),fallbackMeta,retryAttempted: true,authType: "oauth",site: "forceRefreshAuth",});- }- log(`[${this.provider.displayName}] Auth refresh failed: ${err.message}`);- logStderr(- `Error [${this.provider.displayName}]: Authentication failed — ${err.message}. Check API key.`- );- reportError({- error: err,- providerName: this.provider.name,- providerDisplayName: this.provider.displayName,- streamFormat: this.provider.streamFormat,- modelId: this.targetModel,- httpStatus: 401,- isStreaming: false,- retryAttempted: true,- isInteractive: this.isInteractive,- authType: "oauth",- });- try {- const { error_class, error_code } = classifyError(err, 401, err.message);- recordStats({- model_id: this.targetModel,- provider_name: this.provider.name,- stream_format: this.provider.streamFormat,- latency_ms: Math.round(performance.now() - startTime),- success: false,- http_status: 401,- error_class,- error_code,- token_strategy: this.options.tokenStrategy ?? "standard",- adapter_name: this.getActiveAdapterName(),- middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),- fallback_used: fallbackMeta !== undefined,- fallback_chain: fallbackMeta?.chain,- fallback_attempts: fallbackMeta?.attempts,- invocation_mode: this.options.invocationMode ?? "auto-route",+ if (outcome.kind === "respond") return outcome.response;+ const answered = await settleAuthRetry(outcome.value);+ if (answered) return answered;+ // Recovered and streaming: `response` was reassigned by+ // settleAuthRetry. Fall through to the shared stream handling.+ } else {+ log(`[${this.provider.displayName}] Auth refresh failed: ${err.message}`);+ logStderr(+ `Error [${this.provider.displayName}]: Authentication failed — ${err.message}. Check API key.`+ );+ reportError({+ error: err,+ providerName: this.provider.name,+ providerDisplayName: this.provider.displayName,+ streamFormat: this.provider.streamFormat,+ modelId: this.targetModel,+ httpStatus: 401,+ isStreaming: false,+ retryAttempted: true,+ isInteractive: this.isInteractive,+ authType: "oauth",});- } catch {- // Stats must never crash claudish+ try {+ const { error_class, error_code } = classifyError(err, 401, err.message);+ recordStats({+ model_id: this.targetModel,+ provider_name: this.provider.name,+ stream_format: this.provider.streamFormat,+ latency_ms: Math.round(performance.now() - startTime),+ success: false,+ http_status: 401,+ error_class,+ error_code,+ token_strategy: this.options.tokenStrategy ?? "standard",+ adapter_name: this.getActiveAdapterName(),+ middleware_names: this.middlewareManager.getActiveNames(this.bareModelName),+ fallback_used: fallbackMeta !== undefined,+ fallback_chain: fallbackMeta?.chain,+ fallback_attempts: fallbackMeta?.attempts,+ invocation_mode: this.options.invocationMode ?? "auto-route",+ });+ } catch {+ // Stats must never crash claudish+ }+ return c.json(wrapAnthropicError(401, err.message, "authentication_error"), 401 as any);}- return c.json(wrapAnthropicError(401, err.message, "authentication_error"), 401 as any);}} else {const errorText = await response.text();diff --git a/packages/cli/src/handlers/shared/connection-error.ts b/packages/cli/src/handlers/shared/connection-error.tsindex a6121819..f20408db 100644--- a/packages/cli/src/handlers/shared/connection-error.ts+++ b/packages/cli/src/handlers/shared/connection-error.ts@@ -47,6 +47,32 @@ const CODE_KIND: Record<string, ConnectionErrorKind> = {*/const BUN_CONNECT_MESSAGE = /unable to connect\. is the computer able to access the url\?/i;+/**+ * Error NAMES that mean the same thing as a connect code, matched separately+ * because they do not arrive as one.+ *+ * `AbortSignal.timeout(...)` rejects with a `DOMException` whose `name` is+ * `TimeoutError` and whose `code` is the NUMBER 23 — so `findConnectionCode`'s+ * `typeof e.code === "string"` test skipped it, its message ("The operation+ * timed out.") matched no fallback, and classification returned **null**. A+ * provider that accepts the TCP connection and then never answers therefore+ * fell straight through into a bare 500, with none of the actionable wording+ * every other unreachable-host failure gets.+ *+ * "Refused is covered, hung is not" was the whole of the gap. It bites hardest+ * on local providers, whose health probes carry an `AbortSignal.timeout` and+ * whose inference requests carry a ten-minute one — a wedged Ollama is exactly+ * the fault a retry ladder is for.+ *+ * ONLY `TimeoutError`. `AbortError` is deliberately absent and must stay+ * absent: it is how a client says it has gone away and how our own per-attempt+ * clamp's sibling signal reports a deliberate cancellation, and treating a+ * cancellation as a network fault would retry work nobody is waiting for.+ */+const NAME_KIND: Record<string, ConnectionErrorKind> = {+ TimeoutError: "unreachable",+};+/*** Walk an error and its `cause` chain (undici's `TypeError: fetch failed` wraps* the real syscall error in `.cause`) and return the first known connection@@ -59,6 +85,11 @@ function findConnectionCode(error: unknown): string | null {for (let depth = 0; e && typeof e === "object" && depth < 8 && !seen.has(e); depth++) {seen.add(e);if (typeof e.code === "string" && e.code in CODE_KIND) return e.code;+ // A DOMException carries a NUMERIC `code`, so the name is the only handle+ // on it. Walked at the same depth as `.code`, because a transport that+ // rethrows with `{ cause }` buries a hung-probe timeout just as deeply as+ // it buries a refusal.+ if (typeof e.name === "string" && e.name in NAME_KIND) return e.name;e = e.cause;}const msg = String((error as any)?.message ?? error ?? "");@@ -67,8 +98,16 @@ function findConnectionCode(error: unknown): string | null {return null;}-/** True when the endpoint points at this machine (loopback / unspecified). */-function isLoopback(endpoint: string): boolean {+/**+ * True when the endpoint points at this machine (loopback / unspecified).+ *+ * Exported because it is the ONLY sound discriminator for "this is a local+ * server the user can start" at handler level. Branching on the error CODE+ * instead does not work: on macOS an unrouted remote address reports+ * `ECONNREFUSED` after 75 s, the same code a loopback port refuses in 5 ms.+ * Only the endpoint — or elapsed time — separates them.+ */+export function isLoopback(endpoint: string): boolean {try {const { hostname } = new URL(endpoint);return /^(localhost|127\.\d+\.\d+\.\d+|0\.0\.0\.0|\[?::1\]?)$/i.test(hostname);@@ -87,7 +126,7 @@ export function classifyConnectionError(): { kind: ConnectionErrorKind; code: string } | null {const code = findConnectionCode(error);if (!code) return null;- return { kind: CODE_KIND[code] ?? "unreachable", code };+ return { kind: CODE_KIND[code] ?? NAME_KIND[code] ?? "unreachable", code };}function hostOf(endpoint: string): string {diff --git a/packages/cli/src/handlers/shared/local-queue.ts b/packages/cli/src/handlers/shared/local-queue.tsindex dd0d8d9c..3308d04a 100644--- a/packages/cli/src/handlers/shared/local-queue.ts+++ b/packages/cli/src/handlers/shared/local-queue.ts@@ -33,6 +33,29 @@ interface QueuedRequest {resolve: (response: Response) => void;reject: (error: Error) => void;providerId: string; // For debugging/stats (e.g., "ollama", "lmstudio")+ /**+ * Set when the caller can be cancelled while still QUEUED — a connection+ * retry bounded by a per-attempt clamp, or a client that went away.+ *+ * This is the only queue whose ACTIVE request may legally run for ten+ * minutes (local inference), so it is the only one where an admission wait+ * can outlive the caller's own budget. Without it an aborted attempt's entry+ * stayed in the queue and its `fetchFn` fired later, against a provider+ * nobody was waiting on.+ */+ signal?: AbortSignal;+ /** Detaches the abort listener. Always called, on every exit path. */+ detach?: () => void;+ /** True once the abort listener has rejected this entry. */+ abandoned?: boolean;+}++/** Normalise an abort reason into an Error the queue's `reject` accepts. */+function toAbortError(reason: unknown): Error {+ if (reason instanceof Error) return reason;+ const err = new Error("Request aborted while queued");+ err.name = "AbortError";+ return err;}/**@@ -126,8 +149,13 @@ export class LocalModelQueue {async enqueue(fetchFn: () => Promise<Response>,providerId: string,- concurrencyOverride?: number+ concurrencyOverride?: number,+ signal?: AbortSignal): Promise<Response> {+ // Already cancelled before we even got here: never occupy a slot for it.+ if (signal?.aborted) {+ throw toAbortError(signal.reason);+ }// Handle concurrency overrideif (concurrencyOverride !== undefined) {if (concurrencyOverride === 0) {@@ -169,8 +197,25 @@ export class LocalModelQueue {resolve,reject,providerId,+ signal,};+ if (signal) {+ const onAbort = () => {+ queuedRequest.abandoned = true;+ queuedRequest.detach?.();+ queuedRequest.detach = undefined;+ // Splice it OUT. Leaving it in and merely rejecting the promise+ // still lets processQueue invoke its fetchFn later, firing a request+ // whose caller is already gone.+ const i = this.queue.indexOf(queuedRequest);+ if (i !== -1) this.queue.splice(i, 1);+ reject(toAbortError(signal.reason));+ };+ queuedRequest.detach = () => signal.removeEventListener("abort", onAbort);+ signal.addEventListener("abort", onAbort, { once: true });+ }+this.queue.push(queuedRequest);if (getLogLevel() === "debug") {log(@@ -195,6 +240,14 @@ export class LocalModelQueue {const request = this.queue.shift();if (!request) break;+ // Aborted while it waited. The listener has already rejected the caller;+ // all that is left is to not run its fetchFn.+ if (request.abandoned || request.signal?.aborted) {+ request.detach?.();+ request.detach = undefined;+ continue;+ }+if (getLogLevel() === "debug") {log(`[LocalQueue] Processing request for ${request.providerId} (${this.queue.length} remaining in queue, ${this.activeRequests + 1}/${this.maxParallel} active)`@@ -218,6 +271,10 @@ export class LocalModelQueue {*/private async executeRequest(request: QueuedRequest): Promise<void> {this.activeRequests++;+ // Past admission, the caller's signal is the fetch's business, not the+ // queue's — the fetch was handed the same signal and will end itself.+ request.detach?.();+ request.detach = undefined;try {const response = await request.fetchFn();diff --git a/packages/cli/src/handlers/shared/transient-retry.ts b/packages/cli/src/handlers/shared/transient-retry.tsnew file mode 100644index 00000000..911f5244--- /dev/null+++ b/packages/cli/src/handlers/shared/transient-retry.ts@@ -0,0 +1,375 @@+/**+ * Tier 1 of connection recovery: re-issue a failed operation on a shared+ * episode clock, inside the request that failed, before a single byte has been+ * flushed.+ *+ * WHERE THIS LIVES AND WHY IT IS NOT A TRANSPORT WRAPPER. `enqueueRequest` and+ * `getRequestInit` are OPTIONAL on the transport interface, so a wrapper down+ * there would miss every transport implementing neither; only the handler can+ * choose the final status; and the byte-stable re-issue closure already exists+ * at the handler level, built once from the serialized body. The separating+ * rule is structural rather than stylistic: **the transports handle the+ * has-a-Response case (429 loops, model fallback); this file handles the+ * no-Response case.** They cannot overlap, because a connect failure never+ * produces a Response.+ *+ * The existing per-transport 429 loops deliberately do NOT converge here. Their+ * budgets are measured and provider-specific — one is sized at ~3 s so a config+ * TUI probe deadline is not blown, another drives a model-fallback chain off+ * observed refusal latencies — and merging them is the textbook wrong+ * abstraction.+ *+ * NOTHING IN THIS FILE RUNS ON A HEALTHY REQUEST. Every construct is built from+ * inside a `catch`, after classification has already returned non-null. That is+ * enforced by placement, not by a flag.+ */++import type { Context } from "hono";+import { log } from "../../logger.js";+import { recoveryClock } from "../../recovery/clock.js";+import { type EpisodeHandle, joinEpisode } from "../../recovery/coordinator.js";+import { logDeadlineIfShortened, resolveTier1DeadlineMs } from "../../recovery/settings.js";+import {+ type ConnectionErrorKind,+ buildConnectionErrorMessage,+ classifyConnectionError,+} from "./connection-error.js";++export { EPISODE_GRACE_MS } from "../../recovery/coordinator.js";++/**+ * Connection backoff. Deliberately SEPARATE from `STREAM_RETRY_DELAYS_MS`:+ * those three values are load-bearing for the stream sniffer's budget and for a+ * duration quoted verbatim in a user-facing exhaustion message, and merging the+ * two schedules would couple unrelated budgets to each other.+ *+ * The last element REPEATS — the schedule is 5/10/30/60/60/… and the DEADLINE,+ * not the array, is what ends it. That inverts `STREAM_RETRY_DELAYS_MS`, where+ * the array running out IS the budget.+ */+export const CONNECTION_RETRY_DELAYS_MS = [5_000, 10_000, 30_000, 60_000] as const;++/** The gap before the attempt at `ladderIndex`. Clamped to the last element. */+export function connectionRetryDelayMs(ladderIndex: number): number {+ const i = Math.max(0, Math.min(ladderIndex, CONNECTION_RETRY_DELAYS_MS.length - 1));+ return CONNECTION_RETRY_DELAYS_MS[i] as number;+}++/**+ * Ceiling on ONE retry attempt's connect-and-headers phase. Disarmed the+ * instant `fetch()` resolves, so it can never cut a live response body.+ *+ * NOT 75 000, and the 4 ms this avoids is the whole reason. macOS's own TCP+ * connect timeout was measured at **75.004 s** against an unrouted address, so+ * a 75 000 ms cap races the operating system by four milliseconds and is+ * decided differently on different runs — which makes every assertion keyed on+ * "the attempt ended at the clamp" flaky by construction. 45 s clears the+ * collision by 30 seconds, always wins the race, and keeps the ladder+ * responsive: at the default deadline it still leaves room for the full+ * 5/10/30/60/60 sequence, because a clamped attempt only costs its own wall+ * clock when the fault is slow, and a slow fault is exactly the case where+ * waiting out 75 s per attempt would spend the entire budget on two of them.+ */+export const PER_ATTEMPT_CONNECT_CAP_MS = 45_000;++/** Below this much budget remaining, do not start another attempt. */+export const MIN_ATTEMPT_SLOT_MS = 3_000;++/**+ * The deadline the AUTH-path catches use, deliberately earlier than the fetch+ * catch's.+ *+ * Both sit in the same request and share one `deadlineAt`. If auth recovery+ * consumes the whole of it and then SUCCEEDS, the flow proceeds to the primary+ * fetch — which is byte-identical to today's expression and therefore+ * unclamped — and a maximal connect hang lands the response write a full+ * connect timeout past the deadline. Reserving the unclamped attempt's own+ * worst case out of the auth path's budget restores the margin the derivation+ * assumed, and costs one function rather than an edit to the healthy path.+ */+export function refreshDeadlineAt(deadlineAt: number): number {+ return deadlineAt - PER_ATTEMPT_CONNECT_CAP_MS;+}++/**+ * PROCESS ms at which the INBOUND request arrived — not at which this candidate+ * started.+ *+ * `handle()` mints its own `startTime` and the fallback chain calls `handle()`+ * once PER CANDIDATE, so deriving the deadline from that value gave every+ * candidate in a chain a fresh full budget and the chain as a whole could hold+ * a socket for candidates × deadline. A `WeakMap` keyed on the inbound+ * `Request` needs no route change and no context mutation (the fallback+ * handler's invariant forbids `c.set` no less than `c.header`), collects+ * itself, and is inherited by every later candidate because they share+ * `c.req.raw`.+ *+ * The residual is real and wanted: a candidate that recovers late and then+ * returns a retryable status leaves candidate 2 with only the remaining budget+ * rather than a fresh one. That is the point.+ */+const INBOUND_START = new WeakMap<Request, number>();++export function inboundStartedAtPerf(c: Context): number {+ const key = c.req?.raw as Request | undefined;+ if (!key) return recoveryClock().now();+ const seen = INBOUND_START.get(key);+ if (seen !== undefined) return seen;+ const t = recoveryClock().now();+ INBOUND_START.set(key, t);+ return t;+}++/** The absolute tier-1 deadline for this inbound request, PROCESS ms. */+export function tier1DeadlineAt(c: Context): number {+ const budget = resolveTier1DeadlineMs();+ logDeadlineIfShortened(budget);+ return inboundStartedAtPerf(c) + budget;+}++export interface ConnectionErrorInfo {+ kind: ConnectionErrorKind;+ code: string;+}++/**+ * Add an abort signal to an already-built fetch init WITHOUT discarding the+ * transport's own.+ *+ * The order is the entire point. The handler's fetch expressions spread the+ * transport's `getRequestInit()` **last**, so a signal written before that+ * spread is silently overwritten — and for a local provider the thing doing the+ * overwriting is a ten-minute `AbortSignal.timeout`. Compose rather than+ * replace: the per-attempt clamp then bounds the attempt while the transport's+ * own ceiling still applies, which is what both of them were for.+ */+export function mergeSignalIntoInit(+ init: Record<string, unknown>,+ signal?: AbortSignal+): RequestInit {+ if (!signal) return init as RequestInit;+ const own = init.signal as AbortSignal | undefined;+ return { ...init, signal: own ? AbortSignal.any([own, signal]) : signal } as RequestInit;+}++export interface ConnectionRetryContext {+ providerName: string;+ providerDisplayName: string;+ /**+ * The endpoint the FAILING call was made to. On the inference path this is+ * the model endpoint; on an auth path the model endpoint may not be computed+ * yet and a refresh can contact several auth/setup/catalog hosts, so it is+ * read from the error. Naming the wrong host in the message is a real defect,+ * not a cosmetic one.+ */+ resolveEndpoint: (err: unknown) => string;+ /** Absolute deadline for THIS request, PROCESS ms. */+ deadlineAt: number;+ /** `c.req.raw.signal` — the client going away. */+ signal: AbortSignal;+}++export type ConnectionRetryResult<T> =+ | { kind: "ok"; value: T; attempts: number; recoveryMs: number; episodeId: string }+ /**+ * NOTE the absence of a `uiLeased` field. Whether a surface is painting this+ * episode is LIVE and must be read at the moment the status is chosen; a+ * boolean on this result IS a cache of it, and by the time a caller+ * destructures the result it can already be stale.+ */+ | {+ kind: "exhausted";+ conn: ConnectionErrorInfo;+ error: unknown;+ endpoint: string;+ attempts: number;+ recoveryMs: number;+ episodeId: string;+ }+ | {+ kind: "gave_up";+ conn: ConnectionErrorInfo;+ error: unknown;+ endpoint: string;+ attempts: number;+ recoveryMs: number;+ episodeId: string;+ }+ | { kind: "client_gone"; attempts: number; recoveryMs: number; episodeId: string }+ /** A later attempt threw something that is NOT a connection error. Not ours. */+ | { kind: "threw"; error: unknown; attempts: number; recoveryMs: number; episodeId: string };++/** True when the rejection is the inbound client going away, not our own clamp. */+function isClientAbort(signal: AbortSignal, err: unknown): boolean {+ if (signal.aborted) return true;+ return (err as { name?: string })?.name === "AbortError";+}++/**+ * Re-issue `op` on a classified connection error, on the shared episode clock.+ *+ * `op` TAKES the signal rather than closing over one. That is what lets a+ * single contract cover both the fetch path and the auth path: the per-attempt+ * clamp is built here, merged with the client signal here, and handed in, so+ * the clamp bounds the OPERATION rather than only the `fetch` buried inside it.+ *+ * Classification runs on EVERY attempt, not just the first. A retry that throws+ * an auth failure, a transport bug or a programming error must not be+ * relabelled as the previous network error — that would quietly widen recovery+ * past the classified set. Such a result comes back as `threw` and the caller+ * rethrows it exactly as it rethrows an unclassifiable first failure today.+ */+export async function withConnectionRetry<T>(+ op: (signal: AbortSignal) => Promise<T>,+ first: unknown,+ ctx: ConnectionRetryContext+): Promise<ConnectionRetryResult<T>> {+ const clock = recoveryClock();+ const firstConn = classifyConnectionError(first);+ if (!firstConn) {+ // The caller is contractually required to classify before calling. Being+ // defensive here costs nothing and keeps a future caller's mistake from+ // silently widening what "transient" means.+ return { kind: "threw", error: first, attempts: 0, recoveryMs: 0, episodeId: "" };+ }++ let conn: ConnectionErrorInfo = firstConn;+ let error: unknown = first;+ let endpoint = ctx.resolveEndpoint(first);++ const handle: EpisodeHandle = joinEpisode({+ providerName: ctx.providerName,+ providerDisplayName: ctx.providerDisplayName,+ endpoint,+ kind: conn.kind,+ code: conn.code,+ reason: buildConnectionErrorMessage(conn.kind, ctx.providerDisplayName, endpoint),+ deadlineAt: ctx.deadlineAt,+ });++ const finish = <R extends ConnectionRetryResult<T>>(r: R): R => r;++ try {+ handle.recordAttemptResult(conn.code, false);++ for (;;) {+ if (ctx.signal.aborted) {+ return finish({+ kind: "client_gone",+ attempts: handle.attempts(),+ recoveryMs: handle.recoveryMs(),+ episodeId: handle.episodeId,+ });+ }++ const delay = connectionRetryDelayMs(handle.ladderIndex());+ const now = clock.now();+ // The check bounds the ATTEMPT THAT FOLLOWS the sleep, not just the+ // sleep. Bounding only the sleep is how a budget stops being a ceiling.+ if (now + delay + MIN_ATTEMPT_SLOT_MS > ctx.deadlineAt) {+ handle.handoff();+ return finish({+ kind: "exhausted",+ conn,+ error,+ endpoint,+ attempts: handle.attempts(),+ recoveryMs: handle.recoveryMs(),+ episodeId: handle.episodeId,+ });+ }++ let waited: { kind: "attempt" } | { kind: "gave_up" };+ try {+ waited = await handle.waitForNextAttempt(ctx.signal, delay);+ } catch (err) {+ if (isClientAbort(ctx.signal, err)) {+ log(`[Recovery] client gone during wait (episode ${handle.episodeId})`);+ return finish({+ kind: "client_gone",+ attempts: handle.attempts(),+ recoveryMs: handle.recoveryMs(),+ episodeId: handle.episodeId,+ });+ }+ throw err;+ }++ if (waited.kind === "gave_up") {+ return finish({+ kind: "gave_up",+ conn,+ error,+ endpoint,+ attempts: handle.attempts(),+ recoveryMs: handle.recoveryMs(),+ episodeId: handle.episodeId,+ });+ }++ // Per-attempt clamp. Cleared the moment the operation settles, so it can+ // only ever bound connect-and-headers.+ const attemptAc = new AbortController();+ const remaining = ctx.deadlineAt - clock.now();+ const clampMs = Math.max(+ MIN_ATTEMPT_SLOT_MS,+ Math.min(PER_ATTEMPT_CONNECT_CAP_MS, remaining)+ );+ const clampTimer = clock.setTimeout(+ () => attemptAc.abort(new DOMException("attempt cap", "TimeoutError")),+ clampMs+ );+ const merged = AbortSignal.any([ctx.signal, attemptAc.signal]);++ try {+ const value = await op(merged);+ handle.recordAttemptResult("ok", true);+ log(+ `[Recovery] ${ctx.providerDisplayName} recovered after ${handle.attempts()} attempts ` ++ `in ${handle.recoveryMs()}ms (episode ${handle.episodeId})`+ );+ return finish({+ kind: "ok",+ value,+ attempts: handle.attempts(),+ recoveryMs: handle.recoveryMs(),+ episodeId: handle.episodeId,+ });+ } catch (err) {+ if (isClientAbort(ctx.signal, err)) {+ log(`[Recovery] client gone during attempt (episode ${handle.episodeId})`);+ return finish({+ kind: "client_gone",+ attempts: handle.attempts(),+ recoveryMs: handle.recoveryMs(),+ episodeId: handle.episodeId,+ });+ }+ // Re-classify EVERY attempt. Our own clamp lands here as a+ // `TimeoutError`, which classification now recognises for the same+ // reason a hung upstream does: both are a failure to get a response+ // out of a host we could not reach in time.+ const next = classifyConnectionError(err);+ if (!next) {+ return finish({+ kind: "threw",+ error: err,+ attempts: handle.attempts(),+ recoveryMs: handle.recoveryMs(),+ episodeId: handle.episodeId,+ });+ }+ conn = next;+ error = err;+ endpoint = ctx.resolveEndpoint(err) || endpoint;+ handle.recordAttemptResult(next.code, false);+ } finally {+ clock.clearTimeout(clampTimer);+ }+ }+ } finally {+ // Unconditional. A waiter that never leaves is the subscribe-without-+ // unsubscribe leak this design named as its own most likely failure.+ handle.leave();+ }+}diff --git a/packages/cli/src/logger.ts b/packages/cli/src/logger.tsindex 1e7c5dd7..df61b230 100644--- a/packages/cli/src/logger.ts+++ b/packages/cli/src/logger.ts@@ -157,6 +157,12 @@ function isStructuralLogWorthy(msg: string): boolean {// empty and whose failure the user most needs named.msg.startsWith("[Claude Code]") ||msg.startsWith("[Fallback]") ||+ // Connection-recovery episodes: which target, which attempt, how long the+ // next gap is, and how the episode ended. Without this entry the ladder's+ // only trace is behind `-d`, and the one thing a user reports about an+ // outage is that the session hung — a report nobody can check against a+ // log that was never written.+ msg.startsWith("[Recovery]") ||msg.startsWith("[Streaming] ===") || // HANDLER STARTEDmsg.startsWith("[Streaming] Chunk:") ||msg.startsWith("[Streaming] Received") ||diff --git a/packages/cli/src/profile-config.ts b/packages/cli/src/profile-config.tsindex 036c577a..cb8bcedc 100644--- a/packages/cli/src/profile-config.ts+++ b/packages/cli/src/profile-config.ts@@ -242,6 +242,37 @@ export interface ClaudishProfileConfig {* `readProOnUltracode()`, NOT this allowlist — see its doc comment.*/proOnUltracode?: boolean;++ /**+ * Master switch for connection RECOVERY itself — the retry ladder claudish+ * runs when it cannot even reach the provider. Default ON. Turning it off+ * restores the immediate `connection_error` 400 everywhere.+ *+ * It exists for CI and scripted `-p` runs, which would otherwise hold a dead+ * endpoint open for the whole tier-1 deadline instead of failing at once.+ * Precedence: --recovery/--no-recovery flag > CLAUDISH_RECOVERY env >+ * project `.claudish.json` > this field > true. The scoped read is+ * `readRecoveryEnabled()`, NOT this allowlist — see its doc comment.+ *+ * An OBJECT rather than a bare boolean so a later `deadlineMs` needs no+ * second allowlist entry, and because `{}` can then mean "no opinion" and+ * fall through to the next scope, which a boolean cannot express.+ */+ recovery?: { enabled?: boolean };++ /**+ * Whether claudish may own a terminal surface on which a recovery episode's+ * reason is legible. Default ON.+ *+ * In this phase it decides one thing only: a REFUSED connection to a+ * loopback endpoint (a stopped Ollama) skips the ladder entirely when the+ * user has turned this off, because nothing could ever display why the+ * request is being held and they have said they do not want it to be.+ * Precedence: --recovery-ui/--no-recovery-ui flag > CLAUDISH_RECOVERY_UI env+ * > project `.claudish.json` > this field > true. The scoped read is+ * `readRecoveryUi()`, NOT this allowlist — see its doc comment.+ */+ recoveryUi?: { enabled?: boolean };}/**@@ -361,6 +392,15 @@ export function loadConfig(): ClaudishProfileConfig {if (config.proOnUltracode !== undefined) {merged.proOnUltracode = config.proOnUltracode;}+ // Same trap again, for both recovery switches. Omitted here, the field+ // survives on disk until the first global save and is then silently+ // dropped — turning the user's off-switch back ON with no error.+ if (config.recovery !== undefined) {+ merged.recovery = config.recovery;+ }+ if (config.recoveryUi !== undefined) {+ merged.recoveryUi = config.recoveryUi;+ }return merged;} catch (error) {console.error(`Warning: Failed to load config, using defaults: ${error}`);@@ -484,6 +524,57 @@ export function readProOnUltracode(return undefined;}+/**+ * Read a `{ enabled?: boolean }` switch from the project file, else the global+ * file. Shared by `readRecoveryEnabled` and `readRecoveryUi`.+ *+ * The nesting is what makes `{}` expressible, and `{}` means "no opinion" —+ * a project file that carries `"recovery": {}` must fall through to the global+ * scope rather than reading as `true`. That is why this checks+ * `typeof parsed?.[key]?.enabled === "boolean"` and not the bare-boolean shape+ * `readProOnUltracode` uses: the two fields have different types on purpose.+ */+function readNestedEnabled(+ key: "recovery" | "recoveryUi",+ paths: ScopedConfigPaths+): boolean | undefined {+ for (const pathFn of [paths.project, paths.global]) {+ try {+ const path = pathFn();+ if (!existsSync(path)) continue;+ const parsed = JSON.parse(readFileSync(path, "utf-8")) as Record<string, unknown>;+ const value = (parsed?.[key] as { enabled?: unknown } | undefined)?.enabled;+ if (typeof value === "boolean") return value;+ } catch {+ // Garbled/unreadable file → skip this scope rather than fail the run.+ }+ }+ return undefined;+}++/**+ * Read `recovery.enabled` from the project file, else the global file.+ *+ * Deliberately a RAW per-file read rather than `loadConfig()`, for the same+ * reason `readProOnUltracode` is: `loadConfig` merges only the GLOBAL scope, so+ * a project `.claudish.json` setting this key would be invisible to it.+ *+ * Returns undefined when neither scope states a boolean — the caller then+ * applies its own default (true).+ */+export function readRecoveryEnabled(+ paths: ScopedConfigPaths = defaultScopedConfigPaths+): boolean | undefined {+ return readNestedEnabled("recovery", paths);+}++/** Read `recoveryUi.enabled` from the project file, else the global file. */+export function readRecoveryUi(+ paths: ScopedConfigPaths = defaultScopedConfigPaths+): boolean | undefined {+ return readNestedEnabled("recoveryUi", paths);+}+/*** Detect if CWD looks like a project directory*/diff --git a/packages/cli/src/providers/probe-live.ts b/packages/cli/src/providers/probe-live.tsindex 98b0abff..5f11e5bb 100644--- a/packages/cli/src/providers/probe-live.ts+++ b/packages/cli/src/providers/probe-live.ts@@ -206,6 +206,16 @@ export async function probeLink(method: "POST",headers: {"Content-Type": "application/json",+ // A probe must FAIL FAST. Every probe POSTs /v1/messages through the+ // proxy, so it enters the same handler as a real turn — and a real+ // turn now holds an unreachable provider open for the whole tier-1+ // deadline. Without this header, probing an unreachable link would+ // burn the probe's own timeout and then report `timeout` (the probe's+ // abort fires first) instead of `network-error`, breaking `--probe`+ // and the config TUI's Test All for exactly the failure they exist to+ // diagnose — and multiplying a Test All run by that timeout per dead+ // link.+ "x-claudish-no-recovery": "1",},body: JSON.stringify({model: link.modelSpec,diff --git a/packages/cli/src/providers/transport/local.ts b/packages/cli/src/providers/transport/local.tsindex 7aba380c..73cf4d46 100644--- a/packages/cli/src/providers/transport/local.ts+++ b/packages/cli/src/providers/transport/local.ts@@ -48,6 +48,11 @@ export class LocalTransport implements ProviderTransport {private config: LocalProviderConfig;private modelName: string;private concurrency?: number;+ /**+ * SUCCESS-ONLY latch: true once a probe has actually reached the server.+ * A FAILED probe must never set it — see the comment at the end of+ * `checkHealth()` for what setting it there made `refreshAuth()` return.+ */private healthChecked = false;private isHealthy = false;/**@@ -159,9 +164,17 @@ export class LocalTransport implements ProviderTransport {return {};}- async enqueueRequest(fetchFn: () => Promise<Response>): Promise<Response> {+ async enqueueRequest(+ fetchFn: () => Promise<Response>,+ opts?: { signal?: AbortSignal }+ ): Promise<Response> {if (!LocalModelQueue.isEnabled()) return fetchFn();- return LocalModelQueue.getInstance().enqueue(fetchFn, this.name, this.concurrency);+ return LocalModelQueue.getInstance().enqueue(+ fetchFn,+ this.name,+ this.concurrency,+ opts?.signal+ );}/**@@ -256,7 +269,24 @@ export class LocalTransport implements ProviderTransport {log(`[${this.displayName}] /v1/models failed: ${e?.message || e}`);}- this.healthChecked = true;+ // `healthChecked` latches SUCCESS ONLY. It used to be set here too, and+ // that made a retried `refreshAuth()` a LIE: `refreshAuth` opens with+ // `if (this.healthChecked) return;`, so the second call issued no probe and+ // DID NOT THROW — it returned successfully for a server that was still+ // dead. Harmless while nothing called it twice inside a request; the moment+ // a retry ladder does, attempt 2 resolves instantly, the episode closes as+ // "recovered", and a recovery record is written for an outage that never+ // ended, while the real failure re-appears milliseconds later from the+ // fetch path as a second, unrelated-looking episode.+ //+ // Three consequences of the fix, all wanted:+ // - a retried refreshAuth() RE-PROBES, which is the entire point;+ // - a dead local server costs one extra probe per request instead of+ // latching unhealthy for the process lifetime. Against a refused+ // loopback port that probe returns in ~1 ms;+ // - a recovered server now runs fetchContextWindow(). Today it never+ // does: the failed probe latched the flag that guards it, so the+ // provider served forever on a stale context window.this.isHealthy = false;log(`[${this.displayName}] Health check FAILED - provider not available`);return false;diff --git a/packages/cli/src/providers/transport/types.ts b/packages/cli/src/providers/transport/types.tsindex b4cd3a78..440a179e 100644--- a/packages/cli/src/providers/transport/types.ts+++ b/packages/cli/src/providers/transport/types.ts@@ -84,8 +84,19 @@ export interface ProviderTransport {/*** Optional request queue for rate limiting / concurrency control.* If provided, the ComposedHandler will call this instead of raw fetch.- */- enqueueRequest?(fetchFn: () => Promise<Response>): Promise<Response>;+ *+ * `opts.signal` is OPTIONAL, and so is honouring it — the implementations+ * that ignore the second argument keep compiling and behaving identically.+ * It exists because a retry attempt is bounded by a per-attempt clamp, and a+ * clamp that reaches the `fetch` but not the queue admission in front of it+ * bounds the wrong thing: the caller's wall clock then includes a wait+ * governed by whatever the ACTIVE request's own timeout is. On the local+ * queue that number is ten minutes.+ */+ enqueueRequest?(+ fetchFn: () => Promise<Response>,+ opts?: { signal?: AbortSignal }+ ): Promise<Response>;/*** Optional auth refresh (e.g., OAuth token rotation).diff --git a/packages/cli/src/recovery/clock.ts b/packages/cli/src/recovery/clock.tsnew file mode 100644index 00000000..68e209e1--- /dev/null+++ b/packages/cli/src/recovery/clock.ts@@ -0,0 +1,65 @@+/**+ * The one clock the recovery machinery reads.+ *+ * Every interval in this subsystem is measured in PROCESS ms — the unit+ * `performance.now()` returns and the unit `composed-handler.ts`'s `startTime`+ * already carries. Epoch ms (`Date.now()`) is reserved for values that cross a+ * process boundary or are shown to a human, and the two are never differenced+ * against each other. Nothing here produces epoch ms; the pane protocol that+ * needs it is a later phase.+ *+ * It is injectable for ONE reason: the backoff ladder is 5/10/30/60/60 seconds,+ * and a unit test that asserts those gaps against the real clock takes three+ * minutes and is flaky at the margins. `mock.module()` is not an option — the+ * project's standing rule is that mocking shared infrastructure bleeds across+ * sibling test files in Bun's module registry — so the seam is an explicit+ * parameterless injection instead.+ */++export interface RecoveryClock {+ /** PROCESS ms, monotonic. Same origin as `performance.now()`. */+ now(): number;+ /** Returns an opaque handle understood by this clock's `clearTimeout`. */+ setTimeout(fn: () => void, ms: number): unknown;+ clearTimeout(handle: unknown): void;+ /**+ * Stop a pending timer holding the event loop open.+ *+ * Used for exactly one timer — the post-handoff grace, which outlives the+ * request that created it and must never be the reason the process refuses+ * to exit. The ATTEMPT timer is deliberately NOT unref'd: a handler awaiting+ * the next rung has nothing else keeping Bun's loop alive, so unref'ing it+ * would end the run instead of the wait.+ */+ unref?(handle: unknown): void;+}++const REAL_CLOCK: RecoveryClock = {+ now: () => performance.now(),+ setTimeout: (fn, ms) => setTimeout(fn, ms),+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),+ unref: (handle) => {+ (handle as { unref?: () => void })?.unref?.();+ },+};++let active: RecoveryClock = REAL_CLOCK;++/** The clock every recovery module reads. Never cache the RESULT of `now()`. */+export function recoveryClock(): RecoveryClock {+ return active;+}++/**+ * Install a deterministic clock. Tests only — production never calls this, and+ * a test that does MUST restore in an `afterEach`, because this is module+ * state shared with every other test in the same Bun process.+ */+export function setRecoveryClock(clock: RecoveryClock): void {+ active = clock;+}++/** Restore the real clock. */+export function resetRecoveryClock(): void {+ active = REAL_CLOCK;+}diff --git a/packages/cli/src/recovery/coordinator.ts b/packages/cli/src/recovery/coordinator.tsnew file mode 100644index 00000000..5f384bab--- /dev/null+++ b/packages/cli/src/recovery/coordinator.ts@@ -0,0 +1,500 @@+/**+ * The recovery coordinator — one EPISODE per unreachable target, shared by+ * every request that is failing against it.+ *+ * WHY A COORDINATOR AND NOT N INDEPENDENT LADDERS. Claude Code issues+ * concurrent requests: the main loop, the small title/summary model, and every+ * subagent. During an outage all of them fail within milliseconds of each+ * other. Give each its own ladder and you get N times the connect attempts+ * against a dead network, N unsynchronised countdowns, and no single number a+ * banner could ever show. With one episode there is one timer per target, every+ * parked request wakes together, and each still re-issues ITS OWN bytes —+ * which matters, because they are different requests and the body was+ * serialized per request.+ *+ * THREE LIFETIMES LIVE HERE AND THEY ARE NOT THE SAME OBJECT. This is the+ * distinction the design got wrong once and it is worth restating:+ *+ * - the DEADLINE belongs to one inbound request. Its owner is the waiter.+ * A waiter past its own deadline answers for itself and leaves.+ * - the LADDER belongs to the episode. It ends when the last waiter leaves+ * or an attempt succeeds — never because one waiter ran out of time.+ * - the PANE LEASE belongs to a renderer painting this episode. Nothing in+ * this file grants one yet; see `uiLeaseValid`.+ *+ * Letting one field mean all three is what made a four-waiter episode show+ * `waiters: 4` while exactly one of them was still being retried.+ */++import { randomUUID } from "node:crypto";+import type { ConnectionErrorKind } from "../handlers/shared/connection-error.js";+import { log } from "../logger.js";+import { recoveryClock } from "./clock.js";++export type RecoveryState = "attempting" | "waiting" | "recovered" | "handoff" | "abandoned";++export type RecoveryOutcome =+ | "recovered"+ | "handoff"+ | "client_gone"+ | "gave_up"+ | "grace_expired"+ | "shutdown";++/** What a parked waiter is woken with. An abort REJECTS instead. */+export type WaitOutcome = { kind: "attempt" } | { kind: "gave_up" };++/**+ * How long a handed-off episode stays open waiting for the client to come back.+ *+ * Sized against a measurement, not a guess: Claude Code's own backoff after a+ * 503 doubles off ~0.5 s and CAPS at ~38.4 s, so 120 s is 3.1× the worst+ * observed rejoin gap.+ *+ * Defined here rather than beside the backoff ladder because it is EPISODE+ * state, and keeping it here is what lets this module stay free of any import+ * from `transient-retry.ts` — the ladder's own delays are handed IN by the+ * caller for exactly the same reason. One-way dependency, no cycle.+ */+export const EPISODE_GRACE_MS = 120_000;++export interface EpisodeSeed {+ providerName: string;+ providerDisplayName: string;+ /** The endpoint that actually failed — the AUTH host on an auth-path failure. */+ endpoint: string;+ kind: ConnectionErrorKind;+ code: string | null;+ /** The same sentence the immediate 400 would have carried. */+ reason: string;+ /** This waiter's own absolute deadline, PROCESS ms. */+ deadlineAt: number;+}++interface Waiter {+ deadlineAt: number;+ tier: 1 | 2;+ leftByDeadline: boolean;+ /** Non-null exactly while this waiter is parked. */+ wake: ((outcome: WaitOutcome) => void) | null;+ fail: ((err: unknown) => void) | null;+ /** Detach the abort listener. Always called; an Observer leak is the named risk. */+ detach: (() => void) | null;+}++interface Episode {+ episodeId: string;+ key: string;+ providerDisplayName: string;+ endpoint: string;+ host: string;+ kind: ConnectionErrorKind;+ loopback: boolean;+ code: string | null;+ reason: string;+ state: RecoveryState;+ startedAtPerf: number;+ startedAtMs: number;+ /** Set when a pane is first ASKED for. Null for the whole of this phase. */+ paneRequestedAtPerf: number | null;+ ladderIndex: number;+ attempts: number;+ clientRetries: number;+ /** Ladder rounds, so N concurrent waiters advance the ladder ONCE per round. */+ round: number;+ advancedForRound: number;+ /** How many attempts in this episode have SUCCEEDED. */+ recoveredCount: number;+ lastOutcome: string;+ maxTier: 1 | 2;+ waiters: Set<Waiter>;+ attemptTimer: unknown | null;+ graceTimer: unknown | null;+ nextAttemptAtPerf: number | null;+ /** True once ANY waiter has left because IT ran out of budget. */+ anyLeftByDeadline: boolean;+ gaveUp: boolean;+}++const episodes = new Map<string, Episode>();+const byId = new Map<string, Episode>();++function hostOf(endpoint: string): string {+ try {+ return new URL(endpoint).host || endpoint;+ } catch {+ return endpoint;+ }+}++/** Exported for tests and for `shutdown()`; not part of the waiter contract. */+export function episodeCount(): number {+ return episodes.size;+}++/** Snapshot for logs and tests. Never mutate the returned object. */+export function describeEpisode(episodeId: string): Readonly<Record<string, unknown>> | null {+ const ep = byId.get(episodeId);+ if (!ep) return null;+ return {+ episodeId: ep.episodeId,+ key: ep.key,+ state: ep.state,+ ladderIndex: ep.ladderIndex,+ attempts: ep.attempts,+ round: ep.round,+ clientRetries: ep.clientRetries,+ waiters: ep.waiters.size,+ maxTier: ep.maxTier,+ lastOutcome: ep.lastOutcome,+ nextAttemptAtPerf: ep.nextAttemptAtPerf,+ };+}++/**+ * Is a renderer currently painting this episode?+ *+ * SEAM, deliberately inert in this phase. There is no socket, no pane and no+ * heartbeat yet, so the honest answer is false and the exhaustion arm keeps+ * answering today's 400. It is a function rather than a field because the+ * answer is LIVE — a lease read once and cached into a boolean is stale by the+ * time the status is chosen, which is the whole reason the previous design's+ * `uiAttached` latch was wrong.+ */+export function uiLeaseValid(_episodeId: string): boolean {+ return false;+}++export interface EpisodeHandle {+ readonly episodeId: string;+ readonly key: string;+ /** Total attempts this EPISODE has made, across every waiter and both tiers. */+ attempts(): number;+ /** Ms since the episode opened — not since this request started. */+ recoveryMs(): number;+ ladderIndex(): number;+ /** LIVE. Never cache the result. */+ uiLeaseValid(): boolean;+ /**+ * Park until the next attempt is due. Resolves `{kind:"attempt"}` on the+ * shared timer, `{kind:"gave_up"}` if the user asked to stop, and REJECTS+ * with the signal's abort reason if the client goes away.+ *+ * `delayMs` is the caller's reading of the ladder at `ladderIndex()`. It is+ * used only by the FIRST waiter to park in a round — the timer is shared, so+ * a second waiter joining an armed round inherits the gap already running+ * rather than restarting it. That is the whole point of one episode.+ */+ waitForNextAttempt(signal: AbortSignal, delayMs: number): Promise<WaitOutcome>;+ recordAttemptResult(outcome: string, ok: boolean): void;+ /**+ * THIS waiter ran out of budget. It does not move the episode: the episode+ * enters `handoff` only when the LAST waiter has left and at least one of+ * them left this way — a property of the SET, computed on the final leave.+ */+ handoff(): void;+ close(outcome: RecoveryOutcome): void;+ /** MUST be called in a `finally`. */+ leave(): void;+}++/**+ * Join the episode for this target, creating it if this is the first failure.+ *+ * A request arriving while an episode is in `handoff` REJOINS it — same+ * `episodeId`, same ladder position, `clientRetries` incremented — which is+ * what makes an in-request hold and a client-side retry read as one continuous+ * recovery rather than as two unrelated failures.+ */+export function joinEpisode(seed: EpisodeSeed): EpisodeHandle {+ const clock = recoveryClock();+ const host = hostOf(seed.endpoint);+ const key = `${seed.providerName}|${host}`;++ let ep = episodes.get(key);+ let tier: 1 | 2 = 1;++ if (ep && (ep.state === "recovered" || ep.state === "abandoned")) {+ episodes.delete(key);+ ep = undefined;+ }++ if (ep) {+ if (ep.state === "handoff") {+ // The client came back inside the grace window: same episode, same+ // ladder, one more client retry. The ladder does NOT reset — the target+ // has been down for the whole of it and starting again at 5 s would+ // hammer a dead host harder the longer the outage lasted.+ if (ep.graceTimer !== null) {+ clock.clearTimeout(ep.graceTimer);+ ep.graceTimer = null;+ }+ ep.clientRetries++;+ ep.state = "attempting";+ ep.maxTier = 2;+ tier = 2;+ log(+ `[Recovery] ${ep.providerDisplayName} rejoined episode ${ep.episodeId} ` ++ `(client retry ${ep.clientRetries}, ladder ${ep.ladderIndex}, attempts ${ep.attempts})`+ );+ }+ } else {+ const nowPerf = clock.now();+ ep = {+ episodeId: randomUUID(),+ key,+ providerDisplayName: seed.providerDisplayName,+ endpoint: seed.endpoint,+ host,+ kind: seed.kind,+ loopback: false,+ code: seed.code,+ reason: seed.reason,+ state: "attempting",+ startedAtPerf: nowPerf,+ startedAtMs: Date.now(),+ paneRequestedAtPerf: null,+ ladderIndex: 0,+ attempts: 0,+ clientRetries: 0,+ round: 0,+ // Round 0 counts as already advanced. The failure that OPENS an episode+ // is attempt 1, and attempt 1's gap is the ladder's FIRST rung (5 s) —+ // so recording it must not push the index to the second (10 s). Getting+ // this off by one turns the specified 5/10/30/60/60 into 10/30/60/60.+ advancedForRound: 0,+ recoveredCount: 0,+ lastOutcome: seed.code ?? "unknown",+ maxTier: 1,+ waiters: new Set(),+ attemptTimer: null,+ graceTimer: null,+ nextAttemptAtPerf: null,+ anyLeftByDeadline: false,+ gaveUp: false,+ };+ episodes.set(key, ep);+ byId.set(ep.episodeId, ep);+ log(+ `[Recovery] episode ${ep.episodeId} opened for ${ep.providerDisplayName} at ${ep.endpoint} ` ++ `(${ep.kind}/${ep.code ?? "?"})`+ );+ }++ const episode = ep;+ const waiter: Waiter = {+ deadlineAt: seed.deadlineAt,+ tier,+ leftByDeadline: false,+ wake: null,+ fail: null,+ detach: null,+ };+ episode.waiters.add(waiter);++ let left = false;++ return {+ episodeId: episode.episodeId,+ key: episode.key,+ attempts: () => episode.attempts,+ recoveryMs: () => Math.round(recoveryClock().now() - episode.startedAtPerf),+ ladderIndex: () => episode.ladderIndex,+ uiLeaseValid: () => uiLeaseValid(episode.episodeId),++ waitForNextAttempt(signal: AbortSignal, delayMs: number): Promise<WaitOutcome> {+ if (episode.gaveUp || episode.state === "abandoned") {+ return Promise.resolve({ kind: "gave_up" });+ }+ if (signal.aborted) return Promise.reject(signal.reason ?? new Error("aborted"));++ return new Promise<WaitOutcome>((resolve, reject) => {+ const onAbort = () => {+ waiter.wake = null;+ waiter.fail = null;+ waiter.detach = null;+ signal.removeEventListener("abort", onAbort);+ reject(signal.reason ?? new Error("aborted"));+ };+ // Unsubscribe is not optional. A parked waiter that leaves without+ // detaching keeps this closure — and the whole episode — alive for as+ // long as the client signal exists.+ waiter.detach = () => signal.removeEventListener("abort", onAbort);+ waiter.wake = (outcome) => {+ waiter.detach?.();+ waiter.detach = null;+ waiter.wake = null;+ waiter.fail = null;+ resolve(outcome);+ };+ waiter.fail = (err) => {+ waiter.detach?.();+ waiter.detach = null;+ waiter.wake = null;+ waiter.fail = null;+ reject(err);+ };+ signal.addEventListener("abort", onAbort, { once: true });+ armAttemptTimer(episode, delayMs);+ });+ },++ recordAttemptResult(outcome: string, ok: boolean): void {+ episode.attempts++;+ episode.lastOutcome = outcome;+ if (ok) {+ // The target just proved reachable. The episode is NOT torn down here:+ // other waiters may still be parked on the shared timer, and closing+ // it from under them clears that timer and strands them forever with+ // nothing to wake them. Wake them instead, and reset the ladder — a+ // host that answered a second ago has not earned a sixty-second gap.+ // The episode's own end is decided by the LAST waiter to leave.+ episode.recoveredCount++;+ episode.ladderIndex = 0;+ episode.advancedForRound = episode.round;+ episode.state = "attempting";+ clearAttemptTimer(episode);+ for (const w of [...episode.waiters]) w.wake?.({ kind: "attempt" });+ return;+ }+ // Advance the ladder ONCE per round however many waiters attempted it.+ if (episode.advancedForRound !== episode.round) {+ episode.advancedForRound = episode.round;+ episode.ladderIndex++;+ }+ log(+ `[Recovery] ${episode.providerDisplayName} attempt ${episode.attempts} failed: ${outcome} ` ++ `(episode ${episode.episodeId}, ladder ${episode.ladderIndex})`+ );+ },++ handoff(): void {+ waiter.leftByDeadline = true;+ episode.anyLeftByDeadline = true;+ },++ close(outcome: RecoveryOutcome): void {+ closeEpisode(episode, outcome);+ },++ leave(): void {+ if (left) return;+ left = true;+ waiter.detach?.();+ waiter.detach = null;+ waiter.wake = null;+ waiter.fail = null;+ episode.waiters.delete(waiter);+ if (episode.waiters.size > 0) return;++ // Last one out.+ clearAttemptTimer(episode);+ if (episode.state === "recovered" || episode.state === "abandoned") {+ byId.delete(episode.episodeId);+ return;+ }++ if (episode.recoveredCount > 0 && !episode.anyLeftByDeadline) {+ closeEpisode(episode, "recovered");+ } else if (episode.anyLeftByDeadline) {+ // A DELIBERATE handoff: a re-POST is expected, so hold the counters.+ episode.state = "handoff";+ const c = recoveryClock();+ const timer = c.setTimeout(() => {+ episode.graceTimer = null;+ closeEpisode(episode, "grace_expired");+ }, EPISODE_GRACE_MS);+ c.unref?.(timer);+ episode.graceTimer = timer;+ log(+ `[Recovery] episode ${episode.episodeId} handed off after ${Math.round(+ c.now() - episode.startedAtPerf+ )}ms, ${episode.attempts} attempts — holding ${EPISODE_GRACE_MS / 1000}s for a client retry`+ );+ } else {+ // The client went away. The grace is for a handoff, not a general+ // retention policy: release now.+ closeEpisode(episode, "client_gone");+ }+ },+ };+}++function armAttemptTimer(episode: Episode, delay: number): void {+ if (episode.attemptTimer !== null) return;+ const clock = recoveryClock();+ episode.state = "waiting";+ episode.nextAttemptAtPerf = clock.now() + delay;+ episode.attemptTimer = clock.setTimeout(() => {+ episode.attemptTimer = null;+ episode.nextAttemptAtPerf = null;+ episode.state = "attempting";+ episode.round++;+ for (const w of [...episode.waiters]) w.wake?.({ kind: "attempt" });+ }, delay);+ log(+ `[Recovery] ${episode.providerDisplayName} waiting ${delay / 1000}s before attempt ` ++ `${episode.attempts + 1} (episode ${episode.episodeId}, ${episode.waiters.size} waiting)`+ );+}++function clearAttemptTimer(episode: Episode): void {+ if (episode.attemptTimer === null) return;+ recoveryClock().clearTimeout(episode.attemptTimer);+ episode.attemptTimer = null;+ episode.nextAttemptAtPerf = null;+}++function closeEpisode(episode: Episode, outcome: RecoveryOutcome): void {+ if (episode.state === "recovered" || episode.state === "abandoned") return;+ const clock = recoveryClock();+ clearAttemptTimer(episode);+ if (episode.graceTimer !== null) {+ clock.clearTimeout(episode.graceTimer);+ episode.graceTimer = null;+ }+ episode.state = outcome === "recovered" ? "recovered" : "abandoned";+ if (episodes.get(episode.key) === episode) episodes.delete(episode.key);+ byId.delete(episode.episodeId);+ // Never strand a parked waiter. Shutdown and give-up both reach here with+ // waiters still on the shared timer, and the timer has just been cleared —+ // without this they would wait on a promise nothing can ever settle.+ if (episode.state === "abandoned") {+ for (const w of [...episode.waiters]) w.wake?.({ kind: "gave_up" });+ }+ log(+ `[Recovery] episode ${episode.episodeId} closed: ${outcome} after ` ++ `${Math.round(clock.now() - episode.startedAtPerf)}ms and ${episode.attempts} attempts`+ );+}++/**+ * Collapse the wait for an episode and attempt now. The pane's `[r] try now`+ * key routes here in a later phase; nothing calls it in this one, and it is+ * exported now so the ladder never grows a second wake path later.+ */+export function tryNow(episodeId: string): void {+ const ep = byId.get(episodeId);+ if (!ep || ep.attemptTimer === null) return;+ clearAttemptTimer(ep);+ ep.state = "attempting";+ ep.round++;+ for (const w of [...ep.waiters]) w.wake?.({ kind: "attempt" });+}++/** Wake every waiter of every episode with `gave_up`. The `[q]` key, later. */+export function giveUp(episodeId: string): void {+ const ep = byId.get(episodeId);+ if (!ep) return;+ ep.gaveUp = true;+ clearAttemptTimer(ep);+ for (const w of [...ep.waiters]) w.wake?.({ kind: "gave_up" });+}++/** Proxy shutdown: no episode may outlive the process that owns its timers. */+export function closeAllEpisodes(outcome: RecoveryOutcome = "shutdown"): void {+ for (const ep of [...episodes.values()]) closeEpisode(ep, outcome);+ for (const ep of [...byId.values()]) closeEpisode(ep, outcome);+ episodes.clear();+ byId.clear();+}diff --git a/packages/cli/src/recovery/settings.ts b/packages/cli/src/recovery/settings.tsnew file mode 100644index 00000000..e894fc84--- /dev/null+++ b/packages/cli/src/recovery/settings.ts@@ -0,0 +1,188 @@+/**+ * The two recovery switches, and the ONE place the tier-1 deadline is derived.+ *+ * Precedence for both switches, identical to the shape `cli.ts` already+ * implements for `debug`:+ *+ * CLI flag > environment > project `.claudish.json` > global config > true+ *+ * `{}` at any scope means "no opinion" and falls through to the next one —+ * which is why both fields are objects rather than bare booleans.+ */++import { ENV } from "../config.js";+import { log } from "../logger.js";+import { readRecoveryEnabled, readRecoveryUi } from "../profile-config.js";++/** Flag layer. Set once by `cli.ts`'s arg loop; undefined means "not given". */+interface RecoveryFlagOverrides {+ recovery?: boolean;+ recoveryUi?: boolean;+}++let flagOverrides: RecoveryFlagOverrides = {};++/** Called by `cli.ts` when `--recovery` / `--no-recovery[-ui]` is parsed. */+export function setRecoveryFlagOverrides(overrides: RecoveryFlagOverrides): void {+ flagOverrides = { ...flagOverrides, ...overrides };+}++/** Tests and long-lived hosts (`serve`) that must not inherit a stale flag. */+export function resetRecoveryFlagOverrides(): void {+ flagOverrides = {};+}++/** `1`/`true` → true, `0`/`false` → false, anything else → undefined. */+function parseEnvBool(raw: string | undefined): boolean | undefined {+ const v = raw?.trim().toLowerCase();+ if (v === "1" || v === "true") return true;+ if (v === "0" || v === "false") return false;+ return undefined;+}++/**+ * Is the retry ladder allowed to run at all? Default true.+ *+ * The one row of the status table that reads this answers today's immediate+ * 400 — so turning it off restores pre-recovery behaviour exactly, which is+ * what makes it a safe CI switch rather than a feature toggle.+ */+export function resolveRecoveryEnabled(): boolean {+ if (flagOverrides.recovery !== undefined) return flagOverrides.recovery;+ const env = parseEnvBool(process.env[ENV.CLAUDISH_RECOVERY]);+ if (env !== undefined) return env;+ const scoped = readRecoveryEnabled();+ if (scoped !== undefined) return scoped;+ return true;+}++/**+ * May claudish own a surface on which a recovery episode's reason is legible?+ * Default true.+ *+ * NOTHING READS THIS YET, and that is expected. It exists now for two reasons.+ * The first is that the status decision it will gate — whether an exhausted+ * episode may answer a RETRYABLE status instead of an inline error — is a later+ * phase, and landing the switch early means that phase changes one branch+ * rather than four files. The second is the CLAUDE.md invariant it trips: a new+ * `ClaudishProfileConfig` field that is not in `loadConfig`'s allowlist AND+ * does not have a scoped reader survives on disk until the first global save+ * and is then dropped, silently. That trap has caught this codebase twice, so+ * the field is landed with its round-trip test the moment it is defined rather+ * than the moment it is first consumed.+ *+ * It is a question about the USER'S CONFIGURATION and about nothing else. It+ * must never be conflated with "can this process open a pane right now", which+ * is a launch-order fact that is false in every unwrapped launch, in `-p`, in+ * `serve` and in the whole test suite.+ */+export function resolveRecoveryUi(): boolean {+ if (flagOverrides.recoveryUi !== undefined) return flagOverrides.recoveryUi;+ const env = parseEnvBool(process.env[ENV.CLAUDISH_RECOVERY_UI]);+ if (env !== undefined) return env;+ const scoped = readRecoveryUi();+ if (scoped !== undefined) return scoped;+ return true;+}++// ─── The deadline ────────────────────────────────────────────────────────────++/**+ * Claude Code's own default per-request timeout, MEASURED — not assumed.+ *+ * Six replications at 359.4 / 360.1 / 360.1 / 360.1 / 360.1 / 360.1 s against a+ * custom base URL, and it was then PROVED to be this variable rather than a+ * fixed watchdog by setting `API_TIMEOUT_MS=20000` and observing six aborts at+ * exactly 20.000 s.+ */+export const DEFAULT_API_TIMEOUT_MS = 360_000;++/**+ * We never derive a hold longer than this from the environment, however+ * generous `API_TIMEOUT_MS` is. It stops the constant from tracking one Claude+ * Code version's undocumented default, and it keeps the hold inside the range+ * where the other ceilings in this system (Bun's `idleTimeout`, lifted per+ * request but only on the recovery path) were reasoned about.+ */+export const CLIENT_CEILING_CLAMP_MS = 300_000;++/**+ * Reserve subtracted from the client's ceiling: the unclamped first attempt's+ * tail, the response write, and the gap between the client starting its clock+ * and our handler starting ours. Losing this race means the client aborts a+ * request we were about to answer, so the margin is deliberately generous.+ */+export const DEADLINE_MARGIN_MS = 30_000;++/**+ * Below this much budget, recovery is not worth attempting — but we clamp UP to+ * it rather than disabling, because a client that aborts is handled correctly+ * (the waiter leaves within a millisecond of `c.req.raw.signal` firing) whereas+ * a silently-skipped ladder is the failure this floor exists to make visible.+ *+ * WHY 15 s specifically, rather than a round number. The ladder's first rung is+ * 5 s and no attempt is started with less than `MIN_ATTEMPT_SLOT_MS` (3 s) of+ * budget left, so the smallest deadline that buys even ONE retry beyond the+ * unchanged first attempt is 5 + 3 = 8 s. 15 s buys that retry with room for+ * the attempt itself to take a few seconds, and stops one rung short of the+ * second (5 + 10 + 3 = 18 s). Anything under 8 s would make the ladder a pure+ * delay in front of the same 400 — machinery that runs, logs and recovers+ * nothing, which is worse than not running.+ */+export const TIER1_DEADLINE_FLOOR_MS = 15_000;++/**+ * The tier-1 hold, DERIVED from the environment on every request.+ *+ * max(FLOOR, min(API_TIMEOUT_MS ?? 360_000, 300_000) − 30_000)+ *+ * At the default this is 270 000 ms. It is not hardcoded, and that is the point:+ * `API_TIMEOUT_MS` is a user-settable knob that sets the client's ceiling+ * exactly, so a machine with `API_TIMEOUT_MS=60000` running against a hardcoded+ * 270 s hold would end EVERY episode in `client_gone` — the feature doing+ * nothing at all, silently, forever, with nothing printed anywhere.+ *+ * A 270 s hold is not racing an impatient client. Claude Code's retry budget+ * was measured to be a COUNT (~11 attempts), not a duration: on the hung-upstream+ * path it was still retrying after 40 minutes and six full 360 s attempts. One+ * tier-1 hold spends well under one of those attempts.+ */+export function resolveTier1DeadlineMs(env: NodeJS.ProcessEnv = process.env): number {+ const raw = env[ENV.API_TIMEOUT_MS];+ const parsed = raw === undefined ? Number.NaN : Number(raw);+ const clientCeiling =+ Number.isFinite(parsed) && parsed > 0+ ? Math.min(parsed, CLIENT_CEILING_CLAMP_MS)+ : CLIENT_CEILING_CLAMP_MS;+ const derived = clientCeiling - DEADLINE_MARGIN_MS;+ return Math.max(TIER1_DEADLINE_FLOOR_MS, derived);+}++/** The value `resolveTier1DeadlineMs` returns with nothing set. */+export const DEFAULT_TIER1_DEADLINE_MS = CLIENT_CEILING_CLAMP_MS - DEADLINE_MARGIN_MS;++let deadlineNoticeLogged = false;++/**+ * Announce a deadline the environment shortened, ONCE per process.+ *+ * A shortened budget is not an error and must not read as one, but it must not+ * be mysterious either: the whole point of deriving the number is that the user+ * can see it. Emitted from inside the recovery path, so a healthy run prints+ * nothing.+ */+export function logDeadlineIfShortened(deadlineMs: number): void {+ if (deadlineNoticeLogged) return;+ if (deadlineMs >= DEFAULT_TIER1_DEADLINE_MS) return;+ deadlineNoticeLogged = true;+ const raw = process.env[ENV.API_TIMEOUT_MS];+ log(+ `[Recovery] tier-1 hold shortened to ${Math.round(deadlineMs / 1000)}s ` ++ `(API_TIMEOUT_MS=${raw ?? "unset"}; default would be ${Math.round(DEFAULT_TIER1_DEADLINE_MS / 1000)}s)`+ );+}++/** Tests only — the notice latch is process state. */+export function resetDeadlineNotice(): void {+ deadlineNoticeLogged = false;+}