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

30.1 KB
Raw Blame

import { createHash } from 'crypto';
import { existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync } from 'fs';
import { parseEnv } from 'util';
import { basename, join } from 'path';
import { ENV_PROXY_VARS, sanitizeEnv } from '../supervisor/env-sanitizer.js';
import { logger } from '../utils/logger.js';
import { paths } from './paths.js';
import { readJsonFileWithBom, stripUtf8Bom } from './atomic-json.js';
import { SettingsDefaultsManager } from './SettingsDefaultsManager.js';
import type { ClaudeCredential } from './quota-cooldown.js';
import {
  readClaudeOAuthToken,
  decodeJwtExpMs,
  writeStaleMarker,
  clearStaleMarker,
  resolveClaudeCredentialProfile,
  resolveEffectiveClaudeConfigDir,
  type ClaudeCredentialProfile,
  type OAuthTokenResult,
} from './oauth-token.js';

/** #2753 — the credential profile's label for logging (never the token itself): 'default' for the bare keychain entry, else the config dir's basename. */
function resolveConfigDirProfileLabel(): string {
  const settings = SettingsDefaultsManager.loadFromFile(paths.settings());
  const { configDir, explicitConfigDir } = resolveClaudeCredentialProfile(settings.CLAUDE_MEM_CLAUDE_CONFIG_DIR);
  return explicitConfigDir ? basename(configDir) : 'default';
}

/**
 * The account identity that quota state is keyed by (RateLimitStore entries,
 * the 'claude' quota-cooldown breaker). It follows the credential the SDK
 * child uses: 'default' for the bare keychain entry, else the config dir's
 * basename plus the 8-hex sha256 suffix Claude Code gives that profile's
 * keychain entry (see deriveMacKeychainServiceName). Two dirs that share a
 * basename stay apart, and no path (or username) reaches /api/health or
 * quota-cooldown.json.
 */
export function credentialProfileKey(profile: ClaudeCredentialProfile): string {
  if (!profile.explicitConfigDir) return 'default';
  const suffix = createHash('sha256').update(profile.configDir.normalize('NFC')).digest('hex').slice(0, 8);
  return `${basename(profile.configDir)}#${suffix}`;
}

/** The quota key for the credential the next Claude spawn will use. */
export function resolveConfigDirProfileKey(): string {
  const settings = SettingsDefaultsManager.loadFromFile(paths.settings());
  return credentialProfileKey(resolveClaudeCredentialProfile(settings.CLAUDE_MEM_CLAUDE_CONFIG_DIR));
}

// Resolved lazily so tests (and any rare runtime path-overrides) can target a
// temp file via CLAUDE_MEM_ENV_FILE without depending on module-load order.
// Production callers see the canonical ~/.claude-mem/.env path through
// paths.envFile() unchanged.
export function envFilePath(): string {
  return process.env.CLAUDE_MEM_ENV_FILE ?? paths.envFile();
}

const BLOCKED_ENV_VARS = [
  'ANTHROPIC_API_KEY',       // Issue #733: Prevent auto-discovery from project .env files
  'ANTHROPIC_AUTH_TOKEN',    // Same leak risk as ANTHROPIC_API_KEY; a token inherited from the
                             // shell would otherwise short-circuit OAuth lookup at spawn time.
                             // The fresh token from ~/.claude-mem/.env is re-injected below
                             // when explicit gateway credentials are configured.
  'ANTHROPIC_BASE_URL',      // Issue #2375: same leak class as AUTH_TOKEN. A leaked BASE_URL
                             // alone (no token) was enough to trigger the OAuth-skip path,
                             // sending the subprocess to a proxy with no credentials.
                             // Re-injected from ~/.claude-mem/.env when configured.
  'ANTHROPIC_FALLBACK_API_KEY', // Read by claude-mem only: a shell-exported copy never reaches
                             // the CLI. A quota-fallback run injects it as ANTHROPIC_API_KEY.
  'CLAUDECODE',              // Prevent "cannot be launched inside another Claude Code session" error
  'CLAUDE_CODE_OAUTH_TOKEN', // Issue #2215: prevent stale parent-process token from leaking into
                             // isolated env. The fresh token is read from the keychain at spawn
                             // time by buildIsolatedEnvWithFreshOAuth(), which also injects a
                             // long-lived token the user put in ~/.claude-mem/.env (plan-19).
  // Issue #2357 (defense-in-depth): host CLI effort config, not part of the
  // plugin's contract. The SDK subprocess reads CLAUDE_CODE_EFFORT_LEVEL and
  // forwards it as the `effort` Messages API parameter; models that don't
  // support effort (Haiku 4.5, Sonnet 4.5, older) reject with a permanent
  // HTTP 400, which previously retried forever. env-sanitizer's CLAUDE_CODE_*
  // prefix filter already strips these on spawn paths that chain sanitizeEnv,
  // but BLOCKED_ENV_VARS is the canonical leak deny-list — naming them here
  // guarantees buildIsolatedEnv() strips them even on a path that forgets to
  // chain sanitizeEnv.
  'CLAUDE_CODE_EFFORT_LEVEL',
  'CLAUDE_CODE_ALWAYS_ENABLE_EFFORT',
];

