UNPKG

@bitkyc08/opencodex

Version:

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code

1,991 lines • 107 kB
import { MuseLoginError, museLoginErrorMessage } from "./meta-muse-errors";
import type { KiroOAuthMetadata, OAuthController, OAuthCredentials } from "./types";
import { mapFill } from "../providers/resolved-model-policy-merge";
import { initializeProviderModelSelection } from "../providers/initial-model-selection";
import type { OcxConfig, OcxProviderConfig, RefreshPolicy } from "../types";
import { getDefaultConfig, initializePersistedConfigIfMissing, loadConfig, mutatePersistedConfig, observeInitialConfigState, saveConfig } from "../config";
import { resolveProviderApiKey } from "../providers/key-store";
import { projectEmail } from "../lib/privacy";
import { KiroTokenRefreshError, environmentKiroRoutingMetadata, loginKiro, refreshKiroToken, settleKiroLoginTransaction } from "./kiro";
import { KiroUserIdentityUnavailableError } from "./kiro-account-identity";
import { precheckOAuthReauthIdentity } from "./reauth-precheck";
import {
  OAuthMutationBusyError,
  OAuthRefreshIntentIOError,
  clearOAuthRefreshIntent,
  createOAuthRefreshIntentLock,
  credentialGeneration,
  getAccountCredentialWithStatus,
  getAccountSet,
  getCredential,
  markAccountNeedsReauthIfGeneration, accountNeedsReauthForStatus, markAccountRefreshAttentionIfGeneration,
  markOAuthRefreshIntentStaleOwner,
  mergeAccountCredential,
  normalizeAuthStoreBuffer,
  readOAuthRefreshIntent,
  rollbackCredentialWriteIfMatch,
  saveAccountCredential,
  saveCredential,
  saveCredentialWithReceipt,
  writeOAuthRefreshIntent,
  type OAuthCredentialWriteReceipt,
  type OAuthRefreshIntent,
  type AuthStore,
} from "./store";
import { loginXai, refreshXaiToken, XAI_LOCAL_CLI_DETACH_WARNING, XaiTokenRequestError } from "./xai";
import { ANTHROPIC_OAUTH_BETA, AnthropicTokenError } from "./anthropic";
import { isAnthropicOAuthInstance, anthropicInstanceRowShapeMatches } from "../providers/anthropic-instance";
import { captureModelsOAuthTarget, guardModelsOAuthRequest, mayResolveModelsOAuth } from "./model-discovery-auth";
import { anthropicOAuthDefinition, assertAnthropicInstanceLoginConfig, AnthropicInstanceCollisionError,
  clearAnthropicRefreshIntentBestEffort, clearAnthropicRefreshIntentForKnownFailure,
  resumeAnthropicRefreshIntentCleanup, clearObservedAnthropicRefreshIntent } from "./anthropic-oauth-definitions";
import { loginKimi, refreshKimiToken } from "./kimi";
import { loginNous, NousTokenError, refreshNousToken, clearNousRefreshIntent, RefreshIntentIOError } from "./nous";
import { ChatGptTokenRequestError, ChatGptTokenError, loginChatGPT, refreshChatGPTToken, type ChatGPTLoginFlow } from "./chatgpt";
import { loginAntigravity, refreshAntigravityToken } from "./google-antigravity";
import { AntigravityProjectDiscoveryError } from "./antigravity-discovery-diagnostics";
import { loginCursor, refreshCursorToken } from "./cursor";
import { loginZed, refreshZedToken } from "./zed";
import { assertDevinCliAdoptionOwnership, loginDevin, refreshDevinToken } from "./devin";
import { validateDevinApiBaseUrl } from "./devin/api-base";
import { loginGithubCopilot, refreshGithubCopilotToken, validateCopilotApiBaseUrl } from "./github-copilot";
import { loginM365Copilot, refreshM365CopilotToken } from "./m365-copilot";
import { M365BrowserUnavailableError } from "./m365-copilot-browser";
import { loginCommandCode, refreshCommandCodeToken } from "./command-code";
import { loginMetaMuse, refreshMetaMuseToken } from "./meta-muse";
import { loginWorkBuddy, refreshWorkBuddyToken } from "./workbuddy";
import { WORKBUDDY_CONFIG_URL, workBuddyHeaders } from "../providers/workbuddy";
import { DSH_ACCOUNT_AUTH } from "./dsh";
import { loginOrcaRouter, orcaRouterInferenceBaseUrl, refreshOrcaRouterKey } from "./orcarouter";
import { ANTIGRAVITY_DISCOVERY_UA } from "../adapters/google-antigravity-wire";
import { deriveOAuthDefaultModel, deriveOAuthProviderConfig } from "../providers/derive";
import { isOAuthCredentialSiblingOf, oauthCredentialSlot } from "./credential-siblings";
import { apiKeyPoolEntryId, sanitizeApiKeyValue } from "../providers/api-keys";
import { preservableApiKeyPool } from "./api-key-pool-preserve";
import { effectiveGoogleMode, getProviderRegistryEntry, mergeRegistryStaticHeaders, providerMatchesRegistryTransport } from "../providers/registry";
import { providerModelsUrl, resolveProviderModelDiscoveryUrl } from "../providers/model-discovery";
import { resolveProviderTransport } from "../providers/xai-transport";
import { detectGrokCliToken, hasComparableGrokIdentity, isSameGrokIdentity, shouldAdoptGrokGeneration } from "./local-token-detect";
import { logOAuthEvent } from "./log";
import { MAX_OAUTH_TOKEN_REFRESH_WAITERS, retireSettledOAuthRefreshFlight, tokenRefreshWaiters, type OAuthRefreshFlightEvidence } from "./refresh-flight-retirement";
export { MAX_OAUTH_TOKEN_REFRESH_WAITERS };
import { captureConfigGeneration, sweepExpiredOnWrite } from "../lib/state-store-sweeper";
import { admitLoginFlow, classifyLoginCodeError, clearManualCodeSlot, CodeLoginUnsupportedError, ensureManualCodeSlot, kiroLoginSettling, latestLoginFlowKey, loginAbort, loginFlowProvider, loginState, recordStartedLoginFlow, settleLoginFlow, waitForManualLoginCode, type LoginCodeError, type OAuthLoginHint } from "./login-flow-state";
export { cancelLoginFlow, clearLoginState, CodeLoginUnsupportedError, isCodeLoginFlow, loginFlowAccountId, reconcileOAuthFlowState, submitLoginCode, submitManualLoginCode, waitForLoginSettled } from "./login-flow-state";
export type { LoginCodeError, LoginFlowState } from "./login-flow-state";
import { randomUUID } from "node:crypto";
export {
  CODEX_HEALTH_AUTH_FAILED_NOTE,
  CODEX_HEALTH_MANAGEMENT_API_UNAVAILABLE_NOTE,
  CODEX_HEALTH_UNAVAILABLE_NOTE,
  MASKED_ACCOUNT_FALLBACK,
  collectOAuthHealthEntries,
  collectOAuthHealthEntriesForCli,
  detectOAuthWarning,
  oauthAccountHealthFields,
  oauthHealthLabel,
  oauthHealthSummary,
  projectCodexAccountHealth,
  projectOAuthAccountHealth,
  projectStoredOAuthAccountHealth,
  type CodexHealthSource,
  type OAuthAccountHealth,
  type OAuthAccountHealthFields,
  type OAuthCliHealthReport,
  type OAuthHealthEntry,
  type OAuthHealthLabel,
} from "./health";
export { OAUTH_REFRESH_LOCK_WAIT_MS, peekAuthStore, peekOAuthRefreshIntent } from "./store";
import { codexAccountNamespaceProviderCollisionError } from "../codex/account-namespace-match";
import { REFRESH_SKEW_MS } from "./refresh-policy";
import { newerClaudeCredentialForInstance, captureAnthropicCredentialOwnerForInstance, claudeAdoptionSlotCurrent, claudeCredentialGenerationCurrent } from "./anthropic-continuity";
import { anthropicSubscriptionLabel } from "../providers/anthropic-subscription";
import { mergeOAuthOrganizationName, normalizeOAuthPlan, mergeOAuthPlan, oauthOrganizationNameSummary, withMergedOAuthLabels } from "./plan";
import { mergeAnthropicIdentity, type AnthropicIdentityResolver } from "./anthropic-identity";
import { anthropicReauthSlotGuard, observeAnthropicSlotOrganizations } from "./anthropic-login-slot";
import { AnthropicCrossInstanceDuplicateError, AnthropicLocalCliImportError, assertAnthropicCredentialSource } from "./store-anthropic-instance";
export interface OAuthAccessSnapshot {
  /** Private M365 discovery session; never projected into account summaries. */
  m365?: import("./types").M365CopilotWebSession;
  workbuddy?: import("./types").WorkBuddyOAuthMetadata;
  provider: string;
  accountId: string;
  generation: string;
  accessToken: string;
  /** Cloud Code Assist project selected during Antigravity login. */
  projectId?: string;
  /** Safe request-routing subset; refresh-only Kiro client secrets never leave the credential store. */
  kiro?: Pick<KiroOAuthMetadata, "profileArn" | "apiRegion" | "ssoRegion" | "authType">;
  /**
   * Allowlisted origin for this account. Copilot and Devin pin credentials to regional or tenant
   * hosts. Routing, discovery, refresh and failover use the same snapshot so a concurrent switch
   * cannot pair one account's token with another account's origin (#2568d).
   */
  apiBaseUrl?: string;
  /**
   * The upstream's own user id for providers that sign requests with it (Zed's `user_id`).
   * `accountId` is the local store slot key, a hash, and must never stand in for it.
   */
  providerUserId?: string;
}

export interface ObservedOAuthAccessSnapshot extends OAuthAccessSnapshot {
  /** Retained for callers that predate `apiBaseUrl` moving onto the base snapshot. */
  apiBaseUrl?: string;
}

export type OAuthActiveTokenObservation =
  | { readonly kind: "available"; readonly snapshot: ObservedOAuthAccessSnapshot }
  | { readonly kind: "paused" }
  | { readonly kind: "missing" }
  | { readonly kind: "malformed" }
  | { readonly kind: "needs-reauth" }
  | { readonly kind: "expired" }
  | { readonly kind: "near-expiry" }
  | { readonly kind: "unsupported" };

const MAX_OAUTH_TOKEN_REFRESH_FLIGHTS = 32;
const OAUTH_TOKEN_REFRESH_FLIGHT_STALE_MS = 120_000;
interface OAuthTokenRefreshFlight extends OAuthRefreshFlightEvidence { promise: Promise<OAuthAccessSnapshot>; startedAt: number; abort: AbortController; settled?: boolean; retirementDeferredLogged?: boolean; requireUsable?: boolean }
const tokenRefreshes = new Map<string, OAuthTokenRefreshFlight>();
export class OAuthTokenRefreshBusyError extends Error {
  readonly code = "OAUTH_TOKEN_REFRESH_BUSY";
  readonly retryable = true;
  constructor() { super("OAuth token refresh capacity reached"); this.name = "OAuthTokenRefreshBusyError"; }
}
export class OAuthTokenRefreshStaleError extends Error {
  readonly code = "OAUTH_TOKEN_REFRESH_STALE";
  readonly retryable = true;
  constructor() { super("OAuth token refresh owner became stale"); this.name = "OAuthTokenRefreshStaleError"; }
}
/** Known pre-dispatch cancellation; independent waiters may acquire a new owner. */
class OAuthDiscoveryRefreshCancelledError extends OAuthTokenRefreshStaleError {}

/** Focused owner-identity tests only. Synthetic owners retain no account data. */
export function seedOAuthTokenRefreshFlightsForTests(rows: Array<{ key: string; startedAt?: number; flightId?: string; dispatched?: boolean }>): {
  promises: Promise<OAuthAccessSnapshot>[];
  cleanup: () => void;
} {
  const inserted: OAuthTokenRefreshFlight[] = [];
  const promises = rows.map(({ key, startedAt, flightId, dispatched }) => {
    const abort = new AbortController();
    const promise = new Promise<OAuthAccessSnapshot>((_resolve, reject) => {
      abort.signal.addEventListener("abort", () => reject(abort.signal.reason), { once: true });
    });
    const flight: OAuthTokenRefreshFlight = { promise, startedAt: startedAt ?? Date.now(), abort, flightId: flightId ?? randomUUID(), dispatched: dispatched ?? false };
    abort.signal.addEventListener("abort", () => { flight.settled = true; }, { once: true });
    tokenRefreshes.set(key, flight);
    inserted.push(flight);
    return promise;
  });
  return {
    promises,
    cleanup() {
      for (const [key, flight] of tokenRefreshes) {
        if (!inserted.includes(flight)) continue;
        tokenRefreshes.delete(key);
        flight.abort.abort(new Error("test cleanup"));
      }
    },
  };
}
const XAI_PERMANENT_FAILURE_TTL_MS=30_000;
const permanentRefreshFailures=new Map<string,number>();
interface XaiRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; requireUsableAccount?: boolean }
interface AnthropicRefreshDeps { resolveIdentity?: AnthropicIdentityResolver; intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; flight?: OAuthRefreshFlightEvidence; replacedStaleFlight?: OAuthRefreshFlightEvidence }
interface GenericRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; authorityCurrent?: () => boolean; requireUsableAccount?: boolean }
function verdictKey(p:string,a:string,c:OAuthCredentials){return `${p}\0${a}\0${credentialGeneration(c)}`;}
function cached(p:string,a:string,c:OAuthCredentials,now:()=>number){const k=verdictKey(p,a,c),u=permanentRefreshFailures.get(k);if(u===undefined)return false;if(u<=now()){permanentRefreshFailures.delete(k);return false;}return true;}
export function sweepExpiredXaiPermanentFailureVerdicts(now=Date.now()):number{let removed=0;for(const[key,until]of permanentRefreshFailures){if(until>now)continue;permanentRefreshFailures.delete(key);removed+=1;}return removed;}

