Skip to content

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

111 KB
Raw Blame
// Claude Code over stream-json both ways: prompt on stdin, one retained CLI process per thread,
// each turn settled by the CLI's own `result` frame.
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { createServer as createNetServer } from "node:net";
import { homedir, tmpdir } from "node:os";
import { join, dirname, isAbsolute, normalize } from "node:path";

import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";
import { openStartupModelCatalog, unconfirmedModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";
import { writeFileAtomicIfChanged } from "../atomic.ts";
import { augmentedPath, findCliCandidates } from "../env-path.ts"; import { BASH_MAX_TIMEOUT_MS } from "../system-prompt.ts";
import { boxAudienceKey, brokerSocketPath, describeSpawnFailure, killCliTree, spawnCli } from "../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../engine-stop.ts";
import { execCliProbe } from "../cli-probe-cache.ts"; import { cliToLaunch, cliVersionProbe } from "../cli-version-probe.ts";
import { claudeAuthStatus } from "./claude-auth-status.ts";
import { projectMcpServers } from "./claude-project-mcp.ts";
import { botSettingsFor, folderSettingsEnv, withBotSettings } from "./claude-bot-settings.ts"; import { claudeHookSettings } from "./claude-hooks.ts";
import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";
import { claudeAuthFailure, claudeAuthRecovery, claudeOAuthExpired, readRefusalFrame, refusedSignedOut, type RefusalRead } from "./claude-auth-recovery.ts"; import { sumNativeTurnResults, type NativeTurnResult } from "./claude-turn-result.ts"; import { AWS_CREDENTIAL_ENV_KEYS, bedrockResultError, withBedrockCredentialError } from "./claude-bedrock-aws.ts";
import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS, claudeModelExtras, currentEngineCatalog, endpointContextWindowsField, endpointModelCatalog, withCliVersionGate } from "./claude-model-extras.ts";
import { claudeOwnMcpOverHttp, withLoopbackNoProxy } from "./own-mcp-http.ts"; import { claudeAgentsMount, claudeToolSearchSetting } from "./claude-tool-search.ts"; import { claudeDisabledNativeSkillRules, unusableBuiltIns } from "./claude-unusable-tools.ts"; import { shellOff } from "./shell-off.ts"; import { EMAIL_READ_TOOL_NAMES } from "../../shared/email.ts";
import { claudeElicitations } from "./claude-elicitation.ts"; import { claudePrestartTools, type ClaudePrestartTools } from "./claude-prestart.ts"; import { spawnContractDiff } from "./claude-spawn-contract.ts"; import { claudeContextUsage, liveContextBreakdown, writeControlFrame } from "./claude-context-usage.ts";
import { claudeCostSnapshot, readCostHistory, recordCostState, restoredCostBase, turnCostFromRunningTotal } from "./claude-cost-history.ts";
export { claudeCostSnapshot, restoredCostBase, turnCostFromRunningTotal, type ClaudeCostSnapshot } from "./claude-cost-history.ts";
import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts"; import { CLAUDE_REPLAY_FLOOR, type ClaudeCliVersion, claudeCliSupports, claudeCliUpdate, parseClaudeCliVersion } from "./claude-cli-version.ts";
import { ClaudeLoginController } from "./claude-login-auth.ts";

import type {
  DriverCreateInput,
  ProviderDriver,
  ProviderInstance,
  ProviderSnapshot,
  RuntimeEvent,
  RuntimeEventListener,
  SendTurnInput,
  SteerOutcome,
  TextGenerationOptions,
} from "../contracts.ts";
import { appMountFor, customServerGate, gateQueryTools, gateServer, limitUngatedOutput } from "../mcp-gate-config.ts";
import { canUseMcpServer } from "../../shared/tool-scope.ts";
import { assertToolScopeSupported } from "../../shared/tool-scope-support.ts";
import { newEventId, newId } from "../contracts.ts";
import { askInputSummary, commandSummary, toolDetailPreview } from "../tool-summary.ts";
import { classifyError, computeBackoff, interruptibleDelay, mayResendTurn, USAGE_LIMIT } from "./retry.ts";
import { claudeApiError, claudeApiErrorMessage, claudeLimitError, claudeLimitFacts, claudeLimitRefusal, claudeUsageLimit, claudeVersionTooOld, type ClaudeLimit } from "./claude-limits.ts";
import { createOrgModelBlocks, modelSwapNotice, withOrgBlocks } from "./claude-model-access.ts";
import { engineHomes } from "../engine-homes/engine-homes.ts";
import { TEAM_TOOLS_FAILED, failedCustomMcp, teamToolsFailed } from "./team-tools.ts";
import { PRESTART_IDLE_MS, armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose, stoppedForRoom } from "./session-idle.ts";
import { keyedStable, promptHalves, withRosterNote, withVolatileNote } from "./prompt-split.ts"; import { CLAUDE_OWN_MEMORY_OFF } from "./claude-own-memory.ts";
import { versionAtLeast } from "./acp/version-probe.ts";
import {
  applyClaudeInject,
  decodeInjectId,
  mergeLocalInject,
  probeLocalInjects,
  resolveInjectId,
} from "./local-inject.ts";
import { appendNative } from "./native.ts";
import type { KeepWarmContract } from "./claude-keepwarm.ts"; import { claudeForks } from "./claude-warm-summary.ts";
import { BACKGROUND_CALL_TIMEOUT_MS, backgroundCallArgs, spawnBackgroundCall } from "./claude-background.ts"; import { withEndpointFolder } from "./claude-endpoint-folder.ts";
import { permissionLaunchCwd, shellRequest } from "./permission-command.ts"; import { readToolPaths } from "../own-file-reads.ts";
import { SPAWNED_PROXIES } from "../proxy-paths.ts"; import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";
import { extractMcpImages, isOwnScreenToolName, ownScreenMounts } from "../mcp-tool-images.ts"; import { claudeToolDraft } from "./tool-progress.ts"; import { redactSecretsInText } from "../../shared/redact.ts"; import { foldTranscriptImages, imageFoldTarget, transcriptImagesOver } from "./claude-transcript-images.ts";
import {
  ASK_USER_QUESTION_TOOL,
  ASK_USER_TOOL,
  askQuestionSummary,
  parseAskQuestions,
  parseChoices,
  questionChoices,
  type AskQuestion,
} from "../../shared/ask-question.ts";

/** Parent-session credentials/routing a named account must not inherit. */
export const CLAUDE_ACCOUNT_ENV_KEYS = [
  "CLAUDE_CODE_OAUTH_TOKEN",
  "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
  "CLAUDE_CODE_OAUTH_SCOPES",
  "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
  "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
  "ANTHROPIC_API_KEY",
  "ANTHROPIC_AUTH_TOKEN",
  "ANTHROPIC_BASE_URL",
  "ANTHROPIC_CUSTOM_HEADERS",
  "CLAUDE_CODE_USE_BEDROCK",
  "CLAUDE_CODE_USE_VERTEX",
  "CLAUDE_CODE_USE_FOUNDRY",
] as const;

export function resolveClaudeConfigDir(configDir?: string, env: NodeJS.ProcessEnv = process.env): string {
  const home = env.HOME || env.USERPROFILE || homedir();
  const configured = configDir?.trim() || env.CLAUDE_CONFIG_DIR?.trim() || join(home, ".claude");
  const expanded = configured === "~" ? home : configured.startsWith("~/") ? join(home, configured.slice(2)) : configured;
  if (!isAbsolute(expanded) || /[\p{Cc}\p{Cf}]/u.test(expanded)) {
    throw new Error("claude: configDir must be an absolute path or start with ~/");
  }
  return normalize(expanded);
}

/** What an error `result` says failed: its `errors` (2.1.295: "No conversation found with session ID: …"), else its
 * text in plain words, else its kind; never its synthetic message's "stop_sequence", nor the subtype "success". */
export function claudeResultError(frame: { errors?: unknown; result?: unknown; subtype?: unknown; terminal_reason?: unknown; api_error_status?: unknown }): string {
  const errors = Array.isArray(frame.errors) ? frame.errors.filter((error): error is string => typeof error === "string" && error.trim() !== "") : [];
  if (errors.length) return errors.join("; ");
  if (typeof frame.result === "string" && frame.result.trim()) return claudeApiErrorMessage(frame, frame.result);
  return `Claude ended the turn with an error (${String((frame.subtype !== "success" && frame.subtype) || frame.terminal_reason || "unknown")}).`;
}

/** The CLI environment shared by auth probes and turns, so a probe never reports an API-key login
 * that the turn would strip. */
function claudeEnvironment(
  model?: string | null,
  source: NodeJS.ProcessEnv = process.env,
  configDir?: string,
  instanceEnvironment: NodeJS.ProcessEnv = {},
  endpoint = false, bedrock = false,
): NodeJS.ProcessEnv {
  const env: NodeJS.ProcessEnv = { BASH_MAX_TIMEOUT_MS: String(BASH_MAX_TIMEOUT_MS), ...source, PATH: augmentedPath(), NPM_CONFIG_LOGLEVEL: "error" };
  if (configDir?.trim()) env.CLAUDE_CONFIG_DIR = resolveClaudeConfigDir(configDir, env);
  else if (env.CLAUDE_CONFIG_DIR) env.CLAUDE_CONFIG_DIR = resolveClaudeConfigDir(undefined, env);
  if (configDir?.trim() || endpoint || bedrock) {
    for (const key of bedrock ? [...CLAUDE_ACCOUNT_ENV_KEYS, ...AWS_CREDENTIAL_ENV_KEYS] : CLAUDE_ACCOUNT_ENV_KEYS) {
      // Subscription OAuth always comes from this account's own login, never the parent's.
      if (key.startsWith("CLAUDE_CODE_OAUTH_") || key.endsWith("_FILE_DESCRIPTOR") || !Object.hasOwn(instanceEnvironment, key)) {
        delete env[key];
      }
    }
  }
  delete env.CLAUDECODE;
  delete env.CLAUDE_CODE_ENTRYPOINT;
  stripWorkspaceCredentialEnv(env);
  const applied = applyClaudeInject(env, model);
  // An inherited ANTHROPIC_API_KEY would flip a subscription login to pay-as-you-go.
  if (!applied.injected && !instanceEnvironment.ANTHROPIC_API_KEY) delete env.ANTHROPIC_API_KEY;
  return env;
}

/** Escape hatch: the bot inherits this machine's Claude Code setup (MCP servers, connectors,
 * skills, agents, hooks, personal CLAUDE.md). */
function inheritsUserConfig(env: NodeJS.ProcessEnv): boolean {
  return env.OMB_CLAUDE_INHERIT_USER_CONFIG === "1";
}

export function claudeInheritWarning(env: NodeJS.ProcessEnv): ProviderSnapshot["warning"] | undefined {
  if (!inheritsUserConfig(env)) return undefined;
  return {
    title: "Bots inherit this machine's Claude Code setup",
    message:
      "OMB_CLAUDE_INHERIT_USER_CONFIG=1 is set on the OpenMausBot process, so every Claude bot also loads this " +
      "computer's own MCP servers, connectors, skills, hooks and personal CLAUDE.md on every turn — often thousands " +
      "of extra tokens per model call, and tools nobody gave the bot. Unless a bot genuinely needs a server from " +
      "your user-scope Claude config, remove the variable and restart; add the server under the Apps panel → MCP servers " +
      "or the bot project's .mcp.json instead.",
  };
}

/** The selected CLI account's auth settings, without its hooks, permissions, MCP servers or
 * personal instructions. */
export function readClaudeAuthSettings(
  env: NodeJS.ProcessEnv,
  instanceEnvironment: NodeJS.ProcessEnv = {},
): { env?: Record<string, string>; apiKeyHelper?: string } {
  if (CLAUDE_ACCOUNT_ENV_KEYS.some((key) => instanceEnvironment[key])) return {};
  try {
    const settings = JSON.parse(readFileSync(join(resolveClaudeConfigDir(undefined, env), "settings.json"), "utf8"));
    const authEnv: Record<string, string> = {};
    for (const key of CLAUDE_ACCOUNT_ENV_KEYS) {
      if (!key.endsWith("_FILE_DESCRIPTOR") && typeof settings?.env?.[key] === "string") {
        authEnv[key] = settings.env[key];
      }
    }
    return {
      ...(Object.keys(authEnv).length ? { env: authEnv } : {}),
      ...(typeof settings?.apiKeyHelper === "string" && settings.apiKeyHelper.trim()
        ? { apiKeyHelper: settings.apiKeyHelper } : {}),
    };
  } catch {
    return {};
  }
}

/** OMB_CLAUDE_AUTOCOMPACT: a token count, "auto" (the CLI's own window) or "off"; unset, 1M for the "Claude Opus 5.5 (1M)" pick
 * (also as a gateway names it, after a slash or provider dot), else 200K. The CLI rejects a window outside 100k-1M as an argument error, so a configured value is clamped. */
export function autoCompactWindow(env: NodeJS.ProcessEnv, model?: string | null): string | null {
  const raw = (env.OMB_CLAUDE_AUTOCOMPACT ?? "").trim().toLowerCase();
  if (raw === "off") return null;
  if (raw === "auto") return "auto";
  const fallback = model && OPUS_1M_PICK.test(model.toLowerCase()) ? 1_000_000 : DEFAULT_AUTOCOMPACT_TOKENS, parsed = raw ? Number(raw) : fallback;
  if (!Number.isFinite(parsed) || parsed <= 0) return String(fallback);
  return String(Math.min(1_000_000, Math.max(100_000, Math.floor(parsed))));
}

