@agentchatme/codex 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -16
- package/dist/daemon-main.js +2071 -808
- package/dist/daemon-main.js.map +1 -1
- package/dist/index.js +1940 -1069
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -46,8 +46,8 @@ var require_windows = __commonJS({
|
|
|
46
46
|
"use strict";
|
|
47
47
|
module.exports = isexe;
|
|
48
48
|
isexe.sync = sync;
|
|
49
|
-
var
|
|
50
|
-
function checkPathExt(
|
|
49
|
+
var fs10 = __require("fs");
|
|
50
|
+
function checkPathExt(path12, 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 &&
|
|
61
|
+
if (p && path12.substr(-p.length).toLowerCase() === p) {
|
|
62
62
|
return true;
|
|
63
63
|
}
|
|
64
64
|
}
|
|
65
65
|
return false;
|
|
66
66
|
}
|
|
67
|
-
function checkStat(stat,
|
|
67
|
+
function checkStat(stat, path12, options) {
|
|
68
68
|
if (!stat.isSymbolicLink() && !stat.isFile()) {
|
|
69
69
|
return false;
|
|
70
70
|
}
|
|
71
|
-
return checkPathExt(
|
|
71
|
+
return checkPathExt(path12, options);
|
|
72
72
|
}
|
|
73
|
-
function isexe(
|
|
74
|
-
|
|
75
|
-
cb(er, er ? false : checkStat(stat,
|
|
73
|
+
function isexe(path12, options, cb) {
|
|
74
|
+
fs10.stat(path12, function(er, stat) {
|
|
75
|
+
cb(er, er ? false : checkStat(stat, path12, options));
|
|
76
76
|
});
|
|
77
77
|
}
|
|
78
|
-
function sync(
|
|
79
|
-
return checkStat(
|
|
78
|
+
function sync(path12, options) {
|
|
79
|
+
return checkStat(fs10.statSync(path12), path12, 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
|
|
91
|
-
function isexe(
|
|
92
|
-
|
|
90
|
+
var fs10 = __require("fs");
|
|
91
|
+
function isexe(path12, options, cb) {
|
|
92
|
+
fs10.stat(path12, function(er, stat) {
|
|
93
93
|
cb(er, er ? false : checkStat(stat, options));
|
|
94
94
|
});
|
|
95
95
|
}
|
|
96
|
-
function sync(
|
|
97
|
-
return checkStat(
|
|
96
|
+
function sync(path12, options) {
|
|
97
|
+
return checkStat(fs10.statSync(path12), 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
|
|
122
|
+
var fs10 = __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(
|
|
131
|
+
function isexe(path12, 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(
|
|
141
|
-
isexe(
|
|
140
|
+
return new Promise(function(resolve9, reject) {
|
|
141
|
+
isexe(path12, options || {}, function(er, is) {
|
|
142
142
|
if (er) {
|
|
143
143
|
reject(er);
|
|
144
144
|
} else {
|
|
145
|
-
|
|
145
|
+
resolve9(is);
|
|
146
146
|
}
|
|
147
147
|
});
|
|
148
148
|
});
|
|
149
149
|
}
|
|
150
|
-
core(
|
|
150
|
+
core(path12, 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(
|
|
160
|
+
function sync(path12, options) {
|
|
161
161
|
try {
|
|
162
|
-
return core.sync(
|
|
162
|
+
return core.sync(path12, 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
|
|
179
|
+
var path12 = __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((
|
|
212
|
+
const step = (i) => new Promise((resolve9, reject) => {
|
|
213
213
|
if (i === pathEnv.length)
|
|
214
|
-
return opt.all && found.length ?
|
|
214
|
+
return opt.all && found.length ? resolve9(found) : reject(getNotFoundError(cmd));
|
|
215
215
|
const ppRaw = pathEnv[i];
|
|
216
216
|
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
217
|
-
const pCmd =
|
|
217
|
+
const pCmd = path12.join(pathPart, cmd);
|
|
218
218
|
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
219
|
-
|
|
219
|
+
resolve9(subStep(p, i, 0));
|
|
220
220
|
});
|
|
221
|
-
const subStep = (p, i, ii) => new Promise((
|
|
221
|
+
const subStep = (p, i, ii) => new Promise((resolve9, reject) => {
|
|
222
222
|
if (ii === pathExt.length)
|
|
223
|
-
return
|
|
223
|
+
return resolve9(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
|
|
230
|
+
return resolve9(p + ext);
|
|
231
231
|
}
|
|
232
|
-
return
|
|
232
|
+
return resolve9(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 =
|
|
244
|
+
const pCmd = path12.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
|
|
292
|
+
var path12 = __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 ?
|
|
310
|
+
pathExt: withoutPathExt ? path12.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 =
|
|
319
|
+
resolved = path12.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 [
|
|
374
|
-
const binary =
|
|
373
|
+
const [path12, argument] = match[0].replace(/#! ?/, "").split(" ");
|
|
374
|
+
const binary = path12.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
|
|
387
|
+
var fs10 = __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 =
|
|
395
|
-
|
|
396
|
-
|
|
394
|
+
fd = fs10.openSync(command, "r");
|
|
395
|
+
fs10.readSync(fd, buffer, 0, size, 0);
|
|
396
|
+
fs10.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
|
|
409
|
+
var path12 = __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 =
|
|
434
|
+
parsed.command = path12.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
|
|
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 =
|
|
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
|
|
522
|
+
var parse2 = require_parse();
|
|
523
523
|
var enoent = require_enoent();
|
|
524
524
|
function spawn(command, args, options) {
|
|
525
|
-
const parsed =
|
|
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 =
|
|
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 =
|
|
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
|
|
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
|
|
|
@@ -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];
|
|
@@ -3478,7 +3478,7 @@ var require_websocket = __commonJS({
|
|
|
3478
3478
|
}
|
|
3479
3479
|
let extensions;
|
|
3480
3480
|
try {
|
|
3481
|
-
extensions =
|
|
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
|
|
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
|
|
|
@@ -4241,14 +4241,17 @@ var init_wrapper = __esm({
|
|
|
4241
4241
|
});
|
|
4242
4242
|
|
|
4243
4243
|
// src/index.ts
|
|
4244
|
-
import * as
|
|
4244
|
+
import * as fs9 from "fs";
|
|
4245
4245
|
import { parseArgs } from "util";
|
|
4246
4246
|
|
|
4247
|
-
// node_modules/.pnpm/@agentchatme+agent-core@0.
|
|
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)
|
|
@@ -4360,200 +4363,534 @@ var log = {
|
|
|
4360
4363
|
info: (msg) => emit("info", msg),
|
|
4361
4364
|
debug: (msg) => emit("debug", msg)
|
|
4362
4365
|
};
|
|
4363
|
-
var
|
|
4364
|
-
var
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
import * as path2 from "path";
|
|
4368
|
-
|
|
4369
|
-
// node_modules/.pnpm/agentchatme@1.3.0_ws@8.21.1/node_modules/agentchatme/dist/index.js
|
|
4370
|
-
var __defProp3 = Object.defineProperty;
|
|
4371
|
-
var __export3 = (target, all) => {
|
|
4372
|
-
for (var name in all)
|
|
4373
|
-
__defProp3(target, name, { get: all[name], enumerable: true });
|
|
4374
|
-
};
|
|
4375
|
-
var ErrorCode = {
|
|
4376
|
-
AGENT_NOT_FOUND: "AGENT_NOT_FOUND",
|
|
4377
|
-
AGENT_SUSPENDED: "AGENT_SUSPENDED",
|
|
4378
|
-
AGENT_PAUSED_BY_OWNER: "AGENT_PAUSED_BY_OWNER",
|
|
4379
|
-
HANDLE_TAKEN: "HANDLE_TAKEN",
|
|
4380
|
-
INVALID_HANDLE: "INVALID_HANDLE",
|
|
4381
|
-
/**
|
|
4382
|
-
* 409 from `POST /v1/register` (and `/register/verify`): the email already
|
|
4383
|
-
* backs the maximum number of live agents. The cap is server-tunable and
|
|
4384
|
-
* arrives in `details.limit`; deleting an agent frees a slot.
|
|
4385
|
-
*/
|
|
4386
|
-
EMAIL_LIMIT_REACHED: "EMAIL_LIMIT_REACHED",
|
|
4387
|
-
/**
|
|
4388
|
-
* 409 from `POST /v1/register` (and `/register/verify`): the email has
|
|
4389
|
-
* spent its lifetime registration budget (deleted agents included).
|
|
4390
|
-
* `details.limit` carries the cap; only a different email helps.
|
|
4391
|
-
*/
|
|
4392
|
-
EMAIL_EXHAUSTED: "EMAIL_EXHAUSTED",
|
|
4393
|
-
/**
|
|
4394
|
-
* Legacy spelling of `EMAIL_LIMIT_REACHED` from servers that still enforce
|
|
4395
|
-
* one live agent per email. Retired server-side; mapped to
|
|
4396
|
-
* `EmailLimitReachedError` so callers never branch on it.
|
|
4397
|
-
*/
|
|
4398
|
-
EMAIL_TAKEN: "EMAIL_TAKEN",
|
|
4399
|
-
/**
|
|
4400
|
-
* 409 from `POST /v1/agents/recover/verify`: the email backs more than one
|
|
4401
|
-
* agent and recovery was started without a `handle`. `details.handles`
|
|
4402
|
-
* lists the candidates; re-run `recover()` with one of them.
|
|
4403
|
-
*/
|
|
4404
|
-
HANDLE_REQUIRED: "HANDLE_REQUIRED",
|
|
4405
|
-
SUSPENDED: "SUSPENDED",
|
|
4406
|
-
RESTRICTED: "RESTRICTED",
|
|
4407
|
-
CONVERSATION_NOT_FOUND: "CONVERSATION_NOT_FOUND",
|
|
4408
|
-
MESSAGE_NOT_FOUND: "MESSAGE_NOT_FOUND",
|
|
4409
|
-
GROUP_DELETED: "GROUP_DELETED",
|
|
4410
|
-
RATE_LIMITED: "RATE_LIMITED",
|
|
4411
|
-
RECIPIENT_BACKLOGGED: "RECIPIENT_BACKLOGGED",
|
|
4412
|
-
AWAITING_REPLY: "AWAITING_REPLY",
|
|
4413
|
-
BLOCKED: "BLOCKED",
|
|
4414
|
-
UNAUTHORIZED: "UNAUTHORIZED",
|
|
4415
|
-
FORBIDDEN: "FORBIDDEN",
|
|
4416
|
-
VALIDATION_ERROR: "VALIDATION_ERROR",
|
|
4417
|
-
INTERNAL_ERROR: "INTERNAL_ERROR",
|
|
4418
|
-
OWNER_NOT_FOUND: "OWNER_NOT_FOUND",
|
|
4419
|
-
INVALID_API_KEY: "INVALID_API_KEY",
|
|
4420
|
-
ALREADY_CLAIMED: "ALREADY_CLAIMED",
|
|
4421
|
-
CLAIM_NOT_FOUND: "CLAIM_NOT_FOUND"
|
|
4422
|
-
};
|
|
4423
|
-
function parseRetryAfter(raw, now2 = Date.now()) {
|
|
4424
|
-
if (!raw) return null;
|
|
4425
|
-
const trimmed = raw.trim();
|
|
4426
|
-
if (!trimmed) return null;
|
|
4427
|
-
if (/^\d+$/.test(trimmed)) {
|
|
4428
|
-
const seconds = Number(trimmed);
|
|
4429
|
-
return Number.isFinite(seconds) ? seconds * 1e3 : null;
|
|
4430
|
-
}
|
|
4431
|
-
if (!/[a-zA-Z]/.test(trimmed)) return null;
|
|
4432
|
-
const epoch = Date.parse(trimmed);
|
|
4433
|
-
if (!Number.isFinite(epoch)) return null;
|
|
4434
|
-
return Math.max(0, epoch - now2);
|
|
4366
|
+
var RUN_PROFILES = ["answer", "work", "full"];
|
|
4367
|
+
var PEER_RUN_WARNING = "runs started by peers' messages can read and change this machine";
|
|
4368
|
+
function runProfileWarning(profile2) {
|
|
4369
|
+
return profile2 === "work" || profile2 === "full" ? PEER_RUN_WARNING : null;
|
|
4435
4370
|
}
|
|
4436
|
-
|
|
4437
|
-
|
|
4438
|
-
|
|
4439
|
-
|
|
4440
|
-
|
|
4441
|
-
|
|
4442
|
-
* Include it in bug reports — the operator can look up the full
|
|
4443
|
-
* server-side trace in seconds.
|
|
4444
|
-
*/
|
|
4445
|
-
requestId;
|
|
4446
|
-
constructor(response, status, requestId = null) {
|
|
4447
|
-
super(response.message);
|
|
4448
|
-
this.name = "AgentChatError";
|
|
4449
|
-
this.code = response.code;
|
|
4450
|
-
this.status = status;
|
|
4451
|
-
this.details = response.details;
|
|
4452
|
-
this.requestId = requestId;
|
|
4453
|
-
Object.setPrototypeOf(this, new.target.prototype);
|
|
4454
|
-
}
|
|
4455
|
-
};
|
|
4456
|
-
var RateLimitedError = class extends AgentChatError {
|
|
4457
|
-
retryAfterMs;
|
|
4458
|
-
constructor(response, status, retryAfterMs, requestId = null) {
|
|
4459
|
-
super(response, status, requestId);
|
|
4460
|
-
this.name = "RateLimitedError";
|
|
4461
|
-
this.retryAfterMs = retryAfterMs;
|
|
4462
|
-
}
|
|
4463
|
-
};
|
|
4464
|
-
var SuspendedError = class extends AgentChatError {
|
|
4465
|
-
constructor(response, status, requestId = null) {
|
|
4466
|
-
super(response, status, requestId);
|
|
4467
|
-
this.name = "SuspendedError";
|
|
4468
|
-
}
|
|
4469
|
-
};
|
|
4470
|
-
var RestrictedError = class extends AgentChatError {
|
|
4471
|
-
constructor(response, status, requestId = null) {
|
|
4472
|
-
super(response, status, requestId);
|
|
4473
|
-
this.name = "RestrictedError";
|
|
4474
|
-
}
|
|
4475
|
-
};
|
|
4476
|
-
var RecipientBackloggedError = class extends AgentChatError {
|
|
4477
|
-
recipientHandle;
|
|
4478
|
-
undeliveredCount;
|
|
4479
|
-
constructor(response, status, requestId = null) {
|
|
4480
|
-
super(response, status, requestId);
|
|
4481
|
-
this.name = "RecipientBackloggedError";
|
|
4482
|
-
const d = response.details;
|
|
4483
|
-
this.recipientHandle = typeof d?.recipient_handle === "string" ? d.recipient_handle : null;
|
|
4484
|
-
this.undeliveredCount = typeof d?.undelivered_count === "number" ? d.undelivered_count : null;
|
|
4485
|
-
}
|
|
4486
|
-
};
|
|
4487
|
-
var AwaitingReplyError = class extends AgentChatError {
|
|
4488
|
-
recipientHandle;
|
|
4489
|
-
waitingSince;
|
|
4490
|
-
constructor(response, status, requestId = null) {
|
|
4491
|
-
super(response, status, requestId);
|
|
4492
|
-
this.name = "AwaitingReplyError";
|
|
4493
|
-
const d = response.details;
|
|
4494
|
-
this.recipientHandle = typeof d?.recipient_handle === "string" ? d.recipient_handle : null;
|
|
4495
|
-
this.waitingSince = typeof d?.waiting_since === "string" ? d.waiting_since : null;
|
|
4496
|
-
}
|
|
4497
|
-
};
|
|
4498
|
-
var BlockedError = class extends AgentChatError {
|
|
4499
|
-
constructor(response, status, requestId = null) {
|
|
4500
|
-
super(response, status, requestId);
|
|
4501
|
-
this.name = "BlockedError";
|
|
4502
|
-
}
|
|
4503
|
-
};
|
|
4504
|
-
var ValidationError = class extends AgentChatError {
|
|
4505
|
-
constructor(response, status, requestId = null) {
|
|
4506
|
-
super(response, status, requestId);
|
|
4507
|
-
this.name = "ValidationError";
|
|
4508
|
-
}
|
|
4509
|
-
};
|
|
4510
|
-
var UnauthorizedError = class extends AgentChatError {
|
|
4511
|
-
constructor(response, status, requestId = null) {
|
|
4512
|
-
super(response, status, requestId);
|
|
4513
|
-
this.name = "UnauthorizedError";
|
|
4371
|
+
function identityOf(dir) {
|
|
4372
|
+
try {
|
|
4373
|
+
const st = fs2.statSync(dir, { bigint: true });
|
|
4374
|
+
return st.ino === 0n ? null : `${st.dev}:${st.ino}`;
|
|
4375
|
+
} catch {
|
|
4376
|
+
return null;
|
|
4514
4377
|
}
|
|
4515
|
-
}
|
|
4516
|
-
|
|
4517
|
-
|
|
4518
|
-
|
|
4519
|
-
|
|
4378
|
+
}
|
|
4379
|
+
function realOrResolved(p) {
|
|
4380
|
+
const resolved = path2.resolve(p);
|
|
4381
|
+
try {
|
|
4382
|
+
return fs2.realpathSync.native(resolved);
|
|
4383
|
+
} catch {
|
|
4384
|
+
return resolved;
|
|
4520
4385
|
}
|
|
4521
|
-
}
|
|
4522
|
-
|
|
4523
|
-
|
|
4524
|
-
|
|
4525
|
-
|
|
4386
|
+
}
|
|
4387
|
+
function spelling(p) {
|
|
4388
|
+
return process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p;
|
|
4389
|
+
}
|
|
4390
|
+
function workdirExposesHome(workdir, home = os.homedir()) {
|
|
4391
|
+
const dir = realOrResolved(workdir);
|
|
4392
|
+
if (dir === path2.parse(dir).root) return true;
|
|
4393
|
+
const homes = [.../* @__PURE__ */ new Set([path2.resolve(home), realOrResolved(home)])];
|
|
4394
|
+
const homeIds = new Set(homes.map(identityOf).filter((id) => id !== null));
|
|
4395
|
+
for (const h of homes) {
|
|
4396
|
+
const parts = h.slice(path2.parse(h).root.length).split(path2.sep).filter((part) => part.length > 0);
|
|
4397
|
+
for (let i = 0; i <= parts.length; i++) {
|
|
4398
|
+
const candidate = path2.join(dir, ...parts.slice(i));
|
|
4399
|
+
const id = identityOf(candidate);
|
|
4400
|
+
if (id !== null ? homeIds.has(id) : spelling(realOrResolved(candidate)) === spelling(realOrResolved(h)) && fs2.existsSync(candidate)) return true;
|
|
4401
|
+
}
|
|
4526
4402
|
}
|
|
4527
|
-
|
|
4528
|
-
|
|
4529
|
-
|
|
4530
|
-
|
|
4531
|
-
|
|
4532
|
-
|
|
4533
|
-
|
|
4534
|
-
|
|
4535
|
-
|
|
4536
|
-
|
|
4537
|
-
|
|
4538
|
-
|
|
4403
|
+
return false;
|
|
4404
|
+
}
|
|
4405
|
+
var RUN_PROFILE_ENV = "AGENTCHAT_RUN_PROFILE";
|
|
4406
|
+
var DEFAULT_RUN_PROFILE = "answer";
|
|
4407
|
+
function isRunProfile(value) {
|
|
4408
|
+
return typeof value === "string" && RUN_PROFILES.includes(value);
|
|
4409
|
+
}
|
|
4410
|
+
function resolveRunProfile(env = process.env) {
|
|
4411
|
+
const raw = env[RUN_PROFILE_ENV]?.trim().toLowerCase();
|
|
4412
|
+
return isRunProfile(raw) ? raw : DEFAULT_RUN_PROFILE;
|
|
4413
|
+
}
|
|
4414
|
+
var INTEGRATION_ENV = "AGENTCHAT_INTEGRATION";
|
|
4415
|
+
var INTEGRATION_ENV_LEGACY = "AGENTCHAT_DOORBELL";
|
|
4416
|
+
var INTEGRATION_ENV_LEGACY_REMOVAL = "2027-02-01";
|
|
4417
|
+
function isOff(raw) {
|
|
4418
|
+
const value = raw?.trim().toLowerCase();
|
|
4419
|
+
return value === "off" || value === "0" || value === "false";
|
|
4420
|
+
}
|
|
4421
|
+
function integrationDisabledBy(env = process.env) {
|
|
4422
|
+
if (env[INTEGRATION_ENV] !== void 0 && env[INTEGRATION_ENV].trim().length > 0) {
|
|
4423
|
+
return isOff(env[INTEGRATION_ENV]) ? INTEGRATION_ENV : null;
|
|
4539
4424
|
}
|
|
4540
|
-
|
|
4541
|
-
function policyLimit(details) {
|
|
4542
|
-
const limit = details?.limit;
|
|
4543
|
-
return typeof limit === "number" && Number.isInteger(limit) ? limit : null;
|
|
4425
|
+
return isOff(env[INTEGRATION_ENV_LEGACY]) ? INTEGRATION_ENV_LEGACY : null;
|
|
4544
4426
|
}
|
|
4545
|
-
|
|
4546
|
-
|
|
4547
|
-
|
|
4548
|
-
|
|
4549
|
-
|
|
4550
|
-
|
|
4427
|
+
function integrationDisabled(env = process.env) {
|
|
4428
|
+
return integrationDisabledBy(env) !== null;
|
|
4429
|
+
}
|
|
4430
|
+
var RUN_BUDGET_ENV = "AGENTCHAT_RUN_BUDGET_MS";
|
|
4431
|
+
var DEFAULT_RUN_BUDGET_MS = 10 * 6e4;
|
|
4432
|
+
var MAX_RUN_BUDGET_MS = 2 * 60 * 6e4;
|
|
4433
|
+
var spawnCommand = import_cross_spawn.default;
|
|
4434
|
+
var spawnCommandSync = import_cross_spawn.default.sync;
|
|
4435
|
+
var DEFAULT_GRACE_MS = 5e3;
|
|
4436
|
+
var DEFAULT_DRAIN_MS = 2e3;
|
|
4437
|
+
var DEFAULT_ABANDON_MS = 5e3;
|
|
4438
|
+
var STDERR_TAIL_CHARS = 400;
|
|
4439
|
+
function redactDiagnostic(value, max = STDERR_TAIL_CHARS) {
|
|
4440
|
+
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);
|
|
4441
|
+
}
|
|
4442
|
+
var KILL_TIMEOUT_MS = 5e3;
|
|
4443
|
+
function killProcessTree(child, signal) {
|
|
4444
|
+
if (child.pid === void 0) return;
|
|
4445
|
+
try {
|
|
4446
|
+
if (process.platform === "win32") {
|
|
4447
|
+
spawnCommandSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
4448
|
+
windowsHide: true,
|
|
4449
|
+
stdio: "ignore",
|
|
4450
|
+
timeout: KILL_TIMEOUT_MS
|
|
4451
|
+
});
|
|
4452
|
+
} else {
|
|
4453
|
+
process.kill(-child.pid, signal);
|
|
4454
|
+
}
|
|
4455
|
+
} catch {
|
|
4456
|
+
try {
|
|
4457
|
+
child.kill(signal);
|
|
4458
|
+
} catch {
|
|
4459
|
+
}
|
|
4551
4460
|
}
|
|
4552
|
-
}
|
|
4553
|
-
|
|
4554
|
-
|
|
4555
|
-
|
|
4556
|
-
|
|
4461
|
+
}
|
|
4462
|
+
function fileTime(ms) {
|
|
4463
|
+
return String((BigInt(Math.round(ms)) + 11644473600000n) * 10000n);
|
|
4464
|
+
}
|
|
4465
|
+
var WINDOWS_SWEEP_TIMEOUT_MS = 6e4;
|
|
4466
|
+
function sweepWindowsDescendants(rootPid, aliveFromMs, aliveUntilMs, options = {}) {
|
|
4467
|
+
if (process.platform !== "win32" || !Number.isInteger(rootPid) || rootPid <= 0) return Promise.resolve(null);
|
|
4468
|
+
const script = [
|
|
4469
|
+
"$ErrorActionPreference = 'Continue'",
|
|
4470
|
+
// Progress records ('Preparing modules for first use') would reach stderr as CLIXML.
|
|
4471
|
+
"$ProgressPreference = 'SilentlyContinue'",
|
|
4472
|
+
`$from = [DateTime]::FromFileTime(${fileTime(aliveFromMs - 1e3)})`,
|
|
4473
|
+
`$until = [DateTime]::FromFileTime(${fileTime(aliveUntilMs + 1e3)})`,
|
|
4474
|
+
"Write-Output ('window ' + $from.ToUniversalTime().ToString('o') + ' ' + $until.ToUniversalTime().ToString('o'))",
|
|
4475
|
+
`foreach ($p in @(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${rootPid}')) {`,
|
|
4476
|
+
" Write-Output ('candidate ' + $p.ProcessId + ' ' + $p.CreationDate.ToUniversalTime().ToString('o'))",
|
|
4477
|
+
" if ($p.CreationDate -ge $from -and $p.CreationDate -le $until) {",
|
|
4478
|
+
" & taskkill.exe /T /F /PID $p.ProcessId 2>&1 | Out-Null",
|
|
4479
|
+
" Write-Output ('kill ' + $p.ProcessId + ' ' + $LASTEXITCODE)",
|
|
4480
|
+
" }",
|
|
4481
|
+
"}"
|
|
4482
|
+
].join("\n");
|
|
4483
|
+
return new Promise((resolve22) => {
|
|
4484
|
+
let stdout = "";
|
|
4485
|
+
let stderr = "";
|
|
4486
|
+
let timedOut = false;
|
|
4487
|
+
let done = false;
|
|
4488
|
+
const finish = (exitCode) => {
|
|
4489
|
+
if (done) return;
|
|
4490
|
+
done = true;
|
|
4491
|
+
clearTimeout(timer);
|
|
4492
|
+
const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
|
|
4493
|
+
resolve22({
|
|
4494
|
+
exitCode,
|
|
4495
|
+
timedOut,
|
|
4496
|
+
candidates: lines.filter((l) => l.startsWith("candidate ")).map((l) => l.slice("candidate ".length)),
|
|
4497
|
+
killed: lines.filter((l) => l.startsWith("kill ")).map((l) => l.split(" ")).map(([, pid, code]) => ({ pid: Number(pid), code: Number(code) })),
|
|
4498
|
+
window: lines.find((l) => l.startsWith("window "))?.slice("window ".length) ?? null,
|
|
4499
|
+
stderr: redactDiagnostic(stderr)
|
|
4500
|
+
});
|
|
4501
|
+
};
|
|
4502
|
+
let sweeper;
|
|
4503
|
+
try {
|
|
4504
|
+
sweeper = spawnCommand(
|
|
4505
|
+
"powershell.exe",
|
|
4506
|
+
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")],
|
|
4507
|
+
{ stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
|
|
4508
|
+
);
|
|
4509
|
+
} catch (err) {
|
|
4510
|
+
stderr = String(err);
|
|
4511
|
+
finish(null);
|
|
4512
|
+
return;
|
|
4513
|
+
}
|
|
4514
|
+
const timer = setTimeout(() => {
|
|
4515
|
+
timedOut = true;
|
|
4516
|
+
try {
|
|
4517
|
+
sweeper.kill();
|
|
4518
|
+
} catch {
|
|
4519
|
+
}
|
|
4520
|
+
finish(null);
|
|
4521
|
+
}, options.timeoutMs ?? WINDOWS_SWEEP_TIMEOUT_MS);
|
|
4522
|
+
timer.unref?.();
|
|
4523
|
+
sweeper.stdout?.on("data", (c) => {
|
|
4524
|
+
stdout = (stdout + String(c)).slice(-16e3);
|
|
4525
|
+
});
|
|
4526
|
+
sweeper.stderr?.on("data", (c) => {
|
|
4527
|
+
stderr = (stderr + String(c)).slice(-4e3);
|
|
4528
|
+
});
|
|
4529
|
+
sweeper.on("error", (err) => {
|
|
4530
|
+
stderr += String(err);
|
|
4531
|
+
finish(null);
|
|
4532
|
+
});
|
|
4533
|
+
sweeper.on("close", (code) => finish(code));
|
|
4534
|
+
});
|
|
4535
|
+
}
|
|
4536
|
+
function describeWindowsSweep(sweep) {
|
|
4537
|
+
const killed = sweep.killed.map((k) => `${k.pid} (taskkill ${k.code})`).join(", ") || "none";
|
|
4538
|
+
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}` : ""}`;
|
|
4539
|
+
}
|
|
4540
|
+
function spawnRun(spec) {
|
|
4541
|
+
const started = Date.now();
|
|
4542
|
+
const graceMs = spec.graceMs ?? DEFAULT_GRACE_MS;
|
|
4543
|
+
const drainMs = spec.drainMs ?? DEFAULT_DRAIN_MS;
|
|
4544
|
+
const abandonMs = spec.abandonMs ?? DEFAULT_ABANDON_MS;
|
|
4545
|
+
return new Promise((resolve22) => {
|
|
4546
|
+
let settled = false;
|
|
4547
|
+
let stdoutBytes = 0;
|
|
4548
|
+
let stderrTail = "";
|
|
4549
|
+
let timedOut = false;
|
|
4550
|
+
let interrupted = false;
|
|
4551
|
+
let terminating = false;
|
|
4552
|
+
let exited = null;
|
|
4553
|
+
const timers = /* @__PURE__ */ new Set();
|
|
4554
|
+
let onAbort = null;
|
|
4555
|
+
let child = null;
|
|
4556
|
+
const later = (ms, fn) => {
|
|
4557
|
+
const timer = setTimeout(() => {
|
|
4558
|
+
timers.delete(timer);
|
|
4559
|
+
fn();
|
|
4560
|
+
}, ms);
|
|
4561
|
+
timers.add(timer);
|
|
4562
|
+
};
|
|
4563
|
+
const finish = (outcome) => {
|
|
4564
|
+
if (settled) return;
|
|
4565
|
+
settled = true;
|
|
4566
|
+
for (const timer of timers) clearTimeout(timer);
|
|
4567
|
+
timers.clear();
|
|
4568
|
+
if (onAbort) spec.signal?.removeEventListener("abort", onAbort);
|
|
4569
|
+
resolve22({ ...outcome, durationMs: Date.now() - started });
|
|
4570
|
+
};
|
|
4571
|
+
const detach = () => {
|
|
4572
|
+
if (child === null) return;
|
|
4573
|
+
for (const stream of [child.stdin, child.stdout, child.stderr]) {
|
|
4574
|
+
try {
|
|
4575
|
+
stream?.destroy();
|
|
4576
|
+
} catch {
|
|
4577
|
+
}
|
|
4578
|
+
}
|
|
4579
|
+
try {
|
|
4580
|
+
child.unref();
|
|
4581
|
+
} catch {
|
|
4582
|
+
}
|
|
4583
|
+
};
|
|
4584
|
+
const classify = (code, signal, note) => {
|
|
4585
|
+
const tail = redactDiagnostic(stderrTail);
|
|
4586
|
+
const extra = `${note ? ` (${note})` : ""}${tail ? `: ${tail}` : ""}`;
|
|
4587
|
+
if (timedOut) {
|
|
4588
|
+
return { state: "timed_out", exitCode: code, detail: `run exceeded its ${Math.round(spec.budgetMs / 1e3)} s budget and was killed${extra}` };
|
|
4589
|
+
}
|
|
4590
|
+
if (interrupted) {
|
|
4591
|
+
return { state: "failed", exitCode: code, detail: `interrupted \u2014 the integration was stopping; the tray stays unread for the next run${extra}` };
|
|
4592
|
+
}
|
|
4593
|
+
if (code === 0) return note ? { state: "ok", exitCode: 0, detail: note } : { state: "ok", exitCode: 0 };
|
|
4594
|
+
const exit = code === null ? `signal ${signal ?? "unknown"}` : `exit ${code}`;
|
|
4595
|
+
if (stdoutBytes === 0) return { state: "not_started", exitCode: code, detail: `${exit} with nothing on stdout${extra}` };
|
|
4596
|
+
return { state: "failed", exitCode: code, detail: `${exit}${extra}` };
|
|
4597
|
+
};
|
|
4598
|
+
if (spec.signal?.aborted) {
|
|
4599
|
+
finish({ state: "not_started", exitCode: null, detail: "interrupted before the runtime was started" });
|
|
4600
|
+
return;
|
|
4601
|
+
}
|
|
4602
|
+
try {
|
|
4603
|
+
child = spawnCommand(spec.command, [...spec.args], {
|
|
4604
|
+
cwd: spec.cwd,
|
|
4605
|
+
env: spec.env,
|
|
4606
|
+
stdio: [spec.stdin === null ? "ignore" : "pipe", "pipe", "pipe"],
|
|
4607
|
+
detached: process.platform !== "win32",
|
|
4608
|
+
windowsHide: true,
|
|
4609
|
+
...spec.shell === true ? { shell: true } : {}
|
|
4610
|
+
});
|
|
4611
|
+
} catch (err) {
|
|
4612
|
+
finish({ state: "not_started", exitCode: null, detail: redactDiagnostic(String(err)) });
|
|
4613
|
+
return;
|
|
4614
|
+
}
|
|
4615
|
+
const proc = child;
|
|
4616
|
+
if (spec.onStarted) {
|
|
4617
|
+
const onStarted = spec.onStarted;
|
|
4618
|
+
proc.once("spawn", () => {
|
|
4619
|
+
try {
|
|
4620
|
+
onStarted();
|
|
4621
|
+
} catch {
|
|
4622
|
+
}
|
|
4623
|
+
});
|
|
4624
|
+
}
|
|
4625
|
+
proc.stdout?.on("data", (chunk) => {
|
|
4626
|
+
stdoutBytes += chunk.length;
|
|
4627
|
+
});
|
|
4628
|
+
proc.stderr?.on("data", (chunk) => {
|
|
4629
|
+
stderrTail = (stderrTail + String(chunk)).slice(-4 * STDERR_TAIL_CHARS);
|
|
4630
|
+
});
|
|
4631
|
+
proc.stdout?.on("error", () => void 0);
|
|
4632
|
+
proc.stderr?.on("error", () => void 0);
|
|
4633
|
+
if (spec.stdin !== null && proc.stdin) {
|
|
4634
|
+
proc.stdin.on("error", () => {
|
|
4635
|
+
});
|
|
4636
|
+
try {
|
|
4637
|
+
proc.stdin.write(spec.stdin);
|
|
4638
|
+
proc.stdin.end();
|
|
4639
|
+
} catch {
|
|
4640
|
+
}
|
|
4641
|
+
}
|
|
4642
|
+
const terminate = () => {
|
|
4643
|
+
if (terminating || settled) return;
|
|
4644
|
+
terminating = true;
|
|
4645
|
+
killProcessTree(proc, "SIGTERM");
|
|
4646
|
+
later(graceMs, () => {
|
|
4647
|
+
if (settled) return;
|
|
4648
|
+
killProcessTree(proc, "SIGKILL");
|
|
4649
|
+
later(abandonMs, () => {
|
|
4650
|
+
if (settled) return;
|
|
4651
|
+
if (exited !== null) return;
|
|
4652
|
+
detach();
|
|
4653
|
+
const tail = redactDiagnostic(stderrTail);
|
|
4654
|
+
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}` : ""}`;
|
|
4655
|
+
finish(
|
|
4656
|
+
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}` }
|
|
4657
|
+
);
|
|
4658
|
+
});
|
|
4659
|
+
});
|
|
4660
|
+
};
|
|
4661
|
+
later(spec.budgetMs, () => {
|
|
4662
|
+
if (exited !== null) return;
|
|
4663
|
+
timedOut = true;
|
|
4664
|
+
terminate();
|
|
4665
|
+
});
|
|
4666
|
+
if (spec.signal) {
|
|
4667
|
+
onAbort = () => {
|
|
4668
|
+
if (settled) return;
|
|
4669
|
+
interrupted = true;
|
|
4670
|
+
terminate();
|
|
4671
|
+
};
|
|
4672
|
+
spec.signal.addEventListener("abort", onAbort, { once: true });
|
|
4673
|
+
}
|
|
4674
|
+
proc.on("error", (err) => {
|
|
4675
|
+
finish({ state: "not_started", exitCode: null, detail: redactDiagnostic(String(err)) });
|
|
4676
|
+
});
|
|
4677
|
+
proc.on("exit", (code, signal) => {
|
|
4678
|
+
exited = { code, signal, at: Date.now() };
|
|
4679
|
+
later(drainMs, () => {
|
|
4680
|
+
if (settled || exited === null) return;
|
|
4681
|
+
killProcessTree(proc, "SIGKILL");
|
|
4682
|
+
if (proc.pid !== void 0) {
|
|
4683
|
+
void sweepWindowsDescendants(proc.pid, started, exited.at).then((sweep) => {
|
|
4684
|
+
if (sweep !== null) (sweep.exitCode === 0 ? log.info : log.warn)(describeWindowsSweep(sweep));
|
|
4685
|
+
});
|
|
4686
|
+
}
|
|
4687
|
+
detach();
|
|
4688
|
+
finish(
|
|
4689
|
+
classify(
|
|
4690
|
+
exited.code,
|
|
4691
|
+
exited.signal,
|
|
4692
|
+
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"
|
|
4693
|
+
)
|
|
4694
|
+
);
|
|
4695
|
+
});
|
|
4696
|
+
});
|
|
4697
|
+
proc.on("close", (code, signal) => {
|
|
4698
|
+
finish(classify(code, signal, null));
|
|
4699
|
+
});
|
|
4700
|
+
});
|
|
4701
|
+
}
|
|
4702
|
+
|
|
4703
|
+
// node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/chunk-NAAHIK7Z.js
|
|
4704
|
+
import * as path3 from "path";
|
|
4705
|
+
|
|
4706
|
+
// node_modules/.pnpm/agentchatme@1.3.0_ws@8.21.1/node_modules/agentchatme/dist/index.js
|
|
4707
|
+
var __defProp3 = Object.defineProperty;
|
|
4708
|
+
var __export3 = (target, all) => {
|
|
4709
|
+
for (var name in all)
|
|
4710
|
+
__defProp3(target, name, { get: all[name], enumerable: true });
|
|
4711
|
+
};
|
|
4712
|
+
var ErrorCode = {
|
|
4713
|
+
AGENT_NOT_FOUND: "AGENT_NOT_FOUND",
|
|
4714
|
+
AGENT_SUSPENDED: "AGENT_SUSPENDED",
|
|
4715
|
+
AGENT_PAUSED_BY_OWNER: "AGENT_PAUSED_BY_OWNER",
|
|
4716
|
+
HANDLE_TAKEN: "HANDLE_TAKEN",
|
|
4717
|
+
INVALID_HANDLE: "INVALID_HANDLE",
|
|
4718
|
+
/**
|
|
4719
|
+
* 409 from `POST /v1/register` (and `/register/verify`): the email already
|
|
4720
|
+
* backs the maximum number of live agents. The cap is server-tunable and
|
|
4721
|
+
* arrives in `details.limit`; deleting an agent frees a slot.
|
|
4722
|
+
*/
|
|
4723
|
+
EMAIL_LIMIT_REACHED: "EMAIL_LIMIT_REACHED",
|
|
4724
|
+
/**
|
|
4725
|
+
* 409 from `POST /v1/register` (and `/register/verify`): the email has
|
|
4726
|
+
* spent its lifetime registration budget (deleted agents included).
|
|
4727
|
+
* `details.limit` carries the cap; only a different email helps.
|
|
4728
|
+
*/
|
|
4729
|
+
EMAIL_EXHAUSTED: "EMAIL_EXHAUSTED",
|
|
4730
|
+
/**
|
|
4731
|
+
* Legacy spelling of `EMAIL_LIMIT_REACHED` from servers that still enforce
|
|
4732
|
+
* one live agent per email. Retired server-side; mapped to
|
|
4733
|
+
* `EmailLimitReachedError` so callers never branch on it.
|
|
4734
|
+
*/
|
|
4735
|
+
EMAIL_TAKEN: "EMAIL_TAKEN",
|
|
4736
|
+
/**
|
|
4737
|
+
* 409 from `POST /v1/agents/recover/verify`: the email backs more than one
|
|
4738
|
+
* agent and recovery was started without a `handle`. `details.handles`
|
|
4739
|
+
* lists the candidates; re-run `recover()` with one of them.
|
|
4740
|
+
*/
|
|
4741
|
+
HANDLE_REQUIRED: "HANDLE_REQUIRED",
|
|
4742
|
+
SUSPENDED: "SUSPENDED",
|
|
4743
|
+
RESTRICTED: "RESTRICTED",
|
|
4744
|
+
CONVERSATION_NOT_FOUND: "CONVERSATION_NOT_FOUND",
|
|
4745
|
+
MESSAGE_NOT_FOUND: "MESSAGE_NOT_FOUND",
|
|
4746
|
+
GROUP_DELETED: "GROUP_DELETED",
|
|
4747
|
+
RATE_LIMITED: "RATE_LIMITED",
|
|
4748
|
+
RECIPIENT_BACKLOGGED: "RECIPIENT_BACKLOGGED",
|
|
4749
|
+
AWAITING_REPLY: "AWAITING_REPLY",
|
|
4750
|
+
BLOCKED: "BLOCKED",
|
|
4751
|
+
UNAUTHORIZED: "UNAUTHORIZED",
|
|
4752
|
+
FORBIDDEN: "FORBIDDEN",
|
|
4753
|
+
VALIDATION_ERROR: "VALIDATION_ERROR",
|
|
4754
|
+
INTERNAL_ERROR: "INTERNAL_ERROR",
|
|
4755
|
+
OWNER_NOT_FOUND: "OWNER_NOT_FOUND",
|
|
4756
|
+
INVALID_API_KEY: "INVALID_API_KEY",
|
|
4757
|
+
ALREADY_CLAIMED: "ALREADY_CLAIMED",
|
|
4758
|
+
CLAIM_NOT_FOUND: "CLAIM_NOT_FOUND"
|
|
4759
|
+
};
|
|
4760
|
+
function parseRetryAfter(raw, now2 = Date.now()) {
|
|
4761
|
+
if (!raw) return null;
|
|
4762
|
+
const trimmed = raw.trim();
|
|
4763
|
+
if (!trimmed) return null;
|
|
4764
|
+
if (/^\d+$/.test(trimmed)) {
|
|
4765
|
+
const seconds = Number(trimmed);
|
|
4766
|
+
return Number.isFinite(seconds) ? seconds * 1e3 : null;
|
|
4767
|
+
}
|
|
4768
|
+
if (!/[a-zA-Z]/.test(trimmed)) return null;
|
|
4769
|
+
const epoch = Date.parse(trimmed);
|
|
4770
|
+
if (!Number.isFinite(epoch)) return null;
|
|
4771
|
+
return Math.max(0, epoch - now2);
|
|
4772
|
+
}
|
|
4773
|
+
var AgentChatError = class extends Error {
|
|
4774
|
+
code;
|
|
4775
|
+
status;
|
|
4776
|
+
details;
|
|
4777
|
+
/**
|
|
4778
|
+
* The server's `x-request-id` for the failing request, when present.
|
|
4779
|
+
* Include it in bug reports — the operator can look up the full
|
|
4780
|
+
* server-side trace in seconds.
|
|
4781
|
+
*/
|
|
4782
|
+
requestId;
|
|
4783
|
+
constructor(response, status, requestId = null) {
|
|
4784
|
+
super(response.message);
|
|
4785
|
+
this.name = "AgentChatError";
|
|
4786
|
+
this.code = response.code;
|
|
4787
|
+
this.status = status;
|
|
4788
|
+
this.details = response.details;
|
|
4789
|
+
this.requestId = requestId;
|
|
4790
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
4791
|
+
}
|
|
4792
|
+
};
|
|
4793
|
+
var RateLimitedError = class extends AgentChatError {
|
|
4794
|
+
retryAfterMs;
|
|
4795
|
+
constructor(response, status, retryAfterMs, requestId = null) {
|
|
4796
|
+
super(response, status, requestId);
|
|
4797
|
+
this.name = "RateLimitedError";
|
|
4798
|
+
this.retryAfterMs = retryAfterMs;
|
|
4799
|
+
}
|
|
4800
|
+
};
|
|
4801
|
+
var SuspendedError = class extends AgentChatError {
|
|
4802
|
+
constructor(response, status, requestId = null) {
|
|
4803
|
+
super(response, status, requestId);
|
|
4804
|
+
this.name = "SuspendedError";
|
|
4805
|
+
}
|
|
4806
|
+
};
|
|
4807
|
+
var RestrictedError = class extends AgentChatError {
|
|
4808
|
+
constructor(response, status, requestId = null) {
|
|
4809
|
+
super(response, status, requestId);
|
|
4810
|
+
this.name = "RestrictedError";
|
|
4811
|
+
}
|
|
4812
|
+
};
|
|
4813
|
+
var RecipientBackloggedError = class extends AgentChatError {
|
|
4814
|
+
recipientHandle;
|
|
4815
|
+
undeliveredCount;
|
|
4816
|
+
constructor(response, status, requestId = null) {
|
|
4817
|
+
super(response, status, requestId);
|
|
4818
|
+
this.name = "RecipientBackloggedError";
|
|
4819
|
+
const d = response.details;
|
|
4820
|
+
this.recipientHandle = typeof d?.recipient_handle === "string" ? d.recipient_handle : null;
|
|
4821
|
+
this.undeliveredCount = typeof d?.undelivered_count === "number" ? d.undelivered_count : null;
|
|
4822
|
+
}
|
|
4823
|
+
};
|
|
4824
|
+
var AwaitingReplyError = class extends AgentChatError {
|
|
4825
|
+
recipientHandle;
|
|
4826
|
+
waitingSince;
|
|
4827
|
+
constructor(response, status, requestId = null) {
|
|
4828
|
+
super(response, status, requestId);
|
|
4829
|
+
this.name = "AwaitingReplyError";
|
|
4830
|
+
const d = response.details;
|
|
4831
|
+
this.recipientHandle = typeof d?.recipient_handle === "string" ? d.recipient_handle : null;
|
|
4832
|
+
this.waitingSince = typeof d?.waiting_since === "string" ? d.waiting_since : null;
|
|
4833
|
+
}
|
|
4834
|
+
};
|
|
4835
|
+
var BlockedError = class extends AgentChatError {
|
|
4836
|
+
constructor(response, status, requestId = null) {
|
|
4837
|
+
super(response, status, requestId);
|
|
4838
|
+
this.name = "BlockedError";
|
|
4839
|
+
}
|
|
4840
|
+
};
|
|
4841
|
+
var ValidationError = class extends AgentChatError {
|
|
4842
|
+
constructor(response, status, requestId = null) {
|
|
4843
|
+
super(response, status, requestId);
|
|
4844
|
+
this.name = "ValidationError";
|
|
4845
|
+
}
|
|
4846
|
+
};
|
|
4847
|
+
var UnauthorizedError = class extends AgentChatError {
|
|
4848
|
+
constructor(response, status, requestId = null) {
|
|
4849
|
+
super(response, status, requestId);
|
|
4850
|
+
this.name = "UnauthorizedError";
|
|
4851
|
+
}
|
|
4852
|
+
};
|
|
4853
|
+
var ForbiddenError = class extends AgentChatError {
|
|
4854
|
+
constructor(response, status, requestId = null) {
|
|
4855
|
+
super(response, status, requestId);
|
|
4856
|
+
this.name = "ForbiddenError";
|
|
4857
|
+
}
|
|
4858
|
+
};
|
|
4859
|
+
var NotFoundError = class extends AgentChatError {
|
|
4860
|
+
constructor(response, status, requestId = null) {
|
|
4861
|
+
super(response, status, requestId);
|
|
4862
|
+
this.name = "NotFoundError";
|
|
4863
|
+
}
|
|
4864
|
+
};
|
|
4865
|
+
var GroupDeletedError = class extends AgentChatError {
|
|
4866
|
+
groupId;
|
|
4867
|
+
deletedByHandle;
|
|
4868
|
+
deletedAt;
|
|
4869
|
+
constructor(response, status, requestId = null) {
|
|
4870
|
+
super(response, status, requestId);
|
|
4871
|
+
this.name = "GroupDeletedError";
|
|
4872
|
+
const d = response.details;
|
|
4873
|
+
this.groupId = typeof d?.group_id === "string" ? d.group_id : null;
|
|
4874
|
+
this.deletedByHandle = typeof d?.deleted_by_handle === "string" ? d.deleted_by_handle : null;
|
|
4875
|
+
this.deletedAt = typeof d?.deleted_at === "string" ? d.deleted_at : null;
|
|
4876
|
+
}
|
|
4877
|
+
};
|
|
4878
|
+
function policyLimit(details) {
|
|
4879
|
+
const limit = details?.limit;
|
|
4880
|
+
return typeof limit === "number" && Number.isInteger(limit) ? limit : null;
|
|
4881
|
+
}
|
|
4882
|
+
var EmailLimitReachedError = class extends AgentChatError {
|
|
4883
|
+
limit;
|
|
4884
|
+
constructor(response, status, requestId = null) {
|
|
4885
|
+
super(response, status, requestId);
|
|
4886
|
+
this.name = "EmailLimitReachedError";
|
|
4887
|
+
this.limit = policyLimit(response.details);
|
|
4888
|
+
}
|
|
4889
|
+
};
|
|
4890
|
+
var EmailExhaustedError = class extends AgentChatError {
|
|
4891
|
+
limit;
|
|
4892
|
+
constructor(response, status, requestId = null) {
|
|
4893
|
+
super(response, status, requestId);
|
|
4557
4894
|
this.name = "EmailExhaustedError";
|
|
4558
4895
|
this.limit = policyLimit(response.details);
|
|
4559
4896
|
}
|
|
@@ -4689,8 +5026,8 @@ var HttpTransport = class {
|
|
|
4689
5026
|
}
|
|
4690
5027
|
this.fetchFn = f.bind(globalThis);
|
|
4691
5028
|
}
|
|
4692
|
-
async request(method,
|
|
4693
|
-
const url = `${this.baseUrl}${
|
|
5029
|
+
async request(method, path12, opts = {}) {
|
|
5030
|
+
const url = `${this.baseUrl}${path12}`;
|
|
4694
5031
|
const policy = resolveRetryPolicy(opts.retry, this.retry);
|
|
4695
5032
|
const canRetry = isRetryEligible(method, opts.idempotencyKey, opts.retry);
|
|
4696
5033
|
const maxAttempts = canRetry ? policy.maxRetries + 1 : 1;
|
|
@@ -4923,10 +5260,10 @@ function statusToCode(status) {
|
|
|
4923
5260
|
}
|
|
4924
5261
|
async function sleep(ms, signal) {
|
|
4925
5262
|
if (ms <= 0) return;
|
|
4926
|
-
await new Promise((
|
|
5263
|
+
await new Promise((resolve9, reject) => {
|
|
4927
5264
|
const timer = setTimeout(() => {
|
|
4928
5265
|
if (signal) signal.removeEventListener("abort", onAbort);
|
|
4929
|
-
|
|
5266
|
+
resolve9();
|
|
4930
5267
|
}, ms);
|
|
4931
5268
|
const onAbort = () => {
|
|
4932
5269
|
clearTimeout(timer);
|
|
@@ -5134,31 +5471,31 @@ var AgentChatClient = class _AgentChatClient {
|
|
|
5134
5471
|
return this.get(`/v1/texts?${params.toString()}`, options);
|
|
5135
5472
|
}
|
|
5136
5473
|
// ─── Internal request helpers ─────────────────────────────────────────────
|
|
5137
|
-
async get(
|
|
5138
|
-
const res = await this.http.request("GET",
|
|
5474
|
+
async get(path12, opts) {
|
|
5475
|
+
const res = await this.http.request("GET", path12, this.toRequestOpts(opts));
|
|
5139
5476
|
return res.data;
|
|
5140
5477
|
}
|
|
5141
|
-
async del(
|
|
5142
|
-
const res = await this.http.request("DELETE",
|
|
5478
|
+
async del(path12, opts) {
|
|
5479
|
+
const res = await this.http.request("DELETE", path12, this.toRequestOpts(opts));
|
|
5143
5480
|
return res.data;
|
|
5144
5481
|
}
|
|
5145
|
-
async post(
|
|
5146
|
-
const res = await this.http.request("POST",
|
|
5482
|
+
async post(path12, body, opts) {
|
|
5483
|
+
const res = await this.http.request("POST", path12, {
|
|
5147
5484
|
...this.toRequestOpts(opts, { idempotent: false }),
|
|
5148
5485
|
body
|
|
5149
5486
|
});
|
|
5150
5487
|
return res.data;
|
|
5151
5488
|
}
|
|
5152
|
-
async patch(
|
|
5153
|
-
const res = await this.http.request("PATCH",
|
|
5489
|
+
async patch(path12, body, opts) {
|
|
5490
|
+
const res = await this.http.request("PATCH", path12, {
|
|
5154
5491
|
...this.toRequestOpts(opts, { idempotent: false }),
|
|
5155
5492
|
body
|
|
5156
5493
|
});
|
|
5157
5494
|
return res.data;
|
|
5158
5495
|
}
|
|
5159
|
-
async put(
|
|
5496
|
+
async put(path12, body, opts) {
|
|
5160
5497
|
const headers = opts?.contentType ? { "Content-Type": opts.contentType } : void 0;
|
|
5161
|
-
const res = await this.http.request("PUT",
|
|
5498
|
+
const res = await this.http.request("PUT", path12, {
|
|
5162
5499
|
...this.toRequestOpts(opts),
|
|
5163
5500
|
body,
|
|
5164
5501
|
rawBody: opts?.rawBody,
|
|
@@ -7131,17 +7468,17 @@ var RealtimeClient = class {
|
|
|
7131
7468
|
*/
|
|
7132
7469
|
heldAtMost(run22) {
|
|
7133
7470
|
const ms = this.options.inFlightAdoptMs;
|
|
7134
|
-
return new Promise((
|
|
7135
|
-
const timer = setTimeout(
|
|
7471
|
+
return new Promise((resolve9) => {
|
|
7472
|
+
const timer = setTimeout(resolve9, ms);
|
|
7136
7473
|
unref(timer);
|
|
7137
7474
|
run22.then(
|
|
7138
7475
|
() => {
|
|
7139
7476
|
clearTimeout(timer);
|
|
7140
|
-
|
|
7477
|
+
resolve9();
|
|
7141
7478
|
},
|
|
7142
7479
|
() => {
|
|
7143
7480
|
clearTimeout(timer);
|
|
7144
|
-
|
|
7481
|
+
resolve9();
|
|
7145
7482
|
}
|
|
7146
7483
|
);
|
|
7147
7484
|
});
|
|
@@ -8308,9 +8645,9 @@ var TurnTracker = class {
|
|
|
8308
8645
|
*/
|
|
8309
8646
|
async confirmedEnd(handle, done) {
|
|
8310
8647
|
if (!this.holds(handle)) return null;
|
|
8311
|
-
const released = new Promise((
|
|
8648
|
+
const released = new Promise((resolve9) => {
|
|
8312
8649
|
const list = this.waiters.get(handle.key) ?? [];
|
|
8313
|
-
list.push(() =>
|
|
8650
|
+
list.push(() => resolve9(null));
|
|
8314
8651
|
this.waiters.set(handle.key, list);
|
|
8315
8652
|
});
|
|
8316
8653
|
let report = done;
|
|
@@ -8387,9 +8724,9 @@ function nodeModules() {
|
|
|
8387
8724
|
/* @vite-ignore */
|
|
8388
8725
|
PATH_MODULE
|
|
8389
8726
|
)
|
|
8390
|
-
]).then(([
|
|
8391
|
-
fs:
|
|
8392
|
-
path:
|
|
8727
|
+
]).then(([fs10, path12]) => ({
|
|
8728
|
+
fs: fs10.default ?? fs10,
|
|
8729
|
+
path: path12.default ?? path12
|
|
8393
8730
|
}));
|
|
8394
8731
|
return modules;
|
|
8395
8732
|
}
|
|
@@ -8407,8 +8744,8 @@ function randomSuffix() {
|
|
|
8407
8744
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
8408
8745
|
}
|
|
8409
8746
|
async function renameWithRetry2(from, to, options = {}) {
|
|
8410
|
-
const { fs:
|
|
8411
|
-
const rename = options.rename ?? ((a, b) =>
|
|
8747
|
+
const { fs: fs10 } = await nodeModules();
|
|
8748
|
+
const rename = options.rename ?? ((a, b) => fs10.rename(a, b));
|
|
8412
8749
|
const attempts = options.retry ?? isWindows() ? RENAME_ATTEMPTS2 : 1;
|
|
8413
8750
|
for (let attempt = 1; ; attempt++) {
|
|
8414
8751
|
try {
|
|
@@ -8417,16 +8754,16 @@ async function renameWithRetry2(from, to, options = {}) {
|
|
|
8417
8754
|
} catch (err) {
|
|
8418
8755
|
const code = err.code;
|
|
8419
8756
|
if (attempt >= attempts || code === void 0 || !RENAME_RETRY_CODES2.has(code)) throw err;
|
|
8420
|
-
await new Promise((
|
|
8757
|
+
await new Promise((resolve9) => setTimeout(resolve9, RENAME_DELAY_MS2));
|
|
8421
8758
|
}
|
|
8422
8759
|
}
|
|
8423
8760
|
}
|
|
8424
8761
|
async function writeAtomic(file, data, options = {}) {
|
|
8425
|
-
const { fs:
|
|
8426
|
-
await
|
|
8427
|
-
const tmp =
|
|
8762
|
+
const { fs: fs10, path: path12 } = await nodeModules();
|
|
8763
|
+
await fs10.mkdir(path12.dirname(file), { recursive: true, mode: 448 });
|
|
8764
|
+
const tmp = path12.join(path12.dirname(file), `.${path12.basename(file)}.${randomSuffix()}.tmp`);
|
|
8428
8765
|
try {
|
|
8429
|
-
const handle = await
|
|
8766
|
+
const handle = await fs10.open(tmp, "wx", options.mode ?? 438);
|
|
8430
8767
|
try {
|
|
8431
8768
|
if (options.mode !== void 0) await handle.chmod(options.mode);
|
|
8432
8769
|
await handle.writeFile(data);
|
|
@@ -8436,14 +8773,14 @@ async function writeAtomic(file, data, options = {}) {
|
|
|
8436
8773
|
}
|
|
8437
8774
|
await renameWithRetry2(tmp, file, options);
|
|
8438
8775
|
} catch (err) {
|
|
8439
|
-
await
|
|
8776
|
+
await fs10.rm(tmp, { force: true }).catch(() => void 0);
|
|
8440
8777
|
throw err;
|
|
8441
8778
|
}
|
|
8442
8779
|
}
|
|
8443
8780
|
async function readBytes(file) {
|
|
8444
|
-
const { fs:
|
|
8781
|
+
const { fs: fs10 } = await nodeModules();
|
|
8445
8782
|
try {
|
|
8446
|
-
return new Uint8Array(await
|
|
8783
|
+
return new Uint8Array(await fs10.readFile(file));
|
|
8447
8784
|
} catch {
|
|
8448
8785
|
return null;
|
|
8449
8786
|
}
|
|
@@ -9360,7 +9697,7 @@ var ReceiveLoop = class {
|
|
|
9360
9697
|
if (!run22.stale() || this.stopped) this.finishCycle(summary);
|
|
9361
9698
|
})();
|
|
9362
9699
|
let timer = null;
|
|
9363
|
-
const overdue = new Promise((
|
|
9700
|
+
const overdue = new Promise((resolve9) => {
|
|
9364
9701
|
if (!Number.isFinite(this.cycleTimeoutMs)) return;
|
|
9365
9702
|
const check = () => {
|
|
9366
9703
|
timer = null;
|
|
@@ -9368,7 +9705,7 @@ var ReceiveLoop = class {
|
|
|
9368
9705
|
const excluded = excludedMs + (excludedSince !== null ? now2 - excludedSince : 0);
|
|
9369
9706
|
const active = now2 - startedAt - excluded;
|
|
9370
9707
|
if (active >= this.cycleTimeoutMs) {
|
|
9371
|
-
|
|
9708
|
+
resolve9("overdue");
|
|
9372
9709
|
return;
|
|
9373
9710
|
}
|
|
9374
9711
|
timer = this._setTimeout(check, Math.max(1, this.cycleTimeoutMs - active));
|
|
@@ -9419,7 +9756,7 @@ var ReceiveLoop = class {
|
|
|
9419
9756
|
}
|
|
9420
9757
|
/** The runtime's model call, bounded by `gateCallTimeoutMs` (and the cycle's own abandonment). */
|
|
9421
9758
|
boundedModelCall(run22) {
|
|
9422
|
-
return (prompt2) => new Promise((
|
|
9759
|
+
return (prompt2) => new Promise((resolve9, reject) => {
|
|
9423
9760
|
const controller = new AbortController();
|
|
9424
9761
|
const abort = () => {
|
|
9425
9762
|
controller.abort();
|
|
@@ -9446,7 +9783,7 @@ var ReceiveLoop = class {
|
|
|
9446
9783
|
(text) => {
|
|
9447
9784
|
if (timer !== null) this._clearTimeout(timer);
|
|
9448
9785
|
run22.signal.removeEventListener("abort", abort);
|
|
9449
|
-
|
|
9786
|
+
resolve9(text);
|
|
9450
9787
|
},
|
|
9451
9788
|
(err) => {
|
|
9452
9789
|
if (timer !== null) this._clearTimeout(timer);
|
|
@@ -9915,18 +10252,21 @@ var DAY = 24 * HOUR;
|
|
|
9915
10252
|
var INBOX_TRAY_MAX_LIMIT = 50;
|
|
9916
10253
|
var MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
|
|
9917
10254
|
|
|
9918
|
-
// node_modules/.pnpm/@agentchatme+agent-core@0.
|
|
9919
|
-
import * as
|
|
10255
|
+
// node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/chunk-NAAHIK7Z.js
|
|
10256
|
+
import * as fs3 from "fs";
|
|
9920
10257
|
import * as path22 from "path";
|
|
9921
10258
|
import { createHash } from "crypto";
|
|
9922
10259
|
import * as fs22 from "fs";
|
|
9923
|
-
import * as
|
|
10260
|
+
import * as path32 from "path";
|
|
9924
10261
|
import * as fs4 from "fs";
|
|
9925
10262
|
import * as path4 from "path";
|
|
10263
|
+
import * as os2 from "os";
|
|
10264
|
+
import * as os22 from "os";
|
|
10265
|
+
import * as path7 from "path";
|
|
9926
10266
|
var TEXTS_CACHE_FILE = "texts.json";
|
|
9927
10267
|
var FETCH_TIMEOUT_MS = 5e3;
|
|
9928
10268
|
function textsCachePath(home) {
|
|
9929
|
-
return
|
|
10269
|
+
return path3.join(home, TEXTS_CACHE_FILE);
|
|
9930
10270
|
}
|
|
9931
10271
|
function readCachedTexts(home, runtime) {
|
|
9932
10272
|
const raw = readJsonFile(textsCachePath(home));
|
|
@@ -10427,8 +10767,8 @@ function getErrorMap() {
|
|
|
10427
10767
|
return overrideErrorMap;
|
|
10428
10768
|
}
|
|
10429
10769
|
var makeIssue = (params) => {
|
|
10430
|
-
const { data, path:
|
|
10431
|
-
const fullPath = [...
|
|
10770
|
+
const { data, path: path82, errorMaps, issueData } = params;
|
|
10771
|
+
const fullPath = [...path82, ...issueData.path || []];
|
|
10432
10772
|
const fullIssue = {
|
|
10433
10773
|
...issueData,
|
|
10434
10774
|
path: fullPath
|
|
@@ -10540,11 +10880,11 @@ var errorUtil;
|
|
|
10540
10880
|
errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
|
|
10541
10881
|
})(errorUtil || (errorUtil = {}));
|
|
10542
10882
|
var ParseInputLazyPath = class {
|
|
10543
|
-
constructor(parent, value,
|
|
10883
|
+
constructor(parent, value, path82, key) {
|
|
10544
10884
|
this._cachedPath = [];
|
|
10545
10885
|
this.parent = parent;
|
|
10546
10886
|
this.data = value;
|
|
10547
|
-
this._path =
|
|
10887
|
+
this._path = path82;
|
|
10548
10888
|
this._key = key;
|
|
10549
10889
|
}
|
|
10550
10890
|
get path() {
|
|
@@ -14041,7 +14381,7 @@ function clearCredentials(home) {
|
|
|
14041
14381
|
let removed = false;
|
|
14042
14382
|
for (const p of [credentialsPath(home), pendingPath(home)]) {
|
|
14043
14383
|
try {
|
|
14044
|
-
|
|
14384
|
+
fs3.unlinkSync(p);
|
|
14045
14385
|
removed = true;
|
|
14046
14386
|
} catch {
|
|
14047
14387
|
}
|
|
@@ -14071,7 +14411,7 @@ function writePending(home, pending) {
|
|
|
14071
14411
|
}
|
|
14072
14412
|
function clearPending(home) {
|
|
14073
14413
|
try {
|
|
14074
|
-
|
|
14414
|
+
fs3.unlinkSync(pendingPath(home));
|
|
14075
14415
|
} catch {
|
|
14076
14416
|
}
|
|
14077
14417
|
}
|
|
@@ -14178,35 +14518,9 @@ function readLocal2(file) {
|
|
|
14178
14518
|
return { exists: true, bytes: new Uint8Array(0), version: null };
|
|
14179
14519
|
}
|
|
14180
14520
|
}
|
|
14181
|
-
|
|
14182
|
-
|
|
14183
|
-
var DEFAULT_RUN_PROFILE = "answer";
|
|
14184
|
-
function isRunProfile(value) {
|
|
14185
|
-
return typeof value === "string" && RUN_PROFILES.includes(value);
|
|
14186
|
-
}
|
|
14187
|
-
function resolveRunProfile(env = process.env) {
|
|
14188
|
-
const raw = env[RUN_PROFILE_ENV]?.trim().toLowerCase();
|
|
14189
|
-
return isRunProfile(raw) ? raw : DEFAULT_RUN_PROFILE;
|
|
14190
|
-
}
|
|
14191
|
-
var INTEGRATION_ENV = "AGENTCHAT_INTEGRATION";
|
|
14192
|
-
var INTEGRATION_ENV_LEGACY = "AGENTCHAT_DOORBELL";
|
|
14193
|
-
var INTEGRATION_ENV_LEGACY_REMOVAL = "2027-02-01";
|
|
14194
|
-
function isOff(raw) {
|
|
14195
|
-
const value = raw?.trim().toLowerCase();
|
|
14196
|
-
return value === "off" || value === "0" || value === "false";
|
|
14197
|
-
}
|
|
14198
|
-
function integrationDisabledBy(env = process.env) {
|
|
14199
|
-
if (env[INTEGRATION_ENV] !== void 0 && env[INTEGRATION_ENV].trim().length > 0) {
|
|
14200
|
-
return isOff(env[INTEGRATION_ENV]) ? INTEGRATION_ENV : null;
|
|
14201
|
-
}
|
|
14202
|
-
return isOff(env[INTEGRATION_ENV_LEGACY]) ? INTEGRATION_ENV_LEGACY : null;
|
|
14203
|
-
}
|
|
14204
|
-
function integrationDisabled(env = process.env) {
|
|
14205
|
-
return integrationDisabledBy(env) !== null;
|
|
14521
|
+
function identityLineOf(texts) {
|
|
14522
|
+
return texts.identity_line;
|
|
14206
14523
|
}
|
|
14207
|
-
var RUN_BUDGET_ENV = "AGENTCHAT_RUN_BUDGET_MS";
|
|
14208
|
-
var DEFAULT_RUN_BUDGET_MS = 10 * 6e4;
|
|
14209
|
-
var MAX_RUN_BUDGET_MS = 2 * 60 * 6e4;
|
|
14210
14524
|
var INTEGRATION_STATUS_FILE = "integration.status.json";
|
|
14211
14525
|
var LEGACY_STATUS_FILE = "doorbell.status.json";
|
|
14212
14526
|
var SOCKET_STATES = ["off", "idle", "connecting", "ready", "reconnecting", "blocked", "closed"];
|
|
@@ -14254,6 +14568,7 @@ var StatusSchema = external_exports.object({
|
|
|
14254
14568
|
runtime: external_exports.string().nullable(),
|
|
14255
14569
|
handle: external_exports.string().nullable(),
|
|
14256
14570
|
profile: external_exports.string(),
|
|
14571
|
+
workdir: external_exports.string().optional(),
|
|
14257
14572
|
socket: external_exports.enum([...SOCKET_STATES, LEGACY_BLOCKED_STATE]),
|
|
14258
14573
|
wakes: external_exports.number().optional(),
|
|
14259
14574
|
wakes_absorbed: external_exports.number().optional(),
|
|
@@ -14272,6 +14587,10 @@ var StatusSchema = external_exports.object({
|
|
|
14272
14587
|
last_error: external_exports.string().nullable(),
|
|
14273
14588
|
texts: TextsStatusSchema.nullable().default(null),
|
|
14274
14589
|
capabilities: external_exports.array(external_exports.string()).nullable().optional(),
|
|
14590
|
+
standby: external_exports.object({ home: external_exports.string().nullable(), pid: external_exports.number().nullable(), since: external_exports.string().nullable() }).nullable().optional(),
|
|
14591
|
+
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(),
|
|
14592
|
+
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(),
|
|
14593
|
+
lease_errors: external_exports.object({ count: external_exports.number(), last: external_exports.string().nullable() }).nullable().optional(),
|
|
14275
14594
|
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(),
|
|
14276
14595
|
intake_paused: external_exports.boolean().nullable().optional()
|
|
14277
14596
|
}).passthrough();
|
|
@@ -14284,6 +14603,7 @@ function normalize(raw) {
|
|
|
14284
14603
|
runtime: raw.runtime,
|
|
14285
14604
|
handle: raw.handle,
|
|
14286
14605
|
profile: raw.profile,
|
|
14606
|
+
...raw.workdir !== void 0 ? { workdir: raw.workdir } : {},
|
|
14287
14607
|
socket: raw.socket === LEGACY_BLOCKED_STATE ? "blocked" : raw.socket,
|
|
14288
14608
|
wakes: raw.wakes ?? raw.knocks ?? 0,
|
|
14289
14609
|
wakes_absorbed: raw.wakes_absorbed ?? raw.knocks_absorbed ?? 0,
|
|
@@ -14301,14 +14621,18 @@ function normalize(raw) {
|
|
|
14301
14621
|
texts: raw.texts,
|
|
14302
14622
|
capabilities: raw.capabilities ?? null,
|
|
14303
14623
|
recent_cycles: raw.recent_cycles ?? null,
|
|
14304
|
-
intake_paused: raw.intake_paused ?? null
|
|
14624
|
+
intake_paused: raw.intake_paused ?? null,
|
|
14625
|
+
standby: raw.standby ?? null,
|
|
14626
|
+
runs_failing: raw.runs_failing ?? null,
|
|
14627
|
+
unservable: raw.unservable ?? null,
|
|
14628
|
+
lease_errors: raw.lease_errors ?? null
|
|
14305
14629
|
};
|
|
14306
14630
|
}
|
|
14307
14631
|
function integrationStatusPath(home) {
|
|
14308
|
-
return
|
|
14632
|
+
return path32.join(home, INTEGRATION_STATUS_FILE);
|
|
14309
14633
|
}
|
|
14310
14634
|
function legacyStatusPath(home) {
|
|
14311
|
-
return
|
|
14635
|
+
return path32.join(home, LEGACY_STATUS_FILE);
|
|
14312
14636
|
}
|
|
14313
14637
|
function readIntegrationStatus(home) {
|
|
14314
14638
|
for (const file of [integrationStatusPath(home), legacyStatusPath(home)]) {
|
|
@@ -14343,8 +14667,20 @@ function formatIntegrationStatus(status, now2 = Date.now()) {
|
|
|
14343
14667
|
if (status === null) return ["Integration: no status recorded yet (the daemon has not run, or is still starting)"];
|
|
14344
14668
|
const age = integrationStatusAge(status, now2);
|
|
14345
14669
|
const stale = age !== null && age > 3 * 6e4;
|
|
14670
|
+
const profileWarning = runProfileWarning(status.profile);
|
|
14671
|
+
const standby = status.standby ?? null;
|
|
14672
|
+
const failing = status.runs_failing ?? null;
|
|
14673
|
+
const unservable = status.unservable ?? null;
|
|
14346
14674
|
const lines = [
|
|
14347
|
-
`Integration: socket ${status.socket}${stale ? ` (status last written ${ago(age)} \u2014 the daemon may be down)` : ""}`,
|
|
14675
|
+
`Integration: socket ${status.socket}${stale ? ` (status last written ${ago(age)} \u2014 the daemon may be down)` : ""}${unservable !== null ? " \u2014 this home gave the agent up (below)" : standby !== null ? " \u2014 standing by: another listener serves this agent" : failing !== null ? " \u2014 but runs are failing (below)" : ""}`,
|
|
14676
|
+
...unservable !== null ? [
|
|
14677
|
+
` gave up: ${unservable.reason === "key_refused" ? "the server refuses this home's key" : "runs fail for a runtime reason, and another listener for the agent was waiting"} \u2014 ${unservable.detail} (since ${unservable.since}). No socket, no run here while another listener can serve it; looks again at ${unservable.retry_at}${unservable.reason === "runs_failing" ? " (the runtime checked first: a check that passes clears this)" : " (signing in again here clears this at once)"}, and takes the agent back whenever no other listener holds it.`
|
|
14678
|
+
] : [],
|
|
14679
|
+
...standby !== null ? [` standby: ${standby.home ?? "another identity home"}${standby.pid !== null ? ` (pid ${standby.pid})` : ""} serves this agent${standby.since !== null ? ` since ${standby.since}` : ""}; this one holds no socket and starts no run while it does (no message is answered twice), and takes over when it stops`] : [],
|
|
14680
|
+
...failing !== null ? [
|
|
14681
|
+
` runs failing: ${failing.reason} \u2014 since ${failing.since} (${ago(Math.max(0, now2 - Date.parse(failing.since)))}), ${failing.runs_missed} run(s) missed; checked ${ago(Math.max(0, now2 - Date.parse(failing.checked_at)))}. ${unservable !== null ? "The runtime recheck clears this." : "Wakes still arrive, are counted and start runs; the next run that succeeds clears this."}`
|
|
14682
|
+
] : [],
|
|
14683
|
+
...status.lease_errors !== void 0 && status.lease_errors !== null && status.lease_errors.count > 0 ? [` lock: ${status.lease_errors.count} renewal(s) failed${status.lease_errors.last ? ` (last: ${status.lease_errors.last})` : ""}; a lock that cannot be renewed for 45 s is given up`] : [],
|
|
14348
14684
|
" delivery: acknowledged on receipt by the SDK socket (delivered = this machine received it; read is the agent\u2019s own verdict inside its run)",
|
|
14349
14685
|
` wakes: ${status.wakes} (${status.wakes_absorbed} absorbed into a pending run), invites: ${status.invites}`,
|
|
14350
14686
|
` runs: ${status.runs_started} started, ${status.runs_ok} ok, ${status.runs_failed} failed, ${status.runs_timed_out} timed out, ${status.runs_not_started} did not start; ${status.runs_skipped_empty} wake(s) found the tray empty (no run)`,
|
|
@@ -14352,7 +14688,10 @@ function formatIntegrationStatus(status, now2 = Date.now()) {
|
|
|
14352
14688
|
...status.capabilities === null || status.capabilities === void 0 ? [] : [
|
|
14353
14689
|
status.capabilities.includes("rewake") ? " re-wake: the server wakes this agent again for cards it has not answered (+1 m, +5 m, +30 m, +3 h)" : " re-wake: not offered by this server \u2014 an unanswered card waits for the next message"
|
|
14354
14690
|
],
|
|
14355
|
-
` profile: ${status.profile}${status.runtime ? ` (${status.runtime})` : ""}`
|
|
14691
|
+
` profile: ${status.profile}${status.runtime ? ` (${status.runtime})` : ""}${profileWarning !== null ? ` \u2014 ${profileWarning}` : ""}`,
|
|
14692
|
+
...status.workdir !== void 0 && workdirExposesHome(status.workdir) ? [
|
|
14693
|
+
` workdir: ${status.workdir} is your home folder or contains it \u2014 a run started by a peer's message there can see everything under it${status.profile === "answer" ? " (the presets' answer runs use their own empty folder instead)" : ""}; point the workdir at a folder of its own`
|
|
14694
|
+
] : []
|
|
14356
14695
|
];
|
|
14357
14696
|
if (status.last_run) {
|
|
14358
14697
|
const r = status.last_run;
|
|
@@ -14369,9 +14708,9 @@ function formatIntegrationStatus(status, now2 = Date.now()) {
|
|
|
14369
14708
|
if (cycles.length > 0) {
|
|
14370
14709
|
const last = cycles[cycles.length - 1];
|
|
14371
14710
|
lines.push(` cycles: ${cycles.length} recent; the last one ${last.outcome} (${last.cards} card(s), ${last.invites} invite(s)) ${ago(Math.max(0, now2 - Date.parse(last.at)))}`);
|
|
14372
|
-
const
|
|
14373
|
-
if (
|
|
14374
|
-
lines.push(` WARNING: the last ${
|
|
14711
|
+
const failing2 = failedCyclesInARow(status);
|
|
14712
|
+
if (failing2 !== null && failing2.count >= REPEATED_FAILED_CYCLES) {
|
|
14713
|
+
lines.push(` WARNING: the last ${failing2.count} wake cycles did not get done (latest: ${failing2.latest.outcome}${failing2.latest.failure ? ` \u2014 ${failing2.latest.failure}` : ""})`);
|
|
14375
14714
|
}
|
|
14376
14715
|
}
|
|
14377
14716
|
if (status.retry_due_at) {
|
|
@@ -14455,9 +14794,73 @@ function alwaysOnState(home) {
|
|
|
14455
14794
|
}
|
|
14456
14795
|
return "down";
|
|
14457
14796
|
}
|
|
14797
|
+
var LEASE_STALE_MS = 45e3;
|
|
14798
|
+
var BOOT_MARGIN_MS = 6e4;
|
|
14799
|
+
function hostname22() {
|
|
14800
|
+
try {
|
|
14801
|
+
return os2.hostname();
|
|
14802
|
+
} catch {
|
|
14803
|
+
return "";
|
|
14804
|
+
}
|
|
14805
|
+
}
|
|
14806
|
+
function bootedAt(now2 = Date.now()) {
|
|
14807
|
+
return now2 - os2.uptime() * 1e3;
|
|
14808
|
+
}
|
|
14809
|
+
function pidAlive(pid) {
|
|
14810
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
14811
|
+
try {
|
|
14812
|
+
process.kill(pid, 0);
|
|
14813
|
+
return true;
|
|
14814
|
+
} catch (err) {
|
|
14815
|
+
return err.code === "EPERM";
|
|
14816
|
+
}
|
|
14817
|
+
}
|
|
14818
|
+
function parseLease(raw) {
|
|
14819
|
+
const text = raw.trim();
|
|
14820
|
+
const firstLine = text.split(/\r?\n/, 1)[0]?.trim() ?? "";
|
|
14821
|
+
if (!/^\d+$/.test(firstLine)) return null;
|
|
14822
|
+
const pid = Number(firstLine);
|
|
14823
|
+
const rest = text.slice(firstLine.length).trim();
|
|
14824
|
+
if (rest.length === 0) return { pid, token: null, host: null, renewed_at: null };
|
|
14825
|
+
try {
|
|
14826
|
+
const j = JSON.parse(rest);
|
|
14827
|
+
return {
|
|
14828
|
+
pid,
|
|
14829
|
+
token: typeof j["token"] === "string" ? j["token"] : null,
|
|
14830
|
+
host: typeof j["host"] === "string" ? j["host"] : null,
|
|
14831
|
+
...typeof j["home"] === "string" ? { home: j["home"] } : {},
|
|
14832
|
+
...typeof j["label"] === "string" ? { label: j["label"] } : {},
|
|
14833
|
+
...typeof j["acquired_at"] === "string" ? { acquired_at: j["acquired_at"] } : {},
|
|
14834
|
+
renewed_at: typeof j["renewed_at"] === "number" && Number.isFinite(j["renewed_at"]) ? j["renewed_at"] : null
|
|
14835
|
+
};
|
|
14836
|
+
} catch {
|
|
14837
|
+
return null;
|
|
14838
|
+
}
|
|
14839
|
+
}
|
|
14840
|
+
var sameHost = (holder) => holder.host === null || holder.host === hostname22();
|
|
14841
|
+
function legacyLive(holder, mtimeMs, booted) {
|
|
14842
|
+
if (!pidAlive(holder.pid)) return false;
|
|
14843
|
+
return mtimeMs === null || mtimeMs >= booted - BOOT_MARGIN_MS;
|
|
14844
|
+
}
|
|
14845
|
+
function holderLive(holder, at = {}) {
|
|
14846
|
+
const now2 = at.now ?? Date.now();
|
|
14847
|
+
if (holder.renewed_at === null) return legacyLive(holder, at.mtimeMs ?? null, at.bootedAt ?? bootedAt(now2));
|
|
14848
|
+
if (sameHost(holder) && !pidAlive(holder.pid)) return false;
|
|
14849
|
+
return Math.abs(now2 - holder.renewed_at) < (at.staleMs ?? LEASE_STALE_MS);
|
|
14850
|
+
}
|
|
14851
|
+
var DAEMON_LOCK_FILE = "daemon.lock";
|
|
14852
|
+
var AGENT_LOCK_DIR_ENV = "AGENTCHAT_LOCK_DIR";
|
|
14853
|
+
function agentLockDir(env = process.env, system = process.platform, home = os22.homedir()) {
|
|
14854
|
+
const override = env[AGENT_LOCK_DIR_ENV]?.trim();
|
|
14855
|
+
if (override !== void 0 && override.length > 0) return path7.resolve(override);
|
|
14856
|
+
const p = system === "win32" ? path7.win32 : path7.posix;
|
|
14857
|
+
if (system === "darwin") return p.join(home, "Library", "Application Support", "AgentChat", "locks");
|
|
14858
|
+
if (system === "win32") return p.join(home, "AppData", "Local", "AgentChat", "locks");
|
|
14859
|
+
return p.join(home, ".local", "state", "agentchat", "locks");
|
|
14860
|
+
}
|
|
14458
14861
|
|
|
14459
|
-
// node_modules/.pnpm/@agentchatme+agent-core@0.
|
|
14460
|
-
var VERSION2 = "0.
|
|
14862
|
+
// node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/chunk-UE7DKW3C.js
|
|
14863
|
+
var VERSION2 = "0.5.0";
|
|
14461
14864
|
var HOSTED_MCP_PATH2 = integration_exports.HOSTED_MCP_PATH;
|
|
14462
14865
|
function hostedMcpUrl2(apiBase) {
|
|
14463
14866
|
return integration_exports.hostedMcpUrl(apiBase);
|
|
@@ -14471,14 +14874,75 @@ async function probeHostedMcp(params) {
|
|
|
14471
14874
|
...params.fetch !== void 0 ? { fetch: params.fetch } : {}
|
|
14472
14875
|
});
|
|
14473
14876
|
}
|
|
14877
|
+
var PROBE_KILL_WAIT_MS = 5e3;
|
|
14878
|
+
var MAX_OUTPUT = 64 * 1024;
|
|
14879
|
+
function runProbe(command, args, options) {
|
|
14880
|
+
return new Promise((resolve9) => {
|
|
14881
|
+
let child;
|
|
14882
|
+
try {
|
|
14883
|
+
child = spawnCommand(command, [...args], {
|
|
14884
|
+
...options.env !== void 0 ? { env: options.env } : {},
|
|
14885
|
+
...options.cwd !== void 0 ? { cwd: options.cwd } : {},
|
|
14886
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
14887
|
+
// Its own process group on POSIX, so the whole tree can be killed.
|
|
14888
|
+
detached: process.platform !== "win32",
|
|
14889
|
+
windowsHide: true
|
|
14890
|
+
});
|
|
14891
|
+
} catch (err) {
|
|
14892
|
+
resolve9({ error: err instanceof Error ? err : new Error(String(err)), status: null, stdout: "", stderr: "", timedOut: false });
|
|
14893
|
+
return;
|
|
14894
|
+
}
|
|
14895
|
+
const proc = child;
|
|
14896
|
+
let stdout = "";
|
|
14897
|
+
let stderr = "";
|
|
14898
|
+
let timedOut = false;
|
|
14899
|
+
let stopped = false;
|
|
14900
|
+
let finished = false;
|
|
14901
|
+
let giveUp = null;
|
|
14902
|
+
const finish = (result) => {
|
|
14903
|
+
if (finished) return;
|
|
14904
|
+
finished = true;
|
|
14905
|
+
clearTimeout(timer);
|
|
14906
|
+
if (giveUp !== null) clearTimeout(giveUp);
|
|
14907
|
+
resolve9(result);
|
|
14908
|
+
};
|
|
14909
|
+
proc.stdout?.on("data", (chunk) => {
|
|
14910
|
+
if (stdout.length < MAX_OUTPUT) stdout += chunk.toString("utf-8");
|
|
14911
|
+
});
|
|
14912
|
+
proc.stderr?.on("data", (chunk) => {
|
|
14913
|
+
if (stderr.length < MAX_OUTPUT) stderr += chunk.toString("utf-8");
|
|
14914
|
+
});
|
|
14915
|
+
const stop = (error, byTimeout) => {
|
|
14916
|
+
if (timedOut || finished) return;
|
|
14917
|
+
timedOut = byTimeout;
|
|
14918
|
+
stopped = true;
|
|
14919
|
+
killProcessTree(proc, "SIGKILL");
|
|
14920
|
+
giveUp = setTimeout(() => {
|
|
14921
|
+
proc.stdout?.destroy();
|
|
14922
|
+
proc.stderr?.destroy();
|
|
14923
|
+
finish({ error, status: null, stdout, stderr, timedOut });
|
|
14924
|
+
}, PROBE_KILL_WAIT_MS);
|
|
14925
|
+
proc.once("close", () => finish({ error, status: null, stdout, stderr, timedOut }));
|
|
14926
|
+
};
|
|
14927
|
+
const timer = setTimeout(() => stop(new Error(`${command} ${args.join(" ")} did not answer within ${Math.round(options.timeoutMs / 1e3)} s`), true), options.timeoutMs);
|
|
14928
|
+
const onAbort = () => stop(new Error(`${command} ${args.join(" ")} was stopped`), false);
|
|
14929
|
+
if (options.signal?.aborted) onAbort();
|
|
14930
|
+
else options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
14931
|
+
proc.on("error", (err) => finish({ error: err, status: null, stdout, stderr, timedOut }));
|
|
14932
|
+
proc.on("close", (code) => {
|
|
14933
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
14934
|
+
if (!stopped) finish({ status: code, stdout, stderr, timedOut });
|
|
14935
|
+
});
|
|
14936
|
+
});
|
|
14937
|
+
}
|
|
14474
14938
|
|
|
14475
|
-
// node_modules/.pnpm/@agentchatme+agent-core@0.
|
|
14476
|
-
import * as
|
|
14939
|
+
// node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/index.js
|
|
14940
|
+
import * as fs5 from "fs";
|
|
14477
14941
|
import * as path5 from "path";
|
|
14478
14942
|
import * as readline from "readline";
|
|
14479
14943
|
import * as crypto from "crypto";
|
|
14480
14944
|
import * as fs23 from "fs";
|
|
14481
|
-
import * as
|
|
14945
|
+
import * as os3 from "os";
|
|
14482
14946
|
import * as path23 from "path";
|
|
14483
14947
|
async function traySummary(client) {
|
|
14484
14948
|
const tray = await client.inbox.tray({ limit: INBOX_TRAY_MAX_LIMIT });
|
|
@@ -14519,9 +14983,6 @@ function clearOfferDeclined(home) {
|
|
|
14519
14983
|
delete state.offer_declined_at;
|
|
14520
14984
|
writeState(home, state);
|
|
14521
14985
|
}
|
|
14522
|
-
function identityLineOf(texts) {
|
|
14523
|
-
return texts.identity_line;
|
|
14524
|
-
}
|
|
14525
14986
|
var ANCHOR_START = integration_exports.anchor.START_MARKER;
|
|
14526
14987
|
var ANCHOR_END = integration_exports.anchor.END_MARKER;
|
|
14527
14988
|
var MARKER_LINES = /* @__PURE__ */ new Set([
|
|
@@ -14598,7 +15059,7 @@ var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
|
14598
15059
|
function readInstructionFile(filePath) {
|
|
14599
15060
|
let bytes;
|
|
14600
15061
|
try {
|
|
14601
|
-
bytes =
|
|
15062
|
+
bytes = fs5.readFileSync(filePath);
|
|
14602
15063
|
} catch (err) {
|
|
14603
15064
|
if (err.code === "ENOENT") return null;
|
|
14604
15065
|
throw err;
|
|
@@ -14616,22 +15077,22 @@ function resolveWriteTarget(filePath) {
|
|
|
14616
15077
|
for (let hops = 0; hops < 40; hops++) {
|
|
14617
15078
|
let stat;
|
|
14618
15079
|
try {
|
|
14619
|
-
stat =
|
|
15080
|
+
stat = fs5.lstatSync(current);
|
|
14620
15081
|
} catch (err) {
|
|
14621
15082
|
if (err.code === "ENOENT") return current;
|
|
14622
15083
|
throw err;
|
|
14623
15084
|
}
|
|
14624
15085
|
if (!stat.isSymbolicLink()) return current;
|
|
14625
|
-
const link =
|
|
14626
|
-
const joined = path5.isAbsolute(link) ? link : `${
|
|
14627
|
-
current = path5.join(
|
|
15086
|
+
const link = fs5.readlinkSync(current);
|
|
15087
|
+
const joined = path5.isAbsolute(link) ? link : `${fs5.realpathSync.native(path5.dirname(current))}${path5.sep}${link}`;
|
|
15088
|
+
current = path5.join(fs5.realpathSync.native(path5.dirname(joined)), path5.basename(joined));
|
|
14628
15089
|
}
|
|
14629
15090
|
throw Object.assign(new Error(`${filePath}: too many symbolic links`), { code: "ELOOP" });
|
|
14630
15091
|
}
|
|
14631
15092
|
var IN_PLACE_FALLBACK_CODES = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EROFS", "EBUSY", "EXDEV"]);
|
|
14632
15093
|
function stillWritable(file) {
|
|
14633
15094
|
try {
|
|
14634
|
-
|
|
15095
|
+
fs5.accessSync(file, fs5.constants.W_OK);
|
|
14635
15096
|
return true;
|
|
14636
15097
|
} catch {
|
|
14637
15098
|
return false;
|
|
@@ -14641,29 +15102,29 @@ function writeInstructionFile(filePath, data) {
|
|
|
14641
15102
|
const target = resolveWriteTarget(filePath);
|
|
14642
15103
|
let existing = null;
|
|
14643
15104
|
try {
|
|
14644
|
-
existing =
|
|
15105
|
+
existing = fs5.statSync(target);
|
|
14645
15106
|
} catch (err) {
|
|
14646
15107
|
if (err.code !== "ENOENT") throw err;
|
|
14647
15108
|
}
|
|
14648
15109
|
if (existing !== null) {
|
|
14649
15110
|
if (!existing.isFile()) throw new Error(`${filePath} is not a regular file`);
|
|
14650
|
-
|
|
15111
|
+
fs5.accessSync(target, fs5.constants.W_OK);
|
|
14651
15112
|
} else {
|
|
14652
|
-
|
|
15113
|
+
fs5.mkdirSync(path5.dirname(target), { recursive: true });
|
|
14653
15114
|
}
|
|
14654
15115
|
try {
|
|
14655
15116
|
atomicWriteFile(target, data, existing === null ? void 0 : existing.mode & 4095);
|
|
14656
15117
|
} catch (err) {
|
|
14657
15118
|
const code = err.code;
|
|
14658
15119
|
if (existing !== null && code !== void 0 && IN_PLACE_FALLBACK_CODES.has(code) && stillWritable(target)) {
|
|
14659
|
-
|
|
15120
|
+
fs5.writeFileSync(target, data, "utf-8");
|
|
14660
15121
|
return;
|
|
14661
15122
|
}
|
|
14662
15123
|
throw err;
|
|
14663
15124
|
}
|
|
14664
15125
|
if (existing !== null && typeof process.getuid === "function" && process.getuid() === 0 && (existing.uid !== 0 || existing.gid !== 0)) {
|
|
14665
15126
|
try {
|
|
14666
|
-
|
|
15127
|
+
fs5.chownSync(target, existing.uid, existing.gid);
|
|
14667
15128
|
} catch {
|
|
14668
15129
|
}
|
|
14669
15130
|
}
|
|
@@ -15384,6 +15845,29 @@ function createIdentityCommands(profile2) {
|
|
|
15384
15845
|
if (anchorFile2 !== null) checks.push(await identityLineCheck(anchorFile2, creds, apiBase, texts, opts.fix === true));
|
|
15385
15846
|
}
|
|
15386
15847
|
const integration = readIntegrationStatus(home);
|
|
15848
|
+
const runsFailing = integration?.runs_failing ?? null;
|
|
15849
|
+
const gaveUp = integration?.unservable ?? null;
|
|
15850
|
+
if (gaveUp !== null) {
|
|
15851
|
+
checks.push({
|
|
15852
|
+
name: "runs",
|
|
15853
|
+
verdict: "FAIL",
|
|
15854
|
+
detail: gaveUp.reason === "key_refused" ? `this home gave the agent up: the server refuses its key (${gaveUp.detail}); it looks again at ${gaveUp.retry_at} (every 5 min) and takes the agent back whenever no other listener holds it, but only a key the server accepts can serve \u2014 sign in again here (login/recover; that clears this at once), or log out if another home serves the agent` : `this home gave the agent up: ${gaveUp.detail} (since ${gaveUp.since}); its runtime is checked again at ${gaveUp.retry_at} (every 60 s) and a check that passes clears this; it takes the agent back whenever no other listener holds it`
|
|
15855
|
+
});
|
|
15856
|
+
} else if (runsFailing !== null) {
|
|
15857
|
+
checks.push({
|
|
15858
|
+
name: "runs",
|
|
15859
|
+
verdict: "FAIL",
|
|
15860
|
+
detail: `runs failing: ${runsFailing.reason} \u2014 since ${runsFailing.since}, ${runsFailing.runs_missed} run(s) missed (checked ${runsFailing.checked_at}); fix that, and the next run that succeeds clears this`
|
|
15861
|
+
});
|
|
15862
|
+
}
|
|
15863
|
+
const standby = integration?.standby ?? null;
|
|
15864
|
+
if (standby !== null) {
|
|
15865
|
+
checks.push({
|
|
15866
|
+
name: "single-listener",
|
|
15867
|
+
verdict: "WARN",
|
|
15868
|
+
detail: `another listener serves this agent: ${standby.home ?? "another identity home"}${standby.pid !== null ? ` (pid ${standby.pid})` : ""}; this one stands by (no socket, no run) so no message is answered twice`
|
|
15869
|
+
});
|
|
15870
|
+
}
|
|
15387
15871
|
const cycles = integration?.recent_cycles ?? [];
|
|
15388
15872
|
if (cycles.length > 0) {
|
|
15389
15873
|
const failing = failedCyclesInARow(integration);
|
|
@@ -15582,7 +16066,7 @@ function launchdSightings(label) {
|
|
|
15582
16066
|
}
|
|
15583
16067
|
if (!registrationSkipped()) {
|
|
15584
16068
|
const fullLabel = launchdLabel(label);
|
|
15585
|
-
const uid = typeof process.getuid === "function" ? process.getuid() :
|
|
16069
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : os3.userInfo().uid;
|
|
15586
16070
|
const printed = run2("launchctl", ["print", `gui/${uid}/${fullLabel}`]);
|
|
15587
16071
|
const listed = printed.ok ? null : run2("launchctl", ["list", fullLabel]);
|
|
15588
16072
|
if (printed.ok || listed?.ok === true) {
|
|
@@ -15660,7 +16144,7 @@ function servesHome(label, home) {
|
|
|
15660
16144
|
return sightings(label).some((s) => s.home !== null && sameHome(s.home, home));
|
|
15661
16145
|
}
|
|
15662
16146
|
function systemdUnitPath(label) {
|
|
15663
|
-
return path23.join(
|
|
16147
|
+
return path23.join(os3.homedir(), ".config", "systemd", "user", `${label}.service`);
|
|
15664
16148
|
}
|
|
15665
16149
|
function systemdQuote(value) {
|
|
15666
16150
|
return '"' + value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/"/g, '\\"').replace(/\$/g, "$$$$").replace(/%/g, "%%") + '"';
|
|
@@ -15693,9 +16177,9 @@ function installSystemd(p) {
|
|
|
15693
16177
|
log.info(`wrote ${unitPath}`);
|
|
15694
16178
|
if (registrationSkipped()) return;
|
|
15695
16179
|
run2("systemctl", ["--user", "daemon-reload"]);
|
|
15696
|
-
const linger = run2("loginctl", ["enable-linger",
|
|
16180
|
+
const linger = run2("loginctl", ["enable-linger", os3.userInfo().username]);
|
|
15697
16181
|
if (!linger.ok) {
|
|
15698
|
-
log.warn(`could not enable-linger (service won't survive logout until you run: sudo loginctl enable-linger ${
|
|
16182
|
+
log.warn(`could not enable-linger (service won't survive logout until you run: sudo loginctl enable-linger ${os3.userInfo().username})`);
|
|
15699
16183
|
}
|
|
15700
16184
|
const enabled = run2("systemctl", ["--user", "enable", p.label]);
|
|
15701
16185
|
if (!enabled.ok) throw new Error(`systemctl enable failed: ${enabled.out}`);
|
|
@@ -15740,7 +16224,7 @@ function foreignNote(label, home) {
|
|
|
15740
16224
|
return ` \u2014 but it serves ${loaded.home}, not this config (${home})`;
|
|
15741
16225
|
}
|
|
15742
16226
|
function launchdPlistPath(label) {
|
|
15743
|
-
return path23.join(
|
|
16227
|
+
return path23.join(os3.homedir(), "Library", "LaunchAgents", `${launchdLabel(label)}.plist`);
|
|
15744
16228
|
}
|
|
15745
16229
|
var launchdLabel = (label) => `me.agentchat.${label}`;
|
|
15746
16230
|
function xmlEscape(value) {
|
|
@@ -15811,7 +16295,7 @@ function uninstallLaunchd(label, home) {
|
|
|
15811
16295
|
function statusLaunchd(label, home) {
|
|
15812
16296
|
const fullLabel = launchdLabel(label);
|
|
15813
16297
|
if (registrationSkipped()) return dryRunStatus(`launchd ${fullLabel}`, launchdPlistPath(label));
|
|
15814
|
-
const uid = typeof process.getuid === "function" ? process.getuid() :
|
|
16298
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : os3.userInfo().uid;
|
|
15815
16299
|
const modern = run2("launchctl", ["print", `gui/${uid}/${fullLabel}`]);
|
|
15816
16300
|
const loaded = modern.ok || run2("launchctl", ["list", fullLabel]).ok;
|
|
15817
16301
|
return `launchd ${fullLabel}: ${loaded ? `loaded${foreignNote(label, home)}` : "not loaded"}`;
|
|
@@ -15840,11 +16324,11 @@ function winMode() {
|
|
|
15840
16324
|
return hostOs === "win32" || hostOs === "wsl" ? hostOs : null;
|
|
15841
16325
|
}
|
|
15842
16326
|
function winMasterDir() {
|
|
15843
|
-
return path23.join(
|
|
16327
|
+
return path23.join(os3.homedir(), ".agentchat", "daemon");
|
|
15844
16328
|
}
|
|
15845
16329
|
function winStartupDir(mode) {
|
|
15846
16330
|
if (mode === "win32") {
|
|
15847
|
-
return path23.join(
|
|
16331
|
+
return path23.join(os3.homedir(), "AppData", "Roaming", "Microsoft", "Windows", "Start Menu", "Programs", "Startup");
|
|
15848
16332
|
}
|
|
15849
16333
|
const appdata = run2("cmd.exe", ["/c", "echo %APPDATA%"]).out.split(/\r?\n/).pop()?.trim() ?? "";
|
|
15850
16334
|
const base = run2("wslpath", ["-u", appdata]).out.trim();
|
|
@@ -15892,9 +16376,11 @@ function killLauncher(label, mode) {
|
|
|
15892
16376
|
return run2(mode === "win32" ? "powershell" : "powershell.exe", ["-NoProfile", "-Command", ps]);
|
|
15893
16377
|
}
|
|
15894
16378
|
function lockedDaemonPid(home) {
|
|
16379
|
+
const file = path23.join(home, DAEMON_LOCK_FILE);
|
|
15895
16380
|
try {
|
|
15896
|
-
const
|
|
15897
|
-
|
|
16381
|
+
const holder = parseLease(fs23.readFileSync(file, "utf-8"));
|
|
16382
|
+
if (holder === null || !Number.isInteger(holder.pid) || holder.pid <= 0) return null;
|
|
16383
|
+
return holderLive(holder, { mtimeMs: fs23.statSync(file).mtimeMs }) ? holder.pid : null;
|
|
15898
16384
|
} catch {
|
|
15899
16385
|
return null;
|
|
15900
16386
|
}
|
|
@@ -16043,17 +16529,17 @@ function serviceDefinitionCurrent(opts) {
|
|
|
16043
16529
|
}
|
|
16044
16530
|
|
|
16045
16531
|
// src/host.ts
|
|
16046
|
-
import * as
|
|
16532
|
+
import * as os4 from "os";
|
|
16047
16533
|
import * as path6 from "path";
|
|
16048
16534
|
|
|
16049
16535
|
// src/version.ts
|
|
16050
|
-
var VERSION3 = "0.
|
|
16536
|
+
var VERSION3 = "0.5.0";
|
|
16051
16537
|
|
|
16052
16538
|
// src/host.ts
|
|
16053
16539
|
function codexHome() {
|
|
16054
16540
|
const override = process.env["CODEX_HOME"];
|
|
16055
16541
|
if (override !== void 0 && override.trim().length > 0) return path6.resolve(override);
|
|
16056
|
-
return path6.join(
|
|
16542
|
+
return path6.join(os4.homedir(), ".codex");
|
|
16057
16543
|
}
|
|
16058
16544
|
function identityHome() {
|
|
16059
16545
|
return path6.join(codexHome(), "agentchat");
|
|
@@ -16079,11 +16565,18 @@ function skillDir() {
|
|
|
16079
16565
|
function skillPath() {
|
|
16080
16566
|
return path6.join(skillDir(), MANUAL_FILENAME);
|
|
16081
16567
|
}
|
|
16568
|
+
function runWorkdirFor(home) {
|
|
16569
|
+
return path6.join(home, "daemon-workdir");
|
|
16570
|
+
}
|
|
16571
|
+
function resolveRunWorkdir(home, env = process.env) {
|
|
16572
|
+
const cwd = env["AGENTCHAT_RUN_CWD"]?.trim();
|
|
16573
|
+
return cwd !== void 0 && cwd.length > 0 ? path6.resolve(cwd) : runWorkdirFor(home);
|
|
16574
|
+
}
|
|
16082
16575
|
var LABEL = "Codex";
|
|
16083
16576
|
var CLIENT = { runtime: "codex", version: VERSION3 };
|
|
16084
16577
|
var SERVICE_BASE_LABEL = "agentchatd-codex";
|
|
16085
16578
|
function serviceLabel2() {
|
|
16086
|
-
return serviceLabelFor(SERVICE_BASE_LABEL, identityHome(), path6.join(
|
|
16579
|
+
return serviceLabelFor(SERVICE_BASE_LABEL, identityHome(), path6.join(os4.homedir(), ".codex", "agentchat"));
|
|
16087
16580
|
}
|
|
16088
16581
|
function supersededServiceLabels() {
|
|
16089
16582
|
return serviceLabel2() === SERVICE_BASE_LABEL ? [] : [SERVICE_BASE_LABEL];
|
|
@@ -16110,11 +16603,11 @@ function serviceEnv() {
|
|
|
16110
16603
|
}
|
|
16111
16604
|
|
|
16112
16605
|
// src/placement.ts
|
|
16113
|
-
import * as
|
|
16114
|
-
import * as
|
|
16606
|
+
import * as fs6 from "fs";
|
|
16607
|
+
import * as path8 from "path";
|
|
16115
16608
|
var TOML_START = "# agentchat:start";
|
|
16116
16609
|
var TOML_END = "# agentchat:end";
|
|
16117
|
-
var LEGACY_BUNDLE =
|
|
16610
|
+
var LEGACY_BUNDLE = path8.join("bin", "agentchat.mjs");
|
|
16118
16611
|
var LEGACY_MANUAL = "SKILL.md";
|
|
16119
16612
|
function lineSetsVariable(line, name) {
|
|
16120
16613
|
const trimmed = line.trim();
|
|
@@ -16151,7 +16644,7 @@ function stripQuotes(value) {
|
|
|
16151
16644
|
}
|
|
16152
16645
|
function readKeyFromDotEnv() {
|
|
16153
16646
|
try {
|
|
16154
|
-
for (const line of
|
|
16647
|
+
for (const line of fs6.readFileSync(dotEnvPath(), "utf-8").split(/\r?\n/)) {
|
|
16155
16648
|
if (!lineSetsVariable(line, API_KEY_ENV)) continue;
|
|
16156
16649
|
return stripQuotes(line.slice(line.indexOf("=") + 1).trim()) || void 0;
|
|
16157
16650
|
}
|
|
@@ -16164,12 +16657,12 @@ function placeKey(apiKey) {
|
|
|
16164
16657
|
if (!trimmed || /[\r\n#"'\s]/.test(trimmed)) return { name: "key", status: "failed", detail: "the key is empty or contains characters a .env line cannot carry" };
|
|
16165
16658
|
try {
|
|
16166
16659
|
const file = dotEnvPath();
|
|
16167
|
-
|
|
16168
|
-
const existing =
|
|
16660
|
+
fs6.mkdirSync(path8.dirname(file), { recursive: true });
|
|
16661
|
+
const existing = fs6.existsSync(file) ? fs6.readFileSync(file, "utf-8") : "";
|
|
16169
16662
|
const next = upsertDotEnvLine(existing, API_KEY_ENV, trimmed);
|
|
16170
16663
|
if (next === existing) {
|
|
16171
16664
|
try {
|
|
16172
|
-
|
|
16665
|
+
fs6.chmodSync(file, 384);
|
|
16173
16666
|
} catch {
|
|
16174
16667
|
}
|
|
16175
16668
|
return { name: "key", status: "ok", detail: `${API_KEY_ENV} in ${file}` };
|
|
@@ -16183,11 +16676,11 @@ function placeKey(apiKey) {
|
|
|
16183
16676
|
function removeKey() {
|
|
16184
16677
|
const file = dotEnvPath();
|
|
16185
16678
|
try {
|
|
16186
|
-
if (!
|
|
16187
|
-
const existing =
|
|
16679
|
+
if (!fs6.existsSync(file)) return { name: "key", status: "ok", detail: `no ${API_KEY_ENV} to remove` };
|
|
16680
|
+
const existing = fs6.readFileSync(file, "utf-8");
|
|
16188
16681
|
const next = removeDotEnvLine(existing, API_KEY_ENV);
|
|
16189
16682
|
if (next === existing) return { name: "key", status: "ok", detail: `no ${API_KEY_ENV} in ${file}` };
|
|
16190
|
-
if (next.trim().length === 0)
|
|
16683
|
+
if (next.trim().length === 0) fs6.rmSync(file, { force: true });
|
|
16191
16684
|
else atomicWriteFile(file, next, 384);
|
|
16192
16685
|
return { name: "key", status: "changed", detail: `${API_KEY_ENV} removed from ${file}` };
|
|
16193
16686
|
} catch (err) {
|
|
@@ -16237,600 +16730,470 @@ function handWrittenAgentchatServer(existing) {
|
|
|
16237
16730
|
const lines = [];
|
|
16238
16731
|
let inside = false;
|
|
16239
16732
|
let found = false;
|
|
16240
|
-
for (const line of stripTomlBlock(existing).split(/\r?\n/)) {
|
|
16241
|
-
const header = /^\s*\[\s*([^\]]+?)\s*\]/.exec(line);
|
|
16242
|
-
if (header && !line.trimStart().startsWith("[[")) {
|
|
16243
|
-
const name = header[1].replace(/\s+/g, "");
|
|
16244
|
-
inside = name === `mcp_servers.${MCP_SERVER_NAME}` || name.startsWith(`mcp_servers.${MCP_SERVER_NAME}.`);
|
|
16245
|
-
found ||= inside;
|
|
16246
|
-
}
|
|
16247
|
-
if (inside) lines.push(line);
|
|
16248
|
-
}
|
|
16249
|
-
return found ? lines.join("\n") : null;
|
|
16250
|
-
}
|
|
16251
|
-
function handWrittenSendsClientHeader(existing) {
|
|
16252
|
-
const text = handWrittenAgentchatServer(existing);
|
|
16253
|
-
return text !== null && new RegExp(CLIENT_HEADER, "i").test(text);
|
|
16254
|
-
}
|
|
16255
|
-
function hasUnfencedAgentchatServer(existing) {
|
|
16256
|
-
return new RegExp(`^\\s*\\[mcp_servers\\.${MCP_SERVER_NAME}\\]`, "m").test(stripTomlBlock(existing));
|
|
16257
|
-
}
|
|
16258
|
-
function readConfigText() {
|
|
16259
|
-
try {
|
|
16260
|
-
return fs5.readFileSync(configPath(), "utf-8");
|
|
16261
|
-
} catch {
|
|
16262
|
-
return "";
|
|
16263
|
-
}
|
|
16264
|
-
}
|
|
16265
|
-
function inspectMcpBlock(apiBase) {
|
|
16266
|
-
let config = "";
|
|
16267
|
-
try {
|
|
16268
|
-
config = fs5.readFileSync(configPath(), "utf-8");
|
|
16269
|
-
} catch {
|
|
16270
|
-
return "missing";
|
|
16271
|
-
}
|
|
16272
|
-
if (hasUnfencedAgentchatServer(config)) return "foreign";
|
|
16273
|
-
if (config.includes(mcpBlock(apiBase))) return "current";
|
|
16274
|
-
return config.includes(TOML_START) ? "stale" : "missing";
|
|
16275
|
-
}
|
|
16276
|
-
function placeMcp(apiBase) {
|
|
16277
|
-
const file = configPath();
|
|
16278
|
-
const state = inspectMcpBlock(apiBase);
|
|
16279
|
-
if (state === "foreign") {
|
|
16280
|
-
return { name: "mcp", status: "skipped", detail: `${file} already defines [mcp_servers.${MCP_SERVER_NAME}] outside the agentchat block \u2014 left untouched; remove it and re-run if it is not yours` };
|
|
16281
|
-
}
|
|
16282
|
-
if (state === "current") return { name: "mcp", status: "ok", detail: `[mcp_servers.${MCP_SERVER_NAME}] \u2192 ${hostedMcpUrl2(apiBase)} (bearer token from ${API_KEY_ENV}) in ${file}` };
|
|
16283
|
-
try {
|
|
16284
|
-
fs5.mkdirSync(path7.dirname(file), { recursive: true });
|
|
16285
|
-
const existing = fs5.existsSync(file) ? fs5.readFileSync(file, "utf-8") : "";
|
|
16286
|
-
let mode = 384;
|
|
16287
|
-
try {
|
|
16288
|
-
mode = fs5.statSync(file).mode & 511;
|
|
16289
|
-
} catch {
|
|
16290
|
-
}
|
|
16291
|
-
atomicWriteFile(file, upsertTomlBlock(existing, mcpBlock(apiBase)), mode);
|
|
16292
|
-
return {
|
|
16293
|
-
name: "mcp",
|
|
16294
|
-
status: "changed",
|
|
16295
|
-
detail: `[mcp_servers.${MCP_SERVER_NAME}] \u2192 ${hostedMcpUrl2(apiBase)} (bearer token from ${API_KEY_ENV}) in ${file}${state === "stale" ? " (the previous entry was replaced)" : ""}`
|
|
16296
|
-
};
|
|
16297
|
-
} catch (err) {
|
|
16298
|
-
return { name: "mcp", status: "failed", detail: `could not write ${file}: ${String(err)}` };
|
|
16299
|
-
}
|
|
16300
|
-
}
|
|
16301
|
-
function removeMcp() {
|
|
16302
|
-
const file = configPath();
|
|
16303
|
-
try {
|
|
16304
|
-
if (!fs5.existsSync(file)) return { name: "mcp", status: "ok", detail: "no config.toml" };
|
|
16305
|
-
const existing = fs5.readFileSync(file, "utf-8");
|
|
16306
|
-
const next = stripTomlBlock(existing);
|
|
16307
|
-
if (next === existing) return { name: "mcp", status: "ok", detail: `no agentchat block in ${file}` };
|
|
16308
|
-
const mode = fs5.statSync(file).mode & 511;
|
|
16309
|
-
atomicWriteFile(file, next, mode);
|
|
16310
|
-
return { name: "mcp", status: "changed", detail: `[mcp_servers.${MCP_SERVER_NAME}] removed from ${file}` };
|
|
16311
|
-
} catch (err) {
|
|
16312
|
-
return { name: "mcp", status: "failed", detail: `could not update ${file}: ${String(err)}` };
|
|
16313
|
-
}
|
|
16314
|
-
}
|
|
16315
|
-
function skillPresent() {
|
|
16316
|
-
return fs5.existsSync(skillPath());
|
|
16317
|
-
}
|
|
16318
|
-
function manualStep(result, removedLegacy) {
|
|
16319
|
-
const status = result.state === "failed" ? "failed" : result.upToDate === false ? "warned" : result.written || removedLegacy ? "changed" : "ok";
|
|
16320
|
-
return { name: "manual", status, detail: `${describeManualSync(result)}${removedLegacy ? " (old on-disk manual removed)" : ""}` };
|
|
16321
|
-
}
|
|
16322
|
-
async function placeSkill(manual, apiBase) {
|
|
16323
|
-
const result = await syncManual2({ path: skillPath(), served: manual, apiBase });
|
|
16324
|
-
const legacy = path7.join(identityHome(), LEGACY_MANUAL);
|
|
16325
|
-
let removedLegacy = false;
|
|
16326
|
-
try {
|
|
16327
|
-
if (fs5.existsSync(legacy)) {
|
|
16328
|
-
fs5.rmSync(legacy, { force: true });
|
|
16329
|
-
removedLegacy = true;
|
|
16330
|
-
}
|
|
16331
|
-
} catch {
|
|
16332
|
-
}
|
|
16333
|
-
return manualStep(result, removedLegacy);
|
|
16334
|
-
}
|
|
16335
|
-
function removeSkill() {
|
|
16336
|
-
try {
|
|
16337
|
-
let removed = false;
|
|
16338
|
-
if (fs5.existsSync(skillPath())) {
|
|
16339
|
-
fs5.rmSync(skillDir(), { recursive: true, force: true });
|
|
16340
|
-
removed = true;
|
|
16341
|
-
}
|
|
16342
|
-
const legacy = path7.join(identityHome(), LEGACY_MANUAL);
|
|
16343
|
-
if (fs5.existsSync(legacy)) {
|
|
16344
|
-
fs5.rmSync(legacy, { force: true });
|
|
16345
|
-
removed = true;
|
|
16346
|
-
}
|
|
16347
|
-
return { name: "manual", status: removed ? "changed" : "ok", detail: removed ? "agentchat skill removed" : "no agentchat skill to remove" };
|
|
16348
|
-
} catch (err) {
|
|
16349
|
-
return { name: "manual", status: "failed", detail: `could not remove the agentchat skill: ${String(err)}` };
|
|
16350
|
-
}
|
|
16351
|
-
}
|
|
16352
|
-
function placeIdentityLine(handle, identityLine) {
|
|
16353
|
-
if (identityLine === null) {
|
|
16354
|
-
return {
|
|
16355
|
-
name: "identity",
|
|
16356
|
-
status: "skipped",
|
|
16357
|
-
detail: `identity line for @${handle} not written \u2014 the served texts (GET /v1/texts) could not be fetched and none are cached; run \`doctor --fix\` once online`
|
|
16358
|
-
};
|
|
16359
|
-
}
|
|
16360
|
-
try {
|
|
16361
|
-
const current = anchorIsCurrentAt(anchorFile(), identityLine, handle);
|
|
16362
|
-
if (!current) writeAnchor(anchorFile(), renderAnchorBlock(identityLine, handle), handle);
|
|
16363
|
-
return { name: "identity", status: current ? "ok" : "changed", detail: `identity line for @${handle} in ${anchorFile()}` };
|
|
16364
|
-
} catch (err) {
|
|
16365
|
-
return { name: "identity", status: "failed", detail: `could not write the identity line to ${anchorFile()}: ${String(err)}` };
|
|
16366
|
-
}
|
|
16367
|
-
}
|
|
16368
|
-
function placeOffer() {
|
|
16369
|
-
try {
|
|
16370
|
-
const declined = offerDeclined(identityHome());
|
|
16371
|
-
writeAnchor(anchorFile(), declined ? renderDeclinedBlock(hostCopy()) : renderUnregisteredBlock(hostCopy()));
|
|
16372
|
-
return { name: "identity", status: "changed", detail: declined ? `${path7.basename(anchorFile())}: AgentChat present, not asking` : `${path7.basename(anchorFile())}: setup offer (no account yet)` };
|
|
16373
|
-
} catch (err) {
|
|
16374
|
-
return { name: "identity", status: "failed", detail: `could not write ${anchorFile()}: ${String(err)}` };
|
|
16375
|
-
}
|
|
16376
|
-
}
|
|
16377
|
-
function leafIsOurs(leaf) {
|
|
16378
|
-
return typeof leaf.command === "string" && leaf.command.replace(/\\/g, "/").includes("agentchat/bin/agentchat.mjs");
|
|
16379
|
-
}
|
|
16380
|
-
function withoutLegacyHooks(doc) {
|
|
16381
|
-
const hooks = doc["hooks"];
|
|
16382
|
-
if (!hooks || typeof hooks !== "object" || Array.isArray(hooks)) return { doc, removed: 0 };
|
|
16383
|
-
let removed = 0;
|
|
16384
|
-
const nextHooks = {};
|
|
16385
|
-
for (const [event, groups] of Object.entries(hooks)) {
|
|
16386
|
-
if (!Array.isArray(groups)) {
|
|
16387
|
-
nextHooks[event] = groups;
|
|
16388
|
-
continue;
|
|
16389
|
-
}
|
|
16390
|
-
const kept = [];
|
|
16391
|
-
for (const group of groups) {
|
|
16392
|
-
if (!group || !Array.isArray(group.hooks)) {
|
|
16393
|
-
kept.push(group);
|
|
16394
|
-
continue;
|
|
16395
|
-
}
|
|
16396
|
-
const leaves = group.hooks.filter((leaf) => {
|
|
16397
|
-
const ours = leafIsOurs(leaf);
|
|
16398
|
-
if (ours) removed += 1;
|
|
16399
|
-
return !ours;
|
|
16400
|
-
});
|
|
16401
|
-
if (leaves.length === 0) continue;
|
|
16402
|
-
kept.push(leaves.length === group.hooks.length ? group : { ...group, hooks: leaves });
|
|
16403
|
-
}
|
|
16404
|
-
if (kept.length > 0) nextHooks[event] = kept;
|
|
16405
|
-
}
|
|
16406
|
-
const next = { ...doc };
|
|
16407
|
-
if (Object.keys(nextHooks).length > 0) next["hooks"] = nextHooks;
|
|
16408
|
-
else delete next["hooks"];
|
|
16409
|
-
return { doc: next, removed };
|
|
16410
|
-
}
|
|
16411
|
-
function legacyHooksPresent() {
|
|
16412
|
-
try {
|
|
16413
|
-
return withoutLegacyHooks(JSON.parse(fs5.readFileSync(hooksPath(), "utf-8"))).removed > 0;
|
|
16414
|
-
} catch {
|
|
16415
|
-
return false;
|
|
16416
|
-
}
|
|
16417
|
-
}
|
|
16418
|
-
function legacyBundlePresent() {
|
|
16419
|
-
return fs5.existsSync(path7.join(identityHome(), LEGACY_BUNDLE));
|
|
16420
|
-
}
|
|
16421
|
-
function removeLegacyWiring() {
|
|
16422
|
-
const notes = [];
|
|
16423
|
-
const file = hooksPath();
|
|
16424
|
-
if (fs5.existsSync(file)) {
|
|
16425
|
-
try {
|
|
16426
|
-
const parsed = JSON.parse(fs5.readFileSync(file, "utf-8"));
|
|
16427
|
-
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
16428
|
-
const { doc, removed } = withoutLegacyHooks(parsed);
|
|
16429
|
-
if (removed > 0) {
|
|
16430
|
-
let mode = 384;
|
|
16431
|
-
try {
|
|
16432
|
-
mode = fs5.statSync(file).mode & 511;
|
|
16433
|
-
} catch {
|
|
16434
|
-
}
|
|
16435
|
-
if (Object.keys(doc).length === 0) fs5.unlinkSync(file);
|
|
16436
|
-
else atomicWriteFile(file, JSON.stringify(doc, null, 2) + "\n", mode);
|
|
16437
|
-
notes.push(`${removed} lifecycle hook${removed === 1 ? "" : "s"} removed from hooks.json (receiving no longer needs hooks)`);
|
|
16438
|
-
}
|
|
16439
|
-
}
|
|
16440
|
-
} catch (err) {
|
|
16441
|
-
return { name: "legacy", status: "failed", detail: `${file} could not be read as JSON; the old AgentChat hooks were left in place: ${String(err)}` };
|
|
16442
|
-
}
|
|
16443
|
-
}
|
|
16444
|
-
const bundle = path7.join(identityHome(), LEGACY_BUNDLE);
|
|
16445
|
-
if (fs5.existsSync(bundle)) {
|
|
16446
|
-
try {
|
|
16447
|
-
fs5.rmSync(bundle, { force: true });
|
|
16448
|
-
notes.push("stable CLI bundle removed");
|
|
16449
|
-
} catch {
|
|
16733
|
+
for (const line of stripTomlBlock(existing).split(/\r?\n/)) {
|
|
16734
|
+
const header = /^\s*\[\s*([^\]]+?)\s*\]/.exec(line);
|
|
16735
|
+
if (header && !line.trimStart().startsWith("[[")) {
|
|
16736
|
+
const name = header[1].replace(/\s+/g, "");
|
|
16737
|
+
inside = name === `mcp_servers.${MCP_SERVER_NAME}` || name.startsWith(`mcp_servers.${MCP_SERVER_NAME}.`);
|
|
16738
|
+
found ||= inside;
|
|
16450
16739
|
}
|
|
16740
|
+
if (inside) lines.push(line);
|
|
16451
16741
|
}
|
|
16452
|
-
|
|
16453
|
-
log.debug(`legacy cleanup: ${notes.join("; ")}`);
|
|
16454
|
-
return { name: "legacy", status: "changed", detail: notes.join("; ") };
|
|
16742
|
+
return found ? lines.join("\n") : null;
|
|
16455
16743
|
}
|
|
16456
|
-
|
|
16457
|
-
const
|
|
16458
|
-
|
|
16459
|
-
if (legacy) steps.push(legacy);
|
|
16460
|
-
steps.push(await placeSkill(manual, identity?.apiBase ?? null));
|
|
16461
|
-
if (identity) {
|
|
16462
|
-
steps.push(placeKey(identity.apiKey));
|
|
16463
|
-
steps.push(placeMcp(identity.apiBase));
|
|
16464
|
-
steps.push(placeIdentityLine(identity.handle, identity.identityLine));
|
|
16465
|
-
} else {
|
|
16466
|
-
steps.push(placeOffer());
|
|
16467
|
-
}
|
|
16468
|
-
return steps;
|
|
16744
|
+
function handWrittenSendsClientHeader(existing) {
|
|
16745
|
+
const text = handWrittenAgentchatServer(existing);
|
|
16746
|
+
return text !== null && new RegExp(CLIENT_HEADER, "i").test(text);
|
|
16469
16747
|
}
|
|
16470
|
-
function
|
|
16471
|
-
return [
|
|
16748
|
+
function hasUnfencedAgentchatServer(existing) {
|
|
16749
|
+
return new RegExp(`^\\s*\\[mcp_servers\\.${MCP_SERVER_NAME}\\]`, "m").test(stripTomlBlock(existing));
|
|
16472
16750
|
}
|
|
16473
|
-
function
|
|
16474
|
-
const steps = [];
|
|
16475
|
-
const legacy = removeLegacyWiring();
|
|
16476
|
-
if (legacy) steps.push(legacy);
|
|
16477
|
-
steps.push(removeKey());
|
|
16478
|
-
steps.push(removeMcp());
|
|
16479
|
-
steps.push(removeSkill());
|
|
16751
|
+
function readConfigText() {
|
|
16480
16752
|
try {
|
|
16481
|
-
|
|
16482
|
-
} catch
|
|
16483
|
-
|
|
16753
|
+
return fs6.readFileSync(configPath(), "utf-8");
|
|
16754
|
+
} catch {
|
|
16755
|
+
return "";
|
|
16484
16756
|
}
|
|
16485
|
-
return steps;
|
|
16486
16757
|
}
|
|
16487
|
-
function
|
|
16488
|
-
let
|
|
16489
|
-
let current;
|
|
16758
|
+
function inspectMcpBlock(apiBase) {
|
|
16759
|
+
let config = "";
|
|
16490
16760
|
try {
|
|
16491
|
-
|
|
16492
|
-
|
|
16493
|
-
|
|
16494
|
-
return { name: "identity", ok: false, verdict: "FAIL", detail: `cannot read ${anchorFile()}: ${err instanceof Error ? err.message : String(err)}` };
|
|
16761
|
+
config = fs6.readFileSync(configPath(), "utf-8");
|
|
16762
|
+
} catch {
|
|
16763
|
+
return "missing";
|
|
16495
16764
|
}
|
|
16496
|
-
|
|
16497
|
-
return
|
|
16498
|
-
|
|
16499
|
-
ok: current === true || current === null && claimed === identity.handle,
|
|
16500
|
-
...older ? { verdict: "WARN" } : {},
|
|
16501
|
-
detail: current === true ? `identity line for @${identity.handle} in ${anchorFile()}` : current === null && claimed === identity.handle ? `identity line for @${identity.handle} in ${anchorFile()} (served texts unavailable \u2014 currency not checked)` : claimed === null ? `identity line missing from ${anchorFile()}` : claimed !== identity.handle ? `${anchorFile()} says @${claimed} but this agent is @${identity.handle}` : `${anchorFile()} carries an older identity text (or a second AgentChat block) \u2014 install or \`doctor --fix\` rewrites it`
|
|
16502
|
-
};
|
|
16765
|
+
if (hasUnfencedAgentchatServer(config)) return "foreign";
|
|
16766
|
+
if (config.includes(mcpBlock(apiBase))) return "current";
|
|
16767
|
+
return config.includes(TOML_START) ? "stale" : "missing";
|
|
16503
16768
|
}
|
|
16504
|
-
function
|
|
16505
|
-
const
|
|
16506
|
-
|
|
16507
|
-
|
|
16508
|
-
|
|
16509
|
-
checks.push({
|
|
16510
|
-
name: "key",
|
|
16511
|
-
ok: inDotEnv === identity.apiKey,
|
|
16512
|
-
detail: inDotEnv === identity.apiKey ? `${API_KEY_ENV} in ${dotEnvPath()} matches this agent's credentials` : inDotEnv === void 0 ? `${API_KEY_ENV} is not in ${dotEnvPath()} \u2014 the hosted tools cannot authenticate` : `${API_KEY_ENV} in ${dotEnvPath()} differs from this agent's credentials`
|
|
16513
|
-
});
|
|
16769
|
+
function placeMcp(apiBase) {
|
|
16770
|
+
const file = configPath();
|
|
16771
|
+
const state = inspectMcpBlock(apiBase);
|
|
16772
|
+
if (state === "foreign") {
|
|
16773
|
+
return { name: "mcp", status: "skipped", detail: `${file} already defines [mcp_servers.${MCP_SERVER_NAME}] outside the agentchat block \u2014 left untouched; remove it and re-run if it is not yours` };
|
|
16514
16774
|
}
|
|
16515
|
-
|
|
16516
|
-
checks.push({ name: "manual", ok: skill.state === "current" || skill.state === "unchecked", verdict: skill.verdict, detail: skill.detail });
|
|
16517
|
-
const mcp = inspectMcpBlock(identity?.apiBase ?? process.env["AGENTCHAT_API_BASE"]?.trim() ?? "https://api.agentchat.me");
|
|
16518
|
-
const handWrittenNamesClient = mcp === "foreign" && handWrittenSendsClientHeader(readConfigText());
|
|
16519
|
-
checks.push({
|
|
16520
|
-
name: "mcp",
|
|
16521
|
-
// A hand-written entry is the user's: nothing for this integration to
|
|
16522
|
-
// repair (ok), but said — a WARN — when it does not name this runtime to
|
|
16523
|
-
// the hosted tools: they then show it the wake-webhook tools, a second
|
|
16524
|
-
// way of being woken it does not need.
|
|
16525
|
-
ok: mcp === "current" || mcp === "foreign",
|
|
16526
|
-
...mcp === "foreign" && !handWrittenNamesClient ? { verdict: "WARN" } : {},
|
|
16527
|
-
detail: mcp === "current" ? `[mcp_servers.${MCP_SERVER_NAME}] \u2192 hosted tools, bearer token from ${API_KEY_ENV}, named as Codex ${CLIENT.version}` : mcp === "foreign" ? handWrittenNamesClient ? `[mcp_servers.${MCP_SERVER_NAME}] is managed by hand in ${configPath()}` : `[mcp_servers.${MCP_SERVER_NAME}] is managed by hand in ${configPath()} and does not send ${CLIENT_HEADER}, so the hosted tools take this agent for an unknown client and show it the wake-webhook tools \u2014 add \`${mcpHttpHeadersLine()}\` to it` : mcp === "stale" ? `the agentchat block in ${configPath()} is from an older release` : `no [mcp_servers.${MCP_SERVER_NAME}] in ${configPath()} \u2014 the agent has no AgentChat tools`
|
|
16528
|
-
});
|
|
16529
|
-
const leftovers = [legacyHooksPresent() ? "hooks in hooks.json" : null, legacyBundlePresent() ? "stable CLI bundle" : null].filter((v) => v !== null);
|
|
16530
|
-
checks.push({ name: "legacy", ok: leftovers.length === 0, detail: leftovers.length === 0 ? "no pre-0.1.0 wiring left" : `pre-0.1.0 wiring still present: ${leftovers.join(", ")}` });
|
|
16531
|
-
return checks;
|
|
16532
|
-
}
|
|
16533
|
-
function placementMark(step) {
|
|
16534
|
-
if ("status" in step) return step.status === "failed" ? "\u2717" : step.status === "skipped" || step.status === "warned" ? "\u2013" : "\u2713";
|
|
16535
|
-
if (step.verdict !== void 0) return step.verdict === "PASS" ? "\u2713" : step.verdict === "WARN" ? "\u2013" : "\u2717";
|
|
16536
|
-
return step.ok ? "\u2713" : "\u2717";
|
|
16537
|
-
}
|
|
16538
|
-
function formatPlacement(steps) {
|
|
16539
|
-
return steps.map((step) => ` ${placementMark(step)} ${step.name}: ${step.detail}`);
|
|
16540
|
-
}
|
|
16541
|
-
|
|
16542
|
-
// src/identity.ts
|
|
16543
|
-
import * as path10 from "path";
|
|
16544
|
-
|
|
16545
|
-
// node_modules/.pnpm/@agentchatme+agent-core@0.4.1/node_modules/@agentchatme/agent-core/dist/chunk-AE4XHKHQ.js
|
|
16546
|
-
var DEFAULT_GRACE_MS = 5e3;
|
|
16547
|
-
var DEFAULT_DRAIN_MS = 2e3;
|
|
16548
|
-
var DEFAULT_ABANDON_MS = 5e3;
|
|
16549
|
-
var STDERR_TAIL_CHARS = 400;
|
|
16550
|
-
function redactDiagnostic(value, max = STDERR_TAIL_CHARS) {
|
|
16551
|
-
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);
|
|
16552
|
-
}
|
|
16553
|
-
var KILL_TIMEOUT_MS = 5e3;
|
|
16554
|
-
function killProcessTree(child, signal) {
|
|
16555
|
-
if (child.pid === void 0) return;
|
|
16775
|
+
if (state === "current") return { name: "mcp", status: "ok", detail: `[mcp_servers.${MCP_SERVER_NAME}] \u2192 ${hostedMcpUrl2(apiBase)} (bearer token from ${API_KEY_ENV}) in ${file}` };
|
|
16556
16776
|
try {
|
|
16557
|
-
|
|
16558
|
-
|
|
16559
|
-
|
|
16560
|
-
stdio: "ignore",
|
|
16561
|
-
timeout: KILL_TIMEOUT_MS
|
|
16562
|
-
});
|
|
16563
|
-
} else {
|
|
16564
|
-
process.kill(-child.pid, signal);
|
|
16565
|
-
}
|
|
16566
|
-
} catch {
|
|
16777
|
+
fs6.mkdirSync(path8.dirname(file), { recursive: true });
|
|
16778
|
+
const existing = fs6.existsSync(file) ? fs6.readFileSync(file, "utf-8") : "";
|
|
16779
|
+
let mode = 384;
|
|
16567
16780
|
try {
|
|
16568
|
-
|
|
16781
|
+
mode = fs6.statSync(file).mode & 511;
|
|
16569
16782
|
} catch {
|
|
16570
16783
|
}
|
|
16571
|
-
|
|
16572
|
-
|
|
16573
|
-
|
|
16574
|
-
|
|
16575
|
-
}
|
|
16576
|
-
var WINDOWS_SWEEP_TIMEOUT_MS = 6e4;
|
|
16577
|
-
function sweepWindowsDescendants(rootPid, aliveFromMs, aliveUntilMs, options = {}) {
|
|
16578
|
-
if (process.platform !== "win32" || !Number.isInteger(rootPid) || rootPid <= 0) return Promise.resolve(null);
|
|
16579
|
-
const script = [
|
|
16580
|
-
"$ErrorActionPreference = 'Continue'",
|
|
16581
|
-
// Progress records ('Preparing modules for first use') would reach stderr as CLIXML.
|
|
16582
|
-
"$ProgressPreference = 'SilentlyContinue'",
|
|
16583
|
-
`$from = [DateTime]::FromFileTime(${fileTime(aliveFromMs - 1e3)})`,
|
|
16584
|
-
`$until = [DateTime]::FromFileTime(${fileTime(aliveUntilMs + 1e3)})`,
|
|
16585
|
-
"Write-Output ('window ' + $from.ToUniversalTime().ToString('o') + ' ' + $until.ToUniversalTime().ToString('o'))",
|
|
16586
|
-
`foreach ($p in @(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${rootPid}')) {`,
|
|
16587
|
-
" Write-Output ('candidate ' + $p.ProcessId + ' ' + $p.CreationDate.ToUniversalTime().ToString('o'))",
|
|
16588
|
-
" if ($p.CreationDate -ge $from -and $p.CreationDate -le $until) {",
|
|
16589
|
-
" & taskkill.exe /T /F /PID $p.ProcessId 2>&1 | Out-Null",
|
|
16590
|
-
" Write-Output ('kill ' + $p.ProcessId + ' ' + $LASTEXITCODE)",
|
|
16591
|
-
" }",
|
|
16592
|
-
"}"
|
|
16593
|
-
].join("\n");
|
|
16594
|
-
return new Promise((resolve6) => {
|
|
16595
|
-
let stdout = "";
|
|
16596
|
-
let stderr = "";
|
|
16597
|
-
let timedOut = false;
|
|
16598
|
-
let done = false;
|
|
16599
|
-
const finish = (exitCode) => {
|
|
16600
|
-
if (done) return;
|
|
16601
|
-
done = true;
|
|
16602
|
-
clearTimeout(timer);
|
|
16603
|
-
const lines = stdout.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
|
|
16604
|
-
resolve6({
|
|
16605
|
-
exitCode,
|
|
16606
|
-
timedOut,
|
|
16607
|
-
candidates: lines.filter((l) => l.startsWith("candidate ")).map((l) => l.slice("candidate ".length)),
|
|
16608
|
-
killed: lines.filter((l) => l.startsWith("kill ")).map((l) => l.split(" ")).map(([, pid, code]) => ({ pid: Number(pid), code: Number(code) })),
|
|
16609
|
-
window: lines.find((l) => l.startsWith("window "))?.slice("window ".length) ?? null,
|
|
16610
|
-
stderr: redactDiagnostic(stderr)
|
|
16611
|
-
});
|
|
16612
|
-
};
|
|
16613
|
-
let sweeper;
|
|
16614
|
-
try {
|
|
16615
|
-
sweeper = spawnCommand(
|
|
16616
|
-
"powershell.exe",
|
|
16617
|
-
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")],
|
|
16618
|
-
{ stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
|
|
16619
|
-
);
|
|
16620
|
-
} catch (err) {
|
|
16621
|
-
stderr = String(err);
|
|
16622
|
-
finish(null);
|
|
16623
|
-
return;
|
|
16624
|
-
}
|
|
16625
|
-
const timer = setTimeout(() => {
|
|
16626
|
-
timedOut = true;
|
|
16627
|
-
try {
|
|
16628
|
-
sweeper.kill();
|
|
16629
|
-
} catch {
|
|
16630
|
-
}
|
|
16631
|
-
finish(null);
|
|
16632
|
-
}, options.timeoutMs ?? WINDOWS_SWEEP_TIMEOUT_MS);
|
|
16633
|
-
timer.unref?.();
|
|
16634
|
-
sweeper.stdout?.on("data", (c) => {
|
|
16635
|
-
stdout = (stdout + String(c)).slice(-16e3);
|
|
16636
|
-
});
|
|
16637
|
-
sweeper.stderr?.on("data", (c) => {
|
|
16638
|
-
stderr = (stderr + String(c)).slice(-4e3);
|
|
16639
|
-
});
|
|
16640
|
-
sweeper.on("error", (err) => {
|
|
16641
|
-
stderr += String(err);
|
|
16642
|
-
finish(null);
|
|
16643
|
-
});
|
|
16644
|
-
sweeper.on("close", (code) => finish(code));
|
|
16645
|
-
});
|
|
16646
|
-
}
|
|
16647
|
-
function describeWindowsSweep(sweep) {
|
|
16648
|
-
const killed = sweep.killed.map((k) => `${k.pid} (taskkill ${k.code})`).join(", ") || "none";
|
|
16649
|
-
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}` : ""}`;
|
|
16650
|
-
}
|
|
16651
|
-
function spawnRun(spec) {
|
|
16652
|
-
const started = Date.now();
|
|
16653
|
-
const graceMs = spec.graceMs ?? DEFAULT_GRACE_MS;
|
|
16654
|
-
const drainMs = spec.drainMs ?? DEFAULT_DRAIN_MS;
|
|
16655
|
-
const abandonMs = spec.abandonMs ?? DEFAULT_ABANDON_MS;
|
|
16656
|
-
return new Promise((resolve6) => {
|
|
16657
|
-
let settled = false;
|
|
16658
|
-
let stdoutBytes = 0;
|
|
16659
|
-
let stderrTail = "";
|
|
16660
|
-
let timedOut = false;
|
|
16661
|
-
let interrupted = false;
|
|
16662
|
-
let terminating = false;
|
|
16663
|
-
let exited = null;
|
|
16664
|
-
const timers = /* @__PURE__ */ new Set();
|
|
16665
|
-
let onAbort = null;
|
|
16666
|
-
let child = null;
|
|
16667
|
-
const later = (ms, fn) => {
|
|
16668
|
-
const timer = setTimeout(() => {
|
|
16669
|
-
timers.delete(timer);
|
|
16670
|
-
fn();
|
|
16671
|
-
}, ms);
|
|
16672
|
-
timers.add(timer);
|
|
16673
|
-
};
|
|
16674
|
-
const finish = (outcome) => {
|
|
16675
|
-
if (settled) return;
|
|
16676
|
-
settled = true;
|
|
16677
|
-
for (const timer of timers) clearTimeout(timer);
|
|
16678
|
-
timers.clear();
|
|
16679
|
-
if (onAbort) spec.signal?.removeEventListener("abort", onAbort);
|
|
16680
|
-
resolve6({ ...outcome, durationMs: Date.now() - started });
|
|
16681
|
-
};
|
|
16682
|
-
const detach = () => {
|
|
16683
|
-
if (child === null) return;
|
|
16684
|
-
for (const stream of [child.stdin, child.stdout, child.stderr]) {
|
|
16685
|
-
try {
|
|
16686
|
-
stream?.destroy();
|
|
16687
|
-
} catch {
|
|
16688
|
-
}
|
|
16689
|
-
}
|
|
16690
|
-
try {
|
|
16691
|
-
child.unref();
|
|
16692
|
-
} catch {
|
|
16693
|
-
}
|
|
16784
|
+
atomicWriteFile(file, upsertTomlBlock(existing, mcpBlock(apiBase)), mode);
|
|
16785
|
+
return {
|
|
16786
|
+
name: "mcp",
|
|
16787
|
+
status: "changed",
|
|
16788
|
+
detail: `[mcp_servers.${MCP_SERVER_NAME}] \u2192 ${hostedMcpUrl2(apiBase)} (bearer token from ${API_KEY_ENV}) in ${file}${state === "stale" ? " (the previous entry was replaced)" : ""}`
|
|
16694
16789
|
};
|
|
16695
|
-
|
|
16696
|
-
|
|
16697
|
-
|
|
16698
|
-
|
|
16699
|
-
|
|
16700
|
-
|
|
16701
|
-
|
|
16702
|
-
|
|
16703
|
-
|
|
16704
|
-
|
|
16705
|
-
|
|
16706
|
-
|
|
16707
|
-
|
|
16790
|
+
} catch (err) {
|
|
16791
|
+
return { name: "mcp", status: "failed", detail: `could not write ${file}: ${String(err)}` };
|
|
16792
|
+
}
|
|
16793
|
+
}
|
|
16794
|
+
function removeMcp() {
|
|
16795
|
+
const file = configPath();
|
|
16796
|
+
try {
|
|
16797
|
+
if (!fs6.existsSync(file)) return { name: "mcp", status: "ok", detail: "no config.toml" };
|
|
16798
|
+
const existing = fs6.readFileSync(file, "utf-8");
|
|
16799
|
+
const next = stripTomlBlock(existing);
|
|
16800
|
+
if (next === existing) return { name: "mcp", status: "ok", detail: `no agentchat block in ${file}` };
|
|
16801
|
+
const mode = fs6.statSync(file).mode & 511;
|
|
16802
|
+
atomicWriteFile(file, next, mode);
|
|
16803
|
+
return { name: "mcp", status: "changed", detail: `[mcp_servers.${MCP_SERVER_NAME}] removed from ${file}` };
|
|
16804
|
+
} catch (err) {
|
|
16805
|
+
return { name: "mcp", status: "failed", detail: `could not update ${file}: ${String(err)}` };
|
|
16806
|
+
}
|
|
16807
|
+
}
|
|
16808
|
+
function skillPresent() {
|
|
16809
|
+
return fs6.existsSync(skillPath());
|
|
16810
|
+
}
|
|
16811
|
+
function manualStep(result, removedLegacy) {
|
|
16812
|
+
const status = result.state === "failed" ? "failed" : result.upToDate === false ? "warned" : result.written || removedLegacy ? "changed" : "ok";
|
|
16813
|
+
return { name: "manual", status, detail: `${describeManualSync(result)}${removedLegacy ? " (old on-disk manual removed)" : ""}` };
|
|
16814
|
+
}
|
|
16815
|
+
async function placeSkill(manual, apiBase) {
|
|
16816
|
+
const result = await syncManual2({ path: skillPath(), served: manual, apiBase });
|
|
16817
|
+
const legacy = path8.join(identityHome(), LEGACY_MANUAL);
|
|
16818
|
+
let removedLegacy = false;
|
|
16819
|
+
try {
|
|
16820
|
+
if (fs6.existsSync(legacy)) {
|
|
16821
|
+
fs6.rmSync(legacy, { force: true });
|
|
16822
|
+
removedLegacy = true;
|
|
16823
|
+
}
|
|
16824
|
+
} catch {
|
|
16825
|
+
}
|
|
16826
|
+
return manualStep(result, removedLegacy);
|
|
16827
|
+
}
|
|
16828
|
+
function removeSkill() {
|
|
16829
|
+
try {
|
|
16830
|
+
let removed = false;
|
|
16831
|
+
if (fs6.existsSync(skillPath())) {
|
|
16832
|
+
fs6.rmSync(skillDir(), { recursive: true, force: true });
|
|
16833
|
+
removed = true;
|
|
16834
|
+
}
|
|
16835
|
+
const legacy = path8.join(identityHome(), LEGACY_MANUAL);
|
|
16836
|
+
if (fs6.existsSync(legacy)) {
|
|
16837
|
+
fs6.rmSync(legacy, { force: true });
|
|
16838
|
+
removed = true;
|
|
16839
|
+
}
|
|
16840
|
+
return { name: "manual", status: removed ? "changed" : "ok", detail: removed ? "agentchat skill removed" : "no agentchat skill to remove" };
|
|
16841
|
+
} catch (err) {
|
|
16842
|
+
return { name: "manual", status: "failed", detail: `could not remove the agentchat skill: ${String(err)}` };
|
|
16843
|
+
}
|
|
16844
|
+
}
|
|
16845
|
+
function placeIdentityLine(handle, identityLine) {
|
|
16846
|
+
if (identityLine === null) {
|
|
16847
|
+
return {
|
|
16848
|
+
name: "identity",
|
|
16849
|
+
status: "skipped",
|
|
16850
|
+
detail: `identity line for @${handle} not written \u2014 the served texts (GET /v1/texts) could not be fetched and none are cached; run \`doctor --fix\` once online`
|
|
16708
16851
|
};
|
|
16709
|
-
|
|
16710
|
-
|
|
16711
|
-
|
|
16852
|
+
}
|
|
16853
|
+
try {
|
|
16854
|
+
const current = anchorIsCurrentAt(anchorFile(), identityLine, handle);
|
|
16855
|
+
if (!current) writeAnchor(anchorFile(), renderAnchorBlock(identityLine, handle), handle);
|
|
16856
|
+
return { name: "identity", status: current ? "ok" : "changed", detail: `identity line for @${handle} in ${anchorFile()}` };
|
|
16857
|
+
} catch (err) {
|
|
16858
|
+
return { name: "identity", status: "failed", detail: `could not write the identity line to ${anchorFile()}: ${String(err)}` };
|
|
16859
|
+
}
|
|
16860
|
+
}
|
|
16861
|
+
function placeOffer() {
|
|
16862
|
+
try {
|
|
16863
|
+
const declined = offerDeclined(identityHome());
|
|
16864
|
+
writeAnchor(anchorFile(), declined ? renderDeclinedBlock(hostCopy()) : renderUnregisteredBlock(hostCopy()));
|
|
16865
|
+
return { name: "identity", status: "changed", detail: declined ? `${path8.basename(anchorFile())}: AgentChat present, not asking` : `${path8.basename(anchorFile())}: setup offer (no account yet)` };
|
|
16866
|
+
} catch (err) {
|
|
16867
|
+
return { name: "identity", status: "failed", detail: `could not write ${anchorFile()}: ${String(err)}` };
|
|
16868
|
+
}
|
|
16869
|
+
}
|
|
16870
|
+
function leafIsOurs(leaf) {
|
|
16871
|
+
return typeof leaf.command === "string" && leaf.command.replace(/\\/g, "/").includes("agentchat/bin/agentchat.mjs");
|
|
16872
|
+
}
|
|
16873
|
+
function withoutLegacyHooks(doc) {
|
|
16874
|
+
const hooks = doc["hooks"];
|
|
16875
|
+
if (!hooks || typeof hooks !== "object" || Array.isArray(hooks)) return { doc, removed: 0 };
|
|
16876
|
+
let removed = 0;
|
|
16877
|
+
const nextHooks = {};
|
|
16878
|
+
for (const [event, groups] of Object.entries(hooks)) {
|
|
16879
|
+
if (!Array.isArray(groups)) {
|
|
16880
|
+
nextHooks[event] = groups;
|
|
16881
|
+
continue;
|
|
16712
16882
|
}
|
|
16713
|
-
|
|
16714
|
-
|
|
16715
|
-
|
|
16716
|
-
|
|
16717
|
-
|
|
16718
|
-
|
|
16719
|
-
|
|
16720
|
-
|
|
16883
|
+
const kept = [];
|
|
16884
|
+
for (const group of groups) {
|
|
16885
|
+
if (!group || !Array.isArray(group.hooks)) {
|
|
16886
|
+
kept.push(group);
|
|
16887
|
+
continue;
|
|
16888
|
+
}
|
|
16889
|
+
const leaves = group.hooks.filter((leaf) => {
|
|
16890
|
+
const ours = leafIsOurs(leaf);
|
|
16891
|
+
if (ours) removed += 1;
|
|
16892
|
+
return !ours;
|
|
16721
16893
|
});
|
|
16722
|
-
|
|
16723
|
-
|
|
16724
|
-
return;
|
|
16894
|
+
if (leaves.length === 0) continue;
|
|
16895
|
+
kept.push(leaves.length === group.hooks.length ? group : { ...group, hooks: leaves });
|
|
16725
16896
|
}
|
|
16726
|
-
|
|
16727
|
-
|
|
16728
|
-
|
|
16729
|
-
|
|
16730
|
-
|
|
16731
|
-
|
|
16732
|
-
|
|
16897
|
+
if (kept.length > 0) nextHooks[event] = kept;
|
|
16898
|
+
}
|
|
16899
|
+
const next = { ...doc };
|
|
16900
|
+
if (Object.keys(nextHooks).length > 0) next["hooks"] = nextHooks;
|
|
16901
|
+
else delete next["hooks"];
|
|
16902
|
+
return { doc: next, removed };
|
|
16903
|
+
}
|
|
16904
|
+
function legacyHooksPresent() {
|
|
16905
|
+
try {
|
|
16906
|
+
return withoutLegacyHooks(JSON.parse(fs6.readFileSync(hooksPath(), "utf-8"))).removed > 0;
|
|
16907
|
+
} catch {
|
|
16908
|
+
return false;
|
|
16909
|
+
}
|
|
16910
|
+
}
|
|
16911
|
+
function legacyBundlePresent() {
|
|
16912
|
+
return fs6.existsSync(path8.join(identityHome(), LEGACY_BUNDLE));
|
|
16913
|
+
}
|
|
16914
|
+
function removeLegacyWiring() {
|
|
16915
|
+
const notes = [];
|
|
16916
|
+
const file = hooksPath();
|
|
16917
|
+
if (fs6.existsSync(file)) {
|
|
16918
|
+
try {
|
|
16919
|
+
const parsed = JSON.parse(fs6.readFileSync(file, "utf-8"));
|
|
16920
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
16921
|
+
const { doc, removed } = withoutLegacyHooks(parsed);
|
|
16922
|
+
if (removed > 0) {
|
|
16923
|
+
let mode = 384;
|
|
16924
|
+
try {
|
|
16925
|
+
mode = fs6.statSync(file).mode & 511;
|
|
16926
|
+
} catch {
|
|
16927
|
+
}
|
|
16928
|
+
if (Object.keys(doc).length === 0) fs6.unlinkSync(file);
|
|
16929
|
+
else atomicWriteFile(file, JSON.stringify(doc, null, 2) + "\n", mode);
|
|
16930
|
+
notes.push(`${removed} lifecycle hook${removed === 1 ? "" : "s"} removed from hooks.json (receiving no longer needs hooks)`);
|
|
16733
16931
|
}
|
|
16734
|
-
});
|
|
16735
|
-
}
|
|
16736
|
-
proc.stdout?.on("data", (chunk) => {
|
|
16737
|
-
stdoutBytes += chunk.length;
|
|
16738
|
-
});
|
|
16739
|
-
proc.stderr?.on("data", (chunk) => {
|
|
16740
|
-
stderrTail = (stderrTail + String(chunk)).slice(-4 * STDERR_TAIL_CHARS);
|
|
16741
|
-
});
|
|
16742
|
-
proc.stdout?.on("error", () => void 0);
|
|
16743
|
-
proc.stderr?.on("error", () => void 0);
|
|
16744
|
-
if (spec.stdin !== null && proc.stdin) {
|
|
16745
|
-
proc.stdin.on("error", () => {
|
|
16746
|
-
});
|
|
16747
|
-
try {
|
|
16748
|
-
proc.stdin.write(spec.stdin);
|
|
16749
|
-
proc.stdin.end();
|
|
16750
|
-
} catch {
|
|
16751
16932
|
}
|
|
16933
|
+
} catch (err) {
|
|
16934
|
+
return { name: "legacy", status: "failed", detail: `${file} could not be read as JSON; the old AgentChat hooks were left in place: ${String(err)}` };
|
|
16752
16935
|
}
|
|
16753
|
-
|
|
16754
|
-
|
|
16755
|
-
|
|
16756
|
-
|
|
16757
|
-
|
|
16758
|
-
|
|
16759
|
-
|
|
16760
|
-
later(abandonMs, () => {
|
|
16761
|
-
if (settled) return;
|
|
16762
|
-
if (exited !== null) return;
|
|
16763
|
-
detach();
|
|
16764
|
-
const tail = redactDiagnostic(stderrTail);
|
|
16765
|
-
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}` : ""}`;
|
|
16766
|
-
finish(
|
|
16767
|
-
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}` }
|
|
16768
|
-
);
|
|
16769
|
-
});
|
|
16770
|
-
});
|
|
16771
|
-
};
|
|
16772
|
-
later(spec.budgetMs, () => {
|
|
16773
|
-
if (exited !== null) return;
|
|
16774
|
-
timedOut = true;
|
|
16775
|
-
terminate();
|
|
16776
|
-
});
|
|
16777
|
-
if (spec.signal) {
|
|
16778
|
-
onAbort = () => {
|
|
16779
|
-
if (settled) return;
|
|
16780
|
-
interrupted = true;
|
|
16781
|
-
terminate();
|
|
16782
|
-
};
|
|
16783
|
-
spec.signal.addEventListener("abort", onAbort, { once: true });
|
|
16936
|
+
}
|
|
16937
|
+
const bundle = path8.join(identityHome(), LEGACY_BUNDLE);
|
|
16938
|
+
if (fs6.existsSync(bundle)) {
|
|
16939
|
+
try {
|
|
16940
|
+
fs6.rmSync(bundle, { force: true });
|
|
16941
|
+
notes.push("stable CLI bundle removed");
|
|
16942
|
+
} catch {
|
|
16784
16943
|
}
|
|
16785
|
-
|
|
16786
|
-
|
|
16787
|
-
|
|
16788
|
-
|
|
16789
|
-
|
|
16790
|
-
|
|
16791
|
-
|
|
16792
|
-
|
|
16793
|
-
|
|
16794
|
-
|
|
16795
|
-
|
|
16796
|
-
|
|
16797
|
-
|
|
16798
|
-
|
|
16799
|
-
|
|
16800
|
-
|
|
16801
|
-
|
|
16802
|
-
|
|
16803
|
-
|
|
16804
|
-
|
|
16805
|
-
|
|
16806
|
-
|
|
16807
|
-
|
|
16808
|
-
|
|
16809
|
-
|
|
16944
|
+
}
|
|
16945
|
+
if (notes.length === 0) return null;
|
|
16946
|
+
log.debug(`legacy cleanup: ${notes.join("; ")}`);
|
|
16947
|
+
return { name: "legacy", status: "changed", detail: notes.join("; ") };
|
|
16948
|
+
}
|
|
16949
|
+
async function placeAll(identity, manual) {
|
|
16950
|
+
const steps = [];
|
|
16951
|
+
const legacy = removeLegacyWiring();
|
|
16952
|
+
if (legacy) steps.push(legacy);
|
|
16953
|
+
steps.push(await placeSkill(manual, identity?.apiBase ?? null));
|
|
16954
|
+
if (identity) {
|
|
16955
|
+
steps.push(placeKey(identity.apiKey));
|
|
16956
|
+
steps.push(placeMcp(identity.apiBase));
|
|
16957
|
+
steps.push(placeIdentityLine(identity.handle, identity.identityLine));
|
|
16958
|
+
} else {
|
|
16959
|
+
steps.push(placeOffer());
|
|
16960
|
+
}
|
|
16961
|
+
return steps;
|
|
16962
|
+
}
|
|
16963
|
+
function unplaceIdentity() {
|
|
16964
|
+
return [removeKey(), placeOffer()];
|
|
16965
|
+
}
|
|
16966
|
+
function removePlacement() {
|
|
16967
|
+
const steps = [];
|
|
16968
|
+
const legacy = removeLegacyWiring();
|
|
16969
|
+
if (legacy) steps.push(legacy);
|
|
16970
|
+
steps.push(removeKey());
|
|
16971
|
+
steps.push(removeMcp());
|
|
16972
|
+
steps.push(removeSkill());
|
|
16973
|
+
try {
|
|
16974
|
+
steps.push({ name: "identity", status: removeAnchorAt(anchorFile()) === "removed" ? "changed" : "ok", detail: `${path8.basename(anchorFile())} AgentChat block removed` });
|
|
16975
|
+
} catch (err) {
|
|
16976
|
+
steps.push({ name: "identity", status: "failed", detail: `could not remove the AgentChat block from ${anchorFile()}: ${err instanceof Error ? err.message : String(err)} \u2014 remove it by hand` });
|
|
16977
|
+
}
|
|
16978
|
+
return steps;
|
|
16979
|
+
}
|
|
16980
|
+
function identityCheck(identity) {
|
|
16981
|
+
let claimed;
|
|
16982
|
+
let current;
|
|
16983
|
+
try {
|
|
16984
|
+
claimed = readAnchorHandleAt(anchorFile(), identity.identityLineTemplate);
|
|
16985
|
+
current = identity.identityLine === null ? null : anchorIsCurrentAt(anchorFile(), identity.identityLine, identity.handle);
|
|
16986
|
+
} catch (err) {
|
|
16987
|
+
return { name: "identity", ok: false, verdict: "FAIL", detail: `cannot read ${anchorFile()}: ${err instanceof Error ? err.message : String(err)}` };
|
|
16988
|
+
}
|
|
16989
|
+
const older = current === false && claimed === identity.handle;
|
|
16990
|
+
return {
|
|
16991
|
+
name: "identity",
|
|
16992
|
+
ok: current === true || current === null && claimed === identity.handle,
|
|
16993
|
+
...older ? { verdict: "WARN" } : {},
|
|
16994
|
+
detail: current === true ? `identity line for @${identity.handle} in ${anchorFile()}` : current === null && claimed === identity.handle ? `identity line for @${identity.handle} in ${anchorFile()} (served texts unavailable \u2014 currency not checked)` : claimed === null ? `identity line missing from ${anchorFile()}` : claimed !== identity.handle ? `${anchorFile()} says @${claimed} but this agent is @${identity.handle}` : `${anchorFile()} carries an older identity text (or a second AgentChat block) \u2014 install or \`doctor --fix\` rewrites it`
|
|
16995
|
+
};
|
|
16996
|
+
}
|
|
16997
|
+
function checkPlacement(identity, manual) {
|
|
16998
|
+
const checks = [];
|
|
16999
|
+
if (identity) {
|
|
17000
|
+
checks.push(identityCheck(identity));
|
|
17001
|
+
const inDotEnv = readKeyFromDotEnv();
|
|
17002
|
+
checks.push({
|
|
17003
|
+
name: "key",
|
|
17004
|
+
ok: inDotEnv === identity.apiKey,
|
|
17005
|
+
detail: inDotEnv === identity.apiKey ? `${API_KEY_ENV} in ${dotEnvPath()} matches this agent's credentials` : inDotEnv === void 0 ? `${API_KEY_ENV} is not in ${dotEnvPath()} \u2014 the hosted tools cannot authenticate` : `${API_KEY_ENV} in ${dotEnvPath()} differs from this agent's credentials`
|
|
16810
17006
|
});
|
|
17007
|
+
}
|
|
17008
|
+
const skill = checkManual({ path: skillPath(), served: manual, apiBase: identity?.apiBase ?? null });
|
|
17009
|
+
checks.push({ name: "manual", ok: skill.state === "current" || skill.state === "unchecked", verdict: skill.verdict, detail: skill.detail });
|
|
17010
|
+
const mcp = inspectMcpBlock(identity?.apiBase ?? process.env["AGENTCHAT_API_BASE"]?.trim() ?? "https://api.agentchat.me");
|
|
17011
|
+
const handWrittenNamesClient = mcp === "foreign" && handWrittenSendsClientHeader(readConfigText());
|
|
17012
|
+
checks.push({
|
|
17013
|
+
name: "mcp",
|
|
17014
|
+
// A hand-written entry is the user's: nothing for this integration to
|
|
17015
|
+
// repair (ok), but said — a WARN — when it does not name this runtime to
|
|
17016
|
+
// the hosted tools: they then show it the wake-webhook tools, a second
|
|
17017
|
+
// way of being woken it does not need.
|
|
17018
|
+
ok: mcp === "current" || mcp === "foreign",
|
|
17019
|
+
...mcp === "foreign" && !handWrittenNamesClient ? { verdict: "WARN" } : {},
|
|
17020
|
+
detail: mcp === "current" ? `[mcp_servers.${MCP_SERVER_NAME}] \u2192 hosted tools, bearer token from ${API_KEY_ENV}, named as Codex ${CLIENT.version}` : mcp === "foreign" ? handWrittenNamesClient ? `[mcp_servers.${MCP_SERVER_NAME}] is managed by hand in ${configPath()}` : `[mcp_servers.${MCP_SERVER_NAME}] is managed by hand in ${configPath()} and does not send ${CLIENT_HEADER}, so the hosted tools take this agent for an unknown client and show it the wake-webhook tools \u2014 add \`${mcpHttpHeadersLine()}\` to it` : mcp === "stale" ? `the agentchat block in ${configPath()} is from an older release` : `no [mcp_servers.${MCP_SERVER_NAME}] in ${configPath()} \u2014 the agent has no AgentChat tools`
|
|
16811
17021
|
});
|
|
17022
|
+
const leftovers = [legacyHooksPresent() ? "hooks in hooks.json" : null, legacyBundlePresent() ? "stable CLI bundle" : null].filter((v) => v !== null);
|
|
17023
|
+
checks.push({ name: "legacy", ok: leftovers.length === 0, detail: leftovers.length === 0 ? "no pre-0.1.0 wiring left" : `pre-0.1.0 wiring still present: ${leftovers.join(", ")}` });
|
|
17024
|
+
return checks;
|
|
17025
|
+
}
|
|
17026
|
+
function placementMark(step) {
|
|
17027
|
+
if ("status" in step) return step.status === "failed" ? "\u2717" : step.status === "skipped" || step.status === "warned" ? "\u2013" : "\u2713";
|
|
17028
|
+
if (step.verdict !== void 0) return step.verdict === "PASS" ? "\u2713" : step.verdict === "WARN" ? "\u2013" : "\u2717";
|
|
17029
|
+
return step.ok ? "\u2713" : "\u2717";
|
|
17030
|
+
}
|
|
17031
|
+
function formatPlacement(steps) {
|
|
17032
|
+
return steps.map((step) => ` ${placementMark(step)} ${step.name}: ${step.detail}`);
|
|
16812
17033
|
}
|
|
16813
17034
|
|
|
16814
|
-
//
|
|
16815
|
-
import * as
|
|
16816
|
-
|
|
16817
|
-
|
|
17035
|
+
// src/identity.ts
|
|
17036
|
+
import * as path11 from "path";
|
|
17037
|
+
|
|
17038
|
+
// node_modules/.pnpm/@agentchatme+agent-core@0.5.0/node_modules/@agentchatme/agent-core/dist/presets.js
|
|
17039
|
+
import * as fs7 from "fs";
|
|
17040
|
+
import * as os5 from "os";
|
|
17041
|
+
import * as path9 from "path";
|
|
16818
17042
|
import * as fs24 from "fs";
|
|
16819
|
-
import * as
|
|
17043
|
+
import * as os23 from "os";
|
|
16820
17044
|
import * as path24 from "path";
|
|
16821
17045
|
function semverAtLeast(actual, minimum) {
|
|
16822
|
-
const
|
|
17046
|
+
const parse2 = (value) => {
|
|
16823
17047
|
const match = value.match(/(\d+)\.(\d+)\.(\d+)/);
|
|
16824
17048
|
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
|
|
16825
17049
|
};
|
|
16826
|
-
const a =
|
|
16827
|
-
const b =
|
|
17050
|
+
const a = parse2(actual);
|
|
17051
|
+
const b = parse2(minimum);
|
|
16828
17052
|
if (a === null || b === null) return false;
|
|
16829
17053
|
for (let index = 0; index < 3; index++) {
|
|
16830
17054
|
if (a[index] !== b[index]) return (a[index] ?? 0) > (b[index] ?? 0);
|
|
16831
17055
|
}
|
|
16832
17056
|
return true;
|
|
16833
17057
|
}
|
|
17058
|
+
var CLAUDE_CODE_ENV_KEPT = [
|
|
17059
|
+
// Sign-in and provider
|
|
17060
|
+
"CLAUDE_CODE_OAUTH_TOKEN",
|
|
17061
|
+
"CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
|
|
17062
|
+
"CLAUDE_CODE_OAUTH_SCOPES",
|
|
17063
|
+
"CLAUDE_CODE_API_KEY_HELPER_TTL_MS",
|
|
17064
|
+
"CLAUDE_CODE_USE_BEDROCK",
|
|
17065
|
+
"CLAUDE_CODE_USE_VERTEX",
|
|
17066
|
+
"CLAUDE_CODE_USE_FOUNDRY",
|
|
17067
|
+
"CLAUDE_CODE_USE_MANTLE",
|
|
17068
|
+
"CLAUDE_CODE_USE_ANTHROPIC_AWS",
|
|
17069
|
+
"CLAUDE_CODE_SKIP_BEDROCK_AUTH",
|
|
17070
|
+
"CLAUDE_CODE_SKIP_VERTEX_AUTH",
|
|
17071
|
+
"CLAUDE_CODE_SKIP_FOUNDRY_AUTH",
|
|
17072
|
+
"CLAUDE_CODE_SKIP_MANTLE_AUTH",
|
|
17073
|
+
"CLAUDE_CODE_SKIP_ANTHROPIC_AWS_AUTH",
|
|
17074
|
+
"CLAUDE_CODE_AWS_CHAIN_RESOLVE_TIMEOUT_MS",
|
|
17075
|
+
// Network and TLS
|
|
17076
|
+
"CLAUDE_CODE_CLIENT_CERT",
|
|
17077
|
+
"CLAUDE_CODE_CLIENT_KEY",
|
|
17078
|
+
"CLAUDE_CODE_CLIENT_KEY_PASSPHRASE",
|
|
17079
|
+
"CLAUDE_CODE_CERT_STORE",
|
|
17080
|
+
"CLAUDE_CODE_PROXY_RESOLVES_HOSTS",
|
|
17081
|
+
"CLAUDE_CODE_CONNECT_TIMEOUT_MS",
|
|
17082
|
+
// Privacy and secrets switches the user turned on
|
|
17083
|
+
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
|
|
17084
|
+
"CLAUDE_CODE_ENABLE_TELEMETRY",
|
|
17085
|
+
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB",
|
|
17086
|
+
"CLAUDE_CODE_MCP_ALLOWLIST_ENV",
|
|
17087
|
+
"CLAUDE_CODE_DISABLE_CLAUDE_MDS",
|
|
17088
|
+
"CLAUDE_CODE_DISABLE_AUTO_MEMORY",
|
|
17089
|
+
// Model request settings the user chose
|
|
17090
|
+
"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS",
|
|
17091
|
+
"CLAUDE_CODE_EXTRA_BODY",
|
|
17092
|
+
"CLAUDE_CODE_MAX_OUTPUT_TOKENS",
|
|
17093
|
+
// Platform
|
|
17094
|
+
"CLAUDE_CODE_GIT_BASH_PATH",
|
|
17095
|
+
"CLAUDE_CODE_TMPDIR",
|
|
17096
|
+
// Set by the preset itself (a larger value of the user's is kept)
|
|
17097
|
+
"CLAUDE_CODE_MCP_STARTUP_WAIT_MS"
|
|
17098
|
+
];
|
|
17099
|
+
var CLAUDE_SESSION_ENV = ["CLAUDECODE", "CLAUDE_PID", "CLAUDE_EFFORT", "CLAUDE_JOB_DIR", "CLAUDE_PROJECT_DIR", "TRACEPARENT", "TRACESTATE", "AI_AGENT"];
|
|
17100
|
+
var CODEX_SESSION_ENV = [
|
|
17101
|
+
"CODEX_SANDBOX",
|
|
17102
|
+
"CODEX_SANDBOX_NETWORK_DISABLED",
|
|
17103
|
+
"CODEX_SESSION_ID",
|
|
17104
|
+
"CODEX_THREAD_ID",
|
|
17105
|
+
"CODEX_VERSION",
|
|
17106
|
+
"CODEX_PERMISSION_PROFILE",
|
|
17107
|
+
"CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN",
|
|
17108
|
+
"CODEX_ESCALATE_SOCKET",
|
|
17109
|
+
"CODEX_NETWORK_PROXY_ACTIVE",
|
|
17110
|
+
"CODEX_NETWORK_ALLOW_LOCAL_BINDING",
|
|
17111
|
+
"CODEX_NETWORK_PROXY_ATTRIBUTION",
|
|
17112
|
+
"CODEX_NETWORK_PROXY_CREDENTIAL_BROKER_ACTIVE",
|
|
17113
|
+
"CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS",
|
|
17114
|
+
"CODEX_WINDOWS_SANDBOX_PROXY_PORTS"
|
|
17115
|
+
];
|
|
17116
|
+
var CODEX_MANAGED_PROXY_ENV = [
|
|
17117
|
+
"ELECTRON_GET_USE_PROXY",
|
|
17118
|
+
"NODE_USE_ENV_PROXY",
|
|
17119
|
+
"HTTP_PROXY",
|
|
17120
|
+
"HTTPS_PROXY",
|
|
17121
|
+
"YARN_HTTP_PROXY",
|
|
17122
|
+
"YARN_HTTPS_PROXY",
|
|
17123
|
+
"NPM_CONFIG_HTTP_PROXY",
|
|
17124
|
+
"NPM_CONFIG_HTTPS_PROXY",
|
|
17125
|
+
"NPM_CONFIG_PROXY",
|
|
17126
|
+
"BUNDLE_HTTP_PROXY",
|
|
17127
|
+
"BUNDLE_HTTPS_PROXY",
|
|
17128
|
+
"PIP_PROXY",
|
|
17129
|
+
"DOCKER_HTTP_PROXY",
|
|
17130
|
+
"DOCKER_HTTPS_PROXY",
|
|
17131
|
+
"WS_PROXY",
|
|
17132
|
+
"WSS_PROXY",
|
|
17133
|
+
"NO_PROXY",
|
|
17134
|
+
"NPM_CONFIG_NOPROXY",
|
|
17135
|
+
"YARN_NO_PROXY",
|
|
17136
|
+
"BUNDLE_NO_PROXY",
|
|
17137
|
+
"ALL_PROXY",
|
|
17138
|
+
"FTP_PROXY"
|
|
17139
|
+
];
|
|
17140
|
+
var CODEX_CA_ENV_KEYS = [
|
|
17141
|
+
"CODEX_CA_CERTIFICATE",
|
|
17142
|
+
"SSL_CERT_FILE",
|
|
17143
|
+
"REQUESTS_CA_BUNDLE",
|
|
17144
|
+
"CURL_CA_BUNDLE",
|
|
17145
|
+
"NODE_EXTRA_CA_CERTS",
|
|
17146
|
+
"GIT_SSL_CAINFO",
|
|
17147
|
+
"CARGO_HTTP_CAINFO",
|
|
17148
|
+
"PIP_CERT",
|
|
17149
|
+
"BUNDLE_SSL_CA_CERT",
|
|
17150
|
+
"NPM_CONFIG_CAFILE"
|
|
17151
|
+
];
|
|
17152
|
+
function isManagedCaBundle(value) {
|
|
17153
|
+
return /[\\/]proxy[\\/]ca-bundle-[0-9a-fA-F]{64}\.pem$/.test(value);
|
|
17154
|
+
}
|
|
17155
|
+
var CODEX_PROXY_GIT_SSH_MARKER = "CODEX_PROXY_GIT_SSH_COMMAND=1 ";
|
|
17156
|
+
function isParentSessionEnv(key) {
|
|
17157
|
+
const upper = key.toUpperCase();
|
|
17158
|
+
if (upper.startsWith("CLAUDE_CODE_")) return !CLAUDE_CODE_ENV_KEPT.includes(upper);
|
|
17159
|
+
return CLAUDE_SESSION_ENV.includes(upper) || CODEX_SESSION_ENV.includes(upper);
|
|
17160
|
+
}
|
|
17161
|
+
function envValue(env, name) {
|
|
17162
|
+
for (const [key, value] of Object.entries(env)) if (key.toUpperCase() === name) return value;
|
|
17163
|
+
return void 0;
|
|
17164
|
+
}
|
|
17165
|
+
function brokeredDummies(env) {
|
|
17166
|
+
const marker = envValue(env, "CODEX_NETWORK_PROXY_BROKERED_CREDENTIALS");
|
|
17167
|
+
const out = /* @__PURE__ */ new Set();
|
|
17168
|
+
if (marker === void 0) return out;
|
|
17169
|
+
let pairs;
|
|
17170
|
+
try {
|
|
17171
|
+
pairs = JSON.parse(marker);
|
|
17172
|
+
} catch {
|
|
17173
|
+
return out;
|
|
17174
|
+
}
|
|
17175
|
+
if (!Array.isArray(pairs)) return out;
|
|
17176
|
+
for (const pair of pairs) {
|
|
17177
|
+
if (!Array.isArray(pair) || typeof pair[0] !== "string" || typeof pair[1] !== "string") continue;
|
|
17178
|
+
if (envValue(env, pair[0].toUpperCase()) === pair[1]) out.add(pair[0].toUpperCase());
|
|
17179
|
+
}
|
|
17180
|
+
return out;
|
|
17181
|
+
}
|
|
17182
|
+
function withoutParentSession(env) {
|
|
17183
|
+
const proxyActive = envValue(env, "CODEX_NETWORK_PROXY_ACTIVE") !== void 0;
|
|
17184
|
+
const dummies = brokeredDummies(env);
|
|
17185
|
+
const copy = {};
|
|
17186
|
+
for (const [key, value] of Object.entries(env)) {
|
|
17187
|
+
const upper = key.toUpperCase();
|
|
17188
|
+
if (isParentSessionEnv(key)) continue;
|
|
17189
|
+
if (proxyActive && CODEX_MANAGED_PROXY_ENV.includes(upper)) continue;
|
|
17190
|
+
if (proxyActive && value !== void 0 && CODEX_CA_ENV_KEYS.includes(upper) && isManagedCaBundle(value)) continue;
|
|
17191
|
+
if (value !== void 0 && upper === "GIT_SSH_COMMAND" && value.startsWith(CODEX_PROXY_GIT_SSH_MARKER)) continue;
|
|
17192
|
+
if (dummies.has(upper)) continue;
|
|
17193
|
+
copy[key] = value;
|
|
17194
|
+
}
|
|
17195
|
+
return copy;
|
|
17196
|
+
}
|
|
16834
17197
|
function withoutInheritedKey(env) {
|
|
16835
17198
|
const copy = { ...env };
|
|
16836
17199
|
delete copy["AGENTCHAT_API_KEY"];
|
|
@@ -16840,28 +17203,28 @@ var CLAUDE_CODE_PRESET = "claude-code";
|
|
|
16840
17203
|
var MIN_CLAUDE_CODE_VERSION = "2.1.274";
|
|
16841
17204
|
var CLAUDE_MCP_SERVER_NAME = "agentchat";
|
|
16842
17205
|
var AGENTCHAT_TOOL_ALLOW = `mcp__${CLAUDE_MCP_SERVER_NAME}__*`;
|
|
16843
|
-
var ANSWER_TOOLS = ["Read", "Glob", "Grep"
|
|
17206
|
+
var ANSWER_TOOLS = ["Read", "Glob", "Grep"];
|
|
17207
|
+
var WEB_TOOLS = ["WebSearch", "WebFetch"];
|
|
16844
17208
|
var WORK_TOOLS = ["Bash", "Edit", "Write", "MultiEdit", "NotebookEdit"];
|
|
16845
|
-
var
|
|
16846
|
-
|
|
16847
|
-
|
|
16848
|
-
"
|
|
16849
|
-
|
|
16850
|
-
|
|
16851
|
-
"CLAUDE_CODE_EFFORT_LEVEL",
|
|
16852
|
-
"CLAUDE_EFFORT",
|
|
16853
|
-
"AI_AGENT"
|
|
16854
|
-
];
|
|
17209
|
+
var ANSWER_DENIED_TOOLS = ["WebFetch", "WebSearch", "Bash"];
|
|
17210
|
+
var ANSWER_SETTINGS = JSON.stringify({
|
|
17211
|
+
permissions: { blockReadsOutsideWorkingDirectories: true },
|
|
17212
|
+
env: { CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" },
|
|
17213
|
+
disableAllHooks: true
|
|
17214
|
+
});
|
|
16855
17215
|
var MCP_STARTUP_WAIT_MS = "15000";
|
|
16856
17216
|
function claudeConfigDirFrom(env = process.env) {
|
|
16857
17217
|
const override = env["CLAUDE_CONFIG_DIR"];
|
|
16858
|
-
return override !== void 0 && override.trim().length > 0 ?
|
|
17218
|
+
return override !== void 0 && override.trim().length > 0 ? path9.resolve(override) : void 0;
|
|
16859
17219
|
}
|
|
16860
17220
|
function claudeHomeFor(configDirOverride) {
|
|
16861
|
-
return configDirOverride ??
|
|
17221
|
+
return configDirOverride ?? path9.join(os5.homedir(), ".claude");
|
|
17222
|
+
}
|
|
17223
|
+
function claudeProjectsDirFor(configDirOverride) {
|
|
17224
|
+
return path9.join(claudeHomeFor(configDirOverride), "projects");
|
|
16862
17225
|
}
|
|
16863
17226
|
function claudeUserStatePathFor(configDirOverride) {
|
|
16864
|
-
return configDirOverride !== void 0 ?
|
|
17227
|
+
return configDirOverride !== void 0 ? path9.join(configDirOverride, ".claude.json") : path9.join(os5.homedir(), ".claude.json");
|
|
16865
17228
|
}
|
|
16866
17229
|
function claudeProcessEnv(configDirOverride, source) {
|
|
16867
17230
|
const env = { ...source };
|
|
@@ -16870,46 +17233,37 @@ function claudeProcessEnv(configDirOverride, source) {
|
|
|
16870
17233
|
return env;
|
|
16871
17234
|
}
|
|
16872
17235
|
function buildClaudeEnv(configDirOverride, source = process.env) {
|
|
16873
|
-
const env = claudeProcessEnv(configDirOverride, source);
|
|
16874
|
-
for (const key of PARENT_ENV_KEYS) delete env[key];
|
|
17236
|
+
const env = claudeProcessEnv(configDirOverride, withoutParentSession(source));
|
|
16875
17237
|
env["DISABLE_AUTOUPDATER"] = "1";
|
|
16876
17238
|
const wait = Number(env["CLAUDE_CODE_MCP_STARTUP_WAIT_MS"]);
|
|
16877
17239
|
if (!Number.isFinite(wait) || wait < Number(MCP_STARTUP_WAIT_MS)) env["CLAUDE_CODE_MCP_STARTUP_WAIT_MS"] = MCP_STARTUP_WAIT_MS;
|
|
16878
17240
|
return env;
|
|
16879
17241
|
}
|
|
16880
|
-
|
|
16881
|
-
|
|
16882
|
-
|
|
16883
|
-
|
|
16884
|
-
|
|
16885
|
-
env: claudeProcessEnv(configDirOverride, process.env)
|
|
16886
|
-
});
|
|
17242
|
+
var PROBE_TIMEOUT_MS = 1e4;
|
|
17243
|
+
async function claudeSignIn(configDirOverride, command = "claude", timeoutMs = PROBE_TIMEOUT_MS, signal) {
|
|
17244
|
+
const status = await runProbe(command, ["auth", "status"], { timeoutMs, env: claudeProcessEnv(configDirOverride, process.env), ...signal !== void 0 ? { signal } : {} });
|
|
17245
|
+
if (status.timedOut) return { signedIn: false, unanswered: `claude auth status did not answer within ${Math.round(timeoutMs / 1e3)} s (killed)` };
|
|
17246
|
+
if (signal?.aborted) return { signedIn: false, unanswered: "claude auth status was stopped" };
|
|
16887
17247
|
if (!status.error) {
|
|
16888
17248
|
try {
|
|
16889
|
-
const parsed = JSON.parse(
|
|
16890
|
-
if (typeof parsed?.loggedIn === "boolean") return parsed.loggedIn;
|
|
17249
|
+
const parsed = JSON.parse(status.stdout.trim());
|
|
17250
|
+
if (typeof parsed?.loggedIn === "boolean") return { signedIn: parsed.loggedIn, unanswered: null };
|
|
16891
17251
|
} catch {
|
|
16892
17252
|
}
|
|
16893
|
-
if (status.status === 0) return true;
|
|
17253
|
+
if (status.status === 0) return { signedIn: true, unanswered: null };
|
|
16894
17254
|
}
|
|
16895
17255
|
const configDir = claudeHomeFor(configDirOverride);
|
|
16896
|
-
if (
|
|
16897
|
-
if (process.platform !== "darwin") return false;
|
|
16898
|
-
const keychain =
|
|
16899
|
-
|
|
16900
|
-
|
|
16901
|
-
|
|
16902
|
-
|
|
16903
|
-
}
|
|
16904
|
-
|
|
16905
|
-
const version = spawnCommandSync(command, ["--version"], {
|
|
16906
|
-
encoding: "utf-8",
|
|
16907
|
-
timeout: 1e4,
|
|
16908
|
-
windowsHide: true,
|
|
16909
|
-
env: claudeProcessEnv(configDirOverride, process.env)
|
|
16910
|
-
});
|
|
17256
|
+
if (fs7.existsSync(path9.join(configDir, ".credentials.json"))) return { signedIn: true, unanswered: null };
|
|
17257
|
+
if (process.platform !== "darwin") return { signedIn: false, unanswered: null };
|
|
17258
|
+
const keychain = await runProbe("security", ["find-generic-password", "-s", "Claude Code-credentials"], { timeoutMs: Math.min(timeoutMs, 5e3), ...signal !== void 0 ? { signal } : {} });
|
|
17259
|
+
return { signedIn: !keychain.error && keychain.status === 0, unanswered: null };
|
|
17260
|
+
}
|
|
17261
|
+
async function inspectClaudeRuntime(configDirOverride, command = "claude", timeoutMs = PROBE_TIMEOUT_MS, signal) {
|
|
17262
|
+
const version = await runProbe(command, ["--version"], { timeoutMs, env: claudeProcessEnv(configDirOverride, process.env), ...signal !== void 0 ? { signal } : {} });
|
|
17263
|
+
if (version.timedOut) return { ok: false, detail: `claude --version did not answer within ${Math.round(timeoutMs / 1e3)} s (killed)` };
|
|
17264
|
+
if (signal?.aborted) return { ok: false, detail: "claude --version was stopped" };
|
|
16911
17265
|
if (version.error) return { ok: false, detail: `claude CLI not found on PATH (${version.error.message})` };
|
|
16912
|
-
const rendered =
|
|
17266
|
+
const rendered = (version.stdout || version.stderr).trim();
|
|
16913
17267
|
if (version.status !== 0) return { ok: false, detail: rendered || `claude --version exited ${version.status}` };
|
|
16914
17268
|
return semverAtLeast(rendered, MIN_CLAUDE_CODE_VERSION) ? { ok: true, detail: rendered } : {
|
|
16915
17269
|
ok: false,
|
|
@@ -16917,14 +17271,36 @@ function inspectClaudeRuntime(configDirOverride, command = "claude") {
|
|
|
16917
17271
|
};
|
|
16918
17272
|
}
|
|
16919
17273
|
function deniedAncestorOf(dir, denied) {
|
|
16920
|
-
const target =
|
|
17274
|
+
const target = path9.resolve(dir);
|
|
16921
17275
|
for (const raw of denied) {
|
|
16922
|
-
const root =
|
|
16923
|
-
if (target === root || target.startsWith(root.endsWith(
|
|
17276
|
+
const root = path9.resolve(raw);
|
|
17277
|
+
if (target === root || target.startsWith(root.endsWith(path9.sep) ? root : root + path9.sep)) return root;
|
|
16924
17278
|
}
|
|
16925
17279
|
return null;
|
|
16926
17280
|
}
|
|
16927
|
-
function
|
|
17281
|
+
function expressibleAllow(raw) {
|
|
17282
|
+
return expressible(raw) && !/[*?[\]\\!#]/.test(raw);
|
|
17283
|
+
}
|
|
17284
|
+
function workdirPaths(workdir) {
|
|
17285
|
+
const given = path9.resolve(workdir);
|
|
17286
|
+
let real = given;
|
|
17287
|
+
try {
|
|
17288
|
+
real = fs7.realpathSync(given);
|
|
17289
|
+
} catch {
|
|
17290
|
+
}
|
|
17291
|
+
return real === given ? [given] : [given, real];
|
|
17292
|
+
}
|
|
17293
|
+
function workdirReadRules(workdir) {
|
|
17294
|
+
if (workdir === void 0 || process.platform === "win32") return [];
|
|
17295
|
+
const rules = [];
|
|
17296
|
+
for (const raw of workdirPaths(workdir)) {
|
|
17297
|
+
const clean = raw.replace(/\/+$/, "");
|
|
17298
|
+
if (!expressibleAllow(raw) || clean.length === 0) continue;
|
|
17299
|
+
rules.push(`Read(/${clean})`, `Read(/${clean}/**)`);
|
|
17300
|
+
}
|
|
17301
|
+
return rules;
|
|
17302
|
+
}
|
|
17303
|
+
function claudeProfileArgs(profile2, workdir) {
|
|
16928
17304
|
switch (profile2) {
|
|
16929
17305
|
case "answer":
|
|
16930
17306
|
return [
|
|
@@ -16935,8 +17311,12 @@ function claudeProfileArgs(profile2) {
|
|
|
16935
17311
|
"--tools",
|
|
16936
17312
|
ANSWER_TOOLS.join(","),
|
|
16937
17313
|
"--allowedTools",
|
|
16938
|
-
[AGENTCHAT_TOOL_ALLOW, ...
|
|
17314
|
+
[AGENTCHAT_TOOL_ALLOW, ...workdirReadRules(workdir)].join(","),
|
|
17315
|
+
"--settings",
|
|
17316
|
+
ANSWER_SETTINGS
|
|
16939
17317
|
];
|
|
17318
|
+
// `work` and `full` are the operator's explicit opt-in: a run started by
|
|
17319
|
+
// any peer's message can then read and change this machine.
|
|
16940
17320
|
case "work":
|
|
16941
17321
|
return [
|
|
16942
17322
|
"--permission-mode",
|
|
@@ -16944,7 +17324,7 @@ function claudeProfileArgs(profile2) {
|
|
|
16944
17324
|
"--permission-prompts",
|
|
16945
17325
|
"none",
|
|
16946
17326
|
"--allowedTools",
|
|
16947
|
-
[AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WORK_TOOLS].join(",")
|
|
17327
|
+
[AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WEB_TOOLS, ...WORK_TOOLS].join(",")
|
|
16948
17328
|
];
|
|
16949
17329
|
case "full":
|
|
16950
17330
|
return ["--dangerously-skip-permissions", "--permission-prompts", "none", "--allowedTools", AGENTCHAT_TOOL_ALLOW];
|
|
@@ -16968,7 +17348,7 @@ function readDenyRules(paths) {
|
|
|
16968
17348
|
}
|
|
16969
17349
|
function claudeRunArgs(profile2, options = {}) {
|
|
16970
17350
|
const budget = options.maxBudgetUsd?.trim();
|
|
16971
|
-
const deny = readDenyRules(options.denyReadPaths ?? []);
|
|
17351
|
+
const deny = [...profile2 === "answer" ? ANSWER_DENIED_TOOLS : [], ...readDenyRules(options.denyReadPaths ?? [])];
|
|
16972
17352
|
return [
|
|
16973
17353
|
"-p",
|
|
16974
17354
|
"--output-format",
|
|
@@ -16979,7 +17359,8 @@ function claudeRunArgs(profile2, options = {}) {
|
|
|
16979
17359
|
...budget !== void 0 && /^\d+(\.\d+)?$/.test(budget) ? ["--max-budget-usd", budget] : [],
|
|
16980
17360
|
// Variadic, so it is closed by the boolean flag right after it.
|
|
16981
17361
|
...options.mcpConfigPath !== void 0 ? ["--mcp-config", options.mcpConfigPath, "--strict-mcp-config"] : [],
|
|
16982
|
-
...
|
|
17362
|
+
...options.appendSystemPromptFile !== void 0 ? ["--append-system-prompt-file", options.appendSystemPromptFile] : [],
|
|
17363
|
+
...claudeProfileArgs(profile2, options.workdir),
|
|
16983
17364
|
// Last: the option is variadic and the prompt arrives on stdin, so there
|
|
16984
17365
|
// is no positional for it to swallow.
|
|
16985
17366
|
...deny.length > 0 ? ["--disallowedTools", deny.join(",")] : []
|
|
@@ -16990,7 +17371,70 @@ function claudeMcpConfig(apiBase, apiKey, clientVersion = VERSION2) {
|
|
|
16990
17371
|
return `${JSON.stringify({ mcpServers: { [CLAUDE_MCP_SERVER_NAME]: { type: "http", url: hostedMcpUrl2(apiBase), headers } } }, null, 2)}
|
|
16991
17372
|
`;
|
|
16992
17373
|
}
|
|
16993
|
-
var
|
|
17374
|
+
var ANSWER_ENV = Object.freeze({
|
|
17375
|
+
CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1",
|
|
17376
|
+
CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1"
|
|
17377
|
+
});
|
|
17378
|
+
function claudeManagedSettingsDir(platform = process.platform) {
|
|
17379
|
+
if (platform === "darwin") return "/Library/Application Support/ClaudeCode";
|
|
17380
|
+
if (platform === "win32") return "C:\\Program Files\\ClaudeCode";
|
|
17381
|
+
return "/etc/claude-code";
|
|
17382
|
+
}
|
|
17383
|
+
function gitRootOf(dir) {
|
|
17384
|
+
let current = path9.resolve(dir);
|
|
17385
|
+
for (; ; ) {
|
|
17386
|
+
if (fs7.existsSync(path9.join(current, ".git"))) return current;
|
|
17387
|
+
const parent = path9.dirname(current);
|
|
17388
|
+
if (parent === current) return null;
|
|
17389
|
+
current = parent;
|
|
17390
|
+
}
|
|
17391
|
+
}
|
|
17392
|
+
function claudeSettingsFilesGrantingDirectories(configDirOverride, workdir) {
|
|
17393
|
+
const managed = claudeManagedSettingsDir();
|
|
17394
|
+
const dropIns = (() => {
|
|
17395
|
+
try {
|
|
17396
|
+
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));
|
|
17397
|
+
} catch {
|
|
17398
|
+
return [];
|
|
17399
|
+
}
|
|
17400
|
+
})();
|
|
17401
|
+
const cwdLocal = path9.join(path9.resolve(workdir), ".claude", "settings.local.json");
|
|
17402
|
+
const root = gitRootOf(workdir);
|
|
17403
|
+
const rootLocal = root !== null ? path9.join(root, ".claude", "settings.local.json") : cwdLocal;
|
|
17404
|
+
return [
|
|
17405
|
+
path9.join(claudeHomeFor(configDirOverride), "settings.json"),
|
|
17406
|
+
path9.join(managed, "managed-settings.json"),
|
|
17407
|
+
...dropIns,
|
|
17408
|
+
.../* @__PURE__ */ new Set([rootLocal, cwdLocal])
|
|
17409
|
+
];
|
|
17410
|
+
}
|
|
17411
|
+
function claudeExtraDirectoriesGrant(configDirOverride, workdir) {
|
|
17412
|
+
for (const file of claudeSettingsFilesGrantingDirectories(configDirOverride, workdir)) {
|
|
17413
|
+
let text;
|
|
17414
|
+
try {
|
|
17415
|
+
text = fs7.readFileSync(file, "utf-8");
|
|
17416
|
+
} catch {
|
|
17417
|
+
continue;
|
|
17418
|
+
}
|
|
17419
|
+
let parsed;
|
|
17420
|
+
try {
|
|
17421
|
+
parsed = JSON.parse(text);
|
|
17422
|
+
} catch {
|
|
17423
|
+
if (text.includes("additionalDirectories")) return { file, detail: "names permissions.additionalDirectories and is not valid JSON" };
|
|
17424
|
+
continue;
|
|
17425
|
+
}
|
|
17426
|
+
const dirs = parsed?.permissions?.additionalDirectories;
|
|
17427
|
+
if (Array.isArray(dirs) && dirs.length > 0) return { file, detail: `lists permissions.additionalDirectories (${dirs.length} folder${dirs.length === 1 ? "" : "s"})` };
|
|
17428
|
+
}
|
|
17429
|
+
return null;
|
|
17430
|
+
}
|
|
17431
|
+
function extraDirectoriesRefusal(grant) {
|
|
17432
|
+
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).`;
|
|
17433
|
+
}
|
|
17434
|
+
function claudeAnswerFallbackWorkdir(configDirOverride) {
|
|
17435
|
+
return path9.join(claudeHomeFor(configDirOverride), "agentchat-answer-workdir");
|
|
17436
|
+
}
|
|
17437
|
+
var ClaudeRunner = class _ClaudeRunner {
|
|
16994
17438
|
constructor(options) {
|
|
16995
17439
|
this.options = options;
|
|
16996
17440
|
this.command = options.command ?? "claude";
|
|
@@ -17001,24 +17445,51 @@ var ClaudeRunner = class {
|
|
|
17001
17445
|
/** The workdir warning is one line per process, not one per preflight (preflight repeats every few minutes). */
|
|
17002
17446
|
warnedWorkdir = false;
|
|
17003
17447
|
warnedDeny = false;
|
|
17004
|
-
|
|
17448
|
+
warnedHome = false;
|
|
17449
|
+
/**
|
|
17450
|
+
* Where this runner's runs work: the configured workdir, except that an
|
|
17451
|
+
* `answer` run never works in the home folder or above it — it gets
|
|
17452
|
+
* `claudeAnswerFallbackWorkdir` (its readable folder would be the whole home).
|
|
17453
|
+
*/
|
|
17454
|
+
workdir() {
|
|
17455
|
+
if (this.options.profile === "answer" && workdirExposesHome(this.options.workdir)) return claudeAnswerFallbackWorkdir(this.options.configDir);
|
|
17456
|
+
return this.options.workdir;
|
|
17457
|
+
}
|
|
17458
|
+
/** The denied path the workdir sits in, or null when the run can read its own cwd. */
|
|
17005
17459
|
workdirDeniedBy() {
|
|
17006
|
-
return deniedAncestorOf(this.
|
|
17460
|
+
return deniedAncestorOf(this.workdir(), this.options.denyReadPaths);
|
|
17007
17461
|
}
|
|
17008
|
-
async preflight() {
|
|
17009
|
-
const runtime = inspectClaudeRuntime(this.options.configDir, this.command);
|
|
17462
|
+
async preflight(options = {}) {
|
|
17463
|
+
const runtime = await inspectClaudeRuntime(this.options.configDir, this.command, PROBE_TIMEOUT_MS, options.signal);
|
|
17010
17464
|
if (!runtime.ok) return { ok: false, detail: runtime.detail };
|
|
17011
|
-
|
|
17012
|
-
|
|
17465
|
+
const signIn = await claudeSignIn(this.options.configDir, this.command, PROBE_TIMEOUT_MS, options.signal);
|
|
17466
|
+
if (signIn.unanswered !== null) return { ok: false, detail: signIn.unanswered };
|
|
17467
|
+
if (!signIn.signedIn) return { ok: false, detail: "claude is not signed in (run `claude` once and sign in)" };
|
|
17468
|
+
if (this.options.profile === "answer" && this.options.mcpConfigPath === void 0) {
|
|
17469
|
+
const answerMcp = this.options.answerMcp;
|
|
17470
|
+
if (answerMcp === void 0) {
|
|
17471
|
+
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" };
|
|
17472
|
+
}
|
|
17473
|
+
if (deniedAncestorOf(answerMcp.file, this.options.denyReadPaths) === null) {
|
|
17474
|
+
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(", ")})` };
|
|
17475
|
+
}
|
|
17476
|
+
}
|
|
17477
|
+
if (this.options.profile === "answer") {
|
|
17478
|
+
const grant = claudeExtraDirectoriesGrant(this.options.configDir, this.workdir());
|
|
17479
|
+
if (grant !== null) return { ok: false, detail: extraDirectoriesRefusal(grant) };
|
|
17480
|
+
}
|
|
17481
|
+
if (this.workdir() !== this.options.workdir && !this.warnedHome) {
|
|
17482
|
+
this.warnedHome = true;
|
|
17483
|
+
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.`);
|
|
17013
17484
|
}
|
|
17014
17485
|
const denied = this.workdirDeniedBy();
|
|
17015
17486
|
if (denied !== null && !this.warnedWorkdir) {
|
|
17016
17487
|
this.warnedWorkdir = true;
|
|
17017
17488
|
log.warn(
|
|
17018
|
-
`the run workdir ${this.
|
|
17489
|
+
`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}` : ""}`
|
|
17019
17490
|
);
|
|
17020
17491
|
}
|
|
17021
|
-
const uncovered = inexpressibleDenyPaths(this.
|
|
17492
|
+
const uncovered = inexpressibleDenyPaths(this.readDenyPaths());
|
|
17022
17493
|
if (uncovered.length > 0) {
|
|
17023
17494
|
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)`;
|
|
17024
17495
|
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).` };
|
|
@@ -17027,40 +17498,127 @@ var ClaudeRunner = class {
|
|
|
17027
17498
|
log.warn(`${why}: runs can read those paths.`);
|
|
17028
17499
|
}
|
|
17029
17500
|
}
|
|
17030
|
-
if (this.options.mcpConfigPath !== void 0 && !
|
|
17501
|
+
if (this.options.mcpConfigPath !== void 0 && !fs7.existsSync(this.options.mcpConfigPath)) {
|
|
17031
17502
|
return { ok: false, detail: `the hosted tool config ${this.options.mcpConfigPath} is missing` };
|
|
17032
17503
|
}
|
|
17033
|
-
|
|
17504
|
+
fs7.mkdirSync(this.workdir(), { recursive: true, mode: 448 });
|
|
17034
17505
|
return { ok: true };
|
|
17035
17506
|
}
|
|
17036
|
-
/**
|
|
17037
|
-
|
|
17507
|
+
/** `<dir>/<stem>.<run id><ext>`: a file of this run's own beside `file` (the run id reduced to letters, digits and `-`). */
|
|
17508
|
+
static perRun(file, runId, ext) {
|
|
17509
|
+
const stem = path9.basename(file, path9.extname(file));
|
|
17510
|
+
const id = runId.replace(/[^A-Za-z0-9-]/g, "").slice(0, 64) || "run";
|
|
17511
|
+
return path9.join(path9.dirname(file), `${stem}.${id}${ext}`);
|
|
17512
|
+
}
|
|
17513
|
+
/** The answer run's own files for `runId`: its AgentChat-only tool config (integration path) and its identity-line file. */
|
|
17514
|
+
answerRunFiles(runId) {
|
|
17515
|
+
if (this.options.profile !== "answer") return {};
|
|
17516
|
+
const base = this.options.mcpConfigPath ?? this.options.answerMcp?.file;
|
|
17517
|
+
return {
|
|
17518
|
+
...this.options.mcpConfigPath === void 0 && this.options.answerMcp !== void 0 ? { mcpConfigPath: _ClaudeRunner.perRun(this.options.answerMcp.file, runId, ".json") } : {},
|
|
17519
|
+
...base !== void 0 ? { identityFile: _ClaudeRunner.perRun(base, runId, ".identity.md") } : {}
|
|
17520
|
+
};
|
|
17521
|
+
}
|
|
17522
|
+
/**
|
|
17523
|
+
* What this runner's runs are denied reading: the key store, and for an
|
|
17524
|
+
* `answer` run also Claude Code's own record of every project
|
|
17525
|
+
* (`<config dir>/projects`: transcripts and auto memory). Claude Code lets a
|
|
17526
|
+
* run read its project's memory folder even with auto memory off and reads
|
|
17527
|
+
* blocked outside the working directories (seen on 2.1.322); a deny rule
|
|
17528
|
+
* wins over that.
|
|
17529
|
+
*/
|
|
17530
|
+
readDenyPaths() {
|
|
17531
|
+
return this.options.profile === "answer" ? [...this.options.denyReadPaths, claudeProjectsDirFor(this.options.configDir)] : [...this.options.denyReadPaths];
|
|
17532
|
+
}
|
|
17533
|
+
argsFor(mcpConfigPath, appendSystemPromptFile) {
|
|
17038
17534
|
return claudeRunArgs(this.options.profile, {
|
|
17039
17535
|
maxBudgetUsd: (this.options.env ?? process.env)["AGENTCHAT_RUN_MAX_BUDGET_USD"],
|
|
17040
|
-
|
|
17041
|
-
|
|
17536
|
+
workdir: this.workdir(),
|
|
17537
|
+
denyReadPaths: this.readDenyPaths(),
|
|
17538
|
+
...mcpConfigPath !== void 0 ? { mcpConfigPath } : {},
|
|
17539
|
+
...appendSystemPromptFile !== void 0 ? { appendSystemPromptFile } : {}
|
|
17042
17540
|
});
|
|
17043
17541
|
}
|
|
17542
|
+
/**
|
|
17543
|
+
* The argv of a run — exported for tests to pin per profile. With a `runId`,
|
|
17544
|
+
* that run's own files (an answer run's tool config and identity-line file);
|
|
17545
|
+
* without, the configured `answerMcp.file` stands in and no identity file.
|
|
17546
|
+
*/
|
|
17547
|
+
args(runId, identityLine) {
|
|
17548
|
+
if (runId === void 0) {
|
|
17549
|
+
const mcpConfigPath = this.options.mcpConfigPath ?? (this.options.profile === "answer" ? this.options.answerMcp?.file : void 0);
|
|
17550
|
+
return this.argsFor(mcpConfigPath, void 0);
|
|
17551
|
+
}
|
|
17552
|
+
const files = this.answerRunFiles(runId);
|
|
17553
|
+
return this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityLine === true ? files.identityFile : void 0);
|
|
17554
|
+
}
|
|
17555
|
+
/** The run's environment: no parent session; an answer run loads no CLAUDE.md and no auto memory (`ANSWER_ENV`). */
|
|
17556
|
+
runEnv() {
|
|
17557
|
+
const env = buildClaudeEnv(this.options.configDir, this.options.env ?? process.env);
|
|
17558
|
+
return this.options.profile === "answer" ? { ...env, ...ANSWER_ENV } : env;
|
|
17559
|
+
}
|
|
17044
17560
|
async start(request) {
|
|
17045
|
-
const
|
|
17046
|
-
|
|
17047
|
-
|
|
17048
|
-
|
|
17049
|
-
|
|
17050
|
-
|
|
17051
|
-
|
|
17052
|
-
|
|
17053
|
-
|
|
17054
|
-
|
|
17055
|
-
|
|
17056
|
-
|
|
17057
|
-
|
|
17058
|
-
|
|
17059
|
-
|
|
17561
|
+
const startedAt = Date.now();
|
|
17562
|
+
const notStarted = (detail) => ({ state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail });
|
|
17563
|
+
const answer = this.options.profile === "answer";
|
|
17564
|
+
const answerMcp = answer && this.options.mcpConfigPath === void 0 ? this.options.answerMcp : void 0;
|
|
17565
|
+
if (answer && this.options.mcpConfigPath === void 0 && answerMcp === void 0) {
|
|
17566
|
+
return notStarted("an answer run needs the AgentChat-only tool config (ClaudeRunnerOptions.answerMcp)");
|
|
17567
|
+
}
|
|
17568
|
+
if (answer) {
|
|
17569
|
+
const grant = claudeExtraDirectoriesGrant(this.options.configDir, this.workdir());
|
|
17570
|
+
if (grant !== null) return notStarted(extraDirectoriesRefusal(grant));
|
|
17571
|
+
}
|
|
17572
|
+
const files = this.answerRunFiles(request.runId);
|
|
17573
|
+
const identityFile = answer && request.identityLine !== void 0 ? files.identityFile : void 0;
|
|
17574
|
+
const written = [];
|
|
17575
|
+
const cleanup = () => {
|
|
17576
|
+
for (const file of written) fs7.rmSync(file, { force: true });
|
|
17577
|
+
};
|
|
17578
|
+
if (answerMcp !== void 0 && files.mcpConfigPath !== void 0) {
|
|
17579
|
+
const key = answerMcp.apiKey();
|
|
17580
|
+
if (key === null) return notStarted("no AgentChat key for the answer run's tool config");
|
|
17581
|
+
try {
|
|
17582
|
+
atomicWriteFile(files.mcpConfigPath, claudeMcpConfig(answerMcp.apiBase, key, answerMcp.clientVersion ?? VERSION2), 384);
|
|
17583
|
+
written.push(files.mcpConfigPath);
|
|
17584
|
+
} catch (err) {
|
|
17585
|
+
cleanup();
|
|
17586
|
+
return notStarted(`could not write the answer run's tool config ${files.mcpConfigPath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
17587
|
+
}
|
|
17588
|
+
}
|
|
17589
|
+
if (identityFile !== void 0 && request.identityLine !== void 0) {
|
|
17590
|
+
try {
|
|
17591
|
+
atomicWriteFile(identityFile, `${request.identityLine.trim()}
|
|
17592
|
+
`, 384);
|
|
17593
|
+
written.push(identityFile);
|
|
17594
|
+
} catch (err) {
|
|
17595
|
+
cleanup();
|
|
17596
|
+
return notStarted(`could not write the answer run's identity line ${identityFile}: ${err instanceof Error ? err.message : String(err)}`);
|
|
17597
|
+
}
|
|
17598
|
+
}
|
|
17599
|
+
try {
|
|
17600
|
+
const args = this.argsFor(files.mcpConfigPath ?? this.options.mcpConfigPath, identityFile);
|
|
17601
|
+
log.debug(`claude ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
|
|
17602
|
+
return await spawnRun({
|
|
17603
|
+
command: this.command,
|
|
17604
|
+
args,
|
|
17605
|
+
cwd: this.workdir(),
|
|
17606
|
+
env: this.runEnv(),
|
|
17607
|
+
stdin: request.prompt,
|
|
17608
|
+
budgetMs: request.budgetMs,
|
|
17609
|
+
// Stopping SIGTERMs this run's process group instead of orphaning it.
|
|
17610
|
+
...request.signal ? { signal: request.signal } : {},
|
|
17611
|
+
// The engine records a group invite as offered the moment the process
|
|
17612
|
+
// has spawned, so a run cut short still counts as the one offer.
|
|
17613
|
+
...request.onStarted ? { onStarted: request.onStarted } : {}
|
|
17614
|
+
});
|
|
17615
|
+
} finally {
|
|
17616
|
+
cleanup();
|
|
17617
|
+
}
|
|
17060
17618
|
}
|
|
17061
17619
|
};
|
|
17062
17620
|
function claudeMcpConfigPath(home) {
|
|
17063
|
-
return
|
|
17621
|
+
return path9.join(home, "presets", `${CLAUDE_CODE_PRESET}.mcp.json`);
|
|
17064
17622
|
}
|
|
17065
17623
|
var claudeCodePreset = {
|
|
17066
17624
|
name: CLAUDE_CODE_PRESET,
|
|
@@ -17075,11 +17633,13 @@ var claudeCodePreset = {
|
|
|
17075
17633
|
// Every run's file tools are denied the identity home.
|
|
17076
17634
|
serviceEnv: ["CLAUDE_CONFIG_DIR"],
|
|
17077
17635
|
readsIdentityHome: false,
|
|
17078
|
-
inspect(env = process.env, command = "claude") {
|
|
17636
|
+
async inspect(env = process.env, command = "claude") {
|
|
17079
17637
|
const configDir = claudeConfigDirFrom(env);
|
|
17080
|
-
const runtime = inspectClaudeRuntime(configDir, command);
|
|
17638
|
+
const runtime = await inspectClaudeRuntime(configDir, command);
|
|
17081
17639
|
if (!runtime.ok) return runtime;
|
|
17082
|
-
|
|
17640
|
+
const signIn = await claudeSignIn(configDir, command);
|
|
17641
|
+
if (signIn.unanswered !== null) return { ok: false, detail: `${runtime.detail}, ${signIn.unanswered}` };
|
|
17642
|
+
return signIn.signedIn ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in (run \`claude\` once and sign in)` };
|
|
17083
17643
|
},
|
|
17084
17644
|
runner(ctx) {
|
|
17085
17645
|
const env = withoutInheritedKey(ctx.env ?? process.env);
|
|
@@ -17092,7 +17652,7 @@ var claudeCodePreset = {
|
|
|
17092
17652
|
profile: ctx.profile,
|
|
17093
17653
|
// The listener's home (its key and this file), the user-scope MCP state
|
|
17094
17654
|
// and an integration's identity home beside it: no run reads a key.
|
|
17095
|
-
denyReadPaths: [ctx.home, claudeUserStatePathFor(configDir),
|
|
17655
|
+
denyReadPaths: [ctx.home, claudeUserStatePathFor(configDir), path9.join(claudeHomeFor(configDir), "agentchat")],
|
|
17096
17656
|
mcpConfigPath,
|
|
17097
17657
|
workdirAdvice: "Start the listener from a directory outside it, or pass --workdir.",
|
|
17098
17658
|
// On POSIX a listener's run must not start with its key readable; on
|
|
@@ -17111,35 +17671,59 @@ var CODEX_PROMPT_FROM_STDIN = "-";
|
|
|
17111
17671
|
function codexHomeFrom(env = process.env) {
|
|
17112
17672
|
const override = env["CODEX_HOME"];
|
|
17113
17673
|
if (override !== void 0 && override.trim().length > 0) return path24.resolve(override);
|
|
17114
|
-
return path24.join(
|
|
17115
|
-
}
|
|
17116
|
-
|
|
17117
|
-
|
|
17118
|
-
|
|
17119
|
-
|
|
17120
|
-
|
|
17121
|
-
env: { ...process.env, CODEX_HOME: codexHome2 }
|
|
17122
|
-
});
|
|
17674
|
+
return path24.join(os23.homedir(), ".codex");
|
|
17675
|
+
}
|
|
17676
|
+
var CODEX_PROBE_TIMEOUT_MS = 1e4;
|
|
17677
|
+
async function inspectCodexRuntime(codexHome2, command = "codex", timeoutMs = CODEX_PROBE_TIMEOUT_MS, signal) {
|
|
17678
|
+
const result = await runProbe(command, ["--version"], { timeoutMs, env: { ...process.env, CODEX_HOME: codexHome2 }, ...signal !== void 0 ? { signal } : {} });
|
|
17679
|
+
if (result.timedOut) return { ok: false, detail: `codex --version did not answer within ${Math.round(timeoutMs / 1e3)} s (killed)` };
|
|
17680
|
+
if (signal?.aborted) return { ok: false, detail: "codex --version was stopped" };
|
|
17123
17681
|
if (result.error) return { ok: false, detail: `codex CLI not found on PATH (${result.error.message})` };
|
|
17124
|
-
const rendered =
|
|
17682
|
+
const rendered = (result.stdout || result.stderr).trim();
|
|
17125
17683
|
if (result.status !== 0) return { ok: false, detail: rendered || `codex --version exited ${result.status}` };
|
|
17126
17684
|
return semverAtLeast(rendered, MIN_CODEX_VERSION) ? { ok: true, detail: rendered } : { ok: false, detail: `${rendered || "unrecognized version"}; AgentChat requires Codex >= ${MIN_CODEX_VERSION}` };
|
|
17127
17685
|
}
|
|
17128
|
-
function codexIsLoggedIn(codexHome2, command = "codex") {
|
|
17129
|
-
const status =
|
|
17130
|
-
encoding: "utf-8",
|
|
17131
|
-
timeout: 1e4,
|
|
17132
|
-
windowsHide: true,
|
|
17133
|
-
env: { ...process.env, CODEX_HOME: codexHome2 }
|
|
17134
|
-
});
|
|
17686
|
+
async function codexIsLoggedIn(codexHome2, command = "codex", timeoutMs = CODEX_PROBE_TIMEOUT_MS, signal) {
|
|
17687
|
+
const status = await runProbe(command, ["login", "status"], { timeoutMs, env: { ...process.env, CODEX_HOME: codexHome2 }, ...signal !== void 0 ? { signal } : {} });
|
|
17135
17688
|
if (status.error) return { ok: false, detail: status.error.message };
|
|
17136
|
-
const detail = `${status.stdout
|
|
17689
|
+
const detail = `${status.stdout}${status.stderr}`.trim().slice(0, 200);
|
|
17137
17690
|
return status.status === 0 ? { ok: true, detail: detail || "signed in" } : { ok: false, detail: detail || "codex is not signed in (run `codex login`)" };
|
|
17138
17691
|
}
|
|
17692
|
+
var CODEX_ANSWER_PERMISSIONS = "agentchat_answer";
|
|
17693
|
+
var CODEX_ANSWER_FILESYSTEM = '{ ":workspace_roots" = "read" }';
|
|
17694
|
+
var CODEX_ANSWER_DISABLED_FEATURES = [
|
|
17695
|
+
"shell_tool",
|
|
17696
|
+
"view_image",
|
|
17697
|
+
"image_generation",
|
|
17698
|
+
"plugins",
|
|
17699
|
+
"apps",
|
|
17700
|
+
"memories",
|
|
17701
|
+
"browser_use",
|
|
17702
|
+
"browser_use_external",
|
|
17703
|
+
"computer_use",
|
|
17704
|
+
"in_app_browser"
|
|
17705
|
+
];
|
|
17139
17706
|
function codexProfileArgs(profile2) {
|
|
17140
17707
|
switch (profile2) {
|
|
17141
17708
|
case "answer":
|
|
17142
|
-
return [
|
|
17709
|
+
return [
|
|
17710
|
+
"-c",
|
|
17711
|
+
'approval_policy="never"',
|
|
17712
|
+
"-c",
|
|
17713
|
+
`default_permissions="${CODEX_ANSWER_PERMISSIONS}"`,
|
|
17714
|
+
"-c",
|
|
17715
|
+
`permissions.${CODEX_ANSWER_PERMISSIONS}.filesystem=${CODEX_ANSWER_FILESYSTEM}`,
|
|
17716
|
+
"-c",
|
|
17717
|
+
'web_search="disabled"',
|
|
17718
|
+
// No project or ancestor AGENTS.md (core/src/agents_md.rs:65-67, 129: a
|
|
17719
|
+
// zero budget reads none). $CODEX_HOME/AGENTS.md has no such switch in
|
|
17720
|
+
// 0.154.0 (codex-home/src/instructions/mod.rs, wired unconditionally).
|
|
17721
|
+
"-c",
|
|
17722
|
+
"project_doc_max_bytes=0",
|
|
17723
|
+
...CODEX_ANSWER_DISABLED_FEATURES.flatMap((feature) => ["--disable", feature])
|
|
17724
|
+
];
|
|
17725
|
+
// `work` and `full` are the operator's explicit opt-in: a run started by
|
|
17726
|
+
// any peer's message can then read and change this machine.
|
|
17143
17727
|
case "work":
|
|
17144
17728
|
return ["--sandbox", "workspace-write", "-c", 'approval_policy="never"'];
|
|
17145
17729
|
case "full":
|
|
@@ -17150,6 +17734,9 @@ function codexClientHeadersToml(clientVersion = VERSION2) {
|
|
|
17150
17734
|
const pairs = Object.entries(clientHeadersOf({ runtime: "codex", version: clientVersion })).map(([name, value]) => `${JSON.stringify(name)} = ${JSON.stringify(value)}`);
|
|
17151
17735
|
return `{ ${pairs.join(", ")} }`;
|
|
17152
17736
|
}
|
|
17737
|
+
function codexPinnedUrlArgs(url) {
|
|
17738
|
+
return ["-c", `mcp_servers.${CODEX_MCP_SERVER_NAME}.url=${JSON.stringify(url)}`];
|
|
17739
|
+
}
|
|
17153
17740
|
function codexMcpOverrideArgs(override) {
|
|
17154
17741
|
const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`;
|
|
17155
17742
|
return [
|
|
@@ -17176,6 +17763,81 @@ function codexRunArgs(profile2, options) {
|
|
|
17176
17763
|
CODEX_PROMPT_FROM_STDIN
|
|
17177
17764
|
];
|
|
17178
17765
|
}
|
|
17766
|
+
function codexAnswerFallbackWorkdir(codexHome2) {
|
|
17767
|
+
return path24.join(codexHome2, "agentchat-answer-workdir");
|
|
17768
|
+
}
|
|
17769
|
+
var CODEX_MCP_LIST_TIMEOUT_MS = 2e4;
|
|
17770
|
+
var CODEX_MCP_LIST_KILL_WAIT_MS = 1e4;
|
|
17771
|
+
var CODEX_MCP_LIST_MAX_BYTES = 1024 * 1024;
|
|
17772
|
+
function codexServerNameAddressable(name) {
|
|
17773
|
+
return /^[A-Za-z0-9_:@/-]+$/.test(name);
|
|
17774
|
+
}
|
|
17775
|
+
function parseCodexMcpList(stdout) {
|
|
17776
|
+
let parsed;
|
|
17777
|
+
try {
|
|
17778
|
+
parsed = JSON.parse(stdout);
|
|
17779
|
+
} catch {
|
|
17780
|
+
return { ok: false, detail: "its output is not JSON" };
|
|
17781
|
+
}
|
|
17782
|
+
if (!Array.isArray(parsed)) return { ok: false, detail: "its output is not a list" };
|
|
17783
|
+
const names = [];
|
|
17784
|
+
for (const entry of parsed) {
|
|
17785
|
+
const name = entry?.name;
|
|
17786
|
+
const enabled = entry?.enabled;
|
|
17787
|
+
if (typeof name !== "string" || name.length === 0) return { ok: false, detail: "an entry has no name" };
|
|
17788
|
+
if (enabled !== false) names.push(name);
|
|
17789
|
+
}
|
|
17790
|
+
return { ok: true, names };
|
|
17791
|
+
}
|
|
17792
|
+
function codexMcpDisableArgs(names) {
|
|
17793
|
+
const args = [];
|
|
17794
|
+
for (const name of names) {
|
|
17795
|
+
if (name === CODEX_MCP_SERVER_NAME) continue;
|
|
17796
|
+
if (!codexServerNameAddressable(name)) {
|
|
17797
|
+
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` };
|
|
17798
|
+
}
|
|
17799
|
+
args.push("-c", `mcp_servers.${name}.enabled=false`);
|
|
17800
|
+
}
|
|
17801
|
+
return { ok: true, args };
|
|
17802
|
+
}
|
|
17803
|
+
function codexAnswerListingRefusal(detail) {
|
|
17804
|
+
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`;
|
|
17805
|
+
}
|
|
17806
|
+
var CODEX_MCP_LIST_MAX_AGE_MS = 60 * 6e4;
|
|
17807
|
+
function codexConfigLayerFiles(codexHome2, workdir, platform = process.platform, env = process.env) {
|
|
17808
|
+
const p = platform === "win32" ? path24.win32 : path24.posix;
|
|
17809
|
+
const programData = env["ProgramData"] ?? env["PROGRAMDATA"] ?? "C:\\ProgramData";
|
|
17810
|
+
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"];
|
|
17811
|
+
const user = (() => {
|
|
17812
|
+
try {
|
|
17813
|
+
return os23.userInfo().username;
|
|
17814
|
+
} catch {
|
|
17815
|
+
return null;
|
|
17816
|
+
}
|
|
17817
|
+
})();
|
|
17818
|
+
const managedPrefs = platform === "darwin" ? ["/Library/Managed Preferences/com.openai.codex.plist", ...user !== null ? [p.join("/Library/Managed Preferences", user, "com.openai.codex.plist")] : []] : [];
|
|
17819
|
+
const tree = [];
|
|
17820
|
+
let current = p.resolve(workdir);
|
|
17821
|
+
tree.push(p.join(current, "config.toml"));
|
|
17822
|
+
for (; ; ) {
|
|
17823
|
+
tree.push(p.join(current, ".codex", "config.toml"));
|
|
17824
|
+
const parent = p.dirname(current);
|
|
17825
|
+
if (parent === current) break;
|
|
17826
|
+
current = parent;
|
|
17827
|
+
}
|
|
17828
|
+
return [...system, ...managedPrefs, p.join(codexHome2, "config.toml"), ...tree];
|
|
17829
|
+
}
|
|
17830
|
+
function codexListingKey(files, parts) {
|
|
17831
|
+
const stats = files.map((file) => {
|
|
17832
|
+
try {
|
|
17833
|
+
const st = fs24.statSync(file);
|
|
17834
|
+
return `${file}\0${st.size}\0${st.mtimeMs}`;
|
|
17835
|
+
} catch {
|
|
17836
|
+
return `${file}\0-`;
|
|
17837
|
+
}
|
|
17838
|
+
});
|
|
17839
|
+
return [...parts, ...stats].join("");
|
|
17840
|
+
}
|
|
17179
17841
|
var CodexRunner = class {
|
|
17180
17842
|
constructor(options) {
|
|
17181
17843
|
this.options = options;
|
|
@@ -17184,32 +17846,138 @@ var CodexRunner = class {
|
|
|
17184
17846
|
options;
|
|
17185
17847
|
name = "codex";
|
|
17186
17848
|
command;
|
|
17187
|
-
|
|
17188
|
-
|
|
17849
|
+
warnedHome = false;
|
|
17850
|
+
/** 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. */
|
|
17851
|
+
listing = null;
|
|
17852
|
+
/**
|
|
17853
|
+
* Where this runner's runs work (`-C`): the configured workdir, except that an
|
|
17854
|
+
* `answer` run never has the home folder or above it as its workspace root —
|
|
17855
|
+
* it gets `codexAnswerFallbackWorkdir`.
|
|
17856
|
+
*/
|
|
17857
|
+
workdir() {
|
|
17858
|
+
if (this.options.profile === "answer" && workdirExposesHome(this.options.workdir)) return codexAnswerFallbackWorkdir(this.options.codexHome);
|
|
17859
|
+
return this.options.workdir;
|
|
17860
|
+
}
|
|
17861
|
+
async preflight(options = {}) {
|
|
17862
|
+
const runtime = await inspectCodexRuntime(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal);
|
|
17189
17863
|
if (!runtime.ok) return { ok: false, detail: runtime.detail };
|
|
17190
|
-
const auth = codexIsLoggedIn(this.options.codexHome, this.command);
|
|
17864
|
+
const auth = await codexIsLoggedIn(this.options.codexHome, this.command, CODEX_PROBE_TIMEOUT_MS, options.signal);
|
|
17191
17865
|
if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` };
|
|
17192
|
-
|
|
17866
|
+
if (this.workdir() !== this.options.workdir && !this.warnedHome) {
|
|
17867
|
+
this.warnedHome = true;
|
|
17868
|
+
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.`);
|
|
17869
|
+
}
|
|
17870
|
+
fs24.mkdirSync(this.workdir(), { recursive: true });
|
|
17871
|
+
if (this.options.profile === "answer") {
|
|
17872
|
+
const disables = await this.answerMcpDisables();
|
|
17873
|
+
if (!disables.ok) return { ok: false, detail: codexAnswerListingRefusal(disables.detail) };
|
|
17874
|
+
}
|
|
17193
17875
|
return { ok: true };
|
|
17194
17876
|
}
|
|
17195
|
-
/** The exact argv one run uses — exported for tests to pin per profile. */
|
|
17877
|
+
/** The exact argv one run uses — exported for tests to pin per profile. An `answer` run adds `answerMcpDisables()` before the prompt. */
|
|
17196
17878
|
args() {
|
|
17197
|
-
|
|
17879
|
+
const args = codexRunArgs(this.options.profile, { workdir: this.workdir(), ...this.options.mcp !== void 0 ? { mcp: this.options.mcp } : {} });
|
|
17880
|
+
if (this.options.mcp !== void 0 || this.options.pinMcpUrl === void 0) return args;
|
|
17881
|
+
return [...args.slice(0, -1), ...codexPinnedUrlArgs(this.options.pinMcpUrl), CODEX_PROMPT_FROM_STDIN];
|
|
17198
17882
|
}
|
|
17199
17883
|
/** The child environment: Codex's home and the key the hosted server needs, under the configured name. */
|
|
17200
17884
|
env() {
|
|
17201
|
-
const env = { ...this.options.env ?? process.env, CODEX_HOME: this.options.codexHome };
|
|
17885
|
+
const env = { ...withoutParentSession(this.options.env ?? process.env), CODEX_HOME: this.options.codexHome };
|
|
17202
17886
|
const key = this.options.apiKey();
|
|
17203
17887
|
if (key !== null) env[this.options.keyEnv] = key;
|
|
17204
17888
|
return env;
|
|
17205
17889
|
}
|
|
17890
|
+
/**
|
|
17891
|
+
* For an `answer` run: `-c mcp_servers.<name>.enabled=false` for every MCP
|
|
17892
|
+
* server the run would load but AgentChat's — the user's own in config.toml,
|
|
17893
|
+
* a project's, a managed one. Codex has no "only this server" switch, and a
|
|
17894
|
+
* tool such a server marks read-only runs without approval. Asked of Codex
|
|
17895
|
+
* itself (`codex mcp list --json`, with the run's own `-c`/`--disable`
|
|
17896
|
+
* flags, from the run's workdir), so every layer is counted. Any failure —
|
|
17897
|
+
* an error, a timeout, output that is not the list — means no run.
|
|
17898
|
+
*/
|
|
17899
|
+
async answerMcpDisables() {
|
|
17900
|
+
const run3 = this.args();
|
|
17901
|
+
const flags = run3.flatMap((arg, i) => run3[i - 1] === "-c" || run3[i - 1] === "--disable" ? [run3[i - 1], arg] : []);
|
|
17902
|
+
const key = codexListingKey(codexConfigLayerFiles(this.options.codexHome, this.workdir()), [this.command, this.workdir(), ...flags]);
|
|
17903
|
+
if (this.listing !== null && this.listing.key === key && Date.now() - this.listing.at < CODEX_MCP_LIST_MAX_AGE_MS) return this.listing.result;
|
|
17904
|
+
const listed = await new Promise((resolve32) => {
|
|
17905
|
+
let child;
|
|
17906
|
+
try {
|
|
17907
|
+
child = spawnCommand(this.command, ["mcp", "list", "--json", ...flags], {
|
|
17908
|
+
cwd: this.workdir(),
|
|
17909
|
+
env: this.env(),
|
|
17910
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
17911
|
+
// Its own process group on POSIX, so a hung listing is killed with
|
|
17912
|
+
// everything it started (the npm launcher and the native binary).
|
|
17913
|
+
detached: process.platform !== "win32",
|
|
17914
|
+
windowsHide: true
|
|
17915
|
+
});
|
|
17916
|
+
} catch (err) {
|
|
17917
|
+
resolve32({ ok: false, detail: err instanceof Error ? err.message : String(err) });
|
|
17918
|
+
return;
|
|
17919
|
+
}
|
|
17920
|
+
const proc = child;
|
|
17921
|
+
let stdout = "";
|
|
17922
|
+
let stderr = "";
|
|
17923
|
+
let stopped = null;
|
|
17924
|
+
let settled = false;
|
|
17925
|
+
let abandonTimer = null;
|
|
17926
|
+
const settle = (result2) => {
|
|
17927
|
+
if (settled) return;
|
|
17928
|
+
settled = true;
|
|
17929
|
+
clearTimeout(timer);
|
|
17930
|
+
if (abandonTimer !== null) clearTimeout(abandonTimer);
|
|
17931
|
+
resolve32(result2);
|
|
17932
|
+
};
|
|
17933
|
+
const stop = (why) => {
|
|
17934
|
+
if (stopped !== null) return;
|
|
17935
|
+
stopped = why;
|
|
17936
|
+
killProcessTree(proc, "SIGKILL");
|
|
17937
|
+
abandonTimer = setTimeout(() => settle({ ok: false, detail: `${why} (and it did not exit after being killed)` }), CODEX_MCP_LIST_KILL_WAIT_MS);
|
|
17938
|
+
};
|
|
17939
|
+
proc.stderr?.on("data", (chunk) => {
|
|
17940
|
+
if (stderr.length < 4096) stderr += chunk.toString("utf-8");
|
|
17941
|
+
});
|
|
17942
|
+
const timeoutMs = this.options.mcpListTimeoutMs ?? CODEX_MCP_LIST_TIMEOUT_MS;
|
|
17943
|
+
const timer = setTimeout(() => stop(`no answer within ${Math.round(timeoutMs / 1e3)} s`), timeoutMs);
|
|
17944
|
+
proc.stdout?.on("data", (chunk) => {
|
|
17945
|
+
stdout += chunk.toString("utf-8");
|
|
17946
|
+
if (stdout.length > CODEX_MCP_LIST_MAX_BYTES) stop("its output is too long");
|
|
17947
|
+
});
|
|
17948
|
+
proc.on("error", (err) => {
|
|
17949
|
+
if (stopped === null) settle({ ok: false, detail: err.message });
|
|
17950
|
+
});
|
|
17951
|
+
proc.on("close", (code) => {
|
|
17952
|
+
if (stopped !== null) {
|
|
17953
|
+
settle({ ok: false, detail: stopped });
|
|
17954
|
+
return;
|
|
17955
|
+
}
|
|
17956
|
+
const said = redactDiagnostic(stderr.split(/\r?\n/).find((line) => line.trim().length > 0) ?? "", 200);
|
|
17957
|
+
if (code !== 0) settle({ ok: false, detail: `it exited ${code}${said ? `: ${said}` : ""}` });
|
|
17958
|
+
else settle({ ok: true, stdout });
|
|
17959
|
+
});
|
|
17960
|
+
});
|
|
17961
|
+
if (!listed.ok) return listed;
|
|
17962
|
+
const parsed = parseCodexMcpList(listed.stdout);
|
|
17963
|
+
if (!parsed.ok) return parsed;
|
|
17964
|
+
const result = codexMcpDisableArgs(parsed.names);
|
|
17965
|
+
if (result.ok) this.listing = { key, at: Date.now(), result };
|
|
17966
|
+
return result;
|
|
17967
|
+
}
|
|
17206
17968
|
async start(request) {
|
|
17207
|
-
const
|
|
17969
|
+
const startedAt = Date.now();
|
|
17970
|
+
let args = this.args();
|
|
17971
|
+
if (this.options.profile === "answer") {
|
|
17972
|
+
const disables = await this.answerMcpDisables();
|
|
17973
|
+
if (!disables.ok) return { state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail: codexAnswerListingRefusal(disables.detail) };
|
|
17974
|
+
args = [...args.slice(0, -1), ...disables.args, CODEX_PROMPT_FROM_STDIN];
|
|
17975
|
+
}
|
|
17208
17976
|
log.debug(`codex ${args.join(" ")} (prompt on stdin, ${request.kind} run ${request.runId})`);
|
|
17209
17977
|
return spawnRun({
|
|
17210
17978
|
command: this.command,
|
|
17211
17979
|
args,
|
|
17212
|
-
cwd: this.
|
|
17980
|
+
cwd: this.workdir(),
|
|
17213
17981
|
env: this.env(),
|
|
17214
17982
|
// Written to stdin and then closed: `codex exec -` reads its
|
|
17215
17983
|
// instructions until EOF. Never as an argument (see codexRunArgs).
|
|
@@ -17253,14 +18021,15 @@ var codexPreset = {
|
|
|
17253
18021
|
},
|
|
17254
18022
|
label: "Codex",
|
|
17255
18023
|
runtime: "codex",
|
|
17256
|
-
// A read-only sandbox reads the whole filesystem.
|
|
17257
18024
|
serviceEnv: ["CODEX_HOME"],
|
|
18025
|
+
// `work` and `full` read the whole filesystem (an `answer` run reads only its
|
|
18026
|
+
// workdir): true, because the field is one for every profile.
|
|
17258
18027
|
readsIdentityHome: true,
|
|
17259
|
-
inspect(env = process.env, command = "codex") {
|
|
18028
|
+
async inspect(env = process.env, command = "codex") {
|
|
17260
18029
|
const home = codexHomeFrom(env);
|
|
17261
|
-
const runtime = inspectCodexRuntime(home, command);
|
|
18030
|
+
const runtime = await inspectCodexRuntime(home, command);
|
|
17262
18031
|
if (!runtime.ok) return runtime;
|
|
17263
|
-
const auth = codexIsLoggedIn(home, command);
|
|
18032
|
+
const auth = await codexIsLoggedIn(home, command);
|
|
17264
18033
|
return auth.ok ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in: ${auth.detail}` };
|
|
17265
18034
|
},
|
|
17266
18035
|
runner(ctx) {
|
|
@@ -17283,24 +18052,36 @@ var PRESETS = Object.freeze({
|
|
|
17283
18052
|
[codexPreset.name]: codexPreset
|
|
17284
18053
|
});
|
|
17285
18054
|
|
|
18055
|
+
// src/runner.ts
|
|
18056
|
+
var CodexRunner2 = class extends CodexRunner {
|
|
18057
|
+
constructor(options) {
|
|
18058
|
+
const { identityHome: identityHome2, ...rest } = options;
|
|
18059
|
+
super({ ...rest, apiKey: () => resolveIdentity(identityHome2)?.apiKey ?? null, keyEnv: API_KEY_ENV });
|
|
18060
|
+
}
|
|
18061
|
+
};
|
|
18062
|
+
function profileNote(profile2) {
|
|
18063
|
+
const warning = runProfileWarning(profile2);
|
|
18064
|
+
return warning !== null ? ` \u2014 ${warning}` : "";
|
|
18065
|
+
}
|
|
18066
|
+
|
|
17286
18067
|
// src/service.ts
|
|
17287
|
-
import * as
|
|
17288
|
-
import * as
|
|
18068
|
+
import * as fs8 from "fs";
|
|
18069
|
+
import * as path10 from "path";
|
|
17289
18070
|
import { fileURLToPath } from "url";
|
|
17290
|
-
var DAEMON_REL =
|
|
18071
|
+
var DAEMON_REL = path10.join("bin", "agentchat-daemon.mjs");
|
|
17291
18072
|
function shippedDaemonPath() {
|
|
17292
|
-
return
|
|
18073
|
+
return path10.join(path10.dirname(fileURLToPath(import.meta.url)), "daemon-main.js");
|
|
17293
18074
|
}
|
|
17294
18075
|
function stableDaemonPath() {
|
|
17295
|
-
return
|
|
18076
|
+
return path10.join(identityHome(), DAEMON_REL);
|
|
17296
18077
|
}
|
|
17297
18078
|
function copyDaemonBundle() {
|
|
17298
18079
|
const src = shippedDaemonPath();
|
|
17299
|
-
if (!
|
|
18080
|
+
if (!fs8.existsSync(src)) throw new Error(`the daemon bundle is missing from this install (expected ${src})`);
|
|
17300
18081
|
const dest = stableDaemonPath();
|
|
17301
|
-
|
|
17302
|
-
if (
|
|
17303
|
-
else
|
|
18082
|
+
fs8.mkdirSync(path10.dirname(dest), { recursive: true });
|
|
18083
|
+
if (path10.resolve(src) !== path10.resolve(dest)) atomicCopyFile(src, dest);
|
|
18084
|
+
else fs8.chmodSync(dest, 493);
|
|
17304
18085
|
return dest;
|
|
17305
18086
|
}
|
|
17306
18087
|
function serviceOpts() {
|
|
@@ -17311,7 +18092,7 @@ function ensureListenerService(opts = {}) {
|
|
|
17311
18092
|
if (!opts.force && alwaysOnOptedOut(home)) return { ok: false, detail: "switched off by the user" };
|
|
17312
18093
|
try {
|
|
17313
18094
|
const service = serviceOpts();
|
|
17314
|
-
if (!opts.force && alwaysOnWanted(home) && readAlwaysOnInstalledVersion(home) === VERSION3 &&
|
|
18095
|
+
if (!opts.force && alwaysOnWanted(home) && readAlwaysOnInstalledVersion(home) === VERSION3 && fs8.existsSync(service.entry) && serviceDefinitionCurrent(service)) {
|
|
17315
18096
|
return { ok: true };
|
|
17316
18097
|
}
|
|
17317
18098
|
const entry = copyDaemonBundle();
|
|
@@ -17326,7 +18107,7 @@ function ensureListenerService(opts = {}) {
|
|
|
17326
18107
|
function listenerServiceCurrent() {
|
|
17327
18108
|
const home = identityHome();
|
|
17328
18109
|
const service = serviceOpts();
|
|
17329
|
-
return alwaysOnWanted(home) &&
|
|
18110
|
+
return alwaysOnWanted(home) && fs8.existsSync(service.entry) && readAlwaysOnInstalledVersion(home) === VERSION3 && serviceDefinitionCurrent(service);
|
|
17330
18111
|
}
|
|
17331
18112
|
function removeListenerService() {
|
|
17332
18113
|
const home = identityHome();
|
|
@@ -17369,12 +18150,20 @@ var profile = {
|
|
|
17369
18150
|
},
|
|
17370
18151
|
unplace: () => unplaceIdentity().map((s) => ` ${s.name}: ${s.detail}`),
|
|
17371
18152
|
logoutHints: () => [`To remove the integration too, run \`${invocation()} uninstall\`.`],
|
|
17372
|
-
extraDoctorChecks: async (ctx) =>
|
|
17373
|
-
|
|
17374
|
-
|
|
17375
|
-
|
|
17376
|
-
|
|
17377
|
-
|
|
18153
|
+
extraDoctorChecks: async (ctx) => {
|
|
18154
|
+
const runtime = await runtimeChecks();
|
|
18155
|
+
return [
|
|
18156
|
+
...runtime,
|
|
18157
|
+
...await placementChecks(ctx.fix === true, ctx, ctx.manual),
|
|
18158
|
+
serviceCheck(ctx.fix === true),
|
|
18159
|
+
workdirCheck(),
|
|
18160
|
+
profileCheck(),
|
|
18161
|
+
// The runner's own gate needs a working, signed-in Codex first; the checks above say when it is not.
|
|
18162
|
+
...runtime.every((c) => c.verdict === "PASS") ? [await preflightCheck()] : [],
|
|
18163
|
+
integrationCheck(),
|
|
18164
|
+
...[leaseCheck()].filter((c) => c !== null)
|
|
18165
|
+
];
|
|
18166
|
+
},
|
|
17378
18167
|
// The shared status already fetched the served texts once; the placement
|
|
17379
18168
|
// checks reuse the identity line, its template and the announced manual
|
|
17380
18169
|
// rather than fetching `/v1/texts` again.
|
|
@@ -17391,15 +18180,15 @@ var profile = {
|
|
|
17391
18180
|
function concise(value) {
|
|
17392
18181
|
return value.replace(/\s+/g, " ").trim().slice(0, 180);
|
|
17393
18182
|
}
|
|
17394
|
-
function runtimeChecks() {
|
|
17395
|
-
const runtime = inspectCodexRuntime(codexHome());
|
|
18183
|
+
async function runtimeChecks() {
|
|
18184
|
+
const runtime = await inspectCodexRuntime(codexHome());
|
|
17396
18185
|
if (!runtime.ok) {
|
|
17397
18186
|
return [
|
|
17398
18187
|
{ name: "codex-cli", verdict: "FAIL", detail: runtime.detail },
|
|
17399
18188
|
{ name: "codex-auth", verdict: "FAIL", detail: "cannot check until the Codex CLI works" }
|
|
17400
18189
|
];
|
|
17401
18190
|
}
|
|
17402
|
-
const auth = codexIsLoggedIn(codexHome());
|
|
18191
|
+
const auth = await codexIsLoggedIn(codexHome());
|
|
17403
18192
|
return [
|
|
17404
18193
|
{ name: "codex-cli", verdict: "PASS", detail: concise(runtime.detail) },
|
|
17405
18194
|
{ name: "codex-auth", verdict: auth.ok ? "PASS" : "FAIL", detail: auth.ok ? "Codex is signed in; headless runs can start" : concise(auth.detail) }
|
|
@@ -17431,6 +18220,56 @@ function serviceCheck(fix) {
|
|
|
17431
18220
|
const state = alwaysOnState(home);
|
|
17432
18221
|
return { name: "service", verdict: state === "down" ? "FAIL" : "PASS", detail: `${state}; service definition and daemon bundle match ${VERSION3}` };
|
|
17433
18222
|
}
|
|
18223
|
+
function runSettings() {
|
|
18224
|
+
const shell = { profile: resolveRunProfile(), workdir: resolveRunWorkdir(identityHome()) };
|
|
18225
|
+
const status = readIntegrationStatus(identityHome());
|
|
18226
|
+
if (status === null || !isRunProfile(status.profile)) return { ...shell, differs: null };
|
|
18227
|
+
const recorded = { profile: status.profile, workdir: status.workdir ?? shell.workdir };
|
|
18228
|
+
const changes = [
|
|
18229
|
+
recorded.profile !== shell.profile ? `profile ${shell.profile}` : null,
|
|
18230
|
+
path11.resolve(recorded.workdir) !== shell.workdir ? `working root ${shell.workdir}` : null
|
|
18231
|
+
].filter((c) => c !== null);
|
|
18232
|
+
return { ...recorded, differs: changes.length > 0 ? changes.join(" and ") : null };
|
|
18233
|
+
}
|
|
18234
|
+
function settingsNote(settings) {
|
|
18235
|
+
return settings.differs !== null ? ` (the daemon's, from its status; install, \`daemon install\` or \`doctor --fix\` from this shell would set ${settings.differs})` : "";
|
|
18236
|
+
}
|
|
18237
|
+
function daemonRunner(settings = runSettings()) {
|
|
18238
|
+
const apiBase = resolveIdentity(identityHome())?.apiBase ?? DEFAULT_API_BASE;
|
|
18239
|
+
return new CodexRunner2({ codexHome: codexHome(), identityHome: identityHome(), workdir: settings.workdir, profile: settings.profile, pinMcpUrl: hostedMcpUrl2(apiBase) });
|
|
18240
|
+
}
|
|
18241
|
+
function workdirCheck() {
|
|
18242
|
+
const settings = runSettings();
|
|
18243
|
+
const workdir = settings.workdir;
|
|
18244
|
+
const note = settingsNote(settings);
|
|
18245
|
+
const fix = `point AGENTCHAT_RUN_CWD at a folder of its own (or unset it for ${runWorkdirFor(identityHome())}), then \`${invocation()} daemon install\``;
|
|
18246
|
+
if (workdirExposesHome(workdir)) {
|
|
18247
|
+
return {
|
|
18248
|
+
name: "run-workdir",
|
|
18249
|
+
verdict: "WARN",
|
|
18250
|
+
detail: `${workdir}${note} is your home folder or contains it \u2014 ${settings.profile === "answer" ? `answer runs work in ${codexAnswerFallbackWorkdir(codexHome())} instead` : "a run started by a peer's message there can see everything under it"}; ${fix}`
|
|
18251
|
+
};
|
|
18252
|
+
}
|
|
18253
|
+
if (deniedAncestorOf(codexHome(), [workdir]) !== null) {
|
|
18254
|
+
const what = path11.resolve(workdir) === codexHome() ? "is $CODEX_HOME" : `contains ${codexHome()}`;
|
|
18255
|
+
return { name: "run-workdir", verdict: "WARN", detail: `${workdir}${note} ${what}, where the key is (.env, agentchat/credentials): a run working there can read it \u2014 ${fix}` };
|
|
18256
|
+
}
|
|
18257
|
+
return { name: "run-workdir", verdict: "PASS", detail: `${workdir}${note}` };
|
|
18258
|
+
}
|
|
18259
|
+
function profileCheck() {
|
|
18260
|
+
const settings = runSettings();
|
|
18261
|
+
const warning = runProfileWarning(settings.profile);
|
|
18262
|
+
if (warning !== null) return { name: "run-profile", verdict: "WARN", detail: `${settings.profile}: ${warning}${settingsNote(settings)} (AGENTCHAT_RUN_PROFILE; answer is the default)` };
|
|
18263
|
+
return {
|
|
18264
|
+
name: "run-profile",
|
|
18265
|
+
verdict: settings.differs !== null ? "WARN" : "PASS",
|
|
18266
|
+
detail: `answer: the AgentChat tools only \u2014 no shell, no web, no file tool (apply_patch reads ${daemonRunner(settings).workdir()} alone and writes nothing), no other MCP server, no project AGENTS.md; ${anchorFile()} is still in its context${settingsNote(settings)}`
|
|
18267
|
+
};
|
|
18268
|
+
}
|
|
18269
|
+
async function preflightCheck() {
|
|
18270
|
+
const pre = await daemonRunner().preflight();
|
|
18271
|
+
return pre.ok ? { name: "run-preflight", verdict: "PASS", detail: "the daemon can start a run (the runner's preflight passes)" } : { name: "run-preflight", verdict: "FAIL", detail: `no run starts: ${pre.detail ?? "the runner's preflight failed"}` };
|
|
18272
|
+
}
|
|
17434
18273
|
function integrationCheck() {
|
|
17435
18274
|
const home = identityHome();
|
|
17436
18275
|
if (readCredentials(home) === null) return { name: "integration", verdict: "PASS", detail: "no identity \u2014 the daemon idles by design" };
|
|
@@ -17439,16 +18278,42 @@ function integrationCheck() {
|
|
|
17439
18278
|
const age = integrationStatusAge(status) ?? Number.POSITIVE_INFINITY;
|
|
17440
18279
|
if (age > 3 * 6e4) return { name: "integration", verdict: "FAIL", detail: `status last written ${Math.round(age / 6e4)} min ago \u2014 the daemon is not running` };
|
|
17441
18280
|
if (status.socket === "off") return { name: "integration", verdict: "PASS", detail: `${integrationDisabledBy() ?? INTEGRATION_ENV}=off \u2014 resident, holding no socket` };
|
|
18281
|
+
const gaveUp = status.unservable ?? null;
|
|
18282
|
+
if (gaveUp !== null) return { name: "integration", verdict: "FAIL", detail: gaveUpLine(gaveUp) };
|
|
18283
|
+
const standby = status.standby ?? null;
|
|
18284
|
+
if (standby !== null) {
|
|
18285
|
+
return {
|
|
18286
|
+
name: "integration",
|
|
18287
|
+
verdict: "WARN",
|
|
18288
|
+
detail: `standing by \u2014 ${standby.home ?? "another identity home"}${standby.pid !== null ? ` (pid ${standby.pid})` : ""} serves this agent; this daemon holds no socket and starts no run while it does, and takes over when it stops`
|
|
18289
|
+
};
|
|
18290
|
+
}
|
|
17442
18291
|
if (status.socket === "ready") {
|
|
17443
18292
|
const texts = status.texts?.source ?? "none";
|
|
18293
|
+
const failing = status.runs_failing ?? null;
|
|
18294
|
+
if (failing !== null) {
|
|
18295
|
+
return { name: "integration", verdict: "WARN", detail: `socket ready, but runs are failing: ${failing.reason} (since ${failing.since}, ${failing.runs_missed} run(s) missed)` };
|
|
18296
|
+
}
|
|
17444
18297
|
return {
|
|
17445
18298
|
name: "integration",
|
|
17446
18299
|
verdict: texts === "none" ? "WARN" : "PASS",
|
|
17447
|
-
detail: `socket ready (acks on receipt), ${status.wakes} wake(s), ${status.runs_started} run(s) (${status.runs_ok} ok), texts ${texts === "server" ? "served" : texts === "cache" ? "from cache" : "NOT fetched yet"}, profile ${status.profile}`
|
|
18300
|
+
detail: `socket ready (acks on receipt), ${status.wakes} wake(s), ${status.runs_started} run(s) (${status.runs_ok} ok), texts ${texts === "server" ? "served" : texts === "cache" ? "from cache" : "NOT fetched yet"}, profile ${status.profile}${profileNote(status.profile)}`
|
|
17448
18301
|
};
|
|
17449
18302
|
}
|
|
17450
18303
|
return { name: "integration", verdict: "WARN", detail: `socket ${status.socket}${status.last_error ? ` \u2014 ${status.last_error}` : ""}` };
|
|
17451
18304
|
}
|
|
18305
|
+
function gaveUpLine(gaveUp) {
|
|
18306
|
+
return gaveUp.reason === "key_refused" ? `this home gave the agent up: the server refuses its key (${gaveUp.detail}); signing in again here (\`${invocation()} login\` or \`recover\`) clears this at once \u2014 or log out here if another home serves the agent; it looks again at ${gaveUp.retry_at}` : `this home gave the agent up to another listener that was waiting: ${gaveUp.detail} (since ${gaveUp.since}); a runtime check that passes clears this (next at ${gaveUp.retry_at}, every 60 s), and it takes the agent back whenever no other listener holds it`;
|
|
18307
|
+
}
|
|
18308
|
+
function leaseCheck() {
|
|
18309
|
+
const errors = readIntegrationStatus(identityHome())?.lease_errors ?? null;
|
|
18310
|
+
if (errors === null || errors.count === 0) return null;
|
|
18311
|
+
return {
|
|
18312
|
+
name: "locks",
|
|
18313
|
+
verdict: "WARN",
|
|
18314
|
+
detail: `${errors.count} lock renewal(s) failed${errors.last ? ` (last: ${errors.last})` : ""}; a lock that cannot be renewed for 45 s is given up \u2014 check that ${identityHome()} and ${agentLockDir()} are there and writable`
|
|
18315
|
+
};
|
|
18316
|
+
}
|
|
17452
18317
|
var commands = createIdentityCommands(profile);
|
|
17453
18318
|
function runNotNow() {
|
|
17454
18319
|
const home = identityHome();
|
|
@@ -17456,7 +18321,7 @@ function runNotNow() {
|
|
|
17456
18321
|
try {
|
|
17457
18322
|
writeAnchor(anchorFile(), renderDeclinedBlock({ invoke: invocation(), label: LABEL }));
|
|
17458
18323
|
} catch (err) {
|
|
17459
|
-
console.error(`Recorded, but could not update ${
|
|
18324
|
+
console.error(`Recorded, but could not update ${path11.basename(anchorFile())}: ${String(err)}`);
|
|
17460
18325
|
return 1;
|
|
17461
18326
|
}
|
|
17462
18327
|
console.log([`Noted \u2014 ${LABEL} will not ask about AgentChat again.`, `Changed your mind? ${invocation()} register --email <email> --handle <handle>`].join("\n"));
|
|
@@ -17493,12 +18358,18 @@ two of you can DM each other \u2014 and it has its own front door:
|
|
|
17493
18358
|
Claude Code: npx -y @agentchatme/claude-code
|
|
17494
18359
|
|
|
17495
18360
|
Switches (captured into the service from the shell that runs install, \`daemon install\` or \`doctor --fix\`):
|
|
17496
|
-
AGENTCHAT_RUN_PROFILE=answer|work|full what a headless run may do (default
|
|
18361
|
+
AGENTCHAT_RUN_PROFILE=answer|work|full what a headless run may do. answer (default): the AgentChat tools only \u2014 no
|
|
18362
|
+
shell, no web, no file tool, no other MCP server (each run lists them with
|
|
18363
|
+
\`codex mcp list\`; a server with a "." in its name stops answer runs);
|
|
18364
|
+
$CODEX_HOME/AGENTS.md is still in its context, so keep private notes out of it.
|
|
18365
|
+
work and full: ${PEER_RUN_WARNING}
|
|
17497
18366
|
${INTEGRATION_ENV}=off hold no socket, start no run; tools + manual stay
|
|
17498
18367
|
(${INTEGRATION_ENV_LEGACY}=off, the previous name, is still read; its removal is scheduled for ${INTEGRATION_ENV_LEGACY_REMOVAL};
|
|
17499
18368
|
${INTEGRATION_ENV} wins when both are set)
|
|
17500
18369
|
AGENTCHAT_RUN_BUDGET_MS kill a run past this (default 600000)
|
|
17501
|
-
AGENTCHAT_RUN_CWD the run's working root (default $CODEX_HOME/agentchat/daemon-workdir)
|
|
18370
|
+
AGENTCHAT_RUN_CWD the run's working root (default $CODEX_HOME/agentchat/daemon-workdir); one that
|
|
18371
|
+
is your home folder or contains it gives answer runs
|
|
18372
|
+
$CODEX_HOME/agentchat-answer-workdir
|
|
17502
18373
|
AGENTCHAT_API_BASE override the server
|
|
17503
18374
|
AGENTCHAT_API_KEY override the stored key (never captured into the service)
|
|
17504
18375
|
`;
|
|
@@ -17580,7 +18451,7 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
17580
18451
|
}
|
|
17581
18452
|
}
|
|
17582
18453
|
async function runInstall() {
|
|
17583
|
-
const runtime = inspectCodexRuntime(codexHome());
|
|
18454
|
+
const runtime = await inspectCodexRuntime(codexHome());
|
|
17584
18455
|
if (!runtime.ok) {
|
|
17585
18456
|
console.log(`${LABEL}: not installed \u2014 ${runtime.detail}`);
|
|
17586
18457
|
return 1;
|
|
@@ -17606,7 +18477,7 @@ async function runInstall() {
|
|
|
17606
18477
|
`AgentChat integration for ${LABEL} ${VERSION3}`,
|
|
17607
18478
|
"",
|
|
17608
18479
|
...formatPlacement(steps),
|
|
17609
|
-
...failed ? [` \u2717 service: not registered until the failed step above is resolved \u2014 re-run \`${invocation()}\``] : service === "enabled" ? [` \u2713 service: integration daemon registered (${serviceLabel2()}); profile ${profile2}${integrationDisabled() ? `; ${integrationDisabledBy()}=off \u2014 holding no socket` : ""}`] : service === "off-by-choice" ? [" \u25CB service: integration daemon off (your choice; `daemon install` turns it on)"] : [` \u2717 service: could not be registered (${serviceDetail}) \u2014 \`${invocation()} daemon install\` retries it`],
|
|
18480
|
+
...failed ? [` \u2717 service: not registered until the failed step above is resolved \u2014 re-run \`${invocation()}\``] : service === "enabled" ? [` \u2713 service: integration daemon registered (${serviceLabel2()}); profile ${profile2}${profileNote(profile2)}${integrationDisabled() ? `; ${integrationDisabledBy()}=off \u2014 holding no socket` : ""}`] : service === "off-by-choice" ? [" \u25CB service: integration daemon off (your choice; `daemon install` turns it on)"] : [` \u2717 service: could not be registered (${serviceDetail}) \u2014 \`${invocation()} daemon install\` retries it`],
|
|
17610
18481
|
"",
|
|
17611
18482
|
...identity ? [`Connected as @${identity.handle}. Open a new Codex session for the tools to load.`] : ["Next:", " 1. Open a new Codex session", ' 2. Ask Codex: "Set up your AgentChat account."']
|
|
17612
18483
|
].join("\n")
|
|
@@ -17629,7 +18500,7 @@ function runUninstall() {
|
|
|
17629
18500
|
for (const step of steps) if (step.status === "failed") warnings.push(step.detail);
|
|
17630
18501
|
if (serviceRemoved) {
|
|
17631
18502
|
try {
|
|
17632
|
-
|
|
18503
|
+
fs9.rmSync(stableDaemonPath(), { force: true });
|
|
17633
18504
|
} catch {
|
|
17634
18505
|
}
|
|
17635
18506
|
}
|
|
@@ -17657,7 +18528,7 @@ function runDaemonCmd(sub) {
|
|
|
17657
18528
|
return 1;
|
|
17658
18529
|
}
|
|
17659
18530
|
console.log(
|
|
17660
|
-
`Integration daemon is ON for ${LABEL} (${serviceLabel2()}): a peer's message starts one headless Codex run with profile ${resolveRunProfile()} while this machine is up.${integrationDisabled() ? ` ${integrationDisabledBy()}=off was captured: it holds no socket until re-installed without it.` : ""}`
|
|
18531
|
+
`Integration daemon is ON for ${LABEL} (${serviceLabel2()}): a peer's message starts one headless Codex run with profile ${resolveRunProfile()} while this machine is up.${runProfileWarning(resolveRunProfile()) !== null ? ` With ${resolveRunProfile()}, ${runProfileWarning(resolveRunProfile())}.` : ""}${integrationDisabled() ? ` ${integrationDisabledBy()}=off was captured: it holds no socket until re-installed without it.` : ""}`
|
|
17661
18532
|
);
|
|
17662
18533
|
return 0;
|
|
17663
18534
|
}
|