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

42.7 KB
Raw Blame
import type { ChildProcessWithoutNullStreams } from 'node:child_process';
import {
  chmodSync,
  constants as fsConstants,
  copyFileSync,
  mkdirSync,
  mkdtempSync,
  readdirSync,
  readFileSync,
  rmSync,
  statSync,
  symlinkSync,
  writeFileSync,
  type Stats,
} from 'node:fs';
import { rm } from 'node:fs/promises';
import { homedir, tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { executableFingerprint } from '../../shared/executable-fingerprint.js';
import { killProcessTree } from '../../shared/kill-process-tree.js';
import { buildSpawnSyncInvocation, lookupWindowsCommand, spawnHidden } from '../../shared/spawn.js';
import { ENV_PROXY_VARS, sanitizeEnv } from '../../supervisor/env-sanitizer.js';
import { getSupervisor } from '../../supervisor/index.js';
import { logger } from '../../utils/logger.js';

const APP_SERVER_WORKDIR_PREFIX = 'claude-mem-codex-app-server-';
// Each private runtime records the worker that owns it, so a later worker can
// tell a leftover from a root another live worker is still using.
const APP_SERVER_OWNER_FILE = 'owner.json';
// Roots written before owner.json existed have no owner to ask; once they are
// this old they are treated as left behind.
const LEGACY_APP_SERVER_WORKDIR_MAX_AGE_MS = 6 * 60 * 60 * 1000;
const MAX_PROTOCOL_LINE_BYTES = 8 * 1024 * 1024;
const MAX_STDERR_TAIL_BYTES = 64 * 1024;
const INTERRUPT_TIMEOUT_MS = 5_000;

const DISABLED_FEATURES = [
  'apps',
  'artifact',
  'browser_use',
  'browser_use_external',
  'browser_use_full_cdp_access',
  'chronicle',
  'code_mode',
  'code_mode_only',
  'computer_use',
  'current_time_reminder',
  'default_mode_request_user_input',
  'deferred_executor',
  'goals',
  'hooks',
  'image_generation',
  'memories',
  'multi_agent',
  'multi_agent_v2',
  'plugins',
  'request_permissions_tool',
  'skill_search',
  'shell_tool',
  'standalone_web_search',
  'token_budget',
  'unified_exec',
  'view_image',
  'web_search_cached',
  'web_search_request',
  'workspace_dependencies',
] as const;

const FORBIDDEN_ITEM_TYPES = new Set([
  'commandExecution',
  'fileChange',
  'mcpToolCall',
  'dynamicToolCall',
  'collabAgentToolCall',
  'subAgentActivity',
  'webSearch',
  'imageView',
  'imageGeneration',
]);
const TERMINAL_TURN_STATUSES = new Set(['completed', 'interrupted', 'failed']);

const EMPTY_HOOKS = {
  PreToolUse: [],
  PermissionRequest: [],
  PostToolUse: [],
  PreCompact: [],
  PostCompact: [],
  SessionStart: [],
  UserPromptSubmit: [],
  SubagentStart: [],
  SubagentStop: [],
  Stop: [],
};

type JsonObject = Record<string, unknown>;

interface PendingRequest {
  resolve: (value: unknown) => void;
  reject: (error: Error) => void;
  timer: ReturnType<typeof setTimeout>;
  removeAbort?: () => void;
}

interface ActiveTurn {
  threadId: string;
  turnId: string | null;
  finalText: string | null;
  completedItems: number;
  agentMessages: number;
  terminalItems: number;
  tokenUsage: JsonObject | null;
  terminalTurn: JsonObject | null;
  protocolError: Error | null;
  completion: Promise<void>;
  complete: () => void;
}

interface PrivateRuntime {
  root: string;
  workspace: string;
  codexHome: string;
}

export interface CodexAppServerClientOptions {
  nativeCodexHome?: string;
}

export interface CodexAppServerTurnOptions {
  codexPath: string;
  model: string;
  reasoningEffort: string | null;
  prompt: string;
  timeoutMs: number;
  signal?: AbortSignal;
  /** Recheck caller-owned admission after waiting in the serialized queue. */
  beforeSend?: () => void;
  /** Publish admission failures before releasing the queue to the next caller. */
  onFailure?: (error: unknown) => void;
}

export interface CodexAppServerTurnResult {
  content: string;
  inputTokens?: number;
  outputTokens?: number;
  tokensUsed?: number;
}

export function buildCodexAppServerArgs(): string[] {
  return ['app-server', '--listen', 'stdio://'];
}

export function buildCodexAppServerLaunch(
  codexPath: string,
  platform: NodeJS.Platform = process.platform,
  findCommand: (command: string) => string | null = lookupWindowsCommand,
): { command: string; args: string[]; windowsVerbatimArguments?: boolean } {
  const command = platform === 'win32' && codexPath === 'codex'
    ? findCommand('codex') ?? 'codex.cmd'
    : codexPath;
  const invocation = buildSpawnSyncInvocation(command, buildCodexAppServerArgs(), { encoding: 'utf-8' }, platform);
  return {
    command: invocation.command,
    args: invocation.args,
    windowsVerbatimArguments: invocation.options.windowsVerbatimArguments,
  };
}

export function buildCodexAppServerThreadConfig(mcpServerNames: readonly string[]): JsonObject {
  const config: JsonObject = {
    project_doc_max_bytes: 0,
    include_environment_context: false,
    'agents.enabled': false,
    'orchestrator.mcp.enabled': false,
    'orchestrator.skills.enabled': false,
    'skills.bundled.enabled': false,
    'skills.include_instructions': false,
    'tools.experimental_request_user_input.enabled': false,
    hooks: EMPTY_HOOKS,
    notify: [],
    web_search: 'disabled',
  };

  for (const feature of DISABLED_FEATURES) {
    config[`features.${feature}`] = false;
  }

  if (mcpServerNames.length > 0) {
    config.mcp_servers = Object.fromEntries(
      [...new Set(mcpServerNames)].sort().map(name => [name, { enabled: false }]),
    );
  }

  return config;
}

function isObject(value: unknown): value is JsonObject {
  return value !== null && typeof value === 'object' && !Array.isArray(value);
}

function asString(value: unknown, label: string): string {
  if (typeof value !== 'string' || value.length === 0) {
    throw new Error(`Codex app-server returned invalid ${label}`);
  }
  return value;
}

/** Keeps the app-server TurnError text and structured code available for classification. */
function codexTurnError(prefix: string, error: unknown): Error {
  const detail = isObject(error) && typeof error.message === 'string' && error.message.trim()
    ? `: ${error.message}`
    : '';
  const result = new Error(`${prefix}${detail}`);
  if (isObject(error) && error.codexErrorInfo != null) {
    Object.assign(result, { codexErrorInfo: error.codexErrorInfo });
  }
  return result;
}

function resolveNativeCodexHome(explicitHome?: string): string {
  const configured = explicitHome || process.env.CODEX_HOME;
  // The auth symlink lives in a different directory: resolve the selected
  // profile from the caller's cwd, preserving the path Codex itself uses.
  return resolve(configured || join(process.env.HOME || homedir(), '.codex'));
}

/**
 * `code` on a failure the user fixes on this machine (log in with ChatGPT,
 * tighten the auth file), so it is classified as setup rather than guessed
 * from its wording.
 */
export const CODEX_SETUP_REQUIRED_CODE = 'codex_setup_required';

function codexSetupError(message: string): Error {
  return Object.assign(new Error(message), { code: CODEX_SETUP_REQUIRED_CODE });
}

/** Codex infers ChatGPT for legacy token files whose optional auth_mode is absent or null. */
function hasChatGptAuth(auth: unknown): boolean {
  if (!isObject(auth)) return false;
  if (auth.auth_mode != null) return auth.auth_mode === 'chatgpt' || auth.auth_mode === 'chatgptAuthTokens';
  // AuthDotJson.resolved_mode gives these credential fields precedence over
  // legacy ChatGPT tokens. Even an empty API-key string selects API-key auth.
  return isObject(auth.tokens) && [auth.OPENAI_API_KEY, auth.personal_access_token,
    auth.bedrock_api_key, auth.bedrock_access_keys].every(value => value == null);
}

/**
 * `code` on a turn that completed without any agent message. The turn ran and
 * was billed, so it is an output failure, never resent ("never pay twice"); it
 * is classified by code rather than by its diagnostic text.
 */
export const CODEX_NO_AGENT_MESSAGE_CODE = 'codex_no_agent_message';

/**
 * `code` on a completed turn whose structured output was malformed (not JSON,
 * or no string `content`). Like a missing agent message, the turn was billed:
 * an output failure, never resent.
 */
export const CODEX_MALFORMED_OUTPUT_CODE = 'codex_malformed_structured_output';

/**
 * `code` on a turn refused because Codex could not attest the observer's
 * isolation: it loaded instruction sources, or kept MCP servers, that the
 * observer cannot switch off. The Codex configuration on this machine decides
 * that, so every turn is refused the same way until it changes.
 */
export const CODEX_ISOLATION_UNATTESTED_CODE = 'codex_isolation_unattested';

function codexIsolationError(message: string): Error {
  return Object.assign(new Error(message), { code: CODEX_ISOLATION_UNATTESTED_CODE });
}

let sweptStaleWorkdirs = false;

function isProcessAlive(pid: number): boolean {
  try {
    process.kill(pid, 0);
    return true;
  } catch (error) {
    // EPERM: the process exists but belongs to another user.
    return (error as NodeJS.ErrnoException).code === 'EPERM';
  }
}

function readAppServerOwnerPid(root: string): number | null {
  try {
    const owner = JSON.parse(readFileSync(join(root, APP_SERVER_OWNER_FILE), 'utf8')) as { pid?: unknown };
    return typeof owner.pid === 'number' && Number.isInteger(owner.pid) && owner.pid > 0 ? owner.pid : null;
  } catch {
    return null;
  }
}

export interface SweepStaleAppServerWorkdirsOptions {
  baseDir?: string;
  now?: number;
  legacyMaxAgeMs?: number;
  isPidAlive?: (pid: number) => boolean;
}

/**
 * Remove private runtimes that a crashed or killed worker left in the temp
 * directory (#4788). invalidate() removes a root on a normal exit, but nothing
 * runs when the worker itself dies, and each leftover holds a Codex home.
 * A root is removed only when its owner process is dead, or, for roots that
 * predate owner.json, when it is older than legacyMaxAgeMs. The directory scan
 * is synchronous and cheap; the deletions run asynchronously, and the promise
 * resolves with the removed paths once they settle. Never rejects: a directory
 * still held open (Windows) is retried on the next sweep.
 */
export async function sweepStaleAppServerWorkdirs(options: SweepStaleAppServerWorkdirsOptions = {}): Promise<string[]> {
  const {
    baseDir = tmpdir(),
    now = Date.now(),
    legacyMaxAgeMs = LEGACY_APP_SERVER_WORKDIR_MAX_AGE_MS,
    isPidAlive = isProcessAlive,
  } = options;
  let names: string[];
  try {
    names = readdirSync(baseDir);
  } catch {
    return [];
  }
  const staleRoots: string[] = [];
  for (const name of names) {
    if (!name.startsWith(APP_SERVER_WORKDIR_PREFIX)) continue;
    const root = join(baseDir, name);
    try {
      const stat = statSync(root);
      if (!stat.isDirectory()) continue;
      const ownerPid = readAppServerOwnerPid(root);
      if (ownerPid !== null ? isPidAlive(ownerPid) : now - stat.mtimeMs < legacyMaxAgeMs) continue;
      staleRoots.push(root);
    } catch { /* best effort */ }
  }
  const results = await Promise.allSettled(
    staleRoots.map(root => rm(root, { recursive: true, force: true }).then(() => root)),
  );
  return results.flatMap(result => (result.status === 'fulfilled' ? [result.value] : []));
}

export type ScopedAuthMode = 'symlink' | 'copy';

export interface ProvisionScopedAuthOptions {
  platform?: NodeJS.Platform;
  symlink?: (target: string, path: string, type: 'file') => void;
  copy?: (source: string, destination: string, mode?: number) => void;
}

// Windows refuses file symlinks to an unprivileged process unless Developer
// Mode is on. Node reports that as EPERM (or EACCES); ENOTSUP covers a
// filesystem with no symlink support.
const SYMLINK_UNAVAILABLE_CODES = new Set(['EPERM', 'EACCES', 'ENOTSUP']);

/**
 * Give the private Codex home the user's ChatGPT credentials.
 *
 * Never hard-link them. Codex saves credentials (`codex login`, token refresh)
 * by writing a temporary file and renaming it over the original, and it refuses
 * to do that when the file has more than one hard link (`persist_failed: atomic
 * credential replacement does not support hard-linked files`). A hard link from
 * this private home made the user's own `auth.json` unwritable for as long as the
 * app-server's home existed, so signing in to Codex failed while claude-mem ran.
 *
 * A symlink is the supported way to share the file: Codex follows it and
 * replaces the real file, so a refresh in either home reaches both. Where the
 * platform cannot create one (Windows without Developer Mode or elevation) the
 * private home gets its own copy instead. That copy is a snapshot, like the
 * login the app-server read at start; `recycle()` starts a fresh app-server that
 * copies the current credentials.
 */
export function provisionScopedAuth(
  nativeAuth: string,
  scopedAuth: string,
  options: ProvisionScopedAuthOptions = {},
): ScopedAuthMode {
  const { platform = process.platform, symlink = symlinkSync, copy = copyFileSync } = options;
  try {
    symlink(nativeAuth, scopedAuth, 'file');
    return 'symlink';
  } catch (error) {
    // Elsewhere symlinks always work, and a copy would quietly diverge from the
    // user's login, so only Windows may fall back, and only for a permission
    // problem.
    const code = (error as NodeJS.ErrnoException | undefined)?.code;
    if (platform !== 'win32' || code === undefined || !SYMLINK_UNAVAILABLE_CODES.has(code)) throw error;
  }
  copy(nativeAuth, scopedAuth, fsConstants.COPYFILE_EXCL);
  return 'copy';
}

function requireCodexChatGptLogin(nativeCodexHome: string): string {
  const nativeAuth = join(nativeCodexHome, 'auth.json');
  let authStat: Stats;
  try {
    authStat = statSync(nativeAuth);
  } catch (error) {
    throw codexSetupError(`No Codex ChatGPT login at ${nativeAuth} (run \`codex login\`): ${error instanceof Error ? error.message : String(error)}`);
  }
  if (!authStat.isFile()) throw codexSetupError(`Codex ChatGPT auth is not a file: ${nativeAuth}`);
  if (process.platform !== 'win32') {
    if (typeof process.getuid === 'function' && authStat.uid !== process.getuid()) {
      throw codexSetupError(`Codex ChatGPT auth is not owned by the claude-mem worker user: ${nativeAuth}`);
    }
    if ((authStat.mode & 0o077) !== 0) {
      throw codexSetupError(`Codex ChatGPT auth permissions must deny group and other access: ${nativeAuth}`);
    }
  }
  let auth: unknown;
  try {
    auth = JSON.parse(readFileSync(nativeAuth, 'utf8'));
  } catch (error) {
    throw codexSetupError(`Cannot read Codex ChatGPT auth: ${error instanceof Error ? error.message : String(error)}`);
  }
  if (!hasChatGptAuth(auth)) {
    throw codexSetupError('claude-mem requires Codex CLI to be logged in with ChatGPT, not an API key');
  }
  return nativeAuth;
}

export function hasCodexChatGptLogin(): boolean {
  try {
    requireCodexChatGptLogin(resolveNativeCodexHome());
    return true;
  } catch {
    return false;
  }
}

function createPrivateRuntime(nativeCodexHome: string): PrivateRuntime {
  if (!sweptStaleWorkdirs) {
    sweptStaleWorkdirs = true;
    // Not awaited: removing many leftover Codex homes must not delay this turn.
    void sweepStaleAppServerWorkdirs().then(removed => {
      if (removed.length > 0) logger.debug('SDK', 'Removed stale Codex app-server workdirs', { count: removed.length });
    });
  }
  const root = mkdtempSync(join(tmpdir(), APP_SERVER_WORKDIR_PREFIX));
  try {
    writeFileSync(
      join(root, APP_SERVER_OWNER_FILE),
      JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }),
      { mode: 0o600 },
    );
    const workspace = join(root, 'workspace');
    const codexHome = join(root, 'codex-home');
    mkdirSync(workspace, { mode: 0o700 });
    mkdirSync(codexHome, { mode: 0o700 });
    if (process.platform !== 'win32') {
      chmodSync(root, 0o700);
      chmodSync(workspace, 0o700);
      chmodSync(codexHome, 0o700);
    }

    const nativeAuth = requireCodexChatGptLogin(nativeCodexHome);
    provisionScopedAuth(nativeAuth, join(codexHome, 'auth.json'));
    return { root, workspace, codexHome };
  } catch (error) {
    rmSync(root, { recursive: true, force: true });
    throw error;
  }
}

