Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

chore: merge origin/main into worktree-investgiage-gpt-file

Jack Rudenko5d08ea8c8890
diff --cc packages/cli/src/claude-runner.ts
index 061b785d,3ef1f58b..a225065b
--- a/packages/cli/src/claude-runner.ts
+++ b/packages/cli/src/claude-runner.ts
@@@ -811,13 -811,11 +811,13 @@@ export function createTempSettingsFile
// Directory may already exist
}
- const timestamp = Date.now();
- const tempPath = join(claudishDir, `settings-${timestamp}.json`);
+ // The pid keeps the name unique across processes started in the same millisecond
+ // (madbench, team slots): with the timestamp alone they shared one file and each
+ // Claude Code loaded the last writer's status line and hooks.
+ const tempPath = join(claudishDir, `settings-${process.pid}-${Date.now()}.json`);
// The file the proxy's TokenTracker writes: one a parent ASSIGNED (a team slot's or
- // channel session's own CLAUDISH_TOKEN_FILE), else `tokens-<port>.json` in .claudish.
+ // MCP session's own CLAUDISH_TOKEN_FILE), else `tokens-<port>.json` in .claudish.
// An enclosing claudish session's PUBLISHED file (inherited by a claudish run from its
// Bash tool) is not an assignment — see assignedTokenFile. Resolved by the same
// function as the tracker and the summary, so the status line can never be pointed at
diff --cc packages/cli/src/cli.ts
index 0974c207,e358d61d..28df7663
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@@ -10,12 -10,7 +10,13 @@@ import { homedir } from "node:os"
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { EFFORT_LEVELS, isEffortLevel } from "./adapters/base-api-format.js";
+ import { setCredentialPromptRole } from "./auth/credentials/prompt-role.js";
+import {
+ CODE_MODE_ENV_VAR,
+ CODE_MODE_SETTINGS,
+ DEFAULT_CODE_MODE_SETTING,
+ parseCodeModeSetting,
+} from "./code-mode/policy.js";
import { ENV } from "./config.js";
import { setStderrQuiet } from "./logger.js";
import {
diff --cc packages/cli/src/handlers/composed-handler.ts
index 9526ac60,427282a4..499f3d66
--- a/packages/cli/src/handlers/composed-handler.ts
+++ b/packages/cli/src/handlers/composed-handler.ts
@@@ -1375,12 -1380,11 +1455,13 @@@ export class ComposedHandler implement
authType: "oauth",
site: "refreshAuth",
recovery: recoveryTally,
- }
+ },
+ "401"
);
if (outcome.kind === "respond") return outcome.response;
- // Recovered: fall through as if the first refresh had succeeded.
+ // Recovered: fall through as if the first refresh had succeeded,
+ // bound to the artifact the successful attempt minted.
+ binding = outcome.value || undefined;
} else {
log(`[${this.provider.displayName}] Auth/health check failed: ${err.message}`);
logStderr(
@@@ -1550,13 -1468,14 +1630,19 @@@
// The touch is refresh-conditional, which makes this rare, not safe.
// Every header fetch below goes through this, so a header the wire requires
// (a beta token next to the field it wrote) survives the auth retries too.
+ //
+ // Signed by the binding passed, never by shared transport state: the
+ // primary fetch and parameter retry pass this request's `binding`, the 401
+ // retry the one `forceRefreshAuth` just returned, a retry leg its own.
++ //
+ // The headers of THIS request's latest attempt — the one whose answer is
+ // returned (primary, parameter re-fetch or auth retry), recorded on this
+ // call's own `signing` record so a concurrent request on the same handler
+ // cannot replace it. `handle` names the signer from them (`signingCredential`).
- const fetchHeaders = async (): Promise<Record<string, string>> => {
- const fetched = await this.provider.getHeaders(payload);
+ const fetchHeaders = async (b: AuthBinding | undefined): Promise<Record<string, string>> => {
+ const fetched = await this.provider.getHeaders(payload, b);
mergeWireHeaders(fetched, wireHeaders);
+ signing.headers = fetched;
return fetched;
};
let headers: Record<string, string>;
@@@ -1907,37 -1848,11 +2047,39 @@@
// 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.
+ /** Answers that never reached the upstream (another credential silo): reported as such. */
+ const notResentResponses = new WeakSet<Response>();
const doAuthRetry = async (sig?: AbortSignal): Promise<Response> => {
- // The headers of the request the upstream rejected, so a transport can
+ // A returned binding replaces this request's: the retry, and every
- // retry leg after it, sign with the artifact just minted.
- const refreshed = await this.provider.forceRefreshAuth!();
++ // retry leg after it, sign with the artifact just minted. The headers
++ // of the request the upstream rejected go with it, so a transport can
+ // tell a stale failure from one naming the credential it holds now.
- await this.provider.forceRefreshAuth!({ rejectedHeaders: headers });
- const retryHeaders = await fetchHeaders();
++ const refreshed = await this.provider.forceRefreshAuth!({ rejectedHeaders: headers });
+ if (refreshed) {
+ // The body was built for THIS binding's account (code mode renders
+ // its encrypted reasoning and keys its records by it): a refresh
+ // onto another arm or account must not resend it. Answered with
+ // the upstream's own 401, never a throw: inside the recovery
+ // ladder an unclassified throw escapes `handle()`.
+ if (
+ binding &&
+ !isSameCredentialSilo(
+ { auth: binding.auth, accountKey: accountKeyFromBinding(binding) },
+ { auth: refreshed.auth, accountKey: accountKeyFromBinding(refreshed) }
+ )
+ ) {
+ log(`[${this.provider.displayName}] sign-in changed during the request; not resent`);
+ const notResent = new Response(
+ "Codex sign-in changed during the request; it was not resent",
+ { status: response.status }
+ );
+ notResentResponses.add(notResent);
+ return notResent;
+ }
+ binding = refreshed;
+ endpoint = this.provider.getEndpoint(this.targetModel, binding);
+ }
+ const retryHeaders = await fetchHeaders(binding);
// 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.
@@@ -2012,6 -1920,56 +2154,59 @@@
} catch {
// Stats must never crash claudish
}
+ // A 401/403 that SURVIVED a fresh credential is terminal for a
+ // subscription, or wherever the transport says so: answered 400 with
+ // the terminal verdict and the same hint and wording as the generic
+ // remap below, so the login line lands inline and the chain stops.
+ // 401/403 ONLY: Antigravity's terminal 429 keeps its own route.
- if (retryResp.status === 401 || retryResp.status === 403) {
++ // A RESENT request only: a not-resent answer (the refresh signed in
++ // another account) proves nothing about the login, so it keeps its
++ // own 401 and message rather than "the login was rejected".
++ if (resent && (retryResp.status === 401 || retryResp.status === 403)) {
+ const transportTerminal = this.provider.classifyTerminalError?.(
+ retryResp.status,
+ errorText
+ );
+ // The subscription stop is for a credential rejection only; a model
+ // or allowance miss keeps its pass-through route (`isCredentialRejection`).
+ if (
+ (isSubscriptionProvider(this.provider.name) &&
+ isCredentialRejection(retryResp.status, errorText)) ||
+ transportTerminal === true
+ ) {
+ const hint = getRecoveryHint(
+ retryResp.status,
+ errorText,
+ this.provider.displayName,
+ transportTerminal,
+ this.provider.name
+ );
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(errorText);
+ } catch {
+ parsed = undefined;
+ }
+ const providerMsg = extractProviderMessage(parsed ?? errorText);
+ const surfaced = buildSurfacedErrorMessage({
+ providerDisplayName: this.provider.displayName,
+ status: retryResp.status,
+ hint,
+ providerMessage: providerMsg,
+ });
+ return c.json(
+ wrapAnthropicError(
+ 400,
+ surfaced,
+ "invalid_request_error",
+ retryResp.status,
+ providerMsg
+ ),
+ 400 as any,
+ authVerdictHeaders("terminal")
+ );
+ }
+ }
return c.json(wrapAnthropicError(retryResp.status, errorText), retryResp.status as any);
}
return null;
diff --cc packages/cli/src/handlers/fallback-handler.ts
index 44ce583d,7d0f983f..44b89fdf
--- a/packages/cli/src/handlers/fallback-handler.ts
+++ b/packages/cli/src/handlers/fallback-handler.ts
@@@ -13,13 -13,10 +13,15 @@@ import type { Context } from "hono"
import { logStderr } from "../logger.js";
import { ComposedHandler } from "./composed-handler.js";
import { extractUpstreamStatus } from "./shared/anthropic-error.js";
+ import { authVerdict, isCredentialRejection } from "./shared/auth-failure.js";
import { hasQuotaExhaustionWording } from "./shared/quota-exhaustion.js";
-import { isClaudishConnectionVerdict, isRecoveryHoldResponse } from "./shared/recovery-marker.js";
+import {
+ hasStreamFailureMarker,
+ isClaudishConnectionVerdict,
+ isRecoveryHoldResponse,
+ isStreamFailureResponse,
+} from "./shared/recovery-marker.js";
+ import { isSubscriptionProvider } from "./shared/remote-provider-types.js";
import type { ModelHandler } from "./types.js";
export interface FallbackCandidate {
@@@ -118,19 -126,31 +131,44 @@@ export class FallbackHandler implement
return response;
}
+ // ── THE STREAM-FAILURE MARKER, SAME PLACE AND SAME REASONS ────────────
+ //
+ // A non-streamed turn whose stream ended on an SSE `error` (the provider
+ // answered 200, then the stream failed) is answered by the JSON collector
+ // with an error response. In streaming mode the same failure never comes
+ // back through here as an error, so neither may this one: it is not the
+ // provider's verdict on the request, and its body can quote an upstream
+ // message containing quota wording. Returned verbatim, before the body is
+ // read, so it is neither advanced past nor folded with earlier errors.
+ if (isStreamFailureResponse(response)) {
+ return response;
+ }
+
+ // A CREDENTIAL VERDICT leaves this handler untouched too, for the
+ // recovery hold's second reason: folded into `formatCombinedError`, a
+ // transient 503 behind an earlier candidate's 404 became a terminal 400
+ // (`exhaustedChainStatus` is 503 only when EVERY error is transient), so
+ // Claude Code stopped instead of retrying the same hop, and the verdict
+ // header was dropped. A terminal verdict keeps its exact message and
+ // `upstream_status` the same way (`auth-failure.ts`).
+ //
+ // One exception, for a TERMINAL verdict on a subscription: the chain
+ // moves on to its remaining SUBSCRIPTION candidates, never a metered one
+ // (project owner, 2026-10-20). A bare `glm-5.3` whose Zen Go key expired
+ // is served by the Token Plan the user also holds, not stopped and not
+ // billed per token.
+ const verdict = authVerdict(response.headers);
+ const subscriptionRejected =
+ verdict === "terminal" && !!provider && isSubscriptionProvider(provider);
+ if (verdict && !subscriptionRejected) {
+ if (errors.length > 0) {
+ logStderr(
+ `[Fallback] ${name}: credential ${verdict === "terminal" ? "rejected" : "temporarily unavailable"} — stopping the chain here.`
+ );
+ }
+ return response;
+ }
+
// Clone before reading body so we can still return the original if needed
const errorBody = await response.clone().text();
@@@ -251,11 -337,19 +355,23 @@@ export function isRetryableError
// predicate rather than either half is what stops chain-safety from being a
// property of which arm happened to answer.
if (isClaudishConnectionVerdict(headers)) return false;
+ // A stream that failed after a 200 is not a provider's verdict either; see
+ // `STREAM_FAILURE_HEADER` in recovery-marker.ts. Above the wording match for
+ // the same reason as the line above.
+ if (hasStreamFailureMarker(headers)) return false;
+ // ── A CREDENTIAL VERDICT IS NEVER A REASON TO ADVANCE EITHER ──────────────
+ //
+ // `ComposedHandler` marks its answer to a credential failure it could place
+ // (`auth-failure.ts`): `terminal` — a subscription login that cannot succeed
+ // on retry, answered 400 so the message lands inline — or `transient` — a
+ // 5xx/429 on the credential path, which the SAME hop answers on Claude Code's
+ // own retry. Either way the next candidate is the wrong remedy, and for a
+ // subscription it is a metered one (project owner, 2026-10-16). Above the
+ // quota wording and the `upstream_status` recovery below, because a terminal
+ // 400 carries `upstream_status: 401`, which that recovery reads as retryable.
+ if (authVerdict(headers)) return false;
+
// A spent subscription allowance is retryable AT THE CHAIN LEVEL: this
// provider cannot serve, but the next one can.
//
diff --cc packages/cli/src/providers/transport/openai-codex.ts
index d7240ffb,bb69f0d1..049af0e9
--- a/packages/cli/src/providers/transport/openai-codex.ts
+++ b/packages/cli/src/providers/transport/openai-codex.ts
@@@ -23,41 -26,21 +26,43 @@@
import { normalizeCodexModel } from "../../adapters/codex-api-format.js";
import { lookupModelForProvider } from "../../adapters/model-catalog.js";
+import { CodexOAuth } from "../../auth/codex-oauth.js";
import { credentials } from "../../auth/credentials/authority.js";
import { recordSignedArm } from "../../auth/credentials/billing-probe.js";
+import { CodexOAuthHalf } from "../../auth/credentials/codex-credential.js";
+ import { isTransientCredentialError } from "../../auth/credentials/credential-error.js";
import type { RequestAuth } from "../../auth/credentials/types.js";
import { classifyConnectionError } from "../../handlers/shared/connection-error.js";
+import type { RemoteProvider } from "../../handlers/shared/remote-provider-types.js";
import { conversationKey } from "./conversation-key.js";
import { OpenAIProviderTransport } from "./openai.js";
+import type { AuthBinding } from "./types.js";
+
+/**
+ * What `forceRefreshAuth` uses of the Codex OAuth login. Injectable so a test
+ * never touches the real singleton (a test suite once deleted the real Codex
+ * login through a singleton reset); production passes nothing.
+ */
+export interface CodexOAuthRefresher {
+ /** Rotate the OAuth token (single-flight through CodexOAuth's refresh lock). */
+ refreshToken(): Promise<unknown>;
+ /** Mint a request artifact from the OAuth half ONLY. */
+ mintOAuthAuth(): Promise<RequestAuth | null>;
+}
+
+const defaultCodexOAuthRefresher: CodexOAuthRefresher = {
+ refreshToken: () => CodexOAuth.getInstance().refreshToken(),
+ mintOAuthAuth: () => new CodexOAuthHalf().getRequestAuth({ model: "" }),
+};
export class OpenAICodexTransport extends OpenAIProviderTransport {
/**
- * The last auth artifact refreshAuth() minted. Shared by every request on this
- * transport, so the request path never reads it: ComposedHandler passes the
- * request's own `AuthBinding` instead. Read only by callers that pass no
- * binding (probes, tests). Null when OAuth is unavailable — the transport then
- * falls back to the OpenAI base transport's api-key path.
- * The per-request auth artifact, populated by refreshAuth() (called before
- * getEndpoint/getHeaders/transformPayload): the OAuth artifact, or the
- * endpoint-less api-key artifact when there is no OAuth login. Null only
- * before the first refreshAuth(); a refreshAuth() that throws never reaches
- * getHeaders().
++ * The last auth artifact refreshAuth() minted: the OAuth artifact, or the
++ * endpoint-less api-key artifact when there is no OAuth login. Shared by
++ * every request on this transport, so the request path never reads it:
++ * ComposedHandler passes the request's own `AuthBinding` instead. Read only
++ * by callers that pass no binding (probes, tests). Null only before the first
++ * refreshAuth(); a refreshAuth() that throws never reaches getHeaders().
*/
private cachedAuth: RequestAuth | null = null;
diff --cc packages/cli/src/providers/transport/types.ts
index a99d2a43,1f9e6b5f..197b9d09
--- a/packages/cli/src/providers/transport/types.ts
+++ b/packages/cli/src/providers/transport/types.ts
@@@ -139,10 -108,23 +139,27 @@@ export interface ProviderTransport
* Force refresh auth credentials after a 401 response.
* Used by OAuth providers (Vertex, CodeAssist) to handle token expiry.
* ComposedHandler calls this automatically on 401 and retries the request.
+ * A returned binding REPLACES the request's binding for the retry.
+ *
+ * `ctx.rejectedHeaders` are the headers of the request the upstream just
+ * rejected, so a transport holding several credentials can tell a stale
+ * failure (its credential already changed) from one that names the
+ * credential it holds now.
*/
- // biome-ignore lint/suspicious/noConfusingVoidType: legacy transports return Promise<void>, which `undefined` would reject
- forceRefreshAuth?(): Promise<AuthBinding | void>;
- forceRefreshAuth?(ctx?: { rejectedHeaders?: Record<string, string> }): Promise<void>;
++ forceRefreshAuth?(
++ ctx?: { rejectedHeaders?: Record<string, string> }
++ // biome-ignore lint/suspicious/noConfusingVoidType: legacy transports return Promise<void>, which `undefined` would reject
++ ): Promise<AuthBinding | void>;
+
+ /**
+ * Optional: a display-safe name of the credential that signed a request
+ * (`RequestAuth.signer`), for a provider with several login sources, looked
+ * up from the headers THAT request was sent with — never from the
+ * transport's current state, which a concurrent request may have rotated.
+ * ComposedHandler returns it on the response as `x-claudish-signed-with`
+ * (URI-encoded), which `--probe` reads per request.
+ */
+ signingCredential?(sentHeaders: Record<string, string>): string | undefined;
/**
* Optional per-provider verdict on whether an error response is TERMINAL