@agentchatme/claude-code 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -46,8 +46,8 @@ var require_windows = __commonJS({
46
46
  "use strict";
47
47
  module.exports = isexe;
48
48
  isexe.sync = sync;
49
- var fs6 = __require("fs");
50
- function checkPathExt(path10, options) {
49
+ var fs9 = __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 && path10.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, path10, options) {
67
+ function checkStat(stat, path13, options) {
68
68
  if (!stat.isSymbolicLink() && !stat.isFile()) {
69
69
  return false;
70
70
  }
71
- return checkPathExt(path10, options);
71
+ return checkPathExt(path13, options);
72
72
  }
73
- function isexe(path10, options, cb) {
74
- fs6.stat(path10, function(er, stat) {
75
- cb(er, er ? false : checkStat(stat, path10, options));
73
+ function isexe(path13, options, cb) {
74
+ fs9.stat(path13, function(er, stat) {
75
+ cb(er, er ? false : checkStat(stat, path13, options));
76
76
  });
77
77
  }
78
- function sync(path10, options) {
79
- return checkStat(fs6.statSync(path10), path10, options);
78
+ function sync(path13, options) {
79
+ return checkStat(fs9.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 fs6 = __require("fs");
91
- function isexe(path10, options, cb) {
92
- fs6.stat(path10, function(er, stat) {
90
+ var fs9 = __require("fs");
91
+ function isexe(path13, options, cb) {
92
+ fs9.stat(path13, function(er, stat) {
93
93
  cb(er, er ? false : checkStat(stat, options));
94
94
  });
95
95
  }
96
- function sync(path10, options) {
97
- return checkStat(fs6.statSync(path10), options);
96
+ function sync(path13, options) {
97
+ return checkStat(fs9.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 fs6 = __require("fs");
122
+ var fs9 = __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(path10, 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(resolve7, reject) {
141
- isexe(path10, options || {}, function(er, is) {
140
+ return new Promise(function(resolve11, reject) {
141
+ isexe(path13, options || {}, function(er, is) {
142
142
  if (er) {
143
143
  reject(er);
144
144
  } else {
145
- resolve7(is);
145
+ resolve11(is);
146
146
  }
147
147
  });
148
148
  });
149
149
  }
150
- core(path10, 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(path10, options) {
160
+ function sync(path13, options) {
161
161
  try {
162
- return core.sync(path10, 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 path10 = __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((resolve7, reject) => {
212
+ const step = (i) => new Promise((resolve11, reject) => {
213
213
  if (i === pathEnv.length)
214
- return opt.all && found.length ? resolve7(found) : reject(getNotFoundError(cmd));
214
+ return opt.all && found.length ? resolve11(found) : reject(getNotFoundError(cmd));
215
215
  const ppRaw = pathEnv[i];
216
216
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
217
- const pCmd = path10.join(pathPart, cmd);
217
+ const pCmd = path13.join(pathPart, cmd);
218
218
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
219
- resolve7(subStep(p, i, 0));
219
+ resolve11(subStep(p, i, 0));
220
220
  });
221
- const subStep = (p, i, ii) => new Promise((resolve7, reject) => {
221
+ const subStep = (p, i, ii) => new Promise((resolve11, reject) => {
222
222
  if (ii === pathExt.length)
223
- return resolve7(step(i + 1));
223
+ return resolve11(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 resolve7(p + ext);
230
+ return resolve11(p + ext);
231
231
  }
232
- return resolve7(subStep(p, i, ii + 1));
232
+ return resolve11(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 = path10.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 path10 = __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 ? path10.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 = path10.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 [path10, argument] = match[0].replace(/#! ?/, "").split(" ");
374
- const binary = path10.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 fs6 = __require("fs");
387
+ var fs9 = __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 = fs6.openSync(command, "r");
395
- fs6.readSync(fd, buffer, 0, size, 0);
396
- fs6.closeSync(fd);
394
+ fd = fs9.openSync(command, "r");
395
+ fs9.readSync(fd, buffer, 0, size, 0);
396
+ fs9.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 path10 = __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 = path10.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(" ");
@@ -441,7 +441,7 @@ var require_parse = __commonJS({
441
441
  }
442
442
  return parsed;
443
443
  }
444
- function parse(command, args, options) {
444
+ function parse2(command, args, options) {
445
445
  if (args && !Array.isArray(args)) {
446
446
  options = args;
447
447
  args = null;
@@ -460,7 +460,7 @@ var require_parse = __commonJS({
460
460
  };
461
461
  return options.shell ? parsed : parseNonShell(parsed);
462
462
  }
463
- module.exports = parse;
463
+ module.exports = parse2;
464
464
  }
465
465
  });
466
466
 
@@ -519,16 +519,16 @@ var require_cross_spawn = __commonJS({
519
519
  "node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(exports, module) {
520
520
  "use strict";
521
521
  var cp = __require("child_process");
522
- var parse = require_parse();
522
+ var parse2 = require_parse();
523
523
  var enoent = require_enoent();
524
524
  function spawn(command, args, options) {
525
- const parsed = parse(command, args, options);
525
+ const parsed = parse2(command, args, options);
526
526
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
527
527
  enoent.hookChildProcess(spawned, parsed);
528
528
  return spawned;
529
529
  }
530
530
  function spawnSync(command, args, options) {
531
- const parsed = parse(command, args, options);
531
+ const parsed = parse2(command, args, options);
532
532
  const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
533
533
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
534
534
  return result;
@@ -536,7 +536,7 @@ var require_cross_spawn = __commonJS({
536
536
  module.exports = spawn;
537
537
  module.exports.spawn = spawn;
538
538
  module.exports.sync = spawnSync;
539
- module.exports._parse = parse;
539
+ module.exports._parse = parse2;
540
540
  module.exports._enoent = enoent;
541
541
  }
542
542
  });
@@ -2627,7 +2627,7 @@ var require_extension = __commonJS({
2627
2627
  if (dest[name] === void 0) dest[name] = [elem];
2628
2628
  else dest[name].push(elem);
2629
2629
  }
2630
- function parse(header) {
2630
+ function parse2(header) {
2631
2631
  const offers = /* @__PURE__ */ Object.create(null);
2632
2632
  let params = /* @__PURE__ */ Object.create(null);
2633
2633
  let mustUnescape = false;
@@ -2767,7 +2767,7 @@ var require_extension = __commonJS({
2767
2767
  }).join(", ");
2768
2768
  }).join(", ");
2769
2769
  }
2770
- module.exports = { format, parse };
2770
+ module.exports = { format, parse: parse2 };
2771
2771
  }
2772
2772
  });
2773
2773
 
@@ -2780,7 +2780,7 @@ var require_websocket = __commonJS({
2780
2780
  var http = __require("http");
2781
2781
  var net = __require("net");
2782
2782
  var tls = __require("tls");
2783
- var { randomBytes: randomBytes2, createHash } = __require("crypto");
2783
+ var { randomBytes: randomBytes2, createHash: createHash2 } = __require("crypto");
2784
2784
  var { Duplex, Readable } = __require("stream");
2785
2785
  var { URL: URL2 } = __require("url");
2786
2786
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -2801,7 +2801,7 @@ var require_websocket = __commonJS({
2801
2801
  var {
2802
2802
  EventTarget: { addEventListener, removeEventListener }
2803
2803
  } = require_event_target();
2804
- var { format, parse } = require_extension();
2804
+ var { format, parse: parse2 } = require_extension();
2805
2805
  var { toBuffer } = require_buffer_util();
2806
2806
  var kAborted = /* @__PURE__ */ Symbol("kAborted");
2807
2807
  var protocolVersions = [8, 13];
@@ -3448,7 +3448,7 @@ var require_websocket = __commonJS({
3448
3448
  abortHandshake(websocket, socket, "Invalid Upgrade header");
3449
3449
  return;
3450
3450
  }
3451
- const digest = createHash("sha1").update(key + GUID).digest("base64");
3451
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
3452
3452
  if (res.headers["sec-websocket-accept"] !== digest) {
3453
3453
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
3454
3454
  return;
@@ -3478,7 +3478,7 @@ var require_websocket = __commonJS({
3478
3478
  }
3479
3479
  let extensions;
3480
3480
  try {
3481
- extensions = parse(secWebSocketExtensions);
3481
+ extensions = parse2(secWebSocketExtensions);
3482
3482
  } catch (err) {
3483
3483
  const message = "Invalid Sec-WebSocket-Extensions header";
3484
3484
  abortHandshake(websocket, socket, message);
@@ -3770,7 +3770,7 @@ var require_subprotocol = __commonJS({
3770
3770
  "node_modules/.pnpm/ws@8.21.1/node_modules/ws/lib/subprotocol.js"(exports, module) {
3771
3771
  "use strict";
3772
3772
  var { tokenChars } = require_validation();
3773
- function parse(header) {
3773
+ function parse2(header) {
3774
3774
  const protocols = /* @__PURE__ */ new Set();
3775
3775
  let start = -1;
3776
3776
  let end = -1;
@@ -3806,7 +3806,7 @@ var require_subprotocol = __commonJS({
3806
3806
  protocols.add(protocol);
3807
3807
  return protocols;
3808
3808
  }
3809
- module.exports = { parse };
3809
+ module.exports = { parse: parse2 };
3810
3810
  }
3811
3811
  });
3812
3812
 
@@ -3817,7 +3817,7 @@ var require_websocket_server = __commonJS({
3817
3817
  var EventEmitter = __require("events");
3818
3818
  var http = __require("http");
3819
3819
  var { Duplex } = __require("stream");
3820
- var { createHash } = __require("crypto");
3820
+ var { createHash: createHash2 } = __require("crypto");
3821
3821
  var extension2 = require_extension();
3822
3822
  var PerMessageDeflate2 = require_permessage_deflate();
3823
3823
  var subprotocol2 = require_subprotocol();
@@ -4124,7 +4124,7 @@ var require_websocket_server = __commonJS({
4124
4124
  );
4125
4125
  }
4126
4126
  if (this._state > RUNNING) return abortHandshake(socket, 503);
4127
- const digest = createHash("sha1").update(key + GUID).digest("base64");
4127
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
4128
4128
  const headers = [
4129
4129
  "HTTP/1.1 101 Switching Protocols",
4130
4130
  "Upgrade: websocket",
@@ -4242,13 +4242,16 @@ var init_wrapper = __esm({
4242
4242
 
4243
4243
  // src/daemon-main.ts
4244
4244
  import { parseArgs } from "util";
4245
- import * as path9 from "path";
4245
+ import * as path12 from "path";
4246
4246
 
4247
- // node_modules/.pnpm/@agentchatme+agent-core@0.4.1/node_modules/@agentchatme/agent-core/dist/chunk-QDM4EFI7.js
4247
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/chunk-AFDD53DD.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";
4251
4251
  import * as path from "path";
4252
+ import * as fs2 from "fs";
4253
+ import * as os from "os";
4254
+ import * as path2 from "path";
4252
4255
  var __defProp2 = Object.defineProperty;
4253
4256
  var __export2 = (target, all) => {
4254
4257
  for (var name in all)
@@ -4341,200 +4344,532 @@ var log = {
4341
4344
  info: (msg) => emit("info", msg),
4342
4345
  debug: (msg) => emit("debug", msg)
4343
4346
  };
4344
- var spawnCommand = import_cross_spawn.default;
4345
- var spawnCommandSync = import_cross_spawn.default.sync;
4346
-
4347
- // node_modules/.pnpm/@agentchatme+agent-core@0.4.1/node_modules/@agentchatme/agent-core/dist/chunk-7LAAAXUO.js
4348
- import * as path2 from "path";
4349
-
4350
- // node_modules/.pnpm/agentchatme@1.3.0_ws@8.21.1/node_modules/agentchatme/dist/index.js
4351
- var __defProp3 = Object.defineProperty;
4352
- var __export3 = (target, all) => {
4353
- for (var name in all)
4354
- __defProp3(target, name, { get: all[name], enumerable: true });
4355
- };
4356
- var ErrorCode = {
4357
- AGENT_NOT_FOUND: "AGENT_NOT_FOUND",
4358
- AGENT_SUSPENDED: "AGENT_SUSPENDED",
4359
- AGENT_PAUSED_BY_OWNER: "AGENT_PAUSED_BY_OWNER",
4360
- HANDLE_TAKEN: "HANDLE_TAKEN",
4361
- INVALID_HANDLE: "INVALID_HANDLE",
4362
- /**
4363
- * 409 from `POST /v1/register` (and `/register/verify`): the email already
4364
- * backs the maximum number of live agents. The cap is server-tunable and
4365
- * arrives in `details.limit`; deleting an agent frees a slot.
4366
- */
4367
- EMAIL_LIMIT_REACHED: "EMAIL_LIMIT_REACHED",
4368
- /**
4369
- * 409 from `POST /v1/register` (and `/register/verify`): the email has
4370
- * spent its lifetime registration budget (deleted agents included).
4371
- * `details.limit` carries the cap; only a different email helps.
4372
- */
4373
- EMAIL_EXHAUSTED: "EMAIL_EXHAUSTED",
4374
- /**
4375
- * Legacy spelling of `EMAIL_LIMIT_REACHED` from servers that still enforce
4376
- * one live agent per email. Retired server-side; mapped to
4377
- * `EmailLimitReachedError` so callers never branch on it.
4378
- */
4379
- EMAIL_TAKEN: "EMAIL_TAKEN",
4380
- /**
4381
- * 409 from `POST /v1/agents/recover/verify`: the email backs more than one
4382
- * agent and recovery was started without a `handle`. `details.handles`
4383
- * lists the candidates; re-run `recover()` with one of them.
4384
- */
4385
- HANDLE_REQUIRED: "HANDLE_REQUIRED",
4386
- SUSPENDED: "SUSPENDED",
4387
- RESTRICTED: "RESTRICTED",
4388
- CONVERSATION_NOT_FOUND: "CONVERSATION_NOT_FOUND",
4389
- MESSAGE_NOT_FOUND: "MESSAGE_NOT_FOUND",
4390
- GROUP_DELETED: "GROUP_DELETED",
4391
- RATE_LIMITED: "RATE_LIMITED",
4392
- RECIPIENT_BACKLOGGED: "RECIPIENT_BACKLOGGED",
4393
- AWAITING_REPLY: "AWAITING_REPLY",
4394
- BLOCKED: "BLOCKED",
4395
- UNAUTHORIZED: "UNAUTHORIZED",
4396
- FORBIDDEN: "FORBIDDEN",
4397
- VALIDATION_ERROR: "VALIDATION_ERROR",
4398
- INTERNAL_ERROR: "INTERNAL_ERROR",
4399
- OWNER_NOT_FOUND: "OWNER_NOT_FOUND",
4400
- INVALID_API_KEY: "INVALID_API_KEY",
4401
- ALREADY_CLAIMED: "ALREADY_CLAIMED",
4402
- CLAIM_NOT_FOUND: "CLAIM_NOT_FOUND"
4403
- };
4404
- function parseRetryAfter(raw, now2 = Date.now()) {
4405
- if (!raw) return null;
4406
- const trimmed = raw.trim();
4407
- if (!trimmed) return null;
4408
- if (/^\d+$/.test(trimmed)) {
4409
- const seconds = Number(trimmed);
4410
- return Number.isFinite(seconds) ? seconds * 1e3 : null;
4347
+ var RUN_PROFILES = ["answer", "work", "full"];
4348
+ function identityOf(dir) {
4349
+ try {
4350
+ const st = fs2.statSync(dir, { bigint: true });
4351
+ return st.ino === 0n ? null : `${st.dev}:${st.ino}`;
4352
+ } catch {
4353
+ return null;
4411
4354
  }
4412
- if (!/[a-zA-Z]/.test(trimmed)) return null;
4413
- const epoch = Date.parse(trimmed);
4414
- if (!Number.isFinite(epoch)) return null;
4415
- return Math.max(0, epoch - now2);
4416
4355
  }
4417
- var AgentChatError = class extends Error {
4418
- code;
4419
- status;
4420
- details;
4421
- /**
4422
- * The server's `x-request-id` for the failing request, when present.
4423
- * Include it in bug reports — the operator can look up the full
4424
- * server-side trace in seconds.
4425
- */
4426
- requestId;
4427
- constructor(response, status, requestId = null) {
4428
- super(response.message);
4429
- this.name = "AgentChatError";
4430
- this.code = response.code;
4431
- this.status = status;
4432
- this.details = response.details;
4433
- this.requestId = requestId;
4434
- Object.setPrototypeOf(this, new.target.prototype);
4435
- }
4436
- };
4437
- var RateLimitedError = class extends AgentChatError {
4438
- retryAfterMs;
4439
- constructor(response, status, retryAfterMs, requestId = null) {
4440
- super(response, status, requestId);
4441
- this.name = "RateLimitedError";
4442
- this.retryAfterMs = retryAfterMs;
4443
- }
4444
- };
4445
- var SuspendedError = class extends AgentChatError {
4446
- constructor(response, status, requestId = null) {
4447
- super(response, status, requestId);
4448
- this.name = "SuspendedError";
4449
- }
4450
- };
4451
- var RestrictedError = class extends AgentChatError {
4452
- constructor(response, status, requestId = null) {
4453
- super(response, status, requestId);
4454
- this.name = "RestrictedError";
4455
- }
4456
- };
4457
- var RecipientBackloggedError = class extends AgentChatError {
4458
- recipientHandle;
4459
- undeliveredCount;
4460
- constructor(response, status, requestId = null) {
4461
- super(response, status, requestId);
4462
- this.name = "RecipientBackloggedError";
4463
- const d = response.details;
4464
- this.recipientHandle = typeof d?.recipient_handle === "string" ? d.recipient_handle : null;
4465
- this.undeliveredCount = typeof d?.undelivered_count === "number" ? d.undelivered_count : null;
4466
- }
4467
- };
4468
- var AwaitingReplyError = class extends AgentChatError {
4469
- recipientHandle;
4470
- waitingSince;
4471
- constructor(response, status, requestId = null) {
4472
- super(response, status, requestId);
4473
- this.name = "AwaitingReplyError";
4474
- const d = response.details;
4475
- this.recipientHandle = typeof d?.recipient_handle === "string" ? d.recipient_handle : null;
4476
- this.waitingSince = typeof d?.waiting_since === "string" ? d.waiting_since : null;
4477
- }
4478
- };
4479
- var BlockedError = class extends AgentChatError {
4480
- constructor(response, status, requestId = null) {
4481
- super(response, status, requestId);
4482
- this.name = "BlockedError";
4483
- }
4484
- };
4485
- var ValidationError = class extends AgentChatError {
4486
- constructor(response, status, requestId = null) {
4487
- super(response, status, requestId);
4488
- this.name = "ValidationError";
4489
- }
4490
- };
4491
- var UnauthorizedError = class extends AgentChatError {
4492
- constructor(response, status, requestId = null) {
4493
- super(response, status, requestId);
4494
- this.name = "UnauthorizedError";
4495
- }
4496
- };
4497
- var ForbiddenError = class extends AgentChatError {
4498
- constructor(response, status, requestId = null) {
4499
- super(response, status, requestId);
4500
- this.name = "ForbiddenError";
4356
+ function realOrResolved(p) {
4357
+ const resolved = path2.resolve(p);
4358
+ try {
4359
+ return fs2.realpathSync.native(resolved);
4360
+ } catch {
4361
+ return resolved;
4501
4362
  }
4502
- };
4503
- var NotFoundError = class extends AgentChatError {
4504
- constructor(response, status, requestId = null) {
4505
- super(response, status, requestId);
4506
- this.name = "NotFoundError";
4363
+ }
4364
+ function spelling(p) {
4365
+ return process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p;
4366
+ }
4367
+ function workdirExposesHome(workdir, home = os.homedir()) {
4368
+ const dir = realOrResolved(workdir);
4369
+ if (dir === path2.parse(dir).root) return true;
4370
+ const homes = [.../* @__PURE__ */ new Set([path2.resolve(home), realOrResolved(home)])];
4371
+ const homeIds = new Set(homes.map(identityOf).filter((id) => id !== null));
4372
+ for (const h of homes) {
4373
+ const parts = h.slice(path2.parse(h).root.length).split(path2.sep).filter((part) => part.length > 0);
4374
+ for (let i = 0; i <= parts.length; i++) {
4375
+ const candidate = path2.join(dir, ...parts.slice(i));
4376
+ const id = identityOf(candidate);
4377
+ if (id !== null ? homeIds.has(id) : spelling(realOrResolved(candidate)) === spelling(realOrResolved(h)) && fs2.existsSync(candidate)) return true;
4378
+ }
4507
4379
  }
4508
- };
4509
- var GroupDeletedError = class extends AgentChatError {
4510
- groupId;
4511
- deletedByHandle;
4512
- deletedAt;
4513
- constructor(response, status, requestId = null) {
4514
- super(response, status, requestId);
4515
- this.name = "GroupDeletedError";
4516
- const d = response.details;
4517
- this.groupId = typeof d?.group_id === "string" ? d.group_id : null;
4518
- this.deletedByHandle = typeof d?.deleted_by_handle === "string" ? d.deleted_by_handle : null;
4519
- this.deletedAt = typeof d?.deleted_at === "string" ? d.deleted_at : null;
4380
+ return false;
4381
+ }
4382
+ var RUN_PROFILE_ENV = "AGENTCHAT_RUN_PROFILE";
4383
+ var DEFAULT_RUN_PROFILE = "answer";
4384
+ function isRunProfile(value) {
4385
+ return typeof value === "string" && RUN_PROFILES.includes(value);
4386
+ }
4387
+ function resolveRunProfile(env = process.env) {
4388
+ const raw = env[RUN_PROFILE_ENV]?.trim().toLowerCase();
4389
+ return isRunProfile(raw) ? raw : DEFAULT_RUN_PROFILE;
4390
+ }
4391
+ var INTEGRATION_ENV = "AGENTCHAT_INTEGRATION";
4392
+ var INTEGRATION_ENV_LEGACY = "AGENTCHAT_DOORBELL";
4393
+ var INTEGRATION_ENV_LEGACY_REMOVAL = "2027-02-01";
4394
+ function isOff(raw) {
4395
+ const value = raw?.trim().toLowerCase();
4396
+ return value === "off" || value === "0" || value === "false";
4397
+ }
4398
+ function integrationDisabledBy(env = process.env) {
4399
+ if (env[INTEGRATION_ENV] !== void 0 && env[INTEGRATION_ENV].trim().length > 0) {
4400
+ return isOff(env[INTEGRATION_ENV]) ? INTEGRATION_ENV : null;
4520
4401
  }
4521
- };
4522
- function policyLimit(details) {
4523
- const limit = details?.limit;
4524
- return typeof limit === "number" && Number.isInteger(limit) ? limit : null;
4402
+ return isOff(env[INTEGRATION_ENV_LEGACY]) ? INTEGRATION_ENV_LEGACY : null;
4525
4403
  }
4526
- var EmailLimitReachedError = class extends AgentChatError {
4527
- limit;
4528
- constructor(response, status, requestId = null) {
4529
- super(response, status, requestId);
4530
- this.name = "EmailLimitReachedError";
4531
- this.limit = policyLimit(response.details);
4404
+ var RUN_BUDGET_ENV = "AGENTCHAT_RUN_BUDGET_MS";
4405
+ var DEFAULT_RUN_BUDGET_MS = 10 * 6e4;
4406
+ var MAX_RUN_BUDGET_MS = 2 * 60 * 6e4;
4407
+ function resolveRunBudgetMs(env = process.env) {
4408
+ const parsed = Number(env[RUN_BUDGET_ENV]);
4409
+ if (!Number.isFinite(parsed) || parsed < 1e3) return DEFAULT_RUN_BUDGET_MS;
4410
+ return Math.min(parsed, MAX_RUN_BUDGET_MS);
4411
+ }
4412
+ var spawnCommand = import_cross_spawn.default;
4413
+ var spawnCommandSync = import_cross_spawn.default.sync;
4414
+ var DEFAULT_GRACE_MS = 5e3;
4415
+ var DEFAULT_DRAIN_MS = 2e3;
4416
+ var DEFAULT_ABANDON_MS = 5e3;
4417
+ var STDERR_TAIL_CHARS = 400;
4418
+ function redactDiagnostic(value, max = STDERR_TAIL_CHARS) {
4419
+ return value.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, "").replace(/\b(api[_ -]?key\s*[:=]\s*)\S+/gi, "$1[redacted]").replace(/\b(Bearer)\s+[A-Za-z0-9._~-]{8,}\b/gi, "$1 [redacted]").replace(/\bac_[A-Za-z0-9_-]{8,}\b/g, "[redacted AgentChat key]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, "[redacted key]").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "").replace(/\s+/g, " ").trim().slice(-max);
4420
+ }
4421
+ var KILL_TIMEOUT_MS = 5e3;
4422
+ function killProcessTree(child, signal) {
4423
+ if (child.pid === void 0) return;
4424
+ try {
4425
+ if (process.platform === "win32") {
4426
+ spawnCommandSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
4427
+ windowsHide: true,
4428
+ stdio: "ignore",
4429
+ timeout: KILL_TIMEOUT_MS
4430
+ });
4431
+ } else {
4432
+ process.kill(-child.pid, signal);
4433
+ }
4434
+ } catch {
4435
+ try {
4436
+ child.kill(signal);
4437
+ } catch {
4438
+ }
4532
4439
  }
4533
- };
4534
- var EmailExhaustedError = class extends AgentChatError {
4535
- limit;
4536
- constructor(response, status, requestId = null) {
4537
- super(response, status, requestId);
4440
+ }
4441
+ function fileTime(ms) {
4442
+ return String((BigInt(Math.round(ms)) + 11644473600000n) * 10000n);
4443
+ }
4444
+ var WINDOWS_SWEEP_TIMEOUT_MS = 6e4;
4445
+ function sweepWindowsDescendants(rootPid, aliveFromMs, aliveUntilMs, options = {}) {
4446
+ if (process.platform !== "win32" || !Number.isInteger(rootPid) || rootPid <= 0) return Promise.resolve(null);
4447
+ const script = [
4448
+ "$ErrorActionPreference = 'Continue'",
4449
+ // Progress records ('Preparing modules for first use') would reach stderr as CLIXML.
4450
+ "$ProgressPreference = 'SilentlyContinue'",
4451
+ `$from = [DateTime]::FromFileTime(${fileTime(aliveFromMs - 1e3)})`,
4452
+ `$until = [DateTime]::FromFileTime(${fileTime(aliveUntilMs + 1e3)})`,
4453
+ "Write-Output ('window ' + $from.ToUniversalTime().ToString('o') + ' ' + $until.ToUniversalTime().ToString('o'))",
4454
+ `foreach ($p in @(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${rootPid}')) {`,
4455
+ " Write-Output ('candidate ' + $p.ProcessId + ' ' + $p.CreationDate.ToUniversalTime().ToString('o'))",
4456
+ " if ($p.CreationDate -ge $from -and $p.CreationDate -le $until) {",
4457
+ " & taskkill.exe /T /F /PID $p.ProcessId 2>&1 | Out-Null",
4458
+ " Write-Output ('kill ' + $p.ProcessId + ' ' + $LASTEXITCODE)",
4459
+ " }",
4460
+ "}"
4461
+ ].join("\n");
4462
+ return new Promise((resolve22) => {
4463
+ let stdout = "";
4464
+ let stderr = "";
4465
+ let timedOut = false;
4466
+ let done = false;
4467
+ const finish = (exitCode) => {
4468
+ if (done) return;
4469
+ done = true;
4470
+ clearTimeout(timer);
4471
+ const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
4472
+ resolve22({
4473
+ exitCode,
4474
+ timedOut,
4475
+ candidates: lines.filter((l) => l.startsWith("candidate ")).map((l) => l.slice("candidate ".length)),
4476
+ killed: lines.filter((l) => l.startsWith("kill ")).map((l) => l.split(" ")).map(([, pid, code]) => ({ pid: Number(pid), code: Number(code) })),
4477
+ window: lines.find((l) => l.startsWith("window "))?.slice("window ".length) ?? null,
4478
+ stderr: redactDiagnostic(stderr)
4479
+ });
4480
+ };
4481
+ let sweeper;
4482
+ try {
4483
+ sweeper = spawnCommand(
4484
+ "powershell.exe",
4485
+ ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")],
4486
+ { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
4487
+ );
4488
+ } catch (err) {
4489
+ stderr = String(err);
4490
+ finish(null);
4491
+ return;
4492
+ }
4493
+ const timer = setTimeout(() => {
4494
+ timedOut = true;
4495
+ try {
4496
+ sweeper.kill();
4497
+ } catch {
4498
+ }
4499
+ finish(null);
4500
+ }, options.timeoutMs ?? WINDOWS_SWEEP_TIMEOUT_MS);
4501
+ timer.unref?.();
4502
+ sweeper.stdout?.on("data", (c) => {
4503
+ stdout = (stdout + String(c)).slice(-16e3);
4504
+ });
4505
+ sweeper.stderr?.on("data", (c) => {
4506
+ stderr = (stderr + String(c)).slice(-4e3);
4507
+ });
4508
+ sweeper.on("error", (err) => {
4509
+ stderr += String(err);
4510
+ finish(null);
4511
+ });
4512
+ sweeper.on("close", (code) => finish(code));
4513
+ });
4514
+ }
4515
+ function describeWindowsSweep(sweep) {
4516
+ const killed = sweep.killed.map((k) => `${k.pid} (taskkill ${k.code})`).join(", ") || "none";
4517
+ return `windows leftover sweep: exit ${sweep.exitCode ?? (sweep.timedOut ? "timed out" : "none")}; window ${sweep.window ?? "?"}; children seen ${sweep.candidates.length > 0 ? sweep.candidates.join(", ") : "none"}; killed ${killed}${sweep.stderr ? `; stderr: ${sweep.stderr}` : ""}`;
4518
+ }
4519
+ function spawnRun(spec) {
4520
+ const started = Date.now();
4521
+ const graceMs = spec.graceMs ?? DEFAULT_GRACE_MS;
4522
+ const drainMs = spec.drainMs ?? DEFAULT_DRAIN_MS;
4523
+ const abandonMs = spec.abandonMs ?? DEFAULT_ABANDON_MS;
4524
+ return new Promise((resolve22) => {
4525
+ let settled = false;
4526
+ let stdoutBytes = 0;
4527
+ let stderrTail = "";
4528
+ let timedOut = false;
4529
+ let interrupted = false;
4530
+ let terminating = false;
4531
+ let exited = null;
4532
+ const timers = /* @__PURE__ */ new Set();
4533
+ let onAbort = null;
4534
+ let child = null;
4535
+ const later = (ms, fn) => {
4536
+ const timer = setTimeout(() => {
4537
+ timers.delete(timer);
4538
+ fn();
4539
+ }, ms);
4540
+ timers.add(timer);
4541
+ };
4542
+ const finish = (outcome) => {
4543
+ if (settled) return;
4544
+ settled = true;
4545
+ for (const timer of timers) clearTimeout(timer);
4546
+ timers.clear();
4547
+ if (onAbort) spec.signal?.removeEventListener("abort", onAbort);
4548
+ resolve22({ ...outcome, durationMs: Date.now() - started });
4549
+ };
4550
+ const detach = () => {
4551
+ if (child === null) return;
4552
+ for (const stream of [child.stdin, child.stdout, child.stderr]) {
4553
+ try {
4554
+ stream?.destroy();
4555
+ } catch {
4556
+ }
4557
+ }
4558
+ try {
4559
+ child.unref();
4560
+ } catch {
4561
+ }
4562
+ };
4563
+ const classify = (code, signal, note) => {
4564
+ const tail = redactDiagnostic(stderrTail);
4565
+ const extra = `${note ? ` (${note})` : ""}${tail ? `: ${tail}` : ""}`;
4566
+ if (timedOut) {
4567
+ return { state: "timed_out", exitCode: code, detail: `run exceeded its ${Math.round(spec.budgetMs / 1e3)} s budget and was killed${extra}` };
4568
+ }
4569
+ if (interrupted) {
4570
+ return { state: "failed", exitCode: code, detail: `interrupted \u2014 the integration was stopping; the tray stays unread for the next run${extra}` };
4571
+ }
4572
+ if (code === 0) return note ? { state: "ok", exitCode: 0, detail: note } : { state: "ok", exitCode: 0 };
4573
+ const exit = code === null ? `signal ${signal ?? "unknown"}` : `exit ${code}`;
4574
+ if (stdoutBytes === 0) return { state: "not_started", exitCode: code, detail: `${exit} with nothing on stdout${extra}` };
4575
+ return { state: "failed", exitCode: code, detail: `${exit}${extra}` };
4576
+ };
4577
+ if (spec.signal?.aborted) {
4578
+ finish({ state: "not_started", exitCode: null, detail: "interrupted before the runtime was started" });
4579
+ return;
4580
+ }
4581
+ try {
4582
+ child = spawnCommand(spec.command, [...spec.args], {
4583
+ cwd: spec.cwd,
4584
+ env: spec.env,
4585
+ stdio: [spec.stdin === null ? "ignore" : "pipe", "pipe", "pipe"],
4586
+ detached: process.platform !== "win32",
4587
+ windowsHide: true,
4588
+ ...spec.shell === true ? { shell: true } : {}
4589
+ });
4590
+ } catch (err) {
4591
+ finish({ state: "not_started", exitCode: null, detail: redactDiagnostic(String(err)) });
4592
+ return;
4593
+ }
4594
+ const proc = child;
4595
+ if (spec.onStarted) {
4596
+ const onStarted = spec.onStarted;
4597
+ proc.once("spawn", () => {
4598
+ try {
4599
+ onStarted();
4600
+ } catch {
4601
+ }
4602
+ });
4603
+ }
4604
+ proc.stdout?.on("data", (chunk) => {
4605
+ stdoutBytes += chunk.length;
4606
+ });
4607
+ proc.stderr?.on("data", (chunk) => {
4608
+ stderrTail = (stderrTail + String(chunk)).slice(-4 * STDERR_TAIL_CHARS);
4609
+ });
4610
+ proc.stdout?.on("error", () => void 0);
4611
+ proc.stderr?.on("error", () => void 0);
4612
+ if (spec.stdin !== null && proc.stdin) {
4613
+ proc.stdin.on("error", () => {
4614
+ });
4615
+ try {
4616
+ proc.stdin.write(spec.stdin);
4617
+ proc.stdin.end();
4618
+ } catch {
4619
+ }
4620
+ }
4621
+ const terminate = () => {
4622
+ if (terminating || settled) return;
4623
+ terminating = true;
4624
+ killProcessTree(proc, "SIGTERM");
4625
+ later(graceMs, () => {
4626
+ if (settled) return;
4627
+ killProcessTree(proc, "SIGKILL");
4628
+ later(abandonMs, () => {
4629
+ if (settled) return;
4630
+ if (exited !== null) return;
4631
+ detach();
4632
+ const tail = redactDiagnostic(stderrTail);
4633
+ const why = `the run did not end ${Math.round((graceMs + abandonMs) / 1e3)} s after it was signalled (SIGKILL included) \u2014 abandoned so the next wake can run${tail ? `: ${tail}` : ""}`;
4634
+ finish(
4635
+ timedOut ? { state: "timed_out", exitCode: null, detail: `run exceeded its ${Math.round(spec.budgetMs / 1e3)} s budget; ${why}` } : { state: "failed", exitCode: null, detail: `interrupted \u2014 ${why}` }
4636
+ );
4637
+ });
4638
+ });
4639
+ };
4640
+ later(spec.budgetMs, () => {
4641
+ if (exited !== null) return;
4642
+ timedOut = true;
4643
+ terminate();
4644
+ });
4645
+ if (spec.signal) {
4646
+ onAbort = () => {
4647
+ if (settled) return;
4648
+ interrupted = true;
4649
+ terminate();
4650
+ };
4651
+ spec.signal.addEventListener("abort", onAbort, { once: true });
4652
+ }
4653
+ proc.on("error", (err) => {
4654
+ finish({ state: "not_started", exitCode: null, detail: redactDiagnostic(String(err)) });
4655
+ });
4656
+ proc.on("exit", (code, signal) => {
4657
+ exited = { code, signal, at: Date.now() };
4658
+ later(drainMs, () => {
4659
+ if (settled || exited === null) return;
4660
+ killProcessTree(proc, "SIGKILL");
4661
+ if (proc.pid !== void 0) {
4662
+ void sweepWindowsDescendants(proc.pid, started, exited.at).then((sweep) => {
4663
+ if (sweep !== null) (sweep.exitCode === 0 ? log.info : log.warn)(describeWindowsSweep(sweep));
4664
+ });
4665
+ }
4666
+ detach();
4667
+ finish(
4668
+ classify(
4669
+ exited.code,
4670
+ exited.signal,
4671
+ process.platform === "win32" ? "a process the run started kept its output open after it exited; its children were swept (taskkill) and the run detached from it \u2014 a process the sweep cannot see can survive" : "a process the run started kept its output open after it exited; the run's process group was signalled (SIGKILL) and the run detached from it \u2014 a process that left the group can survive"
4672
+ )
4673
+ );
4674
+ });
4675
+ });
4676
+ proc.on("close", (code, signal) => {
4677
+ finish(classify(code, signal, null));
4678
+ });
4679
+ });
4680
+ }
4681
+
4682
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/chunk-NAAHIK7Z.js
4683
+ import * as path3 from "path";
4684
+
4685
+ // node_modules/.pnpm/agentchatme@1.3.0_ws@8.21.1/node_modules/agentchatme/dist/index.js
4686
+ var __defProp3 = Object.defineProperty;
4687
+ var __export3 = (target, all) => {
4688
+ for (var name in all)
4689
+ __defProp3(target, name, { get: all[name], enumerable: true });
4690
+ };
4691
+ var ErrorCode = {
4692
+ AGENT_NOT_FOUND: "AGENT_NOT_FOUND",
4693
+ AGENT_SUSPENDED: "AGENT_SUSPENDED",
4694
+ AGENT_PAUSED_BY_OWNER: "AGENT_PAUSED_BY_OWNER",
4695
+ HANDLE_TAKEN: "HANDLE_TAKEN",
4696
+ INVALID_HANDLE: "INVALID_HANDLE",
4697
+ /**
4698
+ * 409 from `POST /v1/register` (and `/register/verify`): the email already
4699
+ * backs the maximum number of live agents. The cap is server-tunable and
4700
+ * arrives in `details.limit`; deleting an agent frees a slot.
4701
+ */
4702
+ EMAIL_LIMIT_REACHED: "EMAIL_LIMIT_REACHED",
4703
+ /**
4704
+ * 409 from `POST /v1/register` (and `/register/verify`): the email has
4705
+ * spent its lifetime registration budget (deleted agents included).
4706
+ * `details.limit` carries the cap; only a different email helps.
4707
+ */
4708
+ EMAIL_EXHAUSTED: "EMAIL_EXHAUSTED",
4709
+ /**
4710
+ * Legacy spelling of `EMAIL_LIMIT_REACHED` from servers that still enforce
4711
+ * one live agent per email. Retired server-side; mapped to
4712
+ * `EmailLimitReachedError` so callers never branch on it.
4713
+ */
4714
+ EMAIL_TAKEN: "EMAIL_TAKEN",
4715
+ /**
4716
+ * 409 from `POST /v1/agents/recover/verify`: the email backs more than one
4717
+ * agent and recovery was started without a `handle`. `details.handles`
4718
+ * lists the candidates; re-run `recover()` with one of them.
4719
+ */
4720
+ HANDLE_REQUIRED: "HANDLE_REQUIRED",
4721
+ SUSPENDED: "SUSPENDED",
4722
+ RESTRICTED: "RESTRICTED",
4723
+ CONVERSATION_NOT_FOUND: "CONVERSATION_NOT_FOUND",
4724
+ MESSAGE_NOT_FOUND: "MESSAGE_NOT_FOUND",
4725
+ GROUP_DELETED: "GROUP_DELETED",
4726
+ RATE_LIMITED: "RATE_LIMITED",
4727
+ RECIPIENT_BACKLOGGED: "RECIPIENT_BACKLOGGED",
4728
+ AWAITING_REPLY: "AWAITING_REPLY",
4729
+ BLOCKED: "BLOCKED",
4730
+ UNAUTHORIZED: "UNAUTHORIZED",
4731
+ FORBIDDEN: "FORBIDDEN",
4732
+ VALIDATION_ERROR: "VALIDATION_ERROR",
4733
+ INTERNAL_ERROR: "INTERNAL_ERROR",
4734
+ OWNER_NOT_FOUND: "OWNER_NOT_FOUND",
4735
+ INVALID_API_KEY: "INVALID_API_KEY",
4736
+ ALREADY_CLAIMED: "ALREADY_CLAIMED",
4737
+ CLAIM_NOT_FOUND: "CLAIM_NOT_FOUND"
4738
+ };
4739
+ function parseRetryAfter(raw, now2 = Date.now()) {
4740
+ if (!raw) return null;
4741
+ const trimmed = raw.trim();
4742
+ if (!trimmed) return null;
4743
+ if (/^\d+$/.test(trimmed)) {
4744
+ const seconds = Number(trimmed);
4745
+ return Number.isFinite(seconds) ? seconds * 1e3 : null;
4746
+ }
4747
+ if (!/[a-zA-Z]/.test(trimmed)) return null;
4748
+ const epoch = Date.parse(trimmed);
4749
+ if (!Number.isFinite(epoch)) return null;
4750
+ return Math.max(0, epoch - now2);
4751
+ }
4752
+ var AgentChatError = class extends Error {
4753
+ code;
4754
+ status;
4755
+ details;
4756
+ /**
4757
+ * The server's `x-request-id` for the failing request, when present.
4758
+ * Include it in bug reports — the operator can look up the full
4759
+ * server-side trace in seconds.
4760
+ */
4761
+ requestId;
4762
+ constructor(response, status, requestId = null) {
4763
+ super(response.message);
4764
+ this.name = "AgentChatError";
4765
+ this.code = response.code;
4766
+ this.status = status;
4767
+ this.details = response.details;
4768
+ this.requestId = requestId;
4769
+ Object.setPrototypeOf(this, new.target.prototype);
4770
+ }
4771
+ };
4772
+ var RateLimitedError = class extends AgentChatError {
4773
+ retryAfterMs;
4774
+ constructor(response, status, retryAfterMs, requestId = null) {
4775
+ super(response, status, requestId);
4776
+ this.name = "RateLimitedError";
4777
+ this.retryAfterMs = retryAfterMs;
4778
+ }
4779
+ };
4780
+ var SuspendedError = class extends AgentChatError {
4781
+ constructor(response, status, requestId = null) {
4782
+ super(response, status, requestId);
4783
+ this.name = "SuspendedError";
4784
+ }
4785
+ };
4786
+ var RestrictedError = class extends AgentChatError {
4787
+ constructor(response, status, requestId = null) {
4788
+ super(response, status, requestId);
4789
+ this.name = "RestrictedError";
4790
+ }
4791
+ };
4792
+ var RecipientBackloggedError = class extends AgentChatError {
4793
+ recipientHandle;
4794
+ undeliveredCount;
4795
+ constructor(response, status, requestId = null) {
4796
+ super(response, status, requestId);
4797
+ this.name = "RecipientBackloggedError";
4798
+ const d = response.details;
4799
+ this.recipientHandle = typeof d?.recipient_handle === "string" ? d.recipient_handle : null;
4800
+ this.undeliveredCount = typeof d?.undelivered_count === "number" ? d.undelivered_count : null;
4801
+ }
4802
+ };
4803
+ var AwaitingReplyError = class extends AgentChatError {
4804
+ recipientHandle;
4805
+ waitingSince;
4806
+ constructor(response, status, requestId = null) {
4807
+ super(response, status, requestId);
4808
+ this.name = "AwaitingReplyError";
4809
+ const d = response.details;
4810
+ this.recipientHandle = typeof d?.recipient_handle === "string" ? d.recipient_handle : null;
4811
+ this.waitingSince = typeof d?.waiting_since === "string" ? d.waiting_since : null;
4812
+ }
4813
+ };
4814
+ var BlockedError = class extends AgentChatError {
4815
+ constructor(response, status, requestId = null) {
4816
+ super(response, status, requestId);
4817
+ this.name = "BlockedError";
4818
+ }
4819
+ };
4820
+ var ValidationError = class extends AgentChatError {
4821
+ constructor(response, status, requestId = null) {
4822
+ super(response, status, requestId);
4823
+ this.name = "ValidationError";
4824
+ }
4825
+ };
4826
+ var UnauthorizedError = class extends AgentChatError {
4827
+ constructor(response, status, requestId = null) {
4828
+ super(response, status, requestId);
4829
+ this.name = "UnauthorizedError";
4830
+ }
4831
+ };
4832
+ var ForbiddenError = class extends AgentChatError {
4833
+ constructor(response, status, requestId = null) {
4834
+ super(response, status, requestId);
4835
+ this.name = "ForbiddenError";
4836
+ }
4837
+ };
4838
+ var NotFoundError = class extends AgentChatError {
4839
+ constructor(response, status, requestId = null) {
4840
+ super(response, status, requestId);
4841
+ this.name = "NotFoundError";
4842
+ }
4843
+ };
4844
+ var GroupDeletedError = class extends AgentChatError {
4845
+ groupId;
4846
+ deletedByHandle;
4847
+ deletedAt;
4848
+ constructor(response, status, requestId = null) {
4849
+ super(response, status, requestId);
4850
+ this.name = "GroupDeletedError";
4851
+ const d = response.details;
4852
+ this.groupId = typeof d?.group_id === "string" ? d.group_id : null;
4853
+ this.deletedByHandle = typeof d?.deleted_by_handle === "string" ? d.deleted_by_handle : null;
4854
+ this.deletedAt = typeof d?.deleted_at === "string" ? d.deleted_at : null;
4855
+ }
4856
+ };
4857
+ function policyLimit(details) {
4858
+ const limit = details?.limit;
4859
+ return typeof limit === "number" && Number.isInteger(limit) ? limit : null;
4860
+ }
4861
+ var EmailLimitReachedError = class extends AgentChatError {
4862
+ limit;
4863
+ constructor(response, status, requestId = null) {
4864
+ super(response, status, requestId);
4865
+ this.name = "EmailLimitReachedError";
4866
+ this.limit = policyLimit(response.details);
4867
+ }
4868
+ };
4869
+ var EmailExhaustedError = class extends AgentChatError {
4870
+ limit;
4871
+ constructor(response, status, requestId = null) {
4872
+ super(response, status, requestId);
4538
4873
  this.name = "EmailExhaustedError";
4539
4874
  this.limit = policyLimit(response.details);
4540
4875
  }
@@ -4670,8 +5005,8 @@ var HttpTransport = class {
4670
5005
  }
4671
5006
  this.fetchFn = f.bind(globalThis);
4672
5007
  }
4673
- async request(method, path10, opts = {}) {
4674
- const url = `${this.baseUrl}${path10}`;
5008
+ async request(method, path13, opts = {}) {
5009
+ const url = `${this.baseUrl}${path13}`;
4675
5010
  const policy = resolveRetryPolicy(opts.retry, this.retry);
4676
5011
  const canRetry = isRetryEligible(method, opts.idempotencyKey, opts.retry);
4677
5012
  const maxAttempts = canRetry ? policy.maxRetries + 1 : 1;
@@ -4904,10 +5239,10 @@ function statusToCode(status) {
4904
5239
  }
4905
5240
  async function sleep(ms, signal) {
4906
5241
  if (ms <= 0) return;
4907
- await new Promise((resolve7, reject) => {
5242
+ await new Promise((resolve11, reject) => {
4908
5243
  const timer = setTimeout(() => {
4909
5244
  if (signal) signal.removeEventListener("abort", onAbort);
4910
- resolve7();
5245
+ resolve11();
4911
5246
  }, ms);
4912
5247
  const onAbort = () => {
4913
5248
  clearTimeout(timer);
@@ -5115,31 +5450,31 @@ var AgentChatClient = class _AgentChatClient {
5115
5450
  return this.get(`/v1/texts?${params.toString()}`, options);
5116
5451
  }
5117
5452
  // ─── Internal request helpers ─────────────────────────────────────────────
5118
- async get(path10, opts) {
5119
- const res = await this.http.request("GET", path10, this.toRequestOpts(opts));
5453
+ async get(path13, opts) {
5454
+ const res = await this.http.request("GET", path13, this.toRequestOpts(opts));
5120
5455
  return res.data;
5121
5456
  }
5122
- async del(path10, opts) {
5123
- const res = await this.http.request("DELETE", path10, this.toRequestOpts(opts));
5457
+ async del(path13, opts) {
5458
+ const res = await this.http.request("DELETE", path13, this.toRequestOpts(opts));
5124
5459
  return res.data;
5125
5460
  }
5126
- async post(path10, body, opts) {
5127
- const res = await this.http.request("POST", path10, {
5461
+ async post(path13, body, opts) {
5462
+ const res = await this.http.request("POST", path13, {
5128
5463
  ...this.toRequestOpts(opts, { idempotent: false }),
5129
5464
  body
5130
5465
  });
5131
5466
  return res.data;
5132
5467
  }
5133
- async patch(path10, body, opts) {
5134
- const res = await this.http.request("PATCH", path10, {
5468
+ async patch(path13, body, opts) {
5469
+ const res = await this.http.request("PATCH", path13, {
5135
5470
  ...this.toRequestOpts(opts, { idempotent: false }),
5136
5471
  body
5137
5472
  });
5138
5473
  return res.data;
5139
5474
  }
5140
- async put(path10, body, opts) {
5475
+ async put(path13, body, opts) {
5141
5476
  const headers = opts?.contentType ? { "Content-Type": opts.contentType } : void 0;
5142
- const res = await this.http.request("PUT", path10, {
5477
+ const res = await this.http.request("PUT", path13, {
5143
5478
  ...this.toRequestOpts(opts),
5144
5479
  body,
5145
5480
  rawBody: opts?.rawBody,
@@ -7112,17 +7447,17 @@ var RealtimeClient = class {
7112
7447
  */
7113
7448
  heldAtMost(run2) {
7114
7449
  const ms = this.options.inFlightAdoptMs;
7115
- return new Promise((resolve7) => {
7116
- const timer = setTimeout(resolve7, ms);
7450
+ return new Promise((resolve11) => {
7451
+ const timer = setTimeout(resolve11, ms);
7117
7452
  unref(timer);
7118
7453
  run2.then(
7119
7454
  () => {
7120
7455
  clearTimeout(timer);
7121
- resolve7();
7456
+ resolve11();
7122
7457
  },
7123
7458
  () => {
7124
7459
  clearTimeout(timer);
7125
- resolve7();
7460
+ resolve11();
7126
7461
  }
7127
7462
  );
7128
7463
  });
@@ -8289,9 +8624,9 @@ var TurnTracker = class {
8289
8624
  */
8290
8625
  async confirmedEnd(handle, done) {
8291
8626
  if (!this.holds(handle)) return null;
8292
- const released = new Promise((resolve7) => {
8627
+ const released = new Promise((resolve11) => {
8293
8628
  const list = this.waiters.get(handle.key) ?? [];
8294
- list.push(() => resolve7(null));
8629
+ list.push(() => resolve11(null));
8295
8630
  this.waiters.set(handle.key, list);
8296
8631
  });
8297
8632
  let report = done;
@@ -8368,9 +8703,9 @@ function nodeModules() {
8368
8703
  /* @vite-ignore */
8369
8704
  PATH_MODULE
8370
8705
  )
8371
- ]).then(([fs6, path10]) => ({
8372
- fs: fs6.default ?? fs6,
8373
- path: path10.default ?? path10
8706
+ ]).then(([fs9, path13]) => ({
8707
+ fs: fs9.default ?? fs9,
8708
+ path: path13.default ?? path13
8374
8709
  }));
8375
8710
  return modules;
8376
8711
  }
@@ -8388,8 +8723,8 @@ function randomSuffix() {
8388
8723
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
8389
8724
  }
8390
8725
  async function renameWithRetry2(from, to, options = {}) {
8391
- const { fs: fs6 } = await nodeModules();
8392
- const rename = options.rename ?? ((a, b) => fs6.rename(a, b));
8726
+ const { fs: fs9 } = await nodeModules();
8727
+ const rename = options.rename ?? ((a, b) => fs9.rename(a, b));
8393
8728
  const attempts = options.retry ?? isWindows() ? RENAME_ATTEMPTS2 : 1;
8394
8729
  for (let attempt = 1; ; attempt++) {
8395
8730
  try {
@@ -8398,16 +8733,16 @@ async function renameWithRetry2(from, to, options = {}) {
8398
8733
  } catch (err) {
8399
8734
  const code = err.code;
8400
8735
  if (attempt >= attempts || code === void 0 || !RENAME_RETRY_CODES2.has(code)) throw err;
8401
- await new Promise((resolve7) => setTimeout(resolve7, RENAME_DELAY_MS2));
8736
+ await new Promise((resolve11) => setTimeout(resolve11, RENAME_DELAY_MS2));
8402
8737
  }
8403
8738
  }
8404
8739
  }
8405
8740
  async function writeAtomic(file, data, options = {}) {
8406
- const { fs: fs6, path: path10 } = await nodeModules();
8407
- await fs6.mkdir(path10.dirname(file), { recursive: true, mode: 448 });
8408
- const tmp = path10.join(path10.dirname(file), `.${path10.basename(file)}.${randomSuffix()}.tmp`);
8741
+ const { fs: fs9, path: path13 } = await nodeModules();
8742
+ await fs9.mkdir(path13.dirname(file), { recursive: true, mode: 448 });
8743
+ const tmp = path13.join(path13.dirname(file), `.${path13.basename(file)}.${randomSuffix()}.tmp`);
8409
8744
  try {
8410
- const handle = await fs6.open(tmp, "wx", options.mode ?? 438);
8745
+ const handle = await fs9.open(tmp, "wx", options.mode ?? 438);
8411
8746
  try {
8412
8747
  if (options.mode !== void 0) await handle.chmod(options.mode);
8413
8748
  await handle.writeFile(data);
@@ -8417,14 +8752,14 @@ async function writeAtomic(file, data, options = {}) {
8417
8752
  }
8418
8753
  await renameWithRetry2(tmp, file, options);
8419
8754
  } catch (err) {
8420
- await fs6.rm(tmp, { force: true }).catch(() => void 0);
8755
+ await fs9.rm(tmp, { force: true }).catch(() => void 0);
8421
8756
  throw err;
8422
8757
  }
8423
8758
  }
8424
8759
  async function readBytes(file) {
8425
- const { fs: fs6 } = await nodeModules();
8760
+ const { fs: fs9 } = await nodeModules();
8426
8761
  try {
8427
- return new Uint8Array(await fs6.readFile(file));
8762
+ return new Uint8Array(await fs9.readFile(file));
8428
8763
  } catch {
8429
8764
  return null;
8430
8765
  }
@@ -9341,7 +9676,7 @@ var ReceiveLoop = class {
9341
9676
  if (!run2.stale() || this.stopped) this.finishCycle(summary);
9342
9677
  })();
9343
9678
  let timer = null;
9344
- const overdue = new Promise((resolve7) => {
9679
+ const overdue = new Promise((resolve11) => {
9345
9680
  if (!Number.isFinite(this.cycleTimeoutMs)) return;
9346
9681
  const check = () => {
9347
9682
  timer = null;
@@ -9349,7 +9684,7 @@ var ReceiveLoop = class {
9349
9684
  const excluded = excludedMs + (excludedSince !== null ? now2 - excludedSince : 0);
9350
9685
  const active = now2 - startedAt - excluded;
9351
9686
  if (active >= this.cycleTimeoutMs) {
9352
- resolve7("overdue");
9687
+ resolve11("overdue");
9353
9688
  return;
9354
9689
  }
9355
9690
  timer = this._setTimeout(check, Math.max(1, this.cycleTimeoutMs - active));
@@ -9400,7 +9735,7 @@ var ReceiveLoop = class {
9400
9735
  }
9401
9736
  /** The runtime's model call, bounded by `gateCallTimeoutMs` (and the cycle's own abandonment). */
9402
9737
  boundedModelCall(run2) {
9403
- return (prompt) => new Promise((resolve7, reject) => {
9738
+ return (prompt) => new Promise((resolve11, reject) => {
9404
9739
  const controller = new AbortController();
9405
9740
  const abort = () => {
9406
9741
  controller.abort();
@@ -9427,7 +9762,7 @@ var ReceiveLoop = class {
9427
9762
  (text) => {
9428
9763
  if (timer !== null) this._clearTimeout(timer);
9429
9764
  run2.signal.removeEventListener("abort", abort);
9430
- resolve7(text);
9765
+ resolve11(text);
9431
9766
  },
9432
9767
  (err) => {
9433
9768
  if (timer !== null) this._clearTimeout(timer);
@@ -9895,16 +10230,23 @@ var HOUR = 60 * MIN;
9895
10230
  var DAY = 24 * HOUR;
9896
10231
  var MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
9897
10232
 
9898
- // node_modules/.pnpm/@agentchatme+agent-core@0.4.1/node_modules/@agentchatme/agent-core/dist/chunk-7LAAAXUO.js
10233
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/chunk-NAAHIK7Z.js
9899
10234
  import * as path22 from "path";
9900
- import * as path3 from "path";
10235
+ import * as path32 from "path";
9901
10236
  import * as fs4 from "fs";
9902
10237
  import * as path4 from "path";
10238
+ import * as crypto from "crypto";
9903
10239
  import * as fs5 from "fs";
10240
+ import * as os2 from "os";
9904
10241
  import * as path5 from "path";
10242
+ import * as path6 from "path";
10243
+ import * as crypto2 from "crypto";
10244
+ import * as fs6 from "fs";
10245
+ import * as os22 from "os";
10246
+ import * as path7 from "path";
9905
10247
  var TEXTS_CACHE_FILE = "texts.json";
9906
10248
  function textsCachePath(home) {
9907
- return path2.join(home, TEXTS_CACHE_FILE);
10249
+ return path3.join(home, TEXTS_CACHE_FILE);
9908
10250
  }
9909
10251
  var external_exports = {};
9910
10252
  __export2(external_exports, {
@@ -10373,8 +10715,8 @@ function getErrorMap() {
10373
10715
  return overrideErrorMap;
10374
10716
  }
10375
10717
  var makeIssue = (params) => {
10376
- const { data, path: path62, errorMaps, issueData } = params;
10377
- const fullPath = [...path62, ...issueData.path || []];
10718
+ const { data, path: path82, errorMaps, issueData } = params;
10719
+ const fullPath = [...path82, ...issueData.path || []];
10378
10720
  const fullIssue = {
10379
10721
  ...issueData,
10380
10722
  path: fullPath
@@ -10486,11 +10828,11 @@ var errorUtil;
10486
10828
  errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
10487
10829
  })(errorUtil || (errorUtil = {}));
10488
10830
  var ParseInputLazyPath = class {
10489
- constructor(parent, value, path62, key) {
10831
+ constructor(parent, value, path82, key) {
10490
10832
  this._cachedPath = [];
10491
10833
  this.parent = parent;
10492
10834
  this.data = value;
10493
- this._path = path62;
10835
+ this._path = path82;
10494
10836
  this._key = key;
10495
10837
  }
10496
10838
  get path() {
@@ -14013,36 +14355,8 @@ function describeManualSync(result) {
14013
14355
  return `could not write ${at}: ${result.error}`;
14014
14356
  }
14015
14357
  }
14016
- var RUN_PROFILES = ["answer", "work", "full"];
14017
- var RUN_PROFILE_ENV = "AGENTCHAT_RUN_PROFILE";
14018
- var DEFAULT_RUN_PROFILE = "answer";
14019
- function isRunProfile(value) {
14020
- return typeof value === "string" && RUN_PROFILES.includes(value);
14021
- }
14022
- function resolveRunProfile(env = process.env) {
14023
- const raw = env[RUN_PROFILE_ENV]?.trim().toLowerCase();
14024
- return isRunProfile(raw) ? raw : DEFAULT_RUN_PROFILE;
14025
- }
14026
- var INTEGRATION_ENV = "AGENTCHAT_INTEGRATION";
14027
- var INTEGRATION_ENV_LEGACY = "AGENTCHAT_DOORBELL";
14028
- var INTEGRATION_ENV_LEGACY_REMOVAL = "2027-02-01";
14029
- function isOff(raw) {
14030
- const value = raw?.trim().toLowerCase();
14031
- return value === "off" || value === "0" || value === "false";
14032
- }
14033
- function integrationDisabledBy(env = process.env) {
14034
- if (env[INTEGRATION_ENV] !== void 0 && env[INTEGRATION_ENV].trim().length > 0) {
14035
- return isOff(env[INTEGRATION_ENV]) ? INTEGRATION_ENV : null;
14036
- }
14037
- return isOff(env[INTEGRATION_ENV_LEGACY]) ? INTEGRATION_ENV_LEGACY : null;
14038
- }
14039
- var RUN_BUDGET_ENV = "AGENTCHAT_RUN_BUDGET_MS";
14040
- var DEFAULT_RUN_BUDGET_MS = 10 * 6e4;
14041
- var MAX_RUN_BUDGET_MS = 2 * 60 * 6e4;
14042
- function resolveRunBudgetMs(env = process.env) {
14043
- const parsed = Number(env[RUN_BUDGET_ENV]);
14044
- if (!Number.isFinite(parsed) || parsed < 1e3) return DEFAULT_RUN_BUDGET_MS;
14045
- return Math.min(parsed, MAX_RUN_BUDGET_MS);
14358
+ function normalizeHandle2(handle) {
14359
+ return integration_exports.anchor.normalizeHandle(handle);
14046
14360
  }
14047
14361
  var INTEGRATION_STATUS_FILE = "integration.status.json";
14048
14362
  var SOCKET_STATES = ["off", "idle", "connecting", "ready", "reconnecting", "blocked", "closed"];
@@ -14069,6 +14383,7 @@ var StatusSchema = external_exports.object({
14069
14383
  runtime: external_exports.string().nullable(),
14070
14384
  handle: external_exports.string().nullable(),
14071
14385
  profile: external_exports.string(),
14386
+ workdir: external_exports.string().optional(),
14072
14387
  socket: external_exports.enum([...SOCKET_STATES, LEGACY_BLOCKED_STATE]),
14073
14388
  wakes: external_exports.number().optional(),
14074
14389
  wakes_absorbed: external_exports.number().optional(),
@@ -14087,11 +14402,15 @@ var StatusSchema = external_exports.object({
14087
14402
  last_error: external_exports.string().nullable(),
14088
14403
  texts: TextsStatusSchema.nullable().default(null),
14089
14404
  capabilities: external_exports.array(external_exports.string()).nullable().optional(),
14405
+ standby: external_exports.object({ home: external_exports.string().nullable(), pid: external_exports.number().nullable(), since: external_exports.string().nullable() }).nullable().optional(),
14406
+ runs_failing: external_exports.object({ reason: external_exports.string(), since: external_exports.string(), runs_missed: external_exports.number(), checked_at: external_exports.string() }).nullable().optional(),
14407
+ unservable: external_exports.object({ reason: external_exports.enum(["key_refused", "runs_failing"]), detail: external_exports.string(), since: external_exports.string(), retry_at: external_exports.string() }).nullable().optional(),
14408
+ lease_errors: external_exports.object({ count: external_exports.number(), last: external_exports.string().nullable() }).nullable().optional(),
14090
14409
  recent_cycles: external_exports.array(external_exports.object({ at: external_exports.string(), outcome: external_exports.string(), cards: external_exports.number(), invites: external_exports.number(), failure: external_exports.string().nullable() })).nullable().optional(),
14091
14410
  intake_paused: external_exports.boolean().nullable().optional()
14092
14411
  }).passthrough();
14093
14412
  function integrationStatusPath(home) {
14094
- return path3.join(home, INTEGRATION_STATUS_FILE);
14413
+ return path32.join(home, INTEGRATION_STATUS_FILE);
14095
14414
  }
14096
14415
  function writeIntegrationStatus(home, status) {
14097
14416
  try {
@@ -14119,366 +14438,501 @@ function idle(home) {
14119
14438
  } catch {
14120
14439
  }
14121
14440
  }
14122
- function acquireLeaderLock(home) {
14123
- const lockPath = path5.join(home, "daemon.lock");
14124
- fs5.mkdirSync(home, { recursive: true });
14125
- const tryWrite = () => {
14126
- try {
14127
- const fd = fs5.openSync(lockPath, "wx");
14128
- fs5.writeSync(fd, String(process.pid));
14129
- fs5.closeSync(fd);
14130
- return true;
14131
- } catch {
14132
- return false;
14133
- }
14134
- };
14135
- if (tryWrite()) return makeHandle(lockPath);
14136
- let holderPid = 0;
14441
+ var LEASE_RENEW_MS = 1e4;
14442
+ var LEASE_STALE_MS = 45e3;
14443
+ var WRITE_GRACE_MS = 5e3;
14444
+ var GUARD_STALE_MS = 1e4;
14445
+ var BOOT_MARGIN_MS = 6e4;
14446
+ var ATTEMPTS = 40;
14447
+ var BACKOFF_MS = 25;
14448
+ var sleep2 = (ms) => new Promise((resolve32) => setTimeout(resolve32, ms));
14449
+ function pause(ms, signal) {
14450
+ if (signal?.aborted === true) return Promise.resolve();
14451
+ return new Promise((resolve32) => {
14452
+ const done = () => {
14453
+ clearTimeout(timer);
14454
+ signal?.removeEventListener("abort", done);
14455
+ resolve32();
14456
+ };
14457
+ const timer = setTimeout(done, ms);
14458
+ signal?.addEventListener("abort", done, { once: true });
14459
+ });
14460
+ }
14461
+ function leaseConfirmMs(renewMs = LEASE_RENEW_MS) {
14462
+ return Math.round(renewMs * 1.5);
14463
+ }
14464
+ function leaseStartupObserveMs(options = {}) {
14465
+ return (options.staleMs ?? LEASE_STALE_MS) + (options.renewMs ?? LEASE_RENEW_MS);
14466
+ }
14467
+ function hostname22() {
14137
14468
  try {
14138
- holderPid = Number.parseInt(fs5.readFileSync(lockPath, "utf-8").trim(), 10);
14469
+ return os2.hostname();
14139
14470
  } catch {
14471
+ return "";
14140
14472
  }
14141
- if (holderPid && isAlive(holderPid)) {
14142
- log.error(`another agentchatd already holds ${lockPath} (pid ${holderPid})`);
14143
- return null;
14144
- }
14145
- log.warn(`stealing stale lock ${lockPath} (dead pid ${holderPid || "?"})`);
14473
+ }
14474
+ function bootedAt(now2 = Date.now()) {
14475
+ return now2 - os2.uptime() * 1e3;
14476
+ }
14477
+ function pidAlive(pid) {
14478
+ if (!Number.isInteger(pid) || pid <= 0) return false;
14146
14479
  try {
14147
- fs5.writeFileSync(lockPath, String(process.pid));
14148
- return makeHandle(lockPath);
14480
+ process.kill(pid, 0);
14481
+ return true;
14149
14482
  } catch (err) {
14150
- log.error(`could not steal stale lock: ${String(err)}`);
14151
- return null;
14483
+ return err.code === "EPERM";
14152
14484
  }
14153
14485
  }
14154
- function isAlive(pid) {
14486
+ function parseLease(raw) {
14487
+ const text = raw.trim();
14488
+ const firstLine = text.split(/\r?\n/, 1)[0]?.trim() ?? "";
14489
+ if (!/^\d+$/.test(firstLine)) return null;
14490
+ const pid = Number(firstLine);
14491
+ const rest = text.slice(firstLine.length).trim();
14492
+ if (rest.length === 0) return { pid, token: null, host: null, renewed_at: null };
14155
14493
  try {
14156
- process.kill(pid, 0);
14157
- return true;
14494
+ const j = JSON.parse(rest);
14495
+ return {
14496
+ pid,
14497
+ token: typeof j["token"] === "string" ? j["token"] : null,
14498
+ host: typeof j["host"] === "string" ? j["host"] : null,
14499
+ ...typeof j["home"] === "string" ? { home: j["home"] } : {},
14500
+ ...typeof j["label"] === "string" ? { label: j["label"] } : {},
14501
+ ...typeof j["acquired_at"] === "string" ? { acquired_at: j["acquired_at"] } : {},
14502
+ renewed_at: typeof j["renewed_at"] === "number" && Number.isFinite(j["renewed_at"]) ? j["renewed_at"] : null
14503
+ };
14158
14504
  } catch {
14159
- return false;
14505
+ return null;
14160
14506
  }
14161
14507
  }
14162
- function makeHandle(lockPath) {
14163
- let released = false;
14164
- const release = () => {
14165
- if (released) return;
14166
- released = true;
14167
- try {
14168
- if (fs5.readFileSync(lockPath, "utf-8").trim() === String(process.pid)) {
14169
- fs5.unlinkSync(lockPath);
14170
- }
14171
- } catch {
14172
- }
14173
- };
14174
- return { release };
14508
+ var sameHost = (holder) => holder.host === null || holder.host === hostname22();
14509
+ function legacyLive(holder, mtimeMs, booted) {
14510
+ if (!pidAlive(holder.pid)) return false;
14511
+ return mtimeMs === null || mtimeMs >= booted - BOOT_MARGIN_MS;
14175
14512
  }
14176
-
14177
- // node_modules/.pnpm/@agentchatme+agent-core@0.4.1/node_modules/@agentchatme/agent-core/dist/chunk-XDWBTX5J.js
14178
- var VERSION2 = "0.4.1";
14179
- var HOSTED_MCP_PATH2 = integration_exports.HOSTED_MCP_PATH;
14180
- function hostedMcpUrl2(apiBase) {
14181
- return integration_exports.hostedMcpUrl(apiBase);
14513
+ function holderLive(holder, at = {}) {
14514
+ const now2 = at.now ?? Date.now();
14515
+ if (holder.renewed_at === null) return legacyLive(holder, at.mtimeMs ?? null, at.bootedAt ?? bootedAt(now2));
14516
+ if (sameHost(holder) && !pidAlive(holder.pid)) return false;
14517
+ return Math.abs(now2 - holder.renewed_at) < (at.staleMs ?? LEASE_STALE_MS);
14182
14518
  }
14183
-
14184
- // node_modules/.pnpm/@agentchatme+agent-core@0.4.1/node_modules/@agentchatme/agent-core/dist/index.js
14185
- var StateSchema = external_exports.object({
14186
- // Set when the user has said "not now" to setting up a handle. PERMANENT
14187
- // until they change their mind, because the prompt that needs suppressing
14188
- // lives in the always-loaded instruction file and would otherwise be re-read
14189
- // — and re-acted on — every single session.
14190
- offer_declined_at: external_exports.string().optional()
14191
- });
14192
- var ANCHOR_START = integration_exports.anchor.START_MARKER;
14193
- var ANCHOR_END = integration_exports.anchor.END_MARKER;
14194
- var MARKER_LINES = /* @__PURE__ */ new Set([
14195
- integration_exports.anchor.START_MARKER,
14196
- integration_exports.anchor.END_MARKER,
14197
- integration_exports.anchor.LEGACY_START_MARKER,
14198
- integration_exports.anchor.LEGACY_END_MARKER
14199
- ]);
14200
- var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
14201
- var NO_TEXTS = Object.freeze({ identityLine: null, identityLineTemplate: null, manual: null });
14202
-
14203
- // node_modules/.pnpm/@agentchatme+agent-core@0.4.1/node_modules/@agentchatme/agent-core/dist/chunk-AE4XHKHQ.js
14204
- var DEFAULT_GRACE_MS = 5e3;
14205
- var DEFAULT_DRAIN_MS = 2e3;
14206
- var DEFAULT_ABANDON_MS = 5e3;
14207
- var STDERR_TAIL_CHARS = 400;
14208
- function redactDiagnostic(value, max = STDERR_TAIL_CHARS) {
14209
- return value.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, "").replace(/\b(api[_ -]?key\s*[:=]\s*)\S+/gi, "$1[redacted]").replace(/\b(Bearer)\s+[A-Za-z0-9._~-]{8,}\b/gi, "$1 [redacted]").replace(/\bac_[A-Za-z0-9_-]{8,}\b/g, "[redacted AgentChat key]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, "[redacted key]").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "").replace(/\s+/g, " ").trim().slice(-max);
14519
+ var observations = /* @__PURE__ */ new Map();
14520
+ function judge(file, holder, ctx) {
14521
+ if (holder === null) return mtimeOf(file) !== null && ctx.now - (mtimeOf(file) ?? 0) < WRITE_GRACE_MS ? "writing" : "stale";
14522
+ if (holder.renewed_at === null) return legacyLive(holder, mtimeOf(file), ctx.booted) ? "held" : "stale";
14523
+ if (sameHost(holder)) {
14524
+ if (!pidAlive(holder.pid)) return "stale";
14525
+ const mtime = mtimeOf(file);
14526
+ if (mtime !== null && mtime < ctx.booted - BOOT_MARGIN_MS && holder.renewed_at < ctx.booted - BOOT_MARGIN_MS) return "stale";
14527
+ }
14528
+ const signature = `${holder.token ?? ""}\0${holder.renewed_at}`;
14529
+ const seen = observations.get(file);
14530
+ if (seen === void 0 || seen.signature !== signature) {
14531
+ observations.set(file, { signature, firstSeen: ctx.mono });
14532
+ return "held";
14533
+ }
14534
+ return ctx.mono - seen.firstSeen >= ctx.staleMs ? "observed" : "held";
14210
14535
  }
14211
- var KILL_TIMEOUT_MS = 5e3;
14212
- function killProcessTree(child, signal) {
14213
- if (child.pid === void 0) return;
14536
+ function signatureOf(holder) {
14537
+ return holder === null || holder.renewed_at === null ? null : `${holder.token ?? ""}\0${holder.renewed_at}`;
14538
+ }
14539
+ function readRaw(file) {
14214
14540
  try {
14215
- if (process.platform === "win32") {
14216
- spawnCommandSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
14217
- windowsHide: true,
14218
- stdio: "ignore",
14219
- timeout: KILL_TIMEOUT_MS
14220
- });
14221
- } else {
14222
- process.kill(-child.pid, signal);
14223
- }
14541
+ return fs5.readFileSync(file, "utf-8");
14224
14542
  } catch {
14225
- try {
14226
- child.kill(signal);
14227
- } catch {
14228
- }
14543
+ return null;
14229
14544
  }
14230
14545
  }
14231
- function fileTime(ms) {
14232
- return String((BigInt(Math.round(ms)) + 11644473600000n) * 10000n);
14546
+ function mtimeOf(file) {
14547
+ try {
14548
+ return fs5.statSync(file).mtimeMs;
14549
+ } catch {
14550
+ return null;
14551
+ }
14233
14552
  }
14234
- var WINDOWS_SWEEP_TIMEOUT_MS = 6e4;
14235
- function sweepWindowsDescendants(rootPid, aliveFromMs, aliveUntilMs, options = {}) {
14236
- if (process.platform !== "win32" || !Number.isInteger(rootPid) || rootPid <= 0) return Promise.resolve(null);
14237
- const script = [
14238
- "$ErrorActionPreference = 'Continue'",
14239
- // Progress records ('Preparing modules for first use') would reach stderr as CLIXML.
14240
- "$ProgressPreference = 'SilentlyContinue'",
14241
- `$from = [DateTime]::FromFileTime(${fileTime(aliveFromMs - 1e3)})`,
14242
- `$until = [DateTime]::FromFileTime(${fileTime(aliveUntilMs + 1e3)})`,
14243
- "Write-Output ('window ' + $from.ToUniversalTime().ToString('o') + ' ' + $until.ToUniversalTime().ToString('o'))",
14244
- `foreach ($p in @(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${rootPid}')) {`,
14245
- " Write-Output ('candidate ' + $p.ProcessId + ' ' + $p.CreationDate.ToUniversalTime().ToString('o'))",
14246
- " if ($p.CreationDate -ge $from -and $p.CreationDate -le $until) {",
14247
- " & taskkill.exe /T /F /PID $p.ProcessId 2>&1 | Out-Null",
14248
- " Write-Output ('kill ' + $p.ProcessId + ' ' + $LASTEXITCODE)",
14249
- " }",
14250
- "}"
14251
- ].join("\n");
14252
- return new Promise((resolve7) => {
14253
- let stdout = "";
14254
- let stderr = "";
14255
- let timedOut = false;
14256
- let done = false;
14257
- const finish = (exitCode) => {
14258
- if (done) return;
14259
- done = true;
14260
- clearTimeout(timer);
14261
- const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
14262
- resolve7({
14263
- exitCode,
14264
- timedOut,
14265
- candidates: lines.filter((l) => l.startsWith("candidate ")).map((l) => l.slice("candidate ".length)),
14266
- killed: lines.filter((l) => l.startsWith("kill ")).map((l) => l.split(" ")).map(([, pid, code]) => ({ pid: Number(pid), code: Number(code) })),
14267
- window: lines.find((l) => l.startsWith("window "))?.slice("window ".length) ?? null,
14268
- stderr: redactDiagnostic(stderr)
14269
- });
14270
- };
14271
- let sweeper;
14272
- try {
14273
- sweeper = spawnCommand(
14274
- "powershell.exe",
14275
- ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")],
14276
- { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
14277
- );
14278
- } catch (err) {
14279
- stderr = String(err);
14280
- finish(null);
14281
- return;
14553
+ function createExclusive(file, content) {
14554
+ let fd;
14555
+ try {
14556
+ fd = fs5.openSync(file, "wx", 384);
14557
+ } catch (err) {
14558
+ if (err.code === "EEXIST") return false;
14559
+ throw err;
14560
+ }
14561
+ try {
14562
+ fs5.writeSync(fd, content);
14563
+ fs5.fsyncSync(fd);
14564
+ } finally {
14565
+ fs5.closeSync(fd);
14566
+ }
14567
+ return true;
14568
+ }
14569
+ function removeIfStill(file, content) {
14570
+ if (readRaw(file) !== content) return;
14571
+ const aside = `${file}.gone-${crypto.randomUUID()}`;
14572
+ try {
14573
+ fs5.renameSync(file, aside);
14574
+ } catch {
14575
+ return;
14576
+ }
14577
+ if (readRaw(aside) === content) fs5.rmSync(aside, { force: true });
14578
+ else {
14579
+ try {
14580
+ fs5.linkSync(aside, file);
14581
+ } catch {
14282
14582
  }
14283
- const timer = setTimeout(() => {
14284
- timedOut = true;
14583
+ fs5.rmSync(aside, { force: true });
14584
+ }
14585
+ }
14586
+ function replaceContent(file, content) {
14587
+ const temp = `${file}.renew-${crypto.randomUUID()}`;
14588
+ try {
14589
+ fs5.writeFileSync(temp, content, { mode: 384 });
14590
+ fs5.renameSync(temp, file);
14591
+ } catch {
14592
+ fs5.rmSync(temp, { force: true });
14593
+ fs5.writeFileSync(file, content, { mode: 384 });
14594
+ }
14595
+ }
14596
+ function withGuard(file, now2, fn) {
14597
+ const guard = `${file}.takeover`;
14598
+ const mine = `${process.pid}
14599
+ ${JSON.stringify({ pid: process.pid, token: crypto.randomUUID(), host: hostname22(), renewed_at: now2 })}
14600
+ `;
14601
+ if (!createExclusive(guard, mine)) {
14602
+ const raw = readRaw(guard);
14603
+ const g = raw === null ? null : parseLease(raw);
14604
+ const dead = g !== null && sameHost(g) && !pidAlive(g.pid);
14605
+ if (raw !== null && (dead || now2 - (mtimeOf(guard) ?? now2) > GUARD_STALE_MS)) removeIfStill(guard, raw);
14606
+ return false;
14607
+ }
14608
+ try {
14609
+ fn();
14610
+ } finally {
14611
+ removeIfStill(guard, mine);
14612
+ }
14613
+ return true;
14614
+ }
14615
+ async function acquireLease(file, info = {}, options = {}) {
14616
+ const now2 = options.now ?? Date.now;
14617
+ const mono = options.monotonic ?? (() => performance.now());
14618
+ const staleMs = options.staleMs ?? LEASE_STALE_MS;
14619
+ const renewMs = options.renewMs ?? LEASE_RENEW_MS;
14620
+ const booted = (options.bootedAt ?? (() => bootedAt(now2())))();
14621
+ const signal = options.signal;
14622
+ const observeUntil = performance.now() + (options.observeMs ?? 0);
14623
+ const pollMs = Math.max(50, Math.min(1e3, Math.round(renewMs / 4)));
14624
+ let firstSignature = null;
14625
+ let confirmed = null;
14626
+ fs5.mkdirSync(path5.dirname(file), { recursive: true, mode: 448 });
14627
+ const token = crypto.randomUUID();
14628
+ const acquiredAt = new Date(now2()).toISOString();
14629
+ const render2 = (renewedAt) => `${process.pid}
14630
+ ${JSON.stringify({ pid: process.pid, token, host: hostname22(), ...info, acquired_at: acquiredAt, renewed_at: renewedAt })}
14631
+ `;
14632
+ let attempt = 0;
14633
+ while (attempt < ATTEMPTS) {
14634
+ if (createExclusive(file, render2(now2()))) {
14635
+ observations.delete(file);
14636
+ return { ok: true, lease: startLease(file, token, render2, options) };
14637
+ }
14638
+ const raw2 = readRaw(file);
14639
+ if (raw2 === null) {
14640
+ attempt += 1;
14641
+ continue;
14642
+ }
14643
+ const holder2 = parseLease(raw2);
14644
+ const verdict = judge(file, holder2, { now: now2(), mono: mono(), staleMs, booted });
14645
+ if (verdict === "writing") {
14646
+ attempt += 1;
14647
+ await sleep2(BACKOFF_MS);
14648
+ continue;
14649
+ }
14650
+ if (verdict === "observed" && raw2 !== confirmed) {
14651
+ await pause(leaseConfirmMs(renewMs), signal);
14652
+ if (signal?.aborted === true) return { ok: false, path: file, holder: holder2 };
14653
+ if (readRaw(file) !== raw2) continue;
14654
+ confirmed = raw2;
14655
+ } else if (verdict === "held") {
14656
+ const signature = signatureOf(holder2);
14657
+ if (firstSignature !== null && signature !== firstSignature) return { ok: false, path: file, holder: holder2 };
14658
+ firstSignature ??= signature;
14659
+ if (signature === null || performance.now() >= observeUntil || signal?.aborted === true) return { ok: false, path: file, holder: holder2 };
14660
+ await pause(pollMs, signal);
14661
+ continue;
14662
+ }
14663
+ attempt += 1;
14664
+ if (!withGuard(file, now2(), () => removeIfStill(file, raw2))) await sleep2(BACKOFF_MS);
14665
+ }
14666
+ const raw = readRaw(file);
14667
+ const holder = raw === null ? null : parseLease(raw);
14668
+ return { ok: false, path: file, holder: holder !== null && holderLive(holder, { now: now2(), staleMs, mtimeMs: mtimeOf(file), bootedAt: booted }) ? holder : null };
14669
+ }
14670
+ function startLease(file, token, render2, options) {
14671
+ const now2 = options.now ?? Date.now;
14672
+ const mono = options.monotonic ?? (() => performance.now());
14673
+ const staleMs = options.staleMs ?? LEASE_STALE_MS;
14674
+ const listeners = [];
14675
+ let lost = false;
14676
+ let renewErrors = 0;
14677
+ let lastRenewError = null;
14678
+ let lastRenewedMono = mono();
14679
+ let content = readRaw(file) ?? "";
14680
+ const loseIt = (why) => {
14681
+ if (lost) return;
14682
+ lost = true;
14683
+ clearInterval(timer);
14684
+ for (const l of listeners) {
14285
14685
  try {
14286
- sweeper.kill();
14686
+ l(why);
14287
14687
  } catch {
14288
14688
  }
14289
- finish(null);
14290
- }, options.timeoutMs ?? WINDOWS_SWEEP_TIMEOUT_MS);
14291
- timer.unref?.();
14292
- sweeper.stdout?.on("data", (c) => {
14293
- stdout = (stdout + String(c)).slice(-16e3);
14294
- });
14295
- sweeper.stderr?.on("data", (c) => {
14296
- stderr = (stderr + String(c)).slice(-4e3);
14297
- });
14298
- sweeper.on("error", (err) => {
14299
- stderr += String(err);
14300
- finish(null);
14301
- });
14302
- sweeper.on("close", (code) => finish(code));
14303
- });
14304
- }
14305
- function describeWindowsSweep(sweep) {
14306
- const killed = sweep.killed.map((k) => `${k.pid} (taskkill ${k.code})`).join(", ") || "none";
14307
- return `windows leftover sweep: exit ${sweep.exitCode ?? (sweep.timedOut ? "timed out" : "none")}; window ${sweep.window ?? "?"}; children seen ${sweep.candidates.length > 0 ? sweep.candidates.join(", ") : "none"}; killed ${killed}${sweep.stderr ? `; stderr: ${sweep.stderr}` : ""}`;
14308
- }
14309
- function spawnRun(spec) {
14310
- const started = Date.now();
14311
- const graceMs = spec.graceMs ?? DEFAULT_GRACE_MS;
14312
- const drainMs = spec.drainMs ?? DEFAULT_DRAIN_MS;
14313
- const abandonMs = spec.abandonMs ?? DEFAULT_ABANDON_MS;
14314
- return new Promise((resolve7) => {
14315
- let settled = false;
14316
- let stdoutBytes = 0;
14317
- let stderrTail = "";
14318
- let timedOut = false;
14319
- let interrupted = false;
14320
- let terminating = false;
14321
- let exited = null;
14322
- const timers = /* @__PURE__ */ new Set();
14323
- let onAbort = null;
14324
- let child = null;
14325
- const later = (ms, fn) => {
14326
- const timer = setTimeout(() => {
14327
- timers.delete(timer);
14328
- fn();
14329
- }, ms);
14330
- timers.add(timer);
14331
- };
14332
- const finish = (outcome) => {
14333
- if (settled) return;
14334
- settled = true;
14335
- for (const timer of timers) clearTimeout(timer);
14336
- timers.clear();
14337
- if (onAbort) spec.signal?.removeEventListener("abort", onAbort);
14338
- resolve7({ ...outcome, durationMs: Date.now() - started });
14339
- };
14340
- const detach = () => {
14341
- if (child === null) return;
14342
- for (const stream of [child.stdin, child.stdout, child.stderr]) {
14343
- try {
14344
- stream?.destroy();
14345
- } catch {
14689
+ }
14690
+ };
14691
+ const renew = () => {
14692
+ if (lost) return;
14693
+ try {
14694
+ const done = withGuard(file, now2(), () => {
14695
+ const raw = readRaw(file);
14696
+ const holder = raw === null ? null : parseLease(raw);
14697
+ if (holder?.token !== token) {
14698
+ loseIt(raw === null ? `${file} was removed` : `${file} now names another holder (pid ${holder?.pid ?? "?"})`);
14699
+ return;
14346
14700
  }
14347
- }
14701
+ const next = render2(now2());
14702
+ replaceContent(file, next);
14703
+ content = next;
14704
+ lastRenewedMono = mono();
14705
+ });
14706
+ if (!done && mono() - lastRenewedMono >= staleMs) loseIt(`could not renew ${file} for ${Math.round(staleMs / 1e3)} s (its guard stayed taken)`);
14707
+ } catch (err) {
14708
+ renewErrors += 1;
14709
+ lastRenewError = err instanceof Error ? err.message : String(err);
14710
+ if (readRaw(file) === null) loseIt(`${file} is gone (${lastRenewError})`);
14711
+ else if (mono() - lastRenewedMono >= staleMs) loseIt(`could not renew ${file} for ${Math.round(staleMs / 1e3)} s (${lastRenewError})`);
14712
+ }
14713
+ };
14714
+ const timer = setInterval(renew, options.renewMs ?? LEASE_RENEW_MS);
14715
+ timer.unref();
14716
+ return {
14717
+ path: file,
14718
+ get lost() {
14719
+ return lost;
14720
+ },
14721
+ get renewErrors() {
14722
+ return renewErrors;
14723
+ },
14724
+ get lastRenewError() {
14725
+ return lastRenewError;
14726
+ },
14727
+ onLost(listener) {
14728
+ listeners.push(listener);
14729
+ },
14730
+ release() {
14731
+ if (lost) return;
14732
+ lost = true;
14733
+ clearInterval(timer);
14348
14734
  try {
14349
- child.unref();
14735
+ const done = withGuard(file, now2(), () => {
14736
+ const raw = readRaw(file);
14737
+ if (raw !== null && parseLease(raw)?.token === token) removeIfStill(file, raw);
14738
+ });
14739
+ if (!done) removeIfStill(file, readRaw(file) === content ? content : "\0");
14350
14740
  } catch {
14351
14741
  }
14352
- };
14353
- const classify = (code, signal, note) => {
14354
- const tail = redactDiagnostic(stderrTail);
14355
- const extra = `${note ? ` (${note})` : ""}${tail ? `: ${tail}` : ""}`;
14356
- if (timedOut) {
14357
- return { state: "timed_out", exitCode: code, detail: `run exceeded its ${Math.round(spec.budgetMs / 1e3)} s budget and was killed${extra}` };
14358
- }
14359
- if (interrupted) {
14360
- return { state: "failed", exitCode: code, detail: `interrupted \u2014 the integration was stopping; the tray stays unread for the next run${extra}` };
14361
- }
14362
- if (code === 0) return note ? { state: "ok", exitCode: 0, detail: note } : { state: "ok", exitCode: 0 };
14363
- const exit = code === null ? `signal ${signal ?? "unknown"}` : `exit ${code}`;
14364
- if (stdoutBytes === 0) return { state: "not_started", exitCode: code, detail: `${exit} with nothing on stdout${extra}` };
14365
- return { state: "failed", exitCode: code, detail: `${exit}${extra}` };
14366
- };
14367
- if (spec.signal?.aborted) {
14368
- finish({ state: "not_started", exitCode: null, detail: "interrupted before the runtime was started" });
14369
- return;
14370
14742
  }
14743
+ };
14744
+ }
14745
+ var DAEMON_LOCK_FILE = "daemon.lock";
14746
+ async function acquireLeaderLock(home, options = {}) {
14747
+ const lockPath = path6.join(home, DAEMON_LOCK_FILE);
14748
+ const attempt = await acquireLease(lockPath, { home: path6.resolve(home) }, { observeMs: leaseStartupObserveMs(options), ...options });
14749
+ if (attempt.ok) return attempt.lease;
14750
+ log.error(`another agentchat daemon already holds ${lockPath}${attempt.holder !== null ? ` (pid ${attempt.holder.pid})` : ""}`);
14751
+ return null;
14752
+ }
14753
+ var AGENT_LOCK_DIR_ENV = "AGENTCHAT_LOCK_DIR";
14754
+ function agentLockDir(env = process.env, system = process.platform, home = os22.homedir()) {
14755
+ const override = env[AGENT_LOCK_DIR_ENV]?.trim();
14756
+ if (override !== void 0 && override.length > 0) return path7.resolve(override);
14757
+ const p = system === "win32" ? path7.win32 : path7.posix;
14758
+ if (system === "darwin") return p.join(home, "Library", "Application Support", "AgentChat", "locks");
14759
+ if (system === "win32") return p.join(home, "AppData", "Local", "AgentChat", "locks");
14760
+ return p.join(home, ".local", "state", "agentchat", "locks");
14761
+ }
14762
+ function originOf(apiBase) {
14763
+ try {
14764
+ return new URL(apiBase).origin.toLowerCase();
14765
+ } catch {
14766
+ return apiBase.trim().toLowerCase();
14767
+ }
14768
+ }
14769
+ function agentLockPath(agent, env = process.env) {
14770
+ const id = crypto2.createHash("sha256").update(`${originOf(agent.apiBase)}
14771
+ ${normalizeHandle2(agent.handle)}`).digest("hex").slice(0, 32);
14772
+ return path7.join(agentLockDir(env), `agent-${id}.lock`);
14773
+ }
14774
+ function acquireAgentLock(agent, env = process.env, options = {}) {
14775
+ return acquireLease(agentLockPath(agent, env), { home: path7.resolve(agent.home), label: `@${normalizeHandle2(agent.handle)}` }, options);
14776
+ }
14777
+ function agentLockRefusal(agent, holder, file) {
14778
+ const who = holder === null ? `another listener (its lock ${file} is being taken over right now)` : `${holder.home !== void 0 ? holder.home : "another identity home"} (pid ${holder.pid}${holder.host !== null ? ` on ${holder.host}` : ""}${holder.acquired_at !== void 0 ? `, since ${holder.acquired_at}` : ""})`;
14779
+ return `@${normalizeHandle2(agent.handle)} is served by ${who}: this one (${path7.resolve(agent.home)}) holds no socket and starts no run while it does, so no message is answered twice. Stop that one, or log out here; this one takes over when it stops.`;
14780
+ }
14781
+ var STANDBY_MARKER_FRESH_MS = 9e4;
14782
+ function hostnameOf() {
14783
+ try {
14784
+ return os22.hostname();
14785
+ } catch {
14786
+ return "";
14787
+ }
14788
+ }
14789
+ function standbyMarkerPath(lockFile, home) {
14790
+ return `${lockFile}.standby-${crypto2.createHash("sha256").update(path7.resolve(home)).digest("hex").slice(0, 16)}`;
14791
+ }
14792
+ function markStandby(lockFile, home) {
14793
+ const file = standbyMarkerPath(lockFile, home);
14794
+ const content = `${process.pid}
14795
+ ${JSON.stringify({ pid: process.pid, host: hostnameOf(), home: path7.resolve(home), at: Date.now() })}
14796
+ `;
14797
+ try {
14798
+ fs6.mkdirSync(path7.dirname(file), { recursive: true, mode: 448 });
14799
+ const temp = `${file}.${crypto2.randomUUID()}`;
14800
+ fs6.writeFileSync(temp, content, { mode: 384 });
14801
+ fs6.renameSync(temp, file);
14802
+ } catch {
14803
+ }
14804
+ }
14805
+ function clearStandby(lockFile, home) {
14806
+ try {
14807
+ fs6.rmSync(standbyMarkerPath(lockFile, home), { force: true });
14808
+ } catch {
14809
+ }
14810
+ }
14811
+ function standbyWaiting(lockFile, home, now2 = Date.now()) {
14812
+ const own = standbyMarkerPath(lockFile, home);
14813
+ const prefix = `${path7.basename(lockFile)}.standby-`;
14814
+ let names;
14815
+ try {
14816
+ names = fs6.readdirSync(path7.dirname(lockFile));
14817
+ } catch {
14818
+ return false;
14819
+ }
14820
+ for (const name of names) {
14821
+ if (!name.startsWith(prefix) || name.includes(".", prefix.length)) continue;
14822
+ const file = path7.join(path7.dirname(lockFile), name);
14823
+ if (file === own) continue;
14824
+ try {
14825
+ const st = fs6.statSync(file);
14826
+ if (Math.abs(now2 - st.mtimeMs) >= STANDBY_MARKER_FRESH_MS) continue;
14827
+ const marker = parseLease(fs6.readFileSync(file, "utf-8"));
14828
+ if (marker === null) continue;
14829
+ const sameHost2 = marker.host === null || marker.host === hostnameOf();
14830
+ if (sameHost2 && !pidAlive(marker.pid)) continue;
14831
+ return true;
14832
+ } catch {
14833
+ continue;
14834
+ }
14835
+ }
14836
+ return false;
14837
+ }
14838
+
14839
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/chunk-UE7DKW3C.js
14840
+ var VERSION2 = "0.5.0";
14841
+ var HOSTED_MCP_PATH2 = integration_exports.HOSTED_MCP_PATH;
14842
+ function hostedMcpUrl2(apiBase) {
14843
+ return integration_exports.hostedMcpUrl(apiBase);
14844
+ }
14845
+ var PROBE_KILL_WAIT_MS = 5e3;
14846
+ var MAX_OUTPUT = 64 * 1024;
14847
+ function runProbe(command, args, options) {
14848
+ return new Promise((resolve11) => {
14849
+ let child;
14371
14850
  try {
14372
- child = spawnCommand(spec.command, [...spec.args], {
14373
- cwd: spec.cwd,
14374
- env: spec.env,
14375
- stdio: [spec.stdin === null ? "ignore" : "pipe", "pipe", "pipe"],
14851
+ child = spawnCommand(command, [...args], {
14852
+ ...options.env !== void 0 ? { env: options.env } : {},
14853
+ ...options.cwd !== void 0 ? { cwd: options.cwd } : {},
14854
+ stdio: ["ignore", "pipe", "pipe"],
14855
+ // Its own process group on POSIX, so the whole tree can be killed.
14376
14856
  detached: process.platform !== "win32",
14377
- windowsHide: true,
14378
- ...spec.shell === true ? { shell: true } : {}
14857
+ windowsHide: true
14379
14858
  });
14380
14859
  } catch (err) {
14381
- finish({ state: "not_started", exitCode: null, detail: redactDiagnostic(String(err)) });
14860
+ resolve11({ error: err instanceof Error ? err : new Error(String(err)), status: null, stdout: "", stderr: "", timedOut: false });
14382
14861
  return;
14383
14862
  }
14384
14863
  const proc = child;
14385
- if (spec.onStarted) {
14386
- const onStarted = spec.onStarted;
14387
- proc.once("spawn", () => {
14388
- try {
14389
- onStarted();
14390
- } catch {
14391
- }
14392
- });
14393
- }
14864
+ let stdout = "";
14865
+ let stderr = "";
14866
+ let timedOut = false;
14867
+ let stopped = false;
14868
+ let finished = false;
14869
+ let giveUp = null;
14870
+ const finish = (result) => {
14871
+ if (finished) return;
14872
+ finished = true;
14873
+ clearTimeout(timer);
14874
+ if (giveUp !== null) clearTimeout(giveUp);
14875
+ resolve11(result);
14876
+ };
14394
14877
  proc.stdout?.on("data", (chunk) => {
14395
- stdoutBytes += chunk.length;
14878
+ if (stdout.length < MAX_OUTPUT) stdout += chunk.toString("utf-8");
14396
14879
  });
14397
14880
  proc.stderr?.on("data", (chunk) => {
14398
- stderrTail = (stderrTail + String(chunk)).slice(-4 * STDERR_TAIL_CHARS);
14881
+ if (stderr.length < MAX_OUTPUT) stderr += chunk.toString("utf-8");
14399
14882
  });
14400
- proc.stdout?.on("error", () => void 0);
14401
- proc.stderr?.on("error", () => void 0);
14402
- if (spec.stdin !== null && proc.stdin) {
14403
- proc.stdin.on("error", () => {
14404
- });
14405
- try {
14406
- proc.stdin.write(spec.stdin);
14407
- proc.stdin.end();
14408
- } catch {
14409
- }
14410
- }
14411
- const terminate = () => {
14412
- if (terminating || settled) return;
14413
- terminating = true;
14414
- killProcessTree(proc, "SIGTERM");
14415
- later(graceMs, () => {
14416
- if (settled) return;
14417
- killProcessTree(proc, "SIGKILL");
14418
- later(abandonMs, () => {
14419
- if (settled) return;
14420
- if (exited !== null) return;
14421
- detach();
14422
- const tail = redactDiagnostic(stderrTail);
14423
- const why = `the run did not end ${Math.round((graceMs + abandonMs) / 1e3)} s after it was signalled (SIGKILL included) \u2014 abandoned so the next wake can run${tail ? `: ${tail}` : ""}`;
14424
- finish(
14425
- timedOut ? { state: "timed_out", exitCode: null, detail: `run exceeded its ${Math.round(spec.budgetMs / 1e3)} s budget; ${why}` } : { state: "failed", exitCode: null, detail: `interrupted \u2014 ${why}` }
14426
- );
14427
- });
14428
- });
14883
+ const stop = (error, byTimeout) => {
14884
+ if (timedOut || finished) return;
14885
+ timedOut = byTimeout;
14886
+ stopped = true;
14887
+ killProcessTree(proc, "SIGKILL");
14888
+ giveUp = setTimeout(() => {
14889
+ proc.stdout?.destroy();
14890
+ proc.stderr?.destroy();
14891
+ finish({ error, status: null, stdout, stderr, timedOut });
14892
+ }, PROBE_KILL_WAIT_MS);
14893
+ proc.once("close", () => finish({ error, status: null, stdout, stderr, timedOut }));
14429
14894
  };
14430
- later(spec.budgetMs, () => {
14431
- if (exited !== null) return;
14432
- timedOut = true;
14433
- terminate();
14434
- });
14435
- if (spec.signal) {
14436
- onAbort = () => {
14437
- if (settled) return;
14438
- interrupted = true;
14439
- terminate();
14440
- };
14441
- spec.signal.addEventListener("abort", onAbort, { once: true });
14442
- }
14443
- proc.on("error", (err) => {
14444
- finish({ state: "not_started", exitCode: null, detail: redactDiagnostic(String(err)) });
14445
- });
14446
- proc.on("exit", (code, signal) => {
14447
- exited = { code, signal, at: Date.now() };
14448
- later(drainMs, () => {
14449
- if (settled || exited === null) return;
14450
- killProcessTree(proc, "SIGKILL");
14451
- if (proc.pid !== void 0) {
14452
- void sweepWindowsDescendants(proc.pid, started, exited.at).then((sweep) => {
14453
- if (sweep !== null) (sweep.exitCode === 0 ? log.info : log.warn)(describeWindowsSweep(sweep));
14454
- });
14455
- }
14456
- detach();
14457
- finish(
14458
- classify(
14459
- exited.code,
14460
- exited.signal,
14461
- process.platform === "win32" ? "a process the run started kept its output open after it exited; its children were swept (taskkill) and the run detached from it \u2014 a process the sweep cannot see can survive" : "a process the run started kept its output open after it exited; the run's process group was signalled (SIGKILL) and the run detached from it \u2014 a process that left the group can survive"
14462
- )
14463
- );
14464
- });
14465
- });
14466
- proc.on("close", (code, signal) => {
14467
- finish(classify(code, signal, null));
14895
+ const timer = setTimeout(() => stop(new Error(`${command} ${args.join(" ")} did not answer within ${Math.round(options.timeoutMs / 1e3)} s`), true), options.timeoutMs);
14896
+ const onAbort = () => stop(new Error(`${command} ${args.join(" ")} was stopped`), false);
14897
+ if (options.signal?.aborted) onAbort();
14898
+ else options.signal?.addEventListener("abort", onAbort, { once: true });
14899
+ proc.on("error", (err) => finish({ error: err, status: null, stdout, stderr, timedOut }));
14900
+ proc.on("close", (code) => {
14901
+ options.signal?.removeEventListener("abort", onAbort);
14902
+ if (!stopped) finish({ status: code, stdout, stderr, timedOut });
14468
14903
  });
14469
14904
  });
14470
14905
  }
14471
14906
 
14472
- // node_modules/.pnpm/@agentchatme+agent-core@0.4.1/node_modules/@agentchatme/agent-core/dist/daemon-entry.js
14907
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/index.js
14908
+ var StateSchema = external_exports.object({
14909
+ // Set when the user has said "not now" to setting up a handle. PERMANENT
14910
+ // until they change their mind, because the prompt that needs suppressing
14911
+ // lives in the always-loaded instruction file and would otherwise be re-read
14912
+ // — and re-acted on — every single session.
14913
+ offer_declined_at: external_exports.string().optional()
14914
+ });
14915
+ var ANCHOR_START = integration_exports.anchor.START_MARKER;
14916
+ var ANCHOR_END = integration_exports.anchor.END_MARKER;
14917
+ var MARKER_LINES = /* @__PURE__ */ new Set([
14918
+ integration_exports.anchor.START_MARKER,
14919
+ integration_exports.anchor.END_MARKER,
14920
+ integration_exports.anchor.LEGACY_START_MARKER,
14921
+ integration_exports.anchor.LEGACY_END_MARKER
14922
+ ]);
14923
+ var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
14924
+ var NO_TEXTS = Object.freeze({ identityLine: null, identityLineTemplate: null, manual: null });
14925
+
14926
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/daemon-entry.js
14473
14927
  import * as path23 from "path";
14474
- import * as fs2 from "fs";
14475
- import * as path6 from "path";
14476
- import * as crypto from "crypto";
14928
+ import * as fs3 from "fs";
14929
+ import * as path8 from "path";
14930
+ import * as crypto3 from "crypto";
14477
14931
  function wsBaseFor(apiBase) {
14478
14932
  return apiBase.replace(/^http/, "ws").replace(/\/+$/, "");
14479
14933
  }
14480
14934
  async function resolveDaemonConfig(opts) {
14481
- const home = path6.resolve(opts.home);
14935
+ const home = path8.resolve(opts.home);
14482
14936
  const id = resolveIdentity(home, { envKey: opts.envKey !== false });
14483
14937
  if (id === null) {
14484
14938
  throw new Error(`no AgentChat identity in ${home} \u2014 register this agent first`);
@@ -14505,7 +14959,7 @@ async function resolveDaemonConfig(opts) {
14505
14959
  apiBase: id.apiBase,
14506
14960
  wsBase: wsBaseFor(id.apiBase),
14507
14961
  home,
14508
- workdir: path6.resolve(opts.workdir)
14962
+ workdir: path8.resolve(opts.workdir)
14509
14963
  };
14510
14964
  }
14511
14965
  function socketStateOf(next, previous) {
@@ -14532,6 +14986,7 @@ var HEARTBEAT_MS = 3e4;
14532
14986
  var STATUS_MS = 3e4;
14533
14987
  var HTTP_TIMEOUT_MS = 1e4;
14534
14988
  var RUNNER_DEADLINE_SLACK_MS = 6e4;
14989
+ var RUNTIME_RECHECK_MS = 5 * 6e4;
14535
14990
  var PREFLIGHT_DEADLINE_MS = 6e4;
14536
14991
  var CYCLE_FAILURE_CHARS = 240;
14537
14992
  function reasonOf(source, frameReason) {
@@ -14659,6 +15114,16 @@ var Integration = class {
14659
15114
  statusTimer = null;
14660
15115
  socket = "idle";
14661
15116
  lastError = null;
15117
+ /** When the first run that did not get done since the last good one ended; null while runs succeed. */
15118
+ failingSince = null;
15119
+ /** Runs that did not get done since then. */
15120
+ failingRuns = 0;
15121
+ /** What the runtime's own check says while runs fail (status `runs_failing`); null when it has not failed one. */
15122
+ runsFailing = null;
15123
+ lastRecheckAt = 0;
15124
+ recheckInFlight = null;
15125
+ /** Aborts a runtime check in flight when the integration stops (its probes are killed, not left running). */
15126
+ recheckAbort = new AbortController();
14662
15127
  stopping = false;
14663
15128
  stopped = null;
14664
15129
  invites = 0;
@@ -14704,7 +15169,8 @@ var Integration = class {
14704
15169
  this.stopping = true;
14705
15170
  if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
14706
15171
  if (this.statusTimer) clearInterval(this.statusTimer);
14707
- this.stopped = this.loop.stop();
15172
+ this.recheckAbort.abort();
15173
+ this.stopped = Promise.all([this.loop.stop(), this.recheckInFlight ?? Promise.resolve()]).then(() => void 0);
14708
15174
  this.texts.stop();
14709
15175
  this.manual?.stop();
14710
15176
  this.socket = "closed";
@@ -14744,6 +15210,11 @@ var Integration = class {
14744
15210
  runtime: this.options.runner.name,
14745
15211
  handle: this.options.cfg.handle,
14746
15212
  profile: this.options.profile,
15213
+ workdir: this.options.cfg.workdir,
15214
+ standby: null,
15215
+ runs_failing: this.runsFailing,
15216
+ unservable: null,
15217
+ ...this.options.statusExtra?.() ?? {},
14747
15218
  socket: this.stopping ? "closed" : this.socket,
14748
15219
  wakes: status.coalescer.wakes,
14749
15220
  wakes_absorbed: status.coalescer.absorbed,
@@ -14781,7 +15252,7 @@ var Integration = class {
14781
15252
  const kind = request.cards === 0 && (request.invites ?? 0) > 0 ? "invite" : "wake";
14782
15253
  const wake = this.pendingWake ?? { reason: kind === "invite" ? "invite" : "messages" };
14783
15254
  this.pendingWake = null;
14784
- const runId = crypto.randomUUID();
15255
+ const runId = crypto3.randomUUID();
14785
15256
  const startedAt = Date.now();
14786
15257
  const budgetMs = this.options.budgetMs;
14787
15258
  const slackMs = this.options.runnerDeadlineSlackMs ?? RUNNER_DEADLINE_SLACK_MS;
@@ -14792,16 +15263,19 @@ var Integration = class {
14792
15263
  const onAbort = () => controller.abort();
14793
15264
  if (request.signal.aborted) controller.abort();
14794
15265
  else request.signal.addEventListener("abort", onAbort, { once: true });
15266
+ const identityLine = this.texts.current()?.identity_line;
14795
15267
  let outcome;
14796
15268
  try {
14797
15269
  outcome = await withDeadline(
14798
15270
  this.options.runner.start({
14799
15271
  kind,
14800
15272
  wake,
14801
- prompt: `${request.prompt}
15273
+ // No pointer, no trailing blank lines.
15274
+ prompt: this.options.manualPointer.trim().length > 0 ? `${request.prompt}
14802
15275
 
14803
- ${this.options.manualPointer}`,
15276
+ ${this.options.manualPointer}` : request.prompt,
14804
15277
  runId,
15278
+ ...identityLine !== void 0 && identityLine.trim().length > 0 ? { identityLine } : {},
14805
15279
  budgetMs,
14806
15280
  signal: controller.signal
14807
15281
  }),
@@ -14848,9 +15322,71 @@ ${this.options.manualPointer}`,
14848
15322
  if (outcome.state !== "ok") {
14849
15323
  log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ""} \u2014 the cards stay on the tray; the next wake (or the server's re-wake) finds them`);
14850
15324
  }
15325
+ this.noteRunHealth(outcome, this.lastRun.ended_at);
14851
15326
  this.writeStatus();
14852
15327
  return outcome.state === "ok" ? { status: "completed" } : { status: outcome.state === "not_started" ? "not_started" : "failed", ...outcome.detail !== void 0 ? { detail: outcome.detail } : {} };
14853
15328
  }
15329
+ /**
15330
+ * A run that did not get done may be the runtime itself (signed out, the
15331
+ * binary gone, a flag an upgrade dropped): checked again, at most once per
15332
+ * `RUNTIME_RECHECK_MS`, and said in status until a run succeeds. Wakes keep
15333
+ * starting runs meanwhile — each is the quickest way back — and are counted.
15334
+ */
15335
+ noteRunHealth(outcome, endedAt) {
15336
+ if (outcome.state === "ok") {
15337
+ if (this.runsFailing !== null) log.info(`runs work again (${this.failingRuns} run(s) missed since ${this.failingSince})`);
15338
+ this.failingSince = null;
15339
+ this.failingRuns = 0;
15340
+ this.runsFailing = null;
15341
+ this.lastRecheckAt = 0;
15342
+ return;
15343
+ }
15344
+ this.failingSince ??= endedAt;
15345
+ this.failingRuns += 1;
15346
+ if (this.runsFailing !== null) this.runsFailing = { ...this.runsFailing, runs_missed: this.failingRuns };
15347
+ const recheckMs = this.options.runtimeRecheckMs ?? RUNTIME_RECHECK_MS;
15348
+ if (this.recheckInFlight === null && !this.stopping && (this.lastRecheckAt === 0 || Date.now() - this.lastRecheckAt >= recheckMs)) {
15349
+ this.recheckInFlight = this.recheckRuntime().finally(() => {
15350
+ this.recheckInFlight = null;
15351
+ });
15352
+ }
15353
+ }
15354
+ async recheckRuntime() {
15355
+ this.lastRecheckAt = Date.now();
15356
+ const pre = await withDeadline(this.options.runner.preflight({ signal: this.recheckAbort.signal }), PREFLIGHT_DEADLINE_MS, () => ({
15357
+ ok: false,
15358
+ detail: `preflight did not answer within ${Math.round(PREFLIGHT_DEADLINE_MS / 1e3)} s`
15359
+ })).catch((err) => ({ ok: false, detail: `preflight threw: ${err instanceof Error ? err.message : String(err)}` }));
15360
+ if (this.failingSince === null || this.stopping) return;
15361
+ const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
15362
+ if (!pre.ok) {
15363
+ const reason = `${this.options.runner.name}: ${pre.detail ?? "its check failed"}`;
15364
+ if (this.runsFailing?.reason !== reason) log.warn(`runs failing \u2014 ${reason} (since ${this.failingSince}, ${this.failingRuns} run(s) missed); status says so until a run succeeds`);
15365
+ this.runsFailing = { reason, since: this.failingSince, runs_missed: this.failingRuns, checked_at: checkedAt };
15366
+ } else if (this.runsFailing !== null) {
15367
+ this.runsFailing = {
15368
+ ...this.runsFailing,
15369
+ reason: `${this.options.runner.name} checks out now, but runs still fail${this.lastRun?.detail ? ` (last: ${this.lastRun.detail})` : ""}`,
15370
+ checked_at: checkedAt
15371
+ };
15372
+ }
15373
+ this.writeStatus();
15374
+ }
15375
+ /**
15376
+ * Whether this integration can serve its agent: not while the server refuses
15377
+ * its key (socket `blocked`: rotated by `recover` elsewhere, revoked), nor
15378
+ * while runs fail for a runtime reason (`runs_failing`). The supervisor then
15379
+ * gives the agent up so a healthy listener for it can serve.
15380
+ */
15381
+ health() {
15382
+ if (this.socket === "blocked") return { ok: false, reason: `the server refuses this home's key${this.lastError ? ` (${this.lastError})` : ""}`, runsFailing: null };
15383
+ if (this.runsFailing !== null) return { ok: false, reason: `runs failing: ${this.runsFailing.reason}`, runsFailing: this.runsFailing };
15384
+ return { ok: true };
15385
+ }
15386
+ /** Test seam: resolves when a runtime check started by a failed run has finished. */
15387
+ async runtimeCheckDone() {
15388
+ await this.recheckInFlight;
15389
+ }
14854
15390
  onEvent(event) {
14855
15391
  switch (event.type) {
14856
15392
  case "wake": {
@@ -14893,10 +15429,24 @@ ${this.options.manualPointer}`,
14893
15429
  var POLL_MS = 5e3;
14894
15430
  var TICK_MS = 250;
14895
15431
  var MAX_BACKOFF_MS = 5 * 6e4;
15432
+ var STANDBY_POLL_MS = 3e4;
15433
+ var UNSERVABLE_RECHECK_MS = 6e4;
15434
+ var BLOCKED_RETRY_MS = 5 * 6e4;
14896
15435
  var SHUTDOWN_GRACE_MS = 1e4;
14897
15436
  var MAX_LOG_BYTES = 5 * 1024 * 1024;
14898
15437
  var KEEP_LOG_BYTES = 1024 * 1024;
14899
- var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
15438
+ function sleepUnless(ms, signal) {
15439
+ if (signal?.aborted === true) return Promise.resolve();
15440
+ return new Promise((resolve32) => {
15441
+ const done = () => {
15442
+ clearTimeout(timer);
15443
+ signal?.removeEventListener("abort", done);
15444
+ resolve32();
15445
+ };
15446
+ const timer = setTimeout(done, ms);
15447
+ signal?.addEventListener("abort", done, { once: true });
15448
+ });
15449
+ }
14900
15450
  function fingerprint(home, envKey) {
14901
15451
  const id = resolveIdentity(home, { envKey });
14902
15452
  return id === null ? null : `${id.apiKey}:${id.handle ?? ""}`;
@@ -14904,23 +15454,25 @@ function fingerprint(home, envKey) {
14904
15454
  function boundDaemonLog(home) {
14905
15455
  const file = path23.join(home, "daemon.log");
14906
15456
  try {
14907
- const size = fs2.statSync(file).size;
15457
+ const size = fs3.statSync(file).size;
14908
15458
  if (size <= MAX_LOG_BYTES) return;
14909
- const fd = fs2.openSync(file, "r");
15459
+ const fd = fs3.openSync(file, "r");
14910
15460
  try {
14911
15461
  const keep = Buffer.alloc(Math.min(KEEP_LOG_BYTES, size));
14912
- fs2.readSync(fd, keep, 0, keep.length, size - keep.length);
14913
- fs2.writeFileSync(
15462
+ fs3.readSync(fd, keep, 0, keep.length, size - keep.length);
15463
+ fs3.writeFileSync(
14914
15464
  file,
14915
15465
  `[agentchat:info] older daemon log output truncated at ${(/* @__PURE__ */ new Date()).toISOString()}
14916
15466
  ${keep.toString("utf-8")}`
14917
15467
  );
14918
15468
  } finally {
14919
- fs2.closeSync(fd);
15469
+ fs3.closeSync(fd);
14920
15470
  }
14921
15471
  } catch {
14922
15472
  }
14923
15473
  }
15474
+ var StandbyError = class extends Error {
15475
+ };
14924
15476
  async function runIntegration(opts) {
14925
15477
  const home = path23.resolve(opts.home);
14926
15478
  const workdir = path23.resolve(opts.workdir);
@@ -14929,10 +15481,23 @@ async function runIntegration(opts) {
14929
15481
  const budgetMs = opts.budgetMs ?? resolveRunBudgetMs(env);
14930
15482
  boundDaemonLog(home);
14931
15483
  if (process.env["AGENTCHAT_LOG_LEVEL"] === void 0) process.env["AGENTCHAT_LOG_LEVEL"] = "info";
14932
- const lock = acquireLeaderLock(home);
15484
+ let nudged = false;
15485
+ const stopChecks = new AbortController();
15486
+ if (opts.signal?.aborted === true) stopChecks.abort();
15487
+ else opts.signal?.addEventListener("abort", () => stopChecks.abort(), { once: true });
15488
+ const lock = await acquireLeaderLock(home, { ...opts.lease ?? {}, signal: stopChecks.signal });
14933
15489
  if (lock === null) return 1;
15490
+ let homeLost = null;
15491
+ let starting = null;
15492
+ lock.onLost((why) => {
15493
+ homeLost = why;
15494
+ nudged = true;
15495
+ starting?.stop();
15496
+ live?.stop();
15497
+ log.error(`lost this home's daemon lock (${why}) \u2014 another daemon serves ${home} now; this one exits`);
15498
+ });
14934
15499
  const envKey = opts.credentialsFromHomeOnly !== true;
14935
- const identityOf = () => resolveIdentity(home, { envKey });
15500
+ const identityOf2 = () => resolveIdentity(home, { envKey });
14936
15501
  const disabledBy = integrationDisabledBy(env);
14937
15502
  const disabled = disabledBy !== null;
14938
15503
  let live = null;
@@ -14941,6 +15506,37 @@ async function runIntegration(opts) {
14941
15506
  let failures = 0;
14942
15507
  let lastFailure = null;
14943
15508
  let shuttingDown = false;
15509
+ let agentLock = null;
15510
+ let agentLost = null;
15511
+ let standby = null;
15512
+ let unservable = null;
15513
+ let lastRunner = null;
15514
+ let cachedCfg = null;
15515
+ let agentLockFile = null;
15516
+ let prepared = null;
15517
+ let standbyCheck = null;
15518
+ const runnerFor = (cfg, fp) => {
15519
+ if (prepared === null || prepared.fp !== fp) prepared = { fp, runner: isRunnerFactory(opts.runner) ? opts.runner.create(cfg) : opts.runner };
15520
+ return prepared.runner;
15521
+ };
15522
+ const preflightOf = async (runner) => {
15523
+ const deadlineMs = opts.preflightDeadlineMs ?? PREFLIGHT_DEADLINE_MS;
15524
+ return withDeadline(runner.preflight({ signal: stopChecks.signal }), deadlineMs, () => ({ ok: false, detail: `preflight did not answer within ${Math.round(deadlineMs / 1e3)} s` })).catch(
15525
+ (err) => ({ ok: false, detail: `preflight threw: ${err instanceof Error ? err.message : String(err)}` })
15526
+ );
15527
+ };
15528
+ const releaseAgent = () => {
15529
+ agentLock?.release();
15530
+ agentLock = null;
15531
+ agentLost = null;
15532
+ };
15533
+ const stopWaiting = () => {
15534
+ if (agentLockFile !== null) clearStandby(agentLockFile, home);
15535
+ };
15536
+ const leaseErrors = () => {
15537
+ const count = lock.renewErrors + (agentLock?.renewErrors ?? 0);
15538
+ return count === 0 ? null : { count, last: agentLock?.lastRenewError ?? lock.lastRenewError };
15539
+ };
14944
15540
  const offStatus = (handle) => writeIntegrationStatus(home, {
14945
15541
  version: 2,
14946
15542
  updated_at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -14948,6 +15544,7 @@ async function runIntegration(opts) {
14948
15544
  runtime: opts.runner.name,
14949
15545
  handle,
14950
15546
  profile,
15547
+ workdir,
14951
15548
  socket: disabled ? "off" : "idle",
14952
15549
  wakes: 0,
14953
15550
  wakes_absorbed: 0,
@@ -14962,7 +15559,11 @@ async function runIntegration(opts) {
14962
15559
  retry_rung: 0,
14963
15560
  retry_due_at: null,
14964
15561
  last_error: lastFailure,
14965
- texts: null
15562
+ texts: null,
15563
+ standby,
15564
+ runs_failing: unservable?.runsFailing ?? null,
15565
+ unservable: unservable === null ? null : { reason: unservable.kind, detail: unservable.detail, since: unservable.since, retry_at: new Date(unservable.retryAt).toISOString() },
15566
+ lease_errors: leaseErrors()
14966
15567
  });
14967
15568
  const disconnect = (why) => {
14968
15569
  if (live === null) return;
@@ -14970,21 +15571,22 @@ async function runIntegration(opts) {
14970
15571
  live.stop();
14971
15572
  live = null;
14972
15573
  liveFingerprint = null;
15574
+ releaseAgent();
14973
15575
  idle(home);
14974
15576
  };
14975
15577
  const shutdown = (sig) => {
14976
15578
  if (shuttingDown) return;
14977
15579
  shuttingDown = true;
15580
+ stopChecks.abort();
14978
15581
  log.info(`${sig} \u2014 shutting down`);
14979
15582
  };
14980
15583
  const onSigint = () => shutdown("SIGINT");
14981
15584
  const onSigterm = () => shutdown("SIGTERM");
14982
15585
  process.on("SIGINT", onSigint);
14983
15586
  process.on("SIGTERM", onSigterm);
14984
- let nudged = false;
14985
15587
  try {
14986
- fs2.mkdirSync(home, { recursive: true });
14987
- const watcher = fs2.watch(home, (_event, filename) => {
15588
+ fs3.mkdirSync(home, { recursive: true });
15589
+ const watcher = fs3.watch(home, (_event, filename) => {
14988
15590
  if (filename === null || String(filename).startsWith("credentials")) nudged = true;
14989
15591
  });
14990
15592
  watcher.on("error", (err) => {
@@ -15010,19 +15612,98 @@ async function runIntegration(opts) {
15010
15612
  if (shuttingDown || opts.signal?.aborted) break;
15011
15613
  const fp = fingerprint(home, envKey);
15012
15614
  const identityChanged = fp !== observedFingerprint;
15615
+ if (homeLost !== null) break;
15013
15616
  if (identityChanged) {
15014
15617
  disconnect(fp === null ? "signed out" : "identity changed");
15015
15618
  observedFingerprint = fp;
15016
15619
  failures = 0;
15017
15620
  lastFailure = null;
15018
- if (fp === null || disabled) offStatus(fp === null ? null : identityOf()?.handle ?? null);
15621
+ stopWaiting();
15622
+ standby = null;
15623
+ unservable = null;
15624
+ cachedCfg = null;
15625
+ agentLockFile = null;
15626
+ if (fp === null || disabled) offStatus(fp === null ? null : identityOf2()?.handle ?? null);
15019
15627
  }
15020
15628
  if (fp === null) {
15021
15629
  } else if (disabled) {
15022
- } else if (fp !== liveFingerprint) {
15630
+ } else if (live !== null && fp === liveFingerprint) {
15631
+ const health = live.health();
15632
+ if (agentLost !== null) {
15633
+ const why = agentLost;
15634
+ disconnect(`the agent lock is no longer this home's (${why})`);
15635
+ lastFailure = `@${cachedCfg?.cfg.handle ?? "?"}: ${why}; another listener serves this agent now`;
15636
+ } else if (!health.ok) {
15637
+ const handle = cachedCfg?.cfg.handle ?? "?";
15638
+ const kind = health.runsFailing === null ? "key_refused" : "runs_failing";
15639
+ if (kind === "key_refused" || agentLockFile !== null && standbyWaiting(agentLockFile, home)) {
15640
+ const retryMs = opts.unservableRecheckMs ?? (kind === "key_refused" ? BLOCKED_RETRY_MS : UNSERVABLE_RECHECK_MS);
15641
+ unservable = { kind, detail: health.reason, since: (/* @__PURE__ */ new Date()).toISOString(), retryAt: Date.now() + retryMs, runsFailing: health.runsFailing };
15642
+ disconnect(`this home cannot serve @${handle} (${health.reason}): giving it up to ${kind === "key_refused" ? "any healthy listener" : "the healthy listener waiting for it"}`);
15643
+ lastFailure = `this home cannot serve @${handle}: ${health.reason}. It holds no socket and starts no run while another listener can serve @${handle}; it looks again every ${Math.round(retryMs / 1e3)} s${kind === "runs_failing" ? " (the runtime checked first: a check that passes clears this)" : " (signing in again here clears this at once)"}, and takes @${handle} back whenever no other listener holds it.`;
15644
+ log.warn(lastFailure);
15645
+ offStatus(handle);
15646
+ }
15647
+ }
15648
+ } else if (live === null) {
15023
15649
  try {
15024
- const cfg = await resolveDaemonConfig({ home, workdir, client: opts.client, envKey });
15025
- const runner = isRunnerFactory(opts.runner) ? opts.runner.create(cfg) : opts.runner;
15650
+ if (unservable !== null && Date.now() < unservable.retryAt) throw new StandbyError(unservable.detail);
15651
+ const waiting = unservable;
15652
+ if (waiting !== null && waiting.kind === "runs_failing" && lastRunner !== null) {
15653
+ const before = waiting;
15654
+ const checker = lastRunner;
15655
+ const pre = await preflightOf(checker);
15656
+ standbyCheck = { fp, ok: pre.ok, detail: pre.ok ? null : `${checker.name}: ${pre.detail ?? "its check failed"}`, at: Date.now() };
15657
+ if (shuttingDown || opts.signal?.aborted) throw new StandbyError("stopping");
15658
+ if (pre.ok) unservable = null;
15659
+ else unservable = { ...before, detail: `runs failing: ${checker.name}: ${pre.detail ?? "its check failed"}`, retryAt: Date.now() + (opts.unservableRecheckMs ?? UNSERVABLE_RECHECK_MS) };
15660
+ }
15661
+ if (cachedCfg === null || cachedCfg.fp !== fp) cachedCfg = { fp, cfg: await resolveDaemonConfig({ home, workdir, client: opts.client, envKey }) };
15662
+ const cfg = cachedCfg.cfg;
15663
+ agentLockFile = agentLockPath({ apiBase: cfg.apiBase, handle: cfg.handle });
15664
+ const attempt = await acquireAgentLock({ apiBase: cfg.apiBase, handle: cfg.handle, home }, process.env, { ...opts.lease ?? {}, signal: stopChecks.signal });
15665
+ if (shuttingDown || opts.signal?.aborted) {
15666
+ if (attempt.ok) attempt.lease.release();
15667
+ throw new StandbyError("stopping");
15668
+ }
15669
+ if (!attempt.ok) {
15670
+ const current = unservable;
15671
+ if (current !== null) {
15672
+ unservable = { ...current, retryAt: Date.now() + (opts.unservableRecheckMs ?? (current.kind === "key_refused" ? BLOCKED_RETRY_MS : UNSERVABLE_RECHECK_MS)) };
15673
+ throw new StandbyError(current.detail);
15674
+ }
15675
+ standby = { home: attempt.holder?.home ?? null, pid: attempt.holder?.pid ?? null, since: attempt.holder?.acquired_at ?? null };
15676
+ const recheckMs = opts.runtimeRecheckMs ?? RUNTIME_RECHECK_MS;
15677
+ if (standbyCheck === null || standbyCheck.fp !== fp || Date.now() - standbyCheck.at >= recheckMs) {
15678
+ const runner2 = runnerFor(cfg, fp);
15679
+ const pre = await preflightOf(runner2);
15680
+ if (shuttingDown || opts.signal?.aborted) throw new StandbyError("stopping");
15681
+ standbyCheck = { fp, ok: pre.ok, detail: pre.ok ? null : `${runner2.name}: ${pre.detail ?? "its check failed"}`, at: Date.now() };
15682
+ }
15683
+ if (standbyCheck.ok) markStandby(attempt.path, home);
15684
+ else clearStandby(attempt.path, home);
15685
+ const refusal2 = agentLockRefusal({ handle: cfg.handle, home }, attempt.holder, attempt.path);
15686
+ const msg = standbyCheck.ok ? refusal2 : `${refusal2} Its own runtime does not check out (${standbyCheck.detail ?? "its check failed"}), so it does not offer to take over from a holder whose runs fail.`;
15687
+ if (msg !== lastFailure) log.warn(msg);
15688
+ lastFailure = msg;
15689
+ throw new StandbyError(msg);
15690
+ }
15691
+ stopWaiting();
15692
+ if (standby !== null) log.info(`@${cfg.handle}: the other listener stopped; this one serves the agent now`);
15693
+ if (unservable !== null) log.info(`@${cfg.handle}: no other listener holds the agent; this home serves it again (${unservable.detail})`);
15694
+ standby = null;
15695
+ unservable = null;
15696
+ const lease = attempt.lease;
15697
+ agentLock = lease;
15698
+ lease.onLost((why) => {
15699
+ if (agentLock !== lease) return;
15700
+ agentLost = why;
15701
+ nudged = true;
15702
+ starting?.stop();
15703
+ live?.stop();
15704
+ });
15705
+ const runner = runnerFor(cfg, fp);
15706
+ lastRunner = runner;
15026
15707
  const candidate = new Integration({
15027
15708
  cfg,
15028
15709
  runner,
@@ -15031,31 +15712,51 @@ async function runIntegration(opts) {
15031
15712
  ...opts.manualPath !== void 0 ? { manualPath: opts.manualPath } : {},
15032
15713
  profile,
15033
15714
  budgetMs,
15034
- ...opts.dismissIgnoredInvites !== void 0 ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {}
15715
+ ...opts.dismissIgnoredInvites !== void 0 ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {},
15716
+ ...opts.runtimeRecheckMs !== void 0 ? { runtimeRecheckMs: opts.runtimeRecheckMs } : {},
15717
+ ...opts.quietMs !== void 0 ? { quietMs: opts.quietMs } : {},
15718
+ ...opts.maxMs !== void 0 ? { maxMs: opts.maxMs } : {},
15719
+ ...opts.paceMs !== void 0 ? { paceMs: opts.paceMs } : {},
15720
+ statusExtra: () => ({ lease_errors: leaseErrors() })
15035
15721
  });
15036
- await candidate.start();
15722
+ starting = candidate;
15723
+ try {
15724
+ await candidate.start();
15725
+ } finally {
15726
+ starting = null;
15727
+ }
15728
+ if (agentLost !== null || homeLost !== null) {
15729
+ candidate.stop();
15730
+ throw new StandbyError(`the agent lock is no longer this home's (${agentLost ?? homeLost})`);
15731
+ }
15037
15732
  live = candidate;
15038
15733
  liveFingerprint = fp;
15039
15734
  failures = 0;
15040
15735
  lastFailure = null;
15041
15736
  } catch (err) {
15042
- const msg = String(err instanceof Error ? err.message : err);
15043
- if (msg !== lastFailure) {
15044
- log.warn(`not connecting yet: ${msg}`);
15045
- lastFailure = msg;
15046
- offStatus(identityOf()?.handle ?? null);
15047
- }
15048
- failures += 1;
15737
+ releaseAgent();
15049
15738
  live = null;
15050
15739
  liveFingerprint = null;
15740
+ if (err instanceof StandbyError) {
15741
+ offStatus(cachedCfg?.cfg.handle ?? identityOf2()?.handle ?? null);
15742
+ } else {
15743
+ const msg = String(err instanceof Error ? err.message : err);
15744
+ if (msg !== lastFailure) {
15745
+ log.warn(`not connecting yet: ${msg}`);
15746
+ lastFailure = msg;
15747
+ offStatus(identityOf2()?.handle ?? null);
15748
+ }
15749
+ failures += 1;
15750
+ }
15051
15751
  idle(home);
15052
15752
  }
15053
15753
  }
15054
- const waitMs = failures === 0 ? POLL_MS : Math.min(POLL_MS * 2 ** Math.min(failures, 6), MAX_BACKOFF_MS);
15754
+ const pollMs = opts.pollMs ?? POLL_MS;
15755
+ const waitMs = homeLost !== null || agentLost !== null ? 0 : standby !== null || unservable !== null ? opts.standbyPollMs ?? STANDBY_POLL_MS : failures === 0 ? pollMs : Math.min(pollMs * 2 ** Math.min(failures, 6), MAX_BACKOFF_MS);
15055
15756
  nudged = false;
15056
15757
  const deadline = Date.now() + waitMs;
15057
15758
  while (!nudged && !shuttingDown && !opts.signal?.aborted && Date.now() < deadline) {
15058
- await sleep2(TICK_MS);
15759
+ await sleepUnless(opts.tickMs ?? TICK_MS, opts.signal);
15059
15760
  }
15060
15761
  }
15061
15762
  process.off("SIGINT", onSigint);
@@ -15065,8 +15766,11 @@ async function runIntegration(opts) {
15065
15766
  if (!ended) log.warn(`a run in flight did not end within ${Math.round(SHUTDOWN_GRACE_MS / 1e3)}s of being interrupted \u2014 exiting anyway`);
15066
15767
  live = null;
15067
15768
  }
15769
+ releaseAgent();
15770
+ stopWaiting();
15068
15771
  idle(home);
15069
15772
  lock.release();
15773
+ if (homeLost !== null) return 1;
15070
15774
  if (shuttingDown) {
15071
15775
  log.info("shutdown complete");
15072
15776
  (opts.exit ?? process.exit)(0);
@@ -15075,29 +15779,168 @@ async function runIntegration(opts) {
15075
15779
  }
15076
15780
 
15077
15781
  // src/host.ts
15078
- import * as os3 from "os";
15079
- import * as path8 from "path";
15782
+ import * as os4 from "os";
15783
+ import * as path10 from "path";
15080
15784
 
15081
- // node_modules/.pnpm/@agentchatme+agent-core@0.4.1/node_modules/@agentchatme/agent-core/dist/presets.js
15082
- import * as fs3 from "fs";
15083
- import * as os from "os";
15084
- import * as path7 from "path";
15785
+ // node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/presets.js
15786
+ import * as fs7 from "fs";
15787
+ import * as os3 from "os";
15788
+ import * as path9 from "path";
15085
15789
  import * as fs22 from "fs";
15086
- import * as os2 from "os";
15790
+ import * as os23 from "os";
15087
15791
  import * as path24 from "path";
15088
15792
  function semverAtLeast(actual, minimum) {
15089
- const parse = (value) => {
15793
+ const parse2 = (value) => {
15090
15794
  const match = value.match(/(\d+)\.(\d+)\.(\d+)/);
15091
15795
  return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
15092
15796
  };
15093
- const a = parse(actual);
15094
- const b = parse(minimum);
15797
+ const a = parse2(actual);
15798
+ const b = parse2(minimum);
15095
15799
  if (a === null || b === null) return false;
15096
15800
  for (let index = 0; index < 3; index++) {
15097
15801
  if (a[index] !== b[index]) return (a[index] ?? 0) > (b[index] ?? 0);
15098
15802
  }
15099
15803
  return true;
15100
15804
  }
15805
+ var CLAUDE_CODE_ENV_KEPT = [
15806
+ // Sign-in and provider
15807
+ "CLAUDE_CODE_OAUTH_TOKEN",
15808
+ "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
15809
+ "CLAUDE_CODE_OAUTH_SCOPES",
15810
+ "CLAUDE_CODE_API_KEY_HELPER_TTL_MS",
15811
+ "CLAUDE_CODE_USE_BEDROCK",
15812
+ "CLAUDE_CODE_USE_VERTEX",
15813
+ "CLAUDE_CODE_USE_FOUNDRY",
15814
+ "CLAUDE_CODE_USE_MANTLE",
15815
+ "CLAUDE_CODE_USE_ANTHROPIC_AWS",
15816
+ "CLAUDE_CODE_SKIP_BEDROCK_AUTH",
15817
+ "CLAUDE_CODE_SKIP_VERTEX_AUTH",
15818
+ "CLAUDE_CODE_SKIP_FOUNDRY_AUTH",
15819
+ "CLAUDE_CODE_SKIP_MANTLE_AUTH",
15820
+ "CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH",
15821
+ "CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS",
15822
+ // Network and TLS
15823
+ "CLAUDE_CODE_CLIENT_CERT",
15824
+ "CLAUDE_CODE_CLIENT_KEY",
15825
+ "CLAUDE_CODE_CLIENT_KEY_PASSPHRASE",
15826
+ "CLAUDE_CODE_CERT_STORE",
15827
+ "CLAUDE_CODE_PROXY_RESOLVES_HOSTS",
15828
+ "CLAUDE_CODE_CONNECT_TIMEOUT_MS",
15829
+ // Privacy and secrets switches the user turned on
15830
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
15831
+ "CLAUDE_CODE_ENABLE_TELEMETRY",
15832
+ "CLAUDE_CODE_SUBPROCESS_ENV_SCRUB",
15833
+ "CLAUDE_CODE_MCP_ALLOWLIST_ENV",
15834
+ "CLAUDE_CODE_DISABLE_CLAUDE_MDS",
15835
+ "CLAUDE_CODE_DISABLE_AUTO_MEMORY",
15836
+ // Model request settings the user chose
15837
+ "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS",
15838
+ "CLAUDE_CODE_EXTRA_BODY",
15839
+ "CLAUDE_CODE_MAX_OUTPUT_TOKENS",
15840
+ // Platform
15841
+ "CLAUDE_CODE_GIT_BASH_PATH",
15842
+ "CLAUDE_CODE_TMPDIR",
15843
+ // Set by the preset itself (a larger value of the user's is kept)
15844
+ "CLAUDE_CODE_MCP_STARTUP_WAIT_MS"
15845
+ ];
15846
+ var CLAUDE_SESSION_ENV = ["CLAUDECODE", "CLAUDE_PID", "CLAUDE_EFFORT", "CLAUDE_JOB_DIR", "CLAUDE_PROJECT_DIR", "TRACEPARENT", "TRACESTATE", "AI_AGENT"];
15847
+ var CODEX_SESSION_ENV = [
15848
+ "CODEX_SANDBOX",
15849
+ "CODEX_SANDBOX_NETWORK_DISABLED",
15850
+ "CODEX_SESSION_ID",
15851
+ "CODEX_THREAD_ID",
15852
+ "CODEX_VERSION",
15853
+ "CODEX_PERMISSION_PROFILE",
15854
+ "CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN",
15855
+ "CODEX_ESCALATE_SOCKET",
15856
+ "CODEX_NETWORK_PROXY_ACTIVE",
15857
+ "CODEX_NETWORK_ALLOW_LOCAL_BINDING",
15858
+ "CODEX_NETWORK_PROXY_ATTRIBUTION",
15859
+ "CODEX_NETWORK_PROXY_CREDENTIAL_BROKER_ACTIVE",
15860
+ "CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS",
15861
+ "CODEX_WINDOWS_SANDBOX_PROXY_PORTS"
15862
+ ];
15863
+ var CODEX_MANAGED_PROXY_ENV = [
15864
+ "ELECTRON_GET_USE_PROXY",
15865
+ "NODE_USE_ENV_PROXY",
15866
+ "HTTP_PROXY",
15867
+ "HTTPS_PROXY",
15868
+ "YARN_HTTP_PROXY",
15869
+ "YARN_HTTPS_PROXY",
15870
+ "NPM_CONFIG_HTTP_PROXY",
15871
+ "NPM_CONFIG_HTTPS_PROXY",
15872
+ "NPM_CONFIG_PROXY",
15873
+ "BUNDLE_HTTP_PROXY",
15874
+ "BUNDLE_HTTPS_PROXY",
15875
+ "PIP_PROXY",
15876
+ "DOCKER_HTTP_PROXY",
15877
+ "DOCKER_HTTPS_PROXY",
15878
+ "WS_PROXY",
15879
+ "WSS_PROXY",
15880
+ "NO_PROXY",
15881
+ "NPM_CONFIG_NOPROXY",
15882
+ "YARN_NO_PROXY",
15883
+ "BUNDLE_NO_PROXY",
15884
+ "ALL_PROXY",
15885
+ "FTP_PROXY"
15886
+ ];
15887
+ var CODEX_CA_ENV_KEYS = [
15888
+ "CODEX_CA_CERTIFICATE",
15889
+ "SSL_CERT_FILE",
15890
+ "REQUESTS_CA_BUNDLE",
15891
+ "CURL_CA_BUNDLE",
15892
+ "NODE_EXTRA_CA_CERTS",
15893
+ "GIT_SSL_CAINFO",
15894
+ "CARGO_HTTP_CAINFO",
15895
+ "PIP_CERT",
15896
+ "BUNDLE_SSL_CA_CERT",
15897
+ "NPM_CONFIG_CAFILE"
15898
+ ];
15899
+ function isManagedCaBundle(value) {
15900
+ return /[\\/]proxy[\\/]ca-bundle-[0-9a-fA-F]{64}\.pem$/.test(value);
15901
+ }
15902
+ var CODEX_PROXY_GIT_SSH_MARKER = "CODEX_PROXY_GIT_SSH_COMMAND=1 ";
15903
+ function isParentSessionEnv(key) {
15904
+ const upper = key.toUpperCase();
15905
+ if (upper.startsWith("CLAUDE_CODE_")) return !CLAUDE_CODE_ENV_KEPT.includes(upper);
15906
+ return CLAUDE_SESSION_ENV.includes(upper) || CODEX_SESSION_ENV.includes(upper);
15907
+ }
15908
+ function envValue(env, name) {
15909
+ for (const [key, value] of Object.entries(env)) if (key.toUpperCase() === name) return value;
15910
+ return void 0;
15911
+ }
15912
+ function brokeredDummies(env) {
15913
+ const marker = envValue(env, "CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS");
15914
+ const out = /* @__PURE__ */ new Set();
15915
+ if (marker === void 0) return out;
15916
+ let pairs;
15917
+ try {
15918
+ pairs = JSON.parse(marker);
15919
+ } catch {
15920
+ return out;
15921
+ }
15922
+ if (!Array.isArray(pairs)) return out;
15923
+ for (const pair of pairs) {
15924
+ if (!Array.isArray(pair) || typeof pair[0] !== "string" || typeof pair[1] !== "string") continue;
15925
+ if (envValue(env, pair[0].toUpperCase()) === pair[1]) out.add(pair[0].toUpperCase());
15926
+ }
15927
+ return out;
15928
+ }
15929
+ function withoutParentSession(env) {
15930
+ const proxyActive = envValue(env, "CODEX_NETWORK_PROXY_ACTIVE") !== void 0;
15931
+ const dummies = brokeredDummies(env);
15932
+ const copy = {};
15933
+ for (const [key, value] of Object.entries(env)) {
15934
+ const upper = key.toUpperCase();
15935
+ if (isParentSessionEnv(key)) continue;
15936
+ if (proxyActive && CODEX_MANAGED_PROXY_ENV.includes(upper)) continue;
15937
+ if (proxyActive && value !== void 0 && CODEX_CA_ENV_KEYS.includes(upper) && isManagedCaBundle(value)) continue;
15938
+ if (value !== void 0 && upper === "GIT_SSH_COMMAND" && value.startsWith(CODEX_PROXY_GIT_SSH_MARKER)) continue;
15939
+ if (dummies.has(upper)) continue;
15940
+ copy[key] = value;
15941
+ }
15942
+ return copy;
15943
+ }
15101
15944
  function withoutInheritedKey(env) {
15102
15945
  const copy = { ...env };
15103
15946
  delete copy["AGENTCHAT_API_KEY"];
@@ -15107,28 +15950,28 @@ var CLAUDE_CODE_PRESET = "claude-code";
15107
15950
  var MIN_CLAUDE_CODE_VERSION = "2.1.274";
15108
15951
  var CLAUDE_MCP_SERVER_NAME = "agentchat";
15109
15952
  var AGENTCHAT_TOOL_ALLOW = `mcp__${CLAUDE_MCP_SERVER_NAME}__*`;
15110
- var ANSWER_TOOLS = ["Read", "Glob", "Grep", "WebSearch", "WebFetch"];
15953
+ var ANSWER_TOOLS = ["Read", "Glob", "Grep"];
15954
+ var WEB_TOOLS = ["WebSearch", "WebFetch"];
15111
15955
  var WORK_TOOLS = ["Bash", "Edit", "Write", "MultiEdit", "NotebookEdit"];
15112
- var PARENT_ENV_KEYS = [
15113
- "CLAUDECODE",
15114
- "CLAUDE_CODE_CHILD_SESSION",
15115
- "CLAUDE_CODE_SESSION_ID",
15116
- "CLAUDE_CODE_ENTRYPOINT",
15117
- "CLAUDE_CODE_EXECPATH",
15118
- "CLAUDE_CODE_EFFORT_LEVEL",
15119
- "CLAUDE_EFFORT",
15120
- "AI_AGENT"
15121
- ];
15956
+ var ANSWER_DENIED_TOOLS = ["WebFetch", "WebSearch", "Bash"];
15957
+ var ANSWER_SETTINGS = JSON.stringify({
15958
+ permissions: { blockReadsOutsideWorkingDirectories: true },
15959
+ env: { CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" },
15960
+ disableAllHooks: true
15961
+ });
15122
15962
  var MCP_STARTUP_WAIT_MS = "15000";
15123
15963
  function claudeConfigDirFrom(env = process.env) {
15124
15964
  const override = env["CLAUDE_CONFIG_DIR"];
15125
- return override !== void 0 && override.trim().length > 0 ? path7.resolve(override) : void 0;
15965
+ return override !== void 0 && override.trim().length > 0 ? path9.resolve(override) : void 0;
15126
15966
  }
15127
15967
  function claudeHomeFor(configDirOverride) {
15128
- return configDirOverride ?? path7.join(os.homedir(), ".claude");
15968
+ return configDirOverride ?? path9.join(os3.homedir(), ".claude");
15969
+ }
15970
+ function claudeProjectsDirFor(configDirOverride) {
15971
+ return path9.join(claudeHomeFor(configDirOverride), "projects");
15129
15972
  }
15130
15973
  function claudeUserStatePathFor(configDirOverride) {
15131
- return configDirOverride !== void 0 ? path7.join(configDirOverride, ".claude.json") : path7.join(os.homedir(), ".claude.json");
15974
+ return configDirOverride !== void 0 ? path9.join(configDirOverride, ".claude.json") : path9.join(os3.homedir(), ".claude.json");
15132
15975
  }
15133
15976
  function claudeProcessEnv(configDirOverride, source) {
15134
15977
  const env = { ...source };
@@ -15137,46 +15980,37 @@ function claudeProcessEnv(configDirOverride, source) {
15137
15980
  return env;
15138
15981
  }
15139
15982
  function buildClaudeEnv(configDirOverride, source = process.env) {
15140
- const env = claudeProcessEnv(configDirOverride, source);
15141
- for (const key of PARENT_ENV_KEYS) delete env[key];
15983
+ const env = claudeProcessEnv(configDirOverride, withoutParentSession(source));
15142
15984
  env["DISABLE_AUTOUPDATER"] = "1";
15143
15985
  const wait = Number(env["CLAUDE_CODE_MCP_STARTUP_WAIT_MS"]);
15144
15986
  if (!Number.isFinite(wait) || wait < Number(MCP_STARTUP_WAIT_MS)) env["CLAUDE_CODE_MCP_STARTUP_WAIT_MS"] = MCP_STARTUP_WAIT_MS;
15145
15987
  return env;
15146
15988
  }
15147
- function claudeIsLoggedIn(configDirOverride, command = "claude") {
15148
- const status = spawnCommandSync(command, ["auth", "status"], {
15149
- encoding: "utf-8",
15150
- timeout: 1e4,
15151
- windowsHide: true,
15152
- env: claudeProcessEnv(configDirOverride, process.env)
15153
- });
15989
+ var PROBE_TIMEOUT_MS = 1e4;
15990
+ async function claudeSignIn(configDirOverride, command = "claude", timeoutMs = PROBE_TIMEOUT_MS, signal) {
15991
+ const status = await runProbe(command, ["auth", "status"], { timeoutMs, env: claudeProcessEnv(configDirOverride, process.env), ...signal !== void 0 ? { signal } : {} });
15992
+ if (status.timedOut) return { signedIn: false, unanswered: `claude auth status did not answer within ${Math.round(timeoutMs / 1e3)} s (killed)` };
15993
+ if (signal?.aborted) return { signedIn: false, unanswered: "claude auth status was stopped" };
15154
15994
  if (!status.error) {
15155
15995
  try {
15156
- const parsed = JSON.parse(String(status.stdout ?? "").trim());
15157
- if (typeof parsed?.loggedIn === "boolean") return parsed.loggedIn;
15996
+ const parsed = JSON.parse(status.stdout.trim());
15997
+ if (typeof parsed?.loggedIn === "boolean") return { signedIn: parsed.loggedIn, unanswered: null };
15158
15998
  } catch {
15159
15999
  }
15160
- if (status.status === 0) return true;
16000
+ if (status.status === 0) return { signedIn: true, unanswered: null };
15161
16001
  }
15162
16002
  const configDir = claudeHomeFor(configDirOverride);
15163
- if (fs3.existsSync(path7.join(configDir, ".credentials.json"))) return true;
15164
- if (process.platform !== "darwin") return false;
15165
- const keychain = spawnCommandSync("security", ["find-generic-password", "-s", "Claude Code-credentials"], {
15166
- encoding: "utf-8",
15167
- timeout: 5e3
15168
- });
15169
- return !keychain.error && keychain.status === 0;
15170
- }
15171
- function inspectClaudeRuntime(configDirOverride, command = "claude") {
15172
- const version = spawnCommandSync(command, ["--version"], {
15173
- encoding: "utf-8",
15174
- timeout: 1e4,
15175
- windowsHide: true,
15176
- env: claudeProcessEnv(configDirOverride, process.env)
15177
- });
16003
+ if (fs7.existsSync(path9.join(configDir, ".credentials.json"))) return { signedIn: true, unanswered: null };
16004
+ if (process.platform !== "darwin") return { signedIn: false, unanswered: null };
16005
+ const keychain = await runProbe("security", ["find-generic-password", "-s", "Claude Code-credentials"], { timeoutMs: Math.min(timeoutMs, 5e3), ...signal !== void 0 ? { signal } : {} });
16006
+ return { signedIn: !keychain.error && keychain.status === 0, unanswered: null };
16007
+ }
16008
+ async function inspectClaudeRuntime(configDirOverride, command = "claude", timeoutMs = PROBE_TIMEOUT_MS, signal) {
16009
+ const version = await runProbe(command, ["--version"], { timeoutMs, env: claudeProcessEnv(configDirOverride, process.env), ...signal !== void 0 ? { signal } : {} });
16010
+ if (version.timedOut) return { ok: false, detail: `claude --version did not answer within ${Math.round(timeoutMs / 1e3)} s (killed)` };
16011
+ if (signal?.aborted) return { ok: false, detail: "claude --version was stopped" };
15178
16012
  if (version.error) return { ok: false, detail: `claude CLI not found on PATH (${version.error.message})` };
15179
- const rendered = String(version.stdout || version.stderr).trim();
16013
+ const rendered = (version.stdout || version.stderr).trim();
15180
16014
  if (version.status !== 0) return { ok: false, detail: rendered || `claude --version exited ${version.status}` };
15181
16015
  return semverAtLeast(rendered, MIN_CLAUDE_CODE_VERSION) ? { ok: true, detail: rendered } : {
15182
16016
  ok: false,
@@ -15184,14 +16018,36 @@ function inspectClaudeRuntime(configDirOverride, command = "claude") {
15184
16018
  };
15185
16019
  }
15186
16020
  function deniedAncestorOf(dir, denied) {
15187
- const target = path7.resolve(dir);
16021
+ const target = path9.resolve(dir);
15188
16022
  for (const raw of denied) {
15189
- const root = path7.resolve(raw);
15190
- if (target === root || target.startsWith(root.endsWith(path7.sep) ? root : root + path7.sep)) return root;
16023
+ const root = path9.resolve(raw);
16024
+ if (target === root || target.startsWith(root.endsWith(path9.sep) ? root : root + path9.sep)) return root;
15191
16025
  }
15192
16026
  return null;
15193
16027
  }
15194
- function claudeProfileArgs(profile) {
16028
+ function expressibleAllow(raw) {
16029
+ return expressible(raw) && !/[*?[\]\\!#]/.test(raw);
16030
+ }
16031
+ function workdirPaths(workdir) {
16032
+ const given = path9.resolve(workdir);
16033
+ let real = given;
16034
+ try {
16035
+ real = fs7.realpathSync(given);
16036
+ } catch {
16037
+ }
16038
+ return real === given ? [given] : [given, real];
16039
+ }
16040
+ function workdirReadRules(workdir) {
16041
+ if (workdir === void 0 || process.platform === "win32") return [];
16042
+ const rules = [];
16043
+ for (const raw of workdirPaths(workdir)) {
16044
+ const clean = raw.replace(/\/+$/, "");
16045
+ if (!expressibleAllow(raw) || clean.length === 0) continue;
16046
+ rules.push(`Read(/${clean})`, `Read(/${clean}/**)`);
16047
+ }
16048
+ return rules;
16049
+ }
16050
+ function claudeProfileArgs(profile, workdir) {
15195
16051
  switch (profile) {
15196
16052
  case "answer":
15197
16053
  return [
@@ -15202,8 +16058,12 @@ function claudeProfileArgs(profile) {
15202
16058
  "--tools",
15203
16059
  ANSWER_TOOLS.join(","),
15204
16060
  "--allowedTools",
15205
- [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS].join(",")
16061
+ [AGENTCHAT_TOOL_ALLOW, ...workdirReadRules(workdir)].join(","),
16062
+ "--settings",
16063
+ ANSWER_SETTINGS
15206
16064
  ];
16065
+ // `work` and `full` are the operator's explicit opt-in: a run started by
16066
+ // any peer's message can then read and change this machine.
15207
16067
  case "work":
15208
16068
  return [
15209
16069
  "--permission-mode",
@@ -15211,7 +16071,7 @@ function claudeProfileArgs(profile) {
15211
16071
  "--permission-prompts",
15212
16072
  "none",
15213
16073
  "--allowedTools",
15214
- [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WORK_TOOLS].join(",")
16074
+ [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WEB_TOOLS, ...WORK_TOOLS].join(",")
15215
16075
  ];
15216
16076
  case "full":
15217
16077
  return ["--dangerously-skip-permissions", "--permission-prompts", "none", "--allowedTools", AGENTCHAT_TOOL_ALLOW];
@@ -15235,7 +16095,7 @@ function readDenyRules(paths) {
15235
16095
  }
15236
16096
  function claudeRunArgs(profile, options = {}) {
15237
16097
  const budget = options.maxBudgetUsd?.trim();
15238
- const deny = readDenyRules(options.denyReadPaths ?? []);
16098
+ const deny = [...profile === "answer" ? ANSWER_DENIED_TOOLS : [], ...readDenyRules(options.denyReadPaths ?? [])];
15239
16099
  return [
15240
16100
  "-p",
15241
16101
  "--output-format",
@@ -15246,7 +16106,8 @@ function claudeRunArgs(profile, options = {}) {
15246
16106
  ...budget !== void 0 && /^\d+(\.\d+)?$/.test(budget) ? ["--max-budget-usd", budget] : [],
15247
16107
  // Variadic, so it is closed by the boolean flag right after it.
15248
16108
  ...options.mcpConfigPath !== void 0 ? ["--mcp-config", options.mcpConfigPath, "--strict-mcp-config"] : [],
15249
- ...claudeProfileArgs(profile),
16109
+ ...options.appendSystemPromptFile !== void 0 ? ["--append-system-prompt-file", options.appendSystemPromptFile] : [],
16110
+ ...claudeProfileArgs(profile, options.workdir),
15250
16111
  // Last: the option is variadic and the prompt arrives on stdin, so there
15251
16112
  // is no positional for it to swallow.
15252
16113
  ...deny.length > 0 ? ["--disallowedTools", deny.join(",")] : []
@@ -15257,7 +16118,70 @@ function claudeMcpConfig(apiBase, apiKey, clientVersion = VERSION2) {
15257
16118
  return `${JSON.stringify({ mcpServers: { [CLAUDE_MCP_SERVER_NAME]: { type: "http", url: hostedMcpUrl2(apiBase), headers } } }, null, 2)}
15258
16119
  `;
15259
16120
  }
15260
- var ClaudeRunner = class {
16121
+ var ANSWER_ENV = Object.freeze({
16122
+ CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1",
16123
+ CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1"
16124
+ });
16125
+ function claudeManagedSettingsDir(platform = process.platform) {
16126
+ if (platform === "darwin") return "/Library/Application Support/ClaudeCode";
16127
+ if (platform === "win32") return "C:\\Program Files\\ClaudeCode";
16128
+ return "/etc/claude-code";
16129
+ }
16130
+ function gitRootOf(dir) {
16131
+ let current = path9.resolve(dir);
16132
+ for (; ; ) {
16133
+ if (fs7.existsSync(path9.join(current, ".git"))) return current;
16134
+ const parent = path9.dirname(current);
16135
+ if (parent === current) return null;
16136
+ current = parent;
16137
+ }
16138
+ }
16139
+ function claudeSettingsFilesGrantingDirectories(configDirOverride, workdir) {
16140
+ const managed = claudeManagedSettingsDir();
16141
+ const dropIns = (() => {
16142
+ try {
16143
+ 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));
16144
+ } catch {
16145
+ return [];
16146
+ }
16147
+ })();
16148
+ const cwdLocal = path9.join(path9.resolve(workdir), ".claude", "settings.local.json");
16149
+ const root = gitRootOf(workdir);
16150
+ const rootLocal = root !== null ? path9.join(root, ".claude", "settings.local.json") : cwdLocal;
16151
+ return [
16152
+ path9.join(claudeHomeFor(configDirOverride), "settings.json"),
16153
+ path9.join(managed, "managed-settings.json"),
16154
+ ...dropIns,
16155
+ .../* @__PURE__ */ new Set([rootLocal, cwdLocal])
16156
+ ];
16157
+ }
16158
+ function claudeExtraDirectoriesGrant(configDirOverride, workdir) {
16159
+ for (const file of claudeSettingsFilesGrantingDirectories(configDirOverride, workdir)) {
16160
+ let text;
16161
+ try {
16162
+ text = fs7.readFileSync(file, "utf-8");
16163
+ } catch {
16164
+ continue;
16165
+ }
16166
+ let parsed;
16167
+ try {
16168
+ parsed = JSON.parse(text);
16169
+ } catch {
16170
+ if (text.includes("additionalDirectories")) return { file, detail: "names permissions.additionalDirectories and is not valid JSON" };
16171
+ continue;
16172
+ }
16173
+ const dirs = parsed?.permissions?.additionalDirectories;
16174
+ if (Array.isArray(dirs) && dirs.length > 0) return { file, detail: `lists permissions.additionalDirectories (${dirs.length} folder${dirs.length === 1 ? "" : "s"})` };
16175
+ }
16176
+ return null;
16177
+ }
16178
+ function extraDirectoriesRefusal(grant) {
16179
+ 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).`;
16180
+ }
16181
+ function claudeAnswerFallbackWorkdir(configDirOverride) {
16182
+ return path9.join(claudeHomeFor(configDirOverride), "agentchat-answer-workdir");
16183
+ }
16184
+ var ClaudeRunner = class _ClaudeRunner {
15261
16185
  constructor(options) {
15262
16186
  this.options = options;
15263
16187
  this.command = options.command ?? "claude";
@@ -15268,24 +16192,51 @@ var ClaudeRunner = class {
15268
16192
  /** The workdir warning is one line per process, not one per preflight (preflight repeats every few minutes). */
15269
16193
  warnedWorkdir = false;
15270
16194
  warnedDeny = false;
15271
- /** The denied path the configured workdir sits in, or null when the run can read its own cwd. */
16195
+ warnedHome = false;
16196
+ /**
16197
+ * Where this runner's runs work: the configured workdir, except that an
16198
+ * `answer` run never works in the home folder or above it — it gets
16199
+ * `claudeAnswerFallbackWorkdir` (its readable folder would be the whole home).
16200
+ */
16201
+ workdir() {
16202
+ if (this.options.profile === "answer" && workdirExposesHome(this.options.workdir)) return claudeAnswerFallbackWorkdir(this.options.configDir);
16203
+ return this.options.workdir;
16204
+ }
16205
+ /** The denied path the workdir sits in, or null when the run can read its own cwd. */
15272
16206
  workdirDeniedBy() {
15273
- return deniedAncestorOf(this.options.workdir, this.options.denyReadPaths);
16207
+ return deniedAncestorOf(this.workdir(), this.options.denyReadPaths);
15274
16208
  }
15275
- async preflight() {
15276
- const runtime = inspectClaudeRuntime(this.options.configDir, this.command);
16209
+ async preflight(options = {}) {
16210
+ const runtime = await inspectClaudeRuntime(this.options.configDir, this.command, PROBE_TIMEOUT_MS, options.signal);
15277
16211
  if (!runtime.ok) return { ok: false, detail: runtime.detail };
15278
- if (!claudeIsLoggedIn(this.options.configDir, this.command)) {
15279
- return { ok: false, detail: "claude is not signed in (run `claude` once and sign in)" };
16212
+ const signIn = await claudeSignIn(this.options.configDir, this.command, PROBE_TIMEOUT_MS, options.signal);
16213
+ if (signIn.unanswered !== null) return { ok: false, detail: signIn.unanswered };
16214
+ if (!signIn.signedIn) return { ok: false, detail: "claude is not signed in (run `claude` once and sign in)" };
16215
+ if (this.options.profile === "answer" && this.options.mcpConfigPath === void 0) {
16216
+ const answerMcp = this.options.answerMcp;
16217
+ if (answerMcp === void 0) {
16218
+ return { ok: false, detail: "an answer run needs the AgentChat-only tool config (ClaudeRunnerOptions.answerMcp): without it the run would load every MCP server the user registered" };
16219
+ }
16220
+ if (deniedAncestorOf(answerMcp.file, this.options.denyReadPaths) === null) {
16221
+ return { ok: false, detail: `the answer runs' tool config ${answerMcp.file} holds the key and must sit inside a path the runs are denied (${this.options.denyReadPaths.join(", ")})` };
16222
+ }
16223
+ }
16224
+ if (this.options.profile === "answer") {
16225
+ const grant = claudeExtraDirectoriesGrant(this.options.configDir, this.workdir());
16226
+ if (grant !== null) return { ok: false, detail: extraDirectoriesRefusal(grant) };
16227
+ }
16228
+ if (this.workdir() !== this.options.workdir && !this.warnedHome) {
16229
+ this.warnedHome = true;
16230
+ 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.`);
15280
16231
  }
15281
16232
  const denied = this.workdirDeniedBy();
15282
16233
  if (denied !== null && !this.warnedWorkdir) {
15283
16234
  this.warnedWorkdir = true;
15284
16235
  log.warn(
15285
- `the run workdir ${this.options.workdir} is inside ${denied}, which every run's file tools are denied: runs cannot read their own working directory.${this.options.workdirAdvice ? ` ${this.options.workdirAdvice}` : ""}`
16236
+ `the run workdir ${this.workdir()} is inside ${denied}, which every run's file tools are denied: runs cannot read their own working directory.${this.options.workdirAdvice ? ` ${this.options.workdirAdvice}` : ""}`
15286
16237
  );
15287
16238
  }
15288
- const uncovered = inexpressibleDenyPaths(this.options.denyReadPaths);
16239
+ const uncovered = inexpressibleDenyPaths(this.readDenyPaths());
15289
16240
  if (uncovered.length > 0) {
15290
16241
  const why = process.platform === "win32" ? `Claude Code's rule syntax for Windows paths is undocumented, so no read-deny rule is given for ${uncovered.join(", ")}` : `no read-deny rule can carry ${uncovered.join(", ")} (a comma or whitespace in the path)`;
15291
16242
  if (this.options.inexpressibleDeny === "refuse") return { ok: false, detail: `${why}: a run could read the key there. Use an identity home whose path has no comma or whitespace (--home).` };
@@ -15294,40 +16245,127 @@ var ClaudeRunner = class {
15294
16245
  log.warn(`${why}: runs can read those paths.`);
15295
16246
  }
15296
16247
  }
15297
- if (this.options.mcpConfigPath !== void 0 && !fs3.existsSync(this.options.mcpConfigPath)) {
16248
+ if (this.options.mcpConfigPath !== void 0 && !fs7.existsSync(this.options.mcpConfigPath)) {
15298
16249
  return { ok: false, detail: `the hosted tool config ${this.options.mcpConfigPath} is missing` };
15299
16250
  }
15300
- fs3.mkdirSync(this.options.workdir, { recursive: true, mode: 448 });
16251
+ fs7.mkdirSync(this.workdir(), { recursive: true, mode: 448 });
15301
16252
  return { ok: true };
15302
16253
  }
15303
- /** The exact argv one run uses — exported for tests to pin per profile. */
15304
- args() {
16254
+ /** `<dir>/<stem>.<run id><ext>`: a file of this run's own beside `file` (the run id reduced to letters, digits and `-`). */
16255
+ static perRun(file, runId, ext) {
16256
+ const stem = path9.basename(file, path9.extname(file));
16257
+ const id = runId.replace(/[^A-Za-z0-9-]/g, "").slice(0, 64) || "run";
16258
+ return path9.join(path9.dirname(file), `${stem}.${id}${ext}`);
16259
+ }
16260
+ /** The answer run's own files for `runId`: its AgentChat-only tool config (integration path) and its identity-line file. */
16261
+ answerRunFiles(runId) {
16262
+ if (this.options.profile !== "answer") return {};
16263
+ const base = this.options.mcpConfigPath ?? this.options.answerMcp?.file;
16264
+ return {
16265
+ ...this.options.mcpConfigPath === void 0 && this.options.answerMcp !== void 0 ? { mcpConfigPath: _ClaudeRunner.perRun(this.options.answerMcp.file, runId, ".json") } : {},
16266
+ ...base !== void 0 ? { identityFile: _ClaudeRunner.perRun(base, runId, ".identity.md") } : {}
16267
+ };
16268
+ }
16269
+ /**
16270
+ * What this runner's runs are denied reading: the key store, and for an
16271
+ * `answer` run also Claude Code's own record of every project
16272
+ * (`<config dir>/projects`: transcripts and auto memory). Claude Code lets a
16273
+ * run read its project's memory folder even with auto memory off and reads
16274
+ * blocked outside the working directories (seen on 2.1.322); a deny rule
16275
+ * wins over that.
16276
+ */
16277
+ readDenyPaths() {
16278
+ return this.options.profile === "answer" ? [...this.options.denyReadPaths, claudeProjectsDirFor(this.options.configDir)] : [...this.options.denyReadPaths];
16279
+ }
16280
+ argsFor(mcpConfigPath, appendSystemPromptFile) {
15305
16281
  return claudeRunArgs(this.options.profile, {
15306
16282
  maxBudgetUsd: (this.options.env ?? process.env)["AGENTCHAT_RUN_MAX_BUDGET_USD"],
15307
- denyReadPaths: this.options.denyReadPaths,
15308
- mcpConfigPath: this.options.mcpConfigPath
16283
+ workdir: this.workdir(),
16284
+ denyReadPaths: this.readDenyPaths(),
16285
+ ...mcpConfigPath !== void 0 ? { mcpConfigPath } : {},
16286
+ ...appendSystemPromptFile !== void 0 ? { appendSystemPromptFile } : {}
15309
16287
  });
15310
16288
  }
16289
+ /**
16290
+ * The argv of a run — exported for tests to pin per profile. With a `runId`,
16291
+ * that run's own files (an answer run's tool config and identity-line file);
16292
+ * without, the configured `answerMcp.file` stands in and no identity file.
16293
+ */
16294
+ args(runId, identityLine) {
16295
+ if (runId === void 0) {
16296
+ const mcpConfigPath = this.options.mcpConfigPath ?? (this.options.profile === "answer" ? this.options.answerMcp?.file : void 0);
16297
+ return this.argsFor(mcpConfigPath, void 0);
16298
+ }
16299
+ const files = this.answerRunFiles(runId);
16300
+ return this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityLine === true ? files.identityFile : void 0);
16301
+ }
16302
+ /** The run's environment: no parent session; an answer run loads no CLAUDE.md and no auto memory (`ANSWER_ENV`). */
16303
+ runEnv() {
16304
+ const env = buildClaudeEnv(this.options.configDir, this.options.env ?? process.env);
16305
+ return this.options.profile === "answer" ? { ...env, ...ANSWER_ENV } : env;
16306
+ }
15311
16307
  async start(request) {
15312
- const args = this.args();
15313
- log.debug(`claude ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
15314
- return spawnRun({
15315
- command: this.command,
15316
- args,
15317
- cwd: this.options.workdir,
15318
- env: buildClaudeEnv(this.options.configDir, this.options.env ?? process.env),
15319
- stdin: request.prompt,
15320
- budgetMs: request.budgetMs,
15321
- // Stopping SIGTERMs this run's process group instead of orphaning it.
15322
- ...request.signal ? { signal: request.signal } : {},
15323
- // The engine records a group invite as offered the moment the process
15324
- // has spawned, so a run cut short still counts as the one offer.
15325
- ...request.onStarted ? { onStarted: request.onStarted } : {}
15326
- });
16308
+ const startedAt = Date.now();
16309
+ const notStarted = (detail) => ({ state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail });
16310
+ const answer = this.options.profile === "answer";
16311
+ const answerMcp = answer && this.options.mcpConfigPath === void 0 ? this.options.answerMcp : void 0;
16312
+ if (answer && this.options.mcpConfigPath === void 0 && answerMcp === void 0) {
16313
+ return notStarted("an answer run needs the AgentChat-only tool config (ClaudeRunnerOptions.answerMcp)");
16314
+ }
16315
+ if (answer) {
16316
+ const grant = claudeExtraDirectoriesGrant(this.options.configDir, this.workdir());
16317
+ if (grant !== null) return notStarted(extraDirectoriesRefusal(grant));
16318
+ }
16319
+ const files = this.answerRunFiles(request.runId);
16320
+ const identityFile = answer && request.identityLine !== void 0 ? files.identityFile : void 0;
16321
+ const written = [];
16322
+ const cleanup = () => {
16323
+ for (const file of written) fs7.rmSync(file, { force: true });
16324
+ };
16325
+ if (answerMcp !== void 0 && files.mcpConfigPath !== void 0) {
16326
+ const key = answerMcp.apiKey();
16327
+ if (key === null) return notStarted("no AgentChat key for the answer run's tool config");
16328
+ try {
16329
+ atomicWriteFile(files.mcpConfigPath, claudeMcpConfig(answerMcp.apiBase, key, answerMcp.clientVersion ?? VERSION2), 384);
16330
+ written.push(files.mcpConfigPath);
16331
+ } catch (err) {
16332
+ cleanup();
16333
+ return notStarted(`could not write the answer run's tool config ${files.mcpConfigPath}: ${err instanceof Error ? err.message : String(err)}`);
16334
+ }
16335
+ }
16336
+ if (identityFile !== void 0 && request.identityLine !== void 0) {
16337
+ try {
16338
+ atomicWriteFile(identityFile, `${request.identityLine.trim()}
16339
+ `, 384);
16340
+ written.push(identityFile);
16341
+ } catch (err) {
16342
+ cleanup();
16343
+ return notStarted(`could not write the answer run's identity line ${identityFile}: ${err instanceof Error ? err.message : String(err)}`);
16344
+ }
16345
+ }
16346
+ try {
16347
+ const args = this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityFile);
16348
+ log.debug(`claude ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
16349
+ return await spawnRun({
16350
+ command: this.command,
16351
+ args,
16352
+ cwd: this.workdir(),
16353
+ env: this.runEnv(),
16354
+ stdin: request.prompt,
16355
+ budgetMs: request.budgetMs,
16356
+ // Stopping SIGTERMs this run's process group instead of orphaning it.
16357
+ ...request.signal ? { signal: request.signal } : {},
16358
+ // The engine records a group invite as offered the moment the process
16359
+ // has spawned, so a run cut short still counts as the one offer.
16360
+ ...request.onStarted ? { onStarted: request.onStarted } : {}
16361
+ });
16362
+ } finally {
16363
+ cleanup();
16364
+ }
15327
16365
  }
15328
16366
  };
15329
16367
  function claudeMcpConfigPath(home) {
15330
- return path7.join(home, "presets", `${CLAUDE_CODE_PRESET}.mcp.json`);
16368
+ return path9.join(home, "presets", `${CLAUDE_CODE_PRESET}.mcp.json`);
15331
16369
  }
15332
16370
  var claudeCodePreset = {
15333
16371
  name: CLAUDE_CODE_PRESET,
@@ -15342,11 +16380,13 @@ var claudeCodePreset = {
15342
16380
  // Every run's file tools are denied the identity home.
15343
16381
  serviceEnv: ["CLAUDE_CONFIG_DIR"],
15344
16382
  readsIdentityHome: false,
15345
- inspect(env = process.env, command = "claude") {
16383
+ async inspect(env = process.env, command = "claude") {
15346
16384
  const configDir = claudeConfigDirFrom(env);
15347
- const runtime = inspectClaudeRuntime(configDir, command);
16385
+ const runtime = await inspectClaudeRuntime(configDir, command);
15348
16386
  if (!runtime.ok) return runtime;
15349
- return claudeIsLoggedIn(configDir, command) ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in (run \`claude\` once and sign in)` };
16387
+ const signIn = await claudeSignIn(configDir, command);
16388
+ if (signIn.unanswered !== null) return { ok: false, detail: `${runtime.detail}, ${signIn.unanswered}` };
16389
+ return signIn.signedIn ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in (run \`claude\` once and sign in)` };
15350
16390
  },
15351
16391
  runner(ctx) {
15352
16392
  const env = withoutInheritedKey(ctx.env ?? process.env);
@@ -15359,7 +16399,7 @@ var claudeCodePreset = {
15359
16399
  profile: ctx.profile,
15360
16400
  // The listener's home (its key and this file), the user-scope MCP state
15361
16401
  // and an integration's identity home beside it: no run reads a key.
15362
- denyReadPaths: [ctx.home, claudeUserStatePathFor(configDir), path7.join(claudeHomeFor(configDir), "agentchat")],
16402
+ denyReadPaths: [ctx.home, claudeUserStatePathFor(configDir), path9.join(claudeHomeFor(configDir), "agentchat")],
15363
16403
  mcpConfigPath,
15364
16404
  workdirAdvice: "Start the listener from a directory outside it, or pass --workdir.",
15365
16405
  // On POSIX a listener's run must not start with its key readable; on
@@ -15378,35 +16418,59 @@ var CODEX_PROMPT_FROM_STDIN = "-";
15378
16418
  function codexHomeFrom(env = process.env) {
15379
16419
  const override = env["CODEX_HOME"];
15380
16420
  if (override !== void 0 && override.trim().length > 0) return path24.resolve(override);
15381
- return path24.join(os2.homedir(), ".codex");
15382
- }
15383
- function inspectCodexRuntime(codexHome, command = "codex") {
15384
- const result = spawnCommandSync(command, ["--version"], {
15385
- encoding: "utf-8",
15386
- timeout: 1e4,
15387
- windowsHide: true,
15388
- env: { ...process.env, CODEX_HOME: codexHome }
15389
- });
16421
+ return path24.join(os23.homedir(), ".codex");
16422
+ }
16423
+ var CODEX_PROBE_TIMEOUT_MS = 1e4;
16424
+ async function inspectCodexRuntime(codexHome, command = "codex", timeoutMs = CODEX_PROBE_TIMEOUT_MS, signal) {
16425
+ const result = await runProbe(command, ["--version"], { timeoutMs, env: { ...process.env, CODEX_HOME: codexHome }, ...signal !== void 0 ? { signal } : {} });
16426
+ if (result.timedOut) return { ok: false, detail: `codex --version did not answer within ${Math.round(timeoutMs / 1e3)} s (killed)` };
16427
+ if (signal?.aborted) return { ok: false, detail: "codex --version was stopped" };
15390
16428
  if (result.error) return { ok: false, detail: `codex CLI not found on PATH (${result.error.message})` };
15391
- const rendered = String(result.stdout || result.stderr).trim();
16429
+ const rendered = (result.stdout || result.stderr).trim();
15392
16430
  if (result.status !== 0) return { ok: false, detail: rendered || `codex --version exited ${result.status}` };
15393
16431
  return semverAtLeast(rendered, MIN_CODEX_VERSION) ? { ok: true, detail: rendered } : { ok: false, detail: `${rendered || "unrecognized version"}; AgentChat requires Codex >= ${MIN_CODEX_VERSION}` };
15394
16432
  }
15395
- function codexIsLoggedIn(codexHome, command = "codex") {
15396
- const status = spawnCommandSync(command, ["login", "status"], {
15397
- encoding: "utf-8",
15398
- timeout: 1e4,
15399
- windowsHide: true,
15400
- env: { ...process.env, CODEX_HOME: codexHome }
15401
- });
16433
+ async function codexIsLoggedIn(codexHome, command = "codex", timeoutMs = CODEX_PROBE_TIMEOUT_MS, signal) {
16434
+ const status = await runProbe(command, ["login", "status"], { timeoutMs, env: { ...process.env, CODEX_HOME: codexHome }, ...signal !== void 0 ? { signal } : {} });
15402
16435
  if (status.error) return { ok: false, detail: status.error.message };
15403
- const detail = `${status.stdout ?? ""}${status.stderr ?? ""}`.trim().slice(0, 200);
16436
+ const detail = `${status.stdout}${status.stderr}`.trim().slice(0, 200);
15404
16437
  return status.status === 0 ? { ok: true, detail: detail || "signed in" } : { ok: false, detail: detail || "codex is not signed in (run `codex login`)" };
15405
16438
  }
16439
+ var CODEX_ANSWER_PERMISSIONS = "agentchat_answer";
16440
+ var CODEX_ANSWER_FILESYSTEM = '{ ":workspace_roots" = "read" }';
16441
+ var CODEX_ANSWER_DISABLED_FEATURES = [
16442
+ "shell_tool",
16443
+ "view_image",
16444
+ "image_generation",
16445
+ "plugins",
16446
+ "apps",
16447
+ "memories",
16448
+ "browser_use",
16449
+ "browser_use_external",
16450
+ "computer_use",
16451
+ "in_app_browser"
16452
+ ];
15406
16453
  function codexProfileArgs(profile) {
15407
16454
  switch (profile) {
15408
16455
  case "answer":
15409
- return ["--sandbox", "read-only", "-c", 'approval_policy="never"'];
16456
+ return [
16457
+ "-c",
16458
+ 'approval_policy="never"',
16459
+ "-c",
16460
+ `default_permissions="${CODEX_ANSWER_PERMISSIONS}"`,
16461
+ "-c",
16462
+ `permissions.${CODEX_ANSWER_PERMISSIONS}.filesystem=${CODEX_ANSWER_FILESYSTEM}`,
16463
+ "-c",
16464
+ 'web_search="disabled"',
16465
+ // No project or ancestor AGENTS.md (core/src/agents_md.rs:65-67, 129: a
16466
+ // zero budget reads none). $CODEX_HOME/AGENTS.md has no such switch in
16467
+ // 0.154.0 (codex-home/src/instructions/mod.rs, wired unconditionally).
16468
+ "-c",
16469
+ "project_doc_max_bytes=0",
16470
+ ...CODEX_ANSWER_DISABLED_FEATURES.flatMap((feature) => ["--disable", feature])
16471
+ ];
16472
+ // `work` and `full` are the operator's explicit opt-in: a run started by
16473
+ // any peer's message can then read and change this machine.
15410
16474
  case "work":
15411
16475
  return ["--sandbox", "workspace-write", "-c", 'approval_policy="never"'];
15412
16476
  case "full":
@@ -15417,6 +16481,9 @@ function codexClientHeadersToml(clientVersion = VERSION2) {
15417
16481
  const pairs = Object.entries(clientHeadersOf({ runtime: "codex", version: clientVersion })).map(([name, value]) => `${JSON.stringify(name)} = ${JSON.stringify(value)}`);
15418
16482
  return `{ ${pairs.join(", ")} }`;
15419
16483
  }
16484
+ function codexPinnedUrlArgs(url) {
16485
+ return ["-c", `mcp_servers.${CODEX_MCP_SERVER_NAME}.url=${JSON.stringify(url)}`];
16486
+ }
15420
16487
  function codexMcpOverrideArgs(override) {
15421
16488
  const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`;
15422
16489
  return [
@@ -15443,6 +16510,81 @@ function codexRunArgs(profile, options) {
15443
16510
  CODEX_PROMPT_FROM_STDIN
15444
16511
  ];
15445
16512
  }
16513
+ function codexAnswerFallbackWorkdir(codexHome) {
16514
+ return path24.join(codexHome, "agentchat-answer-workdir");
16515
+ }
16516
+ var CODEX_MCP_LIST_TIMEOUT_MS = 2e4;
16517
+ var CODEX_MCP_LIST_KILL_WAIT_MS = 1e4;
16518
+ var CODEX_MCP_LIST_MAX_BYTES = 1024 * 1024;
16519
+ function codexServerNameAddressable(name) {
16520
+ return /^[A-Za-z0-9_:@/-]+$/.test(name);
16521
+ }
16522
+ function parseCodexMcpList(stdout) {
16523
+ let parsed;
16524
+ try {
16525
+ parsed = JSON.parse(stdout);
16526
+ } catch {
16527
+ return { ok: false, detail: "its output is not JSON" };
16528
+ }
16529
+ if (!Array.isArray(parsed)) return { ok: false, detail: "its output is not a list" };
16530
+ const names = [];
16531
+ for (const entry of parsed) {
16532
+ const name = entry?.name;
16533
+ const enabled = entry?.enabled;
16534
+ if (typeof name !== "string" || name.length === 0) return { ok: false, detail: "an entry has no name" };
16535
+ if (enabled !== false) names.push(name);
16536
+ }
16537
+ return { ok: true, names };
16538
+ }
16539
+ function codexMcpDisableArgs(names) {
16540
+ const args = [];
16541
+ for (const name of names) {
16542
+ if (name === CODEX_MCP_SERVER_NAME) continue;
16543
+ if (!codexServerNameAddressable(name)) {
16544
+ return { ok: false, detail: `the MCP server "${name}" cannot be switched off for one run (Codex reads a "." in a -c key as a table); rename it or remove it` };
16545
+ }
16546
+ args.push("-c", `mcp_servers.${name}.enabled=false`);
16547
+ }
16548
+ return { ok: true, args };
16549
+ }
16550
+ function codexAnswerListingRefusal(detail) {
16551
+ return `could not list Codex's MCP servers (\`codex mcp list --json\` with the answer flags: ${detail}); an answer run starts only with every server but ${CODEX_MCP_SERVER_NAME} switched off`;
16552
+ }
16553
+ var CODEX_MCP_LIST_MAX_AGE_MS = 60 * 6e4;
16554
+ function codexConfigLayerFiles(codexHome, workdir, platform = process.platform, env = process.env) {
16555
+ const p = platform === "win32" ? path24.win32 : path24.posix;
16556
+ const programData = env["ProgramData"] ?? env["PROGRAMDATA"] ?? "C:\\ProgramData";
16557
+ const system = platform === "win32" ? [p.join(programData, "OpenAI", "Codex", "config.toml"), p.join(programData, "OpenAI", "Codex", "requirements.toml")] : ["/etc/codex/config.toml", "/etc/codex/managed_config.toml", "/etc/codex/requirements.toml"];
16558
+ const user = (() => {
16559
+ try {
16560
+ return os23.userInfo().username;
16561
+ } catch {
16562
+ return null;
16563
+ }
16564
+ })();
16565
+ const managedPrefs = platform === "darwin" ? ["/Library/Managed Preferences/com.openai.codex.plist", ...user !== null ? [p.join("/Library/Managed Preferences", user, "com.openai.codex.plist")] : []] : [];
16566
+ const tree = [];
16567
+ let current = p.resolve(workdir);
16568
+ tree.push(p.join(current, "config.toml"));
16569
+ for (; ; ) {
16570
+ tree.push(p.join(current, ".codex", "config.toml"));
16571
+ const parent = p.dirname(current);
16572
+ if (parent === current) break;
16573
+ current = parent;
16574
+ }
16575
+ return [...system, ...managedPrefs, p.join(codexHome, "config.toml"), ...tree];
16576
+ }
16577
+ function codexListingKey(files, parts) {
16578
+ const stats = files.map((file) => {
16579
+ try {
16580
+ const st = fs22.statSync(file);
16581
+ return `${file}\0${st.size}\0${st.mtimeMs}`;
16582
+ } catch {
16583
+ return `${file}\0-`;
16584
+ }
16585
+ });
16586
+ return [...parts, ...stats].join("");
16587
+ }
15446
16588
  var CodexRunner = class {
15447
16589
  constructor(options) {
15448
16590
  this.options = options;
@@ -15451,32 +16593,138 @@ var CodexRunner = class {
15451
16593
  options;
15452
16594
  name = "codex";
15453
16595
  command;
15454
- async preflight() {
15455
- const runtime = inspectCodexRuntime(this.options.codexHome, this.command);
16596
+ warnedHome = false;
16597
+ /** 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. */
16598
+ listing = null;
16599
+ /**
16600
+ * Where this runner's runs work (`-C`): the configured workdir, except that an
16601
+ * `answer` run never has the home folder or above it as its workspace root —
16602
+ * it gets `codexAnswerFallbackWorkdir`.
16603
+ */
16604
+ workdir() {
16605
+ if (this.options.profile === "answer" && workdirExposesHome(this.options.workdir)) return codexAnswerFallbackWorkdir(this.options.codexHome);
16606
+ return this.options.workdir;
16607
+ }
16608
+ async preflight(options = {}) {
16609
+ const runtime = await inspectCodexRuntime(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal);
15456
16610
  if (!runtime.ok) return { ok: false, detail: runtime.detail };
15457
- const auth = codexIsLoggedIn(this.options.codexHome, this.command);
16611
+ const auth = await codexIsLoggedIn(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal);
15458
16612
  if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` };
15459
- fs22.mkdirSync(this.options.workdir, { recursive: true });
16613
+ if (this.workdir() !== this.options.workdir && !this.warnedHome) {
16614
+ this.warnedHome = true;
16615
+ 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.`);
16616
+ }
16617
+ fs22.mkdirSync(this.workdir(), { recursive: true });
16618
+ if (this.options.profile === "answer") {
16619
+ const disables = await this.answerMcpDisables();
16620
+ if (!disables.ok) return { ok: false, detail: codexAnswerListingRefusal(disables.detail) };
16621
+ }
15460
16622
  return { ok: true };
15461
16623
  }
15462
- /** The exact argv one run uses — exported for tests to pin per profile. */
16624
+ /** The exact argv one run uses — exported for tests to pin per profile. An `answer` run adds `answerMcpDisables()` before the prompt. */
15463
16625
  args() {
15464
- return codexRunArgs(this.options.profile, { workdir: this.options.workdir, ...this.options.mcp !== void 0 ? { mcp: this.options.mcp } : {} });
16626
+ const args = codexRunArgs(this.options.profile, { workdir: this.workdir(), ...this.options.mcp !== void 0 ? { mcp: this.options.mcp } : {} });
16627
+ if (this.options.mcp !== void 0 || this.options.pinMcpUrl === void 0) return args;
16628
+ return [...args.slice(0, -1), ...codexPinnedUrlArgs(this.options.pinMcpUrl), CODEX_PROMPT_FROM_STDIN];
15465
16629
  }
15466
16630
  /** The child environment: Codex's home and the key the hosted server needs, under the configured name. */
15467
16631
  env() {
15468
- const env = { ...this.options.env ?? process.env, CODEX_HOME: this.options.codexHome };
16632
+ const env = { ...withoutParentSession(this.options.env ?? process.env), CODEX_HOME: this.options.codexHome };
15469
16633
  const key = this.options.apiKey();
15470
16634
  if (key !== null) env[this.options.keyEnv] = key;
15471
16635
  return env;
15472
16636
  }
16637
+ /**
16638
+ * For an `answer` run: `-c mcp_servers.<name>.enabled=false` for every MCP
16639
+ * server the run would load but AgentChat's — the user's own in config.toml,
16640
+ * a project's, a managed one. Codex has no "only this server" switch, and a
16641
+ * tool such a server marks read-only runs without approval. Asked of Codex
16642
+ * itself (`codex mcp list --json`, with the run's own `-c`/`--disable`
16643
+ * flags, from the run's workdir), so every layer is counted. Any failure —
16644
+ * an error, a timeout, output that is not the list — means no run.
16645
+ */
16646
+ async answerMcpDisables() {
16647
+ const run2 = this.args();
16648
+ const flags = run2.flatMap((arg, i) => run2[i - 1] === "-c" || run2[i - 1] === "--disable" ? [run2[i - 1], arg] : []);
16649
+ const key = codexListingKey(codexConfigLayerFiles(this.options.codexHome, this.workdir()), [this.command, this.workdir(), ...flags]);
16650
+ if (this.listing !== null && this.listing.key === key && Date.now() - this.listing.at < CODEX_MCP_LIST_MAX_AGE_MS) return this.listing.result;
16651
+ const listed = await new Promise((resolve32) => {
16652
+ let child;
16653
+ try {
16654
+ child = spawnCommand(this.command, ["mcp", "list", "--json", ...flags], {
16655
+ cwd: this.workdir(),
16656
+ env: this.env(),
16657
+ stdio: ["ignore", "pipe", "pipe"],
16658
+ // Its own process group on POSIX, so a hung listing is killed with
16659
+ // everything it started (the npm launcher and the native binary).
16660
+ detached: process.platform !== "win32",
16661
+ windowsHide: true
16662
+ });
16663
+ } catch (err) {
16664
+ resolve32({ ok: false, detail: err instanceof Error ? err.message : String(err) });
16665
+ return;
16666
+ }
16667
+ const proc = child;
16668
+ let stdout = "";
16669
+ let stderr = "";
16670
+ let stopped = null;
16671
+ let settled = false;
16672
+ let abandonTimer = null;
16673
+ const settle = (result2) => {
16674
+ if (settled) return;
16675
+ settled = true;
16676
+ clearTimeout(timer);
16677
+ if (abandonTimer !== null) clearTimeout(abandonTimer);
16678
+ resolve32(result2);
16679
+ };
16680
+ const stop = (why) => {
16681
+ if (stopped !== null) return;
16682
+ stopped = why;
16683
+ killProcessTree(proc, "SIGKILL");
16684
+ abandonTimer = setTimeout(() => settle({ ok: false, detail: `${why} (and it did not exit after being killed)` }), CODEX_MCP_LIST_KILL_WAIT_MS);
16685
+ };
16686
+ proc.stderr?.on("data", (chunk) => {
16687
+ if (stderr.length < 4096) stderr += chunk.toString("utf-8");
16688
+ });
16689
+ const timeoutMs = this.options.mcpListTimeoutMs ?? CODEX_MCP_LIST_TIMEOUT_MS;
16690
+ const timer = setTimeout(() => stop(`no answer within ${Math.round(timeoutMs / 1e3)} s`), timeoutMs);
16691
+ proc.stdout?.on("data", (chunk) => {
16692
+ stdout += chunk.toString("utf-8");
16693
+ if (stdout.length > CODEX_MCP_LIST_MAX_BYTES) stop("its output is too long");
16694
+ });
16695
+ proc.on("error", (err) => {
16696
+ if (stopped === null) settle({ ok: false, detail: err.message });
16697
+ });
16698
+ proc.on("close", (code) => {
16699
+ if (stopped !== null) {
16700
+ settle({ ok: false, detail: stopped });
16701
+ return;
16702
+ }
16703
+ const said = redactDiagnostic(stderr.split(/\r?\n/).find((line) => line.trim().length > 0) ?? "", 200);
16704
+ if (code !== 0) settle({ ok: false, detail: `it exited ${code}${said ? `: ${said}` : ""}` });
16705
+ else settle({ ok: true, stdout });
16706
+ });
16707
+ });
16708
+ if (!listed.ok) return listed;
16709
+ const parsed = parseCodexMcpList(listed.stdout);
16710
+ if (!parsed.ok) return parsed;
16711
+ const result = codexMcpDisableArgs(parsed.names);
16712
+ if (result.ok) this.listing = { key, at: Date.now(), result };
16713
+ return result;
16714
+ }
15473
16715
  async start(request) {
15474
- const args = this.args();
16716
+ const startedAt = Date.now();
16717
+ let args = this.args();
16718
+ if (this.options.profile === "answer") {
16719
+ const disables = await this.answerMcpDisables();
16720
+ if (!disables.ok) return { state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail: codexAnswerListingRefusal(disables.detail) };
16721
+ args = [...args.slice(0, -1), ...disables.args, CODEX_PROMPT_FROM_STDIN];
16722
+ }
15475
16723
  log.debug(`codex ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
15476
16724
  return spawnRun({
15477
16725
  command: this.command,
15478
16726
  args,
15479
- cwd: this.options.workdir,
16727
+ cwd: this.workdir(),
15480
16728
  env: this.env(),
15481
16729
  // Written to stdin and then closed: `codex exec -` reads its
15482
16730
  // instructions until EOF. Never as an argument (see codexRunArgs).
@@ -15520,14 +16768,15 @@ var codexPreset = {
15520
16768
  },
15521
16769
  label: "Codex",
15522
16770
  runtime: "codex",
15523
- // A read-only sandbox reads the whole filesystem.
15524
16771
  serviceEnv: ["CODEX_HOME"],
16772
+ // `work` and `full` read the whole filesystem (an `answer` run reads only its
16773
+ // workdir): true, because the field is one for every profile.
15525
16774
  readsIdentityHome: true,
15526
- inspect(env = process.env, command = "codex") {
16775
+ async inspect(env = process.env, command = "codex") {
15527
16776
  const home = codexHomeFrom(env);
15528
- const runtime = inspectCodexRuntime(home, command);
16777
+ const runtime = await inspectCodexRuntime(home, command);
15529
16778
  if (!runtime.ok) return runtime;
15530
- const auth = codexIsLoggedIn(home, command);
16779
+ const auth = await codexIsLoggedIn(home, command);
15531
16780
  return auth.ok ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in: ${auth.detail}` };
15532
16781
  },
15533
16782
  runner(ctx) {
@@ -15551,40 +16800,40 @@ var PRESETS = Object.freeze({
15551
16800
  });
15552
16801
 
15553
16802
  // src/version.ts
15554
- var VERSION3 = "0.4.1";
16803
+ var VERSION3 = "0.5.0";
15555
16804
 
15556
16805
  // src/host.ts
15557
16806
  function claudeConfigOverride() {
15558
16807
  const override = process.env["CLAUDE_CONFIG_DIR"];
15559
- return override !== void 0 && override.trim().length > 0 ? path8.resolve(override) : void 0;
16808
+ return override !== void 0 && override.trim().length > 0 ? path10.resolve(override) : void 0;
15560
16809
  }
15561
16810
  function claudeHome() {
15562
- return claudeConfigOverride() ?? path8.join(os3.homedir(), ".claude");
16811
+ return claudeConfigOverride() ?? path10.join(os4.homedir(), ".claude");
15563
16812
  }
15564
16813
  function identityHome() {
15565
16814
  return identityHomeFor(claudeConfigOverride());
15566
16815
  }
15567
16816
  function identityHomeFor(configDirOverride) {
15568
- return path8.join(configDirOverride ?? path8.join(os3.homedir(), ".claude"), "agentchat");
16817
+ return path10.join(configDirOverride ?? path10.join(os4.homedir(), ".claude"), "agentchat");
15569
16818
  }
15570
16819
  function runWorkdirFor(configDirOverride) {
15571
- return path8.join(configDirOverride ?? path8.join(os3.homedir(), ".claude"), "agentchat-workdir");
16820
+ return path10.join(configDirOverride ?? path10.join(os4.homedir(), ".claude"), "agentchat-workdir");
15572
16821
  }
15573
16822
  function resolveRunWorkdir(configDirOverride, env = process.env) {
15574
16823
  const cwd = env["AGENTCHAT_RUN_CWD"]?.trim();
15575
- return cwd !== void 0 && cwd.length > 0 ? path8.resolve(cwd) : runWorkdirFor(configDirOverride);
16824
+ return cwd !== void 0 && cwd.length > 0 ? path10.resolve(cwd) : runWorkdirFor(configDirOverride);
15576
16825
  }
15577
16826
  function claudeUserStatePathFor2(configDirOverride) {
15578
16827
  return claudeUserStatePathFor(configDirOverride);
15579
16828
  }
15580
16829
  function skillsDir() {
15581
- return path8.join(claudeHome(), "skills");
16830
+ return path10.join(claudeHome(), "skills");
15582
16831
  }
15583
16832
  function skillDir() {
15584
- return path8.join(skillsDir(), MANUAL_SKILL_NAME2);
16833
+ return path10.join(skillsDir(), MANUAL_SKILL_NAME2);
15585
16834
  }
15586
16835
  function skillPath() {
15587
- return path8.join(skillDir(), MANUAL_FILENAME);
16836
+ return path10.join(skillDir(), MANUAL_FILENAME);
15588
16837
  }
15589
16838
  var CLIENT = { runtime: "claude-code", version: VERSION3 };
15590
16839
  function invocation() {
@@ -15594,18 +16843,73 @@ function invocation() {
15594
16843
  }
15595
16844
 
15596
16845
  // src/runner.ts
16846
+ import * as fs8 from "fs";
16847
+ import * as path11 from "path";
15597
16848
  function denyReadPathsFor(configDirOverride) {
15598
16849
  return [identityHomeFor(configDirOverride), claudeUserStatePathFor2(configDirOverride)];
15599
16850
  }
16851
+ function answerToolConfigFor(identityHome2) {
16852
+ return claudeMcpConfigPath(identityHome2);
16853
+ }
16854
+ function answerRunKey(identityHome2, apiBase, handle) {
16855
+ const id = resolveIdentity(identityHome2);
16856
+ if (id === null || id.apiBase !== apiBase) return null;
16857
+ if (handle !== void 0 && id.source === "file" && id.handle !== null && id.handle !== handle) return null;
16858
+ return id.apiKey;
16859
+ }
15600
16860
  var ClaudeRunner2 = class extends ClaudeRunner {
15601
16861
  constructor(options) {
16862
+ const { apiBase, identityHome: given, handle, ...rest } = options;
16863
+ const identityHome2 = given !== void 0 ? path11.resolve(given) : identityHomeFor(options.configDir);
16864
+ const deny = denyReadPathsFor(options.configDir);
15602
16865
  super({
15603
- ...options,
15604
- denyReadPaths: denyReadPathsFor(options.configDir),
16866
+ ...rest,
16867
+ denyReadPaths: deny.includes(identityHome2) ? deny : [identityHome2, ...deny],
16868
+ answerMcp: {
16869
+ file: answerToolConfigFor(identityHome2),
16870
+ apiBase,
16871
+ // Read for each run: a run follows the credential as it is when it starts (`answerRunKey`).
16872
+ apiKey: () => answerRunKey(identityHome2, apiBase, handle),
16873
+ clientVersion: VERSION3
16874
+ },
15605
16875
  workdirAdvice: `Point AGENTCHAT_RUN_CWD outside it, or unset it for the default ${runWorkdirFor(options.configDir)}, then re-run \`${invocation()} daemon install\``
15606
16876
  });
15607
16877
  }
15608
16878
  };
16879
+ function answerRunFilePattern(stem) {
16880
+ const escaped = stem.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
16881
+ return new RegExp(`^\\.?${escaped}\\.[A-Za-z0-9-]{1,64}\\.(json|identity\\.md)(\\.[0-9a-f]{12}\\.tmp)?$`);
16882
+ }
16883
+ function removeAnswerRunFiles(identityHome2) {
16884
+ const config = answerToolConfigFor(identityHome2);
16885
+ const dir = path11.dirname(config);
16886
+ const stem = path11.basename(config, path11.extname(config));
16887
+ let names;
16888
+ try {
16889
+ names = fs8.readdirSync(dir);
16890
+ } catch {
16891
+ return { removed: [], failed: [] };
16892
+ }
16893
+ const pattern = answerRunFilePattern(stem);
16894
+ const removed = [];
16895
+ const failed = [];
16896
+ for (const name of names.filter((n) => pattern.test(n))) {
16897
+ try {
16898
+ fs8.rmSync(path11.join(dir, name), { force: true });
16899
+ removed.push(name);
16900
+ } catch {
16901
+ failed.push(name);
16902
+ }
16903
+ }
16904
+ try {
16905
+ if (fs8.readdirSync(dir).length === 0) fs8.rmdirSync(dir);
16906
+ } catch {
16907
+ }
16908
+ return { removed, failed };
16909
+ }
16910
+ function runPointer(profile, skill) {
16911
+ return profile === "answer" ? "" : manualPointer(`at ${skill}`);
16912
+ }
15609
16913
 
15610
16914
  // src/daemon-main.ts
15611
16915
  async function main(argv = process.argv.slice(2)) {
@@ -15622,17 +16926,26 @@ async function main(argv = process.argv.slice(2)) {
15622
16926
  console.error("Usage: agentchat-daemon [--home <dir>] [--workdir <dir>]");
15623
16927
  return 1;
15624
16928
  }
15625
- const home = values.home !== void 0 ? path9.resolve(values.home) : identityHome();
16929
+ const home = values.home !== void 0 ? path12.resolve(values.home) : identityHome();
15626
16930
  const configDir = claudeConfigOverride();
15627
- const workdir = values.workdir !== void 0 ? path9.resolve(values.workdir) : resolveRunWorkdir(configDir);
16931
+ const workdir = values.workdir !== void 0 ? path12.resolve(values.workdir) : resolveRunWorkdir(configDir);
15628
16932
  const profile = resolveRunProfile();
16933
+ const runner = {
16934
+ // The runner's own name (`ClaudeRunner.name`), for status before any identity is known.
16935
+ name: "claude",
16936
+ create: (identity) => {
16937
+ const { removed } = removeAnswerRunFiles(identity.home);
16938
+ if (removed.length > 0) log.info(`removed ${removed.length} file(s) an interrupted answer run left in ${identity.home}`);
16939
+ return new ClaudeRunner2({ configDir, workdir, profile, identityHome: identity.home, apiBase: identity.apiBase, handle: identity.handle });
16940
+ }
16941
+ };
15629
16942
  return await runIntegration({
15630
16943
  home,
15631
16944
  workdir,
15632
16945
  profile,
15633
- runner: new ClaudeRunner2({ configDir, workdir, profile }),
16946
+ runner,
15634
16947
  client: CLIENT,
15635
- manualPointer: manualPointer(`at ${skillPath()}`),
16948
+ manualPointer: runPointer(profile, skillPath()),
15636
16949
  manualPath: skillPath()
15637
16950
  });
15638
16951
  }