function tokenNumber(value: unknown): number | undefined {
  return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
}

function normalizeUsage(usage: JsonObject | null): Omit<CodexAppServerTurnResult, 'content'> {
  if (!usage) return {};

  const total = isObject(usage.total) ? usage.total : usage;
  // Codex's input/output totals already include their cache/reasoning
  // breakdowns. Adding those details again inflates usage and context size.
  const inputTokens = tokenNumber(total.inputTokens ?? total.input_tokens);
  const outputTokens = tokenNumber(total.outputTokens ?? total.output_tokens);
  const tokensUsed = inputTokens === undefined && outputTokens === undefined
    ? undefined
    : (inputTokens ?? 0) + (outputTokens ?? 0);

  return {
    ...(inputTokens !== undefined ? { inputTokens } : {}),
    ...(outputTokens !== undefined ? { outputTokens } : {}),
    ...(tokensUsed !== undefined ? { tokensUsed } : {}),
  };
}

export class CodexAppServerClient {
  private readonly nativeCodexHome: string;
  private child: ChildProcessWithoutNullStreams | null = null;
  private startPromise: Promise<void> | null = null;
  private nextRequestId = 1;
  private pending = new Map<number, PendingRequest>();
  private protocolFragments: string[] = [];
  private protocolLineBytes = 0;
  private stderrTail = '';
  private privateRoot: string | null = null;
  private workspace: string | null = null;
  private codexPath = '';
  private binaryFingerprint = '';
  private activeTurn: ActiveTurn | null = null;
  private queueTail: Promise<void> = Promise.resolve();
  private closed = false;
  private closePromise: Promise<void> | null = null;
  private cleanupPromise: Promise<void> = Promise.resolve();

