agentschat-mcp 0.34.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1264 @@
1
+ #!/usr/bin/env node
2
+ // codex/manager.ts
3
+ import { spawn } from "node:child_process";
4
+ import { mkdirSync as mkdirSync2, openSync, closeSync, readFileSync as readFileSync3, writeFileSync, unlinkSync, existsSync as existsSync2, renameSync } from "node:fs";
5
+ import { join as join3, resolve as resolve3 } from "node:path";
6
+ import { homedir as homedir3 } from "node:os";
7
+ import { createHash as createHash2 } from "node:crypto";
8
+ import { parseArgs } from "node:util";
9
+
10
+ // codex/bots-config.ts
11
+ import { readFileSync as readFileSync2, realpathSync as realpathSync2, mkdirSync } from "node:fs";
12
+ import { homedir as homedir2 } from "node:os";
13
+ import { dirname, isAbsolute as isAbsolute2, join as join2, resolve as resolve2 } from "node:path";
14
+
15
+ // codex/config.ts
16
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
17
+ import { homedir } from "node:os";
18
+ import { isAbsolute, join, resolve } from "node:path";
19
+ import { createHash } from "node:crypto";
20
+
21
+ // src/identity.ts
22
+ function validateIdentityProfile(profile, file, allowDevToken = false) {
23
+ const nonempty = (value) => typeof value === "string" && value.trim().length > 0;
24
+ if (!profile || typeof profile !== "object" || Array.isArray(profile) || !nonempty(profile.agent_id) || !nonempty(profile.token) || !allowDevToken && profile.token === "dev-token" || profile.capabilities !== undefined && (!Array.isArray(profile.capabilities) || !profile.capabilities.every(nonempty))) {
25
+ throw new Error(`Invalid identity profile at ${file}. Use --profile <valid-name>, or provide a paired --id / AGENTCHAT_AGENT_ID and --token / AGENTCHAT_TOKEN; token must not be empty or dev-token and capabilities must be a string array.`);
26
+ }
27
+ }
28
+
29
+ // node_modules/smol-toml/dist/date.js
30
+ /*!
31
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
32
+ * SPDX-License-Identifier: BSD-3-Clause
33
+ *
34
+ * Redistribution and use in source and binary forms, with or without
35
+ * modification, are permitted provided that the following conditions are met:
36
+ *
37
+ * 1. Redistributions of source code must retain the above copyright notice, this
38
+ * list of conditions and the following disclaimer.
39
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
40
+ * this list of conditions and the following disclaimer in the
41
+ * documentation and/or other materials provided with the distribution.
42
+ * 3. Neither the name of the copyright holder nor the names of its contributors
43
+ * may be used to endorse or promote products derived from this software without
44
+ * specific prior written permission.
45
+ *
46
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
47
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
48
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
49
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
50
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
52
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
53
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
54
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
55
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
56
+ */
57
+ var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;
58
+
59
+ class TomlDate extends Date {
60
+ #hasDate = false;
61
+ #hasTime = false;
62
+ #offset = null;
63
+ constructor(date) {
64
+ let hasDate = true;
65
+ let hasTime = true;
66
+ let offset = "Z";
67
+ if (typeof date === "string") {
68
+ let match = date.match(DATE_TIME_RE);
69
+ if (match) {
70
+ if (!match[1]) {
71
+ hasDate = false;
72
+ date = `0000-01-01T${date}`;
73
+ }
74
+ hasTime = !!match[2];
75
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
76
+ if (match[2] && +match[2] > 23) {
77
+ date = "";
78
+ } else {
79
+ offset = match[3] || null;
80
+ date = date.toUpperCase();
81
+ if (!offset && hasTime)
82
+ date += "Z";
83
+ }
84
+ } else {
85
+ date = "";
86
+ }
87
+ }
88
+ super(date);
89
+ if (!isNaN(this.getTime())) {
90
+ this.#hasDate = hasDate;
91
+ this.#hasTime = hasTime;
92
+ this.#offset = offset;
93
+ }
94
+ }
95
+ isDateTime() {
96
+ return this.#hasDate && this.#hasTime;
97
+ }
98
+ isLocal() {
99
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
100
+ }
101
+ isDate() {
102
+ return this.#hasDate && !this.#hasTime;
103
+ }
104
+ isTime() {
105
+ return this.#hasTime && !this.#hasDate;
106
+ }
107
+ isValid() {
108
+ return this.#hasDate || this.#hasTime;
109
+ }
110
+ toISOString() {
111
+ let iso = super.toISOString();
112
+ if (this.isDate())
113
+ return iso.slice(0, 10);
114
+ if (this.isTime())
115
+ return iso.slice(11, 23);
116
+ if (this.#offset === null)
117
+ return iso.slice(0, -1);
118
+ if (this.#offset === "Z")
119
+ return iso;
120
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
121
+ offset = this.#offset[0] === "-" ? offset : -offset;
122
+ let offsetDate = new Date(this.getTime() - offset * 60000);
123
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
124
+ }
125
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
126
+ let date = new TomlDate(jsDate);
127
+ date.#offset = offset;
128
+ return date;
129
+ }
130
+ static wrapAsLocalDateTime(jsDate) {
131
+ let date = new TomlDate(jsDate);
132
+ date.#offset = null;
133
+ return date;
134
+ }
135
+ static wrapAsLocalDate(jsDate) {
136
+ let date = new TomlDate(jsDate);
137
+ date.#hasTime = false;
138
+ date.#offset = null;
139
+ return date;
140
+ }
141
+ static wrapAsLocalTime(jsDate) {
142
+ let date = new TomlDate(jsDate);
143
+ date.#hasDate = false;
144
+ date.#offset = null;
145
+ return date;
146
+ }
147
+ }
148
+
149
+ // node_modules/smol-toml/dist/error.js
150
+ /*!
151
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
152
+ * SPDX-License-Identifier: BSD-3-Clause
153
+ *
154
+ * Redistribution and use in source and binary forms, with or without
155
+ * modification, are permitted provided that the following conditions are met:
156
+ *
157
+ * 1. Redistributions of source code must retain the above copyright notice, this
158
+ * list of conditions and the following disclaimer.
159
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
160
+ * this list of conditions and the following disclaimer in the
161
+ * documentation and/or other materials provided with the distribution.
162
+ * 3. Neither the name of the copyright holder nor the names of its contributors
163
+ * may be used to endorse or promote products derived from this software without
164
+ * specific prior written permission.
165
+ *
166
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
167
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
168
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
169
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
170
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
171
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
172
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
173
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
174
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
175
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
176
+ */
177
+ function getLineColFromPtr(string, ptr) {
178
+ let lines = string.slice(0, ptr).split(/\r\n|\n|\r/g);
179
+ return [lines.length, lines.pop().length + 1];
180
+ }
181
+ function makeCodeBlock(string, line, column) {
182
+ let lines = string.split(/\r\n|\n|\r/g);
183
+ let codeblock = "";
184
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
185
+ for (let i = line - 1;i <= line + 1; i++) {
186
+ let l = lines[i - 1];
187
+ if (!l)
188
+ continue;
189
+ codeblock += i.toString().padEnd(numberLen, " ");
190
+ codeblock += ": ";
191
+ codeblock += l;
192
+ codeblock += `
193
+ `;
194
+ if (i === line) {
195
+ codeblock += " ".repeat(numberLen + column + 2);
196
+ codeblock += `^
197
+ `;
198
+ }
199
+ }
200
+ return codeblock;
201
+ }
202
+
203
+ class TomlError extends Error {
204
+ line;
205
+ column;
206
+ codeblock;
207
+ constructor(message, options) {
208
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
209
+ const codeblock = makeCodeBlock(options.toml, line, column);
210
+ super(`Invalid TOML document: ${message}
211
+
212
+ ${codeblock}`, options);
213
+ this.line = line;
214
+ this.column = column;
215
+ this.codeblock = codeblock;
216
+ }
217
+ }
218
+
219
+ // node_modules/smol-toml/dist/util.js
220
+ /*!
221
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
222
+ * SPDX-License-Identifier: BSD-3-Clause
223
+ *
224
+ * Redistribution and use in source and binary forms, with or without
225
+ * modification, are permitted provided that the following conditions are met:
226
+ *
227
+ * 1. Redistributions of source code must retain the above copyright notice, this
228
+ * list of conditions and the following disclaimer.
229
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
230
+ * this list of conditions and the following disclaimer in the
231
+ * documentation and/or other materials provided with the distribution.
232
+ * 3. Neither the name of the copyright holder nor the names of its contributors
233
+ * may be used to endorse or promote products derived from this software without
234
+ * specific prior written permission.
235
+ *
236
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
237
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
238
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
239
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
240
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
241
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
242
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
243
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
244
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
245
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
246
+ */
247
+ function indexOfNewline(str, start = 0) {
248
+ let idx = str.indexOf(`
249
+ `, start);
250
+ if (str.charCodeAt(idx - 1) === 13)
251
+ idx--;
252
+ return idx;
253
+ }
254
+ function skipComment(ctx) {
255
+ for (;ctx.p < ctx.s.length; ctx.p++) {
256
+ let c = ctx.s.charCodeAt(ctx.p);
257
+ if (c === 10)
258
+ break;
259
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
260
+ ctx.p++;
261
+ break;
262
+ }
263
+ if (c < 32 && c !== 9 || c === 127) {
264
+ throw new TomlError("control characters are not allowed in comments", {
265
+ toml: ctx.s,
266
+ ptr: ctx.p
267
+ });
268
+ }
269
+ }
270
+ }
271
+ function skipVoid(ctx, banNewLines, banComments) {
272
+ let c;
273
+ while (true) {
274
+ while ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10))
275
+ ctx.p++;
276
+ if (banComments || c !== 35)
277
+ break;
278
+ skipComment(ctx);
279
+ }
280
+ }
281
+ function skipUntil(ctx, sep, end) {
282
+ let ptr = ctx.p;
283
+ if (!end) {
284
+ ptr = indexOfNewline(ctx.s, ptr);
285
+ ctx.p = ptr < 0 ? ctx.s.length : ptr;
286
+ return;
287
+ }
288
+ for (;ctx.p < ctx.s.length; ctx.p++) {
289
+ let c = ctx.s.charCodeAt(ctx.p);
290
+ if (c === 35) {
291
+ skipComment(ctx);
292
+ } else if (c === end || c === sep) {
293
+ return;
294
+ }
295
+ }
296
+ throw new TomlError("cannot find end of structure", {
297
+ toml: ctx.s,
298
+ ptr
299
+ });
300
+ }
301
+
302
+ // node_modules/smol-toml/dist/primitive.js
303
+ /*!
304
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
305
+ * SPDX-License-Identifier: BSD-3-Clause
306
+ *
307
+ * Redistribution and use in source and binary forms, with or without
308
+ * modification, are permitted provided that the following conditions are met:
309
+ *
310
+ * 1. Redistributions of source code must retain the above copyright notice, this
311
+ * list of conditions and the following disclaimer.
312
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
313
+ * this list of conditions and the following disclaimer in the
314
+ * documentation and/or other materials provided with the distribution.
315
+ * 3. Neither the name of the copyright holder nor the names of its contributors
316
+ * may be used to endorse or promote products derived from this software without
317
+ * specific prior written permission.
318
+ *
319
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
320
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
321
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
322
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
323
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
324
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
325
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
326
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
327
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
328
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
329
+ */
330
+ var INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/;
331
+ var FLOAT_REGEX = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/;
332
+ var LEADING_ZERO = /^[+-]?0[0-9_]/;
333
+ function parseString(ctx) {
334
+ let start = ctx.p;
335
+ let c = ctx.s.charCodeAt(ctx.p++);
336
+ let first = c;
337
+ let isLiteral = c === 39;
338
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
339
+ if (isMultiline) {
340
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
341
+ ctx.p++;
342
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
343
+ ctx.p += 2;
344
+ }
345
+ let parsed = "";
346
+ let sliceStart = ctx.p;
347
+ let state = 0;
348
+ for (;ctx.p < ctx.s.length; ctx.p++) {
349
+ c = ctx.s.charCodeAt(ctx.p);
350
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
351
+ state = state && 3;
352
+ } else if (c < 32 && c !== 9 || c === 127) {
353
+ throw new TomlError("control characters are not allowed in strings", {
354
+ toml: ctx.s,
355
+ ptr: ctx.p
356
+ });
357
+ } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
358
+ if (isMultiline) {
359
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
360
+ ctx.p++;
361
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
362
+ ctx.p++;
363
+ }
364
+ if (!state)
365
+ parsed += ctx.s.slice(sliceStart, ctx.p);
366
+ ctx.p += isMultiline ? 3 : 1;
367
+ return parsed;
368
+ } else if (!state) {
369
+ if (!isLiteral && c === 92) {
370
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
371
+ state = 1;
372
+ }
373
+ } else if (state === 1) {
374
+ if (c === 120 || c === 117 || c === 85) {
375
+ let value = 0;
376
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
377
+ for (let j = 0;j < len; j++, ctx.p++) {
378
+ let hex = ctx.s.charCodeAt(ctx.p + 1);
379
+ let digit = hex >= 48 && hex <= 57 ? hex - 48 : hex >= 65 && hex <= 70 ? hex - 65 + 10 : hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1;
380
+ if (digit < 0)
381
+ throw new TomlError("invalid non-hex character in unicode escape", { toml: ctx.s, ptr: ctx.p + 1 });
382
+ value = value << 4 | digit;
383
+ }
384
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
385
+ throw new TomlError("invalid unicode escape", { toml: ctx.s, ptr: ctx.p });
386
+ }
387
+ parsed += String.fromCodePoint(value);
388
+ sliceStart = ctx.p + 1;
389
+ state = 0;
390
+ } else if (c === 32 || c === 9) {
391
+ state = 2;
392
+ } else {
393
+ if (c === 98)
394
+ parsed += "\b";
395
+ else if (c === 116)
396
+ parsed += "\t";
397
+ else if (c === 110)
398
+ parsed += `
399
+ `;
400
+ else if (c === 102)
401
+ parsed += "\f";
402
+ else if (c === 114)
403
+ parsed += "\r";
404
+ else if (c === 101)
405
+ parsed += "\x1B";
406
+ else if (c === 34)
407
+ parsed += '"';
408
+ else if (c === 92)
409
+ parsed += "\\";
410
+ else
411
+ throw new TomlError("unrecognized escape sequence", { toml: ctx.s, ptr: ctx.p });
412
+ sliceStart = ctx.p + 1;
413
+ state = 0;
414
+ }
415
+ } else if (c !== 32 && c !== 9) {
416
+ if (state === 2) {
417
+ throw new TomlError("invalid escape: only line-ending whitespace may be escaped", {
418
+ toml: ctx.s,
419
+ ptr: sliceStart
420
+ });
421
+ }
422
+ state = !isLiteral && c === 92 ? 1 : 0;
423
+ sliceStart = ctx.p;
424
+ }
425
+ }
426
+ throw new TomlError("unfinished string", { toml: ctx.s, ptr: start });
427
+ }
428
+ function sliceAndTrimEndOf(ctx, start, end) {
429
+ let value = ctx.s.slice(start, end);
430
+ let commentIdx = value.indexOf("#");
431
+ if (commentIdx > 0) {
432
+ skipComment({ s: value, p: commentIdx, d: 0 });
433
+ value = value.slice(0, commentIdx);
434
+ }
435
+ return value.trimEnd();
436
+ }
437
+ function parseValue(ctx, integersAsBigInt, end) {
438
+ let ptr = ctx.p;
439
+ let err = { toml: ctx.s, ptr };
440
+ skipUntil(ctx, 44, end);
441
+ let value = sliceAndTrimEndOf(ctx, ptr, ctx.p);
442
+ if (!value)
443
+ throw new TomlError("incomplete declaration: value expected", err);
444
+ if (value === "-inf")
445
+ return -Infinity;
446
+ if (value === "inf" || value === "+inf")
447
+ return Infinity;
448
+ if (value === "nan" || value === "+nan" || value === "-nan")
449
+ return NaN;
450
+ if (value === "-0")
451
+ return integersAsBigInt ? 0n : 0;
452
+ let isInt = INT_REGEX.test(value);
453
+ if (isInt || FLOAT_REGEX.test(value)) {
454
+ if (LEADING_ZERO.test(value)) {
455
+ throw new TomlError("leading zeroes are not allowed", err);
456
+ }
457
+ value = value.replace(/_/g, "");
458
+ let numeric = +value;
459
+ if (isNaN(numeric)) {
460
+ throw new TomlError("invalid number", err);
461
+ }
462
+ if (isInt) {
463
+ if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {
464
+ throw new TomlError("integer value cannot be represented losslessly", err);
465
+ }
466
+ if (isInt || integersAsBigInt === true)
467
+ numeric = BigInt(value);
468
+ }
469
+ return numeric;
470
+ }
471
+ const date = new TomlDate(value);
472
+ if (!date.isValid())
473
+ throw new TomlError("invalid value", err);
474
+ return date;
475
+ }
476
+
477
+ // node_modules/smol-toml/dist/extract.js
478
+ /*!
479
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
480
+ * SPDX-License-Identifier: BSD-3-Clause
481
+ *
482
+ * Redistribution and use in source and binary forms, with or without
483
+ * modification, are permitted provided that the following conditions are met:
484
+ *
485
+ * 1. Redistributions of source code must retain the above copyright notice, this
486
+ * list of conditions and the following disclaimer.
487
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
488
+ * this list of conditions and the following disclaimer in the
489
+ * documentation and/or other materials provided with the distribution.
490
+ * 3. Neither the name of the copyright holder nor the names of its contributors
491
+ * may be used to endorse or promote products derived from this software without
492
+ * specific prior written permission.
493
+ *
494
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
495
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
496
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
497
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
498
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
499
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
500
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
501
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
502
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
503
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
504
+ */
505
+ function extractValue(ctx, end, integersAsBigInt) {
506
+ let ptr = ctx.p;
507
+ let c = ctx.s.charCodeAt(ptr);
508
+ if (c === 91 || c === 123) {
509
+ if (!ctx.d--) {
510
+ throw new TomlError("document contains excessively nested structures. aborting.", {
511
+ toml: ctx.s,
512
+ ptr
513
+ });
514
+ }
515
+ let value = c === 91 ? parseArray(ctx, integersAsBigInt) : parseInlineTable(ctx, integersAsBigInt);
516
+ ctx.d++;
517
+ return value;
518
+ }
519
+ if (c === 34 || c === 39) {
520
+ return parseString(ctx);
521
+ }
522
+ if (c === 116) {
523
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
524
+ throw new TomlError("invalid value", { toml: ctx.s, ptr });
525
+ ctx.p++;
526
+ return true;
527
+ }
528
+ if (c === 102) {
529
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101)
530
+ throw new TomlError("invalid value", { toml: ctx.s, ptr });
531
+ ctx.p++;
532
+ return false;
533
+ }
534
+ return parseValue(ctx, integersAsBigInt, end);
535
+ }
536
+
537
+ // node_modules/smol-toml/dist/struct.js
538
+ /*!
539
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
540
+ * SPDX-License-Identifier: BSD-3-Clause
541
+ *
542
+ * Redistribution and use in source and binary forms, with or without
543
+ * modification, are permitted provided that the following conditions are met:
544
+ *
545
+ * 1. Redistributions of source code must retain the above copyright notice, this
546
+ * list of conditions and the following disclaimer.
547
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
548
+ * this list of conditions and the following disclaimer in the
549
+ * documentation and/or other materials provided with the distribution.
550
+ * 3. Neither the name of the copyright holder nor the names of its contributors
551
+ * may be used to endorse or promote products derived from this software without
552
+ * specific prior written permission.
553
+ *
554
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
555
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
556
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
557
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
558
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
559
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
560
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
561
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
562
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
563
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
564
+ */
565
+ var KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \t]*$/;
566
+ function parseKey(ctx, end = "=") {
567
+ let start = ctx.p;
568
+ let dot = start - 1;
569
+ let parsed = [];
570
+ let endPtr = ctx.s.indexOf(end, start);
571
+ if (endPtr < 0) {
572
+ throw new TomlError("incomplete key-value: cannot find end of key", {
573
+ toml: ctx.s,
574
+ ptr: start
575
+ });
576
+ }
577
+ do {
578
+ let c = ctx.s.charCodeAt(ctx.p = ++dot);
579
+ if (c !== 32 && c !== 9) {
580
+ if (c === 34 || c === 39) {
581
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2)) {
582
+ throw new TomlError("multiline strings are not allowed in keys", {
583
+ toml: ctx.s,
584
+ ptr: ctx.p
585
+ });
586
+ }
587
+ let part = parseString(ctx);
588
+ dot = ctx.s.indexOf(".", ctx.p);
589
+ let strEnd = ctx.s.slice(ctx.p, dot < 0 || dot > endPtr ? endPtr : dot);
590
+ let newLine = indexOfNewline(strEnd);
591
+ if (newLine > -1) {
592
+ throw new TomlError("newlines are not allowed in keys", {
593
+ toml: ctx.s,
594
+ ptr: newLine
595
+ });
596
+ }
597
+ if (strEnd.trimStart()) {
598
+ throw new TomlError("found extra tokens after the string part", {
599
+ toml: ctx.s,
600
+ ptr: ctx.p
601
+ });
602
+ }
603
+ if (endPtr < ctx.p) {
604
+ endPtr = ctx.s.indexOf(end, ctx.p);
605
+ if (endPtr < 0) {
606
+ throw new TomlError("incomplete key-value: cannot find end of key", {
607
+ toml: ctx.s,
608
+ ptr: start
609
+ });
610
+ }
611
+ }
612
+ parsed.push(part);
613
+ } else {
614
+ dot = ctx.s.indexOf(".", ctx.p);
615
+ let part = ctx.s.slice(ctx.p, dot < 0 || dot > endPtr ? endPtr : dot);
616
+ if (!KEY_PART_RE.test(part)) {
617
+ throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys", {
618
+ toml: ctx.s,
619
+ ptr: ctx.p
620
+ });
621
+ }
622
+ parsed.push(part.trimEnd());
623
+ }
624
+ }
625
+ } while (dot + 1 && dot < endPtr);
626
+ ctx.p = endPtr + 1;
627
+ skipVoid(ctx, true, true);
628
+ return parsed;
629
+ }
630
+ function parseInlineTable(ctx, integersAsBigInt) {
631
+ let res = {};
632
+ let seen = new Set;
633
+ let c;
634
+ ctx.p++;
635
+ while (ctx.p < ctx.s.length) {
636
+ skipVoid(ctx);
637
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
638
+ ctx.p++;
639
+ return res;
640
+ }
641
+ let k;
642
+ let t = res;
643
+ let hasOwn = false;
644
+ let p = ctx.p;
645
+ let key = parseKey(ctx);
646
+ for (let i = 0;i < key.length; i++) {
647
+ if (i)
648
+ t = hasOwn ? t[k] : t[k] = {};
649
+ k = key[i];
650
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
651
+ throw new TomlError("trying to redefine an already defined value", {
652
+ toml: ctx.s,
653
+ ptr: p
654
+ });
655
+ }
656
+ if (!hasOwn && k === "__proto__") {
657
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
658
+ }
659
+ }
660
+ if (hasOwn) {
661
+ throw new TomlError("trying to redefine an already defined value", {
662
+ toml: ctx.s,
663
+ ptr: ctx.p
664
+ });
665
+ }
666
+ let value = extractValue(ctx, 125, integersAsBigInt);
667
+ seen.add(t[k] = value);
668
+ skipVoid(ctx);
669
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
670
+ return res;
671
+ }
672
+ if (c !== 44) {
673
+ throw new TomlError("expected comma or end of structure", { toml: ctx.s, ptr: ctx.p - 1 });
674
+ }
675
+ }
676
+ throw new TomlError("unfinished table encountered", {
677
+ toml: ctx.s,
678
+ ptr: ctx.p
679
+ });
680
+ }
681
+ function parseArray(ctx, integersAsBigInt) {
682
+ let res = [];
683
+ let c;
684
+ ctx.p++;
685
+ while (ctx.p < ctx.s.length) {
686
+ skipVoid(ctx);
687
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
688
+ ctx.p++;
689
+ return res;
690
+ }
691
+ res.push(extractValue(ctx, 93, integersAsBigInt));
692
+ skipVoid(ctx);
693
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
694
+ return res;
695
+ }
696
+ if (c !== 44) {
697
+ throw new TomlError("expected comma or end of structure", { toml: ctx.s, ptr: ctx.p - 1 });
698
+ }
699
+ }
700
+ throw new TomlError("unfinished array encountered", {
701
+ toml: ctx.s,
702
+ ptr: ctx.p
703
+ });
704
+ }
705
+
706
+ // node_modules/smol-toml/dist/parse.js
707
+ /*!
708
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
709
+ * SPDX-License-Identifier: BSD-3-Clause
710
+ *
711
+ * Redistribution and use in source and binary forms, with or without
712
+ * modification, are permitted provided that the following conditions are met:
713
+ *
714
+ * 1. Redistributions of source code must retain the above copyright notice, this
715
+ * list of conditions and the following disclaimer.
716
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
717
+ * this list of conditions and the following disclaimer in the
718
+ * documentation and/or other materials provided with the distribution.
719
+ * 3. Neither the name of the copyright holder nor the names of its contributors
720
+ * may be used to endorse or promote products derived from this software without
721
+ * specific prior written permission.
722
+ *
723
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
724
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
725
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
726
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
727
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
728
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
729
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
730
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
731
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
732
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
733
+ */
734
+ function peekTable(key, table, meta, type) {
735
+ let t = table;
736
+ let m = meta;
737
+ let k;
738
+ let hasOwn = false;
739
+ let state;
740
+ for (let i = 0;i < key.length; i++) {
741
+ if (i) {
742
+ t = hasOwn ? t[k] : t[k] = {};
743
+ m = (state = m[k]).c;
744
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
745
+ return null;
746
+ }
747
+ if (state.t === 2) {
748
+ let l = t.length - 1;
749
+ t = t[l];
750
+ m = m[l].c;
751
+ }
752
+ }
753
+ k = key[i];
754
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
755
+ return null;
756
+ }
757
+ if (!hasOwn) {
758
+ if (k === "__proto__") {
759
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
760
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
761
+ }
762
+ m[k] = {
763
+ t: i < key.length - 1 && type === 2 ? 3 : type,
764
+ d: false,
765
+ i: 0,
766
+ c: {}
767
+ };
768
+ }
769
+ }
770
+ state = m[k];
771
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
772
+ return null;
773
+ }
774
+ if (type === 2) {
775
+ if (!state.d) {
776
+ state.d = true;
777
+ t[k] = [];
778
+ }
779
+ t[k].push(t = {});
780
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: {} };
781
+ }
782
+ if (state.d) {
783
+ return null;
784
+ }
785
+ state.d = true;
786
+ if (type === 1) {
787
+ t = hasOwn ? t[k] : t[k] = {};
788
+ } else if (type === 0 && hasOwn) {
789
+ return null;
790
+ }
791
+ return [k, t, state.c];
792
+ }
793
+ function parse(toml, { maxDepth = 1000, integersAsBigInt } = {}) {
794
+ let ctx = { s: toml, p: 0, d: maxDepth };
795
+ let res = {};
796
+ let meta = {};
797
+ let tmp;
798
+ let tbl = res;
799
+ let m = meta;
800
+ skipVoid(ctx);
801
+ while (ctx.p < toml.length) {
802
+ if (toml.charCodeAt(ctx.p) === 91) {
803
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
804
+ tmp = ctx.p += +isTableArray;
805
+ let k = parseKey(ctx, "]");
806
+ if (isTableArray) {
807
+ if (toml.charCodeAt(ctx.p - 1) !== 93) {
808
+ throw new TomlError("expected end of table declaration", {
809
+ toml,
810
+ ptr: ctx.p - 1
811
+ });
812
+ }
813
+ ctx.p++;
814
+ }
815
+ let p = peekTable(k, res, meta, isTableArray ? 2 : 1);
816
+ if (!p) {
817
+ throw new TomlError("trying to redefine an already defined table or value", {
818
+ toml,
819
+ ptr: tmp
820
+ });
821
+ }
822
+ m = p[2];
823
+ tbl = p[1];
824
+ } else {
825
+ tmp = ctx.p;
826
+ let k = parseKey(ctx);
827
+ let p = peekTable(k, tbl, m, 0);
828
+ if (!p) {
829
+ throw new TomlError("trying to redefine an already defined table or value", {
830
+ toml,
831
+ ptr: tmp
832
+ });
833
+ }
834
+ p[1][p[0]] = extractValue(ctx, undefined, integersAsBigInt);
835
+ }
836
+ skipVoid(ctx, true);
837
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && tmp !== 13) {
838
+ throw new TomlError("each key-value declaration must be followed by an end-of-line", {
839
+ toml,
840
+ ptr: ctx.p
841
+ });
842
+ }
843
+ skipVoid(ctx);
844
+ }
845
+ return res;
846
+ }
847
+
848
+ // node_modules/smol-toml/dist/stringify.js
849
+ /*!
850
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
851
+ * SPDX-License-Identifier: BSD-3-Clause
852
+ *
853
+ * Redistribution and use in source and binary forms, with or without
854
+ * modification, are permitted provided that the following conditions are met:
855
+ *
856
+ * 1. Redistributions of source code must retain the above copyright notice, this
857
+ * list of conditions and the following disclaimer.
858
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
859
+ * this list of conditions and the following disclaimer in the
860
+ * documentation and/or other materials provided with the distribution.
861
+ * 3. Neither the name of the copyright holder nor the names of its contributors
862
+ * may be used to endorse or promote products derived from this software without
863
+ * specific prior written permission.
864
+ *
865
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
866
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
867
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
868
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
869
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
870
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
871
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
872
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
873
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
874
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
875
+ */
876
+
877
+ // node_modules/smol-toml/dist/index.js
878
+ /*!
879
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
880
+ * SPDX-License-Identifier: BSD-3-Clause
881
+ *
882
+ * Redistribution and use in source and binary forms, with or without
883
+ * modification, are permitted provided that the following conditions are met:
884
+ *
885
+ * 1. Redistributions of source code must retain the above copyright notice, this
886
+ * list of conditions and the following disclaimer.
887
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
888
+ * this list of conditions and the following disclaimer in the
889
+ * documentation and/or other materials provided with the distribution.
890
+ * 3. Neither the name of the copyright holder nor the names of its contributors
891
+ * may be used to endorse or promote products derived from this software without
892
+ * specific prior written permission.
893
+ *
894
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
895
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
896
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
897
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
898
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
899
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
900
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
901
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
902
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
903
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
904
+ */
905
+
906
+ // codex/config.ts
907
+ function permissionMode(value) {
908
+ if (value === undefined)
909
+ return "full-access";
910
+ if (value !== "full-access" && value !== "read-only")
911
+ throw new Error("permissions must be full-access or read-only");
912
+ return value;
913
+ }
914
+ function readJson(file) {
915
+ try {
916
+ return JSON.parse(readFileSync(file, "utf8"));
917
+ } catch {
918
+ throw new Error(`Cannot read valid JSON: ${file}`);
919
+ }
920
+ }
921
+ function strings(value, name) {
922
+ if (value === undefined)
923
+ return [];
924
+ if (!Array.isArray(value) || value.some((x) => typeof x !== "string" || !x.trim()))
925
+ throw new Error(`${name} must be an array of nonempty strings`);
926
+ return value;
927
+ }
928
+ function resolveConfig(opts, env = process.env, home = homedir()) {
929
+ const cwd = realpathSync(opts.cwd ?? process.cwd());
930
+ const configFile = join(cwd, ".agentschat/config.json");
931
+ const project = opts.settings ?? (existsSync(configFile) ? readJson(configFile) : {});
932
+ if (!project || typeof project !== "object" || Array.isArray(project))
933
+ throw new Error("Invalid project config");
934
+ const allowed = new Set(["profile", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions"]);
935
+ if (Object.keys(project).some((k) => !allowed.has(k)))
936
+ throw new Error("Unknown project config field (credentials belong in a private profile)");
937
+ for (const k of ["profile", "agent_id", "api_url", "ws_url"])
938
+ if (project[k] !== undefined && (typeof project[k] !== "string" || !project[k].trim()))
939
+ throw new Error(`Invalid project ${k}`);
940
+ const localProfile = join(cwd, ".agentschat/profile.json");
941
+ let codexProfile;
942
+ const codexFile = join(cwd, ".codex/config.toml");
943
+ if (opts.settings === undefined && existsSync(codexFile)) {
944
+ let doc;
945
+ try {
946
+ doc = parse(readFileSync(codexFile, "utf8"));
947
+ } catch {
948
+ throw new Error("Invalid project .codex/config.toml");
949
+ }
950
+ const mcp = doc.mcp_servers?.agentschat;
951
+ if (mcp && mcp.enabled !== false) {
952
+ const args = Array.isArray(mcp.args) ? mcp.args : [];
953
+ const index = args.indexOf("--profile");
954
+ codexProfile = mcp.env?.AGENTSCHAT_PROFILE ?? mcp.env?.AGENTCHAT_PROFILE ?? (index >= 0 ? args[index + 1] : undefined);
955
+ if ((index >= 0 || codexProfile !== undefined) && (typeof codexProfile !== "string" || !codexProfile.trim() || codexProfile.startsWith("--")))
956
+ throw new Error("Invalid project MCP profile selector");
957
+ }
958
+ }
959
+ const choices = [
960
+ [opts.profile, "flag"],
961
+ [project.profile, "project-config"],
962
+ [opts.settings === undefined && existsSync(localProfile) ? localProfile : undefined, "project-profile"],
963
+ [codexProfile, "project-codex"],
964
+ [env.AGENTSCHAT_PROFILE, "env"],
965
+ [env.AGENTCHAT_PROFILE, "legacy-env"],
966
+ ["profile", "default"]
967
+ ];
968
+ const [selector, source] = choices.find(([v]) => v !== undefined && v !== "");
969
+ let profileFile;
970
+ if (selector.startsWith("~/"))
971
+ profileFile = join(home, selector.slice(2));
972
+ else if (isAbsolute(selector) || selector.includes("/"))
973
+ profileFile = resolve(cwd, selector);
974
+ else {
975
+ const name = selector.endsWith(".json") ? selector : `${selector}.json`;
976
+ profileFile = join(home, ".agentschat/profiles", name);
977
+ if (!existsSync(profileFile))
978
+ profileFile = join(home, ".agentschat", name);
979
+ if (!existsSync(profileFile))
980
+ profileFile = join(home, ".agentchat", name);
981
+ }
982
+ if (!existsSync(profileFile))
983
+ throw new Error(`Selected profile missing: ${profileFile}; no identity fallback or registration`);
984
+ if (process.platform !== "win32" && statSync(profileFile).mode & 63)
985
+ throw new Error(`Profile must be private (chmod 600): ${profileFile}`);
986
+ const profile = readJson(profileFile);
987
+ validateIdentityProfile(profile, profileFile);
988
+ if (project.agent_id !== undefined && project.agent_id !== profile.agent_id)
989
+ throw new Error("Project agent_id does not match selected profile");
990
+ const apiUrl = project.api_url ?? "https://agents-chat.com";
991
+ const wsUrl = project.ws_url ?? `${apiUrl.replace(/^http/, "ws").replace(/\/$/, "")}/ws`;
992
+ for (const [raw, protocols] of [[apiUrl, ["https:", "http:"]], [wsUrl, ["wss:", "ws:"]]]) {
993
+ const url = new URL(raw);
994
+ if (!protocols.includes(url.protocol) || url.username || url.password || url.search || url.hash || !url.protocol.endsWith("s:") && !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))
995
+ throw new Error("Server URLs must use TLS (except loopback) and contain no credentials/query");
996
+ }
997
+ const canonicalApi = new URL(apiUrl).href.replace(/\/$/, "");
998
+ const key = createHash("sha256").update(JSON.stringify([cwd, canonicalApi, profile.agent_id])).digest("hex").slice(0, 24);
999
+ return {
1000
+ cwd,
1001
+ profileFile,
1002
+ source,
1003
+ permissions: permissionMode(project.permissions),
1004
+ agentId: profile.agent_id,
1005
+ token: profile.token,
1006
+ apiUrl: canonicalApi,
1007
+ wsUrl,
1008
+ channels: strings(project.channels, "channels"),
1009
+ senders: strings(project.senders, "senders"),
1010
+ codexBin: opts.codexBin ?? "codex",
1011
+ stateDir: join(home, ".agentschat/codex-bridge", key)
1012
+ };
1013
+ }
1014
+
1015
+ // codex/bots-config.ts
1016
+ function defaultRegistry(home = homedir2()) {
1017
+ return join2(home, ".agentschat/codex-bots.json");
1018
+ }
1019
+ function loadBots(file = defaultRegistry(), home = homedir2()) {
1020
+ let doc;
1021
+ try {
1022
+ doc = JSON.parse(readFileSync2(file, "utf8"));
1023
+ } catch {
1024
+ throw new Error("Cannot read bot registry JSON");
1025
+ }
1026
+ const object = (x) => x && typeof x === "object" && !Array.isArray(x);
1027
+ const fields = (x, keys) => {
1028
+ if (!object(x) || Object.keys(x).some((k) => !keys.includes(k)))
1029
+ throw new Error("Unknown or invalid bot registry field");
1030
+ };
1031
+ const text = (x) => typeof x === "string" && x.trim().length > 0;
1032
+ fields(doc, ["version", "default_workdir", "codex_bin", "bots"]);
1033
+ if (doc.version !== 1 || !Array.isArray(doc.bots))
1034
+ throw new Error("Registry requires version 1 and bots array");
1035
+ for (const k of ["default_workdir", "codex_bin"])
1036
+ if (doc[k] !== undefined && !text(doc[k]))
1037
+ throw new Error(`Invalid ${k}`);
1038
+ const path = (value) => value.startsWith("~/") ? join2(home, value.slice(2)) : isAbsolute2(value) ? value : resolve2(dirname(file), value);
1039
+ const defaultDir = doc.default_workdir ? path(doc.default_workdir) : join2(home, ".agentschat/workspace");
1040
+ const names = new Set, identities = new Set;
1041
+ const bots = [];
1042
+ for (const bot of doc.bots) {
1043
+ fields(bot, ["name", "profile", "workdir", "enabled", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions"]);
1044
+ if (!text(bot.name) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(bot.name) || names.has(bot.name))
1045
+ throw new Error("Bot names must be unique simple labels");
1046
+ names.add(bot.name);
1047
+ if (bot.enabled !== undefined && typeof bot.enabled !== "boolean")
1048
+ throw new Error("Invalid bot enabled flag");
1049
+ if (bot.enabled === false)
1050
+ continue;
1051
+ if (!text(bot.profile) || bot.workdir !== undefined && !text(bot.workdir))
1052
+ throw new Error(`Bot ${bot.name} needs a profile and valid optional workdir`);
1053
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(bot.profile))
1054
+ throw new Error(`Bot ${bot.name}: profile must be a central profile name`);
1055
+ if (!doc.default_workdir && !bot.workdir)
1056
+ mkdirSync(defaultDir, { recursive: true, mode: 448 });
1057
+ const cwd = realpathSync2(bot.workdir ? path(bot.workdir) : defaultDir);
1058
+ const settings = {};
1059
+ for (const k of ["agent_id", "channels", "senders", "api_url", "ws_url", "permissions"])
1060
+ if (bot[k] !== undefined)
1061
+ settings[k] = bot[k];
1062
+ const config = resolveConfig({ cwd, profile: bot.profile, settings, codexBin: doc.codex_bin }, {}, home);
1063
+ const identity = JSON.stringify([config.apiUrl, config.agentId]);
1064
+ if (identities.has(identity))
1065
+ throw new Error("Duplicate AgentsChat account in enabled bots (even with different workdirs)");
1066
+ identities.add(identity);
1067
+ bots.push({ ...config, source: "bot-registry", name: bot.name });
1068
+ }
1069
+ return bots;
1070
+ }
1071
+
1072
+ // codex/processes.ts
1073
+ import { execFile } from "node:child_process";
1074
+ import { promisify } from "node:util";
1075
+ import { basename } from "node:path";
1076
+ function parseProcesses(text) {
1077
+ return text.split(`
1078
+ `).flatMap((line) => {
1079
+ const m = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
1080
+ return m ? [{ pid: Number(m[1]), ppid: Number(m[2]), command: m[3].trim() }] : [];
1081
+ });
1082
+ }
1083
+ function externalCodexPresent(rows, managerPid) {
1084
+ const children = new Set([managerPid]);
1085
+ let changed = true;
1086
+ while (changed) {
1087
+ changed = false;
1088
+ for (const row of rows)
1089
+ if (children.has(row.ppid) && !children.has(row.pid)) {
1090
+ children.add(row.pid);
1091
+ changed = true;
1092
+ }
1093
+ }
1094
+ return rows.some((r) => !children.has(r.pid) && basename(r.command) === "codex");
1095
+ }
1096
+ async function codexPresent(managerPid = process.pid) {
1097
+ const { stdout } = await promisify(execFile)("/bin/ps", ["-axo", "pid=,ppid=,comm="], { timeout: 5000, maxBuffer: 4 * 1024 * 1024 });
1098
+ return externalCodexPresent(parseProcesses(stdout), managerPid);
1099
+ }
1100
+
1101
+ // codex/manager.ts
1102
+ var { values } = parseArgs({ options: { "codex-bots": { type: "boolean" }, config: { type: "string" }, "watch-codex": { type: "boolean" }, check: { type: "boolean" }, status: { type: "boolean" }, help: { type: "boolean" } } });
1103
+ var root = join3(homedir3(), ".agentschat/codex-bots");
1104
+ var registry = resolve3(values.config ?? defaultRegistry());
1105
+ var statusFile = join3(root, "status.json");
1106
+ var lock = join3(root, "manager.lock");
1107
+ var workers = new Map;
1108
+ var stopping = false;
1109
+ var missing = 0;
1110
+ var timer;
1111
+ function removeDeadLock(file) {
1112
+ if (!existsSync2(file))
1113
+ return;
1114
+ const pid = Number(readFileSync3(file, "utf8"));
1115
+ if (!Number.isInteger(pid) || pid <= 0)
1116
+ return;
1117
+ try {
1118
+ process.kill(pid, 0);
1119
+ } catch (e) {
1120
+ if (e.code === "ESRCH")
1121
+ unlinkSync(file);
1122
+ }
1123
+ }
1124
+ function save() {
1125
+ writeFileSync(statusFile + ".tmp", JSON.stringify({ pid: process.pid, updated_at: new Date().toISOString(), bots: [...workers.values()].map((w) => ({ name: w.config.name, agent_id: w.config.agentId, workdir: w.config.cwd, pid: w.child?.pid, status: w.status })) }, null, 2), { mode: 384 });
1126
+ renameSync(statusFile + ".tmp", statusFile);
1127
+ }
1128
+ async function stop(w) {
1129
+ const child = w.child;
1130
+ if (child && child.exitCode === null && child.signalCode === null)
1131
+ await new Promise((done) => {
1132
+ const timeout = setTimeout(() => killGroup(child), 20000);
1133
+ child.once("exit", () => {
1134
+ clearTimeout(timeout);
1135
+ killGroup(child);
1136
+ done();
1137
+ });
1138
+ child.kill("SIGTERM");
1139
+ });
1140
+ w.child = undefined;
1141
+ w.status = "stopped";
1142
+ }
1143
+ function killGroup(child) {
1144
+ if (child.pid)
1145
+ try {
1146
+ process.kill(-child.pid, "SIGKILL");
1147
+ } catch {}
1148
+ }
1149
+ function start(w) {
1150
+ removeDeadLock(join3(w.config.stateDir, "bridge.lock"));
1151
+ w.status = "starting";
1152
+ const child = spawn(process.execPath, [resolve3(process.argv[1]), "--codex-bridge", "--managed-worker"], { cwd: w.config.cwd, detached: true, stdio: ["ignore", "pipe", "pipe", "ipc"] });
1153
+ w.child = child;
1154
+ child.once("spawn", () => child.send(w.config, () => {}));
1155
+ let buffer = "";
1156
+ child.stderr?.on("data", (data) => {
1157
+ buffer = (buffer + String(data)).slice(-8192);
1158
+ if (buffer.includes(`AgentsChat connected as ${w.config.agentId}`)) {
1159
+ w.status = "connected";
1160
+ w.failures = 0;
1161
+ buffer = "";
1162
+ save();
1163
+ } else if (buffer.includes("disconnected")) {
1164
+ w.status = "reconnecting";
1165
+ buffer = "";
1166
+ save();
1167
+ }
1168
+ });
1169
+ child.stdout?.resume();
1170
+ const failed = () => {
1171
+ if (w.child !== child)
1172
+ return;
1173
+ killGroup(child);
1174
+ w.child = undefined;
1175
+ w.status = "retrying";
1176
+ w.next = Date.now() + Math.min(60000, 1000 * 2 ** Math.min(++w.failures, 6));
1177
+ save();
1178
+ };
1179
+ child.once("error", failed);
1180
+ child.once("exit", failed);
1181
+ }
1182
+ async function tick() {
1183
+ try {
1184
+ const configs = loadBots(registry);
1185
+ for (const [name, worker] of workers) {
1186
+ const c = configs.find((c2) => c2.name === name);
1187
+ if (!c || createHash2("sha256").update(JSON.stringify(c)).digest("hex") !== worker.fingerprint) {
1188
+ await stop(worker);
1189
+ workers.delete(name);
1190
+ }
1191
+ }
1192
+ for (const c of configs)
1193
+ if (!workers.has(c.name))
1194
+ workers.set(c.name, { config: c, fingerprint: createHash2("sha256").update(JSON.stringify(c)).digest("hex"), failures: 0, next: 0, status: "waiting" });
1195
+ } catch {
1196
+ console.error("Invalid registry; keeping last valid configuration");
1197
+ }
1198
+ if (stopping)
1199
+ return;
1200
+ let active;
1201
+ try {
1202
+ active = !values["watch-codex"] || await codexPresent();
1203
+ } catch {
1204
+ console.error("Process detection unavailable");
1205
+ return;
1206
+ }
1207
+ missing = active ? 0 : missing + 1;
1208
+ for (const w of workers.values()) {
1209
+ if (stopping)
1210
+ break;
1211
+ if (active && !w.child && Date.now() >= w.next)
1212
+ start(w);
1213
+ else if (!active && missing >= 2 && w.child)
1214
+ await stop(w);
1215
+ }
1216
+ save();
1217
+ }
1218
+ async function main() {
1219
+ if (values.help) {
1220
+ console.log(`agentschat-mcp --codex-bots [--config FILE] [--watch-codex] [--check|--status]
1221
+ Central registry: ~/.agentschat/codex-bots.json; profiles: ~/.agentschat/profiles
1222
+ Watch polls external Codex processes every 5 seconds.`);
1223
+ return;
1224
+ }
1225
+ if (values.status) {
1226
+ console.log(readFileSync3(statusFile, "utf8"));
1227
+ return;
1228
+ }
1229
+ const configs = loadBots(registry);
1230
+ if (values.check) {
1231
+ console.log(JSON.stringify(configs.map((c) => ({ name: c.name, agent_id: c.agentId, workdir: c.cwd, profile: c.profileFile }))));
1232
+ return;
1233
+ }
1234
+ mkdirSync2(root, { recursive: true, mode: 448 });
1235
+ removeDeadLock(lock);
1236
+ const fd = openSync(lock, "wx", 384);
1237
+ writeFileSync(fd, String(process.pid));
1238
+ closeSync(fd);
1239
+ let running = Promise.resolve();
1240
+ const loop = () => {
1241
+ running = tick().catch(() => console.error("Supervisor tick failed")).finally(() => {
1242
+ if (!stopping)
1243
+ timer = setTimeout(loop, 5000);
1244
+ });
1245
+ };
1246
+ const shutdown = async () => {
1247
+ if (stopping)
1248
+ return;
1249
+ stopping = true;
1250
+ clearTimeout(timer);
1251
+ await running;
1252
+ await Promise.all([...workers.values()].map(stop));
1253
+ save();
1254
+ if (readFileSync3(lock, "utf8") === String(process.pid))
1255
+ unlinkSync(lock);
1256
+ };
1257
+ process.once("SIGINT", () => void shutdown());
1258
+ process.once("SIGTERM", () => void shutdown());
1259
+ loop();
1260
+ }
1261
+ main().catch(() => {
1262
+ console.error("Bot manager failed; check registry, profile permissions, and existing manager");
1263
+ process.exitCode = 1;
1264
+ });