const DEFAULT_AUTOCOMPACT_TOKENS = 200_000, OPUS_1M_PICK = /(?:^|[/.])claude-opus-5-5\[1m\]$/;

const withWhy = (refusal: string, why: string | undefined) => why ? `${refusal} ${why}` : refusal;

/** Probed on Claude Code 2.1.284 in `default` mode: without this list, built-in "read-only" Bash
 * commands run unasked, and `xargs head` reads any file. */
export const GUEST_CLAUDE_TOOLS = ["Read", "Grep", "Glob", "Edit", "Write", "WebSearch"] as const;
const GUEST_FORBIDDEN_TOOLS = new Set(["Bash", "PowerShell", "WebFetch", "BashOutput", "KillShell", "KillBash", "NotebookEdit", "Task", "Agent"]);
export const GUEST_CLAUDE_PERMISSIONS = {
  blockReadsOutsideWorkingDirectories: true,
  deny: ["Bash", "PowerShell", "WebFetch", "Read(//proc/**)"],
} as const;

const DRIVER_KIND = "claudeAgent";

const NO_ANTHROPIC_KEY = "No Anthropic API key — open Settings → AI → Providers.";

export interface ClaudeConfig {
  cli: string;
  configDir?: string;
  managed?: boolean;
  managedModels?: string[];
  /** A custom endpoint's own models: the whole catalog, first one the default. No Claude model is offered. */
  endpointModels?: string[]; endpointContextWindows?: Record<string, number>;
  permissionMode: "acceptEdits" | "auto" | "bypassPermissions";
  tools?: string[];
  disallowedTools?: string[];
  requireApiKey?: boolean; bedrock?: boolean;
}

export { STATIC_CLAUDE_MODELS };

/** Maps an API slug a local host serves to `host::model`, so the turn injects instead of asking
 *  for /login. */
async function resolveClaudeTurnModel(
  model: string | null | undefined,
  env: Record<string, string | undefined>,
  endpointModels?: string[],
): Promise<string | null | undefined> {
  if (endpointModels) return model && endpointModels.includes(model) ? model : endpointModels[0];
  if (!model || decodeInjectId(model) || currentEngineCatalog("claude").options.some((option) => option.id === model)) {
    return model;
  }
  return resolveInjectId(model, await probeLocalInjects(env)) ?? model;
}

/** Extra ids from ~/.claude/settings.json's extraModels. Its `model` is Claude Code's last-used
 *  slug, not a catalog entry. */
export function readClaudeModelCatalog(env: Record<string, string | undefined> = process.env) {
  let settings: Record<string, unknown> = {};
  try {
    settings = JSON.parse(readFileSync(join(resolveClaudeConfigDir(undefined, env), "settings.json"), "utf8")) as Record<string, unknown>;
  } catch {
    settings = {};
  }

  const { extras, envModel } = claudeModelExtras(settings, env);
  const official = currentEngineCatalog("claude"), options = official.options.map((option) => ({ ...option }));
  const seen = new Set(options.map((option) => option.id));
  for (const extra of extras) {
    if (seen.has(extra.id)) continue;
    seen.add(extra.id);
    options.push(extra.custom || extra.id === envModel
      ? { id: extra.id, label: extra.label, custom: true }
      : { id: extra.id, label: extra.label });
  }
  return { default: official.default, options };
}

const PERM_PROXY_PATH = SPAWNED_PROXIES.permission;
const DWEB_PROXY_PATH = SPAWNED_PROXIES.dweb;
const HOOK_HELPER_PATH = SPAWNED_PROXIES.hook;
// In the packaged app process.execPath is the Electron binary; this makes it run as plain node.
const NODE_ENV_FLAG = { ELECTRON_RUN_AS_NODE: "1" };