export interface LoginOpts {
  forceLogin?: boolean;
  /** When set, persist into this account slot and require matching identity. */
  reauthAccountId?: string;
  /**
   * ChatGPT and xAI: `device` selects the device grant instead of the
   * localhost callback flow, for hosts with no browser or no loopback
   * listener (#3366). Ignored by every other provider.
   */
  flow?: ChatGPTLoginFlow;
  /** Code-display login: no callback server; completes from a pasted code (needs `codeRedirectUri`). */
  codeMode?: boolean;
  /** Publish this sibling row (see credential-siblings.ts) instead of the login's own row. */
  publishRow?: string;
}

export interface LoginFlowLifecycle {
  flowId?: string;
  /** Protect this flow's outcome from automatic cleanup while its outer login owns it. */
  retainOutcome?: () => boolean;
  /** Internal handoff of this flow's credential after its store write is confirmed. */
  onCredentialPersisted?: (credential: OAuthCredentials) => void;
  /** Runs after background credential/config persistence settles, before status becomes done. */
  onSettled?: () => void | Promise<void>;
}

export interface OAuthProviderDef {
  login(ctrl: OAuthController, opts?: LoginOpts, providerConfig?: OcxProviderConfig): Promise<OAuthCredentials>;
  refresh(
    refreshToken: string,
    signal?: AbortSignal,
    credential?: OAuthCredentials,
    /** Store row being refreshed; passed by the generic lock only. */
    accountId?: string,
  ): Promise<OAuthCredentials>;
  /** provider entry written into config.json on first login. */
  providerConfig: OcxProviderConfig;
  /** Resolve login-owned config from the latest disk state (for configurable OAuth origins). */
  resolveProviderConfig?: (config: OcxConfig) => OcxProviderConfig;
  defaultModel: string;
  /**
   * Built-in proactive-refresh policy, risk-tiered by the provider's ToS exposure (devlog
   * 260703_oauth-multi-account-refresh-and-tos). A user's per-provider `config.providers[x].refreshPolicy`
   * overrides this. Default when unset here: "lazy-only".
   */
  defaultRefreshPolicy?: RefreshPolicy;
  /** Provider-hosted page that DISPLAYS the code; its presence enables `codeMode`. */
  codeRedirectUri?: string;
  /** Has an RFC 8628 device grant besides its browser login; `flow: "device"` selects it. */
  deviceLogin?: true;
}

function oauthConfig(id: string): OcxProviderConfig {
  const config = deriveOAuthProviderConfig(id);
  if (!config) throw new Error(`OAuth provider missing from registry: ${id}`);
  return config;
}

function oauthDefaultModel(id: string): string {
  const model = deriveOAuthDefaultModel(id);
  if (!model) throw new Error(`OAuth provider missing default model in registry: ${id}`);
  return model;
}

export const OAUTH_PROVIDERS: Record<string, OAuthProviderDef> = {
  "m365-copilot": {
    login: loginM365Copilot, refresh: refreshM365CopilotToken,
    providerConfig: oauthConfig("m365-copilot"), defaultModel: oauthDefaultModel("m365-copilot"),
    defaultRefreshPolicy: "lazy-only",
  },
  "workbuddy-ai": {
    login: loginWorkBuddy, refresh: refreshWorkBuddyToken,
    providerConfig: oauthConfig("workbuddy-ai"), defaultModel: oauthDefaultModel("workbuddy-ai"),
    defaultRefreshPolicy: "lazy-only",
  },
  "dsh-account": {
    ...DSH_ACCOUNT_AUTH,
    providerConfig: oauthConfig("dsh-account"),
    defaultModel: oauthDefaultModel("dsh-account"),
  },
  "command-code": {
    // Add-account/reauth must not reimport the current local CLI credential.
    login: (ctrl, opts) => loginCommandCode(ctrl, { importLocal: opts?.forceLogin ? "off" : "fallback" }),
    refresh: refreshCommandCodeToken,
    providerConfig: oauthConfig("command-code"),
    defaultModel: oauthDefaultModel("command-code"),
    defaultRefreshPolicy: "disabled",
  },
  "orcarouter-oauth": {
    login: (ctrl, _opts, providerConfig) => loginOrcaRouter(ctrl, {
      baseUrl: process.env.ORCAROUTER_API_BASE_URL
        ?? process.env.ORCAROUTER_BASE_URL
        ?? providerConfig?.baseUrl,
      authBaseUrl: process.env.ORCAROUTER_AUTH_BASE_URL,
    }),
    refresh: refreshOrcaRouterKey,
    providerConfig: oauthConfig("orcarouter-oauth"),
    resolveProviderConfig: config => ({
      ...oauthConfig("orcarouter-oauth"),
      baseUrl: orcaRouterInferenceBaseUrl(
        process.env.ORCAROUTER_API_BASE_URL
          ?? process.env.ORCAROUTER_BASE_URL
          ?? config.providers["orcarouter-oauth"]?.baseUrl,
      ),
    }),
    defaultModel: oauthDefaultModel("orcarouter-oauth"),
    // The credential is a durable API key. There is no refresh endpoint.
    defaultRefreshPolicy: "disabled",
  },
  xai: {
    // forceLogin skips the local grok-cli import so a SECOND account can be chosen in the browser.
    login: (ctrl, opts) => loginXai(ctrl, { importLocal: opts?.forceLogin ? "off" : "fallback", device: opts?.flow === "device" }),
    deviceLogin: true,
    refresh: refreshXaiToken,
    providerConfig: oauthConfig("xai"),
    defaultModel: oauthDefaultModel("xai"),
  },
  anthropic: anthropicOAuthDefinition("anthropic"),
  anthropic2: anthropicOAuthDefinition("anthropic2"),
  kimi: {
    login: (ctrl) => loginKimi(ctrl),
    refresh: refreshKimiToken,
    providerConfig: oauthConfig("kimi"),
    defaultModel: oauthDefaultModel("kimi"),
  },
  "meta-muse": {
    // Add-account/reauth must not reimport the credential already on disk; it starts the
    // device grant instead, the same mapping command-code uses above.
    login: (ctrl, opts) => loginMetaMuse(ctrl, {}, { importLocal: opts?.forceLogin ? "off" : "fallback" }),
    refresh: refreshMetaMuseToken,
    providerConfig: oauthConfig("meta-muse"),
    defaultModel: oauthDefaultModel("meta-muse"),
    // Static API key that Meta scopes to its own CLI. Never generate unattended traffic
    // on it — same posture as anthropic, for the same reason: the vendor restricts use
    // outside its own client, so every exchange stays attributable to a user action.
    defaultRefreshPolicy: "disabled",
  },
  nous: {
    // Nous Portal device-grant login (RFC 8628) against portal.nousresearch.com.
    // The access token is the per-request inference JWT (scope inference:invoke).
    // Refresh tokens are single-use and rotated server-side on every refresh:
    // keep background refresh lazy-only (the default) so concurrent refreshes
    // cannot trip the Portal's token-reuse revocation.
    login: (ctrl) => loginNous(ctrl),
    refresh: (rt, signal) => refreshNousToken(rt, signal),
    providerConfig: oauthConfig("nous"),
    defaultModel: oauthDefaultModel("nous"),
    // Single-use rotating refresh tokens must never be background-refreshed
    // proactively: concurrent refreshes would trip the Portal's reuse
    // revocation. Anchor the lazy-only default explicitly so it cannot be
    // silently overridden to proactive.
    defaultRefreshPolicy: "lazy-only",
  },
  kiro: {
    login: (ctrl, opts) => loginKiro(ctrl, { forceLogin: opts?.forceLogin }),
    refresh: (rt, signal, credential) => refreshKiroToken(rt, signal, credential),
    providerConfig: oauthConfig("kiro"),
    defaultModel: oauthDefaultModel("kiro"),
  },
  "google-antigravity": {
    login: (ctrl, opts) => loginAntigravity(ctrl, { forceAccountSelect: opts?.forceLogin === true }),
    refresh: refreshAntigravityToken,
    providerConfig: oauthConfig("google-antigravity"),
    defaultModel: oauthDefaultModel("google-antigravity"),
  },
  cursor: {
    login: (ctrl, opts) => loginCursor(ctrl, undefined, { forceLogin: opts?.forceLogin }),
    refresh: refreshCursorToken,
    providerConfig: oauthConfig("cursor"),
    defaultModel: oauthDefaultModel("cursor"),
  },
  zed: {
    login: ctrl => loginZed(ctrl),
    refresh: refreshZedToken,
    providerConfig: oauthConfig("zed"),
    defaultModel: oauthDefaultModel("zed"),
    defaultRefreshPolicy: "disabled",
  },
  devin: {
    // Import-first: adopts a signed-in Devin CLI credential when one exists and
    // only then falls back to the Auth0 browser flow. forceLogin skips the
    // import so reauth/add-account can reach a different account than the CLI's.
    login: (ctrl, opts) => loginDevin(ctrl, opts),
    refresh: refreshDevinToken,
    providerConfig: oauthConfig("devin"),
    defaultModel: oauthDefaultModel("devin"),
    defaultRefreshPolicy: "disabled",
  },
  "github-copilot": {
    login: (ctrl) => loginGithubCopilot(ctrl),
    refresh: (rt, signal) => refreshGithubCopilotToken(rt, signal),
    providerConfig: oauthConfig("github-copilot"),
    defaultModel: oauthDefaultModel("github-copilot"),
    // Unofficial Copilot bridge — keep proactive traffic lazy-only (no background guardian spam).
    defaultRefreshPolicy: "lazy-only",
  },
  chatgpt: {
    login: (ctrl, opts) => loginChatGPT(ctrl, { forceLogin: opts?.forceLogin, flow: opts?.flow }),
    refresh: (rt, signal) => refreshChatGPTToken(rt, { signal }),
    providerConfig: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward" as const },
    defaultModel: "gpt-5.6-luna",
  },
};

/**
 * Removed provider ids that still name a live successor.
 *
 * `devin-cli` was merged into `devin` (import-first login absorbed the CLI
 * credential import; devlog/_fin/260913_devin_provider_merge). The id can
 * still arrive here from a saved config row or a stored credential slot that
 * the startup migration has not rekeyed yet, and from a user typing the old
 * name at `ocx login`. It is deliberately NOT an OAUTH_PROVIDERS entry:
 * keeping one would re-expose it as a separate dashboard/login row, and its
 * `oauthConfig("devin-cli")` would throw at module load once the registry row
 * is gone. The alias map covers the paths that must keep working — refresh
 * policy resolution below, and the login-cli dispatch that warns and reroutes.
 */
export const DEPRECATED_OAUTH_PROVIDER_ALIASES: Record<string, string> = {
  "devin-cli": "devin",
};

export function isOAuthProvider(name: string): boolean {
  return name in OAUTH_PROVIDERS;
}

export function isPublicOAuthProvider(name: string): boolean {
  return name !== "chatgpt" && isOAuthProvider(name);
}

/** Providers that can log in from a displayed code, with no inbound port and no browser here. */
export function supportsCodeLoginMode(name: string): boolean {
  return OAUTH_PROVIDERS[name]?.codeRedirectUri !== undefined;
}

/** Providers that can log in with a device grant: a URL and a short code, approved in any browser. */
export function supportsDeviceLoginMode(name: string): boolean {
  return OAUTH_PROVIDERS[name]?.deviceLogin === true;
}

function isRefreshPolicy(value: unknown): value is RefreshPolicy {
  return value === "proactive" || value === "lazy-only" || value === "disabled";
}

/**
 * The effective proactive-refresh policy for a provider: the user's per-provider
 * `config.providers[provider].refreshPolicy` if set, else the provider def's risk-tiered default,
 * else "lazy-only". The guardian acts only when this resolves to "proactive".
 */
export function resolveRefreshPolicy(provider: string, config: OcxConfig): RefreshPolicy {
  const override = config.providers[provider]?.refreshPolicy;
  if (isRefreshPolicy(override)) return override;
  // Resolve through the alias map so a lingering `devin-cli` row inherits
  // devin's "disabled" policy. Without it the row would fall to "lazy-only"
  // and the guardian would attempt refreshes Cognition has no endpoint for,
  // marking the account needsReauth on a durable key that cannot refresh.
  const def = OAUTH_PROVIDERS[DEPRECATED_OAUTH_PROVIDER_ALIASES[provider] ?? provider];
  return def?.defaultRefreshPolicy ?? "lazy-only";
}

/** The discovered project id stored on an OAuth credential (Antigravity CCA), if any. */
export function getOAuthCredentialProjectId(provider: string): string | undefined {
  return getCredential(provider)?.projectId;
}

/** Allowlisted Copilot API origin from the active credential, if still valid. */
export function getOAuthCredentialApiBaseUrl(provider: string): string | undefined {
  return validateCopilotApiBaseUrl(getCredential(provider)?.apiBaseUrl);
}

