Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

37.3 KB
Raw Blame
/**
 * The one provider-dispatch rule, shared by SessionRoutes (generator start)
 * and worker-service (getAiStatus) — previously duplicated in both.
 *
 * Semantics: openrouter wins when selected AND a key exists; else gemini when
 * selected AND a key exists; else openai-compatible when selected AND fully
 * configured; else claude (silent fall-through, unchanged).
 *
 * Trial-expiry fallback (plan 2026-08-26 Phase 6): when the selected
 * openrouter config points at the cmem.ai gateway AND a terminal gateway
 * rejection has been recorded (CLAUDE_MEM_PRO_FALLBACK_AT non-empty), dispatch
 * returns 'claude' during a cooldown — memory runs on the user's Anthropic
 * plan, as the installer promised. It then permits a periodic gateway probe
 * so subscribing can recover automatically. User-owned openrouter.ai (or any
 * non-gateway) base URLs ignore the fallback marker entirely.
 *
 * Provider fallback (CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER, default 'claude' —
 * the Anthropic plan): while the selected provider's breaker holds because it
 * cannot serve (a spent allowance, a rate limit or over-capacity refusal that
 * outlasted its retries, an outage or repeated unusable replies — see
 * routeAroundUnservableProvider), every plain return is routed to the
 * fallback, provided it can serve (for Claude: a Claude login or key exists)
 * and is not itself held. Once the window elapses the primary is re-probed and
 * takes the work back. 'off' leaves dispatch waiting on the primary. The
 * cmem-gateway branch keeps its own marker and runs first, untouched.
 */

import { SettingsDefaultsManager, type SettingsDefaults } from '../../shared/SettingsDefaultsManager.js';
import { SELECTABLE_PROVIDERS, type SelectableProvider } from '../../ui/provider-options.js';
import { readFileSync } from 'fs';
import { parseJsonWithBom } from '../../shared/atomic-json.js';
import { settingsTarget } from '../../shared/settings-document.js';
import { paths } from '../../shared/paths.js';
import { logger } from '../../utils/logger.js';
import { normalizePlatformSource } from '../../shared/platform-source.js';
import { PROVIDER_BY_SOURCE_SETTING, parseProviderBySource } from '../../shared/provider-by-source.js';
import { isCmemGatewayUrl, setSessionProviderResolver, writeProFallbackAt, type ProFallbackNotice } from '../../shared/cmem-gateway.js';
import { cmemCapProbeAllowed, cmemCapExhaustedAt } from '../../shared/cmem-cap-probe.js';
import { scrubErrorMessage, type ObserverQuotaNoticeHold } from '../../shared/observer-health.js';
import { hasAnthropicApiKey } from '../../shared/EnvManager.js';
import { resolveOpenAICompatPreset } from '../../shared/openai-compat-presets.js';
import { isGeminiAvailable, isGeminiSelected } from './GeminiProvider.js';
import { isOpenRouterAvailable, isOpenRouterSelected, resolveOpenRouterConfig } from './OpenRouterProvider.js';
import { isOpenAICompatAvailable, isOpenAICompatSelected } from './OpenAICompatProvider.js';
import { hasCodexChatGptLogin } from './CodexAppServerClient.js';
import { CODEX_CLI_SETUP_RECHECK_COOLDOWN_MS, getDependencyStatus, isDependencyStatusInCooldown } from '../../shared/dependency-health.js';
import { isCodexSelected } from './CodexProvider.js';
import { isClassified, type ClassifiedProviderError } from './provider-errors.js';
import { canClaudeServeAsFallback, claudeQuotaStandIn } from '../../shared/claude-fallback-readiness.js';
import {
  cooldownAppliesToCurrentAccount,
  getQuotaCooldown,
  isQuotaCooldownActive,
  isQuotaCooldownHolding,
  recordQuotaExhausted,
  releaseQuotaProbe,
  setQuotaFallbackResolver,
  setUnservableProviderRouter,
  tryAdmitCmemGatewayProbe,
  type QuotaCooldownState,
  type QuotaFallbackResolver,
  type QuotaProvider,
} from '../../shared/quota-cooldown.js';

/**
 * Every provider dispatch can name. `openai-compatible` is the generic
 * OpenAI-shaped endpoint provider (NVIDIA NIM and friends) — see
 * src/shared/openai-compat-presets.ts for why it is not folded into
 * openrouter.
 */
export type { SelectableProvider } from '../../ui/provider-options.js';

/** Retry a fallen-back gateway occasionally so a later subscription recovers. */
export const CMEM_FALLBACK_RETRY_MS = 15 * 60_000;

export function shouldUseCmemFallback(
  fallbackAt: string | undefined | null,
  nowMs: number = Date.now(),
): boolean {
  const timestamp = Date.parse((fallbackAt ?? '').trim());
  if (Number.isNaN(timestamp)) return Boolean((fallbackAt ?? '').trim());
  const age = nowMs - timestamp;
  return age >= 0 && age < CMEM_FALLBACK_RETRY_MS;
}

