@agentchatme/agent-core 0.4.0 → 0.5.0

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.js CHANGED
@@ -1,14 +1,18 @@
1
1
  import {
2
- hostedMcpUrl
3
- } from "./chunk-HOY2FERJ.js";
4
- import {
5
- spawnRun
6
- } from "./chunk-TH6XOVA3.js";
2
+ VERSION,
3
+ hostedMcpUrl,
4
+ runProbe
5
+ } from "./chunk-UE7DKW3C.js";
7
6
  import {
8
7
  atomicWriteFile,
8
+ clientHeadersOf,
9
+ killProcessTree,
9
10
  log,
10
- spawnCommandSync
11
- } from "./chunk-NCSF3CCV.js";
11
+ redactDiagnostic,
12
+ spawnCommand,
13
+ spawnRun,
14
+ workdirExposesHome
15
+ } from "./chunk-AFDD53DD.js";
12
16
 
13
17
  // src/presets/claude-code.ts
14
18
  import * as fs from "fs";
@@ -31,6 +35,145 @@ function semverAtLeast(actual, minimum) {
31
35
  }
32
36
 
33
37
  // src/presets/types.ts
38
+ var CLAUDE_CODE_ENV_KEPT = [
39
+ // Sign-in and provider
40
+ "CLAUDE_CODE_OAUTH_TOKEN",
41
+ "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
42
+ "CLAUDE_CODE_OAUTH_SCOPES",
43
+ "CLAUDE_CODE_API_KEY_HELPER_TTL_MS",
44
+ "CLAUDE_CODE_USE_BEDROCK",
45
+ "CLAUDE_CODE_USE_VERTEX",
46
+ "CLAUDE_CODE_USE_FOUNDRY",
47
+ "CLAUDE_CODE_USE_MANTLE",
48
+ "CLAUDE_CODE_USE_ANTHROPIC_AWS",
49
+ "CLAUDE_CODE_SKIP_BEDROCK_AUTH",
50
+ "CLAUDE_CODE_SKIP_VERTEX_AUTH",
51
+ "CLAUDE_CODE_SKIP_FOUNDRY_AUTH",
52
+ "CLAUDE_CODE_SKIP_MANTLE_AUTH",
53
+ "CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH",
54
+ "CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS",
55
+ // Network and TLS
56
+ "CLAUDE_CODE_CLIENT_CERT",
57
+ "CLAUDE_CODE_CLIENT_KEY",
58
+ "CLAUDE_CODE_CLIENT_KEY_PASSPHRASE",
59
+ "CLAUDE_CODE_CERT_STORE",
60
+ "CLAUDE_CODE_PROXY_RESOLVES_HOSTS",
61
+ "CLAUDE_CODE_CONNECT_TIMEOUT_MS",
62
+ // Privacy and secrets switches the user turned on
63
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
64
+ "CLAUDE_CODE_ENABLE_TELEMETRY",
65
+ "CLAUDE_CODE_SUBPROCESS_ENV_SCRUB",
66
+ "CLAUDE_CODE_MCP_ALLOWLIST_ENV",
67
+ "CLAUDE_CODE_DISABLE_CLAUDE_MDS",
68
+ "CLAUDE_CODE_DISABLE_AUTO_MEMORY",
69
+ // Model request settings the user chose
70
+ "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS",
71
+ "CLAUDE_CODE_EXTRA_BODY",
72
+ "CLAUDE_CODE_MAX_OUTPUT_TOKENS",
73
+ // Platform
74
+ "CLAUDE_CODE_GIT_BASH_PATH",
75
+ "CLAUDE_CODE_TMPDIR",
76
+ // Set by the preset itself (a larger value of the user's is kept)
77
+ "CLAUDE_CODE_MCP_STARTUP_WAIT_MS"
78
+ ];
79
+ var CLAUDE_SESSION_ENV = ["CLAUDECODE", "CLAUDE_PID", "CLAUDE_EFFORT", "CLAUDE_JOB_DIR", "CLAUDE_PROJECT_DIR", "TRACEPARENT", "TRACESTATE", "AI_AGENT"];
80
+ var CODEX_SESSION_ENV = [
81
+ "CODEX_SANDBOX",
82
+ "CODEX_SANDBOX_NETWORK_DISABLED",
83
+ "CODEX_SESSION_ID",
84
+ "CODEX_THREAD_ID",
85
+ "CODEX_VERSION",
86
+ "CODEX_PERMISSION_PROFILE",
87
+ "CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN",
88
+ "CODEX_ESCALATE_SOCKET",
89
+ "CODEX_NETWORK_PROXY_ACTIVE",
90
+ "CODEX_NETWORK_ALLOW_LOCAL_BINDING",
91
+ "CODEX_NETWORK_PROXY_ATTRIBUTION",
92
+ "CODEX_NETWORK_PROXY_CREDENTIAL_BROKER_ACTIVE",
93
+ "CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS",
94
+ "CODEX_WINDOWS_SANDBOX_PROXY_PORTS"
95
+ ];
96
+ var CODEX_MANAGED_PROXY_ENV = [
97
+ "ELECTRON_GET_USE_PROXY",
98
+ "NODE_USE_ENV_PROXY",
99
+ "HTTP_PROXY",
100
+ "HTTPS_PROXY",
101
+ "YARN_HTTP_PROXY",
102
+ "YARN_HTTPS_PROXY",
103
+ "NPM_CONFIG_HTTP_PROXY",
104
+ "NPM_CONFIG_HTTPS_PROXY",
105
+ "NPM_CONFIG_PROXY",
106
+ "BUNDLE_HTTP_PROXY",
107
+ "BUNDLE_HTTPS_PROXY",
108
+ "PIP_PROXY",
109
+ "DOCKER_HTTP_PROXY",
110
+ "DOCKER_HTTPS_PROXY",
111
+ "WS_PROXY",
112
+ "WSS_PROXY",
113
+ "NO_PROXY",
114
+ "NPM_CONFIG_NOPROXY",
115
+ "YARN_NO_PROXY",
116
+ "BUNDLE_NO_PROXY",
117
+ "ALL_PROXY",
118
+ "FTP_PROXY"
119
+ ];
120
+ var CODEX_CA_ENV_KEYS = [
121
+ "CODEX_CA_CERTIFICATE",
122
+ "SSL_CERT_FILE",
123
+ "REQUESTS_CA_BUNDLE",
124
+ "CURL_CA_BUNDLE",
125
+ "NODE_EXTRA_CA_CERTS",
126
+ "GIT_SSL_CAINFO",
127
+ "CARGO_HTTP_CAINFO",
128
+ "PIP_CERT",
129
+ "BUNDLE_SSL_CA_CERT",
130
+ "NPM_CONFIG_CAFILE"
131
+ ];
132
+ function isManagedCaBundle(value) {
133
+ return /[\\/]proxy[\\/]ca-bundle-[0-9a-fA-F]{64}\.pem$/.test(value);
134
+ }
135
+ var CODEX_PROXY_GIT_SSH_MARKER = "CODEX_PROXY_GIT_SSH_COMMAND=1 ";
136
+ function isParentSessionEnv(key) {
137
+ const upper = key.toUpperCase();
138
+ if (upper.startsWith("CLAUDE_CODE_")) return !CLAUDE_CODE_ENV_KEPT.includes(upper);
139
+ return CLAUDE_SESSION_ENV.includes(upper) || CODEX_SESSION_ENV.includes(upper);
140
+ }
141
+ function envValue(env, name) {
142
+ for (const [key, value] of Object.entries(env)) if (key.toUpperCase() === name) return value;
143
+ return void 0;
144
+ }
145
+ function brokeredDummies(env) {
146
+ const marker = envValue(env, "CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS");
147
+ const out = /* @__PURE__ */ new Set();
148
+ if (marker === void 0) return out;
149
+ let pairs;
150
+ try {
151
+ pairs = JSON.parse(marker);
152
+ } catch {
153
+ return out;
154
+ }
155
+ if (!Array.isArray(pairs)) return out;
156
+ for (const pair of pairs) {
157
+ if (!Array.isArray(pair) || typeof pair[0] !== "string" || typeof pair[1] !== "string") continue;
158
+ if (envValue(env, pair[0].toUpperCase()) === pair[1]) out.add(pair[0].toUpperCase());
159
+ }
160
+ return out;
161
+ }
162
+ function withoutParentSession(env) {
163
+ const proxyActive = envValue(env, "CODEX_NETWORK_PROXY_ACTIVE") !== void 0;
164
+ const dummies = brokeredDummies(env);
165
+ const copy = {};
166
+ for (const [key, value] of Object.entries(env)) {
167
+ const upper = key.toUpperCase();
168
+ if (isParentSessionEnv(key)) continue;
169
+ if (proxyActive && CODEX_MANAGED_PROXY_ENV.includes(upper)) continue;
170
+ if (proxyActive && value !== void 0 && CODEX_CA_ENV_KEYS.includes(upper) && isManagedCaBundle(value)) continue;
171
+ if (value !== void 0 && upper === "GIT_SSH_COMMAND" && value.startsWith(CODEX_PROXY_GIT_SSH_MARKER)) continue;
172
+ if (dummies.has(upper)) continue;
173
+ copy[key] = value;
174
+ }
175
+ return copy;
176
+ }
34
177
  function withoutInheritedKey(env) {
35
178
  const copy = { ...env };
36
179
  delete copy["AGENTCHAT_API_KEY"];
@@ -42,8 +185,15 @@ var CLAUDE_CODE_PRESET = "claude-code";
42
185
  var MIN_CLAUDE_CODE_VERSION = "2.1.274";
43
186
  var CLAUDE_MCP_SERVER_NAME = "agentchat";
44
187
  var AGENTCHAT_TOOL_ALLOW = `mcp__${CLAUDE_MCP_SERVER_NAME}__*`;
45
- var ANSWER_TOOLS = ["Read", "Glob", "Grep", "WebSearch", "WebFetch"];
188
+ var ANSWER_TOOLS = ["Read", "Glob", "Grep"];
189
+ var WEB_TOOLS = ["WebSearch", "WebFetch"];
46
190
  var WORK_TOOLS = ["Bash", "Edit", "Write", "MultiEdit", "NotebookEdit"];
191
+ var ANSWER_DENIED_TOOLS = ["WebFetch", "WebSearch", "Bash"];
192
+ var ANSWER_SETTINGS = JSON.stringify({
193
+ permissions: { blockReadsOutsideWorkingDirectories: true },
194
+ env: { CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" },
195
+ disableAllHooks: true
196
+ });
47
197
  var PARENT_ENV_KEYS = [
48
198
  "CLAUDECODE",
49
199
  "CLAUDE_CODE_CHILD_SESSION",
@@ -52,7 +202,11 @@ var PARENT_ENV_KEYS = [
52
202
  "CLAUDE_CODE_EXECPATH",
53
203
  "CLAUDE_CODE_EFFORT_LEVEL",
54
204
  "CLAUDE_EFFORT",
55
- "AI_AGENT"
205
+ "AI_AGENT",
206
+ "CLAUDE_CODE_MESSAGING_SOCKET",
207
+ "CLAUDE_CODE_MESSAGING_TOKEN",
208
+ "CLAUDE_CODE_SESSION_ATTENDED",
209
+ "CLAUDE_PID"
56
210
  ];
57
211
  var MCP_STARTUP_WAIT_MS = "15000";
58
212
  function claudeConfigDirFrom(env = process.env) {
@@ -62,6 +216,9 @@ function claudeConfigDirFrom(env = process.env) {
62
216
  function claudeHomeFor(configDirOverride) {
63
217
  return configDirOverride ?? path.join(os.homedir(), ".claude");
64
218
  }
219
+ function claudeProjectsDirFor(configDirOverride) {
220
+ return path.join(claudeHomeFor(configDirOverride), "projects");
221
+ }
65
222
  function claudeUserStatePathFor(configDirOverride) {
66
223
  return configDirOverride !== void 0 ? path.join(configDirOverride, ".claude.json") : path.join(os.homedir(), ".claude.json");
67
224
  }
@@ -72,46 +229,40 @@ function claudeProcessEnv(configDirOverride, source) {
72
229
  return env;
73
230
  }
74
231
  function buildClaudeEnv(configDirOverride, source = process.env) {
75
- const env = claudeProcessEnv(configDirOverride, source);
76
- for (const key of PARENT_ENV_KEYS) delete env[key];
232
+ const env = claudeProcessEnv(configDirOverride, withoutParentSession(source));
77
233
  env["DISABLE_AUTOUPDATER"] = "1";
78
234
  const wait = Number(env["CLAUDE_CODE_MCP_STARTUP_WAIT_MS"]);
79
235
  if (!Number.isFinite(wait) || wait < Number(MCP_STARTUP_WAIT_MS)) env["CLAUDE_CODE_MCP_STARTUP_WAIT_MS"] = MCP_STARTUP_WAIT_MS;
80
236
  return env;
81
237
  }
82
- function claudeIsLoggedIn(configDirOverride, command = "claude") {
83
- const status = spawnCommandSync(command, ["auth", "status"], {
84
- encoding: "utf-8",
85
- timeout: 1e4,
86
- windowsHide: true,
87
- env: claudeProcessEnv(configDirOverride, process.env)
88
- });
238
+ var PROBE_TIMEOUT_MS = 1e4;
239
+ async function claudeSignIn(configDirOverride, command = "claude", timeoutMs = PROBE_TIMEOUT_MS, signal) {
240
+ const status = await runProbe(command, ["auth", "status"], { timeoutMs, env: claudeProcessEnv(configDirOverride, process.env), ...signal !== void 0 ? { signal } : {} });
241
+ if (status.timedOut) return { signedIn: false, unanswered: `claude auth status did not answer within ${Math.round(timeoutMs / 1e3)} s (killed)` };
242
+ if (signal?.aborted) return { signedIn: false, unanswered: "claude auth status was stopped" };
89
243
  if (!status.error) {
90
244
  try {
91
- const parsed = JSON.parse(String(status.stdout ?? "").trim());
92
- if (typeof parsed?.loggedIn === "boolean") return parsed.loggedIn;
245
+ const parsed = JSON.parse(status.stdout.trim());
246
+ if (typeof parsed?.loggedIn === "boolean") return { signedIn: parsed.loggedIn, unanswered: null };
93
247
  } catch {
94
248
  }
95
- if (status.status === 0) return true;
249
+ if (status.status === 0) return { signedIn: true, unanswered: null };
96
250
  }
97
251
  const configDir = claudeHomeFor(configDirOverride);
98
- if (fs.existsSync(path.join(configDir, ".credentials.json"))) return true;
99
- if (process.platform !== "darwin") return false;
100
- const keychain = spawnCommandSync("security", ["find-generic-password", "-s", "Claude Code-credentials"], {
101
- encoding: "utf-8",
102
- timeout: 5e3
103
- });
104
- return !keychain.error && keychain.status === 0;
105
- }
106
- function inspectClaudeRuntime(configDirOverride, command = "claude") {
107
- const version = spawnCommandSync(command, ["--version"], {
108
- encoding: "utf-8",
109
- timeout: 1e4,
110
- windowsHide: true,
111
- env: claudeProcessEnv(configDirOverride, process.env)
112
- });
252
+ if (fs.existsSync(path.join(configDir, ".credentials.json"))) return { signedIn: true, unanswered: null };
253
+ if (process.platform !== "darwin") return { signedIn: false, unanswered: null };
254
+ const keychain = await runProbe("security", ["find-generic-password", "-s", "Claude Code-credentials"], { timeoutMs: Math.min(timeoutMs, 5e3), ...signal !== void 0 ? { signal } : {} });
255
+ return { signedIn: !keychain.error && keychain.status === 0, unanswered: null };
256
+ }
257
+ async function claudeIsLoggedIn(configDirOverride, command = "claude", timeoutMs = PROBE_TIMEOUT_MS) {
258
+ return (await claudeSignIn(configDirOverride, command, timeoutMs)).signedIn;
259
+ }
260
+ async function inspectClaudeRuntime(configDirOverride, command = "claude", timeoutMs = PROBE_TIMEOUT_MS, signal) {
261
+ const version = await runProbe(command, ["--version"], { timeoutMs, env: claudeProcessEnv(configDirOverride, process.env), ...signal !== void 0 ? { signal } : {} });
262
+ if (version.timedOut) return { ok: false, detail: `claude --version did not answer within ${Math.round(timeoutMs / 1e3)} s (killed)` };
263
+ if (signal?.aborted) return { ok: false, detail: "claude --version was stopped" };
113
264
  if (version.error) return { ok: false, detail: `claude CLI not found on PATH (${version.error.message})` };
114
- const rendered = String(version.stdout || version.stderr).trim();
265
+ const rendered = (version.stdout || version.stderr).trim();
115
266
  if (version.status !== 0) return { ok: false, detail: rendered || `claude --version exited ${version.status}` };
116
267
  return semverAtLeast(rendered, MIN_CLAUDE_CODE_VERSION) ? { ok: true, detail: rendered } : {
117
268
  ok: false,
@@ -126,7 +277,29 @@ function deniedAncestorOf(dir, denied) {
126
277
  }
127
278
  return null;
128
279
  }
129
- function claudeProfileArgs(profile) {
280
+ function expressibleAllow(raw) {
281
+ return expressible(raw) && !/[*?[\]\\!#]/.test(raw);
282
+ }
283
+ function workdirPaths(workdir) {
284
+ const given = path.resolve(workdir);
285
+ let real = given;
286
+ try {
287
+ real = fs.realpathSync(given);
288
+ } catch {
289
+ }
290
+ return real === given ? [given] : [given, real];
291
+ }
292
+ function workdirReadRules(workdir) {
293
+ if (workdir === void 0 || process.platform === "win32") return [];
294
+ const rules = [];
295
+ for (const raw of workdirPaths(workdir)) {
296
+ const clean = raw.replace(/\/+$/, "");
297
+ if (!expressibleAllow(raw) || clean.length === 0) continue;
298
+ rules.push(`Read(/${clean})`, `Read(/${clean}/**)`);
299
+ }
300
+ return rules;
301
+ }
302
+ function claudeProfileArgs(profile, workdir) {
130
303
  switch (profile) {
131
304
  case "answer":
132
305
  return [
@@ -137,8 +310,12 @@ function claudeProfileArgs(profile) {
137
310
  "--tools",
138
311
  ANSWER_TOOLS.join(","),
139
312
  "--allowedTools",
140
- [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS].join(",")
313
+ [AGENTCHAT_TOOL_ALLOW, ...workdirReadRules(workdir)].join(","),
314
+ "--settings",
315
+ ANSWER_SETTINGS
141
316
  ];
317
+ // `work` and `full` are the operator's explicit opt-in: a run started by
318
+ // any peer's message can then read and change this machine.
142
319
  case "work":
143
320
  return [
144
321
  "--permission-mode",
@@ -146,7 +323,7 @@ function claudeProfileArgs(profile) {
146
323
  "--permission-prompts",
147
324
  "none",
148
325
  "--allowedTools",
149
- [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WORK_TOOLS].join(",")
326
+ [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WEB_TOOLS, ...WORK_TOOLS].join(",")
150
327
  ];
151
328
  case "full":
152
329
  return ["--dangerously-skip-permissions", "--permission-prompts", "none", "--allowedTools", AGENTCHAT_TOOL_ALLOW];
@@ -170,7 +347,7 @@ function readDenyRules(paths) {
170
347
  }
171
348
  function claudeRunArgs(profile, options = {}) {
172
349
  const budget = options.maxBudgetUsd?.trim();
173
- const deny = readDenyRules(options.denyReadPaths ?? []);
350
+ const deny = [...profile === "answer" ? ANSWER_DENIED_TOOLS : [], ...readDenyRules(options.denyReadPaths ?? [])];
174
351
  return [
175
352
  "-p",
176
353
  "--output-format",
@@ -181,21 +358,82 @@ function claudeRunArgs(profile, options = {}) {
181
358
  ...budget !== void 0 && /^\d+(\.\d+)?$/.test(budget) ? ["--max-budget-usd", budget] : [],
182
359
  // Variadic, so it is closed by the boolean flag right after it.
183
360
  ...options.mcpConfigPath !== void 0 ? ["--mcp-config", options.mcpConfigPath, "--strict-mcp-config"] : [],
184
- ...claudeProfileArgs(profile),
361
+ ...options.appendSystemPromptFile !== void 0 ? ["--append-system-prompt-file", options.appendSystemPromptFile] : [],
362
+ ...claudeProfileArgs(profile, options.workdir),
185
363
  // Last: the option is variadic and the prompt arrives on stdin, so there
186
364
  // is no positional for it to swallow.
187
365
  ...deny.length > 0 ? ["--disallowedTools", deny.join(",")] : []
188
366
  ];
189
367
  }
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
- )}
368
+ function claudeMcpConfig(apiBase, apiKey, clientVersion = VERSION) {
369
+ const headers = { Authorization: `Bearer ${apiKey}`, ...clientHeadersOf({ runtime: "claude-code", version: clientVersion }) };
370
+ return `${JSON.stringify({ mcpServers: { [CLAUDE_MCP_SERVER_NAME]: { type: "http", url: hostedMcpUrl(apiBase), headers } } }, null, 2)}
196
371
  `;
197
372
  }
198
- var ClaudeRunner = class {
373
+ var ANSWER_ENV = Object.freeze({
374
+ CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1",
375
+ CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1"
376
+ });
377
+ function claudeManagedSettingsDir(platform = process.platform) {
378
+ if (platform === "darwin") return "/Library/Application Support/ClaudeCode";
379
+ if (platform === "win32") return "C:\\Program Files\\ClaudeCode";
380
+ return "/etc/claude-code";
381
+ }
382
+ function gitRootOf(dir) {
383
+ let current = path.resolve(dir);
384
+ for (; ; ) {
385
+ if (fs.existsSync(path.join(current, ".git"))) return current;
386
+ const parent = path.dirname(current);
387
+ if (parent === current) return null;
388
+ current = parent;
389
+ }
390
+ }
391
+ function claudeSettingsFilesGrantingDirectories(configDirOverride, workdir) {
392
+ const managed = claudeManagedSettingsDir();
393
+ const dropIns = (() => {
394
+ try {
395
+ return fs.readdirSync(path.join(managed, "managed-settings.d")).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => path.join(managed, "managed-settings.d", name));
396
+ } catch {
397
+ return [];
398
+ }
399
+ })();
400
+ const cwdLocal = path.join(path.resolve(workdir), ".claude", "settings.local.json");
401
+ const root = gitRootOf(workdir);
402
+ const rootLocal = root !== null ? path.join(root, ".claude", "settings.local.json") : cwdLocal;
403
+ return [
404
+ path.join(claudeHomeFor(configDirOverride), "settings.json"),
405
+ path.join(managed, "managed-settings.json"),
406
+ ...dropIns,
407
+ .../* @__PURE__ */ new Set([rootLocal, cwdLocal])
408
+ ];
409
+ }
410
+ function claudeExtraDirectoriesGrant(configDirOverride, workdir) {
411
+ for (const file of claudeSettingsFilesGrantingDirectories(configDirOverride, workdir)) {
412
+ let text;
413
+ try {
414
+ text = fs.readFileSync(file, "utf-8");
415
+ } catch {
416
+ continue;
417
+ }
418
+ let parsed;
419
+ try {
420
+ parsed = JSON.parse(text);
421
+ } catch {
422
+ if (text.includes("additionalDirectories")) return { file, detail: "names permissions.additionalDirectories and is not valid JSON" };
423
+ continue;
424
+ }
425
+ const dirs = parsed?.permissions?.additionalDirectories;
426
+ if (Array.isArray(dirs) && dirs.length > 0) return { file, detail: `lists permissions.additionalDirectories (${dirs.length} folder${dirs.length === 1 ? "" : "s"})` };
427
+ }
428
+ return null;
429
+ }
430
+ function extraDirectoriesRefusal(grant) {
431
+ return `answer runs do not start while ${grant.file} ${grant.detail}: Claude Code counts those as working directories, so a run started by a peer's message could read them. Remove the key from that file (your own sessions can use --add-dir instead).`;
432
+ }
433
+ function claudeAnswerFallbackWorkdir(configDirOverride) {
434
+ return path.join(claudeHomeFor(configDirOverride), "agentchat-answer-workdir");
435
+ }
436
+ var ClaudeRunner = class _ClaudeRunner {
199
437
  constructor(options) {
200
438
  this.options = options;
201
439
  this.command = options.command ?? "claude";
@@ -206,24 +444,51 @@ var ClaudeRunner = class {
206
444
  /** The workdir warning is one line per process, not one per preflight (preflight repeats every few minutes). */
207
445
  warnedWorkdir = false;
208
446
  warnedDeny = false;
209
- /** The denied path the configured workdir sits in, or null when the run can read its own cwd. */
447
+ warnedHome = false;
448
+ /**
449
+ * Where this runner's runs work: the configured workdir, except that an
450
+ * `answer` run never works in the home folder or above it — it gets
451
+ * `claudeAnswerFallbackWorkdir` (its readable folder would be the whole home).
452
+ */
453
+ workdir() {
454
+ if (this.options.profile === "answer" && workdirExposesHome(this.options.workdir)) return claudeAnswerFallbackWorkdir(this.options.configDir);
455
+ return this.options.workdir;
456
+ }
457
+ /** The denied path the workdir sits in, or null when the run can read its own cwd. */
210
458
  workdirDeniedBy() {
211
- return deniedAncestorOf(this.options.workdir, this.options.denyReadPaths);
459
+ return deniedAncestorOf(this.workdir(), this.options.denyReadPaths);
212
460
  }
213
- async preflight() {
214
- const runtime = inspectClaudeRuntime(this.options.configDir, this.command);
461
+ async preflight(options = {}) {
462
+ const runtime = await inspectClaudeRuntime(this.options.configDir, this.command, PROBE_TIMEOUT_MS, options.signal);
215
463
  if (!runtime.ok) return { ok: false, detail: runtime.detail };
216
- if (!claudeIsLoggedIn(this.options.configDir, this.command)) {
217
- return { ok: false, detail: "claude is not signed in (run `claude` once and sign in)" };
464
+ const signIn = await claudeSignIn(this.options.configDir, this.command, PROBE_TIMEOUT_MS, options.signal);
465
+ if (signIn.unanswered !== null) return { ok: false, detail: signIn.unanswered };
466
+ if (!signIn.signedIn) return { ok: false, detail: "claude is not signed in (run `claude` once and sign in)" };
467
+ if (this.options.profile === "answer" && this.options.mcpConfigPath === void 0) {
468
+ const answerMcp = this.options.answerMcp;
469
+ if (answerMcp === void 0) {
470
+ return { ok: false, detail: "an answer run needs the AgentChat-only tool config (ClaudeRunnerOptions.answerMcp): without it the run would load every MCP server the user registered" };
471
+ }
472
+ if (deniedAncestorOf(answerMcp.file, this.options.denyReadPaths) === null) {
473
+ return { ok: false, detail: `the answer runs' tool config ${answerMcp.file} holds the key and must sit inside a path the runs are denied (${this.options.denyReadPaths.join(", ")})` };
474
+ }
475
+ }
476
+ if (this.options.profile === "answer") {
477
+ const grant = claudeExtraDirectoriesGrant(this.options.configDir, this.workdir());
478
+ if (grant !== null) return { ok: false, detail: extraDirectoriesRefusal(grant) };
479
+ }
480
+ if (this.workdir() !== this.options.workdir && !this.warnedHome) {
481
+ this.warnedHome = true;
482
+ log.warn(`the run workdir ${this.options.workdir} is your home folder or contains it: answer runs work in ${this.workdir()} instead, so a peer-started run reads none of your files there. Point the workdir at a folder of its own to choose another.`);
218
483
  }
219
484
  const denied = this.workdirDeniedBy();
220
485
  if (denied !== null && !this.warnedWorkdir) {
221
486
  this.warnedWorkdir = true;
222
487
  log.warn(
223
- `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}` : ""}`
488
+ `the run workdir ${this.workdir()} is inside ${denied}, which every run's file tools are denied: runs cannot read their own working directory.${this.options.workdirAdvice ? ` ${this.options.workdirAdvice}` : ""}`
224
489
  );
225
490
  }
226
- const uncovered = inexpressibleDenyPaths(this.options.denyReadPaths);
491
+ const uncovered = inexpressibleDenyPaths(this.readDenyPaths());
227
492
  if (uncovered.length > 0) {
228
493
  const why = process.platform === "win32" ? `Claude Code's rule syntax for Windows paths is undocumented, so no read-deny rule is given for ${uncovered.join(", ")}` : `no read-deny rule can carry ${uncovered.join(", ")} (a comma or whitespace in the path)`;
229
494
  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).` };
@@ -235,33 +500,120 @@ var ClaudeRunner = class {
235
500
  if (this.options.mcpConfigPath !== void 0 && !fs.existsSync(this.options.mcpConfigPath)) {
236
501
  return { ok: false, detail: `the hosted tool config ${this.options.mcpConfigPath} is missing` };
237
502
  }
238
- fs.mkdirSync(this.options.workdir, { recursive: true, mode: 448 });
503
+ fs.mkdirSync(this.workdir(), { recursive: true, mode: 448 });
239
504
  return { ok: true };
240
505
  }
241
- /** The exact argv one run uses — exported for tests to pin per profile. */
242
- args() {
506
+ /** `<dir>/<stem>.<run id><ext>`: a file of this run's own beside `file` (the run id reduced to letters, digits and `-`). */
507
+ static perRun(file, runId, ext) {
508
+ const stem = path.basename(file, path.extname(file));
509
+ const id = runId.replace(/[^A-Za-z0-9-]/g, "").slice(0, 64) || "run";
510
+ return path.join(path.dirname(file), `${stem}.${id}${ext}`);
511
+ }
512
+ /** The answer run's own files for `runId`: its AgentChat-only tool config (integration path) and its identity-line file. */
513
+ answerRunFiles(runId) {
514
+ if (this.options.profile !== "answer") return {};
515
+ const base = this.options.mcpConfigPath ?? this.options.answerMcp?.file;
516
+ return {
517
+ ...this.options.mcpConfigPath === void 0 && this.options.answerMcp !== void 0 ? { mcpConfigPath: _ClaudeRunner.perRun(this.options.answerMcp.file, runId, ".json") } : {},
518
+ ...base !== void 0 ? { identityFile: _ClaudeRunner.perRun(base, runId, ".identity.md") } : {}
519
+ };
520
+ }
521
+ /**
522
+ * What this runner's runs are denied reading: the key store, and for an
523
+ * `answer` run also Claude Code's own record of every project
524
+ * (`<config dir>/projects`: transcripts and auto memory). Claude Code lets a
525
+ * run read its project's memory folder even with auto memory off and reads
526
+ * blocked outside the working directories (seen on 2.1.322); a deny rule
527
+ * wins over that.
528
+ */
529
+ readDenyPaths() {
530
+ return this.options.profile === "answer" ? [...this.options.denyReadPaths, claudeProjectsDirFor(this.options.configDir)] : [...this.options.denyReadPaths];
531
+ }
532
+ argsFor(mcpConfigPath, appendSystemPromptFile) {
243
533
  return claudeRunArgs(this.options.profile, {
244
534
  maxBudgetUsd: (this.options.env ?? process.env)["AGENTCHAT_RUN_MAX_BUDGET_USD"],
245
- denyReadPaths: this.options.denyReadPaths,
246
- mcpConfigPath: this.options.mcpConfigPath
535
+ workdir: this.workdir(),
536
+ denyReadPaths: this.readDenyPaths(),
537
+ ...mcpConfigPath !== void 0 ? { mcpConfigPath } : {},
538
+ ...appendSystemPromptFile !== void 0 ? { appendSystemPromptFile } : {}
247
539
  });
248
540
  }
541
+ /**
542
+ * The argv of a run — exported for tests to pin per profile. With a `runId`,
543
+ * that run's own files (an answer run's tool config and identity-line file);
544
+ * without, the configured `answerMcp.file` stands in and no identity file.
545
+ */
546
+ args(runId, identityLine) {
547
+ if (runId === void 0) {
548
+ const mcpConfigPath = this.options.mcpConfigPath ?? (this.options.profile === "answer" ? this.options.answerMcp?.file : void 0);
549
+ return this.argsFor(mcpConfigPath, void 0);
550
+ }
551
+ const files = this.answerRunFiles(runId);
552
+ return this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityLine === true ? files.identityFile : void 0);
553
+ }
554
+ /** The run's environment: no parent session; an answer run loads no CLAUDE.md and no auto memory (`ANSWER_ENV`). */
555
+ runEnv() {
556
+ const env = buildClaudeEnv(this.options.configDir, this.options.env ?? process.env);
557
+ return this.options.profile === "answer" ? { ...env, ...ANSWER_ENV } : env;
558
+ }
249
559
  async start(request) {
250
- const args = this.args();
251
- log.debug(`claude ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
252
- return spawnRun({
253
- command: this.command,
254
- args,
255
- cwd: this.options.workdir,
256
- env: buildClaudeEnv(this.options.configDir, this.options.env ?? process.env),
257
- stdin: request.prompt,
258
- budgetMs: request.budgetMs,
259
- // Stopping SIGTERMs this run's process group instead of orphaning it.
260
- ...request.signal ? { signal: request.signal } : {},
261
- // The engine records a group invite as offered the moment the process
262
- // has spawned, so a run cut short still counts as the one offer.
263
- ...request.onStarted ? { onStarted: request.onStarted } : {}
264
- });
560
+ const startedAt = Date.now();
561
+ const notStarted = (detail) => ({ state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail });
562
+ const answer = this.options.profile === "answer";
563
+ const answerMcp = answer && this.options.mcpConfigPath === void 0 ? this.options.answerMcp : void 0;
564
+ if (answer && this.options.mcpConfigPath === void 0 && answerMcp === void 0) {
565
+ return notStarted("an answer run needs the AgentChat-only tool config (ClaudeRunnerOptions.answerMcp)");
566
+ }
567
+ if (answer) {
568
+ const grant = claudeExtraDirectoriesGrant(this.options.configDir, this.workdir());
569
+ if (grant !== null) return notStarted(extraDirectoriesRefusal(grant));
570
+ }
571
+ const files = this.answerRunFiles(request.runId);
572
+ const identityFile = answer && request.identityLine !== void 0 ? files.identityFile : void 0;
573
+ const written = [];
574
+ const cleanup = () => {
575
+ for (const file of written) fs.rmSync(file, { force: true });
576
+ };
577
+ if (answerMcp !== void 0 && files.mcpConfigPath !== void 0) {
578
+ const key = answerMcp.apiKey();
579
+ if (key === null) return notStarted("no AgentChat key for the answer run's tool config");
580
+ try {
581
+ atomicWriteFile(files.mcpConfigPath, claudeMcpConfig(answerMcp.apiBase, key, answerMcp.clientVersion ?? VERSION), 384);
582
+ written.push(files.mcpConfigPath);
583
+ } catch (err) {
584
+ cleanup();
585
+ return notStarted(`could not write the answer run's tool config ${files.mcpConfigPath}: ${err instanceof Error ? err.message : String(err)}`);
586
+ }
587
+ }
588
+ if (identityFile !== void 0 && request.identityLine !== void 0) {
589
+ try {
590
+ atomicWriteFile(identityFile, `${request.identityLine.trim()}
591
+ `, 384);
592
+ written.push(identityFile);
593
+ } catch (err) {
594
+ cleanup();
595
+ return notStarted(`could not write the answer run's identity line ${identityFile}: ${err instanceof Error ? err.message : String(err)}`);
596
+ }
597
+ }
598
+ try {
599
+ const args = this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityFile);
600
+ log.debug(`claude ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
601
+ return await spawnRun({
602
+ command: this.command,
603
+ args,
604
+ cwd: this.workdir(),
605
+ env: this.runEnv(),
606
+ stdin: request.prompt,
607
+ budgetMs: request.budgetMs,
608
+ // Stopping SIGTERMs this run's process group instead of orphaning it.
609
+ ...request.signal ? { signal: request.signal } : {},
610
+ // The engine records a group invite as offered the moment the process
611
+ // has spawned, so a run cut short still counts as the one offer.
612
+ ...request.onStarted ? { onStarted: request.onStarted } : {}
613
+ });
614
+ } finally {
615
+ cleanup();
616
+ }
265
617
  }
266
618
  };
267
619
  function claudeMcpConfigPath(home) {
@@ -271,7 +623,7 @@ var claudeCodePreset = {
271
623
  name: CLAUDE_CODE_PRESET,
272
624
  describeMcp({ home, apiBase }) {
273
625
  return [
274
- `--mcp-config ${claudeMcpConfigPath(home)} (owner-only): ${CLAUDE_MCP_SERVER_NAME} \u2192 ${hostedMcpUrl(apiBase)}, Authorization: Bearer <this home's key>`,
626
+ `--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
627
  "--strict-mcp-config: no other MCP server (user, project or plugin) is loaded in these runs"
276
628
  ];
277
629
  },
@@ -280,17 +632,19 @@ var claudeCodePreset = {
280
632
  // Every run's file tools are denied the identity home.
281
633
  serviceEnv: ["CLAUDE_CONFIG_DIR"],
282
634
  readsIdentityHome: false,
283
- inspect(env = process.env, command = "claude") {
635
+ async inspect(env = process.env, command = "claude") {
284
636
  const configDir = claudeConfigDirFrom(env);
285
- const runtime = inspectClaudeRuntime(configDir, command);
637
+ const runtime = await inspectClaudeRuntime(configDir, command);
286
638
  if (!runtime.ok) return runtime;
287
- return claudeIsLoggedIn(configDir, command) ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in (run \`claude\` once and sign in)` };
639
+ const signIn = await claudeSignIn(configDir, command);
640
+ if (signIn.unanswered !== null) return { ok: false, detail: `${runtime.detail}, ${signIn.unanswered}` };
641
+ return signIn.signedIn ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in (run \`claude\` once and sign in)` };
288
642
  },
289
643
  runner(ctx) {
290
644
  const env = withoutInheritedKey(ctx.env ?? process.env);
291
645
  const configDir = claudeConfigDirFrom(env);
292
646
  const mcpConfigPath = claudeMcpConfigPath(ctx.home);
293
- atomicWriteFile(mcpConfigPath, claudeMcpConfig(ctx.apiBase, ctx.apiKey), 384);
647
+ atomicWriteFile(mcpConfigPath, claudeMcpConfig(ctx.apiBase, ctx.apiKey, ctx.clientVersion ?? VERSION), 384);
294
648
  return new ClaudeRunner({
295
649
  configDir,
296
650
  workdir: ctx.workdir,
@@ -323,39 +677,70 @@ function codexHomeFrom(env = process.env) {
323
677
  if (override !== void 0 && override.trim().length > 0) return path2.resolve(override);
324
678
  return path2.join(os2.homedir(), ".codex");
325
679
  }
326
- function inspectCodexRuntime(codexHome, command = "codex") {
327
- const result = spawnCommandSync(command, ["--version"], {
328
- encoding: "utf-8",
329
- timeout: 1e4,
330
- windowsHide: true,
331
- env: { ...process.env, CODEX_HOME: codexHome }
332
- });
680
+ var CODEX_PROBE_TIMEOUT_MS = 1e4;
681
+ async function inspectCodexRuntime(codexHome, command = "codex", timeoutMs = CODEX_PROBE_TIMEOUT_MS, signal) {
682
+ const result = await runProbe(command, ["--version"], { timeoutMs, env: { ...process.env, CODEX_HOME: codexHome }, ...signal !== void 0 ? { signal } : {} });
683
+ if (result.timedOut) return { ok: false, detail: `codex --version did not answer within ${Math.round(timeoutMs / 1e3)} s (killed)` };
684
+ if (signal?.aborted) return { ok: false, detail: "codex --version was stopped" };
333
685
  if (result.error) return { ok: false, detail: `codex CLI not found on PATH (${result.error.message})` };
334
- const rendered = String(result.stdout || result.stderr).trim();
686
+ const rendered = (result.stdout || result.stderr).trim();
335
687
  if (result.status !== 0) return { ok: false, detail: rendered || `codex --version exited ${result.status}` };
336
688
  return semverAtLeast(rendered, MIN_CODEX_VERSION) ? { ok: true, detail: rendered } : { ok: false, detail: `${rendered || "unrecognized version"}; AgentChat requires Codex >= ${MIN_CODEX_VERSION}` };
337
689
  }
338
- function codexIsLoggedIn(codexHome, command = "codex") {
339
- const status = spawnCommandSync(command, ["login", "status"], {
340
- encoding: "utf-8",
341
- timeout: 1e4,
342
- windowsHide: true,
343
- env: { ...process.env, CODEX_HOME: codexHome }
344
- });
690
+ async function codexIsLoggedIn(codexHome, command = "codex", timeoutMs = CODEX_PROBE_TIMEOUT_MS, signal) {
691
+ const status = await runProbe(command, ["login", "status"], { timeoutMs, env: { ...process.env, CODEX_HOME: codexHome }, ...signal !== void 0 ? { signal } : {} });
345
692
  if (status.error) return { ok: false, detail: status.error.message };
346
- const detail = `${status.stdout ?? ""}${status.stderr ?? ""}`.trim().slice(0, 200);
693
+ const detail = `${status.stdout}${status.stderr}`.trim().slice(0, 200);
347
694
  return status.status === 0 ? { ok: true, detail: detail || "signed in" } : { ok: false, detail: detail || "codex is not signed in (run `codex login`)" };
348
695
  }
696
+ var CODEX_ANSWER_PERMISSIONS = "agentchat_answer";
697
+ var CODEX_ANSWER_FILESYSTEM = '{ ":workspace_roots" = "read" }';
698
+ var CODEX_ANSWER_DISABLED_FEATURES = [
699
+ "shell_tool",
700
+ "view_image",
701
+ "image_generation",
702
+ "plugins",
703
+ "apps",
704
+ "memories",
705
+ "browser_use",
706
+ "browser_use_external",
707
+ "computer_use",
708
+ "in_app_browser"
709
+ ];
349
710
  function codexProfileArgs(profile) {
350
711
  switch (profile) {
351
712
  case "answer":
352
- return ["--sandbox", "read-only", "-c", 'approval_policy="never"'];
713
+ return [
714
+ "-c",
715
+ 'approval_policy="never"',
716
+ "-c",
717
+ `default_permissions="${CODEX_ANSWER_PERMISSIONS}"`,
718
+ "-c",
719
+ `permissions.${CODEX_ANSWER_PERMISSIONS}.filesystem=${CODEX_ANSWER_FILESYSTEM}`,
720
+ "-c",
721
+ 'web_search="disabled"',
722
+ // No project or ancestor AGENTS.md (core/src/agents_md.rs:65-67, 129: a
723
+ // zero budget reads none). $CODEX_HOME/AGENTS.md has no such switch in
724
+ // 0.154.0 (codex-home/src/instructions/mod.rs, wired unconditionally).
725
+ "-c",
726
+ "project_doc_max_bytes=0",
727
+ ...CODEX_ANSWER_DISABLED_FEATURES.flatMap((feature) => ["--disable", feature])
728
+ ];
729
+ // `work` and `full` are the operator's explicit opt-in: a run started by
730
+ // any peer's message can then read and change this machine.
353
731
  case "work":
354
732
  return ["--sandbox", "workspace-write", "-c", 'approval_policy="never"'];
355
733
  case "full":
356
734
  return ["--dangerously-bypass-approvals-and-sandbox"];
357
735
  }
358
736
  }
737
+ function codexClientHeadersToml(clientVersion = VERSION) {
738
+ const pairs = Object.entries(clientHeadersOf({ runtime: "codex", version: clientVersion })).map(([name, value]) => `${JSON.stringify(name)} = ${JSON.stringify(value)}`);
739
+ return `{ ${pairs.join(", ")} }`;
740
+ }
741
+ function codexPinnedUrlArgs(url) {
742
+ return ["-c", `mcp_servers.${CODEX_MCP_SERVER_NAME}.url=${JSON.stringify(url)}`];
743
+ }
359
744
  function codexMcpOverrideArgs(override) {
360
745
  const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`;
361
746
  return [
@@ -364,7 +749,9 @@ function codexMcpOverrideArgs(override) {
364
749
  "-c",
365
750
  `${table}.bearer_token_env_var=${JSON.stringify(override.keyEnv)}`,
366
751
  "-c",
367
- `${table}.default_tools_approval_mode="approve"`
752
+ `${table}.default_tools_approval_mode="approve"`,
753
+ "-c",
754
+ `${table}.http_headers=${codexClientHeadersToml(override.clientVersion ?? VERSION)}`
368
755
  ];
369
756
  }
370
757
  function codexRunArgs(profile, options) {
@@ -380,6 +767,81 @@ function codexRunArgs(profile, options) {
380
767
  CODEX_PROMPT_FROM_STDIN
381
768
  ];
382
769
  }
770
+ function codexAnswerFallbackWorkdir(codexHome) {
771
+ return path2.join(codexHome, "agentchat-answer-workdir");
772
+ }
773
+ var CODEX_MCP_LIST_TIMEOUT_MS = 2e4;
774
+ var CODEX_MCP_LIST_KILL_WAIT_MS = 1e4;
775
+ var CODEX_MCP_LIST_MAX_BYTES = 1024 * 1024;
776
+ function codexServerNameAddressable(name) {
777
+ return /^[A-Za-z0-9_:@/-]+$/.test(name);
778
+ }
779
+ function parseCodexMcpList(stdout) {
780
+ let parsed;
781
+ try {
782
+ parsed = JSON.parse(stdout);
783
+ } catch {
784
+ return { ok: false, detail: "its output is not JSON" };
785
+ }
786
+ if (!Array.isArray(parsed)) return { ok: false, detail: "its output is not a list" };
787
+ const names = [];
788
+ for (const entry of parsed) {
789
+ const name = entry?.name;
790
+ const enabled = entry?.enabled;
791
+ if (typeof name !== "string" || name.length === 0) return { ok: false, detail: "an entry has no name" };
792
+ if (enabled !== false) names.push(name);
793
+ }
794
+ return { ok: true, names };
795
+ }
796
+ function codexMcpDisableArgs(names) {
797
+ const args = [];
798
+ for (const name of names) {
799
+ if (name === CODEX_MCP_SERVER_NAME) continue;
800
+ if (!codexServerNameAddressable(name)) {
801
+ return { ok: false, detail: `the MCP server "${name}" cannot be switched off for one run (Codex reads a "." in a -c key as a table); rename it or remove it` };
802
+ }
803
+ args.push("-c", `mcp_servers.${name}.enabled=false`);
804
+ }
805
+ return { ok: true, args };
806
+ }
807
+ function codexAnswerListingRefusal(detail) {
808
+ return `could not list Codex's MCP servers (\`codex mcp list --json\` with the answer flags: ${detail}); an answer run starts only with every server but ${CODEX_MCP_SERVER_NAME} switched off`;
809
+ }
810
+ var CODEX_MCP_LIST_MAX_AGE_MS = 60 * 6e4;
811
+ function codexConfigLayerFiles(codexHome, workdir, platform = process.platform, env = process.env) {
812
+ const p = platform === "win32" ? path2.win32 : path2.posix;
813
+ const programData = env["ProgramData"] ?? env["PROGRAMDATA"] ?? "C:\\ProgramData";
814
+ const system = platform === "win32" ? [p.join(programData, "OpenAI", "Codex", "config.toml"), p.join(programData, "OpenAI", "Codex", "requirements.toml")] : ["/etc/codex/config.toml", "/etc/codex/managed_config.toml", "/etc/codex/requirements.toml"];
815
+ const user = (() => {
816
+ try {
817
+ return os2.userInfo().username;
818
+ } catch {
819
+ return null;
820
+ }
821
+ })();
822
+ const managedPrefs = platform === "darwin" ? ["/Library/Managed Preferences/com.openai.codex.plist", ...user !== null ? [p.join("/Library/Managed Preferences", user, "com.openai.codex.plist")] : []] : [];
823
+ const tree = [];
824
+ let current = p.resolve(workdir);
825
+ tree.push(p.join(current, "config.toml"));
826
+ for (; ; ) {
827
+ tree.push(p.join(current, ".codex", "config.toml"));
828
+ const parent = p.dirname(current);
829
+ if (parent === current) break;
830
+ current = parent;
831
+ }
832
+ return [...system, ...managedPrefs, p.join(codexHome, "config.toml"), ...tree];
833
+ }
834
+ function codexListingKey(files, parts) {
835
+ const stats = files.map((file) => {
836
+ try {
837
+ const st = fs2.statSync(file);
838
+ return `${file}\0${st.size}\0${st.mtimeMs}`;
839
+ } catch {
840
+ return `${file}\0-`;
841
+ }
842
+ });
843
+ return [...parts, ...stats].join("");
844
+ }
383
845
  var CodexRunner = class {
384
846
  constructor(options) {
385
847
  this.options = options;
@@ -388,32 +850,138 @@ var CodexRunner = class {
388
850
  options;
389
851
  name = "codex";
390
852
  command;
391
- async preflight() {
392
- const runtime = inspectCodexRuntime(this.options.codexHome, this.command);
853
+ warnedHome = false;
854
+ /** The last good listing and what it depended on: a stranger's DM does not cost a listing (and its contacts to the user's MCP hosts) on every run. */
855
+ listing = null;
856
+ /**
857
+ * Where this runner's runs work (`-C`): the configured workdir, except that an
858
+ * `answer` run never has the home folder or above it as its workspace root —
859
+ * it gets `codexAnswerFallbackWorkdir`.
860
+ */
861
+ workdir() {
862
+ if (this.options.profile === "answer" && workdirExposesHome(this.options.workdir)) return codexAnswerFallbackWorkdir(this.options.codexHome);
863
+ return this.options.workdir;
864
+ }
865
+ async preflight(options = {}) {
866
+ const runtime = await inspectCodexRuntime(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal);
393
867
  if (!runtime.ok) return { ok: false, detail: runtime.detail };
394
- const auth = codexIsLoggedIn(this.options.codexHome, this.command);
868
+ const auth = await codexIsLoggedIn(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal);
395
869
  if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` };
396
- fs2.mkdirSync(this.options.workdir, { recursive: true });
870
+ if (this.workdir() !== this.options.workdir && !this.warnedHome) {
871
+ this.warnedHome = true;
872
+ log.warn(`the run workdir ${this.options.workdir} is your home folder or contains it: answer runs work in ${this.workdir()} instead, so a peer-started run reaches none of your files there. Point the workdir at a folder of its own to choose another.`);
873
+ }
874
+ fs2.mkdirSync(this.workdir(), { recursive: true });
875
+ if (this.options.profile === "answer") {
876
+ const disables = await this.answerMcpDisables();
877
+ if (!disables.ok) return { ok: false, detail: codexAnswerListingRefusal(disables.detail) };
878
+ }
397
879
  return { ok: true };
398
880
  }
399
- /** The exact argv one run uses — exported for tests to pin per profile. */
881
+ /** The exact argv one run uses — exported for tests to pin per profile. An `answer` run adds `answerMcpDisables()` before the prompt. */
400
882
  args() {
401
- return codexRunArgs(this.options.profile, { workdir: this.options.workdir, ...this.options.mcp !== void 0 ? { mcp: this.options.mcp } : {} });
883
+ const args = codexRunArgs(this.options.profile, { workdir: this.workdir(), ...this.options.mcp !== void 0 ? { mcp: this.options.mcp } : {} });
884
+ if (this.options.mcp !== void 0 || this.options.pinMcpUrl === void 0) return args;
885
+ return [...args.slice(0, -1), ...codexPinnedUrlArgs(this.options.pinMcpUrl), CODEX_PROMPT_FROM_STDIN];
402
886
  }
403
887
  /** The child environment: Codex's home and the key the hosted server needs, under the configured name. */
404
888
  env() {
405
- const env = { ...this.options.env ?? process.env, CODEX_HOME: this.options.codexHome };
889
+ const env = { ...withoutParentSession(this.options.env ?? process.env), CODEX_HOME: this.options.codexHome };
406
890
  const key = this.options.apiKey();
407
891
  if (key !== null) env[this.options.keyEnv] = key;
408
892
  return env;
409
893
  }
894
+ /**
895
+ * For an `answer` run: `-c mcp_servers.<name>.enabled=false` for every MCP
896
+ * server the run would load but AgentChat's — the user's own in config.toml,
897
+ * a project's, a managed one. Codex has no "only this server" switch, and a
898
+ * tool such a server marks read-only runs without approval. Asked of Codex
899
+ * itself (`codex mcp list --json`, with the run's own `-c`/`--disable`
900
+ * flags, from the run's workdir), so every layer is counted. Any failure —
901
+ * an error, a timeout, output that is not the list — means no run.
902
+ */
903
+ async answerMcpDisables() {
904
+ const run = this.args();
905
+ const flags = run.flatMap((arg, i) => run[i - 1] === "-c" || run[i - 1] === "--disable" ? [run[i - 1], arg] : []);
906
+ const key = codexListingKey(codexConfigLayerFiles(this.options.codexHome, this.workdir()), [this.command, this.workdir(), ...flags]);
907
+ if (this.listing !== null && this.listing.key === key && Date.now() - this.listing.at < CODEX_MCP_LIST_MAX_AGE_MS) return this.listing.result;
908
+ const listed = await new Promise((resolve3) => {
909
+ let child;
910
+ try {
911
+ child = spawnCommand(this.command, ["mcp", "list", "--json", ...flags], {
912
+ cwd: this.workdir(),
913
+ env: this.env(),
914
+ stdio: ["ignore", "pipe", "pipe"],
915
+ // Its own process group on POSIX, so a hung listing is killed with
916
+ // everything it started (the npm launcher and the native binary).
917
+ detached: process.platform !== "win32",
918
+ windowsHide: true
919
+ });
920
+ } catch (err) {
921
+ resolve3({ ok: false, detail: err instanceof Error ? err.message : String(err) });
922
+ return;
923
+ }
924
+ const proc = child;
925
+ let stdout = "";
926
+ let stderr = "";
927
+ let stopped = null;
928
+ let settled = false;
929
+ let abandonTimer = null;
930
+ const settle = (result2) => {
931
+ if (settled) return;
932
+ settled = true;
933
+ clearTimeout(timer);
934
+ if (abandonTimer !== null) clearTimeout(abandonTimer);
935
+ resolve3(result2);
936
+ };
937
+ const stop = (why) => {
938
+ if (stopped !== null) return;
939
+ stopped = why;
940
+ killProcessTree(proc, "SIGKILL");
941
+ abandonTimer = setTimeout(() => settle({ ok: false, detail: `${why} (and it did not exit after being killed)` }), CODEX_MCP_LIST_KILL_WAIT_MS);
942
+ };
943
+ proc.stderr?.on("data", (chunk) => {
944
+ if (stderr.length < 4096) stderr += chunk.toString("utf-8");
945
+ });
946
+ const timeoutMs = this.options.mcpListTimeoutMs ?? CODEX_MCP_LIST_TIMEOUT_MS;
947
+ const timer = setTimeout(() => stop(`no answer within ${Math.round(timeoutMs / 1e3)} s`), timeoutMs);
948
+ proc.stdout?.on("data", (chunk) => {
949
+ stdout += chunk.toString("utf-8");
950
+ if (stdout.length > CODEX_MCP_LIST_MAX_BYTES) stop("its output is too long");
951
+ });
952
+ proc.on("error", (err) => {
953
+ if (stopped === null) settle({ ok: false, detail: err.message });
954
+ });
955
+ proc.on("close", (code) => {
956
+ if (stopped !== null) {
957
+ settle({ ok: false, detail: stopped });
958
+ return;
959
+ }
960
+ const said = redactDiagnostic(stderr.split(/\r?\n/).find((line) => line.trim().length > 0) ?? "", 200);
961
+ if (code !== 0) settle({ ok: false, detail: `it exited ${code}${said ? `: ${said}` : ""}` });
962
+ else settle({ ok: true, stdout });
963
+ });
964
+ });
965
+ if (!listed.ok) return listed;
966
+ const parsed = parseCodexMcpList(listed.stdout);
967
+ if (!parsed.ok) return parsed;
968
+ const result = codexMcpDisableArgs(parsed.names);
969
+ if (result.ok) this.listing = { key, at: Date.now(), result };
970
+ return result;
971
+ }
410
972
  async start(request) {
411
- const args = this.args();
973
+ const startedAt = Date.now();
974
+ let args = this.args();
975
+ if (this.options.profile === "answer") {
976
+ const disables = await this.answerMcpDisables();
977
+ if (!disables.ok) return { state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail: codexAnswerListingRefusal(disables.detail) };
978
+ args = [...args.slice(0, -1), ...disables.args, CODEX_PROMPT_FROM_STDIN];
979
+ }
412
980
  log.debug(`codex ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
413
981
  return spawnRun({
414
982
  command: this.command,
415
983
  args,
416
- cwd: this.options.workdir,
984
+ cwd: this.workdir(),
417
985
  env: this.env(),
418
986
  // Written to stdin and then closed: `codex exec -` reads its
419
987
  // instructions until EOF. Never as an argument (see codexRunArgs).
@@ -451,19 +1019,21 @@ var codexPreset = {
451
1019
  `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.url="${hostedMcpUrl(apiBase)}"`,
452
1020
  `-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
1021
  `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.default_tools_approval_mode="approve"`,
1022
+ `-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
1023
  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
1024
  ];
456
1025
  },
457
1026
  label: "Codex",
458
1027
  runtime: "codex",
459
- // A read-only sandbox reads the whole filesystem.
460
1028
  serviceEnv: ["CODEX_HOME"],
1029
+ // `work` and `full` read the whole filesystem (an `answer` run reads only its
1030
+ // workdir): true, because the field is one for every profile.
461
1031
  readsIdentityHome: true,
462
- inspect(env = process.env, command = "codex") {
1032
+ async inspect(env = process.env, command = "codex") {
463
1033
  const home = codexHomeFrom(env);
464
- const runtime = inspectCodexRuntime(home, command);
1034
+ const runtime = await inspectCodexRuntime(home, command);
465
1035
  if (!runtime.ok) return runtime;
466
- const auth = codexIsLoggedIn(home, command);
1036
+ const auth = await codexIsLoggedIn(home, command);
467
1037
  return auth.ok ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in: ${auth.detail}` };
468
1038
  },
469
1039
  runner(ctx) {
@@ -475,7 +1045,7 @@ var codexPreset = {
475
1045
  profile: ctx.profile,
476
1046
  apiKey: () => apiKey,
477
1047
  keyEnv: LISTENER_KEY_ENV,
478
- mcp: { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV },
1048
+ mcp: { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV, clientVersion: ctx.clientVersion ?? VERSION },
479
1049
  ...ctx.command !== void 0 ? { command: ctx.command } : {},
480
1050
  env
481
1051
  });
@@ -495,12 +1065,25 @@ function presetNames() {
495
1065
  }
496
1066
  export {
497
1067
  AGENTCHAT_TOOL_ALLOW,
1068
+ ANSWER_DENIED_TOOLS,
1069
+ ANSWER_ENV,
1070
+ ANSWER_SETTINGS,
498
1071
  ANSWER_TOOLS,
1072
+ CLAUDE_CODE_ENV_KEPT,
499
1073
  CLAUDE_CODE_PRESET,
500
1074
  CLAUDE_MCP_SERVER_NAME,
1075
+ CLAUDE_SESSION_ENV,
1076
+ CODEX_ANSWER_DISABLED_FEATURES,
1077
+ CODEX_ANSWER_FILESYSTEM,
1078
+ CODEX_ANSWER_PERMISSIONS,
1079
+ CODEX_MANAGED_PROXY_ENV,
1080
+ CODEX_MCP_LIST_MAX_AGE_MS,
1081
+ CODEX_MCP_LIST_TIMEOUT_MS,
501
1082
  CODEX_MCP_SERVER_NAME,
502
1083
  CODEX_PRESET,
1084
+ CODEX_PROBE_TIMEOUT_MS,
503
1085
  CODEX_PROMPT_FROM_STDIN,
1086
+ CODEX_SESSION_ENV,
504
1087
  ClaudeRunner,
505
1088
  CodexRunner,
506
1089
  LISTENER_KEY_ENV,
@@ -508,31 +1091,50 @@ export {
508
1091
  MIN_CODEX_VERSION,
509
1092
  PARENT_ENV_KEYS,
510
1093
  PRESETS,
1094
+ PROBE_TIMEOUT_MS,
1095
+ WEB_TOOLS,
511
1096
  WORK_TOOLS,
512
1097
  agentchatTableKeys,
513
1098
  buildClaudeEnv,
1099
+ claudeAnswerFallbackWorkdir,
514
1100
  claudeCodePreset,
515
1101
  claudeConfigDirFrom,
1102
+ claudeExtraDirectoriesGrant,
516
1103
  claudeHomeFor,
517
1104
  claudeIsLoggedIn,
1105
+ claudeManagedSettingsDir,
518
1106
  claudeMcpConfig,
519
1107
  claudeMcpConfigPath,
520
1108
  claudeProfileArgs,
1109
+ claudeProjectsDirFor,
521
1110
  claudeRunArgs,
1111
+ claudeSettingsFilesGrantingDirectories,
1112
+ claudeSignIn,
522
1113
  claudeUserStatePathFor,
1114
+ codexAnswerFallbackWorkdir,
1115
+ codexClientHeadersToml,
1116
+ codexConfigLayerFiles,
523
1117
  codexHomeFrom,
524
1118
  codexIsLoggedIn,
1119
+ codexMcpDisableArgs,
525
1120
  codexMcpOverrideArgs,
1121
+ codexPinnedUrlArgs,
526
1122
  codexPreset,
527
1123
  codexProfileArgs,
528
1124
  codexRunArgs,
1125
+ codexServerNameAddressable,
529
1126
  deniedAncestorOf,
530
1127
  inexpressibleDenyPaths,
531
1128
  inspectClaudeRuntime,
532
1129
  inspectCodexRuntime,
1130
+ isParentSessionEnv,
1131
+ parseCodexMcpList,
533
1132
  presetNamed,
534
1133
  presetNames,
535
1134
  readDenyRules,
536
- semverAtLeast
1135
+ semverAtLeast,
1136
+ withoutParentSession,
1137
+ workdirPaths,
1138
+ workdirReadRules
537
1139
  };
538
1140
  //# sourceMappingURL=presets.js.map