/** Provider ids that support real OAuth login (drives the GUI's "Log in with …" buttons). */
export function listOAuthProviders(): string[] {
  return Object.keys(OAUTH_PROVIDERS).filter(isPublicOAuthProvider);
}
import { OAuthAccountUnusableError, OAuthLoginSupersededError, OAuthAccountPausedError, OAuthLoginRequiredError, OAuthProviderNamespaceCollisionError, OAuthProviderPublicationError, OAuthReauthIdentityMismatchError, OAuthReauthIdentityUnverifiedError, UnsupportedOAuthProviderError } from "./oauth-errors";
export { OAuthAccountPausedError, OAuthLoginRequiredError, OAuthProviderNamespaceCollisionError, OAuthProviderPublicationError, OAuthReauthIdentityMismatchError, OAuthReauthIdentityUnverifiedError, UnsupportedOAuthProviderError } from "./oauth-errors";
/** Project arbitrary OAuth failures onto the small, stable public error vocabulary. */
export function publicOAuthErrorPresentation(error: unknown): import("../lib/client-error-body").ProxyErrorPresentation | undefined {
  if (error instanceof OAuthLoginRequiredError) return "oauth_login";
  if (error instanceof AntigravityProjectDiscoveryError) return "discovery";
  if (error instanceof MuseLoginError && error.kind === "validation-http" && error.status !== undefined) return "muse_http";
  return undefined;
}

export function publicOAuthAuthenticationErrorMessage(error: unknown): string {
  if (error instanceof AntigravityProjectDiscoveryError) return error.publicMessage;
  if (error instanceof M365BrowserUnavailableError) return error.message;
  if (error instanceof MuseLoginError) return museLoginErrorMessage(error.kind, error.status);
  if (error instanceof OAuthMutationBusyError) {
    return error.message === "OAuth mutation queue wait timed out"
      ? "OAuth mutation queue wait timed out"
      : "OAuth mutation queue is busy";
  }
  if (
    (error instanceof OAuthLoginRequiredError && isOAuthProvider(error.provider))
    || error instanceof OAuthAccountPausedError
    || error instanceof OAuthProviderPublicationError
    || error instanceof OAuthProviderNamespaceCollisionError
    // Reauth identity outcomes carry fixed, account-free remediation text. Dropping them to the
    // generic message hides WHICH failure the user must fix (sign in with the selected account).
    || error instanceof OAuthReauthIdentityMismatchError
    || error instanceof OAuthReauthIdentityUnverifiedError
    || error instanceof OAuthTokenRefreshBusyError
    || error instanceof OAuthTokenRefreshStaleError
    || error instanceof AnthropicInstanceCollisionError
    || error instanceof AnthropicCrossInstanceDuplicateError
    || error instanceof AnthropicLocalCliImportError
    // Fixed, account-free text: a Kiro login that could not name its user left the existing
    // organization account in place, and the user must confirm the signed-in CLI user (#6641).
    || error instanceof KiroUserIdentityUnavailableError
  ) return error.message;
  return "OAuth authentication failed. Check the OpenCodex account status and retry.";
}

function accessSnapshot(provider: string, accountId: string, cred: OAuthCredentials, oauthProvider = provider): OAuthAccessSnapshot {
  // Derived, not read back: a stored `authType` is trusted when present, but a credential imported
  // before the field existed still routes correctly because the client pair implies SSO OIDC.
  const kiroAuthType = cred.kiro?.authType
    ?? (cred.kiro?.clientId && cred.kiro?.clientSecret ? "aws_sso_oidc" as const : undefined);
  const storedKiroRouting = {
    ...(cred.kiro?.profileArn ? { profileArn: cred.kiro.profileArn } : {}),
    ...(cred.kiro?.apiRegion ? { apiRegion: cred.kiro.apiRegion } : {}),
    ...(cred.kiro?.ssoRegion ? { ssoRegion: cred.kiro.ssoRegion } : {}),
  };
  // `authType` is a property OF the account, not routing the environment can substitute for, so it
  // is merged after the environment fallback decision rather than counting as stored routing.
  // Folding it into `storedKiroRouting` would make a client-pair-only credential look non-empty
  // and silently disable `environmentKiroRoutingMetadata()` for it.
  const kiroAuthTypeRouting = kiroAuthType ? { authType: kiroAuthType } : {};
  // Validated here, not at the call site: an unvalidated origin from a legacy or crafted
  // credential must never travel with a bearer, and dropping it makes the transport fall back to
  // the canonical host rather than to whatever the previous account was using.
  // The host rides on the OAuth definition the snapshot was resolved through, not the routed
  // slot name: a custom provider reusing the Devin definition keeps its stored tenant URL.
  const accountApiBaseUrl = oauthProvider === "github-copilot"
    ? validateCopilotApiBaseUrl(cred.apiBaseUrl)
    : oauthProvider === "devin" || oauthProvider === "devin-cli"
      ? validateDevinApiBaseUrl(cred.apiBaseUrl)
      : undefined;
  return {
    provider,
    accountId,
    generation: credentialGeneration(cred),
    accessToken: cred.access,
    ...(oauthProvider === "workbuddy-ai" && cred.workbuddy ? { workbuddy: { ...cred.workbuddy } } : {}),
    ...(oauthProvider === "m365-copilot" && cred.m365 ? { m365: { ...cred.m365 } } : {}),
    ...(cred.projectId ? { projectId: cred.projectId } : {}),
    ...(accountApiBaseUrl ? { apiBaseUrl: accountApiBaseUrl } : {}),
    ...(oauthProvider === "zed" && cred.accountId ? { providerUserId: cred.accountId } : {}),
    // Stored account metadata remains authoritative. Metadata-less legacy/environment credentials
    // may use explicit environment routing, but never borrow the currently signed-in local CLI account.
    ...(provider === "kiro"
      ? {
          kiro: {
            ...(Object.keys(storedKiroRouting).length > 0
              ? storedKiroRouting
              : environmentKiroRoutingMetadata() ?? {}),
            ...kiroAuthTypeRouting,
          },
        }
      : {}),
  };
}

/**
 * Observe the active OAuth token from an auth-store buffer supplied by its filesystem owner.
 * Missing, malformed, reauth-required, and expiring credentials are typed no-token outcomes;
 * this path never refreshes, locks, hardens, backs up, or persists credentials.
 */
export function observeActiveOAuthAccessToken(
  provider: string,
  authStoreBuffer: Uint8Array | null,
  now = Date.now(),
): OAuthActiveTokenObservation {
  const authStore = normalizeAuthStoreBuffer(authStoreBuffer);
  if (authStore.kind === "absent") return { kind: "missing" };
  if (authStore.kind === "malformed") return { kind: "malformed" };
  if (!isOAuthProvider(oauthCredentialSlot(provider))) return { kind: "unsupported" };

  const accountSet = authStore.store[oauthCredentialSlot(provider)];
  const account = accountSet?.accounts.find(candidate => candidate.id === accountSet.activeAccountId);
  if (!account) return { kind: "missing" };
  if (account.paused === true) return { kind: "paused" };
  if (account.needsReauth) return { kind: "needs-reauth" };
  if (account.credential.expires <= now) return { kind: "expired" };
  if (account.credential.expires <= now + REFRESH_SKEW_MS) return { kind: "near-expiry" };

  const apiBaseUrl = provider === "github-copilot"
    ? validateCopilotApiBaseUrl(account.credential.apiBaseUrl)
    : undefined;
  return {
    kind: "available",
    snapshot: {
      ...accessSnapshot(provider, account.id, account.credential),
      ...(apiBaseUrl ? { apiBaseUrl } : {}),
    },
  };
}

async function resolveAccessSnapshotForAccount(
  provider: string,
  accountId: string,
  rejectedGeneration?: string,
  requireUsableAccount = false,
  oauthProvider = provider,
  authorityCurrent?: () => boolean,
  retryCancelledDiscovery = true,
): Promise<OAuthAccessSnapshot> {
  // A sibling row resolves, refreshes and single-flights under its owner's login, then keeps its own label.
  const slot = oauthCredentialSlot(provider);
  if (slot !== provider) return { ...await resolveAccessSnapshotForAccount(slot, accountId, rejectedGeneration, requireUsableAccount, oauthProvider === provider ? slot : oauthProvider, authorityCurrent, retryCancelledDiscovery), provider };
  const def = OAUTH_PROVIDERS[oauthProvider];
  if (!def) throw new UnsupportedOAuthProviderError(oauthProvider);
  // One store read answers both questions. A caller that opts in gets the account REJECTED
  // when it needs reauthentication, which a bare credential read cannot detect: a revoked
  // account keeps a readable credential, so resolution would otherwise succeed and the
  // request would dispatch on an account already known to need a fresh login.
  const row = getAccountCredentialWithStatus(provider, accountId);
  if (!row) throw new OAuthLoginRequiredError(provider);
  if (row.paused === true) throw new OAuthAccountPausedError();
  if (requireUsableAccount && row.needsReauth) throw new OAuthLoginRequiredError(provider);
  const cred = row.credential;
  const current = accessSnapshot(provider, accountId, cred, oauthProvider);
  if (rejectedGeneration !== undefined && current.generation !== rejectedGeneration) return current;
  if (rejectedGeneration === undefined && cred.expires > Date.now() + REFRESH_SKEW_MS) return current;

  const key = `${provider}\u0000${accountId}`;
  let existing = tokenRefreshes.get(key);
  let replacedStaleFlight: OAuthRefreshFlightEvidence | undefined;
  if (existing && (existing.abort.signal.reason instanceof OAuthTokenRefreshStaleError
    || Date.now() - existing.startedAt > OAUTH_TOKEN_REFRESH_FLIGHT_STALE_MS)) {
    replacedStaleFlight = { flightId: existing.flightId, dispatched: existing.dispatched };
    existing.abort.abort(new OAuthTokenRefreshStaleError());
  }
  // Count every consumer, including same-flight joins, until its promise settles. Cancelling
  // a client cannot recycle this permit. Stale-flight abort above still runs under pressure;
  // no replacement starts until the old consumers have actually released enough capacity.
  const waiter = tokenRefreshWaiters.tryAcquire();
  if (!waiter) throw new OAuthTokenRefreshBusyError();
  let unrestrictedRetry = false;
  try {
    if (existing && replacedStaleFlight) {
      // A replacement would wait for this owner's lock anyway. Keep its registry slot
      // through definitive-result cleanup and durable retirement, even with spare capacity.
      // In particular, an ignored abort must not mark a late explicit rejection as uncertain.
      await existing.promise.catch(() => {});
      if (tokenRefreshes.get(key) === existing && !retireSettledOAuthRefreshFlight(tokenRefreshes, key, existing)) {
        throw new OAuthTokenRefreshStaleError();
      }
      // Other admitted replacements may have resumed first and installed the next flight.
      existing = tokenRefreshes.get(key);
    }
    if (existing) {
      logOAuthEvent("OAuth refresh joined existing operation", { provider, accountId });
      const joined = await existing.promise;
      // The owner may not have required usability; a mark that landed meanwhile still rejects us.
      if (requireUsableAccount && getAccountCredentialWithStatus(provider, accountId)?.needsReauth) throw new OAuthAccountUnusableError(provider);
      return joined;
    }
    if (tokenRefreshes.size >= MAX_OAUTH_TOKEN_REFRESH_FLIGHTS) {
      for (const [staleKey, stale] of tokenRefreshes) {
        if (stale.abort.signal.reason instanceof OAuthTokenRefreshStaleError) retireSettledOAuthRefreshFlight(tokenRefreshes, staleKey, stale);
      }
      if (tokenRefreshes.size >= MAX_OAUTH_TOKEN_REFRESH_FLIGHTS) throw new OAuthTokenRefreshBusyError();
    }

    const abort = new AbortController();
    const flight: OAuthTokenRefreshFlight = {
      promise: undefined as unknown as Promise<OAuthAccessSnapshot>,
      startedAt: Date.now(),
      abort,
      flightId: randomUUID(),
      dispatched: false,
      requireUsable: requireUsableAccount,
    };
    const refresh = (async (): Promise<OAuthAccessSnapshot> => {
      const accessToken = await refreshAndPersistAccessToken(provider, accountId, def, cred, abort.signal, flight, replacedStaleFlight, authorityCurrent, requireUsableAccount);
      const persistedRow = getAccountCredentialWithStatus(provider, accountId);
      if (!persistedRow) throw new OAuthLoginRequiredError(provider);
      if (persistedRow.paused === true) throw new OAuthAccountPausedError();
      if (requireUsableAccount && persistedRow.needsReauth) throw new OAuthAccountUnusableError(provider);
      const persisted = persistedRow.credential;
      if (persisted.access !== accessToken) {
        throw new Error(`OAuth refresh persisted an unexpected access token for ${provider}`);
      }
      return accessSnapshot(provider, accountId, persisted, oauthProvider);
    })().catch(error => {
      if (abort.signal.reason instanceof OAuthTokenRefreshStaleError) throw abort.signal.reason;
      throw error;
    }).finally(() => {
      flight.settled = true;
      if (tokenRefreshes.get(key) !== flight) return;
      if (abort.signal.reason instanceof OAuthTokenRefreshStaleError) {
        retireSettledOAuthRefreshFlight(tokenRefreshes, key, flight);
      } else tokenRefreshes.delete(key);
    });
    flight.promise = refresh;
    tokenRefreshes.set(key, flight);
    return await refresh;
  } catch (error) {
    // An unrestricted caller that joined a usable-only owner is not bound by that owner's rejection.
    if (!requireUsableAccount && error instanceof OAuthAccountUnusableError) unrestrictedRetry = true;
    else if (authorityCurrent || !retryCancelledDiscovery || !(error instanceof OAuthDiscoveryRefreshCancelledError)) throw error;
  } finally { waiter.release(); }
  if (unrestrictedRetry) return resolveAccessSnapshotForAccount(provider, accountId, rejectedGeneration, false, oauthProvider, authorityCurrent, retryCancelledDiscovery);
  return resolveAccessSnapshotForAccount(provider, accountId, rejectedGeneration, requireUsableAccount, oauthProvider, undefined, false);
}