  constructor(options: CodexAppServerClientOptions = {}) {
    this.nativeCodexHome = resolveNativeCodexHome(options.nativeCodexHome);
  }

  async runTurn(options: CodexAppServerTurnOptions): Promise<CodexAppServerTurnResult> {
    return this.withExclusive(options.signal, async () => {
      try {
        return await this.runTurnExclusive(options);
      } catch (error) {
        options.onFailure?.(error);
        throw error;
      }
    });
  }

  async close(): Promise<void> {
    if (this.closePromise) return this.closePromise;

    this.closed = true;
    const queueDrained = this.queueTail;
    this.closePromise = (async () => {
      await this.invalidate(new Error('Codex app-server client closed'));
      await queueDrained;
    })();
    return this.closePromise;
  }

  /**
   * Kill the running app-server child without retiring this client, so the
   * next `ensureStarted()` spawns a fresh process that reads the current
   * credentials from disk. Used by the pool when a recovery probe follows
   * an auth cooldown: the stale child still holds the old OAuth token in
   * memory, and a `codex login` in another terminal wrote new tokens that
   * only a fresh spawn will pick up.
   */
  async recycle(): Promise<void> {
    if (this.closed || !this.child) return;
    await this.invalidate(new Error('Codex app-server recycled for credential refresh'));
  }

