@agentchatme/agent-core 0.4.0 → 0.4.1

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.
package/dist/presets.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TextsRuntime } from 'agentchatme';
2
- import { a as RunProfile, b as RunRunner, f as RunPreflight, g as RunRequest, c as RunOutcome } from './runner-BzgsiS3V.js';
2
+ import { a as RunProfile, b as RunRunner, f as RunPreflight, g as RunRequest, c as RunOutcome } from './runner-B-ZZDAAm.js';
3
3
 
4
4
  /** What a preset needs to build a runner acting as one agent. */
5
5
  interface PresetContext {
@@ -15,6 +15,14 @@ interface PresetContext {
15
15
  readonly env?: NodeJS.ProcessEnv;
16
16
  /** Test seam: the runtime's binary. */
17
17
  readonly command?: string;
18
+ /**
19
+ * The version the runs name in `X-AgentChat-Client-Version`: the front door
20
+ * that placed them (the `agentchat` listener passes its own). Defaults to
21
+ * this engine's version. The client name is the runtime's (`claude-code`,
22
+ * `codex`): a run the listener wakes needs no wake-webhook tools, and the
23
+ * hosted tools spell their names per runtime by it.
24
+ */
25
+ readonly clientVersion?: string;
18
26
  }
19
27
  interface PresetInspection {
20
28
  readonly ok: boolean;
@@ -133,7 +141,15 @@ declare function readDenyRules(paths: readonly string[]): string[];
133
141
  */
134
142
  declare function claudeRunArgs(profile: RunProfile, options?: ClaudeRunArgOptions): string[];
135
143
  /** The `--mcp-config` document: the hosted server, by HTTP, with the agent's key. Owner-only on disk. */
136
- declare function claudeMcpConfig(apiBase: string, apiKey: string): string;
144
+ /**
145
+ * The `--mcp-config` file a listener's run is given: the hosted tool server
146
+ * with this agent's key, and the client headers that name the runtime to it
147
+ * (`X-AgentChat-Client: claude-code`, `-Version`: the front door that placed
148
+ * the run). The hosted tool server names a client only from these headers:
149
+ * without them a run is an unknown client and is shown the wake-webhook
150
+ * tools, a second way of being woken that the listener makes unnecessary.
151
+ */
152
+ declare function claudeMcpConfig(apiBase: string, apiKey: string, clientVersion?: string): string;
137
153
  interface ClaudeRunnerOptions {
138
154
  readonly configDir: string | undefined;
139
155
  /**
@@ -205,7 +221,18 @@ declare function codexProfileArgs(profile: RunProfile): string[];
205
221
  interface CodexMcpOverride {
206
222
  readonly url: string;
207
223
  readonly keyEnv: string;
224
+ /** The version named in `X-AgentChat-Client-Version` (the front door that placed the run). Defaults to this engine's. */
225
+ readonly clientVersion?: string;
208
226
  }
227
+ /**
228
+ * `{"X-AgentChat-Client" = "codex", "X-AgentChat-Client-Version" = "<version>"}`:
229
+ * the client headers that name the runtime to the hosted tool server, as a
230
+ * TOML inline table for `-c …http_headers=`. Codex parses a `-c` value as
231
+ * TOML (inline tables included) since before 0.154.0, and sends
232
+ * `http_headers` on every request to a streamable-HTTP server. Without them
233
+ * a run is an unknown client and is shown the wake-webhook tools.
234
+ */
235
+ declare function codexClientHeadersToml(clientVersion?: string): string;
209
236
  /** The `-c` overrides that make `[mcp_servers.agentchat]` this agent's, for one run. TOML values, no key in them. */
210
237
  declare function codexMcpOverrideArgs(override: CodexMcpOverride): string[];
211
238
  /**
@@ -259,4 +286,4 @@ declare const PRESETS: Readonly<Record<string, Preset>>;
259
286
  declare function presetNamed(name: string): Preset | null;
260
287
  declare function presetNames(): string[];
261
288
 
262
- export { AGENTCHAT_TOOL_ALLOW, ANSWER_TOOLS, CLAUDE_CODE_PRESET, CLAUDE_MCP_SERVER_NAME, CODEX_MCP_SERVER_NAME, CODEX_PRESET, CODEX_PROMPT_FROM_STDIN, type ClaudeRunArgOptions, ClaudeRunner, type ClaudeRunnerOptions, type CodexMcpOverride, CodexRunner, type CodexRunnerOptions, LISTENER_KEY_ENV, MIN_CLAUDE_CODE_VERSION, MIN_CODEX_VERSION, PARENT_ENV_KEYS, PRESETS, type Preset, type PresetContext, type PresetInspection, WORK_TOOLS, agentchatTableKeys, buildClaudeEnv, claudeCodePreset, claudeConfigDirFrom, claudeHomeFor, claudeIsLoggedIn, claudeMcpConfig, claudeMcpConfigPath, claudeProfileArgs, claudeRunArgs, claudeUserStatePathFor, codexHomeFrom, codexIsLoggedIn, codexMcpOverrideArgs, codexPreset, codexProfileArgs, codexRunArgs, deniedAncestorOf, inexpressibleDenyPaths, inspectClaudeRuntime, inspectCodexRuntime, presetNamed, presetNames, readDenyRules, semverAtLeast };
289
+ export { AGENTCHAT_TOOL_ALLOW, ANSWER_TOOLS, CLAUDE_CODE_PRESET, CLAUDE_MCP_SERVER_NAME, CODEX_MCP_SERVER_NAME, CODEX_PRESET, CODEX_PROMPT_FROM_STDIN, type ClaudeRunArgOptions, ClaudeRunner, type ClaudeRunnerOptions, type CodexMcpOverride, CodexRunner, type CodexRunnerOptions, LISTENER_KEY_ENV, MIN_CLAUDE_CODE_VERSION, MIN_CODEX_VERSION, PARENT_ENV_KEYS, PRESETS, type Preset, type PresetContext, type PresetInspection, WORK_TOOLS, agentchatTableKeys, buildClaudeEnv, claudeCodePreset, claudeConfigDirFrom, claudeHomeFor, claudeIsLoggedIn, claudeMcpConfig, claudeMcpConfigPath, claudeProfileArgs, claudeRunArgs, claudeUserStatePathFor, codexClientHeadersToml, codexHomeFrom, codexIsLoggedIn, codexMcpOverrideArgs, codexPreset, codexProfileArgs, codexRunArgs, deniedAncestorOf, inexpressibleDenyPaths, inspectClaudeRuntime, inspectCodexRuntime, presetNamed, presetNames, readDenyRules, semverAtLeast };
package/dist/presets.js CHANGED
@@ -1,14 +1,16 @@
1
1
  import {
2
+ VERSION,
2
3
  hostedMcpUrl
3
- } from "./chunk-HOY2FERJ.js";
4
+ } from "./chunk-XDWBTX5J.js";
4
5
  import {
5
6
  spawnRun
6
- } from "./chunk-TH6XOVA3.js";
7
+ } from "./chunk-AE4XHKHQ.js";
7
8
  import {
8
9
  atomicWriteFile,
10
+ clientHeadersOf,
9
11
  log,
10
12
  spawnCommandSync
11
- } from "./chunk-NCSF3CCV.js";
13
+ } from "./chunk-QDM4EFI7.js";
12
14
 
13
15
  // src/presets/claude-code.ts
14
16
  import * as fs from "fs";
@@ -187,12 +189,9 @@ function claudeRunArgs(profile, options = {}) {
187
189
  ...deny.length > 0 ? ["--disallowedTools", deny.join(",")] : []
188
190
  ];
189
191
  }
190
- function claudeMcpConfig(apiBase, apiKey) {
191
- return `${JSON.stringify(
192
- { mcpServers: { [CLAUDE_MCP_SERVER_NAME]: { type: "http", url: hostedMcpUrl(apiBase), headers: { Authorization: `Bearer ${apiKey}` } } } },
193
- null,
194
- 2
195
- )}
192
+ function claudeMcpConfig(apiBase, apiKey, clientVersion = VERSION) {
193
+ const headers = { Authorization: `Bearer ${apiKey}`, ...clientHeadersOf({ runtime: "claude-code", version: clientVersion }) };
194
+ return `${JSON.stringify({ mcpServers: { [CLAUDE_MCP_SERVER_NAME]: { type: "http", url: hostedMcpUrl(apiBase), headers } } }, null, 2)}
196
195
  `;
197
196
  }
198
197
  var ClaudeRunner = class {
@@ -271,7 +270,7 @@ var claudeCodePreset = {
271
270
  name: CLAUDE_CODE_PRESET,
272
271
  describeMcp({ home, apiBase }) {
273
272
  return [
274
- `--mcp-config ${claudeMcpConfigPath(home)} (owner-only): ${CLAUDE_MCP_SERVER_NAME} \u2192 ${hostedMcpUrl(apiBase)}, Authorization: Bearer <this home's key>`,
273
+ `--mcp-config ${claudeMcpConfigPath(home)} (owner-only): ${CLAUDE_MCP_SERVER_NAME} \u2192 ${hostedMcpUrl(apiBase)}, Authorization: Bearer <this home's key>, X-AgentChat-Client: claude-code`,
275
274
  "--strict-mcp-config: no other MCP server (user, project or plugin) is loaded in these runs"
276
275
  ];
277
276
  },
@@ -290,7 +289,7 @@ var claudeCodePreset = {
290
289
  const env = withoutInheritedKey(ctx.env ?? process.env);
291
290
  const configDir = claudeConfigDirFrom(env);
292
291
  const mcpConfigPath = claudeMcpConfigPath(ctx.home);
293
- atomicWriteFile(mcpConfigPath, claudeMcpConfig(ctx.apiBase, ctx.apiKey), 384);
292
+ atomicWriteFile(mcpConfigPath, claudeMcpConfig(ctx.apiBase, ctx.apiKey, ctx.clientVersion ?? VERSION), 384);
294
293
  return new ClaudeRunner({
295
294
  configDir,
296
295
  workdir: ctx.workdir,
@@ -356,6 +355,10 @@ function codexProfileArgs(profile) {
356
355
  return ["--dangerously-bypass-approvals-and-sandbox"];
357
356
  }
358
357
  }
358
+ function codexClientHeadersToml(clientVersion = VERSION) {
359
+ const pairs = Object.entries(clientHeadersOf({ runtime: "codex", version: clientVersion })).map(([name, value]) => `${JSON.stringify(name)} = ${JSON.stringify(value)}`);
360
+ return `{ ${pairs.join(", ")} }`;
361
+ }
359
362
  function codexMcpOverrideArgs(override) {
360
363
  const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`;
361
364
  return [
@@ -364,7 +367,9 @@ function codexMcpOverrideArgs(override) {
364
367
  "-c",
365
368
  `${table}.bearer_token_env_var=${JSON.stringify(override.keyEnv)}`,
366
369
  "-c",
367
- `${table}.default_tools_approval_mode="approve"`
370
+ `${table}.default_tools_approval_mode="approve"`,
371
+ "-c",
372
+ `${table}.http_headers=${codexClientHeadersToml(override.clientVersion ?? VERSION)}`
368
373
  ];
369
374
  }
370
375
  function codexRunArgs(profile, options) {
@@ -451,6 +456,7 @@ var codexPreset = {
451
456
  `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.url="${hostedMcpUrl(apiBase)}"`,
452
457
  `-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)`,
453
458
  `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.default_tools_approval_mode="approve"`,
459
+ `-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)`,
454
460
  own === null ? `${file}: no [mcp_servers.${CODEX_MCP_SERVER_NAME}] of its own \u2014 the run sees only the overrides above` : `${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)`
455
461
  ];
456
462
  },
@@ -475,7 +481,7 @@ var codexPreset = {
475
481
  profile: ctx.profile,
476
482
  apiKey: () => apiKey,
477
483
  keyEnv: LISTENER_KEY_ENV,
478
- mcp: { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV },
484
+ mcp: { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV, clientVersion: ctx.clientVersion ?? VERSION },
479
485
  ...ctx.command !== void 0 ? { command: ctx.command } : {},
480
486
  env
481
487
  });
@@ -520,6 +526,7 @@ export {
520
526
  claudeProfileArgs,
521
527
  claudeRunArgs,
522
528
  claudeUserStatePathFor,
529
+ codexClientHeadersToml,
523
530
  codexHomeFrom,
524
531
  codexIsLoggedIn,
525
532
  codexMcpOverrideArgs,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/presets/claude-code.ts","../src/presets/semver.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 { hostedMcpUrl } from '../integration/mcp-probe.js'\nimport type { RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, 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 { spawnCommandSync } from '../util/spawn.js'\nimport { semverAtLeast } from './semver.js'\nimport { withoutInheritedKey, 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// --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.\n// --permission-mode default Manual: reads need no approval, everything else\n// prompts (and is 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//\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.\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/** Built-in tools an `answer` run keeps: read-only files plus the web. */\nexport const ANSWER_TOOLS = ['Read', 'Glob', 'Grep', '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/** Env a parent Claude Code session leaks that would make the child think it is nested. */\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]\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/**\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, source)\n for (const key of PARENT_ENV_KEYS) delete env[key]\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/**\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.\n */\nexport function claudeIsLoggedIn(configDirOverride?: string, command = 'claude'): boolean {\n const status = spawnCommandSync(command, ['auth', 'status'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: claudeProcessEnv(configDirOverride, process.env),\n })\n if (!status.error) {\n try {\n const parsed = JSON.parse(String(status.stdout ?? '').trim()) as { loggedIn?: unknown }\n if (typeof parsed?.loggedIn === 'boolean') return parsed.loggedIn\n } catch {\n /* no JSON: an older build; fall through to the file and keychain */\n }\n if (status.status === 0) return true\n }\n\n const configDir = claudeHomeFor(configDirOverride)\n if (fs.existsSync(path.join(configDir, '.credentials.json'))) return true\n if (process.platform !== 'darwin') return false\n const keychain = spawnCommandSync('security', ['find-generic-password', '-s', 'Claude Code-credentials'], {\n encoding: 'utf-8',\n timeout: 5_000,\n })\n return !keychain.error && keychain.status === 0\n}\n\nexport function inspectClaudeRuntime(configDirOverride?: string, command = 'claude'): PresetInspection {\n const version = spawnCommandSync(command, ['--version'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: claudeProcessEnv(configDirOverride, process.env),\n })\n if (version.error) return { ok: false, detail: `claude CLI not found on PATH (${version.error.message})` }\n const rendered = String(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\nexport function claudeProfileArgs(profile: RunProfile): string[] {\n switch (profile) {\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, ...ANSWER_TOOLS].join(','),\n ]\n case 'work':\n return [\n '--permission-mode',\n 'acceptEdits',\n '--permission-prompts',\n 'none',\n '--allowedTools',\n [AGENTCHAT_TOOL_ALLOW, ...ANSWER_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 /**\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\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 = 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 boolean flag right after it.\n ...(options.mcpConfigPath !== undefined ? ['--mcp-config', options.mcpConfigPath, '--strict-mcp-config'] : []),\n ...claudeProfileArgs(profile),\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. */\nexport function claudeMcpConfig(apiBase: string, apiKey: string): string {\n return `${JSON.stringify(\n { mcpServers: { [CLAUDE_MCP_SERVER_NAME]: { type: 'http', url: hostedMcpUrl(apiBase), headers: { Authorization: `Bearer ${apiKey}` } } } },\n null,\n 2,\n )}\\n`\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.\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`. */\n readonly mcpConfigPath?: string\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\nexport class ClaudeRunner implements RunRunner {\n readonly name = 'claude'\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\n constructor(private readonly options: ClaudeRunnerOptions) {\n this.command = options.command ?? 'claude'\n }\n\n /** The denied path the configured workdir sits in, or null when the run can read its own cwd. */\n workdirDeniedBy(): string | null {\n return deniedAncestorOf(this.options.workdir, this.options.denyReadPaths)\n }\n\n async preflight(): Promise<RunPreflight> {\n const runtime = inspectClaudeRuntime(this.options.configDir, this.command)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n if (!claudeIsLoggedIn(this.options.configDir, this.command)) {\n return { ok: false, detail: 'claude is not signed in (run `claude` once and sign in)' }\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.options.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.options.denyReadPaths)\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.options.workdir, { recursive: true, mode: 0o700 })\n return { ok: true }\n }\n\n /** The exact argv one run uses — exported for tests to pin per profile. */\n args(): string[] {\n return claudeRunArgs(this.options.profile, {\n maxBudgetUsd: (this.options.env ?? process.env)['AGENTCHAT_RUN_MAX_BUDGET_USD'],\n denyReadPaths: this.options.denyReadPaths,\n mcpConfigPath: this.options.mcpConfigPath,\n })\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const args = this.args()\n log.debug(`claude ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId})`)\n return spawnRun({\n command: this.command,\n args,\n cwd: this.options.workdir,\n env: buildClaudeEnv(this.options.configDir, this.options.env ?? process.env),\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 }\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 }) {\n return [\n `--mcp-config ${claudeMcpConfigPath(home)} (owner-only): ${CLAUDE_MCP_SERVER_NAME} → ${hostedMcpUrl(apiBase)}, Authorization: Bearer <this home's key>`,\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 inspect(env = process.env, command = 'claude') {\n const configDir = claudeConfigDirFrom(env)\n const runtime = inspectClaudeRuntime(configDir, command)\n if (!runtime.ok) return runtime\n return claudeIsLoggedIn(configDir, command)\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), 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 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\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 /** Is the runtime installed, new enough and signed in? For `doctor` and `status`. */\n inspect(env?: NodeJS.ProcessEnv, command?: string): 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.\n */\n describeMcp(ctx: { readonly home: string; readonly apiBase: string; readonly env?: NodeJS.ProcessEnv }): 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/** 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 { hostedMcpUrl } from '../integration/mcp-probe.js'\nimport type { RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, RunRequest, RunRunner } from '../integration/runner.js'\nimport { spawnRun } from '../integration/spawn-run.js'\nimport { log } from '../util/log.js'\nimport { spawnCommandSync } from '../util/spawn.js'\nimport { semverAtLeast } from './semver.js'\nimport { withoutInheritedKey, 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. Web search follows the user's own `web_search` setting.\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\nexport function inspectCodexRuntime(codexHome: string, command = 'codex'): PresetInspection {\n const result = spawnCommandSync(command, ['--version'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: { ...process.env, CODEX_HOME: codexHome },\n })\n if (result.error) return { ok: false, detail: `codex CLI not found on PATH (${result.error.message})` }\n const rendered = String(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 function codexIsLoggedIn(codexHome: string, command = 'codex'): PresetInspection {\n const status = spawnCommandSync(command, ['login', 'status'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: { ...process.env, CODEX_HOME: codexHome },\n })\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\nexport function codexProfileArgs(profile: RunProfile): string[] {\n switch (profile) {\n case 'answer':\n return ['--sandbox', 'read-only', '-c', 'approval_policy=\"never\"']\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/** 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\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 `${table}.bearer_token_env_var=${JSON.stringify(override.keyEnv)}`,\n '-c',\n `${table}.default_tools_approval_mode=\"approve\"`,\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 /** Test seam: the binary to run. */\n readonly command?: string\n readonly env?: NodeJS.ProcessEnv\n}\n\nexport class CodexRunner implements RunRunner {\n readonly name = 'codex'\n private readonly command: string\n\n constructor(private readonly options: CodexRunnerOptions) {\n this.command = options.command ?? 'codex'\n }\n\n async preflight(): Promise<RunPreflight> {\n const runtime = inspectCodexRuntime(this.options.codexHome, this.command)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n const auth = codexIsLoggedIn(this.options.codexHome, this.command)\n if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` }\n fs.mkdirSync(this.options.workdir, { recursive: true })\n return { ok: true }\n }\n\n /** The exact argv one run uses — exported for tests to pin per profile. */\n args(): string[] {\n return codexRunArgs(this.options.profile, { workdir: this.options.workdir, ...(this.options.mcp !== undefined ? { mcp: this.options.mcp } : {}) })\n }\n\n /** The child environment: Codex's home and the key the hosted server needs, under the configured name. */\n env(): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = { ...(this.options.env ?? process.env), CODEX_HOME: this.options.codexHome }\n const key = this.options.apiKey()\n if (key !== null) env[this.options.keyEnv] = key\n return env\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const args = this.args()\n log.debug(`codex ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId})`)\n return spawnRun({\n command: this.command,\n args,\n cwd: this.options.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/**\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({ apiBase, env = process.env }) {\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 `-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 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 // A read-only sandbox reads the whole filesystem.\n serviceEnv: ['CODEX_HOME'],\n readsIdentityHome: true,\n inspect(env = process.env, command = 'codex') {\n const home = codexHomeFrom(env)\n const runtime = inspectCodexRuntime(home, command)\n if (!runtime.ok) return runtime\n const auth = 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 return new CodexRunner({\n codexHome: codexHomeFrom(env),\n workdir: ctx.workdir,\n profile: ctx.profile,\n apiKey: () => apiKey,\n keyEnv: LISTENER_KEY_ENV,\n mcp: { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV },\n ...(ctx.command !== undefined ? { command: ctx.command } : {}),\n env,\n })\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 { semverAtLeast } from './semver.js'\nexport {\n CLAUDE_CODE_PRESET,\n MIN_CLAUDE_CODE_VERSION,\n CLAUDE_MCP_SERVER_NAME,\n AGENTCHAT_TOOL_ALLOW,\n ANSWER_TOOLS,\n WORK_TOOLS,\n PARENT_ENV_KEYS,\n claudeConfigDirFrom,\n claudeHomeFor,\n claudeUserStatePathFor,\n buildClaudeEnv,\n claudeIsLoggedIn,\n inspectClaudeRuntime,\n deniedAncestorOf,\n claudeProfileArgs,\n readDenyRules,\n inexpressibleDenyPaths,\n claudeRunArgs,\n claudeMcpConfig,\n claudeMcpConfigPath,\n ClaudeRunner,\n claudeCodePreset,\n type ClaudeRunArgOptions,\n type ClaudeRunnerOptions,\n} from './claude-code.js'\nexport {\n CODEX_PRESET,\n MIN_CODEX_VERSION,\n CODEX_MCP_SERVER_NAME,\n LISTENER_KEY_ENV,\n CODEX_PROMPT_FROM_STDIN,\n codexHomeFrom,\n inspectCodexRuntime,\n codexIsLoggedIn,\n codexProfileArgs,\n codexMcpOverrideArgs,\n codexRunArgs,\n agentchatTableKeys,\n CodexRunner,\n codexPreset,\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[]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K,QAAQ,IAAI,KAAK,OAAQ;AACzF;AAEO,SAAS,cAAwB;AACtC,SAAO,OAAO,KAAK,OAAO;AAC5B;","names":["fs","os","path"]}
1
+ {"version":3,"sources":["../src/presets/claude-code.ts","../src/presets/semver.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 type { RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, 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 { spawnCommandSync } from '../util/spawn.js'\nimport { VERSION } from '../version.js'\nimport { semverAtLeast } from './semver.js'\nimport { withoutInheritedKey, 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// --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.\n// --permission-mode default Manual: reads need no approval, everything else\n// prompts (and is 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//\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.\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/** Built-in tools an `answer` run keeps: read-only files plus the web. */\nexport const ANSWER_TOOLS = ['Read', 'Glob', 'Grep', '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/** Env a parent Claude Code session leaks that would make the child think it is nested. */\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]\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/**\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, source)\n for (const key of PARENT_ENV_KEYS) delete env[key]\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/**\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.\n */\nexport function claudeIsLoggedIn(configDirOverride?: string, command = 'claude'): boolean {\n const status = spawnCommandSync(command, ['auth', 'status'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: claudeProcessEnv(configDirOverride, process.env),\n })\n if (!status.error) {\n try {\n const parsed = JSON.parse(String(status.stdout ?? '').trim()) as { loggedIn?: unknown }\n if (typeof parsed?.loggedIn === 'boolean') return parsed.loggedIn\n } catch {\n /* no JSON: an older build; fall through to the file and keychain */\n }\n if (status.status === 0) return true\n }\n\n const configDir = claudeHomeFor(configDirOverride)\n if (fs.existsSync(path.join(configDir, '.credentials.json'))) return true\n if (process.platform !== 'darwin') return false\n const keychain = spawnCommandSync('security', ['find-generic-password', '-s', 'Claude Code-credentials'], {\n encoding: 'utf-8',\n timeout: 5_000,\n })\n return !keychain.error && keychain.status === 0\n}\n\nexport function inspectClaudeRuntime(configDirOverride?: string, command = 'claude'): PresetInspection {\n const version = spawnCommandSync(command, ['--version'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: claudeProcessEnv(configDirOverride, process.env),\n })\n if (version.error) return { ok: false, detail: `claude CLI not found on PATH (${version.error.message})` }\n const rendered = String(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\nexport function claudeProfileArgs(profile: RunProfile): string[] {\n switch (profile) {\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, ...ANSWER_TOOLS].join(','),\n ]\n case 'work':\n return [\n '--permission-mode',\n 'acceptEdits',\n '--permission-prompts',\n 'none',\n '--allowedTools',\n [AGENTCHAT_TOOL_ALLOW, ...ANSWER_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 /**\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\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 = 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 boolean flag right after it.\n ...(options.mcpConfigPath !== undefined ? ['--mcp-config', options.mcpConfigPath, '--strict-mcp-config'] : []),\n ...claudeProfileArgs(profile),\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\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.\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`. */\n readonly mcpConfigPath?: string\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\nexport class ClaudeRunner implements RunRunner {\n readonly name = 'claude'\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\n constructor(private readonly options: ClaudeRunnerOptions) {\n this.command = options.command ?? 'claude'\n }\n\n /** The denied path the configured workdir sits in, or null when the run can read its own cwd. */\n workdirDeniedBy(): string | null {\n return deniedAncestorOf(this.options.workdir, this.options.denyReadPaths)\n }\n\n async preflight(): Promise<RunPreflight> {\n const runtime = inspectClaudeRuntime(this.options.configDir, this.command)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n if (!claudeIsLoggedIn(this.options.configDir, this.command)) {\n return { ok: false, detail: 'claude is not signed in (run `claude` once and sign in)' }\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.options.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.options.denyReadPaths)\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.options.workdir, { recursive: true, mode: 0o700 })\n return { ok: true }\n }\n\n /** The exact argv one run uses — exported for tests to pin per profile. */\n args(): string[] {\n return claudeRunArgs(this.options.profile, {\n maxBudgetUsd: (this.options.env ?? process.env)['AGENTCHAT_RUN_MAX_BUDGET_USD'],\n denyReadPaths: this.options.denyReadPaths,\n mcpConfigPath: this.options.mcpConfigPath,\n })\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const args = this.args()\n log.debug(`claude ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId})`)\n return spawnRun({\n command: this.command,\n args,\n cwd: this.options.workdir,\n env: buildClaudeEnv(this.options.configDir, this.options.env ?? process.env),\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 }\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 }) {\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 '--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 inspect(env = process.env, command = 'claude') {\n const configDir = claudeConfigDirFrom(env)\n const runtime = inspectClaudeRuntime(configDir, command)\n if (!runtime.ok) return runtime\n return claudeIsLoggedIn(configDir, command)\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 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 /** Is the runtime installed, new enough and signed in? For `doctor` and `status`. */\n inspect(env?: NodeJS.ProcessEnv, command?: string): 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.\n */\n describeMcp(ctx: { readonly home: string; readonly apiBase: string; readonly env?: NodeJS.ProcessEnv }): 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/** 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 type { RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, RunRequest, RunRunner } from '../integration/runner.js'\nimport { spawnRun } from '../integration/spawn-run.js'\nimport { log } from '../util/log.js'\nimport { spawnCommandSync } from '../util/spawn.js'\nimport { VERSION } from '../version.js'\nimport { semverAtLeast } from './semver.js'\nimport { withoutInheritedKey, 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. Web search follows the user's own `web_search` setting.\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\nexport function inspectCodexRuntime(codexHome: string, command = 'codex'): PresetInspection {\n const result = spawnCommandSync(command, ['--version'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: { ...process.env, CODEX_HOME: codexHome },\n })\n if (result.error) return { ok: false, detail: `codex CLI not found on PATH (${result.error.message})` }\n const rendered = String(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 function codexIsLoggedIn(codexHome: string, command = 'codex'): PresetInspection {\n const status = spawnCommandSync(command, ['login', 'status'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: { ...process.env, CODEX_HOME: codexHome },\n })\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\nexport function codexProfileArgs(profile: RunProfile): string[] {\n switch (profile) {\n case 'answer':\n return ['--sandbox', 'read-only', '-c', 'approval_policy=\"never\"']\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/** 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 /** 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/** 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 `${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 /** Test seam: the binary to run. */\n readonly command?: string\n readonly env?: NodeJS.ProcessEnv\n}\n\nexport class CodexRunner implements RunRunner {\n readonly name = 'codex'\n private readonly command: string\n\n constructor(private readonly options: CodexRunnerOptions) {\n this.command = options.command ?? 'codex'\n }\n\n async preflight(): Promise<RunPreflight> {\n const runtime = inspectCodexRuntime(this.options.codexHome, this.command)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n const auth = codexIsLoggedIn(this.options.codexHome, this.command)\n if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` }\n fs.mkdirSync(this.options.workdir, { recursive: true })\n return { ok: true }\n }\n\n /** The exact argv one run uses — exported for tests to pin per profile. */\n args(): string[] {\n return codexRunArgs(this.options.profile, { workdir: this.options.workdir, ...(this.options.mcp !== undefined ? { mcp: this.options.mcp } : {}) })\n }\n\n /** The child environment: Codex's home and the key the hosted server needs, under the configured name. */\n env(): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = { ...(this.options.env ?? process.env), CODEX_HOME: this.options.codexHome }\n const key = this.options.apiKey()\n if (key !== null) env[this.options.keyEnv] = key\n return env\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const args = this.args()\n log.debug(`codex ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId})`)\n return spawnRun({\n command: this.command,\n args,\n cwd: this.options.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/**\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({ apiBase, env = process.env }) {\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 `-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 // A read-only sandbox reads the whole filesystem.\n serviceEnv: ['CODEX_HOME'],\n readsIdentityHome: true,\n inspect(env = process.env, command = 'codex') {\n const home = codexHomeFrom(env)\n const runtime = inspectCodexRuntime(home, command)\n if (!runtime.ok) return runtime\n const auth = 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 return new CodexRunner({\n codexHome: codexHomeFrom(env),\n workdir: ctx.workdir,\n profile: ctx.profile,\n apiKey: () => apiKey,\n keyEnv: LISTENER_KEY_ENV,\n mcp: { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV, clientVersion: ctx.clientVersion ?? VERSION },\n ...(ctx.command !== undefined ? { command: ctx.command } : {}),\n env,\n })\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 { semverAtLeast } from './semver.js'\nexport {\n CLAUDE_CODE_PRESET,\n MIN_CLAUDE_CODE_VERSION,\n CLAUDE_MCP_SERVER_NAME,\n AGENTCHAT_TOOL_ALLOW,\n ANSWER_TOOLS,\n WORK_TOOLS,\n PARENT_ENV_KEYS,\n claudeConfigDirFrom,\n claudeHomeFor,\n claudeUserStatePathFor,\n buildClaudeEnv,\n claudeIsLoggedIn,\n inspectClaudeRuntime,\n deniedAncestorOf,\n claudeProfileArgs,\n readDenyRules,\n inexpressibleDenyPaths,\n claudeRunArgs,\n claudeMcpConfig,\n claudeMcpConfigPath,\n ClaudeRunner,\n claudeCodePreset,\n type ClaudeRunArgOptions,\n type ClaudeRunnerOptions,\n} from './claude-code.js'\nexport {\n CODEX_PRESET,\n MIN_CODEX_VERSION,\n CODEX_MCP_SERVER_NAME,\n LISTENER_KEY_ENV,\n CODEX_PROMPT_FROM_STDIN,\n codexHomeFrom,\n inspectCodexRuntime,\n codexIsLoggedIn,\n codexProfileArgs,\n codexMcpOverrideArgs,\n codexClientHeadersToml,\n codexRunArgs,\n agentchatTableKeys,\n CodexRunner,\n codexPreset,\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,YAAY,QAAQ;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,O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,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","os","path"]}
@@ -8,11 +8,19 @@ declare function resolveRunProfile(env?: NodeJS.ProcessEnv): RunProfile;
8
8
  /** The one switch: `AGENTCHAT_INTEGRATION=off` holds no socket and starts no run. Tools and manual stay. */
9
9
  declare const INTEGRATION_ENV = "AGENTCHAT_INTEGRATION";
10
10
  /**
11
- * The previous spelling of the switch. Honoured for one release: a service
12
- * installed before the rename captured it into its unit file, and that unit
13
- * must keep meaning what the operator set.
11
+ * The previous spelling of the switch (a legacy name: compatibility reader
12
+ * only). Still read, because a service installed before the rename captured
13
+ * it into its unit file, and that unit must keep meaning what the operator
14
+ * set; `AGENTCHAT_INTEGRATION` wins when both are set. Contract v1 (section 7,
15
+ * old integration settings) removes it on `INTEGRATION_ENV_LEGACY_REMOVAL`;
16
+ * tests/legacy-env-removal.test.ts fails from that day, so the reader is
17
+ * deleted in a release rather than remembered. Until then an `off` here is
18
+ * honoured — never silently dropped, which would turn on an integration its
19
+ * operator switched off.
14
20
  */
15
21
  declare const INTEGRATION_ENV_LEGACY = "AGENTCHAT_DOORBELL";
22
+ /** The day contract v1 drops `AGENTCHAT_DOORBELL` (UTC). */
23
+ declare const INTEGRATION_ENV_LEGACY_REMOVAL = "2027-02-01";
16
24
  /** Which switch turned the integration off, or null when it is on. The new spelling wins when both are set. */
17
25
  declare function integrationDisabledBy(env?: NodeJS.ProcessEnv): string | null;
18
26
  declare function integrationDisabled(env?: NodeJS.ProcessEnv): boolean;
@@ -119,4 +127,4 @@ interface RunnerFactory {
119
127
  type RunnerSource = RunRunner | RunnerFactory;
120
128
  declare function isRunnerFactory(source: RunnerSource): source is RunnerFactory;
121
129
 
122
- export { DEFAULT_RUN_BUDGET_MS as D, INTEGRATION_ENV as I, type RunnerSource as R, type RunProfile as a, type RunRunner as b, type RunOutcome as c, type RunKind as d, type RunOutcomeState as e, type RunPreflight as f, type RunRequest as g, type RunWake as h, type RunnerFactory as i, type RunnerIdentity as j, DEFAULT_RUN_PROFILE as k, INTEGRATION_ENV_LEGACY as l, RUN_BUDGET_ENV as m, RUN_PROFILES as n, RUN_PROFILE_ENV as o, integrationDisabled as p, integrationDisabledBy as q, isRunProfile as r, isRunnerFactory as s, resolveRunBudgetMs as t, resolveRunProfile as u };
130
+ export { DEFAULT_RUN_BUDGET_MS as D, INTEGRATION_ENV as I, type RunnerSource as R, type RunProfile as a, type RunRunner as b, type RunOutcome as c, type RunKind as d, type RunOutcomeState as e, type RunPreflight as f, type RunRequest as g, type RunWake as h, type RunnerFactory as i, type RunnerIdentity as j, DEFAULT_RUN_PROFILE as k, INTEGRATION_ENV_LEGACY as l, INTEGRATION_ENV_LEGACY_REMOVAL as m, RUN_BUDGET_ENV as n, RUN_PROFILES as o, RUN_PROFILE_ENV as p, integrationDisabled as q, integrationDisabledBy as r, isRunProfile as s, isRunnerFactory as t, resolveRunBudgetMs as u, resolveRunProfile as v };
@@ -199,6 +199,12 @@ interface DoctorCheck {
199
199
  /** What the shared `status` hands a host's extra lines: what it already fetched from the served texts (one fetch per command). */
200
200
  interface StatusContext {
201
201
  identityLine: string | null;
202
+ /**
203
+ * The served `identity_line_template` from the same texts, or null when none
204
+ * are in hand: what `readAnchorHandleAt` recognises an unmarked block by, in
205
+ * whatever words the server serves today.
206
+ */
207
+ identityLineTemplate: string | null;
202
208
  /** The manual the served texts announce (`texts.manual`), or null when none are in hand — what `checkManual` compares the skill file with. */
203
209
  manual: ServedManual | null;
204
210
  }
@@ -207,6 +213,8 @@ interface DoctorContext {
207
213
  fix?: boolean;
208
214
  /** The served identity line for this agent, or null when the server could not be reached and nothing is cached. */
209
215
  identityLine: string | null;
216
+ /** The served `identity_line_template`, or null when none are in hand (see `StatusContext`). */
217
+ identityLineTemplate: string | null;
210
218
  /** The manual the served texts announce, or null when none are in hand (`--fix` syncs the skill file to it). */
211
219
  manual: ServedManual | null;
212
220
  }
@@ -244,8 +252,12 @@ interface HostProfile {
244
252
  anchorFile?(): string;
245
253
  /** Exactly what a user types to reach this integration. */
246
254
  invocation(): string;
247
- /** Render the anchor block body this host wants from the served identity line (normally `renderAnchorBlock`). */
248
- renderAnchor(identityLine: string): string;
255
+ /**
256
+ * The identity block this host places for `handle` from the served identity
257
+ * line (normally `renderAnchorBlock`, the kit's shape with the handle line).
258
+ * Throws when the line does not name the handle; nothing is written then.
259
+ */
260
+ renderAnchor(identityLine: string, handle: string): string;
249
261
  /**
250
262
  * What to call the anchor in output. Defaults to the instruction file's own
251
263
  * basename (`CLAUDE.md`, `AGENTS.md`), which is what a user actually looks
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentchatme/agent-core",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Shared host-agnostic engine for AgentChat integrations — the resident supervisor on the AgentChat SDK's integration kit (single-run mode: the socket acking on receipt, wakes, the tray before every run), the runner seam and spawnRun, the presets for known coding agents' headless runs, identity storage and flows, service plumbing. Runtime code only; every function takes an identity home, none resolves one.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/integration/mcp-probe.ts"],"sourcesContent":["import { integration as kit } from 'agentchatme'\nimport { clientIdentityOf, type IntegrationClient } from '../client-identity.js'\n\n// ─── Can this key reach the hosted tools? ───────────────────────────────────\n//\n// `status` and `doctor` ask the SDK kit's `probeHostedTools`: one MCP\n// `initialize` over Streamable HTTP with the bearer key — the same first\n// request a runtime makes on connect — then `tools/list`, which must show the\n// tools a run needs (`agentchat_inbox`, `agentchat_decide`). A 401 means the\n// key does not authenticate; a transport error means the endpoint is not\n// reachable from here. No tool is called.\n\nexport const HOSTED_MCP_PATH = kit.HOSTED_MCP_PATH\n\nexport function hostedMcpUrl(apiBase: string): string {\n return kit.hostedMcpUrl(apiBase)\n}\n\nexport interface McpProbeResult {\n readonly ok: boolean\n readonly status?: number\n readonly serverName?: string\n readonly serverVersion?: string\n readonly protocolVersion?: string\n /** Every tool the server listed for this key. */\n readonly tools?: readonly string[]\n /** Tools a run needs that were not listed. */\n readonly missing?: readonly string[]\n readonly error?: string\n}\n\nexport async function probeHostedMcp(params: {\n apiKey: string\n apiBase: string\n /** How this integration identifies to the server. */\n client: IntegrationClient\n /**\n * Accepted for compatibility and ignored: the probe identifies as `client`\n * (headers and `clientInfo` alike), so the server's analytics see the\n * integration, never a free-text name it would file as unknown.\n */\n clientName?: string\n /** Accepted for compatibility and ignored (see `clientName`). */\n clientVersion?: string\n timeoutMs?: number\n fetch?: typeof fetch\n}): Promise<McpProbeResult> {\n return kit.probeHostedTools({\n apiBase: params.apiBase,\n apiKey: params.apiKey,\n clientIdentity: clientIdentityOf(params.client),\n ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),\n ...(params.fetch !== undefined ? { fetch: params.fetch } : {}),\n })\n}\n"],"mappings":";;;;;AAAA,SAAS,eAAe,WAAW;AAY5B,IAAM,kBAAkB,IAAI;AAE5B,SAAS,aAAa,SAAyB;AACpD,SAAO,IAAI,aAAa,OAAO;AACjC;AAeA,eAAsB,eAAe,QAeT;AAC1B,SAAO,IAAI,iBAAiB;AAAA,IAC1B,SAAS,OAAO;AAAA,IAChB,QAAQ,OAAO;AAAA,IACf,gBAAgB,iBAAiB,OAAO,MAAM;AAAA,IAC9C,GAAI,OAAO,cAAc,SAAY,EAAE,WAAW,OAAO,UAAU,IAAI,CAAC;AAAA,IACxE,GAAI,OAAO,UAAU,SAAY,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;AAAA,EAC9D,CAAC;AACH;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/client-identity.ts","../src/util/fsutil.ts","../src/util/log.ts","../src/util/spawn.ts"],"sourcesContent":["import type { AgentChatClientIdentity, AgentChatClientKind, TextsRuntime } from 'agentchatme'\n\n// ─── Who is calling ─────────────────────────────────────────────────────────\n//\n// An integration names itself to the server once: the runtime it serves, as\n// the server's texts endpoint spells it (`claude-code`, `codex`, …), and its\n// own package version. That one value drives two things — the served texts\n// (`GET /v1/texts?runtime=`) and the client identity on every request and on\n// the socket's hello — so the server's analytics tell the runtimes apart\n// instead of lumping them under one bucket. Nothing in this package branches\n// on it: it is a label the integration passes through, never a switch.\n\nexport interface IntegrationClient {\n readonly runtime: TextsRuntime\n readonly version: string\n /**\n * The client name sent to the server when it is not the runtime itself —\n * a front door that serves several runtimes (the `agentchat` listener)\n * names itself here, and `runtime` stays what the texts are rendered for.\n */\n readonly name?: string\n}\n\n/** The name this client identifies as: its own `name`, else its runtime. */\nexport function clientNameOf(client: IntegrationClient): string {\n return client.name ?? client.runtime\n}\n\n/**\n * The SDK's client identity for this integration. The SDK types client names\n * as a closed union and the server normalises whatever arrives, so the\n * runtime name is passed through as-is; the union widens on the SDK side.\n */\nexport function clientIdentityOf(client: IntegrationClient): AgentChatClientIdentity {\n return { name: clientNameOf(client) as unknown as AgentChatClientKind, version: client.version }\n}\n\n/** The same identity as headers, for the one raw request this package still makes (the MCP probe). */\nexport function clientHeadersOf(client: IntegrationClient): Record<string, string> {\n return {\n 'X-AgentChat-Client': clientNameOf(client),\n 'X-AgentChat-Client-Version': client.version,\n }\n}\n","import { randomBytes } from 'node:crypto'\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\n// ─── Atomic replacement ─────────────────────────────────────────────────────\n//\n// Tmp file + rename in the same directory: a reader sees the old file or the\n// new one, never part of one, and a crash leaves the old file or a stray tmp —\n// never a truncated JSON that would make every later invocation throw. A\n// failed write removes its tmp file and leaves the old file exactly as it was.\n//\n// The tmp file is never a path someone else can prepare: its name carries a\n// random suffix, it is created exclusively (`wx`: O_CREAT|O_EXCL, which\n// refuses an existing name — a planted symlink included — instead of following\n// it), its mode is set on the open descriptor rather than on a path, and its\n// contents are flushed before the rename. On Windows a rename onto a file\n// another process has open fails transiently (EPERM / EBUSY / EACCES while a\n// scanner or an editor holds it), so the rename is retried for ~100 ms.\n\n/** A fresh, unguessable tmp name beside `file`. */\nfunction tmpPathFor(file: string): string {\n return path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`)\n}\n\nconst RENAME_RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES'])\nconst RENAME_ATTEMPTS = 6\nconst RENAME_DELAY_MS = 20\n\nfunction sleepSync(ms: number): void {\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)\n}\n\nexport interface RenameRetryOptions {\n /** Defaults to `fs.renameSync`; injectable for tests. */\n readonly rename?: (from: string, to: string) => void\n /** Defaults to Windows only, where the transient sharing errors happen. */\n readonly retry?: boolean\n readonly attempts?: number\n readonly delayMs?: number\n}\n\n/** `renameSync`, retried a few times over ~100 ms on a transient EPERM / EBUSY / EACCES (Windows). */\nexport function renameWithRetry(from: string, to: string, options: RenameRetryOptions = {}): void {\n const rename = options.rename ?? ((a: string, b: string) => fs.renameSync(a, b))\n const retry = options.retry ?? process.platform === 'win32'\n const attempts = retry ? (options.attempts ?? RENAME_ATTEMPTS) : 1\n for (let attempt = 1; ; attempt++) {\n try {\n rename(from, to)\n return\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (attempt >= attempts || code === undefined || !RENAME_RETRY_CODES.has(code)) throw err\n sleepSync(options.delayMs ?? RENAME_DELAY_MS)\n }\n }\n}\n\nfunction removeQuietly(file: string): void {\n try {\n fs.rmSync(file, { force: true })\n } catch {\n /* preserve the original error */\n }\n}\n\n/** `mode` is set exactly (whatever the umask); without one the file gets the umask's default, as `writeFileSync` would. */\nexport function atomicWriteFile(filePath: string, data: string | Uint8Array, mode?: number): void {\n const dir = path.dirname(filePath)\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 })\n const tmp = tmpPathFor(filePath)\n try {\n const fd = fs.openSync(tmp, 'wx', mode ?? 0o666)\n try {\n if (mode !== undefined) fs.fchmodSync(fd, mode)\n fs.writeFileSync(fd, data)\n fs.fsyncSync(fd)\n } finally {\n fs.closeSync(fd)\n }\n renameWithRetry(tmp, filePath)\n } catch (err) {\n removeQuietly(tmp)\n throw err\n }\n}\n\n/** Crash-safe file replacement for shipped executable bundles. */\nexport function atomicCopyFile(source: string, destination: string, mode = 0o755): void {\n const dir = path.dirname(destination)\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 })\n const tmp = tmpPathFor(destination)\n try {\n fs.copyFileSync(source, tmp, fs.constants.COPYFILE_EXCL)\n // Read-write, not read-only: Windows flushes a file to disk only through\n // a handle with write access (FlushFileBuffers), so fsync on a read-only\n // descriptor fails there with EPERM. 0.3.0 opened it read-only and every\n // Windows daemon install failed at this line.\n const fd = fs.openSync(tmp, fs.constants.O_RDWR | (fs.constants.O_NOFOLLOW ?? 0))\n try {\n fs.fchmodSync(fd, mode)\n fs.fsyncSync(fd)\n } finally {\n fs.closeSync(fd)\n }\n renameWithRetry(tmp, destination)\n } catch (err) {\n removeQuietly(tmp)\n throw err\n }\n}\n\nexport function readJsonFile<T>(filePath: string): T | null {\n try {\n const raw = fs.readFileSync(filePath, 'utf-8')\n return JSON.parse(raw) as T\n } catch {\n return null\n }\n}\n","// ─── stderr-only diagnostics ────────────────────────────────────────────────\n//\n// stdout belongs to the hook protocol (platforms parse it as JSON) and to\n// command output the agent reads. Every diagnostic goes to stderr, gated by\n// AGENTCHAT_LOG_LEVEL. There is deliberately no logging dependency here —\n// hooks run on every session start and must add zero startup weight.\n\nconst LEVELS = ['silent', 'error', 'warn', 'info', 'debug'] as const\nexport type LogLevel = (typeof LEVELS)[number]\n\nfunction activeLevel(): number {\n const raw = (process.env['AGENTCHAT_LOG_LEVEL'] ?? 'warn').toLowerCase()\n const idx = LEVELS.indexOf(raw as LogLevel)\n return idx === -1 ? LEVELS.indexOf('warn') : idx\n}\n\nfunction emit(level: LogLevel, msg: string): void {\n if (LEVELS.indexOf(level) <= activeLevel() && level !== 'silent') {\n process.stderr.write(`[agentchat:${level}] ${msg}\\n`)\n }\n}\n\nexport const log = {\n error: (msg: string) => emit('error', msg),\n warn: (msg: string) => emit('warn', msg),\n info: (msg: string) => emit('info', msg),\n debug: (msg: string) => emit('debug', msg),\n}\n","import crossSpawn from 'cross-spawn'\nimport type {\n spawn as nodeSpawn,\n spawnSync as nodeSpawnSync,\n} from 'node:child_process'\n\n// Node's child_process does not resolve npm's `.cmd` shims on Windows the way\n// a terminal does. Coding-agent and npx executables are commonly installed\n// through exactly those shims, so a direct spawn can report ENOENT even though\n// the user's command works. cross-spawn performs PATHEXT/shebang resolution\n// without putting paths or arguments through a shell.\nexport const spawnCommand = crossSpawn as typeof nodeSpawn\nexport const spawnCommandSync = crossSpawn.sync as typeof nodeSpawnSync\n"],"mappings":";;;;;;;AAwBO,SAAS,aAAa,QAAmC;AAC9D,SAAO,OAAO,QAAQ,OAAO;AAC/B;AAOO,SAAS,iBAAiB,QAAoD;AACnF,SAAO,EAAE,MAAM,aAAa,MAAM,GAAqC,SAAS,OAAO,QAAQ;AACjG;AAGO,SAAS,gBAAgB,QAAmD;AACjF,SAAO;AAAA,IACL,sBAAsB,aAAa,MAAM;AAAA,IACzC,8BAA8B,OAAO;AAAA,EACvC;AACF;;;AC3CA,SAAS,mBAAmB;AAC5B,YAAY,QAAQ;AACpB,YAAY,UAAU;AAkBtB,SAAS,WAAW,MAAsB;AACxC,SAAY,UAAU,aAAQ,IAAI,GAAG,IAAS,cAAS,IAAI,CAAC,IAAI,QAAQ,GAAG,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,MAAM;AACrH;AAEA,IAAM,qBAAqB,oBAAI,IAAI,CAAC,SAAS,SAAS,QAAQ,CAAC;AAC/D,IAAM,kBAAkB;AACxB,IAAM,kBAAkB;AAExB,SAAS,UAAU,IAAkB;AACnC,UAAQ,KAAK,IAAI,WAAW,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