/**
 * While a fallback is recorded, whether memory stays on the Anthropic plan
 * with no gateway re-probe: during the fallback window, and for as long as an
 * openrouter breaker still withholds requests after it. That breaker's start
 * gate refuses every gateway run, so a probe admitted into it would run
 * nothing at all, neither on the gateway nor on Claude.
 */
function gatewayProbeWithheld(fallbackAt: string): boolean {
  return shouldUseCmemFallback(fallbackAt) || isQuotaCooldownActive('openrouter');
}

/**
 * A dispatch decision, plus any gateway re-probe claim it took.
 *
 * `gatewayProbeClaimId` is non-null only for the single caller admitted to
 * re-probe the cmem gateway after its fallback window elapsed. It must be
 * handed back to `releaseCmemGatewayProbe` when that run ends.
 */
export interface ProviderSelection {
  provider: SelectableProvider;
  gatewayProbeClaimId: number | null;
  /**
   * The provider this selection stands in for when the quota fallback routed
   * around it, else null. Optional so callers and test doubles that build a
   * selection by hand stay valid — read it loosely (`?? null`).
   */
  fallbackFrom?: SelectableProvider | null;
  /** The gateway is capped and this machine has no authorized, available fallback. */
  capBlocked?: boolean;
}

/** What CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER may name. */
export type QuotaFallbackProvider = SelectableProvider;

/**
 * The configured fallback, or null when it is turned off ('off') or the value
 * is unrecognised. Empty means the default, the Anthropic plan: settings files
 * written before it became the default persisted "" for "nothing chosen", and
 * those installs get the fallback too. Only an explicit 'off' opts out.
 */
export function readQuotaFallbackProvider(): QuotaFallbackProvider | null {
  const settings = SettingsDefaultsManager.loadFromFile(paths.settings());
  const raw = String(settings.CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER ?? '').trim();
  if (raw === '') return 'claude';
  return (SELECTABLE_PROVIDERS as readonly string[]).includes(raw) ? raw as QuotaFallbackProvider : null;
}

/**
 * The cmem gateway as the openrouter fallback, by its trial-expiry marker:
 * 'not-refusing' when the endpoint is not the gateway or no marker is set,
 * 'refusing' inside the marker's window (shouldUseCmemFallback), 'probe' once
 * that window has elapsed. The same window and single re-probe the gateway
 * branch gives a gateway primary: a probe that fails re-stamps the marker
 * (recordCmemFallbackIfEligible), one that succeeds clears it, so one refusal
 * never disqualifies the gateway for good.
 */
function gatewayFallbackState(): 'not-refusing' | 'refusing' | 'probe' {
  const settings = SettingsDefaultsManager.loadFromFile(paths.settings());
  if (!settings.CLAUDE_MEM_PRO_FALLBACK_AT || !isCmemGatewayUrl(settings.CLAUDE_MEM_OPENROUTER_BASE_URL)) {
    return 'not-refusing';
  }
  return shouldUseCmemFallback(settings.CLAUDE_MEM_PRO_FALLBACK_AT) ? 'refusing' : 'probe';
}

/**
 * Whether a fallback has what it needs to run. Claude needs a Claude login or
 * key and a CLI that is not failing to start (canClaudeServeAsFallback);
 * without one, work waits on the primary as it always did. The cmem gateway is skipped inside
 * its trial-expiry window; after it, it is available for the single re-probe,
 * which `selectWithQuotaFallback` claims before sending.
 */
function isFallbackAvailable(provider: QuotaFallbackProvider, sessionModel?: string): boolean {
  switch (provider) {
    case 'codex': {
      const setup = getDependencyStatus('codex_cli');
      return (!setup || !isDependencyStatusInCooldown(setup, CODEX_CLI_SETUP_RECHECK_COOLDOWN_MS))
        && hasCodexChatGptLogin();
    }
    case 'gemini': return isGeminiAvailable();
    case 'openai-compatible': return isOpenAICompatAvailable(paths.settings(), sessionModel);
    case 'claude': return canClaudeServeAsFallback();
    case 'openrouter': return isOpenRouterAvailable() && gatewayFallbackState() !== 'refusing'
      && (!isCmemGatewayUrl(resolveOpenRouterConfig().apiUrl) || cmemCapProbeAllowed());
  }
}

/**
 * `provider`'s breaker when it is a quota hold on the account selected now: a
 * spent allowance or a rate limit that outlasted its retries. A refused
 * credential (an auth cooldown) is not one. Another provider cannot fix the
 * key, and its successes would clear the warning that says it is broken.
 */