export async function getValidAccessTokenSnapshot(
  provider: string,
  options: { oauthProvider?: string } = {},
): Promise<OAuthAccessSnapshot> {
  const set = getAccountSet(provider);
  if (!set) throw new OAuthLoginRequiredError(provider);
  return resolveAccessSnapshotForAccount(provider, set.activeAccountId, undefined, false, options.oauthProvider);
}

/** Providers whose upstream-401 replay path may force a snapshot refresh. */
const FORCE_REFRESH_PROVIDERS = new Set([
  "workbuddy-ai",
  "xai",
  "github-copilot",
  "kiro",
  "google-antigravity",
  "cursor",
  "orcarouter-oauth",
  "devin",
  "dsh-account",
]);

export async function forceRefreshOAuthAccessSnapshot(
  rejected: OAuthAccessSnapshot,
): Promise<OAuthAccessSnapshot> {
  if (!FORCE_REFRESH_PROVIDERS.has(rejected.provider)) throw new UnsupportedOAuthProviderError(rejected.provider);
  return resolveAccessSnapshotForAccount(rejected.provider, rejected.accountId, rejected.generation);
}

/** Return a valid access token for the ACTIVE account, refreshing + persisting if expired. */
export async function getValidAccessToken(provider: string): Promise<string> {
  return (await getValidAccessTokenSnapshot(provider)).accessToken;
}

/**
 * Account-scoped token resolver (multiauth): refresh is single-flighted per
 * (provider, account), and the rotated credential is persisted for THAT account only —
 * a guardian refresh of a background account never switches the active account.
 */
export async function getValidAccessTokenForAccount(provider: string, accountId: string): Promise<string> {
  return (await resolveAccessSnapshotForAccount(provider, accountId)).accessToken;
}

/**
 * Account-scoped resolver returning the FULL snapshot, not just the bearer.
 *
 * A rotator that swaps only the token silently mixes credential generations: Antigravity pairs
 * an account-matched `projectId` with its token (see the pairing comment in
 * server/responses/core.ts), Kiro carries routing metadata, and Copilot's observed snapshot
 * carries an account-specific API origin. Reading those back from "whichever account is active"
 * after a rotation is exactly the mixing this returns in one piece to prevent (#2568).
 */
export async function getValidAccessSnapshotForAccount(
  provider: string,
  accountId: string,
  opts: { requireUsableAccount?: boolean; authorityCurrent?: () => boolean } = {},
): Promise<OAuthAccessSnapshot> {
  return resolveAccessSnapshotForAccount(provider, accountId, undefined, opts.requireUsableAccount === true, provider, opts.authorityCurrent);
}

/** Terminal refresh failures (revoked/rotated-away grants) — retrying cannot succeed. */
function isTerminalRefreshError(err: unknown): boolean {
  const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
  return msg.includes("invalid_grant")
    || msg.includes("refresh_token_reused")
    || msg.includes("revoked")
    // GitHub Copilot refresh surfaces allowlisted OAuth codes (github-copilot.ts):
    || msg.includes("access_denied")
    || msg.includes("expired_token");
}
function terminal(error:unknown):boolean{
  if (error instanceof ChatGptTokenRequestError) return false;
  if(error instanceof XaiTokenRequestError)return ["invalid_grant","refresh_token_reused","revoked_token"].includes(error.oauthError??"");
  if(error instanceof AnthropicTokenError)return (error.httpStatus===400||error.httpStatus===401)&&["invalid_grant","refresh_token_reused","revoked","revoked_token","refresh_token_revoked"].includes(error.oauthError??"");
  if(error instanceof KiroTokenRefreshError)return (error.httpStatus===400||error.httpStatus===401)&&error.oauthError!==undefined;
  if(error instanceof NousTokenError)return error.terminal===true||["invalid_grant","refresh_token_reused","revoked","revoked_token","expired_token"].includes(error.oauthError??"");
  // ChatGPT carries the pool classifier's verdict on the error itself: revoked and
  // expired grants are terminal; unknown/transient failures stay retryable.
  if(error instanceof ChatGptTokenError)return error.terminal;
  // Local durable-write/read/cleanup failures are operational, not credential
  // death: the provider credential was never rejected or consumed. Never mark
  // the account needsReauth for broken local persistence infrastructure.
  if (error instanceof RefreshIntentIOError || error instanceof OAuthRefreshIntentIOError) return false;
  return isTerminalRefreshError(error);
}

/**
 * True when the token endpoint definitively answered and rejected the request.
 *
 * The Anthropic adapter attaches an HTTP status only to an explicit non-success response,
 * which is the retryable rejection this PR handles. Everything else (timeout, dropped
 * connection, a body that could not be read or parsed, or a local persistence fault) leaves
 * the outcome unknown: the server may already have rotated the token, and a blind replay
 * could trip refresh-token-reuse revocation. Those cases must keep the refresh intent.
 *
 * Deliberately narrower than `terminal()`, which asks whether the CREDENTIAL is dead.
 * This asks the different question of whether the ATTEMPT is known to have failed.
 */
function definitivelyAnswered(error: unknown): boolean {
  if (error instanceof AnthropicTokenError) return error.httpStatus !== undefined;
  return false;
}

function authoritative(stored:OAuthCredentials,active:boolean,now:()=>number):OAuthCredentials{if(stored.source!=="local-cli")return stored;const disk=detectGrokCliToken();if(!disk)return stored;const allowed=isSameGrokIdentity(stored,disk)||(active&&!hasComparableGrokIdentity(stored,disk));return allowed&&shouldAdoptGrokGeneration(stored,disk,now(),REFRESH_SKEW_MS)?disk:stored;}
function merged(fresh: OAuthCredentials, previous: OAuthCredentials): OAuthCredentials {
  const identity = mergeAnthropicIdentity(fresh, previous, { sameGrant: true });
  return {
    ...fresh,
    ...identity,
    plan: mergeOAuthPlan(fresh, previous),
    organizationName: mergeOAuthOrganizationName({ ...fresh, ...identity }, previous),
    // Shared: a refresh function returns "local-cli" only when the credential it hands back
    // still is the local CLI's (Devin re-reading the CLI file, Meta Muse echoing its durable
    // CLI key). Relabelling that "oauth" would stop the next forced refresh from re-reading it.
    source: fresh.source === "local-cli" ? "local-cli"
      : previous.source === "local-cli" ? "oauth" : fresh.source ?? previous.source ?? "oauth",
    ...(fresh.projectId === undefined && previous.projectId ? { projectId: previous.projectId } : {}),
    ...(fresh.apiBaseUrl === undefined && previous.apiBaseUrl ? { apiBaseUrl: previous.apiBaseUrl } : {}),
    ...(fresh.email === undefined && previous.email ? { email: previous.email } : {}),
    ...(fresh.accountId === undefined && previous.accountId ? { accountId: previous.accountId } : {}),
    ...(fresh.kiro === undefined && previous.kiro ? { kiro: previous.kiro } : {}),
    ...(fresh.m365 === undefined && previous.m365 && fresh.accountId?.toLowerCase() === previous.accountId?.toLowerCase() ? { m365: previous.m365 } : {}),
  };
}
export async function refreshXaiAccountWithLock(provider:string,accountId:string,def:OAuthProviderDef,callerCredential:OAuthCredentials,deps:XaiRefreshDeps={}):Promise<string>{const writerGeneration=captureConfigGeneration();const now=deps.now??Date.now;const guard=await(deps.intentLock??createOAuthRefreshIntentLock(provider,accountId)).acquire();try{const row=getAccountCredentialWithStatus(provider,accountId);if(!row)throw new OAuthLoginRequiredError(provider);if(row.paused)throw new OAuthAccountPausedError();if(deps.requireUsableAccount&&row.needsReauth)throw new OAuthAccountUnusableError(provider);const stored=row.credential;const active=getAccountSet(provider)?.activeAccountId===accountId,candidate=authoritative(stored,active,now);if(credentialGeneration(candidate)!==credentialGeneration(callerCredential)&&candidate.expires>now()+REFRESH_SKEW_MS){if(credentialGeneration(candidate)!==credentialGeneration(stored)){const o=await mergeAccountCredential(provider,accountId,candidate,{expectedGeneration:credentialGeneration(stored),afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}}return candidate.access;}if(cached(provider,accountId,candidate,now))throw new OAuthLoginRequiredError(provider);const generation=credentialGeneration(candidate);try{const fresh=merged(await def.refresh(candidate.refresh,deps.signal),candidate);const o=await mergeAccountCredential(provider,accountId,fresh,{expectedGeneration:generation,afterPrePersistRead:deps.afterPrePersistRead,keepReauthMarkedAfterDispatch:!row.needsReauth});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));if(candidate.source==="local-cli")console.warn(XAI_LOCAL_CLI_DETACH_WARNING);return fresh.access;}catch(error){if(error instanceof OAuthMutationBusyError){permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));throw error;}if(!terminal(error))throw error;const failedAt=now();permanentRefreshFailures.set(verdictKey(provider,accountId,candidate),failedAt+XAI_PERMANENT_FAILURE_TTL_MS);sweepExpiredOnWrite(failedAt);await markAccountNeedsReauthIfGeneration(provider,accountId,generation,writerGeneration);throw new OAuthLoginRequiredError(provider);}}finally{guard.release();}}


/**
 * Preserve an already-rotated Nous refresh token (RT-B) after a terminal refresh
 * error (e.g. the returned access JWT lacked `inference:invoke`). The unusable
 * access token is NOT persisted as valid: the recovery credential carries an
 * empty access placeholder with a past expiry so it can never be routed, and the
 * account is marked needsReauth by the caller. Generation-safe: a concurrent
 * newer write wins and is never overwritten.
 */
async function preserveNousRotatedRefresh(
  provider: string,
  accountId: string,
  rotatedRefresh: string,
  expectedGeneration: string,
  previous: OAuthCredentials,
): Promise<{ kind: "persisted"; generation: string } | { kind: "superseded" } | { kind: "failed" }> {
  try {
    const recovery: OAuthCredentials = {
      refresh: rotatedRefresh,
      // Never persist the unusable access token: an empty placeholder with a
      // past expiry can never be observed as a valid credential.
      access: "",
      expires: 0,
      ...(previous.accountId ? { accountId: previous.accountId } : {}),
      ...(previous.email ? { email: previous.email } : {}),
      ...(previous.source ? { source: previous.source } : {}),
    };
    const outcome = await mergeAccountCredential(provider, accountId, recovery, { expectedGeneration });
    if (outcome.superseded) return { kind: "superseded" };
    // Return the exact generation this write produced, so the caller never
    // re-reads the store (a concurrent writer could otherwise supply a different
    // credential generation and be marked needsReauth by mistake).
    return { kind: "persisted", generation: credentialGeneration(recovery) };
  } catch (error) {
    // A store-mutation busy outcome is transient and retryable; surface it
    // unchanged so the caller can retry rather than treating it as a permanent
    // RT-B persistence failure.
    if (error instanceof OAuthMutationBusyError) throw error;
    return { kind: "failed" };
  }
}

