@cortexkit/opencode-antigravity-auth 3.0.9 → 3.0.11

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 (131) hide show
  1. package/dist/cli.js +803 -281
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +142 -53
  4. package/dist/index.js +1114 -471
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +152 -63
  7. package/dist/server.js +1145 -502
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +3 -1
  11. package/dist/src/common-auth-embedded/claustrum/consumer.js +25 -21
  12. package/dist/src/common-auth-embedded/claustrum/enrollment.d.ts +5 -0
  13. package/dist/src/common-auth-embedded/claustrum/enrollment.js +27 -0
  14. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  15. package/dist/src/common-auth-embedded/claustrum/index.js +1 -0
  16. package/dist/src/common-auth-embedded/claustrum/quota-writer.d.ts +18 -0
  17. package/dist/src/common-auth-embedded/claustrum/quota-writer.js +253 -0
  18. package/dist/src/common-auth-embedded/claustrum/roster.d.ts +18 -2
  19. package/dist/src/common-auth-embedded/claustrum/roster.js +100 -43
  20. package/dist/src/common-auth-embedded/fs/private-files.d.ts +2 -0
  21. package/dist/src/common-auth-embedded/fs/private-files.js +49 -3
  22. package/dist/src/common-auth-embedded/fs/with-lock.d.ts +1 -0
  23. package/dist/src/common-auth-embedded/fs/with-lock.js +2 -0
  24. package/dist/src/common-auth-embedded/quota/format.d.ts +19 -0
  25. package/dist/src/common-auth-embedded/quota/format.js +50 -5
  26. package/dist/src/common-auth-embedded/quota/index.d.ts +3 -3
  27. package/dist/src/common-auth-embedded/quota/index.js +2 -2
  28. package/dist/src/common-auth-embedded/quota/map.d.ts +24 -1
  29. package/dist/src/common-auth-embedded/quota/map.js +31 -6
  30. package/dist/src/common-auth-embedded/quota/merge.d.ts +6 -1
  31. package/dist/src/common-auth-embedded/quota/merge.js +17 -3
  32. package/dist/src/common-auth-embedded/quota/projection.d.ts +3 -1
  33. package/dist/src/common-auth-embedded/quota/projection.js +3 -1
  34. package/dist/src/common-auth-embedded/setup/enroll.d.ts +34 -0
  35. package/dist/src/common-auth-embedded/setup/enroll.js +116 -34
  36. package/dist/src/common-auth-embedded/setup/index.d.ts +1 -0
  37. package/dist/src/common-auth-embedded/setup/index.js +1 -0
  38. package/dist/src/common-auth-embedded/setup/process-fence.d.ts +14 -0
  39. package/dist/src/common-auth-embedded/setup/process-fence.js +61 -4
  40. package/dist/src/common-auth-embedded/setup/types.d.ts +5 -0
  41. package/dist/src/common-auth-embedded/source-output.json +115 -91
  42. package/dist/src/plugin/lifecycle.d.ts.map +1 -1
  43. package/dist/src/plugin/lifecycle.js +48 -27
  44. package/dist/src/plugin/lifecycle.js.map +1 -1
  45. package/dist/src/plugin/request-helpers.d.ts +5 -0
  46. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  47. package/dist/src/plugin/request-helpers.js +1 -0
  48. package/dist/src/plugin/request-helpers.js.map +1 -1
  49. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  50. package/dist/src/plugin/shared/request-services.js +125 -7
  51. package/dist/src/plugin/shared/request-services.js.map +1 -1
  52. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  53. package/dist/src/plugin/vault-custody.js +13 -3
  54. package/dist/src/plugin/vault-custody.js.map +1 -1
  55. package/dist/tui-build-map.json +25 -25
  56. package/dist/tui-ga-build-map.json +21 -21
  57. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +3 -1
  58. package/dist/types/src/common-auth-embedded/claustrum/enrollment.d.ts +5 -0
  59. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  60. package/dist/types/src/common-auth-embedded/claustrum/quota-writer.d.ts +18 -0
  61. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +18 -2
  62. package/dist/types/src/common-auth-embedded/quota/format.d.ts +19 -0
  63. package/dist/types/src/common-auth-embedded/quota/index.d.ts +3 -3
  64. package/dist/types/src/common-auth-embedded/quota/map.d.ts +24 -1
  65. package/dist/types/src/common-auth-embedded/quota/merge.d.ts +6 -1
  66. package/dist/types/src/common-auth-embedded/quota/projection.d.ts +3 -1
  67. package/dist/types/src/common-auth-embedded/setup/enroll.d.ts +34 -0
  68. package/dist/types/src/common-auth-embedded/setup/index.d.ts +1 -0
  69. package/dist/types/src/common-auth-embedded/setup/process-fence.d.ts +14 -0
  70. package/dist/types/src/common-auth-embedded/setup/types.d.ts +5 -0
  71. package/dist/types/src/plugin/config/schema.d.ts +2 -2
  72. package/dist/types/src/plugin/lifecycle.d.ts.map +1 -1
  73. package/dist/types/src/plugin/request-helpers.d.ts +5 -0
  74. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  75. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  76. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  77. package/package.json +2 -2
  78. package/src/common-auth-embedded/claustrum/consumer.d.ts +3 -1
  79. package/src/common-auth-embedded/claustrum/consumer.js +25 -21
  80. package/src/common-auth-embedded/claustrum/enrollment.d.ts +5 -0
  81. package/src/common-auth-embedded/claustrum/enrollment.js +27 -0
  82. package/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  83. package/src/common-auth-embedded/claustrum/index.js +1 -0
  84. package/src/common-auth-embedded/claustrum/quota-writer.d.ts +18 -0
  85. package/src/common-auth-embedded/claustrum/quota-writer.js +253 -0
  86. package/src/common-auth-embedded/claustrum/roster.d.ts +18 -2
  87. package/src/common-auth-embedded/claustrum/roster.js +100 -43
  88. package/src/common-auth-embedded/fs/private-files.d.ts +2 -0
  89. package/src/common-auth-embedded/fs/private-files.js +49 -3
  90. package/src/common-auth-embedded/fs/with-lock.d.ts +1 -0
  91. package/src/common-auth-embedded/fs/with-lock.js +2 -0
  92. package/src/common-auth-embedded/quota/format.d.ts +19 -0
  93. package/src/common-auth-embedded/quota/format.js +50 -5
  94. package/src/common-auth-embedded/quota/index.d.ts +3 -3
  95. package/src/common-auth-embedded/quota/index.js +2 -2
  96. package/src/common-auth-embedded/quota/map.d.ts +24 -1
  97. package/src/common-auth-embedded/quota/map.js +31 -6
  98. package/src/common-auth-embedded/quota/merge.d.ts +6 -1
  99. package/src/common-auth-embedded/quota/merge.js +17 -3
  100. package/src/common-auth-embedded/quota/projection.d.ts +3 -1
  101. package/src/common-auth-embedded/quota/projection.js +3 -1
  102. package/src/common-auth-embedded/setup/enroll.d.ts +34 -0
  103. package/src/common-auth-embedded/setup/enroll.js +116 -34
  104. package/src/common-auth-embedded/setup/index.d.ts +1 -0
  105. package/src/common-auth-embedded/setup/index.js +1 -0
  106. package/src/common-auth-embedded/setup/process-fence.d.ts +14 -0
  107. package/src/common-auth-embedded/setup/process-fence.js +61 -4
  108. package/src/common-auth-embedded/setup/types.d.ts +5 -0
  109. package/src/common-auth-embedded/source-output.json +115 -91
  110. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +49 -3
  111. package/src/tui-compiled/common-auth-embedded/quota/format.js +50 -5
  112. package/src/tui-compiled/common-auth-embedded/quota/index.js +2 -2
  113. package/src/tui-compiled/common-auth-embedded/quota/map.js +31 -6
  114. package/src/tui-compiled/common-auth-embedded/quota/merge.js +17 -3
  115. package/src/tui-compiled/common-auth-embedded/quota/projection.js +3 -1
  116. package/src/tui-ga-compiled/shared/1ff34afa7c42d196-projection.js +3 -1
  117. package/src/tui-ga-compiled/shared/77138df80c7ae006-map.js +31 -6
  118. package/src/tui-ga-compiled/shared/aef2402f8fc342f0-format.js +50 -5
  119. package/src/tui-ga-compiled/shared/bf17cbee28e58197-index.js +2 -2
  120. package/src/tui-ga-compiled/shared/ecc214300932dfb6-merge.js +17 -3
  121. package/src/tui-ga-raw/shared/1ff34afa7c42d196-projection.js +3 -1
  122. package/src/tui-ga-raw/shared/77138df80c7ae006-map.js +31 -6
  123. package/src/tui-ga-raw/shared/aef2402f8fc342f0-format.js +50 -5
  124. package/src/tui-ga-raw/shared/bf17cbee28e58197-index.js +2 -2
  125. package/src/tui-ga-raw/shared/ecc214300932dfb6-merge.js +17 -3
  126. package/src/tui-raw/common-auth-embedded/fs/private-files.js +49 -3
  127. package/src/tui-raw/common-auth-embedded/quota/format.js +50 -5
  128. package/src/tui-raw/common-auth-embedded/quota/index.js +2 -2
  129. package/src/tui-raw/common-auth-embedded/quota/map.js +31 -6
  130. package/src/tui-raw/common-auth-embedded/quota/merge.js +17 -3
  131. package/src/tui-raw/common-auth-embedded/quota/projection.js +3 -1
