@polygraph/codex-plugin 0.4.21

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,1433 @@
1
+ #!/usr/bin/env node
2
+
3
+ // source/codex/lib/installer.mjs
4
+ import {
5
+ cpSync,
6
+ existsSync,
7
+ mkdirSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ rmSync,
11
+ writeFileSync
12
+ } from "node:fs";
13
+ import { homedir } from "node:os";
14
+ import { dirname, join, relative, resolve, sep } from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+
17
+ // node_modules/smol-toml/dist/error.js
18
+ function getLineColFromPtr(string, ptr) {
19
+ let lines = string.slice(0, ptr).split(/\r\n|\n|\r/g);
20
+ return [lines.length, lines.pop().length + 1];
21
+ }
22
+ function makeCodeBlock(string, line, column) {
23
+ let lines = string.split(/\r\n|\n|\r/g);
24
+ let codeblock = "";
25
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
26
+ for (let i = line - 1; i <= line + 1; i++) {
27
+ let l = lines[i - 1];
28
+ if (!l)
29
+ continue;
30
+ codeblock += i.toString().padEnd(numberLen, " ");
31
+ codeblock += ": ";
32
+ codeblock += l;
33
+ codeblock += "\n";
34
+ if (i === line) {
35
+ codeblock += " ".repeat(numberLen + column + 2);
36
+ codeblock += "^\n";
37
+ }
38
+ }
39
+ return codeblock;
40
+ }
41
+ var TomlError = class extends Error {
42
+ line;
43
+ column;
44
+ codeblock;
45
+ constructor(message, options) {
46
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
47
+ const codeblock = makeCodeBlock(options.toml, line, column);
48
+ super(`Invalid TOML document: ${message}
49
+
50
+ ${codeblock}`, options);
51
+ this.line = line;
52
+ this.column = column;
53
+ this.codeblock = codeblock;
54
+ }
55
+ };
56
+
57
+ // node_modules/smol-toml/dist/util.js
58
+ function isEscaped(str, ptr) {
59
+ let i = 0;
60
+ while (str[ptr - ++i] === "\\")
61
+ ;
62
+ return --i && i % 2;
63
+ }
64
+ function indexOfNewline(str, start = 0, end = str.length) {
65
+ let idx = str.indexOf("\n", start);
66
+ if (str[idx - 1] === "\r")
67
+ idx--;
68
+ return idx <= end ? idx : -1;
69
+ }
70
+ function skipComment(str, ptr) {
71
+ for (let i = ptr; i < str.length; i++) {
72
+ let c = str[i];
73
+ if (c === "\n")
74
+ return i;
75
+ if (c === "\r" && str[i + 1] === "\n")
76
+ return i + 1;
77
+ if (c < " " && c !== " " || c === "\x7F") {
78
+ throw new TomlError("control characters are not allowed in comments", {
79
+ toml: str,
80
+ ptr
81
+ });
82
+ }
83
+ }
84
+ return str.length;
85
+ }
86
+ function skipVoid(str, ptr, banNewLines, banComments) {
87
+ let c;
88
+ while (1) {
89
+ while ((c = str[ptr]) === " " || c === " " || !banNewLines && (c === "\n" || c === "\r" && str[ptr + 1] === "\n"))
90
+ ptr++;
91
+ if (banComments || c !== "#")
92
+ break;
93
+ ptr = skipComment(str, ptr);
94
+ }
95
+ return ptr;
96
+ }
97
+ function skipUntil(str, ptr, sep2, end, banNewLines = false) {
98
+ if (!end) {
99
+ ptr = indexOfNewline(str, ptr);
100
+ return ptr < 0 ? str.length : ptr;
101
+ }
102
+ for (let i = ptr; i < str.length; i++) {
103
+ let c = str[i];
104
+ if (c === "#") {
105
+ i = indexOfNewline(str, i);
106
+ } else if (c === sep2) {
107
+ return i + 1;
108
+ } else if (c === end || banNewLines && (c === "\n" || c === "\r" && str[i + 1] === "\n")) {
109
+ return i;
110
+ }
111
+ }
112
+ throw new TomlError("cannot find end of structure", {
113
+ toml: str,
114
+ ptr
115
+ });
116
+ }
117
+ function getStringEnd(str, seek) {
118
+ let first = str[seek];
119
+ let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2] ? str.slice(seek, seek + 3) : first;
120
+ seek += target.length - 1;
121
+ do
122
+ seek = str.indexOf(target, ++seek);
123
+ while (seek > -1 && first !== "'" && isEscaped(str, seek));
124
+ if (seek > -1) {
125
+ seek += target.length;
126
+ if (target.length > 1) {
127
+ if (str[seek] === first)
128
+ seek++;
129
+ if (str[seek] === first)
130
+ seek++;
131
+ }
132
+ }
133
+ return seek;
134
+ }
135
+
136
+ // node_modules/smol-toml/dist/date.js
137
+ var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;
138
+ var TomlDate = class _TomlDate extends Date {
139
+ #hasDate = false;
140
+ #hasTime = false;
141
+ #offset = null;
142
+ constructor(date) {
143
+ let hasDate = true;
144
+ let hasTime = true;
145
+ let offset = "Z";
146
+ if (typeof date === "string") {
147
+ let match = date.match(DATE_TIME_RE);
148
+ if (match) {
149
+ if (!match[1]) {
150
+ hasDate = false;
151
+ date = `0000-01-01T${date}`;
152
+ }
153
+ hasTime = !!match[2];
154
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
155
+ if (match[2] && +match[2] > 23) {
156
+ date = "";
157
+ } else {
158
+ offset = match[3] || null;
159
+ date = date.toUpperCase();
160
+ if (!offset && hasTime)
161
+ date += "Z";
162
+ }
163
+ } else {
164
+ date = "";
165
+ }
166
+ }
167
+ super(date);
168
+ if (!isNaN(this.getTime())) {
169
+ this.#hasDate = hasDate;
170
+ this.#hasTime = hasTime;
171
+ this.#offset = offset;
172
+ }
173
+ }
174
+ isDateTime() {
175
+ return this.#hasDate && this.#hasTime;
176
+ }
177
+ isLocal() {
178
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
179
+ }
180
+ isDate() {
181
+ return this.#hasDate && !this.#hasTime;
182
+ }
183
+ isTime() {
184
+ return this.#hasTime && !this.#hasDate;
185
+ }
186
+ isValid() {
187
+ return this.#hasDate || this.#hasTime;
188
+ }
189
+ toISOString() {
190
+ let iso = super.toISOString();
191
+ if (this.isDate())
192
+ return iso.slice(0, 10);
193
+ if (this.isTime())
194
+ return iso.slice(11, 23);
195
+ if (this.#offset === null)
196
+ return iso.slice(0, -1);
197
+ if (this.#offset === "Z")
198
+ return iso;
199
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
200
+ offset = this.#offset[0] === "-" ? offset : -offset;
201
+ let offsetDate = new Date(this.getTime() - offset * 6e4);
202
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
203
+ }
204
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
205
+ let date = new _TomlDate(jsDate);
206
+ date.#offset = offset;
207
+ return date;
208
+ }
209
+ static wrapAsLocalDateTime(jsDate) {
210
+ let date = new _TomlDate(jsDate);
211
+ date.#offset = null;
212
+ return date;
213
+ }
214
+ static wrapAsLocalDate(jsDate) {
215
+ let date = new _TomlDate(jsDate);
216
+ date.#hasTime = false;
217
+ date.#offset = null;
218
+ return date;
219
+ }
220
+ static wrapAsLocalTime(jsDate) {
221
+ let date = new _TomlDate(jsDate);
222
+ date.#hasDate = false;
223
+ date.#offset = null;
224
+ return date;
225
+ }
226
+ };
227
+
228
+ // node_modules/smol-toml/dist/primitive.js
229
+ var INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/;
230
+ var FLOAT_REGEX = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/;
231
+ var LEADING_ZERO = /^[+-]?0[0-9_]/;
232
+ var ESCAPE_REGEX = /^[0-9a-f]{2,8}$/i;
233
+ var ESC_MAP = {
234
+ b: "\b",
235
+ t: " ",
236
+ n: "\n",
237
+ f: "\f",
238
+ r: "\r",
239
+ e: "\x1B",
240
+ '"': '"',
241
+ "\\": "\\"
242
+ };
243
+ function parseString(str, ptr = 0, endPtr = str.length) {
244
+ let isLiteral = str[ptr] === "'";
245
+ let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];
246
+ if (isMultiline) {
247
+ endPtr -= 2;
248
+ if (str[ptr += 2] === "\r")
249
+ ptr++;
250
+ if (str[ptr] === "\n")
251
+ ptr++;
252
+ }
253
+ let tmp = 0;
254
+ let isEscape;
255
+ let parsed = "";
256
+ let sliceStart = ptr;
257
+ while (ptr < endPtr - 1) {
258
+ let c = str[ptr++];
259
+ if (c === "\n" || c === "\r" && str[ptr] === "\n") {
260
+ if (!isMultiline) {
261
+ throw new TomlError("newlines are not allowed in strings", {
262
+ toml: str,
263
+ ptr: ptr - 1
264
+ });
265
+ }
266
+ } else if (c < " " && c !== " " || c === "\x7F") {
267
+ throw new TomlError("control characters are not allowed in strings", {
268
+ toml: str,
269
+ ptr: ptr - 1
270
+ });
271
+ }
272
+ if (isEscape) {
273
+ isEscape = false;
274
+ if (c === "x" || c === "u" || c === "U") {
275
+ let code = str.slice(ptr, ptr += c === "x" ? 2 : c === "u" ? 4 : 8);
276
+ if (!ESCAPE_REGEX.test(code)) {
277
+ throw new TomlError("invalid unicode escape", {
278
+ toml: str,
279
+ ptr: tmp
280
+ });
281
+ }
282
+ try {
283
+ parsed += String.fromCodePoint(parseInt(code, 16));
284
+ } catch {
285
+ throw new TomlError("invalid unicode escape", {
286
+ toml: str,
287
+ ptr: tmp
288
+ });
289
+ }
290
+ } else if (isMultiline && (c === "\n" || c === " " || c === " " || c === "\r")) {
291
+ ptr = skipVoid(str, ptr - 1, true);
292
+ if (str[ptr] !== "\n" && str[ptr] !== "\r") {
293
+ throw new TomlError("invalid escape: only line-ending whitespace may be escaped", {
294
+ toml: str,
295
+ ptr: tmp
296
+ });
297
+ }
298
+ ptr = skipVoid(str, ptr);
299
+ } else if (c in ESC_MAP) {
300
+ parsed += ESC_MAP[c];
301
+ } else {
302
+ throw new TomlError("unrecognized escape sequence", {
303
+ toml: str,
304
+ ptr: tmp
305
+ });
306
+ }
307
+ sliceStart = ptr;
308
+ } else if (!isLiteral && c === "\\") {
309
+ tmp = ptr - 1;
310
+ isEscape = true;
311
+ parsed += str.slice(sliceStart, tmp);
312
+ }
313
+ }
314
+ return parsed + str.slice(sliceStart, endPtr - 1);
315
+ }
316
+ function parseValue(value, toml, ptr, integersAsBigInt) {
317
+ if (value === "true")
318
+ return true;
319
+ if (value === "false")
320
+ return false;
321
+ if (value === "-inf")
322
+ return -Infinity;
323
+ if (value === "inf" || value === "+inf")
324
+ return Infinity;
325
+ if (value === "nan" || value === "+nan" || value === "-nan")
326
+ return NaN;
327
+ if (value === "-0")
328
+ return integersAsBigInt ? 0n : 0;
329
+ let isInt = INT_REGEX.test(value);
330
+ if (isInt || FLOAT_REGEX.test(value)) {
331
+ if (LEADING_ZERO.test(value)) {
332
+ throw new TomlError("leading zeroes are not allowed", {
333
+ toml,
334
+ ptr
335
+ });
336
+ }
337
+ value = value.replace(/_/g, "");
338
+ let numeric = +value;
339
+ if (isNaN(numeric)) {
340
+ throw new TomlError("invalid number", {
341
+ toml,
342
+ ptr
343
+ });
344
+ }
345
+ if (isInt) {
346
+ if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {
347
+ throw new TomlError("integer value cannot be represented losslessly", {
348
+ toml,
349
+ ptr
350
+ });
351
+ }
352
+ if (isInt || integersAsBigInt === true)
353
+ numeric = BigInt(value);
354
+ }
355
+ return numeric;
356
+ }
357
+ const date = new TomlDate(value);
358
+ if (!date.isValid()) {
359
+ throw new TomlError("invalid value", {
360
+ toml,
361
+ ptr
362
+ });
363
+ }
364
+ return date;
365
+ }
366
+
367
+ // node_modules/smol-toml/dist/extract.js
368
+ function sliceAndTrimEndOf(str, startPtr, endPtr) {
369
+ let value = str.slice(startPtr, endPtr);
370
+ let commentIdx = value.indexOf("#");
371
+ if (commentIdx > -1) {
372
+ skipComment(str, commentIdx);
373
+ value = value.slice(0, commentIdx);
374
+ }
375
+ return [value.trimEnd(), commentIdx];
376
+ }
377
+ function extractValue(str, ptr, end, depth, integersAsBigInt) {
378
+ if (depth === 0) {
379
+ throw new TomlError("document contains excessively nested structures. aborting.", {
380
+ toml: str,
381
+ ptr
382
+ });
383
+ }
384
+ let c = str[ptr];
385
+ if (c === "[" || c === "{") {
386
+ let [value, endPtr2] = c === "[" ? parseArray(str, ptr, depth, integersAsBigInt) : parseInlineTable(str, ptr, depth, integersAsBigInt);
387
+ if (end) {
388
+ endPtr2 = skipVoid(str, endPtr2);
389
+ if (str[endPtr2] === ",")
390
+ endPtr2++;
391
+ else if (str[endPtr2] !== end) {
392
+ throw new TomlError("expected comma or end of structure", {
393
+ toml: str,
394
+ ptr: endPtr2
395
+ });
396
+ }
397
+ }
398
+ return [value, endPtr2];
399
+ }
400
+ let endPtr;
401
+ if (c === '"' || c === "'") {
402
+ endPtr = getStringEnd(str, ptr);
403
+ let parsed = parseString(str, ptr, endPtr);
404
+ if (end) {
405
+ endPtr = skipVoid(str, endPtr);
406
+ if (str[endPtr] && str[endPtr] !== "," && str[endPtr] !== end && str[endPtr] !== "\n" && str[endPtr] !== "\r") {
407
+ throw new TomlError("unexpected character encountered", {
408
+ toml: str,
409
+ ptr: endPtr
410
+ });
411
+ }
412
+ endPtr += +(str[endPtr] === ",");
413
+ }
414
+ return [parsed, endPtr];
415
+ }
416
+ endPtr = skipUntil(str, ptr, ",", end);
417
+ let slice = sliceAndTrimEndOf(str, ptr, endPtr - +(str[endPtr - 1] === ","));
418
+ if (!slice[0]) {
419
+ throw new TomlError("incomplete key-value declaration: no value specified", {
420
+ toml: str,
421
+ ptr
422
+ });
423
+ }
424
+ if (end && slice[1] > -1) {
425
+ endPtr = skipVoid(str, ptr + slice[1]);
426
+ endPtr += +(str[endPtr] === ",");
427
+ }
428
+ return [
429
+ parseValue(slice[0], str, ptr, integersAsBigInt),
430
+ endPtr
431
+ ];
432
+ }
433
+
434
+ // node_modules/smol-toml/dist/struct.js
435
+ var KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \t]*$/;
436
+ function parseKey(str, ptr, end = "=") {
437
+ let dot = ptr - 1;
438
+ let parsed = [];
439
+ let endPtr = str.indexOf(end, ptr);
440
+ if (endPtr < 0) {
441
+ throw new TomlError("incomplete key-value: cannot find end of key", {
442
+ toml: str,
443
+ ptr
444
+ });
445
+ }
446
+ do {
447
+ let c = str[ptr = ++dot];
448
+ if (c !== " " && c !== " ") {
449
+ if (c === '"' || c === "'") {
450
+ if (c === str[ptr + 1] && c === str[ptr + 2]) {
451
+ throw new TomlError("multiline strings are not allowed in keys", {
452
+ toml: str,
453
+ ptr
454
+ });
455
+ }
456
+ let eos = getStringEnd(str, ptr);
457
+ if (eos < 0) {
458
+ throw new TomlError("unfinished string encountered", {
459
+ toml: str,
460
+ ptr
461
+ });
462
+ }
463
+ dot = str.indexOf(".", eos);
464
+ let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);
465
+ let newLine = indexOfNewline(strEnd);
466
+ if (newLine > -1) {
467
+ throw new TomlError("newlines are not allowed in keys", {
468
+ toml: str,
469
+ ptr: ptr + dot + newLine
470
+ });
471
+ }
472
+ if (strEnd.trimStart()) {
473
+ throw new TomlError("found extra tokens after the string part", {
474
+ toml: str,
475
+ ptr: eos
476
+ });
477
+ }
478
+ if (endPtr < eos) {
479
+ endPtr = str.indexOf(end, eos);
480
+ if (endPtr < 0) {
481
+ throw new TomlError("incomplete key-value: cannot find end of key", {
482
+ toml: str,
483
+ ptr
484
+ });
485
+ }
486
+ }
487
+ parsed.push(parseString(str, ptr, eos));
488
+ } else {
489
+ dot = str.indexOf(".", ptr);
490
+ let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);
491
+ if (!KEY_PART_RE.test(part)) {
492
+ throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys", {
493
+ toml: str,
494
+ ptr
495
+ });
496
+ }
497
+ parsed.push(part.trimEnd());
498
+ }
499
+ }
500
+ } while (dot + 1 && dot < endPtr);
501
+ return [parsed, skipVoid(str, endPtr + 1, true, true)];
502
+ }
503
+ function parseInlineTable(str, ptr, depth, integersAsBigInt) {
504
+ let res = {};
505
+ let seen = /* @__PURE__ */ new Set();
506
+ let c;
507
+ ptr++;
508
+ while ((c = str[ptr++]) !== "}" && c) {
509
+ if (c === ",") {
510
+ throw new TomlError("expected value, found comma", {
511
+ toml: str,
512
+ ptr: ptr - 1
513
+ });
514
+ } else if (c === "#")
515
+ ptr = skipComment(str, ptr);
516
+ else if (c !== " " && c !== " " && c !== "\n" && c !== "\r") {
517
+ let k;
518
+ let t = res;
519
+ let hasOwn = false;
520
+ let [key, keyEndPtr] = parseKey(str, ptr - 1);
521
+ for (let i = 0; i < key.length; i++) {
522
+ if (i)
523
+ t = hasOwn ? t[k] : t[k] = {};
524
+ k = key[i];
525
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
526
+ throw new TomlError("trying to redefine an already defined value", {
527
+ toml: str,
528
+ ptr
529
+ });
530
+ }
531
+ if (!hasOwn && k === "__proto__") {
532
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
533
+ }
534
+ }
535
+ if (hasOwn) {
536
+ throw new TomlError("trying to redefine an already defined value", {
537
+ toml: str,
538
+ ptr
539
+ });
540
+ }
541
+ let [value, valueEndPtr] = extractValue(str, keyEndPtr, "}", depth - 1, integersAsBigInt);
542
+ seen.add(value);
543
+ t[k] = value;
544
+ ptr = valueEndPtr;
545
+ }
546
+ }
547
+ if (!c) {
548
+ throw new TomlError("unfinished table encountered", {
549
+ toml: str,
550
+ ptr
551
+ });
552
+ }
553
+ return [res, ptr];
554
+ }
555
+ function parseArray(str, ptr, depth, integersAsBigInt) {
556
+ let res = [];
557
+ let c;
558
+ ptr++;
559
+ while ((c = str[ptr++]) !== "]" && c) {
560
+ if (c === ",") {
561
+ throw new TomlError("expected value, found comma", {
562
+ toml: str,
563
+ ptr: ptr - 1
564
+ });
565
+ } else if (c === "#")
566
+ ptr = skipComment(str, ptr);
567
+ else if (c !== " " && c !== " " && c !== "\n" && c !== "\r") {
568
+ let e = extractValue(str, ptr - 1, "]", depth - 1, integersAsBigInt);
569
+ res.push(e[0]);
570
+ ptr = e[1];
571
+ }
572
+ }
573
+ if (!c) {
574
+ throw new TomlError("unfinished array encountered", {
575
+ toml: str,
576
+ ptr
577
+ });
578
+ }
579
+ return [res, ptr];
580
+ }
581
+
582
+ // node_modules/smol-toml/dist/parse.js
583
+ function peekTable(key, table, meta, type) {
584
+ let t = table;
585
+ let m = meta;
586
+ let k;
587
+ let hasOwn = false;
588
+ let state;
589
+ for (let i = 0; i < key.length; i++) {
590
+ if (i) {
591
+ t = hasOwn ? t[k] : t[k] = {};
592
+ m = (state = m[k]).c;
593
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
594
+ return null;
595
+ }
596
+ if (state.t === 2) {
597
+ let l = t.length - 1;
598
+ t = t[l];
599
+ m = m[l].c;
600
+ }
601
+ }
602
+ k = key[i];
603
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
604
+ return null;
605
+ }
606
+ if (!hasOwn) {
607
+ if (k === "__proto__") {
608
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
609
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
610
+ }
611
+ m[k] = {
612
+ t: i < key.length - 1 && type === 2 ? 3 : type,
613
+ d: false,
614
+ i: 0,
615
+ c: {}
616
+ };
617
+ }
618
+ }
619
+ state = m[k];
620
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
621
+ return null;
622
+ }
623
+ if (type === 2) {
624
+ if (!state.d) {
625
+ state.d = true;
626
+ t[k] = [];
627
+ }
628
+ t[k].push(t = {});
629
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: {} };
630
+ }
631
+ if (state.d) {
632
+ return null;
633
+ }
634
+ state.d = true;
635
+ if (type === 1) {
636
+ t = hasOwn ? t[k] : t[k] = {};
637
+ } else if (type === 0 && hasOwn) {
638
+ return null;
639
+ }
640
+ return [k, t, state.c];
641
+ }
642
+ function parse(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
643
+ let res = {};
644
+ let meta = {};
645
+ let tbl = res;
646
+ let m = meta;
647
+ for (let ptr = skipVoid(toml, 0); ptr < toml.length; ) {
648
+ if (toml[ptr] === "[") {
649
+ let isTableArray = toml[++ptr] === "[";
650
+ let k = parseKey(toml, ptr += +isTableArray, "]");
651
+ if (isTableArray) {
652
+ if (toml[k[1] - 1] !== "]") {
653
+ throw new TomlError("expected end of table declaration", {
654
+ toml,
655
+ ptr: k[1] - 1
656
+ });
657
+ }
658
+ k[1]++;
659
+ }
660
+ let p = peekTable(
661
+ k[0],
662
+ res,
663
+ meta,
664
+ isTableArray ? 2 : 1
665
+ /* Type.EXPLICIT */
666
+ );
667
+ if (!p) {
668
+ throw new TomlError("trying to redefine an already defined table or value", {
669
+ toml,
670
+ ptr
671
+ });
672
+ }
673
+ m = p[2];
674
+ tbl = p[1];
675
+ ptr = k[1];
676
+ } else {
677
+ let k = parseKey(toml, ptr);
678
+ let p = peekTable(
679
+ k[0],
680
+ tbl,
681
+ m,
682
+ 0
683
+ /* Type.DOTTED */
684
+ );
685
+ if (!p) {
686
+ throw new TomlError("trying to redefine an already defined table or value", {
687
+ toml,
688
+ ptr
689
+ });
690
+ }
691
+ let v = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);
692
+ p[1][p[0]] = v[0];
693
+ ptr = v[1];
694
+ }
695
+ ptr = skipVoid(toml, ptr, true);
696
+ if (toml[ptr] && toml[ptr] !== "\n" && toml[ptr] !== "\r") {
697
+ throw new TomlError("each key-value declaration must be followed by an end-of-line", {
698
+ toml,
699
+ ptr
700
+ });
701
+ }
702
+ ptr = skipVoid(toml, ptr);
703
+ }
704
+ return res;
705
+ }
706
+
707
+ // node_modules/smol-toml/dist/stringify.js
708
+ var BARE_KEY = /^[a-z0-9-_]+$/i;
709
+ function extendedTypeOf(obj) {
710
+ let type = typeof obj;
711
+ if (type === "object") {
712
+ if (Array.isArray(obj))
713
+ return "array";
714
+ if (obj instanceof Date)
715
+ return "date";
716
+ }
717
+ return type;
718
+ }
719
+ function isArrayOfTables(obj) {
720
+ for (let i = 0; i < obj.length; i++) {
721
+ if (extendedTypeOf(obj[i]) !== "object")
722
+ return false;
723
+ }
724
+ return obj.length != 0;
725
+ }
726
+ function formatString(s) {
727
+ return JSON.stringify(s).replace(/\x7f/g, "\\u007f");
728
+ }
729
+ function stringifyValue(val, type, depth, numberAsFloat) {
730
+ if (depth === 0) {
731
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
732
+ }
733
+ if (type === "number") {
734
+ if (isNaN(val))
735
+ return "nan";
736
+ if (val === Infinity)
737
+ return "inf";
738
+ if (val === -Infinity)
739
+ return "-inf";
740
+ if (numberAsFloat && Number.isInteger(val))
741
+ return val.toFixed(1);
742
+ return val.toString();
743
+ }
744
+ if (type === "bigint" || type === "boolean") {
745
+ return val.toString();
746
+ }
747
+ if (type === "string") {
748
+ return formatString(val);
749
+ }
750
+ if (type === "date") {
751
+ if (isNaN(val.getTime())) {
752
+ throw new TypeError("cannot serialize invalid date");
753
+ }
754
+ return val.toISOString();
755
+ }
756
+ if (type === "object") {
757
+ return stringifyInlineTable(val, depth, numberAsFloat);
758
+ }
759
+ if (type === "array") {
760
+ return stringifyArray(val, depth, numberAsFloat);
761
+ }
762
+ }
763
+ function stringifyInlineTable(obj, depth, numberAsFloat) {
764
+ let keys = Object.keys(obj);
765
+ if (keys.length === 0)
766
+ return "{}";
767
+ let res = "{ ";
768
+ for (let i = 0; i < keys.length; i++) {
769
+ let k = keys[i];
770
+ if (i)
771
+ res += ", ";
772
+ res += BARE_KEY.test(k) ? k : formatString(k);
773
+ res += " = ";
774
+ res += stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat);
775
+ }
776
+ return res + " }";
777
+ }
778
+ function stringifyArray(array, depth, numberAsFloat) {
779
+ if (array.length === 0)
780
+ return "[]";
781
+ let res = "[ ";
782
+ for (let i = 0; i < array.length; i++) {
783
+ if (i)
784
+ res += ", ";
785
+ if (array[i] === null || array[i] === void 0) {
786
+ throw new TypeError("arrays cannot contain null or undefined values");
787
+ }
788
+ res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat);
789
+ }
790
+ return res + " ]";
791
+ }
792
+ function stringifyArrayTable(array, key, depth, numberAsFloat) {
793
+ if (depth === 0) {
794
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
795
+ }
796
+ let res = "";
797
+ for (let i = 0; i < array.length; i++) {
798
+ res += `${res && "\n"}[[${key}]]
799
+ `;
800
+ res += stringifyTable(0, array[i], key, depth, numberAsFloat);
801
+ }
802
+ return res;
803
+ }
804
+ function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat) {
805
+ if (depth === 0) {
806
+ throw new Error("Could not stringify the object: maximum object depth exceeded");
807
+ }
808
+ let preamble = "";
809
+ let tables = "";
810
+ let keys = Object.keys(obj);
811
+ for (let i = 0; i < keys.length; i++) {
812
+ let k = keys[i];
813
+ if (obj[k] !== null && obj[k] !== void 0) {
814
+ let type = extendedTypeOf(obj[k]);
815
+ if (type === "symbol" || type === "function") {
816
+ throw new TypeError(`cannot serialize values of type '${type}'`);
817
+ }
818
+ let key = BARE_KEY.test(k) ? k : formatString(k);
819
+ if (type === "array" && isArrayOfTables(obj[k])) {
820
+ tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat);
821
+ } else if (type === "object") {
822
+ let tblKey = prefix ? `${prefix}.${key}` : key;
823
+ tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat);
824
+ } else {
825
+ preamble += key;
826
+ preamble += " = ";
827
+ preamble += stringifyValue(obj[k], type, depth, numberAsFloat);
828
+ preamble += "\n";
829
+ }
830
+ }
831
+ }
832
+ if (tableKey && (preamble || !tables))
833
+ preamble = preamble ? `[${tableKey}]
834
+ ${preamble}` : `[${tableKey}]`;
835
+ return preamble && tables ? `${preamble}
836
+ ${tables}` : preamble || tables;
837
+ }
838
+ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false } = {}) {
839
+ if (extendedTypeOf(obj) !== "object") {
840
+ throw new TypeError("stringify can only be called with an object");
841
+ }
842
+ let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat);
843
+ if (str[str.length - 1] !== "\n")
844
+ return str + "\n";
845
+ return str;
846
+ }
847
+
848
+ // source/codex/lib/installer.mjs
849
+ var PLUGIN_NAME = "polygraph";
850
+ var PLUGIN_ID = "polygraph@polygraph-plugins";
851
+ var MARKETPLACE_NAME = "polygraph-plugins";
852
+ var MARKETPLACE_DISPLAY_NAME = "Polygraph Plugins";
853
+ function getPackageRootFromMetaUrl(metaUrl) {
854
+ return resolve(dirname(fileURLToPath(metaUrl)), "..");
855
+ }
856
+ function resolveCodexHome(env = process.env) {
857
+ const configuredHome = env.CODEX_HOME?.trim();
858
+ if (configuredHome) {
859
+ return resolve(expandHome(configuredHome, env));
860
+ }
861
+ const userHome = env.HOME?.trim() || homedir();
862
+ return join(resolve(expandHome(userHome, env)), ".codex");
863
+ }
864
+ function getConfigPath(codexHome) {
865
+ return join(codexHome, "config.toml");
866
+ }
867
+ function getAgentsPath(codexHome) {
868
+ return join(codexHome, "agents");
869
+ }
870
+ function getCacheRoot(codexHome, version) {
871
+ const base = join(
872
+ codexHome,
873
+ "plugins",
874
+ "cache",
875
+ MARKETPLACE_NAME,
876
+ PLUGIN_NAME
877
+ );
878
+ return version ? join(base, version) : base;
879
+ }
880
+ function resolveUserHome(env = process.env) {
881
+ const userHome = env.HOME?.trim() || homedir();
882
+ return resolve(expandHome(userHome, env));
883
+ }
884
+ function getMarketplacePath(userHome) {
885
+ return join(userHome, ".agents", "plugins", "marketplace.json");
886
+ }
887
+ function getPluginInstallPath(userHome) {
888
+ return join(userHome, ".agents", "plugins", PLUGIN_NAME);
889
+ }
890
+ function loadPackageMetadata(packageRoot) {
891
+ const packageJsonPath = join(packageRoot, "package.json");
892
+ const pluginManifestPath = join(packageRoot, ".codex-plugin", "plugin.json");
893
+ if (!existsSync(packageJsonPath)) {
894
+ throw new Error(`Missing package.json at ${packageJsonPath}`);
895
+ }
896
+ if (!existsSync(pluginManifestPath)) {
897
+ throw new Error(`Missing Codex plugin manifest at ${pluginManifestPath}`);
898
+ }
899
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
900
+ const pluginManifest = JSON.parse(readFileSync(pluginManifestPath, "utf8"));
901
+ if (pluginManifest.name !== PLUGIN_NAME) {
902
+ throw new Error(
903
+ `Expected .codex-plugin/plugin.json name to be "${PLUGIN_NAME}", received "${pluginManifest.name ?? "undefined"}"`
904
+ );
905
+ }
906
+ if (!packageJson.version) {
907
+ throw new Error(`Missing package version in ${packageJsonPath}`);
908
+ }
909
+ if (pluginManifest.version && pluginManifest.version !== packageJson.version) {
910
+ throw new Error(
911
+ `Package version mismatch: package.json has "${packageJson.version}" but plugin manifest has "${pluginManifest.version}"`
912
+ );
913
+ }
914
+ return {
915
+ packageJson,
916
+ pluginManifest,
917
+ version: packageJson.version
918
+ };
919
+ }
920
+ function mirrorCodexPluginCache({ codexHome, packageRoot, packageJson, version }) {
921
+ if (!existsSync(codexHome)) {
922
+ return null;
923
+ }
924
+ const pluginCacheRoot = getCacheRoot(codexHome);
925
+ if (existsSync(pluginCacheRoot)) {
926
+ for (const entry of readdirSync(pluginCacheRoot)) {
927
+ rmSync(join(pluginCacheRoot, entry), { recursive: true, force: true });
928
+ }
929
+ }
930
+ const versionedCachePath = getCacheRoot(codexHome, version);
931
+ mkdirSync(versionedCachePath, { recursive: true });
932
+ for (const relativePath of getPackagePayloadPaths(packageRoot, packageJson)) {
933
+ copyRelativeEntry(packageRoot, versionedCachePath, relativePath);
934
+ }
935
+ return versionedCachePath;
936
+ }
937
+ function installPlugin({
938
+ packageRoot,
939
+ env = process.env,
940
+ force = false
941
+ } = {}) {
942
+ if (!packageRoot) {
943
+ throw new Error("packageRoot is required");
944
+ }
945
+ const { packageJson, version } = loadPackageMetadata(packageRoot);
946
+ const codexHome = resolveCodexHome(env);
947
+ const userHome = resolveUserHome(env);
948
+ const configPath = getConfigPath(codexHome);
949
+ const agentsPath = getAgentsPath(codexHome);
950
+ const marketplacePath = getMarketplacePath(userHome);
951
+ const pluginPath = getPluginInstallPath(userHome);
952
+ const installAlreadyPresent = existsSync(pluginPath);
953
+ let previousVersion = null;
954
+ if (installAlreadyPresent) {
955
+ try {
956
+ const installedPkg = JSON.parse(
957
+ readFileSync(join(pluginPath, "package.json"), "utf8")
958
+ );
959
+ previousVersion = installedPkg.version ?? null;
960
+ } catch {
961
+ }
962
+ }
963
+ const versionMismatch = installAlreadyPresent && previousVersion !== version;
964
+ if (installAlreadyPresent && !force && !versionMismatch && !isValidInstalledPluginDir(pluginPath)) {
965
+ throw new Error(
966
+ `Existing install at ${pluginPath} is incomplete or invalid. Re-run with --force to overwrite it.`
967
+ );
968
+ }
969
+ if (installAlreadyPresent && force) {
970
+ rmSync(pluginPath, { recursive: true, force: true });
971
+ }
972
+ let copied = false;
973
+ if (!installAlreadyPresent || force || versionMismatch) {
974
+ mkdirSync(pluginPath, { recursive: true });
975
+ for (const relativePath of getPackagePayloadPaths(
976
+ packageRoot,
977
+ packageJson
978
+ )) {
979
+ copyRelativeEntry(packageRoot, pluginPath, relativePath);
980
+ }
981
+ copied = true;
982
+ }
983
+ const configChanged = enablePluginInConfig(configPath);
984
+ const agentsChanged = installCodexAgents({ packageRoot, agentsPath });
985
+ const marketplaceChanged = enablePluginInMarketplace({
986
+ marketplacePath,
987
+ pluginPath,
988
+ userHome
989
+ });
990
+ const codexCachePath = mirrorCodexPluginCache({
991
+ codexHome,
992
+ packageRoot,
993
+ packageJson,
994
+ version
995
+ });
996
+ return {
997
+ ok: true,
998
+ action: "install",
999
+ plugin: PLUGIN_ID,
1000
+ version,
1001
+ codexHome,
1002
+ agentsPath,
1003
+ pluginPath,
1004
+ configPath,
1005
+ marketplacePath,
1006
+ codexCachePath,
1007
+ copied,
1008
+ overwritten: installAlreadyPresent && force,
1009
+ pluginUpdated: installAlreadyPresent && versionMismatch && !force,
1010
+ previousVersion,
1011
+ configChanged,
1012
+ agentsChanged,
1013
+ marketplaceChanged
1014
+ };
1015
+ }
1016
+ function checkInstall({ packageRoot, env = process.env } = {}) {
1017
+ let version = null;
1018
+ if (packageRoot) {
1019
+ ({ version } = loadPackageMetadata(packageRoot));
1020
+ }
1021
+ const codexHome = resolveCodexHome(env);
1022
+ const userHome = resolveUserHome(env);
1023
+ const configPath = getConfigPath(codexHome);
1024
+ const agentsPath = getAgentsPath(codexHome);
1025
+ const marketplacePath = getMarketplacePath(userHome);
1026
+ const pluginPath = getPluginInstallPath(userHome);
1027
+ const pluginInstalled = isValidInstalledPluginDir(pluginPath);
1028
+ const configEnabled = isPluginEnabled(configPath);
1029
+ const agentsInstalled = packageRoot ? areCodexAgentsInstalled({ packageRoot, agentsPath }) : hasDefaultCodexAgents(agentsPath);
1030
+ const marketplaceConfigured = isPluginConfiguredInMarketplace({
1031
+ marketplacePath,
1032
+ userHome,
1033
+ pluginPath
1034
+ });
1035
+ const ok = pluginInstalled && configEnabled && agentsInstalled && marketplaceConfigured;
1036
+ const codexHomeExists = existsSync(codexHome);
1037
+ const codexCachePath = codexHomeExists && version ? getCacheRoot(codexHome, version) : null;
1038
+ const codexCacheMirrored = codexCachePath !== null ? isCodexCacheCurrent({ cachePath: codexCachePath, pluginPath }) : null;
1039
+ return {
1040
+ ok,
1041
+ action: "check",
1042
+ plugin: PLUGIN_ID,
1043
+ codexHome,
1044
+ agentsPath,
1045
+ pluginPath,
1046
+ configPath,
1047
+ marketplacePath,
1048
+ codexCachePath,
1049
+ pluginInstalled,
1050
+ configEnabled,
1051
+ agentsInstalled,
1052
+ marketplaceConfigured,
1053
+ codexCacheMirrored
1054
+ };
1055
+ }
1056
+ function enablePluginInConfig(configPath) {
1057
+ const config = readTomlFile(configPath);
1058
+ if (config.plugins !== void 0 && !isPlainObject(config.plugins)) {
1059
+ throw new Error(
1060
+ `Expected plugins table in ${configPath} to be a TOML table`
1061
+ );
1062
+ }
1063
+ const plugins = config.plugins ?? {};
1064
+ const pluginConfig = plugins[PLUGIN_ID];
1065
+ if (pluginConfig !== void 0 && !isPlainObject(pluginConfig)) {
1066
+ throw new Error(
1067
+ `Expected plugins."${PLUGIN_ID}" in ${configPath} to be a TOML table`
1068
+ );
1069
+ }
1070
+ const wasEnabled = pluginConfig?.enabled === true;
1071
+ plugins[PLUGIN_ID] = { ...pluginConfig ?? {}, enabled: true };
1072
+ config.plugins = plugins;
1073
+ writeTomlFile(configPath, config);
1074
+ return !wasEnabled;
1075
+ }
1076
+ function isPluginEnabled(configPath) {
1077
+ if (!existsSync(configPath)) {
1078
+ return false;
1079
+ }
1080
+ const config = readTomlFile(configPath);
1081
+ return config.plugins?.[PLUGIN_ID]?.enabled === true;
1082
+ }
1083
+ function getPackagePayloadPaths(packageRoot, packageJson) {
1084
+ const relativePaths = new Set(packageJson.files ?? []);
1085
+ relativePaths.add("package.json");
1086
+ if (packageJson.bin) {
1087
+ for (const relativePath of Object.values(packageJson.bin)) {
1088
+ relativePaths.add(relativePath);
1089
+ }
1090
+ }
1091
+ for (const extraFile of ["README.md", "LICENSE"]) {
1092
+ if (existsSync(join(packageRoot, extraFile))) {
1093
+ relativePaths.add(extraFile);
1094
+ }
1095
+ }
1096
+ return [...relativePaths];
1097
+ }
1098
+ function copyRelativeEntry(sourceRoot, targetRoot, relativePath) {
1099
+ const sourcePath = join(sourceRoot, relativePath);
1100
+ if (!existsSync(sourcePath)) {
1101
+ return;
1102
+ }
1103
+ cpSync(sourcePath, join(targetRoot, relativePath), { recursive: true });
1104
+ }
1105
+ function installCodexAgents({ packageRoot, agentsPath }) {
1106
+ const agentFiles = listPackageAgentFiles(packageRoot);
1107
+ if (agentFiles.length === 0) {
1108
+ return false;
1109
+ }
1110
+ mkdirSync(agentsPath, { recursive: true });
1111
+ let changed = false;
1112
+ for (const agentFile of agentFiles) {
1113
+ const sourcePath = join(packageRoot, "agents", agentFile);
1114
+ const targetPath = join(agentsPath, agentFile);
1115
+ const sourceContent = readFileSync(sourcePath, "utf8");
1116
+ const targetContent = existsSync(targetPath) ? readFileSync(targetPath, "utf8") : null;
1117
+ if (targetContent !== sourceContent) {
1118
+ writeFileSync(targetPath, sourceContent);
1119
+ changed = true;
1120
+ }
1121
+ }
1122
+ return changed;
1123
+ }
1124
+ function areCodexAgentsInstalled({ packageRoot, agentsPath }) {
1125
+ const agentFiles = listPackageAgentFiles(packageRoot);
1126
+ if (agentFiles.length === 0) {
1127
+ return false;
1128
+ }
1129
+ return agentFiles.every((agentFile) => {
1130
+ const sourcePath = join(packageRoot, "agents", agentFile);
1131
+ const targetPath = join(agentsPath, agentFile);
1132
+ return existsSync(targetPath) && readFileSync(targetPath, "utf8") === readFileSync(sourcePath, "utf8");
1133
+ });
1134
+ }
1135
+ function listPackageAgentFiles(packageRoot) {
1136
+ const agentsDir = join(packageRoot, "agents");
1137
+ if (!existsSync(agentsDir)) {
1138
+ return [];
1139
+ }
1140
+ return readdirSync(agentsDir).filter((entry) => entry.endsWith(".toml")).sort();
1141
+ }
1142
+ function hasDefaultCodexAgents(agentsPath) {
1143
+ return ["polygraph-delegate-subagent.toml", "polygraph-init-subagent.toml"].every(
1144
+ (agentFile) => existsSync(join(agentsPath, agentFile))
1145
+ );
1146
+ }
1147
+ function enablePluginInMarketplace({
1148
+ marketplacePath,
1149
+ pluginPath,
1150
+ userHome
1151
+ }) {
1152
+ const marketplace = readJsonFile(marketplacePath, {});
1153
+ if (marketplace.plugins !== void 0 && !Array.isArray(marketplace.plugins)) {
1154
+ throw new Error(`Expected plugins array in ${marketplacePath}`);
1155
+ }
1156
+ const marketplacePluginPath = toMarketplaceSourcePath(userHome, pluginPath);
1157
+ const nextPluginEntry = {
1158
+ name: PLUGIN_NAME,
1159
+ source: {
1160
+ source: "local",
1161
+ path: marketplacePluginPath
1162
+ },
1163
+ policy: {
1164
+ installation: "AVAILABLE",
1165
+ authentication: "ON_INSTALL"
1166
+ },
1167
+ category: "Productivity"
1168
+ };
1169
+ const plugins = marketplace.plugins ?? [];
1170
+ const existingIndex = plugins.findIndex(
1171
+ (plugin) => plugin?.name === PLUGIN_NAME
1172
+ );
1173
+ const nextPlugins = existingIndex === -1 ? [...plugins, nextPluginEntry] : plugins.map(
1174
+ (plugin, index) => index === existingIndex ? nextPluginEntry : plugin
1175
+ );
1176
+ const nextMarketplace = {
1177
+ ...marketplace,
1178
+ name: marketplace.name ?? MARKETPLACE_NAME,
1179
+ interface: isPlainObject(marketplace.interface) ? {
1180
+ ...marketplace.interface,
1181
+ displayName: marketplace.interface.displayName ?? MARKETPLACE_DISPLAY_NAME
1182
+ } : { displayName: MARKETPLACE_DISPLAY_NAME },
1183
+ plugins: nextPlugins
1184
+ };
1185
+ const changed = JSON.stringify(nextMarketplace) !== JSON.stringify(marketplace);
1186
+ if (changed) {
1187
+ writeJsonFile(marketplacePath, nextMarketplace);
1188
+ }
1189
+ return changed;
1190
+ }
1191
+ function isPluginConfiguredInMarketplace({
1192
+ marketplacePath,
1193
+ userHome,
1194
+ pluginPath
1195
+ }) {
1196
+ if (!existsSync(marketplacePath)) {
1197
+ return false;
1198
+ }
1199
+ const marketplace = readJsonFile(marketplacePath);
1200
+ if (!Array.isArray(marketplace.plugins)) {
1201
+ return false;
1202
+ }
1203
+ const pluginEntry = marketplace.plugins.find(
1204
+ (plugin) => plugin?.name === PLUGIN_NAME
1205
+ );
1206
+ if (!isPlainObject(pluginEntry?.source) || pluginEntry.source.source !== "local") {
1207
+ return false;
1208
+ }
1209
+ const configuredPath = resolve(userHome, pluginEntry.source.path);
1210
+ return configuredPath === resolve(pluginPath);
1211
+ }
1212
+ function readTomlFile(path) {
1213
+ if (!existsSync(path)) {
1214
+ return {};
1215
+ }
1216
+ const raw = readFileSync(path, "utf8");
1217
+ if (raw.trim() === "") {
1218
+ return {};
1219
+ }
1220
+ const parsed = parse(raw);
1221
+ if (!isPlainObject(parsed)) {
1222
+ throw new Error(`Expected TOML document at ${path} to parse to an object`);
1223
+ }
1224
+ return parsed;
1225
+ }
1226
+ function writeTomlFile(path, value) {
1227
+ mkdirSync(dirname(path), { recursive: true });
1228
+ writeFileSync(path, `${stringify(value).trimEnd()}
1229
+ `);
1230
+ }
1231
+ function readJsonFile(path, fallbackValue) {
1232
+ if (!existsSync(path)) {
1233
+ return fallbackValue;
1234
+ }
1235
+ return JSON.parse(readFileSync(path, "utf8"));
1236
+ }
1237
+ function writeJsonFile(path, value) {
1238
+ mkdirSync(dirname(path), { recursive: true });
1239
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
1240
+ `);
1241
+ }
1242
+ function isCodexCacheCurrent({ cachePath, pluginPath }) {
1243
+ if (!existsSync(cachePath) || !existsSync(pluginPath)) {
1244
+ return false;
1245
+ }
1246
+ return directoriesMatch(pluginPath, cachePath);
1247
+ }
1248
+ function directoriesMatch(aDir, bDir) {
1249
+ if (!existsSync(aDir) || !existsSync(bDir)) {
1250
+ return false;
1251
+ }
1252
+ const aEntries = readdirSync(aDir, { withFileTypes: true }).sort(
1253
+ (x, y) => x.name < y.name ? -1 : x.name > y.name ? 1 : 0
1254
+ );
1255
+ const bEntries = readdirSync(bDir, { withFileTypes: true }).sort(
1256
+ (x, y) => x.name < y.name ? -1 : x.name > y.name ? 1 : 0
1257
+ );
1258
+ if (aEntries.length !== bEntries.length) {
1259
+ return false;
1260
+ }
1261
+ for (let i = 0; i < aEntries.length; i++) {
1262
+ const a = aEntries[i];
1263
+ const b = bEntries[i];
1264
+ if (a.name !== b.name || a.isDirectory() !== b.isDirectory()) {
1265
+ return false;
1266
+ }
1267
+ if (a.isDirectory()) {
1268
+ if (!directoriesMatch(join(aDir, a.name), join(bDir, b.name))) {
1269
+ return false;
1270
+ }
1271
+ } else {
1272
+ const aContent = readFileSync(join(aDir, a.name));
1273
+ const bContent = readFileSync(join(bDir, b.name));
1274
+ if (!aContent.equals(bContent)) {
1275
+ return false;
1276
+ }
1277
+ }
1278
+ }
1279
+ return true;
1280
+ }
1281
+ function isValidInstalledPluginDir(candidatePath) {
1282
+ const pluginManifestPath = join(
1283
+ candidatePath,
1284
+ ".codex-plugin",
1285
+ "plugin.json"
1286
+ );
1287
+ const mcpConfigPath = join(candidatePath, ".mcp.json");
1288
+ const skillsPath = join(candidatePath, "skills");
1289
+ if (!existsSync(pluginManifestPath) || !existsSync(mcpConfigPath) || !existsSync(skillsPath)) {
1290
+ return false;
1291
+ }
1292
+ try {
1293
+ const pluginManifest = JSON.parse(readFileSync(pluginManifestPath, "utf8"));
1294
+ return pluginManifest.name === PLUGIN_NAME;
1295
+ } catch {
1296
+ return false;
1297
+ }
1298
+ }
1299
+ function expandHome(inputPath, env) {
1300
+ if (!inputPath.startsWith("~")) {
1301
+ return inputPath;
1302
+ }
1303
+ const userHome = env.HOME?.trim() || homedir();
1304
+ if (inputPath === "~") {
1305
+ return userHome;
1306
+ }
1307
+ if (inputPath.startsWith("~/")) {
1308
+ return join(userHome, inputPath.slice(2));
1309
+ }
1310
+ return inputPath;
1311
+ }
1312
+ function toMarketplaceSourcePath(userHome, targetPath) {
1313
+ const relativePath = relative(userHome, targetPath);
1314
+ if (relativePath === "" || relativePath === "." || relativePath.startsWith(`..${sep}`) || relativePath === "..") {
1315
+ throw new Error(
1316
+ `Expected plugin install path ${targetPath} to be inside ${userHome} so it can be referenced from the personal marketplace`
1317
+ );
1318
+ }
1319
+ return `./${relativePath.split(sep).join("/")}`;
1320
+ }
1321
+ function isPlainObject(value) {
1322
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1323
+ }
1324
+
1325
+ // source/codex/bin/polygraph-codex-plugin.mjs
1326
+ var usage = `Usage:
1327
+ npx @polygraph/codex-plugin
1328
+ npx @polygraph/codex-plugin install [--force] [--json]
1329
+ npx @polygraph/codex-plugin check [--json]`;
1330
+ async function main() {
1331
+ const args = process.argv.slice(2);
1332
+ let command = "install";
1333
+ let json = false;
1334
+ let force = false;
1335
+ for (const arg of args) {
1336
+ if (arg === "--json") {
1337
+ json = true;
1338
+ continue;
1339
+ }
1340
+ if (arg === "--force") {
1341
+ force = true;
1342
+ continue;
1343
+ }
1344
+ if (arg === "install" || arg === "check") {
1345
+ command = arg;
1346
+ continue;
1347
+ }
1348
+ if (arg === "--help" || arg === "-h") {
1349
+ console.log(usage);
1350
+ return;
1351
+ }
1352
+ throw new Error(`Unknown argument: ${arg}
1353
+
1354
+ ${usage}`);
1355
+ }
1356
+ if (command === "check" && force) {
1357
+ throw new Error("--force is only supported with the install command");
1358
+ }
1359
+ const packageRoot = getPackageRootFromMetaUrl(import.meta.url);
1360
+ const result = command === "check" ? checkInstall({ packageRoot, env: process.env }) : installPlugin({ packageRoot, env: process.env, force });
1361
+ if (json) {
1362
+ console.log(JSON.stringify(result, null, 2));
1363
+ } else if (command === "check") {
1364
+ if (result.ok) {
1365
+ console.log(`Polygraph Codex plugin is enabled.`);
1366
+ console.log(`Plugin path: ${result.pluginPath}`);
1367
+ console.log(`Agents: ${result.agentsPath}`);
1368
+ console.log(`Config: ${result.configPath}`);
1369
+ console.log(`Marketplace: ${result.marketplacePath}`);
1370
+ } else {
1371
+ const pluginState = result.pluginInstalled ? "plugin files present" : "plugin files not present";
1372
+ const configState = result.configEnabled ? "plugin enabled in config" : "plugin not enabled in config";
1373
+ const agentsState = result.agentsInstalled ? "agents installed" : "agents not installed";
1374
+ const marketplaceState = result.marketplaceConfigured ? "plugin present in marketplace" : "plugin not present in marketplace";
1375
+ console.error(
1376
+ `Polygraph Codex plugin check failed: ${pluginState}; ${configState}; ${agentsState}; ${marketplaceState}.`
1377
+ );
1378
+ }
1379
+ } else {
1380
+ console.log(`Installed Polygraph Codex plugin ${result.version}.`);
1381
+ console.log(`Plugin path: ${result.pluginPath}`);
1382
+ console.log(`Agents: ${result.agentsPath}`);
1383
+ console.log(`Config: ${result.configPath}`);
1384
+ console.log(`Marketplace: ${result.marketplacePath}`);
1385
+ }
1386
+ if (command === "check" && !result.ok) {
1387
+ process.exitCode = 1;
1388
+ }
1389
+ }
1390
+ main().catch((error) => {
1391
+ const message = error instanceof Error ? error.message : String(error);
1392
+ console.error(`polygraph-codex-plugin failed: ${message}`);
1393
+ process.exitCode = 1;
1394
+ });
1395
+ /*! Bundled license information:
1396
+
1397
+ smol-toml/dist/error.js:
1398
+ smol-toml/dist/util.js:
1399
+ smol-toml/dist/date.js:
1400
+ smol-toml/dist/primitive.js:
1401
+ smol-toml/dist/extract.js:
1402
+ smol-toml/dist/struct.js:
1403
+ smol-toml/dist/parse.js:
1404
+ smol-toml/dist/stringify.js:
1405
+ smol-toml/dist/index.js:
1406
+ (*!
1407
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
1408
+ * SPDX-License-Identifier: BSD-3-Clause
1409
+ *
1410
+ * Redistribution and use in source and binary forms, with or without
1411
+ * modification, are permitted provided that the following conditions are met:
1412
+ *
1413
+ * 1. Redistributions of source code must retain the above copyright notice, this
1414
+ * list of conditions and the following disclaimer.
1415
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
1416
+ * this list of conditions and the following disclaimer in the
1417
+ * documentation and/or other materials provided with the distribution.
1418
+ * 3. Neither the name of the copyright holder nor the names of its contributors
1419
+ * may be used to endorse or promote products derived from this software without
1420
+ * specific prior written permission.
1421
+ *
1422
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1423
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1424
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1425
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1426
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1427
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1428
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1429
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1430
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1431
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1432
+ *)
1433
+ */