function quotaBreakerOf(provider: SelectableProvider): QuotaCooldownState | null {
  const state = getQuotaCooldown(provider);
  return state && state.cause !== 'auth' && cooldownAppliesToCurrentAccount(state) ? state : null;
}

function isHeldForQuota(provider: SelectableProvider, nowMs: number): boolean {
  return quotaBreakerOf(provider) !== null && isQuotaCooldownHolding(provider, nowMs);
}

/**
 * Arm `provider`'s breaker because it cannot serve right now, when — and only
 * when — the fallback can take the work meanwhile. Returns that fallback, or
 * null with nothing armed (no fallback, it is the provider itself, or it
 * cannot serve), leaving the caller's usual handling in place.
 *
 * For failures that do not arm a breaker on their own: an outage or upstream
 * fault that outlived the provider's retries, a rate limit or over-capacity
 * refusal the session would otherwise wait out with Retry-After resumes, a
 * provider that keeps answering without usable output. The window is the
 * short throttle cooldown ('unavailable' / 'rate_limit'), after which the
 * primary is re-probed once and takes the work back when it answers.
 */
export function routeAroundUnservableProvider(
  provider: SelectableProvider,
  message: string,
  window: 'unavailable' | 'rate_limit',
  profile?: string,
): QuotaFallbackProvider | null {
  const fallback = quotaFallbackTarget(provider);
  if (fallback === null) return null;
  recordQuotaExhausted(provider, message, window, undefined, profile);
  return fallback;
}

/**
 * Where work for `primary` may go while `primary` is held: the configured
 * fallback, when it is a different provider, can serve, and is not itself
 * withholding requests (for any reason). Null otherwise — including when
 * nothing is configured.
 *
 * Read-only: it never claims a probe. Keyed on the provider being routed
 * around, so a provider can never be offered as its own fallback.
 */
export function quotaFallbackTarget(
  primary: QuotaProvider,
  nowMs: number = Date.now(),
  sessionModel?: string,
): QuotaFallbackProvider | null {
  const fallback = readQuotaFallbackProvider();
  if (fallback === null || fallback === primary) return null;
  if (!isFallbackAvailable(fallback, sessionModel)) return null;
  if (isQuotaCooldownHolding(fallback, nowMs)) return null;
  return fallback;
}

interface RoutedProvider {
  provider: SelectableProvider;
  fallbackFrom: SelectableProvider | null;
}

/**
 * The shared rule for every plain dispatch return: keep `primary` unless its
 * breaker holds for its quota AND the fallback can serve. When neither can,
 * this returns `primary`, and admission withholds it exactly as it does today.
 *
 * A Claude primary whose other credential can take the work
 * (CLAUDE_MEM_QUOTA_FALLBACK_AUTH_METHOD) stays on Claude, and admission runs
 * it on that credential: same models, same prompts. The provider fallback is
 * next in line, once both credentials are held.
 */
function applyQuotaFallback(primary: SelectableProvider, nowMs: number = Date.now(), sessionModel?: string): RoutedProvider {
  if (!isHeldForQuota(primary, nowMs)) return { provider: primary, fallbackFrom: null };
  if (primary === 'claude' && claudeQuotaStandIn() !== null) return { provider: primary, fallbackFrom: null };
  const fallback = quotaFallbackTarget(primary, nowMs, sessionModel);
  return fallback === null
    ? { provider: primary, fallbackFrom: null }
    : { provider: fallback, fallbackFrom: primary };
}

type QuotaFallbackState = 'primary' | 'fallback' | 'credential' | 'probing' | 'blocked';

/**
 * Last state logged by `selectProviderForGenerator`. Module-level because
 * dispatch runs on every generator start and on the Telegram wrap-up: the log
 * is one line per CHANGE per primary, never one per call. Kept per primary because
 * per-source dispatch runs several primaries side by side.
 */
const quotaFallbackStates = new Map<SelectableProvider, QuotaFallbackState>();