const MODEL_OVERRIDE_ENV_VAR = /^ANTHROPIC_(?:MODEL|SMALL_FAST_MODEL|DEFAULT_(?:[A-Z0-9]+_)?MODEL)(?:_(?:NAME|DESCRIPTION|SUPPORTED_CAPABILITIES))?$/;

export interface ClaudeMemEnv {
  ANTHROPIC_API_KEY?: string;
  /** Read by claude-mem only, never passed to the CLI: the key a quota-fallback run uses (CLAUDE_MEM_QUOTA_FALLBACK_AUTH_METHOD=api-key). */
  ANTHROPIC_FALLBACK_API_KEY?: string;
  ANTHROPIC_BASE_URL?: string;
  ANTHROPIC_AUTH_TOKEN?: string;
  GEMINI_API_KEY?: string;
  GEMINI_API_KEYS?: string;
  OPENROUTER_API_KEY?: string;
  OPENROUTER_API_KEYS?: string;
  OPENAI_COMPAT_API_KEY?: string;
  OPENAI_COMPAT_API_KEYS?: string;
  /** Long-lived token from `claude setup-token`; injected only on the Claude OAuth path (buildIsolatedEnvWithFreshOAuth), ahead of the credential store. */
  CLAUDE_CODE_OAUTH_TOKEN?: string;
}

/**
 * The only env keys ever copied out of ~/.claude-mem/.env. This is the
 * whitelist that load/save/buildIsolatedEnv enforce — only the keys listed
 * here cross the boundary. Do NOT replace the per-key copy loops with
 * Object.assign(result, parsed): that would let arbitrary keys (a leaked
 * CLAUDE_CODE_* or a typo'd ANTHROPIC_* variant) through (see #2375).
 *
 * The `*_API_KEYS` plural entries are the multi-key rotation pools
 * (src/shared/api-key-pool.ts). They are deliberately generic: a third-party
 * endpoint reached through the `openai-compatible` provider supplies its key as
 * OPENAI_COMPAT_API_KEY rather than as a per-vendor name, so adding an endpoint
 * never means widening this whitelist.
 */
const CREDENTIAL_KEYS = [
  'ANTHROPIC_API_KEY',
  'ANTHROPIC_FALLBACK_API_KEY',
  'ANTHROPIC_BASE_URL',
  'ANTHROPIC_AUTH_TOKEN',
  'GEMINI_API_KEY',
  'GEMINI_API_KEYS',
  'OPENROUTER_API_KEY',
  'OPENROUTER_API_KEYS',
  'OPENAI_COMPAT_API_KEY',
  'OPENAI_COMPAT_API_KEYS',
  'CLAUDE_CODE_OAUTH_TOKEN',
] as const;

// Node's stdlib .env parser (util.parseEnv, Node ≥20.12 / stable in 24):
// handles `#` comments, blank lines, KEY=VALUE, and quote-stripping. The
// downstream CREDENTIAL_KEYS whitelist still filters the result — arbitrary
// keys in the file never reach a ClaudeMemEnv. serializeEnvFile is kept custom
// (header banner + selective quoting; no stdlib equivalent).
function parseEnvFile(content: string): Record<string, string> {
  // Windows editors (Notepad, PowerShell 5.1 "UTF8") prefix a BOM, which
  // parseEnv would otherwise glue onto the first key name.
  return parseEnv(stripUtf8Bom(content)) as Record<string, string>;
}

