@liberseek/boft-cli-win32-arm64 0.7.8 → 0.8.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 (58) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.txt +8 -0
  3. package/app/codexhost-distribution.json +1 -1
  4. package/app/console-server.mjs +16801 -16440
  5. package/app/console-web.js +9774 -3685
  6. package/app/desktop-controller.mjs +16475 -374
  7. package/app/host-runtime.mjs +9052 -1793
  8. package/app/plugins/antigravity/manifest.json +18 -1
  9. package/app/plugins/antigravity/plugin.mjs +357 -42
  10. package/app/plugins/claude-code/manifest.json +28 -0
  11. package/app/plugins/claude-code/plugin.mjs +1448 -491
  12. package/app/plugins/codebuddy/manifest.json +17 -0
  13. package/app/plugins/codebuddy/plugin.mjs +6589 -5423
  14. package/app/plugins/codex-usage/manifest.json +9 -0
  15. package/app/plugins/codex-usage/plugin.mjs +16750 -0
  16. package/app/plugins/cursor-cli/manifest.json +18 -1
  17. package/app/plugins/cursor-cli/plugin.mjs +782 -197
  18. package/app/plugins/deepseek-harness/assets/icon.svg +1 -0
  19. package/app/plugins/deepseek-harness/manifest.json +35 -2
  20. package/app/plugins/deepseek-harness/plugin.mjs +879 -242
  21. package/app/plugins/enabled.json +3 -1
  22. package/app/plugins/grok/manifest.json +21 -1
  23. package/app/plugins/grok/plugin.mjs +1274 -241
  24. package/app/plugins/hermes/assets/icon.png +0 -0
  25. package/app/plugins/hermes/manifest.json +30 -2
  26. package/app/plugins/hermes/plugin.mjs +3493 -7686
  27. package/app/plugins/kimi-code/assets/icon.svg +5 -0
  28. package/app/plugins/kimi-code/manifest.json +25 -2
  29. package/app/plugins/kimi-code/plugin.mjs +922 -76
  30. package/app/plugins/kiro-cli/assets/kiro-agent.svg +11 -0
  31. package/app/plugins/kiro-cli/manifest.json +18 -1
  32. package/app/plugins/kiro-cli/plugin.mjs +658 -57
  33. package/app/plugins/muse/manifest.json +18 -1
  34. package/app/plugins/muse/plugin.mjs +332 -17
  35. package/app/plugins/omp/manifest.json +21 -1
  36. package/app/plugins/omp/plugin.mjs +2320 -1131
  37. package/app/plugins/opencode/manifest.json +18 -1
  38. package/app/plugins/opencode/plugin.mjs +979 -184
  39. package/app/plugins/pi/manifest.json +32 -0
  40. package/app/plugins/pi/plugin.mjs +2785 -2090
  41. package/app/plugins/qoder/manifest.json +18 -1
  42. package/app/plugins/qoder/plugin.mjs +832 -82
  43. package/app/plugins/qoder-cn/manifest.json +18 -1
  44. package/app/plugins/qoder-cn/plugin.mjs +832 -82
  45. package/app/plugins/workbuddy/manifest.json +18 -0
  46. package/app/plugins/workbuddy/plugin.mjs +6947 -5773
  47. package/app/plugins/zcode/assets/icon.svg +8 -0
  48. package/app/plugins/zcode/manifest.json +32 -0
  49. package/app/plugins/zcode/plugin.mjs +20110 -0
  50. package/app/renderer-extension.js +4762 -2470
  51. package/bin/boft.exe +0 -0
  52. package/libexec/boft-node-repl.exe +0 -0
  53. package/libexec/boft-shim.exe +0 -0
  54. package/libexec/boft-updater.exe +0 -0
  55. package/licenses/Cordis-LICENSE.txt +21 -0
  56. package/licenses/Cosmokit-LICENSE.txt +21 -0
  57. package/package.json +1 -1
  58. package/app/plugins/kiro-cli/assets/icon.svg +0 -5