function noteQuotaFallbackTransition(primary: SelectableProvider, routed: RoutedProvider, nowMs: number): void {
  let next: QuotaFallbackState;
  const standIn = primary === 'claude' ? claudeQuotaStandIn() : null;
  if (routed.fallbackFrom != null) next = 'fallback';
  else if (isHeldForQuota(primary, nowMs)) next = standIn ? 'credential' : 'blocked';
  else if (quotaBreakerOf(primary) !== null) next = 'probing';
  else next = 'primary';
  if (next === (quotaFallbackStates.get(primary) ?? 'primary')) return;
  quotaFallbackStates.set(primary, next);

  switch (next) {
    case 'fallback': {
      // Name both providers by the names people know them by (cmem.ai, not
      // openrouter): the primary that stopped and the one now doing the work.
      // A Claude backup spends the owner's Anthropic account, so say that and
      // how to stop it.
      const settings = SettingsDefaultsManager.loadFromFile(paths.settings());
      const used = routed.provider === 'claude'
        ? 'the Anthropic plan (Claude), which spends your Anthropic account,'
        : quotaProviderDisplayName(routed.provider, settings);
      logger.warn(
        'SESSION',
        `Primary (${quotaProviderDisplayName(primary, settings)}) cannot serve right now; memory runs on ${used} until it recovers. To stop this, set CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER=off`,
        { primary, fallback: routed.provider, window: quotaBreakerOf(primary)?.window ?? 'quota' },
      );
      return;
    }
    case 'probing':
      logger.info('SESSION', 'Primary quota cooldown elapsed; probing primary', { primary });
      return;
    case 'credential':
      logger.warn('SESSION', standIn === 'subscription'
        ? 'API key quota exhausted; running the Claude observer on the subscription login until the key recovers'
        : 'Claude Code login paused for quota; running the Claude observer on the fallback API key until the login recovers',
      { primary, credential: standIn });
      return;
    case 'blocked': {
      // Distinct from probing: nothing is being probed and nothing can take
      // the work. Name the real cause — the fallback may be held too, or it may
      // simply be unable to serve (no credentials, or equal to the primary).
      const fallback = readQuotaFallbackProvider();
      if (fallback !== null && fallback !== primary && isQuotaCooldownHolding(fallback, nowMs)) {
        logger.warn('SESSION', 'Primary and fallback both in quota cooldown; capture waits until one clears', { primary, fallback });
      } else {
        logger.warn('SESSION', 'Primary in quota cooldown and the quota fallback cannot serve; capture waits until it clears', { primary, fallback });
      }
      return;
    }
    case 'primary':
      logger.info('SESSION', 'Primary recovered from quota cooldown', { primary });
      return;
  }
}

/**
 * A plain (non-gateway-fallback) selection for a caller about to send. The
 * transition log is kept unless the fallback is turned off.
 */
function selectWithQuotaFallback(primary: SelectableProvider, sessionModel?: string): ProviderSelection {
  const nowMs = Date.now();
  let routed = applyQuotaFallback(primary, nowMs, sessionModel);
  let gatewayProbeClaimId: number | null = null;
  // A refusing gateway past its window is re-probed by exactly one caller,
  // through the claim the gateway branch uses; the rest stay with the held
  // primary until that probe resolves.
  if (routed.fallbackFrom !== null && routed.provider === 'openrouter' && gatewayFallbackState() === 'probe') {
    const admission = tryAdmitCmemGatewayProbe();
    if (admission.admitted) gatewayProbeClaimId = admission.claimId;
    else routed = { provider: primary, fallbackFrom: null };
  }
  if (readQuotaFallbackProvider() !== null) {
    noteQuotaFallbackTransition(primary, routed, nowMs);
  }
  return routed.fallbackFrom === null
    ? { provider: routed.provider, gatewayProbeClaimId }
    : { provider: routed.provider, gatewayProbeClaimId, fallbackFrom: routed.fallbackFrom };
}

/** Test seam: forget the last logged quota-fallback state. */
export function resetQuotaFallbackStateForTesting(): void {
  quotaFallbackStates.clear();
}

/**
 * Read-only dispatch, for diagnostics and status. Never claims a probe, so it
 * is safe to call from anywhere — but a caller about to actually SEND must use
 * `selectProviderForGenerator` instead, or it becomes part of the herd.
 */
export function getSelectedProvider(platformSource?: string, sessionModel?: string): SelectableProvider {
  return routedProviderFor(primaryFor(platformSource, sessionModel), platformSource, sessionModel);
}

/** The read-only counterpart of `selectForPrimary`: where `primary`'s work goes right now. */
function routedProviderFor(primary: SelectableProvider, platformSource?: string, sessionModel?: string): SelectableProvider {
  if (primary === 'openrouter') {
    const settings = SettingsDefaultsManager.loadFromFile(paths.settings());
    if (isCmemGatewayUrl(resolveOpenRouterConfig().apiUrl) && !cmemCapProbeAllowed()) {
      return regularProviderAfterCmemCap(platformSource, sessionModel) ?? primary;
    }
    if (
      settings.CLAUDE_MEM_PRO_FALLBACK_AT
      && isCmemGatewayUrl(settings.CLAUDE_MEM_OPENROUTER_BASE_URL)
      && gatewayProbeWithheld(settings.CLAUDE_MEM_PRO_FALLBACK_AT)
    ) {
      return cmemCapExhaustedAt() === null ? 'claude' : regularProviderAfterCmemCap(platformSource, sessionModel) ?? primary;
    }
  }
  return applyQuotaFallback(primary, Date.now(), sessionModel).provider;
}