  private async withExclusive<T>(signal: AbortSignal | undefined, operation: () => Promise<T>): Promise<T> {
    if (this.closed) throw new Error('Codex app-server client closed');

    const previous = this.queueTail;
    let release!: () => void;
    const hold = new Promise<void>(resolve => { release = resolve; });
    this.queueTail = previous.then(() => hold);

    let removeAbort: (() => void) | undefined;
    try {
      if (signal?.aborted) throw new Error('Codex app-server turn aborted while queued');
      if (signal) {
        await Promise.race([
          previous,
          new Promise<never>((_, reject) => {
            const onAbort = () => reject(new Error('Codex app-server turn aborted while queued'));
            signal.addEventListener('abort', onAbort, { once: true });
            removeAbort = () => signal.removeEventListener('abort', onAbort);
          }),
        ]);
      } else {
        await previous;
      }
      if (this.closed) throw new Error('Codex app-server client closed');
      if (signal?.aborted) throw new Error('Codex app-server turn aborted while queued');
      return await operation();
    } finally {
      removeAbort?.();
      release();
    }
  }

  private async runTurnExclusive(options: CodexAppServerTurnOptions): Promise<CodexAppServerTurnResult> {
    options.beforeSend?.();
    await this.ensureStarted(options.codexPath, options.timeoutMs, options.signal);
    const workspace = this.workspace;
    if (!workspace) throw new Error('Codex app-server workspace is unavailable');

    const mcpServerNames = await this.readInheritedMcpServerNames(workspace, options.timeoutMs, options.signal);
    const threadConfig = buildCodexAppServerThreadConfig(mcpServerNames);
    const threadResponse = await this.request('thread/start', {
      ...(options.model ? { model: options.model } : {}),
      cwd: workspace,
      runtimeWorkspaceRoots: [workspace],
      approvalPolicy: 'on-request',
      sandbox: 'read-only',
      serviceName: 'claude-mem',
      baseInstructions: '',
      developerInstructions: [
        'You are the claude-mem memory compression worker.',
        'Use only the supplied text. Do not call tools or inspect the host.',
        'Return the requested text in the JSON content field.',
      ].join(' '),
      config: threadConfig,
      environments: [],
      dynamicTools: [],
      selectedCapabilityRoots: [],
      experimentalRawEvents: true,
      ephemeral: true,
    }, options.timeoutMs, options.signal);

    if (!isObject(threadResponse) || !isObject(threadResponse.thread)) {
      throw new Error('Codex app-server returned invalid thread/start response');
    }
    const instructionSources = threadResponse.instructionSources;
    if (!Array.isArray(instructionSources)) {
      throw codexIsolationError('Codex app-server omitted instructionSources attestation');
    }
    if (instructionSources.length > 0) {
      throw codexIsolationError(`Codex app-server loaded unexpected instruction sources: ${instructionSources.join(', ')}`);
    }

    const threadId = asString(threadResponse.thread.id, 'thread id');
    await this.attestMcpServersDisabled(threadId, mcpServerNames, options.timeoutMs, options.signal);

    let complete!: () => void;
    const completion = new Promise<void>(resolve => { complete = resolve; });
    const active: ActiveTurn = {
      threadId,
      turnId: null,
      finalText: null,
      completedItems: 0,
      agentMessages: 0,
      terminalItems: 0,
      tokenUsage: null,
      terminalTurn: null,
      protocolError: null,
      completion,
      complete,
    };
    this.activeTurn = active;

    try {
      options.beforeSend?.();
      const turnResponse = await this.request('turn/start', {
        threadId,
        input: [{ type: 'text', text: options.prompt }],
        ...(options.model ? { model: options.model } : {}),
        ...(options.reasoningEffort ? { effort: options.reasoningEffort } : {}),
        environments: [],
        outputSchema: {
          type: 'object',
          properties: { content: { type: 'string' } },
          required: ['content'],
          additionalProperties: false,
        },
      }, options.timeoutMs, options.signal);

      if (!isObject(turnResponse) || !isObject(turnResponse.turn)) {
        throw new Error('Codex app-server returned invalid turn/start response');
      }
      active.turnId = asString(turnResponse.turn.id, 'turn id');
      this.acceptTerminalTurn(active, turnResponse.turn);

      if (!active.terminalTurn) {
        await this.waitForTurn(active, options.timeoutMs, options.signal);
      }
      if (active.protocolError) throw active.protocolError;
      if (!active.terminalTurn) throw new Error('Codex app-server turn ended without terminal state');
      if (active.terminalTurn.status !== 'completed') {
        throw codexTurnError(`Codex app-server turn ${String(active.terminalTurn.status)}`, active.terminalTurn.error);
      }
      if (active.finalText === null) {
        throw Object.assign(
          new Error(`Codex app-server completed without a final agent message (${this.describeEmptyTurn(active)})`),
          { code: CODEX_NO_AGENT_MESSAGE_CODE },
        );
      }

      let structured: unknown;
      try {
        structured = JSON.parse(active.finalText);
      } catch (error) {
        throw Object.assign(
          new Error(`Codex app-server returned malformed structured output: ${error instanceof Error ? error.message : String(error)}`),
          { code: CODEX_MALFORMED_OUTPUT_CODE },
        );
      }
      if (!isObject(structured) || typeof structured.content !== 'string') {
        throw Object.assign(
          new Error('Codex app-server structured output omitted string content'),
          { code: CODEX_MALFORMED_OUTPUT_CODE },
        );
      }
      const content = structured.content.trim();
      if (!content) {
        // The model's answer, passed on as one: the observer's skip contract
        // (ResponseProcessor) decides what an empty reply to queued work means.
        // Retrying it here as a transport fault re-sent the whole history and
        // kept the batch pending without bound. Counts only, never the text.
        logger.warn('SDK', 'Codex app-server returned empty structured content', {
          diagnostics: this.describeEmptyTurn(active),
        });
      }
      return { content, ...normalizeUsage(active.tokenUsage) };
    } finally {
      if (this.activeTurn === active) this.activeTurn = null;
      await this.request('thread/unsubscribe', { threadId }, INTERRUPT_TIMEOUT_MS).catch(() => undefined);
    }
  }

