@codexhost/cli-linux-arm64 0.23.0 → 0.24.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.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +1565 -1805
  4. package/app/console-web.js +5786 -1600
  5. package/app/desktop-controller.mjs +13104 -2842
  6. package/app/host-runtime.mjs +50518 -51753
  7. package/app/plugins/antigravity/plugin.mjs +1932 -1148
  8. package/app/plugins/claude-code/plugin.mjs +1676 -1218
  9. package/app/plugins/codebuddy/plugin.mjs +1266 -850
  10. package/app/plugins/codex-usage/plugin.mjs +916 -737
  11. package/app/plugins/copilot/plugin.mjs +838 -640
  12. package/app/plugins/cursor-cli/plugin.mjs +1058 -747
  13. package/app/plugins/deepseek-harness/plugin.mjs +1302 -1070
  14. package/app/plugins/devin/plugin.mjs +949 -752
  15. package/app/plugins/grok/plugin.mjs +1132 -964
  16. package/app/plugins/hermes/plugin.mjs +1084 -905
  17. package/app/plugins/kimi-code/plugin.mjs +977 -804
  18. package/app/plugins/kiro-cli/plugin.mjs +951 -758
  19. package/app/plugins/omp/plugin.mjs +1408 -1169
  20. package/app/plugins/opencode/plugin.mjs +1385 -1142
  21. package/app/plugins/pi/plugin.mjs +1515 -1287
  22. package/app/plugins/qoder/plugin.mjs +861 -676
  23. package/app/plugins/qoder-cn/plugin.mjs +861 -676
  24. package/app/plugins/qwen-code/plugin.mjs +1060 -888
  25. package/app/plugins/workbuddy/plugin.mjs +1272 -856
  26. package/app/plugins/zcode/plugin.mjs +1529 -880
  27. package/app/renderer-extension.js +11568 -7827
  28. package/app/web/assets/index-CTCFIQbU.css +1 -0
  29. package/app/web/assets/index-IvFk9KT-.js +203 -0
  30. package/app/web/codexhost-settings.js +4472 -36194
  31. package/app/web/index.html +2 -2
  32. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  33. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +69 -69
  34. package/app/web/plugins/deepseek-ai__dsh-client-ui-approval/client.js +1 -1
  35. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +74 -74
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +75 -64
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +19 -16
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
  40. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +2 -2
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar/client.js +2 -2
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.js +9 -9
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-right/client.js +1 -1
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-theme/client.js +1 -1
  46. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
  47. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +3 -3
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +7 -7
  49. package/app/web/sw.js +8 -1
  50. package/app/web-modules/server.mjs +2682 -5540
  51. package/bin/codexhost +0 -0
  52. package/libexec/codexhost-shim +0 -0
  53. package/libexec/codexhost-updater +0 -0
  54. package/package.json +1 -1
  55. package/app/web/assets/index-DJW4bmyx.css +0 -1
  56. package/app/web/assets/index-Dyh1KzAB.js +0 -201