function removePrivateTempDir(filePath: string | null | undefined): boolean {
  if (!filePath) return true;
  try {
    rmSync(dirname(filePath), { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
    return true;
  } catch {
    return false;
  }
}

interface Ask {
  id: string;
  kind: "permission" | "question";
  tool: string;
  input: Record<string, unknown>;
  at: number;
}
type AskBehavior = "allow" | "deny" | "answer";
type AskResolutionSource = "user" | "timeout" | "system";

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

function systemEndedReply(kind: Ask["kind"]): { behavior: AskBehavior; message: string } {
  return kind === "question"
    ? { behavior: "answer", message: "OpenMausBot: the turn is ending — wrap up." }
    : { behavior: "deny", message: "OpenMausBot: the turn ended" };
}

function askQuestions(ask: Ask): AskQuestion[] | null {
  return ask.tool === ASK_USER_QUESTION_TOOL || ask.tool === ASK_USER_TOOL ? parseAskQuestions(ask.input) : null;
}

function askSummary(ask: Ask): string {
  const questions = askQuestions(ask);
  if (questions) return askQuestionSummary(questions);
  return askInputSummary(ask.input) ?? ask.tool ?? "tool";
}

/** How long after a `result` the CLI may announce, with `init`, the native turn for a steer sent
 * after the last model call (about 60 ms on 2.1.282). */
export const STEERED_CONTINUATION_GRACE_MS = 2_000;

/** How long a steered continuation may stay silent after its `init` (2.1.282 sends `status` within
 * milliseconds) before the turn closes on the held result. */
export const STEERED_CONTINUATION_SILENCE_MS = 30_000;

const fakeTimerScale = (name: string) => Number(process.env[name] ?? "1") || 1;
const steerGraceScale = () => fakeTimerScale("FAKE_CLAUDE_STEER_GRACE_SCALE");
const steerSilenceScale = () => fakeTimerScale("FAKE_CLAUDE_STEER_SILENCE_SCALE");

/** In a folder of its own, which the bot box puts back read-only: a bind of the file alone would keep showing the box the
 * copy it was started with after a turn renames a new token over it. */
export function hookTokenFile(threadId: string, botId?: string): string {
  const digest = createHash("sha256").update(`${botId ?? ""}\0${threadId}`).digest("hex").slice(0, 24);
  return join(DATA_DIR, "hook-tokens", digest, "token");
}

export function permissionSocketPath(threadId: string, botId?: string) {
  // Half the tag digests the full bot+thread key: Windows named pipes share one global namespace
  // and are never unlinked, and 8 chars keeps POSIX paths under the 104-byte sun_path limit.
  const key = botId ? `${botId}\0${threadId}` : threadId;
  const prefix = threadId.replace(/[^\w-]/g, "").slice(0, 4);
  const digest = createHash("sha256").update(key).digest("hex").slice(0, 4);
  return brokerSocketPath(DATA_DIR, `${prefix}${digest}`);
}

/** Broker bind paths, in order. Windows pipe names are never unlinkable (a hung child can hold one
 * for minutes), and macOS rejects socket paths past `sun_path`, hence the short temp fallback. */
export function brokerSocketCandidates(threadId: string, botId?: string): string[] {
  const base = permissionSocketPath(threadId, botId);
  if (process.platform !== "win32") {
    const scope = createHash("sha256")
      .update(`${DATA_DIR}\0${process.pid}\0${botId ?? ""}\0${threadId}`)
      .digest("hex")
      .slice(0, 16);
    return [base, join(tmpdir(), `omb-perm-${scope}.sock`)];
  }
  return [
    base,
    `${base}-${randomBytes(3).toString("hex")}`,
    `${base}-${randomBytes(3).toString("hex")}`,
  ];
}

export async function createPermissionBroker(opts: {
  socketPaths: string[];
  onAsk: (ask: Ask) => void;
  onResolve: (resolved: Ask & { behavior: AskBehavior; source: AskResolutionSource }) => void;
  isActive?: () => boolean;
  timeoutMs?: number;
}) {
  const timeoutMs = opts.timeoutMs ?? 15 * 60_000;
  const pending = new Map<
    string,
    { ask: Ask; finish: (behavior: AskBehavior, message: string | undefined, source: AskResolutionSource, always?: boolean) => void }
  >();
  // server.close() leaves open connections wired: asks after close must never become cards.
  let closed = false;
  let boundPath = opts.socketPaths[0] ?? "";
  const connectionHandler = (conn: import("node:net").Socket) => {
    conn.on("error", () => {});
    conn.setEncoding("utf8");
    let buf = "";
    conn.on("data", (chunk) => {
      buf += chunk;
      let nl;
      while ((nl = buf.indexOf("\n")) !== -1) {
        const line = buf.slice(0, nl);
        buf = buf.slice(nl + 1);
        let msg: any;
        try {
          msg = JSON.parse(line);
        } catch {
          continue;
        }
        if (msg.t !== "ask") continue;
        const askId = String(msg.id ?? newId());
        const kind = msg.kind === "question" ? ("question" as const) : ("permission" as const);
        if (closed) {
          // Always answer: permission-proxy.ts resolves only on an answer, so a drop hangs the tool.
          try {
            conn.write(JSON.stringify({ t: "answer", id: askId, ...systemEndedReply(kind) }) + "\n");
          } catch {}
          continue;
        }
        // A retained process keeps its proxy connection between turns; late asks fail closed.
        if (opts.isActive && !opts.isActive()) {
          try {
            conn.write(JSON.stringify({ t: "answer", id: askId, ...systemEndedReply(kind) }) + "\n");
          } catch {}
          continue;
        }
        // `pending` is server-scoped: a duplicate id would orphan the first ask.
        if (pending.has(askId)) {
          // askId is client-controlled; JSON.stringify keeps it from corrupting the log line.
          console.error(`permission broker on ${boundPath}: duplicate ask id ${JSON.stringify(askId)} — denying`);
          try {
            conn.write(JSON.stringify({ t: "answer", id: askId, behavior: "deny", message: DUPLICATE_ASK_ID_NOTE }) + "\n");
          } catch {}
          continue;
        }
        const ask: Ask = { id: askId, kind, tool: msg.tool ?? "tool", input: msg.input ?? {}, at: Date.now() };
        const finish = (behavior: AskBehavior, message: string | undefined, source: AskResolutionSource, always?: boolean) => {
          if (!pending.delete(askId)) return;
          clearTimeout(timer);
          try {
            // On `always` the proxy returns the CLI's own suggested rules, so Claude, not the
            // harness, remembers the allow. `source` keeps a timeout note from passing as human words.
            conn.write(
              JSON.stringify({ t: "answer", id: askId, behavior, message, source, ...(always ? { always: true } : {}) }) + "\n",
            );
          } catch {}
          opts.onResolve({ ...ask, behavior, source });
        };
        const timer = kind === "question" ? undefined : setTimeout(() => finish("deny", DENY_TIMEOUT_NOTE, "timeout"), timeoutMs);
        timer?.unref?.();
        pending.set(askId, { ask, finish });
        opts.onAsk(ask);
      }
    });
  };
  let server: ReturnType<typeof createNetServer> | null = null;
  for (const [index, candidate] of opts.socketPaths.entries()) {
    const attempt = createNetServer(connectionHandler);
    try {
      unlinkSync(candidate);
    } catch {}
    let outcome = await new Promise<"listening" | (Error & { code?: string })>((resolve) => {
      attempt.once("listening", () => resolve("listening"));
      attempt.once("error", (error) => resolve(error as Error & { code?: string }));
      attempt.listen(candidate);
    });
    // A fallback under the shared OS temp root must not be connectable by another local account.
    if (outcome === "listening" && process.platform !== "win32") {
      try {
        chmodSync(candidate, 0o600);
      } catch (error) {
        try {
          attempt.close();
        } catch {}
        try {
          unlinkSync(candidate);
        } catch {}
        outcome = error as Error & { code?: string };
      }
    }
    if (outcome === "listening") {
      if (index > 0) {
        console.error(`permission broker: ${opts.socketPaths[0]} is still held — bound fallback ${candidate}`);
      }
      boundPath = candidate;
      server = attempt;
      attempt.on("error", (error) => {
        console.error(`permission broker error on ${candidate}: ${error.message}`);
      });
      break;
    }
    try {
      attempt.close();
    } catch {}
    if (index === opts.socketPaths.length - 1) {
      console.error(`permission broker unavailable on ${candidate}: ${outcome.message}`);
      break;
    }
  }
  // Fail closed: an unbound candidate could connect the proxy to a stale or unrelated listener.
  if (!server) throw new Error("claude: permission broker could not bind a local socket");
  const drain = () => {
    for (const p of Array.from(pending.values())) {
      const { behavior, message } = systemEndedReply(p.ask.kind);
      p.finish(behavior, message, "system");
    }
  };
  return {
    answer(askId: string, behavior: AskBehavior, message?: string, always?: boolean): boolean {
      const p = pending.get(askId);
      if (!p) return false;
      if (p.ask.kind === "question" ? behavior !== "answer" : behavior === "answer") return false;
      p.finish(behavior, message, "user", always && behavior === "allow");
      return true;
    },
    pause() {
      drain();
    },
    close() {
      closed = true;
      drain();
      try {
        server?.close();
      } catch {}
      try {
        unlinkSync(boundPath);
      } catch {}
    },
    socketPath: boundPath,
  };
}

function decodeToolList(value: unknown, field: "tools" | "disallowedTools"): string[] | undefined {
  if (value === undefined) return undefined;
  if (!Array.isArray(value)) throw new Error(`claude: ${field} must be an array of non-empty strings`);
  const decoded: string[] = [];
  const seen = new Set<string>();
  for (const entry of value) {
    if (typeof entry !== "string" || !entry.trim()) {
      throw new Error(`claude: ${field} must be an array of non-empty strings`);
    }
    const normalized = entry.trim();
    if (seen.has(normalized)) continue;
    seen.add(normalized);
    decoded.push(normalized);
  }
  return decoded;
}

function decodeConfig(raw: unknown): ClaudeConfig {
  const o = (raw ?? {}) as Record<string, unknown>;
  const mode = o.permissionMode;
  if (mode !== undefined && mode !== "acceptEdits" && mode !== "auto" && mode !== "bypassPermissions") {
    throw new Error(`claude: invalid permissionMode ${JSON.stringify(mode)}`);
  }
  const tools = decodeToolList(o.tools, "tools");
  const disallowedTools = decodeToolList(o.disallowedTools, "disallowedTools");
  if (o.configDir !== undefined && typeof o.configDir !== "string") throw new Error("claude: configDir must be a string");
  const configDir = typeof o.configDir === "string" ? o.configDir.trim() : undefined;
  if (configDir) resolveClaudeConfigDir(configDir);
  if (o.managedModels !== undefined && (o.managed !== true || !Array.isArray(o.managedModels) || !o.managedModels.length || o.managedModels.some(model => typeof model !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/.test(model)))) throw new Error("Invalid hosted Claude models.");
  if (o.endpointModels !== undefined && ((o.managed === true || o.managedModels !== undefined) || !Array.isArray(o.endpointModels) || !o.endpointModels.length || o.endpointModels.some(model => typeof model !== "string" || !CLAUDE_MODEL_ID.test(model)))) throw new Error("Invalid Claude endpoint models.");
  return {
    cli: typeof o.cli === "string" ? o.cli : "claude",
    ...(configDir ? { configDir } : {}),
    ...(o.managed === true ? { managed: true } : {}),
    ...(o.managedModels ? { managedModels: o.managedModels as string[] } : {}),
    ...(o.endpointModels ? { endpointModels: o.endpointModels as string[] } : {}), ...endpointContextWindowsField(o.endpointContextWindows, o.endpointModels),
    permissionMode: (mode as ClaudeConfig["permissionMode"]) ?? "acceptEdits",
    ...(tools !== undefined ? { tools } : {}),
    ...(disallowedTools !== undefined ? { disallowedTools } : {}),
    ...(o.requireApiKey === true ? { requireApiKey: true } : {}), ...(o.bedrock === true ? { bedrock: true } : {}),
  };
}

function firstText(content: unknown): string {
  if (typeof content === "string") return content;
  return Array.isArray(content) ? content.filter((b) => b?.type === "text" && b.text).map((b) => b.text).join("") : "";
}

type ClaudeImage = NonNullable<SendTurnInput["images"]>[number];
type ClaudeUserContent =
  | { type: "image"; source: { type: "base64"; media_type: ClaudeImage["mime"]; data: string } }
  | { type: "text"; text: string };
type ClaudeUserMessage = {
  type: "user";
  uuid?: string;
  message: { role: "user"; content: string | ClaudeUserContent[] };
};

function claudeUserMessage(
  text: string,
  images: readonly ClaudeImage[] | undefined,
): ClaudeUserMessage {
  if (!images?.length) return { type: "user", message: { role: "user", content: text } };
  const content: ClaudeUserContent[] = images.map((image) => ({
    type: "image",
    source: {
      type: "base64",
      media_type: image.mime,
      data: readFileSync(image.path).toString("base64"),
    },
  }));
  if (text) content.push({ type: "text", text });
  return { type: "user", message: { role: "user", content } };
}

/** Native traces get attached to bug reports: keep the image block's shape, never its bytes. */
function diagnosticClaudeUserMessage(message: ClaudeUserMessage): ClaudeUserMessage {
  if (!Array.isArray(message.message.content)) return message;
  return {
    ...message,
    message: {
      ...message.message,
      content: message.message.content.map((block) =>
        block.type === "image"
          ? {
              ...block,
              source: {
                ...block.source,
                data: `[image data: ${block.source.data.length} base64 chars]`,
              },
            }
          : block,
      ),
    },
  };
}

export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
  driverKind: DRIVER_KIND,
  metadata: { displayName: "Claude", supportsMultipleInstances: true, signInAccount: "Claude" },
  install: {
    command: {
      darwin: "npm install -g @anthropic-ai/claude-code",
      linux: "npm install -g @anthropic-ai/claude-code",
      win32: "npm install -g @anthropic-ai/claude-code",
    },
    needsNode: true,
    docsUrl: "https://claude.com/claude-code",
    signInCommand: "claude",
  },
  models: STATIC_CLAUDE_MODELS,
  decodeConfig,
  defaultConfig: () => decodeConfig({}),

  async create(input: DriverCreateInput<ClaudeConfig>): Promise<ProviderInstance> {
    const { instanceId, config } = input;
    const environment = (model?: string | null) =>
      claudeEnvironment(config.managed ? undefined : model, { ...process.env, ...input.environment }, config.configDir, input.environment, Boolean(config.endpointModels), config.bedrock === true);
    const catalogEnv = environment();
    if (inheritsUserConfig(catalogEnv)) {
      console.error(`claude (${instanceId}): OMB_CLAUDE_INHERIT_USER_CONFIG=1 — bots inherit this machine's Claude Code MCP servers, skills, hooks and CLAUDE.md on every turn; remove it unless a bot needs a user-scope server`);
    }
    let cliVersion: ClaudeCliVersion | null = null;
    let cliVersionChecked = false;
    let models = config.managedModels ? { default: config.managedModels[0], options: config.managedModels.map(id => ({ id, label: id })) }
      : endpointModelCatalog(config.endpointModels, config.endpointContextWindows) ?? currentEngineCatalog("claude");
    const orgBlocks = createOrgModelBlocks(() => engineHomes.everyHome(catalogEnv), (blocked) => { models = withOrgBlocks(models, blocked); });
    const refreshModels = async () => {
      if (config.managed || config.endpointModels) return;
      try {
        const resolved = await mergeLocalInject(readClaudeModelCatalog(catalogEnv), catalogEnv);
        if (resolved.options.length) models = withCliVersionGate(resolved, "claude", cliVersion); else unconfirmedModelCatalog(models);
        await orgBlocks.refresh(true);
      } catch { unconfirmedModelCatalog(models); }
      try { writeStartupModelCache(instanceId, models); } catch {}
    };
    const startupModelRefresh = config.managed || config.endpointModels ? null : (await openStartupModelCatalog({
      instanceId,
      use: (catalog) => { models = catalog; },
      current: () => models,
      refresh: refreshModels,
    }))?.pending ?? null;

    // Whether `claude --help` lists --autocompact (2.1.129 rejects it despite the floor); a launch refusing it keeps it off for that version (every refusing version is remembered).
    let [cliHasAutocompact, cliHelpVersion]: [boolean | null, string | null] = [null, null], autocompactRefusedBy = new Set<string>(), cliProbedAt: string | undefined;
    const readCliVersion = cliVersionProbe(config.cli);
    const ensureCliVersion = async (env: NodeJS.ProcessEnv): Promise<void> => { // and again once PATH finds another copy (an nvm one ahead of Homebrew's)
      const at = findCliCandidates(config.cli, env.PATH ?? "")[0], reprobed = cliVersionChecked, seen = cliProbedAt !== undefined;
      if (reprobed && at === cliProbedAt) { await helpRead?.done; return; } // a help read for this copy may still be running
      const probe = await readCliVersion(env);
      if ("version" in probe) [cliVersion, cliVersionChecked, cliProbedAt] = [parseClaudeCliVersion(probe.version), true, at]; else if (reprobed) [cliVersion, cliVersionChecked, cliHasAutocompact, cliHelpVersion, helpRead] = [null, false, null, null, null]; // another copy that could not be checked: none of the old copy's flags (nor a running read of its help), check again next turn
      if (seen && "version" in probe && (probe.version !== cliHelpVersion || helpRead)) await readCliHelp(probe.version, env); // a running read of another copy's help (a late answer started it) is replaced
    };
    let helpRead: { version: string; done: Promise<void> } | null = null;
    const readCliHelp = (version: string, env: NodeJS.ProcessEnv): Promise<void> => {
      if (helpRead?.version === version) return helpRead.done;
      const read = {
        version,
        done: new Promise<string | null>((resolve) => {
          execCliProbe(cliToLaunch(config.cli, findCliCandidates(config.cli, env.PATH ?? "")[0]), ["--help"], { timeout: 8000, env }, (err, stdout) => resolve(err ? null : stdout)); // on Windows the copy this env finds, not the app PATH's
        }).then((help) => { // a read another copy's read or a failed re-probe replaced since must not bring back its flags
          if (helpRead === read) [cliHasAutocompact, cliHelpVersion, helpRead] = [help === null ? null : !autocompactRefusedBy.has(version) && /^\s*--autocompact\b/m.test(help), version, null];
        }),
      };
      helpRead = read;
      return read.done;
    };
    const listeners = new Set<RuntimeEventListener>();
    const active = new Map<string, { stop: () => void; turnId: string; broker?: Awaited<ReturnType<typeof createPermissionBroker>> }>();

    // Under --input-format stream-json the CLI settles a turn with `result` while stdin stays open,
    // takes the next stdin message as a new turn, and folds one sent mid-turn into the running turn
    // before its next model call (2.1.221).
    interface Session {
      child: ReturnType<typeof spawnCli>;
      broker?: Awaited<ReturnType<typeof createPermissionBroker>>;
      elicit: ReturnType<typeof claudeElicitations>;
      context: ReturnType<typeof claudeContextUsage>;
      mcpConfigPath: string | null;
      systemPromptPath: string | null;
      argsKey: string; /** the CLI version whose --help chose the args, and whether they include --autocompact */ cliVersion: string | null; passedAutocompact: boolean;
      /** the volatile half the conversation holds; null once a compaction may have summarized it away. `roster`: the team roster in the launch prompt, and the one the conversation holds now (a compaction keeps only the first) */
      volatile: string | null; roster: { launched: string; now: string };
      sessionId: string | null;
      /** `init` arrived; before it the CLI took nothing, so a resume retry is safe */
      sawInit: boolean;
      /** why the CLI refused `--resume` with an error result instead of exiting, for the log line */
      resumeRefusal?: string;
      /** the mode `init` reports: the CLI accepts `--permission-mode auto` for any model but runs
       * "default" silently where auto is unavailable (Haiku 4.5, Sonnet 4.5, an org that disabled it) */
      nativePermissionMode: string | null;
      replaysUserMessages: boolean;
      turn: {
        turnId: string;
        input: SendTurnInput;
        retryAbort: AbortController;
        settled: boolean;
        sawStreamDelta: boolean;
        answered?: boolean;
        /** sent to a warm process that has not yet sent this turn's `init`; if it exits first it
         * never took the prompt */
        awaitingInit?: boolean;
        authFailed?: boolean;
        refusalRead?: RefusalRead;
        updateRequired?: boolean;
        limit?: ClaudeLimit | null;
        limitReached?: boolean;
        explained?: boolean;
        stopRequested?: boolean;
        /** Steer uuids no model call has taken in yet. Without --replay-user-messages the CLI never
         * says whether a steer was folded in or runs next. */
        pendingSteers: Set<string>;
        deferred: NativeTurnResult | null;
        continuationGrace: ReturnType<typeof setTimeout> | null;
        armGrace?: () => void;
        continuationSilence: ReturnType<typeof setTimeout> | null;
      } | null;
      idleTimer: ReturnType<typeof setTimeout> | null;
      closing: boolean;
      unconfirmedStopWarned?: boolean;
      /** Started before any message was sent (the adapter's `prestart`) and not yet taken by a turn: it says nothing in the chat.
       * `take` makes the turn that takes it the one its launch is counted as. It waits `spareMs` from `spareAt` (wall clock), on the session it `resumed`. */
      spare?: boolean; spareMs?: number; spareAt?: number; resumed?: string;
      take?: (turnId: string) => void;
      tools?: ClaudePrestartTools;
      /** The engine could not start the `agents` MCP server, or a configured one (the CLI connects them only when a process starts): retired after this turn so the next one reconnects. */ teamToolsFailed?: boolean; customMcpFailed?: boolean;
      stderr: string;
      costTotal: number | null | undefined;
      /** Root close can precede a failed group stop; retry its finalization. */
      finishClose?: () => Promise<void>;
      /** A dead root's surviving group members cannot take the session back; warns, then settles the stopRequested turn. */
      releaseInterrupted?: () => void;
      closed: Promise<void>;
    }
    const sessions = new Map<string, Session>();
    const warmContracts = new Map<string, KeepWarmContract>();
    /** The system prompt each thread's native session is known to hold: a fresh session holds what it launched with, and
     * a resumed one only when the CLI refreshed it (--system-prompt-snapshot); an older CLI's resume keeps what it started with. */
    const recordedPrompts = new Map<string, { session: string; prompt: string }>();
    const warmHolds = new Map<string, number>();
    const spares = new Map<string, Promise<unknown>>(), spareTools = claudePrestartTools();
    const sessionIdle = sessionIdlePolicy("CLAUDE");

    const stopSession = (session: Session) => {
      void killCliTree(session.child).then((stopped) => {
        if (stopped) void session.finishClose?.();
        // A live root keeps the verified-stop wait; a dead root's surviving group members cannot take the session back.
        else if (session.child.exitCode !== null || session.child.signalCode !== null) session.releaseInterrupted?.();
      });
    };
    // The MCP config carries credentials and argv is readable via `ps`: the 0600 file must not sit on disk.
    const clearMcpConfig = (session: Session) => {
      if (!session.mcpConfigPath) return;
      try {
        rmSync(dirname(session.mcpConfigPath), { recursive: true, force: true });
      } catch {}
      session.mcpConfigPath = null;
    };
    /** Forgets a CLI that died mid-turn and removes its files, so the retry starts a clean session. */
    const discardSession = (threadId: string, session: Session) => {
      session.elicit.close(); session.context.close();
      clearMcpConfig(session);
      if (session.systemPromptPath) {
        removePrivateTempDir(session.systemPromptPath);
        session.systemPromptPath = null;
      }
      sessions.delete(threadId);
      session.turn = null;
    };
    const closeSession = (threadId: string, why: string, contractChanged?: string[]) => {
      const s = sessions.get(threadId);
      if (!s || s.closing) return;
      s.closing = true;
      if (!s.spare) forks.closed(threadId, why, s.sessionId);
      stopIdleClose(`${instanceId}\0${threadId}`, s.idleTimer);
      // Close the broker before a replacement binds the same socket; a late close must not unlink it.
      const broker = s.broker;
      s.broker = undefined;
      broker?.close();
      s.elicit.close();
      s.context.close(); s.tools?.close();
      appendNative(threadId, { dir: "out", source: "claude.session", msg: { close: why, ...(contractChanged?.length ? { contractChanged } : {}) } });
      // stdin EOF is the CLI's exit signal; give it a moment, then insist
      try {
        s.child.stdin.end();
      } catch {}
      setTimeout(() => stopSession(s), 5_000).unref?.();
    };
    const armIdle = (threadId: string) => {
      const s = sessions.get(threadId);
      if (!s) return;
      if (s.idleTimer) clearTimeout(s.idleTimer);
      const held = (warmHolds.get(threadId) ?? 0) - Date.now();
      s.idleTimer = armIdleClose(`${instanceId}\0${threadId}`, s.spare ? s.spareMs ?? PRESTART_IDLE_MS : Math.min(2_147_483_647, Math.max(engineIdleMs(threadId, sessionIdle), held)), { close: () => closeSession(threadId, s.spare ? "never used" : "idle"), threadId, policy: sessionIdle, spare: () => s.spare === true, // per-chat
        idle: () => sessions.get(threadId) === s && !s.closing && !s.turn && !active.has(threadId), held: () => !s.spare && (warmHolds.get(threadId) ?? 0) > Date.now() });
    };
    // Keep-warm pings and warm summaries fork a thread's session with its live launch contract (claude-warm-summary.ts).
    const forks = claudeForks({ cli: config.cli, contracts: warmContracts, holds: warmHolds, armIdle, supports: (flag) => cliVersion === null || claudeCliSupports(cliVersion, flag),
      live: (threadId) => { const s = sessions.get(threadId); return s && !s.spare && !s.closing && s.child.exitCode === null ? { sessionId: s.sessionId, turn: Boolean(s.turn), busy: Boolean(s.turn) || active.has(threadId) } : null; },
      summarized: (threadId, run) => { const cost = claudeCostSnapshot(run.costTotal, run.modelUsage); if (cost) recordCostState(run.session, cost); closeSession(threadId, "summarized while idle"); } });
    const writeUser = (s: Session, threadId: string, promptMsg: ClaudeUserMessage): Promise<boolean> => {
      if (!s.child.stdin.writable || s.child.stdin.destroyed) return Promise.resolve(false);
      return new Promise((resolve) => {
        try {
          s.child.stdin.write(JSON.stringify(promptMsg) + "\n", (error) => {
            if (error) return resolve(false);
            appendNative(threadId, {
              dir: "out",
              source: "claude.sdk.message",
              msg: diagnosticClaudeUserMessage(promptMsg),
            });
            resolve(true);
          });
        } catch {
          resolve(false);
        }
      });
    };

    const authRecovery = claudeAuthRecovery((event: RuntimeEvent) => {
      for (const l of Array.from(listeners)) l(event);
    }, async (threadId) => {
      const session = sessions.get(threadId);
      if (!session || !(await killCliTree(session.child))) return false;
      await session.closed;
      return sessions.get(threadId) !== session;
    }, (threadId) => active.has(threadId));
    const emit = (event: RuntimeEvent) => authRecovery.emit(event);
    const base = (threadId: string, turnId: string) => ({
      eventId: newEventId(),
      provider: DRIVER_KIND,
      threadId,
      turnId,
      createdAt: new Date().toISOString(),
    });
    const retryState = new Map<string, { attempt: number; cancelled: boolean; rebuilt?: boolean }>();

    /** `spare`: launch the thread's process as this turn would and stop there: nothing is written to it and no turn starts. */
    const sendTurn = async (turn: SendTurnInput, logicalTurnId?: string, spare = false, spareMs?: number) => {
      if (startupModelRefresh) await startupModelRefresh;
      turn = { ...turn, toolScope: assertToolScopeSupported(DRIVER_KIND, turn.toolScope) };
      if (config.managedModels && (!turn.model || !config.managedModels.includes(turn.model))) throw new Error("This model is not assigned to this workspace.");
      if (config.requireApiKey && !input.environment.ANTHROPIC_API_KEY) throw new Error(NO_ANTHROPIC_KEY);
      if (config.managed && (!turn.model || turn.model.includes("::") || !config.configDir ||
          !input.environment.ANTHROPIC_API_KEY || !input.environment.ANTHROPIC_BASE_URL)) {
        throw new Error("Company model access is unavailable. Reconnect your organization; personal billing will not be used.");
      }
      const { threadId, botId } = turn;
      const relaunch = logicalTurnId !== undefined;
      // A turn waits for a spare still launching, then takes it or replaces it below; a spare never starts beside a turn or another process.
      const taken = () => sessions.has(threadId) || active.has(threadId) || retryState.has(threadId);
      if (spare && taken()) return { turnId: "" };
      if (!spare && spares.has(threadId)) await spares.get(threadId);
      if (!relaunch) {
        // taskkill is asynchronous on Windows: a turn sent right after Stop waits for the stopped
        // process to be gone.
        const stopped = sessions.get(threadId);
        if (stopped?.turn?.stopRequested && active.get(threadId)?.turnId === stopped.turn.turnId &&
            await killCliTree(stopped.child)) await stopped.closed;
        if (active.has(threadId)) throw new Error("a turn is already running on this thread");
      }
      const permissionMode = turn.approvalMode === undefined
        ? config.permissionMode
        : turn.approvalMode === "full" ? "bypassPermissions"
          : turn.approvalMode === "auto" ? "auto"
            : turn.approvalMode === "edits" ? "acceptEdits" : "default";
      const controlsHost = turn.integrations?.localComputer?.scope === "local-computer";
      if (controlsHost && permissionMode === "bypassPermissions" && turn.approvalMode !== "full") {
        throw new Error("local computer control requires the interactive approval broker");
      }
      let turnId = logicalTurnId ?? newId();
      const retryAbort = new AbortController();
      const retry = retryState.get(threadId) ?? { attempt: 0, cancelled: false };
      if (!relaunch) {
        retry.cancelled = false;
        retry.rebuilt = false;
      }
      if (!spare) retryState.set(threadId, retry);
      const retryScale = Number(process.env.FAKE_CLAUDE_RETRY_SCALE ?? "1");
      let sessionId = !turn.sessionReset && typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;
      let newSessionId = sessionId ? null : newId();

      const args = [
        "-p",
        "--output-format", "stream-json",
        "--input-format", "stream-json",
        "--verbose", // required by stream-json output
        "--include-partial-messages",
        "--permission-mode", permissionMode,
      ];
      if (shellOff(turn) && permissionMode !== "default" && !(turn.linkLimited && permissionMode === "acceptEdits")) {
        throw new Error(turn.guestConfined ? "A guest's turn on this Cloud runs only in Ask." : "Work from the person's other place runs here only in Ask or Auto-accept edits.");
      }
      if (shellOff(turn)) args.push("--restricted", "--tools", GUEST_CLAUDE_TOOLS.join(","));
      else if (config.tools !== undefined) args.push("--tools", config.tools.join(","));
      const turnEnvironment = environment();
      const turnModel = config.managed ? turn.model : await resolveClaudeTurnModel(turn.model, turnEnvironment, config.endpointModels);
      const injected = config.managed || config.endpointModels ? { model: turnModel ?? null, injected: false } : applyClaudeInject({ ...turnEnvironment }, turnModel);
      const launchCli = findCliCandidates(config.cli, turnEnvironment.PATH ?? "")[0]; await ensureCliVersion(turnEnvironment);
      for (let tries = 0; tries < 2 && cliVersionChecked && cliProbedAt !== launchCli; tries++) await ensureCliVersion(turnEnvironment); // another copy's late check landed while this turn waited
      const ownCli = cliProbedAt === launchCli, turnCliVersion = ownCli ? cliVersion : null; // still another copy's state: none of its flags, its version counts as unknown
      if (shellOff(turn) && !claudeCliSupports(turnCliVersion, "--restricted")) {
        throw new Error(withWhy("This Claude Code is too old to run this turn without a shell. Update Claude Code.", turn.confinedWhy));
      }
      const replaysUserMessages = turnCliVersion === null || versionAtLeast(turnCliVersion, CLAUDE_REPLAY_FLOOR);
      if (replaysUserMessages) args.push("--replay-user-messages");
      const isolated = !inheritsUserConfig(turnEnvironment); const projectSettingsOnly = isolated && claudeCliSupports(turnCliVersion, "--setting-sources");
      const disallowed = [...(config.disallowedTools ?? []), ...unusableBuiltIns({ isolated, listsTools: config.tools !== undefined, guest: shellOff(turn) }), ...claudeDisabledNativeSkillRules(botId)];
      if (disallowed.length) args.push("--disallowedTools", disallowed.join(","));
      if (turn.toolScope !== undefined && (!isolated || turn.mcpFromUserConfig || turnCliVersion === null || !claudeCliSupports(turnCliVersion, "--strict-mcp-config"))) {
        throw new Error("Claude cannot confirm a restricted MCP configuration for this account. Disable inherited Claude MCP servers and use a current, identifiable Claude CLI before using tool selection.");
      }
      if (isolated) {
        // Without these every turn gets this machine's MCP servers, connectors, skills, hooks and CLAUDE.md (one desktop: 407 tools, ~10k tokens).
        if (!turn.mcpFromUserConfig && claudeCliSupports(turnCliVersion, "--strict-mcp-config")) args.push("--strict-mcp-config");
        if (projectSettingsOnly) args.push("--setting-sources", "project");
        if (turn.userSkillsDir && !shellOff(turn)) args.push("--add-dir", turn.userSkillsDir);
      }
      const compactWindow = autoCompactWindow(turnEnvironment, injected.model);
      const passedAutocompact = Boolean(compactWindow) && ownCli && cliHasAutocompact === true; if (compactWindow && passedAutocompact) args.push("--autocompact", compactWindow);
      // --resume keeps the recorded system prompt, so every turn refreshes it.
      const refreshesRecordedPrompt = ownCli && cliVersionChecked && claudeCliSupports(cliVersion, "--system-prompt-snapshot");
      const knowsRecordedPrompt = refreshesRecordedPrompt && cliVersion !== null;
      if (refreshesRecordedPrompt) args.push("--system-prompt-snapshot", "off");
      // Before any broker or process, so a bad attachment leaves nothing live.
      let promptMsg = claudeUserMessage(turn.text, turn.images);
      // A new process gets the stable half only; the volatile half rides its first message, so a relaunch reuses the cached prefix.
      const halves = promptHalves(turn);
      const launchSystem = halves.stable ?? turn.system;
      // A CLI without the snapshot flag reopens a session with the prompt it recorded at launch, so a changed prompt
      // would never reach it: rebuild the turn from the recovery text in a fresh session instead of resuming stale.
      const recordedPrompt = createHash("sha256").update(keyedStable(turn) ?? turn.system ?? "").digest("hex");
      const recorded = sessionId === null ? undefined : recordedPrompts.get(threadId);
      if (sessionId !== null && !knowsRecordedPrompt && recorded !== undefined && recorded.session === sessionId && recorded.prompt !== recordedPrompt) {
        const recovery = recoveryPromptFor({ recoveryText: turn.recoveryText, currentText: turn.text, failure: "before-accept" });
        console.error(`claude (${instanceId}): session ${sessionId} for thread ${threadId} holds a system prompt this CLI cannot refresh, starting a new one`);
        turn = { ...turn, text: recovery.text, resumeCursor: undefined, recoveryText: undefined };
        sessionId = null;
        newSessionId = newId();
        promptMsg = claudeUserMessage(turn.text, turn.images);
        retry.rebuilt = recovery.replayed;
      }
      if (injected.model) args.push("--model", injected.model);
      if (turn.effort) args.push("--effort", turn.effort);

      // Off argv: Windows' CreateProcess limit (spawn ENAMETOOLONG), and the prompt may be sensitive.
      let systemPromptPath: string | null = null;

      // Pre-allowed: a headless acceptEdits run silently denies anything unlisted.
      const mcpServers: Record<string, unknown> = {};
      const allowed: string[] = [];
      for (const [name, bridge] of [["composio", turn.integrations?.composio], [OWN_APPS_SERVER, turn.integrations?.composioOwn]] as const) {
        if (bridge) { mcpServers[name] = { ...bridge }; allowed.push(`mcp__${name}`); }
      }
      if (turn.integrations?.localComputer) {
        const local = turn.integrations.localComputer;
        mcpServers.computer = { command: local.command, args: local.args, env: local.env };
        // Never pre-allowed: a computer call takes the turn's permission mode, cloud box or host.
      }
      const cwd = turn.cwd ?? homedir(), toolSearch = claudeToolSearchSetting(cwd, turnEnvironment);
      // Pre-allowed, or the CLI's own ListAgents look-alike shadows it.
      if (turn.integrations?.agents) {
        mcpServers.agents = claudeAgentsMount(turn.integrations.agents, toolSearch);
        allowed.push("mcp__agents");
      }
      if (turn.integrations?.phone) {
        mcpServers.phone = { ...turn.integrations.phone };
        allowed.push("mcp__phone");
      }
      if (turn.integrations?.browser) {
        // Behind tool search, the first browser action costs a ToolSearch model step.
        mcpServers.browser = turn.preloadBrowserTools
          ? { ...turn.integrations.browser, alwaysLoad: true }
          : { ...turn.integrations.browser };
        allowed.push("mcp__browser");
      }
      for (const name of ["data", "device"] as const) {
        if (turn.integrations?.[name]) { mcpServers[name] = { ...turn.integrations[name] }; allowed.push(`mcp__${name}`); }
      }
      if (turn.integrations?.email) { mcpServers.email = { ...turn.integrations.email }; allowed.push(...EMAIL_READ_TOOL_NAMES.map((tool) => `mcp__email__${tool}`)); } // Only its reads: a send asks as any tool of a person's own server does.
      if (turn.integrations?.dweb) {
        mcpServers.dweb = {
          command: process.execPath,
          args: [DWEB_PROXY_PATH],
          env: {
            ...NODE_ENV_FLAG,
            DWEB_URL: turn.integrations.dweb.url,
          },
        };
        allowed.push("mcp__dweb");
      }
      // User servers are not pre-allowed, so acceptEdits routes each call to the broker. Remote
      // entries are already in the CLI's shape and it connects itself: Claude Code 2.1.292 sends only
      // spec-defined initialize fields (2025-11-25), so strict servers accept it, and it keeps its MCP
      // tool search for big catalogs.
      const botOwned = new Set<string>();
      for (const [name, server] of Object.entries(turn.integrations?.custom ?? {})) {
        if (Object.hasOwn(mcpServers, name)) continue;
        mcpServers[name] = { ...server };
        botOwned.add(name);
      }
      // --strict-mcp-config makes this the CLI's only MCP source, so the bot project's servers merge
      // last, never shadowing a harness mount. Never for a guest: its folder could declare a command.
      if (isolated && turn.cwd && !shellOff(turn)) {
        for (const [name, server] of Object.entries(projectMcpServers(turn.cwd))) {
          if (Object.hasOwn(mcpServers, name)) continue;
          mcpServers[name] = server;
          botOwned.add(name);
        }
      }
      for (const name of turn.toolScope === undefined ? botOwned : Object.keys(mcpServers)) {
        if (!canUseMcpServer(turn.toolScope, name)) { delete mcpServers[name]; continue; }
        const gated = gateServer({ name, server: mcpServers[name], threadId, nodeEnv: NODE_ENV_FLAG, toolScope: turn.toolScope, ...customServerGate(name, botOwned.has(name), turn.integrations?.customResultBudgets, turnEnvironment), apps: appMountFor(name, turn) });
        if (gated) mcpServers[name] = { ...gated, ...((mcpServers[name] as { alwaysLoad?: unknown })?.alwaysLoad === true ? { alwaysLoad: true } : {}) };
      }
      allowed.splice(0, allowed.length, ...allowed.filter((name) => Object.hasOwn(mcpServers, name.slice("mcp__".length).split("__")[0]!)));
      const ownHttp = claudeOwnMcpOverHttp(mcpServers); // OpenMausBot's own servers by URL where that setting is on: no proxy process each
      // Full access keeps ask_user: native bypass skips permission prompts, not questions.
      let broker: Awaited<ReturnType<typeof createPermissionBroker>> | undefined;
      const socketPath = permissionSocketPath(threadId, botId);
      if (permissionMode !== "bypassPermissions") {
        args.push("--permission-prompt-tool", "mcp__ogb__approve");
      }
      const permissionEnv = { ...NODE_ENV_FLAG, ...(turn.toolScope !== undefined ? { OMB_PERMISSION_TOOL_SCOPE: JSON.stringify(turn.toolScope) } : {}) };
      mcpServers.ogb = { command: process.execPath, args: [PERM_PROXY_PATH, socketPath], env: permissionEnv, alwaysLoad: true };
      allowed.push("mcp__ogb", ...gateQueryTools(mcpServers));
      // A guest pre-allows only harness tools; anything else (the browser can open file:) asks.
      if (shellOff(turn)) allowed.splice(0, allowed.length, ...allowed.filter((name) => name === "mcp__ogb" || name === "mcp__agents"));
      const env = withEndpointFolder(environment(config.endpointModels ? undefined : turnModel), config, () => retryState.delete(threadId)); if (ownHttp) withLoopbackNoProxy(env); env.PATH = turnEnvironment.PATH; // launch the copy this turn checked, not one a newer PATH finds
      // The MCP config carries credentials and argv is readable via `ps`: a 0600 file, removed at settle.
      let mcpConfigPath: string | null = null;
      if (Object.keys(mcpServers).length) {
        mcpConfigPath = join(mkdtempSync(join(tmpdir(), "omb-mcp-")), "mcp.json");
        args.push("--mcp-config", mcpConfigPath);
        args.push("--allowedTools", allowed.join(","));
      }

      const authSettings = isolated && !injected.injected
        ? readClaudeAuthSettings(env, input.environment) : {};
      // The hook helper reads its bearer from a per-thread file refreshed every turn, so a
      // long-lived CLI process never presents a stale token.
      const hooks = turn.integrations?.hooks;
      const hookTokenPath = hooks ? hookTokenFile(threadId, botId) : null;
      if (hooks && hookTokenPath) {
        mkdirSync(dirname(hookTokenPath), { recursive: true, mode: 0o700 });
        if (!spare) writeFileAtomicIfChanged(hookTokenPath, hooks.token, { mode: 0o600, durable: false });
        env.OMB_HOOK_URL = hooks.url;
        env.OMB_HOOK_TOKEN_FILE = hookTokenPath;
        // in the packaged app process.execPath is Electron — run the helper as node
        if (process.versions.electron) env.ELECTRON_RUN_AS_NODE = "1";
      }
      // Every MCP server without alwaysLoad loads on demand behind ToolSearch (claude-tool-search.ts).
      const own: Record<string, unknown> = { ...authSettings, env: { ...authSettings.env, ENABLE_TOOL_SEARCH: toolSearch, ...(isolated ? CLAUDE_OWN_MEMORY_OFF : {}) } };
      // Project-only settings still find the personal memory and rules via ancestors when the bot lives under HOME.
      if (isolated) own.claudeMdExcludes = [join(homedir(), ".claude", "CLAUDE.md"), join(homedir(), ".claude", "rules", "**")];
      if (hooks) own.hooks = claudeHookSettings(HOOK_HELPER_PATH);
      if (shellOff(turn)) own.permissions = GUEST_CLAUDE_PERMISSIONS;
      // Approvals and browser credentials expire at the turn boundary; native background workers and cron jobs must not outlive it.
      env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS = env.CLAUDE_CODE_DISABLE_CRON = "1";
      // Never for a guest: --restricted leaves project settings out, and a hook is a command. The MCP output limit comes after, so one the bot set there is kept.
      const botSettings = shellOff(turn) ? {} : botSettingsFor(turn.botSettingsFile, cwd, env); limitUngatedOutput(env, mcpServers, botOwned, turn.integrations?.customResultBudgets, (botSettings.env as Record<string, unknown> | undefined)?.MAX_MCP_OUTPUT_TOKENS ?? (shellOff(turn) ? undefined : folderSettingsEnv(cwd, "MAX_MCP_OUTPUT_TOKENS", projectSettingsOnly)));
      const settings = withBotSettings(botSettings, own);
      const authSettingsPath = mcpConfigPath && Object.keys(settings).length
        ? join(dirname(mcpConfigPath), "auth-settings.json") : null;
      if (authSettingsPath) args.push("--settings", authSettingsPath);
      const commandCwd = permissionLaunchCwd(cwd);
      const privateFileFlags = new Set(["--mcp-config", "--settings"]);
      const keyArgs = args.filter((a, i) => !privateFileFlags.has(a) && !privateFileFlags.has(args[i - 1] ?? ""));
      const argsKey = JSON.stringify({
        args: keyArgs,
        system: keyedStable(turn) ?? turn.system ?? null,
        mcpServers,
        cwd,
        model: injected.model ?? null,
        base: env.ANTHROPIC_BASE_URL ?? null,
        configDir: env.CLAUDE_CONFIG_DIR ?? null,
        hooks: Boolean(hooks), box: boxAudienceKey(cwd),
        toolSearch, mcpOutputTokens: env.MAX_MCP_OUTPUT_TOKENS ?? null,
        botSettings: createHash("sha256").update(JSON.stringify(botSettings)).digest("hex"),
        // Rotating an account's key/helper must not reuse the old process.
        auth: createHash("sha256").update(JSON.stringify({
          settings: authSettings,
          env: Object.fromEntries(CLAUDE_ACCOUNT_ENV_KEYS.map((key) => [key, env[key]])),
        })).digest("hex"),
      });

      // A process started ahead is taken once it has started up and has listed again the tools the harness serves only during a turn.
      const ahead = sessions.get(threadId);
      if (!spare && ahead?.spare && !ahead.closing && (Date.now() - (ahead.spareAt ?? 0) > (ahead.spareMs ?? PRESTART_IDLE_MS) + 5_000 || (ahead.argsKey === argsKey && !(ahead.tools?.ready && await ahead.tools.relist(Object.keys(mcpServers)))))) closeSession(threadId, "never used");
      const live = sessions.get(threadId), transcript = imageFoldTarget(config, env, cwd), imagesOver = !!transcript && !turn.sessionReset && !!sessionId && live?.sessionId === sessionId && !live.turn && transcriptImagesOver({ ...transcript, sessionId }, turn.images?.length ?? 0);
      if (!turn.sessionReset && !imagesOver && live && !live.turn && !live.closing && live.child.exitCode === null && live.argsKey === argsKey && (sessionId ? sessionId === live.sessionId : !live.resumed)) {
        stopIdleClose(`${instanceId}\0${threadId}`, live.idleTimer); // busy again: no longer idle
        if (live.spare) { live.spare = false; live.resumed = undefined; live.take?.(turnId); appendNative(threadId, { dir: "out", source: "claude.session", msg: { took: "prestarted" } }); }
        live.turn = { turnId, input: turn, retryAbort, settled: false, sawStreamDelta: false, awaitingInit: true, pendingSteers: new Set(), deferred: null, continuationGrace: null, continuationSilence: null };
        active.set(threadId, { stop: () => {
          if (live.turn) live.turn.stopRequested = true;
          closeSession(threadId, "interrupted");
          retry.cancelled = true;
          retryAbort.abort();
          stopSession(live);
        }, turnId, broker: live.broker });
        emit({ ...base(threadId, turnId), type: "turn.started" });
        const volatile = turn.systemVolatile ?? "", roster = turn.systemRoster ?? "", same = !turn.mentionTurn && (volatile === live.volatile || (live.volatile === null && !volatile.trim()));
        const message = same && roster === live.roster.now
          ? promptMsg // a changed roster (a bot added, renamed or removed) rides this message, with no relaunch
          : claudeUserMessage(withRosterNote(same ? turn.text : withVolatileNote(turn.text, volatile, live.volatile === null), roster, live.roster.now), turn.images);
        live.volatile = volatile; live.roster.now = roster;
        const running = live.turn;
        // A warm process can exit just as the next turn is written; its close resumes this turn.
        if (!(await writeUser(live, threadId, message)) && !running?.stopRequested) closeSession(threadId, "stdin write failed");
        if (mcpConfigPath) {
          try {
            rmSync(dirname(mcpConfigPath), { recursive: true, force: true });
          } catch {}
        }
        return { turnId };
      }
      // The old process and its tree end before the new one starts, so two never share the session.
      if (live) { closeSession(threadId, turn.sessionReset ? "context reset" : imagesOver ? "images over the request limit" : "spawn contract changed", turn.sessionReset || imagesOver ? undefined : spawnContractDiff(live.argsKey, argsKey)); await (live.spare ? stopEngineTree(live.child, 0, 0) : stopEngineTree(live.child)); } // an unused spare has nothing to save: no wait for it to leave by itself

      // Until sessions.set() below, this turn owns every launch resource and must release it on failure.
      const cleanupUnownedLaunch = () => {
        broker?.close();
        broker = undefined;
        if (mcpConfigPath) {
          try {
            rmSync(dirname(mcpConfigPath), { recursive: true, force: true });
          } catch {}
          mcpConfigPath = null;
        }
        if (systemPromptPath) {
          removePrivateTempDir(systemPromptPath);
          systemPromptPath = null;
        }
        if (!spare) retryState.delete(threadId);
      };

      try {
        if (launchSystem) {
          systemPromptPath = join(mkdtempSync(join(tmpdir(), "omb-system-")), "prompt.txt");
          writeFileSync(systemPromptPath, launchSystem, { mode: 0o600 });
          args.push("--append-system-prompt-file", systemPromptPath);
        }
        if (socketPath) {
          const askTools = new Map<string, string | undefined>();
          broker = await createPermissionBroker({
            socketPaths: brokerSocketCandidates(threadId, botId),
            isActive: () => Boolean(sessions.get(threadId)?.turn),
            onAsk: (ask) => {
              const eventTurnId = sessions.get(threadId)?.turn?.turnId ?? turnId;
              askTools.set(ask.id, typeof ask.tool === "string" ? ask.tool : undefined);
              const nativeMode = sessions.get(threadId)?.nativePermissionMode ?? null;
              const nativeReview =
                permissionMode === "auto" && nativeMode !== null
                  ? nativeMode === "auto" ? "active" : "inactive"
                  : undefined;
              const questions = askQuestions(ask);
              emit({
                ...base(threadId, eventTurnId),
                type: "request.opened",
                requestId: ask.id,
                requestType: ask.kind,
                tool: ask.tool,
                summary: askSummary(ask),
                // The Bash command, for exact-command grants and for the safety floor.
                ...shellRequest(ask.kind === "permission" && ask.tool === "Bash" ? ask.input.command : undefined, commandCwd), ...(ask.kind === "permission" && readToolPaths(ask.tool, ask.input) ? { reads: readToolPaths(ask.tool, ask.input) } : {}),
                requiresExplicitApproval: ask.kind === "permission" && ask.tool === "Bash" && ask.input.dangerouslyDisableSandbox === true || undefined,
                nativeReview,
                allowSession: ask.kind === "permission" && !(controlsHost && typeof ask.tool === "string" && ask.tool.startsWith("mcp__computer")) ? true : undefined,
                approvalScope:
                  typeof ask.tool === "string" && controlsHost && ask.tool.startsWith("mcp__computer")
                    ? "local-computer"
                    : undefined,
                questions: questions ?? undefined,
                choices: questions ? questionChoices(questions) : parseChoices(ask.input?.choices),
              });
            },
            onResolve: (resolved) => {
              const eventTurnId = sessions.get(threadId)?.turn?.turnId ?? turnId;
              emit({
                ...base(threadId, eventTurnId),
                type: "request.resolved",
                requestId: resolved.id,
                behavior: resolved.behavior,
                source: resolved.source,
                approvalScope:
                  controlsHost && typeof askTools.get(resolved.id) === "string" && askTools.get(resolved.id)!.startsWith("mcp__computer") ? "local-computer" : undefined,
              });
              askTools.delete(resolved.id);
            },
          });
          if (broker.socketPath !== socketPath && mcpConfigPath) {
            mcpServers.ogb = { command: process.execPath, args: [PERM_PROXY_PATH, broker.socketPath], env: permissionEnv, alwaysLoad: true };
          }
        }

        // Write once, only after the broker has selected its real endpoint.
        if (mcpConfigPath) {
          writeFileSync(mcpConfigPath, JSON.stringify({ mcpServers }), { mode: 0o600 });
        }
        if (authSettingsPath) {
          writeFileSync(authSettingsPath, JSON.stringify(settings), { mode: 0o600 });
        }
        if (sessionId) { if (transcript) foldTranscriptImages({ ...transcript, sessionId, incoming: turn.images?.length ?? 0 }); args.push("--resume", sessionId); } // on a custom endpoint a resumed thread resends every past image: older ones become a note, leaving room for this turn's own
        else args.push("--session-id", newSessionId!);
      } catch (error) {
        cleanupUnownedLaunch();
        throw error;
      }

      if (relaunch && retry.cancelled) {
        cleanupUnownedLaunch();
        if (active.get(threadId)?.turnId === turnId) active.delete(threadId);
        emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "interrupted", cost: null });
        return { turnId };
      }

      if (spare && (taken() || ownHttp)) { cleanupUnownedLaunch(); return { turnId: "" }; }
      let child: ReturnType<typeof spawnCli>;
      try {
        child = spawnCli(cliToLaunch(config.cli, launchCli), args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { engine: DRIVER_KIND, ...(broker ? { rw: [broker.socketPath] } : {}), ...(hookTokenPath ? { ro: [dirname(hookTokenPath)] } : {}) } }, "bot");
      } catch (error) {
        cleanupUnownedLaunch();
        throw error;
      }
      if (shellOff(turn)) warmContracts.delete(threadId);
      else {
        warmContracts.set(threadId, {
          args: [...args], env: { ...env }, cwd, system: launchSystem ?? null,
          mcpServers: mcpConfigPath ? JSON.parse(JSON.stringify(mcpServers)) : null,
          settings: authSettingsPath ? JSON.parse(JSON.stringify(settings)) : null,
        });
      }
      let markClosed!: () => void;
      const session: Session = {
        closed: new Promise<void>((resolve) => { markClosed = resolve; }),
        child,
        broker,
        elicit: claudeElicitations((frame) => writeControlFrame(session.child.stdin, frame), (event) => emit({ ...base(threadId, session.turn?.turnId ?? turnId), ...event })),
        context: claudeContextUsage((frame) => writeControlFrame(session.child.stdin, frame)),
        mcpConfigPath,
        systemPromptPath,
        argsKey, cliVersion: cliHelpVersion, passedAutocompact,
        volatile: spare ? null : turn.systemVolatile ?? "", roster: { launched: turn.systemRoster ?? "", now: turn.systemRoster ?? "" },
        sessionId: sessionId ?? newSessionId,
        sawInit: false,
        nativePermissionMode: null,
        replaysUserMessages,
        turn: spare ? null : { turnId, input: turn, retryAbort, settled: false, sawStreamDelta: false, pendingSteers: new Set(), deferred: null, continuationGrace: null, continuationSilence: null },
        idleTimer: null,
        closing: false, spare, take: (taker) => { turnId = taker; }, ...(spare ? { tools: spareTools.forProcess((frame) => writeControlFrame(child.stdin, frame)), spareMs, spareAt: Date.now(), ...(sessionId ? { resumed: sessionId } : {}) } : {}),
        stderr: "",
        costTotal: undefined,
      };
      sessions.set(threadId, session);

      const settle = (
        ok: boolean,
        stopReason: string | null,
        total: number | null = null,
        usage?: { input: number; output: number; cachedInput?: number },
        unsent?: true,
      ) => {
        const t = session.turn;
        if (!t || t.settled) return;
        t.settled = true;
        if (t.continuationGrace) {
          clearTimeout(t.continuationGrace);
          t.continuationGrace = null;
        }
        if (t.continuationSilence) {
          clearTimeout(t.continuationSilence);
          t.continuationSilence = null;
        }
        session.broker?.pause();
        clearMcpConfig(session);
        if (session.systemPromptPath) {
          if (removePrivateTempDir(session.systemPromptPath)) session.systemPromptPath = null;
        }
        active.delete(threadId);
        session.turn = null;
        retryState.delete(threadId);
        // `claude update` cannot change code this child already loaded, and a signed-out child can keep holding the shared OAuth refresh lock: retire both before completing.
        if (stopReason === "update_required" || stopReason === "auth_required") closeSession(threadId, stopReason === "auth_required" ? "authentication required" : "update required");
        else if (session.teamToolsFailed || session.customMcpFailed) closeSession(threadId, session.teamToolsFailed ? "team tools did not connect" : "an MCP server did not connect");
        const cost = turnCostFromRunningTotal(total, session.costTotal ?? null);
        if (total !== null) session.costTotal = total;
        emit({ ...base(threadId, t.turnId), type: "turn.completed", ok, stopReason, cost, ...(usage ? { usage } : {}), ...(unsent ? { unsent } : {}) });
        if (session.child.exitCode === null && !session.closing) armIdle(threadId);
      };
      const settleResult = (result: NativeTurnResult) => settle(result.ok, result.stopReason, result.cost, result.usage, result.unsent);
      const currentTurnId = () => session.turn?.turnId ?? turnId;
      const unconfirmedStopWarning = () => { if (session.unconfirmedStopWarned) return; session.unconfirmedStopWarned = true; emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: "Claude could not be confirmed stopped; its helper processes may still be running." }); };
      session.releaseInterrupted = () => { if (session.turn?.stopRequested) { unconfirmedStopWarning(); settle(false, "interrupted"); } };
      const reachLimit = (frame: { api_error_params?: { rate_limit_info?: unknown } }, words: unknown) => {
        const t = session.turn;
        if (!t || t.limitReached) return;
        t.limitReached = t.explained = true;
        t.limit = claudeLimitRefusal(frame.api_error_params?.rate_limit_info) ?? t.limit;
        const said = typeof words === "string" && USAGE_LIMIT.test(words) ? words : undefined;
        emit({ ...base(threadId, currentTurnId()), type: "runtime.error", ...claudeLimitError(t.limit ?? null, said), ...claudeLimitFacts(t.limit) });
      };
      const noteCostState = (total: unknown, modelUsage: unknown, usage: Parameters<typeof restoredCostBase>[2]) => {
        const state = claudeCostSnapshot(total, modelUsage);
        if (!state) return;
        if (session.costTotal === undefined) {
          session.costTotal = session.sessionId
            ? restoredCostBase(readCostHistory()[session.sessionId] ?? [], state, usage)
            : null;
        }
        if (session.sessionId) recordCostState(session.sessionId, state);
      };
      const ownScreenToolIds = new Set<string>(), ownScreen = ownScreenMounts(Object.keys(mcpServers).filter((name) => !botOwned.has(name))); // OpenMausBot's own computer/browser calls: their screenshots stay out of the chat
      const handleLine = (line: string) => {
        if (session.closing) return;
        let o: any;
        try {
          o = JSON.parse(line);
        } catch {
          return;
        }
        if (session.context.frame(o) || session.tools?.frame(o) || session.spare) return;
        authRecovery.frame(threadId, o, session.costTotal);
        if (session.turn) readRefusalFrame(session.turn.refusalRead ??= {}, o, session.costTotal);
        // A replayed stdin message carries its images again: keep their bytes out of the log.
        appendNative(threadId, { dir: "in", source: "claude.sdk.message", msg: o?.type === "user" && o.isReplay === true && o.message ? diagnosticClaudeUserMessage(o) : o });
        if (session.elicit.frame(o)) return;
        if (session.turn?.continuationSilence && !(o.type === "system" && o.subtype === "init") && !(o.type === "user" && o.isReplay === true)) {
          clearTimeout(session.turn.continuationSilence);
          session.turn.continuationSilence = null;
        }
        switch (o.type) {
          case "system":
            if (o.subtype === "init") {
              // A guest's CLI that kept a command-running tool is stopped before it does anything.
              const tools: unknown[] = Array.isArray(o.tools) ? o.tools : [];
              if (session.turn && shellOff(session.turn.input) && (o.permissionMode !== (session.turn.input.linkLimited && session.turn.input.approvalMode === "edits" ? "acceptEdits" : "default") || tools.some((tool) => typeof tool === "string" && GUEST_FORBIDDEN_TOOLS.has(tool)))) {
                emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: withWhy("This Claude Code kept its shell, so it can't run this turn. Update Claude Code.", session.turn?.input.confinedWhy) });
                session.closing = true;
                stopSession(session);
                break;
              }
              session.sawInit = true;
              if (!session.teamToolsFailed && Array.isArray(o.mcp_servers) && o.mcp_servers.some(teamToolsFailed)) {
                session.teamToolsFailed = true;
                emit({ ...base(threadId, currentTurnId()), type: "runtime.notice", message: TEAM_TOOLS_FAILED });
              }
              if (session.turn) session.turn.awaitingInit = false;
              session.nativePermissionMode = typeof o.permissionMode === "string" ? o.permissionMode : null;
              if (typeof o.session_id === "string") session.sessionId = o.session_id;
              if (session.sessionId && (sessionId === null || knowsRecordedPrompt)) recordedPrompts.set(threadId, { session: session.sessionId, prompt: recordedPrompt });
              const held = session.turn;
              if (held?.continuationGrace) {
                clearTimeout(held.continuationGrace);
                held.continuationGrace = null;
                if (held.continuationSilence) clearTimeout(held.continuationSilence);
                held.continuationSilence = setTimeout(() => {
                  if (session.turn !== held || held.settled || !held.deferred) return;
                  if (held.stopRequested || session.closing) return;
                  held.continuationSilence = null;
                  emit({ ...base(threadId, held.turnId), type: "runtime.error", message: "Claude began a steered message but went silent; the turn was closed." });
                  settleResult(held.deferred);
                }, STEERED_CONTINUATION_SILENCE_MS * steerSilenceScale());
                held.continuationSilence.unref?.();
              }
              const currentRetry = retryState.get(threadId) ?? retry;
              const failedMcp = failedCustomMcp(o.mcp_servers, session.turn?.input.integrations?.custom); if (failedMcp.mcpFailed?.length) session.customMcpFailed = true;
              emit({ ...base(threadId, currentTurnId()), type: "session.started", sessionId: o.session_id, model: o.model, ...(currentRetry.rebuilt ? { rebuilt: true } : {}), ...failedMcp });
              if (currentRetry.rebuilt) emit({ ...base(threadId, currentTurnId()), type: "runtime.notice", message: rebuiltSessionNotice("Claude Code") });
              currentRetry.rebuilt = false;
            } else if (o.subtype === "compact_boundary") {
              session.volatile = null; session.roster.now = session.roster.launched; if (!o.parent_tool_use_id) emit({ ...base(threadId, currentTurnId()), type: "context.compacted" }); // only the system prompt survives a compaction, so the next turn re-sends the volatile half; a subagent's own compaction is not the chat's
            } else if (o.subtype === "thinking_tokens") {
              emit({ ...base(threadId, currentTurnId()), type: "item.updated", itemType: "reasoning", tokens: o.estimated_tokens });
            }
            break;
          case "stream_event": {
            // Subagent narration is dropped: parallel Tasks would interleave prose into one bubble.
            if (o.parent_tool_use_id) break;
            const ev = o.event ?? {}, d = ev.delta ?? {}, draft = claudeToolDraft(session, ev);
            if (draft) emit({ ...base(threadId, currentTurnId()), ...draft });
            if (ev.type !== "content_block_delta") { const call = claudeCallUsage(session, ev); if (call) emit({ ...base(threadId, currentTurnId()), ...call }); break; }
            if (d.type === "text_delta" && typeof d.text === "string" && d.text) {
              if (session.turn) session.turn.sawStreamDelta = true;
              emit({ ...base(threadId, currentTurnId()), type: "content.delta", streamKind: "assistant_text", delta: d.text });
            } else if (d.type === "thinking_delta" && typeof d.thinking === "string" && d.thinking) {
              emit({ ...base(threadId, currentTurnId()), type: "content.delta", streamKind: "reasoning_text", delta: d.thinking });
            }
            break;
          }
          case "assistant": {
            const msg = o.message ?? {};
            const text = firstText(msg.content);
            const swap = modelSwapNotice(session, threadId, session.turn?.input.model, o, models);
            if (swap) emit({ ...base(threadId, currentTurnId()), type: "runtime.notice", message: swap });
            // Signed out, the CLI answers with an api-error frame whose only content is "run /login".
            if (claudeAuthFailure(o, text)) {
              if (session.turn) session.turn.authFailed = session.turn.explained = true;
              emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: text, setup: true });
              break;
            }
            if (claudeUsageLimit(o, text, Boolean(session.turn?.limit))) {
              reachLimit(o, text);
              break;
            }
            if (claudeVersionTooOld(o, text)) {
              if (session.turn) session.turn.updateRequired = session.turn.explained = true;
              emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: text, setup: true, claudeUpdate: true });
              break;
            }
            if ((o.is_api_error_message === true || typeof o.error === "string") && text.trim()) {
              if (session.turn) session.turn.explained = true;
              if (!session.turn?.stopRequested) emit({ ...base(threadId, currentTurnId()), type: "runtime.error", ...withBedrockCredentialError(config.bedrock, input.environment, text, claudeApiError(o, text)) });
              break;
            }
            if (session.turn) session.turn.answered = true;
            if (text.trim()) {
              // fallback delta for CLIs/paths that never streamed the block
              if (!session.turn?.sawStreamDelta) emit({ ...base(threadId, currentTurnId()), type: "content.delta", streamKind: "assistant_text", delta: text });
              if (session.turn) session.turn.sawStreamDelta = false;
              emit({ ...base(threadId, currentTurnId()), type: "item.completed", itemType: "assistant_text", text });
            }
            for (const b of Array.isArray(msg.content) ? msg.content : []) {
              if (b.type === "tool_use") {
                emit({ ...base(threadId, currentTurnId()), type: "item.started", itemType: "tool", itemId: b.id, title: b.name, summary: commandSummary(b.input), input: toolDetailPreview(b.input) }); if (isOwnScreenToolName(b.name, ownScreen)) ownScreenToolIds.add(b.id);
              }
            }
            if (msg.usage) {
              emit({
                ...base(threadId, currentTurnId()), ...(typeof msg.id === "string" ? { itemId: msg.id } : {}),
                type: "thread.token-usage.updated",
                input: (msg.usage.input_tokens || 0) + (msg.usage.cache_read_input_tokens || 0),
                output: msg.usage.output_tokens || 0,
                ...(typeof msg.usage.cache_read_input_tokens === "number"
                  ? { cachedInput: msg.usage.cache_read_input_tokens }
                  : {}),
                // One assistant message is one model call; its prompt is fresh + cache-read + cache-write.
                contextTokens: (msg.usage.input_tokens || 0) + (msg.usage.cache_read_input_tokens || 0) + (msg.usage.cache_creation_input_tokens || 0),
              });
            }
            break;
          }
          case "user": {
            // --replay-user-messages: a model call took this stdin message in.
            if (o.isReplay === true) {
              if (typeof o.uuid === "string") session.turn?.pendingSteers.delete(o.uuid);
              break;
            }
            for (const b of Array.isArray(o.message?.content) ? o.message.content : []) {
              if (b.type === "tool_result") {
                emit({ ...base(threadId, currentTurnId()), type: "item.completed", itemType: "tool", itemId: b.tool_use_id, ok: !b.is_error, output: toolDetailPreview(b.content) });
                for (const img of ownScreenToolIds.delete(b.tool_use_id) ? [] : extractMcpImages(b.content)) {
                  emit({ ...base(threadId, currentTurnId()), type: "item.completed", itemType: "assistant_image", data: img.data, fromTool: true });
                }
              }
            }
            break;
          }
          case "rate_limit_event":
            if (session.turn) session.turn.limit = claudeLimitRefusal(o.rate_limit_info);
            break;
          case "tool_progress":
            // Claude Code 2.1.306 sends one every 30 s while a tool runs: proof the turn is alive.
            emit({ ...base(threadId, currentTurnId()), type: "item.updated", itemType: "tool" });
            break;
          case "result": {
            // A synthetic task-notification completion is not the submitted user turn's result.
            if (o.origin?.kind === "task-notification") break;
            // After a long idle 2.1.295 answers a --resume it no longer has with an error result ("No
            // conversation found with session ID …") and stays up; end it so its close rebuilds once.
            if (o.is_error === true && sessionId && !session.sawInit && session.turn && !session.turn.settled) {
              session.resumeRefusal = claudeResultError(o);
              closeSession(threadId, "resume refused");
              break;
            }
            if (o.is_error === true && !session.turn?.authFailed && (session.turn?.limit ||
                o.api_error === "usage_limit_reached" || USAGE_LIMIT.test(String(o.result ?? "")))) reachLimit(o, o.result);
            if (o.is_error === true && session.turn && !session.turn.settled && !session.turn.explained && !session.turn.stopRequested) {
              session.turn.explained = true; session.turn.authFailed = claudeOAuthExpired(String(o.result ?? ""));
              emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: bedrockResultError(config.bedrock, input.environment, claudeResultError(o)), ...(session.turn.authFailed ? { setup: true } : {}) });
            }
            if (!config.managed) void orgBlocks.refresh();
            // result.usage is per turn "in streaming-input sessions" (2.1.282) even on a retained
            // process; total_cost_usd is the process's running total.
            noteCostState(o.total_cost_usd, o.modelUsage, {
              input: o.usage?.input_tokens || 0,
              cacheRead: o.usage?.cache_read_input_tokens || 0,
              cacheWrite: o.usage?.cache_creation_input_tokens || 0,
              output: o.usage?.output_tokens || 0,
            });
            const native: NativeTurnResult = {
              ok: o.is_error !== true,
                // An error result's stop_reason ("stop_sequence" or none) says nothing; its
                // terminal_reason ("api_error") or subtype ("error_during_execution") does.
              stopReason: session.turn?.authFailed
                ? "auth_required"
                : session.turn?.limitReached
                  ? "quota"
                  : session.turn?.updateRequired
                    ? "update_required"
                    : o.is_error === true
                      ? o.terminal_reason ?? (typeof o.subtype === "string" && o.subtype !== "success" ? o.subtype : null) ?? o.stop_reason ?? null
                      : o.stop_reason ?? o.terminal_reason ?? null,
              cost: o.total_cost_usd ?? null,
              ...(session.turn?.authFailed && session.turn.refusalRead && refusedSignedOut(session.turn.refusalRead) ? { unsent: true as const } : {}),
              ...(o.usage
                ? {
                    usage: {
                      input: (o.usage.input_tokens || 0) + (o.usage.cache_read_input_tokens || 0) + (o.usage.cache_creation_input_tokens || 0),
                      output: o.usage.output_tokens || 0,
                      ...(typeof o.usage.cache_read_input_tokens === "number"
                        ? { cachedInput: o.usage.cache_read_input_tokens }
                        : {}),
                    },
                  }
                : {}),
            };
            const t = session.turn;
            // queued_turn_count ("greater than 0 means at least one more user turn (and result)
            // follows", 2.1.282) misses a stdin steer not yet queued: it said 0 and the CLI ran the
            // message 58 ms later. So 0 decides nothing.
            const queuedTurns = typeof o.queued_turn_count === "number" ? o.queued_turn_count : 0;
            if (t && !t.settled && (queuedTurns > 0 || t.pendingSteers.size > 0)) {
                // Hold the result: a turn.completed now would revoke the turn's capabilities under
                // the continuation (its internal tools would answer 401).
              if (!session.replaysUserMessages) t.pendingSteers.clear();
              t.deferred = sumNativeTurnResults(t.deferred, native);
              t.armGrace = () => {
                if (t.continuationGrace) clearTimeout(t.continuationGrace);
                t.continuationGrace = setTimeout(() => {
                  if (session.turn !== t || t.settled) return;
                  if (t.stopRequested || session.closing) return;
                  t.continuationGrace = null;
                  if (t.deferred) settleResult(t.deferred);
                }, STEERED_CONTINUATION_GRACE_MS * steerGraceScale());
                t.continuationGrace.unref?.();
              };
              t.armGrace();
              appendNative(threadId, { dir: "out", source: "claude.session", msg: { hold: `result: a steered message is still queued (queued_turn_count ${o.queued_turn_count ?? "absent"})` } });
              break;
            }
            settleResult(sumNativeTurnResults(t?.deferred ?? null, native));
            break;
          }
        }
      };

      let buf = "";
      child.stdout.setEncoding("utf8");
      child.stdout.on("data", (chunk) => {
        buf += chunk;
        let nl;
        while ((nl = buf.indexOf("\n")) !== -1) {
          const line = buf.slice(0, nl);
          buf = buf.slice(nl + 1);
          if (line.trim()) handleLine(line);
        }
      });

      child.stderr.on("data", (c) => {
        session.stderr += c;
        if (session.stderr.length > 8192) session.stderr = session.stderr.slice(-8192);
      });

      child.on("error", (e) => {
        if (session.spare) { session.broker?.close(); discardSession(threadId, session); return; }
        emit({ ...base(threadId, currentTurnId()), type: "runtime.error", ...describeSpawnFailure(e, config.cli, cwd) });
        settle(false, "spawn_error");
      });

      let closeFinalized = false;
      const finalizeClose = async (code: number | null, signal: NodeJS.Signals | null) => {
        if (closeFinalized) return;
        // The root can close while its MCP helpers run: reap them before releasing the turn.
        if (!(await killCliTree(child, 0))) {
          session.broker?.close();
          session.broker = undefined;
          if (!session.spare) { if (!session.turn?.stopRequested) unconfirmedStopWarning(); session.releaseInterrupted?.(); }
          return;
        }
        if (closeFinalized) return;
        closeFinalized = true;
        if (session.turn?.stopRequested && !session.turn.settled) {
          settle(false, "interrupted");
        } else if (session.turn?.deferred && !session.turn.settled) {
          // A result is held, so the prompt already ran: never relaunch.
          const held = session.turn.deferred;
          if (session.turn.continuationGrace) {
            settleResult(held);
          } else {
            emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: `claude exited ${code ?? signal} before result${session.stderr ? `: ${session.stderr.trim().slice(-300)}` : ""}` });
            settleResult({ ...held, ok: false, stopReason: "exit_before_result" });
          }
        } else if (session.turn && !session.turn.settled) {
          const { turnId, input: turn, retryAbort } = session.turn;
          // Commander prints this at launch, before init; only a launch that passed the flag counts, so the flag-less relaunch can't loop.
          const refusedAutocompact = session.passedAutocompact && !session.sawInit && /unknown option '--autocompact'/.test(session.stderr);
          if (refusedAutocompact) { if (session.cliVersion !== null) autocompactRefusedBy.add(session.cliVersion); if (session.cliVersion === cliHelpVersion) cliHasAutocompact = false; }
          const retry = retryState.get(threadId) ?? { attempt: 0, cancelled: false };
          const message = `claude exited ${code ?? signal} before result${session.stderr ? `: ${session.stderr.trim().slice(-300)}` : ""}`;
          const verdict = classifyError({ exitCode: code, stderr: message });
          const endedBeforeTurn = session.turn.awaitingInit === true || (refusedAutocompact && !session.turn.sawStreamDelta && session.turn.answered !== true);
          if (!retry.cancelled && !stoppedForRoom(threadId, session.child.pid) && mayResendTurn({ endedBeforeTurn, exitCode: code, transient: verdict.transient,
            streamed: session.turn.sawStreamDelta, answered: session.turn.answered === true, attempt: retry.attempt })) {
            // `active` stays: an interrupt during the backoff reaches stop() and cancels the retry.
            const failedBroker = session.broker;
            session.broker = undefined;
            failedBroker?.pause();
            failedBroker?.close();
            discardSession(threadId, session);
            let delayMs = 0;
            if (!endedBeforeTurn) {
              retry.attempt++;
              delayMs = computeBackoff(retry.attempt - 1);
              emit({ ...base(threadId, turnId), type: "turn.retrying", attempt: retry.attempt, delayMs, reason: verdict.reason });
            }
            void (async () => {
              const wait = interruptibleDelay(delayMs * retryScale, retryAbort.signal);
              await wait.promise;
              if (retry.cancelled) {
                active.delete(threadId);
                retryState.delete(threadId);
                emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "interrupted", cost: null });
                return;
              }
              retryState.set(threadId, retry);
              active.set(threadId, { stop: () => { retry.cancelled = true; retryAbort.abort(); }, turnId });
              try {
                const cursor = session.sessionId ?? sessionId ?? undefined;
                await sendTurn({ ...turn, sessionReset: false, resumeCursor: cursor }, turnId);
              } catch (e) {
                if (active.get(threadId)?.turnId === turnId) active.delete(threadId);
                retryState.delete(threadId);
                emit({ ...base(threadId, turnId), type: "runtime.error", message: e instanceof Error ? e.message : String(e) });
                emit({
                  ...base(threadId, turnId),
                  type: "turn.completed",
                  ok: false,
                  stopReason: "exit_before_result",
                  cost: null,
                });
              }
            })();
            return;
          }
          // A --resume the CLI exited from before `init` never read the prompt; without one fresh
          // session the dead cursor would fail every later turn identically.
          const resumeFailure = classifyResumeFailure({
            attempted: Boolean(sessionId),
            rejected: !session.sawInit,
            promptSubmitted: session.sawInit,
            producedOutput: session.turn.sawStreamDelta,
          });
          if (mayReplay(resumeFailure) && !retry.cancelled) {
            // Without this line a refused --resume looks like an ordinary new session in the logs.
            console.error(`claude (${instanceId}): could not resume session ${sessionId} for thread ${threadId}, starting a new one: ${redactSecretsInText(session.resumeRefusal ?? message)}`);
            const recovery = recoveryPromptFor({
              recoveryText: turn.recoveryText,
              currentText: turn.text,
              failure: resumeFailure,
            });
            session.broker?.close();
            session.broker = undefined;
            discardSession(threadId, session);
            retry.rebuilt = recovery.replayed;
            retryState.set(threadId, retry);
            active.set(threadId, { stop: () => { retry.cancelled = true; retryAbort.abort(); }, turnId });
            void (async () => {
              try {
                await sendTurn({ ...turn, resumeCursor: undefined, recoveryText: undefined, text: recovery.text }, turnId);
              } catch (e) {
                if (active.get(threadId)?.turnId === turnId) active.delete(threadId);
                retryState.delete(threadId);
                emit({
                  ...base(threadId, turnId),
                  type: "runtime.error",
                  message: e instanceof Error ? e.message : String(e),
                });
                emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "exit_before_result", cost: null });
              }
            })();
            return;
          }
          retryState.delete(threadId);
          emit({
            ...base(threadId, currentTurnId()),
            type: "runtime.error",
            message,
          });
          settle(false, "exit_before_result");
        }
        stopIdleClose(`${instanceId}\0${threadId}`, session.idleTimer);
        session.broker?.close();
        session.elicit.close();
        session.context.close();
        clearMcpConfig(session);
        removePrivateTempDir(session.systemPromptPath);
        if (sessions.get(threadId) === session) sessions.delete(threadId);
      };
      child.on("close", (code, signal) => {
        session.finishClose = () => finalizeClose(code, signal);
        void session.finishClose().finally(markClosed);
      });

      if (spare) { armIdle(threadId); return { turnId: "" }; }
      const stop = () => {
        if (session.turn) session.turn.stopRequested = true;
        // taskkill is asynchronous on Windows: retire steering and approvals before the child submits more.
        closeSession(threadId, "interrupted");
        retry.cancelled = true;
        retryAbort.abort();
        stopSession(session);
      };
      active.set(threadId, { stop, turnId, broker });
      emit({ ...base(threadId, turnId), type: "turn.started" });

      // Prompt over stdin, never argv (ARG_MAX); stdin stays open for steers and the next turn.
      if (!(await writeUser(session, threadId, halves.stable !== null && halves.volatile.trim() ? claudeUserMessage(withVolatileNote(turn.text, halves.volatile, true), turn.images) : promptMsg))) {
        if (!session.turn?.stopRequested) settle(false, "stdin_write_failed");
        closeSession(threadId, "stdin write failed");
      }

      return { turnId };
    };

    const steer = async (threadId: string, text: string, images?: readonly ClaudeImage[]): Promise<SteerOutcome> => {
      const s = sessions.get(threadId);
      if (!s || !s.turn || s.turn.settled || s.closing || s.child.exitCode !== null) return "refused";
      const turn = s.turn;
      let message: ClaudeUserMessage;
      try {
        message = claudeUserMessage(text, images);
      } catch {
        return "refused";
      }
      // Counted before the write: a `result` read while the words are in flight must hold for them.
      const id = randomUUID();
      turn.pendingSteers.add(id);
      if (!(await writeUser(s, threadId, { ...message, uuid: id }))) {
        turn.pendingSteers.delete(id);
        return "refused";
      }
      if (!turn.settled && turn.continuationGrace) turn.armGrace?.();
      return "steered";
    };

    const login = new ClaudeLoginController({ cli: config.cli, environment, onAuthenticated: async () => { await refreshModels(); } });
    let lastAuth: Awaited<ReturnType<typeof claudeAuthStatus>> = {};

    const snapshot = async (): Promise<ProviderSnapshot> => {
      const env = environment();
      const probe = await readCliVersion(env);
      if (!("version" in probe)) return { state: "unavailable", ...probe }; // `busy` when the check could not finish
      const { version } = probe;
      [cliVersion, cliVersionChecked, cliProbedAt] = [parseClaudeCliVersion(version), true, findCliCandidates(config.cli, env.PATH ?? "")[0]];
      if (!config.managed && !config.endpointModels) models = withCliVersionGate(models, "claude", cliVersion);
      if (version !== cliHelpVersion || helpRead) await readCliHelp(version, env);
      const update = claudeCliUpdate(version, config.cli);
      const warning = claudeInheritWarning(env);
      if (config.requireApiKey && !input.environment.ANTHROPIC_API_KEY) return { state: "unavailable", version, reason: NO_ANTHROPIC_KEY };
      const probed: typeof lastAuth = config.requireApiKey ? { authenticated: true } : await claudeAuthStatus(config.cli, env);
      const auth = probed.authenticated === undefined ? lastAuth : (lastAuth = probed);
      return { state: "available", version, ...auth, ...claudeBilling(env, auth.account), ...(update ? { update } : {}), ...(warning ? { warning } : {}) };
    };

    /** One-shot call, prompt on stdin (approval summaries can hold secrets), no tools or MCP servers. */
    const generateReview = async (prompt: string, signal?: AbortSignal, onUsage?: TextGenerationOptions["onUsage"], timeoutMs?: number, named?: string, maxOutputTokens?: number): Promise<string> => {
      await ensureCliVersion(environment());
      return new Promise((resolve, reject) => {
        if (config.requireApiKey && !input.environment.ANTHROPIC_API_KEY) {
          reject(new Error(NO_ANTHROPIC_KEY));
          return;
        }
        const model = named ?? config.managedModels?.[0] ?? config.endpointModels?.[0] ?? "claude-haiku-5-5";
        const env = { ...environment(config.endpointModels ? undefined : model), ...(maxOutputTokens === undefined ? {} : { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(maxOutputTokens) }) };
        const args = backgroundCallArgs({ model, outputFormat: onUsage ? "json" : "text", supports: (flag) => cliVersion !== null && claudeCliSupports(cliVersion, flag), isolated: !inheritsUserConfig(env) });
        const { child, removeCwd } = spawnBackgroundCall(config.cli, args, env);
        let stdout = "";
        let stderr = "";
        let settled = false;
        const finish = (error?: Error) => {
          if (settled) return;
          settled = true;
          clearTimeout(timer);
          signal?.removeEventListener("abort", onAbort);
          removeCwd();
          if (error) reject(error);
          else resolve(stdout.trim());
        };
        const onAbort = () => {
          killCliTree(child);
          finish(new Error("Claude review aborted"));
        };
        const timer = setTimeout(() => {
          killCliTree(child);
          finish(new Error("Claude review timed out"));
        }, timeoutMs ?? BACKGROUND_CALL_TIMEOUT_MS);
        timer.unref?.();
        child.stdout.setEncoding("utf8");
        child.stderr.setEncoding("utf8");
        child.stdout.on("data", (chunk: string) => {
          stdout += chunk;
          if (stdout.length > 1_000_000) {
            killCliTree(child);
            finish(new Error("Claude review output exceeded 1 MB"));
          }
        });
        child.stderr.on("data", (chunk: string) => {
          stderr = (stderr + chunk).slice(-8_192);
        });
        child.on("error", (error) => finish(error));
        child.on("close", (code) => {
          if (settled) return;
          if (onUsage) {
            try {
              const result = JSON.parse(stdout);
              if (!result || result.type !== "result") throw new Error("Claude text generation returned no result");
              const count = (value: unknown) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
              const cachedInput = count(result.usage?.cache_read_input_tokens);
              const inputs = [count(result.usage?.input_tokens), cachedInput, count(result.usage?.cache_creation_input_tokens)]
                .filter((value): value is number => value !== undefined);
              const models = result.modelUsage && typeof result.modelUsage === "object" && !Array.isArray(result.modelUsage)
                ? Object.keys(result.modelUsage) : [];
              onUsage({
                model: models.length === 1 ? models[0]! : models.find(candidate => candidate === model || candidate.startsWith(`${model}-`)) ?? model,
                input: inputs.length ? inputs.reduce((sum, value) => sum + value, 0) : undefined,
                output: count(result.usage?.output_tokens),
                cachedInput,
                costUsd: count(result.total_cost_usd),
              });
              if (result.is_error === true) throw new Error(typeof result.result === "string" && result.result.trim() ? result.result : stderr.trim() || "Claude text generation failed");
              if (typeof result.result !== "string") throw new Error("Claude text generation returned no text");
              stdout = result.result;
            } catch (error) {
              finish(error instanceof Error ? error : new Error(String(error)));
              return;
            }
          }
          if (code === 0) finish();
          else finish(new Error(stderr.trim() || stdout.trim().slice(0, 500) || `Claude review exited ${code}`));
        });
        if (signal?.aborted) onAbort();
        else {
          signal?.addEventListener("abort", onAbort, { once: true });
          child.stdin.end(prompt);
        }
      });
    };

    return {
      instanceId,
      driverKind: DRIVER_KIND,
      displayName: input.displayName,
      enabled: input.enabled,
      get models() {
        return models;
      },
      refreshModels,
      ...(startupModelRefresh ? { startupModelRefresh } : {}),
      snapshot,
      startAuthentication: () => login.start(),
      getAuthentication: (flowId) => login.get(flowId),
      completeAuthentication: (flowId, code) => login.complete(flowId, code),
      cancelAuthentication: () => login.cancel(),
      signOut: () => login.signOut(),
      adapter: {
        provider: DRIVER_KIND,
        capabilities: {
          sessionModelSwitch: "in-session",
          guestTurns: "confined",
          agentsMcp: true,
        customMcp: true,
          computerMcp: true,
          composioMcp: true, mcpToolsFoundByName: true,
          phoneMcp: true,
          browserMcp: true,
          dataMcp: true, emailMcp: true, deviceMcp: true,
          images: true,
          nativeImageInput: true,
          effortLevels: ["low", "medium", "high", "xhigh", "max"],
          queueing: true,
          // stream-json takes image blocks on any user message, mid-turn too
          steerImages: true,
          // Only while this CLI can refresh a resumed session's recorded prompt (--system-prompt-snapshot).
          get strictResume() {
            return cliVersionChecked && cliVersion !== null && claudeCliSupports(cliVersion, "--system-prompt-snapshot");
          },
          localComputerMcp: true, nativeCompaction: true,
          hooks: true, askTool: { kind: "mcp", server: "ogb", name: "ask_user" },
        },
        sendTurn: (turn) => authRecovery.send(turn, sendTurn),
        steer,
        interruptTurn: async (threadId) => active.get(threadId)?.stop(),
        respondToRequest: async (threadId, requestId, decision) => {
          const elicited = await sessions.get(threadId)?.elicit.answer(requestId, decision.behavior);
          if (elicited === "failed") return "unavailable";
          if (elicited === "sent") return decision.behavior === "allow" ? "allowed-once" : "rejected";
          const broker = sessions.get(threadId)?.broker ?? active.get(threadId)?.broker;
          if (!broker) return "unavailable";
          const behavior = decision.behavior === "answer" ? "answer" : decision.behavior;
          if (!broker.answer(requestId, behavior, decision.message, decision.always)) return "unavailable";
          return behavior === "allow" ? "allowed-once" : behavior === "answer" ? "answered" : "rejected";
        },
        hasSession: (threadId) => active.has(threadId),
        enginePid: (threadId) => (active.has(threadId) ? sessions.get(threadId)?.child.pid : undefined),
        cacheKeepWarm: forks.adapter,
        prestart: {
          start: (turn, waitMs) => {
            if (!spareTools.usable) return Promise.resolve(false);
            const launch = sendTurn(turn, undefined, true, waitMs).then(() => sessions.get(turn.threadId)?.spare === true, () => false).finally(() => { if (spares.get(turn.threadId) === launch) spares.delete(turn.threadId); });
            spares.set(turn.threadId, launch);
            return launch;
          },
          held: (threadId) => spares.has(threadId) || sessions.get(threadId)?.spare === true, running: (threadId) => spares.has(threadId) || (sessions.get(threadId)?.closing === false && sessions.get(threadId)?.child.exitCode === null), ready: (threadId) => sessions.get(threadId)?.spare === true && sessions.get(threadId)?.tools?.ready === true,
          drop: (threadId) => {
            const close = () => { const s = sessions.get(threadId); if (s?.spare) { closeSession(threadId, "never used"); stopSession(s); } };
            close();
            void spares.get(threadId)?.then(close);
          },
        },
        contextBreakdown: async (threadId, options) => liveContextBreakdown(sessions.get(threadId), options?.signal),
        stopAll: async () => {
          for (const { stop } of active.values()) stop();
          for (const threadId of Array.from(sessions.keys())) closeSession(threadId, "stopAll");
        },
        onEvent: (listener) => {
          listeners.add(listener);
          return () => listeners.delete(listener);
        },
      },
      generateText: (prompt, options) => generateReview(prompt, options?.signal, options?.onUsage, options?.timeoutMs, options?.model, options?.maxOutputTokens),
      reviewPermission: generateReview,
      dispose: async () => {
        try {
          await login.dispose();
        } finally {
          for (const { stop } of active.values()) stop();
          for (const threadId of Array.from(sessions.keys())) closeSession(threadId, "dispose");
          listeners.clear();
          // Engines lead sessions of their own, so nothing stops them once this server exits.
          await stopEngineTrees(Array.from(sessions.values(), (s) => s.child));
        }
      },
    };
  },
};