export async function refreshAnthropicAccountWithLock(
  provider: string,
  accountId: string,
  def: OAuthProviderDef,
  callerCredential: OAuthCredentials,
  deps: AnthropicRefreshDeps = {},
): Promise<string> {
  if (!isAnthropicOAuthInstance(provider)) throw new UnsupportedOAuthProviderError(provider);
  const writerGeneration = captureConfigGeneration();
  const now = deps.now ?? Date.now;
  const guard = await (deps.intentLock ?? createOAuthRefreshIntentLock(provider, accountId)).acquire();
  try {
    const accountSet = getAccountSet(provider);
    const account = accountSet?.accounts.find(candidate => candidate.id === accountId);
    if (!accountSet || !account) throw new OAuthLoginRequiredError(provider);
    if (account.paused) throw new OAuthAccountPausedError();
    const stored = account.credential;
    const owns = captureAnthropicCredentialOwnerForInstance(provider, accountSet, accountId);
    const generation = credentialGeneration(stored);
    let pendingIntent = readOAuthRefreshIntent(provider, accountId);
    const observed = await newerClaudeCredentialForInstance(provider, stored, now(), deps.signal, deps.resolveIdentity,
      { accountId, accounts: accountSet.accounts });
    // Adoption defers its CLI re-read until it holds the writer lock, catching queued rotations.
    let diskVerified = observed.kind === "absent" || observed.kind === "adopt"
      ? undefined : await claudeCredentialGenerationCurrent(observed.diskGeneration, now);
    const assertOwner = (store: AuthStore, checkDisk = true) => {
      if (observed.kind !== "absent" && deps.signal?.aborted) throw new OAuthTokenRefreshStaleError();
      if (!owns(store, checkDisk ? diskVerified : undefined)) {
        if (store[provider]?.accounts.find(a => a.id === accountId)?.paused) throw new OAuthAccountPausedError();
        throw new OAuthTokenRefreshStaleError();
      }
    };
    assertOwner({ [provider]: getAccountSet(provider)! }, observed.kind !== "adopt");
    if (observed.kind === "adopt") {
      const diskGeneration = observed.diskGeneration;
      const outcome = await mergeAccountCredential(provider, accountId, observed.credential, {
        expectedGeneration: generation,
        afterPrePersistRead: async () => {
          await deps.afterPrePersistRead?.();
          diskVerified = await claudeCredentialGenerationCurrent(diskGeneration, now);
        },
        assertOwnership: store => {
          assertOwner(store);
          if (!claudeAdoptionSlotCurrent(store, provider, accountId, observed)) throw new OAuthTokenRefreshStaleError();
        },
      });
      // A superseding write did not adopt our candidate. Its pending intent remains owned by it.
      if (outcome.superseded) throw new OAuthTokenRefreshStaleError();
      if (pendingIntent) clearAnthropicRefreshIntentBestEffort(provider, accountId, pendingIntent);
      return observed.credential.access;
    }
    // Unknown rotation may have consumed this refresh token. Refuse without replay or changing health.
    if (observed.kind === "unresolved") throw new OAuthLoginRequiredError(provider);
    if (pendingIntent?.cleanupPending && pendingIntent.generation === generation) {
      resumeAnthropicRefreshIntentCleanup(provider, accountId, pendingIntent);
      pendingIntent = undefined;
    }
    if (observed.kind === "different"
      && (pendingIntent?.uncertain || pendingIntent?.generation === generation)) throw new OAuthLoginRequiredError(provider);
    if (!pendingIntent?.uncertain && pendingIntent?.generation === generation) {
      if (pendingIntent.staleOwner) throw new OAuthTokenRefreshStaleError();
      if (deps.replacedStaleFlight && pendingIntent.flightId === deps.replacedStaleFlight.flightId) {
        if (deps.replacedStaleFlight.dispatched) {
          markOAuthRefreshIntentStaleOwner(provider, accountId, generation, deps.replacedStaleFlight.flightId);
          throw new OAuthTokenRefreshStaleError();
        }
        if (!clearObservedAnthropicRefreshIntent(provider, accountId, pendingIntent)) {
          throw new OAuthTokenRefreshStaleError();
        }
        pendingIntent = undefined;
      }
    }
    if (pendingIntent?.uncertain || pendingIntent?.generation === generation) {
      await markAccountNeedsReauthIfGeneration(provider, accountId, generation, writerGeneration);
      throw new OAuthLoginRequiredError(provider);
    }
    if (pendingIntent && !clearObservedAnthropicRefreshIntent(provider, accountId, pendingIntent)) {
      throw new OAuthTokenRefreshStaleError();
    }
    if (account?.needsReauth) {
      throw new OAuthLoginRequiredError(provider);
    }
    if (credentialGeneration(stored) !== credentialGeneration(callerCredential) && stored.expires > now() + REFRESH_SKEW_MS) {
      return stored.access;
    }

    let refreshMayHaveReachedProvider = false;
    let attemptIntent: OAuthRefreshIntent | undefined;
    try {
      attemptIntent = writeOAuthRefreshIntent(provider, accountId, generation, now(), deps.flight?.flightId);
      if (deps.signal?.aborted) throw deps.signal.reason;
      // From this point on, even a synchronous client error is conservatively post-dispatch:
      // the provider may have received and rotated the refresh token before the caller learned
      // the outcome.
      refreshMayHaveReachedProvider = true;
      if (deps.flight) deps.flight.dispatched = true;
      const fresh = merged(await def.refresh(stored.refresh, deps.signal), stored);
      const outcome = await mergeAccountCredential(provider, accountId, fresh, {
        expectedGeneration: generation,
        afterPrePersistRead: deps.afterPrePersistRead,
        assertOwnership: store => { if (!owns(store, undefined, true)) throw new OAuthTokenRefreshStaleError(); },
      });
      if (outcome.superseded) {
        if (attemptIntent) clearAnthropicRefreshIntentBestEffort(provider, accountId, attemptIntent);
        if (outcome.stored.expires > now() + REFRESH_SKEW_MS) return outcome.stored.access;
        throw new OAuthLoginRequiredError(provider);
      }
      // The rotated credential is durable now. A cleanup failure must not turn that committed
      // success into a refresh failure; the old-generation intent remains a conservative guard.
      if (attemptIntent) clearAnthropicRefreshIntentBestEffort(provider, accountId, attemptIntent);
      return fresh.access;
    } catch (error) {
      if (error instanceof OAuthMutationBusyError || error instanceof OAuthTokenRefreshStaleError) throw error;
      if (!terminal(error)) {
        // A non-terminal failure tells the caller to retry, but the intent outlived it, so
        // the next attempt hit the pending-intent branch above and raised
        // OAuthLoginRequiredError. One 503 locked the account out of refresh until manual
        // re-auth even after upstream recovered.
        //
        // Clear only for proven pre-dispatch failure or an explicit HTTP rejection.
        // Other transport/body failures may follow rotation and keep the replay guard.
        const requestNotSent = !refreshMayHaveReachedProvider
          || (error instanceof AnthropicTokenError && error.requestNotSent);
        if ((requestNotSent || definitivelyAnswered(error)) && attemptIntent) {
          await clearAnthropicRefreshIntentForKnownFailure(
            provider,
            accountId,
            attemptIntent,
            requestNotSent ? "pre-dispatch" : "definitive-rejection",
            error,
          );
        }
        throw error;
      }
      await markAccountNeedsReauthIfGeneration(provider, accountId, generation, writerGeneration);
      if (attemptIntent) clearAnthropicRefreshIntentBestEffort(provider, accountId, attemptIntent);
      throw new OAuthLoginRequiredError(provider);
    }
  } finally {
    guard.release();
  }
}

export async function refreshGenericAccountWithLock(
  provider: string,
  accountId: string,
  def: OAuthProviderDef,
  callerCredential: OAuthCredentials,
  deps: GenericRefreshDeps = {},
): Promise<string> {
  const writerGeneration = captureConfigGeneration();
  logOAuthEvent("OAuth refresh started", { provider, accountId });
  const guard = await (deps.intentLock ?? createOAuthRefreshIntentLock(provider, accountId)).acquire();
  try {
    // Re-read under the lock: a pause committed while this caller waited must stop the refresh.
    const row = getAccountCredentialWithStatus(provider, accountId);
    if (!row) throw new OAuthLoginRequiredError(provider);
    if (row.paused) throw new OAuthAccountPausedError();
    // A usable-account caller rechecks needsReauth here: a mark committed while it waited must
    // stop the refresh before the stored refresh token is sent.
    if (deps.requireUsableAccount && row.needsReauth) throw new OAuthAccountUnusableError(provider);
    const stored = row.credential;
    if (
      credentialGeneration(stored) !== credentialGeneration(callerCredential)
      && stored.expires > Date.now() + REFRESH_SKEW_MS
    ) {
      logOAuthEvent("OAuth refresh joined existing operation", { provider, accountId });
      return stored.access;
    }
    const generation = credentialGeneration(stored);
    try {
      if (deps.authorityCurrent && !deps.authorityCurrent()) throw new OAuthDiscoveryRefreshCancelledError();
      const refreshed = await def.refresh(stored.refresh, deps.signal, stored, accountId);
      const fresh = merged(refreshed, stored);
      const outcome = await mergeAccountCredential(provider, accountId, fresh, {
        expectedGeneration: generation,
        afterPrePersistRead: deps.afterPrePersistRead,
        // A mark that landed after this flight read the row is newer than the refresh: keep it.
        keepReauthMarkedAfterDispatch: !row.needsReauth,
        ...(provider === "devin" ? { assertOwnership: (store: AuthStore) => {
          if (store[provider]?.accounts.find(row => row.id === accountId)?.paused) throw new OAuthAccountPausedError();
          assertDevinCliAdoptionOwnership(store, provider, accountId, refreshed);
        } } : {}),
      });
      if (outcome.superseded) {
        if (outcome.stored.expires > Date.now() + REFRESH_SKEW_MS) return outcome.stored.access;
        throw new OAuthLoginRequiredError(provider);
      }
      logOAuthEvent("OAuth credentials rotated and persisted", { provider, accountId });
      // Best-effort bookkeeping cleanup: the rotated credential is already
      // durably persisted. A failure to unlink the old-token intent file
      // (EACCES/EPERM/EBUSY/EROFS) must not turn a committed rotation into a
      // failed refresh. The stale intent keys the OLD token, which is no longer
      // stored, so leaving it behind blocks nothing and is safe. It must also
      // never route through the generic refresh error path (no needsReauth).
      if (provider === "nous") {
        try {
          clearNousRefreshIntent(stored.refresh);
        } catch (cleanupErr) {
          logOAuthEvent("OAuth refresh intent cleanup failed (non-fatal)", {
            provider,
            accountId,
            cause: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
          });
        }
      }
      return fresh.access;
    } catch (error) {
      if (error instanceof OAuthMutationBusyError) throw error;
      if (provider === "kiro" && error instanceof KiroTokenRefreshError && error.refreshAttention) {
        await markAccountRefreshAttentionIfGeneration(provider, accountId, generation, writerGeneration);
        throw error;
      }
      if (!terminal(error)) throw error;
      // Nous-specific failure-atomicity: a terminal refresh error that carries
      // an already-issued rotated refresh token (e.g. the access JWT lacked the
      // required `inference:invoke` scope) means the server consumed RT-A and
      // issued RT-B. RT-B must be preserved generation-safely BEFORE forcing
      // reauthentication; discarding it would lose the only usable refresh
      // material and force a full re-auth for no reason.
      if (provider === "nous" && error instanceof NousTokenError) {
        const rotated = error.getRotatedRefresh();
        if (rotated !== undefined && rotated !== stored.refresh) {
          const outcome = await preserveNousRotatedRefresh(
            provider,
            accountId,
            rotated,
            generation,
            stored,
          );
          if (outcome.kind === "persisted") {
            // RT-A's intent is cleared only after RT-B is durably persisted;
            // cleanup itself stays best-effort (a stale RT-A intent keys a token
            // that is no longer stored).
            try {
              clearNousRefreshIntent(stored.refresh);
            } catch (cleanupErr) {
              logOAuthEvent("OAuth refresh intent cleanup failed (non-fatal)", {
                provider,
                accountId,
                cause: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
              });
            }
            // Mark exactly the generation this write produced — never a
            // credential written by a concurrent login between the merge and
            // this step.
            await markAccountNeedsReauthIfGeneration(provider, accountId, outcome.generation, writerGeneration);
          } else {
            // RT-B persistence failed or a newer generation superseded it:
            // never clear RT-A's intent (RT-A was consumed), and mark the old
            // generation needsReauth (a no-op if a newer generation won).
            await markAccountNeedsReauthIfGeneration(provider, accountId, generation, writerGeneration);
          }
          throw new OAuthLoginRequiredError(provider);
        }
      }
      await markAccountNeedsReauthIfGeneration(provider, accountId, generation, writerGeneration);
      throw new OAuthLoginRequiredError(provider);
    }
  } finally {
    guard.release();
  }
}

async function refreshAndPersistAccessToken(
  provider: string,
  accountId: string,
  def: OAuthProviderDef,
  cred: OAuthCredentials,
  signal?: AbortSignal,
  flight?: OAuthRefreshFlightEvidence,
  replacedStaleFlight?: OAuthRefreshFlightEvidence,
  authorityCurrent?: () => boolean,
  requireUsableAccount = false,
): Promise<string> {
  if (provider === "xai") return refreshXaiAccountWithLock(provider, accountId, def, cred, { signal, requireUsableAccount });
  if (isAnthropicOAuthInstance(provider)) return refreshAnthropicAccountWithLock(provider, accountId, def, cred, { signal, flight, replacedStaleFlight });
  return refreshGenericAccountWithLock(provider, accountId, def, cred, { signal, authorityCurrent, requireUsableAccount });
}

/** Resolve discovery credentials only for the caller-owned configured OAuth row. */
export async function getModelsOAuthAccessSnapshot(name: string, prov: OcxProviderConfig | undefined): Promise<OAuthAccessSnapshot> {
  if (!mayResolveModelsOAuth(name, prov)) throw new OAuthLoginRequiredError(name);
  return getValidAccessTokenSnapshot(name);
}

/** Shared /models auth resolver; custom key rows keep their own key, including omitted authMode. */
export async function resolveModelsAuthToken(name: string, prov: OcxProviderConfig): Promise<string | undefined> {
  if (prov.authMode === "forward") return undefined;
  if (prov.authMode === "oauth") {
    try {
      return (await getModelsOAuthAccessSnapshot(name, prov)).accessToken;
    } catch {
      return undefined;
    }
  }
  return resolveProviderApiKey(prov.apiKey);
}

function modelDiscoveryTransportSeed(providerName: string, prov: OcxProviderConfig): OcxProviderConfig {
  const entry = getProviderRegistryEntry(providerName);
  if (
    prov.authMode !== "oauth"
    || entry?.authKind !== "oauth"
    || entry.allowBaseUrlOverride === true
    || /\{[^}]*\}/.test(entry.baseUrl)
    || !providerMatchesRegistryTransport(providerName, prov)
  ) {
    return prov;
  }
  // Normal routing pins fixed OAuth presets before adapter-specific transport resolution.
  // Discovery must do the same so a stale or modified config baseUrl never receives a token.
  return { ...prov, adapter: entry.adapter, baseUrl: entry.baseUrl };
}

