@agentchatme/agent-core 0.4.1 → 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,16 +1,18 @@
1
1
  import {
2
2
  VERSION,
3
- hostedMcpUrl
4
- } from "./chunk-XDWBTX5J.js";
5
- import {
6
- spawnRun
7
- } from "./chunk-AE4XHKHQ.js";
3
+ hostedMcpUrl,
4
+ runProbe
5
+ } from "./chunk-UE7DKW3C.js";
8
6
  import {
9
7
  atomicWriteFile,
10
8
  clientHeadersOf,
9
+ killProcessTree,
11
10
  log,
12
- spawnCommandSync
13
- } from "./chunk-QDM4EFI7.js";
11
+ redactDiagnostic,
12
+ spawnCommand,
13
+ spawnRun,
14
+ workdirExposesHome
15
+ } from "./chunk-AFDD53DD.js";
14
16
 
15
17
  // src/presets/claude-code.ts
16
18
  import * as fs from "fs";
@@ -33,6 +35,145 @@ function semverAtLeast(actual, minimum) {
33
35
  }
34
36
 
35
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
+ }
36
177
  function withoutInheritedKey(env) {
37
178
  const copy = { ...env };
38
179
  delete copy["AGENTCHAT_API_KEY"];
@@ -44,8 +185,15 @@ var CLAUDE_CODE_PRESET = "claude-code";
44
185
  var MIN_CLAUDE_CODE_VERSION = "2.1.274";
45
186
  var CLAUDE_MCP_SERVER_NAME = "agentchat";
46
187
  var AGENTCHAT_TOOL_ALLOW = `mcp__${CLAUDE_MCP_SERVER_NAME}__*`;
47
- var ANSWER_TOOLS = ["Read", "Glob", "Grep", "WebSearch", "WebFetch"];
188
+ var ANSWER_TOOLS = ["Read", "Glob", "Grep"];
189
+ var WEB_TOOLS = ["WebSearch", "WebFetch"];
48
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
+ });
49
197
  var PARENT_ENV_KEYS = [
50
198
  "CLAUDECODE",
51
199
  "CLAUDE_CODE_CHILD_SESSION",
@@ -54,7 +202,11 @@ var PARENT_ENV_KEYS = [
54
202
  "CLAUDE_CODE_EXECPATH",
55
203
  "CLAUDE_CODE_EFFORT_LEVEL",
56
204
  "CLAUDE_EFFORT",
57
- "AI_AGENT"
205
+ "AI_AGENT",
206
+ "CLAUDE_CODE_MESSAGING_SOCKET",
207
+ "CLAUDE_CODE_MESSAGING_TOKEN",
208
+ "CLAUDE_CODE_SESSION_ATTENDED",
209
+ "CLAUDE_PID"
58
210
  ];
59
211
  var MCP_STARTUP_WAIT_MS = "15000";
60
212
  function claudeConfigDirFrom(env = process.env) {
@@ -64,6 +216,9 @@ function claudeConfigDirFrom(env = process.env) {
64
216
  function claudeHomeFor(configDirOverride) {
65
217
  return configDirOverride ?? path.join(os.homedir(), ".claude");
66
218
  }
219
+ function claudeProjectsDirFor(configDirOverride) {
220
+ return path.join(claudeHomeFor(configDirOverride), "projects");
221
+ }
67
222
  function claudeUserStatePathFor(configDirOverride) {
68
223
  return configDirOverride !== void 0 ? path.join(configDirOverride, ".claude.json") : path.join(os.homedir(), ".claude.json");
69
224
  }
@@ -74,46 +229,40 @@ function claudeProcessEnv(configDirOverride, source) {
74
229
  return env;
75
230
  }
76
231
  function buildClaudeEnv(configDirOverride, source = process.env) {
77
- const env = claudeProcessEnv(configDirOverride, source);
78
- for (const key of PARENT_ENV_KEYS) delete env[key];
232
+ const env = claudeProcessEnv(configDirOverride, withoutParentSession(source));
79
233
  env["DISABLE_AUTOUPDATER"] = "1";
80
234
  const wait = Number(env["CLAUDE_CODE_MCP_STARTUP_WAIT_MS"]);
81
235
  if (!Number.isFinite(wait) || wait < Number(MCP_STARTUP_WAIT_MS)) env["CLAUDE_CODE_MCP_STARTUP_WAIT_MS"] = MCP_STARTUP_WAIT_MS;
82
236
  return env;
83
237
  }
84
- function claudeIsLoggedIn(configDirOverride, command = "claude") {
85
- const status = spawnCommandSync(command, ["auth", "status"], {
86
- encoding: "utf-8",
87
- timeout: 1e4,
88
- windowsHide: true,
89
- env: claudeProcessEnv(configDirOverride, process.env)
90
- });
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" };
91
243
  if (!status.error) {
92
244
  try {
93
- const parsed = JSON.parse(String(status.stdout ?? "").trim());
94
- 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 };
95
247
  } catch {
96
248
  }
97
- if (status.status === 0) return true;
249
+ if (status.status === 0) return { signedIn: true, unanswered: null };
98
250
  }
99
251
  const configDir = claudeHomeFor(configDirOverride);
100
- if (fs.existsSync(path.join(configDir, ".credentials.json"))) return true;
101
- if (process.platform !== "darwin") return false;
102
- const keychain = spawnCommandSync("security", ["find-generic-password", "-s", "Claude Code-credentials"], {
103
- encoding: "utf-8",
104
- timeout: 5e3
105
- });
106
- return !keychain.error && keychain.status === 0;
107
- }
108
- function inspectClaudeRuntime(configDirOverride, command = "claude") {
109
- const version = spawnCommandSync(command, ["--version"], {
110
- encoding: "utf-8",
111
- timeout: 1e4,
112
- windowsHide: true,
113
- env: claudeProcessEnv(configDirOverride, process.env)
114
- });
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" };
115
264
  if (version.error) return { ok: false, detail: `claude CLI not found on PATH (${version.error.message})` };
116
- const rendered = String(version.stdout || version.stderr).trim();
265
+ const rendered = (version.stdout || version.stderr).trim();
117
266
  if (version.status !== 0) return { ok: false, detail: rendered || `claude --version exited ${version.status}` };
118
267
  return semverAtLeast(rendered, MIN_CLAUDE_CODE_VERSION) ? { ok: true, detail: rendered } : {
119
268
  ok: false,
@@ -128,7 +277,29 @@ function deniedAncestorOf(dir, denied) {
128
277
  }
129
278
  return null;
130
279
  }
131
- 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) {
132
303
  switch (profile) {
133
304
  case "answer":
134
305
  return [
@@ -139,8 +310,12 @@ function claudeProfileArgs(profile) {
139
310
  "--tools",
140
311
  ANSWER_TOOLS.join(","),
141
312
  "--allowedTools",
142
- [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS].join(",")
313
+ [AGENTCHAT_TOOL_ALLOW, ...workdirReadRules(workdir)].join(","),
314
+ "--settings",
315
+ ANSWER_SETTINGS
143
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.
144
319
  case "work":
145
320
  return [
146
321
  "--permission-mode",
@@ -148,7 +323,7 @@ function claudeProfileArgs(profile) {
148
323
  "--permission-prompts",
149
324
  "none",
150
325
  "--allowedTools",
151
- [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WORK_TOOLS].join(",")
326
+ [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WEB_TOOLS, ...WORK_TOOLS].join(",")
152
327
  ];
153
328
  case "full":
154
329
  return ["--dangerously-skip-permissions", "--permission-prompts", "none", "--allowedTools", AGENTCHAT_TOOL_ALLOW];
@@ -172,7 +347,7 @@ function readDenyRules(paths) {
172
347
  }
173
348
  function claudeRunArgs(profile, options = {}) {
174
349
  const budget = options.maxBudgetUsd?.trim();
175
- const deny = readDenyRules(options.denyReadPaths ?? []);
350
+ const deny = [...profile === "answer" ? ANSWER_DENIED_TOOLS : [], ...readDenyRules(options.denyReadPaths ?? [])];
176
351
  return [
177
352
  "-p",
178
353
  "--output-format",
@@ -183,7 +358,8 @@ function claudeRunArgs(profile, options = {}) {
183
358
  ...budget !== void 0 && /^\d+(\.\d+)?$/.test(budget) ? ["--max-budget-usd", budget] : [],
184
359
  // Variadic, so it is closed by the boolean flag right after it.
185
360
  ...options.mcpConfigPath !== void 0 ? ["--mcp-config", options.mcpConfigPath, "--strict-mcp-config"] : [],
186
- ...claudeProfileArgs(profile),
361
+ ...options.appendSystemPromptFile !== void 0 ? ["--append-system-prompt-file", options.appendSystemPromptFile] : [],
362
+ ...claudeProfileArgs(profile, options.workdir),
187
363
  // Last: the option is variadic and the prompt arrives on stdin, so there
188
364
  // is no positional for it to swallow.
189
365
  ...deny.length > 0 ? ["--disallowedTools", deny.join(",")] : []
@@ -194,7 +370,70 @@ function claudeMcpConfig(apiBase, apiKey, clientVersion = VERSION) {
194
370
  return `${JSON.stringify({ mcpServers: { [CLAUDE_MCP_SERVER_NAME]: { type: "http", url: hostedMcpUrl(apiBase), headers } } }, null, 2)}
195
371
  `;
196
372
  }
197
- 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 {
198
437
  constructor(options) {
199
438
  this.options = options;
200
439
  this.command = options.command ?? "claude";
@@ -205,24 +444,51 @@ var ClaudeRunner = class {
205
444
  /** The workdir warning is one line per process, not one per preflight (preflight repeats every few minutes). */
206
445
  warnedWorkdir = false;
207
446
  warnedDeny = false;
208
- /** 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. */
209
458
  workdirDeniedBy() {
210
- return deniedAncestorOf(this.options.workdir, this.options.denyReadPaths);
459
+ return deniedAncestorOf(this.workdir(), this.options.denyReadPaths);
211
460
  }
212
- async preflight() {
213
- 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);
214
463
  if (!runtime.ok) return { ok: false, detail: runtime.detail };
215
- if (!claudeIsLoggedIn(this.options.configDir, this.command)) {
216
- 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.`);
217
483
  }
218
484
  const denied = this.workdirDeniedBy();
219
485
  if (denied !== null && !this.warnedWorkdir) {
220
486
  this.warnedWorkdir = true;
221
487
  log.warn(
222
- `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}` : ""}`
223
489
  );
224
490
  }
225
- const uncovered = inexpressibleDenyPaths(this.options.denyReadPaths);
491
+ const uncovered = inexpressibleDenyPaths(this.readDenyPaths());
226
492
  if (uncovered.length > 0) {
227
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)`;
228
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).` };
@@ -234,33 +500,120 @@ var ClaudeRunner = class {
234
500
  if (this.options.mcpConfigPath !== void 0 && !fs.existsSync(this.options.mcpConfigPath)) {
235
501
  return { ok: false, detail: `the hosted tool config ${this.options.mcpConfigPath} is missing` };
236
502
  }
237
- fs.mkdirSync(this.options.workdir, { recursive: true, mode: 448 });
503
+ fs.mkdirSync(this.workdir(), { recursive: true, mode: 448 });
238
504
  return { ok: true };
239
505
  }
240
- /** The exact argv one run uses — exported for tests to pin per profile. */
241
- 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) {
242
533
  return claudeRunArgs(this.options.profile, {
243
534
  maxBudgetUsd: (this.options.env ?? process.env)["AGENTCHAT_RUN_MAX_BUDGET_USD"],
244
- denyReadPaths: this.options.denyReadPaths,
245
- mcpConfigPath: this.options.mcpConfigPath
535
+ workdir: this.workdir(),
536
+ denyReadPaths: this.readDenyPaths(),
537
+ ...mcpConfigPath !== void 0 ? { mcpConfigPath } : {},
538
+ ...appendSystemPromptFile !== void 0 ? { appendSystemPromptFile } : {}
246
539
  });
247
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
+ }
248
559
  async start(request) {
249
- const args = this.args();
250
- log.debug(`claude ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
251
- return spawnRun({
252
- command: this.command,
253
- args,
254
- cwd: this.options.workdir,
255
- env: buildClaudeEnv(this.options.configDir, this.options.env ?? process.env),
256
- stdin: request.prompt,
257
- budgetMs: request.budgetMs,
258
- // Stopping SIGTERMs this run's process group instead of orphaning it.
259
- ...request.signal ? { signal: request.signal } : {},
260
- // The engine records a group invite as offered the moment the process
261
- // has spawned, so a run cut short still counts as the one offer.
262
- ...request.onStarted ? { onStarted: request.onStarted } : {}
263
- });
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
+ }
264
617
  }
265
618
  };
266
619
  function claudeMcpConfigPath(home) {
@@ -279,11 +632,13 @@ var claudeCodePreset = {
279
632
  // Every run's file tools are denied the identity home.
280
633
  serviceEnv: ["CLAUDE_CONFIG_DIR"],
281
634
  readsIdentityHome: false,
282
- inspect(env = process.env, command = "claude") {
635
+ async inspect(env = process.env, command = "claude") {
283
636
  const configDir = claudeConfigDirFrom(env);
284
- const runtime = inspectClaudeRuntime(configDir, command);
637
+ const runtime = await inspectClaudeRuntime(configDir, command);
285
638
  if (!runtime.ok) return runtime;
286
- 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)` };
287
642
  },
288
643
  runner(ctx) {
289
644
  const env = withoutInheritedKey(ctx.env ?? process.env);
@@ -322,33 +677,57 @@ function codexHomeFrom(env = process.env) {
322
677
  if (override !== void 0 && override.trim().length > 0) return path2.resolve(override);
323
678
  return path2.join(os2.homedir(), ".codex");
324
679
  }
325
- function inspectCodexRuntime(codexHome, command = "codex") {
326
- const result = spawnCommandSync(command, ["--version"], {
327
- encoding: "utf-8",
328
- timeout: 1e4,
329
- windowsHide: true,
330
- env: { ...process.env, CODEX_HOME: codexHome }
331
- });
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" };
332
685
  if (result.error) return { ok: false, detail: `codex CLI not found on PATH (${result.error.message})` };
333
- const rendered = String(result.stdout || result.stderr).trim();
686
+ const rendered = (result.stdout || result.stderr).trim();
334
687
  if (result.status !== 0) return { ok: false, detail: rendered || `codex --version exited ${result.status}` };
335
688
  return semverAtLeast(rendered, MIN_CODEX_VERSION) ? { ok: true, detail: rendered } : { ok: false, detail: `${rendered || "unrecognized version"}; AgentChat requires Codex >= ${MIN_CODEX_VERSION}` };
336
689
  }
337
- function codexIsLoggedIn(codexHome, command = "codex") {
338
- const status = spawnCommandSync(command, ["login", "status"], {
339
- encoding: "utf-8",
340
- timeout: 1e4,
341
- windowsHide: true,
342
- env: { ...process.env, CODEX_HOME: codexHome }
343
- });
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 } : {} });
344
692
  if (status.error) return { ok: false, detail: status.error.message };
345
- const detail = `${status.stdout ?? ""}${status.stderr ?? ""}`.trim().slice(0, 200);
693
+ const detail = `${status.stdout}${status.stderr}`.trim().slice(0, 200);
346
694
  return status.status === 0 ? { ok: true, detail: detail || "signed in" } : { ok: false, detail: detail || "codex is not signed in (run `codex login`)" };
347
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
+ ];
348
710
  function codexProfileArgs(profile) {
349
711
  switch (profile) {
350
712
  case "answer":
351
- 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.
352
731
  case "work":
353
732
  return ["--sandbox", "workspace-write", "-c", 'approval_policy="never"'];
354
733
  case "full":
@@ -359,6 +738,9 @@ function codexClientHeadersToml(clientVersion = VERSION) {
359
738
  const pairs = Object.entries(clientHeadersOf({ runtime: "codex", version: clientVersion })).map(([name, value]) => `${JSON.stringify(name)} = ${JSON.stringify(value)}`);
360
739
  return `{ ${pairs.join(", ")} }`;
361
740
  }
741
+ function codexPinnedUrlArgs(url) {
742
+ return ["-c", `mcp_servers.${CODEX_MCP_SERVER_NAME}.url=${JSON.stringify(url)}`];
743
+ }
362
744
  function codexMcpOverrideArgs(override) {
363
745
  const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`;
364
746
  return [
@@ -385,6 +767,81 @@ function codexRunArgs(profile, options) {
385
767
  CODEX_PROMPT_FROM_STDIN
386
768
  ];
387
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
+ }
388
845
  var CodexRunner = class {
389
846
  constructor(options) {
390
847
  this.options = options;
@@ -393,32 +850,138 @@ var CodexRunner = class {
393
850
  options;
394
851
  name = "codex";
395
852
  command;
396
- async preflight() {
397
- 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);
398
867
  if (!runtime.ok) return { ok: false, detail: runtime.detail };
399
- const auth = codexIsLoggedIn(this.options.codexHome, this.command);
868
+ const auth = await codexIsLoggedIn(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal);
400
869
  if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` };
401
- 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
+ }
402
879
  return { ok: true };
403
880
  }
404
- /** 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. */
405
882
  args() {
406
- 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];
407
886
  }
408
887
  /** The child environment: Codex's home and the key the hosted server needs, under the configured name. */
409
888
  env() {
410
- 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 };
411
890
  const key = this.options.apiKey();
412
891
  if (key !== null) env[this.options.keyEnv] = key;
413
892
  return env;
414
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
+ }
415
972
  async start(request) {
416
- 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
+ }
417
980
  log.debug(`codex ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
418
981
  return spawnRun({
419
982
  command: this.command,
420
983
  args,
421
- cwd: this.options.workdir,
984
+ cwd: this.workdir(),
422
985
  env: this.env(),
423
986
  // Written to stdin and then closed: `codex exec -` reads its
424
987
  // instructions until EOF. Never as an argument (see codexRunArgs).
@@ -462,14 +1025,15 @@ var codexPreset = {
462
1025
  },
463
1026
  label: "Codex",
464
1027
  runtime: "codex",
465
- // A read-only sandbox reads the whole filesystem.
466
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.
467
1031
  readsIdentityHome: true,
468
- inspect(env = process.env, command = "codex") {
1032
+ async inspect(env = process.env, command = "codex") {
469
1033
  const home = codexHomeFrom(env);
470
- const runtime = inspectCodexRuntime(home, command);
1034
+ const runtime = await inspectCodexRuntime(home, command);
471
1035
  if (!runtime.ok) return runtime;
472
- const auth = codexIsLoggedIn(home, command);
1036
+ const auth = await codexIsLoggedIn(home, command);
473
1037
  return auth.ok ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in: ${auth.detail}` };
474
1038
  },
475
1039
  runner(ctx) {
@@ -501,12 +1065,25 @@ function presetNames() {
501
1065
  }
502
1066
  export {
503
1067
  AGENTCHAT_TOOL_ALLOW,
1068
+ ANSWER_DENIED_TOOLS,
1069
+ ANSWER_ENV,
1070
+ ANSWER_SETTINGS,
504
1071
  ANSWER_TOOLS,
1072
+ CLAUDE_CODE_ENV_KEPT,
505
1073
  CLAUDE_CODE_PRESET,
506
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,
507
1082
  CODEX_MCP_SERVER_NAME,
508
1083
  CODEX_PRESET,
1084
+ CODEX_PROBE_TIMEOUT_MS,
509
1085
  CODEX_PROMPT_FROM_STDIN,
1086
+ CODEX_SESSION_ENV,
510
1087
  ClaudeRunner,
511
1088
  CodexRunner,
512
1089
  LISTENER_KEY_ENV,
@@ -514,32 +1091,50 @@ export {
514
1091
  MIN_CODEX_VERSION,
515
1092
  PARENT_ENV_KEYS,
516
1093
  PRESETS,
1094
+ PROBE_TIMEOUT_MS,
1095
+ WEB_TOOLS,
517
1096
  WORK_TOOLS,
518
1097
  agentchatTableKeys,
519
1098
  buildClaudeEnv,
1099
+ claudeAnswerFallbackWorkdir,
520
1100
  claudeCodePreset,
521
1101
  claudeConfigDirFrom,
1102
+ claudeExtraDirectoriesGrant,
522
1103
  claudeHomeFor,
523
1104
  claudeIsLoggedIn,
1105
+ claudeManagedSettingsDir,
524
1106
  claudeMcpConfig,
525
1107
  claudeMcpConfigPath,
526
1108
  claudeProfileArgs,
1109
+ claudeProjectsDirFor,
527
1110
  claudeRunArgs,
1111
+ claudeSettingsFilesGrantingDirectories,
1112
+ claudeSignIn,
528
1113
  claudeUserStatePathFor,
1114
+ codexAnswerFallbackWorkdir,
529
1115
  codexClientHeadersToml,
1116
+ codexConfigLayerFiles,
530
1117
  codexHomeFrom,
531
1118
  codexIsLoggedIn,
1119
+ codexMcpDisableArgs,
532
1120
  codexMcpOverrideArgs,
1121
+ codexPinnedUrlArgs,
533
1122
  codexPreset,
534
1123
  codexProfileArgs,
535
1124
  codexRunArgs,
1125
+ codexServerNameAddressable,
536
1126
  deniedAncestorOf,
537
1127
  inexpressibleDenyPaths,
538
1128
  inspectClaudeRuntime,
539
1129
  inspectCodexRuntime,
1130
+ isParentSessionEnv,
1131
+ parseCodexMcpList,
540
1132
  presetNamed,
541
1133
  presetNames,
542
1134
  readDenyRules,
543
- semverAtLeast
1135
+ semverAtLeast,
1136
+ withoutParentSession,
1137
+ workdirPaths,
1138
+ workdirReadRules
544
1139
  };
545
1140
  //# sourceMappingURL=presets.js.map