function serializeEnvFile(env: Record<string, string>): string {
  const lines: string[] = [
    '# claude-mem credentials',
    '# This file stores keys and gateway settings for the claude-mem memory agent',
    '# Edit this file or use claude-mem settings to configure',
    '',
  ];

  for (const [key, value] of Object.entries(env)) {
    if (value) {
      const needsQuotes = /[\s#=]/.test(value);
      lines.push(`${key}=${needsQuotes ? `"${value}"` : value}`);
    }
  }

  return lines.join('\n') + '\n';
}

/**
 * Single source of truth for non-OAuth Anthropic credentials (#2375).
 *
 * Contract: ANTHROPIC_API_KEY, ANTHROPIC_BASE_URL, and ANTHROPIC_AUTH_TOKEN
 * are populated ONLY from ~/.claude-mem/.env — never from the parent shell.
 * All three are in BLOCKED_ENV_VARS so process.env values cannot leak into
 * the SDK subprocess; they are re-injected here (and in buildIsolatedEnv)
 * exclusively from the file.
 *
 * The whitelist is enforced by the CREDENTIAL_KEYS copy loop below — only the
 * keys it names are ever copied out (see CREDENTIAL_KEYS for why this must
 * not become Object.assign(result, parsed)).
 */
export function loadClaudeMemEnv(): ClaudeMemEnv {
  const envFile = envFilePath();
  if (!existsSync(envFile)) {
    return {};
  }

  try {
    const content = readFileSync(envFile, 'utf-8');
    const parsed = parseEnvFile(content);

    const result: ClaudeMemEnv = {};
    for (const key of CREDENTIAL_KEYS) {
      if (parsed[key]) result[key] = parsed[key];
    }

    return result;
  } catch (error: unknown) {
    logger.warn('ENV', 'Failed to load .env file', { path: envFile }, error instanceof Error ? error : new Error(String(error)));
    return {};
  }
}

export function saveClaudeMemEnv(env: ClaudeMemEnv): void {
  const envFile = envFilePath();
  let existing: Record<string, string> = {};
  try {
    if (!existsSync(paths.dataDir())) {
      mkdirSync(paths.dataDir(), { recursive: true, mode: 0o700 });
    }
    chmodSync(paths.dataDir(), 0o700);

    existing = existsSync(envFile)
      ? parseEnvFile(readFileSync(envFile, 'utf-8'))
      : {};
  } catch (error) {
    const normalizedError = error instanceof Error ? error : new Error(String(error));
    logger.error('ENV', 'Failed to set up env directory or read existing env', {}, normalizedError);
    throw normalizedError;
  }

  const updated: Record<string, string> = { ...existing };

  // undefined = leave the key untouched; falsy (e.g. '') = delete it.
  for (const key of CREDENTIAL_KEYS) {
    const value = env[key];
    if (value === undefined) continue;
    if (value) {
      updated[key] = value;
    } else {
      delete updated[key];
    }
  }

  try {
    writeFileSync(envFile, serializeEnvFile(updated), { encoding: 'utf-8', mode: 0o600 });
    chmodSync(envFile, 0o600);
  } catch (error: unknown) {
    logger.error('ENV', 'Failed to save .env file', { path: envFile }, error instanceof Error ? error : new Error(String(error)));
    throw error;
  }
}

/**
 * #5400 — Claude Code applies the `env` block of
 * `<Claude config dir>/settings.json` to its own process only. The dir is the
 * credential profile buildIsolatedEnv resolves (CLAUDE_MEM_CLAUDE_CONFIG_DIR
 * setting > CLAUDE_CONFIG_DIR > ~/.claude), so proxies come from the same
 * profile the observer child runs as.
 * The worker is started detached, so those variables are absent from
 * process.env, and the observer CLI is spawned with `settingSources: []`, so
 * it never reads the file either and connects directly (ECONNREFUSED).
 *
 * Copy proxy keys the worker does not already have. An empty string already
 * in the worker env is left alone. Anything else in that block (API keys,
 * CLAUDE_CODE_*) stays out: this is not a general settings-env passthrough.
 * A missing file is the common case and changes nothing; an unparseable one
 * is logged and changes nothing.
 */
function applyMissingProxyEnvFromClaudeSettings(isolatedEnv: Record<string, string>, claudeConfigDir: string): void {
  const settingsPath = join(claudeConfigDir, 'settings.json');
  if (!existsSync(settingsPath)) return;

  let parsed: unknown;
  try {
    parsed = readJsonFileWithBom(settingsPath);
  } catch (error: unknown) {
    // Say so instead of silently spawning the observer without the proxy.
    logger.warn('ENV', 'Could not parse Claude settings.json; its proxy env is not applied', {
      path: settingsPath,
      error: error instanceof Error ? error.message : String(error),
    });
    return;
  }
  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return;

  const settingsEnv = (parsed as { env?: unknown }).env;
  if (settingsEnv === null || typeof settingsEnv !== 'object' || Array.isArray(settingsEnv)) return;

  const source = settingsEnv as Record<string, unknown>;
  for (const key of ENV_PROXY_VARS) {
    if (isolatedEnv[key] !== undefined) continue;
    const value = source[key];
    if (typeof value !== 'string') continue;
    const trimmed = value.trim();
    if (!trimmed) continue;
    isolatedEnv[key] = trimmed;
  }
}

export function buildIsolatedEnv(includeCredentials: boolean = true): Record<string, string> {
  const isolatedEnv: Record<string, string> = {};
  for (const [key, value] of Object.entries(process.env)) {
    if (value !== undefined && !BLOCKED_ENV_VARS.includes(key)) {
      isolatedEnv[key] = value;
    }
  }

  isolatedEnv.CLAUDE_CODE_ENTRYPOINT = 'sdk-ts';

  isolatedEnv.CLAUDE_MEM_INTERNAL = '1';

  // #2753 / #4149 — set CLAUDE_CONFIG_DIR on the SDK SUBPROCESS from the SAME
  // credential profile deriveMacKeychainServiceName (oauth-token.ts) uses to
  // pick the keychain service name, so the child and the worker always agree:
  //   - explicit profile: stamp the effective config dir (the
  //     CLAUDE_MEM_CLAUDE_CONFIG_DIR setting when set, else
  //     process.env.CLAUDE_CONFIG_DIR), so both resolve the suffixed
  //     'Claude Code-credentials-<hash>' keychain entry.
  //   - default profile: leave CLAUDE_CONFIG_DIR UNSET on the child, deleting
  //     any value the blanket process.env copy above carried in. Claude Code
  //     chooses its macOS keychain service name from whether CLAUDE_CONFIG_DIR
  //     is SET, not from its value, so stamping even the default '~/.claude'
  //     made the child hunt for a suffixed entry a normal login never creates
  //     while the worker injects under the bare name. Once the access token
  //     expired the worker stopped injecting, the child could not reach the
  //     refresh token, and capture silently stopped (#4149).
  // This never touches the worker's own paths.CLAUDE_CONFIG_DIR /
  // MARKETPLACE_ROOT, which stay derived solely from
  // process.env.CLAUDE_CONFIG_DIR at module load.
  const configDirSettings = SettingsDefaultsManager.loadFromFile(paths.settings());
  const { configDir, explicitConfigDir } = resolveClaudeCredentialProfile(configDirSettings.CLAUDE_MEM_CLAUDE_CONFIG_DIR);
  // After the process.env copy, so a proxy the worker already has wins.
  applyMissingProxyEnvFromClaudeSettings(isolatedEnv, configDir);
  if (explicitConfigDir) {
    isolatedEnv.CLAUDE_CONFIG_DIR = configDir;
  } else {
    delete isolatedEnv.CLAUDE_CONFIG_DIR;
    // #4689 — CLAUDE_CONFIG_DIR does double duty for the child: it picks the
    // keychain identity AND locates the session-transcript store
    // (${CLAUDE_CONFIG_DIR}/projects/<munged cwd>/). Under the default
    // profile it is deleted above, so every internal SDK session (observer,
    // knowledge corpus) persists into ~/.claude/projects, where importers
    // like Codex pick the transcripts up as user chats. When the user sets a
    // transcript-only dir, stamp it so transcripts land there instead —
    // while the credential profile stays DEFAULT: readClaudeOAuthToken
    // resolves CLAUDE_MEM_CLAUDE_CONFIG_DIR independently below and injects
    // CLAUDE_CODE_OAUTH_TOKEN at spawn time, so the child never needs the
    // (nonexistent) login of the stamped dir. An explicit
    // CLAUDE_MEM_CLAUDE_CONFIG_DIR profile keeps its own stamp above — its
    // credential identity and transcript store are one dir by design
    // (#2753), and the transcript-only setting never overrides it.
    //
    // Trade-off (inherent, not a regression): a token-injected child cannot
    // self-refresh — the refresh token lives in the profile's keychain
    // entry, and a child whose CLAUDE_CONFIG_DIR points elsewhere cannot
    // reach it (#4149's failure mode). Every worker spawn re-reads and
    // re-injects a fresh token, and observer batches are short-lived, so
    // capture keeps working across token rotations; if the stored login
    // itself expires, the stale-login marker surfaces it as usual.
    const transcriptConfigDir = configDirSettings.CLAUDE_MEM_OBSERVER_CLAUDE_CONFIG_DIR?.trim();
    if (transcriptConfigDir) {
      // Same normalization the sister setting goes through
      // (resolveEffectiveClaudeConfigDir): trim → tilde expansion →
      // trailing-separator strip. A value from the settings file or the
      // viewer never passes through a shell, so a docs-style
      // '~/.claude-mem/observer-claude' would otherwise be stamped LITERAL
      // and the child would create <worker cwd>/~/… — and resume would
      // break as soon as the worker cwd changed.
      isolatedEnv.CLAUDE_CONFIG_DIR = resolveEffectiveClaudeConfigDir(transcriptConfigDir);
    }
  }

  if (includeCredentials) {
    const credentials = loadClaudeMemEnv();

    for (const key of CREDENTIAL_KEYS) {
      const value = credentials[key];
      // Injected only by buildIsolatedEnvWithFreshOAuth: the fallback key as ANTHROPIC_API_KEY on a
      // quota-fallback run, the OAuth token on the Claude OAuth path (never toward a gateway).
      if (value && key !== 'ANTHROPIC_FALLBACK_API_KEY' && key !== 'CLAUDE_CODE_OAUTH_TOKEN') isolatedEnv[key] = value;
    }

    // Note: CLAUDE_CODE_OAUTH_TOKEN is intentionally NOT copied from
    // process.env here. OAuth tokens have refresh semantics that this
    // sync path cannot model — copying a parent-process token captured
    // at startup means injecting a stale token days later (issue #2215).
    // Use buildIsolatedEnvWithFreshOAuth() for spawn-time injection.
  }

  // #5315: without the parent gateway, its model aliases are invalid at the
  // Anthropic API. Explicit gateways and cloud backends retain their mappings.
  const usesCloudBackend = ['CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY']
    .some(key => {
      const value = isolatedEnv[key]?.trim().toLowerCase();
      return !!value && value !== '0' && value !== 'false';
    });
  if (!isolatedEnv.ANTHROPIC_BASE_URL && !usesCloudBackend) {
    for (const key of Object.keys(isolatedEnv)) {
      if (MODEL_OVERRIDE_ENV_VAR.test(key) || key === 'CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY') {
        delete isolatedEnv[key];
      }
    }
  }

  return isolatedEnv;
}

/** Credentials for both the OpenCode login probe and its headless run. */
export function buildOpenCodeEnv(): NodeJS.ProcessEnv {
  const env = sanitizeEnv(buildIsolatedEnv());
  const anthropic = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL'] as const;
  // Keep an explicitly configured gateway and its credentials together. Otherwise
  // OpenCode can use its shell login, including the endpoint that goes with it.
  if (!anthropic.some(key => env[key]) && (process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN)) {
    for (const key of anthropic) {
      const value = process.env[key];
      if (value) env[key] = value;
    }
  }
  return env;
}

/**
 * Async variant of buildIsolatedEnv() that reads the OAuth token from the
 * platform-native credential store at the moment of spawn. Use this at SDK
 * spawn-time so the worker subprocess always gets a fresh token.
 *
 * Behavior per OAuthTokenResult:
 *   - present: inject as CLAUDE_CODE_OAUTH_TOKEN env var, clear stale marker.
 *     A stored login close to expiry is left to the CLI instead (#6650).
 *   - expired: do NOT inject. Log re-login message. Write stale marker so
 *     the session-start hook can surface the message to the user.
 *   - absent: proceed without the token. Worker may fall back to
 *     ANTHROPIC_API_KEY or other auth. Without one, log a WARN and pass the
 *     reason to onUnusableLogin for the session notice (#6319).
 *   - expired because the CLI ended the login (no refresh token left): the
 *     stale marker as for expired, then the absent handling (#6319).
 *
 * Issue #2215: this replaces the old "copy CLAUDE_CODE_OAUTH_TOKEN from
 * process.env" path which silently injected stale tokens.
 */
export async function buildIsolatedEnvWithFreshOAuth(
  includeCredentials: boolean = true,
  /**
   * The credential a quota-fallback run bills instead of the primary one
   * (ActiveSession.claudeAuthOverride): 'subscription' bills the Claude Code
   * login even though .env holds a key; 'api-key' bills ANTHROPIC_FALLBACK_API_KEY.
   * Either keeps the primary credential when the other one is missing, and
   * both are ignored under ANTHROPIC_BASE_URL.
   */
  {
    standIn,
    onUnusableLogin,
  }: {
    standIn?: ClaudeCredential;
    /**
     * Called with the reason when this spawn leaves the child no login it can
     * use and no explicit credential stands in (#6319): the store held none,
     * the CLI had ended it, or the read failed. The caller keeps it on the
     * run, so a "Not logged in" reply can be explained per session.
     */
    onUnusableLogin?: (reason: string) => void;
  } = {},
): Promise<Record<string, string>> {
  const isolatedEnv = buildIsolatedEnv(includeCredentials);

  // Defensive: ensure no parent-process OAuth token survives this path even
  // if BLOCKED_ENV_VARS is bypassed. Issue #2215.
  delete isolatedEnv.CLAUDE_CODE_OAUTH_TOKEN;

  if (!includeCredentials) return isolatedEnv;

  // Custom gateway: never inject OAuth (would leak the user's Anthropic OAuth
  // token to a third-party gateway). The user must explicitly configure a
  // gateway-appropriate token in ~/.claude-mem/.env if their gateway requires
  // one. A bare BASE_URL with no token = tokenless gateway (e.g. mTLS at the
  // network boundary).
  //
  // Post-#2375: ANTHROPIC_BASE_URL is in BLOCKED_ENV_VARS, so it can ONLY be
  // present in isolatedEnv when the user intentionally configured it in
  // ~/.claude-mem/.env (see loadClaudeMemEnv re-injection above). A BASE_URL
  // leaked from the parent shell no longer reaches this predicate — that was
  // the root cause of #2375 (leaked BASE_URL → OAuth-skip → no credential at
  // all). Keeping the BASE_URL branch here is therefore the *security*-correct
  // behavior: it prevents the OAuth token from being sent to a user-configured
  // third-party gateway. It is NOT the leak path it was before the deny-list.
  if (isolatedEnv.ANTHROPIC_BASE_URL) {
    clearStaleMarker();
    return isolatedEnv;
  }
  if (standIn === 'api-key') {
    const fallbackKey = loadClaudeMemEnv().ANTHROPIC_FALLBACK_API_KEY;
    if (fallbackKey) {
      delete isolatedEnv.ANTHROPIC_AUTH_TOKEN;
      isolatedEnv.ANTHROPIC_API_KEY = fallbackKey;
      return isolatedEnv;
    }
    logger.warn('OAUTH', 'Quota fallback API key unavailable (ANTHROPIC_FALLBACK_API_KEY is not set); using the primary credential');
  }
  const preferOAuth = standIn === 'subscription';
  const explicitCredentials = {
    ...(isolatedEnv.ANTHROPIC_API_KEY ? { ANTHROPIC_API_KEY: isolatedEnv.ANTHROPIC_API_KEY } : {}),
    ...(isolatedEnv.ANTHROPIC_AUTH_TOKEN ? { ANTHROPIC_AUTH_TOKEN: isolatedEnv.ANTHROPIC_AUTH_TOKEN } : {}),
  };
  const hasExplicitCredentials = Object.keys(explicitCredentials).length > 0;
  // Direct API with explicit credentials: skip OAuth lookup.
  if (hasExplicitCredentials && !preferOAuth) {
    clearStaleMarker();
    return isolatedEnv;
  }
  // The CLI prefers a key over the token, so the key must go for the login to bill.
  delete isolatedEnv.ANTHROPIC_API_KEY;
  delete isolatedEnv.ANTHROPIC_AUTH_TOKEN;
  const restoreExplicitCredentials = (reason: string): Record<string, string> => {
    if (hasExplicitCredentials) {
      logger.warn('OAUTH', `Subscription stand-in unavailable (${reason}); using the .env credentials`);
      Object.assign(isolatedEnv, explicitCredentials);
    }
    return isolatedEnv;
  };

  // plan-19 (#3607) item 4: a long-lived token the user put in ~/.claude-mem/.env
  // (`claude setup-token`) is an explicit auth source, so it goes ahead of the
  // credential store. It needs no refresh, so no spawned child ever rotates a
  // refresh token a worker recycle could interrupt, and a stored login reaching
  // its end date no longer stops capture (#5307).
  const configuredToken = loadClaudeMemEnv().CLAUDE_CODE_OAUTH_TOKEN;
  if (configuredToken) {
    const expiresAt = decodeJwtExpMs(configuredToken);
    if (!isPastExpiry(expiresAt)) {
      isolatedEnv.CLAUDE_CODE_OAUTH_TOKEN = configuredToken;
      logger.info('OAUTH', 'Injected CLAUDE_CODE_OAUTH_TOKEN from ~/.claude-mem/.env at spawn-time', {
        source: 'claude-mem-env',
        expiresAt,
      });
      clearStaleMarker();
      return isolatedEnv;
    }
    logger.warn(
      'OAUTH',
      'CLAUDE_CODE_OAUTH_TOKEN in ~/.claude-mem/.env has expired; using the Claude Code credential store. Replace it with a new `claude setup-token` token.',
      { expiresAt },
    );
  }

  let result: OAuthTokenResult;
  try {
    result = await readClaudeOAuthToken();
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    logger.warn('OAUTH', 'OAuth token read failed unexpectedly; proceeding without token', {}, err);
    if (!hasExplicitCredentials) onUnusableLogin?.(`the credential store read failed: ${err.message}`);
    return restoreExplicitCredentials('token read failed');
  }

  switch (result.kind) {
    case 'present':
      // #6650: a child given the token by env keeps it for its whole run and
      // cannot refresh it. Claude Code refreshes a stored login in its last
      // minutes and revokes the old token, so near expiry the child reads
      // the store itself, as it does once the login has lapsed.
      if (result.source !== 'env-fallback' && isNearExpiry(result.expiresAt)) {
        logger.info('OAUTH', 'Stored Claude Code login is about to be refreshed; leaving it to the CLI', {
          source: result.source,
          expiresAt: result.expiresAt,
        });
        clearStaleMarker();
        break;
      }
      isolatedEnv.CLAUDE_CODE_OAUTH_TOKEN = result.token;
      logger.info('OAUTH', 'Injected fresh CLAUDE_CODE_OAUTH_TOKEN at spawn-time', {
        source: result.source,
        expiresAt: result.expiresAt,
      });
      clearStaleMarker();
      break;
    case 'expired':
      logger.warn(
        'OAUTH',
        `Refusing to inject expired CLAUDE_CODE_OAUTH_TOKEN: ${result.reason}. Run /login in Claude Code (or \`claude auth login\` in a terminal) to refresh it.`,
        { expiresAt: result.expiresAt },
      );
      writeStaleMarker(result.reason);
      break;
    case 'absent':
      // Token is absent — any prior stale-marker would have been written
      // when the token was expired, but is no longer accurate now that the
      // token is gone. Clear it so the session-start hook stops surfacing
      // a stale "expired token, re-login" warning (CodeRabbit review on PR
      // #2282).
      clearStaleMarker();
      break;
  }

  // Leave lapsed logins to the CLI's refresh flow without the spent key taking
  // precedence. A login the CLI ENDED has no refresh token left (#6319), so,
  // like a missing one, it leaves the child nothing to run on.
  if (result.kind === 'present' || (result.kind === 'expired' && result.loginEnded === undefined)) return isolatedEnv;
  if (hasExplicitCredentials) return restoreExplicitCredentials(result.kind === 'absent' ? 'token absent' : 'login ended');
  // #6319: this used to be a DEBUG line, so at INFO the log went quiet while
  // every observer call answered "Not logged in". The `present` branch logs
  // INFO on every spawn, so a WARN per spawn here is the same rate. An ended
  // login already got its WARN above.
  if (result.kind === 'absent') {
    logger.warn(
      'OAUTH',
      `No Claude Code login could be read for the observer (${result.reason}); the observer will rely on the CLI finding its own login. If observations fail with "Not logged in", put a \`claude setup-token\` token in ~/.claude-mem/.env as CLAUDE_CODE_OAUTH_TOKEN.`,
    );
  }
  onUnusableLogin?.(result.reason);
  return isolatedEnv;
}

export function getCredential(key: keyof ClaudeMemEnv): string | undefined {
  const env = loadClaudeMemEnv();
  return env[key];
}

export function hasAnthropicApiKey(): boolean {
  const env = loadClaudeMemEnv();
  return !!env.ANTHROPIC_API_KEY;
}

export function hasAnthropicAuthToken(): boolean {
  const env = loadClaudeMemEnv();
  return !!env.ANTHROPIC_AUTH_TOKEN;
}

/** Whether a JWT `exp` (ms) has passed. An opaque `claude setup-token` token has none and never counts as expired. */
function isPastExpiry(expiresAt: number | undefined): boolean {
  return expiresAt !== undefined && expiresAt <= Date.now();
}

/**
 * #6650: how long before expiry a stored login stops being injected. Claude
 * Code refreshes in the last 5 minutes, and the observers revoked in #6650
 * had been running for up to 6 minutes by then.
 */
const STORED_LOGIN_REFRESH_MARGIN_MS = 15 * 60_000;

function isNearExpiry(expiresAt: number | undefined): boolean {
  return expiresAt !== undefined && expiresAt - STORED_LOGIN_REFRESH_MARGIN_MS <= Date.now();
}

/**
 * Whether ~/.claude-mem/.env holds a CLAUDE_CODE_OAUTH_TOKEN the next spawn
 * would use (never one inherited from the shell). A JWT past its `exp` doesn't
 * count: buildIsolatedEnvWithFreshOAuth skips it, so agent detection and the
 * quota fallback go on to the stored login instead of starting a doomed run.
 */
export function hasConfiguredClaudeOAuthToken(): boolean {
  const token = loadClaudeMemEnv().CLAUDE_CODE_OAUTH_TOKEN;
  return !!token && !isPastExpiry(decodeJwtExpMs(token));
}

export function getAuthMethodDescription(): string {
  if (hasAnthropicApiKey()) {
    return 'API key (from ~/.claude-mem/.env)';
  }
  if (hasAnthropicAuthToken()) {
    return 'Gateway auth token (from ~/.claude-mem/.env)';
  }
  if (hasConfiguredClaudeOAuthToken()) {
    return 'Long-lived CLAUDE_CODE_OAUTH_TOKEN (from ~/.claude-mem/.env)';
  }
  // Note: this is a quick sync hint for logging — the authoritative OAuth
  // path is buildIsolatedEnvWithFreshOAuth() which reads the keychain at
  // spawn time. process.env may or may not carry a token here.
  // #2753: names the resolved profile (suffix/dir basename or 'default'),
  // never the token itself — the profile is the whole point (which
  // config-dir identity's keychain entry this worker will inject).
  const profile = resolveConfigDirProfileLabel();
  if (process.env.CLAUDE_CODE_OAUTH_TOKEN) {
    return `Claude Code OAuth token (env, refreshed via keychain at spawn) profile=${profile}`;
  }
  return `Claude Code OAuth token (read from the Claude Code credential store at spawn) profile=${profile}`;
}