  private async waitForTurn(active: ActiveTurn, timeoutMs: number, signal?: AbortSignal): Promise<void> {
    let timer: ReturnType<typeof setTimeout> | undefined;
    let removeAbort: (() => void) | undefined;
    let stoppedError: Error | undefined;
    let interrupt: Promise<void> | undefined;
    const stop = (error: Error, reject: (error: Error) => void) => {
      if (stoppedError) return;
      stoppedError = error;
      interrupt = this.interruptOrInvalidate(active);
      void interrupt.then(() => reject(error), () => reject(error));
    };
    const timeout = new Promise<never>((_, reject) => {
      timer = setTimeout(() => {
        stop(new Error(`Codex app-server turn timed out after ${timeoutMs}ms`), reject);
      }, timeoutMs);
    });
    const aborted = new Promise<never>((_, reject) => {
      if (!signal) return;
      const onAbort = () => {
        stop(new Error('Codex app-server turn aborted'), reject);
      };
      if (signal.aborted) onAbort();
      else {
        signal.addEventListener('abort', onAbort, { once: true });
        removeAbort = () => signal.removeEventListener('abort', onAbort);
      }
    });

    try {
      await Promise.race([active.completion, timeout, aborted]);
      // A completion notification may arrive while turn/interrupt is still
      // awaiting acknowledgement. Once stopped, that answer cannot turn the
      // cancelled request back into a successful observation.
      if (stoppedError) {
        await interrupt;
        throw stoppedError;
      }
    } finally {
      if (timer) clearTimeout(timer);
      removeAbort?.();
    }
  }