/**
 * Where memory capture runs while `held` is in a quota cooldown: the provider
 * dispatch is using, when that is a different one and not itself holding.
 * Null otherwise, and always null with the fallback turned off.
 *
 * Read by the session-start notice, through the mirrored cooldown. It asks
 * dispatch rather than `quotaFallbackTarget(held)` because the held provider
 * can be either one: after the fallback hits its own quota while the primary
 * has recovered, capture is back on the primary. It also follows dispatch
 * through the cmem-gateway branch, which ignores the quota fallback rule.
 *
 * Paused work does not need a resume of its own: the periodic sweep
 * (SessionRoutes.resumePendingSessions) paces itself on the provider dispatch
 * returns here, so it restarts quota-paused sessions on whichever provider can
 * take them.
 */
export function quotaServingProvider(held: QuotaProvider, nowMs: number = Date.now()): SelectableProvider | null {
  // The primary Claude credential is held, but runs go on the other one meanwhile.
  if (held === 'claude' && claudeQuotaStandIn()) return 'claude';
  if (readQuotaFallbackProvider() === null) return null;
  // The held provider's own routing when it is a primary here (the global one
  // or a mapped one). Otherwise it is only a fallback, and capture continues
  // only if every route still has a provider serving: a primary that was
  // counting on it may now be waiting.
  // No session model here: these are diagnostic/quota views with no live
  // session, so availability stays strictly global-only. The explicit callbacks
  // also keep Array's index out of the optional 2nd parameters
  // (`isProviderConfigured(provider, sessionModel?)`, `routedProviderFor(primary, platformSource?)`).
  const primaries = [globalPrimary(), ...readProviderBySource().values()].filter(provider => isProviderConfigured(provider));
  const routes = (primaries.includes(held as SelectableProvider) ? [held as SelectableProvider] : primaries).map(primary => routedProviderFor(primary));
  if (routes.some(serving => serving === held || isQuotaCooldownHolding(serving, nowMs))) return null;
  return routes[0];
}

function quotaProviderDisplayName(provider: string, settings: SettingsDefaults, auth?: string): string {
  switch (provider) {
    case 'claude': return auth === 'api-key' ? 'your Anthropic API key' : 'your Claude plan';
    case 'openrouter': return isCmemGatewayUrl(resolveOpenRouterConfig().apiUrl) ? 'cmem.ai' : 'OpenRouter';
    case 'gemini': return 'Gemini';
    case 'codex': return 'Codex (your ChatGPT subscription)';
    case 'openai-compatible': {
      const preset = resolveOpenAICompatPreset(settings.CLAUDE_MEM_OPENAI_COMPAT_PRESET);
      return preset.id === 'custom' ? 'your OpenAI-compatible endpoint' : preset.label;
    }
    default: throw new Error(`Cannot name quota notice provider: ${provider}`);
  }
}

/** Defaults are merged by the settings reader; inspect the actual choice for the opt-out hint. */
function usesDefaultClaudeBackup(): boolean {
  const override = process.env.CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER;
  if (override !== undefined) return override.trim() === '';
  try {
    const document = parseJsonWithBom<Record<string, unknown>>(readFileSync(paths.settings(), 'utf8'));
    return !String(settingsTarget(document).CLAUDE_MEM_QUOTA_FALLBACK_PROVIDER ?? '').trim();
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true;
    throw error;
  }
}