/**
 * Provider-correct model-discovery request (URL + headers), so both model-listing paths fetch the
 * LIVE catalog correctly per adapter. Anthropic is the special case: its endpoint is `/v1/models`
 * (not `/models`), it needs `anthropic-version`, and it authenticates with `x-api-key` by default
 * (or `Authorization: Bearer` when `apiKeyTransport = "bearer"`), plus the OAuth beta for oauth
 * mode — not a bare Bearer. Google (ai-studio mode)
 * is the other special case: `x-goog-api-key` + `/v1beta/models`, returning `{ models: [...] }`.
 * The catalog authority gate intentionally degrades that non-OpenAI shape to stale/static data.
 * Antigravity uses its CCA `:fetchAvailableModels` RPC; everyone else uses the OpenAI-style
 * `/models` + Bearer with a `{ data: [{ id, owned_by? }] }` response.
 */
export interface ModelsRequestObservedAuth {
  readonly workbuddy?: import("./types").WorkBuddyOAuthMetadata;
  readonly oauthApiBaseUrl?: string;
}

export function buildModelsRequest(
  prov: OcxProviderConfig,
  apiKey: string | undefined,
  providerName = "",
  observedAuth?: ModelsRequestObservedAuth,
): { method?: "POST"; url: string; headers: Record<string, string> } {
  if (providerName === "workbuddy-ai" || prov.adapter === "workbuddy-ai") {
    const allowed = mayResolveModelsOAuth(providerName, prov);
    return { url: WORKBUDDY_CONFIG_URL, headers: workBuddyHeaders(allowed && observedAuth?.workbuddy ? apiKey : undefined, observedAuth?.workbuddy) };
  }
  const authorizedTarget = captureModelsOAuthTarget(providerName, prov);
  if (prov.authMode === "oauth" && !mayResolveModelsOAuth(providerName, prov)) apiKey = undefined;
  const transportSeed = modelDiscoveryTransportSeed(providerName, prov);
  const copilotApiBaseUrl = observedAuth === undefined
    ? (providerName === "github-copilot" ? getOAuthCredentialApiBaseUrl(providerName) : undefined)
    : observedAuth.oauthApiBaseUrl;
  const effectiveProvider = resolveProviderTransport(
    providerName,
    transportSeed,
    undefined,
    copilotApiBaseUrl,
  );
  // Model discovery is an upstream request like any other, so it carries the same registry
  // static headers the inference path does. Without this a provider is identified correctly
  // when it answers a completion but anonymously when it lists its own models, which is the
  // kind of split fingerprint an upstream rate limiter reads as two different clients.
  const registryStaticHeaders = providerMatchesRegistryTransport(providerName, effectiveProvider)
    ? getProviderRegistryEntry(providerName)?.staticHeaders
    : undefined;
  const headers: Record<string, string> = {
    ...(mergeRegistryStaticHeaders(registryStaticHeaders, effectiveProvider.headers) ?? {}),
  };
  const discoveryUrl = (defaultUrl: string): string => resolveProviderModelDiscoveryUrl(
    providerName,
    prov,
    effectiveProvider.baseUrl,
    defaultUrl,
  );
  const guarded = <T extends { url: string; headers: Record<string, string> }>(request: T): T =>
    guardModelsOAuthRequest(providerName, prov, request, authorizedTarget);
  if (effectiveGoogleMode(providerName, effectiveProvider) === "cloud-code-assist") {
    headers.Accept = "application/json";
    headers["Content-Type"] = "application/json";
    // CLI UA: CCA lists Gemini 4 Argon's wire ids only to the CLI client family. Inference keeps
    // choosing per wire model (antigravityUserAgentForWireModel).
    headers["User-Agent"] = ANTIGRAVITY_DISCOVERY_UA;
    if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
    return guarded({
      method: "POST" as const,
      url: discoveryUrl(`${effectiveProvider.baseUrl.replace(/\/+$/, "")}/v1internal:fetchAvailableModels`),
      headers,
    });
  }
  if (effectiveGoogleMode(providerName, effectiveProvider) === "ai-studio") {
    // Generative Language API: API key goes in x-goog-api-key (never Authorization: Bearer),
    // models live under /v1beta (v1 misses preview models), and pageSize maxes at 1000 —
    // enough to list everything without a pageToken loop. Vertex/antigravity keep the
    // generic branch (they fall back to their static model lists).
    if (apiKey) headers["x-goog-api-key"] = apiKey;
    return guarded({ url: discoveryUrl(`${effectiveProvider.baseUrl}/v1beta/models?pageSize=1000`), headers });
  }
  if (effectiveProvider.adapter === "anthropic") {
    const base = effectiveProvider.baseUrl.replace(/\/v1\/?$/, "");
    headers["anthropic-version"] = "2023-06-01";
    if (effectiveProvider.authMode === "oauth") {
      headers["anthropic-beta"] = ANTHROPIC_OAUTH_BETA;
      if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
    } else if (apiKey) {
      if (effectiveProvider.apiKeyTransport === "bearer") headers["Authorization"] = `Bearer ${apiKey}`;
      else headers["x-api-key"] = apiKey;
    }
    return guarded({ url: discoveryUrl(`${base}/v1/models?limit=1000`), headers });
  }
  if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
  return guarded({ url: discoveryUrl(providerModelsUrl(effectiveProvider.baseUrl)), headers });
}

/**
 * Refresh OAuth-managed provider presets (`models`, `noReasoningModels`, and a stale `defaultModel`)
 * from the registry so a proxy update that revises a provider's models — e.g. dropping deprecated
 * Claude snapshots or adding a new grok endpoint not in the live `/models` — reaches EXISTING
 * configs on the next `ocx start`, instead of only fresh installs. The live `/models` fetch stays
 * the primary source; this keeps the static fallback (and models-not-in-/models) current.
 *
 * Only touches providers that are registry-managed AND still `authMode: "oauth"`. Preset fields
 * are refreshed, while the registry's `liveModels` default is normally filled only when no value
 * is stored. Persists + returns true when anything changed.
 */
function cloneProviderField(value: unknown): unknown {
  if (Array.isArray(value)) return [...value];
  if (value && typeof value === "object") return JSON.parse(JSON.stringify(value));
  return value;
}

const OAUTH_RECONCILE_FIELDS: (keyof OcxProviderConfig)[] = [
  "models",
  "contextWindow",
  "modelContextWindows",
  "defaultMaxOutputTokens",
  "modelMaxOutputTokens",
  "modelInputModalities",
  "noReasoningModels",
  "noVisionModels",
  "reasoningEfforts",
  "modelReasoningEfforts",
  "reasoningEffortMap",
  "modelReasoningEffortMap",
  "noTemperatureModels",
  "noTopPModels",
  "noStopModels",
  "noPenaltyModels",
  "autoToolChoiceOnlyModels",
  "preserveReasoningContentModels",
];
// `requiresReasoningPlaceholderModels` is deliberately NOT reconciled here: no
// OAuth preset seeds it, so the delete-when-preset-undefined branch would wipe
// an explicit user opt-out (`[]`) on every startup. Registry seeds still reach
// existing rows through enrichProviderFromRegistry, which is fill-only and
// preserves explicit saved values.

/**
 * Saved limits and per-model declarations are operator input, including Copilot's
 * long-context evidence. Presets supply missing defaults, not replacements for
 * configured entries. Catalog rosters, capability lists and seeded reasoning
 * ladders still refresh below; unseeded tiers remain operator input.
 * Without provenance, a saved seed cannot be distinguished from an operator edit.
 */
const OAUTH_OPERATOR_MAP_FIELDS: ReadonlySet<keyof OcxProviderConfig> = new Set([
  "modelContextWindows", "modelMaxOutputTokens", "modelInputModalities",
  "modelReasoningEffortMap", "reasoningEffortMap",
]);
const OAUTH_OPERATOR_LIMIT_FIELDS: ReadonlySet<keyof OcxProviderConfig> = new Set([
  "contextWindow", "defaultMaxOutputTokens",
]);
const OAUTH_PRESERVE_WHEN_PRESET_UNSET: ReadonlySet<keyof OcxProviderConfig> = new Set([
  "reasoningEfforts",
]);

const GOOGLE_ANTIGRAVITY_PROVIDER = "google-antigravity";
const GOOGLE_ANTIGRAVITY_LIVE_DISCOVERY_VERSION = 2 as const;

/** Only migrate the three-model experimental seed; an operator's later `liveModels: false` wins. */
function isLegacyCommandCodeStaticCatalog(provider: OcxProviderConfig): boolean {
  return provider.liveModels === false
    && provider.defaultModel === "deepseek-v4-flash"
    && JSON.stringify(provider.models) === JSON.stringify(["deepseek-v4-flash", "kimi-k3", "glm-5.2"]);
}

function isLegacyAntigravityStaticCatalog(provider: OcxProviderConfig): boolean {
  // A fingerprint of the shape version 1 actually shipped, NOT of the current registry.
  // These literals must stay frozen as the model list moves on: matching them is how we
  // know the row is the untouched v1 seed rather than a user's own selection.
  return provider.liveModels === false
    && provider.adapter === "google"
    && provider.baseUrl === "https://daily-cloudcode-pa.googleapis.com"
    && provider.authMode === "oauth"
    && provider.googleMode === "cloud-code-assist"
    && provider.defaultModel === "gemini-3.6-flash"
    && JSON.stringify(provider.models) === JSON.stringify([
      "gemini-3.6-flash",
      "gemini-3.1-pro",
      "gemini-3.1-flash-image",
      "claude-sonnet-4-6",
      "claude-opus-4-6-thinking",
      "gpt-oss-120b-medium",
    ]);
}

/** Refresh registry-owned catalog fields while preserving valid operator selections. */
function applyOAuthPresetCatalog(
  provider: OcxProviderConfig,
  preset: OcxProviderConfig,
): void {
  for (const field of OAUTH_RECONCILE_FIELDS) {
    if (JSON.stringify(provider[field]) === JSON.stringify(preset[field])) continue;
    if (field === "modelReasoningEfforts") {
      // Known unmarked ladders are saved catalog seeds, not evidence of an
      // operator override. Preserve unseeded rows and explicit authoritative
      // overrides; refresh the preset-owned rows (e.g. xAI's effort ladder).
      const authoritative = provider.modelReasoningEffortsAuthoritative === true;
      provider.modelReasoningEfforts = mapFill(
        authoritative ? preset.modelReasoningEfforts : provider.modelReasoningEfforts,
        authoritative ? provider.modelReasoningEfforts : preset.modelReasoningEfforts,
      )[0];
    } else if (OAUTH_OPERATOR_MAP_FIELDS.has(field)) {
      provider[field] = mapFill<unknown>(
        preset[field] as Record<string, unknown> | undefined,
        provider[field] as Record<string, unknown> | undefined,
      )[0] as never;
    } else if (OAUTH_OPERATOR_LIMIT_FIELDS.has(field) && provider[field] !== undefined) {
      continue;
    } else if (preset[field] !== undefined) {
      provider[field] = cloneProviderField(preset[field]) as never;
    } else if (!OAUTH_PRESERVE_WHEN_PRESET_UNSET.has(field)) {
      delete provider[field];
    }
  }
  if (provider.liveModels === undefined && preset.liveModels !== undefined) {
    provider.liveModels = preset.liveModels;
  }
  // Heal only a selection that the refreshed static catalog no longer contains. Providers
  // with live discovery do not expose an enumerable account catalog here, so their saved
  // default remains operator-owned.
  if (
    provider.liveModels !== true &&
    provider.defaultModel
    && preset.defaultModel
    && preset.models
    && preset.models.length > 0
    && !(provider.models ?? []).includes(provider.defaultModel)
  ) {
    provider.defaultModel = preset.defaultModel;
  }
}

/** Promote only the versioned canonical static seed; unmarked `liveModels: false` remains user intent. */
function migrateLegacyAntigravityStaticCatalog(config: OcxConfig): boolean {
  if (config.googleAntigravityStaticCatalogVersion !== 1) return false;
  const provider = config.providers[GOOGLE_ANTIGRAVITY_PROVIDER];
  if (provider && isLegacyAntigravityStaticCatalog(provider)) provider.liveModels = true;
  config.googleAntigravityStaticCatalogVersion = GOOGLE_ANTIGRAVITY_LIVE_DISCOVERY_VERSION;
  return true;
}

interface OAuthReconcileProjection {
  config: OcxConfig;
  changed: boolean;
  touchedProviders: string[];
  touchedAntigravityVersion: boolean;
}

/** Pure projection over a clone: apply every reconciliation rule and report what it touched. */
function projectOAuthProviderReconciliation(config: OcxConfig): OAuthReconcileProjection {
  const projected = structuredClone(config);
  const touchedProviders = new Set<string>();
  const beforeAntigravity = JSON.stringify(projected.providers[GOOGLE_ANTIGRAVITY_PROVIDER]);
  const beforeAntigravityVersion = projected.googleAntigravityStaticCatalogVersion;
  let changed = migrateLegacyAntigravityStaticCatalog(projected);
  if (JSON.stringify(projected.providers[GOOGLE_ANTIGRAVITY_PROVIDER]) !== beforeAntigravity) {
    touchedProviders.add(GOOGLE_ANTIGRAVITY_PROVIDER);
  }
  const touchedAntigravityVersion = projected.googleAntigravityStaticCatalogVersion !== beforeAntigravityVersion;

  for (const [name, prov] of Object.entries(projected.providers)) {
    if (name === "anthropic2" && !anthropicInstanceRowShapeMatches(name, prov)) continue;
    const beforeProvider = JSON.stringify(prov);
    const def = OAUTH_PROVIDERS[name];
    if (name === "command-code" && isLegacyCommandCodeStaticCatalog(prov)) {
      // The former experimental preset was the exact three-model seed above. It was not a user
      // choice to disable discovery, so promote only that shape to the account live catalog.
      prov.liveModels = true;
    }
    if (def && prov.authMode === "oauth") {
      const preset = def.providerConfig;
      applyOAuthPresetCatalog(prov, preset);
    }
    if (JSON.stringify(prov) !== beforeProvider) {
      changed = true;
      touchedProviders.add(name);
    }
  }

  return {
    config: projected,
    changed,
    touchedProviders: [...touchedProviders],
    touchedAntigravityVersion,
  };
}

