@agentchatme/agent-core 0.3.1 → 0.4.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.
@@ -0,0 +1,538 @@
1
+ import {
2
+ hostedMcpUrl
3
+ } from "./chunk-HOY2FERJ.js";
4
+ import {
5
+ spawnRun
6
+ } from "./chunk-TH6XOVA3.js";
7
+ import {
8
+ atomicWriteFile,
9
+ log,
10
+ spawnCommandSync
11
+ } from "./chunk-NCSF3CCV.js";
12
+
13
+ // src/presets/claude-code.ts
14
+ import * as fs from "fs";
15
+ import * as os from "os";
16
+ import * as path from "path";
17
+
18
+ // src/presets/semver.ts
19
+ function semverAtLeast(actual, minimum) {
20
+ const parse = (value) => {
21
+ const match = value.match(/(\d+)\.(\d+)\.(\d+)/);
22
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
23
+ };
24
+ const a = parse(actual);
25
+ const b = parse(minimum);
26
+ if (a === null || b === null) return false;
27
+ for (let index = 0; index < 3; index++) {
28
+ if (a[index] !== b[index]) return (a[index] ?? 0) > (b[index] ?? 0);
29
+ }
30
+ return true;
31
+ }
32
+
33
+ // src/presets/types.ts
34
+ function withoutInheritedKey(env) {
35
+ const copy = { ...env };
36
+ delete copy["AGENTCHAT_API_KEY"];
37
+ return copy;
38
+ }
39
+
40
+ // src/presets/claude-code.ts
41
+ var CLAUDE_CODE_PRESET = "claude-code";
42
+ var MIN_CLAUDE_CODE_VERSION = "2.1.274";
43
+ var CLAUDE_MCP_SERVER_NAME = "agentchat";
44
+ var AGENTCHAT_TOOL_ALLOW = `mcp__${CLAUDE_MCP_SERVER_NAME}__*`;
45
+ var ANSWER_TOOLS = ["Read", "Glob", "Grep", "WebSearch", "WebFetch"];
46
+ var WORK_TOOLS = ["Bash", "Edit", "Write", "MultiEdit", "NotebookEdit"];
47
+ var PARENT_ENV_KEYS = [
48
+ "CLAUDECODE",
49
+ "CLAUDE_CODE_CHILD_SESSION",
50
+ "CLAUDE_CODE_SESSION_ID",
51
+ "CLAUDE_CODE_ENTRYPOINT",
52
+ "CLAUDE_CODE_EXECPATH",
53
+ "CLAUDE_CODE_EFFORT_LEVEL",
54
+ "CLAUDE_EFFORT",
55
+ "AI_AGENT"
56
+ ];
57
+ var MCP_STARTUP_WAIT_MS = "15000";
58
+ function claudeConfigDirFrom(env = process.env) {
59
+ const override = env["CLAUDE_CONFIG_DIR"];
60
+ return override !== void 0 && override.trim().length > 0 ? path.resolve(override) : void 0;
61
+ }
62
+ function claudeHomeFor(configDirOverride) {
63
+ return configDirOverride ?? path.join(os.homedir(), ".claude");
64
+ }
65
+ function claudeUserStatePathFor(configDirOverride) {
66
+ return configDirOverride !== void 0 ? path.join(configDirOverride, ".claude.json") : path.join(os.homedir(), ".claude.json");
67
+ }
68
+ function claudeProcessEnv(configDirOverride, source) {
69
+ const env = { ...source };
70
+ if (configDirOverride === void 0) delete env["CLAUDE_CONFIG_DIR"];
71
+ else env["CLAUDE_CONFIG_DIR"] = configDirOverride;
72
+ return env;
73
+ }
74
+ function buildClaudeEnv(configDirOverride, source = process.env) {
75
+ const env = claudeProcessEnv(configDirOverride, source);
76
+ for (const key of PARENT_ENV_KEYS) delete env[key];
77
+ env["DISABLE_AUTOUPDATER"] = "1";
78
+ const wait = Number(env["CLAUDE_CODE_MCP_STARTUP_WAIT_MS"]);
79
+ if (!Number.isFinite(wait) || wait < Number(MCP_STARTUP_WAIT_MS)) env["CLAUDE_CODE_MCP_STARTUP_WAIT_MS"] = MCP_STARTUP_WAIT_MS;
80
+ return env;
81
+ }
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
+ });
89
+ if (!status.error) {
90
+ try {
91
+ const parsed = JSON.parse(String(status.stdout ?? "").trim());
92
+ if (typeof parsed?.loggedIn === "boolean") return parsed.loggedIn;
93
+ } catch {
94
+ }
95
+ if (status.status === 0) return true;
96
+ }
97
+ 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
+ });
113
+ 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();
115
+ if (version.status !== 0) return { ok: false, detail: rendered || `claude --version exited ${version.status}` };
116
+ return semverAtLeast(rendered, MIN_CLAUDE_CODE_VERSION) ? { ok: true, detail: rendered } : {
117
+ ok: false,
118
+ detail: `${rendered || "unrecognized version"}; AgentChat requires Claude Code >= ${MIN_CLAUDE_CODE_VERSION} (for --permission-prompts none and CLAUDE_CODE_MCP_STARTUP_WAIT_MS)`
119
+ };
120
+ }
121
+ function deniedAncestorOf(dir, denied) {
122
+ const target = path.resolve(dir);
123
+ for (const raw of denied) {
124
+ const root = path.resolve(raw);
125
+ if (target === root || target.startsWith(root.endsWith(path.sep) ? root : root + path.sep)) return root;
126
+ }
127
+ return null;
128
+ }
129
+ function claudeProfileArgs(profile) {
130
+ switch (profile) {
131
+ case "answer":
132
+ return [
133
+ "--permission-mode",
134
+ "default",
135
+ "--permission-prompts",
136
+ "none",
137
+ "--tools",
138
+ ANSWER_TOOLS.join(","),
139
+ "--allowedTools",
140
+ [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS].join(",")
141
+ ];
142
+ case "work":
143
+ return [
144
+ "--permission-mode",
145
+ "acceptEdits",
146
+ "--permission-prompts",
147
+ "none",
148
+ "--allowedTools",
149
+ [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WORK_TOOLS].join(",")
150
+ ];
151
+ case "full":
152
+ return ["--dangerously-skip-permissions", "--permission-prompts", "none", "--allowedTools", AGENTCHAT_TOOL_ALLOW];
153
+ }
154
+ }
155
+ function expressible(raw) {
156
+ return raw.startsWith("/") && !/[,\s]/.test(raw);
157
+ }
158
+ function inexpressibleDenyPaths(paths) {
159
+ return process.platform === "win32" ? [...paths] : paths.filter((p) => !expressible(p));
160
+ }
161
+ function readDenyRules(paths) {
162
+ if (process.platform === "win32") return [];
163
+ const rules = [];
164
+ for (const raw of paths) {
165
+ if (!expressible(raw)) continue;
166
+ const clean = raw.replace(/\/+$/, "");
167
+ rules.push(`Read(/${clean})`, `Read(/${clean}/**)`);
168
+ }
169
+ return rules;
170
+ }
171
+ function claudeRunArgs(profile, options = {}) {
172
+ const budget = options.maxBudgetUsd?.trim();
173
+ const deny = readDenyRules(options.denyReadPaths ?? []);
174
+ return [
175
+ "-p",
176
+ "--output-format",
177
+ "text",
178
+ // A wake run is not a conversation to resume; keep it out of the user's
179
+ // session list and off the disk.
180
+ "--no-session-persistence",
181
+ ...budget !== void 0 && /^\d+(\.\d+)?$/.test(budget) ? ["--max-budget-usd", budget] : [],
182
+ // Variadic, so it is closed by the boolean flag right after it.
183
+ ...options.mcpConfigPath !== void 0 ? ["--mcp-config", options.mcpConfigPath, "--strict-mcp-config"] : [],
184
+ ...claudeProfileArgs(profile),
185
+ // Last: the option is variadic and the prompt arrives on stdin, so there
186
+ // is no positional for it to swallow.
187
+ ...deny.length > 0 ? ["--disallowedTools", deny.join(",")] : []
188
+ ];
189
+ }
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
+ )}
196
+ `;
197
+ }
198
+ var ClaudeRunner = class {
199
+ constructor(options) {
200
+ this.options = options;
201
+ this.command = options.command ?? "claude";
202
+ }
203
+ options;
204
+ name = "claude";
205
+ command;
206
+ /** The workdir warning is one line per process, not one per preflight (preflight repeats every few minutes). */
207
+ warnedWorkdir = false;
208
+ warnedDeny = false;
209
+ /** The denied path the configured workdir sits in, or null when the run can read its own cwd. */
210
+ workdirDeniedBy() {
211
+ return deniedAncestorOf(this.options.workdir, this.options.denyReadPaths);
212
+ }
213
+ async preflight() {
214
+ const runtime = inspectClaudeRuntime(this.options.configDir, this.command);
215
+ 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)" };
218
+ }
219
+ const denied = this.workdirDeniedBy();
220
+ if (denied !== null && !this.warnedWorkdir) {
221
+ this.warnedWorkdir = true;
222
+ 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}` : ""}`
224
+ );
225
+ }
226
+ const uncovered = inexpressibleDenyPaths(this.options.denyReadPaths);
227
+ if (uncovered.length > 0) {
228
+ 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
+ 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).` };
230
+ if (!this.warnedDeny) {
231
+ this.warnedDeny = true;
232
+ log.warn(`${why}: runs can read those paths.`);
233
+ }
234
+ }
235
+ if (this.options.mcpConfigPath !== void 0 && !fs.existsSync(this.options.mcpConfigPath)) {
236
+ return { ok: false, detail: `the hosted tool config ${this.options.mcpConfigPath} is missing` };
237
+ }
238
+ fs.mkdirSync(this.options.workdir, { recursive: true, mode: 448 });
239
+ return { ok: true };
240
+ }
241
+ /** The exact argv one run uses — exported for tests to pin per profile. */
242
+ args() {
243
+ return claudeRunArgs(this.options.profile, {
244
+ maxBudgetUsd: (this.options.env ?? process.env)["AGENTCHAT_RUN_MAX_BUDGET_USD"],
245
+ denyReadPaths: this.options.denyReadPaths,
246
+ mcpConfigPath: this.options.mcpConfigPath
247
+ });
248
+ }
249
+ 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
+ });
265
+ }
266
+ };
267
+ function claudeMcpConfigPath(home) {
268
+ return path.join(home, "presets", `${CLAUDE_CODE_PRESET}.mcp.json`);
269
+ }
270
+ var claudeCodePreset = {
271
+ name: CLAUDE_CODE_PRESET,
272
+ describeMcp({ home, apiBase }) {
273
+ return [
274
+ `--mcp-config ${claudeMcpConfigPath(home)} (owner-only): ${CLAUDE_MCP_SERVER_NAME} \u2192 ${hostedMcpUrl(apiBase)}, Authorization: Bearer <this home's key>`,
275
+ "--strict-mcp-config: no other MCP server (user, project or plugin) is loaded in these runs"
276
+ ];
277
+ },
278
+ label: "Claude Code",
279
+ runtime: "claude-code",
280
+ // Every run's file tools are denied the identity home.
281
+ serviceEnv: ["CLAUDE_CONFIG_DIR"],
282
+ readsIdentityHome: false,
283
+ inspect(env = process.env, command = "claude") {
284
+ const configDir = claudeConfigDirFrom(env);
285
+ const runtime = inspectClaudeRuntime(configDir, command);
286
+ 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)` };
288
+ },
289
+ runner(ctx) {
290
+ const env = withoutInheritedKey(ctx.env ?? process.env);
291
+ const configDir = claudeConfigDirFrom(env);
292
+ const mcpConfigPath = claudeMcpConfigPath(ctx.home);
293
+ atomicWriteFile(mcpConfigPath, claudeMcpConfig(ctx.apiBase, ctx.apiKey), 384);
294
+ return new ClaudeRunner({
295
+ configDir,
296
+ workdir: ctx.workdir,
297
+ profile: ctx.profile,
298
+ // The listener's home (its key and this file), the user-scope MCP state
299
+ // and an integration's identity home beside it: no run reads a key.
300
+ denyReadPaths: [ctx.home, claudeUserStatePathFor(configDir), path.join(claudeHomeFor(configDir), "agentchat")],
301
+ mcpConfigPath,
302
+ workdirAdvice: "Start the listener from a directory outside it, or pass --workdir.",
303
+ // On POSIX a listener's run must not start with its key readable; on
304
+ // Windows no rule exists at all (documented), so it warns.
305
+ inexpressibleDeny: process.platform === "win32" ? "warn" : "refuse",
306
+ ...ctx.command !== void 0 ? { command: ctx.command } : {},
307
+ env
308
+ });
309
+ }
310
+ };
311
+
312
+ // src/presets/codex.ts
313
+ import * as fs2 from "fs";
314
+ import * as os2 from "os";
315
+ import * as path2 from "path";
316
+ var CODEX_PRESET = "codex";
317
+ var MIN_CODEX_VERSION = "0.154.0";
318
+ var CODEX_MCP_SERVER_NAME = "agentchat";
319
+ var LISTENER_KEY_ENV = "AGENTCHAT_LISTENER_API_KEY";
320
+ var CODEX_PROMPT_FROM_STDIN = "-";
321
+ function codexHomeFrom(env = process.env) {
322
+ const override = env["CODEX_HOME"];
323
+ if (override !== void 0 && override.trim().length > 0) return path2.resolve(override);
324
+ return path2.join(os2.homedir(), ".codex");
325
+ }
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
+ });
333
+ 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();
335
+ if (result.status !== 0) return { ok: false, detail: rendered || `codex --version exited ${result.status}` };
336
+ return semverAtLeast(rendered, MIN_CODEX_VERSION) ? { ok: true, detail: rendered } : { ok: false, detail: `${rendered || "unrecognized version"}; AgentChat requires Codex >= ${MIN_CODEX_VERSION}` };
337
+ }
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
+ });
345
+ if (status.error) return { ok: false, detail: status.error.message };
346
+ const detail = `${status.stdout ?? ""}${status.stderr ?? ""}`.trim().slice(0, 200);
347
+ return status.status === 0 ? { ok: true, detail: detail || "signed in" } : { ok: false, detail: detail || "codex is not signed in (run `codex login`)" };
348
+ }
349
+ function codexProfileArgs(profile) {
350
+ switch (profile) {
351
+ case "answer":
352
+ return ["--sandbox", "read-only", "-c", 'approval_policy="never"'];
353
+ case "work":
354
+ return ["--sandbox", "workspace-write", "-c", 'approval_policy="never"'];
355
+ case "full":
356
+ return ["--dangerously-bypass-approvals-and-sandbox"];
357
+ }
358
+ }
359
+ function codexMcpOverrideArgs(override) {
360
+ const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`;
361
+ return [
362
+ "-c",
363
+ `${table}.url=${JSON.stringify(override.url)}`,
364
+ "-c",
365
+ `${table}.bearer_token_env_var=${JSON.stringify(override.keyEnv)}`,
366
+ "-c",
367
+ `${table}.default_tools_approval_mode="approve"`
368
+ ];
369
+ }
370
+ function codexRunArgs(profile, options) {
371
+ return [
372
+ "exec",
373
+ "--json",
374
+ "--skip-git-repo-check",
375
+ "--ephemeral",
376
+ "-C",
377
+ options.workdir,
378
+ ...codexProfileArgs(profile),
379
+ ...options.mcp !== void 0 ? codexMcpOverrideArgs(options.mcp) : [],
380
+ CODEX_PROMPT_FROM_STDIN
381
+ ];
382
+ }
383
+ var CodexRunner = class {
384
+ constructor(options) {
385
+ this.options = options;
386
+ this.command = options.command ?? "codex";
387
+ }
388
+ options;
389
+ name = "codex";
390
+ command;
391
+ async preflight() {
392
+ const runtime = inspectCodexRuntime(this.options.codexHome, this.command);
393
+ if (!runtime.ok) return { ok: false, detail: runtime.detail };
394
+ const auth = codexIsLoggedIn(this.options.codexHome, this.command);
395
+ if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` };
396
+ fs2.mkdirSync(this.options.workdir, { recursive: true });
397
+ return { ok: true };
398
+ }
399
+ /** The exact argv one run uses — exported for tests to pin per profile. */
400
+ args() {
401
+ return codexRunArgs(this.options.profile, { workdir: this.options.workdir, ...this.options.mcp !== void 0 ? { mcp: this.options.mcp } : {} });
402
+ }
403
+ /** The child environment: Codex's home and the key the hosted server needs, under the configured name. */
404
+ env() {
405
+ const env = { ...this.options.env ?? process.env, CODEX_HOME: this.options.codexHome };
406
+ const key = this.options.apiKey();
407
+ if (key !== null) env[this.options.keyEnv] = key;
408
+ return env;
409
+ }
410
+ async start(request) {
411
+ const args = this.args();
412
+ log.debug(`codex ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
413
+ return spawnRun({
414
+ command: this.command,
415
+ args,
416
+ cwd: this.options.workdir,
417
+ env: this.env(),
418
+ // Written to stdin and then closed: `codex exec -` reads its
419
+ // instructions until EOF. Never as an argument (see codexRunArgs).
420
+ stdin: request.prompt,
421
+ budgetMs: request.budgetMs,
422
+ ...request.signal ? { signal: request.signal } : {},
423
+ ...request.onStarted ? { onStarted: request.onStarted } : {}
424
+ });
425
+ }
426
+ };
427
+ function agentchatTableKeys(configToml) {
428
+ const lines = configToml.split(/\r?\n/);
429
+ const header = new RegExp(`^\\s*\\[mcp_servers\\.${CODEX_MCP_SERVER_NAME}\\]\\s*(#.*)?$`);
430
+ const start = lines.findIndex((line) => header.test(line));
431
+ if (start < 0) return null;
432
+ const keys = [];
433
+ for (const line of lines.slice(start + 1)) {
434
+ if (/^\s*\[/.test(line)) break;
435
+ const match = /^\s*([A-Za-z0-9_.-]+)\s*=/.exec(line);
436
+ if (match?.[1] !== void 0) keys.push(match[1]);
437
+ }
438
+ return keys;
439
+ }
440
+ var codexPreset = {
441
+ name: CODEX_PRESET,
442
+ describeMcp({ apiBase, env = process.env }) {
443
+ const file = path2.join(codexHomeFrom(env), "config.toml");
444
+ let own = null;
445
+ try {
446
+ own = agentchatTableKeys(fs2.readFileSync(file, "utf-8"));
447
+ } catch {
448
+ own = null;
449
+ }
450
+ return [
451
+ `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.url="${hostedMcpUrl(apiBase)}"`,
452
+ `-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
+ `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.default_tools_approval_mode="approve"`,
454
+ 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
+ ];
456
+ },
457
+ label: "Codex",
458
+ runtime: "codex",
459
+ // A read-only sandbox reads the whole filesystem.
460
+ serviceEnv: ["CODEX_HOME"],
461
+ readsIdentityHome: true,
462
+ inspect(env = process.env, command = "codex") {
463
+ const home = codexHomeFrom(env);
464
+ const runtime = inspectCodexRuntime(home, command);
465
+ if (!runtime.ok) return runtime;
466
+ const auth = codexIsLoggedIn(home, command);
467
+ return auth.ok ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in: ${auth.detail}` };
468
+ },
469
+ runner(ctx) {
470
+ const env = withoutInheritedKey(ctx.env ?? process.env);
471
+ const apiKey = ctx.apiKey;
472
+ return new CodexRunner({
473
+ codexHome: codexHomeFrom(env),
474
+ workdir: ctx.workdir,
475
+ profile: ctx.profile,
476
+ apiKey: () => apiKey,
477
+ keyEnv: LISTENER_KEY_ENV,
478
+ mcp: { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV },
479
+ ...ctx.command !== void 0 ? { command: ctx.command } : {},
480
+ env
481
+ });
482
+ }
483
+ };
484
+
485
+ // src/presets/index.ts
486
+ var PRESETS = Object.freeze({
487
+ [claudeCodePreset.name]: claudeCodePreset,
488
+ [codexPreset.name]: codexPreset
489
+ });
490
+ function presetNamed(name) {
491
+ return Object.prototype.hasOwnProperty.call(PRESETS, name) ? PRESETS[name] ?? null : null;
492
+ }
493
+ function presetNames() {
494
+ return Object.keys(PRESETS);
495
+ }
496
+ export {
497
+ AGENTCHAT_TOOL_ALLOW,
498
+ ANSWER_TOOLS,
499
+ CLAUDE_CODE_PRESET,
500
+ CLAUDE_MCP_SERVER_NAME,
501
+ CODEX_MCP_SERVER_NAME,
502
+ CODEX_PRESET,
503
+ CODEX_PROMPT_FROM_STDIN,
504
+ ClaudeRunner,
505
+ CodexRunner,
506
+ LISTENER_KEY_ENV,
507
+ MIN_CLAUDE_CODE_VERSION,
508
+ MIN_CODEX_VERSION,
509
+ PARENT_ENV_KEYS,
510
+ PRESETS,
511
+ WORK_TOOLS,
512
+ agentchatTableKeys,
513
+ buildClaudeEnv,
514
+ claudeCodePreset,
515
+ claudeConfigDirFrom,
516
+ claudeHomeFor,
517
+ claudeIsLoggedIn,
518
+ claudeMcpConfig,
519
+ claudeMcpConfigPath,
520
+ claudeProfileArgs,
521
+ claudeRunArgs,
522
+ claudeUserStatePathFor,
523
+ codexHomeFrom,
524
+ codexIsLoggedIn,
525
+ codexMcpOverrideArgs,
526
+ codexPreset,
527
+ codexProfileArgs,
528
+ codexRunArgs,
529
+ deniedAncestorOf,
530
+ inexpressibleDenyPaths,
531
+ inspectClaudeRuntime,
532
+ inspectCodexRuntime,
533
+ presetNamed,
534
+ presetNames,
535
+ readDenyRules,
536
+ semverAtLeast
537
+ };
538
+ //# sourceMappingURL=presets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/presets/claude-code.ts","../src/presets/semver.ts","../src/presets/types.ts","../src/presets/codex.ts","../src/presets/index.ts"],"sourcesContent":["import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { hostedMcpUrl } from '../integration/mcp-probe.js'\nimport type { RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, RunRequest, RunRunner } from '../integration/runner.js'\nimport { spawnRun } from '../integration/spawn-run.js'\nimport { atomicWriteFile } from '../util/fsutil.js'\nimport { log } from '../util/log.js'\nimport { spawnCommandSync } from '../util/spawn.js'\nimport { semverAtLeast } from './semver.js'\nimport { withoutInheritedKey, type Preset, type PresetContext, type PresetInspection } from './types.js'\n\n// ─── Claude Code: one headless run (`claude -p`) ────────────────────────────\n//\n// `claude -p` on the box, riding the user's own Claude Code sign-in and user\n// configuration. The run's output is discarded by `spawnRun`: the agent's only\n// way to say anything on AgentChat is the hosted send tool during the run.\n//\n// The flags, verified against `claude --help` (2.1.316) and\n// code.claude.com/docs/en/cli-reference.md, headless.md, permission-modes.md:\n//\n// --permission-prompts none anything that would prompt is denied, never\n// waited on; the permission mode and allow rules\n// still decide every call first (v2.1.259+).\n// --tools <list> restricts the BUILT-IN tool set; does not affect\n// MCP tools. Listing Glob/Grep explicitly provides\n// the dedicated search tools.\n// --allowedTools <rules> pre-approves. `mcp__agentchat__*` is the whole\n// hosted server; `Bash` pre-approves every shell\n// command (dropped as a broad rule only in auto mode).\n// --disallowedTools <rules> denies. Deny rules win over allow rules, and a\n// `Read(<path>)` rule covers every built-in tool\n// that reads files (Read, Grep, Glob — docs:\n// permissions.md \"Read & Edit\"). Used to keep a\n// run's file tools off the key store. `//`\n// prefixes an absolute path in rule syntax.\n// --permission-mode default Manual: reads need no approval, everything else\n// prompts (and is therefore denied here).\n// --permission-mode acceptEdits file edits and common filesystem commands in\n// the working directory need no approval.\n// --dangerously-skip-permissions = bypassPermissions.\n// --mcp-config <file> --strict-mcp-config\n// the hosted server from a file, and ONLY it: a\n// listener's run acts as the listener's agent,\n// never as whatever key the user scope registers.\n//\n// Whatever the profile, every AgentChat hosted tool is pre-approved: the run\n// exists to read the tray and decide or send through them.\n\nexport const CLAUDE_CODE_PRESET = 'claude-code'\n\n/**\n * Two flags set the floor:\n * * `--permission-prompts none` — Claude Code v2.1.259.\n * * `CLAUDE_CODE_MCP_STARTUP_WAIT_MS` — bounds how long the first\n * non-interactive turn waits for the MCP servers `--allowedTools` names to\n * connect. Added in v2.1.274. Without it a run could start before the\n * hosted inbox tool is there.\n */\nexport const MIN_CLAUDE_CODE_VERSION = '2.1.274'\n\n/** The MCP server name the runs see; every hosted tool is `mcp__agentchat__<tool>`, as the served texts spell them. */\nexport const CLAUDE_MCP_SERVER_NAME = 'agentchat'\nexport const AGENTCHAT_TOOL_ALLOW = `mcp__${CLAUDE_MCP_SERVER_NAME}__*`\n\n/** Built-in tools an `answer` run keeps: read-only files plus the web. */\nexport const ANSWER_TOOLS = ['Read', 'Glob', 'Grep', 'WebSearch', 'WebFetch'] as const\n\n/** Built-in tools a `work` run additionally pre-approves. */\nexport const WORK_TOOLS = ['Bash', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit'] as const\n\n/** Env a parent Claude Code session leaks that would make the child think it is nested. */\nexport const PARENT_ENV_KEYS = [\n 'CLAUDECODE',\n 'CLAUDE_CODE_CHILD_SESSION',\n 'CLAUDE_CODE_SESSION_ID',\n 'CLAUDE_CODE_ENTRYPOINT',\n 'CLAUDE_CODE_EXECPATH',\n 'CLAUDE_CODE_EFFORT_LEVEL',\n 'CLAUDE_EFFORT',\n 'AI_AGENT',\n]\n\n/**\n * How long the first turn of a `-p` run waits for a still-connecting MCP\n * server that `--allowedTools` names. Claude Code's own built-in wait is short\n * (2 s since 2.1.284), and a remote server over a cold network can take\n * longer; the run must not start without the inbox tool.\n */\nconst MCP_STARTUP_WAIT_MS = '15000'\n\n/** Claude Code's supported relocation knob. Unset is NOT the same as `~/.claude`. */\nexport function claudeConfigDirFrom(env: NodeJS.ProcessEnv = process.env): string | undefined {\n const override = env['CLAUDE_CONFIG_DIR']\n return override !== undefined && override.trim().length > 0 ? path.resolve(override) : undefined\n}\n\n/** `~/.claude`, or the relocated config dir. */\nexport function claudeHomeFor(configDirOverride: string | undefined): string {\n return configDirOverride ?? path.join(os.homedir(), '.claude')\n}\n\n/**\n * Where Claude Code keeps user-scoped MCP servers (and so any key registered\n * there): `~/.claude.json`, or `$CLAUDE_CONFIG_DIR/.claude.json`.\n */\nexport function claudeUserStatePathFor(configDirOverride: string | undefined): string {\n return configDirOverride !== undefined ? path.join(configDirOverride, '.claude.json') : path.join(os.homedir(), '.claude.json')\n}\n\nfunction claudeProcessEnv(configDirOverride: string | undefined, source: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const env = { ...source }\n if (configDirOverride === undefined) delete env['CLAUDE_CONFIG_DIR']\n else env['CLAUDE_CONFIG_DIR'] = configDirOverride\n return env\n}\n\nexport function buildClaudeEnv(configDirOverride: string | undefined, source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const env = claudeProcessEnv(configDirOverride, source)\n for (const key of PARENT_ENV_KEYS) delete env[key]\n env['DISABLE_AUTOUPDATER'] = '1'\n const wait = Number(env['CLAUDE_CODE_MCP_STARTUP_WAIT_MS'])\n if (!Number.isFinite(wait) || wait < Number(MCP_STARTUP_WAIT_MS)) env['CLAUDE_CODE_MCP_STARTUP_WAIT_MS'] = MCP_STARTUP_WAIT_MS\n return env\n}\n\n/**\n * Is Claude Code signed in? `claude auth status` prints JSON with a boolean\n * `loggedIn` and exits 0 if logged in, 1 if not. When that JSON is there it is\n * the answer. The file/keychain probes are a fallback for builds without the\n * subcommand; the keychain probe is existence-only and never prompts — a\n * resident listener must never trigger a keychain prompt.\n */\nexport function claudeIsLoggedIn(configDirOverride?: string, command = 'claude'): boolean {\n const status = spawnCommandSync(command, ['auth', 'status'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: claudeProcessEnv(configDirOverride, process.env),\n })\n if (!status.error) {\n try {\n const parsed = JSON.parse(String(status.stdout ?? '').trim()) as { loggedIn?: unknown }\n if (typeof parsed?.loggedIn === 'boolean') return parsed.loggedIn\n } catch {\n /* no JSON: an older build; fall through to the file and keychain */\n }\n if (status.status === 0) return true\n }\n\n const configDir = claudeHomeFor(configDirOverride)\n if (fs.existsSync(path.join(configDir, '.credentials.json'))) return true\n if (process.platform !== 'darwin') return false\n const keychain = spawnCommandSync('security', ['find-generic-password', '-s', 'Claude Code-credentials'], {\n encoding: 'utf-8',\n timeout: 5_000,\n })\n return !keychain.error && keychain.status === 0\n}\n\nexport function inspectClaudeRuntime(configDirOverride?: string, command = 'claude'): PresetInspection {\n const version = spawnCommandSync(command, ['--version'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: claudeProcessEnv(configDirOverride, process.env),\n })\n if (version.error) return { ok: false, detail: `claude CLI not found on PATH (${version.error.message})` }\n const rendered = String(version.stdout || version.stderr).trim()\n if (version.status !== 0) return { ok: false, detail: rendered || `claude --version exited ${version.status}` }\n return semverAtLeast(rendered, MIN_CLAUDE_CODE_VERSION)\n ? { ok: true, detail: rendered }\n : {\n ok: false,\n detail: `${rendered || 'unrecognized version'}; AgentChat requires Claude Code >= ${MIN_CLAUDE_CODE_VERSION} (for --permission-prompts none and CLAUDE_CODE_MCP_STARTUP_WAIT_MS)`,\n }\n}\n\n/**\n * The entry of `denied` that is `dir` or contains it, or null. Whole path\n * segments only: `~/.claude/agentchat` does not contain `~/.claude/agentchat-workdir`.\n */\nexport function deniedAncestorOf(dir: string, denied: readonly string[]): string | null {\n const target = path.resolve(dir)\n for (const raw of denied) {\n const root = path.resolve(raw)\n if (target === root || target.startsWith(root.endsWith(path.sep) ? root : root + path.sep)) return root\n }\n return null\n}\n\nexport function claudeProfileArgs(profile: RunProfile): string[] {\n switch (profile) {\n case 'answer':\n return [\n '--permission-mode',\n 'default',\n '--permission-prompts',\n 'none',\n '--tools',\n ANSWER_TOOLS.join(','),\n '--allowedTools',\n [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS].join(','),\n ]\n case 'work':\n return [\n '--permission-mode',\n 'acceptEdits',\n '--permission-prompts',\n 'none',\n '--allowedTools',\n [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WORK_TOOLS].join(','),\n ]\n case 'full':\n return ['--dangerously-skip-permissions', '--permission-prompts', 'none', '--allowedTools', AGENTCHAT_TOOL_ALLOW]\n }\n}\n\nexport interface ClaudeRunArgOptions {\n /** `AGENTCHAT_RUN_MAX_BUDGET_USD`: stop the run once estimated spend reaches this (print mode only). */\n readonly maxBudgetUsd?: string | undefined\n /**\n * Absolute paths the run's file tools may not read (a directory covers its\n * tree). Rendered as `Read(//<path>)` / `Read(//<dir>/**)` deny rules. A\n * prompt-injected run could otherwise read the key and send it; the wake\n * text should not be the only guard. POSIX paths only — on Windows the\n * rule syntax for drive paths is undocumented, so nothing is rendered.\n */\n readonly denyReadPaths?: readonly string[] | undefined\n /**\n * A `--mcp-config` file holding the hosted server with the agent's key;\n * with it, `--strict-mcp-config` makes it the run's only MCP server. Absent:\n * the run uses the user-scope server the integration registered.\n */\n readonly mcpConfigPath?: string | undefined\n}\n\n/** Whether a path can be carried by a `Read(//<path>)` rule in a comma/space-separated list: absolute POSIX, no comma, no whitespace. */\nfunction expressible(raw: string): boolean {\n return raw.startsWith('/') && !/[,\\s]/.test(raw)\n}\n\n/**\n * The deny paths no rule can carry: on Windows all of them (the rule syntax\n * for drive paths is undocumented), elsewhere a relative path or one with a\n * comma or whitespace. A run would be able to read these.\n */\nexport function inexpressibleDenyPaths(paths: readonly string[]): string[] {\n return process.platform === 'win32' ? [...paths] : paths.filter((p) => !expressible(p))\n}\n\n/** `/Users/x/.claude/agentchat` → `Read(//Users/x/.claude/agentchat/**)` and `Read(//Users/x/.claude/agentchat)`. Paths no rule can carry are left out (`inexpressibleDenyPaths`). */\nexport function readDenyRules(paths: readonly string[]): string[] {\n if (process.platform === 'win32') return []\n const rules: string[] = []\n for (const raw of paths) {\n if (!expressible(raw)) continue\n const clean = raw.replace(/\\/+$/, '')\n rules.push(`Read(/${clean})`, `Read(/${clean}/**)`)\n }\n return rules\n}\n\n/**\n * The full argument list for one headless run. The prompt goes on STDIN, not\n * as a positional: the variadic `--allowedTools` (and `--mcp-config`) would\n * otherwise swallow a trailing positional (verified on 2.1.220; `cat file |\n * claude -p` is the documented piped form).\n */\nexport function claudeRunArgs(profile: RunProfile, options: ClaudeRunArgOptions = {}): string[] {\n const budget = options.maxBudgetUsd?.trim()\n const deny = readDenyRules(options.denyReadPaths ?? [])\n return [\n '-p',\n '--output-format',\n 'text',\n // A wake run is not a conversation to resume; keep it out of the user's\n // session list and off the disk.\n '--no-session-persistence',\n ...(budget !== undefined && /^\\d+(\\.\\d+)?$/.test(budget) ? ['--max-budget-usd', budget] : []),\n // Variadic, so it is closed by the boolean flag right after it.\n ...(options.mcpConfigPath !== undefined ? ['--mcp-config', options.mcpConfigPath, '--strict-mcp-config'] : []),\n ...claudeProfileArgs(profile),\n // Last: the option is variadic and the prompt arrives on stdin, so there\n // is no positional for it to swallow.\n ...(deny.length > 0 ? ['--disallowedTools', deny.join(',')] : []),\n ]\n}\n\n/** The `--mcp-config` document: the hosted server, by HTTP, with the agent's key. Owner-only on disk. */\nexport function claudeMcpConfig(apiBase: string, apiKey: string): string {\n return `${JSON.stringify(\n { mcpServers: { [CLAUDE_MCP_SERVER_NAME]: { type: 'http', url: hostedMcpUrl(apiBase), headers: { Authorization: `Bearer ${apiKey}` } } } },\n null,\n 2,\n )}\\n`\n}\n\nexport interface ClaudeRunnerOptions {\n readonly configDir: string | undefined\n /**\n * The run's working directory; the `work` profile edits and runs shell here.\n * Must lie outside `denyReadPaths`, or the run cannot read its own cwd —\n * preflight says so once and still runs.\n */\n readonly workdir: string\n readonly profile: RunProfile\n /** Paths every run's file tools are denied: the key store (identity home, the user-scope MCP state). */\n readonly denyReadPaths: readonly string[]\n /** See `ClaudeRunArgOptions.mcpConfigPath`. */\n readonly mcpConfigPath?: string\n /** The one-line fix printed when the workdir sits inside a denied path. */\n readonly workdirAdvice?: string\n /**\n * A deny path no rule can carry (a comma or whitespace in it; every path on\n * Windows): `warn` (default) logs it once and runs — the run can then read\n * that path; `refuse` fails preflight with the reason, so no run starts.\n */\n readonly inexpressibleDeny?: 'warn' | 'refuse'\n /** Test seam: the binary to run. */\n readonly command?: string\n readonly env?: NodeJS.ProcessEnv\n}\n\nexport class ClaudeRunner implements RunRunner {\n readonly name = 'claude'\n private readonly command: string\n /** The workdir warning is one line per process, not one per preflight (preflight repeats every few minutes). */\n private warnedWorkdir = false\n private warnedDeny = false\n\n constructor(private readonly options: ClaudeRunnerOptions) {\n this.command = options.command ?? 'claude'\n }\n\n /** The denied path the configured workdir sits in, or null when the run can read its own cwd. */\n workdirDeniedBy(): string | null {\n return deniedAncestorOf(this.options.workdir, this.options.denyReadPaths)\n }\n\n async preflight(): Promise<RunPreflight> {\n const runtime = inspectClaudeRuntime(this.options.configDir, this.command)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n if (!claudeIsLoggedIn(this.options.configDir, this.command)) {\n return { ok: false, detail: 'claude is not signed in (run `claude` once and sign in)' }\n }\n // A cwd inside the key store is an operator choice the deny rules then\n // make unreadable to the run. Said once, with the fix; the run still\n // starts — the hosted tools do not need the cwd.\n const denied = this.workdirDeniedBy()\n if (denied !== null && !this.warnedWorkdir) {\n this.warnedWorkdir = true\n log.warn(\n `the run workdir ${this.options.workdir} is inside ${denied}, which every run's file tools are denied: runs cannot read their own working directory.${this.options.workdirAdvice ? ` ${this.options.workdirAdvice}` : ''}`,\n )\n }\n const uncovered = inexpressibleDenyPaths(this.options.denyReadPaths)\n if (uncovered.length > 0) {\n const why =\n process.platform === 'win32'\n ? `Claude Code's rule syntax for Windows paths is undocumented, so no read-deny rule is given for ${uncovered.join(', ')}`\n : `no read-deny rule can carry ${uncovered.join(', ')} (a comma or whitespace in the path)`\n if (this.options.inexpressibleDeny === 'refuse') return { ok: false, detail: `${why}: a run could read the key there. Use an identity home whose path has no comma or whitespace (--home).` }\n if (!this.warnedDeny) {\n this.warnedDeny = true\n log.warn(`${why}: runs can read those paths.`)\n }\n }\n if (this.options.mcpConfigPath !== undefined && !fs.existsSync(this.options.mcpConfigPath)) {\n return { ok: false, detail: `the hosted tool config ${this.options.mcpConfigPath} is missing` }\n }\n // Owner-only on creation, as the identity home is. Creation only: an\n // operator's own workspace keeps its permissions.\n fs.mkdirSync(this.options.workdir, { recursive: true, mode: 0o700 })\n return { ok: true }\n }\n\n /** The exact argv one run uses — exported for tests to pin per profile. */\n args(): string[] {\n return claudeRunArgs(this.options.profile, {\n maxBudgetUsd: (this.options.env ?? process.env)['AGENTCHAT_RUN_MAX_BUDGET_USD'],\n denyReadPaths: this.options.denyReadPaths,\n mcpConfigPath: this.options.mcpConfigPath,\n })\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const args = this.args()\n log.debug(`claude ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId})`)\n return spawnRun({\n command: this.command,\n args,\n cwd: this.options.workdir,\n env: buildClaudeEnv(this.options.configDir, this.options.env ?? process.env),\n stdin: request.prompt,\n budgetMs: request.budgetMs,\n // Stopping SIGTERMs this run's process group instead of orphaning it.\n ...(request.signal ? { signal: request.signal } : {}),\n // The engine records a group invite as offered the moment the process\n // has spawned, so a run cut short still counts as the one offer.\n ...(request.onStarted ? { onStarted: request.onStarted } : {}),\n })\n }\n}\n\n/** Where a listener keeps the `--mcp-config` file for this preset, inside its identity home. */\nexport function claudeMcpConfigPath(home: string): string {\n return path.join(home, 'presets', `${CLAUDE_CODE_PRESET}.mcp.json`)\n}\n\nexport const claudeCodePreset: Preset = {\n name: CLAUDE_CODE_PRESET,\n describeMcp({ home, apiBase }) {\n return [\n `--mcp-config ${claudeMcpConfigPath(home)} (owner-only): ${CLAUDE_MCP_SERVER_NAME} → ${hostedMcpUrl(apiBase)}, Authorization: Bearer <this home's key>`,\n '--strict-mcp-config: no other MCP server (user, project or plugin) is loaded in these runs',\n ]\n },\n label: 'Claude Code',\n runtime: 'claude-code',\n // Every run's file tools are denied the identity home.\n serviceEnv: ['CLAUDE_CONFIG_DIR'],\n readsIdentityHome: false,\n inspect(env = process.env, command = 'claude') {\n const configDir = claudeConfigDirFrom(env)\n const runtime = inspectClaudeRuntime(configDir, command)\n if (!runtime.ok) return runtime\n return claudeIsLoggedIn(configDir, command)\n ? { ok: true, detail: `${runtime.detail}, signed in` }\n : { ok: false, detail: `${runtime.detail}, not signed in (run \\`claude\\` once and sign in)` }\n },\n runner(ctx: PresetContext): RunRunner {\n // A key in the listener's own environment is not handed to its runs.\n const env = withoutInheritedKey(ctx.env ?? process.env)\n const configDir = claudeConfigDirFrom(env)\n const mcpConfigPath = claudeMcpConfigPath(ctx.home)\n // Rewritten for every identity the listener serves: the runs act as THIS agent.\n atomicWriteFile(mcpConfigPath, claudeMcpConfig(ctx.apiBase, ctx.apiKey), 0o600)\n return new ClaudeRunner({\n configDir,\n workdir: ctx.workdir,\n profile: ctx.profile,\n // The listener's home (its key and this file), the user-scope MCP state\n // and an integration's identity home beside it: no run reads a key.\n denyReadPaths: [ctx.home, claudeUserStatePathFor(configDir), path.join(claudeHomeFor(configDir), 'agentchat')],\n mcpConfigPath,\n workdirAdvice: 'Start the listener from a directory outside it, or pass --workdir.',\n // On POSIX a listener's run must not start with its key readable; on\n // Windows no rule exists at all (documented), so it warns.\n inexpressibleDeny: process.platform === 'win32' ? 'warn' : 'refuse',\n ...(ctx.command !== undefined ? { command: ctx.command } : {}),\n env,\n })\n },\n}\n","/** `actual` (any text containing `x.y.z`) is at least `minimum`. False when either has no version in it. */\nexport function semverAtLeast(actual: string, minimum: string): boolean {\n const parse = (value: string): [number, number, number] | null => {\n const match = value.match(/(\\d+)\\.(\\d+)\\.(\\d+)/)\n return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null\n }\n const a = parse(actual)\n const b = parse(minimum)\n if (a === null || b === null) return false\n for (let index = 0; index < 3; index++) {\n if (a[index] !== b[index]) return (a[index] ?? 0) > (b[index] ?? 0)\n }\n return true\n}\n","import type { TextsRuntime } from 'agentchatme'\nimport type { RunProfile } from '../integration/profile.js'\nimport type { RunRunner } from '../integration/runner.js'\n\n// ─── Presets: how to start one headless run of a known coding agent ─────────\n//\n// The engine (everything in this package outside `presets/`) names no coding\n// agent and never imports from here; `tests/core-is-host-agnostic`\n// asserts both. A preset is the one place that does: the flags a runtime's\n// headless mode takes per run profile, how to tell it is installed and signed\n// in, and how a run of it reaches the hosted AgentChat tools AS a given agent.\n//\n// Two front doors select one, and only ever for the run command: the\n// `agentchat listen --preset <name>` listener (@agentchatme/cli; its identity\n// is the listener's own home, injected into each run), and the runtime's own\n// integration package (its identity home and placement stay the integration's). A preset\n// never decides which identity home is acted on — the caller passes it.\n\n/** What a preset needs to build a runner acting as one agent. */\nexport interface PresetContext {\n /** The identity home of the agent the runs act as. Runs' file tools are kept off it where the runtime allows. */\n readonly home: string\n /** The run's working directory. */\n readonly workdir: string\n readonly profile: RunProfile\n /** The agent's key and API base, for the hosted tool server the runs reach. Never put on argv. */\n readonly apiKey: string\n readonly apiBase: string\n /** The environment runs inherit (defaults to `process.env`). */\n readonly env?: NodeJS.ProcessEnv\n /** Test seam: the runtime's binary. */\n readonly command?: string\n}\n\nexport interface PresetInspection {\n readonly ok: boolean\n readonly detail: string\n}\n\nexport interface Preset {\n /** The name a user types (`--preset <name>`). */\n readonly name: string\n /** Human name for output. */\n readonly label: string\n /** How the served texts spell the hosted tools for this runtime (`GET /v1/texts?runtime=`). */\n readonly runtime: TextsRuntime\n /** Is the runtime installed, new enough and signed in? For `doctor` and `status`. */\n inspect(env?: NodeJS.ProcessEnv, command?: string): PresetInspection\n /**\n * A runner whose runs act as the agent in `ctx`: the hosted tool server is\n * given to each run with that agent's key (a file or an environment\n * variable, never an argument), whatever the runtime's own configuration\n * registers. May write owner-only files into `ctx.home`.\n */\n runner(ctx: PresetContext): RunRunner\n /**\n * The hosted-tool configuration a listener's run of this preset sees, as\n * lines for `doctor` (keys never printed): what the run is given, and what\n * of the user's own configuration still applies.\n */\n describeMcp(ctx: { readonly home: string; readonly apiBase: string; readonly env?: NodeJS.ProcessEnv }): string[]\n /** Variables a service must capture for this runtime (where it keeps its config, when relocated). */\n readonly serviceEnv: readonly string[]\n /** Whether the run can read files under the identity home (decides how the manual is pointed to). */\n readonly readsIdentityHome: boolean\n}\n\n/** The environment a listener's preset runs inherit: the caller's, minus any `AGENTCHAT_API_KEY` in it. */\nexport function withoutInheritedKey(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const copy = { ...env }\n delete copy['AGENTCHAT_API_KEY']\n return copy\n}\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { hostedMcpUrl } from '../integration/mcp-probe.js'\nimport type { RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, RunRequest, RunRunner } from '../integration/runner.js'\nimport { spawnRun } from '../integration/spawn-run.js'\nimport { log } from '../util/log.js'\nimport { spawnCommandSync } from '../util/spawn.js'\nimport { semverAtLeast } from './semver.js'\nimport { withoutInheritedKey, type Preset, type PresetContext, type PresetInspection } from './types.js'\n\n// ─── Codex: one headless run (`codex exec`) ─────────────────────────────────\n//\n// `codex exec` on the box, riding the user's own Codex sign-in and config. The\n// run's output is discarded by `spawnRun`. Flags, verified against `codex exec\n// --help` (codex-cli 0.154.0) and the openai/codex sources:\n//\n// -s, --sandbox read-only|workspace-write|danger-full-access\n// the sandbox policy for model-generated commands\n// --dangerously-bypass-approvals-and-sandbox\n// skip all confirmation prompts and run unsandboxed\n// -c approval_policy=\"never\" `codex exec` already defaults to `never` in\n// headless mode — passed explicitly so a run can\n// never wait on an approval, whatever a profile\n// or requirements file says.\n// -c mcp_servers.<name>.<key>=… per-run config overrides (TOML values): how a\n// listener points the hosted server at its own\n// agent's key, whatever config.toml registers.\n// --json events as JSONL on stdout (discarded; the first\n// event is how \"started\" is told from \"never got\n// going\")\n// --skip-git-repo-check the run's working directory is not a repository\n// --ephemeral no session files on disk for a wake run\n// -C <dir> the working root\n//\n// The hosted AgentChat tools reach the run through `[mcp_servers.agentchat]`\n// (bearer token from an environment variable named in the config, never the\n// key itself), with `default_tools_approval_mode = \"approve\"` so they never\n// prompt. Web search follows the user's own `web_search` setting.\n\nexport const CODEX_PRESET = 'codex'\n\n/** `--ephemeral`, `--sandbox`, `-C`, `--json` all exist on this version; older builds were not checked. */\nexport const MIN_CODEX_VERSION = '0.154.0'\n\n/** The `[mcp_servers.<name>]` table the runs use; tools are `mcp__agentchat__<tool>`, as the served texts spell them. */\nexport const CODEX_MCP_SERVER_NAME = 'agentchat'\n\n/**\n * The variable a listener's runs read the bearer token from. Deliberately not\n * `AGENTCHAT_API_KEY`: Codex loads `$CODEX_HOME/.env` at startup, where an\n * installed integration keeps ITS agent's key under that name.\n */\nexport const LISTENER_KEY_ENV = 'AGENTCHAT_LISTENER_API_KEY'\n\n/**\n * The final positional argument: `-` tells `codex exec` to read its\n * instructions from stdin (\"If not provided as an argument (or if `-` is\n * used), instructions are read from stdin\").\n */\nexport const CODEX_PROMPT_FROM_STDIN = '-'\n\n/** Codex's config root. Honouring CODEX_HOME matters: users relocate it. */\nexport function codexHomeFrom(env: NodeJS.ProcessEnv = process.env): string {\n const override = env['CODEX_HOME']\n if (override !== undefined && override.trim().length > 0) return path.resolve(override)\n return path.join(os.homedir(), '.codex')\n}\n\nexport function inspectCodexRuntime(codexHome: string, command = 'codex'): PresetInspection {\n const result = spawnCommandSync(command, ['--version'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: { ...process.env, CODEX_HOME: codexHome },\n })\n if (result.error) return { ok: false, detail: `codex CLI not found on PATH (${result.error.message})` }\n const rendered = String(result.stdout || result.stderr).trim()\n if (result.status !== 0) return { ok: false, detail: rendered || `codex --version exited ${result.status}` }\n return semverAtLeast(rendered, MIN_CODEX_VERSION)\n ? { ok: true, detail: rendered }\n : { ok: false, detail: `${rendered || 'unrecognized version'}; AgentChat requires Codex >= ${MIN_CODEX_VERSION}` }\n}\n\n/** `codex login status` exits 0 when signed in. */\nexport function codexIsLoggedIn(codexHome: string, command = 'codex'): PresetInspection {\n const status = spawnCommandSync(command, ['login', 'status'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: { ...process.env, CODEX_HOME: codexHome },\n })\n if (status.error) return { ok: false, detail: status.error.message }\n const detail = `${status.stdout ?? ''}${status.stderr ?? ''}`.trim().slice(0, 200)\n return status.status === 0 ? { ok: true, detail: detail || 'signed in' } : { ok: false, detail: detail || 'codex is not signed in (run `codex login`)' }\n}\n\nexport function codexProfileArgs(profile: RunProfile): string[] {\n switch (profile) {\n case 'answer':\n return ['--sandbox', 'read-only', '-c', 'approval_policy=\"never\"']\n case 'work':\n return ['--sandbox', 'workspace-write', '-c', 'approval_policy=\"never\"']\n case 'full':\n return ['--dangerously-bypass-approvals-and-sandbox']\n }\n}\n\n/** Where a run's hosted tool server points, and which variable carries its bearer token. */\nexport interface CodexMcpOverride {\n readonly url: string\n readonly keyEnv: string\n}\n\n/** The `-c` overrides that make `[mcp_servers.agentchat]` this agent's, for one run. TOML values, no key in them. */\nexport function codexMcpOverrideArgs(override: CodexMcpOverride): string[] {\n const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`\n return [\n '-c',\n `${table}.url=${JSON.stringify(override.url)}`,\n '-c',\n `${table}.bearer_token_env_var=${JSON.stringify(override.keyEnv)}`,\n '-c',\n `${table}.default_tools_approval_mode=\"approve\"`,\n ]\n}\n\n/**\n * The full argument list for one headless run. The prompt is NOT an argument:\n * the runner writes it to stdin and closes it. An argument cannot carry it on\n * Windows — npm installs codex as a `.cmd` shim, cross-spawn runs that through\n * cmd.exe, and cmd.exe ends the command at the first line break, so every line\n * after the first was silently dropped (caught by CI on windows-latest).\n */\nexport function codexRunArgs(profile: RunProfile, options: { workdir: string; mcp?: CodexMcpOverride }): string[] {\n return [\n 'exec',\n '--json',\n '--skip-git-repo-check',\n '--ephemeral',\n '-C',\n options.workdir,\n ...codexProfileArgs(profile),\n ...(options.mcp !== undefined ? codexMcpOverrideArgs(options.mcp) : []),\n CODEX_PROMPT_FROM_STDIN,\n ]\n}\n\nexport interface CodexRunnerOptions {\n readonly codexHome: string\n /** The run's working root (`-C`); the `work` profile may write here. */\n readonly workdir: string\n readonly profile: RunProfile\n /** The agent's key, read per run (a credential change between runs is followed). Null: none is set. */\n readonly apiKey: () => string | null\n /** The variable the key is set under in the run's environment. */\n readonly keyEnv: string\n /** Point the hosted server at this agent for each run (`-c` overrides); absent, config.toml decides. */\n readonly mcp?: CodexMcpOverride\n /** Test seam: the binary to run. */\n readonly command?: string\n readonly env?: NodeJS.ProcessEnv\n}\n\nexport class CodexRunner implements RunRunner {\n readonly name = 'codex'\n private readonly command: string\n\n constructor(private readonly options: CodexRunnerOptions) {\n this.command = options.command ?? 'codex'\n }\n\n async preflight(): Promise<RunPreflight> {\n const runtime = inspectCodexRuntime(this.options.codexHome, this.command)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n const auth = codexIsLoggedIn(this.options.codexHome, this.command)\n if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` }\n fs.mkdirSync(this.options.workdir, { recursive: true })\n return { ok: true }\n }\n\n /** The exact argv one run uses — exported for tests to pin per profile. */\n args(): string[] {\n return codexRunArgs(this.options.profile, { workdir: this.options.workdir, ...(this.options.mcp !== undefined ? { mcp: this.options.mcp } : {}) })\n }\n\n /** The child environment: Codex's home and the key the hosted server needs, under the configured name. */\n env(): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = { ...(this.options.env ?? process.env), CODEX_HOME: this.options.codexHome }\n const key = this.options.apiKey()\n if (key !== null) env[this.options.keyEnv] = key\n return env\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const args = this.args()\n log.debug(`codex ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId})`)\n return spawnRun({\n command: this.command,\n args,\n cwd: this.options.workdir,\n env: this.env(),\n // Written to stdin and then closed: `codex exec -` reads its\n // instructions until EOF. Never as an argument (see codexRunArgs).\n stdin: request.prompt,\n budgetMs: request.budgetMs,\n ...(request.signal ? { signal: request.signal } : {}),\n ...(request.onStarted ? { onStarted: request.onStarted } : {}),\n })\n }\n}\n\n/**\n * The keys of `[mcp_servers.agentchat]` in a config.toml, or null when the\n * table is absent. Keys only — a value can be a secret. A line scan, not a\n * TOML parser: enough to say what a run's `-c` overrides merge over.\n */\nexport function agentchatTableKeys(configToml: string): string[] | null {\n const lines = configToml.split(/\\r?\\n/)\n const header = new RegExp(`^\\\\s*\\\\[mcp_servers\\\\.${CODEX_MCP_SERVER_NAME}\\\\]\\\\s*(#.*)?$`)\n const start = lines.findIndex((line) => header.test(line))\n if (start < 0) return null\n const keys: string[] = []\n for (const line of lines.slice(start + 1)) {\n if (/^\\s*\\[/.test(line)) break\n const match = /^\\s*([A-Za-z0-9_.-]+)\\s*=/.exec(line)\n if (match?.[1] !== undefined) keys.push(match[1])\n }\n return keys\n}\n\nexport const codexPreset: Preset = {\n name: CODEX_PRESET,\n describeMcp({ apiBase, env = process.env }) {\n const file = path.join(codexHomeFrom(env), 'config.toml')\n let own: string[] | null = null\n try {\n own = agentchatTableKeys(fs.readFileSync(file, 'utf-8'))\n } catch {\n own = null\n }\n return [\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.url=\"${hostedMcpUrl(apiBase)}\"`,\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.bearer_token_env_var=\"${LISTENER_KEY_ENV}\" (the key set in the run's environment, never on argv)`,\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.default_tools_approval_mode=\"approve\"`,\n own === null\n ? `${file}: no [mcp_servers.${CODEX_MCP_SERVER_NAME}] of its own — the run sees only the overrides above`\n : `${file}: [mcp_servers.${CODEX_MCP_SERVER_NAME}] also sets ${own.length > 0 ? own.join(', ') : 'nothing'}; the overrides above replace their keys, the others still apply (how codex merges -c over an existing table is not verified on a real codex)`,\n ]\n },\n label: 'Codex',\n runtime: 'codex',\n // A read-only sandbox reads the whole filesystem.\n serviceEnv: ['CODEX_HOME'],\n readsIdentityHome: true,\n inspect(env = process.env, command = 'codex') {\n const home = codexHomeFrom(env)\n const runtime = inspectCodexRuntime(home, command)\n if (!runtime.ok) return runtime\n const auth = codexIsLoggedIn(home, command)\n return auth.ok ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in: ${auth.detail}` }\n },\n runner(ctx: PresetContext): RunRunner {\n // A key in the listener's own environment is not handed to its runs.\n const env = withoutInheritedKey(ctx.env ?? process.env)\n const apiKey = ctx.apiKey\n return new CodexRunner({\n codexHome: codexHomeFrom(env),\n workdir: ctx.workdir,\n profile: ctx.profile,\n apiKey: () => apiKey,\n keyEnv: LISTENER_KEY_ENV,\n mcp: { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV },\n ...(ctx.command !== undefined ? { command: ctx.command } : {}),\n env,\n })\n },\n}\n","// ─── @agentchatme/agent-core/presets ────────────────────────────────────────\n//\n// How to start one headless run of a known coding agent, shared by the\n// `agentchat listen --preset <name>` listener and each runtime's own\n// integration package (one copy of the flags, never two). The only module of\n// this package that names a coding agent; the engine never imports it.\n\nimport { claudeCodePreset } from './claude-code.js'\nimport { codexPreset } from './codex.js'\nimport type { Preset } from './types.js'\n\nexport type { Preset, PresetContext, PresetInspection } from './types.js'\nexport { semverAtLeast } from './semver.js'\nexport {\n CLAUDE_CODE_PRESET,\n MIN_CLAUDE_CODE_VERSION,\n CLAUDE_MCP_SERVER_NAME,\n AGENTCHAT_TOOL_ALLOW,\n ANSWER_TOOLS,\n WORK_TOOLS,\n PARENT_ENV_KEYS,\n claudeConfigDirFrom,\n claudeHomeFor,\n claudeUserStatePathFor,\n buildClaudeEnv,\n claudeIsLoggedIn,\n inspectClaudeRuntime,\n deniedAncestorOf,\n claudeProfileArgs,\n readDenyRules,\n inexpressibleDenyPaths,\n claudeRunArgs,\n claudeMcpConfig,\n claudeMcpConfigPath,\n ClaudeRunner,\n claudeCodePreset,\n type ClaudeRunArgOptions,\n type ClaudeRunnerOptions,\n} from './claude-code.js'\nexport {\n CODEX_PRESET,\n MIN_CODEX_VERSION,\n CODEX_MCP_SERVER_NAME,\n LISTENER_KEY_ENV,\n CODEX_PROMPT_FROM_STDIN,\n codexHomeFrom,\n inspectCodexRuntime,\n codexIsLoggedIn,\n codexProfileArgs,\n codexMcpOverrideArgs,\n codexRunArgs,\n agentchatTableKeys,\n CodexRunner,\n codexPreset,\n type CodexMcpOverride,\n type CodexRunnerOptions,\n} from './codex.js'\n\n/** Every preset, by the name a user types. */\nexport const PRESETS: Readonly<Record<string, Preset>> = Object.freeze({\n [claudeCodePreset.name]: claudeCodePreset,\n [codexPreset.name]: codexPreset,\n})\n\nexport function presetNamed(name: string): Preset | null {\n return Object.prototype.hasOwnProperty.call(PRESETS, name) ? (PRESETS[name] ?? null) : null\n}\n\nexport function presetNames(): string[] {\n return Object.keys(PRESETS)\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,YAAY,QAAQ;AACpB,YAAY,QAAQ;AACpB,YAAY,UAAU;;;ACDf,SAAS,cAAc,QAAgB,SAA0B;AACtE,QAAM,QAAQ,CAAC,UAAmD;AAChE,UAAM,QAAQ,MAAM,MAAM,qBAAqB;AAC/C,WAAO,QAAQ,CAAC,OAAO,MAAM,CAAC,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,CAAC,IAAI;AA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