/** Display-only snapshot: dispatch still owns every routing and admission decision. */
const quotaNoticeResolution: QuotaFallbackResolver = (held, nowMs, activeHolds) => {
  // Roles are per route. When CLAUDE_MEM_PROVIDER_BY_SOURCE sends sessions to
  // different primaries, no single main/backup pair describes them all, so the
  // notice stays role-free: it names only who is serving, and
  // quotaServingProvider names one only when every route still has one.
  const primaries = new Set([globalPrimary(), ...readProviderBySource().values()].filter(provider => isProviderConfigured(provider)));
  if (primaries.size > 1) return quotaServingProvider(held, nowMs);
  const settings = SettingsDefaultsManager.loadFromFile(paths.settings());
  const selected = settings.CLAUDE_MEM_PROVIDER;
  const main = (['claude', 'gemini', 'openrouter', 'codex', 'openai-compatible'] as string[]).includes(selected)
    ? selected : 'claude';
  const backup = readQuotaFallbackProvider();
  // Where main's runs actually go: Claude while cmem.ai's trial-expiry
  // fallback stands, so a hold on it is a hold on the provider doing the work.
  const routed = routedProviderFor(main as SelectableProvider);
  const mainAuth = hasAnthropicApiKey() ? 'api-key' : 'subscription';
  const displayName = (provider: string, auth?: string) => quotaProviderDisplayName(provider, settings, auth);
  const retryName = (provider: string, auth?: string) => provider === 'claude' && auth !== 'api-key'
    ? 'Claude' : displayName(provider, auth);
  const holds: ObserverQuotaNoticeHold[] = activeHolds
    .filter(hold => cooldownAppliesToCurrentAccount(hold) && (hold.provider === main || hold.provider === backup || hold.provider === routed))
    .map(hold => ({
      provider: hold.provider,
      ...(hold.profile ? { profile: hold.profile } : {}),
      displayName: displayName(hold.provider, hold.auth ?? mainAuth),
      retryName: retryName(hold.provider, hold.auth ?? mainAuth),
      role: hold.provider === main && !(main === 'claude' && hold.auth && hold.auth !== mainAuth) ? 'main' : 'backup',
      until: hold.until,
      ...(hold.auth ? { auth: hold.auth } : {}),
      ...(hold.reason ? { reason: hold.reason } : {}),
    }));
  const selectedProvider = getSelectedProvider();
  const standIn = selectedProvider === 'claude' && isQuotaCooldownHolding('claude', nowMs) ? claudeQuotaStandIn() : null;
  const serving = !isQuotaCooldownHolding(selectedProvider, nowMs) || standIn
    ? selectedProvider : undefined;
  const servingAuth = serving === 'claude' ? standIn ?? mainAuth : undefined;
  const servingDisplayName = serving === 'claude' && standIn === 'api-key'
    ? 'your backup API key (ANTHROPIC_FALLBACK_API_KEY)'
    : serving ? displayName(serving, servingAuth) : undefined;
  return {
    servingProvider: quotaServingProvider(held, nowMs),
    notice: {
      mainProvider: main,
      mainDisplayName: displayName(main, mainAuth),
      mainRetryName: retryName(main, mainAuth),
      ...(backup && backup !== main ? { backupProvider: backup, backupDisplayName: displayName(backup, mainAuth) } : {}),
      defaultClaudeBackup: usesDefaultClaudeBackup(),
      ...(serving ? { servingProvider: serving, servingDisplayName } : {}),
      ...(servingAuth ? { servingAuth } : {}),
      holds,
    },
  };
};

// The session-start notice reads the serving provider from the mirrored
// cooldown in observer-health.json. See setQuotaFallbackResolver for why the
// answer is injected from here rather than imported there.
setQuotaFallbackResolver(quotaNoticeResolution);
setUnservableProviderRouter((provider, message, window, profile) =>
  provider === 'cmem-gateway' ? null : routeAroundUnservableProvider(provider, message, window, profile));
setSessionProviderResolver(configuredProviderForSource);

/**
 * Dispatch for a caller that is about to start a generator, claiming the single
 * post-cooldown gateway re-probe.
 *
 * The expiry check alone is a bare clock read, and the marker it reads is on
 * DISK — so every process parses the same ISO string and computes the same
 * expiry instant. On a busy machine (#3800 saw 28-69 live sessions) they all
 * observe the window elapse together and hit the gateway at once, which is the
 * same burst the quota breaker exists to prevent, relocated. Worse, each of
 * those failures does a read-modify-write of the user's whole settings.json to
 * re-arm the marker, so a concurrent settings edit can be clobbered.
 *
 * Claiming makes it what the comment always said it was: exactly one probe,
 * through the quota breaker's own claim under the DISTINCT 'cmem-gateway' key.
 * That key never had an entry — the marker IS the gateway's window, so nothing
 * armed it — and a key with no entry admits every caller without a claim,
 * which let the whole herd through. `tryAdmitCmemGatewayProbe` creates the
 * entry for its claim alone: quota-cooldown neither persists nor mirrors it,
 * because while the fallback stands memory runs on the Anthropic plan, which
 * is not a pause.
 */
export function selectProviderForGenerator(platformSource?: string, sessionModel?: string): ProviderSelection {
  return selectForPrimary(primaryFor(platformSource, sessionModel), platformSource, sessionModel);
}

/**
 * The provider the global settings name, by the same order getSelectedProvider
 * reads: codex, openrouter, gemini and openai-compatible each when selected
 * and configured, else claude.
 */
function globalPrimary(sessionModel?: string): SelectableProvider {
  if (isCodexSelected()) return 'codex';
  if (isOpenRouterSelected() && isOpenRouterAvailable()) return 'openrouter';
  if (isGeminiSelected() && isGeminiAvailable()) return 'gemini';
  if (isOpenAICompatSelected() && isOpenAICompatAvailable(paths.settings(), sessionModel)) return 'openai-compatible';
  return 'claude';
}

/** Whether `provider` has what it needs to be a primary (claude and codex have no key to check). */
function isProviderConfigured(provider: SelectableProvider, sessionModel?: string): boolean {
  switch (provider) {
    case 'openrouter': return isOpenRouterAvailable();
    case 'gemini': return isGeminiAvailable();
    case 'openai-compatible': return isOpenAICompatAvailable(paths.settings(), sessionModel);
    case 'claude':
    case 'codex':
      return true;
  }
}