/**
 * Copy only the keys the projection actually touched back onto the caller's live object.
 *
 * Deliberately key-by-key rather than a wholesale clear-and-reassign: a live reference held
 * elsewhere to an untouched provider sub-object must survive startup reconciliation.
 */
function adoptOAuthReconciliation(config: OcxConfig, projection: OAuthReconcileProjection): void {
  for (const name of projection.touchedProviders) {
    const provider = projection.config.providers[name];
    if (provider) config.providers[name] = structuredClone(provider);
    else delete config.providers[name];
  }
  if (projection.touchedAntigravityVersion) {
    config.googleAntigravityStaticCatalogVersion = projection.config.googleAntigravityStaticCatalogVersion;
  }
}

/**
 * Union the keys the on-disk rebase touched with the keys the live projection touched.
 *
 * The rebase runs against the persisted snapshot, which may already carry a reconciliation
 * another process committed. Adopting only its touched set would leave the live object stale
 * for a key it decided was already correct on disk.
 */
function withOAuthReconciliationTouchedKeys(
  projection: OAuthReconcileProjection,
  required: OAuthReconcileProjection,
): OAuthReconcileProjection {
  return {
    ...projection,
    touchedProviders: [...new Set([...projection.touchedProviders, ...required.touchedProviders])],
    touchedAntigravityVersion: projection.touchedAntigravityVersion || required.touchedAntigravityVersion,
  };
}

/**
 * Refresh OAuth provider presets against the registry, rebasing the write on the persisted config.
 *
 * This runs on the boot path (`startServer`), so persistence failure must never be fatal: a
 * missing, malformed or contended config degrades to a warning plus an in-memory adopt, exactly
 * as every other `mutatePersistedConfig` consumer does (`src/storage/policy.ts`,
 * `src/codex/plan-from-token.ts`, `src/server/management/agent-settings-routes.ts`). Throwing
 * here would take the whole proxy down over a config file the operator can still repair.
 */
export function reconcileOAuthProviders(config: OcxConfig, persist = true): boolean {
  const projection = projectOAuthProviderReconciliation(config);
  if (!projection.changed) return false;
  if (!persist) {
    adoptOAuthReconciliation(config, projection);
    return true;
  }
  const outcome = mutatePersistedConfig(fresh => {
    const next = projectOAuthProviderReconciliation(fresh);
    if (next.changed) adoptOAuthReconciliation(fresh, next);
    return { changed: next.changed, value: next };
  });
  if (outcome.status === "unavailable") {
    console.warn(
      `[opencodex] OAuth provider reconciliation could not be persisted (${outcome.reason}); `
      + "applying it in memory for this run only.",
    );
    adoptOAuthReconciliation(config, projection);
    return true;
  }
  adoptOAuthReconciliation(config, withOAuthReconciliationTouchedKeys(outcome.value, projection));
  return true;
}

const OAUTH_LOGIN_OWNED_PROVIDER_FIELDS = [
  "adapter",
  "baseUrl",
  "authMode",
  "headers",
  "apiKeyTransport",
  "responsesPath",
  "googleMode",
  "keyOptional",
] as const satisfies readonly (keyof OcxProviderConfig)[];

/** Add/refresh only an OAuth provider's login-owned config fields (does not persist). */
export function upsertOAuthProvider(config: OcxConfig, provider: string, row = provider): void {
  assertAnthropicInstanceLoginConfig(config, provider);
  if (provider === "chatgpt") return;
  const def = OAUTH_PROVIDERS[provider];
  if (!def || (row !== provider && !isOAuthCredentialSiblingOf(row, provider))) { if (def) throw new UnsupportedOAuthProviderError(row); return; }
  if (provider === GOOGLE_ANTIGRAVITY_PROVIDER) migrateLegacyAntigravityStaticCatalog(config);
  const namespaceCollision = codexAccountNamespaceProviderCollisionError(config.codexAccountNamespaces, row);
  if (namespaceCollision) throw new OAuthProviderNamespaceCollisionError(namespaceCollision);
  const existing = config.providers[row];
  const providerConfig = row !== provider ? oauthConfig(row) : def.resolveProviderConfig?.(config) ?? def.providerConfig;
  // Clone operator state, including xAI wire choices and their migration version.
  const next: OcxProviderConfig = structuredClone(existing ?? providerConfig);
  for (const field of OAUTH_LOGIN_OWNED_PROVIDER_FIELDS) {
    const value = providerConfig[field];
    if (value === undefined) delete next[field];
    else next[field] = structuredClone(value) as never;
  }
  // A login may activate a different account. CCA dispatch must take that account's
  // project from its credential snapshot, never retain the previous account's project.
  if (next.googleMode === "cloud-code-assist") delete next.project;
  // Login used to rebuild the whole row from the preset, so catalog data refreshed
  // immediately. Keep that timing without overwriting unrelated operator-owned fields.
  applyOAuthPresetCatalog(next, providerConfig);
  // The per-model Copilot tier is operator intent, not account or preset metadata.
  if (existing?.modelContextTiers !== undefined) {
    next.modelContextTiers = structuredClone(existing.modelContextTiers);
  }
  // The original Command Code seed was an implementation-owned static catalog, not an
  // operator opt-out. Promote that exact legacy shape when OAuth login refreshes the row.
  if (provider === "command-code" && existing && isLegacyCommandCodeStaticCatalog(existing)) {
    next.liveModels = def.providerConfig.liveModels;
  }
  // OAuth-only providers must never retain credentials for a different auth mechanism.
  delete next.apiKey;
  delete next.apiKeyPool;
  delete (next as unknown as Record<string, unknown>).azureCredential;
  if (existing && getProviderRegistryEntry(row)?.allowKeyAuthOverride === true) {
    // Retain stored key billing intent without resolving env references in the login process.
    // An explicit OAuth choice stays OAuth even when usable key material is retained.
    // Shared sanitizeApiKeyValue trim / no-CRLF checks from api-key pool writes.
    let storedApiKey = sanitizeApiKeyValue(existing.apiKey);
    const storedApiKeyPool = preservableApiKeyPool(existing.apiKeyPool);
    // Retain all-paused pools without activating any paused credential during login.
    if (storedApiKeyPool?.some(entry => entry.key === storedApiKey && entry.disabled)) storedApiKey = undefined;
    if (storedApiKey === undefined) storedApiKey = storedApiKeyPool?.find(entry => !entry.disabled)?.key;
    if (storedApiKeyPool) next.apiKeyPool = storedApiKeyPool;
    if (storedApiKey !== undefined) {
      const pool = storedApiKeyPool ? [...storedApiKeyPool] : [];
      // Keep routing and listProviderApiKeys in sync: never leave a hidden active key that
      // is absent from the pool (listing would fall back to pool[0] as "active").
      if (!pool.some(entry => entry.key === storedApiKey)) {
        pool.push({ id: apiKeyPoolEntryId(storedApiKey), key: storedApiKey });
      }
      next.apiKey = storedApiKey;
      next.apiKeyPool = pool;
      const previousModeAllowsKey = existing.authMode === "key" || existing.authMode === undefined;
      if (previousModeAllowsKey) next.authMode = "key";
    }
  }
  initializeProviderModelSelection(row, next, existing, config);
  config.providers[row] = next;
}

interface RunLoginDeps {
  saveCredential?: typeof saveCredential;
  saveCredentialWithReceipt?: typeof saveCredentialWithReceipt;
  saveAccountCredential?: typeof saveAccountCredential;
  loadConfig?: typeof loadConfig;
  saveConfig?: typeof saveConfig;
  mutatePersistedConfig?: typeof mutatePersistedConfig;
  settleKiroLoginTransaction?: typeof settleKiroLoginTransaction;
  rollbackCredentialWrite?: typeof rollbackCredentialWriteIfMatch;
  assertCurrentOwner?: () => void;
  /** Told which account row the credential write landed in (an id, never the credential). */
  onAccountPersisted?: (accountId: string) => void;
}

/** Run the login flow, persist the credential + upsert the provider entry to disk, return cred. */
export async function runLogin(
  provider: string,
  ctrl: OAuthController,
  opts?: LoginOpts,
  deps: RunLoginDeps = {},
): Promise<OAuthCredentials> {
  const def = OAUTH_PROVIDERS[provider];
  if (!def) throw new UnsupportedOAuthProviderError(provider);
  const row = opts?.publishRow ?? provider;
  if (row !== provider && !isOAuthCredentialSiblingOf(row, provider)) throw new UnsupportedOAuthProviderError(row);
  const loadLatestConfig = deps.loadConfig ?? loadConfig;
  const saveLatestConfig = deps.saveConfig ?? saveConfig;
  const initialBConfigState = provider === "anthropic2" ? observeInitialConfigState() : undefined;
  let preflightConfig = provider !== "chatgpt" ? loadLatestConfig() : undefined;
  if (provider === "anthropic2" && preflightConfig && initialBConfigState === "missing") {
    // Explicit first-login onboarding may create the ordinary defaults, without a B row.
    // The create-only owner never replaces a concurrent file. Reload its winner before login;
    // once the browser starts, later deletion remains a publication refusal, not recreation.
    if (initializePersistedConfigIfMissing(getDefaultConfig()) === "invalid") {
      throw new OAuthProviderPublicationError(provider, false);
    }
    preflightConfig = loadLatestConfig();
  }
  if (preflightConfig) {
    assertAnthropicInstanceLoginConfig(preflightConfig, provider);
    const namespaceCollision = codexAccountNamespaceProviderCollisionError(
      preflightConfig.codexAccountNamespaces,
      row,
    );
    if (namespaceCollision) throw new OAuthProviderNamespaceCollisionError(namespaceCollision);
  }
  if (provider === "anthropic2" && observeInitialConfigState() !== "exists") {
    throw new OAuthProviderPublicationError(provider, false);
  }
  // loginKiro keys its pending CLI-session transaction by object identity. Keep this exact object
  // for settlement even when source normalization below creates a derived credential object.
  const shouldRollbackKiroAccounts = provider === "kiro" && opts?.forceLogin === true;
  let kiroCredentialWrite: OAuthCredentialWriteReceipt | null = null;
  const loginProviderConfig = preflightConfig
    ? (def.resolveProviderConfig?.(preflightConfig) ?? preflightConfig.providers[provider] ?? def.providerConfig)
    : def.providerConfig;
  if (provider === "kiro" && opts?.reauthAccountId
    && getAccountSet("kiro")?.accounts.some(a => a.id === opts.reauthAccountId && a.loginOrigin === "kiro-device")) {
    throw new Error("Native Kiro device accounts cannot be reauthenticated with kiro-cli; remove and re-add the account.");
  }
  const rawCred = await def.login(ctrl, opts, loginProviderConfig);
  const cred: OAuthCredentials = rawCred.source ? rawCred : { ...rawCred, source: "oauth" };
  if (isAnthropicOAuthInstance(provider)) assertAnthropicCredentialSource(provider, cred);
  const settleKiroTransaction = deps.settleKiroLoginTransaction ?? settleKiroLoginTransaction;
  try {
    deps.assertCurrentOwner?.();
    // Validate the provider row before credential persistence. A namespace claimed during the
    // credential write is handled again below before the latest row is re-upserted.
    if (provider !== "chatgpt") {
      const preCommitConfig = loadLatestConfig();
      upsertOAuthProvider(preCommitConfig, provider, row);
    }
    if (opts?.reauthAccountId) {
      const existing = precheckOAuthReauthIdentity(provider, opts.reauthAccountId, cred);
      const assertAccounts = isAnthropicOAuthInstance(provider) ? anthropicReauthSlotGuard(opts.reauthAccountId, cred,
        await observeAnthropicSlotOrganizations(getAccountSet(provider)?.accounts ?? [], cred, opts.reauthAccountId)) : undefined;
      const reauthCred = withMergedOAuthLabels(cred, existing);
      const written = await (deps.saveAccountCredential ?? saveAccountCredential)(provider, opts.reauthAccountId, reauthCred, {
        assertBeforePersist: deps.assertCurrentOwner,
        assertAccounts,
        rotateLoginId: true,
        clearAutomaticPause: true,
      });
      // A reauth whose account was deleted meanwhile wrote nothing and owns no row to report.
      if (written) deps.onAccountPersisted?.(opts.reauthAccountId);
    } else {
      const saveOptions = {
        preserveIdentityless: opts?.forceLogin === true || (provider === "anthropic" && cred.source === "local-cli"),
        assertBeforePersist: deps.assertCurrentOwner,
      };
      if (shouldRollbackKiroAccounts && !deps.saveCredential) {
        kiroCredentialWrite = await (deps.saveCredentialWithReceipt ?? saveCredentialWithReceipt)(
          provider,
          cred,
          saveOptions,
        );
        if (kiroCredentialWrite) deps.onAccountPersisted?.(kiroCredentialWrite.accountId);
      } else {
        // The receipt names the row written; a stubbed save may return none.
        const receipt = await (deps.saveCredential ?? saveCredential)(provider, cred, saveOptions);
        if (receipt) deps.onAccountPersisted?.(receipt.accountId);
      }
    }
    if (provider !== "chatgpt") {
      // Re-run against post-credential state so same-provider API-key additions, removals,
      // and active-key switches survive. A late namespace claim wins over provider creation.
      if (provider === "anthropic2") {
        const publication = (deps.mutatePersistedConfig ?? mutatePersistedConfig)(latestConfig => {
          assertAnthropicInstanceLoginConfig(latestConfig, provider, true);
          if (codexAccountNamespaceProviderCollisionError(latestConfig.codexAccountNamespaces, provider)) {
            throw new OAuthProviderPublicationError(provider);
          }
          upsertOAuthProvider(latestConfig, provider);
          return { changed: true, value: undefined };
        });
        if (publication.status === "unavailable") throw new OAuthProviderPublicationError(provider);
      } else {
        const latestConfig = loadLatestConfig();
        const lateCollision = codexAccountNamespaceProviderCollisionError(
          latestConfig.codexAccountNamespaces,
          row,
        );
        if (lateCollision) {
          throw new OAuthProviderPublicationError();
        }
        upsertOAuthProvider(latestConfig, provider, row);
        saveLatestConfig(latestConfig);
      }
    }
  } catch (error) {
    const errors: unknown[] = [error];
    if (kiroCredentialWrite) {
      try {
        await (deps.rollbackCredentialWrite ?? rollbackCredentialWriteIfMatch)(kiroCredentialWrite);
      } catch (rollbackError) {
        errors.push(rollbackError);
      }
    }
    try {
      settleKiroTransaction(rawCred, false);
    } catch (restoreError) {
      errors.push(restoreError);
    }
    if (errors.length > 1) {
      throw new AggregateError(
        errors,
        "Kiro login persistence failed and the previous Kiro CLI session could not be restored.",
      );
    }
    throw error;
  }
  settleKiroTransaction(rawCred, true);
  if (provider !== "chatgpt") {
    try {
      const { clearModelCache } = await import("../codex/model-cache");
      const { clearGatherRoutedModelsInflight } = await import("../codex/catalog/routed-gather");
      clearModelCache(provider);
      clearGatherRoutedModelsInflight();
      const { clearAccountQuotaCache, clearProviderQuotaCache } = await import("../providers/quota");
      clearProviderQuotaCache();
      clearAccountQuotaCache(provider);
    } catch {
      // Optional state modules may be unavailable in tightly scoped unit tests.
    }
  }
  return cred;
}