package/dist/server.js CHANGED
@@ -64,6 +64,12 @@ function isQuotaCounter(value) {
64
64
  function isQuotaCounters(value) {
65
65
  return isRecord2(value) && Object.values(value).every(isQuotaCounter);
66
66
  }
67
+ function isBoolean(value) {
68
+ return typeof value === "boolean";
69
+ }
70
+ function isQuotaCredits(value) {
71
+ return isRecord2(value) && typeof value.hasCredits === "boolean" && typeof value.unlimited === "boolean" && optional2(value, "balance", isFiniteNumber) && optional2(value, "overageLimitReached", isBoolean) && isFiniteNumber(value.checkedAt);
72
+ }
67
73
  function readQuotaCounters(value) {
68
74
  if (!isRecord2(value))
69
75
  return void 0;
@@ -75,11 +81,16 @@ function decodeQuotaMap(value) {
75
81
  return value;
76
82
  if (!isRecord2(value))
77
83
  return void 0;
78
- const { counters: rawCounters, ...rest } = value;
84
+ const { counters: rawCounters, credits: rawCredits, ...rest } = value;
79
85
  if (!isQuotaMap(rest))
80
86
  return void 0;
81
87
  const counters = readQuotaCounters(rawCounters);
82
- return { ...rest, ...counters === void 0 ? {} : { counters } };
88
+ const credits = isQuotaCredits(rawCredits) ? rawCredits : void 0;
89
+ return {
90
+ ...rest,
91
+ ...counters === void 0 ? {} : { counters },
92
+ ...credits === void 0 ? {} : { credits }
93
+ };
83
94
  }
84
95
  function isQuotaMap(value) {
85
96
  if (!isRecord2(value) || !Array.isArray(value.limits))
@@ -93,7 +104,7 @@ function isQuotaMap(value) {
93
104
  return false;
94
105
  seen.add(key);
95
106
  }
96
- return optional2(value, "budget", isCreditBudgetEntry) && optional2(value, "counters", isQuotaCounters);
107
+ return optional2(value, "budget", isCreditBudgetEntry) && optional2(value, "counters", isQuotaCounters) && optional2(value, "credits", isQuotaCredits);
97
108
  }
98
109
  var ALL_SCOPE, DEFAULT_REQUIRED_LABELS;
99
110
  var init_map = __esm({
@@ -156,7 +167,7 @@ function isQuotaObservation(value) {
156
167
  }
157
168
  if (!coverage.every(isObservedPair))
158
169
  return false;
159
- return (value.budget === void 0 || isObservedBudget(value.budget)) && (value.counters === void 0 || isQuotaCounters(value.counters));
170
+ return (value.budget === void 0 || isObservedBudget(value.budget)) && (value.counters === void 0 || isQuotaCounters(value.counters)) && (value.credits === void 0 || isQuotaCredits(value.credits));
160
171
  }
161
172
  function compareEntries(left, right) {
162
173
  if (left.scope !== right.scope)
@@ -182,6 +193,14 @@ function mergeCounters(stored, observed) {
182
193
  }
183
194
  return counters.size === 0 ? void 0 : Object.fromEntries(counters);
184
195
  }
196
+ function mergeCredits(stored, observed) {
197
+ if (observed === void 0)
198
+ return stored;
199
+ if (stored !== void 0 && observed.checkedAt < stored.checkedAt) {
200
+ return stored;
201
+ }
202
+ return { ...observed };
203
+ }
185
204
  function mergeQuotaObservation(stored, observation) {
186
205
  const decoded = stored === void 0 ? void 0 : decodeQuotaMap(stored);
187
206
  if (stored !== void 0 && decoded === void 0) {
@@ -225,14 +244,16 @@ function mergeQuotaObservation(stored, observation) {
225
244
  const existing = entries.get(key);
226
245
  entries.set(key, existing === void 0 || existing.kind === "absent" ? { scope, label: pair.label, kind: "absent", checkedAt: at } : { scope, label: pair.label, kind: "retired", retiredAt: at });
227
246
  }
228
- const { limits: _limits, budget: _budget, counters: _counters, ...unknownKeys } = base;
247
+ const { limits: _limits, budget: _budget, counters: _counters, credits: _credits, ...unknownKeys } = base;
229
248
  const budget = mergeBudget(base.budget, observation.budget, at);
230
249
  const counters = mergeCounters(base.counters, observation.counters);
250
+ const credits = mergeCredits(base.credits, observation.credits);
231
251
  return {
232
252
  ...unknownKeys,
233
253
  limits: [...entries.values()].sort(compareEntries),
234
254
  ...budget === void 0 ? {} : { budget },
235
- ...counters === void 0 ? {} : { counters }
255
+ ...counters === void 0 ? {} : { counters },
256
+ ...credits === void 0 ? {} : { credits }
236
257
  };
237
258
  }
238
259
  var QuotaCodecError;
@@ -327,6 +348,13 @@ function quotaWindowParts(quota, options) {
327
348
  const parts = windows2.map(({ part }) => part);
328
349
  return age === void 0 ? { windows: parts } : { windows: parts, age };
329
350
  }
351
+ function withShortNames(windows2) {
352
+ const abbreviations = scopeAbbreviations(windows2.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE).map(({ scope }) => scope));
353
+ for (const window of windows2) {
354
+ window.part.short = window.part.kind === "budget" ? "cr" : window.scope === ALL_SCOPE ? window.part.name : abbreviations.get(window.scope) ?? window.scope;
355
+ }
356
+ return windows2;
357
+ }
330
358
  function scopedWindowParts(quota, options) {
331
359
  if (!quota)
332
360
  return { windows: [] };
@@ -340,6 +368,7 @@ function scopedWindowParts(quota, options) {
340
368
  part: {
341
369
  kind: "window",
342
370
  name: quotaWindowName(limit),
371
+ short: "",
343
372
  figure: percentLeft(limit.remainingPercent ?? 0),
344
373
  remainingPercent,
345
374
  checkedAt: limit.checkedAt,
@@ -357,6 +386,7 @@ function scopedWindowParts(quota, options) {
357
386
  part: {
358
387
  kind: "budget",
359
388
  name: "credits",
389
+ short: "",
360
390
  figure,
361
391
  ...remainingPercent === void 0 ? {} : { remainingPercent: clampPercent(remainingPercent) },
362
392
  checkedAt: budget.checkedAt,
@@ -364,6 +394,7 @@ function scopedWindowParts(quota, options) {
364
394
  }
365
395
  });
366
396
  }
397
+ withShortNames(windows2);
367
398
  if (windows2.length > 0) {
368
399
  const age = now - Math.min(...windows2.map(({ part }) => part.checkedAt));
369
400
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
@@ -443,15 +474,14 @@ function narrowTextParts(quota, options) {
443
474
  return grouped;
444
475
  const general = windows2.filter(({ part, scope }) => part.kind === "window" && scope === ALL_SCOPE);
445
476
  const scoped = windows2.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE);
446
- const abbreviations = scopeAbbreviations(scoped.map(({ scope }) => scope));
447
477
  const budget = windows2.find(({ part }) => part.kind === "budget");
448
478
  const budgetLeft = budget?.spent ? 0 : budget?.part.remainingPercent;
449
479
  const extras = [
450
- ...scoped.map(({ scope, part }) => ({
451
- label: abbreviations.get(scope) ?? scope,
480
+ ...scoped.map(({ part }) => ({
481
+ label: part.short,
452
482
  remaining: part.remainingPercent ?? 0
453
483
  })),
454
- ...budgetLeft === void 0 ? [] : [{ label: "cr", remaining: budgetLeft }]
484
+ ...budgetLeft === void 0 || budget === void 0 ? [] : [{ label: budget.part.short, remaining: budgetLeft }]
455
485
  ];
456
486
  const tightest = extras.reduce((best, item) => best === void 0 || item.remaining < best.remaining ? item : best, void 0);
457
487
  const pieces = general.map(({ part }) => `${part.name} ${wholePercent(part.remainingPercent ?? 0)}%`);
@@ -479,6 +509,16 @@ function formatQuota(quota, options) {
479
509
  return parts.join(" \xB7 ");
480
510
  return quota && quota.limits.length > 0 ? NO_LIMITS_REPORTED : NO_QUOTA_READING;
481
511
  }
512
+ function quotaCreditsText(credits) {
513
+ if (credits === void 0)
514
+ return void 0;
515
+ if (credits.unlimited)
516
+ return "Unlimited";
517
+ if (!credits.hasCredits)
518
+ return void 0;
519
+ const { balance } = credits;
520
+ return typeof balance === "number" && Number.isFinite(balance) && balance > 0 ? `${Math.round(balance)} credits` : "Available";
521
+ }
482
522
  var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED, NARROW_GROUP_LIMIT;
483
523
  var init_format = __esm({
484
524
  "../core/dist/common-auth-embedded/quota/format.js"() {
@@ -560,12 +600,14 @@ function projectQuota(map, scope = ALL_SCOPE) {
560
600
  const checkedAt = stamped.length > 0 ? Math.min(...stamped.map((limit) => limit.checkedAt)) : void 0;
561
601
  const budget = map?.budget?.kind === "reading" ? projectBudget(map.budget) : void 0;
562
602
  const counters = readQuotaCounters(map?.counters);
603
+ const credits = isQuotaCredits(map?.credits) ? map.credits : void 0;
563
604
  return {
564
605
  scope,
565
606
  limits,
566
607
  ...checkedAt === void 0 ? {} : { checkedAt },
567
608
  ...budget === void 0 ? {} : { budget },
568
- ...counters === void 0 ? {} : { counters }
609
+ ...counters === void 0 ? {} : { counters },
610
+ ...credits === void 0 ? {} : { credits }
569
611
  };
570
612
  }
571
613
  function budgetExhaustedResetAt(quota, now) {
@@ -608,12 +650,14 @@ __export(quota_exports, {
608
650
  emptyQuotaMap: () => emptyQuotaMap,
609
651
  formatQuota: () => formatQuota,
610
652
  futureResetAt: () => futureResetAt,
653
+ isQuotaCredits: () => isQuotaCredits,
611
654
  isQuotaMap: () => isQuotaMap,
612
655
  isQuotaObservation: () => isQuotaObservation,
613
656
  isQuotaStale: () => isQuotaStale,
614
657
  mergeQuotaObservation: () => mergeQuotaObservation,
615
658
  projectQuota: () => projectQuota,
616
659
  quotaCodec: () => quotaCodec2,
660
+ quotaCreditsText: () => quotaCreditsText,
617
661
  quotaTextParts: () => quotaTextParts,
618
662
  quotaWindowName: () => quotaWindowName,
619
663
  quotaWindowParts: () => quotaWindowParts,
@@ -720,7 +764,8 @@ var init_identity = __esm({
720
764
  // ../core/dist/common-auth-embedded/fs/private-files.js
721
765
  import { randomUUID as randomUUID7 } from "node:crypto";
722
766
  import { lstat as lstat2, readFile as readFile4, rename as rename3, unlink as unlink5 } from "node:fs/promises";
723
- import { dirname as dirname5, resolve as resolve2 } from "node:path";
767
+ import { tmpdir } from "node:os";
768
+ import { dirname as dirname5, join as join4, resolve as resolve2 } from "node:path";
724
769
  function ioCode(detail) {
725
770
  if (detail?.reason === "io-error") {
726
771
  if (detail.win32Code === 2 || detail.win32Code === 3)
@@ -730,8 +775,31 @@ function ioCode(detail) {
730
775
  }
731
776
  return detail?.code ?? "ERR_PRIVATE_FILE";
732
777
  }
778
+ function privateFilesUnavailable(cause) {
779
+ return Object.assign(new Error("Windows private-files native addon is unavailable", { cause }), {
780
+ code: "ERR_PRIVATE_FILES_UNAVAILABLE",
781
+ reason: PRIVATE_FILES_UNAVAILABLE_REASON
782
+ });
783
+ }
784
+ function isUnavailable(api, error) {
785
+ return error instanceof api.PrivateFilesUnavailableError || error?.code === "ERR_PRIVATE_FILES_UNAVAILABLE";
786
+ }
787
+ async function assertNativeAddonLoads(api) {
788
+ try {
789
+ await api.verifyPrivatePath(join4(tmpdir(), `.common-auth-private-files-probe-${randomUUID7()}`), "file");
790
+ } catch (error) {
791
+ if (isUnavailable(api, error))
792
+ throw privateFilesUnavailable(error);
793
+ }
794
+ }
733
795
  function loadBackend() {
734
- backend ??= import("@cortexkit/private-files");
796
+ backend ??= import("@cortexkit/private-files").then(async (api) => {
797
+ if (windowsPrivateFiles)
798
+ await assertNativeAddonLoads(api);
799
+ return api;
800
+ }, (cause) => {
801
+ throw windowsPrivateFiles ? privateFilesUnavailable(cause) : cause;
802
+ });
735
803
  return backend;
736
804
  }
737
805
  async function privateOperation(path5, stage, operation) {
@@ -957,12 +1025,13 @@ async function writePrivateAtomic(path5, bytes, options = {}) {
957
1025
  });
958
1026
  }
959
1027
  }
960
- var windowsPrivateFiles, migrationNotices, backend, PrivateFileError, safeParentOptionsForTest;
1028
+ var windowsPrivateFiles, migrationNotices, backend, PRIVATE_FILES_UNAVAILABLE_REASON, PrivateFileError, safeParentOptionsForTest;
961
1029
  var init_private_files = __esm({
962
1030
  "../core/dist/common-auth-embedded/fs/private-files.js"() {
963
1031
  "use strict";
964
1032
  windowsPrivateFiles = process.platform === "win32";
965
1033
  migrationNotices = /* @__PURE__ */ new Set();
1034
+ PRIVATE_FILES_UNAVAILABLE_REASON = "native-addon-unavailable";
966
1035
  PrivateFileError = class extends Error {
967
1036
  path;
968
1037
  stage;
@@ -977,7 +1046,7 @@ var init_private_files = __esm({
977
1046
  orphanPath;
978
1047
  constructor(path5, stage, cause) {
979
1048
  const detail = cause;
980
- super(`Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`, { cause });
1049
+ super(detail?.code === "ERR_PRIVATE_FILES_UNAVAILABLE" ? `Private file refused at ${stage}: ${path5} (${PRIVATE_FILES_UNAVAILABLE_REASON}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.` : `Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
981
1050
  this.path = path5;
982
1051
  this.stage = stage;
983
1052
  this.name = "PrivateFileError";
@@ -1088,7 +1157,7 @@ var init_atomic_write = __esm({
1088
1157
  // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
1089
1158
  import { randomUUID as randomUUID9 } from "node:crypto";
1090
1159
  import { mkdir as mkdir7, open as open4, readFile as readFile5, rename as rename5, rm as rm4, stat as stat3 } from "node:fs/promises";
1091
- import { dirname as dirname7, join as join4 } from "node:path";
1160
+ import { dirname as dirname7, join as join5 } from "node:path";
1092
1161
  async function createExclusiveText(path5, text2) {
1093
1162
  const handle = await open4(path5, "wx", 384);
1094
1163
  try {
@@ -1106,7 +1175,7 @@ function acquireRefreshFileLock(options) {
1106
1175
  }
1107
1176
  async function acquireRefreshFileLockWithClock(options) {
1108
1177
  const lockPath = lockPathFor(options.path, options.name);
1109
- const legacyOwnerPath = join4(lockPath, "owner.json");
1178
+ const legacyOwnerPath = join5(lockPath, "owner.json");
1110
1179
  const ownerId = randomUUID9();
1111
1180
  const now = options.now ?? Date.now;
1112
1181
  let renewTimer = null;
@@ -1114,8 +1183,8 @@ async function acquireRefreshFileLockWithClock(options) {
1114
1183
  let releaseConfirmed = false;
1115
1184
  let loss;
1116
1185
  let resolveLoss;
1117
- const lostPromise = new Promise((resolve18) => {
1118
- resolveLoss = resolve18;
1186
+ const lostPromise = new Promise((resolve20) => {
1187
+ resolveLoss = resolve20;
1119
1188
  });
1120
1189
  function notifyTimerStep(event) {
1121
1190
  try {
@@ -1149,7 +1218,7 @@ async function acquireRefreshFileLockWithClock(options) {
1149
1218
  let terminalIOError;
1150
1219
  let renewalInFlight = null;
1151
1220
  const evictPath = `${lockPath}.evicting`;
1152
- const evictOwnerPath = join4(evictPath, "owner.json");
1221
+ const evictOwnerPath = join5(evictPath, "owner.json");
1153
1222
  const evictOwnerId = randomUUID9();
1154
1223
  const EVICT_TTL = 5e3;
1155
1224
  const MAX_STEAL_ATTEMPTS = 8;
@@ -1272,7 +1341,7 @@ async function acquireRefreshFileLockWithClock(options) {
1272
1341
  }
1273
1342
  }
1274
1343
  async function backoff() {
1275
- await new Promise((resolve18) => setTimeout(resolve18, Math.floor(Math.random() * 4)));
1344
+ await new Promise((resolve20) => setTimeout(resolve20, Math.floor(Math.random() * 4)));
1276
1345
  }
1277
1346
  async function readLockState(notifyReady = true) {
1278
1347
  if (notifyReady && options.onStep)
@@ -1722,6 +1791,7 @@ function lockPathFor(target, name) {
1722
1791
  async function withLock(target, options, fn) {
1723
1792
  const started = performance.now();
1724
1793
  for (; ; ) {
1794
+ options.signal?.throwIfAborted();
1725
1795
  const lock = await acquireRefreshFileLock({
1726
1796
  path: target,
1727
1797
  name: options.name,
@@ -1732,6 +1802,7 @@ async function withLock(target, options, fn) {
1732
1802
  });
1733
1803
  if (lock) {
1734
1804
  try {
1805
+ options.signal?.throwIfAborted();
1735
1806
  return await fn(lock);
1736
1807
  } finally {
1737
1808
  await lock.release();
@@ -1745,7 +1816,7 @@ async function withLock(target, options, fn) {
1745
1816
  timeoutMs: options.timeoutMs
1746
1817
  });
1747
1818
  }
1748
- await new Promise((resolve18) => setTimeout(resolve18, Math.min(25, Math.ceil(remaining))));
1819
+ await new Promise((resolve20) => setTimeout(resolve20, Math.min(25, Math.ceil(remaining))));
1749
1820
  }
1750
1821
  }
1751
1822
  var LockContentionError, LockOwnershipError;
@@ -1781,13 +1852,13 @@ function assertNotInsideHook(operation) {
1781
1852
  function runInsideHook(operation, fn) {
1782
1853
  return insideHook.run(operation, async () => await fn());
1783
1854
  }
1784
- async function callFailureHook(operation, hook, rowId2, error, logger2) {
1855
+ async function callFailureHook(operation, hook, rowId2, error, logger3) {
1785
1856
  if (!hook)
1786
1857
  return;
1787
1858
  try {
1788
1859
  await runInsideHook(operation, () => hook(rowId2, error));
1789
1860
  } catch (hookError) {
1790
- logger2?.warn("store failure hook threw; the original failure stands", {
1861
+ logger3?.warn("store failure hook threw; the original failure stands", {
1791
1862
  operation,
1792
1863
  rowId: rowId2,
1793
1864
  error: hookError instanceof Error ? hookError.message : String(hookError)
@@ -1864,7 +1935,7 @@ async function acquirePoolLock(spec, defaults, env3) {
1864
1935
  });
1865
1936
  }
1866
1937
  const jitter = Math.floor(Math.random() * (options.retryMs + 1));
1867
- await new Promise((resolve18) => setTimeout(resolve18, Math.min(options.retryMs + jitter, remaining)));
1938
+ await new Promise((resolve20) => setTimeout(resolve20, Math.min(options.retryMs + jitter, remaining)));
1868
1939
  }
1869
1940
  }
1870
1941
  function definedOnly(spec) {
@@ -2942,11 +3013,11 @@ var init_mutate = __esm({
2942
3013
  if (isRecord4(this.state.accounts) && Object.hasOwn(this.state.accounts, id))
2943
3014
  delete this.state.accounts[id];
2944
3015
  }
2945
- setStateAccount(id, fields) {
3016
+ setStateAccount(id, fields2) {
2946
3017
  if (!isRecord4(this.state.accounts))
2947
3018
  this.state.accounts = {};
2948
3019
  Object.defineProperty(this.state.accounts, id, {
2949
- value: fields,
3020
+ value: fields2,
2950
3021
  enumerable: true,
2951
3022
  writable: true,
2952
3023
  configurable: true
@@ -4495,12 +4566,12 @@ var init_pull = __esm({
4495
4566
  firedAtLoad;
4496
4567
  logger;
4497
4568
  inflight = /* @__PURE__ */ new Set();
4498
- constructor(rt, hook, onFailure, firedAtLoad, logger2) {
4569
+ constructor(rt, hook, onFailure, firedAtLoad, logger3) {
4499
4570
  this.rt = rt;
4500
4571
  this.hook = hook;
4501
4572
  this.onFailure = onFailure;
4502
4573
  this.firedAtLoad = firedAtLoad;
4503
- this.logger = logger2;
4574
+ this.logger = logger3;
4504
4575
  }
4505
4576
  fire(id, reason) {
4506
4577
  if (!this.hook)
@@ -5582,15 +5653,15 @@ function createRedactor(options = {}) {
5582
5653
  return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
5583
5654
  }
5584
5655
  function errorEntries(error) {
5585
- const fields = error;
5656
+ const fields2 = error;
5586
5657
  const entries = [
5587
5658
  ["name", error.name],
5588
5659
  ["message", error.message],
5589
5660
  ["stack", error.stack]
5590
5661
  ];
5591
5662
  for (const key of ["code", "status", "cause"])
5592
- if (fields[key] !== void 0)
5593
- entries.push([key, fields[key]]);
5663
+ if (fields2[key] !== void 0)
5664
+ entries.push([key, fields2[key]]);
5594
5665
  const listed = new Set(entries.map(([key]) => key));
5595
5666
  for (const entry of Object.entries(error))
5596
5667
  if (!listed.has(entry[0]))
@@ -5832,7 +5903,7 @@ function createEngine(options) {
5832
5903
  } catch {
5833
5904
  }
5834
5905
  }
5835
- function schedule() {
5906
+ function schedule2() {
5836
5907
  if (!timer)
5837
5908
  timer = setTimeout(() => {
5838
5909
  timer = void 0;
@@ -5874,7 +5945,7 @@ function createEngine(options) {
5874
5945
  void flushed.catch(() => {
5875
5946
  });
5876
5947
  } else
5877
- schedule();
5948
+ schedule2();
5878
5949
  } catch {
5879
5950
  }
5880
5951
  }
@@ -6745,9 +6816,9 @@ function findAction(sections, request) {
6745
6816
  return actions?.find((action) => action.id === request.actionId);
6746
6817
  }
6747
6818
  function createCommandMenu(options) {
6748
- const logger2 = options.logger ?? createLogger2("commands");
6819
+ const logger3 = options.logger ?? createLogger2("commands");
6749
6820
  const redact3 = createTextRedactor(options.redaction);
6750
- const seam = { logger: logger2, redact: redact3 };
6821
+ const seam = { logger: logger3, redact: redact3 };
6751
6822
  const now = options.now ?? Date.now;
6752
6823
  const extras = options.extras ?? [];
6753
6824
  const replaced = options.replace ?? {};
@@ -6774,7 +6845,7 @@ function createCommandMenu(options) {
6774
6845
  content: await section.build(invocation)
6775
6846
  };
6776
6847
  } catch (error) {
6777
- logger2.warn("command menu section failed to build", {
6848
+ logger3.warn("command menu section failed to build", {
6778
6849
  command: options.command,
6779
6850
  section: id,
6780
6851
  error: redact3(error instanceof Error ? error.message : String(error))
@@ -6861,7 +6932,7 @@ function createCommandMenu(options) {
6861
6932
  };
6862
6933
  } catch (error) {
6863
6934
  const failure2 = projectFailure(error);
6864
- logger2.warn("command menu action failed", {
6935
+ logger3.warn("command menu action failed", {
6865
6936
  command: options.command,
6866
6937
  section: request.sectionId,
6867
6938
  action: request.actionId,
@@ -7473,7 +7544,7 @@ async function select(terminal, items, options) {
7473
7544
  writeLine("");
7474
7545
  renderedLines = lines;
7475
7546
  };
7476
- return new Promise((resolve18) => {
7547
+ return new Promise((resolve20) => {
7477
7548
  const wasRaw = stdin.isRaw ?? false;
7478
7549
  const cleanup2 = () => {
7479
7550
  if (cleaned)
@@ -7493,7 +7564,7 @@ async function select(terminal, items, options) {
7493
7564
  };
7494
7565
  const finish = (value) => {
7495
7566
  cleanup2();
7496
- resolve18(value);
7567
+ resolve20(value);
7497
7568
  };
7498
7569
  const onSignal = () => finish(null);
7499
7570
  const onKey = (data) => {
@@ -7533,7 +7604,7 @@ async function select(terminal, items, options) {
7533
7604
  stdin.setRawMode(true);
7534
7605
  } catch {
7535
7606
  cleanup2();
7536
- resolve18(null);
7607
+ resolve20(null);
7537
7608
  return;
7538
7609
  }
7539
7610
  stdin.resume();
@@ -8816,7 +8887,7 @@ var init_any_signal = __esm({
8816
8887
  import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID12 } from "node:crypto";
8817
8888
  import { constants as fsConstants } from "node:fs";
8818
8889
  import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename6, stat as stat4, unlink as unlink6 } from "node:fs/promises";
8819
- import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join5, resolve as resolve5 } from "node:path";
8890
+ import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve5 } from "node:path";
8820
8891
  import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8821
8892
  function classifyEnrollmentError(error) {
8822
8893
  if (!(error instanceof ClaustrumCredentialError2))
@@ -8842,7 +8913,7 @@ function getClaustrumEnrollmentPaths(tokenPath) {
8842
8913
  const extension = extname(tokenPath) || ".json";
8843
8914
  const stem = basename3(tokenPath, extname(tokenPath));
8844
8915
  return {
8845
- statePath: join5(dirname9(tokenPath), `${stem}-state${extension}`),
8916
+ statePath: join6(dirname9(tokenPath), `${stem}-state${extension}`),
8846
8917
  tokenPath
8847
8918
  };
8848
8919
  }
@@ -8850,7 +8921,7 @@ function hostEnrollmentPaths(input2) {
8850
8921
  const override = input2.override?.trim();
8851
8922
  if (override && !isAbsolute2(override) && !input2.cwd)
8852
8923
  throw new ClaustrumConsumerError("invalid-state", "A relative Claustrum enrollment override needs a base directory");
8853
- const tokenPath = override ? isAbsolute2(override) ? override : resolve5(input2.cwd, override) : join5(input2.stateDir, `${input2.host}-enrollment.json`);
8924
+ const tokenPath = override ? isAbsolute2(override) ? override : resolve5(input2.cwd, override) : join6(input2.stateDir, `${input2.host}-enrollment.json`);
8854
8925
  return getClaustrumEnrollmentPaths(tokenPath);
8855
8926
  }
8856
8927
  function isRecord6(value) {
@@ -8979,13 +9050,13 @@ async function readBoundedJson(path5) {
8979
9050
  await descriptor.close();
8980
9051
  }
8981
9052
  }
8982
- function accountRecords(text2, fields) {
9053
+ function accountRecords(text2, fields2) {
8983
9054
  const records = [];
8984
9055
  for (const line of text2.split("\n")) {
8985
9056
  if (line.trim() === "" || line.startsWith("#"))
8986
9057
  continue;
8987
9058
  const parts = line.split(":");
8988
- if (parts.length !== fields || !/^[^\s:,]+$/.test(parts[0] ?? "") || !/^\d+$/.test(parts[2] ?? "") || !Number.isSafeInteger(Number(parts[2])) || fields === 7 && (!/^\d+$/.test(parts[3] ?? "") || !Number.isSafeInteger(Number(parts[3]))) || fields === 4 && parts[3] !== "" && !/^[^\s:,]+(?:,[^\s:,]+)*$/.test(parts[3] ?? ""))
9059
+ if (parts.length !== fields2 || !/^[^\s:,]+$/.test(parts[0] ?? "") || !/^\d+$/.test(parts[2] ?? "") || !Number.isSafeInteger(Number(parts[2])) || fields2 === 7 && (!/^\d+$/.test(parts[3] ?? "") || !Number.isSafeInteger(Number(parts[3]))) || fields2 === 4 && parts[3] !== "" && !/^[^\s:,]+(?:,[^\s:,]+)*$/.test(parts[3] ?? ""))
8989
9060
  return void 0;
8990
9061
  records.push(parts);
8991
9062
  }
@@ -9083,7 +9154,7 @@ async function writeStateAtomic(path5, state, ancestorOptions = {}) {
9083
9154
  }
9084
9155
  if (windowsPrivateFiles)
9085
9156
  return writePrivateAtomic(path5, bytes);
9086
- const temporary = join5(parent, `.${basename3(path5)}.${process.pid}.${randomUUID12()}.tmp`);
9157
+ const temporary = join6(parent, `.${basename3(path5)}.${process.pid}.${randomUUID12()}.tmp`);
9087
9158
  let descriptor;
9088
9159
  let created = false;
9089
9160
  try {
@@ -9260,7 +9331,7 @@ async function disconnectClaustrumEnrollment(paths, proposedName) {
9260
9331
  await lock.release();
9261
9332
  }
9262
9333
  }
9263
- var ENROLLMENT_SCHEMA, ENROLLMENT_FILE_MAX_BYTES, ENROLLMENT_LOCK_TTL_MS, TOKEN_RE, TERMINAL_ENROLLMENT_CODES, RETRYABLE_ENROLLMENT_CODES, ClaustrumEnrollmentManager;
9334
+ var ENROLLMENT_SCHEMA, ENROLLMENT_FILE_MAX_BYTES, ENROLLMENT_LOCK_TTL_MS, TOKEN_RE, UNSUPPORTED_ENROLLMENT_CODE, TERMINAL_ENROLLMENT_CODES, RETRYABLE_ENROLLMENT_CODES, ClaustrumEnrollmentManager;
9264
9335
  var init_enrollment = __esm({
9265
9336
  "../core/dist/common-auth-embedded/claustrum/enrollment.js"() {
9266
9337
  "use strict";
@@ -9271,7 +9342,13 @@ var init_enrollment = __esm({
9271
9342
  ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
9272
9343
  ENROLLMENT_LOCK_TTL_MS = 3e4;
9273
9344
  TOKEN_RE = /^[0-9a-f]{64}$/;
9345
+ UNSUPPORTED_ENROLLMENT_CODE = "unknown_method";
9274
9346
  TERMINAL_ENROLLMENT_CODES = /* @__PURE__ */ new Set([
9347
+ // The daemon's answer to an operation it does not implement: a vault built
9348
+ // before the enrollment ceremony. It arrives as a transport Error frame with
9349
+ // no class, which claustrum-client before 0.13.0 labels transient/retry, but
9350
+ // asking again can never succeed.
9351
+ UNSUPPORTED_ENROLLMENT_CODE,
9275
9352
  "invalid_params",
9276
9353
  "pending_exists",
9277
9354
  "not_found",
@@ -9405,6 +9482,18 @@ var init_enrollment = __esm({
9405
9482
  retryCode: refusal3.code
9406
9483
  };
9407
9484
  }
9485
+ if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE) {
9486
+ await lock.assertOwned();
9487
+ await unlink6(this.#paths.statePath).catch((cause) => {
9488
+ if (cause.code !== "ENOENT")
9489
+ throw cause;
9490
+ });
9491
+ return {
9492
+ state: "unavailable",
9493
+ proposedName: state.proposedName,
9494
+ code: refusal3.code
9495
+ };
9496
+ }
9408
9497
  return this.#block(state, refusal3.code);
9409
9498
  }
9410
9499
  }
@@ -9535,9 +9624,9 @@ function scopedRetryReason(served, current) {
9535
9624
  return "version-unchanged";
9536
9625
  return "rotated";
9537
9626
  }
9538
- function decideScopedRetryAfter401(site, served, current, logger2 = defaultLogger) {
9627
+ function decideScopedRetryAfter401(site, served, current, logger3 = defaultLogger) {
9539
9628
  const retry = isScopedCredentialRotation(served, current);
9540
- logger2.debug("scoped 401 re-authorized", {
9629
+ logger3.debug("scoped 401 re-authorized", {
9541
9630
  site,
9542
9631
  credentialId: served.credentialId,
9543
9632
  servedVersion: served.recordVersion,
@@ -10110,6 +10199,7 @@ var init_interlock = __esm({
10110
10199
 
10111
10200
  // ../core/dist/common-auth-embedded/claustrum/roster.js
10112
10201
  import { createHash as createHash7 } from "node:crypto";
10202
+ import { resolve as resolve6 } from "node:path";
10113
10203
  function hash(value) {
10114
10204
  return createHash7("sha256").update(value).digest("hex");
10115
10205
  }
@@ -10330,7 +10420,7 @@ async function readVaultRoster(path5) {
10330
10420
  return decodeRoster(value);
10331
10421
  }
10332
10422
  async function mutateVaultRoster(path5, change, options = {}) {
10333
- return withLock(path5, WRITE_LOCK, async (lock) => {
10423
+ return withLock(path5, { ...WRITE_LOCK, signal: options.signal }, async (lock) => {
10334
10424
  const current = await readVaultRoster(path5);
10335
10425
  const { next, result } = await change(current, {
10336
10426
  assertOwned: () => lock.assertOwned()
@@ -10340,6 +10430,7 @@ async function mutateVaultRoster(path5, change, options = {}) {
10340
10430
  await writeJsonAtomic2(path5, next, {
10341
10431
  beforeRename: async () => {
10342
10432
  await options.beforePublish?.();
10433
+ options.signal?.throwIfAborted();
10343
10434
  await lock.assertOwned();
10344
10435
  }
10345
10436
  });
@@ -10389,43 +10480,51 @@ function receiptFence(row, receipt2) {
10389
10480
  return "bind";
10390
10481
  return "refuse";
10391
10482
  }
10392
- function recordVaultQuota(path5, input2) {
10393
- return mutateVaultRoster(path5, (current) => {
10394
- const row = current?.rows.find((entry) => entry.routeId === input2.routeId);
10395
- const fence = !current || !row ? "refuse" : receiptFence(row, input2);
10396
- if (!current || !row || fence === "refuse")
10397
- return { result: false };
10398
- const quota = mergeQuotaObservation(row.quota, input2.observation);
10399
- const bound = fence === "bind" ? { accountIdentity: input2.accountIdentity, unclaimed: true } : {};
10400
- return {
10401
- next: {
10402
- ...current,
10403
- rows: current.rows.map((entry) => entry === row ? { ...entry, ...bound, quota } : entry)
10404
- },
10405
- result: true
10406
- };
10483
+ async function recordVaultQuota(path5, input2) {
10484
+ const { routeId, observation, ...receipt2 } = input2;
10485
+ return enqueueFencedVaultQuota(path5, {
10486
+ routeId,
10487
+ observation,
10488
+ accountIdentity: receipt2.accountIdentity,
10489
+ receipt: receipt2
10407
10490
  });
10408
10491
  }
10492
+ async function enqueueFencedVaultQuota(path5, publication2) {
10493
+ if (!isQuotaObservation(publication2.observation))
10494
+ return false;
10495
+ const current = pendingVaultQuota(path5, await readVaultRoster(path5));
10496
+ if (!applyVaultQuota(current, publication2).kept)
10497
+ return false;
10498
+ return enqueueVaultQuota(path5, publication2);
10499
+ }
10409
10500
  function recordVaultAccountQuota(path5, input2) {
10410
- return mutateVaultRoster(path5, (current) => {
10411
- const row = current?.rows.find((entry) => entry.routeId === input2.routeId);
10412
- if (!current || !row || row.accountIdentity === void 0 || row.accountIdentity !== input2.accountIdentity)
10413
- return { result: false };
10414
- const quota = mergeQuotaObservation(row.quota, input2.observation);
10415
- return {
10416
- next: {
10417
- ...current,
10418
- rows: current.rows.map((entry) => entry === row ? { ...entry, quota } : entry)
10419
- },
10420
- result: true
10421
- };
10422
- });
10501
+ return enqueueFencedVaultQuota(path5, input2);
10502
+ }
10503
+ function applyVaultQuota(current, input2) {
10504
+ const row = current?.rows.find((entry) => entry.routeId === input2.routeId);
10505
+ const fence = !row ? "refuse" : input2.receipt ? receiptFence(row, input2.receipt) : row.accountIdentity !== void 0 && row.accountIdentity === input2.accountIdentity ? "hold" : "refuse";
10506
+ if (!current || !row || fence === "refuse")
10507
+ return { roster: current, kept: false };
10508
+ const quota = mergeQuotaObservation(row.quota, input2.observation);
10509
+ const bound = fence === "bind" ? { accountIdentity: input2.accountIdentity, unclaimed: true } : {};
10510
+ return {
10511
+ roster: {
10512
+ ...current,
10513
+ rows: current.rows.map((entry) => entry === row ? { ...entry, ...bound, quota } : entry)
10514
+ },
10515
+ kept: true
10516
+ };
10517
+ }
10518
+ function forgetPendingVaultDiscovery(path5) {
10519
+ pendingDiscoveries.delete(resolve6(path5));
10423
10520
  }
10424
10521
  async function refreshVaultRoster(options) {
10425
10522
  options.signal?.throwIfAborted();
10426
10523
  const active2 = async () => await options.isActive?.() ?? true;
10427
- if (!await active2())
10524
+ if (!await active2()) {
10525
+ forgetPendingVaultDiscovery(options.path);
10428
10526
  return void 0;
10527
+ }
10429
10528
  const lease = await acquireRefreshFileLock({
10430
10529
  ...DISCOVERY_LEASE,
10431
10530
  path: options.path,
@@ -10438,8 +10537,18 @@ async function refreshVaultRoster(options) {
10438
10537
  throw new ClaustrumConsumerError("roster-busy", "Claustrum account discovery is already in progress");
10439
10538
  return persisted;
10440
10539
  }
10540
+ const key = resolve6(options.path);
10541
+ let discovered;
10441
10542
  try {
10442
- const inventory = await options.custody.discover(options.signal);
10543
+ const previous = await readVaultRoster(options.path);
10544
+ const pending = pendingDiscoveries.get(key);
10545
+ discovered = pending && (pending.previousView === previous?.view || pending.inventory.view === previous?.view) ? pending : {
10546
+ inventory: await options.custody.discover(options.signal),
10547
+ previousView: previous?.view
10548
+ };
10549
+ pendingDiscoveries.delete(key);
10550
+ const { inventory } = discovered;
10551
+ options.onInventory?.(inventory);
10443
10552
  options.signal?.throwIfAborted();
10444
10553
  return await mutateVaultRoster(options.path, async (current) => {
10445
10554
  if (!await active2())
@@ -10450,7 +10559,16 @@ async function refreshVaultRoster(options) {
10450
10559
  const next = projectVaultRoster(current, inventory, projection);
10451
10560
  const changed = JSON.stringify(current) !== JSON.stringify(next);
10452
10561
  return { ...changed && { next }, result: next };
10562
+ }, {
10563
+ beforePublish: async () => {
10564
+ options.signal?.throwIfAborted();
10565
+ await lease.assertOwned();
10566
+ }
10453
10567
  });
10568
+ } catch (error) {
10569
+ if (error instanceof LockContentionError && discovered && !options.signal?.aborted && await active2())
10570
+ pendingDiscoveries.set(key, discovered);
10571
+ throw error;
10454
10572
  } finally {
10455
10573
  await lease.release();
10456
10574
  }
@@ -10487,7 +10605,7 @@ function resolveVaultPrimary(input2) {
10487
10605
  ...previous && previous.accountIdentity !== identity && { replaced: previous }
10488
10606
  };
10489
10607
  }
10490
- var DEFAULT_ROUTE_PREFIX, SKIPPED_REASONS, WRITE_LOCK, DISCOVERY_LEASE;
10608
+ var DEFAULT_ROUTE_PREFIX, SKIPPED_REASONS, WRITE_LOCK, DISCOVERY_LEASE, pendingDiscoveries;
10491
10609
  var init_roster = __esm({
10492
10610
  "../core/dist/common-auth-embedded/claustrum/roster.js"() {
10493
10611
  "use strict";
@@ -10496,6 +10614,8 @@ var init_roster = __esm({
10496
10614
  init_quota();
10497
10615
  init_errors2();
10498
10616
  init_interlock();
10617
+ init_quota_writer();
10618
+ init_quota_writer();
10499
10619
  DEFAULT_ROUTE_PREFIX = "vault:";
10500
10620
  SKIPPED_REASONS = /* @__PURE__ */ new Set([
10501
10621
  "empty credential id",
@@ -10506,9 +10626,238 @@ var init_roster = __esm({
10506
10626
  WRITE_LOCK = {
10507
10627
  name: "claustrum-roster-write",
10508
10628
  ttlMs: 1e4,
10509
- timeoutMs: 5e3
10629
+ timeoutMs: 5e3,
10630
+ renew: true
10510
10631
  };
10511
10632
  DISCOVERY_LEASE = { name: "claustrum-roster", ttlMs: 3e4 };
10633
+ pendingDiscoveries = /* @__PURE__ */ new Map();
10634
+ }
10635
+ });
10636
+
10637
+ // ../core/dist/common-auth-embedded/claustrum/quota-writer.js
10638
+ import { resolve as resolve7 } from "node:path";
10639
+ function writerFor(path5) {
10640
+ const key = resolve7(path5);
10641
+ let writer = writers.get(key);
10642
+ if (!writer) {
10643
+ writer = {
10644
+ path: key,
10645
+ pending: /* @__PURE__ */ new Map(),
10646
+ listeners: /* @__PURE__ */ new Set(),
10647
+ wake: /* @__PURE__ */ new Set(),
10648
+ abort: new AbortController(),
10649
+ failures: 0,
10650
+ draining: false,
10651
+ order: 0
10652
+ };
10653
+ writers.set(key, writer);
10654
+ }
10655
+ return writer;
10656
+ }
10657
+ function retainVaultQuotaWriter(path5, listener) {
10658
+ const writer = writerFor(path5);
10659
+ writer.listeners.add(listener);
10660
+ let released;
10661
+ return () => released ??= (() => {
10662
+ writer.listeners.delete(listener);
10663
+ return writer.listeners.size ? Promise.resolve() : drainVaultQuota(path5);
10664
+ })();
10665
+ }
10666
+ function fields(publication2) {
10667
+ const result = /* @__PURE__ */ new Map();
10668
+ const { observation } = publication2;
10669
+ const witness = JSON.stringify([
10670
+ publication2.routeId,
10671
+ publication2.receipt?.credentialId,
10672
+ publication2.receipt?.accountIdentitySource,
10673
+ publication2.receipt?.expectedAccountIdentity
10674
+ ]);
10675
+ const add = (key, at, part) => result.set(`${witness}:${key}`, {
10676
+ at,
10677
+ order: 0,
10678
+ publication: { ...publication2, observation: part }
10679
+ });
10680
+ const keyFor = (scope, label) => JSON.stringify([scope ?? "all", label]);
10681
+ const read = /* @__PURE__ */ new Set();
10682
+ for (const reading of observation.readings ?? []) {
10683
+ const key = keyFor(reading.scope, reading.label);
10684
+ read.add(key);
10685
+ add(key, observation.checkedAt, {
10686
+ checkedAt: observation.checkedAt,
10687
+ readings: [{ ...reading }]
10688
+ });
10689
+ }
10690
+ for (const pair of observation.coverage ?? []) {
10691
+ const key = keyFor(pair.scope, pair.label);
10692
+ if (!read.has(key))
10693
+ add(key, observation.checkedAt, {
10694
+ checkedAt: observation.checkedAt,
10695
+ coverage: [{ ...pair }]
10696
+ });
10697
+ }
10698
+ if (observation.budget)
10699
+ add("budget", observation.checkedAt, {
10700
+ checkedAt: observation.checkedAt,
10701
+ budget: { ...observation.budget }
10702
+ });
10703
+ for (const [name, counter] of Object.entries(observation.counters ?? {})) {
10704
+ add(`counter:${name}`, counter.checkedAt, {
10705
+ checkedAt: observation.checkedAt,
10706
+ counters: { [name]: { ...counter } }
10707
+ });
10708
+ }
10709
+ if (observation.credits)
10710
+ add("credits", observation.credits.checkedAt, {
10711
+ checkedAt: observation.checkedAt,
10712
+ credits: { ...observation.credits }
10713
+ });
10714
+ if (!result.size)
10715
+ add("empty", observation.checkedAt, { checkedAt: observation.checkedAt });
10716
+ return result;
10717
+ }
10718
+ function enqueueVaultQuota(path5, publication2) {
10719
+ if (!isQuotaObservation(publication2.observation))
10720
+ return Promise.resolve(false);
10721
+ const writer = writerFor(path5);
10722
+ const account = JSON.stringify([
10723
+ publication2.accountIdentity ?? null,
10724
+ publication2.accountIdentity === void 0 ? publication2.routeId : null
10725
+ ]);
10726
+ const pending = writer.pending.get(account) ?? /* @__PURE__ */ new Map();
10727
+ for (const [key, field] of fields(publication2)) {
10728
+ const previous = pending.get(key);
10729
+ if (!previous || field.at >= previous.at) {
10730
+ field.order = ++writer.order;
10731
+ if (field.publication.observation.coverage)
10732
+ field.priorReading = previous?.publication.observation.readings ? previous.publication : previous?.priorReading;
10733
+ pending.set(key, field);
10734
+ }
10735
+ }
10736
+ if (pending.size)
10737
+ writer.pending.set(account, pending);
10738
+ for (const listener of writer.listeners)
10739
+ listener(publication2);
10740
+ schedule(writer, COALESCE_MS);
10741
+ return Promise.resolve(true);
10742
+ }
10743
+ function orderedFields(pending) {
10744
+ return [...pending.values()].flatMap((account) => [...account.values()]).sort((a, b) => a.order - b.order);
10745
+ }
10746
+ function pendingVaultQuota(path5, roster) {
10747
+ const writer = writers.get(resolve7(path5));
10748
+ if (writer) {
10749
+ for (const field of orderedFields(writer.pending)) {
10750
+ if (field.priorReading)
10751
+ roster = applyVaultQuota(roster, field.priorReading).roster;
10752
+ roster = applyVaultQuota(roster, field.publication).roster;
10753
+ }
10754
+ }
10755
+ return roster;
10756
+ }
10757
+ function schedule(writer, delay3) {
10758
+ if (writer.running || writer.timer || !writer.pending.size || writer.abort.signal.aborted)
10759
+ return;
10760
+ writer.timer = setTimeout(() => {
10761
+ writer.timer = void 0;
10762
+ flush(writer);
10763
+ }, delay3);
10764
+ if (!writer.draining)
10765
+ writer.timer.unref?.();
10766
+ }
10767
+ function flush(writer) {
10768
+ if (writer.running || writer.abort.signal.aborted)
10769
+ return;
10770
+ const batch = new Map([...writer.pending].map(([account, pending]) => [
10771
+ account,
10772
+ new Map(pending)
10773
+ ]));
10774
+ writer.running = (async () => {
10775
+ try {
10776
+ await mutateVaultRoster(writer.path, (current) => {
10777
+ let next = current;
10778
+ for (const field of orderedFields(batch)) {
10779
+ if (field.priorReading)
10780
+ next = applyVaultQuota(next, field.priorReading).roster;
10781
+ next = applyVaultQuota(next, field.publication).roster;
10782
+ }
10783
+ return { ...next !== current && { next }, result: void 0 };
10784
+ }, { signal: writer.abort.signal });
10785
+ for (const [account, fields2] of batch) {
10786
+ const pending = writer.pending.get(account);
10787
+ for (const [key, field] of fields2) {
10788
+ if (pending?.get(key) === field)
10789
+ pending.delete(key);
10790
+ }
10791
+ if (!pending?.size)
10792
+ writer.pending.delete(account);
10793
+ }
10794
+ writer.failures = 0;
10795
+ } catch (error) {
10796
+ if (!writer.abort.signal.aborted && writer.failures++ === 0) {
10797
+ logger.warn("vault quota publication delayed; retrying", {
10798
+ error: error instanceof Error ? error.message : String(error)
10799
+ });
10800
+ }
10801
+ } finally {
10802
+ writer.running = void 0;
10803
+ for (const wake of writer.wake)
10804
+ wake();
10805
+ const backoff = writer.failures ? Math.min(5e3, 100 * 2 ** Math.min(writer.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
10806
+ schedule(writer, backoff);
10807
+ }
10808
+ })();
10809
+ }
10810
+ async function drainVaultQuota(path5, timeoutMs = 1e3) {
10811
+ const key = resolve7(path5);
10812
+ const writer = writers.get(key);
10813
+ if (!writer)
10814
+ return;
10815
+ writer.draining = true;
10816
+ clearTimeout(writer.timer);
10817
+ writer.timer = void 0;
10818
+ let deadline;
10819
+ let wake;
10820
+ const drained = new Promise((done) => {
10821
+ wake = () => {
10822
+ if (!writer.pending.size || writer.abort.signal.aborted)
10823
+ done();
10824
+ };
10825
+ writer.wake.add(wake);
10826
+ wake();
10827
+ });
10828
+ try {
10829
+ if (writer.pending.size)
10830
+ flush(writer);
10831
+ await Promise.race([
10832
+ drained,
10833
+ new Promise((done) => {
10834
+ deadline = setTimeout(done, Math.max(0, timeoutMs));
10835
+ })
10836
+ ]);
10837
+ } finally {
10838
+ clearTimeout(deadline);
10839
+ if (wake)
10840
+ writer.wake.delete(wake);
10841
+ writer.draining = false;
10842
+ if (!writer.listeners.size) {
10843
+ writer.abort.abort();
10844
+ clearTimeout(writer.timer);
10845
+ writer.pending.clear();
10846
+ if (writers.get(key) === writer)
10847
+ writers.delete(key);
10848
+ }
10849
+ }
10850
+ }
10851
+ var writers, logger, COALESCE_MS;
10852
+ var init_quota_writer = __esm({
10853
+ "../core/dist/common-auth-embedded/claustrum/quota-writer.js"() {
10854
+ "use strict";
10855
+ init_logger();
10856
+ init_quota();
10857
+ init_roster();
10858
+ writers = /* @__PURE__ */ new Map();
10859
+ logger = createLogger2("claustrum");
10860
+ COALESCE_MS = 100;
10512
10861
  }
10513
10862
  });
10514
10863
 
@@ -10523,6 +10872,7 @@ var init_consumer = __esm({
10523
10872
  init_enrollment();
10524
10873
  init_errors2();
10525
10874
  init_insula();
10875
+ init_quota_writer();
10526
10876
  init_roster();
10527
10877
  init_watch();
10528
10878
  ClaustrumConsumer = class {
@@ -10546,9 +10896,13 @@ var init_consumer = __esm({
10546
10896
  #insulaSkips = /* @__PURE__ */ new Map();
10547
10897
  /** When this instance last completed a discovery, by `now`. */
10548
10898
  #discoveredAt;
10899
+ #releaseQuotaWriter;
10549
10900
  constructor(options) {
10550
10901
  this.#options = options;
10551
10902
  this.#logger = options.logger ?? createLogger2("claustrum");
10903
+ this.#releaseQuotaWriter = retainVaultQuotaWriter(options.rosterPath, (publication2) => {
10904
+ this.#roster = applyVaultQuota(this.#roster, publication2).roster;
10905
+ });
10552
10906
  }
10553
10907
  #assertOpen(signal) {
10554
10908
  this.#shutdown.signal.throwIfAborted();
@@ -10562,7 +10916,7 @@ var init_consumer = __esm({
10562
10916
  this.#shutdown.signal,
10563
10917
  ...signal ? [signal] : []
10564
10918
  ]);
10565
- return new Promise((resolve18, reject) => {
10919
+ return new Promise((resolve20, reject) => {
10566
10920
  const cleanup2 = () => {
10567
10921
  combined.signal.removeEventListener("abort", abort);
10568
10922
  combined.dispose();
@@ -10577,7 +10931,7 @@ var init_consumer = __esm({
10577
10931
  if (combined.signal.aborted)
10578
10932
  reject(combined.signal.reason);
10579
10933
  else
10580
- resolve18(value);
10934
+ resolve20(value);
10581
10935
  }, (error) => {
10582
10936
  cleanup2();
10583
10937
  reject(error);
@@ -10677,11 +11031,9 @@ var init_consumer = __esm({
10677
11031
  let discovered;
10678
11032
  const roster = await refreshVaultRoster({
10679
11033
  path: this.#options.rosterPath,
10680
- custody: {
10681
- discover: async (signal) => {
10682
- discovered = await custody.discover(signal);
10683
- return discovered;
10684
- }
11034
+ custody,
11035
+ onInventory: (inventory) => {
11036
+ discovered = inventory;
10685
11037
  },
10686
11038
  isActive: () => this.#active(),
10687
11039
  signal: this.#shutdown.signal,
@@ -10694,7 +11046,7 @@ var init_consumer = __esm({
10694
11046
  });
10695
11047
  this.#assertOpen();
10696
11048
  const changed = roster?.view !== this.#roster?.view;
10697
- this.#roster = roster;
11049
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, roster);
10698
11050
  custody.retain(roster?.rows ?? []);
10699
11051
  if (discovered && roster?.view !== void 0)
10700
11052
  this.#grantReach = discovered.grantReach ? { view: roster.view, reach: discovered.grantReach } : void 0;
@@ -10830,7 +11182,7 @@ var init_consumer = __esm({
10830
11182
  return void 0;
10831
11183
  try {
10832
11184
  await readClaustrumEnrollmentToken(this.#options.tokenPath);
10833
- const roster = await readVaultRoster(this.#options.rosterPath);
11185
+ const roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10834
11186
  const row = roster?.rows.find((entry) => entry.routeId === routeId);
10835
11187
  return this.#normalizeInsulaQuota(row?.accountIdentity);
10836
11188
  } catch {
@@ -10844,7 +11196,7 @@ var init_consumer = __esm({
10844
11196
  return { miss: "unreachable" };
10845
11197
  try {
10846
11198
  await readClaustrumEnrollmentToken(this.#options.tokenPath);
10847
- const roster = await readVaultRoster(this.#options.rosterPath);
11199
+ const roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10848
11200
  const account = roster?.rows.find((row) => row.routeId === routeId)?.accountIdentity;
10849
11201
  if (!account || !this.#insula)
10850
11202
  return { miss: "unreachable" };
@@ -10894,7 +11246,7 @@ var init_consumer = __esm({
10894
11246
  this.#insula = void 0;
10895
11247
  throw new ClaustrumConsumerError("not-active", "Claustrum scoped custody is not active");
10896
11248
  }
10897
- const current = await readVaultRoster(this.#options.rosterPath);
11249
+ const current = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10898
11250
  this.#assertOpen(signal);
10899
11251
  const observed = roster.rows.find((row) => row.routeId === routeId);
10900
11252
  const configured = current?.rows.find((row) => row.routeId === routeId);
@@ -10973,13 +11325,13 @@ var init_consumer = __esm({
10973
11325
  async decline(routeId) {
10974
11326
  this.#assertOpen();
10975
11327
  await declineVaultRoute(this.#options.rosterPath, routeId);
10976
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11328
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10977
11329
  this.#custody?.retain(this.#roster?.rows ?? []);
10978
11330
  }
10979
11331
  async accept(routeId) {
10980
11332
  this.#assertOpen();
10981
11333
  await acceptVaultRoute(this.#options.rosterPath, routeId);
10982
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11334
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10983
11335
  }
10984
11336
  /**
10985
11337
  * Store a quota or profile observation for a vault route. The receipt the
@@ -10989,7 +11341,7 @@ var init_consumer = __esm({
10989
11341
  */
10990
11342
  async recordQuota(routeId, observation, attempt) {
10991
11343
  this.#assertOpen();
10992
- const kept = await recordVaultQuota(this.#options.rosterPath, {
11344
+ return recordVaultQuota(this.#options.rosterPath, {
10993
11345
  routeId,
10994
11346
  observation,
10995
11347
  credentialId: attempt.credentialId,
@@ -11001,27 +11353,21 @@ var init_consumer = __esm({
11001
11353
  expectedAccountIdentity: attempt.expectedAccountIdentity
11002
11354
  }
11003
11355
  });
11004
- if (kept)
11005
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11006
- return kept;
11007
11356
  }
11008
11357
  /**
11009
11358
  * Store a background observation that belongs to an account rather than to
11010
11359
  * a served credential (an insula reading from `cachedInsulaQuotaForRoute`).
11011
11360
  * It lands only while the route is still bound to that known account, so no
11012
11361
  * credential fetch is needed and a replaced account's reading is dropped.
11013
- * The in-memory roster is reloaded from the file, without a vault call.
11362
+ * Memory updates immediately; durable publication is detached and coalesced.
11014
11363
  */
11015
11364
  async recordAccountQuota(routeId, accountIdentity, observation) {
11016
11365
  this.#assertOpen();
11017
- const kept = await recordVaultAccountQuota(this.#options.rosterPath, {
11366
+ return recordVaultAccountQuota(this.#options.rosterPath, {
11018
11367
  routeId,
11019
11368
  accountIdentity,
11020
11369
  observation
11021
11370
  });
11022
- if (kept)
11023
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11024
- return kept;
11025
11371
  }
11026
11372
  close() {
11027
11373
  if (this.#shutdown.signal.aborted)
@@ -11036,6 +11382,13 @@ var init_consumer = __esm({
11036
11382
  this.#insula = void 0;
11037
11383
  this.#roster = void 0;
11038
11384
  this.#grantReach = void 0;
11385
+ void this.#releaseQuotaWriter();
11386
+ forgetPendingVaultDiscovery(this.#options.rosterPath);
11387
+ }
11388
+ /** Close immediately; the last consumer also waits for the writer's bounded drain. */
11389
+ async dispose() {
11390
+ this.close();
11391
+ await this.#releaseQuotaWriter();
11039
11392
  }
11040
11393
  };
11041
11394
  }
@@ -11078,6 +11431,7 @@ __export(claustrum_exports, {
11078
11431
  declineAccount: () => declineAccount,
11079
11432
  declineVaultRoute: () => declineVaultRoute,
11080
11433
  disconnectClaustrumEnrollment: () => disconnectClaustrumEnrollment,
11434
+ drainVaultQuota: () => drainVaultQuota,
11081
11435
  enrollmentAuthority: () => enrollmentAuthority,
11082
11436
  enrollmentName: () => enrollmentName,
11083
11437
  getClaustrumEnrollmentPaths: () => getClaustrumEnrollmentPaths,
@@ -11116,6 +11470,7 @@ var init_claustrum = __esm({
11116
11470
  init_host_slot();
11117
11471
  init_insula();
11118
11472
  init_interlock();
11473
+ init_quota_writer();
11119
11474
  init_roster();
11120
11475
  init_watch();
11121
11476
  }
@@ -11196,7 +11551,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11196
11551
  if (!released && lastUpdate + RENEWAL_STALE < Date.now())
11197
11552
  compromise();
11198
11553
  }
11199
- function schedule(delay3 = UPDATE) {
11554
+ function schedule2(delay3 = UPDATE) {
11200
11555
  if (released)
11201
11556
  return;
11202
11557
  timer = setTimeout(() => {
@@ -11210,7 +11565,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11210
11565
  if (errorCode(error) === "ENOENT" || lastUpdate + RENEWAL_STALE < Date.now())
11211
11566
  compromise();
11212
11567
  else
11213
- schedule(1e3);
11568
+ schedule2(1e3);
11214
11569
  }
11215
11570
  async function update() {
11216
11571
  assertFresh();
@@ -11243,14 +11598,14 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11243
11598
  mtime = next.getTime();
11244
11599
  lastUpdate = Date.now();
11245
11600
  active.set(path5, { ...identity, mtime, renewedAt: lastUpdate });
11246
- schedule();
11601
+ schedule2();
11247
11602
  }
11248
11603
  onRenew?.(async () => {
11249
11604
  if (timer)
11250
11605
  clearTimeout(timer);
11251
11606
  await update();
11252
11607
  });
11253
- schedule();
11608
+ schedule2();
11254
11609
  return {
11255
11610
  assertFresh,
11256
11611
  async release() {
@@ -11309,7 +11664,7 @@ var init_lock = __esm({
11309
11664
  import { createHash as createHash8 } from "node:crypto";
11310
11665
  import { constants as constants2 } from "node:fs";
11311
11666
  import { lstat as lstat3, mkdir as mkdir10, open as open7, unlink as unlink7 } from "node:fs/promises";
11312
- import { dirname as dirname10, resolve as resolve6 } from "node:path";
11667
+ import { dirname as dirname10, resolve as resolve8 } from "node:path";
11313
11668
  import { setTimeout as sleep2 } from "node:timers/promises";
11314
11669
  function rootSpans(text2) {
11315
11670
  let i = text2.indexOf("{") + 1;
@@ -11510,8 +11865,8 @@ function createPiSlot(options, onStep, hooks) {
11510
11865
  if (!provider2 || !options.authPath || !options.stashPath || !placeholderKey || placeholderKey.startsWith("!") || placeholderKey.includes("$") || !Number.isFinite(timeout) || timeout < 0) {
11511
11866
  throw new PiSlotError("invalid-options");
11512
11867
  }
11513
- const authPath = resolve6(options.authPath);
11514
- const stashPath = resolve6(options.stashPath);
11868
+ const authPath = resolve8(options.authPath);
11869
+ const stashPath = resolve8(options.stashPath);
11515
11870
  if (authPath === stashPath || stashPath === `${authPath}.lock`) {
11516
11871
  throw new PiSlotError("invalid-options");
11517
11872
  }
@@ -18230,7 +18585,7 @@ async function rmEvictingDir(evictingPath) {
18230
18585
  });
18231
18586
  }
18232
18587
  async function sleep(ms) {
18233
- await new Promise((resolve18) => setTimeout(resolve18, ms));
18588
+ await new Promise((resolve20) => setTimeout(resolve20, ms));
18234
18589
  }
18235
18590
  async function acquireFencedFileLock(options) {
18236
18591
  const lockPath = `${options.path}.${options.name}.lock`;
@@ -18346,8 +18701,8 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
18346
18701
  let released = false;
18347
18702
  let lost = false;
18348
18703
  let lostResolve = null;
18349
- let lostPromise = new Promise((resolve18) => {
18350
- lostResolve = resolve18;
18704
+ let lostPromise = new Promise((resolve20) => {
18705
+ lostResolve = resolve20;
18351
18706
  });
18352
18707
  const markLost = () => {
18353
18708
  if (lost)
@@ -18357,9 +18712,9 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
18357
18712
  clearInterval(renewTimer);
18358
18713
  renewTimer = null;
18359
18714
  }
18360
- const resolve18 = lostResolve;
18715
+ const resolve20 = lostResolve;
18361
18716
  lostResolve = null;
18362
- resolve18?.();
18717
+ resolve20?.();
18363
18718
  };
18364
18719
  const setupRenew = () => {
18365
18720
  if (options.renew === false)
@@ -18586,7 +18941,7 @@ var AccountStorageUnreadableError = class extends Error {
18586
18941
  }
18587
18942
  };
18588
18943
  var RETRY_DELAYS_MS = [100, 200, 400, 800, 1e3];
18589
- var DEFAULT_SLEEP = (ms) => new Promise((resolve18) => setTimeout(resolve18, ms));
18944
+ var DEFAULT_SLEEP = (ms) => new Promise((resolve20) => setTimeout(resolve20, ms));
18590
18945
  var DEFAULT_BUILD_BACKUP_PATH = (path5, now) => `${path5}.corrupt-${now.toISOString().replace(/[:.]/g, "-")}`;
18591
18946
  async function ensureSecurePermissions(path5) {
18592
18947
  try {
@@ -18977,7 +19332,7 @@ async function saveAccountStorageReplace(path5, incoming) {
18977
19332
  return mutateAccountStorage(path5, () => incoming);
18978
19333
  }
18979
19334
  async function clearAccountStorage(path5) {
18980
- const sleep5 = (ms) => new Promise((resolve18) => setTimeout(resolve18, ms));
19335
+ const sleep5 = (ms) => new Promise((resolve20) => setTimeout(resolve20, ms));
18981
19336
  const lock = await acquireWithRetry(path5, sleep5);
18982
19337
  try {
18983
19338
  await assertLegacyAccountStorageWritable(path5);
@@ -20168,8 +20523,8 @@ var AccountManager = class _AccountManager {
20168
20523
  await this.saveInFlight;
20169
20524
  return;
20170
20525
  }
20171
- return new Promise((resolve18, reject) => {
20172
- this.savePromiseResolvers.push({ resolve: resolve18, reject });
20526
+ return new Promise((resolve20, reject) => {
20527
+ this.savePromiseResolvers.push({ resolve: resolve20, reject });
20173
20528
  });
20174
20529
  }
20175
20530
  async dispose() {
@@ -20212,8 +20567,8 @@ var AccountManager = class _AccountManager {
20212
20567
  reject(error);
20213
20568
  throw error;
20214
20569
  }
20215
- for (const { resolve: resolve18 } of resolvers)
20216
- resolve18();
20570
+ for (const { resolve: resolve20 } of resolvers)
20571
+ resolve20();
20217
20572
  }
20218
20573
  async executeSave() {
20219
20574
  this.savePending = false;
@@ -20227,16 +20582,16 @@ var AccountManager = class _AccountManager {
20227
20582
  }
20228
20583
  try {
20229
20584
  await this.saveToDisk();
20230
- for (const { resolve: resolve18 } of resolvers) {
20231
- resolve18();
20585
+ for (const { resolve: resolve20 } of resolvers) {
20586
+ resolve20();
20232
20587
  }
20233
20588
  } catch (error) {
20234
20589
  if (isStorageLockContention(error)) {
20235
20590
  this.onDiagnostic?.("Skipped account-state persist due to storage lock contention", {
20236
20591
  error: String(error)
20237
20592
  });
20238
- for (const { resolve: resolve18 } of resolvers) {
20239
- resolve18();
20593
+ for (const { resolve: resolve20 } of resolvers) {
20594
+ resolve20();
20240
20595
  }
20241
20596
  return;
20242
20597
  }
@@ -20713,7 +21068,7 @@ function getHttpsProxy(url) {
20713
21068
  }
20714
21069
  }
20715
21070
  function waitForHead(socket, timeoutMs, onTimeout) {
20716
- return new Promise((resolve18, reject) => {
21071
+ return new Promise((resolve20, reject) => {
20717
21072
  let buffer = Buffer3.alloc(0);
20718
21073
  const timeout = setTimeout(() => {
20719
21074
  onTimeout();
@@ -20736,7 +21091,7 @@ function waitForHead(socket, timeoutMs, onTimeout) {
20736
21091
  return;
20737
21092
  const head = buffer.subarray(0, marker).toString("latin1");
20738
21093
  const leftover = buffer.subarray(marker + 4);
20739
- cleanup2(() => resolve18({ head, leftover }));
21094
+ cleanup2(() => resolve20({ head, leftover }));
20740
21095
  };
20741
21096
  socket.on("data", onData);
20742
21097
  socket.once("error", onError);
@@ -20750,7 +21105,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
20750
21105
  port: Number(proxyUrl.port || DEFAULT_PROXY_PORT),
20751
21106
  signal: signal ?? void 0
20752
21107
  });
20753
- await new Promise((resolve18, reject) => {
21108
+ await new Promise((resolve20, reject) => {
20754
21109
  const timeout = setTimeout(() => {
20755
21110
  onDebug?.(`agy transport proxy connect timeout after ${timeoutMs}ms`);
20756
21111
  proxySocket.destroy();
@@ -20759,7 +21114,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
20759
21114
  const cleanup2 = () => clearTimeout(timeout);
20760
21115
  proxySocket.once("connect", () => {
20761
21116
  cleanup2();
20762
- resolve18();
21117
+ resolve20();
20763
21118
  });
20764
21119
  proxySocket.once("error", (error) => {
20765
21120
  cleanup2();
@@ -20784,7 +21139,7 @@ Host: ${targetHost}:${targetPort}\r
20784
21139
  if (leftover.length > 0) {
20785
21140
  proxySocket.unshift(leftover);
20786
21141
  }
20787
- return await new Promise((resolve18, reject) => {
21142
+ return await new Promise((resolve20, reject) => {
20788
21143
  const tlsOptions = {
20789
21144
  socket: proxySocket,
20790
21145
  servername: targetHost,
@@ -20799,7 +21154,7 @@ Host: ${targetHost}:${targetPort}\r
20799
21154
  const cleanup2 = () => clearTimeout(timeout);
20800
21155
  tlsSocket.once("secureConnect", () => {
20801
21156
  cleanup2();
20802
- resolve18(tlsSocket);
21157
+ resolve20(tlsSocket);
20803
21158
  });
20804
21159
  tlsSocket.once("error", (error) => {
20805
21160
  cleanup2();
@@ -20808,7 +21163,7 @@ Host: ${targetHost}:${targetPort}\r
20808
21163
  });
20809
21164
  }
20810
21165
  async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
20811
- return await new Promise((resolve18, reject) => {
21166
+ return await new Promise((resolve20, reject) => {
20812
21167
  const tlsOptions = {
20813
21168
  host: targetUrl.hostname,
20814
21169
  port: Number(targetUrl.port || DEFAULT_HTTPS_PORT),
@@ -20824,7 +21179,7 @@ async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
20824
21179
  const cleanup2 = () => clearTimeout(timeout);
20825
21180
  socket.once("secureConnect", () => {
20826
21181
  cleanup2();
20827
- resolve18(socket);
21182
+ resolve20(socket);
20828
21183
  });
20829
21184
  socket.once("error", (error) => {
20830
21185
  cleanup2();
@@ -22027,11 +22382,11 @@ function containsCredential(value, credentials, projectIds, seen = /* @__PURE__
22027
22382
  function redactCredentialError(error, credentials, projectIds) {
22028
22383
  const source = error instanceof Error || error instanceof DOMException ? error : void 0;
22029
22384
  const message = redactCredentialText(source?.message ?? String(error), credentials, projectIds);
22030
- const fields = source ? Reflect.ownKeys(source).map((key) => ({
22385
+ const fields2 = source ? Reflect.ownKeys(source).map((key) => ({
22031
22386
  key,
22032
22387
  descriptor: Object.getOwnPropertyDescriptor(source, key)
22033
22388
  })) : [];
22034
- const cause = fields.find(({ key }) => key === "cause")?.descriptor;
22389
+ const cause = fields2.find(({ key }) => key === "cause")?.descriptor;
22035
22390
  const secretCause = cause && (!("value" in cause) || containsCredential(cause.value, credentials, projectIds));
22036
22391
  try {
22037
22392
  if (source) {
@@ -22041,7 +22396,7 @@ function redactCredentialError(error, credentials, projectIds) {
22041
22396
  configurable: true,
22042
22397
  writable: true
22043
22398
  });
22044
- for (const { key, descriptor } of fields) {
22399
+ for (const { key, descriptor } of fields2) {
22045
22400
  if (key === "message" || key === "cause" || !("value" in descriptor))
22046
22401
  continue;
22047
22402
  const value = scrub2(descriptor.value, credentials, projectIds);
@@ -22056,7 +22411,7 @@ function redactCredentialError(error, credentials, projectIds) {
22056
22411
  }
22057
22412
  const safe = new Error(message);
22058
22413
  safe.name = redactCredentialText(source?.name ?? "Error", credentials, projectIds);
22059
- for (const { key, descriptor } of fields) {
22414
+ for (const { key, descriptor } of fields2) {
22060
22415
  if (key === "message" || key === "cause" || !("value" in descriptor))
22061
22416
  continue;
22062
22417
  Object.defineProperty(safe, key, {
@@ -22183,15 +22538,15 @@ async function redactCredentialResponse(response, credentials, bufferedBody, pro
22183
22538
 
22184
22539
  // ../core/dist/pi-paths.js
22185
22540
  import { homedir } from "node:os";
22186
- import { dirname as dirname11, join as join6 } from "node:path";
22541
+ import { dirname as dirname11, join as join7 } from "node:path";
22187
22542
  function getPiConfigDir() {
22188
- return process.env.PI_AGENT_DIR?.trim() || join6(homedir(), ".pi", "agent");
22543
+ return process.env.PI_AGENT_DIR?.trim() || join7(homedir(), ".pi", "agent");
22189
22544
  }
22190
22545
  function getPiAntigravityAuthFile() {
22191
- return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join6(getPiConfigDir(), "antigravity-accounts.json");
22546
+ return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join7(getPiConfigDir(), "antigravity-accounts.json");
22192
22547
  }
22193
22548
  function getPiAntigravityVaultDir() {
22194
- return join6(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
22549
+ return join7(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
22195
22550
  }
22196
22551
 
22197
22552
  // ../core/dist/pre-response-deadline.js
@@ -22367,8 +22722,8 @@ function getDefaultTierId(allowedTiers) {
22367
22722
  return allowedTiers[0]?.id;
22368
22723
  }
22369
22724
  function wait(ms) {
22370
- return new Promise((resolve18) => {
22371
- setTimeout(resolve18, ms);
22725
+ return new Promise((resolve20) => {
22726
+ setTimeout(resolve20, ms);
22372
22727
  });
22373
22728
  }
22374
22729
  function extractManagedProjectId(payload) {
@@ -22927,11 +23282,16 @@ function mostConstrainedWindow(windows2) {
22927
23282
  };
22928
23283
  }
22929
23284
  function poolForBucketId(bucketId) {
22930
- if (bucketId.startsWith("gemini-"))
22931
- return "gemini";
22932
- if (bucketId.startsWith("3p-"))
22933
- return "non-gemini";
22934
- return null;
23285
+ switch (bucketId) {
23286
+ case "gemini-5h":
23287
+ case "gemini-weekly":
23288
+ return "gemini";
23289
+ case "3p-5h":
23290
+ case "3p-weekly":
23291
+ return "non-gemini";
23292
+ default:
23293
+ return null;
23294
+ }
22935
23295
  }
22936
23296
  function parseDescriptionModelCount(description) {
22937
23297
  const prefixMatch = description.match(/^[^:]+:\s*/);
@@ -22952,31 +23312,60 @@ function windowDurationMs(window) {
22952
23312
  }
22953
23313
  }
22954
23314
  function aggregateQuotaSummary(response) {
22955
- const groups = {};
22956
- let totalCount = 0;
23315
+ const windowsByPool = {
23316
+ gemini: /* @__PURE__ */ new Map(),
23317
+ "non-gemini": /* @__PURE__ */ new Map()
23318
+ };
23319
+ const modelCounts = {
23320
+ gemini: 0,
23321
+ "non-gemini": 0
23322
+ };
23323
+ const seenBucketIds = /* @__PURE__ */ new Set();
23324
+ const duplicateBucketIds = /* @__PURE__ */ new Set();
22957
23325
  for (const group of response.groups) {
22958
- const windows2 = [];
23326
+ const contributingPools = /* @__PURE__ */ new Set();
22959
23327
  for (const bucket of group.buckets) {
22960
- const pool2 = poolForBucketId(bucket.bucketId);
22961
- if (!pool2)
23328
+ if (bucket.disabled === true)
23329
+ continue;
23330
+ const pool = poolForBucketId(bucket.bucketId);
23331
+ if (!pool)
22962
23332
  continue;
22963
- windows2.push({
23333
+ contributingPools.add(pool);
23334
+ const window = {
22964
23335
  window: bucket.window,
22965
23336
  remainingFraction: normalizeRemainingFraction(bucket.remainingFraction),
22966
23337
  resetTime: bucket.resetTime
22967
- });
23338
+ };
23339
+ const previous = windowsByPool[pool].get(bucket.bucketId);
23340
+ if (seenBucketIds.has(bucket.bucketId)) {
23341
+ duplicateBucketIds.add(bucket.bucketId);
23342
+ } else {
23343
+ seenBucketIds.add(bucket.bucketId);
23344
+ }
23345
+ if (!previous || window.remainingFraction < previous.remainingFraction) {
23346
+ windowsByPool[pool].set(bucket.bucketId, window);
23347
+ }
22968
23348
  }
23349
+ const modelCount = group.description ? parseDescriptionModelCount(group.description) : 0;
23350
+ for (const pool of contributingPools)
23351
+ modelCounts[pool] += modelCount;
23352
+ }
23353
+ if (duplicateBucketIds.size > 0) {
23354
+ log4.debug("duplicate quota summary bucket ids", {
23355
+ bucketIds: [...duplicateBucketIds].sort()
23356
+ });
23357
+ }
23358
+ const groups = {};
23359
+ let totalCount = 0;
23360
+ for (const pool of ["gemini", "non-gemini"]) {
23361
+ const windows2 = [...windowsByPool[pool].values()];
22969
23362
  if (windows2.length === 0)
22970
23363
  continue;
22971
23364
  windows2.sort((a, b) => windowDurationMs(a.window) - windowDurationMs(b.window));
22972
23365
  const constrained = mostConstrainedWindow(windows2);
22973
- const recognizedBucket = group.buckets.find((bucket) => poolForBucketId(bucket.bucketId));
22974
- if (!recognizedBucket)
23366
+ if (!constrained)
22975
23367
  continue;
22976
- const pool = poolForBucketId(recognizedBucket.bucketId);
22977
- if (!pool || !constrained)
22978
- continue;
22979
- const modelCount = group.description ? parseDescriptionModelCount(group.description) : 0;
23368
+ const modelCount = modelCounts[pool];
22980
23369
  groups[pool] = {
22981
23370
  remainingFraction: constrained.remainingFraction,
22982
23371
  resetTime: constrained.resetTime,
@@ -23339,6 +23728,7 @@ function toGeminiSchema(schema, options = {}) {
23339
23728
  }
23340
23729
  const numericConstraintHints = [];
23341
23730
  const inputSchema = mergeSchemaAllOf(schema, numericConstraintHints);
23731
+ const schemaType = typeof inputSchema.type === "string" ? inputSchema.type.toUpperCase() : void 0;
23342
23732
  let result = {};
23343
23733
  const propertyNames = /* @__PURE__ */ new Set();
23344
23734
  if (inputSchema.properties && typeof inputSchema.properties === "object") {
@@ -23347,6 +23737,12 @@ function toGeminiSchema(schema, options = {}) {
23347
23737
  }
23348
23738
  }
23349
23739
  for (const [key, value] of Object.entries(inputSchema)) {
23740
+ if (schemaType !== void 0) {
23741
+ if (key === "items" && schemaType !== "ARRAY")
23742
+ continue;
23743
+ if (schemaType !== "OBJECT" && ["properties", "required", "propertyOrdering"].includes(key))
23744
+ continue;
23745
+ }
23350
23746
  if (options.claudeValidated) {
23351
23747
  if (key === "title")
23352
23748
  continue;
@@ -24395,12 +24791,12 @@ async function commitVaultProviderState(input2) {
24395
24791
  function untilAborted(pending, signal) {
24396
24792
  if (!signal)
24397
24793
  return pending;
24398
- return new Promise((resolve18, reject) => {
24794
+ return new Promise((resolve20, reject) => {
24399
24795
  const abort = () => reject(signal.reason);
24400
24796
  signal.addEventListener("abort", abort, { once: true });
24401
24797
  if (signal.aborted)
24402
24798
  abort();
24403
- pending.then(resolve18, reject).finally(() => signal.removeEventListener("abort", abort));
24799
+ pending.then(resolve20, reject).finally(() => signal.removeEventListener("abort", abort));
24404
24800
  });
24405
24801
  }
24406
24802
  var AntigravityVaultSourceError = class extends Error {
@@ -24666,6 +25062,7 @@ function createAntigravityVaultAccountSource(options) {
24666
25062
  }
24667
25063
 
24668
25064
  // ../core/dist/vault-enrollment-authority.js
25065
+ var UNSUPPORTED_VAULT_CODE = "unknown_method";
24669
25066
  var VAULT_ACCOUNT_REMEDY = "Vault account access is unavailable. Connect accounts in the vault, or disconnect the vault to use local accounts.";
24670
25067
  async function enrollmentAuthority2(paths, proposedName, reader) {
24671
25068
  try {
@@ -24876,21 +25273,21 @@ import { randomBytes as randomBytes5 } from "node:crypto";
24876
25273
  function present2(value) {
24877
25274
  return value === null ? void 0 : value;
24878
25275
  }
24879
- function accessBlockOf(fields) {
24880
- if (fields === void 0) return { kind: "none" };
24881
- if (fields.accountIneligible === true) {
24882
- const reason = present2(fields.accountIneligibleReason);
24883
- const at = present2(fields.accountIneligibleAt);
25276
+ function accessBlockOf(fields2) {
25277
+ if (fields2 === void 0) return { kind: "none" };
25278
+ if (fields2.accountIneligible === true) {
25279
+ const reason = present2(fields2.accountIneligibleReason);
25280
+ const at = present2(fields2.accountIneligibleAt);
24884
25281
  return {
24885
25282
  kind: "ineligible",
24886
25283
  ...reason !== void 0 ? { reason } : {},
24887
25284
  ...at !== void 0 ? { at } : {}
24888
25285
  };
24889
25286
  }
24890
- if (fields.verificationRequired === true) {
24891
- const reason = present2(fields.verificationRequiredReason);
24892
- const verificationUrl = present2(fields.verificationUrl);
24893
- const at = present2(fields.verificationRequiredAt);
25287
+ if (fields2.verificationRequired === true) {
25288
+ const reason = present2(fields2.verificationRequiredReason);
25289
+ const verificationUrl = present2(fields2.verificationUrl);
25290
+ const at = present2(fields2.verificationRequiredAt);
24894
25291
  return {
24895
25292
  kind: "verification-required",
24896
25293
  ...reason !== void 0 ? { reason } : {},
@@ -25019,12 +25416,13 @@ function clearLegacyAccessBlocks(account, enableIfBlocked, now) {
25019
25416
  // src/common-auth-embedded/logger/engine.js
25020
25417
  import { appendFileSync as appendFileSync2, chmodSync as chmodSync2, existsSync as existsSync2, renameSync as renameSync2, statSync as statSync3 } from "node:fs";
25021
25418
  import { open as open8 } from "node:fs/promises";
25022
- import { dirname as dirname13, resolve as resolve8 } from "node:path";
25419
+ import { dirname as dirname13, resolve as resolve10 } from "node:path";
25023
25420
 
25024
25421
  // src/common-auth-embedded/fs/private-files.js
25025
25422
  import { randomUUID as randomUUID13 } from "node:crypto";
25026
25423
  import { lstat as lstat4, readFile as readFile8, rename as rename7, unlink as unlink8 } from "node:fs/promises";
25027
- import { dirname as dirname12, resolve as resolve7 } from "node:path";
25424
+ import { tmpdir as tmpdir2 } from "node:os";
25425
+ import { dirname as dirname12, join as join8, resolve as resolve9 } from "node:path";
25028
25426
  var windowsPrivateFiles2 = process.platform === "win32";
25029
25427
  var migrationNotices2 = /* @__PURE__ */ new Set();
25030
25428
  function ioCode2(detail) {
@@ -25037,8 +25435,32 @@ function ioCode2(detail) {
25037
25435
  return detail?.code ?? "ERR_PRIVATE_FILE";
25038
25436
  }
25039
25437
  var backend2;
25438
+ var PRIVATE_FILES_UNAVAILABLE_REASON2 = "native-addon-unavailable";
25439
+ function privateFilesUnavailable2(cause) {
25440
+ return Object.assign(new Error("Windows private-files native addon is unavailable", { cause }), {
25441
+ code: "ERR_PRIVATE_FILES_UNAVAILABLE",
25442
+ reason: PRIVATE_FILES_UNAVAILABLE_REASON2
25443
+ });
25444
+ }
25445
+ function isUnavailable2(api, error) {
25446
+ return error instanceof api.PrivateFilesUnavailableError || error?.code === "ERR_PRIVATE_FILES_UNAVAILABLE";
25447
+ }
25448
+ async function assertNativeAddonLoads2(api) {
25449
+ try {
25450
+ await api.verifyPrivatePath(join8(tmpdir2(), `.common-auth-private-files-probe-${randomUUID13()}`), "file");
25451
+ } catch (error) {
25452
+ if (isUnavailable2(api, error))
25453
+ throw privateFilesUnavailable2(error);
25454
+ }
25455
+ }
25040
25456
  function loadBackend2() {
25041
- backend2 ??= import("@cortexkit/private-files");
25457
+ backend2 ??= import("@cortexkit/private-files").then(async (api) => {
25458
+ if (windowsPrivateFiles2)
25459
+ await assertNativeAddonLoads2(api);
25460
+ return api;
25461
+ }, (cause) => {
25462
+ throw windowsPrivateFiles2 ? privateFilesUnavailable2(cause) : cause;
25463
+ });
25042
25464
  return backend2;
25043
25465
  }
25044
25466
  var PrivateFileError2 = class extends Error {
@@ -25055,7 +25477,7 @@ var PrivateFileError2 = class extends Error {
25055
25477
  orphanPath;
25056
25478
  constructor(path5, stage, cause) {
25057
25479
  const detail = cause;
25058
- super(`Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`, { cause });
25480
+ super(detail?.code === "ERR_PRIVATE_FILES_UNAVAILABLE" ? `Private file refused at ${stage}: ${path5} (${PRIVATE_FILES_UNAVAILABLE_REASON2}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.` : `Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
25059
25481
  this.path = path5;
25060
25482
  this.stage = stage;
25061
25483
  this.name = "PrivateFileError";
@@ -25075,7 +25497,7 @@ async function privateOperation2(path5, stage, operation) {
25075
25497
  }
25076
25498
  var safeParentOptionsForTest2;
25077
25499
  async function verifySafeDirectory2(path5, options) {
25078
- path5 = resolve7(path5);
25500
+ path5 = resolve9(path5);
25079
25501
  options ??= safeParentOptionsForTest2;
25080
25502
  await privateOperation2(path5, "safe-parent", async () => {
25081
25503
  const result = await (await loadBackend2()).verifySafeParent(path5, options);
@@ -25090,7 +25512,7 @@ async function verifySafeDirectory2(path5, options) {
25090
25512
  });
25091
25513
  }
25092
25514
  async function verifyPrivate2(path5, kind, migrate = false) {
25093
- path5 = resolve7(path5);
25515
+ path5 = resolve9(path5);
25094
25516
  if (kind === "directory")
25095
25517
  return verifySafeDirectory2(path5);
25096
25518
  await privateOperation2(path5, "verify", async () => {
@@ -25125,7 +25547,7 @@ async function verifyPrivate2(path5, kind, migrate = false) {
25125
25547
  });
25126
25548
  }
25127
25549
  async function ensurePrivateDirectory3(path5, _migrate = false, options) {
25128
- path5 = resolve7(path5);
25550
+ path5 = resolve9(path5);
25129
25551
  await privateOperation2(path5, "directory", async () => {
25130
25552
  const api = await loadBackend2();
25131
25553
  try {
@@ -25156,7 +25578,7 @@ async function readPrivateText2(path5, migrate = false) {
25156
25578
  async function readPrivateBuffer2(path5, migrate = false) {
25157
25579
  if (!windowsPrivateFiles2)
25158
25580
  return readFile8(path5);
25159
- path5 = resolve7(path5);
25581
+ path5 = resolve9(path5);
25160
25582
  if (migrate) {
25161
25583
  await verifySafeDirectory2(dirname12(path5));
25162
25584
  await verifyPrivate2(path5, "file", true);
@@ -25164,20 +25586,20 @@ async function readPrivateBuffer2(path5, migrate = false) {
25164
25586
  return privateOperation2(path5, "read", async () => (await loadBackend2()).readOwnerOnly(path5));
25165
25587
  }
25166
25588
  async function createPrivateBytes2(path5, bytes) {
25167
- await verifySafeDirectory2(dirname12(resolve7(path5)));
25589
+ await verifySafeDirectory2(dirname12(resolve9(path5)));
25168
25590
  await privateOperation2(path5, "create", async () => {
25169
- await (await loadBackend2()).createPrivateFile(resolve7(path5), bytes);
25591
+ await (await loadBackend2()).createPrivateFile(resolve9(path5), bytes);
25170
25592
  });
25171
25593
  }
25172
25594
  async function createPrivateDirectoryExclusive2(path5) {
25173
- await verifySafeDirectory2(dirname12(resolve7(path5)));
25595
+ await verifySafeDirectory2(dirname12(resolve9(path5)));
25174
25596
  await privateOperation2(path5, "directory-create", async () => {
25175
- await (await loadBackend2()).createOwnerOnly(resolve7(path5), { kind: "dir" });
25597
+ await (await loadBackend2()).createOwnerOnly(resolve9(path5), { kind: "dir" });
25176
25598
  });
25177
25599
  }
25178
25600
  async function replaceWindowsFile2(from, to, options = {}) {
25179
- from = resolve7(from);
25180
- to = resolve7(to);
25601
+ from = resolve9(from);
25602
+ to = resolve9(to);
25181
25603
  const now = options.now ?? (() => performance.now());
25182
25604
  const start = now();
25183
25605
  const leaseDeadline = options.deadline ?? Infinity;
@@ -25220,7 +25642,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
25220
25642
  throw error;
25221
25643
  }
25222
25644
  async function writePrivateAtomic2(path5, bytes, options = {}) {
25223
- path5 = resolve7(path5);
25645
+ path5 = resolve9(path5);
25224
25646
  await ensurePrivateDirectory3(dirname12(path5));
25225
25647
  try {
25226
25648
  await verifyPrivate2(path5, "file", true);
@@ -25228,7 +25650,7 @@ async function writePrivateAtomic2(path5, bytes, options = {}) {
25228
25650
  if (error.code !== "ENOENT")
25229
25651
  throw error;
25230
25652
  }
25231
- const stage = resolve7(options.stagePath ?? `${path5}.${randomUUID13()}.tmp`);
25653
+ const stage = resolve9(options.stagePath ?? `${path5}.${randomUUID13()}.tmp`);
25232
25654
  if (dirname12(stage) !== dirname12(path5))
25233
25655
  throw new PrivateFileError2(path5, "stage-directory", { code: "EXDEV" });
25234
25656
  let created = false;
@@ -25304,15 +25726,15 @@ function createRedactor2(options = {}) {
25304
25726
  return SECRET_KEY_EXACT2.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
25305
25727
  }
25306
25728
  function errorEntries(error) {
25307
- const fields = error;
25729
+ const fields2 = error;
25308
25730
  const entries = [
25309
25731
  ["name", error.name],
25310
25732
  ["message", error.message],
25311
25733
  ["stack", error.stack]
25312
25734
  ];
25313
25735
  for (const key of ["code", "status", "cause"])
25314
- if (fields[key] !== void 0)
25315
- entries.push([key, fields[key]]);
25736
+ if (fields2[key] !== void 0)
25737
+ entries.push([key, fields2[key]]);
25316
25738
  const listed = new Set(entries.map(([key]) => key));
25317
25739
  for (const entry of Object.entries(error))
25318
25740
  if (!listed.has(entry[0]))
@@ -25413,7 +25835,7 @@ async function openWindowsFile2(sink, file) {
25413
25835
  return sink.handle;
25414
25836
  }
25415
25837
  async function flushWindowsFile2(sink, file, text2) {
25416
- file = resolve8(file);
25838
+ file = resolve10(file);
25417
25839
  try {
25418
25840
  if (sink.file !== file)
25419
25841
  await closeWindowsFile2(sink);
@@ -25550,7 +25972,7 @@ function createEngine2(options) {
25550
25972
  } catch {
25551
25973
  }
25552
25974
  }
25553
- function schedule() {
25975
+ function schedule2() {
25554
25976
  if (!timer)
25555
25977
  timer = setTimeout(() => {
25556
25978
  timer = void 0;
@@ -25592,7 +26014,7 @@ function createEngine2(options) {
25592
26014
  void flushed.catch(() => {
25593
26015
  });
25594
26016
  } else
25595
- schedule();
26017
+ schedule2();
25596
26018
  } catch {
25597
26019
  }
25598
26020
  }
@@ -25671,7 +26093,7 @@ import {
25671
26093
  unlinkSync as unlinkSync2
25672
26094
  } from "node:fs";
25673
26095
  import { homedir as homedir3 } from "node:os";
25674
- import { join as join8 } from "node:path";
26096
+ import { join as join10 } from "node:path";
25675
26097
  import { env } from "node:process";
25676
26098
 
25677
26099
  // src/plugin/logging-utils.ts
@@ -25808,7 +26230,7 @@ import {
25808
26230
  writeFileSync
25809
26231
  } from "node:fs";
25810
26232
  import { homedir as homedir2 } from "node:os";
25811
- import { dirname as dirname14, join as join7, resolve as resolve9 } from "node:path";
26233
+ import { dirname as dirname14, join as join9, resolve as resolve11 } from "node:path";
25812
26234
  var log5 = createLogger4("storage");
25813
26235
  var mutateAccountStorage2 = async (path5, mutate) => {
25814
26236
  await assertLegacyPoolInUse(path5);
@@ -25824,7 +26246,7 @@ var GITIGNORE_ENTRIES = [
25824
26246
  "antigravity-logs/"
25825
26247
  ];
25826
26248
  async function ensureGitignore(configDir) {
25827
- const gitignorePath = join7(configDir, ".gitignore");
26249
+ const gitignorePath = join9(configDir, ".gitignore");
25828
26250
  try {
25829
26251
  let content;
25830
26252
  let existingLines = [];
@@ -25870,7 +26292,7 @@ async function ensureGitignore(configDir) {
25870
26292
  }
25871
26293
  }
25872
26294
  function ensureGitignoreSync(configDir) {
25873
- const gitignorePath = join7(configDir, ".gitignore");
26295
+ const gitignorePath = join9(configDir, ".gitignore");
25874
26296
  try {
25875
26297
  let content;
25876
26298
  let existingLines = [];
@@ -25909,8 +26331,8 @@ function ensureGitignoreSync(configDir) {
25909
26331
  }
25910
26332
  }
25911
26333
  function getLegacyWindowsConfigDir() {
25912
- return join7(
25913
- process.env.APPDATA || join7(homedir2(), "AppData", "Roaming"),
26334
+ return join9(
26335
+ process.env.APPDATA || join9(homedir2(), "AppData", "Roaming"),
25914
26336
  "opencode"
25915
26337
  );
25916
26338
  }
@@ -25918,15 +26340,15 @@ function getConfigDir() {
25918
26340
  if (process.env.OPENCODE_CONFIG_DIR) {
25919
26341
  return process.env.OPENCODE_CONFIG_DIR;
25920
26342
  }
25921
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join7(homedir2(), ".config");
25922
- return join7(xdgConfig2, "opencode");
26343
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join9(homedir2(), ".config");
26344
+ return join9(xdgConfig2, "opencode");
25923
26345
  }
25924
26346
  function migrateLegacyWindowsConfig() {
25925
26347
  if (process.platform !== "win32") {
25926
26348
  return false;
25927
26349
  }
25928
- const newPath = join7(getConfigDir(), "antigravity-accounts.json");
25929
- const legacyPath = join7(
26350
+ const newPath = join9(getConfigDir(), "antigravity-accounts.json");
26351
+ const legacyPath = join9(
25930
26352
  getLegacyWindowsConfigDir(),
25931
26353
  "antigravity-accounts.json"
25932
26354
  );
@@ -25961,11 +26383,11 @@ function migrateLegacyWindowsConfig() {
25961
26383
  }
25962
26384
  }
25963
26385
  function getStoragePathWithMigration() {
25964
- const newPath = join7(getConfigDir(), "antigravity-accounts.json");
26386
+ const newPath = join9(getConfigDir(), "antigravity-accounts.json");
25965
26387
  if (process.platform === "win32") {
25966
26388
  migrateLegacyWindowsConfig();
25967
26389
  if (!existsSync3(newPath)) {
25968
- const legacyPath = join7(
26390
+ const legacyPath = join9(
25969
26391
  getLegacyWindowsConfigDir(),
25970
26392
  "antigravity-accounts.json"
25971
26393
  );
@@ -25996,7 +26418,7 @@ var LegacyAccountPoolRetiredError = class extends Error {
25996
26418
  };
25997
26419
  async function assertLegacyPoolInUse(legacyPath) {
25998
26420
  try {
25999
- await assertLegacyAccountStorageWritable(resolve9(legacyPath));
26421
+ await assertLegacyAccountStorageWritable(resolve11(legacyPath));
26000
26422
  } catch (error) {
26001
26423
  throw new LegacyAccountPoolRetiredError(legacyPath, { cause: error });
26002
26424
  }
@@ -26016,7 +26438,7 @@ function refusalMessage(admission) {
26016
26438
  }
26017
26439
  async function bindingOf(options) {
26018
26440
  const now = options.now ?? (() => Date.now());
26019
- const legacyPath = resolve9(options.legacyPath ?? getStoragePath());
26441
+ const legacyPath = resolve11(options.legacyPath ?? getStoragePath());
26020
26442
  return {
26021
26443
  legacyPath,
26022
26444
  now,
@@ -26084,7 +26506,7 @@ async function openAccountStore(options) {
26084
26506
  }
26085
26507
  function initializeFreshAccountStoreFor(modules, options = {}) {
26086
26508
  return initializeFreshAccountStore(modules, {
26087
- legacyPath: resolve9(options.legacyPath ?? getStoragePath()),
26509
+ legacyPath: resolve11(options.legacyPath ?? getStoragePath()),
26088
26510
  now: options.now ?? (() => Date.now())
26089
26511
  });
26090
26512
  }
@@ -26131,16 +26553,16 @@ var liveLogFilePaths = /* @__PURE__ */ new Set();
26131
26553
  function getConfigDir2() {
26132
26554
  const platform = process.platform;
26133
26555
  if (platform === "win32") {
26134
- return join8(
26135
- env.APPDATA || join8(homedir3(), "AppData", "Roaming"),
26556
+ return join10(
26557
+ env.APPDATA || join10(homedir3(), "AppData", "Roaming"),
26136
26558
  "opencode"
26137
26559
  );
26138
26560
  }
26139
- const xdgConfig2 = env.XDG_CONFIG_HOME || join8(homedir3(), ".config");
26140
- return join8(xdgConfig2, "opencode");
26561
+ const xdgConfig2 = env.XDG_CONFIG_HOME || join10(homedir3(), ".config");
26562
+ return join10(xdgConfig2, "opencode");
26141
26563
  }
26142
26564
  function getLogsDir(customLogDir) {
26143
- const logsDir = customLogDir || join8(getConfigDir2(), "antigravity-logs");
26565
+ const logsDir = customLogDir || join10(getConfigDir2(), "antigravity-logs");
26144
26566
  try {
26145
26567
  mkdirSync2(logsDir, { recursive: true, mode: 448 });
26146
26568
  } catch {
@@ -26151,9 +26573,9 @@ function createLogFilePath(customLogDir) {
26151
26573
  const logsDir = getLogsDir(customLogDir);
26152
26574
  cleanupOldLogs(logsDir, 25);
26153
26575
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
26154
- let candidate = join8(logsDir, `antigravity-debug-${timestamp}.log`);
26576
+ let candidate = join10(logsDir, `antigravity-debug-${timestamp}.log`);
26155
26577
  for (let suffix = 2; liveLogFilePaths.has(candidate); suffix++) {
26156
- candidate = join8(logsDir, `antigravity-debug-${timestamp}-${suffix}.log`);
26578
+ candidate = join10(logsDir, `antigravity-debug-${timestamp}-${suffix}.log`);
26157
26579
  }
26158
26580
  return candidate;
26159
26581
  }
@@ -26161,7 +26583,7 @@ function cleanupOldLogs(logsDir, maxFiles) {
26161
26583
  try {
26162
26584
  const files = readdirSync(logsDir).filter(
26163
26585
  (file) => file.startsWith("antigravity-debug-") && file.endsWith(".log")
26164
- ).map((file) => join8(logsDir, file));
26586
+ ).map((file) => join10(logsDir, file));
26165
26587
  if (files.length <= maxFiles) {
26166
26588
  return;
26167
26589
  }
@@ -26261,13 +26683,13 @@ function closeDebugStream(state) {
26261
26683
  state.logWriter = () => {
26262
26684
  };
26263
26685
  if (state.logFilePath) liveLogFilePaths.delete(state.logFilePath);
26264
- return new Promise((resolve18) => {
26265
- current.once("close", () => resolve18());
26266
- current.once("error", () => resolve18());
26686
+ return new Promise((resolve20) => {
26687
+ current.once("close", () => resolve20());
26688
+ current.once("error", () => resolve20());
26267
26689
  try {
26268
26690
  current.end();
26269
26691
  } catch {
26270
- resolve18();
26692
+ resolve20();
26271
26693
  }
26272
26694
  });
26273
26695
  }
@@ -26539,13 +26961,13 @@ function closeDebugLog() {
26539
26961
  if (!state || !current) return Promise.resolve();
26540
26962
  state.logStream = null;
26541
26963
  if (state.logFilePath) liveLogFilePaths.delete(state.logFilePath);
26542
- return new Promise((resolve18) => {
26543
- current.once("close", () => resolve18());
26544
- current.once("error", () => resolve18());
26964
+ return new Promise((resolve20) => {
26965
+ current.once("close", () => resolve20());
26966
+ current.once("error", () => resolve20());
26545
26967
  try {
26546
26968
  current.end();
26547
26969
  } catch {
26548
- resolve18();
26970
+ resolve20();
26549
26971
  }
26550
26972
  });
26551
26973
  }
@@ -27527,8 +27949,8 @@ var openCodeStore = {
27527
27949
  clear: async () => {
27528
27950
  }
27529
27951
  };
27530
- function defaultDiagnostic(message, fields) {
27531
- debugLogToFile(fields ? `${message} ${JSON.stringify(fields)}` : message);
27952
+ function defaultDiagnostic(message, fields2) {
27953
+ debugLogToFile(fields2 ? `${message} ${JSON.stringify(fields2)}` : message);
27532
27954
  }
27533
27955
  var AccountStoreNotReadyError = class extends Error {
27534
27956
  read;
@@ -27627,7 +28049,7 @@ import { z as z4 } from "zod";
27627
28049
  // src/plugin/config/loader.ts
27628
28050
  import { existsSync as existsSync4, readFileSync as readFileSync2, realpathSync } from "node:fs";
27629
28051
  import { homedir as homedir4 } from "node:os";
27630
- import { basename as basename4, dirname as dirname15, join as join9, resolve as resolve10 } from "node:path";
28052
+ import { basename as basename4, dirname as dirname15, join as join11, resolve as resolve12 } from "node:path";
27631
28053
 
27632
28054
  // src/plugin/config/schema.ts
27633
28055
  import { z } from "zod";
@@ -28122,14 +28544,14 @@ function getConfigDir3() {
28122
28544
  if (process.env.OPENCODE_CONFIG_DIR) {
28123
28545
  return process.env.OPENCODE_CONFIG_DIR;
28124
28546
  }
28125
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join9(homedir4(), ".config");
28126
- return join9(xdgConfig2, "opencode");
28547
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join11(homedir4(), ".config");
28548
+ return join11(xdgConfig2, "opencode");
28127
28549
  }
28128
28550
  function getUserConfigPath() {
28129
- return join9(getConfigDir3(), "antigravity.json");
28551
+ return join11(getConfigDir3(), "antigravity.json");
28130
28552
  }
28131
28553
  function getProjectConfigPath(directory) {
28132
- return join9(directory, ".opencode", "antigravity.json");
28554
+ return join11(directory, ".opencode", "antigravity.json");
28133
28555
  }
28134
28556
  function loadConfigFile(path5, log16) {
28135
28557
  try {
@@ -28185,13 +28607,13 @@ function loadConfigWithLogger(directory, log16) {
28185
28607
  return config;
28186
28608
  }
28187
28609
  function createLocationConfig(directory, options) {
28188
- const logger2 = options?.logger;
28189
- if (typeof logger2?.warn !== "function") {
28610
+ const logger3 = options?.logger;
28611
+ if (typeof logger3?.warn !== "function") {
28190
28612
  throw new TypeError(
28191
28613
  "createLocationConfig requires a logger with a warn function"
28192
28614
  );
28193
28615
  }
28194
- const config = loadConfigWithLogger(directory, logger2);
28616
+ const config = loadConfigWithLogger(directory, logger3);
28195
28617
  return {
28196
28618
  directory,
28197
28619
  config,
@@ -28201,12 +28623,12 @@ function createLocationConfig(directory, options) {
28201
28623
  };
28202
28624
  }
28203
28625
  function canonicalizeOwnedPath(path5) {
28204
- const absolute = resolve10(path5);
28626
+ const absolute = resolve12(path5);
28205
28627
  const missing = [];
28206
28628
  let current = absolute;
28207
28629
  for (; ; ) {
28208
28630
  try {
28209
- return join9(realpathSync(current), ...missing.reverse());
28631
+ return join11(realpathSync(current), ...missing.reverse());
28210
28632
  } catch {
28211
28633
  const parent = dirname15(current);
28212
28634
  if (parent === current) return absolute;
@@ -28756,7 +29178,7 @@ async function replacePoolLogins(repository, results, options = {}) {
28756
29178
  // src/sidebar-state.ts
28757
29179
  import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5 } from "node:fs";
28758
29180
  import { homedir as homedir5 } from "node:os";
28759
- import { dirname as dirname16, join as join10 } from "node:path";
29181
+ import { dirname as dirname16, join as join12 } from "node:path";
28760
29182
 
28761
29183
  // ../../node_modules/.bun/xdg-basedir@5.1.0/node_modules/xdg-basedir/index.js
28762
29184
  import os from "os";
@@ -28815,8 +29237,8 @@ async function emitMergeStep(step) {
28815
29237
  function getSidebarStateFile() {
28816
29238
  const override = process.env[SIDEBAR_STATE_ENV];
28817
29239
  if (override && override.trim().length > 0) return override;
28818
- const base = xdgState ?? join10(homedir5(), ".local", "state");
28819
- return join10(base, SIDEBAR_STATE_DIR, SIDEBAR_STATE_FILENAME);
29240
+ const base = xdgState ?? join12(homedir5(), ".local", "state");
29241
+ return join12(base, SIDEBAR_STATE_DIR, SIDEBAR_STATE_FILENAME);
28820
29242
  }
28821
29243
  function readSidebarState(path5 = getSidebarStateFile()) {
28822
29244
  let raw;
@@ -29162,7 +29584,7 @@ function drainSidebarWrites() {
29162
29584
  return sidebarWriteChain;
29163
29585
  }
29164
29586
  async function sleep3(ms) {
29165
- await new Promise((resolve18) => setTimeout(resolve18, ms));
29587
+ await new Promise((resolve20) => setTimeout(resolve20, ms));
29166
29588
  }
29167
29589
  async function acquireSidebarLockWithRetry(stateFile) {
29168
29590
  const start = Date.now();
@@ -29340,7 +29762,7 @@ function createLocationQuotaManager(options) {
29340
29762
  fetchTimeoutMs: options.fetchTimeoutMs
29341
29763
  });
29342
29764
  const sidebar = options.sidebar;
29343
- const logger2 = options.logger;
29765
+ const logger3 = options.logger;
29344
29766
  return withSidebarPushAfterRefresh(
29345
29767
  manager,
29346
29768
  sidebar ? (account) => pushSidebarQuotaSnapshot(
@@ -29349,7 +29771,7 @@ function createLocationQuotaManager(options) {
29349
29771
  sidebar.getActiveIndexByFamily,
29350
29772
  {
29351
29773
  write: sidebar.write,
29352
- logger: logger2,
29774
+ logger: logger3,
29353
29775
  healthScore: sidebar.healthScore ?? null,
29354
29776
  now: sidebar.now
29355
29777
  }
@@ -29713,14 +30135,14 @@ var LocalQuotaGrantStaleError = class extends Error {
29713
30135
  name = "LocalQuotaGrantStaleError";
29714
30136
  };
29715
30137
  function untilQuotaAborted(pending, signal) {
29716
- return new Promise((resolve18, reject) => {
30138
+ return new Promise((resolve20, reject) => {
29717
30139
  const abort = () => reject(signal.reason);
29718
30140
  if (signal.aborted) abort();
29719
30141
  else signal.addEventListener("abort", abort, { once: true });
29720
30142
  void pending.then(
29721
30143
  (value) => {
29722
30144
  signal.removeEventListener("abort", abort);
29723
- resolve18(value);
30145
+ resolve20(value);
29724
30146
  },
29725
30147
  (error) => {
29726
30148
  signal.removeEventListener("abort", abort);
@@ -30080,7 +30502,7 @@ function heldAccount(manager, ref) {
30080
30502
  );
30081
30503
  }
30082
30504
  function createStoreQuotaService(options) {
30083
- const { manager, logger: logger2 } = options;
30505
+ const { manager, logger: logger3 } = options;
30084
30506
  const credentials = options.credentials ?? createLocalAccountCredentials(manager, { repository: options.repository });
30085
30507
  const authorize = async (account, _signal, purpose = "required") => {
30086
30508
  const ref = account.rowRef;
@@ -30153,11 +30575,11 @@ function createStoreQuotaService(options) {
30153
30575
  };
30154
30576
  const fetchAccountQuota = createAuthorizedFetchAccountQuota({
30155
30577
  authorize: (account) => authorize(account),
30156
- logger: logger2,
30578
+ logger: logger3,
30157
30579
  transport: options.transport
30158
30580
  });
30159
30581
  const quotaManager = createLocationQuotaManager({
30160
- logger: logger2,
30582
+ logger: logger3,
30161
30583
  fetchAccountQuota,
30162
30584
  // Backoff and cache are per credential: a re-authenticated row starts
30163
30585
  // fresh instead of inheriting its predecessor's state.
@@ -30230,7 +30652,7 @@ function createStoreQuotaService(options) {
30230
30652
  (failure2) => failure2.rowId
30231
30653
  );
30232
30654
  failedRows = report === void 0 || failedIds.length === 0 || failedIds.some((id) => id === void 0) ? "all" : new Set(failedIds.filter((id) => id !== void 0));
30233
- logger2.debug("quota readings were not all persisted", {
30655
+ logger3.debug("quota readings were not all persisted", {
30234
30656
  error: error instanceof Error ? error.message : String(error)
30235
30657
  });
30236
30658
  }
@@ -30281,21 +30703,21 @@ import {
30281
30703
  unlinkSync as unlinkSync3,
30282
30704
  writeFileSync as writeFileSync2
30283
30705
  } from "node:fs";
30284
- import { homedir as homedir6, tmpdir } from "node:os";
30285
- import { dirname as dirname17, join as join11 } from "node:path";
30706
+ import { homedir as homedir6, tmpdir as tmpdir3 } from "node:os";
30707
+ import { dirname as dirname17, join as join13 } from "node:path";
30286
30708
  function getConfigDir4() {
30287
30709
  const platform = process.platform;
30288
30710
  if (platform === "win32") {
30289
- return join11(
30290
- process.env.APPDATA || join11(homedir6(), "AppData", "Roaming"),
30711
+ return join13(
30712
+ process.env.APPDATA || join13(homedir6(), "AppData", "Roaming"),
30291
30713
  "opencode"
30292
30714
  );
30293
30715
  }
30294
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join11(homedir6(), ".config");
30295
- return join11(xdgConfig2, "opencode");
30716
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join13(homedir6(), ".config");
30717
+ return join13(xdgConfig2, "opencode");
30296
30718
  }
30297
30719
  function getSignatureCacheFilePath() {
30298
- return join11(getConfigDir4(), "antigravity-signature-cache.json");
30720
+ return join13(getConfigDir4(), "antigravity-signature-cache.json");
30299
30721
  }
30300
30722
  var SignatureCache = class {
30301
30723
  // In-memory cache: key -> entry with signature and optional thinking text
@@ -30578,8 +31000,8 @@ var SignatureCache = class {
30578
31000
  last_write: now
30579
31001
  }
30580
31002
  };
30581
- const tmpPath = join11(
30582
- tmpdir(),
31003
+ const tmpPath = join13(
31004
+ tmpdir3(),
30583
31005
  `antigravity-cache-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`
30584
31006
  );
30585
31007
  writeFileSync2(tmpPath, JSON.stringify(cacheData, null, 2), "utf-8");
@@ -30935,9 +31357,9 @@ function clearSignatureCache(sessionId) {
30935
31357
  // src/plugin/image-saver.ts
30936
31358
  import { chmodSync as chmodSync4, existsSync as existsSync8, mkdirSync as mkdirSync5, writeFileSync as writeFileSync3 } from "node:fs";
30937
31359
  import { homedir as homedir7 } from "node:os";
30938
- import { join as join12 } from "node:path";
31360
+ import { join as join14 } from "node:path";
30939
31361
  function getImageOutputDir(outputDir) {
30940
- const resolved = outputDir ?? join12(homedir7(), ".opencode", "generated-images");
31362
+ const resolved = outputDir ?? join14(homedir7(), ".opencode", "generated-images");
30941
31363
  if (!existsSync8(resolved)) {
30942
31364
  mkdirSync5(resolved, { recursive: true, mode: 448 });
30943
31365
  }
@@ -30960,7 +31382,7 @@ function generateImageFilename(mimeType) {
30960
31382
  function saveImageToDisk(base64Data, mimeType, outputDir) {
30961
31383
  try {
30962
31384
  const resolvedOutputDir = getImageOutputDir(outputDir);
30963
- const filePath = join12(resolvedOutputDir, generateImageFilename(mimeType));
31385
+ const filePath = join14(resolvedOutputDir, generateImageFilename(mimeType));
30964
31386
  writeFileSync3(filePath, Buffer.from(base64Data, "base64"), { mode: 384 });
30965
31387
  chmodSync4(filePath, 384);
30966
31388
  return filePath;
@@ -31395,11 +31817,11 @@ data: ${JSON.stringify(syntheticUsage)}
31395
31817
  // src/plugin/gemini-dump.ts
31396
31818
  import { createHash as createHash12 } from "node:crypto";
31397
31819
  import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync6, writeFileSync as writeFileSync4 } from "node:fs";
31398
- import { tmpdir as tmpdir2 } from "node:os";
31399
- import { join as join13 } from "node:path";
31820
+ import { tmpdir as tmpdir4 } from "node:os";
31821
+ import { join as join15 } from "node:path";
31400
31822
  var DUMP_STATUS_TITLE = "## Gemini Dump Status";
31401
31823
  var DUMP_DIR_ENV = "OPENCODE_ANTIGRAVITY_GEMINI_DUMP_DIR";
31402
- var DEFAULT_DUMP_DIR = join13(tmpdir2(), "opencode-antigravity-gemini-dumps");
31824
+ var DEFAULT_DUMP_DIR = join15(tmpdir4(), "opencode-antigravity-gemini-dumps");
31403
31825
  var DUMP_DIR_MODE = 448;
31404
31826
  var DUMP_FILE_MODE = 384;
31405
31827
  var nextDumpId = 0;
@@ -31553,7 +31975,7 @@ function writeGeminiDump(input2) {
31553
31975
  nextDumpId += 1;
31554
31976
  const id = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${String(nextDumpId).padStart(5, "0")}-${input2.streaming ? "stream" : "json"}`;
31555
31977
  const dumpDir = getGeminiDumpDirectory();
31556
- const prefix = join13(dumpDir, id);
31978
+ const prefix = join15(dumpDir, id);
31557
31979
  mkdirSync6(dumpDir, { recursive: true, mode: DUMP_DIR_MODE });
31558
31980
  const context = {
31559
31981
  id,
@@ -31637,21 +32059,21 @@ import {
31637
32059
  unlinkSync as unlinkSync4,
31638
32060
  writeFileSync as writeFileSync5
31639
32061
  } from "node:fs";
31640
- import { join as join15 } from "node:path";
32062
+ import { join as join17 } from "node:path";
31641
32063
 
31642
32064
  // src/plugin/recovery/constants.ts
31643
32065
  import { homedir as homedir8 } from "node:os";
31644
- import { join as join14 } from "node:path";
32066
+ import { join as join16 } from "node:path";
31645
32067
  function getXdgData() {
31646
32068
  const platform = process.platform;
31647
32069
  if (platform === "win32") {
31648
- return process.env.APPDATA || join14(homedir8(), "AppData", "Roaming");
32070
+ return process.env.APPDATA || join16(homedir8(), "AppData", "Roaming");
31649
32071
  }
31650
- return process.env.XDG_DATA_HOME || join14(homedir8(), ".local", "share");
32072
+ return process.env.XDG_DATA_HOME || join16(homedir8(), ".local", "share");
31651
32073
  }
31652
- var OPENCODE_STORAGE = join14(getXdgData(), "opencode", "storage");
31653
- var MESSAGE_STORAGE = join14(OPENCODE_STORAGE, "message");
31654
- var PART_STORAGE = join14(OPENCODE_STORAGE, "part");
32074
+ var OPENCODE_STORAGE = join16(getXdgData(), "opencode", "storage");
32075
+ var MESSAGE_STORAGE = join16(OPENCODE_STORAGE, "message");
32076
+ var PART_STORAGE = join16(OPENCODE_STORAGE, "part");
31655
32077
  var THINKING_TYPES = /* @__PURE__ */ new Set([
31656
32078
  "thinking",
31657
32079
  "redacted_thinking",
@@ -31661,13 +32083,13 @@ var THINKING_TYPES = /* @__PURE__ */ new Set([
31661
32083
  // src/plugin/recovery/storage.ts
31662
32084
  function getMessageDir(sessionID) {
31663
32085
  if (!existsSync9(MESSAGE_STORAGE)) return "";
31664
- const directPath = join15(MESSAGE_STORAGE, sessionID);
32086
+ const directPath = join17(MESSAGE_STORAGE, sessionID);
31665
32087
  if (existsSync9(directPath)) {
31666
32088
  return directPath;
31667
32089
  }
31668
32090
  try {
31669
32091
  for (const dir of readdirSync2(MESSAGE_STORAGE)) {
31670
- const sessionPath = join15(MESSAGE_STORAGE, dir, sessionID);
32092
+ const sessionPath = join17(MESSAGE_STORAGE, dir, sessionID);
31671
32093
  if (existsSync9(sessionPath)) {
31672
32094
  return sessionPath;
31673
32095
  }
@@ -31684,7 +32106,7 @@ function readMessages(sessionID) {
31684
32106
  for (const file of readdirSync2(messageDir)) {
31685
32107
  if (!file.endsWith(".json")) continue;
31686
32108
  try {
31687
- const content = readFileSync7(join15(messageDir, file), "utf-8");
32109
+ const content = readFileSync7(join17(messageDir, file), "utf-8");
31688
32110
  messages.push(JSON.parse(content));
31689
32111
  } catch {
31690
32112
  }
@@ -31700,14 +32122,14 @@ function readMessages(sessionID) {
31700
32122
  });
31701
32123
  }
31702
32124
  function readParts(messageID) {
31703
- const partDir = join15(PART_STORAGE, messageID);
32125
+ const partDir = join17(PART_STORAGE, messageID);
31704
32126
  if (!existsSync9(partDir)) return [];
31705
32127
  const parts = [];
31706
32128
  try {
31707
32129
  for (const file of readdirSync2(partDir)) {
31708
32130
  if (!file.endsWith(".json")) continue;
31709
32131
  try {
31710
- const content = readFileSync7(join15(partDir, file), "utf-8");
32132
+ const content = readFileSync7(join17(partDir, file), "utf-8");
31711
32133
  parts.push(JSON.parse(content));
31712
32134
  } catch {
31713
32135
  }
@@ -31749,7 +32171,7 @@ function findMessagesWithOrphanThinking(sessionID) {
31749
32171
  return result;
31750
32172
  }
31751
32173
  function prependThinkingPart(sessionID, messageID) {
31752
- const partDir = join15(PART_STORAGE, messageID);
32174
+ const partDir = join17(PART_STORAGE, messageID);
31753
32175
  try {
31754
32176
  if (!existsSync9(partDir)) {
31755
32177
  mkdirSync7(partDir, { recursive: true });
@@ -31764,7 +32186,7 @@ function prependThinkingPart(sessionID, messageID) {
31764
32186
  synthetic: true
31765
32187
  };
31766
32188
  writeFileSync5(
31767
- join15(partDir, `${partId}.json`),
32189
+ join17(partDir, `${partId}.json`),
31768
32190
  JSON.stringify(part, null, 2)
31769
32191
  );
31770
32192
  return true;
@@ -31773,14 +32195,14 @@ function prependThinkingPart(sessionID, messageID) {
31773
32195
  }
31774
32196
  }
31775
32197
  function stripThinkingParts(messageID) {
31776
- const partDir = join15(PART_STORAGE, messageID);
32198
+ const partDir = join17(PART_STORAGE, messageID);
31777
32199
  if (!existsSync9(partDir)) return false;
31778
32200
  let anyRemoved = false;
31779
32201
  try {
31780
32202
  for (const file of readdirSync2(partDir)) {
31781
32203
  if (!file.endsWith(".json")) continue;
31782
32204
  try {
31783
- const filePath = join15(partDir, file);
32205
+ const filePath = join17(partDir, file);
31784
32206
  const content = readFileSync7(filePath, "utf-8");
31785
32207
  const part = JSON.parse(content);
31786
32208
  if (THINKING_TYPES.has(part.type)) {
@@ -33545,6 +33967,7 @@ var NATIVE_GOOGLE_ERROR_MESSAGES = {
33545
33967
  operator_policy: "Antigravity account pool is unavailable under the operator quota policy. Adjust /antigravity-killswitch or refresh quota.",
33546
33968
  soft_quota: "Antigravity account pool is unavailable under the quota protection policy. Add accounts, wait for quota reset, or disable soft quota protection.",
33547
33969
  pool_unavailable: "Antigravity account pool has no account available within the configured wait limit. Add accounts with `opencode auth login` or wait for quota reset.",
33970
+ model_unavailable: "The requested Antigravity model is not available to the configured accounts. Choose another model.",
33548
33971
  missing_access_token: "Missing access token. Run `opencode auth login` to reauthenticate.",
33549
33972
  empty_response: "Antigravity returned an empty response after the internal retry attempts."
33550
33973
  };
@@ -35580,12 +36003,12 @@ async function startOAuthListener({
35580
36003
  let resolveCallback;
35581
36004
  let rejectCallback;
35582
36005
  let timeoutHandle;
35583
- const callbackPromise = new Promise((resolve18, reject) => {
36006
+ const callbackPromise = new Promise((resolve20, reject) => {
35584
36007
  resolveCallback = (url) => {
35585
36008
  if (settled) return;
35586
36009
  settled = true;
35587
36010
  if (timeoutHandle) clearTimeout(timeoutHandle);
35588
- resolve18(url);
36011
+ resolve20(url);
35589
36012
  };
35590
36013
  rejectCallback = (error) => {
35591
36014
  if (settled) return;
@@ -35744,7 +36167,7 @@ async function startOAuthListener({
35744
36167
  });
35745
36168
  });
35746
36169
  const bindAddress = getBindAddress();
35747
- await new Promise((resolve18, reject) => {
36170
+ await new Promise((resolve20, reject) => {
35748
36171
  const handleError = (error) => {
35749
36172
  server.off("error", handleError);
35750
36173
  if (error.code === "EADDRINUSE") {
@@ -35760,7 +36183,7 @@ async function startOAuthListener({
35760
36183
  server.once("error", handleError);
35761
36184
  server.listen(port, bindAddress, () => {
35762
36185
  server.off("error", handleError);
35763
- resolve18();
36186
+ resolve20();
35764
36187
  });
35765
36188
  });
35766
36189
  server.on("error", (error) => {
@@ -35768,7 +36191,7 @@ async function startOAuthListener({
35768
36191
  });
35769
36192
  return {
35770
36193
  waitForCallback: () => callbackPromise,
35771
- close: () => new Promise((resolve18, reject) => {
36194
+ close: () => new Promise((resolve20, reject) => {
35772
36195
  server.close((error) => {
35773
36196
  if (error && error.code !== "ERR_SERVER_NOT_RUNNING") {
35774
36197
  reject(error);
@@ -35777,7 +36200,7 @@ async function startOAuthListener({
35777
36200
  if (!settled) {
35778
36201
  rejectCallback(new Error("OAuth listener closed before callback"));
35779
36202
  }
35780
- resolve18();
36203
+ resolve20();
35781
36204
  });
35782
36205
  })
35783
36206
  };
@@ -35788,7 +36211,7 @@ async function startOAuthListener({
35788
36211
  }
35789
36212
 
35790
36213
  // src/plugin/session-context.ts
35791
- import { resolve as resolve11 } from "node:path";
36214
+ import { resolve as resolve13 } from "node:path";
35792
36215
  import { pathToFileURL } from "node:url";
35793
36216
  var FALLBACK_SESSION_KEY = "__default__";
35794
36217
  function extractOpenCodeSessionIdentity(headers) {
@@ -35802,7 +36225,7 @@ var AgySessionRegistry = class {
35802
36225
  requestSessions;
35803
36226
  parentSessionIds = /* @__PURE__ */ new Map();
35804
36227
  constructor(directory, options = {}) {
35805
- const workspaceUri = directory ? pathToFileURL(resolve11(directory)).href : "";
36228
+ const workspaceUri = directory ? pathToFileURL(resolve13(directory)).href : "";
35806
36229
  this.requestSessions = new AgyRequestSessionStore(workspaceUri, options);
35807
36230
  }
35808
36231
  getOrCreate(identity) {
@@ -36427,10 +36850,10 @@ async function retainResponseLifetime(response, cancellation) {
36427
36850
  cancellation.release();
36428
36851
  throw error;
36429
36852
  }
36430
- let resolve18 = () => {
36853
+ let resolve20 = () => {
36431
36854
  };
36432
36855
  const settled = new Promise((done) => {
36433
- resolve18 = done;
36856
+ resolve20 = done;
36434
36857
  });
36435
36858
  let stopping = false;
36436
36859
  let finished = false;
@@ -36440,7 +36863,7 @@ async function retainResponseLifetime(response, cancellation) {
36440
36863
  finished = true;
36441
36864
  cancellation.signal.removeEventListener("abort", abort);
36442
36865
  cancellation.release();
36443
- resolve18();
36866
+ resolve20();
36444
36867
  };
36445
36868
  const abort = () => {
36446
36869
  if (finished || stopping) return;
@@ -36509,8 +36932,8 @@ function createAfterHandoff(work, signals, onFailure) {
36509
36932
  let running = false;
36510
36933
  let resolveCompletion = () => {
36511
36934
  };
36512
- const completion = new Promise((resolve18) => {
36513
- resolveCompletion = resolve18;
36935
+ const completion = new Promise((resolve20) => {
36936
+ resolveCompletion = resolve20;
36514
36937
  });
36515
36938
  const finish = () => {
36516
36939
  if (finished) return;
@@ -36557,14 +36980,14 @@ function createAfterHandoff(work, signals, onFailure) {
36557
36980
  };
36558
36981
  }
36559
36982
  function publishResponse(dispatch) {
36560
- return new Promise((resolve18, reject) => {
36983
+ return new Promise((resolve20, reject) => {
36561
36984
  let acknowledge;
36562
36985
  void Promise.resolve().then(
36563
36986
  () => dispatch((callback) => {
36564
36987
  acknowledge = callback;
36565
36988
  })
36566
36989
  ).then((response) => {
36567
- resolve18(response);
36990
+ resolve20(response);
36568
36991
  acknowledge?.();
36569
36992
  }, reject);
36570
36993
  });
@@ -36666,7 +37089,7 @@ function formatWaitTime(ms) {
36666
37089
  return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
36667
37090
  }
36668
37091
  function sleep4(ms, signal) {
36669
- return new Promise((resolve18, reject) => {
37092
+ return new Promise((resolve20, reject) => {
36670
37093
  if (signal?.aborted) {
36671
37094
  reject(
36672
37095
  signal.reason instanceof Error ? signal.reason : new Error("Aborted")
@@ -36675,7 +37098,7 @@ function sleep4(ms, signal) {
36675
37098
  }
36676
37099
  const timeout = setTimeout(() => {
36677
37100
  cleanup2();
36678
- resolve18();
37101
+ resolve20();
36679
37102
  }, ms);
36680
37103
  const onAbort = () => {
36681
37104
  cleanup2();
@@ -36931,6 +37354,7 @@ function createRequestExecutor(deps) {
36931
37354
  let localRecaptureUsed = false;
36932
37355
  const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1e3;
36933
37356
  let allAccountsBlockedAt;
37357
+ const modelUnavailableIndexes = /* @__PURE__ */ new Set();
36934
37358
  while (true) {
36935
37359
  await assertAdmission();
36936
37360
  checkAborted();
@@ -36994,6 +37418,26 @@ function createRequestExecutor(deps) {
36994
37418
  const killedIndexes = eligibleIndexes === null ? void 0 : new Set(
36995
37419
  accountManager.getAccounts().map((entry) => entry.index).filter((index) => !eligibleIndexes.has(index))
36996
37420
  );
37421
+ if (modelUnavailableIndexes.size > 0) {
37422
+ const candidates = accountManager.getEnabledAccounts().filter(
37423
+ (entry) => eligibleIndexes === null || eligibleIndexes.has(entry.index)
37424
+ );
37425
+ if (candidates.length > 0 && candidates.every((entry) => modelUnavailableIndexes.has(entry.index))) {
37426
+ pushDebug(
37427
+ `model-unavailable: all ${candidates.length} eligible account(s) skipped`
37428
+ );
37429
+ log16.warn("model-unavailable-all-accounts", {
37430
+ family,
37431
+ model,
37432
+ accounts: candidates.length
37433
+ });
37434
+ return createNativeGoogleErrorResponse({
37435
+ status: 412,
37436
+ reason: "model_unavailable"
37437
+ });
37438
+ }
37439
+ }
37440
+ const excludedIndexes = modelUnavailableIndexes.size === 0 ? killedIndexes : /* @__PURE__ */ new Set([...killedIndexes ?? [], ...modelUnavailableIndexes]);
36997
37441
  let account = accountManager.getCurrentOrNextForFamily(
36998
37442
  family,
36999
37443
  model,
@@ -37002,7 +37446,7 @@ function createRequestExecutor(deps) {
37002
37446
  config.soft_quota_threshold_percent,
37003
37447
  softQuotaCacheTtlMs,
37004
37448
  accountSessionIdentity,
37005
- killedIndexes
37449
+ excludedIndexes
37006
37450
  );
37007
37451
  if (account && eligibleIndexes !== null && !eligibleIndexes.has(account.index)) {
37008
37452
  pushDebug(
@@ -37469,6 +37913,7 @@ function createRequestExecutor(deps) {
37469
37913
  };
37470
37914
  let apiRequestCount = 0;
37471
37915
  let shouldSwitchAccount = false;
37916
+ let skippedForModelUnavailable = false;
37472
37917
  if (account.fingerprint) {
37473
37918
  pushDebug(
37474
37919
  `fingerprint: deviceId=${account.fingerprint.deviceId.slice(0, 8)}...`
@@ -37848,6 +38293,37 @@ function createRequestExecutor(deps) {
37848
38293
  shouldSwitchAccount = true;
37849
38294
  break;
37850
38295
  }
38296
+ if (response.status === 404 && currentEndpoint === ANTIGRAVITY_ENDPOINT_DAILY) {
38297
+ const notFoundBody = await deadline.wait(
38298
+ () => response.clone().text().catch(() => "")
38299
+ );
38300
+ const unavailable = parseModelUnavailableError(notFoundBody);
38301
+ if (unavailable) {
38302
+ if (tokenConsumed) {
38303
+ trackers.token.refund(account.index);
38304
+ tokenConsumed = false;
38305
+ }
38306
+ const reasonCodes = unavailable.reasons.length > 0 ? unavailable.reasons.join(",") : "none";
38307
+ const note = `model-unavailable idx=${account.index} status=${unavailable.status} reasons=${reasonCodes}`;
38308
+ pushDebug(note);
38309
+ debug.logAntigravityDebugResponse(debugContext, response, {
38310
+ note
38311
+ });
38312
+ log16.info("model-unavailable", {
38313
+ accountIndex: account.index,
38314
+ family,
38315
+ model,
38316
+ status: unavailable.status,
38317
+ reasons: unavailable.reasons
38318
+ });
38319
+ void response.body?.cancel().catch(() => {
38320
+ });
38321
+ modelUnavailableIndexes.add(account.index);
38322
+ skippedForModelUnavailable = true;
38323
+ shouldSwitchAccount = true;
38324
+ break;
38325
+ }
38326
+ }
37851
38327
  const quotaKey = getQuotaKey(family, model);
37852
38328
  retryState.resetRateLimitState(account.index, quotaKey);
37853
38329
  retryState.resetAccountFailureState(account.index);
@@ -37914,7 +38390,7 @@ function createRequestExecutor(deps) {
37914
38390
  break;
37915
38391
  }
37916
38392
  }
37917
- const shouldRetryEndpoint = response.status === 403 || response.status === 404 || response.status >= 500;
38393
+ const shouldRetryEndpoint = response.status === 404 || response.status >= 500;
37918
38394
  if (shouldRetryEndpoint && i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
37919
38395
  await logResponseBody2(debugContext, response, response.status);
37920
38396
  lastFailure = createFailureContext(response);
@@ -38165,6 +38641,9 @@ function createRequestExecutor(deps) {
38165
38641
  }
38166
38642
  }
38167
38643
  }
38644
+ if (shouldSwitchAccount && skippedForModelUnavailable) {
38645
+ continue;
38646
+ }
38168
38647
  if (shouldSwitchAccount) {
38169
38648
  accountSwitchCount++;
38170
38649
  if (accountSwitchCount > maxAccountSwitches) {
@@ -38367,6 +38846,32 @@ function createRequestExecutor(deps) {
38367
38846
  dispose
38368
38847
  };
38369
38848
  }
38849
+ var ERROR_REASON_CODE = /^[A-Za-z0-9_.-]{1,128}$/;
38850
+ function parseModelUnavailableError(bodyText) {
38851
+ let body;
38852
+ try {
38853
+ body = JSON.parse(bodyText);
38854
+ } catch {
38855
+ return null;
38856
+ }
38857
+ const envelope = Array.isArray(body) ? body[0] : body;
38858
+ if (!envelope || typeof envelope !== "object") return null;
38859
+ const error = envelope.error;
38860
+ if (!error || typeof error !== "object") return null;
38861
+ if (error.status !== "NOT_FOUND") return null;
38862
+ const details = error.details;
38863
+ const reasons = [];
38864
+ if (Array.isArray(details)) {
38865
+ for (const detail of details) {
38866
+ if (!detail || typeof detail !== "object") continue;
38867
+ const reason = detail.reason;
38868
+ if (typeof reason === "string" && ERROR_REASON_CODE.test(reason)) {
38869
+ reasons.push(reason);
38870
+ }
38871
+ }
38872
+ }
38873
+ return { status: "NOT_FOUND", reasons };
38874
+ }
38370
38875
  function extractRateLimitBodyInfo(body) {
38371
38876
  if (!body || typeof body !== "object") return { retryDelayMs: null };
38372
38877
  const error = body.error;
@@ -38419,8 +38924,8 @@ function extractRateLimitBodyInfo(body) {
38419
38924
  }
38420
38925
  }
38421
38926
  if (message) {
38422
- const afterMatch = message.match(/reset after\s+([0-9hms.]+)/i);
38423
- const rawDuration = afterMatch?.[1];
38927
+ const reset = message.match(/(?:reset after|resets? in)\s+([0-9hms.]+)/i);
38928
+ const rawDuration = reset?.[1];
38424
38929
  if (rawDuration) {
38425
38930
  const parsed = parseDurationToMs(rawDuration);
38426
38931
  if (parsed !== null) {
@@ -39101,13 +39606,13 @@ async function buildLocationRuntime(options, scope) {
39101
39606
  );
39102
39607
  }
39103
39608
  let config;
39104
- const logger2 = createLocationLogger({
39609
+ const logger3 = createLocationLogger({
39105
39610
  sink: options.logSink,
39106
39611
  sinkEnabled: () => config?.config.debug_tui === true
39107
39612
  });
39108
- const log16 = logger2.createLogger("runtime");
39613
+ const log16 = logger3.createLogger("runtime");
39109
39614
  config = createLocationConfig(options.directory, {
39110
- logger: logger2.createLogger("config")
39615
+ logger: logger3.createLogger("config")
39111
39616
  });
39112
39617
  const debug = createLocationDebug(config.config);
39113
39618
  scope.add({ dispose: () => debug.close() }, "consumer");
@@ -39118,7 +39623,7 @@ async function buildLocationRuntime(options, scope) {
39118
39623
  });
39119
39624
  scope.add(operatorSettings, "consumer");
39120
39625
  const applyOperatorSettings = () => {
39121
- logger2.setLevel(operatorSettings.get().log_level);
39626
+ logger3.setLevel(operatorSettings.get().log_level);
39122
39627
  };
39123
39628
  applyOperatorSettings();
39124
39629
  const signatureOptions = {
@@ -39145,7 +39650,7 @@ async function buildLocationRuntime(options, scope) {
39145
39650
  }));
39146
39651
  };
39147
39652
  const quotaManager = createLocationQuotaManager({
39148
- logger: logger2.createLogger("quota"),
39653
+ logger: logger3.createLogger("quota"),
39149
39654
  fetchAccountQuota: options.mayRun ? async (account, signal, purpose) => {
39150
39655
  if (!await options.mayRun?.()) throw new Error(VAULT_ACCOUNT_REMEDY);
39151
39656
  return purpose === "advisory" ? options.fetchAccountQuota(account, signal, purpose) : options.fetchAccountQuota(account, signal);
@@ -39175,7 +39680,7 @@ async function buildLocationRuntime(options, scope) {
39175
39680
  ...options.random ? { random: options.random } : {},
39176
39681
  ...options.acquireLock ? { acquireLock: options.acquireLock } : {},
39177
39682
  healthScore: options.healthScore ?? null,
39178
- logger: logger2.createLogger("background-quota")
39683
+ logger: logger3.createLogger("background-quota")
39179
39684
  });
39180
39685
  const poller = backgroundQuotaRefresh;
39181
39686
  scope.add({ dispose: () => poller.dispose() }, "producer");
@@ -39207,7 +39712,7 @@ async function buildLocationRuntime(options, scope) {
39207
39712
  if (!view || !config?.config.proactive_token_refresh) return;
39208
39713
  const queue2 = createLocationProactiveRefreshQueue(
39209
39714
  {
39210
- logger: logger2.createLogger("refresh-queue"),
39715
+ logger: logger3.createLogger("refresh-queue"),
39211
39716
  refreshToken: options.refreshToken
39212
39717
  },
39213
39718
  {
@@ -39232,7 +39737,7 @@ async function buildLocationRuntime(options, scope) {
39232
39737
  const runtimeConfig2 = config;
39233
39738
  return {
39234
39739
  directory: options.directory,
39235
- logger: logger2,
39740
+ logger: logger3,
39236
39741
  config: runtimeConfig2,
39237
39742
  debug,
39238
39743
  dump,
@@ -39499,7 +40004,7 @@ function createVaultSelectionState(options) {
39499
40004
  report(error);
39500
40005
  }
39501
40006
  };
39502
- const flush = () => {
40007
+ const flush2 = () => {
39503
40008
  writing = writing.then(async () => {
39504
40009
  for (const row of [...changed]) await writeRow(row);
39505
40010
  });
@@ -39515,7 +40020,7 @@ function createVaultSelectionState(options) {
39515
40020
  accessVerdict: mark,
39516
40021
  fingerprint: mark,
39517
40022
  requestSave: () => {
39518
- void flush();
40023
+ void flush2();
39519
40024
  }
39520
40025
  },
39521
40026
  admitted(row, attribution) {
@@ -39538,7 +40043,7 @@ function createVaultSelectionState(options) {
39538
40043
  }
39539
40044
  }
39540
40045
  },
39541
- flush,
40046
+ flush: flush2,
39542
40047
  recordQuota(attribution, quota, signal) {
39543
40048
  return options.source.commitState(
39544
40049
  attribution,
@@ -39711,7 +40216,7 @@ async function checkVaultQuota(input2) {
39711
40216
 
39712
40217
  // src/plugin/vault-custody.ts
39713
40218
  import { chmod as chmod3, mkdir as mkdir11, readFile as readFile9 } from "node:fs/promises";
39714
- import { dirname as dirname18, join as join16 } from "node:path";
40219
+ import { dirname as dirname18, join as join18 } from "node:path";
39715
40220
 
39716
40221
  // src/plugin/vault-insula-quota.ts
39717
40222
  var windows = [
@@ -39761,12 +40266,12 @@ var OPENCODE_VAULT_HOST = "opencode";
39761
40266
  var OPENCODE_VAULT_ENROLLMENT_NAME = getAntigravityVaultEnrollmentName(OPENCODE_VAULT_HOST);
39762
40267
  var OPENCODE_VAULT_DIR_NAME = "antigravity-auth-vault";
39763
40268
  function openCodeVaultPaths(accountFile) {
39764
- const dir = join16(dirname18(accountFile), OPENCODE_VAULT_DIR_NAME);
40269
+ const dir = join18(dirname18(accountFile), OPENCODE_VAULT_DIR_NAME);
39765
40270
  return {
39766
40271
  dir,
39767
- modeFile: join16(dir, "opencode-mode.json"),
39768
- rosterFile: join16(dir, "opencode-roster.json"),
39769
- stateFile: join16(dir, "opencode-state.json")
40272
+ modeFile: join18(dir, "opencode-mode.json"),
40273
+ rosterFile: join18(dir, "opencode-roster.json"),
40274
+ stateFile: join18(dir, "opencode-state.json")
39770
40275
  };
39771
40276
  }
39772
40277
  async function ensureVaultDir(dir) {
@@ -39941,11 +40446,11 @@ function createOpenCodeVaultCustody(options) {
39941
40446
  ].join("\n");
39942
40447
  const waitForApproval = async () => {
39943
40448
  while (!closed) {
39944
- await new Promise((resolve18) => {
40449
+ await new Promise((resolve20) => {
39945
40450
  const done = () => {
39946
40451
  clearTimeout(timer);
39947
40452
  cancelWait = void 0;
39948
- resolve18();
40453
+ resolve20();
39949
40454
  };
39950
40455
  const timer = setTimeout(done, 2e3);
39951
40456
  timer.unref?.();
@@ -40114,6 +40619,9 @@ async function refusalOr(step) {
40114
40619
  }
40115
40620
  return "Done. Start a new request to use the change.";
40116
40621
  }
40622
+ function isUnsupportedEnrollment(status) {
40623
+ return status.state === "unavailable" && status.code === UNSUPPORTED_VAULT_CODE;
40624
+ }
40117
40625
  function describeEnrollment(status) {
40118
40626
  switch (status.state) {
40119
40627
  case "idle":
@@ -40127,7 +40635,7 @@ function describeEnrollment(status) {
40127
40635
  case "blocked":
40128
40636
  return `blocked (${status.code})`;
40129
40637
  case "unavailable":
40130
- return `vault unavailable (${status.code})`;
40638
+ return isUnsupportedEnrollment(status) ? "this vault can't connect plugins yet" : `vault unavailable (${status.code})`;
40131
40639
  case "busy":
40132
40640
  return "another setup step is running";
40133
40641
  }
@@ -40194,10 +40702,15 @@ function enrollmentGuidance(status) {
40194
40702
  return [
40195
40703
  "Resolve the enrollment problem with the vault operator, then request vault access again."
40196
40704
  ];
40197
- if (status.state === "unavailable")
40705
+ if (status.state === "unavailable") {
40706
+ if (isUnsupportedEnrollment(status))
40707
+ return [
40708
+ "This Claustrum vault is too old to connect plugins. Ask the vault operator to update Claustrum, or keep using your local accounts."
40709
+ ];
40198
40710
  return [
40199
40711
  "Check that the vault is running and its connection file is available, then request vault access again."
40200
40712
  ];
40713
+ }
40201
40714
  if (status.state === "busy")
40202
40715
  return [
40203
40716
  "Another enrollment operation is running. OpenCode will keep checking its outcome in the background."
@@ -40574,7 +41087,7 @@ function createGaReauthorize(input2) {
40574
41087
  const continuations = /* @__PURE__ */ new Set();
40575
41088
  const shutdown = new AbortController();
40576
41089
  let disposed = false;
40577
- const waitForRedirect = (code2) => new Promise((resolve18, reject) => {
41090
+ const waitForRedirect = (code2) => new Promise((resolve20, reject) => {
40578
41091
  const detach = () => shutdown.signal.removeEventListener("abort", abort);
40579
41092
  const abort = () => {
40580
41093
  detach();
@@ -40585,7 +41098,7 @@ function createGaReauthorize(input2) {
40585
41098
  void code2.then(
40586
41099
  (value) => {
40587
41100
  detach();
40588
- resolve18(value);
41101
+ resolve20(value);
40589
41102
  },
40590
41103
  (error) => {
40591
41104
  detach();
@@ -40993,8 +41506,8 @@ function gaEngineCollaborators(input2) {
40993
41506
  async function createGaLocalRequestPipeline(input2) {
40994
41507
  const runtime = input2.runtime;
40995
41508
  await input2.assertAdmission?.();
40996
- const logger2 = runtime.logger.createLogger("request");
40997
- const advisory = createAdvisoryRepositoryOwner(input2.repository, logger2);
41509
+ const logger3 = runtime.logger.createLogger("request");
41510
+ const advisory = createAdvisoryRepositoryOwner(input2.repository, logger3);
40998
41511
  const manager = await loadAccountManagerFromRepository(advisory.repository, {
40999
41512
  onWriteError: advisory.owns
41000
41513
  });
@@ -41006,7 +41519,7 @@ async function createGaLocalRequestPipeline(input2) {
41006
41519
  runtime,
41007
41520
  overrides: input2.overrides,
41008
41521
  routes: input2.routes,
41009
- logger: logger2
41522
+ logger: logger3
41010
41523
  }),
41011
41524
  accounts: manager,
41012
41525
  ...input2.assertAdmission ? { assertAdmission: input2.assertAdmission } : {},
@@ -41016,7 +41529,7 @@ async function createGaLocalRequestPipeline(input2) {
41016
41529
  refreshQuotaAfterSuccess: createLocalQuotaRefresh(
41017
41530
  manager,
41018
41531
  runtime.quotaManager,
41019
- logger2
41532
+ logger3
41020
41533
  )
41021
41534
  }),
41022
41535
  // The trackers the manager selects with, so recorded outcomes steer
@@ -41060,13 +41573,13 @@ async function createGaVaultRequestPipeline(input2) {
41060
41573
  const { pool } = input2;
41061
41574
  await input2.assertAdmission?.();
41062
41575
  await pool.sync();
41063
- const logger2 = input2.runtime.logger.createLogger("request");
41576
+ const logger3 = input2.runtime.logger.createLogger("request");
41064
41577
  const executor = createRequestExecutor({
41065
41578
  ...gaEngineCollaborators({
41066
41579
  runtime: input2.runtime,
41067
41580
  overrides: input2.overrides,
41068
41581
  routes: input2.routes,
41069
- logger: logger2
41582
+ logger: logger3
41070
41583
  }),
41071
41584
  accounts: pool.selector,
41072
41585
  ...input2.assertAdmission ? { assertAdmission: input2.assertAdmission } : {},
@@ -43165,11 +43678,11 @@ var OPENCODE2_VAULT_AUTH_LABEL = "Use approved Antigravity vault";
43165
43678
  var GA_POOL_METHOD_ID = "antigravity-auth-pool-browser";
43166
43679
  var LOGIN_FAILED = "The Antigravity pool login could not be completed.";
43167
43680
  function abortable(pending, signal) {
43168
- return new Promise((resolve18, reject) => {
43681
+ return new Promise((resolve20, reject) => {
43169
43682
  const abort = () => reject(signal.reason);
43170
43683
  if (signal.aborted) abort();
43171
43684
  else signal.addEventListener("abort", abort, { once: true });
43172
- void pending.then(resolve18, reject).finally(() => {
43685
+ void pending.then(resolve20, reject).finally(() => {
43173
43686
  signal.removeEventListener("abort", abort);
43174
43687
  });
43175
43688
  });
@@ -43537,11 +44050,11 @@ async function startGaLoopbackBridge(options) {
43537
44050
  }
43538
44051
  }
43539
44052
  };
43540
- await new Promise((resolve18, reject) => {
44053
+ await new Promise((resolve20, reject) => {
43541
44054
  server.once("error", reject);
43542
44055
  server.listen(0, BRIDGE_HOST, () => {
43543
44056
  server.off("error", reject);
43544
- resolve18();
44057
+ resolve20();
43545
44058
  });
43546
44059
  });
43547
44060
  server.unref();
@@ -43645,8 +44158,8 @@ async function startGaLoopbackBridge(options) {
43645
44158
  disposal = (async () => {
43646
44159
  for (const { timer } of queued.values()) clearTimeout(timer);
43647
44160
  queued.clear();
43648
- const closed = new Promise((resolve18) => {
43649
- server.close(() => resolve18());
44161
+ const closed = new Promise((resolve20) => {
44162
+ server.close(() => resolve20());
43650
44163
  });
43651
44164
  for (const controller of running) {
43652
44165
  controller.abort(
@@ -43710,9 +44223,9 @@ async function pipeResponse(upstream, response, onFailure, onHandoff) {
43710
44223
  return;
43711
44224
  }
43712
44225
  if (!response.write(value) && !response.destroyed) {
43713
- await new Promise((resolve18) => {
43714
- response.once("drain", resolve18);
43715
- response.once("close", resolve18);
44226
+ await new Promise((resolve20) => {
44227
+ response.once("drain", resolve20);
44228
+ response.once("close", resolve20);
43716
44229
  });
43717
44230
  }
43718
44231
  if (response.destroyed) {
@@ -43899,9 +44412,9 @@ function createGaRpcActivation(options) {
43899
44412
  const { email: _email, quota, ...rest } = account;
43900
44413
  const entry = (value) => {
43901
44414
  if (value === void 0) return void 0;
43902
- const { remainingFraction: _fraction, windows: windows2, ...fields } = value;
43903
- return windows2 === void 0 ? fields : {
43904
- ...fields,
44415
+ const { remainingFraction: _fraction, windows: windows2, ...fields2 } = value;
44416
+ return windows2 === void 0 ? fields2 : {
44417
+ ...fields2,
43905
44418
  windows: windows2.map(
43906
44419
  ({ remainingFraction: _windowFraction, ...window }) => window
43907
44420
  )
@@ -44367,12 +44880,12 @@ function createGaAntigravityPlugin(overrides = {}) {
44367
44880
 
44368
44881
  // src/plugin/index.ts
44369
44882
  import { createHash as createHash20, randomUUID as randomUUID21 } from "node:crypto";
44370
- import { join as join31, resolve as resolve17 } from "node:path";
44883
+ import { join as join33, resolve as resolve19 } from "node:path";
44371
44884
 
44372
44885
  // src/cli.ts
44373
44886
  import { execFile } from "node:child_process";
44374
44887
  import { realpathSync as realpathSync3 } from "node:fs";
44375
- import { resolve as resolve14 } from "node:path";
44888
+ import { resolve as resolve16 } from "node:path";
44376
44889
  import { createInterface } from "node:readline/promises";
44377
44890
  import { fileURLToPath as fileURLToPath2 } from "node:url";
44378
44891
  import { promisify } from "node:util";
@@ -44416,7 +44929,7 @@ async function performOAuthLogin(request, deps) {
44416
44929
 
44417
44930
  // src/setup.ts
44418
44931
  import { lstat as lstat5, readFile as readFile13 } from "node:fs/promises";
44419
- import { join as join22, resolve as resolve13 } from "node:path";
44932
+ import { join as join24, resolve as resolve15 } from "node:path";
44420
44933
 
44421
44934
  // src/common-auth-embedded/auth-menu/ansi.js
44422
44935
  var ANSI2 = {
@@ -44584,7 +45097,7 @@ async function select2(terminal, items, options) {
44584
45097
  writeLine("");
44585
45098
  renderedLines = lines;
44586
45099
  };
44587
- return new Promise((resolve18) => {
45100
+ return new Promise((resolve20) => {
44588
45101
  const wasRaw = stdin.isRaw ?? false;
44589
45102
  const cleanup2 = () => {
44590
45103
  if (cleaned)
@@ -44604,7 +45117,7 @@ async function select2(terminal, items, options) {
44604
45117
  };
44605
45118
  const finish = (value) => {
44606
45119
  cleanup2();
44607
- resolve18(value);
45120
+ resolve20(value);
44608
45121
  };
44609
45122
  const onSignal = () => finish(null);
44610
45123
  const onKey = (data) => {
@@ -44644,7 +45157,7 @@ async function select2(terminal, items, options) {
44644
45157
  stdin.setRawMode(true);
44645
45158
  } catch {
44646
45159
  cleanup2();
44647
- resolve18(null);
45160
+ resolve20(null);
44648
45161
  return;
44649
45162
  }
44650
45163
  stdin.resume();
@@ -44658,7 +45171,7 @@ async function select2(terminal, items, options) {
44658
45171
  import { createHash as createHash15, randomBytes as randomBytes6, randomUUID as randomUUID17 } from "node:crypto";
44659
45172
  import { constants as fsConstants2 } from "node:fs";
44660
45173
  import { chmod as chmod4, mkdir as mkdir13, open as open10, readFile as readFile11, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
44661
- import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute3, join as join18, resolve as resolve12 } from "node:path";
45174
+ import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute3, join as join20, resolve as resolve14 } from "node:path";
44662
45175
  import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
44663
45176
 
44664
45177
  // src/common-auth-embedded/fs/lock-constants.js
@@ -44680,7 +45193,7 @@ var WRITER_LOCK_CONSTANTS2 = Object.freeze({
44680
45193
  // src/common-auth-embedded/fs/refresh-file-lock.js
44681
45194
  import { randomUUID as randomUUID16 } from "node:crypto";
44682
45195
  import { mkdir as mkdir12, open as open9, readFile as readFile10, rename as rename8, rm as rm5, stat as stat6 } from "node:fs/promises";
44683
- import { dirname as dirname19, join as join17 } from "node:path";
45196
+ import { dirname as dirname19, join as join19 } from "node:path";
44684
45197
 
44685
45198
  // src/common-auth-embedded/fs/with-lock.js
44686
45199
  function lockPathFor2(target, name) {
@@ -44715,7 +45228,7 @@ function acquireRefreshFileLock2(options) {
44715
45228
  }
44716
45229
  async function acquireRefreshFileLockWithClock2(options) {
44717
45230
  const lockPath = lockPathFor2(options.path, options.name);
44718
- const legacyOwnerPath = join17(lockPath, "owner.json");
45231
+ const legacyOwnerPath = join19(lockPath, "owner.json");
44719
45232
  const ownerId = randomUUID16();
44720
45233
  const now = options.now ?? Date.now;
44721
45234
  let renewTimer = null;
@@ -44723,8 +45236,8 @@ async function acquireRefreshFileLockWithClock2(options) {
44723
45236
  let releaseConfirmed = false;
44724
45237
  let loss;
44725
45238
  let resolveLoss;
44726
- const lostPromise = new Promise((resolve18) => {
44727
- resolveLoss = resolve18;
45239
+ const lostPromise = new Promise((resolve20) => {
45240
+ resolveLoss = resolve20;
44728
45241
  });
44729
45242
  function notifyTimerStep(event) {
44730
45243
  try {
@@ -44758,7 +45271,7 @@ async function acquireRefreshFileLockWithClock2(options) {
44758
45271
  let terminalIOError;
44759
45272
  let renewalInFlight = null;
44760
45273
  const evictPath = `${lockPath}.evicting`;
44761
- const evictOwnerPath = join17(evictPath, "owner.json");
45274
+ const evictOwnerPath = join19(evictPath, "owner.json");
44762
45275
  const evictOwnerId = randomUUID16();
44763
45276
  const EVICT_TTL = 5e3;
44764
45277
  const MAX_STEAL_ATTEMPTS = 8;
@@ -44881,7 +45394,7 @@ async function acquireRefreshFileLockWithClock2(options) {
44881
45394
  }
44882
45395
  }
44883
45396
  async function backoff() {
44884
- await new Promise((resolve18) => setTimeout(resolve18, Math.floor(Math.random() * 4)));
45397
+ await new Promise((resolve20) => setTimeout(resolve20, Math.floor(Math.random() * 4)));
44885
45398
  }
44886
45399
  async function readLockState(notifyReady = true) {
44887
45400
  if (notifyReady && options.onStep)
@@ -45329,7 +45842,13 @@ var ENROLLMENT_SCHEMA2 = 1;
45329
45842
  var ENROLLMENT_FILE_MAX_BYTES2 = 16 * 1024;
45330
45843
  var ENROLLMENT_LOCK_TTL_MS2 = 3e4;
45331
45844
  var TOKEN_RE2 = /^[0-9a-f]{64}$/;
45845
+ var UNSUPPORTED_ENROLLMENT_CODE2 = "unknown_method";
45332
45846
  var TERMINAL_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
45847
+ // The daemon's answer to an operation it does not implement: a vault built
45848
+ // before the enrollment ceremony. It arrives as a transport Error frame with
45849
+ // no class, which claustrum-client before 0.13.0 labels transient/retry, but
45850
+ // asking again can never succeed.
45851
+ UNSUPPORTED_ENROLLMENT_CODE2,
45333
45852
  "invalid_params",
45334
45853
  "pending_exists",
45335
45854
  "not_found",
@@ -45359,7 +45878,7 @@ function getClaustrumEnrollmentPaths2(tokenPath) {
45359
45878
  const extension = extname2(tokenPath) || ".json";
45360
45879
  const stem = basename5(tokenPath, extname2(tokenPath));
45361
45880
  return {
45362
- statePath: join18(dirname20(tokenPath), `${stem}-state${extension}`),
45881
+ statePath: join20(dirname20(tokenPath), `${stem}-state${extension}`),
45363
45882
  tokenPath
45364
45883
  };
45365
45884
  }
@@ -45367,7 +45886,7 @@ function hostEnrollmentPaths2(input2) {
45367
45886
  const override = input2.override?.trim();
45368
45887
  if (override && !isAbsolute3(override) && !input2.cwd)
45369
45888
  throw new ClaustrumConsumerError2("invalid-state", "A relative Claustrum enrollment override needs a base directory");
45370
- const tokenPath = override ? isAbsolute3(override) ? override : resolve12(input2.cwd, override) : join18(input2.stateDir, `${input2.host}-enrollment.json`);
45889
+ const tokenPath = override ? isAbsolute3(override) ? override : resolve14(input2.cwd, override) : join20(input2.stateDir, `${input2.host}-enrollment.json`);
45371
45890
  return getClaustrumEnrollmentPaths2(tokenPath);
45372
45891
  }
45373
45892
  function isRecord10(value) {
@@ -45496,13 +46015,13 @@ async function readBoundedJson2(path5) {
45496
46015
  await descriptor.close();
45497
46016
  }
45498
46017
  }
45499
- function accountRecords2(text2, fields) {
46018
+ function accountRecords2(text2, fields2) {
45500
46019
  const records = [];
45501
46020
  for (const line of text2.split("\n")) {
45502
46021
  if (line.trim() === "" || line.startsWith("#"))
45503
46022
  continue;
45504
46023
  const parts = line.split(":");
45505
- if (parts.length !== fields || !/^[^\s:,]+$/.test(parts[0] ?? "") || !/^\d+$/.test(parts[2] ?? "") || !Number.isSafeInteger(Number(parts[2])) || fields === 7 && (!/^\d+$/.test(parts[3] ?? "") || !Number.isSafeInteger(Number(parts[3]))) || fields === 4 && parts[3] !== "" && !/^[^\s:,]+(?:,[^\s:,]+)*$/.test(parts[3] ?? ""))
46024
+ if (parts.length !== fields2 || !/^[^\s:,]+$/.test(parts[0] ?? "") || !/^\d+$/.test(parts[2] ?? "") || !Number.isSafeInteger(Number(parts[2])) || fields2 === 7 && (!/^\d+$/.test(parts[3] ?? "") || !Number.isSafeInteger(Number(parts[3]))) || fields2 === 4 && parts[3] !== "" && !/^[^\s:,]+(?:,[^\s:,]+)*$/.test(parts[3] ?? ""))
45506
46025
  return void 0;
45507
46026
  records.push(parts);
45508
46027
  }
@@ -45600,7 +46119,7 @@ async function writeStateAtomic2(path5, state, ancestorOptions = {}) {
45600
46119
  }
45601
46120
  if (windowsPrivateFiles2)
45602
46121
  return writePrivateAtomic2(path5, bytes);
45603
- const temporary = join18(parent, `.${basename5(path5)}.${process.pid}.${randomUUID17()}.tmp`);
46122
+ const temporary = join20(parent, `.${basename5(path5)}.${process.pid}.${randomUUID17()}.tmp`);
45604
46123
  let descriptor;
45605
46124
  let created = false;
45606
46125
  try {
@@ -45824,6 +46343,18 @@ var ClaustrumEnrollmentManager2 = class {
45824
46343
  retryCode: refusal3.code
45825
46344
  };
45826
46345
  }
46346
+ if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE2) {
46347
+ await lock.assertOwned();
46348
+ await unlink9(this.#paths.statePath).catch((cause) => {
46349
+ if (cause.code !== "ENOENT")
46350
+ throw cause;
46351
+ });
46352
+ return {
46353
+ state: "unavailable",
46354
+ proposedName: state.proposedName,
46355
+ code: refusal3.code
46356
+ };
46357
+ }
45827
46358
  return this.#block(state, refusal3.code);
45828
46359
  }
45829
46360
  }
@@ -45962,7 +46493,7 @@ var ByteTail = class {
45962
46493
  };
45963
46494
  var defaultCommandRunner = {
45964
46495
  run(file, args, options = {}) {
45965
- return new Promise((resolve18) => {
46496
+ return new Promise((resolve20) => {
45966
46497
  const started = performance.now();
45967
46498
  const timeoutMs = options.timeoutMs ?? 15e3;
45968
46499
  const stderr = new ByteTail();
@@ -45980,7 +46511,7 @@ var defaultCommandRunner = {
45980
46511
  stdio: ["ignore", "pipe", "pipe"]
45981
46512
  });
45982
46513
  } catch {
45983
- resolve18({
46514
+ resolve20({
45984
46515
  exitCode: 1,
45985
46516
  stdout: "",
45986
46517
  stderr: "",
@@ -46015,7 +46546,7 @@ var defaultCommandRunner = {
46015
46546
  settled = true;
46016
46547
  if (timer)
46017
46548
  clearTimeout(timer);
46018
- resolve18({
46549
+ resolve20({
46019
46550
  exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
46020
46551
  stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
46021
46552
  stderr: stderr.toString(),
@@ -46101,8 +46632,8 @@ function recordSetupEnrollment(failure2, enrollment) {
46101
46632
  // src/common-auth-embedded/setup/detect.js
46102
46633
  import { accessSync, constants as constants3, existsSync as existsSync11, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync5 } from "node:fs";
46103
46634
  import { mkdtemp, rm as rm6 } from "node:fs/promises";
46104
- import { tmpdir as tmpdir3 } from "node:os";
46105
- import { join as join19 } from "node:path";
46635
+ import { tmpdir as tmpdir5 } from "node:os";
46636
+ import { join as join21 } from "node:path";
46106
46637
  import { parse } from "jsonc-parser";
46107
46638
 
46108
46639
  // src/common-auth-embedded/setup/paths.js
@@ -46273,7 +46804,7 @@ async function detectHosts(plugin2, io = {}) {
46273
46804
  return null;
46274
46805
  let root;
46275
46806
  try {
46276
- root = await mkdtemp(join19(tmpdir3(), "common-auth-setup-version-"));
46807
+ root = await mkdtemp(join21(tmpdir5(), "common-auth-setup-version-"));
46277
46808
  const probeEnv = {
46278
46809
  ...env3,
46279
46810
  HOME: root,
@@ -46342,6 +46873,8 @@ import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexki
46342
46873
  var WINDOWS_CIM_TIMEOUT_MS = 45e3;
46343
46874
  var HOSTS = /* @__PURE__ */ new Set(["opencode", "litecode", "opencode2", "pi"]);
46344
46875
  var RUNTIMES = /* @__PURE__ */ new Set(["node", "bun"]);
46876
+ var WINDOWS_FENCE_FILTER = [...HOSTS, ...RUNTIMES].map((name) => `Name LIKE '${name}%'`).join(" OR ");
46877
+ var WINDOWS_FENCE_QUERY = `$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${WINDOWS_FENCE_FILTER}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`;
46345
46878
  var PI_SCRIPT_PATTERN = /(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;
46346
46879
  function commandArguments(command) {
46347
46880
  return [...command.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2] ?? "");
@@ -46444,6 +46977,7 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);
46444
46977
  };
46445
46978
  async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
46446
46979
  const windows2 = (options.platform ?? process.platform) === "win32";
46980
+ const selfPid = options.selfPid ?? process.pid;
46447
46981
  let inspection = {
46448
46982
  step: windows2 ? "tasklist" : "ps",
46449
46983
  exitCode: null,
@@ -46480,6 +47014,29 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
46480
47014
  }
46481
47015
  };
46482
47016
  try {
47017
+ if (windows2 && options.hostImagesOnly) {
47018
+ const details = await inspect("CIM", "powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_FENCE_QUERY], WINDOWS_CIM_TIMEOUT_MS);
47019
+ if (details.exitCode !== 0)
47020
+ throw new ProcessInspectionError(inspection);
47021
+ const value = JSON.parse(details.stdout);
47022
+ if (!value || typeof value !== "object" || !("complete" in value) || value.complete !== true || !("processes" in value))
47023
+ throw new ProcessInspectionError(inspection);
47024
+ const listed = value.processes;
47025
+ const rows = listed === null ? [] : Array.isArray(listed) ? listed : [listed];
47026
+ const processes2 = [];
47027
+ for (const row of rows) {
47028
+ if (!row || typeof row !== "object" || !("Name" in row) || typeof row.Name !== "string" || !("ProcessId" in row) || !Number.isSafeInteger(row.ProcessId) || row.ProcessId < 0 || !("CommandLine" in row))
47029
+ throw new ProcessInspectionError(inspection);
47030
+ const pid = row.ProcessId;
47031
+ if (!/^(?:node|bun)\.exe$/i.test(row.Name))
47032
+ processes2.push({ pid, command: row.Name });
47033
+ else if (typeof row.CommandLine === "string")
47034
+ processes2.push({ pid, command: row.CommandLine });
47035
+ else if (pid !== selfPid)
47036
+ throw new ProcessInspectionError(inspection);
47037
+ }
47038
+ return processes2;
47039
+ }
46483
47040
  const result = await inspect(windows2 ? "tasklist" : "ps", windows2 ? "tasklist.exe" : "ps", windows2 ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
46484
47041
  if (result.exitCode !== 0)
46485
47042
  throw new ProcessInspectionError(inspection);
@@ -46512,7 +47069,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
46512
47069
  }
46513
47070
  if (!processes.length)
46514
47071
  throw new ProcessInspectionError(inspection);
46515
- const runtimes = processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command));
47072
+ const runtimes = processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command));
46516
47073
  if (windows2 && runtimes.length && options.inspectRuntimes !== false) {
46517
47074
  const details = await inspect("CIM", "powershell.exe", [
46518
47075
  "-NoProfile",
@@ -46545,10 +47102,15 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
46545
47102
  }
46546
47103
  }
46547
47104
  function createProcessFence(runner = defaultCommandRunner, options = {}) {
46548
- const isHost = (entry) => entry.pid !== process.pid && hostName(entry.command) !== null;
47105
+ const selfPid = options.selfPid ?? process.pid;
47106
+ const isHost = (entry) => entry.pid !== selfPid && hostName(entry.command) !== null;
46549
47107
  return {
46550
47108
  async listRunningHosts(env3) {
46551
- return (await listSetupProcesses(runner, { ...options, env: env3 })).filter(isHost);
47109
+ return (await listSetupProcesses(runner, {
47110
+ ...options,
47111
+ env: env3,
47112
+ hostImagesOnly: true
47113
+ })).filter(isHost);
46552
47114
  },
46553
47115
  async previewRunningHosts(env3) {
46554
47116
  const processes = await listSetupProcesses(runner, {
@@ -46559,7 +47121,7 @@ function createProcessFence(runner = defaultCommandRunner, options = {}) {
46559
47121
  const windows2 = (options.platform ?? process.platform) === "win32";
46560
47122
  return {
46561
47123
  hosts: processes.filter(isHost),
46562
- uncheckedRuntimes: windows2 ? processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
47124
+ uncheckedRuntimes: windows2 ? processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
46563
47125
  };
46564
47126
  }
46565
47127
  };
@@ -46572,8 +47134,27 @@ async function assertHostsStopped(fence, env3) {
46572
47134
 
46573
47135
  // src/common-auth-embedded/setup/enroll.js
46574
47136
  var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
47137
+ var UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.";
47138
+ var ENROLLMENT_WAIT_MS = 3e5;
47139
+ var APPROVAL_POLL_MS = 1e3;
47140
+ var PROPOSE_BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
47141
+ function safeCode(code2) {
47142
+ return code2 && /^[a-z][a-z0-9_]{0,63}$/.test(code2) ? code2 : "unknown";
47143
+ }
46575
47144
  var HostNotEnrolledError = class extends Error {
47145
+ reason;
47146
+ lastErrorCode;
47147
+ constructor(message, details) {
47148
+ super(message);
47149
+ this.name = "HostNotEnrolledError";
47150
+ this.reason = details.reason;
47151
+ if (details.lastErrorCode !== void 0)
47152
+ this.lastErrorCode = safeCode(details.lastErrorCode);
47153
+ }
46576
47154
  };
47155
+ function approveCommand(requestId, name) {
47156
+ return `ck auth enroll approve --request-id ${requestId} --name ${name}`;
47157
+ }
46577
47158
  async function connectSetupHost(plugin2, host, io, terminal, fence) {
46578
47159
  const { name, paths: input2 } = plugin2.vault.hosts[host];
46579
47160
  const paths = hostEnrollmentPaths2(input2);
@@ -46582,54 +47163,94 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
46582
47163
  connectionFile: plugin2.vault.connectionFile,
46583
47164
  handshakeTimeoutMs: 2e3
46584
47165
  }).catch(() => {
46585
- throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.");
47166
+ throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.", { reason: "connection-failed" });
46586
47167
  });
47168
+ const now = io.now ?? (() => performance.now());
47169
+ const wait2 = io.wait ?? delay;
46587
47170
  try {
46588
47171
  const manager = new ClaustrumEnrollmentManager2({
46589
47172
  proposedName: name,
46590
47173
  paths,
46591
- client: {
46592
- enrollPropose: async (input3) => {
46593
- await fence();
46594
- return client.enrollPropose(input3);
46595
- },
46596
- enrollPoll: async (input3) => {
46597
- await fence();
46598
- return client.enrollPoll(input3);
46599
- }
46600
- },
47174
+ // Each tick of the wait below checks the fence once, just before
47175
+ // reconcile proposes or polls. Checking again inside every vault call
47176
+ // doubled the process listings per tick, and on Windows each listing
47177
+ // starts PowerShell.
47178
+ client,
46601
47179
  writeTokenFile: async (path5, file) => {
46602
47180
  await fence();
46603
47181
  await writeEnrollmentTokenFile3(path5, file);
46604
47182
  }
46605
47183
  });
47184
+ printLine2(terminal, `Asking the vault to connect ${name}\u2026`);
47185
+ const deadline = now() + ENROLLMENT_WAIT_MS;
46606
47186
  let printedRequest;
46607
- for (let tick = 0; tick < 300; tick++) {
47187
+ let lastCode;
47188
+ let reportedCode;
47189
+ let failedProposals = 0;
47190
+ for (; ; ) {
46608
47191
  await fence();
46609
47192
  const status = await manager.reconcile();
46610
47193
  if (status.state === "approved") {
46611
47194
  printLine2(terminal, `Connected ${host} to Claustrum.`);
46612
47195
  return;
46613
47196
  }
47197
+ if (status.state === "unavailable" && status.code === UNSUPPORTED_ENROLLMENT_CODE2)
47198
+ throw new HostNotEnrolledError(UNSUPPORTED_VAULT_MESSAGE, {
47199
+ reason: "unsupported-vault",
47200
+ lastErrorCode: status.code
47201
+ });
46614
47202
  if (status.state !== "pending" && status.state !== "busy")
46615
- throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
46616
- if (status.state === "pending" && status.requestId && status.requestId !== printedRequest) {
46617
- if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
46618
- throw new HostNotEnrolledError("Invalid enrollment request id.");
46619
- printedRequest = status.requestId;
46620
- printLine2(terminal, "Waiting for approval. In another terminal, run:");
46621
- printLine2(terminal, ` ck auth enroll approve --request-id ${status.requestId} --name ${name}`);
46622
- printLine2(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
46623
- }
46624
- await (io.wait ?? delay)(1e3);
46625
- }
46626
- throw new HostNotEnrolledError("Claustrum approval is still pending; approve with ck and rerun setup.");
47203
+ throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.", {
47204
+ reason: "refused",
47205
+ ..."code" in status && { lastErrorCode: status.code }
47206
+ });
47207
+ let pause = APPROVAL_POLL_MS;
47208
+ if (status.state === "busy")
47209
+ lastCode = "busy";
47210
+ else if (status.retryCode)
47211
+ lastCode = status.retryCode;
47212
+ if (status.state === "pending" && status.requestId) {
47213
+ failedProposals = 0;
47214
+ if (status.requestId !== printedRequest) {
47215
+ if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
47216
+ throw new HostNotEnrolledError("Invalid enrollment request id.", {
47217
+ reason: "invalid-request"
47218
+ });
47219
+ printedRequest = status.requestId;
47220
+ printLine2(terminal, "Waiting for approval. In another terminal, run:");
47221
+ printLine2(terminal, ` ${approveCommand(status.requestId, name)}`);
47222
+ printLine2(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
47223
+ }
47224
+ } else if (status.state === "pending" && status.retryCode) {
47225
+ pause = PROPOSE_BACKOFF_MS[Math.min(failedProposals, PROPOSE_BACKOFF_MS.length - 1)] ?? APPROVAL_POLL_MS;
47226
+ failedProposals++;
47227
+ const code3 = safeCode(status.retryCode);
47228
+ if (code3 !== reportedCode) {
47229
+ reportedCode = code3;
47230
+ printLine2(terminal, `The vault has not created the request yet (${code3}); retrying.`);
47231
+ }
47232
+ }
47233
+ const remaining = deadline - now();
47234
+ if (remaining <= 0)
47235
+ break;
47236
+ await wait2(Math.min(pause, remaining));
47237
+ }
47238
+ if (printedRequest)
47239
+ throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
47240
+ reason: "approval-pending",
47241
+ ...lastCode !== void 0 && { lastErrorCode: lastCode }
47242
+ });
47243
+ const code2 = safeCode(lastCode);
47244
+ throw new HostNotEnrolledError(`The vault never created the enrollment request (last error: ${code2}). Check that ck is running, then rerun setup.`, { reason: "request-not-created", lastErrorCode: code2 });
46627
47245
  } catch (error) {
46628
- if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError)
47246
+ if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError || // Built above from fixed text and vetted values only.
47247
+ error instanceof HostNotEnrolledError)
46629
47248
  throw error;
46630
- if (error instanceof HostNotEnrolledError)
46631
- throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE);
46632
- throw new Error(ENROLLMENT_INCOMPLETE_MESSAGE);
47249
+ const code2 = error?.code;
47250
+ throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE, {
47251
+ reason: "incomplete",
47252
+ ...typeof code2 === "string" && { lastErrorCode: code2 }
47253
+ });
46633
47254
  } finally {
46634
47255
  client.close();
46635
47256
  }
@@ -46667,7 +47288,7 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
46667
47288
  // src/common-auth-embedded/setup/config-write.js
46668
47289
  import { randomUUID as randomUUID18 } from "node:crypto";
46669
47290
  import { mkdir as mkdir14, open as open11, rename as rename10, stat as stat9, unlink as unlink10 } from "node:fs/promises";
46670
- import { basename as basename6, dirname as dirname21, join as join20 } from "node:path";
47291
+ import { basename as basename6, dirname as dirname21, join as join22 } from "node:path";
46671
47292
  import { setTimeout as delay2 } from "node:timers/promises";
46672
47293
  async function writeHostConfigAtomic(file, content, options = {}) {
46673
47294
  const windows2 = (options.platform ?? process.platform) === "win32";
@@ -46682,7 +47303,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
46682
47303
  throw error;
46683
47304
  }
46684
47305
  }
46685
- const stage = join20(parent, `.${basename6(file)}.${(options.stageName ?? randomUUID18)()}.tmp`);
47306
+ const stage = join22(parent, `.${basename6(file)}.${(options.stageName ?? randomUUID18)()}.tmp`);
46686
47307
  let created = false;
46687
47308
  try {
46688
47309
  const handle = await open11(stage, "wx", mode ?? 438);
@@ -47049,11 +47670,11 @@ ${write.content}`);
47049
47670
  // src/plugin/vault-activation.ts
47050
47671
  import { readFile as readFile12 } from "node:fs/promises";
47051
47672
  import { homedir as homedir10 } from "node:os";
47052
- import { join as join21 } from "node:path";
47673
+ import { join as join23 } from "node:path";
47053
47674
  var V1_VAULT_ACTIVATION_LABEL = "Activate approved Antigravity vault";
47054
47675
  function nativeOpenCodeAuthPath(env3 = process.env, home = homedir10()) {
47055
- return join21(
47056
- env3.XDG_DATA_HOME || join21(home, ".local", "share"),
47676
+ return join23(
47677
+ env3.XDG_DATA_HOME || join23(home, ".local", "share"),
47057
47678
  "opencode",
47058
47679
  "auth.json"
47059
47680
  );
@@ -47101,7 +47722,7 @@ function createV1VaultActivationMethod(input2) {
47101
47722
  // src/setup.ts
47102
47723
  var PI_PLACEHOLDER_KEY = "antigravity-vault-custody";
47103
47724
  function nativeAuthPath(host, context) {
47104
- return host === "opencode" ? nativeOpenCodeAuthPath() : join22(context.piAgentDir, "auth.json");
47725
+ return host === "opencode" ? nativeOpenCodeAuthPath() : join24(context.piAgentDir, "auth.json");
47105
47726
  }
47106
47727
  function provider(host) {
47107
47728
  return host === "opencode" ? OPENCODE_VAULT_PROVIDER : ANTIGRAVITY_PROVIDER_ID;
@@ -47157,7 +47778,7 @@ async function writeNativeSlot(host, slot, context, expectedAuthority = "local")
47157
47778
  beforeRename: async () => {
47158
47779
  await assertSetupHostsStopped();
47159
47780
  const claustrum = await loadCommonAuthClaustrum();
47160
- const stateDir = host === "opencode" ? openCodeVaultPaths(resolve13(getStoragePath())).dir : getPiAntigravityVaultDir();
47781
+ const stateDir = host === "opencode" ? openCodeVaultPaths(resolve15(getStoragePath())).dir : getPiAntigravityVaultDir();
47161
47782
  if (await claustrum.enrollmentAuthority(
47162
47783
  claustrum.hostEnrollmentPaths({ stateDir, host }),
47163
47784
  `antigravity-auth-${host}`
@@ -47187,7 +47808,7 @@ async function persistPiSetupLogin(result, context) {
47187
47808
  }
47188
47809
  async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
47189
47810
  const claustrum = await loadCommonAuthClaustrum();
47190
- const opencode = openCodeVaultPaths(resolve13(getStoragePath()));
47811
+ const opencode = openCodeVaultPaths(resolve15(getStoragePath()));
47191
47812
  const piDir = getPiAntigravityVaultDir();
47192
47813
  const hosts = {
47193
47814
  opencode: {
@@ -47206,7 +47827,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
47206
47827
  const assertLocal = async (host, context) => {
47207
47828
  if (host === "opencode")
47208
47829
  return assertLocalOpenCodeLogin(
47209
- resolve13(getStoragePath()),
47830
+ resolve15(getStoragePath()),
47210
47831
  context.opencodeGeneration
47211
47832
  );
47212
47833
  if (await authority(host) !== "local")
@@ -47222,7 +47843,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
47222
47843
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
47223
47844
  if ((await openPiSlot2({
47224
47845
  authPath: nativeAuthPath(host, context),
47225
- stashPath: join22(piDir, "google-login-stash.json"),
47846
+ stashPath: join24(piDir, "google-login-stash.json"),
47226
47847
  provider: ANTIGRAVITY_PROVIDER_ID,
47227
47848
  placeholderKey: PI_PLACEHOLDER_KEY
47228
47849
  }).inspect()).slot === "placeholder")
@@ -47259,7 +47880,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
47259
47880
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
47260
47881
  const inspection = await openPiSlot2({
47261
47882
  authPath: nativeAuthPath("pi", context),
47262
- stashPath: join22(piDir, "google-login-stash.json"),
47883
+ stashPath: join24(piDir, "google-login-stash.json"),
47263
47884
  provider: ANTIGRAVITY_PROVIDER_ID,
47264
47885
  placeholderKey: PI_PLACEHOLDER_KEY
47265
47886
  }).inspect();
@@ -47378,7 +47999,7 @@ Setup has not completed the OpenCode 2 native Google connection.
47378
47999
  await assertSetupHostsStopped();
47379
48000
  await openPiSlot2({
47380
48001
  authPath: nativeAuthPath(host, context),
47381
- stashPath: join22(piDir, "google-login-stash.json"),
48002
+ stashPath: join24(piDir, "google-login-stash.json"),
47382
48003
  provider: ANTIGRAVITY_PROVIDER_ID,
47383
48004
  placeholderKey: PI_PLACEHOLDER_KEY
47384
48005
  }).enterVault();
@@ -47738,7 +48359,7 @@ function createDefaultCliDependencies() {
47738
48359
  throw new Error(
47739
48360
  "Pi setup requires its detected native agent directory."
47740
48361
  );
47741
- const legacyPath = resolve14(getStoragePath());
48362
+ const legacyPath = resolve16(getStoragePath());
47742
48363
  const repository = host === "pi" ? void 0 : await prepareCliLoginStore(legacyPath, context?.opencodeGeneration);
47743
48364
  try {
47744
48365
  return await performOAuthLogin(request, {
@@ -47898,7 +48519,7 @@ async function readAccountStore(legacyPath) {
47898
48519
  function createDefaultAccountStoreOperations() {
47899
48520
  const offline = { processesStopped: true };
47900
48521
  return {
47901
- legacyPath: () => resolve14(getStoragePath()),
48522
+ legacyPath: () => resolve16(getStoragePath()),
47902
48523
  migrate: async (legacyPath) => createAccountMigrationFactory(await loadCommonAuthStoreModules())({
47903
48524
  legacyPath,
47904
48525
  offline,
@@ -48398,17 +49019,17 @@ function isTuiConnected(sessionId) {
48398
49019
 
48399
49020
  // src/rpc/rpc-dir.ts
48400
49021
  import { createHash as createHash16 } from "node:crypto";
48401
- import { homedir as homedir12, tmpdir as tmpdir4 } from "node:os";
48402
- import { isAbsolute as isAbsolute4, join as join26, resolve as resolve15 } from "node:path";
49022
+ import { homedir as homedir12, tmpdir as tmpdir6 } from "node:os";
49023
+ import { isAbsolute as isAbsolute4, join as join28, resolve as resolve17 } from "node:path";
48403
49024
  var RPC_DIR_ENV = "ANTIGRAVITY_AUTH_RPC_DIR";
48404
49025
  function getRpcDir(projectDirectory) {
48405
49026
  const override = process.env[RPC_DIR_ENV]?.trim();
48406
49027
  if (override) {
48407
- return isAbsolute4(override) ? override : resolve15(projectDirectory, override);
49028
+ return isAbsolute4(override) ? override : resolve17(projectDirectory, override);
48408
49029
  }
48409
- const projectHash = createHash16("sha256").update(resolve15(projectDirectory)).digest("hex").slice(0, 16);
48410
- const stateHome = process.env.XDG_STATE_HOME ?? join26(homedir12(), ".local", "state");
48411
- return join26(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
49030
+ const projectHash = createHash16("sha256").update(resolve17(projectDirectory)).digest("hex").slice(0, 16);
49031
+ const stateHome = process.env.XDG_STATE_HOME ?? join28(homedir12(), ".local", "state");
49032
+ return join28(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
48412
49033
  }
48413
49034
 
48414
49035
  // src/common-auth-embedded/rpc/notifications.js
@@ -48419,7 +49040,7 @@ function isSessionId(value) {
48419
49040
  // src/common-auth-embedded/rpc/port-file.js
48420
49041
  import { createHash as createHash17, randomUUID as randomUUID19 } from "node:crypto";
48421
49042
  import { chmod as chmod5, mkdir as mkdir15, open as open12, readdir, rename as rename11, rmdir as rmdir2, stat as stat10, unlink as unlink11 } from "node:fs/promises";
48422
- import { join as join27, resolve as resolve16 } from "node:path";
49043
+ import { join as join29, resolve as resolve18 } from "node:path";
48423
49044
  function isProbeablePid(pid) {
48424
49045
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
48425
49046
  }
@@ -48450,7 +49071,7 @@ async function removeCorruptPortFile(portFile, log16) {
48450
49071
  }
48451
49072
  async function writePortFile(dir, entry, options = {}) {
48452
49073
  const writeOnce = async () => {
48453
- const target = join27(dir, `port-${entry.pid}.json`);
49074
+ const target = join29(dir, `port-${entry.pid}.json`);
48454
49075
  if (windowsPrivateFiles2) {
48455
49076
  await ensurePrivateDirectory3(dir, options.secureDir ?? false);
48456
49077
  await options.beforeWrite?.();
@@ -48506,12 +49127,12 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
48506
49127
  return;
48507
49128
  throw error;
48508
49129
  }
48509
- const active2 = resolve16(activeDir);
49130
+ const active2 = resolve18(activeDir);
48510
49131
  for (const projectDir of projectDirs) {
48511
49132
  if (!projectDir.isDirectory() || !isManagedDir(projectDir.name)) {
48512
49133
  continue;
48513
49134
  }
48514
- const dir = join27(root, projectDir.name);
49135
+ const dir = join29(root, projectDir.name);
48515
49136
  let names;
48516
49137
  try {
48517
49138
  names = await readdir(dir);
@@ -48523,7 +49144,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
48523
49144
  for (const name of names) {
48524
49145
  if (!name.startsWith("port-") || !name.endsWith(".json"))
48525
49146
  continue;
48526
- const portFile = join27(dir, name);
49147
+ const portFile = join29(dir, name);
48527
49148
  let raw;
48528
49149
  try {
48529
49150
  raw = await readPrivateText2(portFile);
@@ -48550,7 +49171,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
48550
49171
  await unlink11(portFile).catch(() => {
48551
49172
  });
48552
49173
  }
48553
- if (resolve16(dir) !== active2)
49174
+ if (resolve18(dir) !== active2)
48554
49175
  await rmdir2(dir).catch(() => {
48555
49176
  });
48556
49177
  }
@@ -48560,7 +49181,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
48560
49181
  import { randomBytes as randomBytes7, timingSafeEqual } from "node:crypto";
48561
49182
  import { unlink as unlink12 } from "node:fs/promises";
48562
49183
  import { createServer as createServer3 } from "node:http";
48563
- import { join as join28 } from "node:path";
49184
+ import { join as join30 } from "node:path";
48564
49185
  var RpcRequestError = class extends Error {
48565
49186
  status;
48566
49187
  constructor(status, message) {
@@ -48580,7 +49201,7 @@ var BodyTooLargeError = class extends Error {
48580
49201
  }
48581
49202
  };
48582
49203
  function readBody(req) {
48583
- return new Promise((resolve18, reject) => {
49204
+ return new Promise((resolve20, reject) => {
48584
49205
  const tooLarge = (declaredOversize = false) => {
48585
49206
  req.removeAllListeners("data");
48586
49207
  req.on("data", () => {
@@ -48603,7 +49224,7 @@ function readBody(req) {
48603
49224
  }
48604
49225
  chunks.push(chunk);
48605
49226
  });
48606
- req.on("end", () => resolve18(Buffer.concat(chunks).toString("utf8")));
49227
+ req.on("end", () => resolve20(Buffer.concat(chunks).toString("utf8")));
48607
49228
  req.on("error", reject);
48608
49229
  });
48609
49230
  }
@@ -48771,12 +49392,12 @@ async function startRpcServer(options) {
48771
49392
  json(500, { error: "internal error" });
48772
49393
  }
48773
49394
  }
48774
- const port = await new Promise((resolve18, reject) => {
49395
+ const port = await new Promise((resolve20, reject) => {
48775
49396
  server.on("error", reject);
48776
49397
  server.listen(0, "127.0.0.1", () => {
48777
49398
  const addr = server.address();
48778
49399
  if (addr && typeof addr === "object")
48779
- resolve18(addr.port);
49400
+ resolve20(addr.port);
48780
49401
  else
48781
49402
  reject(new Error("no port"));
48782
49403
  });
@@ -48799,20 +49420,20 @@ async function startRpcServer(options) {
48799
49420
  rpcPort: port
48800
49421
  });
48801
49422
  } catch (error) {
48802
- await new Promise((resolve18) => server.close(() => resolve18()));
49423
+ await new Promise((resolve20) => server.close(() => resolve20()));
48803
49424
  throw error;
48804
49425
  }
48805
49426
  return {
48806
49427
  port,
48807
49428
  token,
48808
49429
  async stop() {
48809
- await new Promise((resolve18) => {
49430
+ await new Promise((resolve20) => {
48810
49431
  server.closeAllConnections?.();
48811
- server.close(() => resolve18());
49432
+ server.close(() => resolve20());
48812
49433
  for (const socket of connections)
48813
49434
  socket.destroy();
48814
49435
  });
48815
- const portFile = join28(options.dir, `port-${process.pid}.json`);
49436
+ const portFile = join30(options.dir, `port-${process.pid}.json`);
48816
49437
  const current = await readPrivateText2(portFile).then((raw) => JSON.parse(raw)).catch((error) => {
48817
49438
  if (error instanceof PrivateFileError2 && error.code !== "ENOENT")
48818
49439
  throw error;
@@ -49115,7 +49736,7 @@ import { createInterface as createInterface2 } from "node:readline/promises";
49115
49736
  // src/plugin/config/updater.ts
49116
49737
  import { existsSync as existsSync14, mkdirSync as mkdirSync8, readFileSync as readFileSync12, writeFileSync as writeFileSync8 } from "node:fs";
49117
49738
  import { homedir as homedir13 } from "node:os";
49118
- import { dirname as dirname23, join as join29 } from "node:path";
49739
+ import { dirname as dirname23, join as join31 } from "node:path";
49119
49740
  var PLUGIN_NAME = "@cortexkit/opencode-antigravity-auth@latest";
49120
49741
  var SCHEMA_URL = "https://opencode.ai/config.json";
49121
49742
  var OPENCODE_JSON_FILENAME = "opencode.json";
@@ -49127,13 +49748,13 @@ function stripJsonCommentsAndTrailingCommas(json) {
49127
49748
  ).replace(/,(\s*[}\]])/g, "$1");
49128
49749
  }
49129
49750
  function getOpencodeConfigDir() {
49130
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join29(homedir13(), ".config");
49131
- return join29(xdgConfig2, "opencode");
49751
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join31(homedir13(), ".config");
49752
+ return join31(xdgConfig2, "opencode");
49132
49753
  }
49133
49754
  function getOpencodeConfigPath() {
49134
49755
  const configDir = getOpencodeConfigDir();
49135
- const jsoncPath = join29(configDir, OPENCODE_JSONC_FILENAME);
49136
- const jsonPath = join29(configDir, OPENCODE_JSON_FILENAME);
49756
+ const jsoncPath = join31(configDir, OPENCODE_JSONC_FILENAME);
49757
+ const jsonPath = join31(configDir, OPENCODE_JSON_FILENAME);
49137
49758
  if (existsSync14(jsoncPath)) {
49138
49759
  return jsoncPath;
49139
49760
  }
@@ -49392,7 +50013,7 @@ async function select3(items, options) {
49392
50013
  }
49393
50014
  renderedLines = linesWritten;
49394
50015
  };
49395
- return new Promise((resolve18) => {
50016
+ return new Promise((resolve20) => {
49396
50017
  const wasRaw = stdin.isRaw ?? false;
49397
50018
  const cleanup2 = () => {
49398
50019
  if (isCleanedUp) return;
@@ -49413,11 +50034,11 @@ async function select3(items, options) {
49413
50034
  };
49414
50035
  const onSignal = () => {
49415
50036
  cleanup2();
49416
- resolve18(null);
50037
+ resolve20(null);
49417
50038
  };
49418
50039
  const finishWithValue = (value) => {
49419
50040
  cleanup2();
49420
- resolve18(value);
50041
+ resolve20(value);
49421
50042
  };
49422
50043
  const findNextSelectable = (from, direction) => {
49423
50044
  if (items.length === 0) return from;
@@ -49463,7 +50084,7 @@ async function select3(items, options) {
49463
50084
  stdin.setRawMode(true);
49464
50085
  } catch {
49465
50086
  cleanup2();
49466
- resolve18(null);
50087
+ resolve20(null);
49467
50088
  return;
49468
50089
  }
49469
50090
  stdin.resume();
@@ -52721,15 +53342,15 @@ function projectCommandAccountRows(storage) {
52721
53342
 
52722
53343
  // src/plugin/dependencies.ts
52723
53344
  import { homedir as homedir14 } from "node:os";
52724
- import { join as join30 } from "node:path";
53345
+ import { join as join32 } from "node:path";
52725
53346
  function defaultFilesystemRoots() {
52726
- const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join30(homedir14(), ".config");
52727
- const xdgState2 = process.env.XDG_STATE_HOME ?? join30(homedir14(), ".local", "state");
53347
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join32(homedir14(), ".config");
53348
+ const xdgState2 = process.env.XDG_STATE_HOME ?? join32(homedir14(), ".local", "state");
52728
53349
  return {
52729
53350
  projectRoot: process.cwd(),
52730
- userConfigRoot: join30(xdgConfig2, "opencode"),
52731
- sidebarStateRoot: join30(xdgState2, "cortexkit", "antigravity-auth"),
52732
- rpcRoot: join30(xdgState2, "cortexkit", "antigravity-auth", "rpc")
53351
+ userConfigRoot: join32(xdgConfig2, "opencode"),
53352
+ sidebarStateRoot: join32(xdgState2, "cortexkit", "antigravity-auth"),
53353
+ rpcRoot: join32(xdgState2, "cortexkit", "antigravity-auth", "rpc")
52733
53354
  };
52734
53355
  }
52735
53356
  function resolvePluginDependencies(overrides = {}) {
@@ -52758,10 +53379,10 @@ function resolvePluginDependencies(overrides = {}) {
52758
53379
  }
52759
53380
  async function defaultSleep(ms, signal) {
52760
53381
  if (ms <= 0) return;
52761
- await new Promise((resolve18, reject) => {
53382
+ await new Promise((resolve20, reject) => {
52762
53383
  const timer = setTimeout(() => {
52763
53384
  signal?.removeEventListener("abort", onAbort);
52764
- resolve18();
53385
+ resolve20();
52765
53386
  }, ms);
52766
53387
  timer.unref?.();
52767
53388
  const onAbort = () => {
@@ -52783,7 +53404,7 @@ function createEventHandler({
52783
53404
  sessionRegistry,
52784
53405
  sessionRecovery,
52785
53406
  updateChecker,
52786
- logger: logger2
53407
+ logger: logger3
52787
53408
  }) {
52788
53409
  return async (input2) => {
52789
53410
  await updateChecker.event(input2);
@@ -52795,14 +53416,14 @@ function createEventHandler({
52795
53416
  sessionRegistry.register(sessionId, parentSessionId);
52796
53417
  }
52797
53418
  if (parentSessionId) {
52798
- logger2.debug("child-session-detected", {
53419
+ logger3.debug("child-session-detected", {
52799
53420
  sessionId,
52800
53421
  parentID: parentSessionId
52801
53422
  });
52802
53423
  } else {
52803
53424
  const previousSummary = lifecycle.getAccountManager()?.getSessionSummary();
52804
53425
  if (previousSummary && (previousSummary.totalClaude > 0 || previousSummary.totalGemini > 0)) {
52805
- logger2.debug("prev-session-quota-summary", {
53426
+ logger3.debug("prev-session-quota-summary", {
52806
53427
  durationMinutes: previousSummary.durationMinutes,
52807
53428
  totalClaude: previousSummary.totalClaude,
52808
53429
  totalGemini: previousSummary.totalGemini,
@@ -52810,7 +53431,7 @@ function createEventHandler({
52810
53431
  accountsUsed: previousSummary.accountsUsed
52811
53432
  });
52812
53433
  }
52813
- logger2.debug("root-session-detected", { sessionId });
53434
+ logger3.debug("root-session-detected", { sessionId });
52814
53435
  }
52815
53436
  }
52816
53437
  if (input2.event.type === "session.deleted") {
@@ -52819,7 +53440,7 @@ function createEventHandler({
52819
53440
  if (sessionId) {
52820
53441
  sessionRegistry.delete(sessionId);
52821
53442
  lifecycle.getAccountManager()?.deleteSessionState(sessionId);
52822
- const eventLogger = logger2;
53443
+ const eventLogger = logger3;
52823
53444
  void removeSidebarActiveRouting(sessionId).catch((error2) => {
52824
53445
  eventLogger.debug("sidebar-route-remove-failed", {
52825
53446
  sessionId,
@@ -52855,7 +53476,7 @@ function createEventHandler({
52855
53476
  });
52856
53477
  const successToast = getRecoverySuccessToast();
52857
53478
  const isChildSession = sessionRegistry.getParentSessionId(sessionID) !== null;
52858
- logger2.debug("recovery-toast", {
53479
+ logger3.debug("recovery-toast", {
52859
53480
  ...successToast,
52860
53481
  isChildSession,
52861
53482
  toastScope: config.toast_scope
@@ -53347,6 +53968,19 @@ function createGoogleSearchTool({
53347
53968
  // src/plugin/lifecycle.ts
53348
53969
  var NOOP_DRAIN = async () => {
53349
53970
  };
53971
+ async function collectCleanupFailure(cleanup2, failures) {
53972
+ try {
53973
+ await cleanup2();
53974
+ } catch (error) {
53975
+ failures.push(error);
53976
+ }
53977
+ }
53978
+ function reportCleanupFailures(failures) {
53979
+ if (failures.length === 1) throw failures[0];
53980
+ if (failures.length > 1) {
53981
+ throw new AggregateError(failures, "Plugin cleanup failed");
53982
+ }
53983
+ }
53350
53984
  function createPluginLifecycle(options) {
53351
53985
  let accountManager = null;
53352
53986
  let refreshQueue = null;
@@ -53358,19 +53992,19 @@ function createPluginLifecycle(options) {
53358
53992
  const consumers = [];
53359
53993
  const drainSidebarWrites2 = options.drainSidebarWrites ?? NOOP_DRAIN;
53360
53994
  const retire2 = (manager, queue2, requests) => {
53361
- const queueDrained = Promise.resolve(queue2?.dispose());
53995
+ const queueDrained = (async () => {
53996
+ await queue2?.dispose();
53997
+ })();
53362
53998
  const record3 = {
53363
53999
  requests,
53364
54000
  done: (async () => {
53365
- const drained = await Promise.allSettled([
53366
- queueDrained,
53367
- requests?.retire()
54001
+ const failures = [];
54002
+ await Promise.all([
54003
+ collectCleanupFailure(() => queueDrained, failures),
54004
+ collectCleanupFailure(() => requests?.retire(), failures)
53368
54005
  ]);
53369
- await manager.dispose();
53370
- const failed = drained.find(
53371
- (outcome) => outcome.status === "rejected"
53372
- );
53373
- if (failed) throw failed.reason;
54006
+ await collectCleanupFailure(() => manager.dispose(), failures);
54007
+ reportCleanupFailures(failures);
53374
54008
  })()
53375
54009
  };
53376
54010
  retiring.add(record3);
@@ -53380,8 +54014,6 @@ function createPluginLifecycle(options) {
53380
54014
  if (!requests) retiring.delete(record3);
53381
54015
  }
53382
54016
  );
53383
- void queueDrained.catch(() => {
53384
- });
53385
54017
  return { queueDrained, done: record3.done };
53386
54018
  };
53387
54019
  const disposeAccountRuntime = async () => {
@@ -53393,23 +54025,26 @@ function createPluginLifecycle(options) {
53393
54025
  accountRequests = null;
53394
54026
  const retired = [...retiring];
53395
54027
  retiring.clear();
54028
+ const failures = [];
53396
54029
  const aborted = Promise.all([
53397
- oldRequests?.dispose(),
53398
- ...retired.map((record3) => record3.requests?.dispose())
54030
+ collectCleanupFailure(() => oldRequests?.dispose(), failures),
54031
+ ...retired.map(
54032
+ (record3) => collectCleanupFailure(() => record3.requests?.dispose(), failures)
54033
+ )
53399
54034
  ]);
53400
- const liveQueueDrained = Promise.resolve(oldQueue?.dispose());
53401
- void liveQueueDrained.catch(() => {
53402
- });
53403
- await aborted;
53404
- const retirements = await Promise.allSettled(
53405
- retired.map((record3) => record3.done)
54035
+ const liveQueueDrained = collectCleanupFailure(
54036
+ () => oldQueue?.dispose(),
54037
+ failures
53406
54038
  );
53407
- await liveQueueDrained;
53408
- await oldManager?.dispose();
53409
- const failed = retirements.find(
53410
- (outcome) => outcome.status === "rejected"
53411
- );
53412
- if (failed) throw failed.reason;
54039
+ await Promise.all([
54040
+ aborted,
54041
+ liveQueueDrained,
54042
+ ...retired.map(
54043
+ (record3) => collectCleanupFailure(() => record3.done, failures)
54044
+ )
54045
+ ]);
54046
+ await collectCleanupFailure(() => oldManager?.dispose(), failures);
54047
+ reportCleanupFailures(failures);
53413
54048
  };
53414
54049
  const register = (disposable, phase = "consumer") => {
53415
54050
  if (closing) {
@@ -53459,24 +54094,32 @@ function createPluginLifecycle(options) {
53459
54094
  };
53460
54095
  let failDisposal = () => {
53461
54096
  };
53462
- disposal = new Promise((resolve18, reject) => {
53463
- finishDisposal = resolve18;
54097
+ disposal = new Promise((resolve20, reject) => {
54098
+ finishDisposal = resolve20;
53464
54099
  failDisposal = reject;
53465
54100
  });
53466
54101
  void (async () => {
53467
- await disposeAccountRuntime();
53468
- await options.shutdownDiskSignatureCache();
53469
- options.sessionRegistry.clear();
53470
- options.clearFetchState();
54102
+ const failures = [];
54103
+ await collectCleanupFailure(disposeAccountRuntime, failures);
54104
+ await collectCleanupFailure(
54105
+ () => options.shutdownDiskSignatureCache(),
54106
+ failures
54107
+ );
54108
+ await collectCleanupFailure(
54109
+ () => options.sessionRegistry.clear(),
54110
+ failures
54111
+ );
54112
+ await collectCleanupFailure(() => options.clearFetchState(), failures);
53471
54113
  for (const disposable of producers) {
53472
- await disposable.dispose();
54114
+ await collectCleanupFailure(() => disposable.dispose(), failures);
53473
54115
  }
53474
54116
  producers.length = 0;
53475
- await drainSidebarWrites2();
54117
+ await collectCleanupFailure(drainSidebarWrites2, failures);
53476
54118
  for (const disposable of consumers) {
53477
- await disposable.dispose();
54119
+ await collectCleanupFailure(() => disposable.dispose(), failures);
53478
54120
  }
53479
54121
  consumers.length = 0;
54122
+ reportCleanupFailures(failures);
53480
54123
  })().then(finishDisposal, failDisposal);
53481
54124
  }
53482
54125
  return disposal;
@@ -53524,7 +54167,7 @@ function createSourceSidebarPublisher(options) {
53524
54167
  }
53525
54168
 
53526
54169
  // src/plugin/index.ts
53527
- var logger = createLogger4("plugin");
54170
+ var logger2 = createLogger4("plugin");
53528
54171
  function quotaAccountIdentity4(refreshToken) {
53529
54172
  return createHash20("sha256").update(refreshToken).digest("hex").slice(0, 16);
53530
54173
  }
@@ -53593,7 +54236,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53593
54236
  });
53594
54237
  let vaultQuotaPoller;
53595
54238
  const vaultCustody = createOpenCodeVaultCustody({
53596
- accountFile: resolve17(getStoragePath()),
54239
+ accountFile: resolve19(getStoragePath()),
53597
54240
  insulaQuota: true,
53598
54241
  readHostSlot: async () => {
53599
54242
  if (!cachedGetAuth)
@@ -53717,7 +54360,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53717
54360
  });
53718
54361
  function scheduleSidebarPublication() {
53719
54362
  void sidebarPublisher.publish().catch(
53720
- (error) => logger.debug("sidebar-source-publish-failed", {
54363
+ (error) => logger2.debug("sidebar-source-publish-failed", {
53721
54364
  error: error instanceof Error ? error.name : "unknown"
53722
54365
  })
53723
54366
  );
@@ -53747,7 +54390,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53747
54390
  }
53748
54391
  );
53749
54392
  })().catch(
53750
- (error) => logger.debug("sidebar-routing-publish-failed", {
54393
+ (error) => logger2.debug("sidebar-routing-publish-failed", {
53751
54394
  error: error instanceof Error ? error.name : "unknown"
53752
54395
  })
53753
54396
  );
@@ -53792,8 +54435,8 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53792
54435
  readProviderState: () => vaultCustody.readState(),
53793
54436
  publishSidebar: () => sidebarPublisher.publish(),
53794
54437
  transport: vaultQuotaTransport,
53795
- logger,
53796
- onOutcome: (level, outcome) => (level === "warn" ? quotaOutcomeLogger : logger)[level](
54438
+ logger: logger2,
54439
+ onOutcome: (level, outcome) => (level === "warn" ? quotaOutcomeLogger : logger2)[level](
53797
54440
  "vault-quota-tick",
53798
54441
  { ...outcome }
53799
54442
  ),
@@ -53805,7 +54448,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53805
54448
  lifecycle.register(vaultQuotaPoller, "producer");
53806
54449
  }
53807
54450
  const operatorSettings = createOperatorSettingsController({
53808
- projectConfigPath: join31(directory, ".opencode", "antigravity.json"),
54451
+ projectConfigPath: join33(directory, ".opencode", "antigravity.json"),
53809
54452
  // getUserConfigPath() already returns the full file path including
53810
54453
  // 'antigravity.json' — do NOT join again or the path double-nests
53811
54454
  // into <dir>/antigravity.json/antigravity.json.
@@ -53829,7 +54472,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53829
54472
  sessionRegistry,
53830
54473
  sessionRecovery,
53831
54474
  updateChecker,
53832
- logger
54475
+ logger: logger2
53833
54476
  });
53834
54477
  let storeQuota = null;
53835
54478
  const currentStoreQuota = async (knownRepository) => {
@@ -53935,7 +54578,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53935
54578
  source,
53936
54579
  ref,
53937
54580
  signal: check,
53938
- logger,
54581
+ logger: logger2,
53939
54582
  transport: vaultQuotaTransport
53940
54583
  })
53941
54584
  },
@@ -54195,7 +54838,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
54195
54838
  if (await readAuthority2() === "local")
54196
54839
  await lifecycle.getAccountManager()?.refreshFromRepository();
54197
54840
  } catch (error) {
54198
- logger.warn("menu-routing-refresh-failed", { error: String(error) });
54841
+ logger2.warn("menu-routing-refresh-failed", { error: String(error) });
54199
54842
  pushNotification(
54200
54843
  {
54201
54844
  command: ANTIGRAVITY_MENU_COMMAND,