/**
 * Choose the provider this machine normally uses. If cmem is itself the backup,
 * only its recovered primary can take over. Explicit backup settings (including
 * off) win. With no explicit backup a mapped gateway can return to the global
 * provider, and a Codex session can continue on its signed-in ChatGPT plan.
 */
export function regularProviderAfterCmemCap(platformSource?: string, sessionModel?: string): SelectableProvider | null {
  const primary = primaryFor(platformSource, sessionModel);
  const available = (candidate: SelectableProvider) => candidate !== 'openrouter'
    && isFallbackAvailable(candidate, sessionModel) && !isQuotaCooldownHolding(candidate);
  if (primary !== 'openrouter') return available(primary) ? primary : null;

  if (usesDefaultClaudeBackup()) {
    const global = globalPrimary(sessionModel);
    if (available(global)) return global;
    if (platformSource && normalizePlatformSource(platformSource) === 'codex' && available('codex')) return 'codex';
  }
  return quotaFallbackTarget('openrouter', Date.now(), sessionModel);
}

function selectCapFallback(platformSource?: string, sessionModel?: string): ProviderSelection {
  const regular = regularProviderAfterCmemCap(platformSource, sessionModel);
  return regular ? { provider: regular, gatewayProbeClaimId: null, fallbackFrom: 'openrouter' }
    : { provider: 'openrouter', gatewayProbeClaimId: null, capBlocked: true };
}

/** Dispatch for an already-chosen primary: the cmem-gateway branch, then the quota fallback. */
function selectForPrimary(primary: SelectableProvider, platformSource?: string, sessionModel?: string): ProviderSelection {
  if (primary !== 'openrouter') return selectWithQuotaFallback(primary, sessionModel);
  const settings = SettingsDefaultsManager.loadFromFile(paths.settings());
  // A spent cmem allowance is one probe a day. Selecting the gateway again
  // on the immediate fallback resume is what re-sent pro_inference_cap_exhausted.
  if (isCmemGatewayUrl(resolveOpenRouterConfig().apiUrl) && !cmemCapProbeAllowed()) {
    return selectCapFallback(platformSource, sessionModel);
  }
  if (settings.CLAUDE_MEM_PRO_FALLBACK_AT && isCmemGatewayUrl(settings.CLAUDE_MEM_OPENROUTER_BASE_URL)) {
    if (gatewayProbeWithheld(settings.CLAUDE_MEM_PRO_FALLBACK_AT)) {
      if (cmemCapExhaustedAt() !== null) return selectCapFallback(platformSource, sessionModel);
      return { provider: 'claude', gatewayProbeClaimId: null };
    }
    // Window elapsed: exactly one caller re-probes the gateway, the rest stay
    // on the Anthropic plan until that probe resolves — any failure re-stamps
    // the marker, a success clears it, and every exit releases the claim.
    const admission = tryAdmitCmemGatewayProbe();
    if (!admission.admitted) {
      if (cmemCapExhaustedAt() !== null) return selectCapFallback(platformSource, sessionModel);
      return { provider: 'claude', gatewayProbeClaimId: null };
    }
    return { provider: 'openrouter', gatewayProbeClaimId: admission.claimId };
  }
  return selectWithQuotaFallback('openrouter', sessionModel);
}

/** The last malformed value logged, so a bad setting warns once, not on every generator start. */
let warnedProviderBySource: string | null = null;

/**
 * The provider mapped to `platformSource`, or null when the feature is off,
 * the value is malformed (the whole map is then ignored), or the source has no
 * entry.
 */
function providerForSource(platformSource: string | undefined): SelectableProvider | null {
  if (platformSource === undefined) return null;
  const map = readProviderBySource();
  return map.get(normalizePlatformSource(platformSource)) ?? null;
}

function readProviderBySource(): ReadonlyMap<string, SelectableProvider> {
  const raw = SettingsDefaultsManager.loadFromFile(paths.settings())[PROVIDER_BY_SOURCE_SETTING] as unknown;
  const parsed = parseProviderBySource(raw);
  if (parsed.ok) return parsed.map;
  const key = typeof raw === 'string' ? raw : JSON.stringify(raw);
  if (warnedProviderBySource !== key) {
    warnedProviderBySource = key;
    logger.warn('SESSION', `${parsed.error}; ignoring it and using the global provider`);
  }
  return new Map();
}

/** The provider mapped to `platformSource` when it is configured, else null: the global provider serves that session. */
function configuredProviderForSource(platformSource: string | undefined, sessionModel?: string): SelectableProvider | null {
  const mapped = providerForSource(platformSource);
  return mapped !== null && isProviderConfigured(mapped, sessionModel) ? mapped : null;
}

/** The primary for a session of `platformSource`: its mapped provider when configured, else the global one. */
function primaryFor(platformSource?: string, sessionModel?: string): SelectableProvider {
  return configuredProviderForSource(platformSource, sessionModel) ?? globalPrimary(sessionModel);
}

