@agentchatme/agent-core 0.5.2 → 0.6.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
@@ -2,7 +2,7 @@ import {
2
2
  VERSION,
3
3
  hostedMcpUrl,
4
4
  runProbe
5
- } from "./chunk-WDHXWAWF.js";
5
+ } from "./chunk-QUANHUVW.js";
6
6
  import {
7
7
  atomicWriteFile,
8
8
  clientHeadersOf,
@@ -12,7 +12,7 @@ import {
12
12
  spawnCommand,
13
13
  spawnRun,
14
14
  workdirExposesHome
15
- } from "./chunk-AFDD53DD.js";
15
+ } from "./chunk-AVLI55C5.js";
16
16
 
17
17
  // src/presets/claude-code.ts
18
18
  import * as fs from "fs";
@@ -301,6 +301,10 @@ function workdirReadRules(workdir) {
301
301
  }
302
302
  function claudeProfileArgs(profile, workdir) {
303
303
  switch (profile) {
304
+ // The agent itself: the user's own settings decide; AgentChat's tools are
305
+ // pre-approved and nothing waits on a prompt (see the header).
306
+ case "own":
307
+ return ["--permission-prompts", "none", "--allowedTools", AGENTCHAT_TOOL_ALLOW];
304
308
  case "answer":
305
309
  return [
306
310
  "--permission-mode",
@@ -356,8 +360,9 @@ function claudeRunArgs(profile, options = {}) {
356
360
  // session list and off the disk.
357
361
  "--no-session-persistence",
358
362
  ...budget !== void 0 && /^\d+(\.\d+)?$/.test(budget) ? ["--max-budget-usd", budget] : [],
359
- // Variadic, so it is closed by the boolean flag right after it.
360
- ...options.mcpConfigPath !== void 0 ? ["--mcp-config", options.mcpConfigPath, "--strict-mcp-config"] : [],
363
+ // Variadic, so it is closed by the option right after it. `own` keeps the
364
+ // user's other servers: the file's `agentchat` wins over theirs by name.
365
+ ...options.mcpConfigPath !== void 0 ? ["--mcp-config", options.mcpConfigPath, ...profile === "own" ? [] : ["--strict-mcp-config"]] : [],
361
366
  ...options.appendSystemPromptFile !== void 0 ? ["--append-system-prompt-file", options.appendSystemPromptFile] : [],
362
367
  ...claudeProfileArgs(profile, options.workdir),
363
368
  // Last: the option is variadic and the prompt arrives on stdin, so there
@@ -433,6 +438,9 @@ function extraDirectoriesRefusal(grant) {
433
438
  function claudeAnswerFallbackWorkdir(configDirOverride) {
434
439
  return path.join(claudeHomeFor(configDirOverride), "agentchat-answer-workdir");
435
440
  }
441
+ function guardsHomeWorkdir(profile) {
442
+ return profile === "answer" || profile === "own";
443
+ }
436
444
  var ClaudeRunner = class _ClaudeRunner {
437
445
  constructor(options) {
438
446
  this.options = options;
@@ -440,6 +448,7 @@ var ClaudeRunner = class _ClaudeRunner {
440
448
  }
441
449
  options;
442
450
  name = "claude";
451
+ label = "Claude Code";
443
452
  command;
444
453
  /** The workdir warning is one line per process, not one per preflight (preflight repeats every few minutes). */
445
454
  warnedWorkdir = false;
@@ -447,11 +456,11 @@ var ClaudeRunner = class _ClaudeRunner {
447
456
  warnedHome = false;
448
457
  /**
449
458
  * 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
459
+ * `own` or `answer` run never works in the home folder or above it — it gets
451
460
  * `claudeAnswerFallbackWorkdir` (its readable folder would be the whole home).
452
461
  */
453
462
  workdir() {
454
- if (this.options.profile === "answer" && workdirExposesHome(this.options.workdir)) return claudeAnswerFallbackWorkdir(this.options.configDir);
463
+ if (guardsHomeWorkdir(this.options.profile) && workdirExposesHome(this.options.workdir)) return claudeAnswerFallbackWorkdir(this.options.configDir);
455
464
  return this.options.workdir;
456
465
  }
457
466
  /** The denied path the workdir sits in, or null when the run can read its own cwd. */
@@ -479,7 +488,7 @@ var ClaudeRunner = class _ClaudeRunner {
479
488
  }
480
489
  if (this.workdir() !== this.options.workdir && !this.warnedHome) {
481
490
  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.`);
491
+ log.warn(`the run workdir ${this.options.workdir} is your home folder or contains it: ${this.options.profile} runs work in ${this.workdir()} instead, so a peer-started run reads none of your files there. Point the workdir at a folder of its own to choose another.`);
483
492
  }
484
493
  const denied = this.workdirDeniedBy();
485
494
  if (denied !== null && !this.warnedWorkdir) {
@@ -509,12 +518,17 @@ var ClaudeRunner = class _ClaudeRunner {
509
518
  const id = runId.replace(/[^A-Za-z0-9-]/g, "").slice(0, 64) || "run";
510
519
  return path.join(path.dirname(file), `${stem}.${id}${ext}`);
511
520
  }
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 {};
521
+ /**
522
+ * A run's own files for `runId`: an answer run's AgentChat-only tool config
523
+ * (integration path), and the identity-line file of an answer or own run.
524
+ * `work` and `full` write none (they load CLAUDE.md, as before).
525
+ */
526
+ runFiles(runId) {
527
+ const profile = this.options.profile;
528
+ if (profile !== "answer" && profile !== "own") return {};
515
529
  const base = this.options.mcpConfigPath ?? this.options.answerMcp?.file;
516
530
  return {
517
- ...this.options.mcpConfigPath === void 0 && this.options.answerMcp !== void 0 ? { mcpConfigPath: _ClaudeRunner.perRun(this.options.answerMcp.file, runId, ".json") } : {},
531
+ ...profile === "answer" && this.options.mcpConfigPath === void 0 && this.options.answerMcp !== void 0 ? { mcpConfigPath: _ClaudeRunner.perRun(this.options.answerMcp.file, runId, ".json") } : {},
518
532
  ...base !== void 0 ? { identityFile: _ClaudeRunner.perRun(base, runId, ".identity.md") } : {}
519
533
  };
520
534
  }
@@ -540,20 +554,27 @@ var ClaudeRunner = class _ClaudeRunner {
540
554
  }
541
555
  /**
542
556
  * 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.
557
+ * that run's own files (an answer run's tool config, an answer or own run's
558
+ * identity-line file); without, the configured `answerMcp.file` stands in
559
+ * for an answer run's tool config, and no identity file.
545
560
  */
546
561
  args(runId, identityLine) {
547
562
  if (runId === void 0) {
548
563
  const mcpConfigPath = this.options.mcpConfigPath ?? (this.options.profile === "answer" ? this.options.answerMcp?.file : void 0);
549
564
  return this.argsFor(mcpConfigPath, void 0);
550
565
  }
551
- const files = this.answerRunFiles(runId);
566
+ const files = this.runFiles(runId);
552
567
  return this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityLine === true ? files.identityFile : void 0);
553
568
  }
554
- /** The run's environment: no parent session; an answer run loads no CLAUDE.md and no auto memory (`ANSWER_ENV`). */
569
+ /**
570
+ * The run's environment: no parent session; an answer run loads no CLAUDE.md
571
+ * and no auto memory (`ANSWER_ENV`); an own run carries no `AGENTCHAT_API_KEY`
572
+ * the daemon inherited — it has the user's own shell, and it reaches the
573
+ * hosted tools through its MCP entry, never through that variable.
574
+ */
555
575
  runEnv() {
556
- const env = buildClaudeEnv(this.options.configDir, this.options.env ?? process.env);
576
+ const source = this.options.env ?? process.env;
577
+ const env = buildClaudeEnv(this.options.configDir, this.options.profile === "own" ? withoutInheritedKey(source) : source);
557
578
  return this.options.profile === "answer" ? { ...env, ...ANSWER_ENV } : env;
558
579
  }
559
580
  async start(request) {
@@ -568,8 +589,8 @@ var ClaudeRunner = class _ClaudeRunner {
568
589
  const grant = claudeExtraDirectoriesGrant(this.options.configDir, this.workdir());
569
590
  if (grant !== null) return notStarted(extraDirectoriesRefusal(grant));
570
591
  }
571
- const files = this.answerRunFiles(request.runId);
572
- const identityFile = answer && request.identityLine !== void 0 ? files.identityFile : void 0;
592
+ const files = this.runFiles(request.runId);
593
+ const identityFile = request.identityLine !== void 0 ? files.identityFile : void 0;
573
594
  const written = [];
574
595
  const cleanup = () => {
575
596
  for (const file of written) fs.rmSync(file, { force: true });
@@ -592,7 +613,7 @@ var ClaudeRunner = class _ClaudeRunner {
592
613
  written.push(identityFile);
593
614
  } catch (err) {
594
615
  cleanup();
595
- return notStarted(`could not write the answer run's identity line ${identityFile}: ${err instanceof Error ? err.message : String(err)}`);
616
+ return notStarted(`could not write the run's identity line ${identityFile}: ${err instanceof Error ? err.message : String(err)}`);
596
617
  }
597
618
  }
598
619
  try {
@@ -621,10 +642,10 @@ function claudeMcpConfigPath(home) {
621
642
  }
622
643
  var claudeCodePreset = {
623
644
  name: CLAUDE_CODE_PRESET,
624
- describeMcp({ home, apiBase }) {
645
+ describeMcp({ home, apiBase, profile }) {
625
646
  return [
626
647
  `--mcp-config ${claudeMcpConfigPath(home)} (owner-only): ${CLAUDE_MCP_SERVER_NAME} \u2192 ${hostedMcpUrl(apiBase)}, Authorization: Bearer <this home's key>, X-AgentChat-Client: claude-code`,
627
- "--strict-mcp-config: no other MCP server (user, project or plugin) is loaded in these runs"
648
+ profile === "own" ? `own: your other MCP servers load too (the file is not made the only one); this file's ${CLAUDE_MCP_SERVER_NAME} is used in place of a user-scope ${CLAUDE_MCP_SERVER_NAME} (verified); a project- or local-scope one is not covered` : "--strict-mcp-config: no other MCP server (user, project or plugin) is loaded in these runs"
628
649
  ];
629
650
  },
630
651
  label: "Claude Code",
@@ -709,6 +730,9 @@ var CODEX_ANSWER_DISABLED_FEATURES = [
709
730
  ];
710
731
  function codexProfileArgs(profile) {
711
732
  switch (profile) {
733
+ // The agent itself: nothing but the run's shape (see the header).
734
+ case "own":
735
+ return [];
712
736
  case "answer":
713
737
  return [
714
738
  "-c",
@@ -747,7 +771,7 @@ function codexMcpOverrideArgs(override) {
747
771
  "-c",
748
772
  `${table}.url=${JSON.stringify(override.url)}`,
749
773
  "-c",
750
- `${table}.bearer_token_env_var=${JSON.stringify(override.keyEnv)}`,
774
+ override.headersHelper !== void 0 ? `${table}.http_headers_helper=${JSON.stringify(override.headersHelper)}` : `${table}.bearer_token_env_var=${JSON.stringify(override.keyEnv)}`,
751
775
  "-c",
752
776
  `${table}.default_tools_approval_mode="approve"`,
753
777
  "-c",
@@ -793,6 +817,31 @@ function parseCodexMcpList(stdout) {
793
817
  }
794
818
  return { ok: true, names };
795
819
  }
820
+ function codexAgentchatExplicitAuth(stdout) {
821
+ let parsed;
822
+ try {
823
+ parsed = JSON.parse(stdout);
824
+ } catch {
825
+ return { ok: false, detail: "its output is not JSON" };
826
+ }
827
+ if (!Array.isArray(parsed)) return { ok: false, detail: "its output is not a list" };
828
+ const entry = parsed.find((e) => e?.name === CODEX_MCP_SERVER_NAME);
829
+ const transport = entry?.transport !== null && typeof entry?.transport === "object" ? entry.transport : {};
830
+ const keys = [];
831
+ const bearer = transport["bearer_token_env_var"];
832
+ if (typeof bearer === "string" && bearer.length > 0) keys.push("bearer_token_env_var");
833
+ const envHeaders = transport["env_http_headers"];
834
+ if (envHeaders !== null && typeof envHeaders === "object" && Object.keys(envHeaders).some((name) => name.toLowerCase() === "authorization")) keys.push("env_http_headers.Authorization");
835
+ return { ok: true, keys };
836
+ }
837
+ function codexDotEnvKeyNames(content) {
838
+ const names = /* @__PURE__ */ new Set();
839
+ for (const line of content.split(/\r?\n/)) {
840
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*['"]?\S/.exec(line);
841
+ if (match?.[1] === "AGENTCHAT_API_KEY" || match?.[1] === LISTENER_KEY_ENV) names.add(match[1]);
842
+ }
843
+ return [...names];
844
+ }
796
845
  function codexMcpDisableArgs(names) {
797
846
  const args = [];
798
847
  for (const name of names) {
@@ -849,33 +898,39 @@ var CodexRunner = class {
849
898
  }
850
899
  options;
851
900
  name = "codex";
901
+ label = "Codex";
852
902
  command;
853
903
  warnedHome = false;
854
904
  /** 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
905
  listing = null;
906
+ /** The last listing that showed a listener's own run authenticates with its helper alone (`ownAuthProblem`). */
907
+ ownListing = null;
856
908
  /**
857
909
  * 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`.
910
+ * `own` or `answer` run never has the home folder or above it as its
911
+ * workspace root — it gets `codexAnswerFallbackWorkdir`.
860
912
  */
861
913
  workdir() {
862
- if (this.options.profile === "answer" && workdirExposesHome(this.options.workdir)) return codexAnswerFallbackWorkdir(this.options.codexHome);
914
+ if ((this.options.profile === "answer" || this.options.profile === "own") && workdirExposesHome(this.options.workdir)) return codexAnswerFallbackWorkdir(this.options.codexHome);
863
915
  return this.options.workdir;
864
916
  }
865
917
  async preflight(options = {}) {
918
+ if (this.options.refuse !== void 0) return { ok: false, detail: this.options.refuse };
866
919
  const runtime = await inspectCodexRuntime(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal);
867
920
  if (!runtime.ok) return { ok: false, detail: runtime.detail };
868
921
  const auth = await codexIsLoggedIn(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal);
869
922
  if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` };
870
923
  if (this.workdir() !== this.options.workdir && !this.warnedHome) {
871
924
  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.`);
925
+ log.warn(`the run workdir ${this.options.workdir} is your home folder or contains it: ${this.options.profile} runs work in ${this.workdir()} instead, so a peer-started run reaches none of your files there. Point the workdir at a folder of its own to choose another.`);
873
926
  }
874
927
  fs2.mkdirSync(this.workdir(), { recursive: true });
875
928
  if (this.options.profile === "answer") {
876
929
  const disables = await this.answerMcpDisables();
877
930
  if (!disables.ok) return { ok: false, detail: codexAnswerListingRefusal(disables.detail) };
878
931
  }
932
+ const ownProblem = await this.ownAuthProblem();
933
+ if (ownProblem !== null) return { ok: false, detail: ownProblem };
879
934
  return { ok: true };
880
935
  }
881
936
  /** The exact argv one run uses — exported for tests to pin per profile. An `answer` run adds `answerMcpDisables()` before the prompt. */
@@ -884,9 +939,20 @@ var CodexRunner = class {
884
939
  if (this.options.mcp !== void 0 || this.options.pinMcpUrl === void 0) return args;
885
940
  return [...args.slice(0, -1), ...codexPinnedUrlArgs(this.options.pinMcpUrl), CODEX_PROMPT_FROM_STDIN];
886
941
  }
887
- /** The child environment: Codex's home and the key the hosted server needs, under the configured name. */
942
+ /**
943
+ * The child environment: Codex's home and the key the hosted server needs,
944
+ * under the configured name. An `own` run gets no key at all — not the
945
+ * configured one, not an `AGENTCHAT_API_KEY` the daemon inherited: it has
946
+ * the user's own shell, and Codex hands a run's commands its environment.
947
+ * Its hosted server authenticates through a headers helper instead.
948
+ */
888
949
  env() {
889
950
  const env = { ...withoutParentSession(this.options.env ?? process.env), CODEX_HOME: this.options.codexHome };
951
+ if (this.options.profile === "own") {
952
+ delete env["AGENTCHAT_API_KEY"];
953
+ delete env[this.options.keyEnv];
954
+ return env;
955
+ }
890
956
  const key = this.options.apiKey();
891
957
  if (key !== null) env[this.options.keyEnv] = key;
892
958
  return env;
@@ -901,11 +967,62 @@ var CodexRunner = class {
901
967
  * an error, a timeout, output that is not the list — means no run.
902
968
  */
903
969
  async answerMcpDisables() {
970
+ const { flags, key } = this.listingFlags();
971
+ if (this.listing !== null && this.listing.key === key && Date.now() - this.listing.at < CODEX_MCP_LIST_MAX_AGE_MS) return this.listing.result;
972
+ const listed = await this.listMcpServers(flags);
973
+ if (!listed.ok) return listed;
974
+ const parsed = parseCodexMcpList(listed.stdout);
975
+ if (!parsed.ok) return parsed;
976
+ const result = codexMcpDisableArgs(parsed.names);
977
+ if (result.ok) this.listing = { key, at: Date.now(), result };
978
+ return result;
979
+ }
980
+ /**
981
+ * For a listener's `own` run (its key from a headers helper, none in its
982
+ * environment): why it must not start, or null. Two things would make it
983
+ * carry or use a key that is not the helper's — another agent's, as a
984
+ * Codex integration from 0.5.2 or earlier left them: `$CODEX_HOME/.env`
985
+ * setting a key variable (Codex loads it into the run's environment), and an
986
+ * `agentchat` entry that names `bearer_token_env_var` or an `Authorization`
987
+ * in `env_http_headers` in any config layer (Codex sends that in place of the
988
+ * helper's: the run would act as that other agent). The entry is asked of
989
+ * Codex itself (`codex mcp list --json` with the run's own flags, cached as
990
+ * an answer run's listing is); a listing that fails means no run.
991
+ */
992
+ async ownAuthProblem() {
993
+ if (this.options.profile !== "own" || this.options.mcp?.headersHelper === void 0) return null;
994
+ const dotenv = path2.join(this.options.codexHome, ".env");
995
+ let names = [];
996
+ try {
997
+ names = codexDotEnvKeyNames(fs2.readFileSync(dotenv, "utf-8"));
998
+ } catch {
999
+ names = [];
1000
+ }
1001
+ if (names.length > 0) {
1002
+ return `${dotenv} sets ${names.join(" and ")}: Codex loads that file into every run's environment, so this listener's own runs would carry that key. An AgentChat Codex integration from 0.5.2 or earlier left it there (\`npx -y @agentchatme/codex doctor --fix\` takes it out); remove the line, or run this listener with --profile answer`;
1003
+ }
1004
+ const { flags, key } = this.listingFlags();
1005
+ if (this.ownListing !== null && this.ownListing.key === key && Date.now() - this.ownListing.at < CODEX_MCP_LIST_MAX_AGE_MS) return null;
1006
+ const listed = await this.listMcpServers(flags);
1007
+ const auth = listed.ok ? codexAgentchatExplicitAuth(listed.stdout) : listed;
1008
+ if (!auth.ok) {
1009
+ return `could not list Codex's MCP servers (\`codex mcp list --json\` with the own run's flags: ${auth.detail}); a listener's own run starts only once Codex confirms its ${CODEX_MCP_SERVER_NAME} server sends this listener's key`;
1010
+ }
1011
+ if (auth.keys.length > 0) {
1012
+ return `the [mcp_servers.${CODEX_MCP_SERVER_NAME}] Codex loads for these runs sets ${auth.keys.join(" and ")}: Codex sends that credential in place of this listener's headers helper, so its own runs would act as another agent. An AgentChat Codex integration from 0.5.2 or earlier wrote bearer_token_env_var (\`npx -y @agentchatme/codex doctor --fix\` replaces it); remove it, or run this listener with --profile answer`;
1013
+ }
1014
+ this.ownListing = { key, at: Date.now() };
1015
+ return null;
1016
+ }
1017
+ /** The run's config flags (`-c <v>` and `--disable <feature>` pairs) and what a listing of them depends on. */
1018
+ listingFlags() {
904
1019
  const run = this.args();
905
1020
  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) => {
1021
+ return { flags, key: codexListingKey(codexConfigLayerFiles(this.options.codexHome, this.workdir()), [this.command, this.workdir(), ...flags]) };
1022
+ }
1023
+ /** `codex mcp list --json <flags>` from the run's workdir, with the run's environment: its output, or why there is none. Killed with its whole tree past its time. */
1024
+ async listMcpServers(flags) {
1025
+ return new Promise((resolve3) => {
909
1026
  let child;
910
1027
  try {
911
1028
  child = spawnCommand(this.command, ["mcp", "list", "--json", ...flags], {
@@ -927,12 +1044,12 @@ var CodexRunner = class {
927
1044
  let stopped = null;
928
1045
  let settled = false;
929
1046
  let abandonTimer = null;
930
- const settle = (result2) => {
1047
+ const settle = (result) => {
931
1048
  if (settled) return;
932
1049
  settled = true;
933
1050
  clearTimeout(timer);
934
1051
  if (abandonTimer !== null) clearTimeout(abandonTimer);
935
- resolve3(result2);
1052
+ resolve3(result);
936
1053
  };
937
1054
  const stop = (why) => {
938
1055
  if (stopped !== null) return;
@@ -962,21 +1079,18 @@ var CodexRunner = class {
962
1079
  else settle({ ok: true, stdout });
963
1080
  });
964
1081
  });
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
1082
  }
972
1083
  async start(request) {
973
1084
  const startedAt = Date.now();
1085
+ if (this.options.refuse !== void 0) return { state: "not_started", exitCode: null, durationMs: 0, detail: this.options.refuse };
974
1086
  let args = this.args();
975
1087
  if (this.options.profile === "answer") {
976
1088
  const disables = await this.answerMcpDisables();
977
1089
  if (!disables.ok) return { state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail: codexAnswerListingRefusal(disables.detail) };
978
1090
  args = [...args.slice(0, -1), ...disables.args, CODEX_PROMPT_FROM_STDIN];
979
1091
  }
1092
+ const ownProblem = await this.ownAuthProblem();
1093
+ if (ownProblem !== null) return { state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail: ownProblem };
980
1094
  log.debug(`codex ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
981
1095
  return spawnRun({
982
1096
  command: this.command,
@@ -992,6 +1106,31 @@ var CodexRunner = class {
992
1106
  });
993
1107
  }
994
1108
  };
1109
+ function codexListenerHeadersHelperPath(home) {
1110
+ return path2.join(home, "presets", `${CODEX_PRESET}.mcp-headers.mjs`);
1111
+ }
1112
+ var CODEX_LISTENER_HEADERS_HELPER_SOURCE = [
1113
+ "// Written by @agentchatme/agent-core for a listener's Codex runs. Codex runs this on each",
1114
+ '// connection to the MCP server "agentchat" (its http_headers_helper) and sends what it prints',
1115
+ "// as headers: the Authorization header for the key in the credentials file of this identity",
1116
+ "// home, or nothing when there is none. It reads no environment variable. Do not edit: the",
1117
+ "// listener rewrites it.",
1118
+ "import { readFileSync } from 'node:fs'",
1119
+ "let headers = {}",
1120
+ "try {",
1121
+ " const creds = JSON.parse(readFileSync(new URL('../credentials', import.meta.url), 'utf8'))",
1122
+ " const key = creds !== null && typeof creds.api_key === 'string' ? creds.api_key.trim() : ''",
1123
+ " if (key.length >= 20 && !/\\s/.test(key)) headers = { Authorization: `Bearer ${key}` }",
1124
+ "} catch {}",
1125
+ "process.stdout.write(JSON.stringify(headers))",
1126
+ ""
1127
+ ].join("\n");
1128
+ function codexHeadersHelperCommand(script, node = process.execPath, platform = process.platform) {
1129
+ const paths = [node, script];
1130
+ if (paths.some((p) => /[\r\n]/.test(p))) return null;
1131
+ if (platform === "win32") return paths.some((p) => /["%$`]/.test(p)) ? null : paths.map((p) => `"${p}"`).join(" ");
1132
+ return paths.map((p) => `'${p.replace(/'/g, `'\\''`)}'`).join(" ");
1133
+ }
995
1134
  function agentchatTableKeys(configToml) {
996
1135
  const lines = configToml.split(/\r?\n/);
997
1136
  const header = new RegExp(`^\\s*\\[mcp_servers\\.${CODEX_MCP_SERVER_NAME}\\]\\s*(#.*)?$`);
@@ -1007,7 +1146,7 @@ function agentchatTableKeys(configToml) {
1007
1146
  }
1008
1147
  var codexPreset = {
1009
1148
  name: CODEX_PRESET,
1010
- describeMcp({ apiBase, env = process.env }) {
1149
+ describeMcp({ home, apiBase, env = process.env, profile }) {
1011
1150
  const file = path2.join(codexHomeFrom(env), "config.toml");
1012
1151
  let own = null;
1013
1152
  try {
@@ -1017,7 +1156,7 @@ var codexPreset = {
1017
1156
  }
1018
1157
  return [
1019
1158
  `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.url="${hostedMcpUrl(apiBase)}"`,
1020
- `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.bearer_token_env_var="${LISTENER_KEY_ENV}" (the key set in the run's environment, never on argv)`,
1159
+ profile === "own" ? `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.http_headers_helper=<node> ${codexListenerHeadersHelperPath(home)} (own: reads this home's credentials on each connection; no key in the run's environment or on argv; no run while $CODEX_HOME/.env sets a key or the merged ${CODEX_MCP_SERVER_NAME} entry names bearer_token_env_var)` : `-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)`,
1021
1160
  `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.default_tools_approval_mode="approve"`,
1022
1161
  `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.http_headers={ "X-AgentChat-Client" = "codex", "X-AgentChat-Client-Version" = <the listener's version> } (names the runtime to the hosted tools)`,
1023
1162
  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)`
@@ -1026,8 +1165,9 @@ var codexPreset = {
1026
1165
  label: "Codex",
1027
1166
  runtime: "codex",
1028
1167
  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.
1168
+ // `own`, `work` and `full` read the whole filesystem (Codex's sandboxes never
1169
+ // restrict reads; an `answer` run reads only its workdir): true, because the
1170
+ // field is one for every profile.
1031
1171
  readsIdentityHome: true,
1032
1172
  async inspect(env = process.env, command = "codex") {
1033
1173
  const home = codexHomeFrom(env);
@@ -1039,16 +1179,27 @@ var codexPreset = {
1039
1179
  runner(ctx) {
1040
1180
  const env = withoutInheritedKey(ctx.env ?? process.env);
1041
1181
  const apiKey = ctx.apiKey;
1042
- return new CodexRunner({
1182
+ const base = {
1043
1183
  codexHome: codexHomeFrom(env),
1044
1184
  workdir: ctx.workdir,
1045
1185
  profile: ctx.profile,
1046
- apiKey: () => apiKey,
1047
1186
  keyEnv: LISTENER_KEY_ENV,
1048
- mcp: { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV, clientVersion: ctx.clientVersion ?? VERSION },
1049
1187
  ...ctx.command !== void 0 ? { command: ctx.command } : {},
1050
1188
  env
1051
- });
1189
+ };
1190
+ const mcp = { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV, clientVersion: ctx.clientVersion ?? VERSION };
1191
+ if (ctx.profile !== "own") return new CodexRunner({ ...base, apiKey: () => apiKey, mcp });
1192
+ const script = codexListenerHeadersHelperPath(ctx.home);
1193
+ const helper = codexHeadersHelperCommand(script);
1194
+ if (helper === null) {
1195
+ return new CodexRunner({ ...base, apiKey: () => null, mcp, refuse: `the path of Node (${process.execPath}) or of ${script} holds a character a shell command cannot carry quoted: an own run would have its key in its environment instead` });
1196
+ }
1197
+ try {
1198
+ atomicWriteFile(script, CODEX_LISTENER_HEADERS_HELPER_SOURCE, 384);
1199
+ } catch (err) {
1200
+ return new CodexRunner({ ...base, apiKey: () => null, mcp, refuse: `could not write the headers helper ${script}: ${err instanceof Error ? err.message : String(err)}` });
1201
+ }
1202
+ return new CodexRunner({ ...base, apiKey: () => null, mcp: { ...mcp, headersHelper: helper } });
1052
1203
  }
1053
1204
  };
1054
1205
 
@@ -1076,6 +1227,7 @@ export {
1076
1227
  CODEX_ANSWER_DISABLED_FEATURES,
1077
1228
  CODEX_ANSWER_FILESYSTEM,
1078
1229
  CODEX_ANSWER_PERMISSIONS,
1230
+ CODEX_LISTENER_HEADERS_HELPER_SOURCE,
1079
1231
  CODEX_MANAGED_PROXY_ENV,
1080
1232
  CODEX_MCP_LIST_MAX_AGE_MS,
1081
1233
  CODEX_MCP_LIST_TIMEOUT_MS,
@@ -1111,11 +1263,15 @@ export {
1111
1263
  claudeSettingsFilesGrantingDirectories,
1112
1264
  claudeSignIn,
1113
1265
  claudeUserStatePathFor,
1266
+ codexAgentchatExplicitAuth,
1114
1267
  codexAnswerFallbackWorkdir,
1115
1268
  codexClientHeadersToml,
1116
1269
  codexConfigLayerFiles,
1270
+ codexDotEnvKeyNames,
1271
+ codexHeadersHelperCommand,
1117
1272
  codexHomeFrom,
1118
1273
  codexIsLoggedIn,
1274
+ codexListenerHeadersHelperPath,
1119
1275
  codexMcpDisableArgs,
1120
1276
  codexMcpOverrideArgs,
1121
1277
  codexPinnedUrlArgs,