@@ -2220,20 +2220,20 @@ var require_resolve = __commonJS({
2220
2220
  return false;
2221
2221
  }
2222
2222
  function countKeys(schema) {
2223
- let count = 0;
2223
+ let count2 = 0;
2224
2224
  for (const key in schema) {
2225
2225
  if (key === "$ref")
2226
2226
  return Infinity;
2227
- count++;
2227
+ count2++;
2228
2228
  if (SIMPLE_INLINED.has(key))
2229
2229
  continue;
2230
2230
  if (typeof schema[key] == "object") {
2231
- (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
2231
+ (0, util_1.eachItem)(schema[key], (sch) => count2 += countKeys(sch));
2232
2232
  }
2233
- if (count === Infinity)
2233
+ if (count2 === Infinity)
2234
2234
  return Infinity;
2235
2235
  }
2236
- return count;
2236
+ return count2;
2237
2237
  }
2238
2238
  function getFullPath(resolver, id = "", normalize) {
2239
2239
  if (normalize !== false)
@@ -5411,8 +5411,8 @@ var require_contains = __commonJS({
5411
5411
  cxt.result(valid, () => cxt.reset());
5412
5412
  function validateItemsWithCount() {
5413
5413
  const schValid = gen.name("_valid");
5414
- const count = gen.let("count", 0);
5415
- validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
5414
+ const count2 = gen.let("count", 0);
5415
+ validateItems(schValid, () => gen.if(schValid, () => checkLimits(count2)));
5416
5416
  }
5417
5417
  function validateItems(_valid, block) {
5418
5418
  gen.forRange("i", 0, len, (i) => {
@@ -5425,16 +5425,16 @@ var require_contains = __commonJS({
5425
5425
  block();
5426
5426
  });
5427
5427
  }
5428
- function checkLimits(count) {
5429
- gen.code((0, codegen_1._)`${count}++`);
5428
+ function checkLimits(count2) {
5429
+ gen.code((0, codegen_1._)`${count2}++`);
5430
5430
  if (max === void 0) {
5431
- gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
5431
+ gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true).break());
5432
5432
  } else {
5433
- gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
5433
+ gen.if((0, codegen_1._)`${count2} > ${max}`, () => gen.assign(valid, false).break());
5434
5434
  if (min === 1)
5435
5435
  gen.assign(valid, true);
5436
5436
  else
5437
- gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
5437
+ gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true));
5438
5438
  }
5439
5439
  }
5440
5440
  }
@@ -8933,20 +8933,20 @@ var require_resolve2 = __commonJS({
8933
8933
  return false;
8934
8934
  }
8935
8935
  function countKeys(schema) {
8936
- let count = 0;
8936
+ let count2 = 0;
8937
8937
  for (const key in schema) {
8938
8938
  if (key === "$ref")
8939
8939
  return Infinity;
8940
- count++;
8940
+ count2++;
8941
8941
  if (SIMPLE_INLINED.has(key))
8942
8942
  continue;
8943
8943
  if (typeof schema[key] == "object") {
8944
- (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
8944
+ (0, util_1.eachItem)(schema[key], (sch) => count2 += countKeys(sch));
8945
8945
  }
8946
- if (count === Infinity)
8946
+ if (count2 === Infinity)
8947
8947
  return Infinity;
8948
8948
  }
8949
- return count;
8949
+ return count2;
8950
8950
  }
8951
8951
  function getFullPath(resolver, id = "", normalize) {
8952
8952
  if (normalize !== false)
@@ -11309,8 +11309,8 @@ var require_contains2 = __commonJS({
11309
11309
  cxt.result(valid, () => cxt.reset());
11310
11310
  function validateItemsWithCount() {
11311
11311
  const schValid = gen.name("_valid");
11312
- const count = gen.let("count", 0);
11313
- validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
11312
+ const count2 = gen.let("count", 0);
11313
+ validateItems(schValid, () => gen.if(schValid, () => checkLimits(count2)));
11314
11314
  }
11315
11315
  function validateItems(_valid, block) {
11316
11316
  gen.forRange("i", 0, len, (i) => {
@@ -11323,16 +11323,16 @@ var require_contains2 = __commonJS({
11323
11323
  block();
11324
11324
  });
11325
11325
  }
11326
- function checkLimits(count) {
11327
- gen.code((0, codegen_1._)`${count}++`);
11326
+ function checkLimits(count2) {
11327
+ gen.code((0, codegen_1._)`${count2}++`);
11328
11328
  if (max === void 0) {
11329
- gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
11329
+ gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true).break());
11330
11330
  } else {
11331
- gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
11331
+ gen.if((0, codegen_1._)`${count2} > ${max}`, () => gen.assign(valid, false).break());
11332
11332
  if (min === 1)
11333
11333
  gen.assign(valid, true);
11334
11334
  else
11335
- gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
11335
+ gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true));
11336
11336
  }
11337
11337
  }
11338
11338
  }
@@ -12594,6 +12594,11 @@ var require_dist = __commonJS({
12594
12594
  var require_content_type = __commonJS({
12595
12595
  "../../../node_modules/content-type/index.js"(exports) {
12596
12596
  "use strict";
12597
+ /*!
12598
+ * content-type
12599
+ * Copyright(c) 2015 Douglas Christopher Wilson
12600
+ * MIT Licensed
12601
+ */
12597
12602
  var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
12598
12603
  var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/;
12599
12604
  var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
@@ -17697,8 +17702,8 @@ function az_default() {
17697
17702
  }
17698
17703
 
17699
17704
  // ../../../node_modules/zod/v4/locales/be.js
17700
- function getBelarusianPlural(count, one2, few, many) {
17701
- const absCount = Math.abs(count);
17705
+ function getBelarusianPlural(count2, one2, few, many) {
17706
+ const absCount = Math.abs(count2);
17702
17707
  const lastDigit = absCount % 10;
17703
17708
  const lastTwoDigits = absCount % 100;
17704
17709
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -19776,8 +19781,8 @@ function hu_default() {
19776
19781
  }
19777
19782
 
19778
19783
  // ../../../node_modules/zod/v4/locales/hy.js
19779
- function getArmenianPlural(count, one2, many) {
19780
- return Math.abs(count) === 1 ? one2 : many;
19784
+ function getArmenianPlural(count2, one2, many) {
19785
+ return Math.abs(count2) === 1 ? one2 : many;
19781
19786
  }
19782
19787
  function withDefiniteArticle(word) {
19783
19788
  if (!word)
@@ -21905,8 +21910,8 @@ function ro_default() {
21905
21910
  }
21906
21911
 
21907
21912
  // ../../../node_modules/zod/v4/locales/ru.js
21908
- function getRussianPlural(count, one2, few, many) {
21909
- const absCount = Math.abs(count);
21913
+ function getRussianPlural(count2, one2, few, many) {
21914
+ const absCount = Math.abs(count2);
21910
21915
  const lastDigit = absCount % 10;
21911
21916
  const lastTwoDigits = absCount % 100;
21912
21917
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -27575,6 +27580,15 @@ function date4(params) {
27575
27580
  // ../../../node_modules/zod/v4/classic/external.js
27576
27581
  config(en_default());
27577
27582
 
27583
+ // ../../shared-contracts/dist/delegation-read.js
27584
+ var REMOTE_THREAD_REPLY_MAX_BYTES = 16 * 1024 * 1024;
27585
+ var delegationReadParamsSchema = external_exports.strictObject({
27586
+ threadId: external_exports.string().min(1).max(1024),
27587
+ view: external_exports.enum(["result", "messages"]),
27588
+ cursor: external_exports.string().min(1).max(8192).optional(),
27589
+ limit: external_exports.number().int().min(1).max(100).optional()
27590
+ });
27591
+
27578
27592
  // ../../shared-contracts/dist/credential-imports.js
27579
27593
  var credentialSourceSchema = external_exports.object({
27580
27594
  id: external_exports.string().min(1).max(256),
@@ -27645,6 +27659,153 @@ var harnessDisplaySetSchema = external_exports.strictObject({
27645
27659
  initializeOnly: external_exports.boolean().optional()
27646
27660
  });
27647
27661
 
27662
+ // ../../shared-contracts/dist/model-price-overrides.js
27663
+ var usdPerMillionTokens = external_exports.number().finite().nonnegative();
27664
+ var modelPriceOverrideSchema = external_exports.strictObject({
27665
+ input: usdPerMillionTokens,
27666
+ output: usdPerMillionTokens,
27667
+ cacheRead: usdPerMillionTokens.optional(),
27668
+ cacheWrite: usdPerMillionTokens.optional(),
27669
+ cacheWrite1h: usdPerMillionTokens.optional()
27670
+ });
27671
+ var modelPriceKeySchema = external_exports.string().max(512).refine((key) => key.trim() === key && key.length > 0, "Model ID is required");
27672
+ var modelPriceOverridesSchema = external_exports.strictObject({
27673
+ /** Absolute path of the Host's `pricing.json`. */
27674
+ path: external_exports.string(),
27675
+ entries: external_exports.array(external_exports.strictObject({ key: external_exports.string(), price: modelPriceOverrideSchema })),
27676
+ /** Why the existing file is unusable; the Host then ignores it and refuses to overwrite it. */
27677
+ error: external_exports.string().nullable()
27678
+ });
27679
+ var modelPriceOverridesGetSchema = external_exports.strictObject({});
27680
+ var modelPriceOverridesSetSchema = external_exports.strictObject({
27681
+ key: modelPriceKeySchema,
27682
+ price: modelPriceOverrideSchema.nullable(),
27683
+ previousKey: modelPriceKeySchema.optional()
27684
+ });
27685
+ var modelPriceDefaultParamsSchema = external_exports.strictObject({
27686
+ model: modelPriceKeySchema
27687
+ });
27688
+ var modelPriceSuggestionSchema = external_exports.strictObject({
27689
+ /** Verified from catalog canonical links, not inferred from names or equal prices. */
27690
+ official: external_exports.boolean().optional(),
27691
+ canonicalModelId: external_exports.string().min(1).optional(),
27692
+ provider: external_exports.string().min(1).max(512),
27693
+ model: external_exports.string().min(1).max(512),
27694
+ price: modelPriceOverrideSchema
27695
+ });
27696
+ var modelPriceDefaultResultSchema = external_exports.strictObject({
27697
+ price: modelPriceOverrideSchema.nullable(),
27698
+ /** Local catalog suggestions only; never used automatically for pricing. */
27699
+ suggestions: external_exports.array(modelPriceSuggestionSchema).max(6).optional()
27700
+ });
27701
+
27702
+ // ../../shared-contracts/dist/usage-statistics.js
27703
+ var USAGE_STATISTICS_RANGES = ["today", "7d", "30d", "90d", "all"];
27704
+ var count = external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
27705
+ var localDate = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/u);
27706
+ var harness = external_exports.string().min(1).max(128);
27707
+ var model = external_exports.string().min(1).max(512);
27708
+ var project = external_exports.string().min(1).max(4096);
27709
+ var usageStatisticsParamsSchema = external_exports.strictObject({
27710
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
27711
+ harness: harness.optional(),
27712
+ model: model.nullable().optional(),
27713
+ project: project.nullable().optional(),
27714
+ /** One local date inside the range. */
27715
+ date: localDate.optional()
27716
+ });
27717
+ var usageStatisticsTotalsSchema = external_exports.strictObject({
27718
+ requests: count,
27719
+ inputTokens: count,
27720
+ cachedInputTokens: count,
27721
+ cacheWriteInputTokens: count,
27722
+ cacheKnownInputTokens: count,
27723
+ outputTokens: count,
27724
+ reasoningOutputTokens: count,
27725
+ /** USD at the public price, summed over the priced requests only. */
27726
+ costUsd: external_exports.number().finite().min(0),
27727
+ /** Requests without a price (or the cache data the price needs); not in `costUsd`. */
27728
+ unpricedRequests: count,
27729
+ /**
27730
+ * Requests whose storage gave no token counts: counted as requests, with neither tokens nor
27731
+ * cost, and not as unpriced.
27732
+ */
27733
+ unmeteredRequests: count
27734
+ });
27735
+ var totals = usageStatisticsTotalsSchema.shape;
27736
+ var usageStatisticsSessionSchema = external_exports.strictObject({
27737
+ harness,
27738
+ sessionId: external_exports.string().min(1).max(512),
27739
+ project: project.nullable(),
27740
+ /** Models the session used, most requests first. */
27741
+ models: external_exports.array(model).max(16),
27742
+ firstAtMs: count,
27743
+ lastAtMs: count,
27744
+ ...totals
27745
+ });
27746
+ var usageStatisticsResultSchema = external_exports.strictObject({
27747
+ range: external_exports.enum(USAGE_STATISTICS_RANGES),
27748
+ /** First local date of the range; null for all time. */
27749
+ from: localDate.nullable(),
27750
+ to: localDate,
27751
+ /** The filters these figures apply, echoed so a late answer to older filters is recognised. */
27752
+ filters: external_exports.strictObject({
27753
+ harness: harness.nullable(),
27754
+ model: model.nullable(),
27755
+ unknownModel: external_exports.boolean(),
27756
+ project: project.nullable(),
27757
+ unknownProject: external_exports.boolean(),
27758
+ date: localDate.nullable()
27759
+ }),
27760
+ /** Reading of native storage: incomplete while the first read, or a refresh, is under way. */
27761
+ reading: external_exports.strictObject({ complete: external_exports.boolean(), sources: count, read: count }),
27762
+ /** Harnesses whose storage could not be read; their part is missing, the rest is complete. */
27763
+ failures: external_exports.array(external_exports.strictObject({ harness, message: external_exports.string().max(2048) })).max(256),
27764
+ /** Every value seen in the range, ignoring the filters, to choose filters from. */
27765
+ options: external_exports.strictObject({
27766
+ harnesses: external_exports.array(harness).max(256),
27767
+ models: external_exports.array(model.nullable()).max(4096),
27768
+ projects: external_exports.array(project.nullable()).max(4096)
27769
+ }),
27770
+ /** Current display metadata, scoped by Harness. Never a pricing or filter identity.
27771
+ * Optional for older Hosts; missing/conflicting labels fall back to the native model ID.
27772
+ */
27773
+ modelLabels: external_exports.array(external_exports.strictObject({ harness, model, label: model })).max(4096).optional(),
27774
+ /** Native credits, all filters applied, never combined across Harnesses or treated as USD.
27775
+ * Only groups with at least one reported value appear; reportedRequests exposes partial data.
27776
+ */
27777
+ credits: external_exports.array(external_exports.strictObject({
27778
+ harness,
27779
+ model: model.nullable(),
27780
+ credits: external_exports.number().finite().min(0),
27781
+ reportedRequests: count,
27782
+ requests: count
27783
+ })).max(4096).optional(),
27784
+ /** All filters applied. */
27785
+ totals: usageStatisticsTotalsSchema,
27786
+ /** Each date and Harness of the range: every filter except the day. */
27787
+ daily: external_exports.array(external_exports.strictObject({ date: localDate, harness, ...totals })).max(2e5),
27788
+ /** Local weekday (0 = Sunday) and hour, all filters applied. */
27789
+ hourly: external_exports.array(external_exports.strictObject({
27790
+ weekday: external_exports.number().int().min(0).max(6),
27791
+ hour: external_exports.number().int().min(0).max(23),
27792
+ ...totals
27793
+ })).max(168),
27794
+ byHarness: external_exports.array(external_exports.strictObject({ harness, ...totals })).max(256),
27795
+ byModel: external_exports.array(external_exports.strictObject({
27796
+ model: model.nullable(),
27797
+ ...totals,
27798
+ /** Requests priced by what the Harness recorded they cost, not by a price list. */
27799
+ harnessPricedRequests: count
27800
+ })).max(4096),
27801
+ byProject: external_exports.array(external_exports.strictObject({ project: project.nullable(), ...totals })).max(4096),
27802
+ /**
27803
+ * The sessions that spent the most, by cost and by tokens without cache, all filters applied;
27804
+ * requests without a native session are not listed here but count everywhere else.
27805
+ */
27806
+ sessions: external_exports.array(usageStatisticsSessionSchema).max(100)
27807
+ });
27808
+
27648
27809
  // ../../shared-contracts/dist/ids.js
27649
27810
  var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
27650
27811
  message: "Identifier must not be empty or whitespace"
@@ -27655,6 +27816,10 @@ var hostTurnIdSchema = opaqueIdSchema.brand();
27655
27816
  var hostItemIdSchema = opaqueIdSchema.brand();
27656
27817
  var hostInteractionIdSchema = opaqueIdSchema.brand();
27657
27818
 
27819
+ // ../../shared-contracts/dist/thread-prewarm.js
27820
+ var threadPrewarmDiscardParamsSchema = external_exports.object({ threadId: hostThreadIdSchema });
27821
+ var threadPrewarmDiscardResultSchema = external_exports.object({ discarded: external_exports.boolean() });
27822
+
27658
27823
  // ../../shared-contracts/dist/harness-plugins.js
27659
27824
  var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
27660
27825
  var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
@@ -27662,13 +27827,40 @@ var HARNESS_PLUGIN_LIMIT = 128;
27662
27827
  var harnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).refine((id) => id !== "codex", "The official Codex identity is reserved").pipe(harnessIdSchema);
27663
27828
  var relativeResourceSchema = 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");
27664
27829
  var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
27830
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
27831
+ var harnessInstallationGuideSchema = external_exports.object({
27832
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
27833
+ before: localizedTextSchema.optional(),
27834
+ after: localizedTextSchema.optional(),
27835
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
27836
+ }).strict();
27665
27837
  var pluginPresentationShape = {
27666
27838
  id: harnessPluginIdSchema,
27667
27839
  name: external_exports.string().trim().min(1).max(128),
27668
27840
  version: external_exports.string().min(1).max(128),
27841
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
27842
+ kind: external_exports.literal("usage").optional(),
27843
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
27844
+ iconStyle: external_exports.object({
27845
+ vector: external_exports.object({
27846
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
27847
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
27848
+ paths: external_exports.array(external_exports.object({
27849
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
27850
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
27851
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
27852
+ }).strict()).min(1).max(32)
27853
+ }).strict().optional(),
27854
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
27855
+ borderRadius: external_exports.number().min(0).max(50).optional(),
27856
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
27857
+ }).strict().optional(),
27858
+ installation: harnessInstallationGuideSchema.optional(),
27859
+ notice: localizedTextSchema.optional(),
27669
27860
  /** The factory accepts a persisted local entrypoint through its construction context. */
27670
27861
  launchCommand: external_exports.literal(true).optional(),
27671
27862
  links: external_exports.object({
27863
+ website: documentationUrlSchema.optional(),
27672
27864
  documentation: documentationUrlSchema.optional(),
27673
27865
  installation: documentationUrlSchema.optional()
27674
27866
  }).strict().optional()
@@ -27722,6 +27914,9 @@ var consoleOpenResultSchema = external_exports.strictObject({
27722
27914
  url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
27723
27915
  });
27724
27916
  var CONSOLE_HOST_METHODS = Object.freeze([
27917
+ "codexhost/console/remote-connections",
27918
+ "codexhost/runtime/status",
27919
+ "codexhost/remote/ssh-setup",
27725
27920
  "codexhost/harness/plugins/list",
27726
27921
  "codexhost/harness/display-settings/get",
27727
27922
  "codexhost/harness/display-settings/set",
@@ -27742,6 +27937,10 @@ var CONSOLE_HOST_METHODS = Object.freeze([
27742
27937
  "codexhost/account/list",
27743
27938
  "codexhost/account/refresh",
27744
27939
  "codexhost/account/usage/inspect",
27940
+ "codexhost/usage/model-prices/get",
27941
+ "codexhost/usage/model-prices/set",
27942
+ "codexhost/usage/model-prices/default",
27943
+ "codexhost/usage/statistics/get",
27745
27944
  "codexhost/update/check",
27746
27945
  "codexhost/update/start",
27747
27946
  "codexhost/update/status"
@@ -27806,6 +28005,7 @@ var threadUsageSnapshotSchema = external_exports.object({
27806
28005
  cacheWriteInputTokens: nonNegativeSafeIntegerSchema.optional(),
27807
28006
  outputTokens: nonNegativeSafeIntegerSchema.optional(),
27808
28007
  outputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
28008
+ apiOutputTokensPerSecond: finiteNonNegativeNumberSchema.optional(),
27809
28009
  reasoningOutputTokens: nonNegativeSafeIntegerSchema.optional(),
27810
28010
  totalTokens: nonNegativeSafeIntegerSchema.optional(),
27811
28011
  totalCostUsd: finiteNonNegativeNumberSchema.optional(),
@@ -27817,7 +28017,11 @@ var threadUsageSnapshotSchema = external_exports.object({
27817
28017
  planFiveHourUsedPercent: cacheHitRatePercentSchema.optional(),
27818
28018
  planFiveHourResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
27819
28019
  planSevenDayUsedPercent: cacheHitRatePercentSchema.optional(),
27820
- planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional()
28020
+ planSevenDayResetsAtUnix: nonNegativeSafeIntegerSchema.optional(),
28021
+ sessionCacheHitRatePercent: cacheHitRatePercentSchema.optional(),
28022
+ timeToFirstOutputMs: nonNegativeSafeIntegerSchema.optional(),
28023
+ costSource: external_exports.enum(["publicPrice", "native"]).optional(),
28024
+ unpricedModels: external_exports.array(external_exports.string().min(1)).min(1).optional()
27821
28025
  }).strict().superRefine((usage, context) => {
27822
28026
  if (Object.keys(usage).length === 0) {
27823
28027
  context.addIssue({ code: "custom", message: "Thread Usage must contain a reliable field" });
@@ -27838,6 +28042,20 @@ var threadUsageSnapshotSchema = external_exports.object({
27838
28042
  path: ["contextWindowTokens"]
27839
28043
  });
27840
28044
  }
28045
+ if (usage.costSource !== void 0 && usage.totalCostUsd === void 0) {
28046
+ context.addIssue({
28047
+ code: "custom",
28048
+ message: "Thread Usage costSource must be provided with totalCostUsd",
28049
+ path: ["costSource"]
28050
+ });
28051
+ }
28052
+ if (usage.unpricedModels !== void 0 && usage.costSource !== "publicPrice") {
28053
+ context.addIssue({
28054
+ code: "custom",
28055
+ message: "Thread Usage unpricedModels must be provided with a publicPrice cost",
28056
+ path: ["unpricedModels"]
28057
+ });
28058
+ }
27841
28059
  if (usage.planFiveHourResetsAtUnix !== void 0 && usage.planFiveHourUsedPercent === void 0) {
27842
28060
  context.addIssue({
27843
28061
  code: "custom",
@@ -28107,27 +28325,27 @@ var harnessModelCatalogSchema = external_exports.object({
28107
28325
  }).strict().superRefine((catalog, context) => {
28108
28326
  const refs = /* @__PURE__ */ new Set();
28109
28327
  const thinkingIds = new Set(catalog.thinkingOptions.map(({ id }) => id));
28110
- for (const [index, model] of catalog.models.entries()) {
28111
- if (refs.has(model.ref.id)) {
28328
+ for (const [index, model2] of catalog.models.entries()) {
28329
+ if (refs.has(model2.ref.id)) {
28112
28330
  context.addIssue({
28113
28331
  code: "custom",
28114
28332
  message: "Model Catalog refs must be unique",
28115
28333
  path: ["models", index, "ref", "id"]
28116
28334
  });
28117
28335
  }
28118
- refs.add(model.ref.id);
28119
- if (model.fastModel) {
28120
- if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
28336
+ refs.add(model2.ref.id);
28337
+ if (model2.fastModel) {
28338
+ if (refs.has(model2.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model2.fastModel?.id)) {
28121
28339
  context.addIssue({
28122
28340
  code: "custom",
28123
28341
  message: "Fast Model refs must be distinct and unique",
28124
28342
  path: ["models", index, "fastModel"]
28125
28343
  });
28126
28344
  }
28127
- refs.add(model.fastModel.id);
28345
+ refs.add(model2.fastModel.id);
28128
28346
  }
28129
28347
  const supportedThinkingIds = /* @__PURE__ */ new Set();
28130
- for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
28348
+ for (const [optionIndex, optionId] of (model2.supportedThinkingOptionIds ?? []).entries()) {
28131
28349
  if (supportedThinkingIds.has(optionId)) {
28132
28350
  context.addIssue({
28133
28351
  code: "custom",
@@ -28667,6 +28885,85 @@ var updateStatusResultSchema = external_exports.strictObject({
28667
28885
  status: updateStatusSchema.nullable()
28668
28886
  });
28669
28887
 
28888
+ // ../../shared-contracts/dist/remote-runtime.js
28889
+ var remoteUpdatePhaseSchema = external_exports.enum([
28890
+ "idle",
28891
+ "installing",
28892
+ "restarting",
28893
+ "succeeded",
28894
+ "failed"
28895
+ ]);
28896
+ var runtimeStatusSchema = external_exports.object({
28897
+ runningVersion: external_exports.string().nullable(),
28898
+ installedVersion: external_exports.string().nullable(),
28899
+ restartRequired: external_exports.boolean(),
28900
+ remote: external_exports.boolean(),
28901
+ updateSupported: external_exports.boolean(),
28902
+ update: external_exports.object({
28903
+ phase: remoteUpdatePhaseSchema,
28904
+ targetVersion: external_exports.string().nullable(),
28905
+ error: external_exports.string().nullable()
28906
+ })
28907
+ });
28908
+ var remoteUpdateParamsSchema = external_exports.object({
28909
+ version: external_exports.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)
28910
+ }).strict();
28911
+ var remoteSshSetupParamsSchema = external_exports.object({
28912
+ hostname: external_exports.string().min(1).max(1024).refine((value) => !value.startsWith("-") && !/\s/u.test(value)),
28913
+ port: external_exports.number().int().min(1).max(65535).nullable(),
28914
+ identity: external_exports.string().max(4096).nullable(),
28915
+ action: external_exports.enum(["inspect", "install", "update", "repair", "uninstall"]),
28916
+ uninstallPackage: external_exports.boolean().optional(),
28917
+ version: external_exports.string().regex(/^\d+\.\d+\.\d+$/u).nullable()
28918
+ }).strict();
28919
+ var remoteSshSetupResultSchema = external_exports.object({ state: external_exports.enum(["installed", "not-installed"]) }).strict();
28920
+
28921
+ // ../../shared-contracts/dist/remote-connections.js
28922
+ var hostId = external_exports.string().min(1).max(1024);
28923
+ var codexSshConnectionSchema = external_exports.object({
28924
+ hostId,
28925
+ displayName: external_exports.string().min(1).max(1024),
28926
+ source: external_exports.enum(["codex-managed", "discovered"]),
28927
+ sshAlias: external_exports.string().max(1024).nullable(),
28928
+ sshHost: external_exports.string().min(1).max(1024),
28929
+ sshPort: external_exports.number().int().min(1).max(65535).nullable(),
28930
+ identity: external_exports.string().max(4096).nullable(),
28931
+ autoConnect: external_exports.boolean(),
28932
+ connectionAnalyticsId: external_exports.string().max(1024).optional()
28933
+ });
28934
+ var codexSshDraftSchema = external_exports.strictObject({
28935
+ displayName: external_exports.string().min(1).max(1024),
28936
+ hostname: external_exports.string().min(1).max(1024),
28937
+ sshPort: external_exports.number().int().min(1).max(65535).nullable(),
28938
+ identity: external_exports.string().max(4096).nullable()
28939
+ });
28940
+ var remoteConnectionsRequestSchema = external_exports.discriminatedUnion("action", [
28941
+ external_exports.strictObject({ action: external_exports.literal("list") }),
28942
+ external_exports.strictObject({
28943
+ action: external_exports.literal("read-thread"),
28944
+ hostId: hostId.refine((id) => id !== "local"),
28945
+ input: delegationReadParamsSchema
28946
+ }),
28947
+ external_exports.strictObject({
28948
+ action: external_exports.literal("save"),
28949
+ draft: codexSshDraftSchema,
28950
+ previous: codexSshConnectionSchema.nullable()
28951
+ }),
28952
+ external_exports.strictObject({ action: external_exports.literal("remove"), previous: codexSshConnectionSchema }),
28953
+ external_exports.strictObject({ action: external_exports.literal("connect"), hostId, enabled: external_exports.boolean() }),
28954
+ external_exports.strictObject({ action: external_exports.literal("state"), hostId }),
28955
+ external_exports.strictObject({ action: external_exports.literal("runtime"), hostId }),
28956
+ external_exports.strictObject({
28957
+ action: external_exports.literal("update"),
28958
+ hostId: hostId.refine((id) => id !== "local"),
28959
+ version: remoteUpdateParamsSchema.shape.version
28960
+ })
28961
+ ]);
28962
+ var remoteConnectionsReplySchema = external_exports.union([
28963
+ external_exports.strictObject({ result: jsonValueSchema }),
28964
+ external_exports.strictObject({ error: external_exports.strictObject({ code: external_exports.number().int(), message: external_exports.string() }) })
28965
+ ]);
28966
+
28670
28967
  // ../../shared-contracts/dist/index.js
28671
28968
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
28672
28969
 
@@ -28795,7 +29092,6 @@ var tokenFields = [
28795
29092
  "cachedInputTokens",
28796
29093
  "cacheWriteInputTokens",
28797
29094
  "outputTokens",
28798
- "outputTokensPerSecond",
28799
29095
  "reasoningOutputTokens",
28800
29096
  "totalTokens",
28801
29097
  "contextWindowTokens",
@@ -28803,10 +29099,12 @@ var tokenFields = [
28803
29099
  ];
28804
29100
  var safeIntegerFields = [
28805
29101
  "planFiveHourResetsAtUnix",
28806
- "planSevenDayResetsAtUnix"
29102
+ "planSevenDayResetsAtUnix",
29103
+ "timeToFirstOutputMs"
28807
29104
  ];
28808
29105
  var percentFields = [
28809
29106
  "cacheHitRatePercent",
29107
+ "sessionCacheHitRatePercent",
28810
29108
  "planFiveHourUsedPercent",
28811
29109
  "planSevenDayUsedPercent"
28812
29110
  ];
@@ -28814,9 +29112,14 @@ var usageFields = /* @__PURE__ */ new Set([
28814
29112
  ...tokenFields,
28815
29113
  ...safeIntegerFields,
28816
29114
  ...percentFields,
29115
+ "sessionCacheUsage",
28817
29116
  "totalCostUsd",
28818
29117
  "totalCredits",
28819
- "contextUsagePercent"
29118
+ "contextUsagePercent",
29119
+ "outputTokensPerSecond",
29120
+ "apiOutputTokensPerSecond",
29121
+ "costSource",
29122
+ "unpricedModels"
28820
29123
  ]);
28821
29124
  function isRecord(value) {
28822
29125
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -28832,7 +29135,11 @@ function parseHostUsage(value) {
28832
29135
  throw new Error(`Harness Usage contains unknown field '${key}'`);
28833
29136
  }
28834
29137
  }
28835
- for (const field of ["totalCredits", "contextUsagePercent"]) {
29138
+ for (const field of [
29139
+ "totalCredits",
29140
+ "contextUsagePercent",
29141
+ "apiOutputTokensPerSecond"
29142
+ ]) {
28836
29143
  const candidate = value[field];
28837
29144
  if (candidate !== void 0 && (typeof candidate !== "number" || !Number.isFinite(candidate) || candidate < 0)) {
28838
29145
  throw new Error(`Harness Usage '${field}' must be a finite non-negative number`);
@@ -28868,6 +29175,12 @@ function parseHostUsage(value) {
28868
29175
  throw new Error(`Harness Usage '${field}' must be between 0 and 100`);
28869
29176
  }
28870
29177
  }
29178
+ if (value.sessionCacheUsage !== void 0) {
29179
+ const totals2 = value.sessionCacheUsage;
29180
+ if (!isRecord(totals2) || Object.keys(totals2).some((key) => key !== "inputTokens" && key !== "cachedInputTokens") || typeof totals2.inputTokens !== "number" || !Number.isSafeInteger(totals2.inputTokens) || totals2.inputTokens < 0 || typeof totals2.cachedInputTokens !== "number" || !Number.isSafeInteger(totals2.cachedInputTokens) || totals2.cachedInputTokens < 0 || totals2.cachedInputTokens > totals2.inputTokens) {
29181
+ throw new Error("Harness Usage 'sessionCacheUsage' must contain complete bounded token totals");
29182
+ }
29183
+ }
28871
29184
  const hasContextUsed = value.contextUsedTokens !== void 0;
28872
29185
  const hasContextWindow = value.contextWindowTokens !== void 0;
28873
29186
  if (hasContextUsed !== hasContextWindow) {
@@ -28882,8 +29195,43 @@ function parseHostUsage(value) {
28882
29195
  if (value.planSevenDayResetsAtUnix !== void 0 && value.planSevenDayUsedPercent === void 0) {
28883
29196
  throw new Error("Harness Usage 'planSevenDayResetsAtUnix' must be provided with 'planSevenDayUsedPercent'");
28884
29197
  }
29198
+ if (value.costSource !== void 0) {
29199
+ if (value.costSource !== "publicPrice" && value.costSource !== "native") {
29200
+ throw new Error("Harness Usage 'costSource' must be 'publicPrice' or 'native'");
29201
+ }
29202
+ if (value.totalCostUsd === void 0) {
29203
+ throw new Error("Harness Usage 'costSource' must be provided with 'totalCostUsd'");
29204
+ }
29205
+ }
29206
+ if (value.unpricedModels !== void 0) {
29207
+ const models = value.unpricedModels;
29208
+ if (!Array.isArray(models) || models.length === 0 || !models.every((model2) => typeof model2 === "string" && model2.length > 0)) {
29209
+ throw new Error("Harness Usage 'unpricedModels' must be a non-empty list of Model IDs");
29210
+ }
29211
+ if (value.costSource !== "publicPrice") {
29212
+ throw new Error("Harness Usage 'unpricedModels' must be provided with a 'publicPrice' cost");
29213
+ }
29214
+ return { ...value, unpricedModels: [...models] };
29215
+ }
28885
29216
  return { ...value };
28886
29217
  }
29218
+ var requestTokenFields = [
29219
+ "inputTokens",
29220
+ "cachedInputTokens",
29221
+ "cacheWriteInputTokens",
29222
+ "cacheWrite1hInputTokens",
29223
+ "outputTokens",
29224
+ "reasoningOutputTokens",
29225
+ "startedAtMs",
29226
+ "completedAtMs"
29227
+ ];
29228
+ var requestFields = /* @__PURE__ */ new Set([
29229
+ ...requestTokenFields,
29230
+ "requestId",
29231
+ "historical",
29232
+ "model",
29233
+ "provider"
29234
+ ]);
28887
29235
 
28888
29236
  // ../../harness-adapter/dist/live-command-catalog.js
28889
29237
  var COMMON_EXCLUDED_LIVE_COMMANDS = /* @__PURE__ */ new Set([
@@ -29029,11 +29377,13 @@ function cursorDiscoverySpec(skipPinnedVersions) {
29029
29377
  } : {}
29030
29378
  };
29031
29379
  }
29380
+ var CursorNotInstalledError = class extends Error {
29381
+ };
29032
29382
  function resolveCursorExecutable(environment, command) {
29033
29383
  const input = { environment, ...command ? { command } : {} };
29034
29384
  const pinned = resolveHarnessExecutable(cursorDiscoverySpec(false), input);
29035
29385
  if (!pinned)
29036
- throw new Error("Cursor CLI is not installed; install cursor-agent or set CODEXHOST_CURSOR_COMMAND");
29386
+ throw new CursorNotInstalledError("Cursor CLI is not installed; install cursor-agent or set CODEXHOST_CURSOR_COMMAND");
29037
29387
  const explicit = command?.trim() || environment.CODEXHOST_CURSOR_COMMAND?.trim();
29038
29388
  if (explicit || !PINNED_VERSION_AGENT.test(pinned.executable))
29039
29389
  return pinned;
@@ -29177,6 +29527,99 @@ async function fetchCursorAccount(input = {}) {
29177
29527
  import { lstat, opendir, readFile as readFile2, realpath, stat } from "node:fs/promises";
29178
29528
  import path7 from "node:path";
29179
29529
 
29530
+ // ../../harness-adapter/dist/session-import.js
29531
+ var SessionImportChangedError = class extends Error {
29532
+ constructor(message = "Native Session changed during discovery; refresh and retry") {
29533
+ super(message);
29534
+ this.name = "SessionImportChangedError";
29535
+ }
29536
+ };
29537
+ function isMissingFileError(error51) {
29538
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "ENOENT";
29539
+ }
29540
+ function sameFileFingerprint(left, right) {
29541
+ return left === null || right === null ? left === right : left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
29542
+ }
29543
+ function sessionImportTitle(value, maxLength = HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) {
29544
+ if (typeof value !== "string")
29545
+ return null;
29546
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
29547
+ if (!normalized)
29548
+ return null;
29549
+ if (normalized.length <= maxLength)
29550
+ return normalized;
29551
+ const characters = [...normalized];
29552
+ if (characters.length <= maxLength)
29553
+ return normalized;
29554
+ return `${characters.slice(0, maxLength - 1).join("").trimEnd()}…`;
29555
+ }
29556
+ function sessionImportCandidate(input) {
29557
+ const time3 = typeof input.updatedAt === "number" ? input.updatedAt : typeof input.updatedAt === "string" ? Date.parse(input.updatedAt) : Number.NaN;
29558
+ const parsed = harnessSessionImportCandidateSchema.safeParse({
29559
+ nativeSessionId: input.nativeSessionId,
29560
+ cwd: input.cwd,
29561
+ title: typeof input.title === "string" && input.title.trim().length > 0 ? input.title : null,
29562
+ updatedAt: Math.floor(time3),
29563
+ // Unknown must stay unknown; only an explicit boolean is a native statement.
29564
+ running: typeof input.running === "boolean" ? input.running : null
29565
+ });
29566
+ return parsed.success ? parsed.data : null;
29567
+ }
29568
+ var SessionImportScope = class {
29569
+ #abort = new AbortController();
29570
+ #options;
29571
+ #pending = /* @__PURE__ */ new Set();
29572
+ constructor(options) {
29573
+ this.#options = options;
29574
+ }
29575
+ #closed() {
29576
+ return {
29577
+ ok: false,
29578
+ error: { code: "invalidState", message: this.#options.closedMessage, retryable: false }
29579
+ };
29580
+ }
29581
+ read(operation) {
29582
+ const signal = this.#abort.signal;
29583
+ if (signal.aborted)
29584
+ return Promise.resolve(this.#closed());
29585
+ let started;
29586
+ try {
29587
+ started = operation(signal);
29588
+ } catch (error51) {
29589
+ started = Promise.reject(error51 instanceof Error ? error51 : new Error("Session read failed"));
29590
+ }
29591
+ const request = started.then((value) => signal.aborted ? this.#closed() : { ok: true, value }).catch(() => signal.aborted ? this.#closed() : {
29592
+ ok: false,
29593
+ error: {
29594
+ code: "unavailable",
29595
+ message: this.#options.unavailableMessage,
29596
+ retryable: true
29597
+ }
29598
+ }).finally(() => this.#pending.delete(request));
29599
+ this.#pending.add(request);
29600
+ return request;
29601
+ }
29602
+ /** `read` for `resolveCandidate`: a null source is the selected Session having disappeared. */
29603
+ async resolve(operation) {
29604
+ const result = await this.read(operation);
29605
+ if (!result.ok)
29606
+ return result;
29607
+ return result.value ? { ok: true, value: result.value } : {
29608
+ ok: false,
29609
+ error: {
29610
+ code: "sessionNotFound",
29611
+ message: this.#options.notFoundMessage,
29612
+ retryable: false
29613
+ }
29614
+ };
29615
+ }
29616
+ /** Idempotent. Resolves after every started read has settled. */
29617
+ async close() {
29618
+ this.#abort.abort();
29619
+ await Promise.allSettled(this.#pending);
29620
+ }
29621
+ };
29622
+
29180
29623
  // dist/native-history.js
29181
29624
  import { existsSync as existsSync2, readFileSync, realpathSync } from "node:fs";
29182
29625
  import os2 from "node:os";
@@ -29322,8 +29765,6 @@ function cursorExecutionPolicy(ref) {
29322
29765
  // dist/session-import.js
29323
29766
  var SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
29324
29767
  var MAX_METADATA_BYTES = 1024 * 1024;
29325
- var CursorSessionChangedError = class extends Error {
29326
- };
29327
29768
  function errorCode(error51) {
29328
29769
  return typeof error51 === "object" && error51 !== null && "code" in error51 && typeof error51.code === "string" ? error51.code : void 0;
29329
29770
  }
@@ -29331,23 +29772,23 @@ async function optionalStat(file2) {
29331
29772
  try {
29332
29773
  return await lstat(file2);
29333
29774
  } catch (error51) {
29334
- if (errorCode(error51) === "ENOENT")
29775
+ if (isMissingFileError(error51))
29335
29776
  return null;
29336
29777
  throw error51;
29337
29778
  }
29338
29779
  }
29339
- function sameFile(left, right) {
29340
- return left === null || right === null ? left === right : left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
29341
- }
29342
29780
  var CursorSessionImport = class {
29343
29781
  #environment;
29344
- #abort = new AbortController();
29345
- #pending = /* @__PURE__ */ new Set();
29782
+ #scope = new SessionImportScope({
29783
+ closedMessage: "Cursor Session import is closed",
29784
+ unavailableMessage: "Cursor ACP sessions could not be read; close native clients, check storage access and retry",
29785
+ notFoundMessage: "Cursor ACP Session is no longer importable"
29786
+ });
29346
29787
  constructor(environment) {
29347
29788
  this.#environment = { ...environment };
29348
29789
  }
29349
29790
  listCandidates() {
29350
- return this.#read(async (signal) => {
29791
+ return this.#scope.read(async (signal) => {
29351
29792
  const root = path7.join(cursorConfigDirectory(this.#environment), "acp-sessions");
29352
29793
  const info = await optionalStat(root);
29353
29794
  if (!info)
@@ -29365,7 +29806,7 @@ var CursorSessionImport = class {
29365
29806
  if (candidate)
29366
29807
  candidates.push(candidate);
29367
29808
  } catch (error51) {
29368
- if (!(error51 instanceof CursorSessionChangedError))
29809
+ if (!(error51 instanceof SessionImportChangedError))
29369
29810
  throw error51;
29370
29811
  }
29371
29812
  }
@@ -29382,27 +29823,15 @@ var CursorSessionImport = class {
29382
29823
  retryable: false
29383
29824
  }
29384
29825
  };
29385
- const result = await this.#read((signal) => this.#candidate(nativeSessionId, signal));
29386
- if (!result.ok)
29387
- return result;
29388
- if (!result.value)
29389
- return {
29390
- ok: false,
29391
- error: {
29392
- code: "sessionNotFound",
29393
- message: "Cursor ACP Session is no longer importable",
29394
- retryable: false
29395
- }
29396
- };
29397
- return {
29398
- ok: true,
29399
- value: {
29400
- candidate: result.value,
29826
+ return this.#scope.resolve(async (signal) => {
29827
+ const candidate = await this.#candidate(nativeSessionId, signal);
29828
+ return candidate ? {
29829
+ candidate,
29401
29830
  // Native ACP stores do not attest to --force. Imported sessions must not
29402
29831
  // acquire unattended privileges from UI defaults or a guessed locator.
29403
29832
  nativeRef: cursorNativeSessionRef(nativeSessionId, "default")
29404
- }
29405
- };
29833
+ } : null;
29834
+ });
29406
29835
  }
29407
29836
  async #candidate(id, signal) {
29408
29837
  signal.throwIfAborted();
@@ -29433,7 +29862,7 @@ var CursorSessionImport = class {
29433
29862
  const turns = readCursorNativeTurns(id, cwd, this.#environment);
29434
29863
  if (!turns.length)
29435
29864
  return null;
29436
- title = turns[0]?.text.replaceAll("\0", "").replace(/\s+/gu, " ").trim().slice(0, HARNESS_SESSION_IMPORT_TITLE_MAX_LENGTH) || null;
29865
+ title = sessionImportTitle(turns[0]?.text);
29437
29866
  } catch (error51) {
29438
29867
  signal.throwIfAborted();
29439
29868
  if (["EACCES", "EPERM", "EIO", "EMFILE", "ENFILE"].includes(errorCode(error51) ?? ""))
@@ -29442,46 +29871,17 @@ var CursorSessionImport = class {
29442
29871
  }
29443
29872
  signal.throwIfAborted();
29444
29873
  const after = await Promise.all(files.map(optionalStat));
29445
- if (before.some((info, index) => !sameFile(info, after[index] ?? null)))
29446
- throw new CursorSessionChangedError("Cursor Session changed during discovery");
29447
- const parsed = harnessSessionImportCandidateSchema.safeParse({
29874
+ if (before.some((info, index) => !sameFileFingerprint(info, after[index] ?? null)))
29875
+ throw new SessionImportChangedError("Cursor Session changed during discovery");
29876
+ return sessionImportCandidate({
29448
29877
  nativeSessionId: id,
29449
29878
  cwd,
29450
29879
  title,
29451
- updatedAt: Math.floor(Math.max(database.mtimeMs, wal?.mtimeMs ?? 0)),
29452
- // A stable read does not establish that another Cursor process is idle.
29453
- running: null
29880
+ updatedAt: Math.max(database.mtimeMs, wal?.mtimeMs ?? 0)
29454
29881
  });
29455
- return parsed.success ? parsed.data : null;
29456
- }
29457
- #read(operation) {
29458
- const signal = this.#abort.signal;
29459
- if (signal.aborted)
29460
- return Promise.resolve({
29461
- ok: false,
29462
- error: {
29463
- code: "invalidState",
29464
- message: "Cursor Session import is closed",
29465
- retryable: false
29466
- }
29467
- });
29468
- const request = operation(signal).then((value) => {
29469
- signal.throwIfAborted();
29470
- return { ok: true, value };
29471
- }).catch(() => ({
29472
- ok: false,
29473
- error: {
29474
- code: signal.aborted ? "invalidState" : "unavailable",
29475
- message: signal.aborted ? "Cursor Session import is closed" : "Cursor ACP sessions could not be read; close native clients, check storage access and retry",
29476
- retryable: !signal.aborted
29477
- }
29478
- })).finally(() => this.#pending.delete(request));
29479
- this.#pending.add(request);
29480
- return request;
29481
29882
  }
29482
- async close() {
29483
- this.#abort.abort();
29484
- await Promise.allSettled(this.#pending);
29883
+ close() {
29884
+ return this.#scope.close();
29485
29885
  }
29486
29886
  };
29487
29887
 
@@ -29573,14 +29973,14 @@ function cursorModels(info) {
29573
29973
  function cursorCatalog(info) {
29574
29974
  const native = cursorModels(info);
29575
29975
  const thinking = /* @__PURE__ */ new Map();
29576
- const models = native.models.map((model) => {
29577
- const config2 = model.value === native.current ? info.configOptions : info.nativeModels?.find((entry) => entry.value === model.value)?.configOptions;
29976
+ const models = native.models.map((model2) => {
29977
+ const config2 = model2.value === native.current ? info.configOptions : info.nativeModels?.find((entry) => entry.value === model2.value)?.configOptions;
29578
29978
  const options = cursorThinking(config2);
29579
29979
  for (const { id, label } of options)
29580
29980
  thinking.set(id, { id, label });
29581
29981
  return {
29582
- ref: cursorConfiguredModelRef(model.value, config2),
29583
- label: model.name,
29982
+ ref: cursorConfiguredModelRef(model2.value, config2),
29983
+ label: model2.name,
29584
29984
  supportedThinkingOptionIds: options.map(({ id }) => id)
29585
29985
  };
29586
29986
  });
@@ -29597,13 +29997,13 @@ function cursorCatalog(info) {
29597
29997
  function parseCursorNativeModels(input) {
29598
29998
  if (!Array.isArray(input.models))
29599
29999
  throw new Error("Cursor returned no parameterized model catalog");
29600
- return input.models.map((model) => {
29601
- if (typeof model !== "object" || model === null || !("value" in model) || !("name" in model) || !("configOptions" in model) || typeof model.value !== "string" || typeof model.name !== "string" || !Array.isArray(model.configOptions))
30000
+ return input.models.map((model2) => {
30001
+ if (typeof model2 !== "object" || model2 === null || !("value" in model2) || !("name" in model2) || !("configOptions" in model2) || typeof model2.value !== "string" || typeof model2.name !== "string" || !Array.isArray(model2.configOptions))
29602
30002
  throw new Error("Invalid Cursor model metadata");
29603
30003
  return {
29604
- value: model.value,
29605
- name: model.name,
29606
- configOptions: model.configOptions.map((option) => {
30004
+ value: model2.value,
30005
+ name: model2.name,
30006
+ configOptions: model2.configOptions.map((option) => {
29607
30007
  if (typeof option !== "object" || option === null || !("id" in option) || !("name" in option) || !("type" in option) || !("currentValue" in option) || !("options" in option) || typeof option.id !== "string" || typeof option.name !== "string" || option.type !== "select" || typeof option.currentValue !== "string" || !Array.isArray(option.options))
29608
30008
  throw new Error("Invalid Cursor parameter metadata");
29609
30009
  const entries = option.options.map((entry) => {
@@ -29624,7 +30024,7 @@ function parseCursorNativeModels(input) {
29624
30024
  });
29625
30025
  }
29626
30026
  function cursorModelSelection(info, ref) {
29627
- const exact = cursorModels(info).models.find((model2) => cursorModelRef(model2.value).id === ref);
30027
+ const exact = cursorModels(info).models.find((model3) => cursorModelRef(model3.value).id === ref);
29628
30028
  if (exact)
29629
30029
  return [["model", exact.value]];
29630
30030
  if (!ref.startsWith("cursor."))
@@ -29633,8 +30033,8 @@ function cursorModelSelection(info, ref) {
29633
30033
  if (cursorModelRef(decoded).id !== ref)
29634
30034
  throw new Error("Invalid Cursor model reference");
29635
30035
  const match = /^([^\[\]]+)\[([^\[\]]*)\]$/u.exec(decoded);
29636
- const model = match && info.nativeModels?.find((entry) => entry.value === match[1]);
29637
- if (!match || !model)
30036
+ const model2 = match && info.nativeModels?.find((entry) => entry.value === match[1]);
30037
+ if (!match || !model2)
29638
30038
  throw new Error("Model is not in this Cursor session's native catalog");
29639
30039
  const parameters = [];
29640
30040
  for (const parameter of match[2] ? match[2].split(",") : []) {
@@ -29642,12 +30042,12 @@ function cursorModelSelection(info, ref) {
29642
30042
  const [id, value] = pair;
29643
30043
  if (pair.length !== 2 || !id || value === void 0 || parameters.some(([key]) => key === id))
29644
30044
  throw new Error("Invalid Cursor model parameters");
29645
- const option = model.configOptions.find((option2) => option2.id === id);
30045
+ const option = model2.configOptions.find((option2) => option2.id === id);
29646
30046
  if (!option || option.type !== "select" || !option.options.flatMap((entry) => "value" in entry ? [entry] : entry.options).some((entry) => entry.value === value))
29647
30047
  throw new Error("Legacy Cursor model parameter is not selectable in the native catalog");
29648
30048
  parameters.push([id, value]);
29649
30049
  }
29650
- return [["model", model.value], ...parameters];
30050
+ return [["model", model2.value], ...parameters];
29651
30051
  }
29652
30052
  function cursorCapabilities(info) {
29653
30053
  return {
@@ -29658,9 +30058,9 @@ function cursorCapabilities(info) {
29658
30058
  }
29659
30059
  };
29660
30060
  }
29661
- function cursorConfiguredModelRef(model, options) {
30061
+ function cursorConfiguredModelRef(model2, options) {
29662
30062
  const parameters = (options ?? []).flatMap((option) => option.category === "model_config" && option.type === "select" ? [`${option.id}=${option.currentValue}`] : []);
29663
- return cursorModelRef(parameters.length ? `${model}[${parameters.join(",")}]` : model);
30063
+ return cursorModelRef(parameters.length ? `${model2}[${parameters.join(",")}]` : model2);
29664
30064
  }
29665
30065
 
29666
30066
  // dist/transport.js
@@ -31950,9 +32350,9 @@ var Connection = class {
31950
32350
  return;
31951
32351
  }
31952
32352
  const responseBatch = isResponseBatch(batch);
31953
- const responseCount = responseBatch ? 0 : batch.reduce((count, message) => count + (isNotificationMessage(message) ? 0 : 1), 0);
32353
+ const responseCount = responseBatch ? 0 : batch.reduce((count2, message) => count2 + (isNotificationMessage(message) ? 0 : 1), 0);
31954
32354
  let remaining = responseCount;
31955
- let remainingNotifications = batch.reduce((count, message) => count + (isNotificationMessage(message) ? 1 : 0), 0);
32355
+ let remainingNotifications = batch.reduce((count2, message) => count2 + (isNotificationMessage(message) ? 1 : 0), 0);
31956
32356
  let responseSent = false;
31957
32357
  const responses = [];
31958
32358
  const sendResponsesIfReady = async () => {
@@ -45257,7 +45657,7 @@ async function createCursorDelegationBridge(cwd, environment, commandTimeoutMs =
45257
45657
  server.registerTool("harness_inspect", {
45258
45658
  description: "Read a Harness's native Models and Thinking choices. Use opaque IDs only when explicitly selecting; omission retains native defaults.",
45259
45659
  inputSchema: { harness: text, cwd: text.optional() }
45260
- }, ({ harness, cwd: cwd2 }) => run(["harness", "inspect", harness, ...optional2("--cwd", cwd2)]));
45660
+ }, ({ harness: harness2, cwd: cwd2 }) => run(["harness", "inspect", harness2, ...optional2("--cwd", cwd2)]));
45261
45661
  server.registerTool("delegate_start", {
45262
45662
  description: "Start an independent task in another Harness when the user requests delegation. Returns immediately with a task link; use thread_wait for completion. Parent attribution and credentials come from this Cursor session. Do not delegate to Cursor: unattended inbound Cursor tasks are unsupported.",
45263
45663
  inputSchema: {
@@ -45268,15 +45668,15 @@ async function createCursorDelegationBridge(cwd, environment, commandTimeoutMs =
45268
45668
  thinking: text.optional(),
45269
45669
  requestId: text.optional()
45270
45670
  }
45271
- }, ({ harness, task, cwd: cwd2, model, thinking, requestId }) => run([
45671
+ }, ({ harness: harness2, task, cwd: cwd2, model: model2, thinking, requestId }) => run([
45272
45672
  "delegate",
45273
45673
  "start",
45274
45674
  "--harness",
45275
- harness,
45675
+ harness2,
45276
45676
  "--task",
45277
45677
  task,
45278
45678
  ...optional2("--cwd", cwd2),
45279
- ...optional2("--model", model),
45679
+ ...optional2("--model", model2),
45280
45680
  ...optional2("--thinking", thinking),
45281
45681
  ...optional2("--request-id", requestId)
45282
45682
  ]));
@@ -45501,7 +45901,7 @@ var CursorTransport = class {
45501
45901
  return info;
45502
45902
  const modelOption = info.configOptions?.find((option) => option.id === "model");
45503
45903
  const available = modelOption?.type === "select" ? modelOption.options.flatMap((entry) => "value" in entry ? [entry] : entry.options) : void 0;
45504
- if (this.cachedModels?.length && available?.length === this.cachedModels.length && available.every((model) => this.cachedModels?.some((cached2) => cached2.value === model.value && cached2.name === model.name)))
45904
+ if (this.cachedModels?.length && available?.length === this.cachedModels.length && available.every((model2) => this.cachedModels?.some((cached2) => cached2.value === model2.value && cached2.name === model2.name)))
45505
45905
  return { ...info, nativeModels: structuredClone(this.cachedModels) };
45506
45906
  try {
45507
45907
  const models = await this.#bounded(this.#connection.extMethod("cursor/list_available_models", {}));
@@ -46298,7 +46698,13 @@ var CursorTurnOutput = class {
46298
46698
  constructor(turnId, emit, nativeTurnIndex = 0) {
46299
46699
  this.turnId = turnId;
46300
46700
  this.emit = emit;
46301
- this.subagents = new CursorSubagents(turnId, emit, nativeTurnIndex);
46701
+ this.subagents = new CursorSubagents(turnId, (event) => {
46702
+ if (event.type === "item.started") {
46703
+ this.#flushHold();
46704
+ this.#finishText();
46705
+ }
46706
+ emit(event);
46707
+ }, nativeTurnIndex);
46302
46708
  }
46303
46709
  sawWritableIterableClosed() {
46304
46710
  return this.#writableIterableClosed || takeCursorWritableIterableClosed(this.#hold).closed;
@@ -46348,11 +46754,8 @@ var CursorTurnOutput = class {
46348
46754
  this.#text = void 0;
46349
46755
  }
46350
46756
  update(notification) {
46351
- if (this.subagents.update(notification)) {
46352
- this.#flushHold();
46353
- this.#finishText();
46757
+ if (this.subagents.update(notification))
46354
46758
  return;
46355
- }
46356
46759
  const { update } = notification;
46357
46760
  if (update.sessionUpdate === "agent_message_chunk" || update.sessionUpdate === "agent_thought_chunk") {
46358
46761
  if (update.content.type !== "text")
@@ -46368,12 +46771,12 @@ var CursorTurnOutput = class {
46368
46771
  this.#hold = hold;
46369
46772
  this.#appendText(type, emit);
46370
46773
  } else if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
46371
- this.#flushHold();
46372
- this.#finishText();
46373
46774
  if (this.#finishedTools.has(update.toolCallId))
46374
46775
  return;
46375
46776
  let tool = this.#tools.get(update.toolCallId);
46376
46777
  if (!tool) {
46778
+ this.#flushHold();
46779
+ this.#finishText();
46377
46780
  const args = jsonValueSchema.safeParse(update.rawInput ?? {});
46378
46781
  const item2 = {
46379
46782
  type: "toolExecution",
@@ -47173,7 +47576,7 @@ var CursorAdapter = class {
47173
47576
  throw staged.reason;
47174
47577
  if (!derived)
47175
47578
  throw new Error("Cursor native fork did not return a target");
47176
- const model = input.kind === "rollbackLastTurn" ? input.model ?? source?.initialState.effectiveModel : source?.initialState.effectiveModel;
47579
+ const model2 = input.kind === "rollbackLastTurn" ? input.model ?? source?.initialState.effectiveModel : source?.initialState.effectiveModel;
47177
47580
  const thinking = input.kind === "rollbackLastTurn" ? input.thinkingOptionId ?? source?.initialState.effectiveThinkingOptionId : source?.initialState.effectiveThinkingOptionId;
47178
47581
  const mode = input.kind === "rollbackLastTurn" ? input.permissionModeId ?? source?.initialState.effectivePermissionModeId : source?.initialState.effectivePermissionModeId;
47179
47582
  const opened = await this.#openSession({
@@ -47181,7 +47584,7 @@ var CursorAdapter = class {
47181
47584
  cwd: input.cwd,
47182
47585
  environment: options.environment,
47183
47586
  nativeRef: cursorNativeSessionRef(derived.sessionId, executionPolicy),
47184
- ...model ? { model } : {},
47587
+ ...model2 ? { model: model2 } : {},
47185
47588
  ...thinking ? { thinkingOptionId: thinking } : {},
47186
47589
  ...mode ? { permissionModeId: mode } : {}
47187
47590
  }, transport);
@@ -47398,9 +47801,9 @@ var CursorSession = class {
47398
47801
  if (!result.configOptions.some((option) => option.id === configId && option.currentValue === value))
47399
47802
  throw new Error("Cursor did not confirm configuration selection");
47400
47803
  this.info.configOptions = result.configOptions;
47401
- const model = result.configOptions.find((option) => option.id === "model");
47402
- if (model?.type === "select")
47403
- this.initialState.effectiveModel = cursorConfiguredModelRef(model.currentValue, result.configOptions);
47804
+ const model2 = result.configOptions.find((option) => option.id === "model");
47805
+ if (model2?.type === "select")
47806
+ this.initialState.effectiveModel = cursorConfiguredModelRef(model2.currentValue, result.configOptions);
47404
47807
  const mode = result.configOptions.find((option) => option.id === "mode");
47405
47808
  if (mode)
47406
47809
  this.initialState.effectivePermissionModeId = harnessPermissionModeIdSchema.parse(mode.currentValue);
@@ -47530,6 +47933,7 @@ var CursorSession = class {
47530
47933
  };
47531
47934
 
47532
47935
  // ../../harness-broker/dist/client.js
47936
+ import { execFile as execFile4 } from "node:child_process";
47533
47937
  import { randomUUID as randomUUID2 } from "node:crypto";
47534
47938
  import { lstat as lstat2, readFile as readFile4 } from "node:fs/promises";
47535
47939
  import net, {} from "node:net";
@@ -47540,9 +47944,12 @@ var HARNESS_BROKER_MAX_FRAME_BYTES = 8 * 1024 * 1024;
47540
47944
  var HARNESS_BROKER_MAX_PENDING_REQUESTS = 32;
47541
47945
  var HARNESS_BROKER_REQUEST_TIMEOUT_MS = 15e3;
47542
47946
  var HARNESS_BROKER_SESSION_IMPORT_PAGE_SIZE = 100;
47947
+ var HARNESS_BROKER_IDLE_TIMEOUT_MS = 60 * 60 * 1e3;
47948
+ var HARNESS_BROKER_RETIRING_ERROR_CODE = "brokerRetiring";
47543
47949
  var harnessBrokerMethodSchema = external_exports.enum([
47544
47950
  "adapter.inspect",
47545
47951
  "adapter.inspectAccount",
47952
+ "adapter.credits",
47546
47953
  "adapter.open",
47547
47954
  "adapter.sessionImport.list",
47548
47955
  "adapter.sessionImport.resolve",
@@ -47662,6 +48069,14 @@ function defaultHarnessBrokerDescriptorPath(environment = process.env, harnessId
47662
48069
  return path11.join(defaultHarnessBrokerDirectory(environment), `${harnessId}-broker-v1.json`);
47663
48070
  return environment[HARNESS_BROKER_DESCRIPTOR_ENV] ?? path11.join(defaultHarnessBrokerDirectory(environment), HARNESS_BROKER_DESCRIPTOR_FILE);
47664
48071
  }
48072
+ function harnessBrokerLaunchAgentLabel(harnessId = "claude-code") {
48073
+ harnessPluginIdSchema.parse(harnessId);
48074
+ return harnessId === "claude-code" ? "ai.bytepioneer.codexhost.native-harness-broker" : `ai.bytepioneer.codexhost.${harnessId}-broker`;
48075
+ }
48076
+ function harnessBrokerLaunchAgentPlistPath(environment = process.env, harnessId = "claude-code") {
48077
+ const home = environment.HOME || os4.homedir();
48078
+ return path11.join(home, "Library", "LaunchAgents", `${harnessBrokerLaunchAgentLabel(harnessId)}.plist`);
48079
+ }
47665
48080
 
47666
48081
  // ../../harness-broker/dist/validation.js
47667
48082
  var cwdSchema = external_exports.string().min(1).max(16384);
@@ -47836,6 +48251,8 @@ var harnessSessionStateSchema = external_exports.custom((value) => {
47836
48251
  var eventKeys = /* @__PURE__ */ new Map([
47837
48252
  ["session.state.changed", /* @__PURE__ */ new Set(["type", "state"])],
47838
48253
  ["session.usage.changed", /* @__PURE__ */ new Set(["type", "usage", "observedForTurnId"])],
48254
+ ["usage.request", /* @__PURE__ */ new Set(["type", "request"])],
48255
+ ["usage.history", /* @__PURE__ */ new Set(["type", "complete"])],
47839
48256
  ["subagent.state.changed", /* @__PURE__ */ new Set(["type", "nativeSubagentId", "status", "resultSummary"])],
47840
48257
  ["subagent.transcript.changed", /* @__PURE__ */ new Set(["type", "nativeSubagentId"])],
47841
48258
  ["turn.started", /* @__PURE__ */ new Set(["type", "turnId"])],
@@ -47884,6 +48301,8 @@ var harnessOutputSchema = external_exports.custom((value) => {
47884
48301
  return harnessSessionStateSchema.safeParse(event.state).success;
47885
48302
  if (event.type === "session.faulted")
47886
48303
  return harnessErrorSchema.safeParse(event.error).success;
48304
+ if (event.type === "usage.history")
48305
+ return typeof event.complete === "boolean";
47887
48306
  return true;
47888
48307
  }
47889
48308
  if (output.kind === "interaction") {
@@ -47988,10 +48407,55 @@ async function readDescriptor(descriptorPath) {
47988
48407
  try {
47989
48408
  process.kill(descriptor.ownerPid, 0);
47990
48409
  } catch {
47991
- throw new Error("Aqua Harness broker owner process is unavailable");
48410
+ throw new BrokerNotRunningError("its owner process has exited");
47992
48411
  }
47993
48412
  return descriptor;
47994
48413
  }
48414
+ var BrokerNotRunningError = class extends Error {
48415
+ };
48416
+ var BrokerRetiringError = class extends Error {
48417
+ };
48418
+ var BrokerRequestNotDeliveredError = class extends Error {
48419
+ };
48420
+ var HarnessNotInstalledError = class extends Error {
48421
+ };
48422
+ var BROKER_NOT_RUNNING_CODES = /* @__PURE__ */ new Set(["ENOENT", "ECONNREFUSED"]);
48423
+ var BROKER_START_TIMEOUT_MS = 15e3;
48424
+ var BROKER_START_POLL_MS = 250;
48425
+ function classifyConnectFailure(error51) {
48426
+ if (error51 instanceof BrokerNotRunningError)
48427
+ return error51;
48428
+ const code = error51?.code;
48429
+ if (code && BROKER_NOT_RUNNING_CODES.has(code)) {
48430
+ return new BrokerNotRunningError(code === "ENOENT" ? "its descriptor or socket is missing" : "its socket refused the connection");
48431
+ }
48432
+ return error51 instanceof Error ? error51 : new Error(String(error51));
48433
+ }
48434
+ function describeBrokerFailure(error51, harnessId) {
48435
+ if (error51 instanceof BrokerNotRunningError) {
48436
+ return `The ${harnessId} Aqua Harness broker on this Mac could not be started (${error51.message}). Keep the desktop user logged in, then repair the remote service or run on this Mac: codexhost broker install --harness ${harnessId}`;
48437
+ }
48438
+ return error51 instanceof Error ? error51.message : String(error51);
48439
+ }
48440
+ function runLaunchctl(arguments_) {
48441
+ return new Promise((resolve) => {
48442
+ execFile4("/bin/launchctl", arguments_, { timeout: 1e4 }, (error51) => resolve(!error51));
48443
+ });
48444
+ }
48445
+ async function startBrokerLaunchAgent(harnessId, environment) {
48446
+ const uid = process.getuid?.();
48447
+ if (uid === void 0)
48448
+ return;
48449
+ const target = `gui/${uid}/${harnessBrokerLaunchAgentLabel(harnessId)}`;
48450
+ if (await runLaunchctl(["kickstart", target]))
48451
+ return;
48452
+ await runLaunchctl([
48453
+ "bootstrap",
48454
+ `gui/${uid}`,
48455
+ harnessBrokerLaunchAgentPlistPath(environment, harnessId)
48456
+ ]);
48457
+ await runLaunchctl(["kickstart", target]);
48458
+ }
47995
48459
  var BrokerConnection = class _BrokerConnection {
47996
48460
  #onClose;
47997
48461
  onClose(callback) {
@@ -48015,21 +48479,31 @@ var BrokerConnection = class _BrokerConnection {
48015
48479
  socket.once("error", (error51) => this.#fail(error51));
48016
48480
  }
48017
48481
  static async connect(descriptorPath, harnessId) {
48018
- const descriptor = await readDescriptor(descriptorPath);
48019
- if (descriptor.harnessId !== harnessId)
48020
- throw new Error("Aqua broker belongs to another Harness");
48021
- const socket = net.createConnection(descriptor.socketPath);
48022
- await new Promise((resolve, reject) => {
48023
- const timeout = setTimeout(() => reject(new Error("Timed out connecting to Aqua Harness broker")), HARNESS_BROKER_REQUEST_TIMEOUT_MS);
48024
- socket.once("connect", () => {
48025
- clearTimeout(timeout);
48026
- resolve();
48027
- });
48028
- socket.once("error", (error51) => {
48029
- clearTimeout(timeout);
48030
- reject(error51);
48482
+ let descriptor;
48483
+ let socket;
48484
+ let connecting;
48485
+ try {
48486
+ descriptor = await readDescriptor(descriptorPath);
48487
+ if (descriptor.harnessId !== harnessId)
48488
+ throw new Error("Aqua broker belongs to another Harness");
48489
+ connecting = net.createConnection(descriptor.socketPath);
48490
+ const pending = connecting;
48491
+ await new Promise((resolve, reject) => {
48492
+ const timeout = setTimeout(() => reject(new Error("Timed out connecting to Aqua Harness broker")), HARNESS_BROKER_REQUEST_TIMEOUT_MS);
48493
+ pending.once("connect", () => {
48494
+ clearTimeout(timeout);
48495
+ resolve();
48496
+ });
48497
+ pending.once("error", (error51) => {
48498
+ clearTimeout(timeout);
48499
+ reject(error51);
48500
+ });
48031
48501
  });
48032
- });
48502
+ socket = pending;
48503
+ } catch (error51) {
48504
+ connecting?.destroy();
48505
+ throw classifyConnectFailure(error51);
48506
+ }
48033
48507
  const connection = new _BrokerConnection(descriptor, socket);
48034
48508
  const hello = connection.#waitForHello();
48035
48509
  await writeBrokerFrame(socket, {
@@ -48082,15 +48556,24 @@ var BrokerConnection = class _BrokerConnection {
48082
48556
  }, HARNESS_BROKER_REQUEST_TIMEOUT_MS);
48083
48557
  this.#pending.set(id, { resolve, reject, timeout });
48084
48558
  });
48085
- await writeBrokerFrame(this.#socket, {
48086
- version: HARNESS_BROKER_PROTOCOL_VERSION,
48087
- generation: this.#descriptor.generation,
48088
- sequence: this.#inputSequence,
48089
- kind: "request",
48090
- id,
48091
- method,
48092
- params
48093
- });
48559
+ try {
48560
+ await writeBrokerFrame(this.#socket, {
48561
+ version: HARNESS_BROKER_PROTOCOL_VERSION,
48562
+ generation: this.#descriptor.generation,
48563
+ sequence: this.#inputSequence,
48564
+ kind: "request",
48565
+ id,
48566
+ method,
48567
+ params
48568
+ });
48569
+ } catch (error51) {
48570
+ const pending = this.#pending.get(id);
48571
+ if (pending)
48572
+ clearTimeout(pending.timeout);
48573
+ this.#pending.delete(id);
48574
+ response.catch(() => void 0);
48575
+ throw new BrokerRequestNotDeliveredError(error51 instanceof Error ? error51.message : String(error51));
48576
+ }
48094
48577
  return response;
48095
48578
  }
48096
48579
  close() {
@@ -48134,6 +48617,8 @@ var BrokerConnection = class _BrokerConnection {
48134
48617
  this.#pending.delete(frame.id);
48135
48618
  if (frame.ok)
48136
48619
  pending.resolve(frame.value);
48620
+ else if (frame.error?.code === HARNESS_BROKER_RETIRING_ERROR_CODE)
48621
+ pending.reject(new BrokerRetiringError(frame.error.message));
48137
48622
  else
48138
48623
  pending.reject(new Error(frame.error?.message ?? "Broker request failed"));
48139
48624
  }
@@ -48359,18 +48844,20 @@ var BrokeredHarnessAdapter = class {
48359
48844
  harnessId;
48360
48845
  #descriptorPath;
48361
48846
  #forwardEnvironment;
48847
+ #isInstalled;
48848
+ #startBroker;
48849
+ #startTimeoutMs;
48362
48850
  #connection = null;
48363
48851
  #closed = false;
48364
48852
  #sessionImportListing = null;
48853
+ #credits = null;
48854
+ #creditsRefresh = null;
48365
48855
  subagents = {
48366
48856
  readSnapshot: async (input) => {
48367
48857
  try {
48368
- return parseHarnessResult(await (await this.#connect()).request("adapter.subagent.readSnapshot", input));
48858
+ return parseHarnessResult(await this.#request("adapter.subagent.readSnapshot", input));
48369
48859
  } catch (error51) {
48370
- return {
48371
- ok: false,
48372
- error: unavailable(error51 instanceof Error ? error51.message : String(error51))
48373
- };
48860
+ return { ok: false, error: this.#error(error51) };
48374
48861
  }
48375
48862
  }
48376
48863
  };
@@ -48460,12 +48947,39 @@ var BrokeredHarnessAdapter = class {
48460
48947
  if (input.liveCommandCatalog)
48461
48948
  this.liveCommandCatalog = true;
48462
48949
  this.#descriptorPath = input.descriptorPath ?? defaultHarnessBrokerDescriptorPath(input.environment, this.harnessId);
48950
+ this.#isInstalled = input.isInstalled;
48951
+ const environment = input.environment ?? process.env;
48952
+ this.#startBroker = input.startBroker === false ? void 0 : input.startBroker ?? (process.platform === "darwin" && !input.descriptorPath ? () => startBrokerLaunchAgent(this.harnessId, environment) : void 0);
48953
+ this.#startTimeoutMs = input.startTimeoutMs ?? BROKER_START_TIMEOUT_MS;
48954
+ }
48955
+ credits() {
48956
+ return this.#credits;
48957
+ }
48958
+ refreshCredits() {
48959
+ if (this.#closed)
48960
+ return Promise.resolve(null);
48961
+ if (this.#creditsRefresh)
48962
+ return this.#creditsRefresh;
48963
+ this.#creditsRefresh = this.#readCredits().finally(() => {
48964
+ this.#creditsRefresh = null;
48965
+ });
48966
+ return this.#creditsRefresh;
48967
+ }
48968
+ async #readCredits() {
48969
+ try {
48970
+ const value = await this.#request("adapter.credits", {}, true);
48971
+ const credits = accountCreditsSnapshotSchema.nullable().parse(value);
48972
+ if (!this.#closed)
48973
+ this.#credits = credits;
48974
+ } catch {
48975
+ }
48976
+ return this.#credits;
48463
48977
  }
48464
48978
  async inspectAccount() {
48465
48979
  if (this.#closed)
48466
48980
  return null;
48467
48981
  try {
48468
- const value = await (await this.#connect()).request("adapter.inspectAccount", {});
48982
+ const value = await this.#request("adapter.inspectAccount", {}, true);
48469
48983
  return harnessAccountSnapshotSchema.nullable().parse(value);
48470
48984
  } catch {
48471
48985
  return null;
@@ -48475,33 +48989,46 @@ var BrokeredHarnessAdapter = class {
48475
48989
  if (this.#closed)
48476
48990
  return failedInspection("Aqua Harness broker adapter is closed");
48477
48991
  try {
48478
- return harnessInspectionSchema.parse(await (await this.#connect()).request("adapter.inspect", input));
48992
+ return harnessInspectionSchema.parse(await this.#request("adapter.inspect", input, true));
48479
48993
  } catch (error51) {
48480
48994
  this.#connection = null;
48481
- return failedInspection(error51 instanceof Error ? error51.message : String(error51));
48995
+ if (error51 instanceof HarnessNotInstalledError)
48996
+ return { status: "notInstalled", error: this.#error(error51) };
48997
+ return failedInspection(describeBrokerFailure(error51, this.harnessId));
48482
48998
  }
48483
48999
  }
48484
49000
  async open(input) {
48485
49001
  if (this.#closed)
48486
49002
  return { ok: false, error: unavailable("Aqua Harness broker adapter is closed", false) };
49003
+ const safeInput = { ...input };
49004
+ delete safeInput.environment;
49005
+ if (this.#forwardEnvironment && input.environment) {
49006
+ const allowed = [
49007
+ "CODEXHOST_CLI_PATH",
49008
+ "CODEXHOST_CLI_NODE_PATH",
49009
+ "CODEXHOST_RUNTIME_ENDPOINT",
49010
+ "CODEXHOST_RUNTIME_TOKEN",
49011
+ "CODEXHOST_THREAD_ID"
49012
+ ];
49013
+ const environment = Object.fromEntries(Object.entries(input.environment).filter(([key, value]) => allowed.includes(key) && value !== void 0));
49014
+ if (Object.keys(environment).length)
49015
+ safeInput.environment = environment;
49016
+ }
48487
49017
  let connection;
48488
49018
  try {
48489
- const safeInput = { ...input };
48490
- delete safeInput.environment;
48491
- if (this.#forwardEnvironment && input.environment) {
48492
- const allowed = [
48493
- "CODEXHOST_CLI_PATH",
48494
- "CODEXHOST_CLI_NODE_PATH",
48495
- "CODEXHOST_RUNTIME_ENDPOINT",
48496
- "CODEXHOST_RUNTIME_TOKEN",
48497
- "CODEXHOST_THREAD_ID"
48498
- ];
48499
- const environment = Object.fromEntries(Object.entries(input.environment).filter(([key, value]) => allowed.includes(key) && value !== void 0));
48500
- if (Object.keys(environment).length)
48501
- safeInput.environment = environment;
48502
- }
48503
- connection = await this.#connect();
48504
- const result = parseHarnessResult(await connection.request("adapter.open", safeInput));
49019
+ let value;
49020
+ for (let attempt = 0; ; attempt += 1) {
49021
+ connection = await this.#connect();
49022
+ try {
49023
+ value = await connection.request("adapter.open", safeInput);
49024
+ break;
49025
+ } catch (error51) {
49026
+ if (attempt > 0 || !(error51 instanceof BrokerRetiringError || error51 instanceof BrokerRequestNotDeliveredError))
49027
+ throw error51;
49028
+ this.#connection = null;
49029
+ }
49030
+ }
49031
+ const result = parseHarnessResult(value);
48505
49032
  if (!result.ok)
48506
49033
  return result;
48507
49034
  const session = new BrokeredHarnessSession(connection, parseSessionMetadata(result.value), this.harnessId, safeInput, () => this.#connect(), () => {
@@ -48512,25 +49039,51 @@ var BrokeredHarnessAdapter = class {
48512
49039
  } catch (error51) {
48513
49040
  connection?.close();
48514
49041
  this.#connection = null;
48515
- return {
48516
- ok: false,
48517
- error: unavailable(error51 instanceof Error ? error51.message : String(error51))
48518
- };
49042
+ return { ok: false, error: this.#error(error51) };
48519
49043
  }
48520
49044
  }
48521
49045
  async close() {
48522
49046
  this.#closed = true;
49047
+ this.#credits = null;
48523
49048
  await Promise.allSettled([...this.#sessions].map((session) => session.close()));
48524
49049
  this.#sessions.clear();
48525
49050
  const connection = await this.#connection?.catch(() => null);
48526
49051
  await connection?.dispose();
48527
49052
  this.#connection = null;
48528
49053
  }
49054
+ #error(error51) {
49055
+ if (error51 instanceof HarnessNotInstalledError)
49056
+ return {
49057
+ code: "notInstalled",
49058
+ message: error51.message,
49059
+ retryable: false,
49060
+ stage: "harnessBroker"
49061
+ };
49062
+ return unavailable(describeBrokerFailure(error51, this.harnessId));
49063
+ }
49064
+ /**
49065
+ * Sends one adapter-level request. A broker that retired between requests refuses it
49066
+ * unprocessed, so it is retried once on a fresh broker. Idempotent reads also retry
49067
+ * once after a plain disconnect.
49068
+ */
49069
+ async #request(method, params, idempotent = false) {
49070
+ for (let attempt = 0; ; attempt += 1) {
49071
+ const connection = await this.#connect();
49072
+ try {
49073
+ return await connection.request(method, params);
49074
+ } catch (error51) {
49075
+ const retryable = error51 instanceof BrokerRetiringError || error51 instanceof BrokerRequestNotDeliveredError || idempotent && connection.closed;
49076
+ if (attempt > 0 || !retryable)
49077
+ throw error51;
49078
+ this.#connection = null;
49079
+ }
49080
+ }
49081
+ }
48529
49082
  #connect() {
48530
49083
  if (this.#closed)
48531
49084
  return Promise.reject(new Error("Aqua Harness broker adapter is closed"));
48532
49085
  if (!this.#connection) {
48533
- const pending = BrokerConnection.connect(this.#descriptorPath, this.harnessId).then((connection) => {
49086
+ const pending = this.#establish().then((connection) => {
48534
49087
  connection.onClose(() => {
48535
49088
  if (this.#connection === pending)
48536
49089
  this.#connection = null;
@@ -48545,18 +49098,50 @@ var BrokeredHarnessAdapter = class {
48545
49098
  }
48546
49099
  return this.#connection;
48547
49100
  }
49101
+ async #establish() {
49102
+ try {
49103
+ return await BrokerConnection.connect(this.#descriptorPath, this.harnessId);
49104
+ } catch (error51) {
49105
+ if (!(error51 instanceof BrokerNotRunningError) || !this.#startBroker)
49106
+ throw error51;
49107
+ }
49108
+ if (this.#isInstalled && !this.#isInstalled()) {
49109
+ throw new HarnessNotInstalledError(`${this.harnessId} is not installed on this Mac`);
49110
+ }
49111
+ const deadline = Date.now() + this.#startTimeoutMs;
49112
+ for (; ; ) {
49113
+ await this.#startBroker();
49114
+ try {
49115
+ return await BrokerConnection.connect(this.#descriptorPath, this.harnessId);
49116
+ } catch (error51) {
49117
+ if (!(error51 instanceof BrokerNotRunningError) || Date.now() >= deadline)
49118
+ throw error51;
49119
+ }
49120
+ await new Promise((resolve) => setTimeout(resolve, BROKER_START_POLL_MS));
49121
+ }
49122
+ }
48548
49123
  };
48549
49124
 
48550
49125
  // dist/plugin.js
48551
49126
  function createHarnessAdapter(context) {
48552
- if (context.platform === "darwin" && context.managedRemoteHost)
49127
+ if (context.platform === "darwin" && context.managedRemoteHost) {
49128
+ const environment2 = { ...context.environment };
48553
49129
  return new BrokeredHarnessAdapter({
48554
49130
  harnessId: "cursor-cli",
48555
49131
  forwardDelegationEnvironment: true,
48556
49132
  commandCatalog: CURSOR_COMMAND_CATALOG,
48557
49133
  liveCommandCatalog: true,
48558
- environment: { ...context.environment }
49134
+ environment: environment2,
49135
+ isInstalled: () => {
49136
+ try {
49137
+ resolveCursorExecutable(environment2);
49138
+ return true;
49139
+ } catch (error51) {
49140
+ return !(error51 instanceof CursorNotInstalledError);
49141
+ }
49142
+ }
48559
49143
  });
49144
+ }
48560
49145
  const environment = { ...context.environment };
48561
49146
  return Object.assign(new CursorAdapter({ environment }), {
48562
49147
  installation: createCursorInstallation(environment),