@@ -91,14 +91,14 @@ var require_polyfills = __commonJS({
91
91
  fs.fstatSync = statFixSync(fs.fstatSync);
92
92
  fs.lstatSync = statFixSync(fs.lstatSync);
93
93
  if (fs.chmod && !fs.lchmod) {
94
- fs.lchmod = function(path24, mode, cb) {
94
+ fs.lchmod = function(path22, mode, cb) {
95
95
  if (cb) process.nextTick(cb);
96
96
  };
97
97
  fs.lchmodSync = function() {
98
98
  };
99
99
  }
100
100
  if (fs.chown && !fs.lchown) {
101
- fs.lchown = function(path24, uid, gid, cb) {
101
+ fs.lchown = function(path22, uid, gid, cb) {
102
102
  if (cb) process.nextTick(cb);
103
103
  };
104
104
  fs.lchownSync = function() {
@@ -165,9 +165,9 @@ var require_polyfills = __commonJS({
165
165
  };
166
166
  })(fs.readSync);
167
167
  function patchLchmod(fs2) {
168
- fs2.lchmod = function(path24, mode, callback) {
168
+ fs2.lchmod = function(path22, mode, callback) {
169
169
  fs2.open(
170
- path24,
170
+ path22,
171
171
  constants2.O_WRONLY | constants2.O_SYMLINK,
172
172
  mode,
173
173
  function(err, fd) {
@@ -183,8 +183,8 @@ var require_polyfills = __commonJS({
183
183
  }
184
184
  );
185
185
  };
186
- fs2.lchmodSync = function(path24, mode) {
187
- var fd = fs2.openSync(path24, constants2.O_WRONLY | constants2.O_SYMLINK, mode);
186
+ fs2.lchmodSync = function(path22, mode) {
187
+ var fd = fs2.openSync(path22, constants2.O_WRONLY | constants2.O_SYMLINK, mode);
188
188
  var threw = true;
189
189
  var ret;
190
190
  try {
@@ -205,8 +205,8 @@ var require_polyfills = __commonJS({
205
205
  }
206
206
  function patchLutimes(fs2) {
207
207
  if (constants2.hasOwnProperty("O_SYMLINK") && fs2.futimes) {
208
- fs2.lutimes = function(path24, at, mt, cb) {
209
- fs2.open(path24, constants2.O_SYMLINK, function(er, fd) {
208
+ fs2.lutimes = function(path22, at, mt, cb) {
209
+ fs2.open(path22, constants2.O_SYMLINK, function(er, fd) {
210
210
  if (er) {
211
211
  if (cb) cb(er);
212
212
  return;
@@ -218,8 +218,8 @@ var require_polyfills = __commonJS({
218
218
  });
219
219
  });
220
220
  };
221
- fs2.lutimesSync = function(path24, at, mt) {
222
- var fd = fs2.openSync(path24, constants2.O_SYMLINK);
221
+ fs2.lutimesSync = function(path22, at, mt) {
222
+ var fd = fs2.openSync(path22, constants2.O_SYMLINK);
223
223
  var ret;
224
224
  var threw = true;
225
225
  try {
@@ -331,17 +331,17 @@ var require_polyfills = __commonJS({
331
331
  var require_legacy_streams = __commonJS({
332
332
  "node_modules/graceful-fs/legacy-streams.js"(exports, module) {
333
333
  var Stream = __require("stream").Stream;
334
- module.exports = legacy;
335
- function legacy(fs) {
334
+ module.exports = legacy2;
335
+ function legacy2(fs) {
336
336
  return {
337
337
  ReadStream,
338
338
  WriteStream
339
339
  };
340
- function ReadStream(path24, options) {
341
- if (!(this instanceof ReadStream)) return new ReadStream(path24, options);
340
+ function ReadStream(path22, options) {
341
+ if (!(this instanceof ReadStream)) return new ReadStream(path22, options);
342
342
  Stream.call(this);
343
343
  var self = this;
344
- this.path = path24;
344
+ this.path = path22;
345
345
  this.fd = null;
346
346
  this.readable = true;
347
347
  this.paused = false;
@@ -386,10 +386,10 @@ var require_legacy_streams = __commonJS({
386
386
  self._read();
387
387
  });
388
388
  }
389
- function WriteStream(path24, options) {
390
- if (!(this instanceof WriteStream)) return new WriteStream(path24, options);
389
+ function WriteStream(path22, options) {
390
+ if (!(this instanceof WriteStream)) return new WriteStream(path22, options);
391
391
  Stream.call(this);
392
- this.path = path24;
392
+ this.path = path22;
393
393
  this.fd = null;
394
394
  this.writable = true;
395
395
  this.flags = "w";
@@ -451,7 +451,7 @@ var require_graceful_fs = __commonJS({
451
451
  "node_modules/graceful-fs/graceful-fs.js"(exports, module) {
452
452
  var fs = __require("fs");
453
453
  var polyfills = require_polyfills();
454
- var legacy = require_legacy_streams();
454
+ var legacy2 = require_legacy_streams();
455
455
  var clone2 = require_clone();
456
456
  var util = __require("util");
457
457
  var gracefulQueue;
@@ -531,15 +531,15 @@ var require_graceful_fs = __commonJS({
531
531
  fs2.createReadStream = createReadStream2;
532
532
  fs2.createWriteStream = createWriteStream;
533
533
  var fs$readFile = fs2.readFile;
534
- fs2.readFile = readFile11;
535
- function readFile11(path24, options, cb) {
534
+ fs2.readFile = readFile10;
535
+ function readFile10(path22, options, cb) {
536
536
  if (typeof options === "function")
537
537
  cb = options, options = null;
538
- return go$readFile(path24, options, cb);
539
- function go$readFile(path25, options2, cb2, startTime) {
540
- return fs$readFile(path25, options2, function(err) {
538
+ return go$readFile(path22, options, cb);
539
+ function go$readFile(path23, options2, cb2, startTime) {
540
+ return fs$readFile(path23, options2, function(err) {
541
541
  if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
542
- enqueue([go$readFile, [path25, options2, cb2], err, startTime || Date.now(), Date.now()]);
542
+ enqueue([go$readFile, [path23, options2, cb2], err, startTime || Date.now(), Date.now()]);
543
543
  else {
544
544
  if (typeof cb2 === "function")
545
545
  cb2.apply(this, arguments);
@@ -549,14 +549,14 @@ var require_graceful_fs = __commonJS({
549
549
  }
550
550
  var fs$writeFile = fs2.writeFile;
551
551
  fs2.writeFile = writeFile6;
552
- function writeFile6(path24, data, options, cb) {
552
+ function writeFile6(path22, data, options, cb) {
553
553
  if (typeof options === "function")
554
554
  cb = options, options = null;
555
- return go$writeFile(path24, data, options, cb);
556
- function go$writeFile(path25, data2, options2, cb2, startTime) {
557
- return fs$writeFile(path25, data2, options2, function(err) {
555
+ return go$writeFile(path22, data, options, cb);
556
+ function go$writeFile(path23, data2, options2, cb2, startTime) {
557
+ return fs$writeFile(path23, data2, options2, function(err) {
558
558
  if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
559
- enqueue([go$writeFile, [path25, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
559
+ enqueue([go$writeFile, [path23, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
560
560
  else {
561
561
  if (typeof cb2 === "function")
562
562
  cb2.apply(this, arguments);
@@ -567,14 +567,14 @@ var require_graceful_fs = __commonJS({
567
567
  var fs$appendFile = fs2.appendFile;
568
568
  if (fs$appendFile)
569
569
  fs2.appendFile = appendFile;
570
- function appendFile(path24, data, options, cb) {
570
+ function appendFile(path22, data, options, cb) {
571
571
  if (typeof options === "function")
572
572
  cb = options, options = null;
573
- return go$appendFile(path24, data, options, cb);
574
- function go$appendFile(path25, data2, options2, cb2, startTime) {
575
- return fs$appendFile(path25, data2, options2, function(err) {
573
+ return go$appendFile(path22, data, options, cb);
574
+ function go$appendFile(path23, data2, options2, cb2, startTime) {
575
+ return fs$appendFile(path23, data2, options2, function(err) {
576
576
  if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
577
- enqueue([go$appendFile, [path25, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
577
+ enqueue([go$appendFile, [path23, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
578
578
  else {
579
579
  if (typeof cb2 === "function")
580
580
  cb2.apply(this, arguments);
@@ -603,33 +603,33 @@ var require_graceful_fs = __commonJS({
603
603
  }
604
604
  }
605
605
  var fs$readdir = fs2.readdir;
606
- fs2.readdir = readdir7;
606
+ fs2.readdir = readdir6;
607
607
  var noReaddirOptionVersions = /^v[0-5]\./;
608
- function readdir7(path24, options, cb) {
608
+ function readdir6(path22, options, cb) {
609
609
  if (typeof options === "function")
610
610
  cb = options, options = null;
611
- var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path25, options2, cb2, startTime) {
612
- return fs$readdir(path25, fs$readdirCallback(
613
- path25,
611
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path23, options2, cb2, startTime) {
612
+ return fs$readdir(path23, fs$readdirCallback(
613
+ path23,
614
614
  options2,
615
615
  cb2,
616
616
  startTime
617
617
  ));
618
- } : function go$readdir2(path25, options2, cb2, startTime) {
619
- return fs$readdir(path25, options2, fs$readdirCallback(
620
- path25,
618
+ } : function go$readdir2(path23, options2, cb2, startTime) {
619
+ return fs$readdir(path23, options2, fs$readdirCallback(
620
+ path23,
621
621
  options2,
622
622
  cb2,
623
623
  startTime
624
624
  ));
625
625
  };
626
- return go$readdir(path24, options, cb);
627
- function fs$readdirCallback(path25, options2, cb2, startTime) {
626
+ return go$readdir(path22, options, cb);
627
+ function fs$readdirCallback(path23, options2, cb2, startTime) {
628
628
  return function(err, files) {
629
629
  if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
630
630
  enqueue([
631
631
  go$readdir,
632
- [path25, options2, cb2],
632
+ [path23, options2, cb2],
633
633
  err,
634
634
  startTime || Date.now(),
635
635
  Date.now()
@@ -644,7 +644,7 @@ var require_graceful_fs = __commonJS({
644
644
  }
645
645
  }
646
646
  if (process.version.substr(0, 4) === "v0.8") {
647
- var legStreams = legacy(fs2);
647
+ var legStreams = legacy2(fs2);
648
648
  ReadStream = legStreams.ReadStream;
649
649
  WriteStream = legStreams.WriteStream;
650
650
  }
@@ -700,7 +700,7 @@ var require_graceful_fs = __commonJS({
700
700
  enumerable: true,
701
701
  configurable: true
702
702
  });
703
- function ReadStream(path24, options) {
703
+ function ReadStream(path22, options) {
704
704
  if (this instanceof ReadStream)
705
705
  return fs$ReadStream.apply(this, arguments), this;
706
706
  else
@@ -720,7 +720,7 @@ var require_graceful_fs = __commonJS({
720
720
  }
721
721
  });
722
722
  }
723
- function WriteStream(path24, options) {
723
+ function WriteStream(path22, options) {
724
724
  if (this instanceof WriteStream)
725
725
  return fs$WriteStream.apply(this, arguments), this;
726
726
  else
@@ -738,22 +738,22 @@ var require_graceful_fs = __commonJS({
738
738
  }
739
739
  });
740
740
  }
741
- function createReadStream2(path24, options) {
742
- return new fs2.ReadStream(path24, options);
741
+ function createReadStream2(path22, options) {
742
+ return new fs2.ReadStream(path22, options);
743
743
  }
744
- function createWriteStream(path24, options) {
745
- return new fs2.WriteStream(path24, options);
744
+ function createWriteStream(path22, options) {
745
+ return new fs2.WriteStream(path22, options);
746
746
  }
747
747
  var fs$open = fs2.open;
748
748
  fs2.open = open7;
749
- function open7(path24, flags, mode, cb) {
749
+ function open7(path22, flags, mode, cb) {
750
750
  if (typeof mode === "function")
751
751
  cb = mode, mode = null;
752
- return go$open(path24, flags, mode, cb);
753
- function go$open(path25, flags2, mode2, cb2, startTime) {
754
- return fs$open(path25, flags2, mode2, function(err, fd) {
752
+ return go$open(path22, flags, mode, cb);
753
+ function go$open(path23, flags2, mode2, cb2, startTime) {
754
+ return fs$open(path23, flags2, mode2, function(err, fd) {
755
755
  if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
756
- enqueue([go$open, [path25, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
756
+ enqueue([go$open, [path23, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
757
757
  else {
758
758
  if (typeof cb2 === "function")
759
759
  cb2.apply(this, arguments);
@@ -994,21 +994,21 @@ var require_retry = __commonJS({
994
994
  timeout = Math.min(timeout, opts.maxTimeout);
995
995
  return timeout;
996
996
  };
997
- exports.wrap = function(obj, options, methods) {
997
+ exports.wrap = function(obj, options, methods3) {
998
998
  if (options instanceof Array) {
999
- methods = options;
999
+ methods3 = options;
1000
1000
  options = null;
1001
1001
  }
1002
- if (!methods) {
1003
- methods = [];
1002
+ if (!methods3) {
1003
+ methods3 = [];
1004
1004
  for (var key in obj) {
1005
1005
  if (typeof obj[key] === "function") {
1006
- methods.push(key);
1006
+ methods3.push(key);
1007
1007
  }
1008
1008
  }
1009
1009
  }
1010
- for (var i = 0; i < methods.length; i++) {
1011
- var method = methods[i];
1010
+ for (var i = 0; i < methods3.length; i++) {
1011
+ var method = methods3[i];
1012
1012
  var original = obj[method];
1013
1013
  obj[method] = function retryWrapper(original2) {
1014
1014
  var op = exports.operation(options);
@@ -1244,11 +1244,11 @@ var require_mtime_precision = __commonJS({
1244
1244
  function probe(file2, fs, callback) {
1245
1245
  const cachedPrecision = fs[cacheSymbol];
1246
1246
  if (cachedPrecision) {
1247
- return fs.stat(file2, (err, stat6) => {
1247
+ return fs.stat(file2, (err, stat5) => {
1248
1248
  if (err) {
1249
1249
  return callback(err);
1250
1250
  }
1251
- callback(null, stat6.mtime, cachedPrecision);
1251
+ callback(null, stat5.mtime, cachedPrecision);
1252
1252
  });
1253
1253
  }
1254
1254
  const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
@@ -1256,13 +1256,13 @@ var require_mtime_precision = __commonJS({
1256
1256
  if (err) {
1257
1257
  return callback(err);
1258
1258
  }
1259
- fs.stat(file2, (err2, stat6) => {
1259
+ fs.stat(file2, (err2, stat5) => {
1260
1260
  if (err2) {
1261
1261
  return callback(err2);
1262
1262
  }
1263
- const precision = stat6.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
1263
+ const precision = stat5.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
1264
1264
  Object.defineProperty(fs, cacheSymbol, { value: precision });
1265
- callback(null, stat6.mtime, precision);
1265
+ callback(null, stat5.mtime, precision);
1266
1266
  });
1267
1267
  });
1268
1268
  }
@@ -1282,7 +1282,7 @@ var require_mtime_precision = __commonJS({
1282
1282
  var require_lockfile = __commonJS({
1283
1283
  "node_modules/proper-lockfile/lib/lockfile.js"(exports, module) {
1284
1284
  "use strict";
1285
- var path24 = __require("path");
1285
+ var path22 = __require("path");
1286
1286
  var fs = require_graceful_fs();
1287
1287
  var retry = require_retry2();
1288
1288
  var onExit = require_signal_exit();
@@ -1293,7 +1293,7 @@ var require_lockfile = __commonJS({
1293
1293
  }
1294
1294
  function resolveCanonicalPath(file2, options, callback) {
1295
1295
  if (!options.realpath) {
1296
- return callback(null, path24.resolve(file2));
1296
+ return callback(null, path22.resolve(file2));
1297
1297
  }
1298
1298
  options.fs.realpath(file2, callback);
1299
1299
  }
@@ -1316,14 +1316,14 @@ var require_lockfile = __commonJS({
1316
1316
  if (options.stale <= 0) {
1317
1317
  return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file: file2 }));
1318
1318
  }
1319
- options.fs.stat(lockfilePath, (err2, stat6) => {
1319
+ options.fs.stat(lockfilePath, (err2, stat5) => {
1320
1320
  if (err2) {
1321
1321
  if (err2.code === "ENOENT") {
1322
1322
  return acquireLock(file2, { ...options, stale: 0 }, callback);
1323
1323
  }
1324
1324
  return callback(err2);
1325
1325
  }
1326
- if (!isLockStale(stat6, options)) {
1326
+ if (!isLockStale(stat5, options)) {
1327
1327
  return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file: file2 }));
1328
1328
  }
1329
1329
  removeLock(file2, options, (err3) => {
@@ -1335,8 +1335,8 @@ var require_lockfile = __commonJS({
1335
1335
  });
1336
1336
  });
1337
1337
  }
1338
- function isLockStale(stat6, options) {
1339
- return stat6.mtime.getTime() < Date.now() - options.stale;
1338
+ function isLockStale(stat5, options) {
1339
+ return stat5.mtime.getTime() < Date.now() - options.stale;
1340
1340
  }
1341
1341
  function removeLock(file2, options, callback) {
1342
1342
  options.fs.rmdir(getLockFile(file2, options), (err) => {
@@ -1354,7 +1354,7 @@ var require_lockfile = __commonJS({
1354
1354
  lock2.updateDelay = lock2.updateDelay || options.update;
1355
1355
  lock2.updateTimeout = setTimeout(() => {
1356
1356
  lock2.updateTimeout = null;
1357
- options.fs.stat(lock2.lockfilePath, (err, stat6) => {
1357
+ options.fs.stat(lock2.lockfilePath, (err, stat5) => {
1358
1358
  const isOverThreshold = lock2.lastUpdate + options.stale < Date.now();
1359
1359
  if (err) {
1360
1360
  if (err.code === "ENOENT" || isOverThreshold) {
@@ -1363,7 +1363,7 @@ var require_lockfile = __commonJS({
1363
1363
  lock2.updateDelay = 1e3;
1364
1364
  return updateLock(file2, options);
1365
1365
  }
1366
- const isMtimeOurs = lock2.mtime.getTime() === stat6.mtime.getTime();
1366
+ const isMtimeOurs = lock2.mtime.getTime() === stat5.mtime.getTime();
1367
1367
  if (!isMtimeOurs) {
1368
1368
  return setLockAsCompromised(
1369
1369
  file2,
@@ -1476,7 +1476,7 @@ var require_lockfile = __commonJS({
1476
1476
  removeLock(file3, options, callback);
1477
1477
  });
1478
1478
  }
1479
- function check3(file2, options, callback) {
1479
+ function check2(file2, options, callback) {
1480
1480
  options = {
1481
1481
  stale: 1e4,
1482
1482
  realpath: true,
@@ -1488,11 +1488,11 @@ var require_lockfile = __commonJS({
1488
1488
  if (err) {
1489
1489
  return callback(err);
1490
1490
  }
1491
- options.fs.stat(getLockFile(file3, options), (err2, stat6) => {
1491
+ options.fs.stat(getLockFile(file3, options), (err2, stat5) => {
1492
1492
  if (err2) {
1493
1493
  return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
1494
1494
  }
1495
- return callback(null, !isLockStale(stat6, options));
1495
+ return callback(null, !isLockStale(stat5, options));
1496
1496
  });
1497
1497
  });
1498
1498
  }
@@ -1510,7 +1510,7 @@ var require_lockfile = __commonJS({
1510
1510
  });
1511
1511
  module.exports.lock = lock;
1512
1512
  module.exports.unlock = unlock;
1513
- module.exports.check = check3;
1513
+ module.exports.check = check2;
1514
1514
  module.exports.getLocks = getLocks;
1515
1515
  }
1516
1516
  });
@@ -1521,9 +1521,9 @@ var require_adapter = __commonJS({
1521
1521
  "use strict";
1522
1522
  var fs = require_graceful_fs();
1523
1523
  function createSyncFs(fs2) {
1524
- const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
1524
+ const methods3 = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
1525
1525
  const newFs = { ...fs2 };
1526
- methods.forEach((method) => {
1526
+ methods3.forEach((method) => {
1527
1527
  newFs[method] = (...args) => {
1528
1528
  const callback = args.pop();
1529
1529
  let ret;
@@ -1600,7 +1600,7 @@ var require_proper_lockfile = __commonJS({
1600
1600
  function unlockSync(file2, options) {
1601
1601
  return toSync(lockfile2.unlock)(file2, toSyncOptions(options));
1602
1602
  }
1603
- function check3(file2, options) {
1603
+ function check2(file2, options) {
1604
1604
  return toPromise(lockfile2.check)(file2, options);
1605
1605
  }
1606
1606
  function checkSync(file2, options) {
@@ -1611,13 +1611,13 @@ var require_proper_lockfile = __commonJS({
1611
1611
  module.exports.unlock = unlock;
1612
1612
  module.exports.lockSync = lockSync;
1613
1613
  module.exports.unlockSync = unlockSync;
1614
- module.exports.check = check3;
1614
+ module.exports.check = check2;
1615
1615
  module.exports.checkSync = checkSync;
1616
1616
  }
1617
1617
  });
1618
1618
 
1619
1619
  // packages/console-server/src/main.ts
1620
- import path23 from "node:path";
1620
+ import path21 from "node:path";
1621
1621
  import { fileURLToPath } from "node:url";
1622
1622
 
1623
1623
  // packages/update-manager/dist/runtime-metadata.js
@@ -1867,8 +1867,8 @@ function selectInstallerReleaseArtifact(release, target2) {
1867
1867
  if (!asset)
1868
1868
  throw new Error(`GitHub Release must contain exactly one ${name}`);
1869
1869
  const digest = asset.digest === null ? null : SHA256_DIGEST_PATTERN.exec(asset.digest);
1870
- const sha256 = digest?.[1];
1871
- if (!sha256)
1870
+ const sha2562 = digest?.[1];
1871
+ if (!sha2562)
1872
1872
  throw new Error(`GitHub Release asset ${name} has no valid SHA-256 digest`);
1873
1873
  const expectedPrefix = `${DOWNLOAD_URL_PREFIX}v${release.version}/`;
1874
1874
  if (!asset.downloadUrl.startsWith(expectedPrefix) || !asset.downloadUrl.endsWith(`/${name}`)) {
@@ -1876,7 +1876,7 @@ function selectInstallerReleaseArtifact(release, target2) {
1876
1876
  }
1877
1877
  return Object.freeze({
1878
1878
  name,
1879
- source: Object.freeze({ url: asset.downloadUrl, sha256, size: asset.size })
1879
+ source: Object.freeze({ url: asset.downloadUrl, sha256: sha2562, size: asset.size })
1880
1880
  });
1881
1881
  }
1882
1882
 
@@ -1963,9 +1963,9 @@ import path4 from "node:path";
1963
1963
  var LOCK_FILE = "active-update-v1.lock";
1964
1964
  var STATUS_FILE = "status-v1.json";
1965
1965
  var TERMINAL_PHASES = /* @__PURE__ */ new Set(["succeeded", "failed"]);
1966
- async function regularFile(filePath) {
1966
+ async function regularFile(filePath2) {
1967
1967
  try {
1968
- const metadata = await lstat(filePath);
1968
+ const metadata = await lstat(filePath2);
1969
1969
  return metadata.isFile() && !metadata.isSymbolicLink();
1970
1970
  } catch (error51) {
1971
1971
  if (error51.code === "ENOENT")
@@ -2217,18 +2217,18 @@ async function downloadArtifact(source, destination, onProgress) {
2217
2217
  }
2218
2218
  return { bytes, finalUrl: finalUrl.toString() };
2219
2219
  }
2220
- async function sha256File(filePath) {
2220
+ async function sha256File(filePath2) {
2221
2221
  const hash2 = createHash("sha256");
2222
2222
  await new Promise((resolve, reject) => {
2223
- const stream = createReadStream(filePath);
2223
+ const stream = createReadStream(filePath2);
2224
2224
  stream.on("data", (chunk) => hash2.update(chunk));
2225
2225
  stream.once("error", reject);
2226
2226
  stream.once("end", resolve);
2227
2227
  });
2228
2228
  return hash2.digest("hex");
2229
2229
  }
2230
- async function verifyDownloadedArtifact(source, filePath, result) {
2231
- const metadata = await lstat2(filePath);
2230
+ async function verifyDownloadedArtifact(source, filePath2, result) {
2231
+ const metadata = await lstat2(filePath2);
2232
2232
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size === 0) {
2233
2233
  throw new Error("downloaded update artifact is not a non-empty regular file");
2234
2234
  }
@@ -2238,7 +2238,7 @@ async function verifyDownloadedArtifact(source, filePath, result) {
2238
2238
  if (source.size !== void 0 && metadata.size !== source.size) {
2239
2239
  throw new Error(`update artifact size mismatch: expected ${source.size}, got ${metadata.size}`);
2240
2240
  }
2241
- const actual = await sha256File(filePath);
2241
+ const actual = await sha256File(filePath2);
2242
2242
  if (actual !== source.sha256) {
2243
2243
  throw new Error(`update artifact SHA-256 mismatch: expected ${source.sha256}, got ${actual}`);
2244
2244
  }
@@ -2246,7 +2246,7 @@ async function verifyDownloadedArtifact(source, filePath, result) {
2246
2246
 
2247
2247
  // packages/update-manager/dist/updater-ready.js
2248
2248
  import { setTimeout as delay } from "node:timers/promises";
2249
- async function waitForUpdaterReady(child, readStatus2, timeoutMs = 1e4, beforeWait) {
2249
+ async function waitForUpdaterReady(child, readStatus, timeoutMs = 1e4, beforeWait) {
2250
2250
  let failure;
2251
2251
  const onError = (error51) => {
2252
2252
  failure = error51;
@@ -2260,7 +2260,7 @@ async function waitForUpdaterReady(child, readStatus2, timeoutMs = 1e4, beforeWa
2260
2260
  try {
2261
2261
  await beforeWait?.();
2262
2262
  while (true) {
2263
- const status = await readStatus2();
2263
+ const status = await readStatus();
2264
2264
  if (status?.phase === "failed")
2265
2265
  throw new Error(status.error ?? "Background Updater failed");
2266
2266
  if (failure)
@@ -2322,14 +2322,14 @@ function requireAbsolutePath(value, label) {
2322
2322
  return path5.normalize(value);
2323
2323
  }
2324
2324
  async function requireRegularFile(value, label) {
2325
- const filePath = requireAbsolutePath(value, label);
2326
- const metadata = await lstat3(filePath).catch((error51) => {
2325
+ const filePath2 = requireAbsolutePath(value, label);
2326
+ const metadata = await lstat3(filePath2).catch((error51) => {
2327
2327
  throw new Error(`${label} is unavailable: ${errorMessage(error51)}`);
2328
2328
  });
2329
2329
  if (!metadata.isFile() || metadata.isSymbolicLink()) {
2330
2330
  throw new Error(`${label} must be a regular file`);
2331
2331
  }
2332
- return filePath;
2332
+ return filePath2;
2333
2333
  }
2334
2334
  function requireLauncherPid(value) {
2335
2335
  if (!Number.isSafeInteger(value) || value <= 0) {
@@ -2337,8 +2337,8 @@ function requireLauncherPid(value) {
2337
2337
  }
2338
2338
  return value;
2339
2339
  }
2340
- async function writePrivateJson(filePath, value) {
2341
- await writeFile2(filePath, `${JSON.stringify(value)}
2340
+ async function writePrivateJson(filePath2, value) {
2341
+ await writeFile2(filePath2, `${JSON.stringify(value)}
2342
2342
  `, {
2343
2343
  encoding: "utf8",
2344
2344
  mode: 384,
@@ -2575,7 +2575,7 @@ function createBackgroundUpdateManager(dependencies = {}) {
2575
2575
  }
2576
2576
 
2577
2577
  // packages/console-server/src/harnesses.ts
2578
- import path14 from "node:path";
2578
+ import path12 from "node:path";
2579
2579
 
2580
2580
  // packages/harness-plugin-files/dist/discovery.js
2581
2581
  import { readdir as readdir2, realpath as realpath2 } from "node:fs/promises";
@@ -3347,10 +3347,10 @@ function mergeDefs(...defs) {
3347
3347
  function cloneDef(schema) {
3348
3348
  return mergeDefs(schema._zod.def);
3349
3349
  }
3350
- function getElementAtPath(obj, path24) {
3351
- if (!path24)
3350
+ function getElementAtPath(obj, path22) {
3351
+ if (!path22)
3352
3352
  return obj;
3353
- return path24.reduce((acc, key) => acc?.[key], obj);
3353
+ return path22.reduce((acc, key) => acc?.[key], obj);
3354
3354
  }
3355
3355
  function promiseAllObject(promisesObj) {
3356
3356
  const keys = Object.keys(promisesObj);
@@ -3759,11 +3759,11 @@ function explicitlyAborted(x, startIndex = 0) {
3759
3759
  }
3760
3760
  return false;
3761
3761
  }
3762
- function prefixIssues(path24, issues) {
3762
+ function prefixIssues(path22, issues) {
3763
3763
  return issues.map((iss) => {
3764
3764
  var _a3;
3765
3765
  (_a3 = iss).path ?? (_a3.path = []);
3766
- iss.path.unshift(path24);
3766
+ iss.path.unshift(path22);
3767
3767
  return iss;
3768
3768
  });
3769
3769
  }
@@ -3834,8 +3834,8 @@ function cleanEnum(obj) {
3834
3834
  return Number.isNaN(Number.parseInt(k, 10));
3835
3835
  }).map((el) => el[1]);
3836
3836
  }
3837
- function base64ToUint8Array(base643) {
3838
- const binaryString = atob(base643);
3837
+ function base64ToUint8Array(base644) {
3838
+ const binaryString = atob(base644);
3839
3839
  const bytes = new Uint8Array(binaryString.length);
3840
3840
  for (let i = 0; i < binaryString.length; i++) {
3841
3841
  bytes[i] = binaryString.charCodeAt(i);
@@ -3850,9 +3850,9 @@ function uint8ArrayToBase64(bytes) {
3850
3850
  return btoa(binaryString);
3851
3851
  }
3852
3852
  function base64urlToUint8Array(base64url3) {
3853
- const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
3854
- const padding = "=".repeat((4 - base643.length % 4) % 4);
3855
- return base64ToUint8Array(base643 + padding);
3853
+ const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
3854
+ const padding = "=".repeat((4 - base644.length % 4) % 4);
3855
+ return base64ToUint8Array(base644 + padding);
3856
3856
  }
3857
3857
  function uint8ArrayToBase64url(bytes) {
3858
3858
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
@@ -3910,16 +3910,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
3910
3910
  }
3911
3911
  function formatError(error51, mapper = (issue2) => issue2.message) {
3912
3912
  const fieldErrors = { _errors: [] };
3913
- const processError = (error52, path24 = []) => {
3913
+ const processError = (error52, path22 = []) => {
3914
3914
  for (const issue2 of error52.issues) {
3915
3915
  if (issue2.code === "invalid_union" && issue2.errors.length) {
3916
- issue2.errors.map((issues) => processError({ issues }, [...path24, ...issue2.path]));
3916
+ issue2.errors.map((issues) => processError({ issues }, [...path22, ...issue2.path]));
3917
3917
  } else if (issue2.code === "invalid_key") {
3918
- processError({ issues: issue2.issues }, [...path24, ...issue2.path]);
3918
+ processError({ issues: issue2.issues }, [...path22, ...issue2.path]);
3919
3919
  } else if (issue2.code === "invalid_element") {
3920
- processError({ issues: issue2.issues }, [...path24, ...issue2.path]);
3920
+ processError({ issues: issue2.issues }, [...path22, ...issue2.path]);
3921
3921
  } else {
3922
- const fullpath = [...path24, ...issue2.path];
3922
+ const fullpath = [...path22, ...issue2.path];
3923
3923
  if (fullpath.length === 0) {
3924
3924
  fieldErrors._errors.push(mapper(issue2));
3925
3925
  } else {
@@ -3946,17 +3946,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
3946
3946
  }
3947
3947
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
3948
3948
  const result = { errors: [] };
3949
- const processError = (error52, path24 = []) => {
3949
+ const processError = (error52, path22 = []) => {
3950
3950
  var _a3, _b;
3951
3951
  for (const issue2 of error52.issues) {
3952
3952
  if (issue2.code === "invalid_union" && issue2.errors.length) {
3953
- issue2.errors.map((issues) => processError({ issues }, [...path24, ...issue2.path]));
3953
+ issue2.errors.map((issues) => processError({ issues }, [...path22, ...issue2.path]));
3954
3954
  } else if (issue2.code === "invalid_key") {
3955
- processError({ issues: issue2.issues }, [...path24, ...issue2.path]);
3955
+ processError({ issues: issue2.issues }, [...path22, ...issue2.path]);
3956
3956
  } else if (issue2.code === "invalid_element") {
3957
- processError({ issues: issue2.issues }, [...path24, ...issue2.path]);
3957
+ processError({ issues: issue2.issues }, [...path22, ...issue2.path]);
3958
3958
  } else {
3959
- const fullpath = [...path24, ...issue2.path];
3959
+ const fullpath = [...path22, ...issue2.path];
3960
3960
  if (fullpath.length === 0) {
3961
3961
  result.errors.push(mapper(issue2));
3962
3962
  continue;
@@ -3988,8 +3988,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
3988
3988
  }
3989
3989
  function toDotPath(_path) {
3990
3990
  const segs = [];
3991
- const path24 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
3992
- for (const seg of path24) {
3991
+ const path22 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
3992
+ for (const seg of path22) {
3993
3993
  if (typeof seg === "number")
3994
3994
  segs.push(`[${seg}]`);
3995
3995
  else if (typeof seg === "symbol")
@@ -5218,8 +5218,8 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
5218
5218
  function isValidBase64URL(data) {
5219
5219
  if (!base64url.test(data))
5220
5220
  return false;
5221
- const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
5222
- const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
5221
+ const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
5222
+ const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "=");
5223
5223
  return isValidBase64(padded);
5224
5224
  }
5225
5225
  var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
@@ -5673,42 +5673,42 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
5673
5673
  }
5674
5674
  doc.write(`const newResult = {};`);
5675
5675
  for (const key of normalized.keys) {
5676
- const id = ids[key];
5676
+ const id2 = ids[key];
5677
5677
  const k = esc(key);
5678
5678
  const schema = shape[key];
5679
5679
  const isOptionalIn = schema?._zod?.optin === "optional";
5680
5680
  const isOptionalOut = schema?._zod?.optout === "optional";
5681
- doc.write(`const ${id} = ${parseStr(key)};`);
5681
+ doc.write(`const ${id2} = ${parseStr(key)};`);
5682
5682
  if (isOptionalIn && isOptionalOut) {
5683
5683
  doc.write(`
5684
- if (${id}.issues.length) {
5684
+ if (${id2}.issues.length) {
5685
5685
  if (${k} in input) {
5686
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
5686
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
5687
5687
  ...iss,
5688
5688
  path: iss.path ? [${k}, ...iss.path] : [${k}]
5689
5689
  })));
5690
5690
  }
5691
5691
  }
5692
5692
 
5693
- if (${id}.value === undefined) {
5693
+ if (${id2}.value === undefined) {
5694
5694
  if (${k} in input) {
5695
5695
  newResult[${k}] = undefined;
5696
5696
  }
5697
5697
  } else {
5698
- newResult[${k}] = ${id}.value;
5698
+ newResult[${k}] = ${id2}.value;
5699
5699
  }
5700
5700
 
5701
5701
  `);
5702
5702
  } else if (!isOptionalIn) {
5703
5703
  doc.write(`
5704
- const ${id}_present = ${k} in input;
5705
- if (${id}.issues.length) {
5706
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
5704
+ const ${id2}_present = ${k} in input;
5705
+ if (${id2}.issues.length) {
5706
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
5707
5707
  ...iss,
5708
5708
  path: iss.path ? [${k}, ...iss.path] : [${k}]
5709
5709
  })));
5710
5710
  }
5711
- if (!${id}_present && !${id}.issues.length) {
5711
+ if (!${id2}_present && !${id2}.issues.length) {
5712
5712
  payload.issues.push({
5713
5713
  code: "invalid_type",
5714
5714
  expected: "nonoptional",
@@ -5717,30 +5717,30 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
5717
5717
  });
5718
5718
  }
5719
5719
 
5720
- if (${id}_present) {
5721
- if (${id}.value === undefined) {
5720
+ if (${id2}_present) {
5721
+ if (${id2}.value === undefined) {
5722
5722
  newResult[${k}] = undefined;
5723
5723
  } else {
5724
- newResult[${k}] = ${id}.value;
5724
+ newResult[${k}] = ${id2}.value;
5725
5725
  }
5726
5726
  }
5727
5727
 
5728
5728
  `);
5729
5729
  } else {
5730
5730
  doc.write(`
5731
- if (${id}.issues.length) {
5732
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
5731
+ if (${id2}.issues.length) {
5732
+ payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
5733
5733
  ...iss,
5734
5734
  path: iss.path ? [${k}, ...iss.path] : [${k}]
5735
5735
  })));
5736
5736
  }
5737
5737
 
5738
- if (${id}.value === undefined) {
5738
+ if (${id2}.value === undefined) {
5739
5739
  if (${k} in input) {
5740
5740
  newResult[${k}] = undefined;
5741
5741
  }
5742
5742
  } else {
5743
- newResult[${k}] = ${id}.value;
5743
+ newResult[${k}] = ${id2}.value;
5744
5744
  }
5745
5745
 
5746
5746
  `);
@@ -14072,26 +14072,26 @@ function extractDefs(ctx, schema) {
14072
14072
  throw new Error("Unprocessed schema. This is a bug in Zod.");
14073
14073
  const idToSchema = /* @__PURE__ */ new Map();
14074
14074
  for (const entry of ctx.seen.entries()) {
14075
- const id = ctx.metadataRegistry.get(entry[0])?.id;
14076
- if (id) {
14077
- const existing = idToSchema.get(id);
14075
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
14076
+ if (id2) {
14077
+ const existing = idToSchema.get(id2);
14078
14078
  if (existing && existing !== entry[0]) {
14079
- throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
14079
+ throw new Error(`Duplicate schema id "${id2}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
14080
14080
  }
14081
- idToSchema.set(id, entry[0]);
14081
+ idToSchema.set(id2, entry[0]);
14082
14082
  }
14083
14083
  }
14084
14084
  const makeURI = (entry) => {
14085
14085
  const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
14086
14086
  if (ctx.external) {
14087
14087
  const externalId = ctx.external.registry.get(entry[0])?.id;
14088
- const uriGenerator = ctx.external.uri ?? ((id2) => id2);
14088
+ const uriGenerator = ctx.external.uri ?? ((id3) => id3);
14089
14089
  if (externalId) {
14090
14090
  return { ref: uriGenerator(externalId) };
14091
14091
  }
14092
- const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
14093
- entry[1].defId = id;
14094
- return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
14092
+ const id2 = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
14093
+ entry[1].defId = id2;
14094
+ return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id2}` };
14095
14095
  }
14096
14096
  if (entry[1] === root) {
14097
14097
  return { ref: "#" };
@@ -14139,8 +14139,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
14139
14139
  continue;
14140
14140
  }
14141
14141
  }
14142
- const id = ctx.metadataRegistry.get(entry[0])?.id;
14143
- if (id) {
14142
+ const id2 = ctx.metadataRegistry.get(entry[0])?.id;
14143
+ if (id2) {
14144
14144
  extractToDef(entry);
14145
14145
  continue;
14146
14146
  }
@@ -14236,10 +14236,10 @@ function finalize(ctx, schema) {
14236
14236
  } else {
14237
14237
  }
14238
14238
  if (ctx.external?.uri) {
14239
- const id = ctx.external.registry.get(schema)?.id;
14240
- if (!id)
14239
+ const id2 = ctx.external.registry.get(schema)?.id;
14240
+ if (!id2)
14241
14241
  throw new Error("Schema is missing an `id` property");
14242
- result.$id = ctx.external.uri(id);
14242
+ result.$id = ctx.external.uri(id2);
14243
14243
  }
14244
14244
  Object.assign(result, root.def ?? root.schema);
14245
14245
  const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
@@ -14399,9 +14399,9 @@ var numberProcessor = (schema, ctx, _json, _params) => {
14399
14399
  json2.type = "number";
14400
14400
  const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
14401
14401
  const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
14402
- const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
14402
+ const legacy2 = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
14403
14403
  if (exMin) {
14404
- if (legacy) {
14404
+ if (legacy2) {
14405
14405
  json2.minimum = exclusiveMinimum;
14406
14406
  json2.exclusiveMinimum = true;
14407
14407
  } else {
@@ -14411,7 +14411,7 @@ var numberProcessor = (schema, ctx, _json, _params) => {
14411
14411
  json2.minimum = minimum;
14412
14412
  }
14413
14413
  if (exMax) {
14414
- if (legacy) {
14414
+ if (legacy2) {
14415
14415
  json2.maximum = exclusiveMaximum;
14416
14416
  json2.exclusiveMaximum = true;
14417
14417
  } else {
@@ -15273,7 +15273,7 @@ var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
15273
15273
 
15274
15274
  // node_modules/zod/v4/classic/schemas.js
15275
15275
  var _installedGroups = /* @__PURE__ */ new WeakMap();
15276
- function _installLazyMethods(inst, group, methods) {
15276
+ function _installLazyMethods(inst, group, methods3) {
15277
15277
  const proto = Object.getPrototypeOf(inst);
15278
15278
  let installed = _installedGroups.get(proto);
15279
15279
  if (!installed) {
@@ -15283,8 +15283,8 @@ function _installLazyMethods(inst, group, methods) {
15283
15283
  if (installed.has(group))
15284
15284
  return;
15285
15285
  installed.add(group);
15286
- for (const key in methods) {
15287
- const fn = methods[key];
15286
+ for (const key in methods3) {
15287
+ const fn = methods3[key];
15288
15288
  Object.defineProperty(proto, key, {
15289
15289
  configurable: true,
15290
15290
  enumerable: false,
@@ -15357,8 +15357,8 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
15357
15357
  reg.add(this, meta3);
15358
15358
  return this;
15359
15359
  },
15360
- refine(check3, params) {
15361
- return this.check(refine(check3, params));
15360
+ refine(check2, params) {
15361
+ return this.check(refine(check2, params));
15362
15362
  },
15363
15363
  superRefine(refinement, params) {
15364
15364
  return this.check(superRefine(refinement, params));
@@ -16681,13 +16681,13 @@ function resolveRef(ref, ctx) {
16681
16681
  if (!ref.startsWith("#")) {
16682
16682
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
16683
16683
  }
16684
- const path24 = ref.slice(1).split("/").filter(Boolean);
16685
- if (path24.length === 0) {
16684
+ const path22 = ref.slice(1).split("/").filter(Boolean);
16685
+ if (path22.length === 0) {
16686
16686
  return ctx.rootSchema;
16687
16687
  }
16688
16688
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
16689
- if (path24[0] === defsKey) {
16690
- const key = path24[1];
16689
+ if (path22[0] === defsKey) {
16690
+ const key = path22[1];
16691
16691
  if (!key || !ctx.defs[key]) {
16692
16692
  throw new Error(`Reference not found: ${ref}`);
16693
16693
  }
@@ -17095,87 +17095,6 @@ function date4(params) {
17095
17095
  // node_modules/zod/v4/classic/external.js
17096
17096
  config(en_default());
17097
17097
 
17098
- // packages/shared-contracts/dist/ids.js
17099
- var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
17100
- message: "Identifier must not be empty or whitespace"
17101
- });
17102
- var harnessIdSchema = opaqueIdSchema.brand();
17103
- var hostThreadIdSchema = opaqueIdSchema.brand();
17104
- var hostTurnIdSchema = opaqueIdSchema.brand();
17105
- var hostItemIdSchema = opaqueIdSchema.brand();
17106
- var hostInteractionIdSchema = opaqueIdSchema.brand();
17107
-
17108
- // packages/shared-contracts/dist/harness-plugins.js
17109
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
17110
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
17111
- var HARNESS_PLUGIN_LIMIT = 128;
17112
- var installedPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u);
17113
- var installedHarnessPluginIdSchema = installedPluginIdSchema.pipe(harnessIdSchema);
17114
- var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id) => id !== "codex", "The official Codex identity is reserved");
17115
- var pluginRelativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
17116
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
17117
- var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
17118
- var harnessInstallationGuideSchema = external_exports.object({
17119
- commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
17120
- before: localizedTextSchema.optional(),
17121
- after: localizedTextSchema.optional(),
17122
- downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
17123
- }).strict();
17124
- var pluginPresentationShape = {
17125
- id: installedHarnessPluginIdSchema,
17126
- name: external_exports.string().trim().min(1).max(128),
17127
- version: external_exports.string().min(1).max(128),
17128
- /** Capability-only plugin; omitted for existing session-capable plugins. */
17129
- kind: external_exports.literal("usage").optional(),
17130
- /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
17131
- iconStyle: external_exports.object({
17132
- vector: external_exports.object({
17133
- viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
17134
- color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
17135
- paths: external_exports.array(external_exports.object({
17136
- d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
17137
- fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
17138
- fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
17139
- }).strict()).min(1).max(32)
17140
- }).strict().optional(),
17141
- background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
17142
- borderRadius: external_exports.number().min(0).max(50).optional(),
17143
- paddingRatio: external_exports.number().min(0).max(0.25).optional()
17144
- }).strict().optional(),
17145
- installation: harnessInstallationGuideSchema.optional(),
17146
- notice: localizedTextSchema.optional(),
17147
- /** The factory accepts a persisted local entrypoint through its construction context. */
17148
- launchCommand: external_exports.literal(true).optional(),
17149
- links: external_exports.object({
17150
- website: documentationUrlSchema.optional(),
17151
- documentation: documentationUrlSchema.optional(),
17152
- installation: documentationUrlSchema.optional()
17153
- }).strict().optional()
17154
- };
17155
- var harnessPluginManifestSchema = external_exports.object({
17156
- manifestVersion: external_exports.literal(1),
17157
- ...pluginPresentationShape,
17158
- adapterApiVersion: external_exports.number().int().positive(),
17159
- entry: pluginRelativeResourceSchema,
17160
- icon: pluginRelativeResourceSchema.optional()
17161
- }).strict();
17162
- var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
17163
- var harnessPluginDescriptorSchema = external_exports.object({
17164
- ...pluginPresentationShape,
17165
- icon: harnessPluginIconSchema.optional()
17166
- }).strict();
17167
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
17168
- var harnessPluginListResultSchema = external_exports.object({
17169
- plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
17170
- }).strict();
17171
- var harnessPluginConfigurationSchema = external_exports.object({
17172
- version: external_exports.literal(1),
17173
- enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
17174
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
17175
- message: "Enabled plugin IDs must be unique",
17176
- path: ["enabled"]
17177
- });
17178
-
17179
17098
  // packages/shared-contracts/dist/json-value.js
17180
17099
  function rejectExplicitUndefined(keys) {
17181
17100
  return (value, context) => {
@@ -17235,436 +17154,73 @@ var jsonValueSchema = nonCircularSchema.pipe(recursiveJsonValueSchema);
17235
17154
  var jsonArraySchema = nonCircularSchema.pipe(external_exports.array(recursiveJsonValueSchema));
17236
17155
  var jsonObjectSchema = nonCircularSchema.pipe(external_exports.record(external_exports.string(), recursiveJsonValueSchema));
17237
17156
 
17238
- // packages/shared-contracts/dist/desktop-extensions.js
17239
- var DESKTOP_EXTENSION_API_VERSION = 1;
17240
- var DESKTOP_EXTENSION_LIMIT = 64;
17241
- var DESKTOP_EXTENSION_ZIP_MAX_BYTES = 64 * 1024 * 1024;
17242
- var DESKTOP_EXTENSION_ZIP_MAX_BASE64_LENGTH = 4 * Math.ceil(DESKTOP_EXTENSION_ZIP_MAX_BYTES / 3);
17243
- var DESKTOP_EXTENSION_MANIFEST_MAX_BYTES = 128 * 1024;
17244
- var DESKTOP_EXTENSION_SCRIPT_MAX_BYTES = 2 * 1024 * 1024;
17245
- var DESKTOP_EXTENSION_STYLE_MAX_BYTES = 256 * 1024;
17246
- var DESKTOP_EXTENSION_ICON_MAX_BYTES = 128 * 1024;
17247
- var DESKTOP_EXTENSION_SCREENSHOT_LIMIT = 4;
17248
- var DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES = 512 * 1024;
17249
- var DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES = 8 * 1024 * 1024;
17250
- var DESKTOP_EXTENSION_SNAPSHOT_MAX_BYTES = 8 * 1024 * 1024;
17251
- var DESKTOP_EXTENSION_ASSET_MAX_BYTES = 16 * 1024 * 1024;
17252
- var DESKTOP_EXTENSION_SETTINGS_MAX_BYTES = 1024 * 1024;
17253
- var desktopExtensionIdSchema = installedPluginIdSchema;
17254
- var desktopExtensionSlotSchema = external_exports.enum([
17255
- "sidebar.thread-layout",
17256
- "sidebar.thread-badge",
17257
- "appearance.theme"
17258
- ]);
17259
- var desktopExtensionCategorySchema = external_exports.enum([
17260
- "appearance",
17261
- "interface",
17262
- "workflow",
17263
- "analytics",
17264
- "integrations",
17265
- "tools"
17266
- ]);
17267
- var extensionName = external_exports.string().trim().min(1).max(128);
17268
- function desktopExtensionScreenshotMimeType(resource) {
17269
- switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
17270
- case "png":
17271
- return "image/png";
17272
- case "jpg":
17273
- case "jpeg":
17274
- return "image/jpeg";
17275
- case "webp":
17276
- return "image/webp";
17277
- default:
17278
- return void 0;
17157
+ // packages/shared-contracts/dist/errors.js
17158
+ var codexhostErrorSchema = external_exports.strictObject({
17159
+ code: external_exports.string().min(1),
17160
+ message: external_exports.string().min(1),
17161
+ retryable: external_exports.boolean(),
17162
+ diagnostic: external_exports.string().min(1).optional(),
17163
+ stage: external_exports.string().min(1).optional(),
17164
+ durationMs: external_exports.number().int().nonnegative().optional(),
17165
+ stderrTail: external_exports.string().min(1).optional()
17166
+ }).superRefine(rejectExplicitUndefined(["diagnostic", "stage", "durationMs", "stderrTail"]));
17167
+
17168
+ // packages/shared-contracts/dist/harness-presentation.js
17169
+ var localeSchema = external_exports.string().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u);
17170
+ var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text) => text.trim().length > 0);
17171
+ var harnessLocalizationsSchema = external_exports.record(localeSchema, external_exports.object({
17172
+ label: displayText(256).optional(),
17173
+ description: displayText(1024).optional()
17174
+ }).strict()).refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
17175
+ var harnessLocalizedTextSchema = external_exports.record(localeSchema, displayText(4096)).refine((entries) => typeof entries.en === "string", "English fallback is required").refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
17176
+
17177
+ // packages/shared-contracts/dist/ids.js
17178
+ var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
17179
+ message: "Identifier must not be empty or whitespace"
17180
+ });
17181
+ var harnessIdSchema = opaqueIdSchema.brand();
17182
+ var hostThreadIdSchema = opaqueIdSchema.brand();
17183
+ var hostTurnIdSchema = opaqueIdSchema.brand();
17184
+ var hostItemIdSchema = opaqueIdSchema.brand();
17185
+ var hostInteractionIdSchema = opaqueIdSchema.brand();
17186
+
17187
+ // packages/shared-contracts/dist/harness-permission-modes.js
17188
+ var HARNESS_PERMISSION_MODE_ID_MAX_LENGTH = 128;
17189
+ var HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH = 256;
17190
+ var HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH = 1024;
17191
+ var HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH = 32;
17192
+ var nonBlankTextSchema = external_exports.string().refine((value) => value.trim().length > 0, {
17193
+ message: "Value must not be empty or whitespace"
17194
+ });
17195
+ var harnessPermissionModeIdSchema = nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~:-]+$/u, "Permission Mode ID must use transport-safe characters").brand();
17196
+ var harnessPermissionModeSchema = external_exports.object({
17197
+ id: harnessPermissionModeIdSchema,
17198
+ label: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH),
17199
+ description: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH).optional(),
17200
+ dangerous: external_exports.boolean().optional(),
17201
+ localizations: harnessLocalizationsSchema.optional()
17202
+ }).strict();
17203
+ var harnessPermissionModeCatalogSchema = external_exports.object({
17204
+ modes: external_exports.array(harnessPermissionModeSchema).min(1).max(HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH),
17205
+ defaultModeId: harnessPermissionModeIdSchema
17206
+ }).strict().superRefine((catalog, context) => {
17207
+ const ids = /* @__PURE__ */ new Set();
17208
+ for (const [index, mode] of catalog.modes.entries()) {
17209
+ if (ids.has(mode.id)) {
17210
+ context.addIssue({
17211
+ code: "custom",
17212
+ message: "Permission Mode IDs must be unique",
17213
+ path: ["modes", index, "id"]
17214
+ });
17215
+ }
17216
+ ids.add(mode.id);
17279
17217
  }
17280
- }
17281
- function desktopExtensionAssetMimeType(resource) {
17282
- switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
17283
- case "gif":
17284
- return "image/gif";
17285
- case "svg":
17286
- return "image/svg+xml";
17287
- case "woff2":
17288
- return "font/woff2";
17289
- case "json":
17290
- return "application/json";
17291
- case "css":
17292
- return "text/css";
17293
- default:
17294
- return desktopExtensionScreenshotMimeType(resource);
17295
- }
17296
- }
17297
- var hasPortableSegments = (resource) => resource.split("/").every((segment) => !/[. ]$/u.test(segment));
17298
- var desktopExtensionAssetPathSchema = pluginRelativeResourceSchema.refine((resource) => hasPortableSegments(resource) && desktopExtensionAssetMimeType(resource) !== void 0, "Expected a relative Desktop extension asset path with a supported suffix");
17299
- var imagePathSchema = pluginRelativeResourceSchema.refine((resource) => desktopExtensionScreenshotMimeType(resource) !== void 0 && hasPortableSegments(resource), "Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space");
17300
- var desktopExtensionHttpUrlSchema = external_exports.string().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu, "Expected an HTTP(S) URL").pipe(external_exports.url({ protocol: /^https?$/u })).refine((value) => {
17301
- const { username, password } = new URL(value);
17302
- return !username && !password && !/[\\\s]/u.test(value);
17303
- }, "URL must not contain credentials, backslashes, or whitespace");
17304
- function localizedText(text) {
17305
- return external_exports.strictObject({ en: text, "zh-CN": text });
17306
- }
17307
- var desktopExtensionLocalizedTextSchema = localizedText(external_exports.string().trim().min(1));
17308
- var categoriesSchema = external_exports.array(desktopExtensionCategorySchema).max(desktopExtensionCategorySchema.options.length).refine((categories) => new Set(categories).size === categories.length, "Duplicate categories");
17309
- var slotsSchema = external_exports.array(desktopExtensionSlotSchema).max(desktopExtensionSlotSchema.options.length).refine((slots) => new Set(slots).size === slots.length, "Duplicate slots");
17310
- var settingField = {
17311
- key: external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),
17312
- label: desktopExtensionLocalizedTextSchema,
17313
- description: desktopExtensionLocalizedTextSchema.optional()
17314
- };
17315
- var numericSetting = {
17316
- ...settingField,
17317
- step: external_exports.number().positive().optional(),
17318
- default: external_exports.number().optional()
17319
- };
17320
- var settingOption = external_exports.strictObject({
17321
- value: external_exports.string(),
17322
- label: desktopExtensionLocalizedTextSchema
17323
- });
17324
- var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("type", [
17325
- external_exports.strictObject({
17326
- ...settingField,
17327
- type: external_exports.literal("boolean"),
17328
- default: external_exports.boolean().optional()
17329
- }),
17330
- external_exports.strictObject({
17331
- ...settingField,
17332
- type: external_exports.literal("string"),
17333
- placeholder: desktopExtensionLocalizedTextSchema.optional(),
17334
- default: external_exports.string().optional()
17335
- }),
17336
- external_exports.strictObject({
17337
- ...numericSetting,
17338
- type: external_exports.literal("number"),
17339
- min: external_exports.number().optional(),
17340
- max: external_exports.number().optional()
17341
- }),
17342
- external_exports.strictObject({
17343
- ...numericSetting,
17344
- type: external_exports.literal("range"),
17345
- min: external_exports.number(),
17346
- max: external_exports.number()
17347
- }),
17348
- external_exports.strictObject({
17349
- ...settingField,
17350
- type: external_exports.literal("select"),
17351
- options: external_exports.array(settingOption).min(1),
17352
- default: external_exports.string().optional()
17353
- })
17354
- ]).superRefine((field2, ctx) => {
17355
- const issue2 = (path24, message) => ctx.addIssue({ code: "custom", path: [path24], message });
17356
- if (field2.type === "number" || field2.type === "range") {
17357
- const { min = -Infinity, max = Infinity, default: value } = field2;
17358
- if (min > max)
17359
- issue2("max", "Must be at least min");
17360
- if (value !== void 0 && (value < min || value > max))
17361
- issue2("default", "Must be within min and max");
17362
- } else if (field2.type === "select") {
17363
- const values = new Set(field2.options.map(({ value }) => value));
17364
- if (values.size !== field2.options.length)
17365
- issue2("options", "Duplicate option values");
17366
- if (field2.default !== void 0 && !values.has(field2.default))
17367
- issue2("default", "Must match an option value");
17368
- }
17369
- });
17370
- var manifestHeader = external_exports.object({
17371
- manifestVersion: external_exports.int().positive(),
17372
- id: desktopExtensionIdSchema,
17373
- name: external_exports.union([extensionName, localizedText(extensionName)]),
17374
- version: external_exports.string().min(1).max(128),
17375
- desktopApi: external_exports.int().positive()
17376
- }).passthrough();
17377
- var desktopExtensionManifestSchema = manifestHeader.extend({
17378
- manifestVersion: external_exports.literal(1),
17379
- desktopApi: external_exports.literal(DESKTOP_EXTENSION_API_VERSION),
17380
- description: external_exports.strictObject({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).optional(),
17381
- author: external_exports.string().trim().min(1).max(128).optional(),
17382
- repository: desktopExtensionHttpUrlSchema.optional(),
17383
- details: external_exports.strictObject({ en: external_exports.string().max(16384), "zh-CN": external_exports.string().max(16384).optional() }).optional(),
17384
- icon: imagePathSchema.optional(),
17385
- screenshots: external_exports.array(imagePathSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).refine((screenshots) => new Set(screenshots).size === screenshots.length, "Duplicate screenshots").optional(),
17386
- desktop: external_exports.strictObject({
17387
- script: pluginRelativeResourceSchema,
17388
- style: pluginRelativeResourceSchema.optional()
17389
- }).optional(),
17390
- backend: external_exports.strictObject({ script: pluginRelativeResourceSchema.refine(hasPortableSegments) }).optional(),
17391
- slots: slotsSchema.default(() => []),
17392
- settingsSchema: external_exports.array(desktopExtensionSettingFieldSchema).max(32).refine((fields) => new Set(fields.map(({ key }) => key)).size === fields.length, "Duplicate setting keys").optional(),
17393
- categories: categoriesSchema.optional()
17394
- }).strict().refine((manifest) => manifest.desktop !== void 0 || manifest.backend !== void 0, "Expected at least one desktop or backend entry");
17395
- function parseDesktopExtensionManifest(value) {
17396
- const header = manifestHeader.safeParse(value);
17397
- if (!header.success)
17398
- return { state: "invalid", error: external_exports.prettifyError(header.error) };
17399
- if (header.data.desktopApi > DESKTOP_EXTENSION_API_VERSION) {
17400
- return {
17401
- state: "incompatible",
17402
- error: `Desktop API ${header.data.desktopApi} requires a newer codexhost`
17403
- };
17404
- }
17405
- const manifest = desktopExtensionManifestSchema.safeParse(value);
17406
- return manifest.success ? { state: "valid", manifest: manifest.data } : { state: "invalid", error: external_exports.prettifyError(manifest.error) };
17407
- }
17408
- var desktopExtensionConfigurationSchema = external_exports.strictObject({
17409
- version: external_exports.literal(1),
17410
- revision: external_exports.int().nonnegative(),
17411
- enabled: external_exports.array(desktopExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs"),
17412
- reloadToken: external_exports.uuid().optional()
17413
- });
17414
- var desktopExtensionHashSchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
17415
- var desktopExtensionStatusSchema = external_exports.strictObject({
17416
- state: external_exports.enum([
17417
- "running",
17418
- "disabled",
17419
- "invalid",
17420
- "incompatible",
17421
- "conflict",
17422
- "failed",
17423
- "waiting"
17424
- ]),
17425
- hash: desktopExtensionHashSchema.optional(),
17426
- error: external_exports.string().optional(),
17427
- conflictWith: desktopExtensionIdSchema.optional()
17428
- });
17429
- var desktopExtensionsDiagnosticSchema = external_exports.strictObject({
17430
- controllerPid: external_exports.int().positive(),
17431
- targetId: external_exports.string().nullable(),
17432
- updatedAt: external_exports.iso.datetime(),
17433
- handledReloadToken: external_exports.uuid().optional(),
17434
- extensions: external_exports.record(external_exports.string(), desktopExtensionStatusSchema)
17435
- });
17436
- var desktopExtensionTrustTierSchema = external_exports.enum(["official", "community"]);
17437
- function isGitHubDesktopExtensionZipballUrl(url2) {
17438
- return url2.origin === "https://api.github.com" && /^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(url2.pathname);
17439
- }
17440
- var desktopExtensionZipUrlSchema = desktopExtensionHttpUrlSchema.refine((input) => {
17441
- const url2 = new URL(input);
17442
- return /\.zip$/iu.test(url2.pathname) || isGitHubDesktopExtensionZipballUrl(url2) || url2.origin === "https://github.com" && /^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(url2.pathname) || url2.origin === "https://codeload.github.com" && /^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(url2.pathname);
17443
- }, "Expected a .zip download URL or a GitHub zipball URL");
17444
- var desktopExtensionCatalogEntrySchema = external_exports.strictObject({
17445
- id: desktopExtensionIdSchema,
17446
- version: external_exports.string().trim().min(1).max(128),
17447
- name: desktopExtensionLocalizedTextSchema.extend({ en: extensionName, "zh-CN": extensionName }),
17448
- description: localizedText(external_exports.string().trim().min(1).max(4096)),
17449
- details: localizedText(external_exports.string().trim().min(1).max(16384)).optional(),
17450
- author: external_exports.string().trim().min(1).max(128),
17451
- repository: desktopExtensionHttpUrlSchema,
17452
- stars: external_exports.number().int().min(0).optional(),
17453
- downloads: external_exports.number().int().min(0).optional(),
17454
- categories: categoriesSchema.optional(),
17455
- trustTier: desktopExtensionTrustTierSchema.default("community"),
17456
- icon: desktopExtensionHttpUrlSchema.optional(),
17457
- screenshots: external_exports.array(desktopExtensionHttpUrlSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
17458
- downloadUrl: desktopExtensionZipUrlSchema,
17459
- sha256: desktopExtensionHashSchema,
17460
- slots: slotsSchema.optional(),
17461
- publishedAt: external_exports.string().optional(),
17462
- updatedAt: external_exports.string().optional(),
17463
- minCodexHostVersion: external_exports.string().optional()
17464
- });
17465
- var desktopExtensionCatalogSchema = external_exports.strictObject({
17466
- schemaVersion: external_exports.literal(1),
17467
- generatedAt: external_exports.string(),
17468
- extensions: external_exports.array(desktopExtensionCatalogEntrySchema).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, "Duplicate extension IDs")
17469
- });
17470
- function resolveDesktopExtensionSlots(enabledOrder, manifests) {
17471
- const byId = new Map(Array.from(manifests, ({ id, slots = [] }) => [id, slots]));
17472
- const owners = /* @__PURE__ */ new Map();
17473
- const conflicts = /* @__PURE__ */ new Map();
17474
- const active = [];
17475
- for (const id of new Set(enabledOrder)) {
17476
- const slots = byId.get(id);
17477
- if (!slots)
17478
- continue;
17479
- const conflictWith = slots.map((slot) => owners.get(slot)).find((owner) => owner !== void 0);
17480
- if (conflictWith !== void 0) {
17481
- conflicts.set(id, conflictWith);
17482
- continue;
17483
- }
17484
- for (const slot of slots)
17485
- owners.set(slot, id);
17486
- active.push(id);
17487
- }
17488
- return { active, conflicts };
17489
- }
17490
- var DESKTOP_EXTENSIONS_ASSET_METHOD = "codexhost/desktop/extensions/asset";
17491
- var DESKTOP_EXTENSIONS_SETTINGS_GET_METHOD = "codexhost/desktop/extensions/settings/get";
17492
- var DESKTOP_EXTENSIONS_SETTINGS_SET_METHOD = "codexhost/desktop/extensions/settings/set";
17493
- var DESKTOP_EXTENSIONS_BACKEND_INVOKE_METHOD = "codexhost/desktop/extensions/backend/invoke";
17494
- var extensionIdParams = { id: desktopExtensionIdSchema };
17495
- var desktopExtensionsAssetParamsSchema = external_exports.strictObject({
17496
- ...extensionIdParams,
17497
- path: desktopExtensionAssetPathSchema
17498
- });
17499
- var desktopExtensionsAssetResultSchema = external_exports.strictObject({
17500
- mimeType: external_exports.string(),
17501
- dataUrl: external_exports.string()
17502
- });
17503
- var desktopExtensionsSettingsGetParamsSchema = external_exports.strictObject(extensionIdParams);
17504
- var desktopExtensionsSettingsSetParamsSchema = external_exports.strictObject({
17505
- ...extensionIdParams,
17506
- values: jsonObjectSchema
17507
- });
17508
- var desktopExtensionsSettingsResultSchema = external_exports.strictObject({ values: jsonObjectSchema });
17509
- var desktopExtensionBackendMethodSchema = external_exports.string().trim().min(1).max(128);
17510
- var desktopExtensionsBackendInvokeParamsSchema = external_exports.strictObject({
17511
- ...extensionIdParams,
17512
- method: desktopExtensionBackendMethodSchema,
17513
- params: jsonValueSchema.optional()
17514
- });
17515
- var desktopExtensionsBackendInvokeResultSchema = external_exports.strictObject({
17516
- result: jsonValueSchema
17517
- });
17518
-
17519
- // packages/shared-contracts/dist/desktop-extension-management.js
17520
- var DESKTOP_EXTENSIONS_LIST_METHOD = "codexhost/desktop/extensions/list";
17521
- var DESKTOP_EXTENSIONS_ENABLE_METHOD = "codexhost/desktop/extensions/enable";
17522
- var DESKTOP_EXTENSIONS_DISABLE_METHOD = "codexhost/desktop/extensions/disable";
17523
- var DESKTOP_EXTENSIONS_CATALOG_METHOD = "codexhost/desktop/extensions/catalog";
17524
- var DESKTOP_EXTENSIONS_INSTALL_METHOD = "codexhost/desktop/extensions/install";
17525
- var DESKTOP_EXTENSIONS_UNINSTALL_METHOD = "codexhost/desktop/extensions/uninstall";
17526
- var DESKTOP_EXTENSIONS_RECOVER_METHOD = "codexhost/desktop/extensions/disable-all-and-reload";
17527
- var DESKTOP_EXTENSION_MANAGEMENT_METHODS = [
17528
- DESKTOP_EXTENSIONS_LIST_METHOD,
17529
- DESKTOP_EXTENSIONS_ENABLE_METHOD,
17530
- DESKTOP_EXTENSIONS_DISABLE_METHOD,
17531
- DESKTOP_EXTENSIONS_RECOVER_METHOD,
17532
- DESKTOP_EXTENSIONS_CATALOG_METHOD,
17533
- DESKTOP_EXTENSIONS_INSTALL_METHOD,
17534
- DESKTOP_EXTENSIONS_UNINSTALL_METHOD,
17535
- DESKTOP_EXTENSIONS_ASSET_METHOD,
17536
- DESKTOP_EXTENSIONS_SETTINGS_GET_METHOD,
17537
- DESKTOP_EXTENSIONS_SETTINGS_SET_METHOD,
17538
- DESKTOP_EXTENSIONS_BACKEND_INVOKE_METHOD
17539
- ];
17540
- var revisionSchema = external_exports.int().nonnegative();
17541
- var desktopExtensionsListParamsSchema = external_exports.strictObject({});
17542
- var desktopExtensionSelectionParamsSchema = external_exports.strictObject({
17543
- id: desktopExtensionIdSchema,
17544
- expectedRevision: revisionSchema
17545
- });
17546
- var desktopExtensionsRecoveryParamsSchema = external_exports.strictObject({
17547
- expectedRevision: revisionSchema.optional()
17548
- });
17549
- var rasterDataUrlSchema = (maxBytes) => external_exports.string().max("data:image/jpeg;base64,".length + 4 * Math.ceil(maxBytes / 3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u);
17550
- var desktopExtensionListItemSchema = external_exports.strictObject({
17551
- // An invalid discovery can have a directory name that isn't a valid extension ID.
17552
- id: external_exports.string().min(1),
17553
- manifest: desktopExtensionManifestSchema.optional(),
17554
- iconDataUrl: rasterDataUrlSchema(DESKTOP_EXTENSION_ICON_MAX_BYTES).optional(),
17555
- screenshotDataUrls: external_exports.array(rasterDataUrlSchema(DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES)).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
17556
- enabled: external_exports.boolean(),
17557
- status: desktopExtensionStatusSchema
17558
- });
17559
- var desktopExtensionsListResultSchema = external_exports.strictObject({
17560
- configuration: desktopExtensionConfigurationSchema,
17561
- desktopConnected: external_exports.boolean(),
17562
- diagnostics: external_exports.array(external_exports.string()),
17563
- extensions: external_exports.array(desktopExtensionListItemSchema)
17564
- });
17565
- var desktopExtensionsCatalogParamsSchema = external_exports.strictObject({
17566
- forceRefresh: external_exports.boolean().optional()
17567
- });
17568
- var desktopExtensionsCatalogResultSchema = external_exports.strictObject({
17569
- catalogUrl: external_exports.string(),
17570
- source: external_exports.enum(["remote", "fallback"]),
17571
- fetchedAt: external_exports.string(),
17572
- cached: external_exports.boolean(),
17573
- extensions: desktopExtensionCatalogSchema.shape.extensions,
17574
- error: external_exports.string().optional()
17575
- });
17576
- var desktopExtensionsInstallParamsSchema = external_exports.strictObject({
17577
- source: external_exports.discriminatedUnion("type", [
17578
- external_exports.strictObject({ type: external_exports.literal("catalog"), id: desktopExtensionIdSchema }),
17579
- external_exports.strictObject({
17580
- type: external_exports.literal("url"),
17581
- url: desktopExtensionHttpUrlSchema,
17582
- expectedSha256: desktopExtensionHashSchema.optional()
17583
- }),
17584
- external_exports.strictObject({
17585
- type: external_exports.literal("zip-base64"),
17586
- fileName: external_exports.string().trim().min(1).max(255),
17587
- contentBase64: external_exports.string().min(4).max(DESKTOP_EXTENSION_ZIP_MAX_BASE64_LENGTH).refine((value) => value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/u.test(value), "Expected standard padded base64")
17588
- })
17589
- ])
17590
- });
17591
- var desktopExtensionsInstallResultSchema = external_exports.strictObject({
17592
- extensionId: desktopExtensionIdSchema,
17593
- version: external_exports.string().min(1),
17594
- replaced: external_exports.boolean(),
17595
- installedPath: external_exports.string(),
17596
- list: desktopExtensionsListResultSchema
17597
- });
17598
- var desktopExtensionsUninstallParamsSchema = external_exports.strictObject({
17599
- id: desktopExtensionIdSchema
17600
- });
17601
- var desktopExtensionsUninstallResultSchema = external_exports.strictObject({
17602
- removedId: desktopExtensionIdSchema,
17603
- list: desktopExtensionsListResultSchema
17604
- });
17605
- var desktopExtensionMutationResultSchema = external_exports.discriminatedUnion("state", [
17606
- external_exports.strictObject({ state: external_exports.literal("saved"), configuration: desktopExtensionConfigurationSchema }),
17607
- external_exports.strictObject({ state: external_exports.literal("slot-conflict"), conflictWith: desktopExtensionIdSchema }),
17608
- external_exports.strictObject({ state: external_exports.literal("revision-conflict"), revision: revisionSchema })
17609
- ]);
17610
-
17611
- // packages/shared-contracts/dist/errors.js
17612
- var codexhostErrorSchema = external_exports.strictObject({
17613
- code: external_exports.string().min(1),
17614
- message: external_exports.string().min(1),
17615
- retryable: external_exports.boolean(),
17616
- diagnostic: external_exports.string().min(1).optional(),
17617
- stage: external_exports.string().min(1).optional(),
17618
- durationMs: external_exports.number().int().nonnegative().optional(),
17619
- stderrTail: external_exports.string().min(1).optional()
17620
- }).superRefine(rejectExplicitUndefined(["diagnostic", "stage", "durationMs", "stderrTail"]));
17621
-
17622
- // packages/shared-contracts/dist/harness-presentation.js
17623
- var localeSchema = external_exports.string().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u);
17624
- var displayText = (maximum) => external_exports.string().min(1).max(maximum).refine((text) => text.trim().length > 0);
17625
- var harnessLocalizationsSchema = external_exports.record(localeSchema, external_exports.object({
17626
- label: displayText(256).optional(),
17627
- description: displayText(1024).optional()
17628
- }).strict()).refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
17629
- var harnessLocalizedTextSchema = external_exports.record(localeSchema, displayText(4096)).refine((entries) => typeof entries.en === "string", "English fallback is required").refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
17630
-
17631
- // packages/shared-contracts/dist/harness-permission-modes.js
17632
- var HARNESS_PERMISSION_MODE_ID_MAX_LENGTH = 128;
17633
- var HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH = 256;
17634
- var HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH = 1024;
17635
- var HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH = 32;
17636
- var nonBlankTextSchema = external_exports.string().refine((value) => value.trim().length > 0, {
17637
- message: "Value must not be empty or whitespace"
17638
- });
17639
- var harnessPermissionModeIdSchema = nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~:-]+$/u, "Permission Mode ID must use transport-safe characters").brand();
17640
- var harnessPermissionModeSchema = external_exports.object({
17641
- id: harnessPermissionModeIdSchema,
17642
- label: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH),
17643
- description: nonBlankTextSchema.max(HARNESS_PERMISSION_MODE_DESCRIPTION_MAX_LENGTH).optional(),
17644
- dangerous: external_exports.boolean().optional(),
17645
- localizations: harnessLocalizationsSchema.optional()
17646
- }).strict();
17647
- var harnessPermissionModeCatalogSchema = external_exports.object({
17648
- modes: external_exports.array(harnessPermissionModeSchema).min(1).max(HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH),
17649
- defaultModeId: harnessPermissionModeIdSchema
17650
- }).strict().superRefine((catalog, context) => {
17651
- const ids = /* @__PURE__ */ new Set();
17652
- for (const [index, mode] of catalog.modes.entries()) {
17653
- if (ids.has(mode.id)) {
17654
- context.addIssue({
17655
- code: "custom",
17656
- message: "Permission Mode IDs must be unique",
17657
- path: ["modes", index, "id"]
17658
- });
17659
- }
17660
- ids.add(mode.id);
17661
- }
17662
- if (!ids.has(catalog.defaultModeId)) {
17663
- context.addIssue({
17664
- code: "custom",
17665
- message: "Default Permission Mode must exist in the catalog",
17666
- path: ["defaultModeId"]
17667
- });
17218
+ if (!ids.has(catalog.defaultModeId)) {
17219
+ context.addIssue({
17220
+ code: "custom",
17221
+ message: "Default Permission Mode must exist in the catalog",
17222
+ path: ["defaultModeId"]
17223
+ });
17668
17224
  }
17669
17225
  });
17670
17226
  var threadPermissionModeSelectParamsSchema = external_exports.object({
@@ -17672,6 +17228,9 @@ var threadPermissionModeSelectParamsSchema = external_exports.object({
17672
17228
  permissionModeId: harnessPermissionModeIdSchema
17673
17229
  }).strict();
17674
17230
 
17231
+ // packages/shared-contracts/dist/harness-route-limit.js
17232
+ var HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH = 8192;
17233
+
17675
17234
  // packages/shared-contracts/dist/thread-usage.js
17676
17235
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
17677
17236
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -17704,7 +17263,7 @@ var composerIndicatorsSchema = external_exports.array(external_exports.object({
17704
17263
  expiresAtUnix: nonNegativeSafeIntegerSchema,
17705
17264
  label: indicatorTextSchema(256).optional(),
17706
17265
  tooltip: indicatorTextSchema(1024).optional()
17707
- }).strict()).max(2).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, {
17266
+ }).strict()).max(2).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, {
17708
17267
  message: "Composer indicator IDs must be unique"
17709
17268
  });
17710
17269
  var threadUsageSnapshotSchema = external_exports.object({
@@ -17730,6 +17289,7 @@ var threadUsageSnapshotSchema = external_exports.object({
17730
17289
  planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
17731
17290
  sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
17732
17291
  timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
17292
+ latestRequestTimeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
17733
17293
  costSource: external_exports.enum(["publicPrice", "native"]).optional(),
17734
17294
  unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
17735
17295
  }).strict().superRefine((usage2, context) => {
@@ -17857,10 +17417,15 @@ var THREAD_OWNERSHIP_LIST_MAX_LENGTH = 100;
17857
17417
  var nonBlankTextSchema2 = external_exports.string().refine((value) => value.trim().length > 0, {
17858
17418
  message: "Value must not be empty or whitespace"
17859
17419
  });
17860
- var harnessModelRefIdSchema = nonBlankTextSchema2.max(HARNESS_MODEL_REF_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Model Ref must use transport-safe opaque characters").brand();
17420
+ var harnessModelRefIdSchema = external_exports.string().min(1).max(HARNESS_MODEL_REF_MAX_LENGTH).refine((id2) => !new RegExp("\\p{Cc}", "u").test(id2), "Model Ref must not contain control characters").brand();
17421
+ var harnessModelServiceTierSchema = external_exports.enum(["priority", "ultrafast"]);
17861
17422
  var harnessModelRefSchema = external_exports.object({
17862
- id: harnessModelRefIdSchema
17423
+ id: harnessModelRefIdSchema,
17424
+ serviceTier: harnessModelServiceTierSchema.optional()
17863
17425
  }).strict();
17426
+ function sameHarnessModelRef(left, right) {
17427
+ return left?.id === right?.id && left?.serviceTier === right?.serviceTier;
17428
+ }
17864
17429
  var harnessThinkingOptionIdSchema = nonBlankTextSchema2.max(HARNESS_THINKING_OPTION_ID_MAX_LENGTH).regex(/^[A-Za-z0-9._~-]+$/u, "Thinking option ID must use transport-safe characters").brand();
17865
17430
  var harnessResolvedModelLabelSchema = nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH);
17866
17431
  var harnessThinkingOptionSchema = external_exports.object({
@@ -17874,7 +17439,15 @@ var harnessModelSchema = external_exports.object({
17874
17439
  /** Optional opaque selection for this same Model with priority processing enabled. */
17875
17440
  fastModel: harnessModelRefSchema.optional(),
17876
17441
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
17877
- }).strict();
17442
+ }).strict().refine((model2) => model2.fastModel?.serviceTier === void 0 || model2.fastModel.id === model2.ref.id, {
17443
+ path: ["fastModel", "id"],
17444
+ message: "A tiered Fast Model must share the base Model ID"
17445
+ });
17446
+ function catalogModelForRef(catalog, ref) {
17447
+ if (!ref)
17448
+ return void 0;
17449
+ return catalog?.models.find((model2) => sameHarnessModelRef(model2.ref, ref) || sameHarnessModelRef(model2.fastModel, ref));
17450
+ }
17878
17451
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
17879
17452
  const ids = /* @__PURE__ */ new Set();
17880
17453
  for (const [index, option] of options.entries()) {
@@ -17894,26 +17467,26 @@ var harnessModelCatalogSchema = external_exports.object({
17894
17467
  thinkingOptions: harnessThinkingOptionsSchema,
17895
17468
  defaultThinkingOptionId: harnessThinkingOptionIdSchema.optional()
17896
17469
  }).strict().superRefine((catalog, context) => {
17897
- const refs = /* @__PURE__ */ new Set();
17898
- const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
17470
+ const refs = [];
17471
+ const thinkingIds = new Set(catalog.thinkingOptions.map(({ id: id2 }) => id2));
17899
17472
  for (const [index, model2] of catalog.models.entries()) {
17900
- if (refs.has(model2.ref.id)) {
17473
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.ref))) {
17901
17474
  context.addIssue({
17902
17475
  code: "custom",
17903
17476
  message: "Model Catalog refs must be unique",
17904
17477
  path: ["models", index, "ref", "id"]
17905
17478
  });
17906
17479
  }
17907
- refs.add(model2.ref.id);
17480
+ refs.push(model2.ref);
17908
17481
  if (model2.fastModel) {
17909
- if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
17482
+ if (refs.some((ref) => sameHarnessModelRef(ref, model2.fastModel))) {
17910
17483
  context.addIssue({
17911
17484
  code: "custom",
17912
17485
  message: "Fast Model refs must be distinct and unique",
17913
17486
  path: ["models", index, "fastModel"]
17914
17487
  });
17915
17488
  }
17916
- refs.add(model2.fastModel.id);
17489
+ refs.push(model2.fastModel);
17917
17490
  }
17918
17491
  const supportedThinkingIds = /* @__PURE__ */ new Set();
17919
17492
  for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
@@ -17934,7 +17507,7 @@ var harnessModelCatalogSchema = external_exports.object({
17934
17507
  }
17935
17508
  }
17936
17509
  }
17937
- if (catalog.defaultModel && !refs.has(catalog.defaultModel.id)) {
17510
+ if (catalog.defaultModel && !catalogModelForRef(catalog, catalog.defaultModel)) {
17938
17511
  context.addIssue({
17939
17512
  code: "custom",
17940
17513
  message: "Default Model must exist in the Model Catalog",
@@ -17974,7 +17547,12 @@ var harnessSessionCapabilitiesSchema = external_exports.object({
17974
17547
  observe: external_exports.boolean()
17975
17548
  }).strict().optional(),
17976
17549
  /** True only when `turn.steer` delivers input into the active Turn through a native primitive. */
17977
- steer: external_exports.boolean().optional()
17550
+ steer: external_exports.boolean().optional(),
17551
+ /**
17552
+ * True when the native plan (task list) outlives the Turn that changed it, so a reopened
17553
+ * Thread gets its latest plan again. Otherwise a plan stays with the Turn that made it.
17554
+ */
17555
+ persistentPlan: external_exports.boolean().optional()
17978
17556
  }).strict();
17979
17557
  var harnessConfigurationStateSchema = external_exports.object({
17980
17558
  effectiveModel: harnessModelRefSchema.optional(),
@@ -17983,7 +17561,7 @@ var harnessConfigurationStateSchema = external_exports.object({
17983
17561
  availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
17984
17562
  effectivePermissionModeId: harnessPermissionModeIdSchema.optional()
17985
17563
  }).strict().superRefine((state, context) => {
17986
- if (state.effectiveThinkingOptionId && state.availableThinkingOptions && !state.availableThinkingOptions.some(({ id }) => id === state.effectiveThinkingOptionId)) {
17564
+ if (state.effectiveThinkingOptionId && state.availableThinkingOptions && !state.availableThinkingOptions.some(({ id: id2 }) => id2 === state.effectiveThinkingOptionId)) {
17987
17565
  context.addIssue({
17988
17566
  code: "custom",
17989
17567
  message: "Effective Thinking option must be currently available",
@@ -17991,150 +17569,761 @@ var harnessConfigurationStateSchema = external_exports.object({
17991
17569
  });
17992
17570
  }
17993
17571
  });
17994
- var harnessWebUiCapabilitySchema = external_exports.object({
17995
- open: external_exports.literal(true)
17996
- }).strict();
17997
- var readyHarnessInspectionSchema = external_exports.object({
17998
- status: external_exports.literal("ready"),
17999
- catalog: harnessModelCatalogSchema,
18000
- permissionModes: harnessPermissionModeCatalogSchema.optional(),
18001
- capabilities: harnessSessionCapabilitiesSchema,
18002
- webUi: harnessWebUiCapabilitySchema.optional()
18003
- }).strict().superRefine((inspection, context) => {
18004
- const selectable = inspection.capabilities.configuration.selectPermissionMode;
18005
- if (selectable !== Boolean(inspection.permissionModes)) {
18006
- context.addIssue({
18007
- code: "custom",
18008
- message: "Permission Mode catalog and capability must agree",
18009
- path: selectable ? ["permissionModes"] : ["capabilities", "configuration", "selectPermissionMode"]
18010
- });
18011
- }
17572
+ var harnessWebUiCapabilitySchema = external_exports.object({
17573
+ open: external_exports.literal(true)
17574
+ }).strict();
17575
+ var readyHarnessInspectionSchema = external_exports.object({
17576
+ status: external_exports.literal("ready"),
17577
+ catalog: harnessModelCatalogSchema,
17578
+ permissionModes: harnessPermissionModeCatalogSchema.optional(),
17579
+ capabilities: harnessSessionCapabilitiesSchema,
17580
+ webUi: harnessWebUiCapabilitySchema.optional()
17581
+ }).strict().superRefine((inspection, context) => {
17582
+ const selectable = inspection.capabilities.configuration.selectPermissionMode;
17583
+ if (selectable !== Boolean(inspection.permissionModes)) {
17584
+ context.addIssue({
17585
+ code: "custom",
17586
+ message: "Permission Mode catalog and capability must agree",
17587
+ path: selectable ? ["permissionModes"] : ["capabilities", "configuration", "selectPermissionMode"]
17588
+ });
17589
+ }
17590
+ });
17591
+ var failedHarnessInspectionSchema = external_exports.object({
17592
+ status: external_exports.enum(["notInstalled", "unavailable", "error"]),
17593
+ error: codexhostErrorSchema
17594
+ }).strict();
17595
+ var harnessInspectionSchema = external_exports.union([
17596
+ readyHarnessInspectionSchema,
17597
+ failedHarnessInspectionSchema
17598
+ ]);
17599
+ var harnessInspectParamsSchema = external_exports.object({
17600
+ harnessId: harnessIdSchema,
17601
+ cwd: nonBlankTextSchema2.max(16384).optional(),
17602
+ refresh: external_exports.boolean().optional(),
17603
+ /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
17604
+ purpose: external_exports.literal("availability").optional(),
17605
+ credentialAccess: external_exports.enum(["allow", "retry"]).optional()
17606
+ }).strict();
17607
+ var harnessWebUiOpenParamsSchema = external_exports.object({
17608
+ harnessId: harnessIdSchema
17609
+ }).strict();
17610
+ var harnessWebUiOpenResultSchema = external_exports.object({}).strict();
17611
+ var threadModelSelectParamsSchema = external_exports.object({
17612
+ threadId: hostThreadIdSchema,
17613
+ model: harnessModelRefSchema
17614
+ }).strict();
17615
+ var threadThinkingSelectParamsSchema = external_exports.object({
17616
+ threadId: hostThreadIdSchema,
17617
+ thinkingOptionId: harnessThinkingOptionIdSchema
17618
+ }).strict();
17619
+ var threadInspectionParamsSchema = external_exports.object({
17620
+ threadId: hostThreadIdSchema,
17621
+ includeReferenceCapability: external_exports.boolean().optional()
17622
+ }).strict();
17623
+ var codexThreadInspectionSchema = external_exports.object({
17624
+ owner: external_exports.literal("codex"),
17625
+ locked: external_exports.boolean(),
17626
+ effectiveModel: harnessModelRefSchema.optional(),
17627
+ resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
17628
+ effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
17629
+ effectivePermissionModeId: harnessPermissionModeIdSchema.optional(),
17630
+ history: harnessHistoryCapabilitiesSchema.optional(),
17631
+ supportsThreadReferences: external_exports.literal(true).optional()
17632
+ }).strict();
17633
+ var externalThreadInspectionSchema = external_exports.object({
17634
+ owner: external_exports.literal("external"),
17635
+ harnessId: nonBlankTextSchema2.max(256),
17636
+ transportModelId: nonBlankTextSchema2.max(HARNESS_TRANSPORT_MODEL_ID_MAX_LENGTH),
17637
+ effectiveModel: harnessModelRefSchema.optional(),
17638
+ resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
17639
+ effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
17640
+ availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
17641
+ effectivePermissionModeId: harnessPermissionModeIdSchema.optional(),
17642
+ history: harnessHistoryCapabilitiesSchema,
17643
+ usage: threadUsageSnapshotSchema.optional(),
17644
+ locked: external_exports.literal(true)
17645
+ }).strict();
17646
+ var threadInspectionSchema = external_exports.discriminatedUnion("owner", [
17647
+ codexThreadInspectionSchema,
17648
+ externalThreadInspectionSchema
17649
+ ]);
17650
+ var threadOwnershipListParamsSchema = external_exports.object({
17651
+ threadIds: external_exports.array(hostThreadIdSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
17652
+ }).strict().superRefine(({ threadIds }, context) => {
17653
+ const seen = /* @__PURE__ */ new Set();
17654
+ for (const [index, threadId] of threadIds.entries()) {
17655
+ if (seen.has(threadId)) {
17656
+ context.addIssue({
17657
+ code: "custom",
17658
+ message: "Thread ownership-list IDs must be unique",
17659
+ path: ["threadIds", index]
17660
+ });
17661
+ }
17662
+ seen.add(threadId);
17663
+ }
17664
+ });
17665
+ var codexThreadOwnershipSchema = external_exports.object({
17666
+ threadId: hostThreadIdSchema,
17667
+ owner: external_exports.literal("codex")
17668
+ }).strict();
17669
+ var externalThreadOwnershipSchema = external_exports.object({
17670
+ threadId: hostThreadIdSchema,
17671
+ owner: external_exports.literal("external"),
17672
+ harnessId: external_exports.string().max(256).pipe(harnessIdSchema)
17673
+ }).strict();
17674
+ var threadOwnershipSchema = external_exports.discriminatedUnion("owner", [
17675
+ codexThreadOwnershipSchema,
17676
+ externalThreadOwnershipSchema
17677
+ ]);
17678
+ var threadOwnershipListResultSchema = external_exports.object({
17679
+ threads: external_exports.array(threadOwnershipSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
17680
+ }).strict().superRefine(({ threads }, context) => {
17681
+ const seen = /* @__PURE__ */ new Set();
17682
+ for (const [index, thread2] of threads.entries()) {
17683
+ if (seen.has(thread2.threadId)) {
17684
+ context.addIssue({
17685
+ code: "custom",
17686
+ message: "Thread ownership-list results must be unique",
17687
+ path: ["threads", index, "threadId"]
17688
+ });
17689
+ }
17690
+ seen.add(thread2.threadId);
17691
+ }
17692
+ });
17693
+ var threadSteeringInspectParamsSchema = external_exports.object({
17694
+ threadId: hostThreadIdSchema,
17695
+ /** The text about to be steered; a Harness command always stops and restarts. */
17696
+ text: external_exports.string().optional()
17697
+ }).strict();
17698
+ var threadSteeringContextSchema = external_exports.object({
17699
+ kind: external_exports.literal("application"),
17700
+ value: external_exports.string().transform((text, context) => {
17701
+ try {
17702
+ return JSON.parse(text);
17703
+ } catch {
17704
+ context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
17705
+ return external_exports.NEVER;
17706
+ }
17707
+ }).pipe(external_exports.object({
17708
+ expectedTurnId: hostTurnIdSchema,
17709
+ clientUserMessageId: external_exports.string().min(1),
17710
+ delivery: external_exports.enum(["newTurn", "activeTurn"])
17711
+ }).strict())
17712
+ }).strict().transform((context) => context.value);
17713
+ var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
17714
+ var threadSteeringInspectResultSchema = external_exports.object({
17715
+ delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
17716
+ }).strict();
17717
+
17718
+ // packages/shared-contracts/dist/harness-plugins.js
17719
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
17720
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
17721
+ var HARNESS_PLUGIN_LIMIT = 128;
17722
+ var installedPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u);
17723
+ var installedHarnessPluginIdSchema = installedPluginIdSchema.pipe(harnessIdSchema);
17724
+ var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id2) => id2 !== "codex", "The official Codex identity is reserved");
17725
+ var pluginRelativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
17726
+ var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
17727
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
17728
+ var harnessInstallationGuideSchema = external_exports.object({
17729
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
17730
+ before: localizedTextSchema.optional(),
17731
+ after: localizedTextSchema.optional(),
17732
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
17733
+ }).strict();
17734
+ var pluginPresentationShape = {
17735
+ id: installedHarnessPluginIdSchema,
17736
+ name: external_exports.string().trim().min(1).max(128),
17737
+ version: external_exports.string().min(1).max(128),
17738
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
17739
+ kind: external_exports.literal("usage").optional(),
17740
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
17741
+ iconStyle: external_exports.object({
17742
+ vector: external_exports.object({
17743
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
17744
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
17745
+ paths: external_exports.array(external_exports.object({
17746
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
17747
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
17748
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
17749
+ }).strict()).min(1).max(32)
17750
+ }).strict().optional(),
17751
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
17752
+ borderRadius: external_exports.number().min(0).max(50).optional(),
17753
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
17754
+ }).strict().optional(),
17755
+ installation: harnessInstallationGuideSchema.optional(),
17756
+ notice: localizedTextSchema.optional(),
17757
+ /** The factory accepts a persisted local entrypoint through its construction context. */
17758
+ launchCommand: external_exports.literal(true).optional(),
17759
+ links: external_exports.object({
17760
+ website: documentationUrlSchema.optional(),
17761
+ documentation: documentationUrlSchema.optional(),
17762
+ installation: documentationUrlSchema.optional()
17763
+ }).strict().optional()
17764
+ };
17765
+ var harnessPluginManifestSchema = external_exports.object({
17766
+ manifestVersion: external_exports.literal(1),
17767
+ ...pluginPresentationShape,
17768
+ adapterApiVersion: external_exports.number().int().positive(),
17769
+ entry: pluginRelativeResourceSchema,
17770
+ icon: pluginRelativeResourceSchema.optional()
17771
+ }).strict();
17772
+ var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
17773
+ var harnessPluginDescriptorSchema = external_exports.object({
17774
+ ...pluginPresentationShape,
17775
+ icon: harnessPluginIconSchema.optional()
17776
+ }).strict();
17777
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
17778
+ var harnessPluginListResultSchema = external_exports.object({
17779
+ plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
17780
+ }).strict();
17781
+ var harnessPluginConfigurationSchema = external_exports.object({
17782
+ version: external_exports.literal(1),
17783
+ enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
17784
+ }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
17785
+ message: "Enabled plugin IDs must be unique",
17786
+ path: ["enabled"]
17787
+ });
17788
+
17789
+ // packages/shared-contracts/dist/desktop-extensions.js
17790
+ var DESKTOP_EXTENSION_API_VERSION = 1;
17791
+ var DESKTOP_EXTENSION_LIMIT = 64;
17792
+ var DESKTOP_EXTENSION_ZIP_MAX_BYTES = 64 * 1024 * 1024;
17793
+ var DESKTOP_EXTENSION_MANIFEST_MAX_BYTES = 128 * 1024;
17794
+ var DESKTOP_EXTENSION_SCRIPT_MAX_BYTES = 2 * 1024 * 1024;
17795
+ var DESKTOP_EXTENSION_STYLE_MAX_BYTES = 256 * 1024;
17796
+ var DESKTOP_EXTENSION_ICON_MAX_BYTES = 128 * 1024;
17797
+ var DESKTOP_EXTENSION_SCREENSHOT_LIMIT = 4;
17798
+ var DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES = 512 * 1024;
17799
+ var DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES = 8 * 1024 * 1024;
17800
+ var DESKTOP_EXTENSION_SNAPSHOT_MAX_BYTES = 8 * 1024 * 1024;
17801
+ var DESKTOP_EXTENSION_ASSET_MAX_BYTES = 16 * 1024 * 1024;
17802
+ var DESKTOP_EXTENSION_SETTINGS_MAX_BYTES = 1024 * 1024;
17803
+ var desktopExtensionIdSchema = installedPluginIdSchema;
17804
+ var desktopExtensionSlotSchema = external_exports.enum([
17805
+ "sidebar.thread-layout",
17806
+ "sidebar.thread-badge",
17807
+ "appearance.theme"
17808
+ ]);
17809
+ var desktopExtensionCategorySchema = external_exports.enum([
17810
+ "appearance",
17811
+ "interface",
17812
+ "workflow",
17813
+ "analytics",
17814
+ "integrations",
17815
+ "tools"
17816
+ ]);
17817
+ var extensionName = external_exports.string().trim().min(1).max(128);
17818
+ function desktopExtensionScreenshotMimeType(resource) {
17819
+ switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
17820
+ case "png":
17821
+ return "image/png";
17822
+ case "jpg":
17823
+ case "jpeg":
17824
+ return "image/jpeg";
17825
+ case "webp":
17826
+ return "image/webp";
17827
+ default:
17828
+ return void 0;
17829
+ }
17830
+ }
17831
+ var hasPortableSegments = (resource) => resource.split("/").every((segment) => !/[. ]$/u.test(segment));
17832
+ var imagePathSchema = pluginRelativeResourceSchema.refine((resource) => desktopExtensionScreenshotMimeType(resource) !== void 0 && hasPortableSegments(resource), "Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space");
17833
+ var desktopExtensionHttpUrlSchema = external_exports.string().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu, "Expected an HTTP(S) URL").pipe(external_exports.url({ protocol: /^https?$/u })).refine((value) => {
17834
+ const { username, password } = new URL(value);
17835
+ return !username && !password && !/[\\\s]/u.test(value);
17836
+ }, "URL must not contain credentials, backslashes, or whitespace");
17837
+ function localizedText(text) {
17838
+ return external_exports.strictObject({ en: text, "zh-CN": text });
17839
+ }
17840
+ var desktopExtensionLocalizedTextSchema = localizedText(external_exports.string().trim().min(1));
17841
+ var categoriesSchema = external_exports.array(desktopExtensionCategorySchema).max(desktopExtensionCategorySchema.options.length).refine((categories) => new Set(categories).size === categories.length, "Duplicate categories");
17842
+ var slotsSchema = external_exports.array(desktopExtensionSlotSchema).max(desktopExtensionSlotSchema.options.length).refine((slots) => new Set(slots).size === slots.length, "Duplicate slots");
17843
+ var settingField = {
17844
+ key: external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),
17845
+ label: desktopExtensionLocalizedTextSchema,
17846
+ description: desktopExtensionLocalizedTextSchema.optional()
17847
+ };
17848
+ var numericSetting = {
17849
+ ...settingField,
17850
+ step: external_exports.number().positive().optional(),
17851
+ default: external_exports.number().optional()
17852
+ };
17853
+ var settingOption = external_exports.strictObject({
17854
+ value: external_exports.string(),
17855
+ label: desktopExtensionLocalizedTextSchema
17856
+ });
17857
+ var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("type", [
17858
+ external_exports.strictObject({
17859
+ ...settingField,
17860
+ type: external_exports.literal("boolean"),
17861
+ default: external_exports.boolean().optional()
17862
+ }),
17863
+ external_exports.strictObject({
17864
+ ...settingField,
17865
+ type: external_exports.literal("string"),
17866
+ placeholder: desktopExtensionLocalizedTextSchema.optional(),
17867
+ default: external_exports.string().optional()
17868
+ }),
17869
+ external_exports.strictObject({
17870
+ ...numericSetting,
17871
+ type: external_exports.literal("number"),
17872
+ min: external_exports.number().optional(),
17873
+ max: external_exports.number().optional()
17874
+ }),
17875
+ external_exports.strictObject({
17876
+ ...numericSetting,
17877
+ type: external_exports.literal("range"),
17878
+ min: external_exports.number(),
17879
+ max: external_exports.number()
17880
+ }),
17881
+ external_exports.strictObject({
17882
+ ...settingField,
17883
+ type: external_exports.literal("select"),
17884
+ options: external_exports.array(settingOption).min(1),
17885
+ default: external_exports.string().optional()
17886
+ })
17887
+ ]).superRefine((field2, ctx) => {
17888
+ const issue2 = (path22, message) => ctx.addIssue({ code: "custom", path: [path22], message });
17889
+ if (field2.type === "number" || field2.type === "range") {
17890
+ const { min = -Infinity, max = Infinity, default: value } = field2;
17891
+ if (min > max)
17892
+ issue2("max", "Must be at least min");
17893
+ if (value !== void 0 && (value < min || value > max))
17894
+ issue2("default", "Must be within min and max");
17895
+ } else if (field2.type === "select") {
17896
+ const values = new Set(field2.options.map(({ value }) => value));
17897
+ if (values.size !== field2.options.length)
17898
+ issue2("options", "Duplicate option values");
17899
+ if (field2.default !== void 0 && !values.has(field2.default))
17900
+ issue2("default", "Must match an option value");
17901
+ }
17902
+ });
17903
+ var manifestHeader = external_exports.object({
17904
+ manifestVersion: external_exports.int().positive(),
17905
+ id: desktopExtensionIdSchema,
17906
+ name: external_exports.union([extensionName, localizedText(extensionName)]),
17907
+ version: external_exports.string().min(1).max(128),
17908
+ desktopApi: external_exports.int().positive()
17909
+ }).passthrough();
17910
+ var desktopExtensionManifestSchema = manifestHeader.extend({
17911
+ manifestVersion: external_exports.literal(1),
17912
+ desktopApi: external_exports.literal(DESKTOP_EXTENSION_API_VERSION),
17913
+ description: external_exports.strictObject({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).optional(),
17914
+ author: external_exports.string().trim().min(1).max(128).optional(),
17915
+ repository: desktopExtensionHttpUrlSchema.optional(),
17916
+ details: external_exports.strictObject({ en: external_exports.string().max(16384), "zh-CN": external_exports.string().max(16384).optional() }).optional(),
17917
+ icon: imagePathSchema.optional(),
17918
+ screenshots: external_exports.array(imagePathSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).refine((screenshots) => new Set(screenshots).size === screenshots.length, "Duplicate screenshots").optional(),
17919
+ desktop: external_exports.strictObject({
17920
+ script: pluginRelativeResourceSchema,
17921
+ style: pluginRelativeResourceSchema.optional()
17922
+ }).optional(),
17923
+ backend: external_exports.strictObject({ script: pluginRelativeResourceSchema.refine(hasPortableSegments) }).optional(),
17924
+ slots: slotsSchema.default(() => []),
17925
+ settingsSchema: external_exports.array(desktopExtensionSettingFieldSchema).max(32).refine((fields) => new Set(fields.map(({ key }) => key)).size === fields.length, "Duplicate setting keys").optional(),
17926
+ categories: categoriesSchema.optional()
17927
+ }).strict().refine((manifest) => manifest.desktop !== void 0 || manifest.backend !== void 0, "Expected at least one desktop or backend entry");
17928
+ function parseDesktopExtensionManifest(value) {
17929
+ const header = manifestHeader.safeParse(value);
17930
+ if (!header.success)
17931
+ return { state: "invalid", error: external_exports.prettifyError(header.error) };
17932
+ if (header.data.desktopApi > DESKTOP_EXTENSION_API_VERSION) {
17933
+ return {
17934
+ state: "incompatible",
17935
+ error: `Desktop API ${header.data.desktopApi} requires a newer codexhost`
17936
+ };
17937
+ }
17938
+ const manifest = desktopExtensionManifestSchema.safeParse(value);
17939
+ return manifest.success ? { state: "valid", manifest: manifest.data } : { state: "invalid", error: external_exports.prettifyError(manifest.error) };
17940
+ }
17941
+ var desktopExtensionHashSchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
17942
+ var desktopExtensionStatusSchema = external_exports.strictObject({
17943
+ state: external_exports.enum([
17944
+ "running",
17945
+ "disabled",
17946
+ "invalid",
17947
+ "incompatible",
17948
+ "conflict",
17949
+ "failed",
17950
+ "waiting"
17951
+ ]),
17952
+ hash: desktopExtensionHashSchema.optional(),
17953
+ error: external_exports.string().optional(),
17954
+ conflictWith: desktopExtensionIdSchema.optional()
17955
+ });
17956
+ var desktopExtensionsDiagnosticSchema = external_exports.strictObject({
17957
+ controllerPid: external_exports.int().positive(),
17958
+ targetId: external_exports.string().nullable(),
17959
+ updatedAt: external_exports.iso.datetime(),
17960
+ handledReloadToken: external_exports.uuid().optional(),
17961
+ extensions: external_exports.record(external_exports.string(), desktopExtensionStatusSchema),
17962
+ surfaces: external_exports.record(external_exports.string(), desktopExtensionStatusSchema).optional()
17963
+ });
17964
+ var desktopExtensionTrustTierSchema = external_exports.enum(["official", "community"]);
17965
+ function isGitHubDesktopExtensionZipballUrl(url2) {
17966
+ return url2.origin === "https://api.github.com" && /^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(url2.pathname);
17967
+ }
17968
+ var desktopExtensionZipUrlSchema = desktopExtensionHttpUrlSchema.refine((input) => {
17969
+ const url2 = new URL(input);
17970
+ return /\.zip$/iu.test(url2.pathname) || isGitHubDesktopExtensionZipballUrl(url2) || url2.origin === "https://github.com" && /^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(url2.pathname) || url2.origin === "https://codeload.github.com" && /^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(url2.pathname);
17971
+ }, "Expected a .zip download URL or a GitHub zipball URL");
17972
+ var desktopExtensionCatalogEntrySchema = external_exports.strictObject({
17973
+ id: desktopExtensionIdSchema,
17974
+ version: external_exports.string().trim().min(1).max(128),
17975
+ name: desktopExtensionLocalizedTextSchema.extend({ en: extensionName, "zh-CN": extensionName }),
17976
+ description: localizedText(external_exports.string().trim().min(1).max(4096)),
17977
+ details: localizedText(external_exports.string().trim().min(1).max(16384)).optional(),
17978
+ author: external_exports.string().trim().min(1).max(128),
17979
+ repository: desktopExtensionHttpUrlSchema,
17980
+ stars: external_exports.number().int().min(0).optional(),
17981
+ downloads: external_exports.number().int().min(0).optional(),
17982
+ categories: categoriesSchema.optional(),
17983
+ trustTier: desktopExtensionTrustTierSchema.default("community"),
17984
+ icon: desktopExtensionHttpUrlSchema.optional(),
17985
+ screenshots: external_exports.array(desktopExtensionHttpUrlSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
17986
+ downloadUrl: desktopExtensionZipUrlSchema,
17987
+ sha256: desktopExtensionHashSchema,
17988
+ slots: slotsSchema.optional(),
17989
+ publishedAt: external_exports.string().optional(),
17990
+ updatedAt: external_exports.string().optional(),
17991
+ minCodexHostVersion: external_exports.string().optional()
17992
+ });
17993
+ var desktopExtensionCatalogSchema = external_exports.strictObject({
17994
+ schemaVersion: external_exports.literal(1),
17995
+ generatedAt: external_exports.string(),
17996
+ extensions: external_exports.array(desktopExtensionCatalogEntrySchema).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
18012
17997
  });
18013
- var failedHarnessInspectionSchema = external_exports.object({
18014
- status: external_exports.enum(["notInstalled", "unavailable", "error"]),
18015
- error: codexhostErrorSchema
18016
- }).strict();
18017
- var harnessInspectionSchema = external_exports.union([
18018
- readyHarnessInspectionSchema,
18019
- failedHarnessInspectionSchema
18020
- ]);
18021
- var harnessInspectParamsSchema = external_exports.object({
18022
- harnessId: harnessIdSchema,
18023
- cwd: nonBlankTextSchema2.max(16384).optional(),
18024
- refresh: external_exports.boolean().optional(),
18025
- /** `availability` asks only whether the Harness can run; see `InspectHarnessInput.purpose`. */
18026
- purpose: external_exports.literal("availability").optional()
18027
- }).strict();
18028
- var harnessWebUiOpenParamsSchema = external_exports.object({
18029
- harnessId: harnessIdSchema
18030
- }).strict();
18031
- var harnessWebUiOpenResultSchema = external_exports.object({}).strict();
18032
- var threadModelSelectParamsSchema = external_exports.object({
18033
- threadId: hostThreadIdSchema,
18034
- model: harnessModelRefSchema
18035
- }).strict();
18036
- var threadThinkingSelectParamsSchema = external_exports.object({
18037
- threadId: hostThreadIdSchema,
18038
- thinkingOptionId: harnessThinkingOptionIdSchema
18039
- }).strict();
18040
- var threadInspectionParamsSchema = external_exports.object({
18041
- threadId: hostThreadIdSchema,
18042
- includeReferenceCapability: external_exports.boolean().optional()
18043
- }).strict();
18044
- var codexThreadInspectionSchema = external_exports.object({
18045
- owner: external_exports.literal("codex"),
18046
- locked: external_exports.boolean(),
18047
- effectiveModel: harnessModelRefSchema.optional(),
18048
- resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
18049
- effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
18050
- effectivePermissionModeId: harnessPermissionModeIdSchema.optional(),
18051
- history: harnessHistoryCapabilitiesSchema.optional(),
18052
- supportsThreadReferences: external_exports.literal(true).optional()
18053
- }).strict();
18054
- var externalThreadInspectionSchema = external_exports.object({
18055
- owner: external_exports.literal("external"),
18056
- harnessId: nonBlankTextSchema2.max(256),
18057
- transportModelId: nonBlankTextSchema2.max(1024),
18058
- effectiveModel: harnessModelRefSchema.optional(),
18059
- resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
18060
- effectiveThinkingOptionId: harnessThinkingOptionIdSchema.optional(),
18061
- availableThinkingOptions: harnessThinkingOptionsSchema.optional(),
18062
- effectivePermissionModeId: harnessPermissionModeIdSchema.optional(),
18063
- history: harnessHistoryCapabilitiesSchema,
18064
- usage: threadUsageSnapshotSchema.optional(),
18065
- locked: external_exports.literal(true)
18066
- }).strict();
18067
- var threadInspectionSchema = external_exports.discriminatedUnion("owner", [
18068
- codexThreadInspectionSchema,
18069
- externalThreadInspectionSchema
18070
- ]);
18071
- var threadOwnershipListParamsSchema = external_exports.object({
18072
- threadIds: external_exports.array(hostThreadIdSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
18073
- }).strict().superRefine(({ threadIds }, context) => {
18074
- const seen = /* @__PURE__ */ new Set();
18075
- for (const [index, threadId] of threadIds.entries()) {
18076
- if (seen.has(threadId)) {
18077
- context.addIssue({
18078
- code: "custom",
18079
- message: "Thread ownership-list IDs must be unique",
18080
- path: ["threadIds", index]
18081
- });
17998
+ function resolveDesktopExtensionSlots(enabledOrder, manifests) {
17999
+ const byId = new Map(Array.from(manifests, ({ id: id2, slots = [] }) => [id2, slots]));
18000
+ const owners = /* @__PURE__ */ new Map();
18001
+ const conflicts = /* @__PURE__ */ new Map();
18002
+ const active2 = [];
18003
+ for (const id2 of new Set(enabledOrder)) {
18004
+ const slots = byId.get(id2);
18005
+ if (!slots)
18006
+ continue;
18007
+ const conflictWith = slots.map((slot) => owners.get(slot)).find((owner) => owner !== void 0);
18008
+ if (conflictWith !== void 0) {
18009
+ conflicts.set(id2, conflictWith);
18010
+ continue;
18082
18011
  }
18083
- seen.add(threadId);
18012
+ for (const slot of slots)
18013
+ owners.set(slot, id2);
18014
+ active2.push(id2);
18015
+ }
18016
+ return { active: active2, conflicts };
18017
+ }
18018
+ var desktopExtensionBackendMethodSchema = external_exports.string().trim().min(1).max(128);
18019
+
18020
+ // packages/shared-contracts/dist/host-extensions.js
18021
+ var reservedName = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu;
18022
+ var HOST_EXTENSION_PAGE_API_VERSION = 1;
18023
+ var hostExtensionIdSchema = desktopExtensionIdSchema.refine((id2) => !reservedName.test(id2), "Reserved extension ID");
18024
+ var hostExtensionTargetSchema = external_exports.enum(["desktop", "web"]);
18025
+ var hostExtensionDigestSchema = desktopExtensionHashSchema;
18026
+ var hostExtensionActivationIdSchema = external_exports.uuid();
18027
+ var hostExtensionResourcePathSchema = pluginRelativeResourceSchema.refine((resource) => !/[\x00-\x1f\x7f<>"|*]/u.test(resource) && resource.split("/").every((part) => !/[. ]$/u.test(part) && !reservedName.test(part)), "Expected a portable relative resource path").refine((path22) => path22.split("/").length <= 32, "Extension resources may be at most 32 segments deep");
18028
+ var legacy = desktopExtensionManifestSchema.shape;
18029
+ var localized = (max, min = 0) => external_exports.strictObject({
18030
+ en: external_exports.string().trim().min(min).max(max),
18031
+ "zh-CN": external_exports.string().trim().min(min).max(max)
18032
+ });
18033
+ var resourceWithSuffix = (suffix) => hostExtensionResourcePathSchema.refine((path22) => path22.endsWith(suffix), `Expected a ${suffix} file`);
18034
+ var moduleEntry = resourceWithSuffix(".mjs");
18035
+ var style = resourceWithSuffix(".css").optional();
18036
+ var hostExtensionCanonicalPath = (path22) => path22.normalize("NFC").toLowerCase();
18037
+ var hostExtensionManifestV2Schema = external_exports.strictObject({
18038
+ manifestVersion: external_exports.literal(2),
18039
+ id: hostExtensionIdSchema,
18040
+ name: localized(128, 1),
18041
+ version: external_exports.string().trim().min(1).max(128),
18042
+ description: localized(4096),
18043
+ details: localized(16384).optional(),
18044
+ author: legacy.author,
18045
+ repository: legacy.repository,
18046
+ icon: legacy.icon.refine((path22) => path22 === void 0 || hostExtensionResourcePathSchema.safeParse(path22).success),
18047
+ screenshots: legacy.screenshots.refine((paths) => paths === void 0 || paths.every((path22) => hostExtensionResourcePathSchema.safeParse(path22).success)),
18048
+ categories: legacy.categories,
18049
+ settingsSchema: legacy.settingsSchema,
18050
+ slots: legacy.slots.removeDefault().optional(),
18051
+ page: external_exports.strictObject({
18052
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
18053
+ entry: moduleEntry,
18054
+ style,
18055
+ title: localized(128, 1).optional()
18056
+ }).optional(),
18057
+ widget: external_exports.strictObject({
18058
+ apiVersion: external_exports.literal(HOST_EXTENSION_PAGE_API_VERSION),
18059
+ entry: moduleEntry,
18060
+ style
18061
+ }).optional(),
18062
+ desktop: external_exports.strictObject({ apiVersion: external_exports.literal(1), script: resourceWithSuffix(".js"), style }).optional(),
18063
+ web: external_exports.strictObject({ apiVersion: external_exports.literal(1), entry: moduleEntry.optional(), style }).refine(({ entry, style: style2 }) => entry !== void 0 || style2 !== void 0, "Expected a Web entry or style").optional(),
18064
+ backend: external_exports.strictObject({ apiVersion: external_exports.literal(1), entry: moduleEntry }).optional()
18065
+ }).refine(({ page, widget, desktop, web, backend }) => Boolean(page || widget || desktop || web || backend), "Expected at least one page, widget, desktop, web, or backend entry").refine(({ page, widget, web, backend }) => !backend || [page?.entry, widget?.entry, web?.entry].every((entry) => entry === void 0 || hostExtensionCanonicalPath(entry) !== hostExtensionCanonicalPath(backend.entry)), { path: ["backend", "entry"], message: "A backend entry cannot also be a frontend entry" });
18066
+ function normalizeText(value) {
18067
+ return typeof value === "string" ? { en: value, "zh-CN": value } : { en: value.en, "zh-CN": value["zh-CN"] ?? value.en };
18068
+ }
18069
+ function parseHostExtensionManifest(value) {
18070
+ const header = external_exports.object({ manifestVersion: external_exports.int().positive() }).safeParse(value);
18071
+ if (!header.success)
18072
+ return { state: "invalid", error: external_exports.prettifyError(header.error) };
18073
+ if (header.data.manifestVersion > 2)
18074
+ return {
18075
+ state: "incompatible",
18076
+ error: `Manifest version ${header.data.manifestVersion} requires a newer codexhost`
18077
+ };
18078
+ if (header.data.manifestVersion === 1) {
18079
+ const legacy2 = parseDesktopExtensionManifest(value);
18080
+ if (legacy2.state !== "valid")
18081
+ return legacy2;
18082
+ const { desktopApi, name, description, details, desktop, backend, ...metadata } = legacy2.manifest;
18083
+ value = {
18084
+ ...metadata,
18085
+ manifestVersion: 2,
18086
+ name: normalizeText(name),
18087
+ description: normalizeText(description ?? ""),
18088
+ ...details ? { details: normalizeText(details) } : {},
18089
+ ...desktop ? { desktop: { apiVersion: desktopApi, ...desktop } } : {},
18090
+ ...backend ? { backend: { apiVersion: 1, entry: backend.script } } : {}
18091
+ };
18084
18092
  }
18093
+ const manifest = hostExtensionManifestV2Schema.safeParse(value);
18094
+ return manifest.success ? { state: "valid", manifest: manifest.data } : { state: "invalid", error: external_exports.prettifyError(manifest.error) };
18095
+ }
18096
+ function targetsForCapabilities({ hasPage, hasWidget, hasDesktop, hasWeb, hasBackend }) {
18097
+ if (hasPage || hasWidget || hasBackend && !hasDesktop && !hasWeb)
18098
+ return ["desktop", "web"];
18099
+ const targets = [];
18100
+ if (hasDesktop)
18101
+ targets.push("desktop");
18102
+ if (hasWeb)
18103
+ targets.push("web");
18104
+ return targets;
18105
+ }
18106
+ var hostExtensionBackendMethodSchema = desktopExtensionBackendMethodSchema;
18107
+
18108
+ // packages/shared-contracts/dist/host-extension-management.js
18109
+ var HOST_EXTENSION_ZIP_MAX_BYTES = DESKTOP_EXTENSION_ZIP_MAX_BYTES;
18110
+ var HOST_EXTENSION_CATALOG_URL = "https://raw.githubusercontent.com/BytePioneer-AI/codexhost-extensions-registry/main/catalog.v2.json";
18111
+ var HOST_EXTENSION_CATALOG_MIRROR_URL = "https://cdn.jsdelivr.net/gh/BytePioneer-AI/codexhost-extensions-registry@main/catalog.v2.json";
18112
+ var hostExtensionRevisionSchema = external_exports.int().nonnegative();
18113
+ var hostExtensionConfigurationSchema = external_exports.strictObject({
18114
+ revision: hostExtensionRevisionSchema,
18115
+ enabled: external_exports.array(hostExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs")
18116
+ });
18117
+ var { downloadUrl, ...catalogMetadata } = desktopExtensionCatalogEntrySchema.shape;
18118
+ var hostExtensionCatalogEntrySchema = external_exports.object({
18119
+ ...catalogMetadata,
18120
+ id: hostExtensionIdSchema,
18121
+ format: external_exports.literal("codexhost"),
18122
+ targets: external_exports.array(hostExtensionTargetSchema).min(1).max(2).refine((targets) => new Set(targets).size === targets.length, "Duplicate targets"),
18123
+ apis: external_exports.strictObject({
18124
+ page: external_exports.int().positive().optional(),
18125
+ widget: external_exports.int().positive().optional(),
18126
+ desktop: external_exports.int().positive().optional(),
18127
+ web: external_exports.int().positive().optional(),
18128
+ backend: external_exports.int().positive().optional()
18129
+ }),
18130
+ downloadUrl: downloadUrl.refine((url2) => url2.startsWith("https://"), "Expected HTTPS")
18131
+ }).refine(({ targets, apis }) => {
18132
+ const derived = targetsForCapabilities({
18133
+ hasPage: Boolean(apis.page),
18134
+ hasWidget: Boolean(apis.widget),
18135
+ hasDesktop: Boolean(apis.desktop),
18136
+ hasWeb: Boolean(apis.web),
18137
+ hasBackend: Boolean(apis.backend)
18138
+ });
18139
+ return targets.length === derived.length && derived.every((target2) => targets.includes(target2));
18140
+ }, "Catalog targets must match the declared APIs");
18141
+ var hostExtensionCatalogSchema = external_exports.object({
18142
+ schemaVersion: external_exports.literal(2),
18143
+ generatedAt: external_exports.string().min(1),
18144
+ extensions: external_exports.array(hostExtensionCatalogEntrySchema).max(1e4).refine((entries) => new Set(entries.map(({ id: id2 }) => id2)).size === entries.length, "Duplicate extension IDs")
18145
+ });
18146
+ var hostExtensionsCatalogResultSchema = hostExtensionCatalogSchema.extend({
18147
+ catalogUrl: desktopExtensionHttpUrlSchema,
18148
+ fetchedAt: external_exports.iso.datetime(),
18149
+ cached: external_exports.boolean()
18150
+ });
18151
+ var id = { id: hostExtensionIdSchema };
18152
+ var active = {
18153
+ ...id,
18154
+ activationId: hostExtensionActivationIdSchema,
18155
+ digest: hostExtensionDigestSchema
18156
+ };
18157
+ var optionalActivation = { ...id, activationId: active.activationId.optional() };
18158
+ var filePath = external_exports.string().min(1).max(4096).refine((path22) => /^(?:\/|[a-z]:[/\\])/iu.test(path22) && !path22.includes("\0") && !path22.split(/[/\\]/u).some((part) => part === "." || part === ".."), "Expected an absolute local path without dot segments");
18159
+ var gitRef = external_exports.string().min(1).max(256).refine((ref) => ref.split("/").every((part) => part && /^[a-z0-9_.-]+$/iu.test(part) && part !== "." && part !== ".."), "Invalid GitHub ref");
18160
+ function base643(maxBytes) {
18161
+ return external_exports.string().max(4 * Math.ceil(maxBytes / 3)).refine((value) => {
18162
+ const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
18163
+ return value.length % 4 === 0 && value.length * 3 / 4 - padding <= maxBytes && /^[A-Za-z0-9+/]*={0,2}$/u.test(value);
18164
+ }, "Expected bounded standard padded base64");
18165
+ }
18166
+ var hostExtensionGitHubSourceSchema = external_exports.strictObject({
18167
+ type: external_exports.literal("github"),
18168
+ repository: external_exports.string().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),
18169
+ ref: gitRef.optional(),
18170
+ tag: gitRef.optional(),
18171
+ asset: external_exports.string().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),
18172
+ subpath: hostExtensionResourcePathSchema.optional()
18173
+ }).refine(({ ref, tag, asset }) => !ref || !tag && !asset, "Use either a zipball ref or a release tag/asset");
18174
+ var hostExtensionInstallSourceSchema = external_exports.union([
18175
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
18176
+ hostExtensionGitHubSourceSchema,
18177
+ external_exports.strictObject({ type: external_exports.literal("zip"), base64: base643(HOST_EXTENSION_ZIP_MAX_BYTES).min(4) }),
18178
+ external_exports.strictObject({ type: external_exports.literal("zip"), localZipPath: filePath }),
18179
+ external_exports.strictObject({ type: external_exports.literal("localDir"), localDir: filePath })
18180
+ ]);
18181
+ var hostExtensionProvenanceSchema = external_exports.discriminatedUnion("type", [
18182
+ external_exports.strictObject({ type: external_exports.literal("catalog"), ...id }),
18183
+ hostExtensionGitHubSourceSchema,
18184
+ external_exports.strictObject({ type: external_exports.literal("zip") }),
18185
+ external_exports.strictObject({ type: external_exports.literal("localDir") })
18186
+ ]);
18187
+ var hostExtensionInstallationSchema = external_exports.strictObject({
18188
+ ...active,
18189
+ manifest: hostExtensionManifestV2Schema,
18190
+ installedAt: external_exports.iso.datetime(),
18191
+ source: hostExtensionProvenanceSchema.optional()
18085
18192
  });
18086
- var codexThreadOwnershipSchema = external_exports.object({
18087
- threadId: hostThreadIdSchema,
18088
- owner: external_exports.literal("codex")
18089
- }).strict();
18090
- var externalThreadOwnershipSchema = external_exports.object({
18091
- threadId: hostThreadIdSchema,
18092
- owner: external_exports.literal("external"),
18093
- harnessId: external_exports.string().max(256).pipe(harnessIdSchema)
18094
- }).strict();
18095
- var threadOwnershipSchema = external_exports.discriminatedUnion("owner", [
18096
- codexThreadOwnershipSchema,
18097
- externalThreadOwnershipSchema
18193
+ var rasterDataUrlSchema = (maxBytes) => external_exports.string().max("data:image/jpeg;base64,".length + 4 * Math.ceil(maxBytes / 3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u);
18194
+ var desktopConflict = { desktopConflictWith: hostExtensionIdSchema.optional() };
18195
+ var backendState = external_exports.enum(["none", "inactive", "starting", "running", "failed"]);
18196
+ var hostExtensionListItemSchema = external_exports.discriminatedUnion("state", [
18197
+ hostExtensionInstallationSchema.extend({
18198
+ state: external_exports.literal("valid"),
18199
+ enabled: external_exports.boolean(),
18200
+ ...desktopConflict,
18201
+ iconDataUrl: rasterDataUrlSchema(DESKTOP_EXTENSION_ICON_MAX_BYTES).optional(),
18202
+ screenshotDataUrls: external_exports.array(rasterDataUrlSchema(DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES)).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
18203
+ backendState: backendState.optional(),
18204
+ backendError: external_exports.string().optional()
18205
+ }),
18206
+ external_exports.strictObject({
18207
+ state: external_exports.enum(["invalid", "incompatible"]),
18208
+ id: external_exports.string().min(1),
18209
+ enabled: external_exports.boolean(),
18210
+ error: external_exports.string()
18211
+ })
18098
18212
  ]);
18099
- var threadOwnershipListResultSchema = external_exports.object({
18100
- threads: external_exports.array(threadOwnershipSchema).min(1).max(THREAD_OWNERSHIP_LIST_MAX_LENGTH)
18101
- }).strict().superRefine(({ threads }, context) => {
18102
- const seen = /* @__PURE__ */ new Set();
18103
- for (const [index, thread2] of threads.entries()) {
18104
- if (seen.has(thread2.threadId)) {
18105
- context.addIssue({
18106
- code: "custom",
18107
- message: "Thread ownership-list results must be unique",
18108
- path: ["threads", index, "threadId"]
18109
- });
18110
- }
18111
- seen.add(thread2.threadId);
18112
- }
18213
+ var hostExtensionsListResultSchema = external_exports.strictObject({
18214
+ revision: hostExtensionRevisionSchema,
18215
+ configuration: hostExtensionConfigurationSchema,
18216
+ diagnostics: external_exports.array(external_exports.string()),
18217
+ extensions: external_exports.array(hostExtensionListItemSchema)
18218
+ });
18219
+ var hostExtensionRuntimeEntrySchema = hostExtensionInstallationSchema.extend({
18220
+ ...desktopConflict,
18221
+ settingsRevision: hostExtensionRevisionSchema
18222
+ });
18223
+ var hostExtensionsSnapshotResultSchema = external_exports.strictObject({
18224
+ /** The Host publishes this revision in extensions-changed, independent of enabled.json's revision. */
18225
+ revision: hostExtensionRevisionSchema,
18226
+ // Enabled, valid activations only. A Desktop conflict does not hide other capabilities.
18227
+ extensions: external_exports.array(hostExtensionRuntimeEntrySchema).max(DESKTOP_EXTENSION_LIMIT)
18228
+ });
18229
+ var HOST_EXTENSIONS_RPC = {
18230
+ list: "codexhost/extensions/list",
18231
+ snapshot: "codexhost/extensions/snapshot",
18232
+ catalog: "codexhost/extensions/catalog",
18233
+ install: "codexhost/extensions/install",
18234
+ update: "codexhost/extensions/update",
18235
+ enable: "codexhost/extensions/enable",
18236
+ disable: "codexhost/extensions/disable",
18237
+ uninstall: "codexhost/extensions/uninstall",
18238
+ recover: "codexhost/extensions/recover",
18239
+ asset: "codexhost/extensions/asset",
18240
+ settingsGet: "codexhost/extensions/settings/get",
18241
+ settingsSet: "codexhost/extensions/settings/set",
18242
+ backendInvoke: "codexhost/extensions/backend/invoke"
18243
+ };
18244
+ var HOST_EXTENSION_MANAGEMENT_METHODS = Object.freeze(Object.values(HOST_EXTENSIONS_RPC));
18245
+ var methods = new Set(HOST_EXTENSION_MANAGEMENT_METHODS);
18246
+ var noParams = external_exports.strictObject({});
18247
+ var expectedRevision = { expectedRevision: hostExtensionRevisionSchema };
18248
+ var selection = external_exports.strictObject({ ...id, ...expectedRevision });
18249
+ var installationResult = hostExtensionInstallationSchema.extend({ replaced: external_exports.boolean() });
18250
+ var mutationResult = external_exports.discriminatedUnion("state", [
18251
+ external_exports.strictObject({ state: external_exports.literal("saved"), configuration: hostExtensionConfigurationSchema }),
18252
+ external_exports.strictObject({ state: external_exports.literal("revision-conflict"), revision: hostExtensionRevisionSchema })
18253
+ ]);
18254
+ var hostExtensionsAssetParamsSchema = external_exports.strictObject({
18255
+ ...optionalActivation,
18256
+ digest: active.digest.optional(),
18257
+ path: hostExtensionResourcePathSchema
18258
+ });
18259
+ var hostExtensionsAssetResultSchema = external_exports.strictObject({
18260
+ mimeType: external_exports.string().min(1),
18261
+ base64: base643(DESKTOP_EXTENSION_ASSET_MAX_BYTES),
18262
+ digest: active.digest
18263
+ });
18264
+ var hostExtensionSettingsSchema = external_exports.strictObject({
18265
+ settingsRevision: hostExtensionRevisionSchema,
18266
+ values: jsonObjectSchema
18113
18267
  });
18114
- var threadSteeringInspectParamsSchema = external_exports.object({
18115
- threadId: hostThreadIdSchema,
18116
- /** The text about to be steered; a Harness command always stops and restarts. */
18117
- text: external_exports.string().optional()
18118
- }).strict();
18119
- var threadSteeringContextSchema = external_exports.object({
18120
- kind: external_exports.literal("application"),
18121
- value: external_exports.string().transform((text, context) => {
18122
- try {
18123
- return JSON.parse(text);
18124
- } catch {
18125
- context.addIssue({ code: "custom", message: "Invalid steering context JSON" });
18126
- return external_exports.NEVER;
18127
- }
18128
- }).pipe(external_exports.object({
18129
- expectedTurnId: hostTurnIdSchema,
18130
- clientUserMessageId: external_exports.string().min(1),
18131
- delivery: external_exports.enum(["newTurn", "activeTurn"])
18132
- }).strict())
18133
- }).strict().transform((context) => context.value);
18134
- var threadSteerDeliverySchema = external_exports.enum(["activeTurn", "newTurn"]);
18135
- var threadSteeringInspectResultSchema = external_exports.object({
18136
- delivery: external_exports.enum(["official", "activeTurn", "newTurn"])
18137
- }).strict();
18268
+ var hostExtensionsRpcSchemas = {
18269
+ [HOST_EXTENSIONS_RPC.list]: { params: noParams, result: hostExtensionsListResultSchema },
18270
+ [HOST_EXTENSIONS_RPC.snapshot]: { params: noParams, result: hostExtensionsSnapshotResultSchema },
18271
+ [HOST_EXTENSIONS_RPC.catalog]: {
18272
+ params: external_exports.strictObject({ forceRefresh: external_exports.boolean().optional() }),
18273
+ result: hostExtensionsCatalogResultSchema
18274
+ },
18275
+ [HOST_EXTENSIONS_RPC.install]: {
18276
+ params: external_exports.strictObject({ source: hostExtensionInstallSourceSchema }),
18277
+ result: installationResult
18278
+ },
18279
+ [HOST_EXTENSIONS_RPC.update]: {
18280
+ params: external_exports.strictObject({
18281
+ ...id,
18282
+ expectedDigest: active.digest,
18283
+ expectedActivationId: active.activationId.optional(),
18284
+ source: hostExtensionInstallSourceSchema.optional()
18285
+ }),
18286
+ result: installationResult
18287
+ },
18288
+ [HOST_EXTENSIONS_RPC.enable]: { params: selection, result: mutationResult },
18289
+ [HOST_EXTENSIONS_RPC.disable]: { params: selection, result: mutationResult },
18290
+ [HOST_EXTENSIONS_RPC.uninstall]: {
18291
+ params: external_exports.strictObject({
18292
+ ...id,
18293
+ removeData: external_exports.boolean().optional(),
18294
+ expectedDigest: active.digest.optional()
18295
+ }),
18296
+ result: external_exports.strictObject({ ...id, removed: external_exports.boolean() })
18297
+ },
18298
+ [HOST_EXTENSIONS_RPC.recover]: {
18299
+ params: external_exports.strictObject({ expectedRevision: expectedRevision.expectedRevision.optional() }),
18300
+ result: mutationResult
18301
+ },
18302
+ [HOST_EXTENSIONS_RPC.asset]: {
18303
+ params: hostExtensionsAssetParamsSchema,
18304
+ result: hostExtensionsAssetResultSchema
18305
+ },
18306
+ [HOST_EXTENSIONS_RPC.settingsGet]: {
18307
+ params: external_exports.strictObject(optionalActivation),
18308
+ result: hostExtensionSettingsSchema
18309
+ },
18310
+ [HOST_EXTENSIONS_RPC.settingsSet]: {
18311
+ params: external_exports.strictObject({
18312
+ ...optionalActivation,
18313
+ expectedSettingsRevision: hostExtensionRevisionSchema,
18314
+ values: jsonObjectSchema
18315
+ }),
18316
+ result: hostExtensionSettingsSchema
18317
+ },
18318
+ [HOST_EXTENSIONS_RPC.backendInvoke]: {
18319
+ params: external_exports.strictObject({
18320
+ ...optionalActivation,
18321
+ method: hostExtensionBackendMethodSchema,
18322
+ params: jsonValueSchema.optional()
18323
+ }),
18324
+ result: external_exports.strictObject({ result: jsonValueSchema })
18325
+ }
18326
+ };
18138
18327
 
18139
18328
  // packages/shared-contracts/dist/thread-archive-confirm.js
18140
18329
  var THREAD_ARCHIVE_CONFIRM_METHOD = "codexhost/thread/archive/confirm";
@@ -18197,7 +18386,7 @@ var CLIENT_CHANNEL_METHODS = [
18197
18386
  "codexhost/harness/session-import/list",
18198
18387
  "codexhost/harness/session-import/import",
18199
18388
  // Host settings shared across Desktop and Web.
18200
- ...DESKTOP_EXTENSION_MANAGEMENT_METHODS,
18389
+ ...HOST_EXTENSION_MANAGEMENT_METHODS,
18201
18390
  "codexhost/harness/installation",
18202
18391
  "codexhost/harness/installation/start",
18203
18392
  "codexhost/harness/installation/status",
@@ -18258,6 +18447,11 @@ var clientChannelEventSchema = external_exports.discriminatedUnion("type", [
18258
18447
  cursor: clientChannelCursorSchema,
18259
18448
  revision: external_exports.number().int().nonnegative()
18260
18449
  }),
18450
+ external_exports.object({
18451
+ type: external_exports.literal("extensions-changed"),
18452
+ cursor: clientChannelCursorSchema,
18453
+ revision: hostExtensionRevisionSchema
18454
+ }),
18261
18455
  external_exports.object({
18262
18456
  type: external_exports.literal("hello"),
18263
18457
  version: external_exports.literal(1),
@@ -18694,7 +18888,7 @@ var DEFAULT_IDLE_RELEASE_SETTINGS = Object.freeze({
18694
18888
 
18695
18889
  // packages/shared-contracts/dist/harness-preferences.js
18696
18890
  var harnessPreferenceScopeSchema = external_exports.string().regex(/^external$/u);
18697
- var preferenceHarnessKey = harnessIdSchema.transform((id) => String(id));
18891
+ var preferenceHarnessKey = harnessIdSchema.transform((id2) => String(id2));
18698
18892
  var harnessDefaultConfigurationSchema = external_exports.strictObject({
18699
18893
  model: harnessModelRefSchema.optional(),
18700
18894
  thinkingOptionId: harnessThinkingOptionIdSchema.optional(),
@@ -18704,11 +18898,19 @@ var newThreadDefaultsSchema = external_exports.strictObject({
18704
18898
  lastHarness: harnessIdSchema.optional(),
18705
18899
  byHarness: external_exports.record(preferenceHarnessKey, harnessDefaultConfigurationSchema)
18706
18900
  });
18901
+ var harnessDelegationDefaultSchema = external_exports.strictObject({
18902
+ model: harnessModelRefSchema.optional(),
18903
+ thinkingOptionId: harnessThinkingOptionIdSchema.optional()
18904
+ }).refine((value) => Boolean(value.model || value.thinkingOptionId), "A delegation default must contain a Model or Thinking option");
18905
+ var delegationDefaultsSchema = external_exports.strictObject({
18906
+ byHarness: external_exports.record(preferenceHarnessKey, harnessDelegationDefaultSchema)
18907
+ });
18707
18908
  var modelId = external_exports.string().min(1).max(1024);
18708
18909
  var harnessPreferenceValuesSchema = external_exports.strictObject({
18709
18910
  idleRelease: idleReleaseSettingsSchema.optional(),
18710
18911
  favorites: external_exports.record(preferenceHarnessKey, external_exports.array(modelId).max(2048)).default({}),
18711
- newThread: newThreadDefaultsSchema.optional()
18912
+ newThread: newThreadDefaultsSchema.optional(),
18913
+ delegation: delegationDefaultsSchema.optional()
18712
18914
  });
18713
18915
  var harnessPreferenceSnapshotSchema = external_exports.strictObject({
18714
18916
  scope: harnessPreferenceScopeSchema,
@@ -18736,6 +18938,11 @@ var harnessPreferenceOperationSchema = external_exports.discriminatedUnion("kind
18736
18938
  lastHarness: harnessIdSchema.optional(),
18737
18939
  harnessId: harnessIdSchema.optional(),
18738
18940
  configuration: harnessDefaultConfigurationSchema.optional()
18941
+ }),
18942
+ external_exports.strictObject({
18943
+ kind: external_exports.literal("delegation"),
18944
+ harnessId: harnessIdSchema,
18945
+ configuration: harnessDelegationDefaultSchema.nullable()
18739
18946
  })
18740
18947
  ]);
18741
18948
  var harnessPreferencePatchSchema = external_exports.strictObject({
@@ -19567,9 +19774,12 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
19567
19774
  ...thread,
19568
19775
  epoch: identity,
19569
19776
  modelId: identity.optional(),
19777
+ serviceTier: harnessModelServiceTierSchema.optional(),
19570
19778
  thinkingOptionId: identity.optional(),
19571
19779
  permissionModeId: identity.optional()
19572
- }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting"),
19780
+ }).refine((value) => [value.modelId, value.thinkingOptionId, value.permissionModeId].filter((v) => v !== void 0).length === 1, "Select exactly one remote setting").refine((value) => value.serviceTier === void 0 || value.modelId !== void 0, {
19781
+ message: "A service tier requires a Model ID"
19782
+ }),
19573
19783
  external_exports.strictObject({
19574
19784
  kind: external_exports.literal("prompt"),
19575
19785
  ...thread,
@@ -19619,7 +19829,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
19619
19829
  external_exports.strictObject({ action: external_exports.literal("catalog") }),
19620
19830
  external_exports.strictObject({
19621
19831
  action: external_exports.literal("read-thread"),
19622
- hostId: hostId.refine((id) => id !== "local"),
19832
+ hostId: hostId.refine((id2) => id2 !== "local"),
19623
19833
  input: delegationReadParamsSchema
19624
19834
  }),
19625
19835
  external_exports.strictObject({
@@ -19633,7 +19843,7 @@ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action
19633
19843
  external_exports.strictObject({ action: external_exports.literal("runtime"), hostId }),
19634
19844
  external_exports.strictObject({
19635
19845
  action: external_exports.literal("update"),
19636
- hostId: hostId.refine((id) => id !== "local"),
19846
+ hostId: hostId.refine((id2) => id2 !== "local"),
19637
19847
  version: remoteUpdateParamsSchema.shape.version
19638
19848
  })
19639
19849
  ]);
@@ -19790,8 +20000,8 @@ async function discoverHarnessPlugins(configuredRoots, diagnose = () => void 0,
19790
20000
  diagnose("invalidConfiguration");
19791
20001
  continue;
19792
20002
  }
19793
- for (const id of enabled)
19794
- enabledIds.add(id);
20003
+ for (const id2 of enabled)
20004
+ enabledIds.add(id2);
19795
20005
  try {
19796
20006
  const directories = (await readdir2(root, { withFileTypes: true })).filter((entry) => entry.isDirectory() || entry.isSymbolicLink()).sort((a, b) => a.name.localeCompare(b.name));
19797
20007
  if (directories.length > HARNESS_PLUGIN_LIMIT) {
@@ -19827,11 +20037,11 @@ var HarnessLaunchSettingsStore = class {
19827
20037
  constructor(environment) {
19828
20038
  this.#directory = path8.join(environment.CODEXHOST_DATA_DIR ? path8.resolve(environment.CODEXHOST_DATA_DIR) : path8.join(os.homedir(), ".codexhost"), "harness-launch-settings");
19829
20039
  }
19830
- #file(id) {
19831
- return path8.join(this.#directory, `${harnessPluginIdSchema.parse(id)}.json`);
20040
+ #file(id2) {
20041
+ return path8.join(this.#directory, `${harnessPluginIdSchema.parse(id2)}.json`);
19832
20042
  }
19833
- async #read(id) {
19834
- const file2 = this.#file(id);
20043
+ async #read(id2) {
20044
+ const file2 = this.#file(id2);
19835
20045
  let text;
19836
20046
  try {
19837
20047
  text = await readFile4(file2, "utf8");
@@ -19850,11 +20060,11 @@ var HarnessLaunchSettingsStore = class {
19850
20060
  }
19851
20061
  return parsed;
19852
20062
  }
19853
- #snapshot(id) {
19854
- let initial = this.#initial.get(id);
20063
+ #snapshot(id2) {
20064
+ let initial = this.#initial.get(id2);
19855
20065
  if (!initial) {
19856
- initial = this.#read(id).then((value) => ({ path: value }), (error51) => ({ error: error51 instanceof Error ? error51 : new Error(String(error51)) }));
19857
- this.#initial.set(id, initial);
20066
+ initial = this.#read(id2).then((value) => ({ path: value }), (error51) => ({ error: error51 instanceof Error ? error51 : new Error(String(error51)) }));
20067
+ this.#initial.set(id2, initial);
19858
20068
  }
19859
20069
  return initial;
19860
20070
  }
@@ -19862,11 +20072,11 @@ var HarnessLaunchSettingsStore = class {
19862
20072
  * Capture the value used to construct this Host's Adapter; changes require a restart. A failed
19863
20073
  * read is remembered for restart reporting but not reused: the next call reads the file again.
19864
20074
  */
19865
- async initialCommand(id) {
19866
- const cached2 = this.#initial.get(id);
20075
+ async initialCommand(id2) {
20076
+ const cached2 = this.#initial.get(id2);
19867
20077
  if (cached2 && "error" in await cached2)
19868
- this.#initial.delete(id);
19869
- const snapshot = await this.#snapshot(id);
20078
+ this.#initial.delete(id2);
20079
+ const snapshot = await this.#snapshot(id2);
19870
20080
  if ("error" in snapshot)
19871
20081
  throw snapshot.error;
19872
20082
  return snapshot.path ?? void 0;
@@ -19875,15 +20085,15 @@ var HarnessLaunchSettingsStore = class {
19875
20085
  #restartRequired(snapshot, value) {
19876
20086
  return "error" in snapshot || value !== snapshot.path;
19877
20087
  }
19878
- async get(id) {
19879
- const snapshot = await this.#snapshot(id);
19880
- const value = await this.#read(id);
20088
+ async get(id2) {
20089
+ const snapshot = await this.#snapshot(id2);
20090
+ const value = await this.#read(id2);
19881
20091
  return { path: value, restartRequired: this.#restartRequired(snapshot, value) };
19882
20092
  }
19883
20093
  /** Replaces the file without reading it, so an unreadable file can always be repaired. */
19884
- async set(id, value) {
19885
- const snapshot = await this.#snapshot(id);
19886
- const file2 = this.#file(id);
20094
+ async set(id2, value) {
20095
+ const snapshot = await this.#snapshot(id2);
20096
+ const file2 = this.#file(id2);
19887
20097
  if (value === null) {
19888
20098
  await rm3(file2, { force: true });
19889
20099
  } else {
@@ -19907,435 +20117,333 @@ var HarnessLaunchSettingsStore = class {
19907
20117
  }
19908
20118
  };
19909
20119
 
19910
- // packages/harness-plugin-files/dist/extension-discovery.js
19911
- import { createHash as createHash2 } from "node:crypto";
19912
- import { lstat as lstat4, readdir as readdir3, realpath as realpath3, stat as stat3 } from "node:fs/promises";
20120
+ // packages/harness-plugin-files/dist/host-extension-io.js
20121
+ import { constants } from "node:fs";
20122
+ import { lstat as lstat4, mkdir as mkdir4, open as open4, realpath as realpath3, rename as rename4, rm as rm4, writeFile as writeFile4 } from "node:fs/promises";
19913
20123
  import path9 from "node:path";
19914
- var DESKTOP_EXTENSION_CONFIGURATION_LOCK = ".enabled.lock";
19915
- function desktopExtensionsRoot(dataDirectory2) {
19916
- return path9.join(dataDirectory2, "desktop-extensions");
19917
- }
19918
- function desktopExtensionsStatusPath(dataDirectory2) {
19919
- return path9.join(dataDirectory2, "diagnostics", "desktop-extensions-v1.json");
19920
- }
20124
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
19921
20125
  function extensionFileMissing(error51) {
19922
20126
  return error51 instanceof Error && "code" in error51 && error51.code === "ENOENT";
19923
20127
  }
19924
- async function privateEntry(file2, directory) {
19925
- const info = await lstat4(file2);
20128
+ function assertPrivateExtensionEntry(file2, info, directory) {
19926
20129
  if (directory ? !info.isDirectory() : !info.isFile())
19927
20130
  throw new Error(`${path9.basename(file2)} must be a regular ${directory ? "directory" : "file"}`);
19928
- if (process.getuid && (info.uid !== process.getuid() || (info.mode & 18) !== 0))
20131
+ if (!privateMode(info))
19929
20132
  throw new Error(`${path9.basename(file2)} must belong to the current user and not permit group/other writes`);
19930
20133
  }
19931
- async function privateExtensionDirectory(directory) {
19932
- await privateEntry(directory, true);
19933
- return realpath3(directory);
19934
- }
19935
- async function checkedExtensionResource(root, relative) {
19936
- const resource = await pluginResourcePath(root, relative);
19937
- for (const candidate of /* @__PURE__ */ new Set([resource, path9.resolve(root, relative)])) {
19938
- let dir = path9.dirname(candidate);
19939
- while (dir !== root) {
19940
- await privateEntry(dir, true);
19941
- dir = path9.dirname(dir);
19942
- }
19943
- }
19944
- await privateEntry(resource, false);
19945
- return resource;
19946
- }
19947
- async function readExtensionResource(root, relative, max) {
19948
- return readPluginFile(await checkedExtensionResource(root, relative), max);
19949
- }
19950
- async function readDesktopExtensionBackend(directory, script) {
19951
- try {
19952
- const scriptPath = await checkedExtensionResource(directory, script);
19953
- const bytes = await readPluginFile(scriptPath, DESKTOP_EXTENSION_SCRIPT_MAX_BYTES);
19954
- const { dev, ino } = await stat3(directory, { bigint: true });
19955
- return {
19956
- directory,
19957
- scriptPath,
19958
- hash: createHash2("sha256").update(bytes).digest("hex"),
19959
- installation: `${dev}:${ino}`
19960
- };
19961
- } catch (error51) {
19962
- if (!extensionFileMissing(error51))
19963
- throw error51;
19964
- throw new Error(`Missing backend entry file ${script}`, { cause: error51 });
19965
- }
19966
- }
19967
- var pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
19968
- var jpegSignature = Buffer.from([255, 216, 255]);
19969
- var riffSignature = Buffer.from("RIFF");
19970
- var webpSignature = Buffer.from("WEBP");
19971
- async function readDesktopExtensionImage(root, relative, maxBytes, label) {
19972
- try {
19973
- const mime = desktopExtensionScreenshotMimeType(relative);
19974
- if (!mime)
19975
- throw new Error("Unsupported image extension");
19976
- const bytes = await readExtensionResource(root, relative, maxBytes);
19977
- const matches = mime === "image/png" ? bytes.subarray(0, 8).equals(pngSignature) : mime === "image/jpeg" ? bytes.subarray(0, 3).equals(jpegSignature) : bytes.subarray(0, 4).equals(riffSignature) && bytes.subarray(8, 12).equals(webpSignature);
19978
- if (!matches)
19979
- throw new Error(`File signature does not match ${mime}`);
19980
- return { bytes, mime };
19981
- } catch (error51) {
19982
- const reason = extensionFileMissing(error51) ? "file not found" : error51 instanceof Error ? error51.message : String(error51);
19983
- throw new Error(`${label} ${JSON.stringify(relative)}: ${reason}`, { cause: error51 });
19984
- }
19985
- }
19986
- function readDesktopExtensionIcon(root, relative) {
19987
- return readDesktopExtensionImage(root, relative, DESKTOP_EXTENSION_ICON_MAX_BYTES, "Icon");
19988
- }
19989
- function readDesktopExtensionScreenshot(root, relative) {
19990
- return readDesktopExtensionImage(root, relative, DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES, "Screenshot");
19991
- }
19992
- function toImageDataUrl({ bytes, mime }) {
19993
- return `data:${mime};base64,${bytes.toString("base64")}`;
19994
- }
19995
- function isDesktopExtensionTransactionEntry(name) {
19996
- return name === DESKTOP_EXTENSION_CONFIGURATION_LOCK || /^\.(?:staging|backup)-/u.test(name);
19997
- }
19998
- async function discover(root, id, screenshotBudget) {
19999
- try {
20000
- if (!desktopExtensionIdSchema.safeParse(id).success)
20001
- throw new Error("Invalid extension directory name");
20002
- const directory = await privateExtensionDirectory(path9.join(root, id));
20003
- const bytes = await readExtensionResource(directory, "manifest.json", DESKTOP_EXTENSION_MANIFEST_MAX_BYTES);
20004
- const data = JSON.parse(bytes.toString("utf8"));
20005
- if (!data || typeof data !== "object" || !("id" in data) || data.id !== id)
20006
- throw new Error("Manifest id must match the directory name");
20007
- const parsed = parseDesktopExtensionManifest(data);
20008
- if (parsed.state !== "valid")
20009
- return { id, ...parsed };
20010
- const { desktop, backend } = parsed.manifest;
20011
- const [script, style, backendEntry] = await Promise.all([
20012
- desktop ? readExtensionResource(directory, desktop.script, DESKTOP_EXTENSION_SCRIPT_MAX_BYTES) : void 0,
20013
- desktop?.style ? readExtensionResource(directory, desktop.style, DESKTOP_EXTENSION_STYLE_MAX_BYTES) : void 0,
20014
- backend ? readDesktopExtensionBackend(directory, backend.script) : void 0
20015
- ]);
20016
- const zero = Buffer.from([0]);
20017
- const hash2 = createHash2("sha256").update(bytes).update(zero);
20018
- if (script)
20019
- hash2.update(script);
20020
- hash2.update(zero);
20021
- if (style)
20022
- hash2.update(style);
20023
- const decoder = new TextDecoder("utf-8", { fatal: true });
20024
- const item = {
20025
- id,
20026
- state: "valid",
20027
- manifest: parsed.manifest,
20028
- hash: hash2.digest("hex"),
20029
- ...script ? { script: decoder.decode(script) } : {},
20030
- ...style ? { style: decoder.decode(style) } : {},
20031
- ...backendEntry ? { backend: backendEntry } : {}
20032
- };
20033
- if (parsed.manifest.icon) {
20034
- const icon = await readDesktopExtensionIcon(directory, parsed.manifest.icon).catch(() => void 0);
20035
- if (icon)
20036
- item.iconDataUrl = toImageDataUrl(icon);
20037
- }
20038
- const screenshots = [];
20039
- let screenshotBytes = 0;
20040
- for (const relative of parsed.manifest.screenshots ?? []) {
20041
- const screenshot = await readDesktopExtensionScreenshot(directory, relative);
20042
- screenshots.push(screenshot);
20043
- screenshotBytes += screenshot.bytes.length;
20044
- }
20045
- if (screenshotBytes > screenshotBudget.remaining) {
20046
- screenshotBudget.omitted = true;
20047
- } else if (screenshots.length) {
20048
- screenshotBudget.remaining -= screenshotBytes;
20049
- item.screenshotDataUrls = screenshots.map(toImageDataUrl);
20050
- }
20051
- return item;
20052
- } catch (error51) {
20053
- return { id, state: "invalid", error: error51 instanceof Error ? error51.message : String(error51) };
20054
- }
20055
- }
20056
- async function discoverDesktopExtensions(configuredRoot) {
20057
- try {
20058
- const root = await privateExtensionDirectory(configuredRoot);
20059
- const names = (await readdir3(root, { withFileTypes: true })).filter((entry) => !isDesktopExtensionTransactionEntry(entry.name) && (entry.isDirectory() || entry.isSymbolicLink())).map((entry) => entry.name).sort();
20060
- if (names.length > DESKTOP_EXTENSION_LIMIT)
20061
- return {
20062
- extensions: [],
20063
- diagnostic: `At most ${DESKTOP_EXTENSION_LIMIT} extensions are supported`
20064
- };
20065
- const extensions = [];
20066
- const screenshotBudget = {
20067
- remaining: DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES,
20068
- omitted: false
20069
- };
20070
- for (const id of names)
20071
- extensions.push(await discover(root, id, screenshotBudget));
20072
- return {
20073
- extensions,
20074
- ...screenshotBudget.omitted ? {
20075
- diagnostic: "Desktop extension screenshot list size limit exceeded; some previews were omitted"
20076
- } : {}
20077
- };
20078
- } catch (error51) {
20079
- return {
20080
- extensions: [],
20081
- ...extensionFileMissing(error51) ? {} : { diagnostic: error51 instanceof Error ? error51.message : String(error51) }
20082
- };
20083
- }
20084
- }
20085
-
20086
- // packages/harness-plugin-files/dist/extension-configuration.js
20087
- var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
20088
- import { randomUUID as randomUUID4 } from "node:crypto";
20089
- import { mkdir as mkdir4, rename as rename4, rm as rm4, writeFile as writeFile4 } from "node:fs/promises";
20090
- import path10 from "node:path";
20091
- var CONFIG_FILE = "enabled.json";
20092
- function missingDesktopExtensionConfiguration(error51) {
20093
- const configuration = { version: 1, revision: 0, enabled: [] };
20094
- return extensionFileMissing(error51) ? { configuration } : {
20095
- configuration,
20096
- diagnostic: `Invalid extension configuration: ${error51 instanceof Error ? error51.message : String(error51)}`
20097
- };
20134
+ async function privateExtensionDirectory(directory) {
20135
+ assertPrivateExtensionEntry(directory, await lstat4(directory), true);
20136
+ return realpath3(directory);
20098
20137
  }
20099
- async function readDesktopExtensionConfiguration(root) {
20138
+ var hostExtensionsRoot = (dataDir) => path9.join(dataDir, "host-extensions");
20139
+ var utf8 = new TextDecoder("utf-8", { fatal: true });
20140
+ var errorMessage2 = (error51) => error51 instanceof Error ? error51.message : String(error51);
20141
+ async function ifMissing(operation) {
20100
20142
  try {
20101
- const directory = await privateExtensionDirectory(root);
20102
- const bytes = await readExtensionResource(directory, CONFIG_FILE, DESKTOP_EXTENSION_MANIFEST_MAX_BYTES);
20103
- return {
20104
- configuration: desktopExtensionConfigurationSchema.parse(JSON.parse(bytes.toString("utf8")))
20105
- };
20143
+ return await operation();
20106
20144
  } catch (error51) {
20107
- return missingDesktopExtensionConfiguration(error51);
20145
+ if (!extensionFileMissing(error51))
20146
+ throw error51;
20147
+ return void 0;
20108
20148
  }
20109
20149
  }
20110
- var DesktopExtensionRevisionConflict = class extends Error {
20111
- revision;
20112
- constructor(revision) {
20113
- super("Extension selection changed; refresh and try again");
20114
- this.revision = revision;
20115
- }
20116
- };
20117
- async function writeDesktopExtensionConfiguration(root, expectedRevision, update) {
20118
- return withDesktopExtensionConfiguration(root, async ({ configuration, save }) => {
20119
- if (expectedRevision !== void 0 && expectedRevision !== configuration.revision)
20120
- throw new DesktopExtensionRevisionConflict(configuration.revision);
20121
- return save(await update(configuration));
20122
- });
20150
+ async function storeRoot(root, create) {
20151
+ if (create)
20152
+ await mkdir4(root, { recursive: true, mode: 448 });
20153
+ return privateExtensionDirectory(root);
20123
20154
  }
20124
- async function withDesktopExtensionConfiguration(root, operation) {
20125
- await mkdir4(root, { recursive: true, mode: 448 });
20126
- const directory = await privateExtensionDirectory(root);
20127
- return withDesktopExtensionDirectoryLock(directory, async (assertLocked) => {
20128
- const { configuration } = await readDesktopExtensionConfiguration(directory);
20129
- return operation({
20130
- directory,
20131
- configuration,
20132
- async save(update) {
20133
- const next = desktopExtensionConfigurationSchema.parse({
20134
- ...configuration,
20135
- ...update,
20136
- revision: configuration.revision + 1
20137
- });
20138
- const temporary = path10.join(directory, `.enabled-${randomUUID4()}.tmp`);
20139
- try {
20140
- await writeFile4(temporary, `${JSON.stringify(next)}
20141
- `, { mode: 384, flag: "wx" });
20142
- assertLocked();
20143
- await rename4(temporary, path10.join(directory, CONFIG_FILE));
20144
- } catch (error51) {
20145
- await rm4(temporary, { force: true }).catch(() => void 0);
20146
- throw error51;
20147
- }
20148
- return next;
20149
- }
20155
+ async function storeChild(root, name, create = false) {
20156
+ const directory = path9.join(root, name);
20157
+ if (create)
20158
+ await mkdir4(directory, { mode: 448 }).catch((error51) => {
20159
+ if (error51.code !== "EEXIST")
20160
+ throw error51;
20150
20161
  });
20151
- });
20152
- }
20153
- async function withDesktopExtensionDirectoryLock(directory, operation) {
20154
- let compromised;
20155
- const release = await import_proper_lockfile.default.lock(directory, {
20156
- lockfilePath: path10.join(directory, DESKTOP_EXTENSION_CONFIGURATION_LOCK),
20157
- retries: { retries: 24, minTimeout: 50, maxTimeout: 500 },
20158
- onCompromised(error51) {
20159
- compromised = error51;
20160
- }
20161
- });
20162
- const assertLocked = () => {
20163
- if (compromised)
20164
- throw compromised;
20165
- };
20162
+ return privateExtensionDirectory(directory);
20163
+ }
20164
+ async function readHostFile(root, relative, max, owned = true) {
20165
+ const parts = hostExtensionResourcePathSchema.parse(relative).split("/");
20166
+ const leaf = parts.pop();
20167
+ if (!leaf)
20168
+ throw new Error(`No file name for ${relative}`);
20169
+ let directory = root;
20170
+ for (const part of parts) {
20171
+ directory = path9.join(directory, part);
20172
+ const info2 = await lstat4(directory);
20173
+ if (!info2.isDirectory() || owned && !privateMode(info2))
20174
+ throw new Error(`Unsafe directory for ${relative}`);
20175
+ }
20176
+ const target2 = path9.join(directory, leaf);
20177
+ const info = await lstat4(target2);
20178
+ if (!info.isFile() || info.nlink !== 1 || owned && !privateMode(info))
20179
+ throw new Error(`Unsafe file: ${relative}`);
20180
+ const handle = await open4(target2, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
20166
20181
  try {
20167
- const result = await operation(assertLocked);
20168
- assertLocked();
20169
- return result;
20182
+ const opened = await handle.stat();
20183
+ if (!opened.isFile() || opened.dev !== info.dev || opened.ino !== info.ino || opened.nlink !== 1 || owned && !privateMode(opened))
20184
+ throw new Error(`File changed while opening: ${relative}`);
20185
+ if (opened.size > max)
20186
+ throw new Error(`File exceeds its size limit: ${relative}`);
20187
+ const buffer = Buffer.allocUnsafe(opened.size + 1);
20188
+ let offset = 0;
20189
+ while (offset < buffer.length) {
20190
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
20191
+ if (!bytesRead)
20192
+ break;
20193
+ offset += bytesRead;
20194
+ }
20195
+ if (offset !== opened.size)
20196
+ throw new Error(`File changed while reading: ${relative}`);
20197
+ return buffer.subarray(0, offset);
20170
20198
  } finally {
20171
- if (!compromised)
20172
- await release();
20199
+ await handle.close();
20173
20200
  }
20174
20201
  }
20202
+ function privateMode({ uid, mode }) {
20203
+ return !process.getuid || uid === process.getuid() && (mode & 18) === 0;
20204
+ }
20175
20205
 
20176
- // packages/harness-plugin-files/dist/extension-management.js
20177
- import { randomUUID as randomUUID5 } from "node:crypto";
20178
- import { readFile as readFile5 } from "node:fs/promises";
20179
- var MAX_STATUS_AGE_MS = 15e3;
20180
- var DesktopExtensionSelectionError = class extends Error {
20181
- };
20182
- var DesktopExtensionSlotConflict = class extends Error {
20183
- conflictWith;
20184
- constructor(conflictWith) {
20185
- super(`Slot already occupied by ${conflictWith}`);
20186
- this.conflictWith = conflictWith;
20206
+ // packages/harness-plugin-files/dist/desktop-extension-artwork.js
20207
+ var pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
20208
+ var jpegSignature = Buffer.from([255, 216, 255]);
20209
+ var riffSignature = Buffer.from("RIFF");
20210
+ var webpSignature = Buffer.from("WEBP");
20211
+
20212
+ // packages/harness-plugin-files/dist/host-extension-files.js
20213
+ import { mkdir as mkdir5, mkdtemp, readdir as readdir3, rename as rename5, rm as rm5, writeFile as writeFile5 } from "node:fs/promises";
20214
+
20215
+ // packages/harness-plugin-files/dist/host-extension-package.js
20216
+ import { createHash as createHash2 } from "node:crypto";
20217
+ import path10 from "node:path";
20218
+ var PACKAGE_INDEX = ".host-extension-generation.json";
20219
+ var MAX_INDEX_BYTES = 8 * 1024 * 1024;
20220
+ var MAX_PACKAGE_BYTES = 256 * 1024 * 1024;
20221
+ var MAX_ENTRIES = 1e4;
20222
+ var sha256 = (bytes) => createHash2("sha256").update(bytes).digest("hex");
20223
+ var allowedSuffix = /\.(?:js|mjs|cjs|css|json|png|jpe?g|webp|gif|woff2|md|txt|svg|ts|tsx|ya?ml)$/iu;
20224
+ function packageLimit(resource) {
20225
+ if (hostExtensionCanonicalPath(resource) === PACKAGE_INDEX || !(allowedSuffix.test(resource) || /^(?:licen[cs]e|notice|\.gitignore|\.gitattributes)$/iu.test(path10.posix.basename(resource))))
20226
+ throw new Error(`Unsupported extension package file: ${resource}`);
20227
+ if (resource === "manifest.json")
20228
+ return DESKTOP_EXTENSION_MANIFEST_MAX_BYTES;
20229
+ if (/\.[cm]?js$/iu.test(resource))
20230
+ return DESKTOP_EXTENSION_SCRIPT_MAX_BYTES;
20231
+ if (/\.css$/iu.test(resource))
20232
+ return DESKTOP_EXTENSION_STYLE_MAX_BYTES;
20233
+ return DESKTOP_EXTENSION_ASSET_MAX_BYTES;
20234
+ }
20235
+ async function readHostPackageIndex(directory, digest) {
20236
+ const bytes = await readHostFile(directory, PACKAGE_INDEX, MAX_INDEX_BYTES);
20237
+ if (sha256(bytes) !== digest)
20238
+ throw new Error("Extension package index digest mismatch");
20239
+ const entries = JSON.parse(utf8.decode(bytes));
20240
+ if (!Array.isArray(entries) || entries.length > MAX_ENTRIES)
20241
+ throw new Error("Invalid extension package index");
20242
+ const index = /* @__PURE__ */ new Map();
20243
+ for (const row of entries) {
20244
+ if (!Array.isArray(row) || row.length !== 2)
20245
+ throw new Error("Invalid extension package index entry");
20246
+ const resource = hostExtensionResourcePathSchema.parse(row[0]);
20247
+ packageLimit(resource);
20248
+ if (index.has(resource))
20249
+ throw new Error("Duplicate extension package index entry");
20250
+ index.set(resource, hostExtensionDigestSchema.parse(row[1]));
20251
+ }
20252
+ return index;
20253
+ }
20254
+ function indexedRead(directory, index) {
20255
+ return async (resource, limit) => {
20256
+ const hash2 = index.get(resource);
20257
+ if (!hash2)
20258
+ throw new Error(`File is missing from the package index: ${resource}`);
20259
+ const bytes = await readHostFile(directory, resource, limit);
20260
+ if (sha256(bytes) !== hash2)
20261
+ throw new Error(`Extension file digest mismatch: ${resource}`);
20262
+ return bytes;
20263
+ };
20264
+ }
20265
+ var InvalidHostExtensionManifest = class extends Error {
20266
+ state;
20267
+ constructor(state, message) {
20268
+ super(message);
20269
+ this.state = state;
20187
20270
  }
20188
20271
  };
20189
- async function readDesktopExtensionSnapshot(root, { skipScanIfNoneEnabled = false } = {}) {
20190
- let directory;
20191
- try {
20192
- directory = await privateExtensionDirectory(root);
20193
- } catch (error51) {
20194
- return {
20195
- selection: missingDesktopExtensionConfiguration(error51),
20196
- discovery: {
20197
- extensions: [],
20198
- ...!extensionFileMissing(error51) && {
20199
- diagnostic: error51 instanceof Error ? error51.message : String(error51)
20200
- }
20201
- }
20202
- };
20203
- }
20204
- return withDesktopExtensionDirectoryLock(directory, async () => {
20205
- const selection = await readDesktopExtensionConfiguration(directory);
20206
- const discovery = skipScanIfNoneEnabled && !selection.configuration.enabled.length ? { extensions: [] } : await discoverDesktopExtensions(directory);
20207
- return { selection, discovery };
20208
- });
20272
+ async function readHostManifest(read) {
20273
+ const result = parseHostExtensionManifest(JSON.parse(utf8.decode(await read("manifest.json", DESKTOP_EXTENSION_MANIFEST_MAX_BYTES))));
20274
+ if (result.state !== "valid")
20275
+ throw new InvalidHostExtensionManifest(result.state, result.error);
20276
+ return result.manifest;
20277
+ }
20278
+ function hostFrontendEntries({ page, widget, desktop, web }) {
20279
+ return [page?.entry, widget?.entry, desktop?.script, web?.entry];
20280
+ }
20281
+ function hostFrontendStyles({ page, widget, desktop, web }) {
20282
+ return [page?.style, widget?.style, desktop?.style, web?.style];
20283
+ }
20284
+ async function image(read, resource, limit) {
20285
+ const bytes = await read(resource, limit);
20286
+ const mime = desktopExtensionScreenshotMimeType(resource);
20287
+ const valid = mime === "image/png" ? bytes.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex")) : mime === "image/jpeg" ? bytes.subarray(0, 3).equals(Buffer.from("ffd8ff", "hex")) : mime === "image/webp" && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP";
20288
+ if (!valid)
20289
+ throw new Error(`Invalid image signature: ${resource}`);
20290
+ return { bytes, mime };
20291
+ }
20292
+ async function validateHostPackageEntries(manifest, read) {
20293
+ for (const script of [...hostFrontendEntries(manifest), manifest.backend?.entry])
20294
+ if (script)
20295
+ utf8.decode(await read(script, DESKTOP_EXTENSION_SCRIPT_MAX_BYTES));
20296
+ for (const style2 of hostFrontendStyles(manifest))
20297
+ if (style2)
20298
+ utf8.decode(await read(style2, DESKTOP_EXTENSION_STYLE_MAX_BYTES));
20299
+ const icon = manifest.icon && await image(read, manifest.icon, DESKTOP_EXTENSION_ICON_MAX_BYTES);
20300
+ const screenshots = [];
20301
+ for (const resource of manifest.screenshots ?? [])
20302
+ screenshots.push(await image(read, resource, DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES));
20303
+ return { icon, screenshots };
20209
20304
  }
20210
- async function listDesktopExtensions(dataDirectory2) {
20211
- const [{ discovery, selection: { configuration, diagnostic } }, status] = await Promise.all([
20212
- readDesktopExtensionSnapshot(desktopExtensionsRoot(dataDirectory2)),
20213
- readStatus(dataDirectory2)
20214
- ]);
20215
- const { conflicts } = resolveDesktopExtensionSlots(configuration.enabled, discovery.extensions.flatMap((item) => item.state === "valid" ? [item.manifest] : []));
20216
- const extensions = discovery.extensions.map((item) => {
20217
- const enabled = configuration.enabled.includes(item.id);
20218
- if (item.state !== "valid")
20219
- return { id: item.id, enabled, status: { state: item.state, error: item.error } };
20220
- const active = status && Object.hasOwn(status.extensions, item.id) ? status.extensions[item.id] : void 0;
20221
- const conflictWith = conflicts.get(item.id);
20222
- const observed = !enabled ? {
20223
- state: "disabled",
20224
- ...active?.state === "disabled" && active.error ? { error: active.error } : {}
20225
- } : conflictWith ? { state: "conflict", conflictWith } : active?.hash === item.hash ? active : { state: "waiting" };
20226
- return {
20227
- id: item.id,
20228
- manifest: item.manifest,
20229
- ...item.iconDataUrl ? { iconDataUrl: item.iconDataUrl } : {},
20230
- ...item.screenshotDataUrls ? { screenshotDataUrls: item.screenshotDataUrls } : {},
20231
- enabled,
20232
- status: observed
20233
- };
20305
+
20306
+ // packages/harness-plugin-files/dist/host-extension-files.js
20307
+ var ACTIVE = "active.json";
20308
+ var ENABLED = "enabled.json";
20309
+ var activeFields = hostExtensionInstallationSchema.omit({ manifest: true, id: true });
20310
+ var activeSchema = activeFields.extend({ generation: hostExtensionActivationIdSchema });
20311
+ function hostExtensionInstallationMetadata({ id: id2, activationId, digest, manifest, installedAt, source }) {
20312
+ return { id: id2, activationId, digest, manifest, installedAt, ...source ? { source } : {} };
20313
+ }
20314
+ var readPointer = (directory) => ifMissing(async () => activeSchema.parse(JSON.parse(utf8.decode(await readHostFile(directory, ACTIVE, 8192)))));
20315
+ async function installationAt(parent, id2, active2) {
20316
+ const directory = await storeChild(parent, active2.generation);
20317
+ const index = await readHostPackageIndex(directory, active2.digest);
20318
+ const read = indexedRead(directory, index);
20319
+ const manifest = await readHostManifest(read);
20320
+ if (id2 !== manifest.id)
20321
+ throw new Error("Manifest id must match the installation directory");
20322
+ const installation = { ...active2, directory, id: id2, manifest };
20323
+ return { installation, read, index };
20324
+ }
20325
+ async function currentAt(root, id2) {
20326
+ const parent = await ifMissing(() => storeChild(root, id2));
20327
+ if (!parent)
20328
+ return;
20329
+ const active2 = await readPointer(parent);
20330
+ if (active2)
20331
+ return { parent, active: active2, ...await installationAt(parent, id2, active2) };
20332
+ }
20333
+ var emptyConfiguration = () => ({ revision: 0, enabled: [] });
20334
+ async function readConfiguration(root) {
20335
+ return await ifMissing(async () => hostExtensionConfigurationSchema.parse(JSON.parse(utf8.decode(await readHostFile(root, ENABLED, 32 * 1024))))) ?? emptyConfiguration();
20336
+ }
20337
+ async function readHostExtensionConfiguration(dataDir) {
20338
+ const root = await ifMissing(() => storeRoot(hostExtensionsRoot(dataDir), false));
20339
+ return root ? readConfiguration(root) : emptyConfiguration();
20340
+ }
20341
+ async function discoverHostExtensions(dataDir) {
20342
+ const diagnostics = [];
20343
+ const configuration = await readHostExtensionConfiguration(dataDir).catch((error51) => {
20344
+ diagnostics.push(`Invalid extension configuration: ${errorMessage2(error51)}`);
20345
+ return emptyConfiguration();
20234
20346
  });
20235
- for (const id of configuration.enabled)
20236
- if (!extensions.some((item) => item.id === id))
20347
+ const installations = [];
20348
+ const extensions = [];
20349
+ const root = await ifMissing(() => storeRoot(hostExtensionsRoot(dataDir), false));
20350
+ if (!root)
20351
+ return { configuration, installations, extensions, diagnostics };
20352
+ const ids = (await readdir3(root, { withFileTypes: true })).filter((entry) => !entry.name.startsWith(".") && (entry.isDirectory() || entry.isSymbolicLink())).map(({ name }) => name).sort();
20353
+ let screenshotBudget = DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES;
20354
+ let omitted = false;
20355
+ for (const id2 of ids) {
20356
+ const enabled = configuration.enabled.includes(id2);
20357
+ try {
20358
+ hostExtensionIdSchema.parse(id2);
20359
+ const resolved = await currentAt(root, id2);
20360
+ if (!resolved)
20361
+ continue;
20362
+ const { installation, read } = resolved;
20363
+ const metadata = hostExtensionInstallationMetadata(installation);
20364
+ const { icon, screenshots } = await validateHostPackageEntries(metadata.manifest, read);
20365
+ const toDataUrl = ({ mime, bytes }) => `data:${mime};base64,${bytes.toString("base64")}`;
20366
+ const size = screenshots.reduce((sum, { bytes }) => sum + bytes.length, 0);
20367
+ const fits = size <= screenshotBudget;
20368
+ if (fits)
20369
+ screenshotBudget -= size;
20370
+ else
20371
+ omitted = true;
20237
20372
  extensions.push({
20238
- id,
20239
- enabled: true,
20240
- status: { state: "invalid", error: "Extension directory not found" }
20373
+ state: "valid",
20374
+ ...metadata,
20375
+ enabled,
20376
+ ...icon ? { iconDataUrl: toDataUrl(icon) } : {},
20377
+ ...fits && screenshots.length ? { screenshotDataUrls: screenshots.map(toDataUrl) } : {}
20241
20378
  });
20242
- return {
20243
- configuration,
20244
- desktopConnected: status !== null,
20245
- diagnostics: [discovery.diagnostic, diagnostic].filter((value) => value !== void 0),
20246
- extensions
20247
- };
20248
- }
20249
- async function updateDesktopExtensionSelection(dataDirectory2, change) {
20250
- const root = desktopExtensionsRoot(dataDirectory2);
20251
- try {
20252
- const configuration = await writeDesktopExtensionConfiguration(root, change.expectedRevision, async ({ enabled }) => {
20253
- if (change.action === "recover")
20254
- return { enabled: [], reloadToken: randomUUID5() };
20255
- if (change.action === "disable")
20256
- return { enabled: enabled.filter((id) => id !== change.id) };
20257
- const { extensions } = await discoverDesktopExtensions(root);
20258
- const item = extensions.find((item2) => item2.id === change.id);
20259
- if (!item || item.state !== "valid")
20260
- throw new DesktopExtensionSelectionError(item?.error ?? "Extension not found");
20261
- const next = enabled.includes(change.id) ? enabled : [...enabled, change.id];
20262
- const { conflicts } = resolveDesktopExtensionSlots(next, extensions.flatMap((item2) => item2.state === "valid" ? [item2.manifest] : []));
20263
- const conflict = conflicts.get(change.id);
20264
- if (conflict)
20265
- throw new DesktopExtensionSlotConflict(conflict);
20266
- return { enabled: next };
20267
- });
20268
- return { state: "saved", configuration };
20269
- } catch (error51) {
20270
- if (error51 instanceof DesktopExtensionRevisionConflict)
20271
- return { state: "revision-conflict", revision: error51.revision };
20272
- if (error51 instanceof DesktopExtensionSlotConflict)
20273
- return { state: "slot-conflict", conflictWith: error51.conflictWith };
20274
- throw error51;
20275
- }
20276
- }
20277
- async function readStatus(dataDirectory2) {
20278
- try {
20279
- const value = desktopExtensionsDiagnosticSchema.parse(JSON.parse(await readFile5(desktopExtensionsStatusPath(dataDirectory2), "utf8")));
20280
- const age = Date.now() - Date.parse(value.updatedAt);
20281
- if (!value.targetId || age < 0 || age > MAX_STATUS_AGE_MS)
20282
- return null;
20283
- try {
20284
- process.kill(value.controllerPid, 0);
20379
+ installations.push(installation);
20285
20380
  } catch (error51) {
20286
- if (error51.code !== "EPERM")
20287
- return null;
20381
+ extensions.push({
20382
+ id: id2,
20383
+ enabled,
20384
+ state: error51 instanceof InvalidHostExtensionManifest ? error51.state : "invalid",
20385
+ error: errorMessage2(error51)
20386
+ });
20288
20387
  }
20289
- return value;
20290
- } catch {
20291
- return null;
20292
20388
  }
20389
+ if (omitted)
20390
+ diagnostics.push("Extension screenshot budget exceeded; some previews were omitted");
20391
+ const { conflicts } = resolveDesktopExtensionSlots(configuration.enabled, installations.filter(({ manifest }) => manifest.desktop).map(({ id: id2, manifest }) => ({ id: id2, slots: manifest.slots ?? [] })));
20392
+ for (const extension of extensions) {
20393
+ const conflict = conflicts.get(extension.id);
20394
+ if (extension.state === "valid" && conflict)
20395
+ extension.desktopConflictWith = conflict;
20396
+ }
20397
+ return { configuration, installations, extensions, diagnostics };
20293
20398
  }
20294
20399
 
20295
- // packages/harness-plugin-files/dist/desktop-extension-catalog.js
20296
- import { constants } from "node:fs";
20297
- import { open as open4 } from "node:fs/promises";
20298
- import path11 from "node:path";
20299
-
20300
- // packages/harness-plugin-files/dist/desktop-extension-seed-catalog.json
20301
- var desktop_extension_seed_catalog_default = {
20302
- schemaVersion: 1,
20303
- generatedAt: "2026-01-01T00:00:00.000Z",
20304
- extensions: []
20305
- };
20306
-
20307
20400
  // packages/harness-plugin-files/dist/desktop-extension-download.js
20308
20401
  var githubHeaders = {
20309
20402
  accept: "application/vnd.github+json",
20310
20403
  "user-agent": "codexhost-desktop-extensions"
20311
20404
  };
20312
- var DesktopExtensionPackageError = class extends Error {
20405
+ var ExtensionDownloadError = class extends Error {
20313
20406
  };
20314
- var ExtensionHttpError = class extends DesktopExtensionPackageError {
20407
+ var ExtensionHttpError = class extends ExtensionDownloadError {
20315
20408
  status;
20316
20409
  constructor(status) {
20317
20410
  super(`Download returned HTTP ${status}`);
20318
20411
  this.status = status;
20319
20412
  }
20320
20413
  };
20321
- async function downloadExtensionBytes(url2, limit, headers) {
20414
+ async function downloadExtensionBytes(url2, limit, headers, { signal: callerSignal, allowUrl }) {
20322
20415
  const parsed = desktopExtensionHttpUrlSchema.safeParse(url2);
20323
20416
  if (!parsed.success)
20324
- throw new DesktopExtensionPackageError("Expected a credential-free HTTP(S) URL");
20417
+ throw new ExtensionDownloadError("Expected a credential-free HTTP(S) URL");
20325
20418
  try {
20326
- if (isGitHubDesktopExtensionZipballUrl(new URL(parsed.data)))
20419
+ let target2 = new URL(parsed.data);
20420
+ if (isGitHubDesktopExtensionZipballUrl(target2))
20327
20421
  headers ??= githubHeaders;
20328
- const response = await fetch(parsed.data, {
20329
- signal: AbortSignal.timeout(12e3),
20330
- redirect: "follow",
20331
- ...headers ? { headers } : {}
20332
- });
20422
+ const timeout = AbortSignal.timeout(12e3);
20423
+ const signal = callerSignal ? AbortSignal.any([timeout, callerSignal]) : timeout;
20424
+ let response;
20425
+ for (let redirects = 0; ; redirects++) {
20426
+ if (!allowUrl(target2))
20427
+ throw new ExtensionDownloadError("Unsafe download URL");
20428
+ response = await fetch(target2.href, {
20429
+ signal,
20430
+ redirect: "manual",
20431
+ ...headers ? { headers } : {}
20432
+ });
20433
+ const location = response.headers.get("location");
20434
+ if (!location || ![301, 302, 303, 307, 308].includes(response.status))
20435
+ break;
20436
+ await response.body?.cancel();
20437
+ if (redirects >= 4)
20438
+ throw new ExtensionDownloadError("Too many download redirects");
20439
+ target2 = new URL(location, target2);
20440
+ }
20333
20441
  const body = response.body;
20334
20442
  if (!response.ok || !body || Number(response.headers.get("content-length")) > limit) {
20335
20443
  await body?.cancel().catch(() => void 0);
20336
20444
  if (!response.ok)
20337
20445
  throw new ExtensionHttpError(response.status);
20338
- throw new DesktopExtensionPackageError("Download is empty or exceeds the size limit");
20446
+ throw new ExtensionDownloadError("Download is empty or exceeds the size limit");
20339
20447
  }
20340
20448
  const reader = body.getReader();
20341
20449
  const chunks = [];
@@ -20347,7 +20455,7 @@ async function downloadExtensionBytes(url2, limit, headers) {
20347
20455
  break;
20348
20456
  size += value.byteLength;
20349
20457
  if (size > limit)
20350
- throw new DesktopExtensionPackageError("Download exceeds the size limit");
20458
+ throw new ExtensionDownloadError("Download exceeds the size limit");
20351
20459
  chunks.push(value);
20352
20460
  }
20353
20461
  } finally {
@@ -20355,467 +20463,121 @@ async function downloadExtensionBytes(url2, limit, headers) {
20355
20463
  }
20356
20464
  return Buffer.concat(chunks, size);
20357
20465
  } catch (error51) {
20358
- if (error51 instanceof DesktopExtensionPackageError)
20359
- throw error51;
20360
- throw new DesktopExtensionPackageError("Download failed or timed out", { cause: error51 });
20361
- }
20362
- }
20363
- async function resolveDesktopExtensionDownload(input) {
20364
- const url2 = desktopExtensionHttpUrlSchema.safeParse(input);
20365
- if (!url2.success)
20366
- throw new DesktopExtensionPackageError("Expected a credential-free HTTP(S) URL");
20367
- const parsed = new URL(url2.data);
20368
- const pathname = /^https:\/\/[^/?#]+([^?#]*)/iu.exec(url2.data)?.[1] ?? "";
20369
- const repository = parsed.origin === "https://github.com" && /^\/([\w-]+)\/([\w-][\w.-]*)(?:\/tree\/([^/]+)(?:\/(.+?))?)?\/?$/u.exec(pathname);
20370
- if (!repository) {
20371
- if (desktopExtensionZipUrlSchema.safeParse(url2.data).success)
20372
- return { url: url2.data };
20373
- throw new DesktopExtensionPackageError("Use a .zip download URL, GitHub repository homepage, or GitHub tree URL");
20374
- }
20375
- const [, owner, repositoryName, encodedRef, encodedSubpath] = repository;
20376
- const repo = repositoryName?.replace(/\.git$/iu, "");
20377
- const api = `https://api.github.com/repos/${owner}/${repo}`;
20378
- if (encodedRef !== void 0) {
20379
- try {
20380
- const ref = decodeURIComponent(encodedRef);
20381
- const parts = encodedSubpath?.split("/").map(decodeURIComponent);
20382
- if (/[\x00-\x1f\x7f\\]/u.test(ref) || ref.split("/").some((part) => !part || part === "." || part === "..") || parts?.some((part) => !part || part === "." || part === ".." || /[\x00-\x1f\x7f/\\]/u.test(part)))
20383
- throw new Error("Invalid ref or subdirectory");
20384
- return {
20385
- url: `${api}/zipball/${encodeURIComponent(ref)}`,
20386
- ...parts ? { subpath: parts.join("/") } : {}
20387
- };
20388
- } catch (error51) {
20389
- throw new DesktopExtensionPackageError("Invalid GitHub tree ref or subdirectory", {
20390
- cause: error51
20391
- });
20392
- }
20393
- }
20394
- const zipball = { url: `${api}/zipball` };
20395
- let release;
20396
- try {
20397
- release = JSON.parse((await downloadExtensionBytes(`${api}/releases/latest`, 1024 * 1024, githubHeaders)).toString("utf8"));
20398
- } catch (error51) {
20399
- if (error51 instanceof ExtensionHttpError && error51.status === 404)
20400
- return zipball;
20401
- if (error51 instanceof DesktopExtensionPackageError)
20466
+ if (error51 instanceof ExtensionDownloadError)
20402
20467
  throw error51;
20403
- throw new DesktopExtensionPackageError("Invalid GitHub Release response", { cause: error51 });
20404
- }
20405
- const assets = release && typeof release === "object" && "assets" in release && release.assets;
20406
- if (Array.isArray(assets)) {
20407
- for (const asset of assets) {
20408
- if (typeof asset?.name !== "string" || !/\.zip$/iu.test(asset.name))
20409
- continue;
20410
- const download2 = desktopExtensionZipUrlSchema.safeParse(asset.browser_download_url);
20411
- if (download2.success) {
20412
- const assetUrl = new URL(download2.data);
20413
- if (assetUrl.origin === "https://github.com" && /\.zip$/iu.test(assetUrl.pathname))
20414
- return { url: download2.data };
20415
- }
20416
- }
20468
+ throw new ExtensionDownloadError("Download failed or timed out", { cause: error51 });
20417
20469
  }
20418
- return zipball;
20419
20470
  }
20420
20471
 
20421
- // packages/harness-plugin-files/dist/desktop-extension-catalog.js
20422
- var PRIMARY = "https://raw.githubusercontent.com/BytePioneer-AI/codexhost-extensions-registry/main/catalog.json";
20423
- var MIRROR = "https://cdn.jsdelivr.net/gh/BytePioneer-AI/codexhost-extensions-registry@main/catalog.json";
20424
- var MAX_BYTES = 2 * 1024 * 1024;
20472
+ // packages/harness-plugin-files/dist/extension-zip.js
20473
+ import { promisify } from "node:util";
20474
+ import { crc32, inflateRaw, inflateRawSync } from "node:zlib";
20475
+ var MAX_UNPACKED_BYTES = 256 * 1024 * 1024;
20476
+ var EXPANSION_FLOOR_BYTES = 16 * 1024 * 1024;
20477
+ var utf82 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
20478
+ var inflate = promisify(inflateRaw);
20479
+
20480
+ // packages/harness-plugin-files/dist/host-extension-sources.js
20425
20481
  var TTL = 5 * 60 * 1e3;
20426
- var fallback = desktopExtensionCatalogSchema.parse(desktop_extension_seed_catalog_default).extensions;
20427
- async function readLocalCatalog(file2) {
20428
- const handle = await open4(file2, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
20429
- try {
20430
- const info = await handle.stat();
20431
- if (!info.isFile() || info.size > MAX_BYTES)
20432
- throw new Error("Invalid local catalog file");
20433
- const buffer = Buffer.alloc(MAX_BYTES + 1);
20434
- let offset = 0;
20435
- while (offset < buffer.length) {
20436
- const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
20437
- if (!bytesRead)
20438
- break;
20439
- offset += bytesRead;
20440
- }
20441
- if (offset > MAX_BYTES)
20442
- throw new Error("Local catalog exceeds the size limit");
20443
- return buffer.subarray(0, offset);
20444
- } finally {
20445
- await handle.close();
20446
- }
20447
- }
20448
- async function fetchCandidate(catalogUrl) {
20449
- const data = path11.isAbsolute(catalogUrl) ? await readLocalCatalog(catalogUrl) : await downloadExtensionBytes(catalogUrl, MAX_BYTES, { accept: "application/json" });
20450
- const { extensions } = desktopExtensionCatalogSchema.parse(JSON.parse(data.toString("utf8")));
20482
+ var httpsDownload = (url2) => url2.protocol === "https:" && !url2.username && !url2.password;
20483
+ var cache;
20484
+ var pending;
20485
+ var PRIMARY_GRACE_MS = 1500;
20486
+ var PRIMARY_FORCE_REFRESH_GRACE_MS = 3e3;
20487
+ function catalogGeneratedAtMs(result) {
20488
+ const parsed = Date.parse(result.generatedAt);
20489
+ return Number.isFinite(parsed) ? parsed : 0;
20490
+ }
20491
+ function pickFresherCatalog(primary, mirror) {
20492
+ return catalogGeneratedAtMs(mirror) > catalogGeneratedAtMs(primary) ? mirror : primary;
20493
+ }
20494
+ async function fetchCatalogFrom(catalogUrl, signal, forceRefresh) {
20495
+ const bytes = await downloadExtensionBytes(catalogUrl, 2 * 1024 * 1024, {
20496
+ accept: "application/json",
20497
+ ...forceRefresh ? { "cache-control": "no-cache" } : {}
20498
+ }, {
20499
+ signal,
20500
+ allowUrl: (url2) => url2.origin === new URL(catalogUrl).origin && httpsDownload(url2)
20501
+ });
20451
20502
  return {
20503
+ ...hostExtensionCatalogSchema.parse(JSON.parse(utf8.decode(bytes))),
20452
20504
  catalogUrl,
20453
- source: "remote",
20454
20505
  fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
20455
- cached: false,
20456
- extensions
20506
+ cached: false
20457
20507
  };
20458
20508
  }
20459
- async function refreshCatalog(override) {
20460
- const candidates = override ? [override] : [PRIMARY, MIRROR];
20509
+ async function raceCatalog(forceRefresh) {
20510
+ const primaryController = new AbortController();
20511
+ const mirrorController = new AbortController();
20512
+ const primaryPromise = fetchCatalogFrom(HOST_EXTENSION_CATALOG_URL, primaryController.signal, forceRefresh);
20513
+ const mirrorPromise = fetchCatalogFrom(HOST_EXTENSION_CATALOG_MIRROR_URL, mirrorController.signal, forceRefresh);
20514
+ primaryPromise.catch(() => void 0);
20515
+ mirrorPromise.catch(() => void 0);
20461
20516
  try {
20462
- return await Promise.any(candidates.map(fetchCandidate));
20463
- } catch {
20517
+ const first = await Promise.any([
20518
+ primaryPromise.then((result) => ({ source: "primary", result })),
20519
+ mirrorPromise.then((result) => ({ source: "mirror", result }))
20520
+ ]);
20521
+ if (first.source === "primary") {
20522
+ mirrorController.abort();
20523
+ return first.result;
20524
+ }
20525
+ const graceMs = forceRefresh ? PRIMARY_FORCE_REFRESH_GRACE_MS : PRIMARY_GRACE_MS;
20526
+ let timer;
20527
+ const primaryWithinGrace = await Promise.race([
20528
+ primaryPromise.catch(() => void 0),
20529
+ new Promise((resolve) => {
20530
+ timer = setTimeout(() => resolve(void 0), graceMs);
20531
+ })
20532
+ ]).finally(() => {
20533
+ if (timer !== void 0)
20534
+ clearTimeout(timer);
20535
+ });
20536
+ if (primaryWithinGrace) {
20537
+ return pickFresherCatalog(primaryWithinGrace, first.result);
20538
+ }
20539
+ primaryController.abort();
20540
+ return first.result;
20541
+ } catch (cause) {
20542
+ throw new Error("Host extension catalog unavailable", { cause });
20543
+ } finally {
20544
+ primaryController.abort();
20545
+ mirrorController.abort();
20464
20546
  }
20465
- return {
20466
- catalogUrl: override ?? PRIMARY,
20467
- source: "fallback",
20468
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
20469
- cached: false,
20470
- extensions: fallback,
20471
- error: "Desktop extension catalog unavailable"
20472
- };
20473
20547
  }
20474
- var cache;
20475
- var pending;
20476
- async function fetchDesktopExtensionCatalog({ forceRefresh, environment = process.env } = {}) {
20477
- const key = environment.CODEXHOST_DESKTOP_EXTENSIONS_CATALOG_URL?.trim() || void 0;
20478
- if (!forceRefresh && cache && cache.key === key && Date.now() < cache.expires)
20548
+ async function fetchHostExtensionCatalog({ forceRefresh = false } = {}) {
20549
+ if (!forceRefresh && cache && Date.now() < cache.expires)
20479
20550
  return { ...structuredClone(cache.result), cached: true };
20480
- if (!forceRefresh && pending && pending.key === key)
20481
- return structuredClone(await pending.promise);
20482
- const request = { key, promise: refreshCatalog(key) };
20551
+ if (pending)
20552
+ return structuredClone(await pending);
20553
+ const request = raceCatalog(forceRefresh);
20483
20554
  pending = request;
20484
20555
  try {
20485
- const result = await request.promise;
20486
- if (pending === request)
20487
- cache = { key, result, expires: Date.now() + TTL };
20556
+ const result = await request;
20557
+ cache = { result, expires: Date.now() + TTL };
20488
20558
  return structuredClone(result);
20489
20559
  } finally {
20490
- if (pending === request)
20491
- pending = void 0;
20492
- }
20493
- }
20494
-
20495
- // packages/harness-plugin-files/dist/desktop-extension-installer.js
20496
- import { createHash as createHash3, randomUUID as randomUUID6 } from "node:crypto";
20497
- import { lstat as lstat5, mkdir as mkdir5, mkdtemp, readdir as readdir4, rename as rename5, rm as rm5, writeFile as writeFile5 } from "node:fs/promises";
20498
- import path12 from "node:path";
20499
- import { Script } from "node:vm";
20500
-
20501
- // packages/harness-plugin-files/dist/desktop-extension-zip.js
20502
- import { crc32, inflateRawSync } from "node:zlib";
20503
- var MAX_UNPACKED_BYTES = 256 * 1024 * 1024;
20504
- var MAX_ENTRIES = 1e4;
20505
- var EXPANSION_RATIO = 200;
20506
- var EXPANSION_FLOOR_BYTES = 16 * 1024 * 1024;
20507
- var END = 101010256;
20508
- var CENTRAL = 33639248;
20509
- var LOCAL = 67324752;
20510
- var utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
20511
- function check2(condition, message) {
20512
- if (!condition)
20513
- throw new Error(`Invalid Desktop extension ZIP: ${message}`);
20514
- }
20515
- function safeName(name, directory) {
20516
- check2(name.length <= 512, "entry path is too long");
20517
- const parts = (directory ? name.slice(0, -1) : name).split("/");
20518
- check2(parts.every((part) => part && part !== "." && part !== ".." && !/[. ]$/u.test(part) && !/[\x00-\x1f\x7f\\<>:"|?*]/u.test(part) && !/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu.test(part)), "unsafe entry path");
20519
- return parts.join("/");
20520
- }
20521
- function readDesktopExtensionZip(zip, subpath) {
20522
- check2(zip.length <= DESKTOP_EXTENSION_ZIP_MAX_BYTES, "archive exceeds the safety size limit");
20523
- const subdirectory = subpath === void 0 ? void 0 : safeName(subpath, false);
20524
- const u16 = (offset) => zip.readUInt16LE(offset);
20525
- const u32 = (offset) => zip.readUInt32LE(offset);
20526
- let end = zip.length - 22;
20527
- const earliest = Math.max(0, end - 65535);
20528
- while (end >= earliest && (u32(end) !== END || end + 22 + u16(end + 20) !== zip.length))
20529
- end--;
20530
- check2(end >= earliest, "missing end of central directory");
20531
- const count2 = u16(end + 10);
20532
- const start = u32(end + 16);
20533
- check2(u16(end + 4) === 0 && u16(end + 6) === 0 && u16(end + 8) === count2, "multi-disk archive");
20534
- check2(start + u32(end + 12) === end, "invalid central directory bounds (ZIP64 is unsupported)");
20535
- check2(count2 > 0 && count2 <= MAX_ENTRIES, `expected 1–${MAX_ENTRIES} entries`);
20536
- const files = /* @__PURE__ */ new Map();
20537
- const paths = /* @__PURE__ */ new Map();
20538
- const ranges = [];
20539
- let total = 0;
20540
- let central = start;
20541
- for (let index = 0; index < count2; index++) {
20542
- check2(central + 46 <= end && u32(central) === CENTRAL, "truncated central entry");
20543
- const flags = u16(central + 8);
20544
- const method = u16(central + 10);
20545
- const crc = u32(central + 16);
20546
- const compressed = u32(central + 20);
20547
- const size = u32(central + 24);
20548
- const nameLength = u16(central + 28);
20549
- const next = central + 46 + nameLength + u16(central + 30) + u16(central + 32);
20550
- const attr = u32(central + 38);
20551
- const type = attr >>> 16 & 61440;
20552
- const local = u32(central + 42);
20553
- check2(next <= end && u16(central + 34) === 0, "invalid central entry bounds");
20554
- check2((flags & ~2062) === 0 && (method === 0 || method === 8), "unsupported ZIP flags or compression");
20555
- const rawName = zip.subarray(central + 46, central + 46 + nameLength);
20556
- const name = utf8.decode(rawName).replaceAll("\\", "/");
20557
- const directory = name.endsWith("/");
20558
- check2(type === 0 || type === (directory ? 16384 : 32768), "symlink or special file");
20559
- check2(directory || !(attr & 16), "inconsistent directory attribute");
20560
- const relative = safeName(name, directory);
20561
- const parts = relative.split("/");
20562
- for (let i = 1; i <= parts.length; i++) {
20563
- const segment = parts.slice(0, i).join("/");
20564
- const key = segment.normalize("NFC").toLowerCase();
20565
- const explicit = i === parts.length;
20566
- const isDirectory = !explicit || directory;
20567
- const previous = paths.get(key);
20568
- check2(!previous || previous.name === segment && previous.directory === isDirectory && !(previous.explicit && explicit), "duplicate or conflicting entry path");
20569
- if (!previous || explicit)
20570
- paths.set(key, { name: segment, directory: isDirectory, explicit });
20571
- }
20572
- check2(local + 30 <= start && u32(local) === LOCAL, "invalid local header");
20573
- const data = local + 30 + nameLength + u16(local + 28);
20574
- check2(data + compressed <= start && u16(local + 26) === nameLength && u16(local + 6) === flags && u16(local + 8) === method && zip.subarray(local + 30, local + 30 + nameLength).equals(rawName), "local header disagrees with central directory");
20575
- let localEnd = data + compressed;
20576
- if (flags & 8) {
20577
- const matches = (offset) => offset + 12 <= start && u32(offset) === crc && u32(offset + 4) === compressed && u32(offset + 8) === size;
20578
- if (localEnd + 4 <= start && u32(localEnd) === 134695760 && matches(localEnd + 4))
20579
- localEnd += 16;
20580
- else {
20581
- check2(matches(localEnd), "invalid data descriptor");
20582
- localEnd += 12;
20583
- }
20584
- } else {
20585
- check2(u32(local + 14) === crc && u32(local + 18) === compressed && u32(local + 22) === size, "local entry sizes or CRC disagree");
20586
- }
20587
- ranges.push({ start: local, end: localEnd });
20588
- total += size;
20589
- check2(total <= MAX_UNPACKED_BYTES, "unpacked data exceeds the safety size limit");
20590
- check2(size <= Math.max(EXPANSION_FLOOR_BYTES, compressed * EXPANSION_RATIO), "entry exceeds the safety compression ratio");
20591
- check2(!directory || size === 0, "directory contains file data");
20592
- const input = zip.subarray(data, data + compressed);
20593
- const bytes = method === 0 ? input : inflateRawSync(input, { maxOutputLength: Math.max(1, size) });
20594
- check2(bytes.length === size && crc32(bytes) === crc, "entry size or CRC mismatch");
20595
- if (!directory)
20596
- files.set(relative, bytes);
20597
- central = next;
20598
- }
20599
- check2(central === end, "incorrect central directory size");
20600
- ranges.sort((a, b) => a.start - b.start);
20601
- let previousEnd = 0;
20602
- for (const { start: start2, end: end2 } of ranges) {
20603
- check2(previousEnd <= start2, "overlapping local entries");
20604
- previousEnd = end2;
20605
- }
20606
- if (subdirectory === void 0 && files.has("manifest.json"))
20607
- return files;
20608
- const roots = [...paths.values()].filter(({ name }) => !name.includes("/"));
20609
- const [wrapper] = roots;
20610
- const prefix = wrapper && `${wrapper.name}/${subdirectory ? `${subdirectory}/` : ""}`;
20611
- check2(roots.length === 1 && wrapper?.directory && prefix && files.has(`${prefix}manifest.json`), subdirectory ? `missing manifest.json in repository subdirectory ${subdirectory}` : "missing manifest.json at the root or inside a single top-level directory");
20612
- const selected = /* @__PURE__ */ new Map();
20613
- for (const [name, bytes] of files)
20614
- if (name.startsWith(prefix))
20615
- selected.set(name.slice(prefix.length), bytes);
20616
- return selected;
20617
- }
20618
-
20619
- // packages/harness-plugin-files/dist/desktop-extension-installer.js
20620
- var utf82 = new TextDecoder("utf-8", { fatal: true });
20621
- function assertPortableId(id) {
20622
- if (!desktopExtensionIdSchema.safeParse(id).success || id === "enabled.json" || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(id))
20623
- throw new DesktopExtensionPackageError("Invalid or reserved extension ID");
20624
- }
20625
- async function pathExists(file2) {
20626
- try {
20627
- const info = await lstat5(file2);
20628
- if (!info.isDirectory() && !info.isSymbolicLink())
20629
- throw new DesktopExtensionPackageError("Extension installation path must be a directory or symlink");
20630
- return true;
20631
- } catch (error51) {
20632
- if (extensionFileMissing(error51))
20633
- return false;
20634
- throw error51;
20635
- }
20636
- }
20637
- async function withInstallationBackup(installed, operation) {
20638
- const backup = path12.join(path12.dirname(installed), `.backup-${path12.basename(installed)}-${randomUUID6()}`);
20639
- const replaced = await pathExists(installed);
20640
- if (replaced)
20641
- await rename5(installed, backup);
20642
- let result;
20643
- try {
20644
- result = await operation(replaced);
20645
- } catch (error51) {
20646
- if (replaced) {
20647
- try {
20648
- await rename5(backup, installed);
20649
- } catch (rollbackError) {
20650
- throw new Error(`Rollback failed; previous extension preserved at ${backup}`, {
20651
- cause: new AggregateError([error51, rollbackError])
20652
- });
20653
- }
20654
- }
20655
- throw error51;
20656
- }
20657
- if (replaced)
20658
- await rm5(backup, { recursive: true, force: true }).catch(() => void 0);
20659
- return result;
20660
- }
20661
- async function installFromZipBuffer({ extensionsRoot, zipBuffer, expectedSha256, subpath }, expected) {
20662
- if (expectedSha256 !== void 0 && createHash3("sha256").update(zipBuffer).digest("hex") !== expectedSha256)
20663
- throw new DesktopExtensionPackageError("Desktop extension ZIP SHA-256 mismatch");
20664
- let files;
20665
- try {
20666
- files = readDesktopExtensionZip(zipBuffer, subpath);
20667
- } catch (error51) {
20668
- throw new DesktopExtensionPackageError(error51 instanceof Error ? error51.message : "Invalid ZIP", {
20669
- cause: error51
20670
- });
20671
- }
20672
- await mkdir5(extensionsRoot, { recursive: true, mode: 448 });
20673
- const root = await privateExtensionDirectory(extensionsRoot);
20674
- const staging = await mkdtemp(path12.join(root, ".staging-"));
20675
- try {
20676
- for (const [relative, bytes] of files) {
20677
- const target2 = path12.join(staging, relative);
20678
- await mkdir5(path12.dirname(target2), { recursive: true, mode: 448 });
20679
- await writeFile5(target2, bytes, { flag: "wx", mode: 384 });
20680
- }
20681
- const manifest = await (async () => {
20682
- try {
20683
- const bytes = await readExtensionResource(staging, "manifest.json", DESKTOP_EXTENSION_MANIFEST_MAX_BYTES);
20684
- const manifest2 = desktopExtensionManifestSchema.parse(JSON.parse(utf82.decode(bytes)));
20685
- if (expected && (manifest2.id !== expected.id || manifest2.version !== expected.version))
20686
- throw new Error("Manifest id or version does not match the catalog entry");
20687
- if (manifest2.desktop) {
20688
- const { script, style } = manifest2.desktop;
20689
- const scriptBytes = await readExtensionResource(staging, script, DESKTOP_EXTENSION_SCRIPT_MAX_BYTES).catch((error51) => {
20690
- if (!extensionFileMissing(error51))
20691
- throw error51;
20692
- throw new Error(`Missing entry file ${script}. Commit the built JavaScript entry or publish a Release .zip.`, { cause: error51 });
20693
- });
20694
- const source = utf82.decode(scriptBytes);
20695
- new Script(`(function(define) { "use strict";
20696
- ${source}
20697
- })`);
20698
- if (style)
20699
- utf82.decode(await readExtensionResource(staging, style, DESKTOP_EXTENSION_STYLE_MAX_BYTES));
20700
- }
20701
- if (manifest2.backend)
20702
- await readDesktopExtensionBackend(staging, manifest2.backend.script);
20703
- if (manifest2.icon)
20704
- await readDesktopExtensionIcon(staging, manifest2.icon);
20705
- for (const screenshot of manifest2.screenshots ?? [])
20706
- await readDesktopExtensionScreenshot(staging, screenshot);
20707
- return manifest2;
20708
- } catch (error51) {
20709
- const reason = error51 instanceof Error ? error51.message : "Invalid manifest or resources";
20710
- throw new DesktopExtensionPackageError(`Invalid extension package: ${reason.slice(0, 768)}`, { cause: error51 });
20711
- }
20712
- })();
20713
- const { id, version: version2 } = manifest;
20714
- assertPortableId(id);
20715
- return await withDesktopExtensionConfiguration(root, async ({ directory, configuration, save }) => {
20716
- const installedPath = path12.join(directory, id);
20717
- if (!await pathExists(installedPath)) {
20718
- const entries = await readdir4(directory, { withFileTypes: true });
20719
- if (entries.filter((entry) => !isDesktopExtensionTransactionEntry(entry.name) && (entry.isDirectory() || entry.isSymbolicLink())).length >= DESKTOP_EXTENSION_LIMIT)
20720
- throw new DesktopExtensionPackageError(`At most ${DESKTOP_EXTENSION_LIMIT} extensions are supported`);
20721
- }
20722
- await save({ enabled: configuration.enabled });
20723
- return withInstallationBackup(installedPath, async (replaced) => {
20724
- await rename5(staging, installedPath);
20725
- return { extensionId: id, version: version2, replaced, installedPath };
20726
- });
20727
- });
20728
- } finally {
20729
- await rm5(staging, { recursive: true, force: true }).catch(() => void 0);
20730
- }
20731
- }
20732
- async function installFromUrl({ extensionsRoot, url: url2, expectedSha256 }) {
20733
- const download2 = await resolveDesktopExtensionDownload(url2);
20734
- const zipBuffer = await downloadExtensionBytes(download2.url, DESKTOP_EXTENSION_ZIP_MAX_BYTES);
20735
- return installFromZipBuffer({
20736
- extensionsRoot,
20737
- zipBuffer,
20738
- expectedSha256,
20739
- subpath: download2.subpath
20740
- });
20741
- }
20742
- var DEFAULT_DESKTOP_EXTENSION_STATS_URL = "https://ext-stats.chost.dev";
20743
- function resolveDesktopExtensionStatsUrl(environment = process.env) {
20744
- const configured = environment.CODEXHOST_DESKTOP_EXTENSIONS_STATS_URL;
20745
- if (configured !== void 0) {
20746
- const trimmed = configured.trim();
20747
- if (!trimmed || /^(?:off|none|false|0)$/iu.test(trimmed))
20748
- return void 0;
20749
- return trimmed;
20750
- }
20751
- if (environment.CODEXHOST_DESKTOP_EXTENSIONS_CATALOG_URL?.trim())
20752
- return void 0;
20753
- return DEFAULT_DESKTOP_EXTENSION_STATS_URL;
20754
- }
20755
- async function reportDesktopExtensionInstall(id, statsUrl) {
20756
- try {
20757
- const { data } = desktopExtensionHttpUrlSchema.safeParse(statsUrl);
20758
- if (data === void 0)
20759
- return;
20760
- const url2 = new URL(data);
20761
- url2.pathname = `${url2.pathname.replace(/\/+$/u, "")}/install/${encodeURIComponent(id)}`;
20762
- url2.search = "";
20763
- url2.hash = "";
20764
- const response = await fetch(url2, {
20765
- method: "POST",
20766
- credentials: "omit",
20767
- redirect: "error",
20768
- signal: AbortSignal.timeout(2e3)
20769
- });
20770
- await response.body?.cancel();
20771
- } catch {
20560
+ pending = void 0;
20772
20561
  }
20773
20562
  }
20774
- async function installFromCatalog({ extensionsRoot, id, ...options }) {
20775
- const { extensions } = await fetchDesktopExtensionCatalog(options);
20776
- const entry = extensions.find((entry2) => entry2.id === id);
20777
- if (!entry)
20778
- throw new DesktopExtensionPackageError("Extension ID was not found in the catalog");
20779
- const zipBuffer = await downloadExtensionBytes(entry.downloadUrl, DESKTOP_EXTENSION_ZIP_MAX_BYTES);
20780
- const installed = await installFromZipBuffer({ extensionsRoot, zipBuffer, expectedSha256: entry.sha256 }, entry);
20781
- void reportDesktopExtensionInstall(installed.extensionId, resolveDesktopExtensionStatsUrl(options.environment ?? process.env));
20782
- return installed;
20783
- }
20784
- async function installDesktopExtension(dataDir, { source }, environment = process.env) {
20785
- const extensionsRoot = desktopExtensionsRoot(dataDir);
20786
- const installed = source.type === "catalog" ? await installFromCatalog({ extensionsRoot, id: source.id, environment }) : source.type === "url" ? await installFromUrl({ extensionsRoot, ...source }) : await installFromZipBuffer({
20787
- extensionsRoot,
20788
- zipBuffer: Buffer.from(source.contentBase64, "base64")
20789
- });
20790
- return { ...installed, list: await listDesktopExtensions(dataDir) };
20791
- }
20792
- async function uninstallDesktopExtension({ dataDir, id }) {
20793
- assertPortableId(id);
20794
- await withDesktopExtensionConfiguration(desktopExtensionsRoot(dataDir), async ({ directory, configuration, save }) => {
20795
- await withInstallationBackup(path12.join(directory, id), async () => {
20796
- await save({ enabled: configuration.enabled.filter((entry) => entry !== id) });
20797
- });
20798
- });
20799
- return { removedId: id, list: await listDesktopExtensions(dataDir) };
20800
- }
20801
20563
 
20802
20564
  // packages/console-server/src/paths.ts
20803
20565
  import os2 from "node:os";
20804
- import path13 from "node:path";
20566
+ import path11 from "node:path";
20805
20567
  var DEFAULT_CONSOLE_PORT = 4399;
20806
20568
  var CONSOLE_PORT_ENV = "CODEXHOST_CONSOLE_PORT";
20807
20569
  var LAUNCHER_EXECUTABLE_ENV = "CODEXHOST_LAUNCHER_EXECUTABLE";
20808
20570
  function dataDirectory(environment = process.env) {
20809
- return environment.CODEXHOST_DATA_DIR ? path13.resolve(environment.CODEXHOST_DATA_DIR) : path13.join(os2.homedir(), ".codexhost");
20571
+ return environment.CODEXHOST_DATA_DIR ? path11.resolve(environment.CODEXHOST_DATA_DIR) : path11.join(os2.homedir(), ".codexhost");
20810
20572
  }
20811
20573
  function consolePaths(environment = process.env) {
20812
20574
  const root = dataDirectory(environment);
20813
20575
  return {
20814
20576
  dataDirectory: root,
20815
- startupRecordFile: path13.join(root, "diagnostics", "launcher-startup-v1.json"),
20816
- controllerStatusFile: path13.join(root, "diagnostics", "desktop-controller-v1.json"),
20817
- logsDirectory: path13.join(root, "logs"),
20818
- hostDescriptorDirectory: path13.join(root, "console", "hosts")
20577
+ startupRecordFile: path11.join(root, "diagnostics", "launcher-startup-v1.json"),
20578
+ controllerStatusFile: path11.join(root, "diagnostics", "desktop-controller-v1.json"),
20579
+ logsDirectory: path11.join(root, "logs"),
20580
+ hostDescriptorDirectory: path11.join(root, "console", "hosts")
20819
20581
  };
20820
20582
  }
20821
20583
  function consolePort(environment = process.env) {
@@ -20831,10 +20593,10 @@ function consolePort(environment = process.env) {
20831
20593
  // packages/console-server/src/harnesses.ts
20832
20594
  var HARNESS_PLUGIN_DIRECTORY_ENV = "CODEXHOST_PLUGIN_DIRECTORY";
20833
20595
  function harnessPluginRoots(appDirectory2, sourceCheckout, environment = process.env) {
20834
- const bundled = sourceCheckout ? path14.resolve(appDirectory2, "..", "..", "host-runtime", "dist", "plugins") : path14.join(appDirectory2, "plugins");
20596
+ const bundled = sourceCheckout ? path12.resolve(appDirectory2, "..", "..", "host-runtime", "dist", "plugins") : path12.join(appDirectory2, "plugins");
20835
20597
  return [
20836
20598
  bundled,
20837
- environment[HARNESS_PLUGIN_DIRECTORY_ENV] ?? path14.join(dataDirectory(environment), "plugins")
20599
+ environment[HARNESS_PLUGIN_DIRECTORY_ENV] ?? path12.join(dataDirectory(environment), "plugins")
20838
20600
  ];
20839
20601
  }
20840
20602
  var ConsoleHarnessError = class extends Error {
@@ -20883,14 +20645,14 @@ function createConsoleHarnesses(roots, environment = process.env) {
20883
20645
  };
20884
20646
  return {
20885
20647
  list,
20886
- async setLaunchPath(id, value) {
20887
- const harness2 = (await list()).find((candidate) => candidate.id === id);
20888
- if (!harness2) throw new ConsoleHarnessError(404, `Harness '${id}' is not installed`);
20648
+ async setLaunchPath(id2, value) {
20649
+ const harness2 = (await list()).find((candidate) => candidate.id === id2);
20650
+ if (!harness2) throw new ConsoleHarnessError(404, `Harness '${id2}' is not installed`);
20889
20651
  if (!harness2.launchCommand) {
20890
- throw new ConsoleHarnessError(400, `Harness '${id}' does not accept an installation path`);
20652
+ throw new ConsoleHarnessError(400, `Harness '${id2}' does not accept an installation path`);
20891
20653
  }
20892
20654
  try {
20893
- const settings = await store.set(id, value);
20655
+ const settings = await store.set(id2, value);
20894
20656
  return { ...harness2, launchPath: settings.path, launchPathError: null };
20895
20657
  } catch (error51) {
20896
20658
  throw new ConsoleHarnessError(400, error51 instanceof Error ? error51.message : String(error51));
@@ -20900,20 +20662,20 @@ function createConsoleHarnesses(roots, environment = process.env) {
20900
20662
  }
20901
20663
 
20902
20664
  // packages/console-server/src/host-client.ts
20903
- import { readdir as readdir6, readFile as readFile7, realpath as realpath4, rm as rm6 } from "node:fs/promises";
20904
- import path16 from "node:path";
20665
+ import { readdir as readdir5, readFile as readFile6, realpath as realpath4, rm as rm6 } from "node:fs/promises";
20666
+ import path14 from "node:path";
20905
20667
 
20906
20668
  // packages/console-server/src/diagnostics.ts
20907
- import { open as open5, readdir as readdir5, readFile as readFile6, stat as stat4 } from "node:fs/promises";
20908
- import path15 from "node:path";
20669
+ import { open as open5, readdir as readdir4, readFile as readFile5, stat as stat3 } from "node:fs/promises";
20670
+ import path13 from "node:path";
20909
20671
  var MAX_DIAGNOSTIC_FILE_BYTES = 256 * 1024;
20910
20672
  var MAX_LOG_TAIL_BYTES = 256 * 1024;
20911
20673
  var LOG_FILE_PATTERN = /^host-runtime-\d{1,10}\.log(?:\.1)?$/u;
20912
- async function readBoundedJson(filePath) {
20674
+ async function readBoundedJson(filePath2) {
20913
20675
  try {
20914
- const metadata = await stat4(filePath);
20676
+ const metadata = await stat3(filePath2);
20915
20677
  if (!metadata.isFile() || metadata.size > MAX_DIAGNOSTIC_FILE_BYTES) return null;
20916
- return JSON.parse(await readFile6(filePath, "utf8"));
20678
+ return JSON.parse(await readFile5(filePath2, "utf8"));
20917
20679
  } catch {
20918
20680
  return null;
20919
20681
  }
@@ -20941,15 +20703,15 @@ function parseStartupRecord(value) {
20941
20703
  desktop: desktop && typeof desktop.version === "string" && typeof desktop.build === "string" && typeof desktop.installRoot === "string" ? { version: desktop.version, build: desktop.build, installRoot: desktop.installRoot } : null
20942
20704
  };
20943
20705
  }
20944
- async function readStartupRecords(filePath) {
20945
- const document = await readBoundedJson(filePath);
20706
+ async function readStartupRecords(filePath2) {
20707
+ const document = await readBoundedJson(filePath2);
20946
20708
  if (!isRecord(document) || document.schemaVersion !== 1 || !Array.isArray(document.records)) {
20947
20709
  return [];
20948
20710
  }
20949
20711
  return document.records.map(parseStartupRecord).filter((record4) => record4 !== null);
20950
20712
  }
20951
- async function readControllerStatus(filePath) {
20952
- const document = await readBoundedJson(filePath);
20713
+ async function readControllerStatus(filePath2) {
20714
+ const document = await readBoundedJson(filePath2);
20953
20715
  if (!isRecord(document) || document.schemaVersion !== 1 || !isRecord(document.renderer)) {
20954
20716
  return null;
20955
20717
  }
@@ -20977,14 +20739,14 @@ function isLogFileName(name) {
20977
20739
  async function listLogFiles(logsDirectory) {
20978
20740
  let names;
20979
20741
  try {
20980
- names = await readdir5(logsDirectory);
20742
+ names = await readdir4(logsDirectory);
20981
20743
  } catch {
20982
20744
  return [];
20983
20745
  }
20984
20746
  const entries = await Promise.all(
20985
20747
  names.filter(isLogFileName).map(async (name) => {
20986
20748
  try {
20987
- const metadata = await stat4(path15.join(logsDirectory, name));
20749
+ const metadata = await stat3(path13.join(logsDirectory, name));
20988
20750
  return metadata.isFile() ? { name, size: metadata.size, modifiedAt: metadata.mtimeMs } : null;
20989
20751
  } catch {
20990
20752
  return null;
@@ -20998,7 +20760,7 @@ async function readLogTail(logsDirectory, name, maxBytes = MAX_LOG_TAIL_BYTES) {
20998
20760
  const limit = Math.max(1, Math.min(maxBytes, MAX_LOG_TAIL_BYTES));
20999
20761
  let handle;
21000
20762
  try {
21001
- handle = await open5(path15.join(logsDirectory, name), "r");
20763
+ handle = await open5(path13.join(logsDirectory, name), "r");
21002
20764
  } catch {
21003
20765
  return null;
21004
20766
  }
@@ -21073,26 +20835,26 @@ function parseDescriptor(value) {
21073
20835
  port: record4.port,
21074
20836
  token: record4.token,
21075
20837
  startedAt: record4.startedAt,
21076
- ...typeof record4.runtimePath === "string" && path16.isAbsolute(record4.runtimePath) ? { runtimePath: record4.runtimePath } : {}
20838
+ ...typeof record4.runtimePath === "string" && path14.isAbsolute(record4.runtimePath) ? { runtimePath: record4.runtimePath } : {}
21077
20839
  };
21078
20840
  }
21079
20841
  async function findHost(descriptorDirectory, isAlive = processIsAlive2) {
21080
20842
  let names;
21081
20843
  try {
21082
- names = await readdir6(descriptorDirectory);
20844
+ names = await readdir5(descriptorDirectory);
21083
20845
  } catch {
21084
20846
  return null;
21085
20847
  }
21086
20848
  const hosts = [];
21087
20849
  for (const name of names.filter((candidate) => DESCRIPTOR_PATTERN.test(candidate))) {
21088
- const filePath = path16.join(descriptorDirectory, name);
20850
+ const filePath2 = path14.join(descriptorDirectory, name);
21089
20851
  try {
21090
- const text = await readFile7(filePath, "utf8");
20852
+ const text = await readFile6(filePath2, "utf8");
21091
20853
  if (text.length > DESCRIPTOR_MAX_BYTES) continue;
21092
20854
  const endpoint = parseDescriptor(JSON.parse(text));
21093
20855
  if (!endpoint) continue;
21094
20856
  if (isAlive(endpoint.pid)) hosts.push(endpoint);
21095
- else await rm6(filePath, { force: true });
20857
+ else await rm6(filePath2, { force: true });
21096
20858
  } catch {
21097
20859
  continue;
21098
20860
  }
@@ -21122,7 +20884,7 @@ function createConsoleHostClient(descriptorDirectory, options = {}) {
21122
20884
  "The running Host does not identify its installation; restart it before updating"
21123
20885
  );
21124
20886
  const [hostDirectory, requestedDirectory] = await Promise.all([
21125
- realpath4(path16.dirname(host.runtimePath)),
20887
+ realpath4(path14.dirname(host.runtimePath)),
21126
20888
  realpath4(options.updateAppDirectory)
21127
20889
  ]).catch(() => {
21128
20890
  throw new Error("The running Host installation could not be verified");
@@ -21130,7 +20892,8 @@ function createConsoleHostClient(descriptorDirectory, options = {}) {
21130
20892
  if (hostDirectory !== requestedDirectory)
21131
20893
  throw new Error("The running Host belongs to a different codexhost installation");
21132
20894
  }
21133
- const response = await fetch(`http://127.0.0.1:${host.port}/rpc`, {
20895
+ const route = method === HOST_EXTENSIONS_RPC.install || method === HOST_EXTENSIONS_RPC.update ? "/extensions/rpc" : "/rpc";
20896
+ const response = await fetch(`http://127.0.0.1:${host.port}${route}`, {
21134
20897
  method: "POST",
21135
20898
  headers: { authorization: `Bearer ${host.token}`, "content-type": "application/json" },
21136
20899
  body: JSON.stringify({ method, params: params ?? {} }),
@@ -21170,12 +20933,12 @@ function createHostUpdates(host) {
21170
20933
  // packages/console-server/src/installation.ts
21171
20934
  import { execFile as execFile2 } from "node:child_process";
21172
20935
  import { existsSync } from "node:fs";
21173
- import { readFile as readFile8 } from "node:fs/promises";
21174
- import path17 from "node:path";
20936
+ import { readFile as readFile7 } from "node:fs/promises";
20937
+ import path15 from "node:path";
21175
20938
  async function readDistribution(appDirectory2) {
21176
20939
  try {
21177
20940
  return parseDistributionMetadata(
21178
- JSON.parse(await readFile8(path17.join(appDirectory2, "codexhost-distribution.json"), "utf8"))
20941
+ JSON.parse(await readFile7(path15.join(appDirectory2, "codexhost-distribution.json"), "utf8"))
21179
20942
  );
21180
20943
  } catch (error51) {
21181
20944
  if (error51.code === "ENOENT") return null;
@@ -21183,17 +20946,17 @@ async function readDistribution(appDirectory2) {
21183
20946
  }
21184
20947
  }
21185
20948
  function installedLauncherCandidates(appDirectory2, platform = process.platform) {
21186
- const resourcesRoot = path17.dirname(appDirectory2);
20949
+ const resourcesRoot = path15.dirname(appDirectory2);
21187
20950
  const suffix = platform === "win32" ? ".exe" : "";
21188
- const candidates = [path17.join(resourcesRoot, "bin", `codexhost${suffix}`)];
21189
- if (platform === "darwin" && path17.basename(resourcesRoot) === "Resources") {
21190
- candidates.unshift(path17.join(path17.dirname(resourcesRoot), "MacOS", "codexhost"));
20951
+ const candidates = [path15.join(resourcesRoot, "bin", `codexhost${suffix}`)];
20952
+ if (platform === "darwin" && path15.basename(resourcesRoot) === "Resources") {
20953
+ candidates.unshift(path15.join(path15.dirname(resourcesRoot), "MacOS", "codexhost"));
21191
20954
  }
21192
20955
  return candidates;
21193
20956
  }
21194
20957
  function resolveLauncherExecutable(appDirectory2, environment = process.env, platform = process.platform, exists = existsSync) {
21195
20958
  const configured = environment[LAUNCHER_EXECUTABLE_ENV];
21196
- if (configured && path17.isAbsolute(configured) && exists(configured)) return configured;
20959
+ if (configured && path15.isAbsolute(configured) && exists(configured)) return configured;
21197
20960
  return installedLauncherCandidates(appDirectory2, platform).find(exists) ?? null;
21198
20961
  }
21199
20962
  async function resolveInstallation(appDirectory2, environment = process.env) {
@@ -21235,7 +20998,7 @@ function launchCommand(installation, environment = process.env) {
21235
20998
  if (installation.distribution?.distribution === "npm") {
21236
20999
  const node = environment.CODEXHOST_NPM_NODE_PATH;
21237
21000
  const wrapper = environment.CODEXHOST_NPM_LAUNCHER_PATH;
21238
- if (node && wrapper && path17.isAbsolute(node) && path17.isAbsolute(wrapper)) {
21001
+ if (node && wrapper && path15.isAbsolute(node) && path15.isAbsolute(wrapper)) {
21239
21002
  return { command: node, args: [wrapper] };
21240
21003
  }
21241
21004
  return null;
@@ -21245,12 +21008,12 @@ function launchCommand(installation, environment = process.env) {
21245
21008
 
21246
21009
  // packages/console-server/src/open.ts
21247
21010
  import { spawn as spawn4 } from "node:child_process";
21248
- import { stat as stat5 } from "node:fs/promises";
21249
- import path22 from "node:path";
21011
+ import { stat as stat4 } from "node:fs/promises";
21012
+ import path20 from "node:path";
21250
21013
 
21251
21014
  // packages/console-server/src/page.ts
21252
- import { readFile as readFile9 } from "node:fs/promises";
21253
- import path18 from "node:path";
21015
+ import { readFile as readFile8 } from "node:fs/promises";
21016
+ import path16 from "node:path";
21254
21017
  var CONSOLE_PAGE_HTML = `<!doctype html>
21255
21018
  <html lang="en">
21256
21019
  <head>
@@ -21271,14 +21034,14 @@ var MISSING_BUNDLE_SCRIPT = `document.body.textContent = "codexhost console asse
21271
21034
  `;
21272
21035
  function consoleBundleCandidates(appDirectory2) {
21273
21036
  return [
21274
- path18.join(appDirectory2, "console-web.js"),
21275
- path18.resolve(appDirectory2, "..", "..", "renderer-extension", "dist", "console.js")
21037
+ path16.join(appDirectory2, "console-web.js"),
21038
+ path16.resolve(appDirectory2, "..", "..", "renderer-extension", "dist", "console.js")
21276
21039
  ];
21277
21040
  }
21278
21041
  async function loadConsoleBundle(appDirectory2) {
21279
21042
  for (const candidate of consoleBundleCandidates(appDirectory2)) {
21280
21043
  try {
21281
- return await readFile9(candidate, "utf8");
21044
+ return await readFile8(candidate, "utf8");
21282
21045
  } catch {
21283
21046
  continue;
21284
21047
  }
@@ -21459,77 +21222,59 @@ function issueUrl(report, home) {
21459
21222
 
21460
21223
  // packages/console-server/src/extensions.ts
21461
21224
  var INSTALL = "POST /api/extensions/install";
21462
- var UNINSTALL = "POST /api/extensions/uninstall";
21463
- var CATALOG = "GET /api/extensions/catalog";
21464
- var ENABLE = "POST /api/extensions/enable";
21465
- var DISABLE = "POST /api/extensions/disable";
21466
- var RECOVERY = "POST /api/extensions/disable-all-and-reload";
21467
- async function extensionsRoute(route, body, dataDirectory2, query, environment = process.env) {
21468
- if (route === "GET /api/extensions")
21469
- return { status: 200, body: await listDesktopExtensions(dataDirectory2) };
21470
- if (route === CATALOG) {
21471
- const value = query.get("forceRefresh");
21472
- const params = desktopExtensionsCatalogParamsSchema.safeParse(
21473
- value === null ? {} : { forceRefresh: value === "true" ? true : value === "false" ? false : value }
21474
- );
21475
- if (!params.success) return { status: 400, body: { error: "Invalid forceRefresh" } };
21476
- return {
21477
- status: 200,
21478
- body: await fetchDesktopExtensionCatalog({ ...params.data, environment })
21479
- };
21480
- }
21481
- if (route === INSTALL || route === UNINSTALL) {
21482
- try {
21483
- if (route === INSTALL) {
21484
- const params2 = desktopExtensionsInstallParamsSchema.safeParse(body);
21485
- if (!params2.success)
21486
- return { status: 400, body: { error: "Invalid extension install parameters" } };
21487
- return {
21488
- status: 200,
21489
- body: await installDesktopExtension(dataDirectory2, params2.data, environment)
21490
- };
21491
- }
21492
- const params = desktopExtensionsUninstallParamsSchema.safeParse(body);
21493
- if (!params.success) return { status: 400, body: { error: "Invalid extension ID" } };
21225
+ var UPDATE = "POST /api/extensions/update";
21226
+ var isExtensionUploadRoute = (route) => route === INSTALL || route === UPDATE;
21227
+ var methods2 = /* @__PURE__ */ new Map([
21228
+ ["GET /api/extensions", HOST_EXTENSIONS_RPC.list],
21229
+ ["GET /api/extensions/snapshot", HOST_EXTENSIONS_RPC.snapshot],
21230
+ ["GET /api/extensions/catalog", HOST_EXTENSIONS_RPC.catalog],
21231
+ [INSTALL, HOST_EXTENSIONS_RPC.install],
21232
+ [UPDATE, HOST_EXTENSIONS_RPC.update],
21233
+ ["POST /api/extensions/uninstall", HOST_EXTENSIONS_RPC.uninstall],
21234
+ ["POST /api/extensions/enable", HOST_EXTENSIONS_RPC.enable],
21235
+ ["POST /api/extensions/disable", HOST_EXTENSIONS_RPC.disable],
21236
+ ["POST /api/extensions/recover", HOST_EXTENSIONS_RPC.recover],
21237
+ ["POST /api/extensions/disable-all-and-reload", HOST_EXTENSIONS_RPC.recover]
21238
+ ]);
21239
+ function consoleList(list) {
21240
+ return {
21241
+ ...list,
21242
+ desktopConnected: false,
21243
+ extensions: list.extensions.map((item) => {
21244
+ if (item.state !== "valid")
21245
+ return { ...item, status: { state: item.state, error: item.error } };
21246
+ const { manifest, enabled, backendState: backendState2, backendError, desktopConflictWith } = item;
21494
21247
  return {
21495
- status: 200,
21496
- body: await uninstallDesktopExtension({ dataDir: dataDirectory2, id: params.data.id })
21248
+ ...item,
21249
+ manifest: { ...manifest, slots: manifest.slots ?? [] },
21250
+ status: !enabled ? { state: "disabled" } : desktopConflictWith ? { state: "conflict", conflictWith: desktopConflictWith } : backendState2 === "failed" ? { state: "failed", error: backendError } : backendState2 === "running" || !manifest.desktop ? { state: "running" } : { state: "waiting" }
21497
21251
  };
21498
- } catch (error51) {
21499
- return error51 instanceof DesktopExtensionPackageError ? { status: 400, body: { error: error51.message } } : { status: 500, body: { error: "Could not install or uninstall Desktop extension" } };
21500
- }
21501
- }
21502
- if (route !== ENABLE && route !== DISABLE && route !== RECOVERY) return;
21252
+ })
21253
+ };
21254
+ }
21255
+ async function extensionsRoute(route, body, dataDirectory2, query, host) {
21256
+ const method = methods2.get(route);
21257
+ if (!method) return;
21258
+ const refresh = query.get("forceRefresh");
21259
+ const input = method !== HOST_EXTENSIONS_RPC.catalog ? body : refresh === null ? {} : {
21260
+ forceRefresh: refresh === "true" ? true : refresh === "false" ? false : refresh
21261
+ };
21262
+ const params = hostExtensionsRpcSchemas[method].params.safeParse(input);
21263
+ if (!params.success) return { status: 400, body: { error: "Invalid extension parameters" } };
21264
+ if ("source" in params.data && params.data.source?.type === "zip" && "localZipPath" in params.data.source)
21265
+ return { status: 400, body: { error: "Use a base64 ZIP; local ZIP paths are not accepted" } };
21503
21266
  try {
21504
- const result = await (async () => {
21505
- if (route === RECOVERY) {
21506
- const params2 = desktopExtensionsRecoveryParamsSchema.safeParse(body);
21507
- if (!params2.success) throw new DesktopExtensionSelectionError("Invalid expectedRevision");
21508
- return updateDesktopExtensionSelection(dataDirectory2, {
21509
- ...params2.data,
21510
- action: "recover"
21511
- });
21512
- }
21513
- const params = desktopExtensionSelectionParamsSchema.safeParse(body);
21514
- if (!params.success)
21515
- throw new DesktopExtensionSelectionError("Invalid extension ID or expectedRevision");
21516
- return updateDesktopExtensionSelection(dataDirectory2, {
21517
- ...params.data,
21518
- action: route === ENABLE ? "enable" : "disable"
21519
- });
21520
- })();
21521
- switch (result.state) {
21522
- case "saved":
21523
- return { status: 200, body: { configuration: result.configuration } };
21524
- case "slot-conflict":
21525
- return {
21526
- status: 409,
21527
- body: {
21528
- error: `Slot already occupied by ${result.conflictWith}`,
21529
- conflictWith: result.conflictWith
21530
- }
21531
- };
21532
- case "revision-conflict":
21267
+ const reply = await host.request(method, params.data);
21268
+ if ("error" in reply)
21269
+ return {
21270
+ status: reply.error.code === -32602 ? 400 : reply.error.code === -32009 ? 409 : reply.error.code === -32601 ? 404 : 500,
21271
+ body: { error: reply.error.message }
21272
+ };
21273
+ if (method === HOST_EXTENSIONS_RPC.list)
21274
+ return { status: 200, body: consoleList(hostExtensionsRpcSchemas[HOST_EXTENSIONS_RPC.list].result.parse(reply.result)) };
21275
+ if (method === HOST_EXTENSIONS_RPC.enable || method === HOST_EXTENSIONS_RPC.disable || method === HOST_EXTENSIONS_RPC.recover) {
21276
+ const result = hostExtensionsRpcSchemas[method].result.parse(reply.result);
21277
+ if (result.state === "revision-conflict")
21533
21278
  return {
21534
21279
  status: 409,
21535
21280
  body: {
@@ -21538,13 +21283,28 @@ async function extensionsRoute(route, body, dataDirectory2, query, environment =
21538
21283
  }
21539
21284
  };
21540
21285
  }
21286
+ return { status: 200, body: hostExtensionsRpcSchemas[method].result.parse(reply.result) };
21541
21287
  } catch (error51) {
21542
- return error51 instanceof DesktopExtensionSelectionError ? { status: 400, body: { error: error51.message } } : { status: 500, body: { error: "Could not save Desktop extension selection" } };
21288
+ if (!(error51 instanceof HostUnavailableError))
21289
+ return { status: 500, body: { error: "Host extension request failed" } };
21290
+ if (method === HOST_EXTENSIONS_RPC.list) {
21291
+ const { configuration, diagnostics, extensions } = await discoverHostExtensions(dataDirectory2);
21292
+ return {
21293
+ status: 200,
21294
+ body: consoleList({ configuration, diagnostics, extensions, revision: 0 })
21295
+ };
21296
+ }
21297
+ if (method === HOST_EXTENSIONS_RPC.catalog)
21298
+ return {
21299
+ status: 200,
21300
+ body: await fetchHostExtensionCatalog(hostExtensionsRpcSchemas[HOST_EXTENSIONS_RPC.catalog].params.parse(input))
21301
+ };
21302
+ return { status: 503, body: { error: "The shared Host is not running" } };
21543
21303
  }
21544
21304
  }
21545
21305
 
21546
21306
  // packages/console-server/src/updates.ts
21547
- import path19 from "node:path";
21307
+ import path17 from "node:path";
21548
21308
  var ERROR_MAX_LENGTH = 500;
21549
21309
  var ConsoleUpdateError = class extends Error {
21550
21310
  constructor(code, message) {
@@ -21578,13 +21338,13 @@ function installationKind(metadata) {
21578
21338
  }
21579
21339
  function absoluteEnvironmentPath(environment, name) {
21580
21340
  const value = environment[name];
21581
- if (!value || !path19.isAbsolute(value)) {
21341
+ if (!value || !path17.isAbsolute(value)) {
21582
21342
  throw new ConsoleUpdateError(
21583
21343
  "unsupported",
21584
21344
  `${name} is unavailable; run 'codexhost console' from the npm command to update`
21585
21345
  );
21586
21346
  }
21587
- return path19.normalize(value);
21347
+ return path17.normalize(value);
21588
21348
  }
21589
21349
  function createConsoleUpdates(options) {
21590
21350
  const environment = options.environment ?? process.env;
@@ -21606,12 +21366,12 @@ function createConsoleUpdates(options) {
21606
21366
  let currentStatusPath = null;
21607
21367
  async function latestStatus() {
21608
21368
  if (!currentStatusPath) {
21609
- const active = await discoverActiveUpdateStatus(stateDirectory());
21610
- if (!active) {
21369
+ const active2 = await discoverActiveUpdateStatus(stateDirectory());
21370
+ if (!active2) {
21611
21371
  const completed = await discoverRecentCompletedUpdateStatus(stateDirectory());
21612
21372
  return completed ? publicStatus(completed.status) : null;
21613
21373
  }
21614
- currentStatusPath = active.statusPath;
21374
+ currentStatusPath = active2.statusPath;
21615
21375
  }
21616
21376
  const status = await manager.readStatus(currentStatusPath);
21617
21377
  return status ? publicStatus(status) : null;
@@ -21628,13 +21388,13 @@ function createConsoleUpdates(options) {
21628
21388
  }
21629
21389
  }
21630
21390
  async function prepare(metadata, target2, release, onPrepared) {
21631
- const resourcesRoot = path19.dirname(target2.appDirectory);
21391
+ const resourcesRoot = path17.dirname(target2.appDirectory);
21632
21392
  const common = {
21633
21393
  version: release.version,
21634
21394
  launcherPid: options.processId ?? process.pid,
21635
21395
  launcherExecutable: options.processExecutable ?? process.execPath,
21636
21396
  runtimeDescriptorPath: target2.runtimeDescriptorPath,
21637
- updaterExecutable: path19.join(
21397
+ updaterExecutable: path17.join(
21638
21398
  resourcesRoot,
21639
21399
  "libexec",
21640
21400
  platform === "win32" ? "codexhost-updater.exe" : "codexhost-updater"
@@ -21671,13 +21431,13 @@ function createConsoleUpdates(options) {
21671
21431
  if (kind === "windows-installer") {
21672
21432
  return manager.prepareWindowsInstaller({ ...common, artifact, installRoot: resourcesRoot });
21673
21433
  }
21674
- const appPath = path19.dirname(path19.dirname(resourcesRoot));
21434
+ const appPath = path17.dirname(path17.dirname(resourcesRoot));
21675
21435
  return manager.prepareMacOsDmg({ ...common, artifact, appPath });
21676
21436
  }
21677
21437
  return Object.freeze({
21678
21438
  async check(target2, signal) {
21679
21439
  const metadata = target2.distribution;
21680
- const runtime = metadata ? null : await readRuntimeMetadata(path19.join(target2.appDirectory, "main.js"), environment).catch(
21440
+ const runtime = metadata ? null : await readRuntimeMetadata(path17.join(target2.appDirectory, "main.js"), environment).catch(
21681
21441
  () => null
21682
21442
  );
21683
21443
  const empty = {
@@ -21728,7 +21488,7 @@ function createConsoleUpdates(options) {
21728
21488
  if (!metadata) {
21729
21489
  throw new ConsoleUpdateError("unsupported", "A source checkout cannot update itself");
21730
21490
  }
21731
- if (!target2.runtimeDescriptorPath || !path19.isAbsolute(target2.runtimeDescriptorPath)) {
21491
+ if (!target2.runtimeDescriptorPath || !path17.isAbsolute(target2.runtimeDescriptorPath)) {
21732
21492
  throw new ConsoleUpdateError("unsupported", "The Launcher runtime path is unavailable");
21733
21493
  }
21734
21494
  if (handedOff) {
@@ -21799,12 +21559,12 @@ function createConsoleUpdates(options) {
21799
21559
  // packages/console-server/src/services.ts
21800
21560
  import { spawn as spawn2 } from "node:child_process";
21801
21561
  import { existsSync as existsSync2 } from "node:fs";
21802
- import path20 from "node:path";
21562
+ import path18 from "node:path";
21803
21563
  function serviceCommand(installation, action, options = {}) {
21804
21564
  if (!installation.launcherExecutable) throw new Error("codexhost Launcher was not found");
21805
21565
  const resource = (packaged, source) => {
21806
- const bundled = path20.join(installation.appDirectory, packaged);
21807
- return existsSync2(bundled) ? bundled : path20.resolve(installation.appDirectory, "..", "..", source, "dist", "main.js");
21566
+ const bundled = path18.join(installation.appDirectory, packaged);
21567
+ return existsSync2(bundled) ? bundled : path18.resolve(installation.appDirectory, "..", "..", source, "dist", "main.js");
21808
21568
  };
21809
21569
  return {
21810
21570
  command: installation.launcherExecutable,
@@ -21841,8 +21601,8 @@ function runServiceCommand(command2, args, environment) {
21841
21601
  }
21842
21602
 
21843
21603
  // packages/console-server/src/web-client.ts
21844
- import { readFile as readFile10 } from "node:fs/promises";
21845
- import path21 from "node:path";
21604
+ import { readFile as readFile9 } from "node:fs/promises";
21605
+ import path19 from "node:path";
21846
21606
  var WEB_CONNECTION_METHODS = [
21847
21607
  "codexhost/accessTokenGet",
21848
21608
  "codexhost/accessTokenRegenerate",
@@ -21858,7 +21618,7 @@ async function webConnectionRequest(dataDirectory2, method, args) {
21858
21618
  let token;
21859
21619
  try {
21860
21620
  const ready = JSON.parse(
21861
- await readFile10(path21.join(dataDirectory2, "web-service-ready.json"), "utf8")
21621
+ await readFile9(path19.join(dataDirectory2, "web-service-ready.json"), "utf8")
21862
21622
  );
21863
21623
  if (!processIsAlive2(ready.pid) || !processIsAlive2(ready.web_pid)) throw new Error();
21864
21624
  const login = new URL(ready.loginUrl);
@@ -21890,7 +21650,7 @@ async function webConnectionRequest(dataDirectory2, method, args) {
21890
21650
  // packages/console-server/src/server.ts
21891
21651
  var CONSOLE_SERVICE = "codexhost-console";
21892
21652
  var MAX_BODY_BYTES = 16 * 1024;
21893
- var MAX_EXTENSION_INSTALL_BODY_BYTES = DESKTOP_EXTENSION_ZIP_MAX_BASE64_LENGTH + MAX_BODY_BYTES;
21653
+ var MAX_EXTENSION_INSTALL_BODY_BYTES = 4 * Math.ceil(HOST_EXTENSION_ZIP_MAX_BYTES / 3) + MAX_BODY_BYTES;
21894
21654
  var INSPECT_CACHE_MS = 2e3;
21895
21655
  var SECURITY_HEADERS = {
21896
21656
  "cache-control": "no-store",
@@ -22141,7 +21901,7 @@ function startConsoleServer(options) {
22141
21901
  try {
22142
21902
  body = await readJsonBody(
22143
21903
  request,
22144
- route === INSTALL ? MAX_EXTENSION_INSTALL_BODY_BYTES : MAX_BODY_BYTES
21904
+ isExtensionUploadRoute(route) ? MAX_EXTENSION_INSTALL_BODY_BYTES : MAX_BODY_BYTES
22145
21905
  );
22146
21906
  } catch (error51) {
22147
21907
  if (!request.complete) response.setHeader("connection", "close");
@@ -22154,7 +21914,7 @@ function startConsoleServer(options) {
22154
21914
  body,
22155
21915
  options.paths.dataDirectory,
22156
21916
  url2.searchParams,
22157
- options.environment
21917
+ options.host
22158
21918
  );
22159
21919
  if (extensions) {
22160
21920
  sendJson(response, extensions.status, extensions.body);
@@ -22282,14 +22042,14 @@ function startConsoleServer(options) {
22282
22042
  return;
22283
22043
  }
22284
22044
  if (route === "POST /api/harnesses/launch-path") {
22285
- const id = body.id;
22045
+ const id2 = body.id;
22286
22046
  const value = body.path;
22287
- if (typeof id !== "string" || !(value === null || typeof value === "string")) {
22047
+ if (typeof id2 !== "string" || !(value === null || typeof value === "string")) {
22288
22048
  sendJson(response, 400, { error: "Expected { id, path }" });
22289
22049
  return;
22290
22050
  }
22291
22051
  try {
22292
- const harness2 = await options.harnesses.setLaunchPath(id, value === "" ? null : value);
22052
+ const harness2 = await options.harnesses.setLaunchPath(id2, value === "" ? null : value);
22293
22053
  sendJson(response, 200, { harness: harness2 });
22294
22054
  } catch (error51) {
22295
22055
  sendJson(response, error51 instanceof ConsoleHarnessError ? error51.status : 500, {
@@ -22397,10 +22157,10 @@ async function stopConsole(environment = process.env) {
22397
22157
  return true;
22398
22158
  }
22399
22159
  async function consoleBuildId(entryPath2, environment = process.env) {
22400
- const files = [entryPath2, ...consoleBundleCandidates(path22.dirname(entryPath2))];
22160
+ const files = [entryPath2, ...consoleBundleCandidates(path20.dirname(entryPath2))];
22401
22161
  const parts = [];
22402
22162
  for (const file2 of files) {
22403
- const metadata = await stat5(file2).catch(() => null);
22163
+ const metadata = await stat4(file2).catch(() => null);
22404
22164
  if (metadata) parts.push(`${Math.trunc(metadata.mtimeMs)}-${metadata.size}`);
22405
22165
  }
22406
22166
  const runtime = await readRuntimeMetadata(entryPath2, environment).catch(() => null);
@@ -22506,7 +22266,7 @@ async function updateFromCommand(appDirectory2, arguments_) {
22506
22266
  var IDLE_TIMEOUT_MS = 30 * 60 * 1e3;
22507
22267
  var HANDOFF_EXIT_DELAY_MS = 500;
22508
22268
  var entryPath = fileURLToPath(import.meta.url);
22509
- var appDirectory = path23.dirname(entryPath);
22269
+ var appDirectory = path21.dirname(entryPath);
22510
22270
  function usage() {
22511
22271
  console.error(
22512
22272
  "usage: console-server open [--no-browser] | console-server ensure | console-server serve | console-server stop | console-server update"