  private async interruptOrInvalidate(active: ActiveTurn): Promise<void> {
    if (!active.turnId) {
      this.invalidate(new Error('Codex app-server turn aborted before turn id was available'));
      return;
    }
    try {
      await this.request('turn/interrupt', {
        threadId: active.threadId,
        turnId: active.turnId,
      }, INTERRUPT_TIMEOUT_MS);
    } catch (error) {
      this.invalidate(error instanceof Error ? error : new Error(String(error)));
    }
  }

  private async readInheritedMcpServerNames(cwd: string, timeoutMs: number, signal?: AbortSignal): Promise<string[]> {
    const response = await this.request('config/read', { cwd, includeLayers: true }, timeoutMs, signal);
    if (!isObject(response) || !isObject(response.config)) {
      throw codexIsolationError('Codex app-server config/read returned invalid effective config');
    }
    const servers = response.config.mcp_servers;
    if (servers === undefined) return [];
    if (!isObject(servers)) throw codexIsolationError('Codex app-server config/read returned invalid mcp_servers');
    return Object.keys(servers).sort();
  }

  private async attestMcpServersDisabled(
    threadId: string,
    expectedNames: readonly string[],
    timeoutMs: number,
    signal?: AbortSignal,
  ): Promise<void> {
    const response = await this.request(
      'mcpServerStatus/list',
      { threadId, detail: 'toolsAndAuthOnly' },
      timeoutMs,
      signal,
    );
    if (!isObject(response) || !Array.isArray(response.data)) {
      throw codexIsolationError('Codex app-server returned invalid MCP isolation attestation');
    }

    const expected = new Set(expectedNames);
    const observed = new Set<string>();
    for (const raw of response.data) {
      if (!isObject(raw) || typeof raw.name !== 'string' || !isObject(raw.tools)) {
        throw codexIsolationError('Codex app-server returned malformed MCP status');
      }
      if (!expected.has(raw.name) || raw.serverInfo !== null || Object.keys(raw.tools).length > 0) {
        throw codexIsolationError(`Codex app-server MCP server ${raw.name} is not fully disabled`);
      }
      observed.add(raw.name);
    }
    if (observed.size !== expected.size || [...expected].some(name => !observed.has(name))) {
      throw codexIsolationError('Codex app-server MCP isolation attestation is incomplete');
    }
  }

  private async ensureStarted(codexPath: string, timeoutMs: number, signal?: AbortSignal): Promise<void> {
    if (this.closed) throw new Error('Codex app-server client closed');

    const fingerprint = executableFingerprint(codexPath);
    if (this.child && (this.codexPath !== codexPath || this.binaryFingerprint !== fingerprint)) {
      this.invalidate(new Error('Codex executable changed; restarting app-server'));
    }
    if (this.child) return;
    if (this.startPromise) return this.startPromise;

    this.startPromise = this.start(codexPath, fingerprint, timeoutMs, signal)
      .finally(() => { this.startPromise = null; });
    return this.startPromise;
  }

  private async start(codexPath: string, fingerprint: string, timeoutMs: number, signal?: AbortSignal): Promise<void> {
    const supervisor = getSupervisor();
    supervisor.assertCanSpawn('codex');
    const runtime = createPrivateRuntime(this.nativeCodexHome);
    this.privateRoot = runtime.root;
    this.workspace = runtime.workspace;
    this.codexPath = codexPath;
    this.binaryFingerprint = fingerprint;
    this.protocolFragments = [];
    this.protocolLineBytes = 0;
    this.stderrTail = '';

    let expectedChild: ChildProcessWithoutNullStreams | undefined;
    try {
      const launch = buildCodexAppServerLaunch(codexPath);
      const child = spawnHidden(launch.command, launch.args, {
        cwd: this.workspace,
        env: sanitizeEnv(buildCodexAppServerEnv(process.env, runtime.codexHome)),
        stdio: ['pipe', 'pipe', 'pipe'],
        shell: false,
        windowsVerbatimArguments: launch.windowsVerbatimArguments,
      }) as ChildProcessWithoutNullStreams;
      expectedChild = child;
      this.child = child;

      // Pipe writes can fail asynchronously after writeMessage returns. The
      // ChildProcess 'error' event does not handle its stdin stream's EPIPE.
      child.stdin.on('error', error => this.onChildExit(child, error));
      child.stdout.setEncoding('utf8');
      child.stderr.setEncoding('utf8');
      child.stdout.on('data', chunk => this.onStdout(child, String(chunk)));
      child.stderr.on('data', chunk => {
        if (this.child !== child) return;
        this.stderrTail = `${this.stderrTail}${String(chunk)}`.slice(-MAX_STDERR_TAIL_BYTES);
      });
      child.on('error', error => this.onChildExit(child, error));
      child.on('close', (code, childSignal) => {
        const error = new Error(`Codex app-server exited with code ${String(code)} signal ${String(childSignal)}: ${this.stderrTail.trim()}`);
        Object.assign(error, { exitCode: code, exitSignal: childSignal });
        this.onChildExit(child, error);
      });

      if (child.pid) {
        const id = `codex-app-server:${child.pid}`;
        const unregister = () => supervisor.unregisterProcess(id);
        child.once('exit', unregister);
        child.once('close', unregister);
        supervisor.registerProcess(id, {
          pid: child.pid, type: 'codex', startedAt: new Date().toISOString(),
        }, child);
      }

      await this.request('initialize', {
        clientInfo: { name: 'claude_mem', title: 'claude-mem', version: '1' },
        capabilities: {
          experimentalApi: true,
          requestAttestation: false,
          optOutNotificationMethods: ['item/agentMessage/delta'],
        },
      }, timeoutMs, signal);
      this.writeMessage({ method: 'initialized', params: {} });
      logger.debug('SDK', 'Started persistent Codex app-server', { pid: child.pid });
    } catch (error) {
      // A rejected initialize RPC leaves a live but unusable child. Never cache it.
      await this.invalidate(error instanceof Error ? error : new Error(String(error)), expectedChild);
      throw error;
    }
  }

