@agentchatme/codex 0.5.1 → 0.5.3

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/index.js CHANGED
@@ -46,8 +46,8 @@ var require_windows = __commonJS({
46
46
  "use strict";
47
47
  module.exports = isexe;
48
48
  isexe.sync = sync;
49
- var fs10 = __require("fs");
50
- function checkPathExt(path12, options) {
49
+ var fs11 = __require("fs");
50
+ function checkPathExt(path13, options) {
51
51
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
52
52
  if (!pathext) {
53
53
  return true;
@@ -58,25 +58,25 @@ var require_windows = __commonJS({
58
58
  }
59
59
  for (var i = 0; i < pathext.length; i++) {
60
60
  var p = pathext[i].toLowerCase();
61
- if (p && path12.substr(-p.length).toLowerCase() === p) {
61
+ if (p && path13.substr(-p.length).toLowerCase() === p) {
62
62
  return true;
63
63
  }
64
64
  }
65
65
  return false;
66
66
  }
67
- function checkStat(stat, path12, options) {
67
+ function checkStat(stat, path13, options) {
68
68
  if (!stat.isSymbolicLink() && !stat.isFile()) {
69
69
  return false;
70
70
  }
71
- return checkPathExt(path12, options);
71
+ return checkPathExt(path13, options);
72
72
  }
73
- function isexe(path12, options, cb) {
74
- fs10.stat(path12, function(er, stat) {
75
- cb(er, er ? false : checkStat(stat, path12, options));
73
+ function isexe(path13, options, cb) {
74
+ fs11.stat(path13, function(er, stat) {
75
+ cb(er, er ? false : checkStat(stat, path13, options));
76
76
  });
77
77
  }
78
- function sync(path12, options) {
79
- return checkStat(fs10.statSync(path12), path12, options);
78
+ function sync(path13, options) {
79
+ return checkStat(fs11.statSync(path13), path13, options);
80
80
  }
81
81
  }
82
82
  });
@@ -87,14 +87,14 @@ var require_mode = __commonJS({
87
87
  "use strict";
88
88
  module.exports = isexe;
89
89
  isexe.sync = sync;
90
- var fs10 = __require("fs");
91
- function isexe(path12, options, cb) {
92
- fs10.stat(path12, function(er, stat) {
90
+ var fs11 = __require("fs");
91
+ function isexe(path13, options, cb) {
92
+ fs11.stat(path13, function(er, stat) {
93
93
  cb(er, er ? false : checkStat(stat, options));
94
94
  });
95
95
  }
96
- function sync(path12, options) {
97
- return checkStat(fs10.statSync(path12), options);
96
+ function sync(path13, options) {
97
+ return checkStat(fs11.statSync(path13), options);
98
98
  }
99
99
  function checkStat(stat, options) {
100
100
  return stat.isFile() && checkMode(stat, options);
@@ -119,7 +119,7 @@ var require_mode = __commonJS({
119
119
  var require_isexe = __commonJS({
120
120
  "node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports, module) {
121
121
  "use strict";
122
- var fs10 = __require("fs");
122
+ var fs11 = __require("fs");
123
123
  var core;
124
124
  if (process.platform === "win32" || global.TESTING_WINDOWS) {
125
125
  core = require_windows();
@@ -128,7 +128,7 @@ var require_isexe = __commonJS({
128
128
  }
129
129
  module.exports = isexe;
130
130
  isexe.sync = sync;
131
- function isexe(path12, options, cb) {
131
+ function isexe(path13, options, cb) {
132
132
  if (typeof options === "function") {
133
133
  cb = options;
134
134
  options = {};
@@ -137,17 +137,17 @@ var require_isexe = __commonJS({
137
137
  if (typeof Promise !== "function") {
138
138
  throw new TypeError("callback not provided");
139
139
  }
140
- return new Promise(function(resolve9, reject) {
141
- isexe(path12, options || {}, function(er, is) {
140
+ return new Promise(function(resolve10, reject) {
141
+ isexe(path13, options || {}, function(er, is) {
142
142
  if (er) {
143
143
  reject(er);
144
144
  } else {
145
- resolve9(is);
145
+ resolve10(is);
146
146
  }
147
147
  });
148
148
  });
149
149
  }
150
- core(path12, options || {}, function(er, is) {
150
+ core(path13, options || {}, function(er, is) {
151
151
  if (er) {
152
152
  if (er.code === "EACCES" || options && options.ignoreErrors) {
153
153
  er = null;
@@ -157,9 +157,9 @@ var require_isexe = __commonJS({
157
157
  cb(er, is);
158
158
  });
159
159
  }
160
- function sync(path12, options) {
160
+ function sync(path13, options) {
161
161
  try {
162
- return core.sync(path12, options || {});
162
+ return core.sync(path13, options || {});
163
163
  } catch (er) {
164
164
  if (options && options.ignoreErrors || er.code === "EACCES") {
165
165
  return false;
@@ -176,7 +176,7 @@ var require_which = __commonJS({
176
176
  "node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(exports, module) {
177
177
  "use strict";
178
178
  var isWindows2 = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
179
- var path12 = __require("path");
179
+ var path13 = __require("path");
180
180
  var COLON = isWindows2 ? ";" : ":";
181
181
  var isexe = require_isexe();
182
182
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -209,27 +209,27 @@ var require_which = __commonJS({
209
209
  opt = {};
210
210
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
211
211
  const found = [];
212
- const step = (i) => new Promise((resolve9, reject) => {
212
+ const step = (i) => new Promise((resolve10, reject) => {
213
213
  if (i === pathEnv.length)
214
- return opt.all && found.length ? resolve9(found) : reject(getNotFoundError(cmd));
214
+ return opt.all && found.length ? resolve10(found) : reject(getNotFoundError(cmd));
215
215
  const ppRaw = pathEnv[i];
216
216
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
217
- const pCmd = path12.join(pathPart, cmd);
217
+ const pCmd = path13.join(pathPart, cmd);
218
218
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
219
- resolve9(subStep(p, i, 0));
219
+ resolve10(subStep(p, i, 0));
220
220
  });
221
- const subStep = (p, i, ii) => new Promise((resolve9, reject) => {
221
+ const subStep = (p, i, ii) => new Promise((resolve10, reject) => {
222
222
  if (ii === pathExt.length)
223
- return resolve9(step(i + 1));
223
+ return resolve10(step(i + 1));
224
224
  const ext = pathExt[ii];
225
225
  isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
226
226
  if (!er && is) {
227
227
  if (opt.all)
228
228
  found.push(p + ext);
229
229
  else
230
- return resolve9(p + ext);
230
+ return resolve10(p + ext);
231
231
  }
232
- return resolve9(subStep(p, i, ii + 1));
232
+ return resolve10(subStep(p, i, ii + 1));
233
233
  });
234
234
  });
235
235
  return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
@@ -241,7 +241,7 @@ var require_which = __commonJS({
241
241
  for (let i = 0; i < pathEnv.length; i++) {
242
242
  const ppRaw = pathEnv[i];
243
243
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
244
- const pCmd = path12.join(pathPart, cmd);
244
+ const pCmd = path13.join(pathPart, cmd);
245
245
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
246
246
  for (let j = 0; j < pathExt.length; j++) {
247
247
  const cur = p + pathExt[j];
@@ -289,7 +289,7 @@ var require_path_key = __commonJS({
289
289
  var require_resolveCommand = __commonJS({
290
290
  "node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
291
291
  "use strict";
292
- var path12 = __require("path");
292
+ var path13 = __require("path");
293
293
  var which = require_which();
294
294
  var getPathKey = require_path_key();
295
295
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -307,7 +307,7 @@ var require_resolveCommand = __commonJS({
307
307
  try {
308
308
  resolved = which.sync(parsed.command, {
309
309
  path: env[getPathKey({ env })],
310
- pathExt: withoutPathExt ? path12.delimiter : void 0
310
+ pathExt: withoutPathExt ? path13.delimiter : void 0
311
311
  });
312
312
  } catch (e) {
313
313
  } finally {
@@ -316,7 +316,7 @@ var require_resolveCommand = __commonJS({
316
316
  }
317
317
  }
318
318
  if (resolved) {
319
- resolved = path12.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
319
+ resolved = path13.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
320
320
  }
321
321
  return resolved;
322
322
  }
@@ -370,8 +370,8 @@ var require_shebang_command = __commonJS({
370
370
  if (!match) {
371
371
  return null;
372
372
  }
373
- const [path12, argument] = match[0].replace(/#! ?/, "").split(" ");
374
- const binary = path12.split("/").pop();
373
+ const [path13, argument] = match[0].replace(/#! ?/, "").split(" ");
374
+ const binary = path13.split("/").pop();
375
375
  if (binary === "env") {
376
376
  return argument;
377
377
  }
@@ -384,16 +384,16 @@ var require_shebang_command = __commonJS({
384
384
  var require_readShebang = __commonJS({
385
385
  "node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
386
386
  "use strict";
387
- var fs10 = __require("fs");
387
+ var fs11 = __require("fs");
388
388
  var shebangCommand = require_shebang_command();
389
389
  function readShebang(command) {
390
390
  const size = 150;
391
391
  const buffer = Buffer.alloc(size);
392
392
  let fd;
393
393
  try {
394
- fd = fs10.openSync(command, "r");
395
- fs10.readSync(fd, buffer, 0, size, 0);
396
- fs10.closeSync(fd);
394
+ fd = fs11.openSync(command, "r");
395
+ fs11.readSync(fd, buffer, 0, size, 0);
396
+ fs11.closeSync(fd);
397
397
  } catch (e) {
398
398
  }
399
399
  return shebangCommand(buffer.toString());
@@ -406,7 +406,7 @@ var require_readShebang = __commonJS({
406
406
  var require_parse = __commonJS({
407
407
  "node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports, module) {
408
408
  "use strict";
409
- var path12 = __require("path");
409
+ var path13 = __require("path");
410
410
  var resolveCommand = require_resolveCommand();
411
411
  var escape = require_escape();
412
412
  var readShebang = require_readShebang();
@@ -431,7 +431,7 @@ var require_parse = __commonJS({
431
431
  const needsShell = !isExecutableRegExp.test(commandFile);
432
432
  if (parsed.options.forceShell || needsShell) {
433
433
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
434
- parsed.command = path12.normalize(parsed.command);
434
+ parsed.command = path13.normalize(parsed.command);
435
435
  parsed.command = escape.command(parsed.command);
436
436
  parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
437
437
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
@@ -4241,10 +4241,10 @@ var init_wrapper = __esm({
4241
4241
  });
4242
4242
 
4243
4243
  // src/index.ts
4244
- import * as fs9 from "fs";
4244
+ import * as fs10 from "fs";
4245
4245
  import { parseArgs } from "util";
4246
4246
 
4247
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.1/node_modules/@agentchatme/agent-core/dist/chunk-AFDD53DD.js
4247
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/chunk-3OUDKIQV.js
4248
4248
  var import_cross_spawn = __toESM(require_cross_spawn(), 1);
4249
4249
  import { randomBytes } from "crypto";
4250
4250
  import * as fs from "fs";
@@ -4345,24 +4345,6 @@ function readJsonFile(filePath) {
4345
4345
  return null;
4346
4346
  }
4347
4347
  }
4348
- var LEVELS = ["silent", "error", "warn", "info", "debug"];
4349
- function activeLevel() {
4350
- const raw = (process.env["AGENTCHAT_LOG_LEVEL"] ?? "warn").toLowerCase();
4351
- const idx = LEVELS.indexOf(raw);
4352
- return idx === -1 ? LEVELS.indexOf("warn") : idx;
4353
- }
4354
- function emit(level, msg) {
4355
- if (LEVELS.indexOf(level) <= activeLevel() && level !== "silent") {
4356
- process.stderr.write(`[agentchat:${level}] ${msg}
4357
- `);
4358
- }
4359
- }
4360
- var log = {
4361
- error: (msg) => emit("error", msg),
4362
- warn: (msg) => emit("warn", msg),
4363
- info: (msg) => emit("info", msg),
4364
- debug: (msg) => emit("debug", msg)
4365
- };
4366
4348
  var RUN_PROFILES = ["answer", "work", "full"];
4367
4349
  var PEER_RUN_WARNING = "runs started by peers' messages can read and change this machine";
4368
4350
  function runProfileWarning(profile2) {
@@ -4430,6 +4412,24 @@ function integrationDisabled(env = process.env) {
4430
4412
  var RUN_BUDGET_ENV = "AGENTCHAT_RUN_BUDGET_MS";
4431
4413
  var DEFAULT_RUN_BUDGET_MS = 10 * 6e4;
4432
4414
  var MAX_RUN_BUDGET_MS = 2 * 60 * 6e4;
4415
+ var LEVELS = ["silent", "error", "warn", "info", "debug"];
4416
+ function activeLevel() {
4417
+ const raw = (process.env["AGENTCHAT_LOG_LEVEL"] ?? "warn").toLowerCase();
4418
+ const idx = LEVELS.indexOf(raw);
4419
+ return idx === -1 ? LEVELS.indexOf("warn") : idx;
4420
+ }
4421
+ function emit(level, msg) {
4422
+ if (LEVELS.indexOf(level) <= activeLevel() && level !== "silent") {
4423
+ process.stderr.write(`[agentchat:${level}] ${msg}
4424
+ `);
4425
+ }
4426
+ }
4427
+ var log = {
4428
+ error: (msg) => emit("error", msg),
4429
+ warn: (msg) => emit("warn", msg),
4430
+ info: (msg) => emit("info", msg),
4431
+ debug: (msg) => emit("debug", msg)
4432
+ };
4433
4433
  var spawnCommand = import_cross_spawn.default;
4434
4434
  var spawnCommandSync = import_cross_spawn.default.sync;
4435
4435
  var DEFAULT_GRACE_MS = 5e3;
@@ -4700,7 +4700,7 @@ function spawnRun(spec) {
4700
4700
  });
4701
4701
  }
4702
4702
 
4703
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.1/node_modules/@agentchatme/agent-core/dist/chunk-CDJASQ3X.js
4703
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/chunk-CQSL6X4D.js
4704
4704
  import * as path3 from "path";
4705
4705
 
4706
4706
  // node_modules/.pnpm/agentchatme@1.4.0_ws@8.21.1/node_modules/agentchatme/dist/index.js
@@ -5058,8 +5058,8 @@ var HttpTransport = class {
5058
5058
  }
5059
5059
  this.fetchFn = f.bind(globalThis);
5060
5060
  }
5061
- async request(method, path12, opts = {}) {
5062
- const url = `${this.baseUrl}${path12}`;
5061
+ async request(method, path13, opts = {}) {
5062
+ const url = `${this.baseUrl}${path13}`;
5063
5063
  const policy = resolveRetryPolicy(opts.retry, this.retry);
5064
5064
  const canRetry = isRetryEligible(method, opts.idempotencyKey, opts.retry);
5065
5065
  const maxAttempts = canRetry ? policy.maxRetries + 1 : 1;
@@ -5293,10 +5293,10 @@ function statusToCode(status) {
5293
5293
  }
5294
5294
  async function sleep(ms, signal) {
5295
5295
  if (ms <= 0) return;
5296
- await new Promise((resolve9, reject) => {
5296
+ await new Promise((resolve10, reject) => {
5297
5297
  const timer = setTimeout(() => {
5298
5298
  if (signal) signal.removeEventListener("abort", onAbort);
5299
- resolve9();
5299
+ resolve10();
5300
5300
  }, ms);
5301
5301
  const onAbort = () => {
5302
5302
  clearTimeout(timer);
@@ -5528,31 +5528,31 @@ var AgentChatClient = class _AgentChatClient {
5528
5528
  return this.get(`/v1/texts?${params.toString()}`, options);
5529
5529
  }
5530
5530
  // ─── Internal request helpers ─────────────────────────────────────────────
5531
- async get(path12, opts) {
5532
- const res = await this.http.request("GET", path12, this.toRequestOpts(opts));
5531
+ async get(path13, opts) {
5532
+ const res = await this.http.request("GET", path13, this.toRequestOpts(opts));
5533
5533
  return res.data;
5534
5534
  }
5535
- async del(path12, opts) {
5536
- const res = await this.http.request("DELETE", path12, this.toRequestOpts(opts));
5535
+ async del(path13, opts) {
5536
+ const res = await this.http.request("DELETE", path13, this.toRequestOpts(opts));
5537
5537
  return res.data;
5538
5538
  }
5539
- async post(path12, body, opts) {
5540
- const res = await this.http.request("POST", path12, {
5539
+ async post(path13, body, opts) {
5540
+ const res = await this.http.request("POST", path13, {
5541
5541
  ...this.toRequestOpts(opts, { idempotent: false }),
5542
5542
  body
5543
5543
  });
5544
5544
  return res.data;
5545
5545
  }
5546
- async patch(path12, body, opts) {
5547
- const res = await this.http.request("PATCH", path12, {
5546
+ async patch(path13, body, opts) {
5547
+ const res = await this.http.request("PATCH", path13, {
5548
5548
  ...this.toRequestOpts(opts, { idempotent: false }),
5549
5549
  body
5550
5550
  });
5551
5551
  return res.data;
5552
5552
  }
5553
- async put(path12, body, opts) {
5553
+ async put(path13, body, opts) {
5554
5554
  const headers = opts?.contentType ? { "Content-Type": opts.contentType } : void 0;
5555
- const res = await this.http.request("PUT", path12, {
5555
+ const res = await this.http.request("PUT", path13, {
5556
5556
  ...this.toRequestOpts(opts),
5557
5557
  body,
5558
5558
  rawBody: opts?.rawBody,
@@ -7525,17 +7525,17 @@ var RealtimeClient = class {
7525
7525
  */
7526
7526
  heldAtMost(run32) {
7527
7527
  const ms = this.options.inFlightAdoptMs;
7528
- return new Promise((resolve9) => {
7529
- const timer = setTimeout(resolve9, ms);
7528
+ return new Promise((resolve10) => {
7529
+ const timer = setTimeout(resolve10, ms);
7530
7530
  unref(timer);
7531
7531
  run32.then(
7532
7532
  () => {
7533
7533
  clearTimeout(timer);
7534
- resolve9();
7534
+ resolve10();
7535
7535
  },
7536
7536
  () => {
7537
7537
  clearTimeout(timer);
7538
- resolve9();
7538
+ resolve10();
7539
7539
  }
7540
7540
  );
7541
7541
  });
@@ -8703,9 +8703,9 @@ var TurnTracker = class {
8703
8703
  */
8704
8704
  async confirmedEnd(handle, done) {
8705
8705
  if (!this.holds(handle)) return null;
8706
- const released = new Promise((resolve9) => {
8706
+ const released = new Promise((resolve10) => {
8707
8707
  const list = this.waiters.get(handle.key) ?? [];
8708
- list.push(() => resolve9(null));
8708
+ list.push(() => resolve10(null));
8709
8709
  this.waiters.set(handle.key, list);
8710
8710
  });
8711
8711
  let report = done;
@@ -8782,9 +8782,9 @@ function nodeModules() {
8782
8782
  /* @vite-ignore */
8783
8783
  PATH_MODULE
8784
8784
  )
8785
- ]).then(([fs10, path12]) => ({
8786
- fs: fs10.default ?? fs10,
8787
- path: path12.default ?? path12
8785
+ ]).then(([fs11, path13]) => ({
8786
+ fs: fs11.default ?? fs11,
8787
+ path: path13.default ?? path13
8788
8788
  }));
8789
8789
  return modules;
8790
8790
  }
@@ -8802,8 +8802,8 @@ function randomSuffix() {
8802
8802
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
8803
8803
  }
8804
8804
  async function renameWithRetry2(from, to, options = {}) {
8805
- const { fs: fs10 } = await nodeModules();
8806
- const rename = options.rename ?? ((a, b) => fs10.rename(a, b));
8805
+ const { fs: fs11 } = await nodeModules();
8806
+ const rename = options.rename ?? ((a, b) => fs11.rename(a, b));
8807
8807
  const attempts = options.retry ?? isWindows() ? RENAME_ATTEMPTS2 : 1;
8808
8808
  for (let attempt = 1; ; attempt++) {
8809
8809
  try {
@@ -8812,16 +8812,16 @@ async function renameWithRetry2(from, to, options = {}) {
8812
8812
  } catch (err) {
8813
8813
  const code = err.code;
8814
8814
  if (attempt >= attempts || code === void 0 || !RENAME_RETRY_CODES2.has(code)) throw err;
8815
- await new Promise((resolve9) => setTimeout(resolve9, RENAME_DELAY_MS2));
8815
+ await new Promise((resolve10) => setTimeout(resolve10, RENAME_DELAY_MS2));
8816
8816
  }
8817
8817
  }
8818
8818
  }
8819
8819
  async function writeAtomic(file, data, options = {}) {
8820
- const { fs: fs10, path: path12 } = await nodeModules();
8821
- await fs10.mkdir(path12.dirname(file), { recursive: true, mode: 448 });
8822
- const tmp = path12.join(path12.dirname(file), `.${path12.basename(file)}.${randomSuffix()}.tmp`);
8820
+ const { fs: fs11, path: path13 } = await nodeModules();
8821
+ await fs11.mkdir(path13.dirname(file), { recursive: true, mode: 448 });
8822
+ const tmp = path13.join(path13.dirname(file), `.${path13.basename(file)}.${randomSuffix()}.tmp`);
8823
8823
  try {
8824
- const handle = await fs10.open(tmp, "wx", options.mode ?? 438);
8824
+ const handle = await fs11.open(tmp, "wx", options.mode ?? 438);
8825
8825
  try {
8826
8826
  if (options.mode !== void 0) await handle.chmod(options.mode);
8827
8827
  await handle.writeFile(data);
@@ -8831,14 +8831,14 @@ async function writeAtomic(file, data, options = {}) {
8831
8831
  }
8832
8832
  await renameWithRetry2(tmp, file, options);
8833
8833
  } catch (err) {
8834
- await fs10.rm(tmp, { force: true }).catch(() => void 0);
8834
+ await fs11.rm(tmp, { force: true }).catch(() => void 0);
8835
8835
  throw err;
8836
8836
  }
8837
8837
  }
8838
8838
  async function readBytes(file) {
8839
- const { fs: fs10 } = await nodeModules();
8839
+ const { fs: fs11 } = await nodeModules();
8840
8840
  try {
8841
- return new Uint8Array(await fs10.readFile(file));
8841
+ return new Uint8Array(await fs11.readFile(file));
8842
8842
  } catch {
8843
8843
  return null;
8844
8844
  }
@@ -9772,7 +9772,7 @@ var ReceiveLoop = class {
9772
9772
  if (!run32.abandoned()) this.finishCycle(summary);
9773
9773
  })();
9774
9774
  let timer = null;
9775
- const overdue = new Promise((resolve9) => {
9775
+ const overdue = new Promise((resolve10) => {
9776
9776
  if (!Number.isFinite(this.cycleTimeoutMs)) return;
9777
9777
  const check = () => {
9778
9778
  timer = null;
@@ -9780,7 +9780,7 @@ var ReceiveLoop = class {
9780
9780
  const excluded = excludedMs + (excludedSince !== null ? now2 - excludedSince : 0);
9781
9781
  const active = now2 - startedAt - excluded;
9782
9782
  if (active >= this.cycleTimeoutMs) {
9783
- resolve9("overdue");
9783
+ resolve10("overdue");
9784
9784
  return;
9785
9785
  }
9786
9786
  timer = this._setTimeout(check, Math.max(1, this.cycleTimeoutMs - active));
@@ -9843,7 +9843,7 @@ var ReceiveLoop = class {
9843
9843
  return (prompt2, options) => run32.exclude(() => call2(prompt2, options));
9844
9844
  }
9845
9845
  deadlineModelCall(run32) {
9846
- return (prompt2) => new Promise((resolve9, reject) => {
9846
+ return (prompt2) => new Promise((resolve10, reject) => {
9847
9847
  const controller = new AbortController();
9848
9848
  const abort = () => {
9849
9849
  controller.abort();
@@ -9870,7 +9870,7 @@ var ReceiveLoop = class {
9870
9870
  (text2) => {
9871
9871
  if (timer !== null) this._clearTimeout(timer);
9872
9872
  run32.signal.removeEventListener("abort", abort);
9873
- resolve9(text2);
9873
+ resolve10(text2);
9874
9874
  },
9875
9875
  (err) => {
9876
9876
  if (timer !== null) this._clearTimeout(timer);
@@ -10547,9 +10547,9 @@ function transport(options, apiKey) {
10547
10547
  ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {}
10548
10548
  });
10549
10549
  }
10550
- async function call(options, method, path12, body, apiKey) {
10550
+ async function call(options, method, path13, body, apiKey) {
10551
10551
  try {
10552
- const res = await transport(options, apiKey).request(method, path12, {
10552
+ const res = await transport(options, apiKey).request(method, path13, {
10553
10553
  ...body !== void 0 ? { body } : {},
10554
10554
  retry: "never",
10555
10555
  ...options.signal ? { signal: options.signal } : {},
@@ -10708,14 +10708,14 @@ async function checkKey(apiKey, options) {
10708
10708
  return { ok: true, handle };
10709
10709
  }
10710
10710
  function defaultSleep(signal) {
10711
- return (ms) => new Promise((resolve9, reject) => {
10711
+ return (ms) => new Promise((resolve10, reject) => {
10712
10712
  if (signal?.aborted) {
10713
10713
  reject(abortError());
10714
10714
  return;
10715
10715
  }
10716
10716
  const timer = setTimeout(() => {
10717
10717
  signal?.removeEventListener("abort", onAbort);
10718
- resolve9();
10718
+ resolve10();
10719
10719
  }, ms);
10720
10720
  const onAbort = () => {
10721
10721
  clearTimeout(timer);
@@ -10910,7 +10910,7 @@ var DAY = 24 * HOUR;
10910
10910
  var INBOX_TRAY_MAX_LIMIT = 50;
10911
10911
  var MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
10912
10912
 
10913
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.1/node_modules/@agentchatme/agent-core/dist/chunk-CDJASQ3X.js
10913
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/chunk-CQSL6X4D.js
10914
10914
  import * as fs3 from "fs";
10915
10915
  import * as path22 from "path";
10916
10916
  import { createHash } from "crypto";
@@ -15009,19 +15009,6 @@ function resolveIdentity(home, options = {}) {
15009
15009
  const envKey = options.envKey === false ? void 0 : process.env["AGENTCHAT_API_KEY"];
15010
15010
  const envBase = process.env["AGENTCHAT_API_BASE"];
15011
15011
  const file = readCredentials(home);
15012
- if (envKey && envKey.trim().length >= 20) {
15013
- return {
15014
- apiKey: envKey.trim(),
15015
- apiBase: envBase?.trim() || file?.api_base || DEFAULT_API_BASE2,
15016
- handle: file?.handle ?? null,
15017
- source: "env"
15018
- };
15019
- }
15020
- if (envKey && envKey.trim().length > 0 && file) {
15021
- log.warn(
15022
- "AGENTCHAT_API_KEY is set but malformed (under 20 chars); using the credentials-file identity instead"
15023
- );
15024
- }
15025
15012
  if (file) {
15026
15013
  return {
15027
15014
  apiKey: file.api_key,
@@ -15030,8 +15017,23 @@ function resolveIdentity(home, options = {}) {
15030
15017
  source: "file"
15031
15018
  };
15032
15019
  }
15020
+ if (envKey && envKey.trim().length >= 20) {
15021
+ return {
15022
+ apiKey: envKey.trim(),
15023
+ apiBase: envBase?.trim() || DEFAULT_API_BASE2,
15024
+ handle: null,
15025
+ source: "env"
15026
+ };
15027
+ }
15033
15028
  return null;
15034
15029
  }
15030
+ function envKeyConflict(home, env = process.env) {
15031
+ const exported = env["AGENTCHAT_API_KEY"]?.trim();
15032
+ if (exported === void 0 || exported.length === 0) return null;
15033
+ const stored = readCredentials(home);
15034
+ if (stored === null || stored.api_key === exported) return null;
15035
+ return `AGENTCHAT_API_KEY is exported and is not the key ${credentialsPath(home)} holds (it is another agent's key, or an old one); commands for this agent act only with that file's key`;
15036
+ }
15035
15037
  function writeCredentials(home, creds) {
15036
15038
  atomicWriteFile(credentialsPath(home), JSON.stringify(creds, null, 2) + "\n", 384);
15037
15039
  }
@@ -15550,8 +15552,8 @@ function agentLockDir(env = process.env, system = process.platform, home = os22.
15550
15552
  return p.join(home, ".local", "state", "agentchat", "locks");
15551
15553
  }
15552
15554
 
15553
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.1/node_modules/@agentchatme/agent-core/dist/chunk-3ERPUP4M.js
15554
- var VERSION2 = "0.5.1";
15555
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/chunk-JL2L4WRG.js
15556
+ var VERSION2 = "0.5.3";
15555
15557
  var HOSTED_MCP_PATH2 = integration_exports.HOSTED_MCP_PATH;
15556
15558
  function hostedMcpUrl2(apiBase) {
15557
15559
  return integration_exports.hostedMcpUrl(apiBase);
@@ -15568,7 +15570,7 @@ async function probeHostedMcp(params) {
15568
15570
  var PROBE_KILL_WAIT_MS = 5e3;
15569
15571
  var MAX_OUTPUT = 64 * 1024;
15570
15572
  function runProbe(command, args, options) {
15571
- return new Promise((resolve9) => {
15573
+ return new Promise((resolve10) => {
15572
15574
  let child;
15573
15575
  try {
15574
15576
  child = spawnCommand(command, [...args], {
@@ -15580,7 +15582,7 @@ function runProbe(command, args, options) {
15580
15582
  windowsHide: true
15581
15583
  });
15582
15584
  } catch (err) {
15583
- resolve9({ error: err instanceof Error ? err : new Error(String(err)), status: null, stdout: "", stderr: "", timedOut: false });
15585
+ resolve10({ error: err instanceof Error ? err : new Error(String(err)), status: null, stdout: "", stderr: "", timedOut: false });
15584
15586
  return;
15585
15587
  }
15586
15588
  const proc = child;
@@ -15595,7 +15597,7 @@ function runProbe(command, args, options) {
15595
15597
  finished = true;
15596
15598
  clearTimeout(timer);
15597
15599
  if (giveUp !== null) clearTimeout(giveUp);
15598
- resolve9(result);
15600
+ resolve10(result);
15599
15601
  };
15600
15602
  proc.stdout?.on("data", (chunk) => {
15601
15603
  if (stdout.length < MAX_OUTPUT) stdout += chunk.toString("utf-8");
@@ -15627,7 +15629,7 @@ function runProbe(command, args, options) {
15627
15629
  });
15628
15630
  }
15629
15631
 
15630
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.1/node_modules/@agentchatme/agent-core/dist/index.js
15632
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/index.js
15631
15633
  import * as fs5 from "fs";
15632
15634
  import * as path5 from "path";
15633
15635
  import * as readline from "readline";
@@ -15835,7 +15837,7 @@ function renderUnregisteredBlock(copy) {
15835
15837
  "**Run the commands yourself, and ask the user one question per turn.** Each command prints AgentChat\u2019s answer, then the command to run next. Relay the answer to the user as it is; ask them for what the next command needs (a value it leaves as `<\u2026>`, such as the code AgentChat emailed them); if it says to wait, wait; then run it. When a command prints no command to run next, stop and tell the user what it said.",
15836
15838
  "",
15837
15839
  `- **New account:** ask for their email, then for the @handle they want (offer a suggestion if they like). Run: \`${invoke} register --email <email> --handle <handle>\`. Never submit a handle the user has not chosen or accepted.`,
15838
- `- **Existing account, with its API key:** run: \`${invoke} login --api-key <ac_\u2026>\``,
15840
+ `- **Existing account, with its API key:** ask the user to run \`${invoke} login\` in their own terminal and paste the key when it asks. Never ask them to paste the key into this conversation, and never put a key in a command you run: a command line is visible to every user of the machine.`,
15839
15841
  `- **Existing account, key lost:** recovery replaces the old API key, so anything still using it stops working; say so and ask before going on. Ask for the email the account uses, then which @handle it is. Run: \`${invoke} recover --handle <handle> --email <email>\``,
15840
15842
  "- **When it is done:** tell the user the @handle and where the API key is stored, exactly as the command printed them.",
15841
15843
  "- Never reuse another active coding agent\u2019s account; each reachable agent needs its own.",
@@ -15952,6 +15954,11 @@ function createIdentityCommands(profile2) {
15952
15954
  const invocation2 = () => profile2.invocation();
15953
15955
  const LABEL2 = profile2.label;
15954
15956
  const clientIdentity = clientIdentityOf(profile2.client);
15957
+ function envKeyRefusal() {
15958
+ const conflict = envKeyConflict(profile2.home());
15959
+ if (conflict === null) return null;
15960
+ return `${conflict}. Unset AGENTCHAT_API_KEY, or, to sign this home in with that key on purpose: printenv AGENTCHAT_API_KEY | ${invocation2()} login --api-key -`;
15961
+ }
15955
15962
  const apiClient = (apiKey, apiBase) => new AgentChatClient({ apiKey, baseUrl: apiBase, clientIdentity, timeoutMs: 5e3, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } });
15956
15963
  const accountOptions = (apiBase) => ({ clientIdentity, apiBase, timeoutMs: 15e3 });
15957
15964
  async function served(apiKey, apiBase) {
@@ -16198,16 +16205,23 @@ ${runLine(codeCommand(kind, pending.flow, code))} again.`);
16198
16205
  const home = profile2.home();
16199
16206
  const apiBase = opts.apiBase ?? process.env["AGENTCHAT_API_BASE"] ?? DEFAULT_API_BASE2;
16200
16207
  let apiKey = opts.apiKey?.trim();
16208
+ const onArgv = apiKey !== void 0 && apiKey.length > 0 && apiKey !== "-";
16201
16209
  if (apiKey === "-") {
16202
16210
  apiKey = await readAllStdin();
16203
16211
  } else if (!apiKey) {
16204
16212
  const fromEnv = process.env["AGENTCHAT_API_KEY"]?.trim();
16213
+ const refusal2 = fromEnv ? envKeyRefusal() : null;
16214
+ if (refusal2 !== null) {
16215
+ console.error(`${refusal2}
16216
+ login does not adopt an exported key in place of the one this home holds; nothing was saved.`);
16217
+ return 1;
16218
+ }
16205
16219
  if (fromEnv) {
16206
16220
  apiKey = fromEnv;
16207
16221
  console.log("Using the key from AGENTCHAT_API_KEY.");
16208
16222
  } else if (process.stdin.isTTY !== true) {
16209
16223
  console.error(
16210
- `Missing API key. Pipe it in: printf %s "$KEY" | ${invocation2()} login --api-key - (or set AGENTCHAT_API_KEY, or pass --api-key ac_live_\u2026, which \`ps\` and shell history can see)`
16224
+ `Missing API key. Run \`${invocation2()} login\` in a terminal and paste the key when it asks, or pipe it in from a file: \`${invocation2()} login --api-key - < key.txt\`. Never put the key itself on a command line: \`ps\` and shell history can see it there.`
16211
16225
  );
16212
16226
  return 1;
16213
16227
  } else {
@@ -16243,7 +16257,10 @@ The key was not saved.`);
16243
16257
  `Signed in as @${check.handle} for ${LABEL2}.`,
16244
16258
  `API key stored at ${credentialsPath(home)} (never commit this file).`,
16245
16259
  ...await placeIdentity(check.handle, apiKey, apiBase),
16246
- NEXT_HINT
16260
+ NEXT_HINT,
16261
+ ...onArgv ? [
16262
+ `Note: the key was on this command line, where \`ps\` and shell history can see it. Next time run \`${invocation2()} login\` and paste it, or pipe it in: \`${invocation2()} login --api-key - < key.txt\`.`
16263
+ ] : []
16247
16264
  ].join("\n")
16248
16265
  );
16249
16266
  return 0;
@@ -16284,6 +16301,12 @@ The key was not saved.`);
16284
16301
  async function runStatus2(opts) {
16285
16302
  const home = profile2.home();
16286
16303
  const anchorFile2 = profile2.anchorFile?.() ?? null;
16304
+ const refusal2 = envKeyRefusal();
16305
+ if (refusal2 !== null) {
16306
+ if (opts.json) console.log(JSON.stringify({ configured: true, host: profile2.id, error: { kind: "env_key_conflict", detail: refusal2 }, home }));
16307
+ else console.error(refusal2);
16308
+ return 1;
16309
+ }
16287
16310
  const identity = resolveIdentity(home);
16288
16311
  const pending = readPending(home);
16289
16312
  const integration = readIntegrationStatus(home);
@@ -16476,6 +16499,8 @@ The key was not saved.`);
16476
16499
  let texts = NO_TEXTS;
16477
16500
  checks.push({ name: "node", verdict: "PASS", detail: process.version });
16478
16501
  checks.push({ name: "home", verdict: "PASS", detail: home });
16502
+ const refusal2 = envKeyRefusal();
16503
+ if (refusal2 !== null) checks.push({ name: "env-key", verdict: "FAIL", detail: refusal2 });
16479
16504
  const creds = readCredentials(home);
16480
16505
  if (creds === null) {
16481
16506
  checks.push({
@@ -17204,7 +17229,7 @@ import * as os4 from "os";
17204
17229
  import * as path6 from "path";
17205
17230
 
17206
17231
  // src/version.ts
17207
- var VERSION3 = "0.5.1";
17232
+ var VERSION3 = "0.5.3";
17208
17233
 
17209
17234
  // src/host.ts
17210
17235
  function codexHome() {
@@ -17274,11 +17299,91 @@ function serviceEnv() {
17274
17299
  }
17275
17300
 
17276
17301
  // src/placement.ts
17302
+ import * as fs7 from "fs";
17303
+ import * as path9 from "path";
17304
+
17305
+ // src/headers-helper.ts
17277
17306
  import * as fs6 from "fs";
17278
17307
  import * as path8 from "path";
17308
+ function headersHelperPathFor(identityHome2) {
17309
+ return path8.join(identityHome2, "bin", "mcp-headers.mjs");
17310
+ }
17311
+ var HEADERS_HELPER_SOURCE = [
17312
+ "// Written by @agentchatme/codex. Codex runs this on each connection to the MCP server",
17313
+ '// "agentchat" (its http_headers_helper) and sends what it prints as headers: the',
17314
+ "// Authorization header for the key in the credentials file of this identity home, or",
17315
+ "// nothing when there is none. It reads no environment variable. Do not edit: install",
17316
+ "// and doctor --fix rewrite it.",
17317
+ "import { readFileSync } from 'node:fs'",
17318
+ "let headers = {}",
17319
+ "try {",
17320
+ " const creds = JSON.parse(readFileSync(new URL('../credentials', import.meta.url), 'utf8'))",
17321
+ " const key = creds !== null && typeof creds.api_key === 'string' ? creds.api_key.trim() : ''",
17322
+ " if (key.length >= 20 && !/\\s/.test(key)) headers = { Authorization: `Bearer ${key}` }",
17323
+ "} catch {}",
17324
+ "process.stdout.write(JSON.stringify(headers))",
17325
+ ""
17326
+ ].join("\n");
17327
+ function headersHelperCommand(script, node = process.execPath, platform = process.platform) {
17328
+ const paths = [node, script];
17329
+ if (paths.some((p) => /[\r\n]/.test(p))) return null;
17330
+ if (platform === "win32") return paths.some((p) => /["%$`]/.test(p)) ? null : paths.map((p) => `"${p}"`).join(" ");
17331
+ return paths.map((p) => `'${p.replace(/'/g, `'\\''`)}'`).join(" ");
17332
+ }
17333
+ var POSIX_TOKEN = "'((?:[^'\\r\\n]|'\\\\'')*)'";
17334
+ function parseHeadersHelper(command) {
17335
+ if (typeof command !== "string") return null;
17336
+ const posix3 = new RegExp(`^${POSIX_TOKEN} ${POSIX_TOKEN}$`).exec(command);
17337
+ if (posix3 !== null) return { node: posix3[1].replace(/'\\''/g, "'"), script: posix3[2].replace(/'\\''/g, "'") };
17338
+ const win = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
17339
+ return win === null ? null : { node: win[1], script: win[2] };
17340
+ }
17341
+ function sourceCurrent(script) {
17342
+ try {
17343
+ return fs6.readFileSync(script, "utf-8") === HEADERS_HELPER_SOURCE;
17344
+ } catch {
17345
+ return false;
17346
+ }
17347
+ }
17348
+ function isExecutable(file) {
17349
+ try {
17350
+ fs6.accessSync(file, fs6.constants.X_OK);
17351
+ return fs6.statSync(file).isFile();
17352
+ } catch {
17353
+ return false;
17354
+ }
17355
+ }
17356
+ function writeHeadersHelper(identityHome2) {
17357
+ const script = headersHelperPathFor(identityHome2);
17358
+ if (sourceCurrent(script)) return;
17359
+ atomicWriteFile(script, HEADERS_HELPER_SOURCE, 384);
17360
+ }
17361
+ function headersHelperState(command, identityHome2) {
17362
+ const parsed = parseHeadersHelper(command);
17363
+ if (parsed === null || path8.resolve(parsed.script) !== path8.resolve(headersHelperPathFor(identityHome2))) return "missing";
17364
+ return sourceCurrent(parsed.script) && isExecutable(parsed.node) ? "current" : "stale";
17365
+ }
17366
+ function headersHelperProblem(command, apiKey, identityHome2) {
17367
+ const parsed = parseHeadersHelper(command);
17368
+ if (parsed === null) return "there is no headers helper of this integration";
17369
+ const result = spawnCommandSync(parsed.node, [parsed.script], { encoding: "utf-8", timeout: 1e4, windowsHide: true, cwd: identityHome2 });
17370
+ if (result.error) return `its headers helper could not run (${result.error.message})`;
17371
+ if (result.status !== 0) return `its headers helper exited ${result.status}`;
17372
+ let headers;
17373
+ try {
17374
+ headers = JSON.parse(String(result.stdout ?? ""));
17375
+ } catch {
17376
+ return "its headers helper printed something other than a JSON object";
17377
+ }
17378
+ const auth = headers !== null && typeof headers === "object" ? headers["Authorization"] : void 0;
17379
+ if (auth === void 0) return `its headers helper finds no key in ${path8.join(identityHome2, "credentials")}`;
17380
+ return auth === `Bearer ${apiKey}` ? null : "its headers helper yields a key other than this agent's credentials";
17381
+ }
17382
+
17383
+ // src/placement.ts
17279
17384
  var TOML_START = "# agentchat:start";
17280
17385
  var TOML_END = "# agentchat:end";
17281
- var LEGACY_BUNDLE = path8.join("bin", "agentchat.mjs");
17386
+ var LEGACY_BUNDLE = path9.join("bin", "agentchat.mjs");
17282
17387
  var LEGACY_MANUAL = "SKILL.md";
17283
17388
  function lineSetsVariable(line, name) {
17284
17389
  const trimmed = line.trim();
@@ -17305,73 +17410,112 @@ function upsertDotEnvLine(content, name, value) {
17305
17410
  if (!next.endsWith("\n")) next += "\n";
17306
17411
  return next;
17307
17412
  }
17308
- function removeDotEnvLine(content, name) {
17309
- const next = content.split(/\r?\n/).filter((line) => !lineSetsVariable(line, name));
17310
- return next.join("\n");
17413
+ function removeDotEnvLine(content, name, value) {
17414
+ const eol = content.includes("\r\n") ? "\r\n" : "\n";
17415
+ const next = content.split(/\r?\n/).filter((line) => !lineSetsVariable(line, name) || value !== void 0 && valueOfLine(line) !== value);
17416
+ return next.join(eol);
17417
+ }
17418
+ function valueOfLine(line) {
17419
+ return stripQuotes(line.slice(line.indexOf("=") + 1).trim());
17420
+ }
17421
+ function keysInDotEnv() {
17422
+ try {
17423
+ return fs7.readFileSync(dotEnvPath(), "utf-8").split(/\r?\n/).filter((line) => lineSetsVariable(line, API_KEY_ENV)).map(valueOfLine).filter((v) => v.length > 0);
17424
+ } catch {
17425
+ return [];
17426
+ }
17311
17427
  }
17312
17428
  function stripQuotes(value) {
17313
17429
  if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) return value.slice(1, -1);
17314
17430
  return value;
17315
17431
  }
17316
- function readKeyFromDotEnv() {
17432
+ function clearDotEnvKey(apiKey) {
17433
+ const file = dotEnvPath();
17434
+ const key = apiKey.trim();
17317
17435
  try {
17318
- for (const line of fs6.readFileSync(dotEnvPath(), "utf-8").split(/\r?\n/)) {
17319
- if (!lineSetsVariable(line, API_KEY_ENV)) continue;
17320
- return stripQuotes(line.slice(line.indexOf("=") + 1).trim()) || void 0;
17436
+ const held = keysInDotEnv();
17437
+ if (held.length === 0) return { name: "key", status: "ok", detail: `the key is in ${path9.join(identityHome(), "credentials")} only (none in ${file})` };
17438
+ const others = held.some((v) => v !== key);
17439
+ if (held.includes(key)) {
17440
+ const existing = fs7.readFileSync(file, "utf-8");
17441
+ const next = removeDotEnvLine(existing, API_KEY_ENV, key);
17442
+ if (next.trim().length === 0) fs7.rmSync(file, { force: true });
17443
+ else atomicWriteFile(file, next, fs7.statSync(file).mode & 511);
17444
+ }
17445
+ if (others) {
17446
+ return {
17447
+ name: "key",
17448
+ status: "warned",
17449
+ detail: `${file} sets ${API_KEY_ENV} to a key that is not this agent's: Codex exports it to every command a session runs, and it no longer reaches the AgentChat tools \u2014 remove that line unless something else of yours needs it`
17450
+ };
17321
17451
  }
17322
- } catch {
17452
+ return {
17453
+ name: "key",
17454
+ status: "changed",
17455
+ detail: `${API_KEY_ENV} taken out of ${file} (an earlier release kept the key there, so Codex exported it to every command a session ran; a Codex already running keeps it until it restarts)`
17456
+ };
17457
+ } catch (err) {
17458
+ return { name: "key", status: "failed", detail: `could not update ${file}: ${String(err)}` };
17323
17459
  }
17324
- return void 0;
17325
17460
  }
17326
- function placeKey(apiKey) {
17461
+ function keepDotEnvKeyForHandWritten(apiKey) {
17327
17462
  const trimmed = apiKey.trim();
17463
+ const warning = `your own [mcp_servers.${MCP_SERVER_NAME}] reads ${API_KEY_ENV}, so this agent's key is kept in ${dotEnvPath()} \u2014 Codex exports it to every command a session runs; remove that entry (the installer then writes one that reads the key from ${path9.join(identityHome(), "credentials")}) to keep it out`;
17328
17464
  if (!trimmed || /[\r\n#"'\s]/.test(trimmed)) return { name: "key", status: "failed", detail: "the key is empty or contains characters a .env line cannot carry" };
17329
17465
  try {
17330
17466
  const file = dotEnvPath();
17331
- fs6.mkdirSync(path8.dirname(file), { recursive: true });
17332
- const existing = fs6.existsSync(file) ? fs6.readFileSync(file, "utf-8") : "";
17467
+ const existing = fs7.existsSync(file) ? fs7.readFileSync(file, "utf-8") : "";
17333
17468
  const next = upsertDotEnvLine(existing, API_KEY_ENV, trimmed);
17334
- if (next === existing) {
17335
- try {
17336
- fs6.chmodSync(file, 384);
17337
- } catch {
17338
- }
17339
- return { name: "key", status: "ok", detail: `${API_KEY_ENV} in ${file}` };
17340
- }
17341
- atomicWriteFile(file, next, 384);
17342
- return { name: "key", status: "changed", detail: `${API_KEY_ENV} in ${file} (Codex loads it at startup; a running Codex picks it up on its next start)` };
17469
+ if (next !== existing) atomicWriteFile(file, next, 384);
17470
+ return { name: "key", status: "warned", detail: warning };
17343
17471
  } catch (err) {
17344
17472
  return { name: "key", status: "failed", detail: `could not write ${API_KEY_ENV} to ${dotEnvPath()}: ${String(err)}` };
17345
17473
  }
17346
17474
  }
17347
- function removeKey() {
17475
+ function handWrittenReadsKeyVariable() {
17476
+ const text2 = handWrittenAgentchatServer(readConfigText());
17477
+ return text2 !== null && new RegExp(`\\b${API_KEY_ENV}\\b`).test(text2);
17478
+ }
17479
+ function removeKey(apiKey) {
17348
17480
  const file = dotEnvPath();
17349
17481
  try {
17350
- if (!fs6.existsSync(file)) return { name: "key", status: "ok", detail: `no ${API_KEY_ENV} to remove` };
17351
- const existing = fs6.readFileSync(file, "utf-8");
17352
- const next = removeDotEnvLine(existing, API_KEY_ENV);
17353
- if (next === existing) return { name: "key", status: "ok", detail: `no ${API_KEY_ENV} in ${file}` };
17354
- if (next.trim().length === 0) fs6.rmSync(file, { force: true });
17355
- else atomicWriteFile(file, next, 384);
17482
+ const held = keysInDotEnv();
17483
+ if (held.length === 0) return { name: "key", status: "ok", detail: `no ${API_KEY_ENV} in ${file}` };
17484
+ const key = apiKey?.trim() ?? null;
17485
+ const ours = key !== null && held.includes(key);
17486
+ if (ours) {
17487
+ const existing = fs7.readFileSync(file, "utf-8");
17488
+ const next = removeDotEnvLine(existing, API_KEY_ENV, key);
17489
+ if (next.trim().length === 0) fs7.rmSync(file, { force: true });
17490
+ else atomicWriteFile(file, next, fs7.statSync(file).mode & 511);
17491
+ }
17492
+ if (held.some((v) => v !== key)) {
17493
+ return { name: "key", status: "warned", detail: `${file} sets ${API_KEY_ENV} to a key that is not this agent's; left as it is \u2014 remove that line unless something else of yours needs it` };
17494
+ }
17356
17495
  return { name: "key", status: "changed", detail: `${API_KEY_ENV} removed from ${file}` };
17357
17496
  } catch (err) {
17358
17497
  return { name: "key", status: "failed", detail: `could not update ${file}: ${String(err)}` };
17359
17498
  }
17360
17499
  }
17361
17500
  function tomlBasicString(value) {
17362
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
17501
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/[\u0000-\u001f\u007f]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
17502
+ return `"${escaped}"`;
17363
17503
  }
17364
17504
  var CLIENT_HEADER = "X-AgentChat-Client";
17365
17505
  function mcpHttpHeadersLine() {
17366
17506
  const pairs = Object.entries(clientHeadersOf(CLIENT)).map(([name, value]) => `${tomlBasicString(name)} = ${tomlBasicString(value)}`);
17367
17507
  return `http_headers = { ${pairs.join(", ")} }`;
17368
17508
  }
17369
- function mcpBlock(apiBase) {
17509
+ function currentHeadersHelperCommand() {
17510
+ return headersHelperCommand(headersHelperPathFor(identityHome()));
17511
+ }
17512
+ function mcpBlock(apiBase, helper) {
17370
17513
  return [
17371
17514
  TOML_START,
17372
17515
  `[mcp_servers.${MCP_SERVER_NAME}]`,
17373
17516
  `url = "${hostedMcpUrl2(apiBase)}"`,
17374
- `bearer_token_env_var = "${API_KEY_ENV}"`,
17517
+ "# The key: Codex runs this on each connection and sends the Authorization header it prints, read from agentchat/credentials. No key in this file or in .env.",
17518
+ `http_headers_helper = ${tomlBasicString(helper)}`,
17375
17519
  "# Names this runtime to the hosted tools: no wake-webhook tools for an agent the listener wakes.",
17376
17520
  mcpHttpHeadersLine(),
17377
17521
  "startup_timeout_sec = 30",
@@ -17380,6 +17524,18 @@ function mcpBlock(apiBase) {
17380
17524
  TOML_END
17381
17525
  ].join("\n");
17382
17526
  }
17527
+ function fencedHelperCommand(config) {
17528
+ const start2 = config.indexOf(TOML_START);
17529
+ const end = config.indexOf(TOML_END);
17530
+ if (start2 < 0 || end <= start2) return void 0;
17531
+ const line = /^http_headers_helper = ("(?:[^"\\]|\\.)*")\s*$/m.exec(config.slice(start2, end));
17532
+ if (line === null) return void 0;
17533
+ try {
17534
+ return JSON.parse(line[1]);
17535
+ } catch {
17536
+ return void 0;
17537
+ }
17538
+ }
17383
17539
  function upsertTomlBlock(existing, block) {
17384
17540
  const cleaned = stripTomlBlock(existing);
17385
17541
  const trimmed = cleaned.replace(/\n+$/, "");
@@ -17421,7 +17577,7 @@ function hasUnfencedAgentchatServer(existing) {
17421
17577
  }
17422
17578
  function readConfigText() {
17423
17579
  try {
17424
- return fs6.readFileSync(configPath(), "utf-8");
17580
+ return fs7.readFileSync(configPath(), "utf-8");
17425
17581
  } catch {
17426
17582
  return "";
17427
17583
  }
@@ -17429,47 +17585,60 @@ function readConfigText() {
17429
17585
  function inspectMcpBlock(apiBase) {
17430
17586
  let config = "";
17431
17587
  try {
17432
- config = fs6.readFileSync(configPath(), "utf-8");
17588
+ config = fs7.readFileSync(configPath(), "utf-8");
17433
17589
  } catch {
17434
17590
  return "missing";
17435
17591
  }
17436
17592
  if (hasUnfencedAgentchatServer(config)) return "foreign";
17437
- if (config.includes(mcpBlock(apiBase))) return "current";
17593
+ const helper = fencedHelperCommand(config);
17594
+ if (helper !== void 0 && headersHelperState(helper, identityHome()) === "current" && config.includes(mcpBlock(apiBase, helper))) return "current";
17438
17595
  return config.includes(TOML_START) ? "stale" : "missing";
17439
17596
  }
17440
- function placeMcp(apiBase) {
17597
+ function placeMcp(apiBase, apiKey) {
17441
17598
  const file = configPath();
17442
17599
  const state = inspectMcpBlock(apiBase);
17443
17600
  if (state === "foreign") {
17444
17601
  return { name: "mcp", status: "skipped", detail: `${file} already defines [mcp_servers.${MCP_SERVER_NAME}] outside the agentchat block \u2014 left untouched; remove it and re-run if it is not yours` };
17445
17602
  }
17446
- if (state === "current") return { name: "mcp", status: "ok", detail: `[mcp_servers.${MCP_SERVER_NAME}] \u2192 ${hostedMcpUrl2(apiBase)} (bearer token from ${API_KEY_ENV}) in ${file}` };
17447
17603
  try {
17448
- fs6.mkdirSync(path8.dirname(file), { recursive: true });
17449
- const existing = fs6.existsSync(file) ? fs6.readFileSync(file, "utf-8") : "";
17604
+ writeHeadersHelper(identityHome());
17605
+ } catch (err) {
17606
+ return { name: "mcp", status: "failed", detail: `could not write the headers helper ${headersHelperPathFor(identityHome())}: ${String(err)}` };
17607
+ }
17608
+ const keyNote = `the key stays in ${path9.join(identityHome(), "credentials")}; Codex asks ${headersHelperPathFor(identityHome())} for it`;
17609
+ if (state === "current") return { name: "mcp", status: "ok", detail: `[mcp_servers.${MCP_SERVER_NAME}] \u2192 ${hostedMcpUrl2(apiBase)} (${keyNote}) in ${file}` };
17610
+ const helper = currentHeadersHelperCommand();
17611
+ if (helper === null) {
17612
+ return { name: "mcp", status: "failed", detail: `the path of Node (${process.execPath}) or of ${headersHelperPathFor(identityHome())} holds a character a shell command cannot carry quoted; move it, then re-run` };
17613
+ }
17614
+ const problem = apiKey !== void 0 ? headersHelperProblem(helper, apiKey, identityHome()) : null;
17615
+ if (problem !== null) return { name: "mcp", status: "failed", detail: `[mcp_servers.${MCP_SERVER_NAME}] left as it was: ${problem}` };
17616
+ try {
17617
+ fs7.mkdirSync(path9.dirname(file), { recursive: true });
17618
+ const existing = fs7.existsSync(file) ? fs7.readFileSync(file, "utf-8") : "";
17450
17619
  let mode = 384;
17451
17620
  try {
17452
- mode = fs6.statSync(file).mode & 511;
17621
+ mode = fs7.statSync(file).mode & 511;
17453
17622
  } catch {
17454
17623
  }
17455
- atomicWriteFile(file, upsertTomlBlock(existing, mcpBlock(apiBase)), mode);
17456
- return {
17457
- name: "mcp",
17458
- status: "changed",
17459
- detail: `[mcp_servers.${MCP_SERVER_NAME}] \u2192 ${hostedMcpUrl2(apiBase)} (bearer token from ${API_KEY_ENV}) in ${file}${state === "stale" ? " (the previous entry was replaced)" : ""}`
17460
- };
17624
+ atomicWriteFile(file, upsertTomlBlock(existing, mcpBlock(apiBase, helper)), mode);
17461
17625
  } catch (err) {
17462
17626
  return { name: "mcp", status: "failed", detail: `could not write ${file}: ${String(err)}` };
17463
17627
  }
17628
+ return {
17629
+ name: "mcp",
17630
+ status: "changed",
17631
+ detail: `[mcp_servers.${MCP_SERVER_NAME}] \u2192 ${hostedMcpUrl2(apiBase)} (${keyNote}) in ${file}${state === "stale" ? " (the previous entry was replaced)" : ""}`
17632
+ };
17464
17633
  }
17465
17634
  function removeMcp() {
17466
17635
  const file = configPath();
17467
17636
  try {
17468
- if (!fs6.existsSync(file)) return { name: "mcp", status: "ok", detail: "no config.toml" };
17469
- const existing = fs6.readFileSync(file, "utf-8");
17637
+ if (!fs7.existsSync(file)) return { name: "mcp", status: "ok", detail: "no config.toml" };
17638
+ const existing = fs7.readFileSync(file, "utf-8");
17470
17639
  const next = stripTomlBlock(existing);
17471
17640
  if (next === existing) return { name: "mcp", status: "ok", detail: `no agentchat block in ${file}` };
17472
- const mode = fs6.statSync(file).mode & 511;
17641
+ const mode = fs7.statSync(file).mode & 511;
17473
17642
  atomicWriteFile(file, next, mode);
17474
17643
  return { name: "mcp", status: "changed", detail: `[mcp_servers.${MCP_SERVER_NAME}] removed from ${file}` };
17475
17644
  } catch (err) {
@@ -17477,7 +17646,7 @@ function removeMcp() {
17477
17646
  }
17478
17647
  }
17479
17648
  function skillPresent() {
17480
- return fs6.existsSync(skillPath());
17649
+ return fs7.existsSync(skillPath());
17481
17650
  }
17482
17651
  function manualStep(result, removedLegacy) {
17483
17652
  const status = result.state === "failed" ? "failed" : result.upToDate === false ? "warned" : result.written || removedLegacy ? "changed" : "ok";
@@ -17485,11 +17654,11 @@ function manualStep(result, removedLegacy) {
17485
17654
  }
17486
17655
  async function placeSkill(manual, apiBase) {
17487
17656
  const result = await syncManual2({ path: skillPath(), served: manual, apiBase });
17488
- const legacy = path8.join(identityHome(), LEGACY_MANUAL);
17657
+ const legacy = path9.join(identityHome(), LEGACY_MANUAL);
17489
17658
  let removedLegacy = false;
17490
17659
  try {
17491
- if (fs6.existsSync(legacy)) {
17492
- fs6.rmSync(legacy, { force: true });
17660
+ if (fs7.existsSync(legacy)) {
17661
+ fs7.rmSync(legacy, { force: true });
17493
17662
  removedLegacy = true;
17494
17663
  }
17495
17664
  } catch {
@@ -17499,13 +17668,13 @@ async function placeSkill(manual, apiBase) {
17499
17668
  function removeSkill() {
17500
17669
  try {
17501
17670
  let removed = false;
17502
- if (fs6.existsSync(skillPath())) {
17503
- fs6.rmSync(skillDir(), { recursive: true, force: true });
17671
+ if (fs7.existsSync(skillPath())) {
17672
+ fs7.rmSync(skillDir(), { recursive: true, force: true });
17504
17673
  removed = true;
17505
17674
  }
17506
- const legacy = path8.join(identityHome(), LEGACY_MANUAL);
17507
- if (fs6.existsSync(legacy)) {
17508
- fs6.rmSync(legacy, { force: true });
17675
+ const legacy = path9.join(identityHome(), LEGACY_MANUAL);
17676
+ if (fs7.existsSync(legacy)) {
17677
+ fs7.rmSync(legacy, { force: true });
17509
17678
  removed = true;
17510
17679
  }
17511
17680
  return { name: "manual", status: removed ? "changed" : "ok", detail: removed ? "agentchat skill removed" : "no agentchat skill to remove" };
@@ -17533,7 +17702,7 @@ function placeOffer() {
17533
17702
  try {
17534
17703
  const declined = offerDeclined(identityHome());
17535
17704
  writeAnchor(anchorFile(), declined ? renderDeclinedBlock(hostCopy()) : renderUnregisteredBlock(hostCopy()));
17536
- return { name: "identity", status: "changed", detail: declined ? `${path8.basename(anchorFile())}: AgentChat present, not asking` : `${path8.basename(anchorFile())}: setup offer (no account yet)` };
17705
+ return { name: "identity", status: "changed", detail: declined ? `${path9.basename(anchorFile())}: AgentChat present, not asking` : `${path9.basename(anchorFile())}: setup offer (no account yet)` };
17537
17706
  } catch (err) {
17538
17707
  return { name: "identity", status: "failed", detail: `could not write ${anchorFile()}: ${String(err)}` };
17539
17708
  }
@@ -17574,29 +17743,29 @@ function withoutLegacyHooks(doc) {
17574
17743
  }
17575
17744
  function legacyHooksPresent() {
17576
17745
  try {
17577
- return withoutLegacyHooks(JSON.parse(fs6.readFileSync(hooksPath(), "utf-8"))).removed > 0;
17746
+ return withoutLegacyHooks(JSON.parse(fs7.readFileSync(hooksPath(), "utf-8"))).removed > 0;
17578
17747
  } catch {
17579
17748
  return false;
17580
17749
  }
17581
17750
  }
17582
17751
  function legacyBundlePresent() {
17583
- return fs6.existsSync(path8.join(identityHome(), LEGACY_BUNDLE));
17752
+ return fs7.existsSync(path9.join(identityHome(), LEGACY_BUNDLE));
17584
17753
  }
17585
17754
  function removeLegacyWiring() {
17586
17755
  const notes = [];
17587
17756
  const file = hooksPath();
17588
- if (fs6.existsSync(file)) {
17757
+ if (fs7.existsSync(file)) {
17589
17758
  try {
17590
- const parsed = JSON.parse(fs6.readFileSync(file, "utf-8"));
17759
+ const parsed = JSON.parse(fs7.readFileSync(file, "utf-8"));
17591
17760
  if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
17592
17761
  const { doc, removed } = withoutLegacyHooks(parsed);
17593
17762
  if (removed > 0) {
17594
17763
  let mode = 384;
17595
17764
  try {
17596
- mode = fs6.statSync(file).mode & 511;
17765
+ mode = fs7.statSync(file).mode & 511;
17597
17766
  } catch {
17598
17767
  }
17599
- if (Object.keys(doc).length === 0) fs6.unlinkSync(file);
17768
+ if (Object.keys(doc).length === 0) fs7.unlinkSync(file);
17600
17769
  else atomicWriteFile(file, JSON.stringify(doc, null, 2) + "\n", mode);
17601
17770
  notes.push(`${removed} lifecycle hook${removed === 1 ? "" : "s"} removed from hooks.json (receiving no longer needs hooks)`);
17602
17771
  }
@@ -17605,10 +17774,10 @@ function removeLegacyWiring() {
17605
17774
  return { name: "legacy", status: "failed", detail: `${file} could not be read as JSON; the old AgentChat hooks were left in place: ${String(err)}` };
17606
17775
  }
17607
17776
  }
17608
- const bundle = path8.join(identityHome(), LEGACY_BUNDLE);
17609
- if (fs6.existsSync(bundle)) {
17777
+ const bundle = path9.join(identityHome(), LEGACY_BUNDLE);
17778
+ if (fs7.existsSync(bundle)) {
17610
17779
  try {
17611
- fs6.rmSync(bundle, { force: true });
17780
+ fs7.rmSync(bundle, { force: true });
17612
17781
  notes.push("stable CLI bundle removed");
17613
17782
  } catch {
17614
17783
  }
@@ -17623,26 +17792,32 @@ async function placeAll(identity, manual) {
17623
17792
  if (legacy) steps.push(legacy);
17624
17793
  steps.push(await placeSkill(manual, identity?.apiBase ?? null));
17625
17794
  if (identity) {
17626
- steps.push(placeKey(identity.apiKey));
17627
- steps.push(placeMcp(identity.apiBase));
17795
+ const mcp = placeMcp(identity.apiBase, identity.apiKey);
17796
+ steps.push(mcp);
17797
+ if (mcp.status === "ok" || mcp.status === "changed") steps.push(clearDotEnvKey(identity.apiKey));
17798
+ else if (mcp.status === "skipped" && handWrittenReadsKeyVariable()) steps.push(keepDotEnvKeyForHandWritten(identity.apiKey));
17628
17799
  steps.push(placeIdentityLine(identity.handle, identity.identityLine));
17629
17800
  } else {
17630
17801
  steps.push(placeOffer());
17631
17802
  }
17632
17803
  return steps;
17633
17804
  }
17634
- function unplaceIdentity() {
17635
- return [removeKey(), placeOffer()];
17805
+ function unplaceIdentity(apiKey) {
17806
+ return [removeKey(apiKey), placeOffer()];
17636
17807
  }
17637
- function removePlacement() {
17808
+ function removePlacement(apiKey) {
17638
17809
  const steps = [];
17639
17810
  const legacy = removeLegacyWiring();
17640
17811
  if (legacy) steps.push(legacy);
17641
- steps.push(removeKey());
17812
+ steps.push(removeKey(apiKey));
17642
17813
  steps.push(removeMcp());
17814
+ try {
17815
+ fs7.rmSync(headersHelperPathFor(identityHome()), { force: true });
17816
+ } catch {
17817
+ }
17643
17818
  steps.push(removeSkill());
17644
17819
  try {
17645
- steps.push({ name: "identity", status: removeAnchorAt(anchorFile()) === "removed" ? "changed" : "ok", detail: `${path8.basename(anchorFile())} AgentChat block removed` });
17820
+ steps.push({ name: "identity", status: removeAnchorAt(anchorFile()) === "removed" ? "changed" : "ok", detail: `${path9.basename(anchorFile())} AgentChat block removed` });
17646
17821
  } catch (err) {
17647
17822
  steps.push({ name: "identity", status: "failed", detail: `could not remove the AgentChat block from ${anchorFile()}: ${err instanceof Error ? err.message : String(err)} \u2014 remove it by hand` });
17648
17823
  }
@@ -17669,26 +17844,36 @@ function checkPlacement(identity, manual) {
17669
17844
  const checks = [];
17670
17845
  if (identity) {
17671
17846
  checks.push(identityCheck(identity));
17672
- const inDotEnv = readKeyFromDotEnv();
17673
- checks.push({
17674
- name: "key",
17675
- ok: inDotEnv === identity.apiKey,
17676
- detail: inDotEnv === identity.apiKey ? `${API_KEY_ENV} in ${dotEnvPath()} matches this agent's credentials` : inDotEnv === void 0 ? `${API_KEY_ENV} is not in ${dotEnvPath()} \u2014 the hosted tools cannot authenticate` : `${API_KEY_ENV} in ${dotEnvPath()} differs from this agent's credentials`
17677
- });
17847
+ const inDotEnv = keysInDotEnv();
17848
+ const handWritten = inspectMcpBlock(identity.apiBase) === "foreign" && handWrittenReadsKeyVariable();
17849
+ checks.push(
17850
+ handWritten ? {
17851
+ name: "key",
17852
+ ok: inDotEnv.length > 0 && inDotEnv.every((v) => v === identity.apiKey),
17853
+ verdict: inDotEnv.length > 0 && inDotEnv.every((v) => v === identity.apiKey) ? "WARN" : "FAIL",
17854
+ detail: inDotEnv.length > 0 && inDotEnv.every((v) => v === identity.apiKey) ? `in ${dotEnvPath()} for your own [mcp_servers.${MCP_SERVER_NAME}], which reads ${API_KEY_ENV}: Codex exports it to every command a session runs` : `your own [mcp_servers.${MCP_SERVER_NAME}] reads ${API_KEY_ENV}, and ${dotEnvPath()} does not hold this agent's key there`
17855
+ } : {
17856
+ name: "key",
17857
+ ok: inDotEnv.length === 0,
17858
+ ...inDotEnv.some((v) => v !== identity.apiKey) ? { verdict: "WARN" } : {},
17859
+ detail: inDotEnv.length === 0 ? `in ${path9.join(identityHome(), "credentials")} only` : inDotEnv.some((v) => v !== identity.apiKey) ? `${dotEnvPath()} sets ${API_KEY_ENV} to a key that is not this agent's: Codex exports it to every command a session runs, and it no longer reaches the AgentChat tools \u2014 remove that line unless something else of yours needs it` : `${dotEnvPath()} still holds this agent's key (an earlier release put it there), so Codex exports it to every command a session runs \u2014 install or \`doctor --fix\` takes it out`
17860
+ }
17861
+ );
17678
17862
  }
17679
17863
  const skill = checkManual({ path: skillPath(), served: manual, apiBase: identity?.apiBase ?? null });
17680
17864
  checks.push({ name: "manual", ok: skill.state === "current" || skill.state === "unchecked", verdict: skill.verdict, detail: skill.detail });
17681
17865
  const mcp = inspectMcpBlock(identity?.apiBase ?? process.env["AGENTCHAT_API_BASE"]?.trim() ?? "https://api.agentchat.me");
17682
17866
  const handWrittenNamesClient = mcp === "foreign" && handWrittenSendsClientHeader(readConfigText());
17867
+ const helperProblem = mcp === "current" && identity ? headersHelperProblem(fencedHelperCommand(readConfigText()), identity.apiKey, identityHome()) : null;
17683
17868
  checks.push({
17684
17869
  name: "mcp",
17685
17870
  // A hand-written entry is the user's: nothing for this integration to
17686
17871
  // repair (ok), but said — a WARN — when it does not name this runtime to
17687
17872
  // the hosted tools: they then show it the wake-webhook tools, a second
17688
17873
  // way of being woken it does not need.
17689
- ok: mcp === "current" || mcp === "foreign",
17874
+ ok: mcp === "current" && helperProblem === null || mcp === "foreign",
17690
17875
  ...mcp === "foreign" && !handWrittenNamesClient ? { verdict: "WARN" } : {},
17691
- detail: mcp === "current" ? `[mcp_servers.${MCP_SERVER_NAME}] \u2192 hosted tools, bearer token from ${API_KEY_ENV}, named as Codex ${CLIENT.version}` : mcp === "foreign" ? handWrittenNamesClient ? `[mcp_servers.${MCP_SERVER_NAME}] is managed by hand in ${configPath()}` : `[mcp_servers.${MCP_SERVER_NAME}] is managed by hand in ${configPath()} and does not send ${CLIENT_HEADER}, so the hosted tools take this agent for an unknown client and show it the wake-webhook tools \u2014 add \`${mcpHttpHeadersLine()}\` to it` : mcp === "stale" ? `the agentchat block in ${configPath()} is from an older release` : `no [mcp_servers.${MCP_SERVER_NAME}] in ${configPath()} \u2014 the agent has no AgentChat tools`
17876
+ detail: mcp === "current" ? helperProblem !== null ? `[mcp_servers.${MCP_SERVER_NAME}]: ${helperProblem}` : `[mcp_servers.${MCP_SERVER_NAME}] \u2192 hosted tools, the key from ${headersHelperPathFor(identityHome())} (it reads ${path9.join(identityHome(), "credentials")}), named as Codex ${CLIENT.version}` : mcp === "foreign" ? handWrittenNamesClient ? `[mcp_servers.${MCP_SERVER_NAME}] is managed by hand in ${configPath()}` : `[mcp_servers.${MCP_SERVER_NAME}] is managed by hand in ${configPath()} and does not send ${CLIENT_HEADER}, so the hosted tools take this agent for an unknown client and show it the wake-webhook tools \u2014 add \`${mcpHttpHeadersLine()}\` to it` : mcp === "stale" ? `the agentchat block in ${configPath()} is from an older release, or its headers helper (${headersHelperPathFor(identityHome())}) or its Node is gone` : `no [mcp_servers.${MCP_SERVER_NAME}] in ${configPath()} \u2014 the agent has no AgentChat tools`
17692
17877
  });
17693
17878
  const leftovers = [legacyHooksPresent() ? "hooks in hooks.json" : null, legacyBundlePresent() ? "stable CLI bundle" : null].filter((v) => v !== null);
17694
17879
  checks.push({ name: "legacy", ok: leftovers.length === 0, detail: leftovers.length === 0 ? "no pre-0.1.0 wiring left" : `pre-0.1.0 wiring still present: ${leftovers.join(", ")}` });
@@ -17704,12 +17889,12 @@ function formatPlacement(steps) {
17704
17889
  }
17705
17890
 
17706
17891
  // src/identity.ts
17707
- import * as path11 from "path";
17892
+ import * as path12 from "path";
17708
17893
 
17709
- // node_modules/.pnpm/@agentchatme+agent-core@0.5.1/node_modules/@agentchatme/agent-core/dist/presets.js
17710
- import * as fs7 from "fs";
17894
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.3/node_modules/@agentchatme/agent-core/dist/presets.js
17895
+ import * as fs8 from "fs";
17711
17896
  import * as os5 from "os";
17712
- import * as path9 from "path";
17897
+ import * as path10 from "path";
17713
17898
  import * as fs24 from "fs";
17714
17899
  import * as os23 from "os";
17715
17900
  import * as path24 from "path";
@@ -17886,16 +18071,16 @@ var ANSWER_SETTINGS = JSON.stringify({
17886
18071
  var MCP_STARTUP_WAIT_MS = "15000";
17887
18072
  function claudeConfigDirFrom(env = process.env) {
17888
18073
  const override = env["CLAUDE_CONFIG_DIR"];
17889
- return override !== void 0 && override.trim().length > 0 ? path9.resolve(override) : void 0;
18074
+ return override !== void 0 && override.trim().length > 0 ? path10.resolve(override) : void 0;
17890
18075
  }
17891
18076
  function claudeHomeFor(configDirOverride) {
17892
- return configDirOverride ?? path9.join(os5.homedir(), ".claude");
18077
+ return configDirOverride ?? path10.join(os5.homedir(), ".claude");
17893
18078
  }
17894
18079
  function claudeProjectsDirFor(configDirOverride) {
17895
- return path9.join(claudeHomeFor(configDirOverride), "projects");
18080
+ return path10.join(claudeHomeFor(configDirOverride), "projects");
17896
18081
  }
17897
18082
  function claudeUserStatePathFor(configDirOverride) {
17898
- return configDirOverride !== void 0 ? path9.join(configDirOverride, ".claude.json") : path9.join(os5.homedir(), ".claude.json");
18083
+ return configDirOverride !== void 0 ? path10.join(configDirOverride, ".claude.json") : path10.join(os5.homedir(), ".claude.json");
17899
18084
  }
17900
18085
  function claudeProcessEnv(configDirOverride, source) {
17901
18086
  const env = { ...source };
@@ -17924,7 +18109,7 @@ async function claudeSignIn(configDirOverride, command = "claude", timeoutMs = P
17924
18109
  if (status.status === 0) return { signedIn: true, unanswered: null };
17925
18110
  }
17926
18111
  const configDir = claudeHomeFor(configDirOverride);
17927
- if (fs7.existsSync(path9.join(configDir, ".credentials.json"))) return { signedIn: true, unanswered: null };
18112
+ if (fs8.existsSync(path10.join(configDir, ".credentials.json"))) return { signedIn: true, unanswered: null };
17928
18113
  if (process.platform !== "darwin") return { signedIn: false, unanswered: null };
17929
18114
  const keychain = await runProbe("security", ["find-generic-password", "-s", "Claude Code-credentials"], { timeoutMs: Math.min(timeoutMs, 5e3), ...signal !== void 0 ? { signal } : {} });
17930
18115
  return { signedIn: !keychain.error && keychain.status === 0, unanswered: null };
@@ -17942,10 +18127,10 @@ async function inspectClaudeRuntime(configDirOverride, command = "claude", timeo
17942
18127
  };
17943
18128
  }
17944
18129
  function deniedAncestorOf(dir, denied) {
17945
- const target = path9.resolve(dir);
18130
+ const target = path10.resolve(dir);
17946
18131
  for (const raw of denied) {
17947
- const root = path9.resolve(raw);
17948
- if (target === root || target.startsWith(root.endsWith(path9.sep) ? root : root + path9.sep)) return root;
18132
+ const root = path10.resolve(raw);
18133
+ if (target === root || target.startsWith(root.endsWith(path10.sep) ? root : root + path10.sep)) return root;
17949
18134
  }
17950
18135
  return null;
17951
18136
  }
@@ -17953,10 +18138,10 @@ function expressibleAllow(raw) {
17953
18138
  return expressible(raw) && !/[*?[\]\\!#]/.test(raw);
17954
18139
  }
17955
18140
  function workdirPaths(workdir) {
17956
- const given = path9.resolve(workdir);
18141
+ const given = path10.resolve(workdir);
17957
18142
  let real = given;
17958
18143
  try {
17959
- real = fs7.realpathSync(given);
18144
+ real = fs8.realpathSync(given);
17960
18145
  } catch {
17961
18146
  }
17962
18147
  return real === given ? [given] : [given, real];
@@ -18052,10 +18237,10 @@ function claudeManagedSettingsDir(platform = process.platform) {
18052
18237
  return "/etc/claude-code";
18053
18238
  }
18054
18239
  function gitRootOf(dir) {
18055
- let current = path9.resolve(dir);
18240
+ let current = path10.resolve(dir);
18056
18241
  for (; ; ) {
18057
- if (fs7.existsSync(path9.join(current, ".git"))) return current;
18058
- const parent = path9.dirname(current);
18242
+ if (fs8.existsSync(path10.join(current, ".git"))) return current;
18243
+ const parent = path10.dirname(current);
18059
18244
  if (parent === current) return null;
18060
18245
  current = parent;
18061
18246
  }
@@ -18064,17 +18249,17 @@ function claudeSettingsFilesGrantingDirectories(configDirOverride, workdir) {
18064
18249
  const managed = claudeManagedSettingsDir();
18065
18250
  const dropIns = (() => {
18066
18251
  try {
18067
- return fs7.readdirSync(path9.join(managed, "managed-settings.d")).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => path9.join(managed, "managed-settings.d", name));
18252
+ return fs8.readdirSync(path10.join(managed, "managed-settings.d")).filter((name) => name.endsWith(".json") && !name.startsWith(".")).sort().map((name) => path10.join(managed, "managed-settings.d", name));
18068
18253
  } catch {
18069
18254
  return [];
18070
18255
  }
18071
18256
  })();
18072
- const cwdLocal = path9.join(path9.resolve(workdir), ".claude", "settings.local.json");
18257
+ const cwdLocal = path10.join(path10.resolve(workdir), ".claude", "settings.local.json");
18073
18258
  const root = gitRootOf(workdir);
18074
- const rootLocal = root !== null ? path9.join(root, ".claude", "settings.local.json") : cwdLocal;
18259
+ const rootLocal = root !== null ? path10.join(root, ".claude", "settings.local.json") : cwdLocal;
18075
18260
  return [
18076
- path9.join(claudeHomeFor(configDirOverride), "settings.json"),
18077
- path9.join(managed, "managed-settings.json"),
18261
+ path10.join(claudeHomeFor(configDirOverride), "settings.json"),
18262
+ path10.join(managed, "managed-settings.json"),
18078
18263
  ...dropIns,
18079
18264
  .../* @__PURE__ */ new Set([rootLocal, cwdLocal])
18080
18265
  ];
@@ -18083,7 +18268,7 @@ function claudeExtraDirectoriesGrant(configDirOverride, workdir) {
18083
18268
  for (const file of claudeSettingsFilesGrantingDirectories(configDirOverride, workdir)) {
18084
18269
  let text2;
18085
18270
  try {
18086
- text2 = fs7.readFileSync(file, "utf-8");
18271
+ text2 = fs8.readFileSync(file, "utf-8");
18087
18272
  } catch {
18088
18273
  continue;
18089
18274
  }
@@ -18103,7 +18288,7 @@ function extraDirectoriesRefusal(grant) {
18103
18288
  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).`;
18104
18289
  }
18105
18290
  function claudeAnswerFallbackWorkdir(configDirOverride) {
18106
- return path9.join(claudeHomeFor(configDirOverride), "agentchat-answer-workdir");
18291
+ return path10.join(claudeHomeFor(configDirOverride), "agentchat-answer-workdir");
18107
18292
  }
18108
18293
  var ClaudeRunner = class _ClaudeRunner {
18109
18294
  constructor(options) {
@@ -18169,17 +18354,17 @@ var ClaudeRunner = class _ClaudeRunner {
18169
18354
  log.warn(`${why}: runs can read those paths.`);
18170
18355
  }
18171
18356
  }
18172
- if (this.options.mcpConfigPath !== void 0 && !fs7.existsSync(this.options.mcpConfigPath)) {
18357
+ if (this.options.mcpConfigPath !== void 0 && !fs8.existsSync(this.options.mcpConfigPath)) {
18173
18358
  return { ok: false, detail: `the hosted tool config ${this.options.mcpConfigPath} is missing` };
18174
18359
  }
18175
- fs7.mkdirSync(this.workdir(), { recursive: true, mode: 448 });
18360
+ fs8.mkdirSync(this.workdir(), { recursive: true, mode: 448 });
18176
18361
  return { ok: true };
18177
18362
  }
18178
18363
  /** `<dir>/<stem>.<run id><ext>`: a file of this run's own beside `file` (the run id reduced to letters, digits and `-`). */
18179
18364
  static perRun(file, runId, ext) {
18180
- const stem = path9.basename(file, path9.extname(file));
18365
+ const stem = path10.basename(file, path10.extname(file));
18181
18366
  const id = runId.replace(/[^A-Za-z0-9-]/g, "").slice(0, 64) || "run";
18182
- return path9.join(path9.dirname(file), `${stem}.${id}${ext}`);
18367
+ return path10.join(path10.dirname(file), `${stem}.${id}${ext}`);
18183
18368
  }
18184
18369
  /** The answer run's own files for `runId`: its AgentChat-only tool config (integration path) and its identity-line file. */
18185
18370
  answerRunFiles(runId) {
@@ -18244,7 +18429,7 @@ var ClaudeRunner = class _ClaudeRunner {
18244
18429
  const identityFile = answer && request.identityLine !== void 0 ? files.identityFile : void 0;
18245
18430
  const written = [];
18246
18431
  const cleanup = () => {
18247
- for (const file of written) fs7.rmSync(file, { force: true });
18432
+ for (const file of written) fs8.rmSync(file, { force: true });
18248
18433
  };
18249
18434
  if (answerMcp !== void 0 && files.mcpConfigPath !== void 0) {
18250
18435
  const key = answerMcp.apiKey();
@@ -18289,7 +18474,7 @@ var ClaudeRunner = class _ClaudeRunner {
18289
18474
  }
18290
18475
  };
18291
18476
  function claudeMcpConfigPath(home) {
18292
- return path9.join(home, "presets", `${CLAUDE_CODE_PRESET}.mcp.json`);
18477
+ return path10.join(home, "presets", `${CLAUDE_CODE_PRESET}.mcp.json`);
18293
18478
  }
18294
18479
  var claudeCodePreset = {
18295
18480
  name: CLAUDE_CODE_PRESET,
@@ -18323,7 +18508,7 @@ var claudeCodePreset = {
18323
18508
  profile: ctx.profile,
18324
18509
  // The listener's home (its key and this file), the user-scope MCP state
18325
18510
  // and an integration's identity home beside it: no run reads a key.
18326
- denyReadPaths: [ctx.home, claudeUserStatePathFor(configDir), path9.join(claudeHomeFor(configDir), "agentchat")],
18511
+ denyReadPaths: [ctx.home, claudeUserStatePathFor(configDir), path10.join(claudeHomeFor(configDir), "agentchat")],
18327
18512
  mcpConfigPath,
18328
18513
  workdirAdvice: "Start the listener from a directory outside it, or pass --workdir.",
18329
18514
  // On POSIX a listener's run must not start with its key readable; on
@@ -18725,9 +18910,35 @@ var PRESETS = Object.freeze({
18725
18910
 
18726
18911
  // src/runner.ts
18727
18912
  var CodexRunner2 = class extends CodexRunner {
18913
+ identityHome;
18914
+ helper;
18728
18915
  constructor(options) {
18729
18916
  const { identityHome: identityHome2, ...rest } = options;
18730
- super({ ...rest, apiKey: () => resolveIdentity(identityHome2)?.apiKey ?? null, keyEnv: API_KEY_ENV });
18917
+ super({ ...rest, apiKey: () => null, keyEnv: API_KEY_ENV });
18918
+ this.identityHome = identityHome2;
18919
+ this.helper = headersHelperCommand(headersHelperPathFor(identityHome2));
18920
+ }
18921
+ /** The preset's argv with the identity home's helper pinned before the prompt (which stays last). */
18922
+ args() {
18923
+ const args = super.args();
18924
+ if (this.helper === null) return args;
18925
+ return [...args.slice(0, -1), "-c", `mcp_servers.${MCP_SERVER_NAME}.http_headers_helper=${JSON.stringify(this.helper)}`, args[args.length - 1]];
18926
+ }
18927
+ /** The preset's environment without any `AGENTCHAT_API_KEY`: the key reaches a run through the helper only. */
18928
+ env() {
18929
+ const env = super.env();
18930
+ delete env[API_KEY_ENV];
18931
+ return env;
18932
+ }
18933
+ /** The helper is there (written when missing or not this release's) before the preset's own gate. */
18934
+ async preflight(options = {}) {
18935
+ if (this.helper === null) return { ok: false, detail: `the path of Node (${process.execPath}) or of ${headersHelperPathFor(this.identityHome)} holds a character a shell command cannot carry quoted` };
18936
+ try {
18937
+ writeHeadersHelper(this.identityHome);
18938
+ } catch (err) {
18939
+ return { ok: false, detail: `could not write the headers helper ${headersHelperPathFor(this.identityHome)}: ${String(err)}` };
18940
+ }
18941
+ return super.preflight(options);
18731
18942
  }
18732
18943
  };
18733
18944
  function profileNote(profile2) {
@@ -18736,23 +18947,23 @@ function profileNote(profile2) {
18736
18947
  }
18737
18948
 
18738
18949
  // src/service.ts
18739
- import * as fs8 from "fs";
18740
- import * as path10 from "path";
18950
+ import * as fs9 from "fs";
18951
+ import * as path11 from "path";
18741
18952
  import { fileURLToPath } from "url";
18742
- var DAEMON_REL = path10.join("bin", "agentchat-daemon.mjs");
18953
+ var DAEMON_REL = path11.join("bin", "agentchat-daemon.mjs");
18743
18954
  function shippedDaemonPath() {
18744
- return path10.join(path10.dirname(fileURLToPath(import.meta.url)), "daemon-main.js");
18955
+ return path11.join(path11.dirname(fileURLToPath(import.meta.url)), "daemon-main.js");
18745
18956
  }
18746
18957
  function stableDaemonPath() {
18747
- return path10.join(identityHome(), DAEMON_REL);
18958
+ return path11.join(identityHome(), DAEMON_REL);
18748
18959
  }
18749
18960
  function copyDaemonBundle() {
18750
18961
  const src = shippedDaemonPath();
18751
- if (!fs8.existsSync(src)) throw new Error(`the daemon bundle is missing from this install (expected ${src})`);
18962
+ if (!fs9.existsSync(src)) throw new Error(`the daemon bundle is missing from this install (expected ${src})`);
18752
18963
  const dest = stableDaemonPath();
18753
- fs8.mkdirSync(path10.dirname(dest), { recursive: true });
18754
- if (path10.resolve(src) !== path10.resolve(dest)) atomicCopyFile(src, dest);
18755
- else fs8.chmodSync(dest, 493);
18964
+ fs9.mkdirSync(path11.dirname(dest), { recursive: true });
18965
+ if (path11.resolve(src) !== path11.resolve(dest)) atomicCopyFile(src, dest);
18966
+ else fs9.chmodSync(dest, 493);
18756
18967
  return dest;
18757
18968
  }
18758
18969
  function serviceOpts() {
@@ -18763,7 +18974,7 @@ function ensureListenerService(opts = {}) {
18763
18974
  if (!opts.force && alwaysOnOptedOut(home)) return { ok: false, detail: "switched off by the user" };
18764
18975
  try {
18765
18976
  const service = serviceOpts();
18766
- if (!opts.force && alwaysOnWanted(home) && readAlwaysOnInstalledVersion(home) === VERSION3 && fs8.existsSync(service.entry) && serviceDefinitionCurrent(service)) {
18977
+ if (!opts.force && alwaysOnWanted(home) && readAlwaysOnInstalledVersion(home) === VERSION3 && fs9.existsSync(service.entry) && serviceDefinitionCurrent(service)) {
18767
18978
  return { ok: true };
18768
18979
  }
18769
18980
  const entry = copyDaemonBundle();
@@ -18778,7 +18989,7 @@ function ensureListenerService(opts = {}) {
18778
18989
  function listenerServiceCurrent() {
18779
18990
  const home = identityHome();
18780
18991
  const service = serviceOpts();
18781
- return alwaysOnWanted(home) && fs8.existsSync(service.entry) && readAlwaysOnInstalledVersion(home) === VERSION3 && serviceDefinitionCurrent(service);
18992
+ return alwaysOnWanted(home) && fs9.existsSync(service.entry) && readAlwaysOnInstalledVersion(home) === VERSION3 && serviceDefinitionCurrent(service);
18782
18993
  }
18783
18994
  function removeListenerService() {
18784
18995
  const home = identityHome();
@@ -18786,10 +18997,15 @@ function removeListenerService() {
18786
18997
  clearAlwaysOnInstalledVersion(home);
18787
18998
  }
18788
18999
 
19000
+ // src/home-identity.ts
19001
+ function homeIdentity(home) {
19002
+ return resolveIdentity(home, { envKey: readCredentials(home) === null });
19003
+ }
19004
+
18789
19005
  // src/identity.ts
18790
19006
  var NO_IDENTITY_TEXTS = { identityLine: null, identityLineTemplate: null };
18791
19007
  function currentPlacementIdentity(texts = NO_IDENTITY_TEXTS) {
18792
- const identity = resolveIdentity(identityHome());
19008
+ const identity = homeIdentity(identityHome());
18793
19009
  if (identity === null || identity.handle === null) return null;
18794
19010
  return { handle: identity.handle, apiKey: identity.apiKey, apiBase: identity.apiBase, identityLine: texts.identityLine, identityLineTemplate: texts.identityLineTemplate };
18795
19011
  }
@@ -18815,11 +19031,13 @@ var profile = {
18815
19031
  // the identity line and the manual they announce. Placing needs no
18816
19032
  // template: the block is found by its fences and replaced in place.
18817
19033
  place: async (handle, apiKey, identityLine, manual) => {
18818
- const identity = resolveIdentity(identityHome());
19034
+ const identity = homeIdentity(identityHome());
18819
19035
  const steps = await placeAll({ handle, apiKey, apiBase: identity?.apiBase ?? "https://api.agentchat.me", identityLine, identityLineTemplate: null }, manual);
18820
19036
  return steps.map((s) => ` ${s.status === "failed" ? "FAILED" : s.name}: ${s.detail}`);
18821
19037
  },
18822
- unplace: () => unplaceIdentity().map((s) => ` ${s.name}: ${s.detail}`),
19038
+ // agent-core resolves the identity BEFORE it clears the credential: only a
19039
+ // key that came from the credential file is this agent's to take out of .env.
19040
+ unplace: (identity) => unplaceIdentity(identity?.source === "file" ? identity.apiKey : null).map((s) => ` ${s.name}: ${s.detail}`),
18823
19041
  logoutHints: () => [`To remove the integration too, run \`${invocation()} uninstall\`.`],
18824
19042
  extraDoctorChecks: async (ctx) => {
18825
19043
  const runtime = await runtimeChecks();
@@ -18898,7 +19116,7 @@ function runSettings() {
18898
19116
  const recorded = { profile: status.profile, workdir: status.workdir ?? shell.workdir };
18899
19117
  const changes = [
18900
19118
  recorded.profile !== shell.profile ? `profile ${shell.profile}` : null,
18901
- path11.resolve(recorded.workdir) !== shell.workdir ? `working root ${shell.workdir}` : null
19119
+ path12.resolve(recorded.workdir) !== shell.workdir ? `working root ${shell.workdir}` : null
18902
19120
  ].filter((c) => c !== null);
18903
19121
  return { ...recorded, differs: changes.length > 0 ? changes.join(" and ") : null };
18904
19122
  }
@@ -18906,7 +19124,7 @@ function settingsNote(settings) {
18906
19124
  return settings.differs !== null ? ` (the daemon's, from its status; install, \`daemon install\` or \`doctor --fix\` from this shell would set ${settings.differs})` : "";
18907
19125
  }
18908
19126
  function daemonRunner(settings = runSettings()) {
18909
- const apiBase = resolveIdentity(identityHome())?.apiBase ?? DEFAULT_API_BASE2;
19127
+ const apiBase = homeIdentity(identityHome())?.apiBase ?? DEFAULT_API_BASE2;
18910
19128
  return new CodexRunner2({ codexHome: codexHome(), identityHome: identityHome(), workdir: settings.workdir, profile: settings.profile, pinMcpUrl: hostedMcpUrl2(apiBase) });
18911
19129
  }
18912
19130
  function workdirCheck() {
@@ -18922,7 +19140,7 @@ function workdirCheck() {
18922
19140
  };
18923
19141
  }
18924
19142
  if (deniedAncestorOf(codexHome(), [workdir]) !== null) {
18925
- const what = path11.resolve(workdir) === codexHome() ? "is $CODEX_HOME" : `contains ${codexHome()}`;
19143
+ const what = path12.resolve(workdir) === codexHome() ? "is $CODEX_HOME" : `contains ${codexHome()}`;
18926
19144
  return { name: "run-workdir", verdict: "WARN", detail: `${workdir}${note} ${what}, where the key is (.env, agentchat/credentials): a run working there can read it \u2014 ${fix}` };
18927
19145
  }
18928
19146
  return { name: "run-workdir", verdict: "PASS", detail: `${workdir}${note}` };
@@ -18992,7 +19210,7 @@ function runNotNow() {
18992
19210
  try {
18993
19211
  writeAnchor(anchorFile(), renderDeclinedBlock({ invoke: invocation(), label: LABEL }));
18994
19212
  } catch (err) {
18995
- console.error(`Recorded, but could not update ${path11.basename(anchorFile())}: ${String(err)}`);
19213
+ console.error(`Recorded, but could not update ${path12.basename(anchorFile())}: ${String(err)}`);
18996
19214
  return 1;
18997
19215
  }
18998
19216
  console.log([`Noted \u2014 ${LABEL} will not ask about AgentChat again.`, `Changed your mind? ${invocation()} register --email <email> --handle <handle>`].join("\n"));
@@ -19010,11 +19228,11 @@ async function runDoctor(opts = {}) {
19010
19228
  var USAGE = `agentchat-codex ${VERSION3} \u2014 the AgentChat integration for Codex
19011
19229
 
19012
19230
  Usage:
19013
- ${invocation()} install: place the served manual, the hosted tools, the key, the identity line; register the integration service
19231
+ ${invocation()} install: place the served manual, the hosted tools, the identity line; register the integration service
19014
19232
  ${invocation()} register --email <e> --handle <h>
19015
19233
  ${invocation()} register --code <6-digit-code>
19016
19234
  ${invocation()} register --not-now stop offering to set this up
19017
- ${invocation()} login --api-key - already have an account: key on stdin (or AGENTCHAT_API_KEY=\u2026, or --api-key <ac_\u2026>)
19235
+ ${invocation()} login already have an account: paste the key when asked (or pipe it: login --api-key - < key.txt)
19018
19236
  ${invocation()} recover --handle <h> --email <e> lost your key (rotates it; --handle defaults to yours)
19019
19237
  ${invocation()} recover --code <6-digit-code>
19020
19238
  ${invocation()} status [--json]
@@ -19042,7 +19260,10 @@ Switches (captured into the service from the shell that runs install, \`daemon i
19042
19260
  is your home folder or contains it gives answer runs
19043
19261
  $CODEX_HOME/agentchat-answer-workdir
19044
19262
  AGENTCHAT_API_BASE override the server
19045
- AGENTCHAT_API_KEY override the stored key (never captured into the service)
19263
+
19264
+ The key is in ${identityHome()}/credentials only; Codex gets it on each connection from
19265
+ ${identityHome()}/bin/mcp-headers.mjs. An exported AGENTCHAT_API_KEY never replaces it:
19266
+ commands, placements and runs act as the agent that file names.
19046
19267
  `;
19047
19268
  async function main(argv = process.argv.slice(2)) {
19048
19269
  let parsed;
@@ -19167,11 +19388,11 @@ function runUninstall() {
19167
19388
  warnings.push(`could not fully remove the integration service: ${String(err)}`);
19168
19389
  }
19169
19390
  markAlwaysOnOptOut(home);
19170
- const steps = removePlacement();
19391
+ const steps = removePlacement(readCredentials(identityHome())?.api_key ?? null);
19171
19392
  for (const step of steps) if (step.status === "failed") warnings.push(step.detail);
19172
19393
  if (serviceRemoved) {
19173
19394
  try {
19174
- fs9.rmSync(stableDaemonPath(), { force: true });
19395
+ fs10.rmSync(stableDaemonPath(), { force: true });
19175
19396
  } catch {
19176
19397
  }
19177
19398
  }