/** Test seam: forget the malformed value already logged. */
export function resetProviderBySourceWarningForTesting(): void {
  warnedProviderBySource = null;
}

/** Release a gateway re-probe claim taken by `selectProviderForGenerator`. */
export function releaseCmemGatewayProbe(claimId: number | null): void {
  releaseQuotaProbe('cmem-gateway', claimId);
}

/**
 * The gateway saying it has stopped serving this account, which is the
 * fallback's trigger:
 *  - kind 'quota_exhausted' (code allowance_exhausted, or a legacy 402): the
 *    allowance is spent, paid accounts at their monthly cap included;
 *  - kind 'auth_invalid': the gateway refused the key. Code 'key_invalid' (not
 *    recognized), code 'subscription_inactive' (a lapsed, cancelled, or unpaid
 *    trial or plan — the very case the installer's fallback promise is for,
 *    #3687, and the most common way the gateway turns an account away), or a
 *    401/403 with no taxonomy envelope at all (an edge or WAF page). Every
 *    refusal leaves the key unusable here, and an auth cooldown in its place
 *    would leave memory on neither the gateway nor Claude.
 */
function isTerminalGatewayRejection(error: ClassifiedProviderError): boolean {
  return error.kind === 'quota_exhausted' || error.kind === 'auth_invalid';
}

/**
 * Settle a failed OpenRouter run against the cmem trial-expiry fallback.
 * Returns true when memory stays on — or moves to — the Anthropic plan: the
 * caller must then NOT feed the observer-health ledger or arm a breaker (the
 * provider switch is the remedy; there is no outage to warn about).
 *
 *  - A terminal gateway rejection records the fallback, with the gateway's own
 *    words for the session-start notice.
 *  - Any other failure of the single post-window re-probe (this run holds the
 *    claim, and no gateway response has cleared the marker since) re-stamps
 *    it: a rate limit or an upstream outage on the probe would otherwise leave
 *    memory on neither the gateway nor Claude.
 *
 * Anything else — a rate limit or an outage outside a fallback, and every
 * failure on a non-gateway base URL (a personal openrouter.ai key running dry)
 * — is not a fallback; the caller books it like any other failure.
 */
export function recordCmemFallbackIfEligible(
  error: unknown,
  gatewayProbeClaimId: number | null = null,
  settingsPath: string = paths.settings(),
): boolean {
  const rejection = isClassified(error) && isTerminalGatewayRejection(error) ? error : null;
  if (rejection === null && gatewayProbeClaimId === null) {
    return false;
  }
  const settings = SettingsDefaultsManager.loadFromFile(settingsPath);
  if (!isCmemGatewayUrl(settings.CLAUDE_MEM_OPENROUTER_BASE_URL)) {
    return false;
  }
  if (rejection === null && !settings.CLAUDE_MEM_PRO_FALLBACK_AT) {
    // The re-probe's claim, but a gateway response already cleared the marker:
    // an ordinary failure of a gateway that serves the account again.
    return false;
  }
  // Already falling back — another generator's rejection armed the window.
  // Handled, but rewriting settings.json would restart the window and race
  // every other writer of the file.
  if (shouldUseCmemFallback(settings.CLAUDE_MEM_PRO_FALLBACK_AT)) {
    return true;
  }
  const detail = isClassified(error) ? { kind: error.kind, ...(error.code ? { code: error.code } : {}) } : {};
  const fallbackAt = new Date().toISOString();
  try {
    // A rejection brings the gateway's words; a failed re-probe only re-stamps,
    // keeping the words of the rejection that started the fallback.
    writeProFallbackAt(fallbackAt, settingsPath, rejection ? gatewayNotice(rejection) : undefined);
  } catch (writeError: unknown) {
    // The marker could not be persisted, so the failure is NOT handled: return
    // false, and the caller books it like any other failure rather than
    // dropping it. This diagnostic explains why the fallback did not arm.
    logger.warn(
      'SESSION',
      'Could not persist the cmem trial-expiry fallback; retaining normal provider failure handling',
      detail,
      writeError instanceof Error ? writeError : new Error(String(writeError)),
    );
    return false;
  }
  logger.info(
    'SESSION',
    rejection
      ? 'Recorded cmem trial-expiry fallback; dispatch checks the local provider'
      : 'cmem gateway re-probe failed; the fallback window was renewed',
    { ...detail, fallbackAt },
  );
  return true;
}

/**
 * The gateway's own words for a rejection, from its taxonomy envelope. A legacy
 * body carries no code and no words, and the notice then stays plan-neutral.
 */
function gatewayNotice(error: ClassifiedProviderError): ProFallbackNotice {
  if (!error.code) return {};
  return {
    message: scrubErrorMessage(error.message),
    ...(error.action ? { action: scrubErrorMessage(error.action) } : {}),
    ...(error.url ? { url: error.url } : {}),
  };
}