  private request(method: string, params: unknown, timeoutMs: number, signal?: AbortSignal): Promise<unknown> {
    if (signal?.aborted) {
      return Promise.reject(new Error(`Codex app-server ${method} aborted`));
    }
    const child = this.child;
    if (!child || child.killed || !child.stdin.writable) {
      return Promise.reject(new Error('Codex app-server is not running'));
    }

    const id = this.nextRequestId++;
    return new Promise((resolve, reject) => {
      const timer = setTimeout(() => {
        pending.removeAbort?.();
        this.pending.delete(id);
        const error = new Error(`Codex app-server ${method} timed out after ${timeoutMs}ms`);
        reject(error);
        this.invalidate(error, child);
      }, timeoutMs);
      const pending: PendingRequest = { resolve, reject, timer };
      if (signal) {
        const onAbort = () => {
          this.pending.delete(id);
          clearTimeout(timer);
          const error = new Error(`Codex app-server ${method} aborted`);
          reject(error);
          this.invalidate(error, child);
        };
        if (signal.aborted) {
          onAbort();
          return;
        }
        signal.addEventListener('abort', onAbort, { once: true });
        pending.removeAbort = () => signal.removeEventListener('abort', onAbort);
      }
      this.pending.set(id, pending);
      try {
        this.writeMessage({ id, method, params });
      } catch (error) {
        this.pending.delete(id);
        clearTimeout(timer);
        pending.removeAbort?.();
        reject(error);
      }
    });
  }

  private writeMessage(message: JsonObject): void {
    const child = this.child;
    if (!child || !child.stdin.writable) throw new Error('Codex app-server stdin is unavailable');
    child.stdin.write(`${JSON.stringify(message)}\n`);
  }

  private onStdout(child: ChildProcessWithoutNullStreams, chunk: string): void {
    if (this.child !== child) return;
    let offset = 0;
    while (offset < chunk.length) {
      const newline = chunk.indexOf('\n', offset);
      const fragment = chunk.slice(offset, newline === -1 ? chunk.length : newline);
      this.protocolLineBytes += Buffer.byteLength(fragment);
      if (this.protocolLineBytes > MAX_PROTOCOL_LINE_BYTES) {
        this.invalidate(new Error('Codex app-server protocol line exceeded safety limit'));
        return;
      }
      if (fragment) this.protocolFragments.push(fragment);
      if (newline === -1) return;

      // The cap belongs to one protocol line, not a stdout chunk containing
      // several lines. Assemble each line once instead of rescanning its
      // growing prefix for every bounded pipe read.
      const line = this.protocolFragments.join('').trim();
      this.protocolFragments = [];
      this.protocolLineBytes = 0;
      offset = newline + 1;
      if (!line) continue;
      let message: unknown;
      try {
        message = JSON.parse(line);
      } catch (error) {
        this.invalidate(new Error(`Codex app-server emitted malformed JSON: ${error instanceof Error ? error.message : String(error)}`));
        return;
      }
      this.handleMessage(message);
      if (this.child !== child) return;
    }
  }

  private handleMessage(message: unknown): void {
    if (!isObject(message)) return;
    if (typeof message.id === 'number' && !message.method) {
      const pending = this.pending.get(message.id);
      if (!pending) return;
      this.pending.delete(message.id);
      clearTimeout(pending.timer);
      pending.removeAbort?.();
      if (isObject(message.error)) {
        pending.reject(new Error(`Codex app-server RPC error ${String(message.error.code)}: ${String(message.error.message)}`));
      } else {
        pending.resolve(message.result);
      }
      return;
    }

    if ((typeof message.id === 'number' || typeof message.id === 'string') && typeof message.method === 'string') {
      this.handleServerRequest(message.id, message.method);
      return;
    }
    if (typeof message.method === 'string') this.handleNotification(message.method, message.params);
  }

  private handleServerRequest(id: number | string, method: string): void {
    if (method === 'item/permissions/requestApproval') {
      this.writeMessage({ id, result: { permissions: {}, scope: 'turn' } });
      return;
    }
    if (method.includes('requestApproval')) {
      this.writeMessage({ id, result: { decision: 'decline', reason: 'claude-mem does not permit tools' } });
      return;
    }
    if (method === 'mcpServer/elicitation/request') {
      this.writeMessage({ id, result: { action: 'decline', content: null } });
      return;
    }
    this.writeMessage({ id, error: { code: -32601, message: `Unsupported server request: ${method}` } });
  }