/**
 * GUI async login: start the flow, return the auth URL EARLY (the flow keeps running in the
 * background until the callback server captures the redirect), with a concurrency guard and an
 * error surfaced via getLoginStatus().
 *
 * Manual fallback: when the browser cannot reach the loopback callback (remote GUI, SSH, blocked
 * localhost), the GUI can POST the final redirect URL or authorization code via
 * submitManualLoginCode(), which feeds OAuthController.onManualCodeInput.
 */

export interface OAuthAccountSummary {
  id: string;
  alias?: string;
  email?: string;
  active: boolean;
  needsReauth?: boolean;
  needsReauthReason?: "verify_account"; needsReauthCause?: "tos_violation";
  expiresAt?: number;
  /**
   * Subscription tier, mirroring the field the OpenAI/Codex provider reports, so a consumer
   * weighting a multi-account pool by seat size needs no per-provider branching (#3777).
   *
   * Always present and explicitly `null` when the tier is unknown. The distinction matters:
   * an ABSENT key means the proxy is too old to report a tier at all, while `null` means this
   * version looked and upstream did not say. Omitting it would make those indistinguishable and
   * invite a consumer to assume a tier.
   *
   * Reports the validated upstream tier stored with the credential. Anthropic profile reads
   * supply the organization tier; Antigravity loadCodeAssist reads prefer paidTier to currentTier.
   * Missing or invalid labels remain null; quota percentages never establish a subscription.
   */
  plan: string | null;
  /** Anthropic display-only subscription name; absent when no tier was observed. */
  planLabel?: string;
  /** Anthropic display-only organization name of the grant; absent when none was observed. */
  organizationName?: string;
}

/**
 * Token-safe login state for one provider.
 *
 * `maskEmails` is an explicit boolean rather than a config read (#3859). This module must not
 * acquire a dependency on config I/O to answer a redaction question: the caller already holds
 * the config at its request boundary and resolves the policy there with `emailMaskingEnabled`.
 * The default masks, so every existing caller keeps today's behaviour.
 */
export function getLoginStatus(provider: string, maskEmails = true, flowId?: string): { loggedIn: boolean; email?: string; source?: OAuthCredentials["source"]; error?: string; errorCode?: LoginCodeError; done: boolean; status: "idle" | "pending" | "complete" | "error"; mode?: "callback" | "code"; flowId?: string; expiresAt?: number; hint?: OAuthLoginHint; activeAccountId?: string; accounts?: OAuthAccountSummary[] } {
  const cred = getCredential(provider);
  // `flowId` reads one of several concurrent flows; without it, the provider's newest flow.
  const flowKey = flowId ?? latestLoginFlowKey(provider);
  // An explicit flow id from another provider must not leak that flow's lifecycle or hint.
  const st = flowKey === undefined || loginFlowProvider(flowKey) !== provider ? undefined : loginState.get(flowKey);
  const set = getAccountSet(provider);
  const accounts: OAuthAccountSummary[] | undefined = set?.accounts.map(a => ({
    id: a.id,
    ...(a.alias ? { alias: a.alias } : {}),
    email: projectEmail(a.credential.email, maskEmails) ?? undefined,
    active: a.id === set.activeAccountId,
    ...(accountNeedsReauthForStatus(provider, a) ? { needsReauth: true } : {}),
    ...(a.needsReauth && a.needsReauthReason === "verify_account" ? { needsReauthReason: a.needsReauthReason, ...(a.needsReauthCause === "tos_violation" ? { needsReauthCause: a.needsReauthCause } : {}) } : {}),
    expiresAt: a.credential.expires,
    // Explicitly null rather than omitted when upstream tier metadata is unknown.
    plan: normalizeOAuthPlan(a.credential.plan) ?? null,
    ...((provider === "anthropic" || provider === "anthropic2") && anthropicSubscriptionLabel(a.credential.plan)
      ? { planLabel: anthropicSubscriptionLabel(a.credential.plan) } : {}),
    ...((provider === "anthropic" || provider === "anthropic2") ? oauthOrganizationNameSummary(a.credential) : {}),
  }));

  // Expired access tokens can still count as logged in with a usable refresh token.
  // Refresh-attention and local-import expiry checks stay in accountNeedsReauthForStatus.
  const activeAccount = set?.accounts.find(a => a.id === set.activeAccountId);
  const activeNeedsReauth = activeAccount && accountNeedsReauthForStatus(provider, activeAccount);
  return {
    loggedIn: !!cred && !activeNeedsReauth,
    email: projectEmail(cred?.email, maskEmails) ?? undefined,
    source: cred?.source,
    error: st?.error,
    ...(st?.errorCode ? { errorCode: st.errorCode } : {}),
    done: st?.done ?? false,
    // The flow's own lifecycle, which `done` alone cannot express: a finished flow that failed
    // and one that succeeded both report done:true. Callers poll this.
    status: !st ? "idle" : !st.done ? "pending" : st.error ? "error" : "complete",
    ...(st?.mode ? { mode: st.mode } : {}),
    ...(st?.flowId ? { flowId: st.flowId } : {}),
    ...(st?.expiresAt !== undefined ? { expiresAt: st.expiresAt } : {}),
    ...(st?.hint && !st.done ? { hint: { url: st.hint.url, instructions: st.hint.instructions, deviceCode: st.hint.deviceCode } } : {}),
    ...(set ? { activeAccountId: set.activeAccountId, accounts } : {}),
  };
}

/**
 * Token-safe per-provider login state for the CLI `ocx status` logins section. Never tokens; the
 * email follows the operator's `privacy.maskEmails` policy, masked by default (#3859).
 */
export function oauthLoginSummary(maskEmails = true): Array<{ provider: string; loggedIn: boolean; email?: string }> {
  return listOAuthProviders().map(provider => {
    const status = getLoginStatus(provider, maskEmails);
    return { provider, loggedIn: status.loggedIn, ...(status.email ? { email: status.email } : {}) };
  });
}

export async function startLoginFlow(
  provider: string,
  opts?: LoginOpts,
  lifecycle?: LoginFlowLifecycle,
): Promise<{ url: string; instructions?: string; deviceCode?: string; expiresAt?: number }> {
  const def = OAUTH_PROVIDERS[provider];
  if (!def) throw new UnsupportedOAuthProviderError(provider);
  // Never silently downgrade to the localhost redirect: the caller asked for code mode
  // precisely because it cannot reach a localhost page.
  if (opts?.codeMode && !supportsCodeLoginMode(provider)) throw new CodeLoginUnsupportedError(provider);
  admitLoginFlow(provider, opts?.codeMode === true);
  // The flow id is the key of every map below. Callers that own one (the management route, the
  // codex auth API) supply it so a later paste can be pinned to this exact attempt.
  const flowId = lifecycle?.flowId ?? randomUUID();
  const expiresAt = recordStartedLoginFlow(provider, flowId, opts?.codeMode === true, lifecycle?.retainOutcome);
  const abort = new AbortController();
  loginAbort.set(flowId, { controller: abort, provider });
  if (provider === "kiro") kiroLoginSettling.add(provider);
  return new Promise((resolve, reject) => {
    let urlResolved = false;
    const ctrl: OAuthController = {
      onAuth: ({ url, instructions, deviceCode }) => {
        if (abort.signal.aborted || loginAbort.get(flowId)?.controller !== abort) return;
        // Device approval can fall back to manual input. Replace, never merge: the
        // previous device code must disappear when the provider changes the next step.
        const hint = { url, instructions, deviceCode };
        // Merged, not replaced: the flow's own identity (mode/flowId/expiresAt) was recorded
        // before the provider produced a URL and must survive every hint update.
        loginState.set(flowId, { ...loginState.get(flowId), done: false, hint });
        if (!urlResolved) {
          urlResolved = true;
          resolve({ ...hint, ...(expiresAt !== undefined ? { expiresAt } : {}) });
        }
      },
      onProgress: () => {},
      // GUI fallback when the browser cannot hit the loopback callback server.
      onManualCodeInput: (expectedState?: string) => waitForManualLoginCode(flowId, abort.signal, expectedState),
      signal: abort.signal,
    };
    const abandonIfNotOwner = (error?: unknown): boolean => {
      if (loginAbort.get(flowId)?.controller === abort) return false;
      if (!urlResolved) reject(error ?? new Error("OAuth login was superseded"));
      return true;
    };
    // The row this flow's own credential write landed in, from the store's receipt. A token match
    // after the fact would miss it once a concurrent login for the same account rotates the token.
    let persistedAccountId: string | undefined;
    const settle = async (error?: unknown, credential?: OAuthCredentials): Promise<void> => {
      // Cancellation deletes this controller and records its own terminal result. A late provider
      // rejection (or an older flow settling after a replacement starts) must not overwrite that
      // state or delete the replacement flow's controller/manual-code slot.
      if (abandonIfNotOwner(error)) return;
      let finalError = error;
      try {
        if (credential && persistedAccountId) lifecycle?.onCredentialPersisted?.(credential);
        await lifecycle?.onSettled?.();
      } catch (settleError) {
        // A successful credential/config commit is not fully live until its owner reconciles the
        // runtime config. For an already-failed login, keep the original recovery error.
        if (finalError === undefined) finalError = settleError;
      }
      if (abandonIfNotOwner(finalError)) return;
      if (finalError === undefined) {
        loginAbort.delete(flowId);
        clearManualCodeSlot(flowId);
        // Answer this flow's caller with the account it wrote, not whichever one is active now.
        settleLoginFlow(flowId, persistedAccountId ? { accountId: persistedAccountId } : {});
        // Local-token import (grok-cli / Claude Code keychain) completes WITHOUT firing onAuth —
        // resolve so the GUI call returns instead of hanging.
        if (!urlResolved) resolve({ url: "", instructions: "Logged in via an existing local CLI/keychain token — no browser needed." });
        return;
      }

      const e = finalError;
      loginAbort.delete(flowId);
      clearManualCodeSlot(flowId);
      const msg = publicOAuthAuthenticationErrorMessage(e);
      settleLoginFlow(flowId, { error: msg, errorCode: classifyLoginCodeError(e) });
      if (!urlResolved) reject(e);
    };
    // Background: runLogin persists the credential + provider entry to disk. The lifecycle hook
    // lets a long-lived server config adopt that settled state before clients observe done=true.
    const assertCurrentOwner = (): void => {
      if (loginAbort.get(flowId)?.controller !== abort) throw new OAuthLoginSupersededError();
    };
    const onAccountPersisted = (accountId: string): void => { persistedAccountId = accountId; };
    void runLogin(provider, ctrl, opts, { assertCurrentOwner, onAccountPersisted }).then(
      credential => settle(undefined, credential),
      (e: unknown) => settle(e),
    ).catch((e: unknown) => {
      // settle catches lifecycle failures, so this is only a defensive promise-boundary guard.
      if (abandonIfNotOwner(e)) return;
      loginAbort.delete(flowId);
      clearManualCodeSlot(flowId);
      const msg = publicOAuthAuthenticationErrorMessage(e);
      settleLoginFlow(flowId, { error: msg, errorCode: classifyLoginCodeError(e) });
      if (!urlResolved) reject(e);
    }).finally(() => {
      if (provider === "kiro") kiroLoginSettling.delete(provider);
    });
  });
}