Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

92.6 KB
Raw Blame
import { decodeRoutedCodexConfig, managedCodexArgs, endpointCodexArgs, type CodexEndpointConfig } from "./codex-endpoint-config.ts";
export { managedCodexArgs, endpointCodexArgs } from "./codex-endpoint-config.ts";
import { codexActionFailure } from "./codex-action-notice.ts";
import { codexToolSurfaceArgs } from "./codex-tool-surface.ts";
import { codexShellDisabled, codexTurnConfigArgs } from "./codex-guest.ts"; import { shellOff } from "./shell-off.ts"; import { withTrailingTurnClock } from "../turn-clock.ts";
import { TEAM_TOOLS_FAILED, teamToolsFailed } from "./team-tools.ts";
import { enabledMcpMounts, mcpStartupTracker, supportsMcpStartup } from "./codex-mcp-startup.ts";
import { boxAdmittedEnv, boxProxyEnvNames, codexInSeccompBox, customServerEnvBox, type McpApprovalMode, mountMcpServer } from "./codex-mcp-mount.ts";
import { reportUnsupportedCalls, rolloutMark, type RolloutMark } from "./codex-unsupported-calls.ts";
// The `codex` CLI headless over its app-server JSON-RPC (NDJSON on stdio): completion is
// `turn/completed`, approvals arrive as server→client requests, resumeCursor is the codex thread id.
import { createHash } from "node:crypto";
import { mkdirSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
import { codexConfigMcp, codexConfigRunsServer, codexMcpDisableArgs, mountedMcpServerName } from "./codex-mcp-names.ts";

import { stripWorkspaceCredentialEnv } from "../config.ts";
import { laterStartup, openStartupModelCatalog, unconfirmedModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";
import { chatgptAccountDirectory, chatgptAccountHome, chatgptAccountSignsInByDevice } from "./codex-account-home.ts";
import { serverVersion } from "../environment.ts";
import { ChatGptPlanAuthController } from "./chatgpt-plan-auth.ts";
import { chatgptPlanCodexArgs, PLAN_TOKEN_BRIDGE_ENV, planTokenRenewal, startPlanTokenBridge, type PlanTokenBridge } from "./codex-plan-token.ts";
export { chatgptPlanCodexArgs } from "./codex-plan-token.ts";
import { captureCliTree, describeSpawnFailure, killCliTree, spawnCli, waitForExit } from "../procs.ts";
import { cliVersionProbe } from "../cli-version-probe.ts";
import { codexLaunch, codexLaunchesStarting, codexLaunchSlot, codexRpcTimeoutMs, keepStopping, RELAUNCH_EXIT_WAIT_MS, spawnHoldingSlot, tryCodexLaunchSlot } from "./codex-process.ts";
import { perTurnCustomMcp } from "../mcp-registry.ts";

import type {
  DriverCreateInput,
  McpServerSpec,
  ProviderDriver,
  ProviderInstance,
  ProviderSnapshot,
  RuntimeEvent,
  RuntimeEventListener,
  SendTurnInput,
  StdioMcpSpec,
  SteerOutcome,
  TextGenerationOptions,
} from "../contracts.ts";
import { newEventId, newId } from "../contracts.ts";
import { codexSelectedProviderArgs, codexThreadSelection, decodeCodexSelection, OFFICIAL_CODEX_PROVIDER, readCodexModelCatalog, STATIC_CODEX_MODELS } from "./codex-catalog.ts";
import { codexBackgroundProviderArgs, codexBackgroundRoute, runCodexBackgroundRoute, runCodexOneShot } from "./codex-background-text.ts";
import { augmentedPath } from "../env-path.ts";
import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.ts";
import { appendNative } from "./native.ts";
import { answersAlone, permissionLaunchCwd, shellRequest } from "./permission-command.ts";
import { commandSummary, toolDetailPreview } from "../tool-summary.ts";
import { codexDeveloperInstructions, codexSandboxNote, syncCodexInstructions } from "./codex-instructions.ts";
import { volatileContextNote, withContextNote } from "./prompt-split.ts";
import type { ApprovalMode } from "../../shared/approval-mode.ts";
import { CodexDeviceAuthController } from "./codex-device-auth.ts"; import { messageItem } from "../harness/text-items.ts";
import { codexAccountEmail, codexHome } from "./codex-identity.ts";
import { keepChatsOutOfCodexHistory, linkSharedCodexHome } from "./codex-shared-home.ts";
import { mcpAppApprovalForm, mcpAppApprovalText, mcpElicitationDeclined, plainRecord } from "./codex-app-approval.ts";
import { archivedNativeCodexThread, CODEX_MISSING_CREDENTIALS, CODEX_SIGN_IN_EXPIRED, CodexRpcError, codexLimitFacts, codexNotSignedIn, codexPlanModelRefused, codexPlanUnsupportedInput, codexResumeRebuild, codexSignInExpired, codexSignInRefused, codexUserError, codexUserFailure, type CodexRoute } from "./codex-errors.ts";
import { codexTierOf } from "./codex-tier.ts"; import { codexLoginCheck, keptCodexLogin, readCodexLogin, storedCodexLogin } from "./codex-login.ts";
import { keyRejected, noteKeyAccepted, noteKeyRejected } from "../key-rejections.ts";
import { classifyResumeFailure, mayReplay, recoveryPromptFor, sessionRebuildNotice } from "../resume-recovery.ts";
import { extractMcpImages, isOwnScreenTool, ownScreenMounts } from "../mcp-tool-images.ts"; import { codexImageInputs, withoutInlineImages } from "./codex-images.ts";
import { parseProtocolAskQuestions, questionChoices } from "../../shared/ask-question.ts";
import { codexQuestionReply, openAsyncQuestion, type CodexAsk } from "./codex-questions.ts";
import { codexReleaseUpdate, codexUpdateCommand } from "./codex-update.ts";
export { codexUpdateCommand };
import { customApprovalParams, namedApprovalParams, permissionProfileUnsupported, withResolvedSandbox, type CodexApprovalParams } from "./codex-approval-config.ts"; import { CodexConnection, codexConfigDigest, codexContractDiff, codexIdentityInputs, codexOwnLogin, codexSpawnContract, codexWarmSessions, type CodexIdentityInputs } from "./codex-warm.ts"; import { codexCompactSession } from "./codex-compact.ts"; import { AGENTS_TOOL_TIMEOUT_SECONDS } from "./agents-tool-limit.ts"; import { COMPUTER_PROXY_TIMEOUT_MS } from "../harness-budget.ts";
import { canUseMcpServer } from "../../shared/tool-scope.ts";
import { assertToolScopeSupported } from "../../shared/tool-scope-support.ts";
import { appMountFor, gateServer, mcpStdioServer } from "../mcp-gate-config.ts"; import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";
import { CALL_TOOL, DESCRIBE_TOOL, SEARCH_TOOL, directoryCallTarget } from "../mcp-directory.ts"; import { codexCommandOutput, codexPatchProgress } from "./tool-progress.ts";

export { decodeCodexSelection, readCodexModelCatalog, STATIC_CODEX_MODELS } from "./codex-catalog.ts";

const DRIVER_KIND = "codex";

export interface CodexConfig {
  cli: string;
  fullAuto: boolean;
  authMode?: "chatgpt-plan";
  managed?: CodexEndpointConfig;
  endpoint?: CodexEndpointConfig;
}

function decodeConfig(raw: unknown): CodexConfig {
  const o = (raw ?? {}) as Record<string, unknown>;
  if (o.authMode !== undefined && o.authMode !== "chatgpt-plan") throw new Error("Unknown Codex sign-in mode.");
  if (o.authMode && o.managed) throw new Error("ChatGPT plan and Company billing cannot be combined.");
  if (o.endpoint && (o.authMode || o.managed)) throw new Error("Direct API, ChatGPT plan and Company billing cannot be combined.");
  return {
    cli: typeof o.cli === "string" ? o.cli : "codex",
    fullAuto: o.fullAuto === true,
    ...(o.authMode === "chatgpt-plan" ? { authMode: "chatgpt-plan" as const } : {}),
    ...(o.endpoint ? { endpoint: decodeRoutedCodexConfig(o.endpoint as object, "Direct API") } : {}),
    ...(o.managed && typeof o.managed === "object" ? { managed: decodeRoutedCodexConfig(o.managed) } : {}),
  };
}

const PRIVATE_ENV_FAMILIES = ["OMB_GATE_CONFIG_", "OMB_REMOTE_MCP_CONFIG_"];
const PROXY_LITERAL_ENV = ["NODE_USE_ENV_PROXY", "NO_PROXY", "no_proxy"];
const SHELL_ESSENTIALS = new Set(["PATH", "HOME", "USER", "LOGNAME", "SHELL", "TMPDIR", "TERM", "LANG", "TZ"]);

const DENY_TIMEOUT_NOTE =
  "OpenMausBot: nobody answered this permission request in time. Skip this action and finish what you can without it.";

const renamedMcpServers = new Set<string>();
function noteRenamedMcpServer(name: string, mountName: string): void {
  if (renamedMcpServers.has(name)) return;
  renamedMcpServers.add(name);
  console.error(`codex: MCP server ${JSON.stringify(name)} is mounted as ${JSON.stringify(mountName)} for this bot to keep its CLI configuration distinct`);
}

/** RequestPermissionProfile uses null for permission families that were not
 * requested; GrantedPermissionProfile requires those keys to be absent. */
function grantedPermissions(raw: unknown): Record<string, unknown> {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
  return Object.fromEntries(
    Object.entries(raw as Record<string, unknown>).filter(([, value]) => value !== null && value !== undefined),
  );
}

function additionalPermissionSummary(permissions: unknown, reason: unknown): string {
  const requested = grantedPermissions(permissions);
  const exact = JSON.stringify(requested);
  const prefix = typeof reason === "string" && reason.trim() ? `${reason.trim()} — ` : "";
  return `${prefix}Requested permissions: ${exact}`;
}

/** Thread-config overrides adding `patterns` to the person's shell exclusions. Codex keeps two
 * representations, the `exclude`/`include_only` lists and the `filters` table, and a higher layer
 * that writes one drops the other below it (codex-cli 0.160, which reports unset fields as null). */
function extendShellExclusions(policy: Record<string, unknown>, patterns: readonly string[]): Record<string, unknown> {
  const unconfirmed = () => new Error("Codex could not confirm its shell environment exclusions. No prompt was sent.");
  const exclude = policy.exclude ?? undefined;
  const filters = policy.filters ?? undefined;
  if (exclude !== undefined && (!Array.isArray(exclude) || exclude.some(name => typeof name !== "string"))) throw unconfirmed();
  if (filters === undefined) {
    return { "shell_environment_policy.exclude": [...new Set([...(exclude ?? []) as string[], ...patterns])] };
  }
  const table = plainRecord(filters);
  if (!table || Object.values(table).some(action => action !== "exclude" && action !== "include")) throw unconfirmed();
  // One Codex layer cannot mix the two; writing filters would drop the lists.
  if (exclude !== undefined || (policy.include_only ?? undefined) !== undefined) throw unconfirmed();
  // Patterns match, merge across layers, and must be unique ignoring case.
  const ours = new Set(patterns.map(pattern => pattern.toLowerCase()));
  return { "shell_environment_policy.filters": Object.fromEntries([
    ...Object.entries(table).filter(([pattern]) => !ours.has(pattern.toLowerCase())),
    ...patterns.map(pattern => [pattern, "exclude"]),
  ]) };
}

/** Native instructions and image bytes stay out of diagnostics; the provider still gets the unmodified request. */
function codexNativeLogMessage(message: unknown): unknown {
  if (!message || typeof message !== "object" || Array.isArray(message)) return message;
  const record = message as Record<string, unknown>;
  const params = record.params;
  if (!params || typeof params !== "object" || Array.isArray(params)) return message;
  if (record.method === "thread/start" || record.method === "thread/resume") {
    return { ...record, params: { ...params, developerInstructions: "[developer instructions omitted]" } };
  }
  if (record.method === "thread/inject_items") {
    return { ...record, params: { ...params, items: "[developer instruction update omitted]" } };
  }
  return record.method === "turn/start" ? withoutInlineImages(message) : message;
}

/** A response arriving after its request timed out is still sanitized, never a secret-bearing orphan. */
export function codexNativeIncomingLogMessage(
  message: any,
  sensitiveResponseIds: ReadonlySet<number>,
): unknown {
  if (message?.id !== undefined && sensitiveResponseIds.has(message.id)) {
    return {
      jsonrpc: message.jsonrpc,
      id: message.id,
      ...(message.error !== undefined
        ? { error: "[config/read error omitted]" }
        : { result: "[effective config omitted]" }),
    };
  }
  if (message?.method === "item/completed" && message.params?.item?.type === "imageGeneration") {
    return {
      ...message,
      params: {
        ...message.params,
        item: {
          ...message.params.item,
          result: `[generated image omitted · ${String(message.params.item.result ?? "").length} base64 chars]`,
          savedPath: undefined,
        },
      },
    };
  }
  return withoutInlineImages(message);
}

export const CodexDriver: ProviderDriver<CodexConfig> = {
  driverKind: DRIVER_KIND,
  metadata: { displayName: "Codex", supportsMultipleInstances: true, signInAccount: "ChatGPT" },
  install: {
    command: {
      darwin: "npm install -g @openai/codex",
      linux: "npm install -g @openai/codex",
      win32: "npm install -g @openai/codex",
    },
    needsNode: true,
    docsUrl: "https://github.com/openai/codex",
    signInCommand: "codex login",
  },
  models: STATIC_CODEX_MODELS,
  decodeConfig,
  defaultConfig: () => decodeConfig({}),

  async create(input: DriverCreateInput<CodexConfig>): Promise<ProviderInstance> {
    const { instanceId, config } = input;
    const routed = config.endpoint ?? config.managed;
    const routedProvider = config.endpoint ? "openmaus_endpoint" : "openmaus_company";
    // Where the browser sign-in cannot call back, an added ChatGPT account is Codex's own login in a Codex home of its own.
    const deviceHome = chatgptAccountSignsInByDevice(config) ? chatgptAccountHome(instanceId) : null;
    const plan = config.authMode === "chatgpt-plan" && !deviceHome, planDirectory = chatgptAccountDirectory(instanceId);
    const childEnv = (): Record<string, string | undefined> => {
      const env: Record<string, string | undefined> = {
        ...process.env,
        ...input.environment,
        PATH: augmentedPath(),
        NPM_CONFIG_LOGLEVEL: "error",
      };
      // A leaked API key silently flips Codex's own ChatGPT login to pay-as-you-go.
      delete env.OPENAI_API_KEY;
      stripWorkspaceCredentialEnv(env);
      delete env.OPENMAUSBOT_CHATGPT_TOKEN;
      delete env.OPENMAUSBOT_CODEX_API_KEY;
      for (const name of PLAN_TOKEN_BRIDGE_ENV) delete env[name];
      if (config.endpoint) {
        env.OPENMAUSBOT_CODEX_API_KEY = input.environment.OPENMAUSBOT_CODEX_API_KEY;
        env.CODEX_HOME = input.environment.CODEX_HOME;
      }
      if (plan || deviceHome) { env.CODEX_HOME = join(planDirectory, "codex"); delete env.CODEX_SQLITE_HOME; }
      return env;
    };
    // The person's Codex setup is linked in, its login stays its own; Codex refuses a CODEX_HOME that does not exist.
    const prepareDeviceHome = () => { if (deviceHome) linkSharedCodexHome(codexHome({ ...process.env, ...input.environment }), deviceHome); };
    try { prepareDeviceHome(); } catch {}
    const catalogEnv = childEnv();
    const planAuth = plan ? new ChatGptPlanAuthController({ directory: planDirectory }) : null;
    const planRenewal = planTokenRenewal(() => readCliVersion(catalogEnv));
    let planGeneration = 0;
    let planSigningOut = false;
    let disposed = false;
    let planWarning: string | undefined;
    let models = plan ? { default: "", options: [] } : routed ? { default: routed.models[0], options: routed.models.map(id => ({ id, label: id, ...(config.endpoint ? { custom: true } : {}) })) } : STATIC_CODEX_MODELS;
    const refreshModels = async (preserveExisting = false) => {
      if (routed) return;
      if (planAuth) {
        const generation = planGeneration;
        const kept = preserveExisting && models.options.length > 0 ? models : null;
        if (!kept) models = { default: "", options: [] };
        try {
          if (!planSigningOut && !disposed) {
            const catalog = await planAuth.models();
            if (generation === planGeneration && !planSigningOut && !disposed && (!kept || catalog.options.length)) models = catalog;
          }
        } catch (error) {
          if (!kept) throw error; unconfirmedModelCatalog(kept);
        }
      } else {
        try {
          const resolved = await readCodexModelCatalog(catalogEnv, fetch, config.cli);
          if (resolved.options.length) models = resolved; else unconfirmedModelCatalog(models);
        } catch { unconfirmedModelCatalog(models); }
      }
      try { writeStartupModelCache(instanceId, models); } catch {}
    };
    // Only ChatGPT's refusal of a model for this account hides it from the account's list; other errors never do.
    const hidePlanRefusedModel = (model: string | undefined, raw: string, route: CodexRoute) => {
      if (!planAuth || !model || !codexPlanModelRefused(raw, route)) return;
      const options = models.options.filter(option => option.id !== model);
      models = { default: models.default === model ? options[0]?.id ?? "" : models.default, options };
      void planAuth.refuseModel(model).then(() => refreshModels(true)).catch(() => {});
    };
    // Codex's model list ships with the CLI: updating 0.155.1 to 0.162.1 in place adds gpt-6.1-sol.
    let modelsCliVersion: string | null = null;
    let startupModelRefresh: Promise<void> | null = null;
    if (routed) {
      await refreshModels();
    } else {
      startupModelRefresh = (await openStartupModelCatalog({
        instanceId,
        use: (catalog) => { models = catalog; },
        current: () => models,
        refresh: async () => {
          if (planAuth) {
            try { await refreshModels(laterStartup()); } catch {}
          } else await refreshModels();
        },
      }))?.pending ?? null;
    }
    // OpenAI can refuse Codex's own ChatGPT login while `codex login status` still reports it. Only a
    // stored ChatGPT login is marked: an API-key login cannot be fixed by a ChatGPT sign-in.
    const ownLogin = !plan && !routed;
    const loginCheck = codexLoginCheck(config.cli);
    const loginMark = (): [string, string] | null => {
      const env = childEnv();
      const home = ownLogin ? codexHome(env) : null;
      const stored = home ? storedCodexLogin(env) : null;
      if (!home || stored === null) return null;
      try {
        const auth = JSON.parse(stored) as { auth_mode?: unknown; tokens?: unknown };
        const chatgpt = typeof auth.auth_mode === "string" ? /chatgpt/i.test(auth.auth_mode) : Boolean(auth.tokens);
        if (!chatgpt) return null;
      } catch { return null; }
      return [`codex-login:${home}`, stored];
    };
    const smallModelsUsable = () => !plan && loginMark() === null;
    const loginRefused = () => { const mark = loginMark(); if (mark) noteKeyRejected(...mark); };
    const loginAccepted = (mark = loginMark()) => { if (mark) noteKeyAccepted(...mark); };
    const loginRejected = () => { const mark = loginMark(); return mark !== null && keyRejected(...mark); };
    const authentication = new CodexDeviceAuthController({
      cli: config.cli,
      environment: () => { prepareDeviceHome(); return childEnv(); },
      signInRejected: loginRejected,
      onAuthenticated: async () => { loginAccepted(); await refreshModels(); },
    });
    const listeners = new Set<RuntimeEventListener>();
    interface Turn {
      stop: () => Promise<boolean>;
      steer?: (text: string) => Promise<SteerOutcome>;
      turnId: string;
      asks: Map<string, CodexAsk>;
      pid?: number;
    }
    const active = new Map<string, Turn>();
    const warm = codexWarmSessions<{ initialized: any; approvalParams: CodexApprovalParams; rolloutPath: unknown }>(instanceId);

    const emit = (event: RuntimeEvent) => {
      for (const l of Array.from(listeners)) l(event);
    };
    const base = (threadId: string, turnId: string) => ({
      eventId: newEventId(),
      provider: DRIVER_KIND,
      threadId,
      turnId,
      createdAt: new Date().toISOString(),
    });

    const sendTurn = async (turn: SendTurnInput) => {
      if (startupModelRefresh) await startupModelRefresh;
      turn = { ...turn, toolScope: assertToolScopeSupported(DRIVER_KIND, turn.toolScope) };
      const generation = planGeneration;
      const assertPlanCurrent = () => {
        if (disposed) throw new Error("This provider was removed. Select a connected account and send again.");
        if (planAuth && (planSigningOut || generation !== planGeneration)) throw new Error("The ChatGPT account changed while this message was preparing. Select a connected account and send again.");
      };
      assertPlanCurrent();
      const planToken = planAuth ? await planAuth.accessToken() : undefined;
      assertPlanCurrent();
      if (planAuth) {
        // ChatGPT refused this model for this account in an earlier turn: carry on with the account's first usable model.
        const refused = planAuth.refusedModels();
        if (turn.model && refused.includes(turn.model)) {
          if (!models.options.length) { await refreshModels(); assertPlanCurrent(); }
          const usable = models.options.find(option => !refused.includes(option.id));
          if (usable) turn = { ...turn, model: usable.id };
        }
        if (!turn.model || !models.options.some(model => model.id === turn.model)) {
          await refreshModels();
          assertPlanCurrent();
          if (!turn.model || !models.options.some(model => model.id === turn.model)) throw new Error("This model is not available to the selected ChatGPT plan. Refresh models and choose a listed model; API billing will not be used.");
        }
        linkSharedCodexHome(codexHome({ ...process.env, ...input.environment }), join(planDirectory, "codex"));
      }
      prepareDeviceHome();
      if (config.endpoint) {
        if (!turn.model || !config.endpoint.models.includes(turn.model)) throw new Error("Select a model configured for this direct API endpoint.");
        if (!input.environment.OPENMAUSBOT_CODEX_API_KEY || !input.environment.CODEX_HOME) throw new Error("Direct API key or isolated Codex home is missing. Edit the endpoint in Settings.");
        mkdirSync(input.environment.CODEX_HOME, { recursive: true, mode: 0o700 });
      }
      if (config.managed) {
        if (!turn.model) {
          throw new Error("Company model access is unavailable: no model is selected. Reconnect your organization; personal billing will not be used.");
        }
        if (!config.managed.models.includes(turn.model)) {
          throw new Error("Company model access is unavailable: " + turn.model + " is not approved for your organization. Reconnect your organization; personal billing will not be used.");
        }
        if (!input.environment.OPENMAUSBOT_COMPANY_API_KEY) {
          throw new Error("Company model access is unavailable: OPENMAUSBOT_COMPANY_API_KEY is missing. Reconnect your organization; personal billing will not be used.");
        }
        if (!input.environment.CODEX_HOME) {
          throw new Error("Company model access is unavailable: CODEX_HOME is missing. Reconnect your organization; personal billing will not be used.");
        }
      }
      // Interrupt state belongs to this turn so activity on other threads cannot cancel or revive its retry.
      let stopRequested = false;
      let promptSubmitted = false;
      let recoveredSession = false, droppedSession: "unsupported-input" | "instruction-overflow" | null = null;
      let loginRaceRetried = false;
      const stopSignal = new AbortController();
      const { threadId } = turn;
      const approvalMode: ApprovalMode = turn.approvalMode ?? (config.fullAuto ? "full" : "ask");
      turn = perTurnCustomMcp(turn);
      let autoAcceptPermissions = approvalMode === "full";
      const chatgptTurn = ownLogin &&
        decodeCodexSelection(turn.model || models.default).modelProvider === OFFICIAL_CODEX_PROVIDER;
      const route: CodexRoute = plan ? "plan" : chatgptTurn ? "own" : "other";
      const hideRefusedModel = (raw: string) => hidePlanRefusedModel(turn.model, raw, route);
      const signedOut = chatgptTurn && await loginCheck.check(childEnv()) === "missing";
      const authBridge = planAuth && await planRenewal.supported() ? await startPlanTokenBridge(() => planAuth.accessToken(), () => { assertPlanCurrent(); if (stopRequested) throw new Error("This task has ended."); }) : null;
      let turnConfigArgs: string[]; try { assertPlanCurrent(); if (active.has(threadId)) throw new Error("a turn is already running on this thread"); turnConfigArgs = codexTurnConfigArgs(turn, childEnv()); } catch (error) { authBridge?.close(); throw error; }
      const turnId = newId();
      if (signedOut) {
        emit({ ...base(threadId, turnId), type: "turn.started" });
        emit({ ...base(threadId, turnId), type: "runtime.error", message: codexNotSignedIn(), setup: true });
        emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "auth_required", cost: null, unsent: true });
        return { turnId };
      }
      const retryScale = Number(process.env.FAKE_CODEX_RETRY_SCALE ?? "1"), ownScreen = new Set<string>();
      let announced = false;
      const waitForLaunchSlot = async (attempt: number) => {
        const waiting: Turn = { stop: async () => { stopRequested = true; stopSignal.abort(); return true; }, turnId, asks: new Map() };
        active.set(threadId, waiting);
        if (attempt === 0 && !announced) emit({ ...base(threadId, turnId), type: "turn.started" });
        announced = true;
        emit({ ...base(threadId, turnId), type: "runtime.notice", message: `Waiting for a free Codex slot: ${codexLaunchesStarting()} Codex runs are starting on this computer. This one starts on its own.` });
        const slot = await codexLaunchSlot(stopSignal.signal);
        if (slot && !stopRequested) return slot;
        slot?.(); authBridge?.close();
        if (active.get(threadId) === waiting) {
          active.delete(threadId);
          emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "interrupted", cost: null });
        }
        return null;
      };
      const launchAttempt = async (attempt: number): Promise<void> => {
        const env = childEnv();
        const launchedLogin = chatgptTurn ? storedCodexLogin(env) : null; if (ownLogin) keepChatsOutOfCodexHistory(env, instanceId);
        if (authBridge) Object.assign(env, authBridge.env); else if (planToken) env.OPENMAUSBOT_CHATGPT_TOKEN = planToken;
        const appServerArgs = ["app-server", ...(plan ? chatgptPlanCodexArgs(!!authBridge) : config.endpoint ? endpointCodexArgs(config.endpoint) : config.managed ? managedCodexArgs(config.managed) : codexSelectedProviderArgs(env, turn.model)), ...codexToolSurfaceArgs(),
          // Native shell snapshots can restore variables the shell policy removed.
          ...(turn.toolScope === undefined && !authBridge ? [] : ["-c", "features.shell_snapshot=false"]),
          // A guest-driven turn: no shell, no file reads (-c wins over config files).
          ...turnConfigArgs];
        const codexConfig = codexConfigMcp(env), declaredInCodexConfig = codexConfig.names;
        if (turn.toolScope !== undefined) appServerArgs.push(...codexMcpDisableArgs(declaredInCodexConfig));
        const baseEnv = new Map(Object.entries(env).filter(([, value]) => value !== undefined));
        const mountedNames = new Set<string>();
        const selectedMcp = new Map<string, StdioMcpSpec>();
        const selectedApprovals = new Map<string, McpApprovalMode>();
        const directoryMounts = new Set<string>();
        const directMounts: string[] = [];
        const literalEnvs = new Map<string, Record<string, string>>();
        const scopedServer = (name: string, mountName: string, server: McpServerSpec): StdioMcpSpec | null => {
          if (!canUseMcpServer(turn.toolScope, name)) return null;
          // Every URL server goes through OpenMausBot's remote proxy: Codex's own client adds fields
          // strict servers refuse (codex-cli 0.160.1 sends elicitation.form/url; rmcp 3.2 can add
          // schemaValidation), and Codex does not speak SSE. A plan turn has no tool_search, so its URL
          // servers use the proxy's tool directory.
          const directory = plan && "url" in server;
          const apps = appMountFor(name, turn);
          if (turn.toolScope === undefined && !("url" in server) && !apps) return server;
          const hash = createHash("sha256").update(mountName).digest("hex");
          // Codex starts MCP children with only a few env names.
          const proxy = turn.toolScope === undefined && "url" in server
            ? mcpStdioServer(server, { nodeEnv: { ELECTRON_RUN_AS_NODE: "1" }, ...(directory ? { directory: { name } } : {}), configEnvName: `OMB_REMOTE_MCP_CONFIG_${hash}`, sourceEnv: env, apps })
            : gateServer({ name, server, threadId, budget: 0, toolScope: turn.toolScope, nodeEnv: { ELECTRON_RUN_AS_NODE: "1" }, configEnvName: `OMB_GATE_CONFIG_${hash}`, directory, sourceEnv: env, apps });
          if (proxy && directory) directoryMounts.add(mountName);
          if (!proxy) return null;
          const shared = { ...proxy.env };
          if (turn.toolScope === undefined) {
            const literal = Object.fromEntries(Object.entries(shared).filter(([key]) => PROXY_LITERAL_ENV.includes(key)));
            for (const key of PROXY_LITERAL_ENV) delete shared[key];
            if (Object.keys(literal).length) literalEnvs.set(mountName, literal);
          }
          return { command: proxy.command, args: proxy.args ?? [], env: shared };
        };
        const mountSelected = (name: string, mountName: string, server: McpServerSpec, approval: McpApprovalMode = "auto", forward: readonly string[] = []) => {
          const selected = scopedServer(name, mountName, server);
          if (selected) {
            selectedMcp.set(mountName, selected); if (ownScreenMounts([mountName]).size) ownScreen.add(mountName);
            selectedApprovals.set(mountName, approval);
            mountMcpServer(appServerArgs, env, mountName, selected, approval, literalEnvs.get(mountName), mountedNames, forward);
            if (turn.toolScope !== undefined && approval === "prompt") appServerArgs.push("-c", `mcp_servers.${mountName}.default_tools_approval_mode="prompt"`);
          }
        };
        if (turn.integrations?.composio) mountSelected("composio", "openmausbot_connectors", turn.integrations.composio);
        if (turn.integrations?.composioOwn) mountSelected(OWN_APPS_SERVER, `openmausbot_${OWN_APPS_SERVER}`, turn.integrations.composioOwn);
        if (turn.integrations?.agents) {
          // OpenMausBot's own coordination tools never ask: "auto" quiets only read-only tools.
          mountSelected("agents", "agents", turn.integrations.agents, "approve"); if (selectedMcp.has("agents")) appServerArgs.push("-c", `mcp_servers.agents.tool_timeout_sec=${AGENTS_TOOL_TIMEOUT_SECONDS}`);
        }
        if (turn.integrations?.localComputer) {
          mountSelected("computer", "computer", turn.integrations.localComputer); if (selectedMcp.has("computer")) appServerArgs.push("-c", `mcp_servers.computer.tool_timeout_sec=${COMPUTER_PROXY_TIMEOUT_MS / 1_000 + 10}`);
        }
        if (turn.integrations?.browser) {
          mountSelected("browser", "browser", turn.integrations.browser);
        }
        for (const name of ["data", "email", "device"] as const) if (turn.integrations?.[name]) mountSelected(name, name, turn.integrations[name]);
        // A `-c` override merges with a same-named server in config.toml, and stdio over url is
        // "invalid configuration" that kills the turn, so such a server mounts under its own name.
        const takenMcpNames = new Set([...declaredInCodexConfig, ...selectedMcp.keys(), ...(turn.integrations?.phone ? ["openmausbot_phone"] : [])]);
        for (const [name, server] of Object.entries(turn.integrations?.custom ?? {}).filter(([name, server]) => turn.toolScope !== undefined || !codexConfigRunsServer(codexConfig, name, server))) {
          const mountName = mountedMcpServerName(name, takenMcpNames);
          takenMcpNames.add(mountName);
          if (mountName !== name) noteRenamedMcpServer(name, mountName);
          mountSelected(name, mountName, server, "prompt", turn.toolScope === undefined && !("url" in server) ? boxProxyEnvNames() : []);
        }
        if (turn.integrations?.phone) {
          if (turn.toolScope !== undefined) {
            mountSelected("phone", "openmausbot_phone", turn.integrations.phone);
          } else {
          const bridge = turn.integrations.phone;
          Object.assign(env, bridge.env);
          for (const name of Object.keys(bridge.env)) mountedNames.add(name);
          const prefix = "mcp_servers.openmausbot_phone";
          directMounts.push("openmausbot_phone");
          appServerArgs.push(
            "-c", `${prefix}.command=${JSON.stringify(bridge.command)}`,
            "-c", `${prefix}.args=${JSON.stringify(bridge.args)}`,
            "-c", `${prefix}.env_vars=${JSON.stringify(Object.keys(bridge.env))}`,
            "-c", `${prefix}.default_tools_approval_mode="auto"`,
          );
          }
        }

        // Codex hands MCP children its shell environment, so mounted variables (and box-admitted custom env) leave that shell.
        const customBox = customServerEnvBox(turn.integrations?.custom, selectedMcp), boxAdmitted = boxAdmittedEnv(customBox);
        const mountedEnv = [...mountedNames].filter((name) => env[name] !== undefined && !SHELL_ESSENTIALS.has(name) && !name.startsWith("LC_")
          && (name === "ELECTRON_RUN_AS_NODE" || boxAdmitted.has(name) || baseEnv.get(name) !== env[name]));
        const privateEnv = [...new Set([
          ...(config.endpoint ? ["OPENMAUSBOT_CODEX_API_KEY"] : []),
          ...(turn.toolScope !== undefined ? ["OMB_GATE_CONFIG_*"] : []),
          ...PRIVATE_ENV_FAMILIES.filter((family) => mountedEnv.some((name) => name.startsWith(family))).map((family) => `${family}*`),
          ...mountedEnv.filter((name) => !PRIVATE_ENV_FAMILIES.some((family) => name.startsWith(family))).sort(),
        ])];
        // Records this turn writes never run without proof that shell snapshots are off.
        const provenPrivateEnv = turn.toolScope !== undefined || directoryMounts.size > 0;
        if (privateEnv.length && turn.toolScope === undefined) appServerArgs.push("-c", "features.shell_snapshot=false");

        const selectionConfig: { config?: Record<string, unknown> } = turn.toolScope === undefined ? {} : { config: { mcp_servers: Object.fromEntries(
          [...selectedMcp].map(([name, server]) => [name, {
            command: server.command, args: server.args, env_vars: Object.keys(server.env), env: {}, default_tools_approval_mode: selectedApprovals.get(name) ?? "prompt",
          }]),
        ) } };

        const commandCwd = permissionLaunchCwd(turn.cwd ?? homedir());
        // A plan login reaches its process through this turn's token or bridge, which end with the turn.
        const contract = plan ? null : codexSpawnContract({ cli: config.cli, args: appServerArgs, env, cwd: turn.cwd ?? homedir(), box: customBox,
          login: codexOwnLogin(ownLogin, env), thread: { model: turn.model ?? null, approvalMode, ...selectionConfig } });
        const reused = contract && attempt === 0 ? warm.take(threadId, contract, typeof turn.resumeCursor === "string" ? turn.resumeCursor : null) : null;
        const releaseSlot = reused ? () => {} : tryCodexLaunchSlot() ?? await waitForLaunchSlot(attempt);
        if (!releaseSlot) return;
        const connection = reused?.connection ?? new CodexConnection(spawnHoldingSlot(releaseSlot, () => spawnCli(...codexLaunch(config.cli, appServerArgs), {
          cwd: turn.cwd ?? homedir(),
          env,
          stdio: ["pipe", "pipe", "pipe"], box: { ...customBox.box, engine: DRIVER_KIND, ...(authBridge ? { rw: [authBridge.socketPath] } : {}) },
        }, "bot")));
        const child = connection.child;

      let abandoned = false, resumedNativeThread = false, busySession = false;
      let codexThreadId: string | null = null;
      let codexTurnId: string | null = null;
      let startingNativeTurn = false;
      const earlyNotifications: any[] = [];
      const mcpStartup = reused ? null : mcpStartupTracker(child);
      let mcpFailed = false, keepable: { configDigest: string; cwd: string; identity: CodexIdentityInputs; provider: string | null; model: string | null; carried: { initialized: any; approvalParams: CodexApprovalParams; rolloutPath: unknown } } | null = null;
      const state = {
        settled: false,
        lastError: "",
        lastErrorSetup: false,
        retryError: "",
        authRecovery: false,
        lastText: "",
        sawStreamDelta: false,
        streamed: false,
        // codex reports token usage as a running total for the app-server process.
        usage: undefined as { input: number; output: number; cachedInput?: number } | undefined,
        usageBaseline: undefined as { input: number; output: number; cachedInput: number } | undefined,
      };

      const asks = new Map<string, CodexAsk>();
      const rpcPending = new Map<number, {
        resolve: (v: any) => void;
        reject: (e: Error) => void;
      }>();

      const send = (obj: unknown) => {
        connection.write(obj);
        appendNative(threadId, {
          dir: "out",
          source: "codex.app-server",
          msg: codexNativeLogMessage(obj),
        });
      };
      const request = (method: string, params: unknown, timeoutMs = codexRpcTimeoutMs(method)) =>
        new Promise<any>((resolve, reject) => {
          const id = connection.nextId++;
          if (method === "config/read") connection.sensitiveResponseIds.add(id);
          // A wedged app-server can accept stdin and never reply.
          const timer = setTimeout(() => {
            if (rpcPending.delete(id)) reject(new Error(`codex ${method} timed out after ${timeoutMs}ms`));
          }, timeoutMs);
          if (typeof timer.unref === "function") timer.unref();
          rpcPending.set(id, {
            resolve: (v) => {
              clearTimeout(timer);
              if (method === "thread/start" || method === "thread/resume") {
                // Notifications can follow the thread response in one stdout chunk.
                const returnedId = v?.thread?.id;
                const requestedId = method === "thread/resume"
                  && params && typeof params === "object" && "threadId" in params
                  ? params.threadId : null;
                if (typeof returnedId === "string" && returnedId) codexThreadId = returnedId;
                else if (typeof requestedId === "string" && requestedId) codexThreadId = requestedId;
              }
              if (method === "turn/start") {
                if (typeof v?.turn?.id !== "string" || !v.turn.id) {
                  reject(new Error("Codex did not return a native turn id"));
                  return;
                }
                // Bind synchronously: one stdout chunk can hold the response, events, completion and a late request.
                codexTurnId = v.turn.id;
                startingNativeTurn = false;
                for (const notification of earlyNotifications.splice(0)) {
                  if (state.settled || abandoned) break;
                  handleNotification(notification);
                }
              }
              resolve(v);
            },
            reject: (e) => {
              clearTimeout(timer);
              reject(e);
            },
          });
          send({ jsonrpc: "2.0", id, method, params });
        });

      let stopping: Promise<boolean> | undefined;
      const terminate = () => stopping ??= killCliTree(child).then((stopped) => {
        if (!stopped) stopping = undefined;
        return stopped;
      });
      let completeStoppedTurn: (() => void) | undefined;
      // Interrupt over the protocol before any signal: killing first surfaced routine stops as
      // "codex exited null (signal SIGTERM) before turn/completed".
      let interruptRequested = false;
      const stop = async () => {
        captureCliTree(child);
        stopRequested = true;
        stopSignal.abort();
        if (!state.settled && !interruptRequested && codexThreadId && codexTurnId &&
            child.exitCode === null && child.signalCode === null) {
          interruptRequested = true;
          const graceMs = Math.max(1, Number(process.env.FAKE_CODEX_INTERRUPT_GRACE_MS ?? 750) || 750);
          try {
            await request("turn/interrupt", { threadId: codexThreadId, turnId: codexTurnId }, graceMs);
          } catch {}
          const deadline = Date.now() + graceMs;
          while (!state.settled && Date.now() < deadline) {
            await new Promise((wake) => setTimeout(wake, 15));
          }
          // Sign-out must wait until the child holding its token has exited.
        }
        const stopped = await terminate();
        if (stopped) completeStoppedTurn?.();
        return stopped;
      };

      const settle = async (ok: boolean, stopReason: string | null) => {
        if (state.settled) return;
        state.settled = true; authBridge?.close();
        for (const finish of Array.from(asks.values())) finish("deny", "OpenMausBot: the turn ended", "system");
        for (const p of rpcPending.values()) p.reject(new Error("turn settled"));
        rpcPending.clear();
        const complete = () => {
          if (active.get(threadId)?.stop !== stop) return;
          active.delete(threadId);
          emit({ ...base(threadId, turnId), type: "turn.completed", ok, stopReason, cost: null, ...(state.usage ? { usage: state.usage } : {}) });
        };
        if (ok && contract && keepable && codexThreadId && !stopRequested && !abandoned && !disposed && !mcpFailed
          && warm.keep(threadId, { connection, contract, nativeThreadId: codexThreadId, ...keepable })) return complete();
        completeStoppedTurn = complete;
        if (await stop()) return;
        emit({ ...base(threadId, turnId), type: "runtime.error", message: "codex did not shut down after termination was requested" });
        await keepStopping(terminate, () => active.get(threadId)?.stop === stop);
        complete();
      };

      // Retires this process before anything async, so a late rpc timer rejection cannot relaunch again.
      const relaunch = async (reason: string, failure: string, failedStop: string, quiet = false) => {
        const delayMs = quiet ? 0 : computeBackoff(attempt);
        if (quiet) announced = true;
        else emit({ ...base(threadId, turnId), type: "turn.retrying", attempt: ++attempt, delayMs, reason });
        abandoned = true;
        releaseSlot();
        const exited = child.exitCode !== null || child.signalCode !== null;
        if (!exited && !(await terminate()) && !(await waitForExit(child, RELAUNCH_EXIT_WAIT_MS))) {
          emit({ ...base(threadId, turnId), type: "runtime.error", message: failure });
          return settle(false, failedStop);
        }
        await interruptibleDelay(Math.max(1, Math.round(delayMs * retryScale)), stopSignal.signal).promise;
        if (!stopRequested) { try { turnConfigArgs = codexTurnConfigArgs(turn, childEnv()); } catch (error) { emit({ ...base(threadId, turnId), type: "runtime.error", message: error instanceof Error ? error.message : String(error) }); return settle(false, "rpc_error"); } void launchAttempt(attempt).catch(() => authBridge?.close()); }
        else await settle(false, "interrupted");
      };

      const steerActiveTurn = async (text: string): Promise<SteerOutcome> => {
        if (state.settled || abandoned || stopRequested || !codexThreadId || !codexTurnId) return "refused";
        if (child.exitCode !== null || child.signalCode !== null) return "refused";
        try {
          const steerTimeoutMs = Math.max(1, Number(process.env.FAKE_CODEX_STEER_TIMEOUT_MS ?? 10_000) || 10_000);
          await request("turn/steer", {
            threadId: codexThreadId,
            input: [{ type: "text", text }],
            expectedTurnId: codexTurnId,
          }, steerTimeoutMs);
          return "steered";
        } catch (error) {
          const message = error instanceof Error ? error.message : String(error);
          if (state.settled || message.includes("timed out")) return "indeterminate";
          return "refused";
        }
      };

      const controlsHost = turn.integrations?.localComputer?.scope === "local-computer";
      const handleServerRequest = (msg: any) => {
        const method = msg.method as string;
        const params = msg.params ?? {};
        const legacy = method === "execCommandApproval" || method === "applyPatchApproval";
        const isMcpElicitation = method === "mcpServer/elicitation/request";
        const isLegacyMcpPermission =
          method === "mcpServer/elicitation/request" &&
          params?._meta?.codex_approval_kind === "mcp_tool_call";
        const mcpAppApproval = isMcpElicitation ? mcpAppApprovalForm(params) : null;
        const isMcpPermission = isLegacyMcpPermission || mcpAppApproval !== null;
        const isQuestion = method === "item/tool/requestUserInput";
        const isAdditionalPermission = method === "item/permissions/requestApproval";
        const isPermission = legacy || isMcpPermission || isAdditionalPermission ||
          method === "item/commandExecution/requestApproval" ||
          method === "item/fileChange/requestApproval";
        // An MCP elicitation asks for real input, not permission; unknown server requests fail closed instead of being accepted by Full access.
        if (!isQuestion && !isPermission) {
          if (isMcpElicitation) {
            send({ jsonrpc: "2.0", id: msg.id, result: { action: "decline" } });
            emit({ ...base(threadId, turnId), type: "runtime.notice", ...mcpElicitationDeclined(params.serverName) });
          } else {
            send({
              jsonrpc: "2.0",
              id: msg.id,
              error: { code: -32601, message: `Unsupported server request: ${method}` },
            });
          }
          return;
        }
        const protocolQuestions = isQuestion ? parseProtocolAskQuestions(params.questions) : null;
        if (isQuestion && !protocolQuestions) {
          send({
            jsonrpc: "2.0",
            id: msg.id,
            error: {
              code: -32602,
              message: Array.isArray(params.questions)
                ? "ask needs at least one answerable question — a string id and question text each; this request sent none."
                : "ask needs params.questions to be an array of questions, each with a string id and question text.",
            },
          });
          return;
        }
        // Codex asks 'Allow the <server> MCP server to run tool "<tool>"?'. The tool runs from the
        // first quote to the closing `"?`, so `web_search" …` cannot pass for web_search.
        const mcpMessage = typeof params.message === "string" ? params.message : "";
        const mcpTool = isLegacyMcpPermission ? / to run tool "(.*)"\?$/.exec(mcpMessage)?.[1] : undefined;
        const searchedServer = isLegacyMcpPermission && typeof params.serverName === "string" && directoryMounts.has(params.serverName);
        const asksAbout = (tool: string) => mcpMessage === `Allow the ${params.serverName} MCP server to run tool "${tool}"?`;
        if (searchedServer && (asksAbout(SEARCH_TOOL) || asksAbout(DESCRIBE_TOOL))) {
          send({ jsonrpc: "2.0", id: msg.id, result: { action: "accept", content: {} } });
          return;
        }
        const runs = searchedServer && asksAbout(CALL_TOOL) ? directoryCallTarget(CALL_TOOL, params._meta?.tool_params) : undefined;
        const tool =
          mcpAppApproval
            ? mcpAppApproval.tool
            : isLegacyMcpPermission
            ? (runs ?? mcpTool ?? "mcp")
            : isAdditionalPermission
              ? "permissions"
            : method === "item/fileChange/requestApproval" || method === "applyPatchApproval"
            ? "edit"
            : isQuestion
              ? "ask_user"
              : "shell";
        const permissionResult = (allow: boolean) =>
          isMcpPermission
            ? allow
              ? (mcpAppApproval?.allowResult ?? { action: "accept", content: {} })
              : { action: "decline" }
            : isAdditionalPermission
              ? { permissions: allow ? grantedPermissions(params.permissions) : {}, scope: "turn" }
              : { decision: allow ? (legacy ? "approved" : "accept") : legacy ? "denied" : "decline" };
        const shell = method === "execCommandApproval" || method === "item/commandExecution/requestApproval" ? params.command : undefined;
        if (autoAcceptPermissions && isPermission && answersAlone(shell)) {
          return send({
            jsonrpc: "2.0",
            id: msg.id,
            result: permissionResult(true),
          });
        }
        const requestId = newId();
        const summary =
          isAdditionalPermission
            ? additionalPermissionSummary(params.permissions, params.reason)
            : isMcpPermission
            ? (mcpAppApproval?.summary ?? (runs ? `Allow the ${params.serverName} MCP server to run tool ${JSON.stringify(runs)}?`
              : typeof params.message === "string" ? params.message : "MCP access requested"))
            : typeof params.command === "string"
            ? params.command
            : protocolQuestions
              ? protocolQuestions.map(({ question }) => question.question).join(" · ")
            : Array.isArray(params.questions)
              ? params.questions.map((q: any) => q.question ?? q.header).filter(Boolean).join(" · ")
              : typeof params.reason === "string"
                ? params.reason
                : tool;
        const choices =
          isQuestion && protocolQuestions ? questionChoices(protocolQuestions.map(({ question }) => question)) : undefined;
        const finish = (behavior: "allow" | "deny" | "answer", message?: string, source: "user" | "timeout" | "system" = "user") => {
          if (!asks.delete(requestId)) return;
          clearTimeout(timer);
          if (isQuestion) {
            send({ jsonrpc: "2.0", id: msg.id, result: codexQuestionReply(behavior, message, source, protocolQuestions ?? []) });
          } else {
            send({
              jsonrpc: "2.0",
              id: msg.id,
              result: permissionResult(behavior === "allow"),
            });
          }
          emit({ ...base(threadId, turnId), type: "request.resolved", requestId, behavior, source });
        };
        const timer = isQuestion ? undefined : setTimeout(() => finish("deny", DENY_TIMEOUT_NOTE, "timeout"), 15 * 60_000);
        timer?.unref?.();
        asks.set(requestId, finish);
        emit({
          ...base(threadId, turnId),
          type: "request.opened",
          requestId,
          requestType: isQuestion ? "question" : "permission",
          tool,
          summary, ...mcpAppApprovalText(mcpAppApproval),
          ...shellRequest(shell, params.cwd ?? (
            !params.threadId || params.threadId === codexThreadId ? commandCwd : undefined
          )),
          choices,
          ...(protocolQuestions ? { questions: protocolQuestions.map((pair) => pair.question) } : {}),
          approvalScope: controlsHost ? "local-computer" : undefined,
          requiresExplicitApproval: isAdditionalPermission || (
            (method === "execCommandApproval" || method === "item/commandExecution/requestApproval") &&
            (params.additionalPermissions != null || params.networkApprovalContext != null)
          ) || undefined,
        });
      };

      const seenReviews = new Set<string>();
      let reviewWarning = false;
      let teamToolsNoticed = false;
      let rolloutAt: RolloutMark | null = null; // where the native rollout ended when this turn began: a refused call's only trace
      let timedOutReview = false;
      const retryMode = approvalMode[0].toUpperCase() + approvalMode.slice(1);
      const reviewNotice = (status: "warning" | "timedOut" | "denied", action?: any) => {
        if (status === "warning") {
          emit({ ...base(threadId, turnId), type: "runtime.error",
            message: `Codex automatic review reported a timeout. Check what ran before retrying. Retry stays ${retryMode}. Select Ask for human approval in approval settings.`,
          });
          return;
        }
        const command = action?.type === "command" ? commandSummary({ command: action.command }) : undefined;
        const target = command ? `: "${command.slice(0, 30)}"` : " for the requested action";
        const outcome = status === "timedOut" ? "timed out" : "denied";
        emit({ ...base(threadId, turnId), type: "runtime.error",
          message: `Codex automatic review ${outcome}${target}. Action did not run. Retry stays ${retryMode}. Select Ask for human approval in approval settings.`,
        });
      };
      // Each bot's Codex reads auth.json when it starts, possibly while another one rewrites it.
      const retryLoginRace = (raw: string, refused: boolean): boolean => {
        const missing = CODEX_MISSING_CREDENTIALS.test(raw);
        if (!chatgptTurn || loginRaceRetried || state.streamed || attempt >= RETRY_MAX_ATTEMPTS - 1 || !(refused || missing)) return false;
        const mark = loginMark();
        if (!mark || (!missing && mark[1] === launchedLogin)) return false;
        loginRaceRetried = true;
        void relaunch("auth", raw, "auth_required").catch(() => {});
        return true;
      };
      const turnError = (error: { message?: unknown; codexErrorInfo?: unknown }) => {
        const raw = String(error.message);
        if (!droppedSession && resumedNativeThread && !state.streamed && !stopRequested && turn.recoveryText?.trim() && codexPlanUnsupportedInput(raw, route)) { droppedSession = "unsupported-input"; void relaunch("unsupported_input", raw, "rpc_error").catch(() => {}); return; }
        const refused = chatgptTurn && loginMark() !== null && (codexSignInRefused(error) ||
          (state.authRecovery && !/\b403\b|forbidden/i.test(raw) && /\b401\b|unauthorized/i.test(raw)));
        if (retryLoginRace(raw, refused)) return;
        if (refused) loginRefused(); else if (chatgptTurn && CODEX_MISSING_CREDENTIALS.test(raw)) loginCheck.forget();
        const reported: ReturnType<typeof codexUserFailure> = refused ? { message: codexSignInExpired(raw) } : codexUserFailure(raw, route, error.codexErrorInfo);
        const setup = refused || classifyError({ text: raw }).reason === "auth";
        if (reported.message === state.lastError && (state.lastErrorSetup || !setup)) return;
        state.lastError = reported.message;
        state.lastErrorSetup ||= setup;
        hideRefusedModel(raw);
        emit({ ...base(threadId, turnId), type: "runtime.error", ...reported, ...(setup ? { setup: true } : {}), ...codexLimitFacts(raw, route, error.codexErrorInfo) });
      };
      const handleNotification = (msg: any) => {
        const p = msg.params ?? {};
        // MCP servers start with the thread, before it has an id; this process serves this turn alone.
        if (msg.method === "mcpServer/startupStatus/updated") {
          mcpStartup?.record(p); mcpFailed ||= p.status === "failed" || p.status === "cancelled";
          if (!teamToolsNoticed && teamToolsFailed(p)) {
            teamToolsNoticed = true;
            emit({ ...base(threadId, turnId), type: "runtime.notice", message: TEAM_TOOLS_FAILED });
          }
          return;
        }
          // The app-server also notifies for native helper threads; only this request's parent writes or settles.
        const connectionError = msg.method === "error" &&
          !("threadId" in p) && !("turnId" in p);
        if (!connectionError) {
          if (!codexThreadId || p.threadId !== codexThreadId) return;
          if (!codexTurnId && msg.method === "thread/tokenUsage/updated" && p.tokenUsage?.total) {
            // A total reported before this turn exists is what the process carried in: the baseline.
            const t = p.tokenUsage.total;
            state.usageBaseline = connection.usageTotal = { input: t.inputTokens ?? 0, output: t.outputTokens ?? 0, cachedInput: t.cachedInputTokens ?? 0 };
            return;
          }
          if (!codexTurnId) {
            // Some servers stream before acknowledging turn/start.
            if (startingNativeTurn) {
              if (earlyNotifications.length >= 1024) {
                void settle(false, "too_many_events_before_turn_start");
              } else {
                earlyNotifications.push(msg);
              }
            }
            return;
          }
          const eventTurnId = msg.method === "turn/started" || msg.method === "turn/completed"
            ? p.turn?.id : p.turnId;
          // guardianWarning is thread-scoped in Codex 0.147.
          if (eventTurnId !== codexTurnId && !(msg.method === "guardianWarning" && eventTurnId === undefined)) return;
        }
        if (msg.method.startsWith("item/") && p.item?.type !== "userMessage") state.streamed = true;
        switch (msg.method) {
          case "guardianWarning":
            if (typeof p.message === "string" && /automatic approval review.*timed out/i.test(p.message)) reviewWarning = true;
            break;
          case "item/autoApprovalReview/completed": {
            const status = p.review?.status;
            if (status !== "timedOut" && status !== "denied") break;
            if (typeof p.reviewId !== "string" || !p.reviewId) break;
            if (!seenReviews.has(p.reviewId)) {
              seenReviews.add(p.reviewId);
              if (status === "timedOut") timedOutReview = true;
              reviewNotice(status, p.action);
            }
            break;
          }
          // item/completed follows with the whole message, so a delta is only a fallback.
          case "item/agentMessage/delta": {
            const delta = typeof p.delta === "string" ? p.delta : "";
            if (delta) {
              state.sawStreamDelta = true;
              emit({ ...base(threadId, turnId), ...messageItem({ id: p.itemId }), type: "content.delta", streamKind: "assistant_text", delta });
            }
            break;
          }
          case "item/reasoning/textDelta":
          case "item/reasoning/summaryTextDelta": {
            if (typeof p.delta === "string" && p.delta) emit({ ...base(threadId, turnId), type: "content.delta", streamKind: "reasoning_text", delta: p.delta });
            break;
          }
          case "item/fileChange/patchUpdated": { const draft = codexPatchProgress(p); if (draft) emit({ ...base(threadId, turnId), ...draft }); break; }
          case "item/commandExecution/outputDelta": { const output = codexCommandOutput(p); if (output) emit({ ...base(threadId, turnId), ...output }); break; }
          case "item/started": {
            const item = p.item ?? {};
            const runs = item.type === "mcpToolCall" && item.tool === CALL_TOOL && typeof item.server === "string" && directoryMounts.has(item.server)
              ? directoryCallTarget(CALL_TOOL, item.arguments) : undefined;
            const title =
              item.type === "commandExecution"
                ? String(item.command ?? "shell")
                : item.type === "fileChange"
                  ? "edit"
                  : item.type === "mcpToolCall"
                    ? (runs ?? item.tool ?? item.name ?? "mcp")
                    : item.type === "webSearch"
                      ? "web_search"
                      : null;
            if (title) {
              emit({
                ...base(threadId, turnId),
                type: "item.started",
                itemType: "tool",
                itemId: item.id,
                title,
                summary: item.type === "commandExecution" ? commandSummary({ command: item.command }) : undefined,
                input: toolDetailPreview(item.type === "commandExecution" ? { command: item.command, cwd: item.cwd } : item.type === "mcpToolCall" ? (runs ? item.arguments?.arguments ?? {} : item.arguments) : item.type === "fileChange" ? item.changes : item.query),
              });
            }
            break;
          }
          case "item/completed": {
            const item = p.item ?? {};
            if (item.type === "agentMessage") {
              if (item.text?.trim()) {
                state.lastText = item.text;
                if (!state.sawStreamDelta) {
                  emit({ ...base(threadId, turnId), ...messageItem(item), type: "content.delta", streamKind: "assistant_text", delta: item.text });
                }
                state.sawStreamDelta = false;
                emit({ ...base(threadId, turnId), ...messageItem(item), type: "item.completed", itemType: "assistant_text", text: item.text });
              }
              openAsyncQuestion(item, asks, steerActiveTurn, (event) => emit({ ...base(threadId, turnId), ...event }));
            } else if (item.type === "imageGeneration" && item.status !== "failed") {
              // The app-server returns the generated raster as base64 `result` and may expose a local
              // `savedPath`; use the bytes, never the provider-owned path.
              if (typeof item.result === "string" && item.result.trim()) {
                emit({
                  ...base(threadId, turnId),
                  type: "item.completed",
                  itemType: "assistant_image",
                  itemId: item.id,
                  data: item.result,
                  alt: typeof item.revisedPrompt === "string" ? item.revisedPrompt : undefined,
                });
              }
            } else if (["commandExecution", "fileChange", "mcpToolCall", "webSearch"].includes(item.type)) {
              emit({
                ...base(threadId, turnId),
                type: "item.completed",
                itemType: "tool",
                itemId: item.id,
                ok: item.status !== "failed" && item.status !== "declined",
                output: toolDetailPreview(item.type === "commandExecution" ? { output: item.aggregatedOutput, exitCode: item.exitCode } : item.type === "mcpToolCall" ? item.error ?? item.result : item.type === "fileChange" ? item.changes : item.action),
              });
              if (item.type === "mcpToolCall" && !isOwnScreenTool(item.server, item.tool, ownScreen)) {
                for (const img of extractMcpImages(item.result)) {
                  emit({ ...base(threadId, turnId), type: "item.completed", itemType: "assistant_image", data: img.data, fromTool: true });
                }
              }
            } else if (item.type === "reasoning" || item.type === "contextCompaction") {
              emit(item.type === "reasoning" ? { ...base(threadId, turnId), type: "item.updated", itemType: "reasoning", tokens: null } : { ...base(threadId, turnId), type: "context.compacted" });
            }
            break;
          }
          case "thread/tokenUsage/updated": {
            // `total` covers this app-server process, `last` the latest model call; codex's inputTokens
            // already includes cachedInputTokens.
            const t = p.tokenUsage?.total;
            const last = p.tokenUsage?.last;
            const shape = (u: { inputTokens?: number; outputTokens?: number; cachedInputTokens?: number }) => ({
              input: u.inputTokens ?? 0, output: u.outputTokens ?? 0, cachedInput: u.cachedInputTokens ?? 0,
            });
            if (t) {
              const b = state.usageBaseline ?? { input: 0, output: 0, cachedInput: 0 };
              const now = connection.usageTotal = shape(t);
              state.usage = {
                input: Math.max(0, now.input - b.input),
                output: Math.max(0, now.output - b.output),
                ...(typeof t.cachedInputTokens === "number" ? { cachedInput: Math.max(0, now.cachedInput - b.cachedInput) } : {}),
              };
            } else if (last) {
              state.usage = { input: last.inputTokens ?? 0, output: last.outputTokens ?? 0, ...(typeof last.cachedInputTokens === "number" ? { cachedInput: last.cachedInputTokens } : {}) };
            }
            if (t) {
              const window = p.tokenUsage?.modelContextWindow;
              emit({
                ...base(threadId, turnId),
                type: "thread.token-usage.updated",
                input: t.inputTokens ?? 0,
                output: t.outputTokens ?? 0, ...(typeof t.reasoningOutputTokens === "number" ? { reasoning: t.reasoningOutputTokens } : {}),
                ...(typeof t.cachedInputTokens === "number" ? { cachedInput: t.cachedInputTokens } : {}),
                ...(last && typeof last.inputTokens === "number" ? { contextTokens: last.inputTokens } : {}),
                ...(typeof window === "number" && window > 0 ? { contextWindow: window } : {}),
              });
            }
            break;
          }
          case "turn/completed": {
            if (reviewWarning && !timedOutReview) reviewNotice("warning");
            const t = p.turn ?? {};
            if (t.status === "completed") {
              if (chatgptTurn) loginAccepted();
            } else if (typeof t.error?.message === "string") {
              turnError(t.error);
            } else if (t.status === "failed" && !state.lastError && state.retryError) {
              turnError({ message: state.retryError });
            }
            if (abandoned) break;
            reportUnsupportedCalls(rolloutAt, (message, text) => emit({ ...base(threadId, turnId), type: "runtime.notice", message, ...(text ? { text } : {}) }));
            void settle(t.status === "completed", t.status === "completed" ? null :
              (classifyError({ text: state.lastError }).reason === "provider_safety" ? "provider_safety" : (state.lastError || t.status || "failed")));
            break;
          }
          case "error": {
            // 0.144 sends {message}; 0.139 and 0.160 nest {error:{message, codexErrorInfo}}.
            const error = p.error && typeof p.error === "object" ? p.error : { message: p.message };
            if (!error.message) break;
            // 0.160 reports each of its own reconnects ("Reconnecting... 1/5") with willRetry: true.
            if (p.willRetry === true) {
              state.retryError = String(error.message);
              break;
            }
            turnError(error);
            break;
          }
          case "modelProvider/authRecoveryStarted":
            state.authRecovery = true;
            break;
          case "modelProvider/authRecoveryCompleted":
            state.authRecovery = false;
            break;
        }
      };

      const message = (msg: any) => {
        if (abandoned || state.settled) return;
        const loggedMessage = codexNativeIncomingLogMessage(msg, connection.sensitiveResponseIds);
        appendNative(threadId, { dir: "in", source: "codex.app-server", msg: loggedMessage });
        if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) {
          const pend = rpcPending.get(msg.id);
          if (pend) {
            rpcPending.delete(msg.id);
            if (msg.error) pend.reject(new CodexRpcError(msg.error));
            else pend.resolve(msg.result);
          }
        } else if (msg.id !== undefined && msg.method) {
          handleServerRequest(msg);
        } else if (msg.method) {
          handleNotification(msg);
        }
      };
      const error = (e: Error) => {
        if (abandoned) return;
        emit({ ...base(threadId, turnId), type: "runtime.error", ...describeSpawnFailure(e, config.cli, turn.cwd ?? homedir()) });
        void settle(false, "spawn_error");
      };
      const close = (code: number | null, signal: NodeJS.Signals | null) => {
        if (abandoned) return;
        if (state.settled) {
          void stop();
          return;
        }
        if (stopRequested) {
          void settle(false, "interrupted");
          return;
        }
        const recentStderr = connection.stderrSinceOutput.trim();
        const hadStreamedOutput = codexTurnId !== null || state.sawStreamDelta;
        // A signal exit (OOM, kill -9) is terminal whatever the stderr says; classifyError cannot see it.
        const verdict =
          signal !== null
            ? { transient: false, reason: "interrupted" }
            : classifyError({ exitCode: code, stderr: recentStderr });
        const exitMessage = `codex exited ${code}${signal ? ` (signal ${signal})` : ""} before turn/completed${
          recentStderr ? `: ${recentStderr.slice(-300)}` : hadStreamedOutput && connection.stderr.trim() ? "; no stderr after the last app-server output" : ""
        }`;
        // Relaunch only when turn/start was never acknowledged: a replay could re-run tools the user saw.
        if (!stopRequested && codexTurnId === null && earlyNotifications.length === 0 && (reused || (verdict.transient && attempt < RETRY_MAX_ATTEMPTS - 1))) {
          void relaunch(verdict.reason, exitMessage, "exit_before_result", Boolean(reused)).catch(() => {});
          return;
        }
        emit({ ...base(threadId, turnId), type: "runtime.error", message: exitMessage });
        void settle(false, "exit_before_result");
      };
      connection.attach({ message, error, close });

      active.set(threadId, { stop, turnId, asks, steer: steerActiveTurn, pid: child.pid });
      if (attempt === 0 && !announced) emit({ ...base(threadId, turnId), type: "turn.started" });

      try {
        const initialized = reused ? reused.carried.initialized : await request("initialize", {
          clientInfo: { name: "openmausbot", title: "OpenMausBot", version: serverVersion() },
          // Named permission profiles are an experimental app-server field in Codex 0.151.
          capabilities: { experimentalApi: true },
        });
        if (!reused) send({ jsonrpc: "2.0", method: "initialized", params: {} });
        // developerInstructions replaces, rather than appends to, native config.
        let effectiveConfig: unknown;
        try {
          const configured = await request("config/read", {
            cwd: turn.cwd ?? homedir(),
            includeLayers: false,
          });
          effectiveConfig = configured?.config;
        } catch (error) {
          // Never expose a possibly secret-bearing config error; codex's "invalid configuration" carries none.
          const invalid = error instanceof CodexRpcError && /^invalid configuration\b/i.test(error.message);
          throw new Error(
            invalid
              ? "Codex rejected its configuration as invalid. Check ~/.codex/config.toml (or CODEX_HOME) for a broken entry, then retry."
              : "Could not read Codex configuration; cannot safely update bot instructions. Retry after checking Codex.",
          );
        }
        // config/read reads the files again (codex-cli 0.160.1); the loaded thread keeps what it started with.
        const configDigest = codexConfigDigest(effectiveConfig);
        if (reused && reused.configDigest !== configDigest) { appendNative(threadId, { dir: "out", source: "codex.session", msg: { close: "configuration changed", contractChanged: codexContractDiff(reused.configDigest, configDigest) } }); return relaunch("", "Codex configuration changed", "rpc_error", true); }
        if (!reused) await warm.retired();
        if (privateEnv.length || authBridge) {
          const snapshot = (effectiveConfig as { features?: { shell_snapshot?: unknown } } | null)?.features?.shell_snapshot;
          if (provenPrivateEnv || authBridge ? snapshot !== false : snapshot === true) {
            throw new Error("Codex could not disable inherited shell snapshots. No prompt was sent.");
          }
        }
        if (privateEnv.length || plan) {
          const rawPolicy = (effectiveConfig as { shell_environment_policy?: unknown } | null)?.shell_environment_policy;
          if (rawPolicy !== undefined && (!rawPolicy || typeof rawPolicy !== "object" || Array.isArray(rawPolicy))) {
            throw new Error("Codex could not confirm its shell environment policy. No prompt was sent.");
          }
          selectionConfig.config = { ...selectionConfig.config,
            ...extendShellExclusions((rawPolicy ?? {}) as Record<string, unknown>, [...(plan ? ["OPENMAUSBOT_CHATGPT_TOKEN"] : []), ...(authBridge ? PLAN_TOKEN_BRIDGE_ENV : []), ...privateEnv]) };
        }
        if (turn.toolScope !== undefined) {
          const catalog = (effectiveConfig as { mcp_servers?: unknown } | null)?.mcp_servers;
          if (!catalog || typeof catalog !== "object" || Array.isArray(catalog)) throw new Error("Codex could not confirm its selected MCP configuration. No prompt was sent.");
          for (const [name, entry] of Object.entries(catalog)) {
            if (entry && typeof entry === "object" && (entry as { enabled?: unknown }).enabled === false) continue;
            const expected = selectedMcp.get(name);
            const actual = entry as { command?: unknown; args?: unknown; env_vars?: unknown; env?: unknown; default_tools_approval_mode?: unknown; tools?: unknown } | null;
            if (!expected || actual?.command !== expected.command
              || JSON.stringify(actual?.args ?? []) !== JSON.stringify(expected.args ?? [])
              || !Array.isArray(actual?.env_vars) || JSON.stringify([...actual.env_vars].sort()) !== JSON.stringify(Object.keys(expected.env).sort())
              || actual.default_tools_approval_mode !== (selectedApprovals.get(name) ?? "prompt")
              || (actual.env != null && (typeof actual.env !== "object" || Array.isArray(actual.env) || Object.keys(actual.env).length > 0))
              || (actual.tools != null && (typeof actual.tools !== "object" || Array.isArray(actual.tools) || Object.keys(actual.tools).length > 0))) {
              throw new Error("Codex has an MCP server outside the selected configuration. Disable native MCP entries for this account before using tool selection. No prompt was sent.");
            }
          }
        }
        // A Codex that did not take the overrides runs nothing for a guest.
        if (shellOff(turn) && !codexShellDisabled(effectiveConfig)) {
          throw new Error(`This Codex could not turn its shell off, so it can't run this turn. Update Codex, or switch this bot to Claude.${turn.confinedWhy ? ` ${turn.confinedWhy}` : ""}`);
        }
        const stableInstructions = typeof turn.systemStable === "string" && typeof turn.systemVolatile === "string"
          ? turn.systemStable
          : null;
        const promptSplit = stableInstructions !== null;
        // Omitting these on a resumed thread would keep the previous named mode.
        let approvalParams: CodexApprovalParams = approvalMode === "custom" ? customApprovalParams(effectiveConfig) : namedApprovalParams(approvalMode, codexInSeccompBox());
        const instructionsFor = (params: CodexApprovalParams) => codexDeveloperInstructions(effectiveConfig, stableInstructions ?? turn.system ?? "", shellOff(turn) ? "" : codexSandboxNote(params));
        // Validate effectiveConfig upfront so invalid native rules fail before thread creation/reuse.
        instructionsFor(approvalParams);
        // Codex's `never` means "do not ask to escalate", not "grant every requested permission":
        // only Full may synthesize approvals.
        autoAcceptPermissions = approvalMode === "full";
        const selection = codexThreadSelection({ routedProvider: routed ? routedProvider : undefined, plan }, turn.model);
        const cursor = !droppedSession && typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;
        let startedModel: string | null = null;
        // The plan refused the dropped session before anything ran, so replaying the chat repeats no side effects.
        let { text: promptText, replayed: rebuiltFromReplay } = droppedSession ? recoveryPromptFor({ recoveryText: turn.recoveryText, currentText: turn.text, failure: "before-accept" }) : { text: turn.text, replayed: false };
        if (reused) {
          codexThreadId = reused.nativeThreadId; approvalParams = reused.carried.approvalParams; resumedNativeThread = true;
          rolloutAt = rolloutMark(reused.carried.rolloutPath); state.usageBaseline = connection.usageTotal;
        } else if (cursor) {
          const resumeThread = () => request("thread/resume", {
            ...selectionConfig,
            threadId: cursor,
            developerInstructions: instructionsFor(approvalParams),
            model: selection.model,
            ...(selection.modelProvider ? { modelProvider: selection.modelProvider } : {}),
            ...approvalParams.thread,
          });
          // An archived session is unarchived and resumed; if that fails it is rebuilt like a missing one.
          const resumeUnarchived = () => resumeThread().catch((error) => !archivedNativeCodexThread(error, cursor) ? Promise.reject(error)
            : request("thread/unarchive", { threadId: cursor }).then(resumeThread, () => Promise.reject(error)));
          try {
            let resumed;
            try {
              resumed = await resumeUnarchived();
            } catch (error) {
              if (!approvalParams.fallback || !permissionProfileUnsupported(error)) throw error;
              approvalParams = approvalParams.fallback;
              resumed = await resumeUnarchived();
            }
            approvalParams = withResolvedSandbox(approvalParams, resumed);
            codexThreadId = resumed?.thread?.id ?? cursor;
            rolloutAt = rolloutMark(resumed?.thread?.path);
            resumedNativeThread = true;
          } catch (error) {
            const failure = classifyResumeFailure({ attempted: true, rejected: error instanceof CodexRpcError, promptSubmitted, producedOutput: state.sawStreamDelta });
            const recoverable = codexResumeRebuild(error, cursor, turn.recoveryText);
            if (recoveredSession || stopRequested || state.settled || !recoverable || !mayReplay(failure)) throw error;
            // Rebuild once, or every later turn fails the same way.
            recoveredSession = true;
            busySession = recoverable.busy;
            const rebuild = recoveryPromptFor({ recoveryText: turn.recoveryText, currentText: turn.text, failure });
            rebuiltFromReplay = rebuild.replayed;
            promptText = rebuild.text;
          }
        }
        if (!codexThreadId) {
          const startThread = () => request("thread/start", {
              ...selectionConfig,
              developerInstructions: instructionsFor(approvalParams),
              cwd: turn.cwd ?? homedir(),
              model: selection.model,
              ...(selection.modelProvider ? { modelProvider: selection.modelProvider } : {}),
              ...approvalParams.thread,
              ...(shellOff(turn) ? { environments: [] } : {}),
              ephemeral: turn.ephemeral === true,
            });
          let started;
          try {
            started = await startThread();
          } catch (error) {
            if (!approvalParams.fallback || !permissionProfileUnsupported(error)) throw error;
            approvalParams = approvalParams.fallback;
            started = await startThread();
          }
          approvalParams = withResolvedSandbox(approvalParams, started);
          codexThreadId = started?.thread?.id ?? null;
          rolloutAt = rolloutMark(started?.thread?.path);
          startedModel = started?.model ?? null;
        }
        if (!codexThreadId) throw new Error("Codex did not return a native thread id");
        const { deliverVolatile, hadVolatile, commitVolatile, resetSession } = await syncCodexInstructions(threadId, codexThreadId, instructionsFor(approvalParams),
          promptSplit ? turn.systemVolatile ?? "" : "", resumedNativeThread, request, Boolean(turn.mentionTurn), Boolean(turn.recoveryText?.trim()));
        if (resetSession) { droppedSession = "instruction-overflow"; return relaunch("instruction_overflow", "Codex did not shut down while moving this conversation to a fresh session", "rpc_error"); }
        if (deliverVolatile) {
          promptText = withContextNote(
            volatileContextNote(promptSplit ? turn.systemVolatile ?? "" : "", hadVolatile),
            promptText,
          );
        }
        emit({ ...base(threadId, turnId), type: "session.started", sessionId: codexThreadId, model: startedModel ?? turn.model ?? null, ...(rebuiltFromReplay || busySession ? { rebuilt: true } : {}) });
        if (busySession || rebuiltFromReplay) emit({ ...base(threadId, turnId), type: "runtime.notice", message: sessionRebuildNotice("Codex", busySession, droppedSession) });
        const turnInput = [
          ...(promptText ? [{ type: "text" as const, text: withTrailingTurnClock(promptText) }] : []),
          ...await codexImageInputs(turn.images),
        ];
        const startTurn = () => {
          promptSubmitted = true;
          startingNativeTurn = true; keepable = { configDigest, cwd: turn.cwd ?? homedir(), identity: codexIdentityInputs(config.cli, env, ownLogin), provider: selection.modelProvider, model: turn.model && selection.serviceTier ? codexTierOf(turn.model)?.model ?? turn.model : turn.model ?? null, carried: { initialized, approvalParams, rolloutPath: rolloutAt?.path } };
          return request("turn/start", {
            threadId: codexThreadId,
            input: turnInput,
            ...approvalParams.turn,
            // No environment: exec_command, apply_patch and view_image are refused (codex-cli 0.159.0).
            // Without the experimental API the field is rejected, not ignored.
            ...(shellOff(turn) ? { environments: [] } : {}),
            // Spread, not `effort ?? null`: codex-cli 0.146.0 treats null as absent (the thread keeps
            // its effort), rejects "", and thread/start takes no effort, so a thread keeps its last level.
            ...(turn.effort ? { effort: turn.effort } : {}), ...(selection.serviceTier ? { serviceTierForTurn: selection.serviceTier } : {}),
          });
        };
        const waitNames = supportsMcpStartup(initialized?.userAgent) ? enabledMcpMounts([...selectedMcp.keys(), ...directMounts], effectiveConfig, turn.toolScope !== undefined) : [];
        const mcpReady = !mcpStartup || await mcpStartup.settled(waitNames, stopSignal.signal);
        if (!mcpReady || stopRequested || state.settled) return releaseSlot();
        try {
          await startTurn();
        } catch (error) {
          if (!approvalParams.fallback || !permissionProfileUnsupported(error)) throw error;
          approvalParams = approvalParams.fallback;
          await startTurn();
        }
        // Only after turn/start accepted the input may the receipt claim delivery.
        if (commitVolatile) commitVolatile();
        releaseSlot();
      } catch (e) {
        const failure = e instanceof Error ? e : { text: String(e) };
        const raw = e instanceof Error ? e.message : String(e);
        const refused = chatgptTurn && loginMark() !== null && codexSignInRefused({ message: raw });
        hideRefusedModel(raw);
        const reported: ReturnType<typeof codexUserFailure> = refused ? { message: codexSignInExpired(raw) } : codexUserFailure(raw, route);
        const needsAuth = refused || /(?:\b401\b|unauthorized|missing bearer|authentication required)/i.test(raw);
        const verdict = classifyError(failure);
        if (reused && !state.settled && !abandoned && !stopRequested && codexTurnId === null && earlyNotifications.length === 0) return relaunch("", reported.message, "rpc_error", true);
        if (!state.settled && !abandoned && !recoveredSession && !stopRequested && !needsAuth && codexTurnId === null && earlyNotifications.length === 0 && verdict.transient && attempt < RETRY_MAX_ATTEMPTS - 1 && state.sawStreamDelta === false) {
          return relaunch(verdict.reason, reported.message, "rpc_error");
        }
        if (!state.settled && !abandoned) {
          if (refused) loginRefused(); else if (chatgptTurn && CODEX_MISSING_CREDENTIALS.test(raw)) loginCheck.forget();
          emit({
            ...base(threadId, turnId), type: "runtime.error",
            ...codexActionFailure(reported.message, earlyNotifications.some((event) => ["commandExecution", "fileChange", "mcpToolCall", "webSearch"].includes(event.params?.item?.type)), reported.text),
            ...(needsAuth ? { setup: true } : codexLimitFacts(raw, route)),
          });
          await settle(false, needsAuth ? "auth_required" : verdict.reason === "provider_safety" ? "provider_safety" : "rpc_error");
        }
      }
    };

    void launchAttempt(0).catch(() => authBridge?.close());
    return { turnId };
  };

  const readCliVersion = cliVersionProbe(config.cli), signedIn = keptCodexLogin();
  const snapshot = async (): Promise<ProviderSnapshot> => {
    const env = childEnv();
    const probe = await readCliVersion(env);
    if (!("version" in probe)) return { state: "unavailable", ...probe, ...(plan ? { chatgptPlan: true } : {}) }; // `busy` when the check could not finish
    const { version } = probe;
    const warning = planWarning ?? (planAuth && !planRenewal.noteVersion(version) ? "Update Codex to 0.165.0 or newer to renew ChatGPT credentials during a running task." : undefined);
    if (planAuth) return { state: "available", version, chatgptPlan: true, billing: "subscription", ...await planAuth.snapshot(), update: await codexReleaseUpdate(version, config.cli),
      ...(warning ? { warning: { title: "Check ChatGPT connection", message: warning } } : {}) };
    if (config.endpoint) return { state: "available", version, authenticated: Boolean(input.environment.OPENMAUSBOT_CODEX_API_KEY && input.environment.CODEX_HOME), billing: "metered" };
    if (config.managed) return { state: "available", version, authenticated: Boolean(input.environment.OPENMAUSBOT_COMPANY_API_KEY && input.environment.CODEX_HOME), billing: "metered" };
    const previousCliVersion = modelsCliVersion;
    modelsCliVersion = version;
    if (previousCliVersion !== null && previousCliVersion !== version) await refreshModels();
    const login = await readCodexLogin(config.cli, env), authenticated = signedIn(login);
    if (authenticated && loginRejected()) {
      return { state: "available", version, authenticated: false, reason: CODEX_SIGN_IN_EXPIRED,
        update: await codexReleaseUpdate(version, config.cli), billing: "subscription" };
    }
    const email = authenticated && !login.apiKey ? await codexAccountEmail(config.cli, env) : null;
    return {
      state: "available",
      version,
      authenticated,
      ...(login.apiKey ? { account: { method: "api-key" as const } } : email ? { account: { email } } : {}), // no ChatGPT sign-out
      update: await codexReleaseUpdate(version, config.cli),
      billing: "subscription",
    };
  };

  let openaiUnreachable = false; // set once OpenAI turned a background call away: later ones go straight to the bot's model
  /** The background one-shot: `codex exec` with no tools or session, in an empty folder. Never
   * generateText, or titles and compaction would each start a Codex process. */
  const generateMemoryText = async (prompt: string, options: TextGenerationOptions = {}): Promise<string> => {
    if (startupModelRefresh) await startupModelRefresh;
    if (disposed) throw new Error("This provider was removed.");
    prepareDeviceHome();
    const env = childEnv();
    let providerArgs: string[] = [];
    let authBridge: PlanTokenBridge | null = null;
    if (planAuth) {
      if (planSigningOut) throw new Error("This ChatGPT account is being disconnected.");
      const generation = planGeneration;
      const stillCurrent = () => { if (planSigningOut || disposed || generation !== planGeneration) throw new Error("This ChatGPT account changed."); };
      if (!models.options.length) await refreshModels();
      const token = await planAuth.accessToken();
      stillCurrent();
      linkSharedCodexHome(codexHome({ ...process.env, ...input.environment }), join(planDirectory, "codex"));
      const renewing = await planRenewal.supported();
      stillCurrent();
      authBridge = renewing ? await startPlanTokenBridge(() => planAuth.accessToken(), stillCurrent) : null;
      Object.assign(env, authBridge?.env ?? { OPENMAUSBOT_CHATGPT_TOKEN: token });
      providerArgs = chatgptPlanCodexArgs(!!authBridge);
    } else if (config.endpoint) {
      if (!input.environment.OPENMAUSBOT_CODEX_API_KEY || !input.environment.CODEX_HOME) throw new Error("Direct API key or isolated Codex home is missing. Edit the endpoint in Settings.");
      mkdirSync(input.environment.CODEX_HOME, { recursive: true, mode: 0o700 });
      providerArgs = endpointCodexArgs(config.endpoint);
    } else if (config.managed) {
      if (!input.environment.OPENMAUSBOT_COMPANY_API_KEY || !input.environment.CODEX_HOME) {
        throw new Error("Company model access is unavailable. Reconnect your organization; personal billing will not be used.");
      }
      providerArgs = managedCodexArgs(config.managed);
    }
    const route = codexBackgroundRoute(models, smallModelsUsable(), options.fallback, openaiUnreachable);
    if (!route) { authBridge?.close(); throw new Error("Codex lists no model for background calls. Refresh models in Settings → AI → Providers, on Codex."); }
    try { return await runCodexBackgroundRoute(route, (id) => {
      const selection = planAuth || routed ? { model: id, modelProvider: null } : decodeCodexSelection(id);
      return runCodexOneShot({
        spawn: spawnCli, kill: killCliTree, cli: config.cli, env, prompt, options,
        model: selection.model ?? id,
        modelProvider: selection.modelProvider,
        providerArgs: planAuth || routed ? providerArgs : codexBackgroundProviderArgs(env, id),
        describeError: (message) => {
          const route: CodexRoute = planAuth ? "plan" : selection.modelProvider === OFFICIAL_CODEX_PROVIDER ? "own" : "other";
          hidePlanRefusedModel(selection.model ?? id, message, route);
          return codexUserError(message, route);
        },
      });
    }, options, planAuth || config.managed ? undefined : () => { openaiUnreachable = true; }); } finally { authBridge?.close(); }
  };

  return {
    instanceId,
    driverKind: DRIVER_KIND,
    displayName: input.displayName,
    enabled: input.enabled,
    get models() {
      return models;
    },
    quickModelsUsable: smallModelsUsable,
    refreshModels,
    ...(startupModelRefresh ? { startupModelRefresh } : {}),
    generateMemoryText,
    ...(plan ? { authenticationMethod: "browser-pkce" as const } : {}),
    ...(!config.endpoint ? {
      startAuthentication: async () => {
        if (planSigningOut || disposed) throw new Error("This account is being disconnected. Wait before signing in again.");
        if (planAuth) planGeneration++; // a new login may replace the account before its status is polled
        return (planAuth ?? authentication).start();
      },
      getAuthentication: async (flowId: string) => {
        const result = await (planAuth ?? authentication).get(flowId);
        if (planAuth && result.phase === "succeeded") planWarning = undefined;
        if (planAuth && result.phase === "succeeded" && !models.options.length) await refreshModels();
        return result;
      },
      cancelAuthentication: () => (planAuth ?? authentication).cancel(),
      signOut: async () => {
        if (!planAuth) {
          const mark = loginMark();
          await warm.closeAll("signed out"); await authentication.signOut();
          loginAccepted(mark);
          return;
        }
        planSigningOut = true;
        planGeneration++;
        try {
          const stopped = await Promise.all([...active.values()].map(({ stop }) => stop()));
          if (stopped.some(value => !value)) throw new Error("A ChatGPT task could not stop safely. Stop the task before signing out.");
          models = { default: "", options: [] };
          await planAuth.signOut();
          planWarning = undefined;
        } catch (error) {
          if ((error as { code?: string }).code !== "chatgpt_revocation_unconfirmed") throw error;
          planWarning = (error as Error).message;
        } finally { planSigningOut = false; }
      },
    } : {}),
    snapshot,
    adapter: {
      provider: DRIVER_KIND,
      capabilities: {
        sessionModelSwitch: "unsupported",
        guestTurns: "confined",
        queueing: true,
        computerMcp: true,
        localComputerMcp: true,
        composioMcp: true,
        agentsMcp: true,
      customMcp: true,
        phoneMcp: true,
        browserMcp: true,
        dataMcp: true, emailMcp: true, deviceMcp: true,
        images: true,
        nativeImageInput: true,
        effortLevels: ["low", "medium", "high", "xhigh", "max"],
        strictResume: true, nativeCompaction: true,
      },
      sendTurn,
      compactSession: codexCompactSession({ instanceId, warm, active, turnId: newId, providerOf: (model) => codexThreadSelection({ routedProvider: routed ? routedProvider : undefined, plan }, model).modelProvider,
        refusal: () => disposed ? "this provider was removed" : planSigningOut ? "this account is being disconnected" : null }),
      interruptTurn: async (threadId) => {
        await active.get(threadId)?.stop();
      },
      steer: async (threadId, text) => {
        const turn = active.get(threadId);
        return turn?.steer ? await turn.steer(text) : "refused";
      },
      respondToRequest: async (threadId, requestId, decision) => {
        const turn = active.get(threadId);
        const finish = turn?.asks.get(requestId);
        if (!finish) return "unavailable";
        return (await finish(decision.behavior, decision.message, "user"))
          ?? (decision.behavior === "allow" ? "allowed-once" : decision.behavior === "answer" ? "answered" : "rejected");
      },
      hasSession: (threadId) => active.has(threadId),
      enginePid: (threadId) => active.get(threadId)?.pid,
      stopAll: async () => {
        await Promise.all([...active.values()].map(({ stop }) => stop())); await warm.closeAll("stopAll");
      },
      onEvent: (listener) => {
        listeners.add(listener);
        return () => listeners.delete(listener);
      },
    },
    dispose: async () => {
      disposed = true;
      planGeneration++;
      await authentication.dispose();
      await planAuth?.dispose();
      await Promise.all([...active.values()].map(({ stop }) => stop())); await warm.closeAll("dispose");
      listeners.clear();
    },
  };
},
};