  private handleNotification(method: string, params: unknown): void {
    const active = this.activeTurn;
    if (!active || !isObject(params)) return;
    if (typeof params.threadId === 'string' && params.threadId !== active.threadId) return;

    if (method === 'item/completed' && isObject(params.item)) {
      const item = params.item;
      active.completedItems += 1;
      if (typeof item.type === 'string' && FORBIDDEN_ITEM_TYPES.has(item.type)) {
        active.protocolError = new Error(`Codex app-server attempted forbidden ${item.type} capability`);
        void this.interruptOrInvalidate(active).finally(() => active.complete());
      }
      if (item.type === 'agentMessage' && typeof item.text === 'string') {
        active.agentMessages += 1;
        if (item.phase === 'final_answer' || active.finalText === null) active.finalText = item.text;
      }
      return;
    }

    if (method === 'thread/tokenUsage/updated' && isObject(params.tokenUsage)) {
      active.tokenUsage = params.tokenUsage;
      return;
    }

    if (method === 'turn/completed' && isObject(params.turn)) {
      this.acceptTerminalTurn(active, params.turn);
      return;
    }

    if (method === 'error') {
      // Codex retries these itself; the turn's final notification decides the outcome.
      if (params.willRetry === true) return;
      active.protocolError = codexTurnError('Codex app-server reported an error', params.error);
      active.complete();
    }
  }

  private acceptTerminalTurn(active: ActiveTurn, turn: JsonObject): void {
    if (typeof turn.status !== 'string' || !TERMINAL_TURN_STATUSES.has(turn.status)) return;
    active.terminalTurn = turn;
    if (Array.isArray(turn.items)) {
      active.terminalItems += turn.items.length;
      for (const raw of turn.items) {
        if (isObject(raw) && typeof raw.type === 'string' && FORBIDDEN_ITEM_TYPES.has(raw.type)) {
          active.protocolError = new Error(`Codex app-server attempted forbidden ${raw.type} capability`);
        }
        if (isObject(raw) && raw.type === 'agentMessage' && typeof raw.text === 'string') {
          active.agentMessages += 1;
          if (raw.phase === 'final_answer' || active.finalText === null) active.finalText = raw.text;
        }
      }
    }
    active.complete();
  }

  private describeEmptyTurn(active: ActiveTurn): string {
    return `completedItems=${active.completedItems}, terminalItems=${active.terminalItems}, `
      + `agentMessages=${active.agentMessages}, finalTextBytes=${Buffer.byteLength(active.finalText ?? '', 'utf8')}`;
  }

  private onChildExit(child: ChildProcessWithoutNullStreams, error: Error): void {
    if (this.child !== child) return;
    void this.invalidate(error, child);
  }

  private invalidate(error: Error, expectedChild?: ChildProcessWithoutNullStreams): Promise<void> {
    if (expectedChild && this.child !== expectedChild) return this.cleanupPromise;
    const child = this.child;
    if (child) logger.debug('SDK', 'Stopping persistent Codex app-server', { pid: child.pid }, error);
    this.child = null;
    this.startPromise = null;
    this.protocolFragments = [];
    this.protocolLineBytes = 0;
    let termination = Promise.resolve();
    if (child) {
      if (child.pid) {
        termination = killProcessTree(child.pid).catch(() => {
          try { child.kill('SIGKILL'); } catch { /* already closed */ }
        });
      } else {
        try { child.kill('SIGKILL'); } catch { /* already closed */ }
      }
    }

    for (const pending of this.pending.values()) {
      clearTimeout(pending.timer);
      pending.removeAbort?.();
      pending.reject(error);
    }
    this.pending.clear();
    if (this.activeTurn) {
      this.activeTurn.protocolError = error;
      this.activeTurn.complete();
    }
    const privateRoot = this.privateRoot;
    this.privateRoot = null;
    this.workspace = null;
    // Codex can still write state, or hold files open on Windows, until its
    // process tree exits. Capture this generation's root before a new start.
    const cleanup = termination.then(() => {
      if (privateRoot) {
        try { rmSync(privateRoot, { recursive: true, force: true }); } catch { /* best effort */ }
      }
    });
    // A timeout or protocol error may have already started teardown before close.
    this.cleanupPromise = Promise.all([this.cleanupPromise, cleanup]).then(() => {});
    return this.cleanupPromise;
  }
}

const APP_SERVER_ENV_ALLOWLIST = new Set([
  ...ENV_PROXY_VARS,
  'APPDATA',
  'CODEX_HOME',
  'HOME',
  'HOMEDRIVE',
  'HOMEPATH',
  'LANG',
  'LOCALAPPDATA',
  'NODE_EXTRA_CA_CERTS',
  'PATH',
  'PATHEXT',
  'SHELL',
  'SSL_CERT_DIR',
  'SSL_CERT_FILE',
  'SystemRoot',
  'TEMP',
  'TMP',
  'TMPDIR',
  'USER',
  'USERPROFILE',
  'USERNAME',
  'WINDIR',
  'XDG_CACHE_HOME',
  'XDG_CONFIG_HOME',
  'XDG_DATA_HOME',
]);

export function buildCodexAppServerEnv(
  env: NodeJS.ProcessEnv = process.env,
  scopedCodexHome?: string,
): NodeJS.ProcessEnv {
  const result: NodeJS.ProcessEnv = {};
  for (const [key, value] of Object.entries(env)) {
    if (value !== undefined && (APP_SERVER_ENV_ALLOWLIST.has(key) || key.startsWith('LC_'))) {
      result[key] = value;
    }
  }
  if (scopedCodexHome) result.CODEX_HOME = scopedCodexHome;
  return result;
}