@agentchatme/agent-core 0.7.0 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/presets/claude-code.ts","../src/presets/semver.ts","../src/presets/runtime-check.ts","../src/presets/types.ts","../src/presets/codex.ts","../src/presets/index.ts"],"sourcesContent":["import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { clientHeadersOf } from '../client-identity.js'\nimport { hostedMcpUrl } from '../integration/mcp-probe.js'\nimport { workdirExposesHome, type RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, RunPreflightOptions, RunRequest, RunRunner } from '../integration/runner.js'\nimport { spawnRun } from '../integration/spawn-run.js'\nimport { atomicWriteFile } from '../util/fsutil.js'\nimport { log } from '../util/log.js'\nimport { runProbe } from '../util/probe.js'\nimport { VERSION } from '../version.js'\nimport { semverAtLeast } from './semver.js'\nimport { RUNTIME_CHECK_DIR, runRuntimeCheck } from './runtime-check.js'\nimport { withoutInheritedKey, withoutParentSession, type Preset, type PresetContext, type PresetInspection } from './types.js'\n\n// ─── Claude Code: one headless run (`claude -p`) ────────────────────────────\n//\n// `claude -p` on the box, riding the user's own Claude Code sign-in and user\n// configuration. The run's output is discarded by `spawnRun`: the agent's only\n// way to say anything on AgentChat is the hosted send tool during the run.\n//\n// The flags, verified against `claude --help` (2.1.316) and\n// code.claude.com/docs/en/cli-reference.md, headless.md, permission-modes.md:\n//\n// --permission-prompts none anything that would prompt is denied, never\n// waited on; the permission mode and allow rules\n// still decide every call first (v2.1.259+).\n// --tools <list> restricts the BUILT-IN tool set; does not affect\n// MCP tools. Listing Glob/Grep explicitly provides\n// the dedicated search tools.\n// --allowedTools <rules> pre-approves. `mcp__agentchat__*` is the whole\n// hosted server; `Bash` pre-approves every shell\n// command (dropped as a broad rule only in auto mode).\n// A bare `Read`, `Glob` or `Grep` pre-approves that\n// tool on EVERY path; `Read(//<dir>/**)` only under\n// `<dir>`. Glob and Grep have no path rules of their\n// own: `Read(<path>)` rules are matched for them\n// (permissions.md \"Glob(path) and Grep(path) rules\n// don't match\"). An allow rule applies only when the\n// requested path AND the file it resolves to match\n// (permissions.md \"Symlinks\"), so a link out of the\n// workdir is never allowed by it.\n// --disallowedTools <rules> denies. Deny rules win over allow rules, and a\n// `Read(<path>)` rule covers every built-in tool\n// that reads files (Read, Grep, Glob — docs:\n// permissions.md \"Read & Edit\"). Used to keep a\n// run's file tools off the key store. `//`\n// prefixes an absolute path in rule syntax. A bare\n// tool name removes the tool.\n// --settings <json> additional settings for this run only. `answer`\n// sets `permissions.blockReadsOutsideWorkingDirectories`\n// (v2.1.257+, settings-reference.md): the file tools\n// refuse every path outside the working directories\n// in every mode, and \"no allow rule lets Claude's\n// file tools through\" — so an allow rule in the\n// user's own settings cannot reopen the disk.\n// --permission-mode default Manual: reads inside the working directories need\n// no approval, everything else prompts (and is\n// therefore denied here).\n// --permission-mode acceptEdits file edits and common filesystem commands in\n// the working directory need no approval.\n// --dangerously-skip-permissions = bypassPermissions.\n// --mcp-config <file> --strict-mcp-config\n// the hosted server from a file, and ONLY it: a\n// listener's run acts as the listener's agent,\n// never as whatever key the user scope registers.\n// --mcp-config <file> (no --strict-mcp-config)\n// `own`: the file's `agentchat` wins over a\n// user-scope `agentchat` (verified on 2.1.327: the\n// user-scope one is not even connected), and every\n// other server the user configured still loads.\n//\n// Whatever the profile, every AgentChat hosted tool is pre-approved: the run\n// exists to read the tray and decide or send through them. In `own` that is\n// all `--allowedTools` says. It cannot be left to the user's settings: in\n// print mode an MCP tool no rule allows is denied (verified on 2.1.327:\n// \"requires approval, and this session has no approval surface\"), and\n// naming the server there is also what makes the first turn wait for it\n// (agent-sdk/mcp.md, \"Named servers\"). A user's deny rule still wins over it.\n//\n// `own` passes nothing else that decides what a run may do: no `--tools`,\n// `--permission-mode`, `--settings` or `--strict-mcp-config`. The user's\n// permission mode (`permissions.defaultMode`; Manual when none is set, the\n// documented built-in for `claude -p`), allow and deny rules, MCP servers,\n// CLAUDE.md, auto memory and hooks apply as in their own `claude -p` runs.\n//\n// The runtime check (`checkRuntime`, runtime-check.ts) is one `claude -p`\n// with a fixed prompt, the same binary and environment as the runs (no key in\n// it), in an empty folder of its own, and nothing to act with:\n//\n// --output-format json one result object (code.claude.com/docs/en/\n// headless.md, \"Output formats\": `type`,\n// `subtype`, `is_error`, `result`, …). The check\n// is ok only on exit 0 with `type: \"result\"`,\n// `subtype: \"success\"` and `is_error: false`\n// (`claudeRuntimeCheckJudge`). Seen on 2.1.328\n// against a stand-in provider: an API error (a\n// refusal, an invalid key, a low credit balance)\n// is `subtype: \"success\"` with `is_error: true`,\n// `api_error_status` set, and exit 1 — so\n// `subtype` alone is not enough.\n// --strict-mcp-config (no --mcp-config) no MCP server at all: not the\n// hosted AgentChat tools, not the user's.\n// --tools \"\" no built-in tool (\"\" for none, `claude --help`).\n// --permission-prompts none nothing waits on a prompt.\n// --settings RUNTIME_CHECK_SETTINGS the user's hooks do not fire on a health\n// check (managed hooks still run), and no\n// instruction file or memory, re-asserted the way\n// `ANSWER_SETTINGS` does (a settings file's `env`\n// would override the process environment).\n// CLAUDE_CODE_DISABLE_CLAUDE_MDS=1, CLAUDE_CODE_DISABLE_AUTO_MEMORY=1\n// the same two, in the environment.\n// --disallowedTools <the key-store deny rules> as on every run.\n//\n// Verified on 2.1.328 against a stand-in model provider: the request carries\n// no tool; an answer is exit 0 with the result above.\n\nexport const CLAUDE_CODE_PRESET = 'claude-code'\n\n/**\n * Two flags set the floor:\n * * `--permission-prompts none` — Claude Code v2.1.259.\n * * `CLAUDE_CODE_MCP_STARTUP_WAIT_MS` — bounds how long the first\n * non-interactive turn waits for the MCP servers `--allowedTools` names to\n * connect. Added in v2.1.274. Without it a run could start before the\n * hosted inbox tool is there.\n */\nexport const MIN_CLAUDE_CODE_VERSION = '2.1.274'\n\n/** The MCP server name the runs see; every hosted tool is `mcp__agentchat__<tool>`, as the served texts spell them. */\nexport const CLAUDE_MCP_SERVER_NAME = 'agentchat'\nexport const AGENTCHAT_TOOL_ALLOW = `mcp__${CLAUDE_MCP_SERVER_NAME}__*`\n\n/**\n * Built-in tools an `answer` run has: the file-reading tools, and only on the\n * run's own working folder (`workdirReadRules`, `ANSWER_SETTINGS`). An `answer`\n * run is started by any peer's message — a stranger's cold DM included — so\n * the only way out it has is the AgentChat tools: no web, no shell, no edits,\n * and nothing outside its workdir to read.\n */\nexport const ANSWER_TOOLS = ['Read', 'Glob', 'Grep'] as const\n\n/** The web tools: `work` pre-approves them; `answer` never has them. */\nexport const WEB_TOOLS = ['WebSearch', 'WebFetch'] as const\n\n/** Built-in tools a `work` run additionally pre-approves. */\nexport const WORK_TOOLS = ['Bash', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit'] as const\n\n/**\n * Denied to every `answer` run by name, on top of `--tools` leaving them out:\n * the ways out (web) and the shell. A bare tool name in a deny rule removes\n * the tool, so even a widened `--tools` list could not bring them back.\n */\nexport const ANSWER_DENIED_TOOLS = ['WebFetch', 'WebSearch', 'Bash'] as const\n\n/**\n * The `--settings` an `answer` run is given. A constant, never built from a\n * path: in print mode a settings value that fails validation is silently\n * ignored (`claude --help`, `-p`), so nothing variable may ride in it. Every\n * key exists at the 2.1.274 floor.\n *\n * permissions.blockReadsOutsideWorkingDirectories (2.1.257+) no file tool\n * reads outside the working directories, whatever allow rule another\n * settings file holds.\n * env the two `ANSWER_ENV` switches again. A settings file's `env` overrides\n * the process environment, and a workdir repository's own\n * `.claude/settings.json` is applied in print mode: there it could turn\n * CLAUDE.md and auto memory back on. `--settings` outranks user, project\n * and local settings (settings.md, \"Settings precedence\").\n * disableAllHooks (1.0.68+) no hook, status line or file-suggestion command:\n * the user's own hooks and a workdir repository's would run a shell\n * command, and inject text, on every peer's message. Managed hooks still\n * run (only managed settings can turn those off).\n */\nexport const ANSWER_SETTINGS = JSON.stringify({\n permissions: { blockReadsOutsideWorkingDirectories: true },\n env: { CLAUDE_CODE_DISABLE_CLAUDE_MDS: '1', CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' },\n disableAllHooks: true,\n})\n\n/**\n * Env a parent Claude Code session leaks that would make the child think it is\n * nested — a sample kept for callers that named it; the rule is\n * `withoutParentSession` (every `CLAUDE_CODE_*` but the user's documented\n * settings, `CLAUDE_PID`, and the Codex session variables).\n */\nexport const PARENT_ENV_KEYS = [\n 'CLAUDECODE',\n 'CLAUDE_CODE_CHILD_SESSION',\n 'CLAUDE_CODE_SESSION_ID',\n 'CLAUDE_CODE_ENTRYPOINT',\n 'CLAUDE_CODE_EXECPATH',\n 'CLAUDE_CODE_EFFORT_LEVEL',\n 'CLAUDE_EFFORT',\n 'AI_AGENT',\n 'CLAUDE_CODE_MESSAGING_SOCKET',\n 'CLAUDE_CODE_MESSAGING_TOKEN',\n 'CLAUDE_CODE_SESSION_ATTENDED',\n 'CLAUDE_PID',\n]\n\n/**\n * How long the first turn of a `-p` run waits for a still-connecting MCP\n * server that `--allowedTools` names. Claude Code's own built-in wait is short\n * (2 s since 2.1.284), and a remote server over a cold network can take\n * longer; the run must not start without the inbox tool.\n */\nconst MCP_STARTUP_WAIT_MS = '15000'\n\n/** Claude Code's supported relocation knob. Unset is NOT the same as `~/.claude`. */\nexport function claudeConfigDirFrom(env: NodeJS.ProcessEnv = process.env): string | undefined {\n const override = env['CLAUDE_CONFIG_DIR']\n return override !== undefined && override.trim().length > 0 ? path.resolve(override) : undefined\n}\n\n/** `~/.claude`, or the relocated config dir. */\nexport function claudeHomeFor(configDirOverride: string | undefined): string {\n return configDirOverride ?? path.join(os.homedir(), '.claude')\n}\n\n/** Where Claude Code keeps every project's transcripts and auto memory: `<config dir>/projects`. */\nexport function claudeProjectsDirFor(configDirOverride: string | undefined): string {\n return path.join(claudeHomeFor(configDirOverride), 'projects')\n}\n\n/**\n * Where Claude Code keeps user-scoped MCP servers (and so any key registered\n * there): `~/.claude.json`, or `$CLAUDE_CONFIG_DIR/.claude.json`.\n */\nexport function claudeUserStatePathFor(configDirOverride: string | undefined): string {\n return configDirOverride !== undefined ? path.join(configDirOverride, '.claude.json') : path.join(os.homedir(), '.claude.json')\n}\n\nfunction claudeProcessEnv(configDirOverride: string | undefined, source: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const env = { ...source }\n if (configDirOverride === undefined) delete env['CLAUDE_CONFIG_DIR']\n else env['CLAUDE_CONFIG_DIR'] = configDirOverride\n return env\n}\n\nexport function buildClaudeEnv(configDirOverride: string | undefined, source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const env = claudeProcessEnv(configDirOverride, withoutParentSession(source))\n env['DISABLE_AUTOUPDATER'] = '1'\n const wait = Number(env['CLAUDE_CODE_MCP_STARTUP_WAIT_MS'])\n if (!Number.isFinite(wait) || wait < Number(MCP_STARTUP_WAIT_MS)) env['CLAUDE_CODE_MCP_STARTUP_WAIT_MS'] = MCP_STARTUP_WAIT_MS\n return env\n}\n\n/** How long a probe (`--version`, the sign-in check) may take; a hung one is killed with its whole tree. */\nexport const PROBE_TIMEOUT_MS = 10_000\n\n/**\n * Is Claude Code signed in? `claude auth status` prints JSON with a boolean\n * `loggedIn` and exits 0 if logged in, 1 if not. When that JSON is there it is\n * the answer. The file/keychain probes are a fallback for builds without the\n * subcommand; the keychain probe is existence-only and never prompts — a\n * resident listener must never trigger a keychain prompt. Async: a hung probe\n * is killed with everything it started (`runProbe`), never left holding the\n * daemon.\n */\n/** What Claude Code's sign-in check found: signed in or not, or no answer (it hung, or was stopped): then `detail` says so. */\nexport interface ClaudeSignIn {\n readonly signedIn: boolean\n /** Why it could not tell: `claude auth status did not answer within 10 s (killed)`. Null when it answered. */\n readonly unanswered: string | null\n}\n\nexport async function claudeSignIn(configDirOverride?: string, command = 'claude', timeoutMs = PROBE_TIMEOUT_MS, signal?: AbortSignal): Promise<ClaudeSignIn> {\n const status = await runProbe(command, ['auth', 'status'], { timeoutMs, env: claudeProcessEnv(configDirOverride, process.env), ...(signal !== undefined ? { signal } : {}) })\n // A check that hung says the runtime is broken, not that this is an old build: no fallback, and said as what it is.\n if (status.timedOut) return { signedIn: false, unanswered: `claude auth status did not answer within ${Math.round(timeoutMs / 1000)} s (killed)` }\n if (signal?.aborted) return { signedIn: false, unanswered: 'claude auth status was stopped' }\n if (!status.error) {\n try {\n const parsed = JSON.parse(status.stdout.trim()) as { loggedIn?: unknown }\n if (typeof parsed?.loggedIn === 'boolean') return { signedIn: parsed.loggedIn, unanswered: null }\n } catch {\n /* no JSON: an older build; fall through to the file and keychain */\n }\n if (status.status === 0) return { signedIn: true, unanswered: null }\n }\n\n const configDir = claudeHomeFor(configDirOverride)\n if (fs.existsSync(path.join(configDir, '.credentials.json'))) return { signedIn: true, unanswered: null }\n if (process.platform !== 'darwin') return { signedIn: false, unanswered: null }\n const keychain = await runProbe('security', ['find-generic-password', '-s', 'Claude Code-credentials'], { timeoutMs: Math.min(timeoutMs, 5_000), ...(signal !== undefined ? { signal } : {}) })\n return { signedIn: !keychain.error && keychain.status === 0, unanswered: null }\n}\n\n/** `claudeSignIn`, as a yes/no (no answer is not signed in). */\nexport async function claudeIsLoggedIn(configDirOverride?: string, command = 'claude', timeoutMs = PROBE_TIMEOUT_MS): Promise<boolean> {\n return (await claudeSignIn(configDirOverride, command, timeoutMs)).signedIn\n}\n\nexport async function inspectClaudeRuntime(configDirOverride?: string, command = 'claude', timeoutMs = PROBE_TIMEOUT_MS, signal?: AbortSignal): Promise<PresetInspection> {\n const version = await runProbe(command, ['--version'], { timeoutMs, env: claudeProcessEnv(configDirOverride, process.env), ...(signal !== undefined ? { signal } : {}) })\n if (version.timedOut) return { ok: false, detail: `claude --version did not answer within ${Math.round(timeoutMs / 1000)} s (killed)` }\n if (signal?.aborted) return { ok: false, detail: 'claude --version was stopped' }\n if (version.error) return { ok: false, detail: `claude CLI not found on PATH (${version.error.message})` }\n const rendered = (version.stdout || version.stderr).trim()\n if (version.status !== 0) return { ok: false, detail: rendered || `claude --version exited ${version.status}` }\n return semverAtLeast(rendered, MIN_CLAUDE_CODE_VERSION)\n ? { ok: true, detail: rendered }\n : {\n ok: false,\n detail: `${rendered || 'unrecognized version'}; AgentChat requires Claude Code >= ${MIN_CLAUDE_CODE_VERSION} (for --permission-prompts none and CLAUDE_CODE_MCP_STARTUP_WAIT_MS)`,\n }\n}\n\n/**\n * The entry of `denied` that is `dir` or contains it, or null. Whole path\n * segments only: `~/.claude/agentchat` does not contain `~/.claude/agentchat-workdir`.\n */\nexport function deniedAncestorOf(dir: string, denied: readonly string[]): string | null {\n const target = path.resolve(dir)\n for (const raw of denied) {\n const root = path.resolve(raw)\n if (target === root || target.startsWith(root.endsWith(path.sep) ? root : root + path.sep)) return root\n }\n return null\n}\n\n/**\n * Whether a path can be carried by a `Read(//<path>)` ALLOW rule in a\n * comma/space-separated list: what `expressible` asks, and no gitignore\n * pattern character either (`*`, `?`, `[`, `]`, `\\`, `!`, `#`). Rules are\n * matched as gitignore patterns and the ones written here are not escaped\n * (permissions.md \"Special characters\"): `/w*` would also allow `/wallet`.\n */\nfunction expressibleAllow(raw: string): boolean {\n return expressible(raw) && !/[*?[\\]\\\\!#]/.test(raw)\n}\n\n/**\n * The paths a workdir is reached by: as given (absolute), and where it really\n * is when that differs (`/tmp/w` is `/private/tmp/w` on macOS; a symlinked\n * workdir). An allow rule matches only when the requested path and the file\n * it resolves to both match, so both spellings are carried. A workdir that\n * does not exist yet is carried as given.\n */\nexport function workdirPaths(workdir: string): string[] {\n const given = path.resolve(workdir)\n let real = given\n try {\n real = fs.realpathSync(given)\n } catch {\n /* not created yet (preflight creates it): only the given spelling */\n }\n return real === given ? [given] : [given, real]\n}\n\n/**\n * `/w` → `Read(//w)` and `Read(//w/**)`, for each spelling of the workdir: the\n * only paths an `answer` run's Read, Glob and Grep are pre-approved on. A\n * spelling no allow rule can carry (whitespace, a comma, a gitignore pattern\n * character; every path on Windows) gets no rule — that fails closed: the run\n * still reads its workdir as its working directory, and nothing else.\n */\nexport function workdirReadRules(workdir: string | undefined): string[] {\n if (workdir === undefined || process.platform === 'win32') return []\n const rules: string[] = []\n for (const raw of workdirPaths(workdir)) {\n const clean = raw.replace(/\\/+$/, '')\n // The filesystem root is no work folder: no rule (its tree is the disk).\n if (!expressibleAllow(raw) || clean.length === 0) continue\n rules.push(`Read(/${clean})`, `Read(/${clean}/**)`)\n }\n return rules\n}\n\n/**\n * The flags for one run profile. `workdir` is the run's working directory:\n * `answer` scopes its file tools to it (absent, they get no allow rule at all).\n */\nexport function claudeProfileArgs(profile: RunProfile, workdir?: string): string[] {\n switch (profile) {\n // The agent itself: the user's own settings decide; AgentChat's tools are\n // pre-approved and nothing waits on a prompt (see the header).\n case 'own':\n return ['--permission-prompts', 'none', '--allowedTools', AGENTCHAT_TOOL_ALLOW]\n case 'answer':\n return [\n '--permission-mode',\n 'default',\n '--permission-prompts',\n 'none',\n '--tools',\n ANSWER_TOOLS.join(','),\n '--allowedTools',\n [AGENTCHAT_TOOL_ALLOW, ...workdirReadRules(workdir)].join(','),\n '--settings',\n ANSWER_SETTINGS,\n ]\n // `work` and `full` are the operator's explicit opt-in: a run started by\n // any peer's message can then read and change this machine.\n case 'work':\n return [\n '--permission-mode',\n 'acceptEdits',\n '--permission-prompts',\n 'none',\n '--allowedTools',\n [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WEB_TOOLS, ...WORK_TOOLS].join(','),\n ]\n case 'full':\n return ['--dangerously-skip-permissions', '--permission-prompts', 'none', '--allowedTools', AGENTCHAT_TOOL_ALLOW]\n }\n}\n\nexport interface ClaudeRunArgOptions {\n /** `AGENTCHAT_RUN_MAX_BUDGET_USD`: stop the run once estimated spend reaches this (print mode only). */\n readonly maxBudgetUsd?: string | undefined\n /** The run's working directory: the one folder an `answer` run's file tools are allowed (`workdirReadRules`). */\n readonly workdir?: string | undefined\n /**\n * Absolute paths the run's file tools may not read (a directory covers its\n * tree). Rendered as `Read(//<path>)` / `Read(//<dir>/**)` deny rules. A\n * prompt-injected run could otherwise read the key and send it; the wake\n * text should not be the only guard. POSIX paths only — on Windows the\n * rule syntax for drive paths is undocumented, so nothing is rendered.\n */\n readonly denyReadPaths?: readonly string[] | undefined\n /**\n * A `--mcp-config` file holding the hosted server with the agent's key;\n * with it, `--strict-mcp-config` makes it the run's only MCP server. Absent:\n * the run uses the user-scope server the integration registered.\n */\n readonly mcpConfigPath?: string | undefined\n /**\n * A file whose text is appended to the system prompt (`--append-system-prompt-file`,\n * documented since 2.1.69): how an `answer` run, which loads no CLAUDE.md,\n * is told its identity line, and how an `own` run is told it whatever its\n * CLAUDE.md holds (a listener's agent is not the one there). A file, not\n * argv text: an argument cannot carry a line break through a Windows `.cmd` shim.\n */\n readonly appendSystemPromptFile?: string | undefined\n}\n\n/**\n * The `--settings` a runtime check is given: no hook of the user's (or a\n * workdir repository's) fires on a health check, and the two `ANSWER_ENV`\n * switches again (a settings file's `env` overrides the process environment;\n * `--settings` outranks user, project and local settings). A constant\n * (`claude --help`: a settings value that fails validation is silently ignored\n * in print mode). Every key exists at the 2.1.274 floor.\n */\nexport const RUNTIME_CHECK_SETTINGS = JSON.stringify({\n env: { CLAUDE_CODE_DISABLE_CLAUDE_MDS: '1', CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' },\n disableAllHooks: true,\n})\n\n/**\n * Whether a runtime check's stdout (`--output-format json`) is a good answer:\n * null when it is one result object with `type: \"result\"`, `subtype:\n * \"success\"` and `is_error: false`; otherwise why not, in ids and flags only\n * (`is_error`, `api_error_status`, `terminal_reason`), never the result text.\n */\nexport function claudeRuntimeCheckJudge(stdout: string): string | null {\n const text = stdout.trim()\n let parsed: unknown = null\n for (const candidate of [text, text.split(/\\r?\\n/).filter((line) => line.trim().length > 0).at(-1) ?? '']) {\n try {\n parsed = JSON.parse(candidate)\n break\n } catch {\n parsed = null\n }\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return 'its answer is not a JSON result'\n const r = parsed as Record<string, unknown>\n if (r['type'] === 'result' && r['subtype'] === 'success' && r['is_error'] === false) return null\n const facts = [\n `type ${typeof r['type'] === 'string' ? r['type'] : '?'}`,\n `subtype ${typeof r['subtype'] === 'string' ? r['subtype'] : '?'}`,\n `is_error ${typeof r['is_error'] === 'boolean' ? String(r['is_error']) : '?'}`,\n ...(typeof r['api_error_status'] === 'number' ? [`api_error_status ${r['api_error_status']}`] : []),\n ...(typeof r['terminal_reason'] === 'string' && /^[a-z_]{1,40}$/.test(r['terminal_reason']) ? [`terminal_reason ${r['terminal_reason']}`] : []),\n ]\n return `the result is not a success (${facts.join(', ')})`\n}\n\n/**\n * The argv of a runtime check: one `claude -p` with no tool of any kind (no\n * MCP server, no built-in tool), no hooks, never waiting on a prompt; the\n * prompt on stdin, as for a run. `denyReadPaths` are the runs' own deny rules.\n */\nexport function claudeRuntimeCheckArgs(denyReadPaths: readonly string[] = []): string[] {\n const deny = readDenyRules(denyReadPaths)\n return [\n '-p',\n '--output-format',\n 'json',\n '--no-session-persistence',\n // No --mcp-config: with this flag, no MCP server loads at all.\n '--strict-mcp-config',\n // Variadic; \"\" is none (`claude --help`). Closed by the option after it.\n '--tools',\n '',\n '--permission-prompts',\n 'none',\n '--settings',\n RUNTIME_CHECK_SETTINGS,\n ...(deny.length > 0 ? ['--disallowedTools', deny.join(',')] : []),\n ]\n}\n\n/** The empty folder a runtime check runs in: beside Claude Code's config, outside every denied path. */\nexport function claudeRuntimeCheckWorkdir(configDirOverride: string | undefined): string {\n return path.join(claudeHomeFor(configDirOverride), RUNTIME_CHECK_DIR)\n}\n\n/** Whether a path can be carried by a `Read(//<path>)` rule in a comma/space-separated list: absolute POSIX, no comma, no whitespace. */\nfunction expressible(raw: string): boolean {\n return raw.startsWith('/') && !/[,\\s]/.test(raw)\n}\n\n/**\n * The deny paths no rule can carry: on Windows all of them (the rule syntax\n * for drive paths is undocumented), elsewhere a relative path or one with a\n * comma or whitespace. A run would be able to read these.\n */\nexport function inexpressibleDenyPaths(paths: readonly string[]): string[] {\n return process.platform === 'win32' ? [...paths] : paths.filter((p) => !expressible(p))\n}\n\n/** `/Users/x/.claude/agentchat` → `Read(//Users/x/.claude/agentchat/**)` and `Read(//Users/x/.claude/agentchat)`. Paths no rule can carry are left out (`inexpressibleDenyPaths`). */\nexport function readDenyRules(paths: readonly string[]): string[] {\n if (process.platform === 'win32') return []\n const rules: string[] = []\n for (const raw of paths) {\n if (!expressible(raw)) continue\n const clean = raw.replace(/\\/+$/, '')\n rules.push(`Read(/${clean})`, `Read(/${clean}/**)`)\n }\n return rules\n}\n\n/**\n * The full argument list for one headless run. The prompt goes on STDIN, not\n * as a positional: the variadic `--allowedTools` (and `--mcp-config`) would\n * otherwise swallow a trailing positional (verified on 2.1.220; `cat file |\n * claude -p` is the documented piped form).\n */\nexport function claudeRunArgs(profile: RunProfile, options: ClaudeRunArgOptions = {}): string[] {\n const budget = options.maxBudgetUsd?.trim()\n const deny = [...(profile === 'answer' ? ANSWER_DENIED_TOOLS : []), ...readDenyRules(options.denyReadPaths ?? [])]\n return [\n '-p',\n '--output-format',\n 'text',\n // A wake run is not a conversation to resume; keep it out of the user's\n // session list and off the disk.\n '--no-session-persistence',\n ...(budget !== undefined && /^\\d+(\\.\\d+)?$/.test(budget) ? ['--max-budget-usd', budget] : []),\n // Variadic, so it is closed by the option right after it. `own` keeps the\n // user's other servers: the file's `agentchat` wins over theirs by name.\n ...(options.mcpConfigPath !== undefined ? ['--mcp-config', options.mcpConfigPath, ...(profile === 'own' ? [] : ['--strict-mcp-config'])] : []),\n ...(options.appendSystemPromptFile !== undefined ? ['--append-system-prompt-file', options.appendSystemPromptFile] : []),\n ...claudeProfileArgs(profile, options.workdir),\n // Last: the option is variadic and the prompt arrives on stdin, so there\n // is no positional for it to swallow.\n ...(deny.length > 0 ? ['--disallowedTools', deny.join(',')] : []),\n ]\n}\n\n/** The `--mcp-config` document: the hosted server, by HTTP, with the agent's key. Owner-only on disk. */\n/**\n * The `--mcp-config` file a listener's run is given: the hosted tool server\n * with this agent's key, and the client headers that name the runtime to it\n * (`X-AgentChat-Client: claude-code`, `-Version`: the front door that placed\n * the run). The hosted tool server names a client only from these headers:\n * without them a run is an unknown client and is shown the wake-webhook\n * tools, a second way of being woken that the listener makes unnecessary.\n */\nexport function claudeMcpConfig(apiBase: string, apiKey: string, clientVersion: string = VERSION): string {\n const headers = { Authorization: `Bearer ${apiKey}`, ...clientHeadersOf({ runtime: 'claude-code', version: clientVersion }) }\n return `${JSON.stringify({ mcpServers: { [CLAUDE_MCP_SERVER_NAME]: { type: 'http', url: hostedMcpUrl(apiBase), headers } } }, null, 2)}\\n`\n}\n\n/**\n * What an `answer` run's environment adds: no CLAUDE.md of any scope (user,\n * project, ancestors, `.claude/rules`, `@` imports) and no auto memory\n * (code.claude.com/docs/en/env-vars; both read by 2.1.274, the floor). The\n * user's own files are not a peer-started run's context: what it could read\n * there it could send. Its identity line comes in by\n * `--append-system-prompt-file` instead.\n */\nexport const ANSWER_ENV: Readonly<Record<string, string>> = Object.freeze({\n CLAUDE_CODE_DISABLE_CLAUDE_MDS: '1',\n CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1',\n})\n\n/** The system folder Claude Code reads managed settings from (code.claude.com/docs/en/managed-settings). */\nexport function claudeManagedSettingsDir(platform: NodeJS.Platform = process.platform): string {\n if (platform === 'darwin') return '/Library/Application Support/ClaudeCode'\n if (platform === 'win32') return 'C:\\\\Program Files\\\\ClaudeCode'\n return '/etc/claude-code'\n}\n\n/** The git repository root at or above `dir` (a `.git` file or folder), or null. */\nfunction gitRootOf(dir: string): string | null {\n let current = path.resolve(dir)\n for (;;) {\n if (fs.existsSync(path.join(current, '.git'))) return current\n const parent = path.dirname(current)\n if (parent === current) return null\n current = parent\n }\n}\n\n/**\n * The settings files that can give an `answer` run more working directories\n * than its own: `permissions.additionalDirectories` there counts as a working\n * directory even under `blockReadsOutsideWorkingDirectories`\n * (settings-reference.md) — the user's settings, the managed file and its\n * `managed-settings.d/` drop-ins, and `.claude/settings.local.json` at the\n * workdir's repository root and in the workdir itself (counted when git does\n * not track it; checked whenever it is there). MDM and server-managed policies\n * are not files and are not covered.\n */\nexport function claudeSettingsFilesGrantingDirectories(configDirOverride: string | undefined, workdir: string): string[] {\n const managed = claudeManagedSettingsDir()\n const dropIns = (() => {\n try {\n return fs\n .readdirSync(path.join(managed, 'managed-settings.d'))\n .filter((name) => name.endsWith('.json') && !name.startsWith('.'))\n .sort()\n .map((name) => path.join(managed, 'managed-settings.d', name))\n } catch {\n return []\n }\n })()\n // Local settings are read at the repository root in a git repository, and\n // in the working directory itself otherwise (and on Windows): both are checked.\n const cwdLocal = path.join(path.resolve(workdir), '.claude', 'settings.local.json')\n const root = gitRootOf(workdir)\n const rootLocal = root !== null ? path.join(root, '.claude', 'settings.local.json') : cwdLocal\n return [\n path.join(claudeHomeFor(configDirOverride), 'settings.json'),\n path.join(managed, 'managed-settings.json'),\n ...dropIns,\n ...new Set([rootLocal, cwdLocal]),\n ]\n}\n\n/**\n * The first of those files that lists `permissions.additionalDirectories`, with\n * why, or null. A file that is not JSON is ignored by Claude Code (and so here),\n * unless it names the key — then it counts, as it may be read another way.\n */\nexport function claudeExtraDirectoriesGrant(configDirOverride: string | undefined, workdir: string): { file: string; detail: string } | null {\n for (const file of claudeSettingsFilesGrantingDirectories(configDirOverride, workdir)) {\n let text: string\n try {\n text = fs.readFileSync(file, 'utf-8')\n } catch {\n continue\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n if (text.includes('additionalDirectories')) return { file, detail: 'names permissions.additionalDirectories and is not valid JSON' }\n continue\n }\n const dirs = (parsed as { permissions?: { additionalDirectories?: unknown } } | null)?.permissions?.additionalDirectories\n if (Array.isArray(dirs) && dirs.length > 0) return { file, detail: `lists permissions.additionalDirectories (${dirs.length} folder${dirs.length === 1 ? '' : 's'})` }\n }\n return null\n}\n\n/** The reason an `answer` run does not start while a settings file grants more working directories. */\nfunction extraDirectoriesRefusal(grant: { file: string; detail: string }): string {\n return `answer runs do not start while ${grant.file} ${grant.detail}: Claude Code counts those as working directories, so a run started by a peer's message could read them. Remove the key from that file (your own sessions can use --add-dir instead).`\n}\n\n/**\n * The AgentChat hosted server alone, for `answer` runs that have no\n * `mcpConfigPath`: written owner-only for each run beside `file`, under a name\n * of that run's own (`<file stem>.<run id>.json`, so a late cleanup of an\n * abandoned run cannot remove the next run's), from the key `apiKey()` returns\n * then (a credential change is followed), passed with `--strict-mcp-config`,\n * and removed when the run ends. An `answer` run then\n * loads no other MCP server — the user's own, a project's, a plugin's, a\n * claude.ai connector — whatever the user scope registers. `file` must sit\n * inside a `denyReadPaths` entry (it holds the key), or preflight refuses.\n * An `own` run writes no tool config (it uses the user's servers); its\n * identity-line file is written beside `file` all the same.\n */\nexport interface ClaudeAnswerMcp {\n readonly file: string\n readonly apiBase: string\n readonly apiKey: () => string | null\n /** The version named in `X-AgentChat-Client-Version` (the front door that placed the run). Defaults to this engine's. */\n readonly clientVersion?: string\n}\n\nexport interface ClaudeRunnerOptions {\n readonly configDir: string | undefined\n /**\n * The run's working directory; the `work` profile edits and runs shell here.\n * Must lie outside `denyReadPaths`, or the run cannot read its own cwd —\n * preflight says so once and still runs. An `own` or `answer` run whose\n * workdir is the home folder or contains it works in\n * `claudeAnswerFallbackWorkdir` instead.\n */\n readonly workdir: string\n readonly profile: RunProfile\n /** Paths every run's file tools are denied: the key store (identity home, the user-scope MCP state). */\n readonly denyReadPaths: readonly string[]\n /** See `ClaudeRunArgOptions.mcpConfigPath`: every profile, strict. */\n readonly mcpConfigPath?: string\n /**\n * See `ClaudeAnswerMcp`. Without it (and without `mcpConfigPath`) an `answer`\n * run does not start: it would load every MCP server the user registered.\n */\n readonly answerMcp?: ClaudeAnswerMcp\n /** The one-line fix printed when the workdir sits inside a denied path. */\n readonly workdirAdvice?: string\n /**\n * A deny path no rule can carry (a comma or whitespace in it; every path on\n * Windows): `warn` (default) logs it once and runs — the run can then read\n * that path; `refuse` fails preflight with the reason, so no run starts.\n */\n readonly inexpressibleDeny?: 'warn' | 'refuse'\n /** Test seam: the binary to run. */\n readonly command?: string\n readonly env?: NodeJS.ProcessEnv\n}\n\n/**\n * The folder an `own` or `answer` run works in when its configured workdir is\n * the user's home folder or contains it (`workdirExposesHome`): an empty folder\n * of its own beside Claude Code's config, never inside a denied path. The run\n * keeps working — it only cannot read the user's files. An `own` run needs\n * this as much: Claude Code lets a run read its working directory without\n * asking in every permission mode, so a home-folder workdir would hand a\n * peer-started run `~/.ssh` whatever the user's allow rules say.\n */\nexport function claudeAnswerFallbackWorkdir(configDirOverride: string | undefined): string {\n return path.join(claudeHomeFor(configDirOverride), 'agentchat-answer-workdir')\n}\n\n/** The profiles whose runs never work in the home folder or above it (`claudeAnswerFallbackWorkdir`). */\nfunction guardsHomeWorkdir(profile: RunProfile): boolean {\n return profile === 'answer' || profile === 'own'\n}\n\nexport class ClaudeRunner implements RunRunner {\n readonly name = 'claude'\n readonly label = 'Claude Code'\n private readonly command: string\n /** The workdir warning is one line per process, not one per preflight (preflight repeats every few minutes). */\n private warnedWorkdir = false\n private warnedDeny = false\n private warnedHome = false\n\n constructor(private readonly options: ClaudeRunnerOptions) {\n this.command = options.command ?? 'claude'\n }\n\n /**\n * Where this runner's runs work: the configured workdir, except that an\n * `own` or `answer` run never works in the home folder or above it — it gets\n * `claudeAnswerFallbackWorkdir` (its readable folder would be the whole home).\n */\n workdir(): string {\n if (guardsHomeWorkdir(this.options.profile) && workdirExposesHome(this.options.workdir)) return claudeAnswerFallbackWorkdir(this.options.configDir)\n return this.options.workdir\n }\n\n /** The denied path the workdir sits in, or null when the run can read its own cwd. */\n workdirDeniedBy(): string | null {\n return deniedAncestorOf(this.workdir(), this.options.denyReadPaths)\n }\n\n async preflight(options: RunPreflightOptions = {}): Promise<RunPreflight> {\n const runtime = await inspectClaudeRuntime(this.options.configDir, this.command, PROBE_TIMEOUT_MS, options.signal)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n const signIn = await claudeSignIn(this.options.configDir, this.command, PROBE_TIMEOUT_MS, options.signal)\n if (signIn.unanswered !== null) return { ok: false, detail: signIn.unanswered }\n if (!signIn.signedIn) return { ok: false, detail: 'claude is not signed in (run `claude` once and sign in)' }\n if (this.options.profile === 'answer' && this.options.mcpConfigPath === undefined) {\n const answerMcp = this.options.answerMcp\n // Fail closed: without an AgentChat-only tool config the run would load\n // every MCP server the user registered.\n if (answerMcp === undefined) {\n return { ok: false, detail: 'an answer run needs the AgentChat-only tool config (ClaudeRunnerOptions.answerMcp): without it the run would load every MCP server the user registered' }\n }\n if (deniedAncestorOf(answerMcp.file, this.options.denyReadPaths) === null) {\n return { ok: false, detail: `the answer runs' tool config ${answerMcp.file} holds the key and must sit inside a path the runs are denied (${this.options.denyReadPaths.join(', ')})` }\n }\n }\n if (this.options.profile === 'answer') {\n const grant = claudeExtraDirectoriesGrant(this.options.configDir, this.workdir())\n if (grant !== null) return { ok: false, detail: extraDirectoriesRefusal(grant) }\n }\n if (this.workdir() !== this.options.workdir && !this.warnedHome) {\n this.warnedHome = true\n log.warn(`the run workdir ${this.options.workdir} is your home folder or contains it: ${this.options.profile} runs work in ${this.workdir()} instead, so a peer-started run reads none of your files there. Point the workdir at a folder of its own to choose another.`)\n }\n // A cwd inside the key store is an operator choice the deny rules then\n // make unreadable to the run. Said once, with the fix; the run still\n // starts — the hosted tools do not need the cwd.\n const denied = this.workdirDeniedBy()\n if (denied !== null && !this.warnedWorkdir) {\n this.warnedWorkdir = true\n log.warn(\n `the run workdir ${this.workdir()} is inside ${denied}, which every run's file tools are denied: runs cannot read their own working directory.${this.options.workdirAdvice ? ` ${this.options.workdirAdvice}` : ''}`,\n )\n }\n const uncovered = inexpressibleDenyPaths(this.readDenyPaths())\n if (uncovered.length > 0) {\n const why =\n process.platform === 'win32'\n ? `Claude Code's rule syntax for Windows paths is undocumented, so no read-deny rule is given for ${uncovered.join(', ')}`\n : `no read-deny rule can carry ${uncovered.join(', ')} (a comma or whitespace in the path)`\n if (this.options.inexpressibleDeny === 'refuse') return { ok: false, detail: `${why}: a run could read the key there. Use an identity home whose path has no comma or whitespace (--home).` }\n if (!this.warnedDeny) {\n this.warnedDeny = true\n log.warn(`${why}: runs can read those paths.`)\n }\n }\n if (this.options.mcpConfigPath !== undefined && !fs.existsSync(this.options.mcpConfigPath)) {\n return { ok: false, detail: `the hosted tool config ${this.options.mcpConfigPath} is missing` }\n }\n // Owner-only on creation, as the identity home is. Creation only: an\n // operator's own workspace keeps its permissions.\n fs.mkdirSync(this.workdir(), { recursive: true, mode: 0o700 })\n return { ok: true }\n }\n\n /** `<dir>/<stem>.<run id><ext>`: a file of this run's own beside `file` (the run id reduced to letters, digits and `-`). */\n private static perRun(file: string, runId: string, ext: string): string {\n const stem = path.basename(file, path.extname(file))\n const id = runId.replace(/[^A-Za-z0-9-]/g, '').slice(0, 64) || 'run'\n return path.join(path.dirname(file), `${stem}.${id}${ext}`)\n }\n\n /**\n * A run's own files for `runId`: an answer run's AgentChat-only tool config\n * (integration path), and the identity-line file of an answer or own run.\n * `work` and `full` write none (they load CLAUDE.md, as before).\n */\n private runFiles(runId: string): { mcpConfigPath?: string; identityFile?: string } {\n const profile = this.options.profile\n if (profile !== 'answer' && profile !== 'own') return {}\n const base = this.options.mcpConfigPath ?? this.options.answerMcp?.file\n return {\n ...(profile === 'answer' && this.options.mcpConfigPath === undefined && this.options.answerMcp !== undefined ? { mcpConfigPath: ClaudeRunner.perRun(this.options.answerMcp.file, runId, '.json') } : {}),\n ...(base !== undefined ? { identityFile: ClaudeRunner.perRun(base, runId, '.identity.md') } : {}),\n }\n }\n\n /**\n * What this runner's runs are denied reading: the key store, and for an\n * `answer` run also Claude Code's own record of every project\n * (`<config dir>/projects`: transcripts and auto memory). Claude Code lets a\n * run read its project's memory folder even with auto memory off and reads\n * blocked outside the working directories (seen on 2.1.322); a deny rule\n * wins over that.\n */\n readDenyPaths(): string[] {\n return this.options.profile === 'answer' ? [...this.options.denyReadPaths, claudeProjectsDirFor(this.options.configDir)] : [...this.options.denyReadPaths]\n }\n\n private argsFor(mcpConfigPath: string | undefined, appendSystemPromptFile: string | undefined): string[] {\n return claudeRunArgs(this.options.profile, {\n maxBudgetUsd: (this.options.env ?? process.env)['AGENTCHAT_RUN_MAX_BUDGET_USD'],\n workdir: this.workdir(),\n denyReadPaths: this.readDenyPaths(),\n ...(mcpConfigPath !== undefined ? { mcpConfigPath } : {}),\n ...(appendSystemPromptFile !== undefined ? { appendSystemPromptFile } : {}),\n })\n }\n\n /**\n * The argv of a run — exported for tests to pin per profile. With a `runId`,\n * that run's own files (an answer run's tool config, an answer or own run's\n * identity-line file); without, the configured `answerMcp.file` stands in\n * for an answer run's tool config, and no identity file.\n */\n args(runId?: string, identityLine?: boolean): string[] {\n if (runId === undefined) {\n const mcpConfigPath = this.options.mcpConfigPath ?? (this.options.profile === 'answer' ? this.options.answerMcp?.file : undefined)\n return this.argsFor(mcpConfigPath, undefined)\n }\n const files = this.runFiles(runId)\n return this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityLine === true ? files.identityFile : undefined)\n }\n\n /**\n * The run's environment: no parent session; an answer run loads no CLAUDE.md\n * and no auto memory (`ANSWER_ENV`); an own run carries no `AGENTCHAT_API_KEY`\n * the daemon inherited — it has the user's own shell, and it reaches the\n * hosted tools through its MCP entry, never through that variable.\n */\n runEnv(): NodeJS.ProcessEnv {\n const source = this.options.env ?? process.env\n const env = buildClaudeEnv(this.options.configDir, this.options.profile === 'own' ? withoutInheritedKey(source) : source)\n return this.options.profile === 'answer' ? { ...env, ...ANSWER_ENV } : env\n }\n\n /**\n * Does the model answer right now, through this runner's binary, sign-in\n * and environment? One `claude -p` with a fixed prompt and no tool at all\n * (`claudeRuntimeCheckArgs`), in its own empty folder, with no key in its\n * environment and no instruction file or memory in its context; ok only\n * when its JSON result says success with no error (`claudeRuntimeCheckJudge`).\n * Its output is read for that alone and never logged. Never throws.\n */\n async checkRuntime(options: RunPreflightOptions = {}): Promise<RunPreflight> {\n return runRuntimeCheck({\n label: 'claude',\n command: this.command,\n args: claudeRuntimeCheckArgs(this.readDenyPaths()),\n cwd: claudeRuntimeCheckWorkdir(this.options.configDir),\n // No key (runRuntimeCheck takes every key variable out); no instruction file or memory.\n env: { ...this.runEnv(), ...ANSWER_ENV },\n // Exit 0 is not enough: the JSON result must say success with no error.\n judge: claudeRuntimeCheckJudge,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n })\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const startedAt = Date.now()\n const notStarted = (detail: string): RunOutcome => ({ state: 'not_started', exitCode: null, durationMs: Date.now() - startedAt, detail })\n const answer = this.options.profile === 'answer'\n // An answer run's own AgentChat-only tool config: written for this run, removed after it.\n const answerMcp = answer && this.options.mcpConfigPath === undefined ? this.options.answerMcp : undefined\n if (answer && this.options.mcpConfigPath === undefined && answerMcp === undefined) {\n return notStarted('an answer run needs the AgentChat-only tool config (ClaudeRunnerOptions.answerMcp)')\n }\n // Settings can change while the daemon runs: checked before every answer run, not only at preflight.\n if (answer) {\n const grant = claudeExtraDirectoriesGrant(this.options.configDir, this.workdir())\n if (grant !== null) return notStarted(extraDirectoriesRefusal(grant))\n }\n const files = this.runFiles(request.runId)\n // answer: it loads no CLAUDE.md. own: whatever CLAUDE.md holds, the run is told who it is (a listener's agent is not the one there).\n const identityFile = request.identityLine !== undefined ? files.identityFile : undefined\n const written: string[] = []\n const cleanup = (): void => {\n for (const file of written) fs.rmSync(file, { force: true })\n }\n if (answerMcp !== undefined && files.mcpConfigPath !== undefined) {\n const key = answerMcp.apiKey()\n if (key === null) return notStarted('no AgentChat key for the answer run\\'s tool config')\n try {\n atomicWriteFile(files.mcpConfigPath, claudeMcpConfig(answerMcp.apiBase, key, answerMcp.clientVersion ?? VERSION), 0o600)\n written.push(files.mcpConfigPath)\n } catch (err) {\n cleanup()\n return notStarted(`could not write the answer run's tool config ${files.mcpConfigPath}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n if (identityFile !== undefined && request.identityLine !== undefined) {\n try {\n atomicWriteFile(identityFile, `${request.identityLine.trim()}\\n`, 0o600)\n written.push(identityFile)\n } catch (err) {\n cleanup()\n return notStarted(`could not write the run's identity line ${identityFile}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n try {\n const args = this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityFile)\n log.debug(`claude ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId}${request.conversationId !== undefined ? ` for ${request.conversationId}` : ''})`)\n return await spawnRun({\n command: this.command,\n args,\n cwd: this.workdir(),\n env: this.runEnv(),\n stdin: request.prompt,\n budgetMs: request.budgetMs,\n // Stopping SIGTERMs this run's process group instead of orphaning it.\n ...(request.signal ? { signal: request.signal } : {}),\n // The engine records a group invite as offered the moment the process\n // has spawned, so a run cut short still counts as the one offer.\n ...(request.onStarted ? { onStarted: request.onStarted } : {}),\n })\n } finally {\n // Only this run's own files: a late cleanup can never touch another run's.\n cleanup()\n }\n }\n}\n\n/** Where a listener keeps the `--mcp-config` file for this preset, inside its identity home. */\nexport function claudeMcpConfigPath(home: string): string {\n return path.join(home, 'presets', `${CLAUDE_CODE_PRESET}.mcp.json`)\n}\n\nexport const claudeCodePreset: Preset = {\n name: CLAUDE_CODE_PRESET,\n describeMcp({ home, apiBase, profile }) {\n return [\n `--mcp-config ${claudeMcpConfigPath(home)} (owner-only): ${CLAUDE_MCP_SERVER_NAME} → ${hostedMcpUrl(apiBase)}, Authorization: Bearer <this home's key>, X-AgentChat-Client: claude-code`,\n profile === 'own'\n ? `own: your other MCP servers load too (the file is not made the only one); this file's ${CLAUDE_MCP_SERVER_NAME} is used in place of a user-scope ${CLAUDE_MCP_SERVER_NAME} (verified); a project- or local-scope one is not covered`\n : '--strict-mcp-config: no other MCP server (user, project or plugin) is loaded in these runs',\n ]\n },\n label: 'Claude Code',\n runtime: 'claude-code',\n // Every run's file tools are denied the identity home.\n serviceEnv: ['CLAUDE_CONFIG_DIR'],\n readsIdentityHome: false,\n async inspect(env = process.env, command = 'claude') {\n const configDir = claudeConfigDirFrom(env)\n const runtime = await inspectClaudeRuntime(configDir, command)\n if (!runtime.ok) return runtime\n const signIn = await claudeSignIn(configDir, command)\n if (signIn.unanswered !== null) return { ok: false, detail: `${runtime.detail}, ${signIn.unanswered}` }\n return signIn.signedIn\n ? { ok: true, detail: `${runtime.detail}, signed in` }\n : { ok: false, detail: `${runtime.detail}, not signed in (run \\`claude\\` once and sign in)` }\n },\n runner(ctx: PresetContext): RunRunner {\n // A key in the listener's own environment is not handed to its runs.\n const env = withoutInheritedKey(ctx.env ?? process.env)\n const configDir = claudeConfigDirFrom(env)\n const mcpConfigPath = claudeMcpConfigPath(ctx.home)\n // Rewritten for every identity the listener serves: the runs act as THIS agent.\n atomicWriteFile(mcpConfigPath, claudeMcpConfig(ctx.apiBase, ctx.apiKey, ctx.clientVersion ?? VERSION), 0o600)\n return new ClaudeRunner({\n configDir,\n workdir: ctx.workdir,\n profile: ctx.profile,\n // The listener's home (its key and this file), the user-scope MCP state\n // and an integration's identity home beside it: no run reads a key.\n denyReadPaths: [ctx.home, claudeUserStatePathFor(configDir), path.join(claudeHomeFor(configDir), 'agentchat')],\n mcpConfigPath,\n workdirAdvice: 'Start the listener from a directory outside it, or pass --workdir.',\n // On POSIX a listener's run must not start with its key readable; on\n // Windows no rule exists at all (documented), so it warns.\n inexpressibleDeny: process.platform === 'win32' ? 'warn' : 'refuse',\n ...(ctx.command !== undefined ? { command: ctx.command } : {}),\n env,\n })\n },\n}\n","/** `actual` (any text containing `x.y.z`) is at least `minimum`. False when either has no version in it. */\nexport function semverAtLeast(actual: string, minimum: string): boolean {\n const parse = (value: string): [number, number, number] | null => {\n const match = value.match(/(\\d+)\\.(\\d+)\\.(\\d+)/)\n return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null\n }\n const a = parse(actual)\n const b = parse(minimum)\n if (a === null || b === null) return false\n for (let index = 0; index < 3; index++) {\n if (a[index] !== b[index]) return (a[index] ?? 0) > (b[index] ?? 0)\n }\n return true\n}\n","import * as fs from 'node:fs'\nimport type { RunPreflight } from '../integration/runner.js'\nimport { spawnRunCapturing } from '../integration/spawn-run.js'\n\n// ─── The runtime check: does the agent's AI answer right now? ───────────────\n//\n// After a conversation's run failed, and no other run has completed since,\n// the SDK kit asks the runner whether the runtime works (`checkRuntime`): an\n// `ok` is the evidence that the failure belongs to that conversation (a\n// provider refusal, a crash on its content), and the kit reports it (could\n// not process). So the check must prove the model answers NOW, through the\n// same binary, account and environment the runs use — a `--version` or a\n// sign-in check passes during a provider outage, and an outage reported as\n// the conversation's failure would hide its messages.\n//\n// The check is one headless run of the runtime with a fixed prompt: no peer\n// content, no AgentChat tools, nothing a run could act on, in an empty folder\n// of its own. Exit 0 with some text is not enough (a usage limit, a low\n// credit balance or an expired sign-in can print a sentence and still be no\n// answer): a runtime whose result says what happened is judged on it\n// (`judge`, e.g. Claude Code's JSON result). For that, the first\n// `RUNTIME_CHECK_OUTPUT_BYTES` of its stdout are kept for the check alone —\n// the prompt is ours, so it holds no peer content — read, and dropped; never\n// logged. Only \"it answered\" and a bounded, redacted diagnostic come back. It\n// is bounded so that its kill path ends inside the engine's 60 s deadline, and\n// it stops (its process group killed) when the integration stops.\n\n/** The fixed prompt: nothing from any peer, nothing to act on. */\nexport const RUNTIME_CHECK_PROMPT = 'Reply with the single word OK.'\n\n/**\n * The check's own budget. Past it the probe is SIGTERMed, SIGKILLed 5 s later\n * and given up 5 s after that: 55 s at most, inside the engine's\n * `RUNTIME_CHECK_DEADLINE_MS` (60 s).\n */\nexport const RUNTIME_CHECK_BUDGET_MS = 45_000\n\n/** The most of a check's stdout kept for its `judge` (a result line is a few kB); more is not read. */\nexport const RUNTIME_CHECK_OUTPUT_BYTES = 128 * 1024\n\n/** The name of the empty folder a runtime check runs in, beside the runtime's own config. */\nexport const RUNTIME_CHECK_DIR = 'agentchat-runtime-check'\n\n/**\n * The variables an AgentChat key travels in (the daemon's own, the listener's\n * Codex bearer variable): never in a runtime check's environment, whatever\n * the runs carry. The check needs no key.\n */\nexport const RUNTIME_CHECK_KEY_ENV: readonly string[] = ['AGENTCHAT_API_KEY', 'AGENTCHAT_LISTENER_API_KEY']\n\n/** `env` without the key variables (`RUNTIME_CHECK_KEY_ENV` and `also`), in any case. */\nfunction withoutKeys(env: NodeJS.ProcessEnv, also: readonly string[]): NodeJS.ProcessEnv {\n const names = new Set([...RUNTIME_CHECK_KEY_ENV, ...also].map((name) => name.toUpperCase()))\n const out: NodeJS.ProcessEnv = {}\n for (const [key, value] of Object.entries(env)) if (!names.has(key.toUpperCase())) out[key] = value\n return out\n}\n\nexport interface RuntimeCheckSpec {\n /** The runtime's name, for the diagnostic. */\n readonly label: string\n readonly command: string\n readonly args: readonly string[]\n /** An empty folder of the check's own (created owner-only). */\n readonly cwd: string\n /** The runs' environment; the key variables are taken out (`RUNTIME_CHECK_KEY_ENV`, `keyEnv`). */\n readonly env: NodeJS.ProcessEnv\n /** Another variable this runtime's runs carry a key in (a Codex runner's `keyEnv`). */\n readonly keyEnv?: string\n readonly signal?: AbortSignal\n /**\n * Reads the runtime's answer (its stdout, bounded) after an exit 0: null\n * when it is a good answer, else why not (ids and flags only, never the\n * text). Absent: exit 0 with something on stdout is ok.\n */\n readonly judge?: (stdout: string) => string | null\n /** Test seam: `RUNTIME_CHECK_BUDGET_MS`. */\n readonly budgetMs?: number\n}\n\n/** Run the check once: ok when the runtime exited 0 having printed an answer. Never throws. */\nexport async function runRuntimeCheck(spec: RuntimeCheckSpec): Promise<RunPreflight> {\n if (spec.signal?.aborted === true) return { ok: false, detail: `${spec.label} runtime check: stopped before it started` }\n try {\n fs.mkdirSync(spec.cwd, { recursive: true, mode: 0o700 })\n } catch (err) {\n return { ok: false, detail: `${spec.label} runtime check: could not create its folder ${spec.cwd}: ${err instanceof Error ? err.message : String(err)}` }\n }\n const { outcome, stdout } = await spawnRunCapturing({\n command: spec.command,\n args: spec.args,\n cwd: spec.cwd,\n env: withoutKeys(spec.env, spec.keyEnv !== undefined ? [spec.keyEnv] : []),\n stdin: RUNTIME_CHECK_PROMPT,\n budgetMs: spec.budgetMs ?? RUNTIME_CHECK_BUDGET_MS,\n requireStdout: true,\n ...(spec.signal !== undefined ? { signal: spec.signal } : {}),\n }, spec.judge !== undefined ? RUNTIME_CHECK_OUTPUT_BYTES : 0)\n if (outcome.state !== 'ok') return { ok: false, detail: `${spec.label} runtime check ${outcome.state.replace('_', ' ')}${outcome.detail ? `: ${outcome.detail}` : ''}` }\n const verdict = spec.judge === undefined ? null : spec.judge(stdout)\n return verdict === null ? { ok: true } : { ok: false, detail: `${spec.label} runtime check failed: exit 0, but ${verdict}` }\n}\n","import type { TextsRuntime } from 'agentchatme'\nimport type { RunProfile } from '../integration/profile.js'\nimport type { RunRunner } from '../integration/runner.js'\n\n// ─── Presets: how to start one headless run of a known coding agent ─────────\n//\n// The engine (everything in this package outside `presets/`) names no coding\n// agent and never imports from here; `tests/core-is-host-agnostic`\n// asserts both. A preset is the one place that does: the flags a runtime's\n// headless mode takes per run profile, how to tell it is installed and signed\n// in, and how a run of it reaches the hosted AgentChat tools AS a given agent.\n//\n// Two front doors select one, and only ever for the run command: the\n// `agentchat listen --preset <name>` listener (@agentchatme/cli; its identity\n// is the listener's own home, injected into each run), and the runtime's own\n// integration package (its identity home and placement stay the integration's). A preset\n// never decides which identity home is acted on — the caller passes it.\n\n/** What a preset needs to build a runner acting as one agent. */\nexport interface PresetContext {\n /** The identity home of the agent the runs act as. Runs' file tools are kept off it where the runtime allows. */\n readonly home: string\n /** The run's working directory. */\n readonly workdir: string\n readonly profile: RunProfile\n /** The agent's key and API base, for the hosted tool server the runs reach. Never put on argv. */\n readonly apiKey: string\n readonly apiBase: string\n /** The environment runs inherit (defaults to `process.env`). */\n readonly env?: NodeJS.ProcessEnv\n /** Test seam: the runtime's binary. */\n readonly command?: string\n /**\n * The version the runs name in `X-AgentChat-Client-Version`: the front door\n * that placed them (the `agentchat` listener passes its own). Defaults to\n * this engine's version. The client name is the runtime's (`claude-code`,\n * `codex`): a run the listener wakes needs no wake-webhook tools, and the\n * hosted tools spell their names per runtime by it.\n */\n readonly clientVersion?: string\n}\n\nexport interface PresetInspection {\n readonly ok: boolean\n readonly detail: string\n}\n\nexport interface Preset {\n /** The name a user types (`--preset <name>`). */\n readonly name: string\n /** Human name for output. */\n readonly label: string\n /** How the served texts spell the hosted tools for this runtime (`GET /v1/texts?runtime=`). */\n readonly runtime: TextsRuntime\n /**\n * Is the runtime installed, new enough and signed in? For `doctor` and\n * `status`. Async: its probes are killed with their whole tree when they\n * hang (a Windows `.cmd` shim, an npm launcher), never left blocking.\n */\n inspect(env?: NodeJS.ProcessEnv, command?: string): Promise<PresetInspection>\n /**\n * A runner whose runs act as the agent in `ctx`: the hosted tool server is\n * given to each run with that agent's key (a file or an environment\n * variable, never an argument), whatever the runtime's own configuration\n * registers. May write owner-only files into `ctx.home`.\n */\n runner(ctx: PresetContext): RunRunner\n /**\n * The hosted-tool configuration a listener's run of this preset sees, as\n * lines for `doctor` (keys never printed): what the run is given, and what\n * of the user's own configuration still applies. `profile` is the\n * listener's (`own` changes what is given); absent, the lines are those of\n * the other profiles.\n */\n describeMcp(ctx: { readonly home: string; readonly apiBase: string; readonly env?: NodeJS.ProcessEnv; readonly profile?: RunProfile }): string[]\n /** Variables a service must capture for this runtime (where it keeps its config, when relocated). */\n readonly serviceEnv: readonly string[]\n /** Whether the run can read files under the identity home (decides how the manual is pointed to). */\n readonly readsIdentityHome: boolean\n}\n\n// ─── A run's environment carries nothing of the session that started it ─────\n//\n// A listener or daemon started from inside a Claude Code or Codex session\n// inherits that session's variables, and every run it starts would too: a\n// session id, a messaging socket and its token (CLAUDE_CODE_MESSAGING_TOKEN\n// lets a process post into the parent session), a sandbox marker\n// (CODEX_SANDBOX makes a child believe it is already sandboxed). They are the\n// parent's, never the run's, in every profile.\n\n/**\n * Documented `CLAUDE_CODE_*` variables that configure how Claude Code signs in\n * and reaches its provider, or switch off traffic and secrets — the user's own\n * settings, kept (code.claude.com/docs/en/env-vars). Every other `CLAUDE_CODE_*`\n * variable is dropped: the ones Claude Code sets for the processes it spawns\n * share the prefix (CLAUDE_CODE_SESSION_ID, _CHILD_SESSION, _MESSAGING_SOCKET,\n * _MESSAGING_TOKEN, _BRIDGE_SESSION_ID, _REMOTE_SESSION_ID, …), and a variable\n * not listed here is one a headless run can do without.\n */\nexport const CLAUDE_CODE_ENV_KEPT: readonly string[] = [\n // Sign-in and provider\n 'CLAUDE_CODE_OAUTH_TOKEN',\n 'CLAUDE_CODE_OAUTH_REFRESH_TOKEN',\n 'CLAUDE_CODE_OAUTH_SCOPES',\n 'CLAUDE_CODE_API_KEY_HELPER_TTL_MS',\n 'CLAUDE_CODE_USE_BEDROCK',\n 'CLAUDE_CODE_USE_VERTEX',\n 'CLAUDE_CODE_USE_FOUNDRY',\n 'CLAUDE_CODE_USE_MANTLE',\n 'CLAUDE_CODE_USE_ANTHROPIC_AWS',\n 'CLAUDE_CODE_SKIP_BEDROCK_AUTH',\n 'CLAUDE_CODE_SKIP_VERTEX_AUTH',\n 'CLAUDE_CODE_SKIP_FOUNDRY_AUTH',\n 'CLAUDE_CODE_SKIP_MANTLE_AUTH',\n 'CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH',\n 'CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS',\n // Network and TLS\n 'CLAUDE_CODE_CLIENT_CERT',\n 'CLAUDE_CODE_CLIENT_KEY',\n 'CLAUDE_CODE_CLIENT_KEY_PASSPHRASE',\n 'CLAUDE_CODE_CERT_STORE',\n 'CLAUDE_CODE_PROXY_RESOLVES_HOSTS',\n 'CLAUDE_CODE_CONNECT_TIMEOUT_MS',\n // Privacy and secrets switches the user turned on\n 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC',\n 'CLAUDE_CODE_ENABLE_TELEMETRY',\n 'CLAUDE_CODE_SUBPROCESS_ENV_SCRUB',\n 'CLAUDE_CODE_MCP_ALLOWLIST_ENV',\n 'CLAUDE_CODE_DISABLE_CLAUDE_MDS',\n 'CLAUDE_CODE_DISABLE_AUTO_MEMORY',\n // Model request settings the user chose\n 'CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS',\n 'CLAUDE_CODE_EXTRA_BODY',\n 'CLAUDE_CODE_MAX_OUTPUT_TOKENS',\n // Platform\n 'CLAUDE_CODE_GIT_BASH_PATH',\n 'CLAUDE_CODE_TMPDIR',\n // Set by the preset itself (a larger value of the user's is kept)\n 'CLAUDE_CODE_MCP_STARTUP_WAIT_MS',\n]\n\n/**\n * Claude Code session variables outside the `CLAUDE_CODE_` prefix\n * (code.claude.com/docs/en/env-vars, hooks.md): what it sets in the processes\n * it spawns — its pid, the effort level, a background job's folder, the\n * project folder, the W3C trace context — and `AI_AGENT`. Not `CLAUDE_ENV_FILE`:\n * that one the user sets (a file sourced before each shell command).\n */\nexport const CLAUDE_SESSION_ENV: readonly string[] = ['CLAUDECODE', 'CLAUDE_PID', 'CLAUDE_EFFORT', 'CLAUDE_JOB_DIR', 'CLAUDE_PROJECT_DIR', 'TRACEPARENT', 'TRACESTATE', 'AI_AGENT']\n\n/**\n * What a Codex session sets in the processes it spawns (openai/codex at\n * rust-v0.154.0: core/src/spawn.rs, core/src/exec_env.rs,\n * protocol/src/shell_environment.rs, network-proxy/src/proxy.rs,\n * shell-escalation/src/unix/escalate_protocol.rs). Not the whole `CODEX_`\n * prefix: CODEX_HOME, CODEX_API_KEY, CODEX_CA_CERTIFICATE are the user's.\n */\nexport const CODEX_SESSION_ENV: readonly string[] = [\n 'CODEX_SANDBOX',\n 'CODEX_SANDBOX_NETWORK_DISABLED',\n 'CODEX_SESSION_ID',\n 'CODEX_THREAD_ID',\n 'CODEX_VERSION',\n 'CODEX_PERMISSION_PROFILE',\n 'CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN',\n 'CODEX_ESCALATE_SOCKET',\n 'CODEX_NETWORK_PROXY_ACTIVE',\n 'CODEX_NETWORK_ALLOW_LOCAL_BINDING',\n 'CODEX_NETWORK_PROXY_ATTRIBUTION',\n 'CODEX_NETWORK_PROXY_CREDENTIAL_BROKER_ACTIVE',\n 'CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS',\n 'CODEX_WINDOWS_SANDBOX_PROXY_PORTS',\n]\n\n/**\n * What a Codex session's managed network proxy puts in its children's\n * environment (openai/codex rust-v0.154.0 network-proxy/src/proxy.rs:578-628\n * `PROXY_ENV_KEYS`): proxy URLs pointing at the parent's proxy, which dies\n * with it. Dropped only when the environment says that proxy was active\n * (`CODEX_NETWORK_PROXY_ACTIVE`): otherwise they are the user's own proxy.\n */\nexport const CODEX_MANAGED_PROXY_ENV: readonly string[] = [\n 'ELECTRON_GET_USE_PROXY',\n 'NODE_USE_ENV_PROXY',\n 'HTTP_PROXY',\n 'HTTPS_PROXY',\n 'YARN_HTTP_PROXY',\n 'YARN_HTTPS_PROXY',\n 'NPM_CONFIG_HTTP_PROXY',\n 'NPM_CONFIG_HTTPS_PROXY',\n 'NPM_CONFIG_PROXY',\n 'BUNDLE_HTTP_PROXY',\n 'BUNDLE_HTTPS_PROXY',\n 'PIP_PROXY',\n 'DOCKER_HTTP_PROXY',\n 'DOCKER_HTTPS_PROXY',\n 'WS_PROXY',\n 'WSS_PROXY',\n 'NO_PROXY',\n 'NPM_CONFIG_NOPROXY',\n 'YARN_NO_PROXY',\n 'BUNDLE_NO_PROXY',\n 'ALL_PROXY',\n 'FTP_PROXY',\n]\n\n/** The CA-bundle variables Codex points at its managed proxy's bundle (network-proxy/src/certs.rs:157-169 `CUSTOM_CA_ENV_KEYS`). */\nconst CODEX_CA_ENV_KEYS: readonly string[] = [\n 'CODEX_CA_CERTIFICATE',\n 'SSL_CERT_FILE',\n 'REQUESTS_CA_BUNDLE',\n 'CURL_CA_BUNDLE',\n 'NODE_EXTRA_CA_CERTS',\n 'GIT_SSL_CAINFO',\n 'CARGO_HTTP_CAINFO',\n 'PIP_CERT',\n 'BUNDLE_SSL_CA_CERT',\n 'NPM_CONFIG_CAFILE',\n]\n\n/**\n * The managed proxy's generated trust bundle, in Codex's own form:\n * `<CODEX_HOME>/proxy/ca-bundle-<64 hex>.pem` (certs.rs:149-152, 434-455, 476).\n * Checked only while the parent's proxy marker is set, so a user's corporate\n * `SSL_CERT_FILE` (or one that merely sits in a folder named `proxy`) stays.\n */\nfunction isManagedCaBundle(value: string): boolean {\n return /[\\\\/]proxy[\\\\/]ca-bundle-[0-9a-fA-F]{64}\\.pem$/.test(value)\n}\n\n/** The managed proxy's `GIT_SSH_COMMAND` starts with this marker (proxy.rs `CODEX_PROXY_GIT_SSH_COMMAND_MARKER`). */\nconst CODEX_PROXY_GIT_SSH_MARKER = 'CODEX_PROXY_GIT_SSH_COMMAND=1 '\n\n/** Whether `key` is a parent session's variable by its name alone. Case-insensitive, as Windows names are. */\nexport function isParentSessionEnv(key: string): boolean {\n const upper = key.toUpperCase()\n if (upper.startsWith('CLAUDE_CODE_')) return !CLAUDE_CODE_ENV_KEPT.includes(upper)\n return CLAUDE_SESSION_ENV.includes(upper) || CODEX_SESSION_ENV.includes(upper)\n}\n\n/** The value of `name` in `env`, whatever its case. */\nfunction envValue(env: NodeJS.ProcessEnv, name: string): string | undefined {\n for (const [key, value] of Object.entries(env)) if (key.toUpperCase() === name) return value\n return undefined\n}\n\n/**\n * The variable names a Codex credential broker replaced with dummy values\n * (`CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS`: a JSON list of [name, dummy]),\n * where the environment still holds that dummy (credential_broker.rs:520-531).\n */\nfunction brokeredDummies(env: NodeJS.ProcessEnv): Set<string> {\n const marker = envValue(env, 'CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS')\n const out = new Set<string>()\n if (marker === undefined) return out\n let pairs: unknown\n try {\n pairs = JSON.parse(marker)\n } catch {\n return out\n }\n if (!Array.isArray(pairs)) return out\n for (const pair of pairs) {\n if (!Array.isArray(pair) || typeof pair[0] !== 'string' || typeof pair[1] !== 'string') continue\n if (envValue(env, pair[0].toUpperCase()) === pair[1]) out.add(pair[0].toUpperCase())\n }\n return out\n}\n\n/**\n * A copy of `env` without any Claude Code or Codex parent-session variable:\n * what every preset run, in every profile, starts from. By name: the session\n * markers above. By value: a parent Codex proxy's URLs and its generated CA\n * bundle (only while its marker says it was active), its SSH command, the\n * dummy credentials its broker substituted. The user's own proxy, CA bundle\n * and settings stay.\n */\nexport function withoutParentSession(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const proxyActive = envValue(env, 'CODEX_NETWORK_PROXY_ACTIVE') !== undefined\n const dummies = brokeredDummies(env)\n const copy: NodeJS.ProcessEnv = {}\n for (const [key, value] of Object.entries(env)) {\n const upper = key.toUpperCase()\n if (isParentSessionEnv(key)) continue\n if (proxyActive && CODEX_MANAGED_PROXY_ENV.includes(upper)) continue\n if (proxyActive && value !== undefined && CODEX_CA_ENV_KEYS.includes(upper) && isManagedCaBundle(value)) continue\n if (value !== undefined && upper === 'GIT_SSH_COMMAND' && value.startsWith(CODEX_PROXY_GIT_SSH_MARKER)) continue\n if (dummies.has(upper)) continue\n copy[key] = value\n }\n return copy\n}\n\n/** The environment a listener's preset runs inherit: the caller's, minus any `AGENTCHAT_API_KEY` in it. */\nexport function withoutInheritedKey(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const copy = { ...env }\n delete copy['AGENTCHAT_API_KEY']\n return copy\n}\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { clientHeadersOf } from '../client-identity.js'\nimport { hostedMcpUrl } from '../integration/mcp-probe.js'\nimport { workdirExposesHome, type RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, RunPreflightOptions, RunRequest, RunRunner } from '../integration/runner.js'\nimport { killProcessTree, redactDiagnostic, spawnRun } from '../integration/spawn-run.js'\nimport { atomicWriteFile } from '../util/fsutil.js'\nimport { log } from '../util/log.js'\nimport { spawnCommand } from '../util/spawn.js'\nimport { runProbe } from '../util/probe.js'\nimport { VERSION } from '../version.js'\nimport { semverAtLeast } from './semver.js'\nimport { RUNTIME_CHECK_DIR, runRuntimeCheck } from './runtime-check.js'\nimport { withoutInheritedKey, withoutParentSession, type Preset, type PresetContext, type PresetInspection } from './types.js'\n\n// ─── Codex: one headless run (`codex exec`) ─────────────────────────────────\n//\n// `codex exec` on the box, riding the user's own Codex sign-in and config. The\n// run's output is discarded by `spawnRun`. Flags, verified against `codex exec\n// --help` (codex-cli 0.154.0) and the openai/codex sources:\n//\n// -s, --sandbox read-only|workspace-write|danger-full-access\n// the sandbox policy for model-generated commands\n// --dangerously-bypass-approvals-and-sandbox\n// skip all confirmation prompts and run unsandboxed\n// -c approval_policy=\"never\" `codex exec` already defaults to `never` in\n// headless mode — passed explicitly so a run can\n// never wait on an approval, whatever a profile\n// or requirements file says.\n// -c mcp_servers.<name>.<key>=… per-run config overrides (TOML values): how a\n// listener points the hosted server at its own\n// agent's key, whatever config.toml registers.\n// --json events as JSONL on stdout (discarded; the first\n// event is how \"started\" is told from \"never got\n// going\")\n// --skip-git-repo-check the run's working directory is not a repository\n// --ephemeral no session files on disk for a wake run\n// -C <dir> the working root\n//\n// The hosted AgentChat tools reach the run through `[mcp_servers.agentchat]`\n// (bearer token from an environment variable named in the config, never the\n// key itself), with `default_tools_approval_mode = \"approve\"` so they never\n// prompt (with `approval_policy = \"never\"`, an MCP tool call that needs\n// approval is denied: codex-rs/core/src/mcp_tool_call.rs).\n//\n// `own` — the agent itself — passes no `--sandbox`, no `approval_policy`, no\n// `--disable` and no permission profile: the user's config.toml (and its\n// profiles, project layers and requirements) decides the sandbox, the web,\n// the tools and the instructions, as in their own `codex exec` runs. Nothing\n// waits on an approval all the same: `codex exec` sets `approval_policy =\n// \"never\"` itself unless the user's config hands approvals to Codex's\n// auto-review (a model, not a person), and it rejects every approval,\n// permission or user-input request a run makes instead of waiting\n// (exec/src/lib.rs at rust-v0.154.0: the headless `AskForApproval::Never`\n// override, `build_exec_config`, `handle_server_request`; verified on the real\n// 0.154.0 with `approval_policy = \"on-request\"` in the user's config: an\n// escalation was rejected at once). The only `-c` keys are AgentChat's own\n// server's (`mcp_servers.agentchat.*`). Codex's sandboxes restrict writes and\n// the network, never reads, so an `own` run's shell can read any file the\n// user can — the identity home's `credentials` included (README, known limits).\n//\n// `answer` — started by any peer's message — must read nothing outside its\n// workdir and have no way out but the AgentChat tools. Codex can restrict a\n// sandbox's READS (a permission profile: `default_permissions` +\n// `[permissions.<name>.filesystem]`), but a shell needs `\":minimal\"` to run at\n// all, and on macOS that also opens /etc, /usr, /Library/Preferences and, for\n// the shell process, read-write /tmp and /var/tmp\n// (codex-rs/sandboxing/src/seatbelt_read_only_platform_defaults.sbpl,\n// seatbelt.rs:27-33; on Linux /etc, /usr, /bin, … in linux-sandbox/src/bwrap.rs).\n// So `answer` has NO shell and no local-file tool (verified against the\n// openai/codex sources at rust-v0.154.0):\n//\n// --disable shell_tool no exec_command / write_stdin\n// (core/src/tools/spec_plan.rs:1083-1088;\n// `unified_exec` cannot be turned off by user\n// config, but it is registered only past\n// this check)\n// --disable view_image, image_generation\n// the image tools that read local files\n// --disable plugins, apps plugin-bundled MCP servers and skills (a\n// computer-use server among them) and the\n// ChatGPT connectors (`codex_apps`)\n// --disable memories the local memory store in CODEX_HOME\n// --disable browser_use, browser_use_external, computer_use, in_app_browser\n// no tool of their own in 0.154.0; off so a\n// later build cannot add one to `answer`\n// -c web_search=\"disabled\" the hosted web search (the top-level key;\n// `tools.web_search=false` is parsed and\n// ignored, config_toml.rs:655-670)\n// -c default_permissions=… + -c permissions.<name>.filesystem={ \":workspace_roots\" = \"read\" }\n// for what cannot be turned off: apply_patch\n// (no feature flag) reads through the sandbox,\n// so it reads only the workdir (`-C`), writes\n// nothing; no network. Replaces\n// `--sandbox read-only`, which reads the whole\n// disk ($CODEX_HOME/.env included).\n//\n// The runtime check (`checkRuntime`, runtime-check.ts) is one `codex exec`\n// with a fixed prompt, the same binary, CODEX_HOME and environment as the runs\n// (no key in it), in an empty folder of its own (`-C`), `--ephemeral`, closed\n// the way an `answer` run is where the 0.154.0 floor allows\n// (`codexRuntimeCheckArgs`):\n//\n// --sandbox read-only nothing written, no network for commands.\n// -c model_reasoning_effort=\"low\" a short answer fits the check's 45 s budget\n// (the runs keep the user's effort).\n// -c web_search=\"disabled\", --disable memories, plugins, apps\n// as an `answer` run: no web search, no local\n// memory, no plugin-bundled servers or skills,\n// no ChatGPT connectors.\n// -c mcp_servers.agentchat.url=<the runs' URL>, -c mcp_servers.agentchat.enabled=false\n// the hosted AgentChat server switched off\n// (with the URL the table is valid whether or\n// not a config layer defines one).\n//\n// The user's OTHER MCP servers still load: Codex 0.154.0 has no documented\n// switch that turns every MCP server off, and switching each off by name\n// (`-c mcp_servers.<name>.enabled=false`) needs the names first — a `codex\n// mcp list --json` per check, as an `answer` run does, which would add its own\n// time and failure to a 45 s probe whose prompt asks for no tool. Codex loads\n// `$CODEX_HOME/.env` itself: an AgentChat key that a Codex integration before\n// 0.5.3 left there is removed by the upgrade (and a listener's own runs do not\n// start while one is there, `ownAuthProblem`). The user's config.toml still\n// decides the model and its provider, as for the runs. Verified on 0.154.0\n// against a stand-in provider: these flags parse with and without an\n// `agentchat` table in config.toml; the model is offered no agentchat tool and\n// no web search, and is asked for low effort; a provider error exits 1 and an\n// answer exits 0.\n\nexport const CODEX_PRESET = 'codex'\n\n/** `--ephemeral`, `--sandbox`, `-C`, `--json` all exist on this version; older builds were not checked. */\nexport const MIN_CODEX_VERSION = '0.154.0'\n\n/** The `[mcp_servers.<name>]` table the runs use; tools are `mcp__agentchat__<tool>`, as the served texts spell them. */\nexport const CODEX_MCP_SERVER_NAME = 'agentchat'\n\n/**\n * The variable a listener's runs read the bearer token from. Deliberately not\n * `AGENTCHAT_API_KEY`: Codex loads `$CODEX_HOME/.env` at startup, where an\n * installed integration keeps ITS agent's key under that name.\n */\nexport const LISTENER_KEY_ENV = 'AGENTCHAT_LISTENER_API_KEY'\n\n/**\n * The final positional argument: `-` tells `codex exec` to read its\n * instructions from stdin (\"If not provided as an argument (or if `-` is\n * used), instructions are read from stdin\").\n */\nexport const CODEX_PROMPT_FROM_STDIN = '-'\n\n/** Codex's config root. Honouring CODEX_HOME matters: users relocate it. */\nexport function codexHomeFrom(env: NodeJS.ProcessEnv = process.env): string {\n const override = env['CODEX_HOME']\n if (override !== undefined && override.trim().length > 0) return path.resolve(override)\n return path.join(os.homedir(), '.codex')\n}\n\n/** How long a probe (`--version`, `login status`) may take; a hung one is killed with its whole tree (`runProbe`). */\nexport const CODEX_PROBE_TIMEOUT_MS = 10_000\n\nexport async function inspectCodexRuntime(codexHome: string, command = 'codex', timeoutMs = CODEX_PROBE_TIMEOUT_MS, signal?: AbortSignal): Promise<PresetInspection> {\n const result = await runProbe(command, ['--version'], { timeoutMs, env: { ...process.env, CODEX_HOME: codexHome }, ...(signal !== undefined ? { signal } : {}) })\n if (result.timedOut) return { ok: false, detail: `codex --version did not answer within ${Math.round(timeoutMs / 1000)} s (killed)` }\n if (signal?.aborted) return { ok: false, detail: 'codex --version was stopped' }\n if (result.error) return { ok: false, detail: `codex CLI not found on PATH (${result.error.message})` }\n const rendered = (result.stdout || result.stderr).trim()\n if (result.status !== 0) return { ok: false, detail: rendered || `codex --version exited ${result.status}` }\n return semverAtLeast(rendered, MIN_CODEX_VERSION)\n ? { ok: true, detail: rendered }\n : { ok: false, detail: `${rendered || 'unrecognized version'}; AgentChat requires Codex >= ${MIN_CODEX_VERSION}` }\n}\n\n/** `codex login status` exits 0 when signed in. */\nexport async function codexIsLoggedIn(codexHome: string, command = 'codex', timeoutMs = CODEX_PROBE_TIMEOUT_MS, signal?: AbortSignal): Promise<PresetInspection> {\n const status = await runProbe(command, ['login', 'status'], { timeoutMs, env: { ...process.env, CODEX_HOME: codexHome }, ...(signal !== undefined ? { signal } : {}) })\n if (status.error) return { ok: false, detail: status.error.message }\n const detail = `${status.stdout}${status.stderr}`.trim().slice(0, 200)\n return status.status === 0 ? { ok: true, detail: detail || 'signed in' } : { ok: false, detail: detail || 'codex is not signed in (run `codex login`)' }\n}\n\n/** The permission profile an `answer` run is given: its own name, so a user's profiles are never selected. */\nexport const CODEX_ANSWER_PERMISSIONS = 'agentchat_answer'\n\n/** Its filesystem table: read the workspace root (the `-C` workdir) and nothing else; no write anywhere. */\nexport const CODEX_ANSWER_FILESYSTEM = '{ \":workspace_roots\" = \"read\" }'\n\n/**\n * Codex features an `answer` run turns off: every model-visible tool that runs\n * a command, reads a local file or reaches out beside the hosted AgentChat\n * tools (see the header). Names as `codex features list` prints them (0.154.0).\n */\nexport const CODEX_ANSWER_DISABLED_FEATURES = [\n 'shell_tool',\n 'view_image',\n 'image_generation',\n 'plugins',\n 'apps',\n 'memories',\n 'browser_use',\n 'browser_use_external',\n 'computer_use',\n 'in_app_browser',\n] as const\n\nexport function codexProfileArgs(profile: RunProfile): string[] {\n switch (profile) {\n // The agent itself: nothing but the run's shape (see the header).\n case 'own':\n return []\n case 'answer':\n return [\n '-c',\n 'approval_policy=\"never\"',\n '-c',\n `default_permissions=\"${CODEX_ANSWER_PERMISSIONS}\"`,\n '-c',\n `permissions.${CODEX_ANSWER_PERMISSIONS}.filesystem=${CODEX_ANSWER_FILESYSTEM}`,\n '-c',\n 'web_search=\"disabled\"',\n // No project or ancestor AGENTS.md (core/src/agents_md.rs:65-67, 129: a\n // zero budget reads none). $CODEX_HOME/AGENTS.md has no such switch in\n // 0.154.0 (codex-home/src/instructions/mod.rs, wired unconditionally).\n '-c',\n 'project_doc_max_bytes=0',\n ...CODEX_ANSWER_DISABLED_FEATURES.flatMap((feature) => ['--disable', feature]),\n ]\n // `work` and `full` are the operator's explicit opt-in: a run started by\n // any peer's message can then read and change this machine.\n case 'work':\n return ['--sandbox', 'workspace-write', '-c', 'approval_policy=\"never\"']\n case 'full':\n return ['--dangerously-bypass-approvals-and-sandbox']\n }\n}\n\n/** The features a runtime check turns off, as an `answer` run does (names at the 0.154.0 floor). */\nexport const CODEX_RUNTIME_CHECK_DISABLED_FEATURES = ['memories', 'plugins', 'apps'] as const\n\n/**\n * The argv of a runtime check: `codex exec` in `dir` (an empty folder), the\n * read-only sandbox, no session files, low reasoning effort, no web search,\n * memories, plugins or connectors, and the hosted AgentChat server switched\n * off for it; the prompt on stdin, as for a run. `agentchatUrl` is the URL the\n * runs pin (with it, the `agentchat` table stays valid whether or not a config\n * layer defines one); without it a config layer must define the table, as the\n * runs need.\n */\nexport function codexRuntimeCheckArgs(dir: string, agentchatUrl?: string): string[] {\n const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`\n return [\n 'exec',\n '--json',\n '--skip-git-repo-check',\n '--ephemeral',\n '-C',\n dir,\n '--sandbox',\n 'read-only',\n '-c',\n 'model_reasoning_effort=\"low\"',\n '-c',\n 'web_search=\"disabled\"',\n ...CODEX_RUNTIME_CHECK_DISABLED_FEATURES.flatMap((feature) => ['--disable', feature]),\n ...(agentchatUrl !== undefined ? ['-c', `${table}.url=${JSON.stringify(agentchatUrl)}`] : []),\n '-c',\n `${table}.enabled=false`,\n CODEX_PROMPT_FROM_STDIN,\n ]\n}\n\n/** The empty folder a runtime check runs in, under CODEX_HOME. */\nexport function codexRuntimeCheckWorkdir(codexHome: string): string {\n return path.join(codexHome, RUNTIME_CHECK_DIR)\n}\n\n/** Where a run's hosted tool server points, and which variable carries its bearer token. */\nexport interface CodexMcpOverride {\n readonly url: string\n readonly keyEnv: string\n /**\n * A headers helper command (`http_headers_helper`) in place of the bearer\n * variable: the run's environment then carries no key. A listener's `own`\n * runs use one (`codexListenerHeadersHelperPath`): with the user's own\n * shell, an environment variable is one `env` away.\n */\n readonly headersHelper?: string\n /** The version named in `X-AgentChat-Client-Version` (the front door that placed the run). Defaults to this engine's. */\n readonly clientVersion?: string\n}\n\n/**\n * `{\"X-AgentChat-Client\" = \"codex\", \"X-AgentChat-Client-Version\" = \"<version>\"}`:\n * the client headers that name the runtime to the hosted tool server, as a\n * TOML inline table for `-c …http_headers=`. Codex parses a `-c` value as\n * TOML (inline tables included) since before 0.154.0, and sends\n * `http_headers` on every request to a streamable-HTTP server. Without them\n * a run is an unknown client and is shown the wake-webhook tools.\n */\nexport function codexClientHeadersToml(clientVersion: string = VERSION): string {\n const pairs = Object.entries(clientHeadersOf({ runtime: 'codex', version: clientVersion })).map(([name, value]) => `${JSON.stringify(name)} = ${JSON.stringify(value)}`)\n return `{ ${pairs.join(', ')} }`\n}\n\n/** `-c mcp_servers.agentchat.url=\"<url>\"`: the hosted server's URL pinned for one run, whatever another config layer says. */\nexport function codexPinnedUrlArgs(url: string): string[] {\n return ['-c', `mcp_servers.${CODEX_MCP_SERVER_NAME}.url=${JSON.stringify(url)}`]\n}\n\n/** The `-c` overrides that make `[mcp_servers.agentchat]` this agent's, for one run. TOML values, no key in them. */\nexport function codexMcpOverrideArgs(override: CodexMcpOverride): string[] {\n const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`\n return [\n '-c',\n `${table}.url=${JSON.stringify(override.url)}`,\n '-c',\n override.headersHelper !== undefined ? `${table}.http_headers_helper=${JSON.stringify(override.headersHelper)}` : `${table}.bearer_token_env_var=${JSON.stringify(override.keyEnv)}`,\n '-c',\n `${table}.default_tools_approval_mode=\"approve\"`,\n '-c',\n `${table}.http_headers=${codexClientHeadersToml(override.clientVersion ?? VERSION)}`,\n ]\n}\n\n/**\n * The full argument list for one headless run. The prompt is NOT an argument:\n * the runner writes it to stdin and closes it. An argument cannot carry it on\n * Windows — npm installs codex as a `.cmd` shim, cross-spawn runs that through\n * cmd.exe, and cmd.exe ends the command at the first line break, so every line\n * after the first was silently dropped (caught by CI on windows-latest).\n */\nexport function codexRunArgs(profile: RunProfile, options: { workdir: string; mcp?: CodexMcpOverride }): string[] {\n return [\n 'exec',\n '--json',\n '--skip-git-repo-check',\n '--ephemeral',\n '-C',\n options.workdir,\n ...codexProfileArgs(profile),\n ...(options.mcp !== undefined ? codexMcpOverrideArgs(options.mcp) : []),\n CODEX_PROMPT_FROM_STDIN,\n ]\n}\n\nexport interface CodexRunnerOptions {\n readonly codexHome: string\n /** The run's working root (`-C`); the `work` profile may write here. */\n readonly workdir: string\n readonly profile: RunProfile\n /** The agent's key, read per run (a credential change between runs is followed). Null: none is set. */\n readonly apiKey: () => string | null\n /** The variable the key is set under in the run's environment. */\n readonly keyEnv: string\n /** Point the hosted server at this agent for each run (`-c` overrides); absent, config.toml decides. */\n readonly mcp?: CodexMcpOverride\n /**\n * Without `mcp` (an integration's own runs): the hosted server's URL\n * (`<api base>/mcp`), pinned on every run with `-c mcp_servers.agentchat.url=…`\n * so no other config layer — a trusted project's `.codex/config.toml`\n * among them — can point the agentchat server, and the key its bearer\n * variable carries, anywhere else. A layer that gives it a `command`\n * instead makes the merged table invalid: the run does not start.\n */\n readonly pinMcpUrl?: string\n /** Test seam: the binary to run. */\n readonly command?: string\n readonly env?: NodeJS.ProcessEnv\n /** Test seam: how long `codex mcp list` may take (`CODEX_MCP_LIST_TIMEOUT_MS`). */\n readonly mcpListTimeoutMs?: number\n /** Why no run may start (preflight and every run say it); absent: runs start. */\n readonly refuse?: string\n}\n\n/**\n * The folder an `own` or `answer` run works in when its configured workdir is\n * the user's home folder or contains it (`workdirExposesHome`): an empty folder\n * of its own under CODEX_HOME. The run keeps working — it only cannot reach the\n * user's files through its workspace root. An `own` run needs this as much: a\n * user's `workspace-write` sandbox would let a peer-started run write anywhere\n * under the workspace root, which would be the whole home.\n */\nexport function codexAnswerFallbackWorkdir(codexHome: string): string {\n return path.join(codexHome, 'agentchat-answer-workdir')\n}\n\n/** How long `codex mcp list` may take before an answer run is given up (not started). */\nexport const CODEX_MCP_LIST_TIMEOUT_MS = 20_000\n/** After a listing is killed: how long to wait for it to have exited (it holds the workdir) before it is given up on. */\nexport const CODEX_MCP_LIST_KILL_WAIT_MS = 10_000\n/** The most `codex mcp list --json` output read; more is a failure, not a truncation. */\nconst CODEX_MCP_LIST_MAX_BYTES = 1024 * 1024\n\n/**\n * A server name a `-c mcp_servers.<name>.enabled=false` override can address.\n * Codex splits a `-c` key on every `.` (codex-rs/config/src/overrides.rs) and\n * the value at the first `=`, but allows `.` in a server name\n * (codex-mcp/src/rmcp_client.rs: `^[a-zA-Z0-9_:@/.-]+$`).\n */\nexport function codexServerNameAddressable(name: string): boolean {\n return /^[A-Za-z0-9_:@/-]+$/.test(name)\n}\n\n/**\n * The names of the MCP servers `codex mcp list --json` reports enabled, or why\n * that output cannot be trusted. Names only: an entry's transport can carry\n * header and env values, and none of it is kept.\n */\nexport function parseCodexMcpList(stdout: string): { ok: true; names: string[] } | { ok: false; detail: string } {\n let parsed: unknown\n try {\n parsed = JSON.parse(stdout)\n } catch {\n return { ok: false, detail: 'its output is not JSON' }\n }\n if (!Array.isArray(parsed)) return { ok: false, detail: 'its output is not a list' }\n const names: string[] = []\n for (const entry of parsed) {\n const name = (entry as { name?: unknown } | null)?.name\n const enabled = (entry as { enabled?: unknown } | null)?.enabled\n if (typeof name !== 'string' || name.length === 0) return { ok: false, detail: 'an entry has no name' }\n if (enabled !== false) names.push(name)\n }\n return { ok: true, names }\n}\n\n/**\n * What the `agentchat` entry of `codex mcp list --json` would authenticate\n * with besides a headers helper: `bearer_token_env_var`, or an `Authorization`\n * in `env_http_headers` (names only, never values). Codex sends either in\n * place of the helper's `Authorization` (\"Helper Authorization is used only\n * when the request has no explicit bearer/OAuth credential\",\n * rmcp-client/src/http_headers.rs). A static `http_headers` is not counted:\n * a listener's run replaces that whole table. An entry the list does not\n * have authenticates with nothing else.\n */\nexport function codexAgentchatExplicitAuth(stdout: string): { ok: true; keys: string[] } | { ok: false; detail: string } {\n let parsed: unknown\n try {\n parsed = JSON.parse(stdout)\n } catch {\n return { ok: false, detail: 'its output is not JSON' }\n }\n if (!Array.isArray(parsed)) return { ok: false, detail: 'its output is not a list' }\n const entry = parsed.find((e) => (e as { name?: unknown } | null)?.name === CODEX_MCP_SERVER_NAME) as { transport?: unknown } | undefined\n const transport = entry?.transport !== null && typeof entry?.transport === 'object' ? (entry.transport as Record<string, unknown>) : {}\n const keys: string[] = []\n const bearer = transport['bearer_token_env_var']\n if (typeof bearer === 'string' && bearer.length > 0) keys.push('bearer_token_env_var')\n const envHeaders = transport['env_http_headers']\n if (envHeaders !== null && typeof envHeaders === 'object' && Object.keys(envHeaders).some((name) => name.toLowerCase() === 'authorization')) keys.push('env_http_headers.Authorization')\n return { ok: true, keys }\n}\n\n/** The key variables a `.env` file sets (`AGENTCHAT_API_KEY`, `LISTENER_KEY_ENV`): names only. Codex loads `$CODEX_HOME/.env` into its own environment, and a run's commands inherit it. */\nexport function codexDotEnvKeyNames(content: string): string[] {\n const names = new Set<string>()\n for (const line of content.split(/\\r?\\n/)) {\n const match = /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*['\"]?\\S/.exec(line)\n if (match?.[1] === 'AGENTCHAT_API_KEY' || match?.[1] === LISTENER_KEY_ENV) names.add(match[1])\n }\n return [...names]\n}\n\n/**\n * `-c mcp_servers.<name>.enabled=false` for every listed server but AgentChat's,\n * or why that cannot be done. Only names Codex listed: an override for a server\n * no config layer defines is a config error (\"invalid transport\").\n */\nexport function codexMcpDisableArgs(names: readonly string[]): { ok: true; args: string[] } | { ok: false; detail: string } {\n const args: string[] = []\n for (const name of names) {\n if (name === CODEX_MCP_SERVER_NAME) continue\n if (!codexServerNameAddressable(name)) {\n return { ok: false, detail: `the MCP server \"${name}\" cannot be switched off for one run (Codex reads a \".\" in a -c key as a table); rename it or remove it` }\n }\n args.push('-c', `mcp_servers.${name}.enabled=false`)\n }\n return { ok: true, args }\n}\n\n/** Why an answer run does not start when Codex's MCP servers cannot be listed (or one cannot be switched off). */\nfunction codexAnswerListingRefusal(detail: string): string {\n return `could not list Codex's MCP servers (\\`codex mcp list --json\\` with the answer flags: ${detail}); an answer run starts only with every server but ${CODEX_MCP_SERVER_NAME} switched off`\n}\n\n/** How long a listing is reused while none of the files it was read from changed (layers that are not files: a cloud bundle). */\nexport const CODEX_MCP_LIST_MAX_AGE_MS = 60 * 60_000\n\n/**\n * The config files `codex mcp list` (and the run) read, in the loader's order\n * (openai/codex rust-v0.154.0 config/src/loader/mod.rs:79-95, 800-841,\n * layer_io.rs:22, 78-92, loader/macos.rs:20):\n *\n * * system: `/etc/codex/config.toml`, the legacy `/etc/codex/managed_config.toml`\n * and `/etc/codex/requirements.toml`; on Windows `<ProgramData>\\OpenAI\\Codex\\`\n * `config.toml` and `requirements.toml` (the ProgramData known folder,\n * `C:\\ProgramData` when it cannot be resolved; `CODEX_HOME\\managed_config.toml`\n * is ignored there),\n * * macOS managed preferences (`com.openai.codex`),\n * * the user's `$CODEX_HOME/config.toml`,\n * * `config.toml` in the workdir and `.codex/config.toml` from the workdir up\n * to its root (a drive root on Windows).\n *\n * Paths are built for `platform` (its own separators and roots), whatever the\n * host: the list is what that platform's Codex reads.\n */\nexport function codexConfigLayerFiles(codexHome: string, workdir: string, platform: NodeJS.Platform = process.platform, env: NodeJS.ProcessEnv = process.env): string[] {\n const p = platform === 'win32' ? path.win32 : path.posix\n const programData = env['ProgramData'] ?? env['PROGRAMDATA'] ?? 'C:\\\\ProgramData'\n const system =\n platform === 'win32'\n ? [p.join(programData, 'OpenAI', 'Codex', 'config.toml'), p.join(programData, 'OpenAI', 'Codex', 'requirements.toml')]\n : ['/etc/codex/config.toml', '/etc/codex/managed_config.toml', '/etc/codex/requirements.toml']\n const user = (() => {\n try {\n return os.userInfo().username\n } catch {\n return null\n }\n })()\n const managedPrefs =\n platform === 'darwin'\n ? ['/Library/Managed Preferences/com.openai.codex.plist', ...(user !== null ? [p.join('/Library/Managed Preferences', user, 'com.openai.codex.plist')] : [])]\n : []\n const tree: string[] = []\n let current = p.resolve(workdir)\n tree.push(p.join(current, 'config.toml'))\n for (;;) {\n tree.push(p.join(current, '.codex', 'config.toml'))\n const parent = p.dirname(current)\n if (parent === current) break\n current = parent\n }\n return [...system, ...managedPrefs, p.join(codexHome, 'config.toml'), ...tree]\n}\n\n/** What the listing depends on: every layer file's size and mtime (or its absence), the flags, the workdir, the binary. */\nfunction codexListingKey(files: readonly string[], parts: readonly string[]): string {\n const stats = files.map((file) => {\n try {\n const st = fs.statSync(file)\n return `${file}\\u0000${st.size}\\u0000${st.mtimeMs}`\n } catch {\n return `${file}\\u0000-`\n }\n })\n return [...parts, ...stats].join('\\u0001')\n}\n\nexport class CodexRunner implements RunRunner {\n readonly name = 'codex'\n readonly label = 'Codex'\n private readonly command: string\n private warnedHome = false\n /** The last good listing and what it depended on: a stranger's DM does not cost a listing (and its contacts to the user's MCP hosts) on every run. */\n private listing: { key: string; at: number; result: { ok: true; args: string[] } } | null = null\n /** The last listing that showed a listener's own run authenticates with its helper alone (`ownAuthProblem`). */\n private ownListing: { key: string; at: number } | null = null\n\n constructor(private readonly options: CodexRunnerOptions) {\n this.command = options.command ?? 'codex'\n }\n\n /**\n * Where this runner's runs work (`-C`): the configured workdir, except that an\n * `own` or `answer` run never has the home folder or above it as its\n * workspace root — it gets `codexAnswerFallbackWorkdir`.\n */\n workdir(): string {\n if ((this.options.profile === 'answer' || this.options.profile === 'own') && workdirExposesHome(this.options.workdir)) return codexAnswerFallbackWorkdir(this.options.codexHome)\n return this.options.workdir\n }\n\n async preflight(options: RunPreflightOptions = {}): Promise<RunPreflight> {\n if (this.options.refuse !== undefined) return { ok: false, detail: this.options.refuse }\n const runtime = await inspectCodexRuntime(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n const auth = await codexIsLoggedIn(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal)\n if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` }\n if (this.workdir() !== this.options.workdir && !this.warnedHome) {\n this.warnedHome = true\n log.warn(`the run workdir ${this.options.workdir} is your home folder or contains it: ${this.options.profile} runs work in ${this.workdir()} instead, so a peer-started run reaches none of your files there. Point the workdir at a folder of its own to choose another.`)\n }\n fs.mkdirSync(this.workdir(), { recursive: true })\n if (this.options.profile === 'answer') {\n // Said up front, not only as a run's detail: a Codex that rejects one of\n // the answer flags, or a server no `-c` key can switch off, stops every\n // answer run.\n const disables = await this.answerMcpDisables()\n if (!disables.ok) return { ok: false, detail: codexAnswerListingRefusal(disables.detail) }\n }\n // Said up front as well: a listener's own run that would carry or use another key.\n const ownProblem = await this.ownAuthProblem()\n if (ownProblem !== null) return { ok: false, detail: ownProblem }\n return { ok: true }\n }\n\n /** The exact argv one run uses — exported for tests to pin per profile. An `answer` run adds `answerMcpDisables()` before the prompt. */\n args(): string[] {\n const args = codexRunArgs(this.options.profile, { workdir: this.workdir(), ...(this.options.mcp !== undefined ? { mcp: this.options.mcp } : {}) })\n if (this.options.mcp !== undefined || this.options.pinMcpUrl === undefined) return args\n // The prompt stays the last positional.\n return [...args.slice(0, -1), ...codexPinnedUrlArgs(this.options.pinMcpUrl), CODEX_PROMPT_FROM_STDIN]\n }\n\n /**\n * The child environment: Codex's home and the key the hosted server needs,\n * under the configured name. An `own` run gets no key at all — not the\n * configured one, not an `AGENTCHAT_API_KEY` the daemon inherited: it has\n * the user's own shell, and Codex hands a run's commands its environment.\n * Its hosted server authenticates through a headers helper instead.\n */\n env(): NodeJS.ProcessEnv {\n // Nothing of a parent Claude Code or Codex session, in every profile.\n const env: NodeJS.ProcessEnv = { ...withoutParentSession(this.options.env ?? process.env), CODEX_HOME: this.options.codexHome }\n if (this.options.profile === 'own') {\n delete env['AGENTCHAT_API_KEY']\n delete env[this.options.keyEnv]\n return env\n }\n const key = this.options.apiKey()\n if (key !== null) env[this.options.keyEnv] = key\n return env\n }\n\n /**\n * For an `answer` run: `-c mcp_servers.<name>.enabled=false` for every MCP\n * server the run would load but AgentChat's — the user's own in config.toml,\n * a project's, a managed one. Codex has no \"only this server\" switch, and a\n * tool such a server marks read-only runs without approval. Asked of Codex\n * itself (`codex mcp list --json`, with the run's own `-c`/`--disable`\n * flags, from the run's workdir), so every layer is counted. Any failure —\n * an error, a timeout, output that is not the list — means no run.\n */\n async answerMcpDisables(): Promise<{ ok: true; args: string[] } | { ok: false; detail: string }> {\n const { flags, key } = this.listingFlags()\n // Reused while nothing it was read from changed (and for at most an hour);\n // a failure is never cached, so the next run asks again.\n if (this.listing !== null && this.listing.key === key && Date.now() - this.listing.at < CODEX_MCP_LIST_MAX_AGE_MS) return this.listing.result\n const listed = await this.listMcpServers(flags)\n if (!listed.ok) return listed\n const parsed = parseCodexMcpList(listed.stdout)\n if (!parsed.ok) return parsed\n const result = codexMcpDisableArgs(parsed.names)\n if (result.ok) this.listing = { key, at: Date.now(), result }\n return result\n }\n\n /**\n * For a listener's `own` run (its key from a headers helper, none in its\n * environment): why it must not start, or null. Two things would make it\n * carry or use a key that is not the helper's — another agent's, as a\n * Codex integration from 0.5.2 or earlier left them: `$CODEX_HOME/.env`\n * setting a key variable (Codex loads it into the run's environment), and an\n * `agentchat` entry that names `bearer_token_env_var` or an `Authorization`\n * in `env_http_headers` in any config layer (Codex sends that in place of the\n * helper's: the run would act as that other agent). The entry is asked of\n * Codex itself (`codex mcp list --json` with the run's own flags, cached as\n * an answer run's listing is); a listing that fails means no run.\n */\n async ownAuthProblem(): Promise<string | null> {\n if (this.options.profile !== 'own' || this.options.mcp?.headersHelper === undefined) return null\n const dotenv = path.join(this.options.codexHome, '.env')\n let names: string[] = []\n try {\n names = codexDotEnvKeyNames(fs.readFileSync(dotenv, 'utf-8'))\n } catch {\n names = []\n }\n if (names.length > 0) {\n return `${dotenv} sets ${names.join(' and ')}: Codex loads that file into every run's environment, so this listener's own runs would carry that key. An AgentChat Codex integration from 0.5.2 or earlier left it there (\\`npx -y @agentchatme/codex doctor --fix\\` takes it out); remove the line, or run this listener with --profile answer`\n }\n const { flags, key } = this.listingFlags()\n if (this.ownListing !== null && this.ownListing.key === key && Date.now() - this.ownListing.at < CODEX_MCP_LIST_MAX_AGE_MS) return null\n const listed = await this.listMcpServers(flags)\n const auth = listed.ok ? codexAgentchatExplicitAuth(listed.stdout) : listed\n if (!auth.ok) {\n return `could not list Codex's MCP servers (\\`codex mcp list --json\\` with the own run's flags: ${auth.detail}); a listener's own run starts only once Codex confirms its ${CODEX_MCP_SERVER_NAME} server sends this listener's key`\n }\n if (auth.keys.length > 0) {\n return `the [mcp_servers.${CODEX_MCP_SERVER_NAME}] Codex loads for these runs sets ${auth.keys.join(' and ')}: Codex sends that credential in place of this listener's headers helper, so its own runs would act as another agent. An AgentChat Codex integration from 0.5.2 or earlier wrote bearer_token_env_var (\\`npx -y @agentchatme/codex doctor --fix\\` replaces it); remove it, or run this listener with --profile answer`\n }\n this.ownListing = { key, at: Date.now() }\n return null\n }\n\n /** The run's config flags (`-c <v>` and `--disable <feature>` pairs) and what a listing of them depends on. */\n private listingFlags(): { flags: string[]; key: string } {\n const run = this.args()\n const flags = run.flatMap((arg, i) => (run[i - 1] === '-c' || run[i - 1] === '--disable' ? [run[i - 1] as string, arg] : []))\n return { flags, key: codexListingKey(codexConfigLayerFiles(this.options.codexHome, this.workdir()), [this.command, this.workdir(), ...flags]) }\n }\n\n /** `codex mcp list --json <flags>` from the run's workdir, with the run's environment: its output, or why there is none. Killed with its whole tree past its time. */\n private async listMcpServers(flags: string[]): Promise<{ ok: true; stdout: string } | { ok: false; detail: string }> {\n return new Promise<{ ok: true; stdout: string } | { ok: false; detail: string }>((resolve) => {\n let child: ReturnType<typeof spawnCommand>\n try {\n child = spawnCommand(this.command, ['mcp', 'list', '--json', ...flags], {\n cwd: this.workdir(),\n env: this.env(),\n stdio: ['ignore', 'pipe', 'pipe'],\n // Its own process group on POSIX, so a hung listing is killed with\n // everything it started (the npm launcher and the native binary).\n detached: process.platform !== 'win32',\n windowsHide: true,\n })\n } catch (err) {\n resolve({ ok: false, detail: err instanceof Error ? err.message : String(err) })\n return\n }\n const proc = child\n let stdout = ''\n let stderr = ''\n let stopped: string | null = null\n let settled = false\n let abandonTimer: NodeJS.Timeout | null = null\n const settle = (result: { ok: true; stdout: string } | { ok: false; detail: string }): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n if (abandonTimer !== null) clearTimeout(abandonTimer)\n resolve(result)\n }\n // A listing that has to be stopped: the whole tree (taskkill /T /F on\n // Windows, where the shim and the real process differ), and the answer\n // waits for it to have exited — it holds the workdir as its cwd. A tree\n // that will not die is given up on after a bound, not waited on forever.\n const stop = (why: string): void => {\n if (stopped !== null) return\n stopped = why\n killProcessTree(proc, 'SIGKILL')\n abandonTimer = setTimeout(() => settle({ ok: false, detail: `${why} (and it did not exit after being killed)` }), CODEX_MCP_LIST_KILL_WAIT_MS)\n }\n proc.stderr?.on('data', (chunk: Buffer) => {\n if (stderr.length < 4096) stderr += chunk.toString('utf-8')\n })\n const timeoutMs = this.options.mcpListTimeoutMs ?? CODEX_MCP_LIST_TIMEOUT_MS\n const timer = setTimeout(() => stop(`no answer within ${Math.round(timeoutMs / 1000)} s`), timeoutMs)\n proc.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf-8')\n if (stdout.length > CODEX_MCP_LIST_MAX_BYTES) stop('its output is too long')\n })\n proc.on('error', (err) => {\n if (stopped === null) settle({ ok: false, detail: err.message })\n })\n proc.on('close', (code) => {\n if (stopped !== null) {\n settle({ ok: false, detail: stopped })\n return\n }\n // Codex's own complaint, first line, bounded and redacted (e.g. \"Unknown feature flag: …\").\n const said = redactDiagnostic(stderr.split(/\\r?\\n/).find((line) => line.trim().length > 0) ?? '', 200)\n if (code !== 0) settle({ ok: false, detail: `it exited ${code}${said ? `: ${said}` : ''}` })\n else settle({ ok: true, stdout })\n })\n })\n }\n\n /**\n * Does the model answer right now, through this runner's binary, sign-in,\n * CODEX_HOME and environment? One `codex exec` with a fixed prompt in its\n * own empty folder, read-only, with the hosted AgentChat server switched off\n * (`codexRuntimeCheckArgs`) and no key in its environment. Its output is\n * discarded. Never throws.\n */\n async checkRuntime(options: RunPreflightOptions = {}): Promise<RunPreflight> {\n if (this.options.refuse !== undefined) return { ok: false, detail: this.options.refuse }\n const dir = codexRuntimeCheckWorkdir(this.options.codexHome)\n return runRuntimeCheck({\n label: 'codex',\n command: this.command,\n args: codexRuntimeCheckArgs(dir, this.options.mcp?.url ?? this.options.pinMcpUrl),\n cwd: dir,\n // The runs' environment; runRuntimeCheck takes every key variable out, this runner's own included.\n env: this.env(),\n keyEnv: this.options.keyEnv,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n })\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const startedAt = Date.now()\n if (this.options.refuse !== undefined) return { state: 'not_started', exitCode: null, durationMs: 0, detail: this.options.refuse }\n let args = this.args()\n if (this.options.profile === 'answer') {\n // Fail closed: an answer run starts only with every MCP server but AgentChat's switched off.\n const disables = await this.answerMcpDisables()\n if (!disables.ok) return { state: 'not_started', exitCode: null, durationMs: Date.now() - startedAt, detail: codexAnswerListingRefusal(disables.detail) }\n args = [...args.slice(0, -1), ...disables.args, CODEX_PROMPT_FROM_STDIN]\n }\n // Fail closed: a listener's own run starts only when it would act as the listener's agent, with no key in its environment.\n const ownProblem = await this.ownAuthProblem()\n if (ownProblem !== null) return { state: 'not_started', exitCode: null, durationMs: Date.now() - startedAt, detail: ownProblem }\n log.debug(`codex ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId}${request.conversationId !== undefined ? ` for ${request.conversationId}` : ''})`)\n return spawnRun({\n command: this.command,\n args,\n cwd: this.workdir(),\n env: this.env(),\n // Written to stdin and then closed: `codex exec -` reads its\n // instructions until EOF. Never as an argument (see codexRunArgs).\n stdin: request.prompt,\n budgetMs: request.budgetMs,\n ...(request.signal ? { signal: request.signal } : {}),\n ...(request.onStarted ? { onStarted: request.onStarted } : {}),\n })\n }\n}\n\n// ─── A listener's own runs: the key from a headers helper, not the environment ─\n//\n// An `own` run has the user's own shell, and Codex hands a run's commands its\n// whole environment (`shell_environment_policy` inherits everything in\n// 0.154.0). So a listener's `own` runs carry no key there: `[mcp_servers.agentchat]`\n// gets `http_headers_helper` — \"Local-only shell command that prints a JSON\n// object of dynamic HTTP headers\" (codex-rs config/src/mcp_types.rs), run with\n// `sh -c` (`cmd /Q /D /C` on Windows) on each connection and again after a\n// 401/403, its `Authorization` used when the server names no bearer token\n// (rmcp-client/src/http_headers.rs) — and the helper reads the listener home's\n// `credentials` itself. The same mechanism the Codex integration places.\n\n/** Where a listener's `own` runs' headers helper lives: `<home>/presets/codex.mcp-headers.mjs` (owner-only; it holds no key). */\nexport function codexListenerHeadersHelperPath(home: string): string {\n return path.join(home, 'presets', `${CODEX_PRESET}.mcp-headers.mjs`)\n}\n\n/**\n * The helper, byte for byte. It reads the `credentials` file of the home whose\n * `presets/` it sits in and nothing else (no environment variable: the\n * identity is the home's), prints `{\"Authorization\":\"Bearer <key>\"}`, or `{}`\n * when there is no key, and never fails.\n */\nexport const CODEX_LISTENER_HEADERS_HELPER_SOURCE = [\n \"// Written by @agentchatme/agent-core for a listener's Codex runs. Codex runs this on each\",\n '// connection to the MCP server \"agentchat\" (its http_headers_helper) and sends what it prints',\n '// as headers: the Authorization header for the key in the credentials file of this identity',\n '// home, or nothing when there is none. It reads no environment variable. Do not edit: the',\n '// listener rewrites it.',\n \"import { readFileSync } from 'node:fs'\",\n 'let headers = {}',\n 'try {',\n \" const creds = JSON.parse(readFileSync(new URL('../credentials', import.meta.url), 'utf8'))\",\n \" const key = creds !== null && typeof creds.api_key === 'string' ? creds.api_key.trim() : ''\",\n ' if (key.length >= 20 && !/\\\\s/.test(key)) headers = { Authorization: `Bearer ${key}` }',\n '} catch {}',\n 'process.stdout.write(JSON.stringify(headers))',\n '',\n].join('\\n')\n\n/**\n * The helper command: this Node and the script, each quoted for the shell\n * Codex runs it in — single quotes on POSIX (`sh -c`; a `'` inside written as\n * `'\\\\''`), double quotes on Windows (`cmd /C`). Null when a path holds what\n * that quoting cannot carry (`\"`, `%`, `$` or a backtick on Windows) or a line\n * break anywhere.\n */\nexport function codexHeadersHelperCommand(script: string, node: string = process.execPath, platform: NodeJS.Platform = process.platform): string | null {\n const paths = [node, script]\n if (paths.some((p) => /[\\r\\n]/.test(p))) return null\n if (platform === 'win32') return paths.some((p) => /[\"%$`]/.test(p)) ? null : paths.map((p) => `\"${p}\"`).join(' ')\n return paths.map((p) => `'${p.replace(/'/g, `'\\\\''`)}'`).join(' ')\n}\n\n/**\n * The keys of `[mcp_servers.agentchat]` in a config.toml, or null when the\n * table is absent. Keys only — a value can be a secret. A line scan, not a\n * TOML parser: enough to say what a run's `-c` overrides merge over.\n */\nexport function agentchatTableKeys(configToml: string): string[] | null {\n const lines = configToml.split(/\\r?\\n/)\n const header = new RegExp(`^\\\\s*\\\\[mcp_servers\\\\.${CODEX_MCP_SERVER_NAME}\\\\]\\\\s*(#.*)?$`)\n const start = lines.findIndex((line) => header.test(line))\n if (start < 0) return null\n const keys: string[] = []\n for (const line of lines.slice(start + 1)) {\n if (/^\\s*\\[/.test(line)) break\n const match = /^\\s*([A-Za-z0-9_.-]+)\\s*=/.exec(line)\n if (match?.[1] !== undefined) keys.push(match[1])\n }\n return keys\n}\n\nexport const codexPreset: Preset = {\n name: CODEX_PRESET,\n describeMcp({ home, apiBase, env = process.env, profile }) {\n const file = path.join(codexHomeFrom(env), 'config.toml')\n let own: string[] | null = null\n try {\n own = agentchatTableKeys(fs.readFileSync(file, 'utf-8'))\n } catch {\n own = null\n }\n return [\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.url=\"${hostedMcpUrl(apiBase)}\"`,\n profile === 'own'\n ? `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.http_headers_helper=<node> ${codexListenerHeadersHelperPath(home)} (own: reads this home's credentials on each connection; no key in the run's environment or on argv; no run while $CODEX_HOME/.env sets a key or the merged ${CODEX_MCP_SERVER_NAME} entry names bearer_token_env_var)`\n : `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.bearer_token_env_var=\"${LISTENER_KEY_ENV}\" (the key set in the run's environment, never on argv)`,\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.default_tools_approval_mode=\"approve\"`,\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.http_headers={ \"X-AgentChat-Client\" = \"codex\", \"X-AgentChat-Client-Version\" = <the listener's version> } (names the runtime to the hosted tools)`,\n own === null\n ? `${file}: no [mcp_servers.${CODEX_MCP_SERVER_NAME}] of its own — the run sees only the overrides above`\n : `${file}: [mcp_servers.${CODEX_MCP_SERVER_NAME}] also sets ${own.length > 0 ? own.join(', ') : 'nothing'}; the overrides above replace their keys, the others still apply (how codex merges -c over an existing table is not verified on a real codex)`,\n ]\n },\n label: 'Codex',\n runtime: 'codex',\n serviceEnv: ['CODEX_HOME'],\n // `own`, `work` and `full` read the whole filesystem (Codex's sandboxes never\n // restrict reads; an `answer` run reads only its workdir): true, because the\n // field is one for every profile.\n readsIdentityHome: true,\n async inspect(env = process.env, command = 'codex') {\n const home = codexHomeFrom(env)\n const runtime = await inspectCodexRuntime(home, command)\n if (!runtime.ok) return runtime\n const auth = await codexIsLoggedIn(home, command)\n return auth.ok ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in: ${auth.detail}` }\n },\n runner(ctx: PresetContext): RunRunner {\n // A key in the listener's own environment is not handed to its runs.\n const env = withoutInheritedKey(ctx.env ?? process.env)\n const apiKey = ctx.apiKey\n const base = {\n codexHome: codexHomeFrom(env),\n workdir: ctx.workdir,\n profile: ctx.profile,\n keyEnv: LISTENER_KEY_ENV,\n ...(ctx.command !== undefined ? { command: ctx.command } : {}),\n env,\n }\n const mcp = { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV, clientVersion: ctx.clientVersion ?? VERSION }\n if (ctx.profile !== 'own') return new CodexRunner({ ...base, apiKey: () => apiKey, mcp })\n // own: the user's shell is the run's, so no key in its environment — the\n // helper reads this home's credentials (rewritten for every identity the\n // listener serves; it holds no key).\n const script = codexListenerHeadersHelperPath(ctx.home)\n const helper = codexHeadersHelperCommand(script)\n if (helper === null) {\n return new CodexRunner({ ...base, apiKey: () => null, mcp, refuse: `the path of Node (${process.execPath}) or of ${script} holds a character a shell command cannot carry quoted: an own run would have its key in its environment instead` })\n }\n try {\n atomicWriteFile(script, CODEX_LISTENER_HEADERS_HELPER_SOURCE, 0o600)\n } catch (err) {\n return new CodexRunner({ ...base, apiKey: () => null, mcp, refuse: `could not write the headers helper ${script}: ${err instanceof Error ? err.message : String(err)}` })\n }\n return new CodexRunner({ ...base, apiKey: () => null, mcp: { ...mcp, headersHelper: helper } })\n },\n}\n","// ─── @agentchatme/agent-core/presets ────────────────────────────────────────\n//\n// How to start one headless run of a known coding agent, shared by the\n// `agentchat listen --preset <name>` listener and each runtime's own\n// integration package (one copy of the flags, never two). The only module of\n// this package that names a coding agent; the engine never imports it.\n\nimport { claudeCodePreset } from './claude-code.js'\nimport { codexPreset } from './codex.js'\nimport type { Preset } from './types.js'\n\nexport type { Preset, PresetContext, PresetInspection } from './types.js'\nexport { withoutParentSession, isParentSessionEnv, CLAUDE_CODE_ENV_KEPT, CLAUDE_SESSION_ENV, CODEX_SESSION_ENV, CODEX_MANAGED_PROXY_ENV } from './types.js'\nexport { semverAtLeast } from './semver.js'\nexport {\n RUNTIME_CHECK_PROMPT,\n RUNTIME_CHECK_BUDGET_MS,\n RUNTIME_CHECK_DIR,\n RUNTIME_CHECK_KEY_ENV,\n RUNTIME_CHECK_OUTPUT_BYTES,\n runRuntimeCheck,\n type RuntimeCheckSpec,\n} from './runtime-check.js'\nexport {\n CLAUDE_CODE_PRESET,\n MIN_CLAUDE_CODE_VERSION,\n PROBE_TIMEOUT_MS,\n CLAUDE_MCP_SERVER_NAME,\n AGENTCHAT_TOOL_ALLOW,\n ANSWER_TOOLS,\n WEB_TOOLS,\n WORK_TOOLS,\n ANSWER_DENIED_TOOLS,\n ANSWER_SETTINGS,\n PARENT_ENV_KEYS,\n claudeConfigDirFrom,\n claudeHomeFor,\n claudeProjectsDirFor,\n claudeUserStatePathFor,\n buildClaudeEnv,\n claudeIsLoggedIn,\n claudeSignIn,\n type ClaudeSignIn,\n inspectClaudeRuntime,\n deniedAncestorOf,\n claudeProfileArgs,\n workdirPaths,\n workdirReadRules,\n readDenyRules,\n inexpressibleDenyPaths,\n claudeRunArgs,\n claudeRuntimeCheckArgs,\n claudeRuntimeCheckJudge,\n claudeRuntimeCheckWorkdir,\n RUNTIME_CHECK_SETTINGS,\n claudeMcpConfig,\n claudeMcpConfigPath,\n ClaudeRunner,\n claudeCodePreset,\n claudeAnswerFallbackWorkdir,\n claudeManagedSettingsDir,\n claudeSettingsFilesGrantingDirectories,\n claudeExtraDirectoriesGrant,\n ANSWER_ENV,\n type ClaudeAnswerMcp,\n type ClaudeRunArgOptions,\n type ClaudeRunnerOptions,\n} from './claude-code.js'\nexport {\n CODEX_PRESET,\n MIN_CODEX_VERSION,\n CODEX_PROBE_TIMEOUT_MS,\n CODEX_MCP_SERVER_NAME,\n LISTENER_KEY_ENV,\n CODEX_PROMPT_FROM_STDIN,\n CODEX_ANSWER_PERMISSIONS,\n CODEX_ANSWER_FILESYSTEM,\n CODEX_ANSWER_DISABLED_FEATURES,\n codexHomeFrom,\n codexListenerHeadersHelperPath,\n CODEX_LISTENER_HEADERS_HELPER_SOURCE,\n codexHeadersHelperCommand,\n inspectCodexRuntime,\n codexIsLoggedIn,\n codexProfileArgs,\n codexMcpOverrideArgs,\n codexPinnedUrlArgs,\n codexClientHeadersToml,\n codexRunArgs,\n codexRuntimeCheckArgs,\n codexRuntimeCheckWorkdir,\n CODEX_RUNTIME_CHECK_DISABLED_FEATURES,\n agentchatTableKeys,\n CodexRunner,\n codexPreset,\n codexAnswerFallbackWorkdir,\n codexServerNameAddressable,\n parseCodexMcpList,\n codexAgentchatExplicitAuth,\n codexDotEnvKeyNames,\n codexMcpDisableArgs,\n CODEX_MCP_LIST_TIMEOUT_MS,\n CODEX_MCP_LIST_MAX_AGE_MS,\n codexConfigLayerFiles,\n type CodexMcpOverride,\n type CodexRunnerOptions,\n} from './codex.js'\n\n/** Every preset, by the name a user types. */\nexport const PRESETS: Readonly<Record<string, Preset>> = Object.freeze({\n [claudeCodePreset.name]: claudeCodePreset,\n [codexPreset.name]: codexPreset,\n})\n\nexport function presetNamed(name: string): Preset | null {\n return Object.prototype.hasOwnProperty.call(PRESETS, name) ? (PRESETS[name] ?? null) : null\n}\n\nexport function presetNames(): string[] {\n return Object.keys(PRESETS)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,YAAYA,SAAQ;AACpB,YAAY,QAAQ;AACpB,YAAY,UAAU;;;ACDf,SAAS,cAAc,QAAgB,SAA0B;AACtE,QAAM,QAAQ,CAAC,UAAmD;AAChE,UAAM,QAAQ,MAAM,MAAM,qBAAqB;AAC/C,WAAO,QAAQ,CAAC,OAAO,MAAM,CAAC,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,CAAC,IAAI;AAAA,EAC1E;AACA,QAAM,IAAI,MAAM,MAAM;AACtB,QAAM,IAAI,MAAM,OAAO;AACvB,MAAI,MAAM,QAAQ,MAAM,KAAM,QAAO;AACrC,WAAS,QAAQ,GAAG,QAAQ,GAAG,SAAS;AACtC,QAAI,EAAE,KAAK,MAAM,EAAE,KAAK,EAAG,SAAQ,EAAE,KAAK,KAAK,MAAM,EAAE,KAAK,KAAK;AAAA,EACnE;AACA,SAAO;AACT;;;ACbA,YAAY,QAAQ;AA4Bb,IAAM,uBAAuB;AAO7B,IAAM,0BAA0B;AAGhC,IAAM,6BAA6B,MAAM;AAGzC,IAAM,oBAAoB;AAO1B,IAAM,wBAA2C,CAAC,qBAAqB,4BAA4B;AAG1G,SAAS,YAAY,KAAwB,MAA4C;AACvF,QAAM,QAAQ,IAAI,IAAI,CAAC,GAAG,uBAAuB,GAAG,IAAI,EAAE,IAAI,CAAC,SAAS,KAAK,YAAY,CAAC,CAAC;AAC3F,QAAM,MAAyB,CAAC;AAChC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,GAAG,EAAG,KAAI,CAAC,MAAM,IAAI,IAAI,YAAY,CAAC,EAAG,K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A,UAAM,MAAM,EAAE,KAAK,aAAa,IAAI,OAAO,GAAG,QAAQ,kBAAkB,eAAe,IAAI,iBAAiB,QAAQ;AACpH,QAAI,IAAI,YAAY,MAAO,QAAO,IAAI,YAAY,EAAE,GAAG,MAAM,QAAQ,MAAM,QAAQ,IAAI,CAAC;AAIxF,UAAM,SAAS,+BAA+B,IAAI,IAAI;AACtD,UAAM,SAAS,0BAA0B,MAAM;AAC/C,QAAI,WAAW,MAAM;AACnB,aAAO,IAAI,YAAY,EAAE,GAAG,MAAM,QAAQ,MAAM,MAAM,KAAK,QAAQ,qBAAqB,QAAQ,QAAQ,WAAW,MAAM,mHAAmH,CAAC;AAAA,IAC/O;AACA,QAAI;AACF,sBAAgB,QAAQ,sCAAsC,GAAK;AAAA,IACrE,SAAS,KAAK;AACZ,aAAO,IAAI,YAAY,EAAE,GAAG,MAAM,QAAQ,MAAM,MAAM,KAAK,QAAQ,sCAAsC,MAAM,KAAK,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,GAAG,CAAC;AAAA,IAC1K;AACA,WAAO,IAAI,YAAY,EAAE,GAAG,MAAM,QAAQ,MAAM,MAAM,KAAK,EAAE,GAAG,KAAK,eAAe,OAAO,EAAE,CAAC;AAAA,EAChG;AACF;;;AC10BO,IAAM,UAA4C,OAAO,OAAO;AAAA,EACrE,CAAC,iBAAiB,IAAI,GAAG;AAAA,EACzB,CAAC,YAAY,IAAI,GAAG;AACtB,CAAC;AAEM,SAAS,YAAY,MAA6B;AACvD,SAAO,OAAO,UAAU,eAAe,KAAK,SAAS,IAAI,IAAK,QAAQ,IAAI,KAAK,OAAQ;AACzF;AAEO,SAAS,cAAwB;AACtC,SAAO,OAAO,KAAK,OAAO;AAC5B;","names":["fs","fs","os","path","resolve"]}
1
+ {"version":3,"sources":["../src/presets/claude-code.ts","../src/presets/semver.ts","../src/presets/runtime-check.ts","../src/presets/types.ts","../src/presets/codex.ts","../src/presets/index.ts"],"sourcesContent":["import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { clientHeadersOf } from '../client-identity.js'\nimport { hostedMcpUrl } from '../integration/mcp-probe.js'\nimport { workdirExposesHome, type RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, RunPreflightOptions, RunRequest, RunRunner } from '../integration/runner.js'\nimport { spawnRun } from '../integration/spawn-run.js'\nimport { atomicWriteFile } from '../util/fsutil.js'\nimport { log } from '../util/log.js'\nimport { runProbe } from '../util/probe.js'\nimport { VERSION } from '../version.js'\nimport { semverAtLeast } from './semver.js'\nimport { RUNTIME_CHECK_DIR, runRuntimeCheck } from './runtime-check.js'\nimport { withoutInheritedKey, withoutParentSession, type Preset, type PresetContext, type PresetInspection } from './types.js'\n\n// ─── Claude Code: one headless run (`claude -p`) ────────────────────────────\n//\n// `claude -p` on the box, riding the user's own Claude Code sign-in and user\n// configuration. The run's output is discarded by `spawnRun`: the agent's only\n// way to say anything on AgentChat is the hosted send tool during the run.\n//\n// The flags, verified against `claude --help` (2.1.316) and\n// code.claude.com/docs/en/cli-reference.md, headless.md, permission-modes.md:\n//\n// --permission-prompts none anything that would prompt is denied, never\n// waited on; the permission mode and allow rules\n// still decide every call first (v2.1.259+).\n// --tools <list> restricts the BUILT-IN tool set; does not affect\n// MCP tools. Listing Glob/Grep explicitly provides\n// the dedicated search tools.\n// --allowedTools <rules> pre-approves. `mcp__agentchat__*` is the whole\n// hosted server; `Bash` pre-approves every shell\n// command (dropped as a broad rule only in auto mode).\n// A bare `Read`, `Glob` or `Grep` pre-approves that\n// tool on EVERY path; `Read(//<dir>/**)` only under\n// `<dir>`. Glob and Grep have no path rules of their\n// own: `Read(<path>)` rules are matched for them\n// (permissions.md \"Glob(path) and Grep(path) rules\n// don't match\"). An allow rule applies only when the\n// requested path AND the file it resolves to match\n// (permissions.md \"Symlinks\"), so a link out of the\n// workdir is never allowed by it.\n// --disallowedTools <rules> denies. Deny rules win over allow rules, and a\n// `Read(<path>)` rule covers every built-in tool\n// that reads files (Read, Grep, Glob — docs:\n// permissions.md \"Read & Edit\"). Used to keep a\n// run's file tools off the key store. `//`\n// prefixes an absolute path in rule syntax. A bare\n// tool name removes the tool.\n// --settings <json> additional settings for this run only. `answer`\n// sets `permissions.blockReadsOutsideWorkingDirectories`\n// (v2.1.257+, settings-reference.md): the file tools\n// refuse every path outside the working directories\n// in every mode, and \"no allow rule lets Claude's\n// file tools through\" — so an allow rule in the\n// user's own settings cannot reopen the disk.\n// --permission-mode default Manual: reads inside the working directories need\n// no approval, everything else prompts (and is\n// therefore denied here).\n// --permission-mode acceptEdits file edits and common filesystem commands in\n// the working directory need no approval.\n// --dangerously-skip-permissions = bypassPermissions.\n// --mcp-config <file> --strict-mcp-config\n// the hosted server from a file, and ONLY it: a\n// listener's run acts as the listener's agent,\n// never as whatever key the user scope registers.\n// --mcp-config <file> (no --strict-mcp-config)\n// `own`: the file's `agentchat` wins over a\n// user-scope `agentchat` (verified on 2.1.327: the\n// user-scope one is not even connected), and every\n// other server the user configured still loads.\n//\n// Whatever the profile, every AgentChat hosted tool is pre-approved: the run\n// exists to read the tray and decide or send through them. In `own` that is\n// all `--allowedTools` says. It cannot be left to the user's settings: in\n// print mode an MCP tool no rule allows is denied (verified on 2.1.327:\n// \"requires approval, and this session has no approval surface\"), and\n// naming the server there is also what makes the first turn wait for it\n// (agent-sdk/mcp.md, \"Named servers\"). A user's deny rule still wins over it.\n//\n// `own` passes nothing else that decides what a run may do: no `--tools`,\n// `--permission-mode`, `--settings` or `--strict-mcp-config`. The user's\n// permission mode (`permissions.defaultMode`; Manual when none is set, the\n// documented built-in for `claude -p`), allow and deny rules, MCP servers,\n// CLAUDE.md, auto memory and hooks apply as in their own `claude -p` runs.\n//\n// The runtime check (`checkRuntime`, runtime-check.ts) is one `claude -p`\n// with a fixed prompt, the same binary and environment as the runs (no key in\n// it), in an empty folder of its own, and nothing to act with:\n//\n// --output-format json one result object (code.claude.com/docs/en/\n// headless.md, \"Output formats\": `type`,\n// `subtype`, `is_error`, `result`, …). The check\n// is ok only on exit 0 with `type: \"result\"`,\n// `subtype: \"success\"`, `is_error: false`,\n// `num_turns` 1 or more and, when `usage` is\n// there, `usage.output_tokens` 1 or more\n// (`claudeRuntimeCheckJudge`; judged by its\n// shape, never by its words). Seen\n// on 2.1.328 against a stand-in provider: an API\n// error (a refusal, an invalid key, a low credit\n// balance) is `subtype: \"success\"` with\n// `is_error: true`, `api_error_status` set, and\n// exit 1 — so `subtype` alone is not enough. With\n// verbose on (`--verbose`, the `verbose` or\n// `viewMode` setting) it prints a JSON array of\n// every message instead, the result last: the\n// judge reads that result.\n// --strict-mcp-config (no --mcp-config) no MCP server at all: not the\n// hosted AgentChat tools, not the user's.\n// --tools \"\" no built-in tool (\"\" for none, `claude --help`).\n// --permission-prompts none nothing waits on a prompt.\n// --settings RUNTIME_CHECK_SETTINGS the user's hooks do not fire on a health\n// check (managed hooks still run), no\n// instruction file or memory, re-asserted the way\n// `ANSWER_SETTINGS` does (a settings file's `env`\n// would override the process environment),\n// verbose output off (`verbose: false`,\n// `viewMode: \"default\"`), so the answer is the one\n// result object, and `language: \"english\"` over\n// the user's `language`.\n// CLAUDE_CODE_DISABLE_CLAUDE_MDS=1, CLAUDE_CODE_DISABLE_AUTO_MEMORY=1\n// the same two, in the environment.\n// --disallowedTools <the key-store deny rules> as on every run.\n//\n// Verified on 2.1.328 against a stand-in model provider: the request carries\n// no tool; an answer is exit 0 with the result above.\n\nexport const CLAUDE_CODE_PRESET = 'claude-code'\n\n/**\n * Two flags set the floor:\n * * `--permission-prompts none` — Claude Code v2.1.259.\n * * `CLAUDE_CODE_MCP_STARTUP_WAIT_MS` — bounds how long the first\n * non-interactive turn waits for the MCP servers `--allowedTools` names to\n * connect. Added in v2.1.274. Without it a run could start before the\n * hosted inbox tool is there.\n */\nexport const MIN_CLAUDE_CODE_VERSION = '2.1.274'\n\n/** The MCP server name the runs see; every hosted tool is `mcp__agentchat__<tool>`, as the served texts spell them. */\nexport const CLAUDE_MCP_SERVER_NAME = 'agentchat'\nexport const AGENTCHAT_TOOL_ALLOW = `mcp__${CLAUDE_MCP_SERVER_NAME}__*`\n\n/**\n * Built-in tools an `answer` run has: the file-reading tools, and only on the\n * run's own working folder (`workdirReadRules`, `ANSWER_SETTINGS`). An `answer`\n * run is started by any peer's message — a stranger's cold DM included — so\n * the only way out it has is the AgentChat tools: no web, no shell, no edits,\n * and nothing outside its workdir to read.\n */\nexport const ANSWER_TOOLS = ['Read', 'Glob', 'Grep'] as const\n\n/** The web tools: `work` pre-approves them; `answer` never has them. */\nexport const WEB_TOOLS = ['WebSearch', 'WebFetch'] as const\n\n/** Built-in tools a `work` run additionally pre-approves. */\nexport const WORK_TOOLS = ['Bash', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit'] as const\n\n/**\n * Denied to every `answer` run by name, on top of `--tools` leaving them out:\n * the ways out (web) and the shell. A bare tool name in a deny rule removes\n * the tool, so even a widened `--tools` list could not bring them back.\n */\nexport const ANSWER_DENIED_TOOLS = ['WebFetch', 'WebSearch', 'Bash'] as const\n\n/**\n * The `--settings` an `answer` run is given. A constant, never built from a\n * path: in print mode a settings value that fails validation is silently\n * ignored (`claude --help`, `-p`), so nothing variable may ride in it. Every\n * key exists at the 2.1.274 floor.\n *\n * permissions.blockReadsOutsideWorkingDirectories (2.1.257+) no file tool\n * reads outside the working directories, whatever allow rule another\n * settings file holds.\n * env the two `ANSWER_ENV` switches again. A settings file's `env` overrides\n * the process environment, and a workdir repository's own\n * `.claude/settings.json` is applied in print mode: there it could turn\n * CLAUDE.md and auto memory back on. `--settings` outranks user, project\n * and local settings (settings.md, \"Settings precedence\").\n * disableAllHooks (1.0.68+) no hook, status line or file-suggestion command:\n * the user's own hooks and a workdir repository's would run a shell\n * command, and inject text, on every peer's message. Managed hooks still\n * run (only managed settings can turn those off).\n */\nexport const ANSWER_SETTINGS = JSON.stringify({\n permissions: { blockReadsOutsideWorkingDirectories: true },\n env: { CLAUDE_CODE_DISABLE_CLAUDE_MDS: '1', CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' },\n disableAllHooks: true,\n})\n\n/**\n * Env a parent Claude Code session leaks that would make the child think it is\n * nested — a sample kept for callers that named it; the rule is\n * `withoutParentSession` (every `CLAUDE_CODE_*` but the user's documented\n * settings, `CLAUDE_PID`, and the Codex session variables).\n */\nexport const PARENT_ENV_KEYS = [\n 'CLAUDECODE',\n 'CLAUDE_CODE_CHILD_SESSION',\n 'CLAUDE_CODE_SESSION_ID',\n 'CLAUDE_CODE_ENTRYPOINT',\n 'CLAUDE_CODE_EXECPATH',\n 'CLAUDE_CODE_EFFORT_LEVEL',\n 'CLAUDE_EFFORT',\n 'AI_AGENT',\n 'CLAUDE_CODE_MESSAGING_SOCKET',\n 'CLAUDE_CODE_MESSAGING_TOKEN',\n 'CLAUDE_CODE_SESSION_ATTENDED',\n 'CLAUDE_PID',\n]\n\n/**\n * How long the first turn of a `-p` run waits for a still-connecting MCP\n * server that `--allowedTools` names. Claude Code's own built-in wait is short\n * (2 s since 2.1.284), and a remote server over a cold network can take\n * longer; the run must not start without the inbox tool.\n */\nconst MCP_STARTUP_WAIT_MS = '15000'\n\n/** Claude Code's supported relocation knob. Unset is NOT the same as `~/.claude`. */\nexport function claudeConfigDirFrom(env: NodeJS.ProcessEnv = process.env): string | undefined {\n const override = env['CLAUDE_CONFIG_DIR']\n return override !== undefined && override.trim().length > 0 ? path.resolve(override) : undefined\n}\n\n/** `~/.claude`, or the relocated config dir. */\nexport function claudeHomeFor(configDirOverride: string | undefined): string {\n return configDirOverride ?? path.join(os.homedir(), '.claude')\n}\n\n/** Where Claude Code keeps every project's transcripts and auto memory: `<config dir>/projects`. */\nexport function claudeProjectsDirFor(configDirOverride: string | undefined): string {\n return path.join(claudeHomeFor(configDirOverride), 'projects')\n}\n\n/**\n * Where Claude Code keeps user-scoped MCP servers (and so any key registered\n * there): `~/.claude.json`, or `$CLAUDE_CONFIG_DIR/.claude.json`.\n */\nexport function claudeUserStatePathFor(configDirOverride: string | undefined): string {\n return configDirOverride !== undefined ? path.join(configDirOverride, '.claude.json') : path.join(os.homedir(), '.claude.json')\n}\n\nfunction claudeProcessEnv(configDirOverride: string | undefined, source: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const env = { ...source }\n if (configDirOverride === undefined) delete env['CLAUDE_CONFIG_DIR']\n else env['CLAUDE_CONFIG_DIR'] = configDirOverride\n return env\n}\n\nexport function buildClaudeEnv(configDirOverride: string | undefined, source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const env = claudeProcessEnv(configDirOverride, withoutParentSession(source))\n env['DISABLE_AUTOUPDATER'] = '1'\n const wait = Number(env['CLAUDE_CODE_MCP_STARTUP_WAIT_MS'])\n if (!Number.isFinite(wait) || wait < Number(MCP_STARTUP_WAIT_MS)) env['CLAUDE_CODE_MCP_STARTUP_WAIT_MS'] = MCP_STARTUP_WAIT_MS\n return env\n}\n\n/** How long a probe (`--version`, the sign-in check) may take; a hung one is killed with its whole tree. */\nexport const PROBE_TIMEOUT_MS = 10_000\n\n/**\n * Is Claude Code signed in? `claude auth status` prints JSON with a boolean\n * `loggedIn` and exits 0 if logged in, 1 if not. When that JSON is there it is\n * the answer. The file/keychain probes are a fallback for builds without the\n * subcommand; the keychain probe is existence-only and never prompts — a\n * resident listener must never trigger a keychain prompt. Async: a hung probe\n * is killed with everything it started (`runProbe`), never left holding the\n * daemon.\n */\n/** What Claude Code's sign-in check found: signed in or not, or no answer (it hung, or was stopped): then `detail` says so. */\nexport interface ClaudeSignIn {\n readonly signedIn: boolean\n /** Why it could not tell: `claude auth status did not answer within 10 s (killed)`. Null when it answered. */\n readonly unanswered: string | null\n}\n\nexport async function claudeSignIn(configDirOverride?: string, command = 'claude', timeoutMs = PROBE_TIMEOUT_MS, signal?: AbortSignal): Promise<ClaudeSignIn> {\n const status = await runProbe(command, ['auth', 'status'], { timeoutMs, env: claudeProcessEnv(configDirOverride, process.env), ...(signal !== undefined ? { signal } : {}) })\n // A check that hung says the runtime is broken, not that this is an old build: no fallback, and said as what it is.\n if (status.timedOut) return { signedIn: false, unanswered: `claude auth status did not answer within ${Math.round(timeoutMs / 1000)} s (killed)` }\n if (signal?.aborted) return { signedIn: false, unanswered: 'claude auth status was stopped' }\n if (!status.error) {\n try {\n const parsed = JSON.parse(status.stdout.trim()) as { loggedIn?: unknown }\n if (typeof parsed?.loggedIn === 'boolean') return { signedIn: parsed.loggedIn, unanswered: null }\n } catch {\n /* no JSON: an older build; fall through to the file and keychain */\n }\n if (status.status === 0) return { signedIn: true, unanswered: null }\n }\n\n const configDir = claudeHomeFor(configDirOverride)\n if (fs.existsSync(path.join(configDir, '.credentials.json'))) return { signedIn: true, unanswered: null }\n if (process.platform !== 'darwin') return { signedIn: false, unanswered: null }\n const keychain = await runProbe('security', ['find-generic-password', '-s', 'Claude Code-credentials'], { timeoutMs: Math.min(timeoutMs, 5_000), ...(signal !== undefined ? { signal } : {}) })\n return { signedIn: !keychain.error && keychain.status === 0, unanswered: null }\n}\n\n/** `claudeSignIn`, as a yes/no (no answer is not signed in). */\nexport async function claudeIsLoggedIn(configDirOverride?: string, command = 'claude', timeoutMs = PROBE_TIMEOUT_MS): Promise<boolean> {\n return (await claudeSignIn(configDirOverride, command, timeoutMs)).signedIn\n}\n\nexport async function inspectClaudeRuntime(configDirOverride?: string, command = 'claude', timeoutMs = PROBE_TIMEOUT_MS, signal?: AbortSignal): Promise<PresetInspection> {\n const version = await runProbe(command, ['--version'], { timeoutMs, env: claudeProcessEnv(configDirOverride, process.env), ...(signal !== undefined ? { signal } : {}) })\n if (version.timedOut) return { ok: false, detail: `claude --version did not answer within ${Math.round(timeoutMs / 1000)} s (killed)` }\n if (signal?.aborted) return { ok: false, detail: 'claude --version was stopped' }\n if (version.error) return { ok: false, detail: `claude CLI not found on PATH (${version.error.message})` }\n const rendered = (version.stdout || version.stderr).trim()\n if (version.status !== 0) return { ok: false, detail: rendered || `claude --version exited ${version.status}` }\n return semverAtLeast(rendered, MIN_CLAUDE_CODE_VERSION)\n ? { ok: true, detail: rendered }\n : {\n ok: false,\n detail: `${rendered || 'unrecognized version'}; AgentChat requires Claude Code >= ${MIN_CLAUDE_CODE_VERSION} (for --permission-prompts none and CLAUDE_CODE_MCP_STARTUP_WAIT_MS)`,\n }\n}\n\n/**\n * The entry of `denied` that is `dir` or contains it, or null. Whole path\n * segments only: `~/.claude/agentchat` does not contain `~/.claude/agentchat-workdir`.\n */\nexport function deniedAncestorOf(dir: string, denied: readonly string[]): string | null {\n const target = path.resolve(dir)\n for (const raw of denied) {\n const root = path.resolve(raw)\n if (target === root || target.startsWith(root.endsWith(path.sep) ? root : root + path.sep)) return root\n }\n return null\n}\n\n/**\n * Whether a path can be carried by a `Read(//<path>)` ALLOW rule in a\n * comma/space-separated list: what `expressible` asks, and no gitignore\n * pattern character either (`*`, `?`, `[`, `]`, `\\`, `!`, `#`). Rules are\n * matched as gitignore patterns and the ones written here are not escaped\n * (permissions.md \"Special characters\"): `/w*` would also allow `/wallet`.\n */\nfunction expressibleAllow(raw: string): boolean {\n return expressible(raw) && !/[*?[\\]\\\\!#]/.test(raw)\n}\n\n/**\n * The paths a workdir is reached by: as given (absolute), and where it really\n * is when that differs (`/tmp/w` is `/private/tmp/w` on macOS; a symlinked\n * workdir). An allow rule matches only when the requested path and the file\n * it resolves to both match, so both spellings are carried. A workdir that\n * does not exist yet is carried as given.\n */\nexport function workdirPaths(workdir: string): string[] {\n const given = path.resolve(workdir)\n let real = given\n try {\n real = fs.realpathSync(given)\n } catch {\n /* not created yet (preflight creates it): only the given spelling */\n }\n return real === given ? [given] : [given, real]\n}\n\n/**\n * `/w` → `Read(//w)` and `Read(//w/**)`, for each spelling of the workdir: the\n * only paths an `answer` run's Read, Glob and Grep are pre-approved on. A\n * spelling no allow rule can carry (whitespace, a comma, a gitignore pattern\n * character; every path on Windows) gets no rule — that fails closed: the run\n * still reads its workdir as its working directory, and nothing else.\n */\nexport function workdirReadRules(workdir: string | undefined): string[] {\n if (workdir === undefined || process.platform === 'win32') return []\n const rules: string[] = []\n for (const raw of workdirPaths(workdir)) {\n const clean = raw.replace(/\\/+$/, '')\n // The filesystem root is no work folder: no rule (its tree is the disk).\n if (!expressibleAllow(raw) || clean.length === 0) continue\n rules.push(`Read(/${clean})`, `Read(/${clean}/**)`)\n }\n return rules\n}\n\n/**\n * The flags for one run profile. `workdir` is the run's working directory:\n * `answer` scopes its file tools to it (absent, they get no allow rule at all).\n */\nexport function claudeProfileArgs(profile: RunProfile, workdir?: string): string[] {\n switch (profile) {\n // The agent itself: the user's own settings decide; AgentChat's tools are\n // pre-approved and nothing waits on a prompt (see the header).\n case 'own':\n return ['--permission-prompts', 'none', '--allowedTools', AGENTCHAT_TOOL_ALLOW]\n case 'answer':\n return [\n '--permission-mode',\n 'default',\n '--permission-prompts',\n 'none',\n '--tools',\n ANSWER_TOOLS.join(','),\n '--allowedTools',\n [AGENTCHAT_TOOL_ALLOW, ...workdirReadRules(workdir)].join(','),\n '--settings',\n ANSWER_SETTINGS,\n ]\n // `work` and `full` are the operator's explicit opt-in: a run started by\n // any peer's message can then read and change this machine.\n case 'work':\n return [\n '--permission-mode',\n 'acceptEdits',\n '--permission-prompts',\n 'none',\n '--allowedTools',\n [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WEB_TOOLS, ...WORK_TOOLS].join(','),\n ]\n case 'full':\n return ['--dangerously-skip-permissions', '--permission-prompts', 'none', '--allowedTools', AGENTCHAT_TOOL_ALLOW]\n }\n}\n\nexport interface ClaudeRunArgOptions {\n /** `AGENTCHAT_RUN_MAX_BUDGET_USD`: stop the run once estimated spend reaches this (print mode only). */\n readonly maxBudgetUsd?: string | undefined\n /** The run's working directory: the one folder an `answer` run's file tools are allowed (`workdirReadRules`). */\n readonly workdir?: string | undefined\n /**\n * Absolute paths the run's file tools may not read (a directory covers its\n * tree). Rendered as `Read(//<path>)` / `Read(//<dir>/**)` deny rules. A\n * prompt-injected run could otherwise read the key and send it; the wake\n * text should not be the only guard. POSIX paths only — on Windows the\n * rule syntax for drive paths is undocumented, so nothing is rendered.\n */\n readonly denyReadPaths?: readonly string[] | undefined\n /**\n * A `--mcp-config` file holding the hosted server with the agent's key;\n * with it, `--strict-mcp-config` makes it the run's only MCP server. Absent:\n * the run uses the user-scope server the integration registered.\n */\n readonly mcpConfigPath?: string | undefined\n /**\n * A file whose text is appended to the system prompt (`--append-system-prompt-file`,\n * documented since 2.1.69): how an `answer` run, which loads no CLAUDE.md,\n * is told its identity line, and how an `own` run is told it whatever its\n * CLAUDE.md holds (a listener's agent is not the one there). A file, not\n * argv text: an argument cannot carry a line break through a Windows `.cmd` shim.\n */\n readonly appendSystemPromptFile?: string | undefined\n}\n\n/**\n * The `--settings` a runtime check is given: no hook of the user's (or a\n * workdir repository's) fires on a health check, the two `ANSWER_ENV`\n * switches again (a settings file's `env` overrides the process environment;\n * `--settings` outranks user, project and local settings), and verbose output\n * off. A constant (`claude --help`: a settings value that fails validation is\n * silently ignored in print mode).\n *\n * verbose: false, viewMode: \"default\" with verbose on (the user's `verbose`\n * setting or its older `~/.claude.json` copy, or `viewMode: \"verbose\"`),\n * `--output-format json` prints a JSON array of every message instead of\n * the one result object. Both keys are documented settings\n * (settings-reference.md: `viewMode` overrides `verbose`; only the\n * `--verbose` flag, never passed here, outranks them). `verbose` is a\n * settings key since 2.1.119, below the floor; `viewMode` is newer, and a\n * version that does not know it ignores just that key (seen on 2.1.328:\n * an unknown key or an invalid value leaves the rest of `--settings` in\n * force, hooks off included). Managed settings outrank `--settings`, so\n * the judge reads the array too (`claudeRuntimeCheckJudge`).\n *\n * language: \"english\" the user's `language` setting is an instruction to\n * answer in that language; the fixed prompt is English, and the check\n * is answered as written (`--settings` outranks the user's value).\n *\n * Verified on 2.1.328 against a stand-in provider: with the user's `verbose:\n * true`, `viewMode: \"verbose\"` or the `~/.claude.json` `verbose`, settings\n * without the two verbose keys printed an array; with them, one result object.\n */\nexport const RUNTIME_CHECK_SETTINGS = JSON.stringify({\n env: { CLAUDE_CODE_DISABLE_CLAUDE_MDS: '1', CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' },\n disableAllHooks: true,\n verbose: false,\n viewMode: 'default',\n language: 'english',\n})\n\n/** The result message in verbose output (a JSON array of messages): the last one with `type: \"result\"`. */\nfunction lastResultMessage(messages: readonly unknown[]): unknown {\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const m = messages[i]\n if (m !== null && typeof m === 'object' && !Array.isArray(m) && (m as Record<string, unknown>)['type'] === 'result') return m\n }\n return null\n}\n\n/**\n * Whether a runtime check's stdout (`--output-format json`) is a good answer:\n * null when its result has `type: \"result\"`, `subtype: \"success\"`,\n * `is_error: false`, at least one turn (`num_turns >= 1`: a run a hook\n * blocked before the model has none) and, when it carries `usage`, at least\n * one output token (`usage.output_tokens >= 1`); otherwise why not, in ids,\n * flags and counts only (`is_error`, `api_error_status`, `terminal_reason`,\n * `num_turns`, `output_tokens`), never the result text. It is judged by its\n * shape, never by its words: a model may answer \"Okay\", or in the user's\n * language. The result is the one object Claude Code prints, or, with verbose\n * output on (the `--verbose` flag, the `verbose` or `viewMode` setting), the\n * last `type: \"result\"` element of the JSON array it prints instead. A false\n * pass is the dangerous direction (an outage reported as one conversation's\n * failure hides its messages), so anything short of all of that is not ok.\n */\nexport function claudeRuntimeCheckJudge(stdout: string): string | null {\n const text = stdout.trim()\n let parsed: unknown = null\n for (const candidate of [text, text.split(/\\r?\\n/).filter((line) => line.trim().length > 0).at(-1) ?? '']) {\n try {\n parsed = JSON.parse(candidate)\n break\n } catch {\n parsed = null\n }\n }\n if (Array.isArray(parsed)) {\n parsed = lastResultMessage(parsed)\n if (parsed === null) return 'its answer is a list of messages with no result'\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return 'its answer is not a JSON result'\n const r = parsed as Record<string, unknown>\n if (r['type'] === 'result' && r['subtype'] === 'success' && r['is_error'] === false) {\n const turns = r['num_turns']\n if (typeof turns !== 'number' || !(turns >= 1)) return `the result has no turn (num_turns ${typeof turns === 'number' ? turns : '?'})`\n const usage = r['usage']\n if (usage !== undefined && usage !== null) {\n const tokens = typeof usage === 'object' && !Array.isArray(usage) ? (usage as Record<string, unknown>)['output_tokens'] : undefined\n if (typeof tokens !== 'number' || !(tokens >= 1)) return `the result has no output (usage.output_tokens ${typeof tokens === 'number' ? tokens : '?'})`\n }\n return null\n }\n const facts = [\n `type ${typeof r['type'] === 'string' ? r['type'] : '?'}`,\n `subtype ${typeof r['subtype'] === 'string' ? r['subtype'] : '?'}`,\n `is_error ${typeof r['is_error'] === 'boolean' ? String(r['is_error']) : '?'}`,\n ...(typeof r['api_error_status'] === 'number' ? [`api_error_status ${r['api_error_status']}`] : []),\n ...(typeof r['terminal_reason'] === 'string' && /^[a-z_]{1,40}$/.test(r['terminal_reason']) ? [`terminal_reason ${r['terminal_reason']}`] : []),\n ]\n return `the result is not a success (${facts.join(', ')})`\n}\n\n/**\n * The argv of a runtime check: one `claude -p` with no tool of any kind (no\n * MCP server, no built-in tool), no hooks, never waiting on a prompt; the\n * prompt on stdin, as for a run. `denyReadPaths` are the runs' own deny rules.\n */\nexport function claudeRuntimeCheckArgs(denyReadPaths: readonly string[] = []): string[] {\n const deny = readDenyRules(denyReadPaths)\n return [\n '-p',\n '--output-format',\n 'json',\n '--no-session-persistence',\n // No --mcp-config: with this flag, no MCP server loads at all.\n '--strict-mcp-config',\n // Variadic; \"\" is none (`claude --help`). Closed by the option after it.\n '--tools',\n '',\n '--permission-prompts',\n 'none',\n '--settings',\n RUNTIME_CHECK_SETTINGS,\n ...(deny.length > 0 ? ['--disallowedTools', deny.join(',')] : []),\n ]\n}\n\n/** The empty folder a runtime check runs in: beside Claude Code's config, outside every denied path. */\nexport function claudeRuntimeCheckWorkdir(configDirOverride: string | undefined): string {\n return path.join(claudeHomeFor(configDirOverride), RUNTIME_CHECK_DIR)\n}\n\n/** Whether a path can be carried by a `Read(//<path>)` rule in a comma/space-separated list: absolute POSIX, no comma, no whitespace. */\nfunction expressible(raw: string): boolean {\n return raw.startsWith('/') && !/[,\\s]/.test(raw)\n}\n\n/**\n * The deny paths no rule can carry: on Windows all of them (the rule syntax\n * for drive paths is undocumented), elsewhere a relative path or one with a\n * comma or whitespace. A run would be able to read these.\n */\nexport function inexpressibleDenyPaths(paths: readonly string[]): string[] {\n return process.platform === 'win32' ? [...paths] : paths.filter((p) => !expressible(p))\n}\n\n/** `/Users/x/.claude/agentchat` → `Read(//Users/x/.claude/agentchat/**)` and `Read(//Users/x/.claude/agentchat)`. Paths no rule can carry are left out (`inexpressibleDenyPaths`). */\nexport function readDenyRules(paths: readonly string[]): string[] {\n if (process.platform === 'win32') return []\n const rules: string[] = []\n for (const raw of paths) {\n if (!expressible(raw)) continue\n const clean = raw.replace(/\\/+$/, '')\n rules.push(`Read(/${clean})`, `Read(/${clean}/**)`)\n }\n return rules\n}\n\n/**\n * The full argument list for one headless run. The prompt goes on STDIN, not\n * as a positional: the variadic `--allowedTools` (and `--mcp-config`) would\n * otherwise swallow a trailing positional (verified on 2.1.220; `cat file |\n * claude -p` is the documented piped form).\n */\nexport function claudeRunArgs(profile: RunProfile, options: ClaudeRunArgOptions = {}): string[] {\n const budget = options.maxBudgetUsd?.trim()\n const deny = [...(profile === 'answer' ? ANSWER_DENIED_TOOLS : []), ...readDenyRules(options.denyReadPaths ?? [])]\n return [\n '-p',\n '--output-format',\n 'text',\n // A wake run is not a conversation to resume; keep it out of the user's\n // session list and off the disk.\n '--no-session-persistence',\n ...(budget !== undefined && /^\\d+(\\.\\d+)?$/.test(budget) ? ['--max-budget-usd', budget] : []),\n // Variadic, so it is closed by the option right after it. `own` keeps the\n // user's other servers: the file's `agentchat` wins over theirs by name.\n ...(options.mcpConfigPath !== undefined ? ['--mcp-config', options.mcpConfigPath, ...(profile === 'own' ? [] : ['--strict-mcp-config'])] : []),\n ...(options.appendSystemPromptFile !== undefined ? ['--append-system-prompt-file', options.appendSystemPromptFile] : []),\n ...claudeProfileArgs(profile, options.workdir),\n // Last: the option is variadic and the prompt arrives on stdin, so there\n // is no positional for it to swallow.\n ...(deny.length > 0 ? ['--disallowedTools', deny.join(',')] : []),\n ]\n}\n\n/** The `--mcp-config` document: the hosted server, by HTTP, with the agent's key. Owner-only on disk. */\n/**\n * The `--mcp-config` file a listener's run is given: the hosted tool server\n * with this agent's key, and the client headers that name the runtime to it\n * (`X-AgentChat-Client: claude-code`, `-Version`: the front door that placed\n * the run). The hosted tool server names a client only from these headers:\n * without them a run is an unknown client and is shown the wake-webhook\n * tools, a second way of being woken that the listener makes unnecessary.\n */\nexport function claudeMcpConfig(apiBase: string, apiKey: string, clientVersion: string = VERSION): string {\n const headers = { Authorization: `Bearer ${apiKey}`, ...clientHeadersOf({ runtime: 'claude-code', version: clientVersion }) }\n return `${JSON.stringify({ mcpServers: { [CLAUDE_MCP_SERVER_NAME]: { type: 'http', url: hostedMcpUrl(apiBase), headers } } }, null, 2)}\\n`\n}\n\n/**\n * What an `answer` run's environment adds: no CLAUDE.md of any scope (user,\n * project, ancestors, `.claude/rules`, `@` imports) and no auto memory\n * (code.claude.com/docs/en/env-vars; both read by 2.1.274, the floor). The\n * user's own files are not a peer-started run's context: what it could read\n * there it could send. Its identity line comes in by\n * `--append-system-prompt-file` instead.\n */\nexport const ANSWER_ENV: Readonly<Record<string, string>> = Object.freeze({\n CLAUDE_CODE_DISABLE_CLAUDE_MDS: '1',\n CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1',\n})\n\n/** The system folder Claude Code reads managed settings from (code.claude.com/docs/en/managed-settings). */\nexport function claudeManagedSettingsDir(platform: NodeJS.Platform = process.platform): string {\n if (platform === 'darwin') return '/Library/Application Support/ClaudeCode'\n if (platform === 'win32') return 'C:\\\\Program Files\\\\ClaudeCode'\n return '/etc/claude-code'\n}\n\n/** The git repository root at or above `dir` (a `.git` file or folder), or null. */\nfunction gitRootOf(dir: string): string | null {\n let current = path.resolve(dir)\n for (;;) {\n if (fs.existsSync(path.join(current, '.git'))) return current\n const parent = path.dirname(current)\n if (parent === current) return null\n current = parent\n }\n}\n\n/**\n * The settings files that can give an `answer` run more working directories\n * than its own: `permissions.additionalDirectories` there counts as a working\n * directory even under `blockReadsOutsideWorkingDirectories`\n * (settings-reference.md) — the user's settings, the managed file and its\n * `managed-settings.d/` drop-ins, and `.claude/settings.local.json` at the\n * workdir's repository root and in the workdir itself (counted when git does\n * not track it; checked whenever it is there). MDM and server-managed policies\n * are not files and are not covered.\n */\nexport function claudeSettingsFilesGrantingDirectories(configDirOverride: string | undefined, workdir: string): string[] {\n const managed = claudeManagedSettingsDir()\n const dropIns = (() => {\n try {\n return fs\n .readdirSync(path.join(managed, 'managed-settings.d'))\n .filter((name) => name.endsWith('.json') && !name.startsWith('.'))\n .sort()\n .map((name) => path.join(managed, 'managed-settings.d', name))\n } catch {\n return []\n }\n })()\n // Local settings are read at the repository root in a git repository, and\n // in the working directory itself otherwise (and on Windows): both are checked.\n const cwdLocal = path.join(path.resolve(workdir), '.claude', 'settings.local.json')\n const root = gitRootOf(workdir)\n const rootLocal = root !== null ? path.join(root, '.claude', 'settings.local.json') : cwdLocal\n return [\n path.join(claudeHomeFor(configDirOverride), 'settings.json'),\n path.join(managed, 'managed-settings.json'),\n ...dropIns,\n ...new Set([rootLocal, cwdLocal]),\n ]\n}\n\n/**\n * The first of those files that lists `permissions.additionalDirectories`, with\n * why, or null. A file that is not JSON is ignored by Claude Code (and so here),\n * unless it names the key — then it counts, as it may be read another way.\n */\nexport function claudeExtraDirectoriesGrant(configDirOverride: string | undefined, workdir: string): { file: string; detail: string } | null {\n for (const file of claudeSettingsFilesGrantingDirectories(configDirOverride, workdir)) {\n let text: string\n try {\n text = fs.readFileSync(file, 'utf-8')\n } catch {\n continue\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n if (text.includes('additionalDirectories')) return { file, detail: 'names permissions.additionalDirectories and is not valid JSON' }\n continue\n }\n const dirs = (parsed as { permissions?: { additionalDirectories?: unknown } } | null)?.permissions?.additionalDirectories\n if (Array.isArray(dirs) && dirs.length > 0) return { file, detail: `lists permissions.additionalDirectories (${dirs.length} folder${dirs.length === 1 ? '' : 's'})` }\n }\n return null\n}\n\n/** The reason an `answer` run does not start while a settings file grants more working directories. */\nfunction extraDirectoriesRefusal(grant: { file: string; detail: string }): string {\n return `answer runs do not start while ${grant.file} ${grant.detail}: Claude Code counts those as working directories, so a run started by a peer's message could read them. Remove the key from that file (your own sessions can use --add-dir instead).`\n}\n\n/**\n * The AgentChat hosted server alone, for `answer` runs that have no\n * `mcpConfigPath`: written owner-only for each run beside `file`, under a name\n * of that run's own (`<file stem>.<run id>.json`, so a late cleanup of an\n * abandoned run cannot remove the next run's), from the key `apiKey()` returns\n * then (a credential change is followed), passed with `--strict-mcp-config`,\n * and removed when the run ends. An `answer` run then\n * loads no other MCP server — the user's own, a project's, a plugin's, a\n * claude.ai connector — whatever the user scope registers. `file` must sit\n * inside a `denyReadPaths` entry (it holds the key), or preflight refuses.\n * An `own` run writes no tool config (it uses the user's servers); its\n * identity-line file is written beside `file` all the same.\n */\nexport interface ClaudeAnswerMcp {\n readonly file: string\n readonly apiBase: string\n readonly apiKey: () => string | null\n /** The version named in `X-AgentChat-Client-Version` (the front door that placed the run). Defaults to this engine's. */\n readonly clientVersion?: string\n}\n\nexport interface ClaudeRunnerOptions {\n readonly configDir: string | undefined\n /**\n * The run's working directory; the `work` profile edits and runs shell here.\n * Must lie outside `denyReadPaths`, or the run cannot read its own cwd —\n * preflight says so once and still runs. An `own` or `answer` run whose\n * workdir is the home folder or contains it works in\n * `claudeAnswerFallbackWorkdir` instead.\n */\n readonly workdir: string\n readonly profile: RunProfile\n /** Paths every run's file tools are denied: the key store (identity home, the user-scope MCP state). */\n readonly denyReadPaths: readonly string[]\n /** See `ClaudeRunArgOptions.mcpConfigPath`: every profile, strict. */\n readonly mcpConfigPath?: string\n /**\n * See `ClaudeAnswerMcp`. Without it (and without `mcpConfigPath`) an `answer`\n * run does not start: it would load every MCP server the user registered.\n */\n readonly answerMcp?: ClaudeAnswerMcp\n /** The one-line fix printed when the workdir sits inside a denied path. */\n readonly workdirAdvice?: string\n /**\n * A deny path no rule can carry (a comma or whitespace in it; every path on\n * Windows): `warn` (default) logs it once and runs — the run can then read\n * that path; `refuse` fails preflight with the reason, so no run starts.\n */\n readonly inexpressibleDeny?: 'warn' | 'refuse'\n /** Test seam: the binary to run. */\n readonly command?: string\n readonly env?: NodeJS.ProcessEnv\n}\n\n/**\n * The folder an `own` or `answer` run works in when its configured workdir is\n * the user's home folder or contains it (`workdirExposesHome`): an empty folder\n * of its own beside Claude Code's config, never inside a denied path. The run\n * keeps working — it only cannot read the user's files. An `own` run needs\n * this as much: Claude Code lets a run read its working directory without\n * asking in every permission mode, so a home-folder workdir would hand a\n * peer-started run `~/.ssh` whatever the user's allow rules say.\n */\nexport function claudeAnswerFallbackWorkdir(configDirOverride: string | undefined): string {\n return path.join(claudeHomeFor(configDirOverride), 'agentchat-answer-workdir')\n}\n\n/** The profiles whose runs never work in the home folder or above it (`claudeAnswerFallbackWorkdir`). */\nfunction guardsHomeWorkdir(profile: RunProfile): boolean {\n return profile === 'answer' || profile === 'own'\n}\n\nexport class ClaudeRunner implements RunRunner {\n readonly name = 'claude'\n readonly label = 'Claude Code'\n private readonly command: string\n /** The workdir warning is one line per process, not one per preflight (preflight repeats every few minutes). */\n private warnedWorkdir = false\n private warnedDeny = false\n private warnedHome = false\n\n constructor(private readonly options: ClaudeRunnerOptions) {\n this.command = options.command ?? 'claude'\n }\n\n /**\n * Where this runner's runs work: the configured workdir, except that an\n * `own` or `answer` run never works in the home folder or above it — it gets\n * `claudeAnswerFallbackWorkdir` (its readable folder would be the whole home).\n */\n workdir(): string {\n if (guardsHomeWorkdir(this.options.profile) && workdirExposesHome(this.options.workdir)) return claudeAnswerFallbackWorkdir(this.options.configDir)\n return this.options.workdir\n }\n\n /** The denied path the workdir sits in, or null when the run can read its own cwd. */\n workdirDeniedBy(): string | null {\n return deniedAncestorOf(this.workdir(), this.options.denyReadPaths)\n }\n\n async preflight(options: RunPreflightOptions = {}): Promise<RunPreflight> {\n const runtime = await inspectClaudeRuntime(this.options.configDir, this.command, PROBE_TIMEOUT_MS, options.signal)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n const signIn = await claudeSignIn(this.options.configDir, this.command, PROBE_TIMEOUT_MS, options.signal)\n if (signIn.unanswered !== null) return { ok: false, detail: signIn.unanswered }\n if (!signIn.signedIn) return { ok: false, detail: 'claude is not signed in (run `claude` once and sign in)' }\n if (this.options.profile === 'answer' && this.options.mcpConfigPath === undefined) {\n const answerMcp = this.options.answerMcp\n // Fail closed: without an AgentChat-only tool config the run would load\n // every MCP server the user registered.\n if (answerMcp === undefined) {\n return { ok: false, detail: 'an answer run needs the AgentChat-only tool config (ClaudeRunnerOptions.answerMcp): without it the run would load every MCP server the user registered' }\n }\n if (deniedAncestorOf(answerMcp.file, this.options.denyReadPaths) === null) {\n return { ok: false, detail: `the answer runs' tool config ${answerMcp.file} holds the key and must sit inside a path the runs are denied (${this.options.denyReadPaths.join(', ')})` }\n }\n }\n if (this.options.profile === 'answer') {\n const grant = claudeExtraDirectoriesGrant(this.options.configDir, this.workdir())\n if (grant !== null) return { ok: false, detail: extraDirectoriesRefusal(grant) }\n }\n if (this.workdir() !== this.options.workdir && !this.warnedHome) {\n this.warnedHome = true\n log.warn(`the run workdir ${this.options.workdir} is your home folder or contains it: ${this.options.profile} runs work in ${this.workdir()} instead, so a peer-started run reads none of your files there. Point the workdir at a folder of its own to choose another.`)\n }\n // A cwd inside the key store is an operator choice the deny rules then\n // make unreadable to the run. Said once, with the fix; the run still\n // starts — the hosted tools do not need the cwd.\n const denied = this.workdirDeniedBy()\n if (denied !== null && !this.warnedWorkdir) {\n this.warnedWorkdir = true\n log.warn(\n `the run workdir ${this.workdir()} is inside ${denied}, which every run's file tools are denied: runs cannot read their own working directory.${this.options.workdirAdvice ? ` ${this.options.workdirAdvice}` : ''}`,\n )\n }\n const uncovered = inexpressibleDenyPaths(this.readDenyPaths())\n if (uncovered.length > 0) {\n const why =\n process.platform === 'win32'\n ? `Claude Code's rule syntax for Windows paths is undocumented, so no read-deny rule is given for ${uncovered.join(', ')}`\n : `no read-deny rule can carry ${uncovered.join(', ')} (a comma or whitespace in the path)`\n if (this.options.inexpressibleDeny === 'refuse') return { ok: false, detail: `${why}: a run could read the key there. Use an identity home whose path has no comma or whitespace (--home).` }\n if (!this.warnedDeny) {\n this.warnedDeny = true\n log.warn(`${why}: runs can read those paths.`)\n }\n }\n if (this.options.mcpConfigPath !== undefined && !fs.existsSync(this.options.mcpConfigPath)) {\n return { ok: false, detail: `the hosted tool config ${this.options.mcpConfigPath} is missing` }\n }\n // Owner-only on creation, as the identity home is. Creation only: an\n // operator's own workspace keeps its permissions.\n fs.mkdirSync(this.workdir(), { recursive: true, mode: 0o700 })\n return { ok: true }\n }\n\n /** `<dir>/<stem>.<run id><ext>`: a file of this run's own beside `file` (the run id reduced to letters, digits and `-`). */\n private static perRun(file: string, runId: string, ext: string): string {\n const stem = path.basename(file, path.extname(file))\n const id = runId.replace(/[^A-Za-z0-9-]/g, '').slice(0, 64) || 'run'\n return path.join(path.dirname(file), `${stem}.${id}${ext}`)\n }\n\n /**\n * A run's own files for `runId`: an answer run's AgentChat-only tool config\n * (integration path), and the identity-line file of an answer or own run.\n * `work` and `full` write none (they load CLAUDE.md, as before).\n */\n private runFiles(runId: string): { mcpConfigPath?: string; identityFile?: string } {\n const profile = this.options.profile\n if (profile !== 'answer' && profile !== 'own') return {}\n const base = this.options.mcpConfigPath ?? this.options.answerMcp?.file\n return {\n ...(profile === 'answer' && this.options.mcpConfigPath === undefined && this.options.answerMcp !== undefined ? { mcpConfigPath: ClaudeRunner.perRun(this.options.answerMcp.file, runId, '.json') } : {}),\n ...(base !== undefined ? { identityFile: ClaudeRunner.perRun(base, runId, '.identity.md') } : {}),\n }\n }\n\n /**\n * What this runner's runs are denied reading: the key store, and for an\n * `answer` run also Claude Code's own record of every project\n * (`<config dir>/projects`: transcripts and auto memory). Claude Code lets a\n * run read its project's memory folder even with auto memory off and reads\n * blocked outside the working directories (seen on 2.1.322); a deny rule\n * wins over that.\n */\n readDenyPaths(): string[] {\n return this.options.profile === 'answer' ? [...this.options.denyReadPaths, claudeProjectsDirFor(this.options.configDir)] : [...this.options.denyReadPaths]\n }\n\n private argsFor(mcpConfigPath: string | undefined, appendSystemPromptFile: string | undefined): string[] {\n return claudeRunArgs(this.options.profile, {\n maxBudgetUsd: (this.options.env ?? process.env)['AGENTCHAT_RUN_MAX_BUDGET_USD'],\n workdir: this.workdir(),\n denyReadPaths: this.readDenyPaths(),\n ...(mcpConfigPath !== undefined ? { mcpConfigPath } : {}),\n ...(appendSystemPromptFile !== undefined ? { appendSystemPromptFile } : {}),\n })\n }\n\n /**\n * The argv of a run — exported for tests to pin per profile. With a `runId`,\n * that run's own files (an answer run's tool config, an answer or own run's\n * identity-line file); without, the configured `answerMcp.file` stands in\n * for an answer run's tool config, and no identity file.\n */\n args(runId?: string, identityLine?: boolean): string[] {\n if (runId === undefined) {\n const mcpConfigPath = this.options.mcpConfigPath ?? (this.options.profile === 'answer' ? this.options.answerMcp?.file : undefined)\n return this.argsFor(mcpConfigPath, undefined)\n }\n const files = this.runFiles(runId)\n return this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityLine === true ? files.identityFile : undefined)\n }\n\n /**\n * The run's environment: no parent session; an answer run loads no CLAUDE.md\n * and no auto memory (`ANSWER_ENV`); an own run carries no `AGENTCHAT_API_KEY`\n * the daemon inherited — it has the user's own shell, and it reaches the\n * hosted tools through its MCP entry, never through that variable.\n */\n runEnv(): NodeJS.ProcessEnv {\n const source = this.options.env ?? process.env\n const env = buildClaudeEnv(this.options.configDir, this.options.profile === 'own' ? withoutInheritedKey(source) : source)\n return this.options.profile === 'answer' ? { ...env, ...ANSWER_ENV } : env\n }\n\n /**\n * Does the model answer right now, through this runner's binary, sign-in\n * and environment? One `claude -p` with a fixed prompt and no tool at all\n * (`claudeRuntimeCheckArgs`), in its own empty folder, with no key in its\n * environment and no instruction file or memory in its context; ok only\n * when its JSON result says success with no error (`claudeRuntimeCheckJudge`).\n * Its output is read for that alone and never logged. Never throws.\n */\n async checkRuntime(options: RunPreflightOptions = {}): Promise<RunPreflight> {\n return runRuntimeCheck({\n label: 'claude',\n command: this.command,\n args: claudeRuntimeCheckArgs(this.readDenyPaths()),\n cwd: claudeRuntimeCheckWorkdir(this.options.configDir),\n // No key (runRuntimeCheck takes every key variable out); no instruction file or memory.\n env: { ...this.runEnv(), ...ANSWER_ENV },\n // Exit 0 is not enough: the JSON result must say success with no error.\n judge: claudeRuntimeCheckJudge,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n })\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const startedAt = Date.now()\n const notStarted = (detail: string): RunOutcome => ({ state: 'not_started', exitCode: null, durationMs: Date.now() - startedAt, detail })\n const answer = this.options.profile === 'answer'\n // An answer run's own AgentChat-only tool config: written for this run, removed after it.\n const answerMcp = answer && this.options.mcpConfigPath === undefined ? this.options.answerMcp : undefined\n if (answer && this.options.mcpConfigPath === undefined && answerMcp === undefined) {\n return notStarted('an answer run needs the AgentChat-only tool config (ClaudeRunnerOptions.answerMcp)')\n }\n // Settings can change while the daemon runs: checked before every answer run, not only at preflight.\n if (answer) {\n const grant = claudeExtraDirectoriesGrant(this.options.configDir, this.workdir())\n if (grant !== null) return notStarted(extraDirectoriesRefusal(grant))\n }\n const files = this.runFiles(request.runId)\n // answer: it loads no CLAUDE.md. own: whatever CLAUDE.md holds, the run is told who it is (a listener's agent is not the one there).\n const identityFile = request.identityLine !== undefined ? files.identityFile : undefined\n const written: string[] = []\n const cleanup = (): void => {\n for (const file of written) fs.rmSync(file, { force: true })\n }\n if (answerMcp !== undefined && files.mcpConfigPath !== undefined) {\n const key = answerMcp.apiKey()\n if (key === null) return notStarted('no AgentChat key for the answer run\\'s tool config')\n try {\n atomicWriteFile(files.mcpConfigPath, claudeMcpConfig(answerMcp.apiBase, key, answerMcp.clientVersion ?? VERSION), 0o600)\n written.push(files.mcpConfigPath)\n } catch (err) {\n cleanup()\n return notStarted(`could not write the answer run's tool config ${files.mcpConfigPath}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n if (identityFile !== undefined && request.identityLine !== undefined) {\n try {\n atomicWriteFile(identityFile, `${request.identityLine.trim()}\\n`, 0o600)\n written.push(identityFile)\n } catch (err) {\n cleanup()\n return notStarted(`could not write the run's identity line ${identityFile}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n try {\n const args = this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityFile)\n log.debug(`claude ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId}${request.conversationId !== undefined ? ` for ${request.conversationId}` : ''})`)\n return await spawnRun({\n command: this.command,\n args,\n cwd: this.workdir(),\n env: this.runEnv(),\n stdin: request.prompt,\n budgetMs: request.budgetMs,\n // Stopping SIGTERMs this run's process group instead of orphaning it.\n ...(request.signal ? { signal: request.signal } : {}),\n // The engine records a group invite as offered the moment the process\n // has spawned, so a run cut short still counts as the one offer.\n ...(request.onStarted ? { onStarted: request.onStarted } : {}),\n })\n } finally {\n // Only this run's own files: a late cleanup can never touch another run's.\n cleanup()\n }\n }\n}\n\n/** Where a listener keeps the `--mcp-config` file for this preset, inside its identity home. */\nexport function claudeMcpConfigPath(home: string): string {\n return path.join(home, 'presets', `${CLAUDE_CODE_PRESET}.mcp.json`)\n}\n\nexport const claudeCodePreset: Preset = {\n name: CLAUDE_CODE_PRESET,\n describeMcp({ home, apiBase, profile }) {\n return [\n `--mcp-config ${claudeMcpConfigPath(home)} (owner-only): ${CLAUDE_MCP_SERVER_NAME} → ${hostedMcpUrl(apiBase)}, Authorization: Bearer <this home's key>, X-AgentChat-Client: claude-code`,\n profile === 'own'\n ? `own: your other MCP servers load too (the file is not made the only one); this file's ${CLAUDE_MCP_SERVER_NAME} is used in place of a user-scope ${CLAUDE_MCP_SERVER_NAME} (verified); a project- or local-scope one is not covered`\n : '--strict-mcp-config: no other MCP server (user, project or plugin) is loaded in these runs',\n ]\n },\n label: 'Claude Code',\n runtime: 'claude-code',\n // Every run's file tools are denied the identity home.\n serviceEnv: ['CLAUDE_CONFIG_DIR'],\n readsIdentityHome: false,\n async inspect(env = process.env, command = 'claude') {\n const configDir = claudeConfigDirFrom(env)\n const runtime = await inspectClaudeRuntime(configDir, command)\n if (!runtime.ok) return runtime\n const signIn = await claudeSignIn(configDir, command)\n if (signIn.unanswered !== null) return { ok: false, detail: `${runtime.detail}, ${signIn.unanswered}` }\n return signIn.signedIn\n ? { ok: true, detail: `${runtime.detail}, signed in` }\n : { ok: false, detail: `${runtime.detail}, not signed in (run \\`claude\\` once and sign in)` }\n },\n runner(ctx: PresetContext): RunRunner {\n // A key in the listener's own environment is not handed to its runs.\n const env = withoutInheritedKey(ctx.env ?? process.env)\n const configDir = claudeConfigDirFrom(env)\n const mcpConfigPath = claudeMcpConfigPath(ctx.home)\n // Rewritten for every identity the listener serves: the runs act as THIS agent.\n atomicWriteFile(mcpConfigPath, claudeMcpConfig(ctx.apiBase, ctx.apiKey, ctx.clientVersion ?? VERSION), 0o600)\n return new ClaudeRunner({\n configDir,\n workdir: ctx.workdir,\n profile: ctx.profile,\n // The listener's home (its key and this file), the user-scope MCP state\n // and an integration's identity home beside it: no run reads a key.\n denyReadPaths: [ctx.home, claudeUserStatePathFor(configDir), path.join(claudeHomeFor(configDir), 'agentchat')],\n mcpConfigPath,\n workdirAdvice: 'Start the listener from a directory outside it, or pass --workdir.',\n // On POSIX a listener's run must not start with its key readable; on\n // Windows no rule exists at all (documented), so it warns.\n inexpressibleDeny: process.platform === 'win32' ? 'warn' : 'refuse',\n ...(ctx.command !== undefined ? { command: ctx.command } : {}),\n env,\n })\n },\n}\n","/** `actual` (any text containing `x.y.z`) is at least `minimum`. False when either has no version in it. */\nexport function semverAtLeast(actual: string, minimum: string): boolean {\n const parse = (value: string): [number, number, number] | null => {\n const match = value.match(/(\\d+)\\.(\\d+)\\.(\\d+)/)\n return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null\n }\n const a = parse(actual)\n const b = parse(minimum)\n if (a === null || b === null) return false\n for (let index = 0; index < 3; index++) {\n if (a[index] !== b[index]) return (a[index] ?? 0) > (b[index] ?? 0)\n }\n return true\n}\n","import * as fs from 'node:fs'\nimport type { RunPreflight } from '../integration/runner.js'\nimport { spawnRunCapturing } from '../integration/spawn-run.js'\n\n// ─── The runtime check: does the agent's AI answer right now? ───────────────\n//\n// After a conversation's run failed, and no other run has completed since,\n// the SDK kit asks the runner whether the runtime works (`checkRuntime`): an\n// `ok` is the evidence that the failure belongs to that conversation (a\n// provider refusal, a crash on its content), and the kit reports it (could\n// not process). So the check must prove the model answers NOW, through the\n// same binary, account and environment the runs use — a `--version` or a\n// sign-in check passes during a provider outage, and an outage reported as\n// the conversation's failure would hide its messages.\n//\n// The check is one headless run of the runtime with a fixed prompt: no peer\n// content, no AgentChat tools, nothing a run could act on, in an empty folder\n// of its own. Exit 0 with some text is not enough (a usage limit, a low\n// credit balance or an expired sign-in can print a sentence and still be no\n// answer): a runtime whose result says what happened is judged on it\n// (`judge`: Claude Code's JSON result, Codex's `--json` events). For that, the first\n// `RUNTIME_CHECK_OUTPUT_BYTES` of its stdout are kept for the check alone —\n// the prompt is ours, so it holds no peer content — read, and dropped; never\n// logged. Only \"it answered\" and a bounded, redacted diagnostic come back. It\n// is bounded so that its kill path ends inside the engine's 60 s deadline, and\n// it stops (its process group killed) when the integration stops.\n\n/** The fixed prompt: nothing from any peer, nothing to act on. */\nexport const RUNTIME_CHECK_PROMPT = 'Reply with the single word OK.'\n\n\n/**\n * The check's own budget. Past it the probe is SIGTERMed, SIGKILLed 5 s later\n * and given up 5 s after that: 55 s at most, inside the engine's\n * `RUNTIME_CHECK_DEADLINE_MS` (60 s).\n */\nexport const RUNTIME_CHECK_BUDGET_MS = 45_000\n\n/** The most of a check's stdout kept for its `judge` (a result line is a few kB); more is not read. */\nexport const RUNTIME_CHECK_OUTPUT_BYTES = 128 * 1024\n\n/** The name of the empty folder a runtime check runs in, beside the runtime's own config. */\nexport const RUNTIME_CHECK_DIR = 'agentchat-runtime-check'\n\n/**\n * The variables an AgentChat key travels in (the daemon's own, the listener's\n * Codex bearer variable): never in a runtime check's environment, whatever\n * the runs carry. The check needs no key.\n */\nexport const RUNTIME_CHECK_KEY_ENV: readonly string[] = ['AGENTCHAT_API_KEY', 'AGENTCHAT_LISTENER_API_KEY']\n\n/** `env` without the key variables (`RUNTIME_CHECK_KEY_ENV` and `also`), in any case. */\nfunction withoutKeys(env: NodeJS.ProcessEnv, also: readonly string[]): NodeJS.ProcessEnv {\n const names = new Set([...RUNTIME_CHECK_KEY_ENV, ...also].map((name) => name.toUpperCase()))\n const out: NodeJS.ProcessEnv = {}\n for (const [key, value] of Object.entries(env)) if (!names.has(key.toUpperCase())) out[key] = value\n return out\n}\n\nexport interface RuntimeCheckSpec {\n /** The runtime's name, for the diagnostic. */\n readonly label: string\n readonly command: string\n readonly args: readonly string[]\n /** An empty folder of the check's own (created owner-only). */\n readonly cwd: string\n /** The runs' environment; the key variables are taken out (`RUNTIME_CHECK_KEY_ENV`, `keyEnv`). */\n readonly env: NodeJS.ProcessEnv\n /** Another variable this runtime's runs carry a key in (a Codex runner's `keyEnv`). */\n readonly keyEnv?: string\n readonly signal?: AbortSignal\n /**\n * Reads the runtime's answer (its stdout, bounded) after an exit 0: null\n * when it is a good answer, else why not (ids and flags only, never the\n * text). Absent: exit 0 with something on stdout is ok.\n */\n readonly judge?: (stdout: string) => string | null\n /** Test seam: `RUNTIME_CHECK_BUDGET_MS`. */\n readonly budgetMs?: number\n}\n\n/** Run the check once: ok when the runtime exited 0 having printed an answer. Never throws. */\nexport async function runRuntimeCheck(spec: RuntimeCheckSpec): Promise<RunPreflight> {\n if (spec.signal?.aborted === true) return { ok: false, detail: `${spec.label} runtime check: stopped before it started` }\n try {\n fs.mkdirSync(spec.cwd, { recursive: true, mode: 0o700 })\n } catch (err) {\n return { ok: false, detail: `${spec.label} runtime check: could not create its folder ${spec.cwd}: ${err instanceof Error ? err.message : String(err)}` }\n }\n const { outcome, stdout } = await spawnRunCapturing({\n command: spec.command,\n args: spec.args,\n cwd: spec.cwd,\n env: withoutKeys(spec.env, spec.keyEnv !== undefined ? [spec.keyEnv] : []),\n stdin: RUNTIME_CHECK_PROMPT,\n budgetMs: spec.budgetMs ?? RUNTIME_CHECK_BUDGET_MS,\n requireStdout: true,\n ...(spec.signal !== undefined ? { signal: spec.signal } : {}),\n }, spec.judge !== undefined ? RUNTIME_CHECK_OUTPUT_BYTES : 0)\n if (outcome.state !== 'ok') return { ok: false, detail: `${spec.label} runtime check ${outcome.state.replace('_', ' ')}${outcome.detail ? `: ${outcome.detail}` : ''}` }\n const verdict = spec.judge === undefined ? null : spec.judge(stdout)\n return verdict === null ? { ok: true } : { ok: false, detail: `${spec.label} runtime check failed: exit 0, but ${verdict}` }\n}\n","import type { TextsRuntime } from 'agentchatme'\nimport type { RunProfile } from '../integration/profile.js'\nimport type { RunRunner } from '../integration/runner.js'\n\n// ─── Presets: how to start one headless run of a known coding agent ─────────\n//\n// The engine (everything in this package outside `presets/`) names no coding\n// agent and never imports from here; `tests/core-is-host-agnostic`\n// asserts both. A preset is the one place that does: the flags a runtime's\n// headless mode takes per run profile, how to tell it is installed and signed\n// in, and how a run of it reaches the hosted AgentChat tools AS a given agent.\n//\n// Two front doors select one, and only ever for the run command: the\n// `agentchat listen --preset <name>` listener (@agentchatme/cli; its identity\n// is the listener's own home, injected into each run), and the runtime's own\n// integration package (its identity home and placement stay the integration's). A preset\n// never decides which identity home is acted on — the caller passes it.\n\n/** What a preset needs to build a runner acting as one agent. */\nexport interface PresetContext {\n /** The identity home of the agent the runs act as. Runs' file tools are kept off it where the runtime allows. */\n readonly home: string\n /** The run's working directory. */\n readonly workdir: string\n readonly profile: RunProfile\n /** The agent's key and API base, for the hosted tool server the runs reach. Never put on argv. */\n readonly apiKey: string\n readonly apiBase: string\n /** The environment runs inherit (defaults to `process.env`). */\n readonly env?: NodeJS.ProcessEnv\n /** Test seam: the runtime's binary. */\n readonly command?: string\n /**\n * The version the runs name in `X-AgentChat-Client-Version`: the front door\n * that placed them (the `agentchat` listener passes its own). Defaults to\n * this engine's version. The client name is the runtime's (`claude-code`,\n * `codex`): a run the listener wakes needs no wake-webhook tools, and the\n * hosted tools spell their names per runtime by it.\n */\n readonly clientVersion?: string\n}\n\nexport interface PresetInspection {\n readonly ok: boolean\n readonly detail: string\n}\n\nexport interface Preset {\n /** The name a user types (`--preset <name>`). */\n readonly name: string\n /** Human name for output. */\n readonly label: string\n /** How the served texts spell the hosted tools for this runtime (`GET /v1/texts?runtime=`). */\n readonly runtime: TextsRuntime\n /**\n * Is the runtime installed, new enough and signed in? For `doctor` and\n * `status`. Async: its probes are killed with their whole tree when they\n * hang (a Windows `.cmd` shim, an npm launcher), never left blocking.\n */\n inspect(env?: NodeJS.ProcessEnv, command?: string): Promise<PresetInspection>\n /**\n * A runner whose runs act as the agent in `ctx`: the hosted tool server is\n * given to each run with that agent's key (a file or an environment\n * variable, never an argument), whatever the runtime's own configuration\n * registers. May write owner-only files into `ctx.home`.\n */\n runner(ctx: PresetContext): RunRunner\n /**\n * The hosted-tool configuration a listener's run of this preset sees, as\n * lines for `doctor` (keys never printed): what the run is given, and what\n * of the user's own configuration still applies. `profile` is the\n * listener's (`own` changes what is given); absent, the lines are those of\n * the other profiles.\n */\n describeMcp(ctx: { readonly home: string; readonly apiBase: string; readonly env?: NodeJS.ProcessEnv; readonly profile?: RunProfile }): string[]\n /** Variables a service must capture for this runtime (where it keeps its config, when relocated). */\n readonly serviceEnv: readonly string[]\n /** Whether the run can read files under the identity home (decides how the manual is pointed to). */\n readonly readsIdentityHome: boolean\n}\n\n// ─── A run's environment carries nothing of the session that started it ─────\n//\n// A listener or daemon started from inside a Claude Code or Codex session\n// inherits that session's variables, and every run it starts would too: a\n// session id, a messaging socket and its token (CLAUDE_CODE_MESSAGING_TOKEN\n// lets a process post into the parent session), a sandbox marker\n// (CODEX_SANDBOX makes a child believe it is already sandboxed). They are the\n// parent's, never the run's, in every profile.\n\n/**\n * Documented `CLAUDE_CODE_*` variables that configure how Claude Code signs in\n * and reaches its provider, or switch off traffic and secrets — the user's own\n * settings, kept (code.claude.com/docs/en/env-vars). Every other `CLAUDE_CODE_*`\n * variable is dropped: the ones Claude Code sets for the processes it spawns\n * share the prefix (CLAUDE_CODE_SESSION_ID, _CHILD_SESSION, _MESSAGING_SOCKET,\n * _MESSAGING_TOKEN, _BRIDGE_SESSION_ID, _REMOTE_SESSION_ID, …), and a variable\n * not listed here is one a headless run can do without.\n */\nexport const CLAUDE_CODE_ENV_KEPT: readonly string[] = [\n // Sign-in and provider\n 'CLAUDE_CODE_OAUTH_TOKEN',\n 'CLAUDE_CODE_OAUTH_REFRESH_TOKEN',\n 'CLAUDE_CODE_OAUTH_SCOPES',\n 'CLAUDE_CODE_API_KEY_HELPER_TTL_MS',\n 'CLAUDE_CODE_USE_BEDROCK',\n 'CLAUDE_CODE_USE_VERTEX',\n 'CLAUDE_CODE_USE_FOUNDRY',\n 'CLAUDE_CODE_USE_MANTLE',\n 'CLAUDE_CODE_USE_ANTHROPIC_AWS',\n 'CLAUDE_CODE_SKIP_BEDROCK_AUTH',\n 'CLAUDE_CODE_SKIP_VERTEX_AUTH',\n 'CLAUDE_CODE_SKIP_FOUNDRY_AUTH',\n 'CLAUDE_CODE_SKIP_MANTLE_AUTH',\n 'CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH',\n 'CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS',\n // Network and TLS\n 'CLAUDE_CODE_CLIENT_CERT',\n 'CLAUDE_CODE_CLIENT_KEY',\n 'CLAUDE_CODE_CLIENT_KEY_PASSPHRASE',\n 'CLAUDE_CODE_CERT_STORE',\n 'CLAUDE_CODE_PROXY_RESOLVES_HOSTS',\n 'CLAUDE_CODE_CONNECT_TIMEOUT_MS',\n // Privacy and secrets switches the user turned on\n 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC',\n 'CLAUDE_CODE_ENABLE_TELEMETRY',\n 'CLAUDE_CODE_SUBPROCESS_ENV_SCRUB',\n 'CLAUDE_CODE_MCP_ALLOWLIST_ENV',\n 'CLAUDE_CODE_DISABLE_CLAUDE_MDS',\n 'CLAUDE_CODE_DISABLE_AUTO_MEMORY',\n // Model request settings the user chose\n 'CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS',\n 'CLAUDE_CODE_EXTRA_BODY',\n 'CLAUDE_CODE_MAX_OUTPUT_TOKENS',\n // Platform\n 'CLAUDE_CODE_GIT_BASH_PATH',\n 'CLAUDE_CODE_TMPDIR',\n // Set by the preset itself (a larger value of the user's is kept)\n 'CLAUDE_CODE_MCP_STARTUP_WAIT_MS',\n]\n\n/**\n * Claude Code session variables outside the `CLAUDE_CODE_` prefix\n * (code.claude.com/docs/en/env-vars, hooks.md): what it sets in the processes\n * it spawns — its pid, the effort level, a background job's folder, the\n * project folder, the W3C trace context — and `AI_AGENT`. Not `CLAUDE_ENV_FILE`:\n * that one the user sets (a file sourced before each shell command).\n */\nexport const CLAUDE_SESSION_ENV: readonly string[] = ['CLAUDECODE', 'CLAUDE_PID', 'CLAUDE_EFFORT', 'CLAUDE_JOB_DIR', 'CLAUDE_PROJECT_DIR', 'TRACEPARENT', 'TRACESTATE', 'AI_AGENT']\n\n/**\n * What a Codex session sets in the processes it spawns (openai/codex at\n * rust-v0.154.0: core/src/spawn.rs, core/src/exec_env.rs,\n * protocol/src/shell_environment.rs, network-proxy/src/proxy.rs,\n * shell-escalation/src/unix/escalate_protocol.rs). Not the whole `CODEX_`\n * prefix: CODEX_HOME, CODEX_API_KEY, CODEX_CA_CERTIFICATE are the user's.\n */\nexport const CODEX_SESSION_ENV: readonly string[] = [\n 'CODEX_SANDBOX',\n 'CODEX_SANDBOX_NETWORK_DISABLED',\n 'CODEX_SESSION_ID',\n 'CODEX_THREAD_ID',\n 'CODEX_VERSION',\n 'CODEX_PERMISSION_PROFILE',\n 'CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN',\n 'CODEX_ESCALATE_SOCKET',\n 'CODEX_NETWORK_PROXY_ACTIVE',\n 'CODEX_NETWORK_ALLOW_LOCAL_BINDING',\n 'CODEX_NETWORK_PROXY_ATTRIBUTION',\n 'CODEX_NETWORK_PROXY_CREDENTIAL_BROKER_ACTIVE',\n 'CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS',\n 'CODEX_WINDOWS_SANDBOX_PROXY_PORTS',\n]\n\n/**\n * What a Codex session's managed network proxy puts in its children's\n * environment (openai/codex rust-v0.154.0 network-proxy/src/proxy.rs:578-628\n * `PROXY_ENV_KEYS`): proxy URLs pointing at the parent's proxy, which dies\n * with it. Dropped only when the environment says that proxy was active\n * (`CODEX_NETWORK_PROXY_ACTIVE`): otherwise they are the user's own proxy.\n */\nexport const CODEX_MANAGED_PROXY_ENV: readonly string[] = [\n 'ELECTRON_GET_USE_PROXY',\n 'NODE_USE_ENV_PROXY',\n 'HTTP_PROXY',\n 'HTTPS_PROXY',\n 'YARN_HTTP_PROXY',\n 'YARN_HTTPS_PROXY',\n 'NPM_CONFIG_HTTP_PROXY',\n 'NPM_CONFIG_HTTPS_PROXY',\n 'NPM_CONFIG_PROXY',\n 'BUNDLE_HTTP_PROXY',\n 'BUNDLE_HTTPS_PROXY',\n 'PIP_PROXY',\n 'DOCKER_HTTP_PROXY',\n 'DOCKER_HTTPS_PROXY',\n 'WS_PROXY',\n 'WSS_PROXY',\n 'NO_PROXY',\n 'NPM_CONFIG_NOPROXY',\n 'YARN_NO_PROXY',\n 'BUNDLE_NO_PROXY',\n 'ALL_PROXY',\n 'FTP_PROXY',\n]\n\n/** The CA-bundle variables Codex points at its managed proxy's bundle (network-proxy/src/certs.rs:157-169 `CUSTOM_CA_ENV_KEYS`). */\nconst CODEX_CA_ENV_KEYS: readonly string[] = [\n 'CODEX_CA_CERTIFICATE',\n 'SSL_CERT_FILE',\n 'REQUESTS_CA_BUNDLE',\n 'CURL_CA_BUNDLE',\n 'NODE_EXTRA_CA_CERTS',\n 'GIT_SSL_CAINFO',\n 'CARGO_HTTP_CAINFO',\n 'PIP_CERT',\n 'BUNDLE_SSL_CA_CERT',\n 'NPM_CONFIG_CAFILE',\n]\n\n/**\n * The managed proxy's generated trust bundle, in Codex's own form:\n * `<CODEX_HOME>/proxy/ca-bundle-<64 hex>.pem` (certs.rs:149-152, 434-455, 476).\n * Checked only while the parent's proxy marker is set, so a user's corporate\n * `SSL_CERT_FILE` (or one that merely sits in a folder named `proxy`) stays.\n */\nfunction isManagedCaBundle(value: string): boolean {\n return /[\\\\/]proxy[\\\\/]ca-bundle-[0-9a-fA-F]{64}\\.pem$/.test(value)\n}\n\n/** The managed proxy's `GIT_SSH_COMMAND` starts with this marker (proxy.rs `CODEX_PROXY_GIT_SSH_COMMAND_MARKER`). */\nconst CODEX_PROXY_GIT_SSH_MARKER = 'CODEX_PROXY_GIT_SSH_COMMAND=1 '\n\n/** Whether `key` is a parent session's variable by its name alone. Case-insensitive, as Windows names are. */\nexport function isParentSessionEnv(key: string): boolean {\n const upper = key.toUpperCase()\n if (upper.startsWith('CLAUDE_CODE_')) return !CLAUDE_CODE_ENV_KEPT.includes(upper)\n return CLAUDE_SESSION_ENV.includes(upper) || CODEX_SESSION_ENV.includes(upper)\n}\n\n/** The value of `name` in `env`, whatever its case. */\nfunction envValue(env: NodeJS.ProcessEnv, name: string): string | undefined {\n for (const [key, value] of Object.entries(env)) if (key.toUpperCase() === name) return value\n return undefined\n}\n\n/**\n * The variable names a Codex credential broker replaced with dummy values\n * (`CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS`: a JSON list of [name, dummy]),\n * where the environment still holds that dummy (credential_broker.rs:520-531).\n */\nfunction brokeredDummies(env: NodeJS.ProcessEnv): Set<string> {\n const marker = envValue(env, 'CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS')\n const out = new Set<string>()\n if (marker === undefined) return out\n let pairs: unknown\n try {\n pairs = JSON.parse(marker)\n } catch {\n return out\n }\n if (!Array.isArray(pairs)) return out\n for (const pair of pairs) {\n if (!Array.isArray(pair) || typeof pair[0] !== 'string' || typeof pair[1] !== 'string') continue\n if (envValue(env, pair[0].toUpperCase()) === pair[1]) out.add(pair[0].toUpperCase())\n }\n return out\n}\n\n/**\n * A copy of `env` without any Claude Code or Codex parent-session variable:\n * what every preset run, in every profile, starts from. By name: the session\n * markers above. By value: a parent Codex proxy's URLs and its generated CA\n * bundle (only while its marker says it was active), its SSH command, the\n * dummy credentials its broker substituted. The user's own proxy, CA bundle\n * and settings stay.\n */\nexport function withoutParentSession(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const proxyActive = envValue(env, 'CODEX_NETWORK_PROXY_ACTIVE') !== undefined\n const dummies = brokeredDummies(env)\n const copy: NodeJS.ProcessEnv = {}\n for (const [key, value] of Object.entries(env)) {\n const upper = key.toUpperCase()\n if (isParentSessionEnv(key)) continue\n if (proxyActive && CODEX_MANAGED_PROXY_ENV.includes(upper)) continue\n if (proxyActive && value !== undefined && CODEX_CA_ENV_KEYS.includes(upper) && isManagedCaBundle(value)) continue\n if (value !== undefined && upper === 'GIT_SSH_COMMAND' && value.startsWith(CODEX_PROXY_GIT_SSH_MARKER)) continue\n if (dummies.has(upper)) continue\n copy[key] = value\n }\n return copy\n}\n\n/** The environment a listener's preset runs inherit: the caller's, minus any `AGENTCHAT_API_KEY` in it. */\nexport function withoutInheritedKey(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const copy = { ...env }\n delete copy['AGENTCHAT_API_KEY']\n return copy\n}\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { clientHeadersOf } from '../client-identity.js'\nimport { hostedMcpUrl } from '../integration/mcp-probe.js'\nimport { workdirExposesHome, type RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, RunPreflightOptions, RunRequest, RunRunner } from '../integration/runner.js'\nimport { killProcessTree, redactDiagnostic, spawnRun } from '../integration/spawn-run.js'\nimport { atomicWriteFile } from '../util/fsutil.js'\nimport { log } from '../util/log.js'\nimport { spawnCommand } from '../util/spawn.js'\nimport { runProbe } from '../util/probe.js'\nimport { VERSION } from '../version.js'\nimport { semverAtLeast } from './semver.js'\nimport { RUNTIME_CHECK_DIR, runRuntimeCheck } from './runtime-check.js'\nimport { withoutInheritedKey, withoutParentSession, type Preset, type PresetContext, type PresetInspection } from './types.js'\n\n// ─── Codex: one headless run (`codex exec`) ─────────────────────────────────\n//\n// `codex exec` on the box, riding the user's own Codex sign-in and config. The\n// run's output is discarded by `spawnRun`. Flags, verified against `codex exec\n// --help` (codex-cli 0.154.0) and the openai/codex sources:\n//\n// -s, --sandbox read-only|workspace-write|danger-full-access\n// the sandbox policy for model-generated commands\n// --dangerously-bypass-approvals-and-sandbox\n// skip all confirmation prompts and run unsandboxed\n// -c approval_policy=\"never\" `codex exec` already defaults to `never` in\n// headless mode — passed explicitly so a run can\n// never wait on an approval, whatever a profile\n// or requirements file says.\n// -c mcp_servers.<name>.<key>=… per-run config overrides (TOML values): how a\n// listener points the hosted server at its own\n// agent's key, whatever config.toml registers.\n// --json events as JSONL on stdout (discarded; the first\n// event is how \"started\" is told from \"never got\n// going\")\n// --skip-git-repo-check the run's working directory is not a repository\n// --ephemeral no session files on disk for a wake run\n// -C <dir> the working root\n//\n// The hosted AgentChat tools reach the run through `[mcp_servers.agentchat]`\n// (bearer token from an environment variable named in the config, never the\n// key itself), with `default_tools_approval_mode = \"approve\"` so they never\n// prompt (with `approval_policy = \"never\"`, an MCP tool call that needs\n// approval is denied: codex-rs/core/src/mcp_tool_call.rs).\n//\n// `own` — the agent itself — passes no `--sandbox`, no `approval_policy`, no\n// `--disable` and no permission profile: the user's config.toml (and its\n// profiles, project layers and requirements) decides the sandbox, the web,\n// the tools and the instructions, as in their own `codex exec` runs. Nothing\n// waits on an approval all the same: `codex exec` sets `approval_policy =\n// \"never\"` itself unless the user's config hands approvals to Codex's\n// auto-review (a model, not a person), and it rejects every approval,\n// permission or user-input request a run makes instead of waiting\n// (exec/src/lib.rs at rust-v0.154.0: the headless `AskForApproval::Never`\n// override, `build_exec_config`, `handle_server_request`; verified on the real\n// 0.154.0 with `approval_policy = \"on-request\"` in the user's config: an\n// escalation was rejected at once). The only `-c` keys are AgentChat's own\n// server's (`mcp_servers.agentchat.*`). Codex's sandboxes restrict writes and\n// the network, never reads, so an `own` run's shell can read any file the\n// user can — the identity home's `credentials` included (README, known limits).\n//\n// `answer` — started by any peer's message — must read nothing outside its\n// workdir and have no way out but the AgentChat tools. Codex can restrict a\n// sandbox's READS (a permission profile: `default_permissions` +\n// `[permissions.<name>.filesystem]`), but a shell needs `\":minimal\"` to run at\n// all, and on macOS that also opens /etc, /usr, /Library/Preferences and, for\n// the shell process, read-write /tmp and /var/tmp\n// (codex-rs/sandboxing/src/seatbelt_read_only_platform_defaults.sbpl,\n// seatbelt.rs:27-33; on Linux /etc, /usr, /bin, … in linux-sandbox/src/bwrap.rs).\n// So `answer` has NO shell and no local-file tool (verified against the\n// openai/codex sources at rust-v0.154.0):\n//\n// --disable shell_tool no exec_command / write_stdin\n// (core/src/tools/spec_plan.rs:1083-1088;\n// `unified_exec` cannot be turned off by user\n// config, but it is registered only past\n// this check)\n// --disable view_image, image_generation\n// the image tools that read local files\n// --disable plugins, apps plugin-bundled MCP servers and skills (a\n// computer-use server among them) and the\n// ChatGPT connectors (`codex_apps`)\n// --disable memories the local memory store in CODEX_HOME\n// --disable browser_use, browser_use_external, computer_use, in_app_browser\n// no tool of their own in 0.154.0; off so a\n// later build cannot add one to `answer`\n// -c web_search=\"disabled\" the hosted web search (the top-level key;\n// `tools.web_search=false` is parsed and\n// ignored, config_toml.rs:655-670)\n// -c default_permissions=… + -c permissions.<name>.filesystem={ \":workspace_roots\" = \"read\" }\n// for what cannot be turned off: apply_patch\n// (no feature flag) reads through the sandbox,\n// so it reads only the workdir (`-C`), writes\n// nothing; no network. Replaces\n// `--sandbox read-only`, which reads the whole\n// disk ($CODEX_HOME/.env included).\n//\n// The runtime check (`checkRuntime`, runtime-check.ts) is one `codex exec`\n// with a fixed prompt, the same binary, CODEX_HOME and environment as the runs\n// (no key in it), in an empty folder of its own (`-C`), `--ephemeral`, closed\n// the way an `answer` run is where the 0.154.0 floor allows\n// (`codexRuntimeCheckArgs`):\n//\n// --sandbox read-only nothing written, no network for commands.\n// -c web_search=\"disabled\", --disable memories, plugins, apps\n// as an `answer` run: no web search, no local\n// memory, no plugin-bundled servers or skills,\n// no ChatGPT connectors.\n// -c mcp_servers.agentchat.url=<the runs' URL>, -c mcp_servers.agentchat.enabled=false\n// the hosted AgentChat server switched off\n// (with the URL the table is valid whether or\n// not a config layer defines one).\n//\n// The user's hooks stay ON in the check (no `--disable hooks`), as in the runs.\n// A hook that breaks every real run must fail the check too: otherwise the\n// check passes, the lone conversation whose run failed is reported, and an\n// innocent conversation gets hidden. Claude Code's check keeps hooks off and\n// leans on the silent rule instead: its runs print text only at the end, so a\n// run that dies early says nothing (`RunOutcome.silent`, counted as a timeout,\n// never reported on the check alone). Codex runs print `--json` events from\n// the start, so a broken Codex run is never silent, and only the check can\n// catch it.\n//\n// No reasoning effort is set: the check asks with the effort the runs use (the\n// user's `model_reasoning_effort`, else the model's default). Codex sends a\n// configured effort as is (protocol/src/openai_models/reasoning_effort.rs:\n// only `ultra` and `persistent` are mapped), so `low` would make a model\n// without it (one that accepts only `high`, or no reasoning effort at all)\n// refuse every check; the check would then never pass for that user.\n//\n// The check is ok only on exit 0 AND, in its `--json` events\n// (exec/src/exec_events.rs), a `turn.completed` with an `agent_message` item\n// that holds text, and no `turn.failed` (`codexRuntimeCheckJudge`): exit 0\n// alone is not an answer. The events are read from a bounded capture\n// (`RUNTIME_CHECK_OUTPUT_BYTES`), never logged.\n//\n// The user's OTHER MCP servers still load: Codex 0.154.0 has no documented\n// switch that turns every MCP server off, and switching each off by name\n// (`-c mcp_servers.<name>.enabled=false`) needs the names first — a `codex\n// mcp list --json` per check, as an `answer` run does, which would add its own\n// time and failure to a 45 s probe whose prompt asks for no tool. Codex loads\n// `$CODEX_HOME/.env` itself: an AgentChat key that a Codex integration before\n// 0.5.3 left there is removed by the upgrade (and a listener's own runs do not\n// start while one is there, `ownAuthProblem`). The user's config.toml still\n// decides the model and its provider, as for the runs. Verified on 0.154.0\n// against a stand-in provider: these flags parse with and without an\n// `agentchat` table in config.toml; the model is offered no agentchat tool and\n// no web search; a provider error exits 1 and an answer exits 0. Rechecked for\n// 0.7.1 (stand-in provider): the request carries no effort of ours, and an\n// answer prints `item.completed` (`agent_message`, \"OK\") then\n// `turn.completed`; a refusal prints `turn.failed` and exits 1.\n\nexport const CODEX_PRESET = 'codex'\n\n/** `--ephemeral`, `--sandbox`, `-C`, `--json` all exist on this version; older builds were not checked. */\nexport const MIN_CODEX_VERSION = '0.154.0'\n\n/** The `[mcp_servers.<name>]` table the runs use; tools are `mcp__agentchat__<tool>`, as the served texts spell them. */\nexport const CODEX_MCP_SERVER_NAME = 'agentchat'\n\n/**\n * The variable a listener's runs read the bearer token from. Deliberately not\n * `AGENTCHAT_API_KEY`: Codex loads `$CODEX_HOME/.env` at startup, where an\n * installed integration keeps ITS agent's key under that name.\n */\nexport const LISTENER_KEY_ENV = 'AGENTCHAT_LISTENER_API_KEY'\n\n/**\n * The final positional argument: `-` tells `codex exec` to read its\n * instructions from stdin (\"If not provided as an argument (or if `-` is\n * used), instructions are read from stdin\").\n */\nexport const CODEX_PROMPT_FROM_STDIN = '-'\n\n/** Codex's config root. Honouring CODEX_HOME matters: users relocate it. */\nexport function codexHomeFrom(env: NodeJS.ProcessEnv = process.env): string {\n const override = env['CODEX_HOME']\n if (override !== undefined && override.trim().length > 0) return path.resolve(override)\n return path.join(os.homedir(), '.codex')\n}\n\n/** How long a probe (`--version`, `login status`) may take; a hung one is killed with its whole tree (`runProbe`). */\nexport const CODEX_PROBE_TIMEOUT_MS = 10_000\n\nexport async function inspectCodexRuntime(codexHome: string, command = 'codex', timeoutMs = CODEX_PROBE_TIMEOUT_MS, signal?: AbortSignal): Promise<PresetInspection> {\n const result = await runProbe(command, ['--version'], { timeoutMs, env: { ...process.env, CODEX_HOME: codexHome }, ...(signal !== undefined ? { signal } : {}) })\n if (result.timedOut) return { ok: false, detail: `codex --version did not answer within ${Math.round(timeoutMs / 1000)} s (killed)` }\n if (signal?.aborted) return { ok: false, detail: 'codex --version was stopped' }\n if (result.error) return { ok: false, detail: `codex CLI not found on PATH (${result.error.message})` }\n const rendered = (result.stdout || result.stderr).trim()\n if (result.status !== 0) return { ok: false, detail: rendered || `codex --version exited ${result.status}` }\n return semverAtLeast(rendered, MIN_CODEX_VERSION)\n ? { ok: true, detail: rendered }\n : { ok: false, detail: `${rendered || 'unrecognized version'}; AgentChat requires Codex >= ${MIN_CODEX_VERSION}` }\n}\n\n/** `codex login status` exits 0 when signed in. */\nexport async function codexIsLoggedIn(codexHome: string, command = 'codex', timeoutMs = CODEX_PROBE_TIMEOUT_MS, signal?: AbortSignal): Promise<PresetInspection> {\n const status = await runProbe(command, ['login', 'status'], { timeoutMs, env: { ...process.env, CODEX_HOME: codexHome }, ...(signal !== undefined ? { signal } : {}) })\n if (status.error) return { ok: false, detail: status.error.message }\n const detail = `${status.stdout}${status.stderr}`.trim().slice(0, 200)\n return status.status === 0 ? { ok: true, detail: detail || 'signed in' } : { ok: false, detail: detail || 'codex is not signed in (run `codex login`)' }\n}\n\n/** The permission profile an `answer` run is given: its own name, so a user's profiles are never selected. */\nexport const CODEX_ANSWER_PERMISSIONS = 'agentchat_answer'\n\n/** Its filesystem table: read the workspace root (the `-C` workdir) and nothing else; no write anywhere. */\nexport const CODEX_ANSWER_FILESYSTEM = '{ \":workspace_roots\" = \"read\" }'\n\n/**\n * Codex features an `answer` run turns off: every model-visible tool that runs\n * a command, reads a local file or reaches out beside the hosted AgentChat\n * tools (see the header). Names as `codex features list` prints them (0.154.0).\n */\nexport const CODEX_ANSWER_DISABLED_FEATURES = [\n 'shell_tool',\n 'view_image',\n 'image_generation',\n 'plugins',\n 'apps',\n 'memories',\n 'browser_use',\n 'browser_use_external',\n 'computer_use',\n 'in_app_browser',\n] as const\n\nexport function codexProfileArgs(profile: RunProfile): string[] {\n switch (profile) {\n // The agent itself: nothing but the run's shape (see the header).\n case 'own':\n return []\n case 'answer':\n return [\n '-c',\n 'approval_policy=\"never\"',\n '-c',\n `default_permissions=\"${CODEX_ANSWER_PERMISSIONS}\"`,\n '-c',\n `permissions.${CODEX_ANSWER_PERMISSIONS}.filesystem=${CODEX_ANSWER_FILESYSTEM}`,\n '-c',\n 'web_search=\"disabled\"',\n // No project or ancestor AGENTS.md (core/src/agents_md.rs:65-67, 129: a\n // zero budget reads none). $CODEX_HOME/AGENTS.md has no such switch in\n // 0.154.0 (codex-home/src/instructions/mod.rs, wired unconditionally).\n '-c',\n 'project_doc_max_bytes=0',\n ...CODEX_ANSWER_DISABLED_FEATURES.flatMap((feature) => ['--disable', feature]),\n ]\n // `work` and `full` are the operator's explicit opt-in: a run started by\n // any peer's message can then read and change this machine.\n case 'work':\n return ['--sandbox', 'workspace-write', '-c', 'approval_policy=\"never\"']\n case 'full':\n return ['--dangerously-bypass-approvals-and-sandbox']\n }\n}\n\n/**\n * The features a runtime check turns off, as an `answer` run does (names at\n * the 0.154.0 floor, `codex features list`). Not `hooks`: a user's hook that\n * breaks every run must fail the check too (see the header).\n */\nexport const CODEX_RUNTIME_CHECK_DISABLED_FEATURES = ['memories', 'plugins', 'apps'] as const\n\n/**\n * The argv of a runtime check: `codex exec` in `dir` (an empty folder), the\n * read-only sandbox, no session files, no web search, memories, plugins or\n * connectors (the user's hooks stay on, as in the runs), and the hosted\n * AgentChat server switched off for it;\n * the prompt on stdin, as for a run. The model and its reasoning effort are\n * the runs' (see the header). `agentchatUrl` is the URL the runs pin (with\n * it, the `agentchat` table stays valid whether or not a config layer defines\n * one); without it a config layer must define the table, as the runs need.\n */\nexport function codexRuntimeCheckArgs(dir: string, agentchatUrl?: string): string[] {\n const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`\n return [\n 'exec',\n '--json',\n '--skip-git-repo-check',\n '--ephemeral',\n '-C',\n dir,\n '--sandbox',\n 'read-only',\n '-c',\n 'web_search=\"disabled\"',\n ...CODEX_RUNTIME_CHECK_DISABLED_FEATURES.flatMap((feature) => ['--disable', feature]),\n ...(agentchatUrl !== undefined ? ['-c', `${table}.url=${JSON.stringify(agentchatUrl)}`] : []),\n '-c',\n `${table}.enabled=false`,\n CODEX_PROMPT_FROM_STDIN,\n ]\n}\n\n/** The empty folder a runtime check runs in, under CODEX_HOME. */\nexport function codexRuntimeCheckWorkdir(codexHome: string): string {\n return path.join(codexHome, RUNTIME_CHECK_DIR)\n}\n\n/** A JSON object, or null for anything else. */\nfunction jsonObject(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null\n}\n\n/**\n * Whether a runtime check's stdout (`codex exec --json`: one event per line,\n * exec/src/exec_events.rs) is a good answer: null when it holds a\n * `turn.completed` event and an `item.completed` whose item is an\n * `agent_message` with text, and no `turn.failed`; otherwise why not, in event\n * types only, never a message or an error's text. Exit 0 alone is not an\n * answer. A line that is not a JSON object is skipped (a cut-off last line\n * included: its events are then missing, and the check is not ok).\n */\nexport function codexRuntimeCheckJudge(stdout: string): string | null {\n let events = 0\n let completed = false\n let failed = false\n let answered = false\n for (const line of stdout.split(/\\r?\\n/)) {\n if (line.trim().length === 0) continue\n let event: Record<string, unknown> | null\n try {\n event = jsonObject(JSON.parse(line))\n } catch {\n continue\n }\n if (event === null) continue\n events += 1\n if (event['type'] === 'turn.completed') completed = true\n else if (event['type'] === 'turn.failed') failed = true\n else if (event['type'] === 'item.completed') {\n const item = jsonObject(event['item'])\n if (item !== null && item['type'] === 'agent_message' && typeof item['text'] === 'string' && item['text'].trim().length > 0) answered = true\n }\n }\n if (events === 0) return 'its answer holds no JSON event'\n if (failed) return 'the turn failed (turn.failed)'\n if (!completed) return 'the turn did not complete (no turn.completed)'\n if (!answered) return 'the turn completed with no agent message'\n return null\n}\n\n/** Where a run's hosted tool server points, and which variable carries its bearer token. */\nexport interface CodexMcpOverride {\n readonly url: string\n readonly keyEnv: string\n /**\n * A headers helper command (`http_headers_helper`) in place of the bearer\n * variable: the run's environment then carries no key. A listener's `own`\n * runs use one (`codexListenerHeadersHelperPath`): with the user's own\n * shell, an environment variable is one `env` away.\n */\n readonly headersHelper?: string\n /** The version named in `X-AgentChat-Client-Version` (the front door that placed the run). Defaults to this engine's. */\n readonly clientVersion?: string\n}\n\n/**\n * `{\"X-AgentChat-Client\" = \"codex\", \"X-AgentChat-Client-Version\" = \"<version>\"}`:\n * the client headers that name the runtime to the hosted tool server, as a\n * TOML inline table for `-c …http_headers=`. Codex parses a `-c` value as\n * TOML (inline tables included) since before 0.154.0, and sends\n * `http_headers` on every request to a streamable-HTTP server. Without them\n * a run is an unknown client and is shown the wake-webhook tools.\n */\nexport function codexClientHeadersToml(clientVersion: string = VERSION): string {\n const pairs = Object.entries(clientHeadersOf({ runtime: 'codex', version: clientVersion })).map(([name, value]) => `${JSON.stringify(name)} = ${JSON.stringify(value)}`)\n return `{ ${pairs.join(', ')} }`\n}\n\n/** `-c mcp_servers.agentchat.url=\"<url>\"`: the hosted server's URL pinned for one run, whatever another config layer says. */\nexport function codexPinnedUrlArgs(url: string): string[] {\n return ['-c', `mcp_servers.${CODEX_MCP_SERVER_NAME}.url=${JSON.stringify(url)}`]\n}\n\n/** The `-c` overrides that make `[mcp_servers.agentchat]` this agent's, for one run. TOML values, no key in them. */\nexport function codexMcpOverrideArgs(override: CodexMcpOverride): string[] {\n const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`\n return [\n '-c',\n `${table}.url=${JSON.stringify(override.url)}`,\n '-c',\n override.headersHelper !== undefined ? `${table}.http_headers_helper=${JSON.stringify(override.headersHelper)}` : `${table}.bearer_token_env_var=${JSON.stringify(override.keyEnv)}`,\n '-c',\n `${table}.default_tools_approval_mode=\"approve\"`,\n '-c',\n `${table}.http_headers=${codexClientHeadersToml(override.clientVersion ?? VERSION)}`,\n ]\n}\n\n/**\n * The full argument list for one headless run. The prompt is NOT an argument:\n * the runner writes it to stdin and closes it. An argument cannot carry it on\n * Windows — npm installs codex as a `.cmd` shim, cross-spawn runs that through\n * cmd.exe, and cmd.exe ends the command at the first line break, so every line\n * after the first was silently dropped (caught by CI on windows-latest).\n */\nexport function codexRunArgs(profile: RunProfile, options: { workdir: string; mcp?: CodexMcpOverride }): string[] {\n return [\n 'exec',\n '--json',\n '--skip-git-repo-check',\n '--ephemeral',\n '-C',\n options.workdir,\n ...codexProfileArgs(profile),\n ...(options.mcp !== undefined ? codexMcpOverrideArgs(options.mcp) : []),\n CODEX_PROMPT_FROM_STDIN,\n ]\n}\n\nexport interface CodexRunnerOptions {\n readonly codexHome: string\n /** The run's working root (`-C`); the `work` profile may write here. */\n readonly workdir: string\n readonly profile: RunProfile\n /** The agent's key, read per run (a credential change between runs is followed). Null: none is set. */\n readonly apiKey: () => string | null\n /** The variable the key is set under in the run's environment. */\n readonly keyEnv: string\n /** Point the hosted server at this agent for each run (`-c` overrides); absent, config.toml decides. */\n readonly mcp?: CodexMcpOverride\n /**\n * Without `mcp` (an integration's own runs): the hosted server's URL\n * (`<api base>/mcp`), pinned on every run with `-c mcp_servers.agentchat.url=…`\n * so no other config layer — a trusted project's `.codex/config.toml`\n * among them — can point the agentchat server, and the key its bearer\n * variable carries, anywhere else. A layer that gives it a `command`\n * instead makes the merged table invalid: the run does not start.\n */\n readonly pinMcpUrl?: string\n /** Test seam: the binary to run. */\n readonly command?: string\n readonly env?: NodeJS.ProcessEnv\n /** Test seam: how long `codex mcp list` may take (`CODEX_MCP_LIST_TIMEOUT_MS`). */\n readonly mcpListTimeoutMs?: number\n /** Why no run may start (preflight and every run say it); absent: runs start. */\n readonly refuse?: string\n}\n\n/**\n * The folder an `own` or `answer` run works in when its configured workdir is\n * the user's home folder or contains it (`workdirExposesHome`): an empty folder\n * of its own under CODEX_HOME. The run keeps working — it only cannot reach the\n * user's files through its workspace root. An `own` run needs this as much: a\n * user's `workspace-write` sandbox would let a peer-started run write anywhere\n * under the workspace root, which would be the whole home.\n */\nexport function codexAnswerFallbackWorkdir(codexHome: string): string {\n return path.join(codexHome, 'agentchat-answer-workdir')\n}\n\n/** How long `codex mcp list` may take before an answer run is given up (not started). */\nexport const CODEX_MCP_LIST_TIMEOUT_MS = 20_000\n/** After a listing is killed: how long to wait for it to have exited (it holds the workdir) before it is given up on. */\nexport const CODEX_MCP_LIST_KILL_WAIT_MS = 10_000\n/** The most `codex mcp list --json` output read; more is a failure, not a truncation. */\nconst CODEX_MCP_LIST_MAX_BYTES = 1024 * 1024\n\n/**\n * A server name a `-c mcp_servers.<name>.enabled=false` override can address.\n * Codex splits a `-c` key on every `.` (codex-rs/config/src/overrides.rs) and\n * the value at the first `=`, but allows `.` in a server name\n * (codex-mcp/src/rmcp_client.rs: `^[a-zA-Z0-9_:@/.-]+$`).\n */\nexport function codexServerNameAddressable(name: string): boolean {\n return /^[A-Za-z0-9_:@/-]+$/.test(name)\n}\n\n/**\n * The names of the MCP servers `codex mcp list --json` reports enabled, or why\n * that output cannot be trusted. Names only: an entry's transport can carry\n * header and env values, and none of it is kept.\n */\nexport function parseCodexMcpList(stdout: string): { ok: true; names: string[] } | { ok: false; detail: string } {\n let parsed: unknown\n try {\n parsed = JSON.parse(stdout)\n } catch {\n return { ok: false, detail: 'its output is not JSON' }\n }\n if (!Array.isArray(parsed)) return { ok: false, detail: 'its output is not a list' }\n const names: string[] = []\n for (const entry of parsed) {\n const name = (entry as { name?: unknown } | null)?.name\n const enabled = (entry as { enabled?: unknown } | null)?.enabled\n if (typeof name !== 'string' || name.length === 0) return { ok: false, detail: 'an entry has no name' }\n if (enabled !== false) names.push(name)\n }\n return { ok: true, names }\n}\n\n/**\n * What the `agentchat` entry of `codex mcp list --json` would authenticate\n * with besides a headers helper: `bearer_token_env_var`, or an `Authorization`\n * in `env_http_headers` (names only, never values). Codex sends either in\n * place of the helper's `Authorization` (\"Helper Authorization is used only\n * when the request has no explicit bearer/OAuth credential\",\n * rmcp-client/src/http_headers.rs). A static `http_headers` is not counted:\n * a listener's run replaces that whole table. An entry the list does not\n * have authenticates with nothing else.\n */\nexport function codexAgentchatExplicitAuth(stdout: string): { ok: true; keys: string[] } | { ok: false; detail: string } {\n let parsed: unknown\n try {\n parsed = JSON.parse(stdout)\n } catch {\n return { ok: false, detail: 'its output is not JSON' }\n }\n if (!Array.isArray(parsed)) return { ok: false, detail: 'its output is not a list' }\n const entry = parsed.find((e) => (e as { name?: unknown } | null)?.name === CODEX_MCP_SERVER_NAME) as { transport?: unknown } | undefined\n const transport = entry?.transport !== null && typeof entry?.transport === 'object' ? (entry.transport as Record<string, unknown>) : {}\n const keys: string[] = []\n const bearer = transport['bearer_token_env_var']\n if (typeof bearer === 'string' && bearer.length > 0) keys.push('bearer_token_env_var')\n const envHeaders = transport['env_http_headers']\n if (envHeaders !== null && typeof envHeaders === 'object' && Object.keys(envHeaders).some((name) => name.toLowerCase() === 'authorization')) keys.push('env_http_headers.Authorization')\n return { ok: true, keys }\n}\n\n/** The key variables a `.env` file sets (`AGENTCHAT_API_KEY`, `LISTENER_KEY_ENV`): names only. Codex loads `$CODEX_HOME/.env` into its own environment, and a run's commands inherit it. */\nexport function codexDotEnvKeyNames(content: string): string[] {\n const names = new Set<string>()\n for (const line of content.split(/\\r?\\n/)) {\n const match = /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*['\"]?\\S/.exec(line)\n if (match?.[1] === 'AGENTCHAT_API_KEY' || match?.[1] === LISTENER_KEY_ENV) names.add(match[1])\n }\n return [...names]\n}\n\n/**\n * `-c mcp_servers.<name>.enabled=false` for every listed server but AgentChat's,\n * or why that cannot be done. Only names Codex listed: an override for a server\n * no config layer defines is a config error (\"invalid transport\").\n */\nexport function codexMcpDisableArgs(names: readonly string[]): { ok: true; args: string[] } | { ok: false; detail: string } {\n const args: string[] = []\n for (const name of names) {\n if (name === CODEX_MCP_SERVER_NAME) continue\n if (!codexServerNameAddressable(name)) {\n return { ok: false, detail: `the MCP server \"${name}\" cannot be switched off for one run (Codex reads a \".\" in a -c key as a table); rename it or remove it` }\n }\n args.push('-c', `mcp_servers.${name}.enabled=false`)\n }\n return { ok: true, args }\n}\n\n/** Why an answer run does not start when Codex's MCP servers cannot be listed (or one cannot be switched off). */\nfunction codexAnswerListingRefusal(detail: string): string {\n return `could not list Codex's MCP servers (\\`codex mcp list --json\\` with the answer flags: ${detail}); an answer run starts only with every server but ${CODEX_MCP_SERVER_NAME} switched off`\n}\n\n/** How long a listing is reused while none of the files it was read from changed (layers that are not files: a cloud bundle). */\nexport const CODEX_MCP_LIST_MAX_AGE_MS = 60 * 60_000\n\n/**\n * The config files `codex mcp list` (and the run) read, in the loader's order\n * (openai/codex rust-v0.154.0 config/src/loader/mod.rs:79-95, 800-841,\n * layer_io.rs:22, 78-92, loader/macos.rs:20):\n *\n * * system: `/etc/codex/config.toml`, the legacy `/etc/codex/managed_config.toml`\n * and `/etc/codex/requirements.toml`; on Windows `<ProgramData>\\OpenAI\\Codex\\`\n * `config.toml` and `requirements.toml` (the ProgramData known folder,\n * `C:\\ProgramData` when it cannot be resolved; `CODEX_HOME\\managed_config.toml`\n * is ignored there),\n * * macOS managed preferences (`com.openai.codex`),\n * * the user's `$CODEX_HOME/config.toml`,\n * * `config.toml` in the workdir and `.codex/config.toml` from the workdir up\n * to its root (a drive root on Windows).\n *\n * Paths are built for `platform` (its own separators and roots), whatever the\n * host: the list is what that platform's Codex reads.\n */\nexport function codexConfigLayerFiles(codexHome: string, workdir: string, platform: NodeJS.Platform = process.platform, env: NodeJS.ProcessEnv = process.env): string[] {\n const p = platform === 'win32' ? path.win32 : path.posix\n const programData = env['ProgramData'] ?? env['PROGRAMDATA'] ?? 'C:\\\\ProgramData'\n const system =\n platform === 'win32'\n ? [p.join(programData, 'OpenAI', 'Codex', 'config.toml'), p.join(programData, 'OpenAI', 'Codex', 'requirements.toml')]\n : ['/etc/codex/config.toml', '/etc/codex/managed_config.toml', '/etc/codex/requirements.toml']\n const user = (() => {\n try {\n return os.userInfo().username\n } catch {\n return null\n }\n })()\n const managedPrefs =\n platform === 'darwin'\n ? ['/Library/Managed Preferences/com.openai.codex.plist', ...(user !== null ? [p.join('/Library/Managed Preferences', user, 'com.openai.codex.plist')] : [])]\n : []\n const tree: string[] = []\n let current = p.resolve(workdir)\n tree.push(p.join(current, 'config.toml'))\n for (;;) {\n tree.push(p.join(current, '.codex', 'config.toml'))\n const parent = p.dirname(current)\n if (parent === current) break\n current = parent\n }\n return [...system, ...managedPrefs, p.join(codexHome, 'config.toml'), ...tree]\n}\n\n/** What the listing depends on: every layer file's size and mtime (or its absence), the flags, the workdir, the binary. */\nfunction codexListingKey(files: readonly string[], parts: readonly string[]): string {\n const stats = files.map((file) => {\n try {\n const st = fs.statSync(file)\n return `${file}\\u0000${st.size}\\u0000${st.mtimeMs}`\n } catch {\n return `${file}\\u0000-`\n }\n })\n return [...parts, ...stats].join('\\u0001')\n}\n\nexport class CodexRunner implements RunRunner {\n readonly name = 'codex'\n readonly label = 'Codex'\n private readonly command: string\n private warnedHome = false\n /** The last good listing and what it depended on: a stranger's DM does not cost a listing (and its contacts to the user's MCP hosts) on every run. */\n private listing: { key: string; at: number; result: { ok: true; args: string[] } } | null = null\n /** The last listing that showed a listener's own run authenticates with its helper alone (`ownAuthProblem`). */\n private ownListing: { key: string; at: number } | null = null\n\n constructor(private readonly options: CodexRunnerOptions) {\n this.command = options.command ?? 'codex'\n }\n\n /**\n * Where this runner's runs work (`-C`): the configured workdir, except that an\n * `own` or `answer` run never has the home folder or above it as its\n * workspace root — it gets `codexAnswerFallbackWorkdir`.\n */\n workdir(): string {\n if ((this.options.profile === 'answer' || this.options.profile === 'own') && workdirExposesHome(this.options.workdir)) return codexAnswerFallbackWorkdir(this.options.codexHome)\n return this.options.workdir\n }\n\n async preflight(options: RunPreflightOptions = {}): Promise<RunPreflight> {\n if (this.options.refuse !== undefined) return { ok: false, detail: this.options.refuse }\n const runtime = await inspectCodexRuntime(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n const auth = await codexIsLoggedIn(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal)\n if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` }\n if (this.workdir() !== this.options.workdir && !this.warnedHome) {\n this.warnedHome = true\n log.warn(`the run workdir ${this.options.workdir} is your home folder or contains it: ${this.options.profile} runs work in ${this.workdir()} instead, so a peer-started run reaches none of your files there. Point the workdir at a folder of its own to choose another.`)\n }\n fs.mkdirSync(this.workdir(), { recursive: true })\n if (this.options.profile === 'answer') {\n // Said up front, not only as a run's detail: a Codex that rejects one of\n // the answer flags, or a server no `-c` key can switch off, stops every\n // answer run.\n const disables = await this.answerMcpDisables()\n if (!disables.ok) return { ok: false, detail: codexAnswerListingRefusal(disables.detail) }\n }\n // Said up front as well: a listener's own run that would carry or use another key.\n const ownProblem = await this.ownAuthProblem()\n if (ownProblem !== null) return { ok: false, detail: ownProblem }\n return { ok: true }\n }\n\n /** The exact argv one run uses — exported for tests to pin per profile. An `answer` run adds `answerMcpDisables()` before the prompt. */\n args(): string[] {\n const args = codexRunArgs(this.options.profile, { workdir: this.workdir(), ...(this.options.mcp !== undefined ? { mcp: this.options.mcp } : {}) })\n if (this.options.mcp !== undefined || this.options.pinMcpUrl === undefined) return args\n // The prompt stays the last positional.\n return [...args.slice(0, -1), ...codexPinnedUrlArgs(this.options.pinMcpUrl), CODEX_PROMPT_FROM_STDIN]\n }\n\n /**\n * The child environment: Codex's home and the key the hosted server needs,\n * under the configured name. An `own` run gets no key at all — not the\n * configured one, not an `AGENTCHAT_API_KEY` the daemon inherited: it has\n * the user's own shell, and Codex hands a run's commands its environment.\n * Its hosted server authenticates through a headers helper instead.\n */\n env(): NodeJS.ProcessEnv {\n // Nothing of a parent Claude Code or Codex session, in every profile.\n const env: NodeJS.ProcessEnv = { ...withoutParentSession(this.options.env ?? process.env), CODEX_HOME: this.options.codexHome }\n if (this.options.profile === 'own') {\n delete env['AGENTCHAT_API_KEY']\n delete env[this.options.keyEnv]\n return env\n }\n const key = this.options.apiKey()\n if (key !== null) env[this.options.keyEnv] = key\n return env\n }\n\n /**\n * For an `answer` run: `-c mcp_servers.<name>.enabled=false` for every MCP\n * server the run would load but AgentChat's — the user's own in config.toml,\n * a project's, a managed one. Codex has no \"only this server\" switch, and a\n * tool such a server marks read-only runs without approval. Asked of Codex\n * itself (`codex mcp list --json`, with the run's own `-c`/`--disable`\n * flags, from the run's workdir), so every layer is counted. Any failure —\n * an error, a timeout, output that is not the list — means no run.\n */\n async answerMcpDisables(): Promise<{ ok: true; args: string[] } | { ok: false; detail: string }> {\n const { flags, key } = this.listingFlags()\n // Reused while nothing it was read from changed (and for at most an hour);\n // a failure is never cached, so the next run asks again.\n if (this.listing !== null && this.listing.key === key && Date.now() - this.listing.at < CODEX_MCP_LIST_MAX_AGE_MS) return this.listing.result\n const listed = await this.listMcpServers(flags)\n if (!listed.ok) return listed\n const parsed = parseCodexMcpList(listed.stdout)\n if (!parsed.ok) return parsed\n const result = codexMcpDisableArgs(parsed.names)\n if (result.ok) this.listing = { key, at: Date.now(), result }\n return result\n }\n\n /**\n * For a listener's `own` run (its key from a headers helper, none in its\n * environment): why it must not start, or null. Two things would make it\n * carry or use a key that is not the helper's — another agent's, as a\n * Codex integration from 0.5.2 or earlier left them: `$CODEX_HOME/.env`\n * setting a key variable (Codex loads it into the run's environment), and an\n * `agentchat` entry that names `bearer_token_env_var` or an `Authorization`\n * in `env_http_headers` in any config layer (Codex sends that in place of the\n * helper's: the run would act as that other agent). The entry is asked of\n * Codex itself (`codex mcp list --json` with the run's own flags, cached as\n * an answer run's listing is); a listing that fails means no run.\n */\n async ownAuthProblem(): Promise<string | null> {\n if (this.options.profile !== 'own' || this.options.mcp?.headersHelper === undefined) return null\n const dotenv = path.join(this.options.codexHome, '.env')\n let names: string[] = []\n try {\n names = codexDotEnvKeyNames(fs.readFileSync(dotenv, 'utf-8'))\n } catch {\n names = []\n }\n if (names.length > 0) {\n return `${dotenv} sets ${names.join(' and ')}: Codex loads that file into every run's environment, so this listener's own runs would carry that key. An AgentChat Codex integration from 0.5.2 or earlier left it there (\\`npx -y @agentchatme/codex doctor --fix\\` takes it out); remove the line, or run this listener with --profile answer`\n }\n const { flags, key } = this.listingFlags()\n if (this.ownListing !== null && this.ownListing.key === key && Date.now() - this.ownListing.at < CODEX_MCP_LIST_MAX_AGE_MS) return null\n const listed = await this.listMcpServers(flags)\n const auth = listed.ok ? codexAgentchatExplicitAuth(listed.stdout) : listed\n if (!auth.ok) {\n return `could not list Codex's MCP servers (\\`codex mcp list --json\\` with the own run's flags: ${auth.detail}); a listener's own run starts only once Codex confirms its ${CODEX_MCP_SERVER_NAME} server sends this listener's key`\n }\n if (auth.keys.length > 0) {\n return `the [mcp_servers.${CODEX_MCP_SERVER_NAME}] Codex loads for these runs sets ${auth.keys.join(' and ')}: Codex sends that credential in place of this listener's headers helper, so its own runs would act as another agent. An AgentChat Codex integration from 0.5.2 or earlier wrote bearer_token_env_var (\\`npx -y @agentchatme/codex doctor --fix\\` replaces it); remove it, or run this listener with --profile answer`\n }\n this.ownListing = { key, at: Date.now() }\n return null\n }\n\n /** The run's config flags (`-c <v>` and `--disable <feature>` pairs) and what a listing of them depends on. */\n private listingFlags(): { flags: string[]; key: string } {\n const run = this.args()\n const flags = run.flatMap((arg, i) => (run[i - 1] === '-c' || run[i - 1] === '--disable' ? [run[i - 1] as string, arg] : []))\n return { flags, key: codexListingKey(codexConfigLayerFiles(this.options.codexHome, this.workdir()), [this.command, this.workdir(), ...flags]) }\n }\n\n /** `codex mcp list --json <flags>` from the run's workdir, with the run's environment: its output, or why there is none. Killed with its whole tree past its time. */\n private async listMcpServers(flags: string[]): Promise<{ ok: true; stdout: string } | { ok: false; detail: string }> {\n return new Promise<{ ok: true; stdout: string } | { ok: false; detail: string }>((resolve) => {\n let child: ReturnType<typeof spawnCommand>\n try {\n child = spawnCommand(this.command, ['mcp', 'list', '--json', ...flags], {\n cwd: this.workdir(),\n env: this.env(),\n stdio: ['ignore', 'pipe', 'pipe'],\n // Its own process group on POSIX, so a hung listing is killed with\n // everything it started (the npm launcher and the native binary).\n detached: process.platform !== 'win32',\n windowsHide: true,\n })\n } catch (err) {\n resolve({ ok: false, detail: err instanceof Error ? err.message : String(err) })\n return\n }\n const proc = child\n let stdout = ''\n let stderr = ''\n let stopped: string | null = null\n let settled = false\n let abandonTimer: NodeJS.Timeout | null = null\n const settle = (result: { ok: true; stdout: string } | { ok: false; detail: string }): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n if (abandonTimer !== null) clearTimeout(abandonTimer)\n resolve(result)\n }\n // A listing that has to be stopped: the whole tree (taskkill /T /F on\n // Windows, where the shim and the real process differ), and the answer\n // waits for it to have exited — it holds the workdir as its cwd. A tree\n // that will not die is given up on after a bound, not waited on forever.\n const stop = (why: string): void => {\n if (stopped !== null) return\n stopped = why\n killProcessTree(proc, 'SIGKILL')\n abandonTimer = setTimeout(() => settle({ ok: false, detail: `${why} (and it did not exit after being killed)` }), CODEX_MCP_LIST_KILL_WAIT_MS)\n }\n proc.stderr?.on('data', (chunk: Buffer) => {\n if (stderr.length < 4096) stderr += chunk.toString('utf-8')\n })\n const timeoutMs = this.options.mcpListTimeoutMs ?? CODEX_MCP_LIST_TIMEOUT_MS\n const timer = setTimeout(() => stop(`no answer within ${Math.round(timeoutMs / 1000)} s`), timeoutMs)\n proc.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf-8')\n if (stdout.length > CODEX_MCP_LIST_MAX_BYTES) stop('its output is too long')\n })\n proc.on('error', (err) => {\n if (stopped === null) settle({ ok: false, detail: err.message })\n })\n proc.on('close', (code) => {\n if (stopped !== null) {\n settle({ ok: false, detail: stopped })\n return\n }\n // Codex's own complaint, first line, bounded and redacted (e.g. \"Unknown feature flag: …\").\n const said = redactDiagnostic(stderr.split(/\\r?\\n/).find((line) => line.trim().length > 0) ?? '', 200)\n if (code !== 0) settle({ ok: false, detail: `it exited ${code}${said ? `: ${said}` : ''}` })\n else settle({ ok: true, stdout })\n })\n })\n }\n\n /**\n * Does the model answer right now, through this runner's binary, sign-in,\n * CODEX_HOME and environment? One `codex exec` with a fixed prompt in its\n * own empty folder, read-only, with the hosted AgentChat server switched\n * off and the user's hooks on, as in the runs (`codexRuntimeCheckArgs`),\n * and no key in its environment; ok only on exit 0 with a completed turn\n * that holds an agent message (`codexRuntimeCheckJudge`). Its output is\n * read for that alone and never logged. Never throws.\n */\n async checkRuntime(options: RunPreflightOptions = {}): Promise<RunPreflight> {\n if (this.options.refuse !== undefined) return { ok: false, detail: this.options.refuse }\n const dir = codexRuntimeCheckWorkdir(this.options.codexHome)\n return runRuntimeCheck({\n label: 'codex',\n command: this.command,\n args: codexRuntimeCheckArgs(dir, this.options.mcp?.url ?? this.options.pinMcpUrl),\n cwd: dir,\n // The runs' environment; runRuntimeCheck takes every key variable out, this runner's own included.\n env: this.env(),\n keyEnv: this.options.keyEnv,\n // Exit 0 is not enough: the events must show a completed turn with the model's answer.\n judge: codexRuntimeCheckJudge,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n })\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const startedAt = Date.now()\n if (this.options.refuse !== undefined) return { state: 'not_started', exitCode: null, durationMs: 0, detail: this.options.refuse }\n let args = this.args()\n if (this.options.profile === 'answer') {\n // Fail closed: an answer run starts only with every MCP server but AgentChat's switched off.\n const disables = await this.answerMcpDisables()\n if (!disables.ok) return { state: 'not_started', exitCode: null, durationMs: Date.now() - startedAt, detail: codexAnswerListingRefusal(disables.detail) }\n args = [...args.slice(0, -1), ...disables.args, CODEX_PROMPT_FROM_STDIN]\n }\n // Fail closed: a listener's own run starts only when it would act as the listener's agent, with no key in its environment.\n const ownProblem = await this.ownAuthProblem()\n if (ownProblem !== null) return { state: 'not_started', exitCode: null, durationMs: Date.now() - startedAt, detail: ownProblem }\n log.debug(`codex ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId}${request.conversationId !== undefined ? ` for ${request.conversationId}` : ''})`)\n return spawnRun({\n command: this.command,\n args,\n cwd: this.workdir(),\n env: this.env(),\n // Written to stdin and then closed: `codex exec -` reads its\n // instructions until EOF. Never as an argument (see codexRunArgs).\n stdin: request.prompt,\n budgetMs: request.budgetMs,\n ...(request.signal ? { signal: request.signal } : {}),\n ...(request.onStarted ? { onStarted: request.onStarted } : {}),\n })\n }\n}\n\n// ─── A listener's own runs: the key from a headers helper, not the environment ─\n//\n// An `own` run has the user's own shell, and Codex hands a run's commands its\n// whole environment (`shell_environment_policy` inherits everything in\n// 0.154.0). So a listener's `own` runs carry no key there: `[mcp_servers.agentchat]`\n// gets `http_headers_helper` — \"Local-only shell command that prints a JSON\n// object of dynamic HTTP headers\" (codex-rs config/src/mcp_types.rs), run with\n// `sh -c` (`cmd /Q /D /C` on Windows) on each connection and again after a\n// 401/403, its `Authorization` used when the server names no bearer token\n// (rmcp-client/src/http_headers.rs) — and the helper reads the listener home's\n// `credentials` itself. The same mechanism the Codex integration places.\n\n/** Where a listener's `own` runs' headers helper lives: `<home>/presets/codex.mcp-headers.mjs` (owner-only; it holds no key). */\nexport function codexListenerHeadersHelperPath(home: string): string {\n return path.join(home, 'presets', `${CODEX_PRESET}.mcp-headers.mjs`)\n}\n\n/**\n * The helper, byte for byte. It reads the `credentials` file of the home whose\n * `presets/` it sits in and nothing else (no environment variable: the\n * identity is the home's), prints `{\"Authorization\":\"Bearer <key>\"}`, or `{}`\n * when there is no key, and never fails.\n */\nexport const CODEX_LISTENER_HEADERS_HELPER_SOURCE = [\n \"// Written by @agentchatme/agent-core for a listener's Codex runs. Codex runs this on each\",\n '// connection to the MCP server \"agentchat\" (its http_headers_helper) and sends what it prints',\n '// as headers: the Authorization header for the key in the credentials file of this identity',\n '// home, or nothing when there is none. It reads no environment variable. Do not edit: the',\n '// listener rewrites it.',\n \"import { readFileSync } from 'node:fs'\",\n 'let headers = {}',\n 'try {',\n \" const creds = JSON.parse(readFileSync(new URL('../credentials', import.meta.url), 'utf8'))\",\n \" const key = creds !== null && typeof creds.api_key === 'string' ? creds.api_key.trim() : ''\",\n ' if (key.length >= 20 && !/\\\\s/.test(key)) headers = { Authorization: `Bearer ${key}` }',\n '} catch {}',\n 'process.stdout.write(JSON.stringify(headers))',\n '',\n].join('\\n')\n\n/**\n * The helper command: this Node and the script, each quoted for the shell\n * Codex runs it in — single quotes on POSIX (`sh -c`; a `'` inside written as\n * `'\\\\''`), double quotes on Windows (`cmd /C`). Null when a path holds what\n * that quoting cannot carry (`\"`, `%`, `$` or a backtick on Windows) or a line\n * break anywhere.\n */\nexport function codexHeadersHelperCommand(script: string, node: string = process.execPath, platform: NodeJS.Platform = process.platform): string | null {\n const paths = [node, script]\n if (paths.some((p) => /[\\r\\n]/.test(p))) return null\n if (platform === 'win32') return paths.some((p) => /[\"%$`]/.test(p)) ? null : paths.map((p) => `\"${p}\"`).join(' ')\n return paths.map((p) => `'${p.replace(/'/g, `'\\\\''`)}'`).join(' ')\n}\n\n/**\n * The keys of `[mcp_servers.agentchat]` in a config.toml, or null when the\n * table is absent. Keys only — a value can be a secret. A line scan, not a\n * TOML parser: enough to say what a run's `-c` overrides merge over.\n */\nexport function agentchatTableKeys(configToml: string): string[] | null {\n const lines = configToml.split(/\\r?\\n/)\n const header = new RegExp(`^\\\\s*\\\\[mcp_servers\\\\.${CODEX_MCP_SERVER_NAME}\\\\]\\\\s*(#.*)?$`)\n const start = lines.findIndex((line) => header.test(line))\n if (start < 0) return null\n const keys: string[] = []\n for (const line of lines.slice(start + 1)) {\n if (/^\\s*\\[/.test(line)) break\n const match = /^\\s*([A-Za-z0-9_.-]+)\\s*=/.exec(line)\n if (match?.[1] !== undefined) keys.push(match[1])\n }\n return keys\n}\n\nexport const codexPreset: Preset = {\n name: CODEX_PRESET,\n describeMcp({ home, apiBase, env = process.env, profile }) {\n const file = path.join(codexHomeFrom(env), 'config.toml')\n let own: string[] | null = null\n try {\n own = agentchatTableKeys(fs.readFileSync(file, 'utf-8'))\n } catch {\n own = null\n }\n return [\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.url=\"${hostedMcpUrl(apiBase)}\"`,\n profile === 'own'\n ? `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.http_headers_helper=<node> ${codexListenerHeadersHelperPath(home)} (own: reads this home's credentials on each connection; no key in the run's environment or on argv; no run while $CODEX_HOME/.env sets a key or the merged ${CODEX_MCP_SERVER_NAME} entry names bearer_token_env_var)`\n : `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.bearer_token_env_var=\"${LISTENER_KEY_ENV}\" (the key set in the run's environment, never on argv)`,\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.default_tools_approval_mode=\"approve\"`,\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.http_headers={ \"X-AgentChat-Client\" = \"codex\", \"X-AgentChat-Client-Version\" = <the listener's version> } (names the runtime to the hosted tools)`,\n own === null\n ? `${file}: no [mcp_servers.${CODEX_MCP_SERVER_NAME}] of its own — the run sees only the overrides above`\n : `${file}: [mcp_servers.${CODEX_MCP_SERVER_NAME}] also sets ${own.length > 0 ? own.join(', ') : 'nothing'}; the overrides above replace their keys, the others still apply (how codex merges -c over an existing table is not verified on a real codex)`,\n ]\n },\n label: 'Codex',\n runtime: 'codex',\n serviceEnv: ['CODEX_HOME'],\n // `own`, `work` and `full` read the whole filesystem (Codex's sandboxes never\n // restrict reads; an `answer` run reads only its workdir): true, because the\n // field is one for every profile.\n readsIdentityHome: true,\n async inspect(env = process.env, command = 'codex') {\n const home = codexHomeFrom(env)\n const runtime = await inspectCodexRuntime(home, command)\n if (!runtime.ok) return runtime\n const auth = await codexIsLoggedIn(home, command)\n return auth.ok ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in: ${auth.detail}` }\n },\n runner(ctx: PresetContext): RunRunner {\n // A key in the listener's own environment is not handed to its runs.\n const env = withoutInheritedKey(ctx.env ?? process.env)\n const apiKey = ctx.apiKey\n const base = {\n codexHome: codexHomeFrom(env),\n workdir: ctx.workdir,\n profile: ctx.profile,\n keyEnv: LISTENER_KEY_ENV,\n ...(ctx.command !== undefined ? { command: ctx.command } : {}),\n env,\n }\n const mcp = { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV, clientVersion: ctx.clientVersion ?? VERSION }\n if (ctx.profile !== 'own') return new CodexRunner({ ...base, apiKey: () => apiKey, mcp })\n // own: the user's shell is the run's, so no key in its environment — the\n // helper reads this home's credentials (rewritten for every identity the\n // listener serves; it holds no key).\n const script = codexListenerHeadersHelperPath(ctx.home)\n const helper = codexHeadersHelperCommand(script)\n if (helper === null) {\n return new CodexRunner({ ...base, apiKey: () => null, mcp, refuse: `the path of Node (${process.execPath}) or of ${script} holds a character a shell command cannot carry quoted: an own run would have its key in its environment instead` })\n }\n try {\n atomicWriteFile(script, CODEX_LISTENER_HEADERS_HELPER_SOURCE, 0o600)\n } catch (err) {\n return new CodexRunner({ ...base, apiKey: () => null, mcp, refuse: `could not write the headers helper ${script}: ${err instanceof Error ? err.message : String(err)}` })\n }\n return new CodexRunner({ ...base, apiKey: () => null, mcp: { ...mcp, headersHelper: helper } })\n },\n}\n","// ─── @agentchatme/agent-core/presets ────────────────────────────────────────\n//\n// How to start one headless run of a known coding agent, shared by the\n// `agentchat listen --preset <name>` listener and each runtime's own\n// integration package (one copy of the flags, never two). The only module of\n// this package that names a coding agent; the engine never imports it.\n\nimport { claudeCodePreset } from './claude-code.js'\nimport { codexPreset } from './codex.js'\nimport type { Preset } from './types.js'\n\nexport type { Preset, PresetContext, PresetInspection } from './types.js'\nexport { withoutParentSession, isParentSessionEnv, CLAUDE_CODE_ENV_KEPT, CLAUDE_SESSION_ENV, CODEX_SESSION_ENV, CODEX_MANAGED_PROXY_ENV } from './types.js'\nexport { semverAtLeast } from './semver.js'\nexport {\n RUNTIME_CHECK_PROMPT,\n RUNTIME_CHECK_BUDGET_MS,\n RUNTIME_CHECK_DIR,\n RUNTIME_CHECK_KEY_ENV,\n RUNTIME_CHECK_OUTPUT_BYTES,\n runRuntimeCheck,\n type RuntimeCheckSpec,\n} from './runtime-check.js'\nexport {\n CLAUDE_CODE_PRESET,\n MIN_CLAUDE_CODE_VERSION,\n PROBE_TIMEOUT_MS,\n CLAUDE_MCP_SERVER_NAME,\n AGENTCHAT_TOOL_ALLOW,\n ANSWER_TOOLS,\n WEB_TOOLS,\n WORK_TOOLS,\n ANSWER_DENIED_TOOLS,\n ANSWER_SETTINGS,\n PARENT_ENV_KEYS,\n claudeConfigDirFrom,\n claudeHomeFor,\n claudeProjectsDirFor,\n claudeUserStatePathFor,\n buildClaudeEnv,\n claudeIsLoggedIn,\n claudeSignIn,\n type ClaudeSignIn,\n inspectClaudeRuntime,\n deniedAncestorOf,\n claudeProfileArgs,\n workdirPaths,\n workdirReadRules,\n readDenyRules,\n inexpressibleDenyPaths,\n claudeRunArgs,\n claudeRuntimeCheckArgs,\n claudeRuntimeCheckJudge,\n claudeRuntimeCheckWorkdir,\n RUNTIME_CHECK_SETTINGS,\n claudeMcpConfig,\n claudeMcpConfigPath,\n ClaudeRunner,\n claudeCodePreset,\n claudeAnswerFallbackWorkdir,\n claudeManagedSettingsDir,\n claudeSettingsFilesGrantingDirectories,\n claudeExtraDirectoriesGrant,\n ANSWER_ENV,\n type ClaudeAnswerMcp,\n type ClaudeRunArgOptions,\n type ClaudeRunnerOptions,\n} from './claude-code.js'\nexport {\n CODEX_PRESET,\n MIN_CODEX_VERSION,\n CODEX_PROBE_TIMEOUT_MS,\n CODEX_MCP_SERVER_NAME,\n LISTENER_KEY_ENV,\n CODEX_PROMPT_FROM_STDIN,\n CODEX_ANSWER_PERMISSIONS,\n CODEX_ANSWER_FILESYSTEM,\n CODEX_ANSWER_DISABLED_FEATURES,\n codexHomeFrom,\n codexListenerHeadersHelperPath,\n CODEX_LISTENER_HEADERS_HELPER_SOURCE,\n codexHeadersHelperCommand,\n inspectCodexRuntime,\n codexIsLoggedIn,\n codexProfileArgs,\n codexMcpOverrideArgs,\n codexPinnedUrlArgs,\n codexClientHeadersToml,\n codexRunArgs,\n codexRuntimeCheckArgs,\n codexRuntimeCheckJudge,\n codexRuntimeCheckWorkdir,\n CODEX_RUNTIME_CHECK_DISABLED_FEATURES,\n agentchatTableKeys,\n CodexRunner,\n codexPreset,\n codexAnswerFallbackWorkdir,\n codexServerNameAddressable,\n parseCodexMcpList,\n codexAgentchatExplicitAuth,\n codexDotEnvKeyNames,\n codexMcpDisableArgs,\n CODEX_MCP_LIST_TIMEOUT_MS,\n CODEX_MCP_LIST_MAX_AGE_MS,\n codexConfigLayerFiles,\n type CodexMcpOverride,\n type CodexRunnerOptions,\n} from './codex.js'\n\n/** Every preset, by the name a user types. */\nexport const PRESETS: Readonly<Record<string, Preset>> = Object.freeze({\n [claudeCodePreset.name]: claudeCodePreset,\n [codexPreset.name]: codexPreset,\n})\n\nexport function presetNamed(name: string): Preset | null {\n return Object.prototype.hasOwnProperty.call(PRESETS, name) ? (PRESETS[name] ?? null) : null\n}\n\nexport function presetNames(): string[] {\n return Object.keys(PRESETS)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,YAAYA,SAAQ;AACpB,YAAY,QAAQ;AACpB,YAAY,UAAU;;;ACDf,SAAS,cAAc,QAAgB,SAA0B;AACtE,QAAM,QAAQ,CAAC,UAAmD;AAChE,UAAM,QAAQ,MAAM,MAAM,qBAAqB;AAC/C,WAAO,QAAQ,CAAC,OAAO,MAAM,CAAC,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,GAAG,OAAO,MAAM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