@cortexkit/opencode-antigravity-auth 3.0.9 → 3.0.10

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 (99) hide show
  1. package/dist/cli.js +489 -175
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +101 -37
  4. package/dist/index.js +666 -269
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +106 -42
  7. package/dist/server.js +697 -300
  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/index.d.ts +1 -0
  13. package/dist/src/common-auth-embedded/claustrum/index.js +1 -0
  14. package/dist/src/common-auth-embedded/claustrum/quota-writer.d.ts +18 -0
  15. package/dist/src/common-auth-embedded/claustrum/quota-writer.js +253 -0
  16. package/dist/src/common-auth-embedded/claustrum/roster.d.ts +18 -2
  17. package/dist/src/common-auth-embedded/claustrum/roster.js +100 -43
  18. package/dist/src/common-auth-embedded/fs/with-lock.d.ts +1 -0
  19. package/dist/src/common-auth-embedded/fs/with-lock.js +2 -0
  20. package/dist/src/common-auth-embedded/quota/format.d.ts +19 -0
  21. package/dist/src/common-auth-embedded/quota/format.js +50 -5
  22. package/dist/src/common-auth-embedded/quota/index.d.ts +3 -3
  23. package/dist/src/common-auth-embedded/quota/index.js +2 -2
  24. package/dist/src/common-auth-embedded/quota/map.d.ts +24 -1
  25. package/dist/src/common-auth-embedded/quota/map.js +31 -6
  26. package/dist/src/common-auth-embedded/quota/merge.d.ts +6 -1
  27. package/dist/src/common-auth-embedded/quota/merge.js +17 -3
  28. package/dist/src/common-auth-embedded/quota/projection.d.ts +3 -1
  29. package/dist/src/common-auth-embedded/quota/projection.js +3 -1
  30. package/dist/src/common-auth-embedded/setup/process-fence.d.ts +7 -0
  31. package/dist/src/common-auth-embedded/setup/process-fence.js +5 -3
  32. package/dist/src/common-auth-embedded/source-output.json +83 -67
  33. package/dist/src/plugin/request-helpers.d.ts +5 -0
  34. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  35. package/dist/src/plugin/request-helpers.js +1 -0
  36. package/dist/src/plugin/request-helpers.js.map +1 -1
  37. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  38. package/dist/src/plugin/shared/request-services.js +123 -5
  39. package/dist/src/plugin/shared/request-services.js.map +1 -1
  40. package/dist/tui-build-map.json +21 -21
  41. package/dist/tui-ga-build-map.json +21 -21
  42. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +3 -1
  43. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  44. package/dist/types/src/common-auth-embedded/claustrum/quota-writer.d.ts +18 -0
  45. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +18 -2
  46. package/dist/types/src/common-auth-embedded/quota/format.d.ts +19 -0
  47. package/dist/types/src/common-auth-embedded/quota/index.d.ts +3 -3
  48. package/dist/types/src/common-auth-embedded/quota/map.d.ts +24 -1
  49. package/dist/types/src/common-auth-embedded/quota/merge.d.ts +6 -1
  50. package/dist/types/src/common-auth-embedded/quota/projection.d.ts +3 -1
  51. package/dist/types/src/common-auth-embedded/setup/process-fence.d.ts +7 -0
  52. package/dist/types/src/plugin/config/schema.d.ts +2 -2
  53. package/dist/types/src/plugin/request-helpers.d.ts +5 -0
  54. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  55. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  56. package/package.json +2 -2
  57. package/src/common-auth-embedded/claustrum/consumer.d.ts +3 -1
  58. package/src/common-auth-embedded/claustrum/consumer.js +25 -21
  59. package/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  60. package/src/common-auth-embedded/claustrum/index.js +1 -0
  61. package/src/common-auth-embedded/claustrum/quota-writer.d.ts +18 -0
  62. package/src/common-auth-embedded/claustrum/quota-writer.js +253 -0
  63. package/src/common-auth-embedded/claustrum/roster.d.ts +18 -2
  64. package/src/common-auth-embedded/claustrum/roster.js +100 -43
  65. package/src/common-auth-embedded/fs/with-lock.d.ts +1 -0
  66. package/src/common-auth-embedded/fs/with-lock.js +2 -0
  67. package/src/common-auth-embedded/quota/format.d.ts +19 -0
  68. package/src/common-auth-embedded/quota/format.js +50 -5
  69. package/src/common-auth-embedded/quota/index.d.ts +3 -3
  70. package/src/common-auth-embedded/quota/index.js +2 -2
  71. package/src/common-auth-embedded/quota/map.d.ts +24 -1
  72. package/src/common-auth-embedded/quota/map.js +31 -6
  73. package/src/common-auth-embedded/quota/merge.d.ts +6 -1
  74. package/src/common-auth-embedded/quota/merge.js +17 -3
  75. package/src/common-auth-embedded/quota/projection.d.ts +3 -1
  76. package/src/common-auth-embedded/quota/projection.js +3 -1
  77. package/src/common-auth-embedded/setup/process-fence.d.ts +7 -0
  78. package/src/common-auth-embedded/setup/process-fence.js +5 -3
  79. package/src/common-auth-embedded/source-output.json +83 -67
  80. package/src/tui-compiled/common-auth-embedded/quota/format.js +50 -5
  81. package/src/tui-compiled/common-auth-embedded/quota/index.js +2 -2
  82. package/src/tui-compiled/common-auth-embedded/quota/map.js +31 -6
  83. package/src/tui-compiled/common-auth-embedded/quota/merge.js +17 -3
  84. package/src/tui-compiled/common-auth-embedded/quota/projection.js +3 -1
  85. package/src/tui-ga-compiled/shared/1ff34afa7c42d196-projection.js +3 -1
  86. package/src/tui-ga-compiled/shared/77138df80c7ae006-map.js +31 -6
  87. package/src/tui-ga-compiled/shared/aef2402f8fc342f0-format.js +50 -5
  88. package/src/tui-ga-compiled/shared/bf17cbee28e58197-index.js +2 -2
  89. package/src/tui-ga-compiled/shared/ecc214300932dfb6-merge.js +17 -3
  90. package/src/tui-ga-raw/shared/1ff34afa7c42d196-projection.js +3 -1
  91. package/src/tui-ga-raw/shared/77138df80c7ae006-map.js +31 -6
  92. package/src/tui-ga-raw/shared/aef2402f8fc342f0-format.js +50 -5
  93. package/src/tui-ga-raw/shared/bf17cbee28e58197-index.js +2 -2
  94. package/src/tui-ga-raw/shared/ecc214300932dfb6-merge.js +17 -3
  95. package/src/tui-raw/common-auth-embedded/quota/format.js +50 -5
  96. package/src/tui-raw/common-auth-embedded/quota/index.js +2 -2
  97. package/src/tui-raw/common-auth-embedded/quota/map.js +31 -6
  98. package/src/tui-raw/common-auth-embedded/quota/merge.js +17 -3
  99. package/src/tui-raw/common-auth-embedded/quota/projection.js +3 -1
package/dist/index.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,
@@ -1114,8 +1158,8 @@ async function acquireRefreshFileLockWithClock(options) {
1114
1158
  let releaseConfirmed = false;
1115
1159
  let loss;
1116
1160
  let resolveLoss;
1117
- const lostPromise = new Promise((resolve18) => {
1118
- resolveLoss = resolve18;
1161
+ const lostPromise = new Promise((resolve20) => {
1162
+ resolveLoss = resolve20;
1119
1163
  });
1120
1164
  function notifyTimerStep(event) {
1121
1165
  try {
@@ -1272,7 +1316,7 @@ async function acquireRefreshFileLockWithClock(options) {
1272
1316
  }
1273
1317
  }
1274
1318
  async function backoff() {
1275
- await new Promise((resolve18) => setTimeout(resolve18, Math.floor(Math.random() * 4)));
1319
+ await new Promise((resolve20) => setTimeout(resolve20, Math.floor(Math.random() * 4)));
1276
1320
  }
1277
1321
  async function readLockState(notifyReady = true) {
1278
1322
  if (notifyReady && options.onStep)
@@ -1722,6 +1766,7 @@ function lockPathFor(target, name) {
1722
1766
  async function withLock(target, options, fn) {
1723
1767
  const started = performance.now();
1724
1768
  for (; ; ) {
1769
+ options.signal?.throwIfAborted();
1725
1770
  const lock = await acquireRefreshFileLock({
1726
1771
  path: target,
1727
1772
  name: options.name,
@@ -1732,6 +1777,7 @@ async function withLock(target, options, fn) {
1732
1777
  });
1733
1778
  if (lock) {
1734
1779
  try {
1780
+ options.signal?.throwIfAborted();
1735
1781
  return await fn(lock);
1736
1782
  } finally {
1737
1783
  await lock.release();
@@ -1745,7 +1791,7 @@ async function withLock(target, options, fn) {
1745
1791
  timeoutMs: options.timeoutMs
1746
1792
  });
1747
1793
  }
1748
- await new Promise((resolve18) => setTimeout(resolve18, Math.min(25, Math.ceil(remaining))));
1794
+ await new Promise((resolve20) => setTimeout(resolve20, Math.min(25, Math.ceil(remaining))));
1749
1795
  }
1750
1796
  }
1751
1797
  var LockContentionError, LockOwnershipError;
@@ -1781,13 +1827,13 @@ function assertNotInsideHook(operation) {
1781
1827
  function runInsideHook(operation, fn) {
1782
1828
  return insideHook.run(operation, async () => await fn());
1783
1829
  }
1784
- async function callFailureHook(operation, hook, rowId2, error, logger2) {
1830
+ async function callFailureHook(operation, hook, rowId2, error, logger3) {
1785
1831
  if (!hook)
1786
1832
  return;
1787
1833
  try {
1788
1834
  await runInsideHook(operation, () => hook(rowId2, error));
1789
1835
  } catch (hookError) {
1790
- logger2?.warn("store failure hook threw; the original failure stands", {
1836
+ logger3?.warn("store failure hook threw; the original failure stands", {
1791
1837
  operation,
1792
1838
  rowId: rowId2,
1793
1839
  error: hookError instanceof Error ? hookError.message : String(hookError)
@@ -1864,7 +1910,7 @@ async function acquirePoolLock(spec, defaults, env3) {
1864
1910
  });
1865
1911
  }
1866
1912
  const jitter = Math.floor(Math.random() * (options.retryMs + 1));
1867
- await new Promise((resolve18) => setTimeout(resolve18, Math.min(options.retryMs + jitter, remaining)));
1913
+ await new Promise((resolve20) => setTimeout(resolve20, Math.min(options.retryMs + jitter, remaining)));
1868
1914
  }
1869
1915
  }
1870
1916
  function definedOnly(spec) {
@@ -2942,11 +2988,11 @@ var init_mutate = __esm({
2942
2988
  if (isRecord4(this.state.accounts) && Object.hasOwn(this.state.accounts, id))
2943
2989
  delete this.state.accounts[id];
2944
2990
  }
2945
- setStateAccount(id, fields) {
2991
+ setStateAccount(id, fields2) {
2946
2992
  if (!isRecord4(this.state.accounts))
2947
2993
  this.state.accounts = {};
2948
2994
  Object.defineProperty(this.state.accounts, id, {
2949
- value: fields,
2995
+ value: fields2,
2950
2996
  enumerable: true,
2951
2997
  writable: true,
2952
2998
  configurable: true
@@ -4495,12 +4541,12 @@ var init_pull = __esm({
4495
4541
  firedAtLoad;
4496
4542
  logger;
4497
4543
  inflight = /* @__PURE__ */ new Set();
4498
- constructor(rt, hook, onFailure, firedAtLoad, logger2) {
4544
+ constructor(rt, hook, onFailure, firedAtLoad, logger3) {
4499
4545
  this.rt = rt;
4500
4546
  this.hook = hook;
4501
4547
  this.onFailure = onFailure;
4502
4548
  this.firedAtLoad = firedAtLoad;
4503
- this.logger = logger2;
4549
+ this.logger = logger3;
4504
4550
  }
4505
4551
  fire(id, reason) {
4506
4552
  if (!this.hook)
@@ -5582,15 +5628,15 @@ function createRedactor(options = {}) {
5582
5628
  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
5629
  }
5584
5630
  function errorEntries(error) {
5585
- const fields = error;
5631
+ const fields2 = error;
5586
5632
  const entries = [
5587
5633
  ["name", error.name],
5588
5634
  ["message", error.message],
5589
5635
  ["stack", error.stack]
5590
5636
  ];
5591
5637
  for (const key of ["code", "status", "cause"])
5592
- if (fields[key] !== void 0)
5593
- entries.push([key, fields[key]]);
5638
+ if (fields2[key] !== void 0)
5639
+ entries.push([key, fields2[key]]);
5594
5640
  const listed = new Set(entries.map(([key]) => key));
5595
5641
  for (const entry of Object.entries(error))
5596
5642
  if (!listed.has(entry[0]))
@@ -5832,7 +5878,7 @@ function createEngine(options) {
5832
5878
  } catch {
5833
5879
  }
5834
5880
  }
5835
- function schedule() {
5881
+ function schedule2() {
5836
5882
  if (!timer)
5837
5883
  timer = setTimeout(() => {
5838
5884
  timer = void 0;
@@ -5874,7 +5920,7 @@ function createEngine(options) {
5874
5920
  void flushed.catch(() => {
5875
5921
  });
5876
5922
  } else
5877
- schedule();
5923
+ schedule2();
5878
5924
  } catch {
5879
5925
  }
5880
5926
  }
@@ -6745,9 +6791,9 @@ function findAction(sections, request) {
6745
6791
  return actions?.find((action) => action.id === request.actionId);
6746
6792
  }
6747
6793
  function createCommandMenu(options) {
6748
- const logger2 = options.logger ?? createLogger2("commands");
6794
+ const logger3 = options.logger ?? createLogger2("commands");
6749
6795
  const redact3 = createTextRedactor(options.redaction);
6750
- const seam = { logger: logger2, redact: redact3 };
6796
+ const seam = { logger: logger3, redact: redact3 };
6751
6797
  const now = options.now ?? Date.now;
6752
6798
  const extras = options.extras ?? [];
6753
6799
  const replaced = options.replace ?? {};
@@ -6774,7 +6820,7 @@ function createCommandMenu(options) {
6774
6820
  content: await section.build(invocation)
6775
6821
  };
6776
6822
  } catch (error) {
6777
- logger2.warn("command menu section failed to build", {
6823
+ logger3.warn("command menu section failed to build", {
6778
6824
  command: options.command,
6779
6825
  section: id,
6780
6826
  error: redact3(error instanceof Error ? error.message : String(error))
@@ -6861,7 +6907,7 @@ function createCommandMenu(options) {
6861
6907
  };
6862
6908
  } catch (error) {
6863
6909
  const failure2 = projectFailure(error);
6864
- logger2.warn("command menu action failed", {
6910
+ logger3.warn("command menu action failed", {
6865
6911
  command: options.command,
6866
6912
  section: request.sectionId,
6867
6913
  action: request.actionId,
@@ -7473,7 +7519,7 @@ async function select(terminal, items, options) {
7473
7519
  writeLine("");
7474
7520
  renderedLines = lines;
7475
7521
  };
7476
- return new Promise((resolve18) => {
7522
+ return new Promise((resolve20) => {
7477
7523
  const wasRaw = stdin.isRaw ?? false;
7478
7524
  const cleanup2 = () => {
7479
7525
  if (cleaned)
@@ -7493,7 +7539,7 @@ async function select(terminal, items, options) {
7493
7539
  };
7494
7540
  const finish = (value) => {
7495
7541
  cleanup2();
7496
- resolve18(value);
7542
+ resolve20(value);
7497
7543
  };
7498
7544
  const onSignal = () => finish(null);
7499
7545
  const onKey = (data) => {
@@ -7533,7 +7579,7 @@ async function select(terminal, items, options) {
7533
7579
  stdin.setRawMode(true);
7534
7580
  } catch {
7535
7581
  cleanup2();
7536
- resolve18(null);
7582
+ resolve20(null);
7537
7583
  return;
7538
7584
  }
7539
7585
  stdin.resume();
@@ -8979,13 +9025,13 @@ async function readBoundedJson(path5) {
8979
9025
  await descriptor.close();
8980
9026
  }
8981
9027
  }
8982
- function accountRecords(text2, fields) {
9028
+ function accountRecords(text2, fields2) {
8983
9029
  const records = [];
8984
9030
  for (const line of text2.split("\n")) {
8985
9031
  if (line.trim() === "" || line.startsWith("#"))
8986
9032
  continue;
8987
9033
  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] ?? ""))
9034
+ 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
9035
  return void 0;
8990
9036
  records.push(parts);
8991
9037
  }
@@ -9535,9 +9581,9 @@ function scopedRetryReason(served, current) {
9535
9581
  return "version-unchanged";
9536
9582
  return "rotated";
9537
9583
  }
9538
- function decideScopedRetryAfter401(site, served, current, logger2 = defaultLogger) {
9584
+ function decideScopedRetryAfter401(site, served, current, logger3 = defaultLogger) {
9539
9585
  const retry = isScopedCredentialRotation(served, current);
9540
- logger2.debug("scoped 401 re-authorized", {
9586
+ logger3.debug("scoped 401 re-authorized", {
9541
9587
  site,
9542
9588
  credentialId: served.credentialId,
9543
9589
  servedVersion: served.recordVersion,
@@ -10110,6 +10156,7 @@ var init_interlock = __esm({
10110
10156
 
10111
10157
  // ../core/dist/common-auth-embedded/claustrum/roster.js
10112
10158
  import { createHash as createHash7 } from "node:crypto";
10159
+ import { resolve as resolve6 } from "node:path";
10113
10160
  function hash(value) {
10114
10161
  return createHash7("sha256").update(value).digest("hex");
10115
10162
  }
@@ -10330,7 +10377,7 @@ async function readVaultRoster(path5) {
10330
10377
  return decodeRoster(value);
10331
10378
  }
10332
10379
  async function mutateVaultRoster(path5, change, options = {}) {
10333
- return withLock(path5, WRITE_LOCK, async (lock) => {
10380
+ return withLock(path5, { ...WRITE_LOCK, signal: options.signal }, async (lock) => {
10334
10381
  const current = await readVaultRoster(path5);
10335
10382
  const { next, result } = await change(current, {
10336
10383
  assertOwned: () => lock.assertOwned()
@@ -10340,6 +10387,7 @@ async function mutateVaultRoster(path5, change, options = {}) {
10340
10387
  await writeJsonAtomic2(path5, next, {
10341
10388
  beforeRename: async () => {
10342
10389
  await options.beforePublish?.();
10390
+ options.signal?.throwIfAborted();
10343
10391
  await lock.assertOwned();
10344
10392
  }
10345
10393
  });
@@ -10389,43 +10437,51 @@ function receiptFence(row, receipt2) {
10389
10437
  return "bind";
10390
10438
  return "refuse";
10391
10439
  }
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
- };
10440
+ async function recordVaultQuota(path5, input2) {
10441
+ const { routeId, observation, ...receipt2 } = input2;
10442
+ return enqueueFencedVaultQuota(path5, {
10443
+ routeId,
10444
+ observation,
10445
+ accountIdentity: receipt2.accountIdentity,
10446
+ receipt: receipt2
10407
10447
  });
10408
10448
  }
10449
+ async function enqueueFencedVaultQuota(path5, publication2) {
10450
+ if (!isQuotaObservation(publication2.observation))
10451
+ return false;
10452
+ const current = pendingVaultQuota(path5, await readVaultRoster(path5));
10453
+ if (!applyVaultQuota(current, publication2).kept)
10454
+ return false;
10455
+ return enqueueVaultQuota(path5, publication2);
10456
+ }
10409
10457
  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
- });
10458
+ return enqueueFencedVaultQuota(path5, input2);
10459
+ }
10460
+ function applyVaultQuota(current, input2) {
10461
+ const row = current?.rows.find((entry) => entry.routeId === input2.routeId);
10462
+ const fence = !row ? "refuse" : input2.receipt ? receiptFence(row, input2.receipt) : row.accountIdentity !== void 0 && row.accountIdentity === input2.accountIdentity ? "hold" : "refuse";
10463
+ if (!current || !row || fence === "refuse")
10464
+ return { roster: current, kept: false };
10465
+ const quota = mergeQuotaObservation(row.quota, input2.observation);
10466
+ const bound = fence === "bind" ? { accountIdentity: input2.accountIdentity, unclaimed: true } : {};
10467
+ return {
10468
+ roster: {
10469
+ ...current,
10470
+ rows: current.rows.map((entry) => entry === row ? { ...entry, ...bound, quota } : entry)
10471
+ },
10472
+ kept: true
10473
+ };
10474
+ }
10475
+ function forgetPendingVaultDiscovery(path5) {
10476
+ pendingDiscoveries.delete(resolve6(path5));
10423
10477
  }
10424
10478
  async function refreshVaultRoster(options) {
10425
10479
  options.signal?.throwIfAborted();
10426
10480
  const active2 = async () => await options.isActive?.() ?? true;
10427
- if (!await active2())
10481
+ if (!await active2()) {
10482
+ forgetPendingVaultDiscovery(options.path);
10428
10483
  return void 0;
10484
+ }
10429
10485
  const lease = await acquireRefreshFileLock({
10430
10486
  ...DISCOVERY_LEASE,
10431
10487
  path: options.path,
@@ -10438,8 +10494,18 @@ async function refreshVaultRoster(options) {
10438
10494
  throw new ClaustrumConsumerError("roster-busy", "Claustrum account discovery is already in progress");
10439
10495
  return persisted;
10440
10496
  }
10497
+ const key = resolve6(options.path);
10498
+ let discovered;
10441
10499
  try {
10442
- const inventory = await options.custody.discover(options.signal);
10500
+ const previous = await readVaultRoster(options.path);
10501
+ const pending = pendingDiscoveries.get(key);
10502
+ discovered = pending && (pending.previousView === previous?.view || pending.inventory.view === previous?.view) ? pending : {
10503
+ inventory: await options.custody.discover(options.signal),
10504
+ previousView: previous?.view
10505
+ };
10506
+ pendingDiscoveries.delete(key);
10507
+ const { inventory } = discovered;
10508
+ options.onInventory?.(inventory);
10443
10509
  options.signal?.throwIfAborted();
10444
10510
  return await mutateVaultRoster(options.path, async (current) => {
10445
10511
  if (!await active2())
@@ -10450,7 +10516,16 @@ async function refreshVaultRoster(options) {
10450
10516
  const next = projectVaultRoster(current, inventory, projection);
10451
10517
  const changed = JSON.stringify(current) !== JSON.stringify(next);
10452
10518
  return { ...changed && { next }, result: next };
10519
+ }, {
10520
+ beforePublish: async () => {
10521
+ options.signal?.throwIfAborted();
10522
+ await lease.assertOwned();
10523
+ }
10453
10524
  });
10525
+ } catch (error) {
10526
+ if (error instanceof LockContentionError && discovered && !options.signal?.aborted && await active2())
10527
+ pendingDiscoveries.set(key, discovered);
10528
+ throw error;
10454
10529
  } finally {
10455
10530
  await lease.release();
10456
10531
  }
@@ -10487,7 +10562,7 @@ function resolveVaultPrimary(input2) {
10487
10562
  ...previous && previous.accountIdentity !== identity && { replaced: previous }
10488
10563
  };
10489
10564
  }
10490
- var DEFAULT_ROUTE_PREFIX, SKIPPED_REASONS, WRITE_LOCK, DISCOVERY_LEASE;
10565
+ var DEFAULT_ROUTE_PREFIX, SKIPPED_REASONS, WRITE_LOCK, DISCOVERY_LEASE, pendingDiscoveries;
10491
10566
  var init_roster = __esm({
10492
10567
  "../core/dist/common-auth-embedded/claustrum/roster.js"() {
10493
10568
  "use strict";
@@ -10496,6 +10571,8 @@ var init_roster = __esm({
10496
10571
  init_quota();
10497
10572
  init_errors2();
10498
10573
  init_interlock();
10574
+ init_quota_writer();
10575
+ init_quota_writer();
10499
10576
  DEFAULT_ROUTE_PREFIX = "vault:";
10500
10577
  SKIPPED_REASONS = /* @__PURE__ */ new Set([
10501
10578
  "empty credential id",
@@ -10506,9 +10583,238 @@ var init_roster = __esm({
10506
10583
  WRITE_LOCK = {
10507
10584
  name: "claustrum-roster-write",
10508
10585
  ttlMs: 1e4,
10509
- timeoutMs: 5e3
10586
+ timeoutMs: 5e3,
10587
+ renew: true
10510
10588
  };
10511
10589
  DISCOVERY_LEASE = { name: "claustrum-roster", ttlMs: 3e4 };
10590
+ pendingDiscoveries = /* @__PURE__ */ new Map();
10591
+ }
10592
+ });
10593
+
10594
+ // ../core/dist/common-auth-embedded/claustrum/quota-writer.js
10595
+ import { resolve as resolve7 } from "node:path";
10596
+ function writerFor(path5) {
10597
+ const key = resolve7(path5);
10598
+ let writer = writers.get(key);
10599
+ if (!writer) {
10600
+ writer = {
10601
+ path: key,
10602
+ pending: /* @__PURE__ */ new Map(),
10603
+ listeners: /* @__PURE__ */ new Set(),
10604
+ wake: /* @__PURE__ */ new Set(),
10605
+ abort: new AbortController(),
10606
+ failures: 0,
10607
+ draining: false,
10608
+ order: 0
10609
+ };
10610
+ writers.set(key, writer);
10611
+ }
10612
+ return writer;
10613
+ }
10614
+ function retainVaultQuotaWriter(path5, listener) {
10615
+ const writer = writerFor(path5);
10616
+ writer.listeners.add(listener);
10617
+ let released;
10618
+ return () => released ??= (() => {
10619
+ writer.listeners.delete(listener);
10620
+ return writer.listeners.size ? Promise.resolve() : drainVaultQuota(path5);
10621
+ })();
10622
+ }
10623
+ function fields(publication2) {
10624
+ const result = /* @__PURE__ */ new Map();
10625
+ const { observation } = publication2;
10626
+ const witness = JSON.stringify([
10627
+ publication2.routeId,
10628
+ publication2.receipt?.credentialId,
10629
+ publication2.receipt?.accountIdentitySource,
10630
+ publication2.receipt?.expectedAccountIdentity
10631
+ ]);
10632
+ const add = (key, at, part) => result.set(`${witness}:${key}`, {
10633
+ at,
10634
+ order: 0,
10635
+ publication: { ...publication2, observation: part }
10636
+ });
10637
+ const keyFor = (scope, label) => JSON.stringify([scope ?? "all", label]);
10638
+ const read = /* @__PURE__ */ new Set();
10639
+ for (const reading of observation.readings ?? []) {
10640
+ const key = keyFor(reading.scope, reading.label);
10641
+ read.add(key);
10642
+ add(key, observation.checkedAt, {
10643
+ checkedAt: observation.checkedAt,
10644
+ readings: [{ ...reading }]
10645
+ });
10646
+ }
10647
+ for (const pair of observation.coverage ?? []) {
10648
+ const key = keyFor(pair.scope, pair.label);
10649
+ if (!read.has(key))
10650
+ add(key, observation.checkedAt, {
10651
+ checkedAt: observation.checkedAt,
10652
+ coverage: [{ ...pair }]
10653
+ });
10654
+ }
10655
+ if (observation.budget)
10656
+ add("budget", observation.checkedAt, {
10657
+ checkedAt: observation.checkedAt,
10658
+ budget: { ...observation.budget }
10659
+ });
10660
+ for (const [name, counter] of Object.entries(observation.counters ?? {})) {
10661
+ add(`counter:${name}`, counter.checkedAt, {
10662
+ checkedAt: observation.checkedAt,
10663
+ counters: { [name]: { ...counter } }
10664
+ });
10665
+ }
10666
+ if (observation.credits)
10667
+ add("credits", observation.credits.checkedAt, {
10668
+ checkedAt: observation.checkedAt,
10669
+ credits: { ...observation.credits }
10670
+ });
10671
+ if (!result.size)
10672
+ add("empty", observation.checkedAt, { checkedAt: observation.checkedAt });
10673
+ return result;
10674
+ }
10675
+ function enqueueVaultQuota(path5, publication2) {
10676
+ if (!isQuotaObservation(publication2.observation))
10677
+ return Promise.resolve(false);
10678
+ const writer = writerFor(path5);
10679
+ const account = JSON.stringify([
10680
+ publication2.accountIdentity ?? null,
10681
+ publication2.accountIdentity === void 0 ? publication2.routeId : null
10682
+ ]);
10683
+ const pending = writer.pending.get(account) ?? /* @__PURE__ */ new Map();
10684
+ for (const [key, field] of fields(publication2)) {
10685
+ const previous = pending.get(key);
10686
+ if (!previous || field.at >= previous.at) {
10687
+ field.order = ++writer.order;
10688
+ if (field.publication.observation.coverage)
10689
+ field.priorReading = previous?.publication.observation.readings ? previous.publication : previous?.priorReading;
10690
+ pending.set(key, field);
10691
+ }
10692
+ }
10693
+ if (pending.size)
10694
+ writer.pending.set(account, pending);
10695
+ for (const listener of writer.listeners)
10696
+ listener(publication2);
10697
+ schedule(writer, COALESCE_MS);
10698
+ return Promise.resolve(true);
10699
+ }
10700
+ function orderedFields(pending) {
10701
+ return [...pending.values()].flatMap((account) => [...account.values()]).sort((a, b) => a.order - b.order);
10702
+ }
10703
+ function pendingVaultQuota(path5, roster) {
10704
+ const writer = writers.get(resolve7(path5));
10705
+ if (writer) {
10706
+ for (const field of orderedFields(writer.pending)) {
10707
+ if (field.priorReading)
10708
+ roster = applyVaultQuota(roster, field.priorReading).roster;
10709
+ roster = applyVaultQuota(roster, field.publication).roster;
10710
+ }
10711
+ }
10712
+ return roster;
10713
+ }
10714
+ function schedule(writer, delay3) {
10715
+ if (writer.running || writer.timer || !writer.pending.size || writer.abort.signal.aborted)
10716
+ return;
10717
+ writer.timer = setTimeout(() => {
10718
+ writer.timer = void 0;
10719
+ flush(writer);
10720
+ }, delay3);
10721
+ if (!writer.draining)
10722
+ writer.timer.unref?.();
10723
+ }
10724
+ function flush(writer) {
10725
+ if (writer.running || writer.abort.signal.aborted)
10726
+ return;
10727
+ const batch = new Map([...writer.pending].map(([account, pending]) => [
10728
+ account,
10729
+ new Map(pending)
10730
+ ]));
10731
+ writer.running = (async () => {
10732
+ try {
10733
+ await mutateVaultRoster(writer.path, (current) => {
10734
+ let next = current;
10735
+ for (const field of orderedFields(batch)) {
10736
+ if (field.priorReading)
10737
+ next = applyVaultQuota(next, field.priorReading).roster;
10738
+ next = applyVaultQuota(next, field.publication).roster;
10739
+ }
10740
+ return { ...next !== current && { next }, result: void 0 };
10741
+ }, { signal: writer.abort.signal });
10742
+ for (const [account, fields2] of batch) {
10743
+ const pending = writer.pending.get(account);
10744
+ for (const [key, field] of fields2) {
10745
+ if (pending?.get(key) === field)
10746
+ pending.delete(key);
10747
+ }
10748
+ if (!pending?.size)
10749
+ writer.pending.delete(account);
10750
+ }
10751
+ writer.failures = 0;
10752
+ } catch (error) {
10753
+ if (!writer.abort.signal.aborted && writer.failures++ === 0) {
10754
+ logger.warn("vault quota publication delayed; retrying", {
10755
+ error: error instanceof Error ? error.message : String(error)
10756
+ });
10757
+ }
10758
+ } finally {
10759
+ writer.running = void 0;
10760
+ for (const wake of writer.wake)
10761
+ wake();
10762
+ const backoff = writer.failures ? Math.min(5e3, 100 * 2 ** Math.min(writer.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
10763
+ schedule(writer, backoff);
10764
+ }
10765
+ })();
10766
+ }
10767
+ async function drainVaultQuota(path5, timeoutMs = 1e3) {
10768
+ const key = resolve7(path5);
10769
+ const writer = writers.get(key);
10770
+ if (!writer)
10771
+ return;
10772
+ writer.draining = true;
10773
+ clearTimeout(writer.timer);
10774
+ writer.timer = void 0;
10775
+ let deadline;
10776
+ let wake;
10777
+ const drained = new Promise((done) => {
10778
+ wake = () => {
10779
+ if (!writer.pending.size || writer.abort.signal.aborted)
10780
+ done();
10781
+ };
10782
+ writer.wake.add(wake);
10783
+ wake();
10784
+ });
10785
+ try {
10786
+ if (writer.pending.size)
10787
+ flush(writer);
10788
+ await Promise.race([
10789
+ drained,
10790
+ new Promise((done) => {
10791
+ deadline = setTimeout(done, Math.max(0, timeoutMs));
10792
+ })
10793
+ ]);
10794
+ } finally {
10795
+ clearTimeout(deadline);
10796
+ if (wake)
10797
+ writer.wake.delete(wake);
10798
+ writer.draining = false;
10799
+ if (!writer.listeners.size) {
10800
+ writer.abort.abort();
10801
+ clearTimeout(writer.timer);
10802
+ writer.pending.clear();
10803
+ if (writers.get(key) === writer)
10804
+ writers.delete(key);
10805
+ }
10806
+ }
10807
+ }
10808
+ var writers, logger, COALESCE_MS;
10809
+ var init_quota_writer = __esm({
10810
+ "../core/dist/common-auth-embedded/claustrum/quota-writer.js"() {
10811
+ "use strict";
10812
+ init_logger();
10813
+ init_quota();
10814
+ init_roster();
10815
+ writers = /* @__PURE__ */ new Map();
10816
+ logger = createLogger2("claustrum");
10817
+ COALESCE_MS = 100;
10512
10818
  }
10513
10819
  });
10514
10820
 
@@ -10523,6 +10829,7 @@ var init_consumer = __esm({
10523
10829
  init_enrollment();
10524
10830
  init_errors2();
10525
10831
  init_insula();
10832
+ init_quota_writer();
10526
10833
  init_roster();
10527
10834
  init_watch();
10528
10835
  ClaustrumConsumer = class {
@@ -10546,9 +10853,13 @@ var init_consumer = __esm({
10546
10853
  #insulaSkips = /* @__PURE__ */ new Map();
10547
10854
  /** When this instance last completed a discovery, by `now`. */
10548
10855
  #discoveredAt;
10856
+ #releaseQuotaWriter;
10549
10857
  constructor(options) {
10550
10858
  this.#options = options;
10551
10859
  this.#logger = options.logger ?? createLogger2("claustrum");
10860
+ this.#releaseQuotaWriter = retainVaultQuotaWriter(options.rosterPath, (publication2) => {
10861
+ this.#roster = applyVaultQuota(this.#roster, publication2).roster;
10862
+ });
10552
10863
  }
10553
10864
  #assertOpen(signal) {
10554
10865
  this.#shutdown.signal.throwIfAborted();
@@ -10562,7 +10873,7 @@ var init_consumer = __esm({
10562
10873
  this.#shutdown.signal,
10563
10874
  ...signal ? [signal] : []
10564
10875
  ]);
10565
- return new Promise((resolve18, reject) => {
10876
+ return new Promise((resolve20, reject) => {
10566
10877
  const cleanup2 = () => {
10567
10878
  combined.signal.removeEventListener("abort", abort);
10568
10879
  combined.dispose();
@@ -10577,7 +10888,7 @@ var init_consumer = __esm({
10577
10888
  if (combined.signal.aborted)
10578
10889
  reject(combined.signal.reason);
10579
10890
  else
10580
- resolve18(value);
10891
+ resolve20(value);
10581
10892
  }, (error) => {
10582
10893
  cleanup2();
10583
10894
  reject(error);
@@ -10677,11 +10988,9 @@ var init_consumer = __esm({
10677
10988
  let discovered;
10678
10989
  const roster = await refreshVaultRoster({
10679
10990
  path: this.#options.rosterPath,
10680
- custody: {
10681
- discover: async (signal) => {
10682
- discovered = await custody.discover(signal);
10683
- return discovered;
10684
- }
10991
+ custody,
10992
+ onInventory: (inventory) => {
10993
+ discovered = inventory;
10685
10994
  },
10686
10995
  isActive: () => this.#active(),
10687
10996
  signal: this.#shutdown.signal,
@@ -10694,7 +11003,7 @@ var init_consumer = __esm({
10694
11003
  });
10695
11004
  this.#assertOpen();
10696
11005
  const changed = roster?.view !== this.#roster?.view;
10697
- this.#roster = roster;
11006
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, roster);
10698
11007
  custody.retain(roster?.rows ?? []);
10699
11008
  if (discovered && roster?.view !== void 0)
10700
11009
  this.#grantReach = discovered.grantReach ? { view: roster.view, reach: discovered.grantReach } : void 0;
@@ -10830,7 +11139,7 @@ var init_consumer = __esm({
10830
11139
  return void 0;
10831
11140
  try {
10832
11141
  await readClaustrumEnrollmentToken(this.#options.tokenPath);
10833
- const roster = await readVaultRoster(this.#options.rosterPath);
11142
+ const roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10834
11143
  const row = roster?.rows.find((entry) => entry.routeId === routeId);
10835
11144
  return this.#normalizeInsulaQuota(row?.accountIdentity);
10836
11145
  } catch {
@@ -10844,7 +11153,7 @@ var init_consumer = __esm({
10844
11153
  return { miss: "unreachable" };
10845
11154
  try {
10846
11155
  await readClaustrumEnrollmentToken(this.#options.tokenPath);
10847
- const roster = await readVaultRoster(this.#options.rosterPath);
11156
+ const roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10848
11157
  const account = roster?.rows.find((row) => row.routeId === routeId)?.accountIdentity;
10849
11158
  if (!account || !this.#insula)
10850
11159
  return { miss: "unreachable" };
@@ -10894,7 +11203,7 @@ var init_consumer = __esm({
10894
11203
  this.#insula = void 0;
10895
11204
  throw new ClaustrumConsumerError("not-active", "Claustrum scoped custody is not active");
10896
11205
  }
10897
- const current = await readVaultRoster(this.#options.rosterPath);
11206
+ const current = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10898
11207
  this.#assertOpen(signal);
10899
11208
  const observed = roster.rows.find((row) => row.routeId === routeId);
10900
11209
  const configured = current?.rows.find((row) => row.routeId === routeId);
@@ -10973,13 +11282,13 @@ var init_consumer = __esm({
10973
11282
  async decline(routeId) {
10974
11283
  this.#assertOpen();
10975
11284
  await declineVaultRoute(this.#options.rosterPath, routeId);
10976
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11285
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10977
11286
  this.#custody?.retain(this.#roster?.rows ?? []);
10978
11287
  }
10979
11288
  async accept(routeId) {
10980
11289
  this.#assertOpen();
10981
11290
  await acceptVaultRoute(this.#options.rosterPath, routeId);
10982
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11291
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10983
11292
  }
10984
11293
  /**
10985
11294
  * Store a quota or profile observation for a vault route. The receipt the
@@ -10989,7 +11298,7 @@ var init_consumer = __esm({
10989
11298
  */
10990
11299
  async recordQuota(routeId, observation, attempt) {
10991
11300
  this.#assertOpen();
10992
- const kept = await recordVaultQuota(this.#options.rosterPath, {
11301
+ return recordVaultQuota(this.#options.rosterPath, {
10993
11302
  routeId,
10994
11303
  observation,
10995
11304
  credentialId: attempt.credentialId,
@@ -11001,27 +11310,21 @@ var init_consumer = __esm({
11001
11310
  expectedAccountIdentity: attempt.expectedAccountIdentity
11002
11311
  }
11003
11312
  });
11004
- if (kept)
11005
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11006
- return kept;
11007
11313
  }
11008
11314
  /**
11009
11315
  * Store a background observation that belongs to an account rather than to
11010
11316
  * a served credential (an insula reading from `cachedInsulaQuotaForRoute`).
11011
11317
  * It lands only while the route is still bound to that known account, so no
11012
11318
  * 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.
11319
+ * Memory updates immediately; durable publication is detached and coalesced.
11014
11320
  */
11015
11321
  async recordAccountQuota(routeId, accountIdentity, observation) {
11016
11322
  this.#assertOpen();
11017
- const kept = await recordVaultAccountQuota(this.#options.rosterPath, {
11323
+ return recordVaultAccountQuota(this.#options.rosterPath, {
11018
11324
  routeId,
11019
11325
  accountIdentity,
11020
11326
  observation
11021
11327
  });
11022
- if (kept)
11023
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11024
- return kept;
11025
11328
  }
11026
11329
  close() {
11027
11330
  if (this.#shutdown.signal.aborted)
@@ -11036,6 +11339,13 @@ var init_consumer = __esm({
11036
11339
  this.#insula = void 0;
11037
11340
  this.#roster = void 0;
11038
11341
  this.#grantReach = void 0;
11342
+ void this.#releaseQuotaWriter();
11343
+ forgetPendingVaultDiscovery(this.#options.rosterPath);
11344
+ }
11345
+ /** Close immediately; the last consumer also waits for the writer's bounded drain. */
11346
+ async dispose() {
11347
+ this.close();
11348
+ await this.#releaseQuotaWriter();
11039
11349
  }
11040
11350
  };
11041
11351
  }
@@ -11078,6 +11388,7 @@ __export(claustrum_exports, {
11078
11388
  declineAccount: () => declineAccount,
11079
11389
  declineVaultRoute: () => declineVaultRoute,
11080
11390
  disconnectClaustrumEnrollment: () => disconnectClaustrumEnrollment,
11391
+ drainVaultQuota: () => drainVaultQuota,
11081
11392
  enrollmentAuthority: () => enrollmentAuthority,
11082
11393
  enrollmentName: () => enrollmentName,
11083
11394
  getClaustrumEnrollmentPaths: () => getClaustrumEnrollmentPaths,
@@ -11116,6 +11427,7 @@ var init_claustrum = __esm({
11116
11427
  init_host_slot();
11117
11428
  init_insula();
11118
11429
  init_interlock();
11430
+ init_quota_writer();
11119
11431
  init_roster();
11120
11432
  init_watch();
11121
11433
  }
@@ -11196,7 +11508,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11196
11508
  if (!released && lastUpdate + RENEWAL_STALE < Date.now())
11197
11509
  compromise();
11198
11510
  }
11199
- function schedule(delay3 = UPDATE) {
11511
+ function schedule2(delay3 = UPDATE) {
11200
11512
  if (released)
11201
11513
  return;
11202
11514
  timer = setTimeout(() => {
@@ -11210,7 +11522,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11210
11522
  if (errorCode(error) === "ENOENT" || lastUpdate + RENEWAL_STALE < Date.now())
11211
11523
  compromise();
11212
11524
  else
11213
- schedule(1e3);
11525
+ schedule2(1e3);
11214
11526
  }
11215
11527
  async function update() {
11216
11528
  assertFresh();
@@ -11243,14 +11555,14 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11243
11555
  mtime = next.getTime();
11244
11556
  lastUpdate = Date.now();
11245
11557
  active.set(path5, { ...identity, mtime, renewedAt: lastUpdate });
11246
- schedule();
11558
+ schedule2();
11247
11559
  }
11248
11560
  onRenew?.(async () => {
11249
11561
  if (timer)
11250
11562
  clearTimeout(timer);
11251
11563
  await update();
11252
11564
  });
11253
- schedule();
11565
+ schedule2();
11254
11566
  return {
11255
11567
  assertFresh,
11256
11568
  async release() {
@@ -11309,7 +11621,7 @@ var init_lock = __esm({
11309
11621
  import { createHash as createHash8 } from "node:crypto";
11310
11622
  import { constants as constants2 } from "node:fs";
11311
11623
  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";
11624
+ import { dirname as dirname10, resolve as resolve8 } from "node:path";
11313
11625
  import { setTimeout as sleep2 } from "node:timers/promises";
11314
11626
  function rootSpans(text2) {
11315
11627
  let i = text2.indexOf("{") + 1;
@@ -11510,8 +11822,8 @@ function createPiSlot(options, onStep, hooks) {
11510
11822
  if (!provider2 || !options.authPath || !options.stashPath || !placeholderKey || placeholderKey.startsWith("!") || placeholderKey.includes("$") || !Number.isFinite(timeout) || timeout < 0) {
11511
11823
  throw new PiSlotError("invalid-options");
11512
11824
  }
11513
- const authPath = resolve6(options.authPath);
11514
- const stashPath = resolve6(options.stashPath);
11825
+ const authPath = resolve8(options.authPath);
11826
+ const stashPath = resolve8(options.stashPath);
11515
11827
  if (authPath === stashPath || stashPath === `${authPath}.lock`) {
11516
11828
  throw new PiSlotError("invalid-options");
11517
11829
  }
@@ -11680,7 +11992,7 @@ var init_pi_slot = __esm({
11680
11992
 
11681
11993
  // src/plugin/index.ts
11682
11994
  import { createHash as createHash20, randomUUID as randomUUID20 } from "node:crypto";
11683
- import { join as join31, resolve as resolve17 } from "node:path";
11995
+ import { join as join31, resolve as resolve19 } from "node:path";
11684
11996
 
11685
11997
  // ../core/dist/abort-forwarding.js
11686
11998
  function forwardAbort(source, target) {
@@ -18228,7 +18540,7 @@ async function rmEvictingDir(evictingPath) {
18228
18540
  });
18229
18541
  }
18230
18542
  async function sleep(ms) {
18231
- await new Promise((resolve18) => setTimeout(resolve18, ms));
18543
+ await new Promise((resolve20) => setTimeout(resolve20, ms));
18232
18544
  }
18233
18545
  async function acquireFencedFileLock(options) {
18234
18546
  const lockPath = `${options.path}.${options.name}.lock`;
@@ -18344,8 +18656,8 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
18344
18656
  let released = false;
18345
18657
  let lost = false;
18346
18658
  let lostResolve = null;
18347
- let lostPromise = new Promise((resolve18) => {
18348
- lostResolve = resolve18;
18659
+ let lostPromise = new Promise((resolve20) => {
18660
+ lostResolve = resolve20;
18349
18661
  });
18350
18662
  const markLost = () => {
18351
18663
  if (lost)
@@ -18355,9 +18667,9 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
18355
18667
  clearInterval(renewTimer);
18356
18668
  renewTimer = null;
18357
18669
  }
18358
- const resolve18 = lostResolve;
18670
+ const resolve20 = lostResolve;
18359
18671
  lostResolve = null;
18360
- resolve18?.();
18672
+ resolve20?.();
18361
18673
  };
18362
18674
  const setupRenew = () => {
18363
18675
  if (options.renew === false)
@@ -18584,7 +18896,7 @@ var AccountStorageUnreadableError = class extends Error {
18584
18896
  }
18585
18897
  };
18586
18898
  var RETRY_DELAYS_MS = [100, 200, 400, 800, 1e3];
18587
- var DEFAULT_SLEEP = (ms) => new Promise((resolve18) => setTimeout(resolve18, ms));
18899
+ var DEFAULT_SLEEP = (ms) => new Promise((resolve20) => setTimeout(resolve20, ms));
18588
18900
  var DEFAULT_BUILD_BACKUP_PATH = (path5, now) => `${path5}.corrupt-${now.toISOString().replace(/[:.]/g, "-")}`;
18589
18901
  async function ensureSecurePermissions(path5) {
18590
18902
  try {
@@ -18975,7 +19287,7 @@ async function saveAccountStorageReplace(path5, incoming) {
18975
19287
  return mutateAccountStorage(path5, () => incoming);
18976
19288
  }
18977
19289
  async function clearAccountStorage(path5) {
18978
- const sleep5 = (ms) => new Promise((resolve18) => setTimeout(resolve18, ms));
19290
+ const sleep5 = (ms) => new Promise((resolve20) => setTimeout(resolve20, ms));
18979
19291
  const lock = await acquireWithRetry(path5, sleep5);
18980
19292
  try {
18981
19293
  await assertLegacyAccountStorageWritable(path5);
@@ -20166,8 +20478,8 @@ var AccountManager = class _AccountManager {
20166
20478
  await this.saveInFlight;
20167
20479
  return;
20168
20480
  }
20169
- return new Promise((resolve18, reject) => {
20170
- this.savePromiseResolvers.push({ resolve: resolve18, reject });
20481
+ return new Promise((resolve20, reject) => {
20482
+ this.savePromiseResolvers.push({ resolve: resolve20, reject });
20171
20483
  });
20172
20484
  }
20173
20485
  async dispose() {
@@ -20210,8 +20522,8 @@ var AccountManager = class _AccountManager {
20210
20522
  reject(error);
20211
20523
  throw error;
20212
20524
  }
20213
- for (const { resolve: resolve18 } of resolvers)
20214
- resolve18();
20525
+ for (const { resolve: resolve20 } of resolvers)
20526
+ resolve20();
20215
20527
  }
20216
20528
  async executeSave() {
20217
20529
  this.savePending = false;
@@ -20225,16 +20537,16 @@ var AccountManager = class _AccountManager {
20225
20537
  }
20226
20538
  try {
20227
20539
  await this.saveToDisk();
20228
- for (const { resolve: resolve18 } of resolvers) {
20229
- resolve18();
20540
+ for (const { resolve: resolve20 } of resolvers) {
20541
+ resolve20();
20230
20542
  }
20231
20543
  } catch (error) {
20232
20544
  if (isStorageLockContention(error)) {
20233
20545
  this.onDiagnostic?.("Skipped account-state persist due to storage lock contention", {
20234
20546
  error: String(error)
20235
20547
  });
20236
- for (const { resolve: resolve18 } of resolvers) {
20237
- resolve18();
20548
+ for (const { resolve: resolve20 } of resolvers) {
20549
+ resolve20();
20238
20550
  }
20239
20551
  return;
20240
20552
  }
@@ -20711,7 +21023,7 @@ function getHttpsProxy(url) {
20711
21023
  }
20712
21024
  }
20713
21025
  function waitForHead(socket, timeoutMs, onTimeout) {
20714
- return new Promise((resolve18, reject) => {
21026
+ return new Promise((resolve20, reject) => {
20715
21027
  let buffer = Buffer3.alloc(0);
20716
21028
  const timeout = setTimeout(() => {
20717
21029
  onTimeout();
@@ -20734,7 +21046,7 @@ function waitForHead(socket, timeoutMs, onTimeout) {
20734
21046
  return;
20735
21047
  const head = buffer.subarray(0, marker).toString("latin1");
20736
21048
  const leftover = buffer.subarray(marker + 4);
20737
- cleanup2(() => resolve18({ head, leftover }));
21049
+ cleanup2(() => resolve20({ head, leftover }));
20738
21050
  };
20739
21051
  socket.on("data", onData);
20740
21052
  socket.once("error", onError);
@@ -20748,7 +21060,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
20748
21060
  port: Number(proxyUrl.port || DEFAULT_PROXY_PORT),
20749
21061
  signal: signal ?? void 0
20750
21062
  });
20751
- await new Promise((resolve18, reject) => {
21063
+ await new Promise((resolve20, reject) => {
20752
21064
  const timeout = setTimeout(() => {
20753
21065
  onDebug?.(`agy transport proxy connect timeout after ${timeoutMs}ms`);
20754
21066
  proxySocket.destroy();
@@ -20757,7 +21069,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
20757
21069
  const cleanup2 = () => clearTimeout(timeout);
20758
21070
  proxySocket.once("connect", () => {
20759
21071
  cleanup2();
20760
- resolve18();
21072
+ resolve20();
20761
21073
  });
20762
21074
  proxySocket.once("error", (error) => {
20763
21075
  cleanup2();
@@ -20782,7 +21094,7 @@ Host: ${targetHost}:${targetPort}\r
20782
21094
  if (leftover.length > 0) {
20783
21095
  proxySocket.unshift(leftover);
20784
21096
  }
20785
- return await new Promise((resolve18, reject) => {
21097
+ return await new Promise((resolve20, reject) => {
20786
21098
  const tlsOptions = {
20787
21099
  socket: proxySocket,
20788
21100
  servername: targetHost,
@@ -20797,7 +21109,7 @@ Host: ${targetHost}:${targetPort}\r
20797
21109
  const cleanup2 = () => clearTimeout(timeout);
20798
21110
  tlsSocket.once("secureConnect", () => {
20799
21111
  cleanup2();
20800
- resolve18(tlsSocket);
21112
+ resolve20(tlsSocket);
20801
21113
  });
20802
21114
  tlsSocket.once("error", (error) => {
20803
21115
  cleanup2();
@@ -20806,7 +21118,7 @@ Host: ${targetHost}:${targetPort}\r
20806
21118
  });
20807
21119
  }
20808
21120
  async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
20809
- return await new Promise((resolve18, reject) => {
21121
+ return await new Promise((resolve20, reject) => {
20810
21122
  const tlsOptions = {
20811
21123
  host: targetUrl.hostname,
20812
21124
  port: Number(targetUrl.port || DEFAULT_HTTPS_PORT),
@@ -20822,7 +21134,7 @@ async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
20822
21134
  const cleanup2 = () => clearTimeout(timeout);
20823
21135
  socket.once("secureConnect", () => {
20824
21136
  cleanup2();
20825
- resolve18(socket);
21137
+ resolve20(socket);
20826
21138
  });
20827
21139
  socket.once("error", (error) => {
20828
21140
  cleanup2();
@@ -22025,11 +22337,11 @@ function containsCredential(value, credentials, projectIds, seen = /* @__PURE__
22025
22337
  function redactCredentialError(error, credentials, projectIds) {
22026
22338
  const source = error instanceof Error || error instanceof DOMException ? error : void 0;
22027
22339
  const message = redactCredentialText(source?.message ?? String(error), credentials, projectIds);
22028
- const fields = source ? Reflect.ownKeys(source).map((key) => ({
22340
+ const fields2 = source ? Reflect.ownKeys(source).map((key) => ({
22029
22341
  key,
22030
22342
  descriptor: Object.getOwnPropertyDescriptor(source, key)
22031
22343
  })) : [];
22032
- const cause = fields.find(({ key }) => key === "cause")?.descriptor;
22344
+ const cause = fields2.find(({ key }) => key === "cause")?.descriptor;
22033
22345
  const secretCause = cause && (!("value" in cause) || containsCredential(cause.value, credentials, projectIds));
22034
22346
  try {
22035
22347
  if (source) {
@@ -22039,7 +22351,7 @@ function redactCredentialError(error, credentials, projectIds) {
22039
22351
  configurable: true,
22040
22352
  writable: true
22041
22353
  });
22042
- for (const { key, descriptor } of fields) {
22354
+ for (const { key, descriptor } of fields2) {
22043
22355
  if (key === "message" || key === "cause" || !("value" in descriptor))
22044
22356
  continue;
22045
22357
  const value = scrub2(descriptor.value, credentials, projectIds);
@@ -22054,7 +22366,7 @@ function redactCredentialError(error, credentials, projectIds) {
22054
22366
  }
22055
22367
  const safe = new Error(message);
22056
22368
  safe.name = redactCredentialText(source?.name ?? "Error", credentials, projectIds);
22057
- for (const { key, descriptor } of fields) {
22369
+ for (const { key, descriptor } of fields2) {
22058
22370
  if (key === "message" || key === "cause" || !("value" in descriptor))
22059
22371
  continue;
22060
22372
  Object.defineProperty(safe, key, {
@@ -22365,8 +22677,8 @@ function getDefaultTierId(allowedTiers) {
22365
22677
  return allowedTiers[0]?.id;
22366
22678
  }
22367
22679
  function wait(ms) {
22368
- return new Promise((resolve18) => {
22369
- setTimeout(resolve18, ms);
22680
+ return new Promise((resolve20) => {
22681
+ setTimeout(resolve20, ms);
22370
22682
  });
22371
22683
  }
22372
22684
  function extractManagedProjectId(payload) {
@@ -24393,12 +24705,12 @@ async function commitVaultProviderState(input2) {
24393
24705
  function untilAborted(pending, signal) {
24394
24706
  if (!signal)
24395
24707
  return pending;
24396
- return new Promise((resolve18, reject) => {
24708
+ return new Promise((resolve20, reject) => {
24397
24709
  const abort = () => reject(signal.reason);
24398
24710
  signal.addEventListener("abort", abort, { once: true });
24399
24711
  if (signal.aborted)
24400
24712
  abort();
24401
- pending.then(resolve18, reject).finally(() => signal.removeEventListener("abort", abort));
24713
+ pending.then(resolve20, reject).finally(() => signal.removeEventListener("abort", abort));
24402
24714
  });
24403
24715
  }
24404
24716
  var AntigravityVaultSourceError = class extends Error {
@@ -24763,7 +25075,7 @@ async function initAntigravityVersion() {
24763
25075
  // src/cli.ts
24764
25076
  import { execFile } from "node:child_process";
24765
25077
  import { realpathSync as realpathSync2 } from "node:fs";
24766
- import { resolve as resolve12 } from "node:path";
25078
+ import { resolve as resolve14 } from "node:path";
24767
25079
  import { createInterface } from "node:readline/promises";
24768
25080
  import { fileURLToPath as fileURLToPath2 } from "node:url";
24769
25081
  import { promisify } from "node:util";
@@ -24821,17 +25133,17 @@ import {
24821
25133
  writeFileSync
24822
25134
  } from "node:fs";
24823
25135
  import { homedir as homedir3 } from "node:os";
24824
- import { dirname as dirname14, join as join8, resolve as resolve9 } from "node:path";
25136
+ import { dirname as dirname14, join as join8, resolve as resolve11 } from "node:path";
24825
25137
 
24826
25138
  // src/common-auth-embedded/logger/engine.js
24827
25139
  import { appendFileSync as appendFileSync2, chmodSync as chmodSync2, existsSync as existsSync2, renameSync as renameSync2, statSync as statSync3 } from "node:fs";
24828
25140
  import { open as open8 } from "node:fs/promises";
24829
- import { dirname as dirname13, resolve as resolve8 } from "node:path";
25141
+ import { dirname as dirname13, resolve as resolve10 } from "node:path";
24830
25142
 
24831
25143
  // src/common-auth-embedded/fs/private-files.js
24832
25144
  import { randomUUID as randomUUID13 } from "node:crypto";
24833
25145
  import { lstat as lstat4, readFile as readFile8, rename as rename7, unlink as unlink8 } from "node:fs/promises";
24834
- import { dirname as dirname12, resolve as resolve7 } from "node:path";
25146
+ import { dirname as dirname12, resolve as resolve9 } from "node:path";
24835
25147
  var windowsPrivateFiles2 = process.platform === "win32";
24836
25148
  var migrationNotices2 = /* @__PURE__ */ new Set();
24837
25149
  function ioCode2(detail) {
@@ -24882,7 +25194,7 @@ async function privateOperation2(path5, stage, operation) {
24882
25194
  }
24883
25195
  var safeParentOptionsForTest2;
24884
25196
  async function verifySafeDirectory2(path5, options) {
24885
- path5 = resolve7(path5);
25197
+ path5 = resolve9(path5);
24886
25198
  options ??= safeParentOptionsForTest2;
24887
25199
  await privateOperation2(path5, "safe-parent", async () => {
24888
25200
  const result = await (await loadBackend2()).verifySafeParent(path5, options);
@@ -24897,7 +25209,7 @@ async function verifySafeDirectory2(path5, options) {
24897
25209
  });
24898
25210
  }
24899
25211
  async function verifyPrivate2(path5, kind, migrate = false) {
24900
- path5 = resolve7(path5);
25212
+ path5 = resolve9(path5);
24901
25213
  if (kind === "directory")
24902
25214
  return verifySafeDirectory2(path5);
24903
25215
  await privateOperation2(path5, "verify", async () => {
@@ -24932,7 +25244,7 @@ async function verifyPrivate2(path5, kind, migrate = false) {
24932
25244
  });
24933
25245
  }
24934
25246
  async function ensurePrivateDirectory3(path5, _migrate = false, options) {
24935
- path5 = resolve7(path5);
25247
+ path5 = resolve9(path5);
24936
25248
  await privateOperation2(path5, "directory", async () => {
24937
25249
  const api = await loadBackend2();
24938
25250
  try {
@@ -24963,7 +25275,7 @@ async function readPrivateText2(path5, migrate = false) {
24963
25275
  async function readPrivateBuffer2(path5, migrate = false) {
24964
25276
  if (!windowsPrivateFiles2)
24965
25277
  return readFile8(path5);
24966
- path5 = resolve7(path5);
25278
+ path5 = resolve9(path5);
24967
25279
  if (migrate) {
24968
25280
  await verifySafeDirectory2(dirname12(path5));
24969
25281
  await verifyPrivate2(path5, "file", true);
@@ -24971,20 +25283,20 @@ async function readPrivateBuffer2(path5, migrate = false) {
24971
25283
  return privateOperation2(path5, "read", async () => (await loadBackend2()).readOwnerOnly(path5));
24972
25284
  }
24973
25285
  async function createPrivateBytes2(path5, bytes) {
24974
- await verifySafeDirectory2(dirname12(resolve7(path5)));
25286
+ await verifySafeDirectory2(dirname12(resolve9(path5)));
24975
25287
  await privateOperation2(path5, "create", async () => {
24976
- await (await loadBackend2()).createPrivateFile(resolve7(path5), bytes);
25288
+ await (await loadBackend2()).createPrivateFile(resolve9(path5), bytes);
24977
25289
  });
24978
25290
  }
24979
25291
  async function createPrivateDirectoryExclusive2(path5) {
24980
- await verifySafeDirectory2(dirname12(resolve7(path5)));
25292
+ await verifySafeDirectory2(dirname12(resolve9(path5)));
24981
25293
  await privateOperation2(path5, "directory-create", async () => {
24982
- await (await loadBackend2()).createOwnerOnly(resolve7(path5), { kind: "dir" });
25294
+ await (await loadBackend2()).createOwnerOnly(resolve9(path5), { kind: "dir" });
24983
25295
  });
24984
25296
  }
24985
25297
  async function replaceWindowsFile2(from, to, options = {}) {
24986
- from = resolve7(from);
24987
- to = resolve7(to);
25298
+ from = resolve9(from);
25299
+ to = resolve9(to);
24988
25300
  const now = options.now ?? (() => performance.now());
24989
25301
  const start = now();
24990
25302
  const leaseDeadline = options.deadline ?? Infinity;
@@ -25027,7 +25339,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
25027
25339
  throw error;
25028
25340
  }
25029
25341
  async function writePrivateAtomic2(path5, bytes, options = {}) {
25030
- path5 = resolve7(path5);
25342
+ path5 = resolve9(path5);
25031
25343
  await ensurePrivateDirectory3(dirname12(path5));
25032
25344
  try {
25033
25345
  await verifyPrivate2(path5, "file", true);
@@ -25035,7 +25347,7 @@ async function writePrivateAtomic2(path5, bytes, options = {}) {
25035
25347
  if (error.code !== "ENOENT")
25036
25348
  throw error;
25037
25349
  }
25038
- const stage = resolve7(options.stagePath ?? `${path5}.${randomUUID13()}.tmp`);
25350
+ const stage = resolve9(options.stagePath ?? `${path5}.${randomUUID13()}.tmp`);
25039
25351
  if (dirname12(stage) !== dirname12(path5))
25040
25352
  throw new PrivateFileError2(path5, "stage-directory", { code: "EXDEV" });
25041
25353
  let created = false;
@@ -25111,15 +25423,15 @@ function createRedactor2(options = {}) {
25111
25423
  return SECRET_KEY_EXACT2.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
25112
25424
  }
25113
25425
  function errorEntries(error) {
25114
- const fields = error;
25426
+ const fields2 = error;
25115
25427
  const entries = [
25116
25428
  ["name", error.name],
25117
25429
  ["message", error.message],
25118
25430
  ["stack", error.stack]
25119
25431
  ];
25120
25432
  for (const key of ["code", "status", "cause"])
25121
- if (fields[key] !== void 0)
25122
- entries.push([key, fields[key]]);
25433
+ if (fields2[key] !== void 0)
25434
+ entries.push([key, fields2[key]]);
25123
25435
  const listed = new Set(entries.map(([key]) => key));
25124
25436
  for (const entry of Object.entries(error))
25125
25437
  if (!listed.has(entry[0]))
@@ -25220,7 +25532,7 @@ async function openWindowsFile2(sink, file) {
25220
25532
  return sink.handle;
25221
25533
  }
25222
25534
  async function flushWindowsFile2(sink, file, text2) {
25223
- file = resolve8(file);
25535
+ file = resolve10(file);
25224
25536
  try {
25225
25537
  if (sink.file !== file)
25226
25538
  await closeWindowsFile2(sink);
@@ -25357,7 +25669,7 @@ function createEngine2(options) {
25357
25669
  } catch {
25358
25670
  }
25359
25671
  }
25360
- function schedule() {
25672
+ function schedule2() {
25361
25673
  if (!timer)
25362
25674
  timer = setTimeout(() => {
25363
25675
  timer = void 0;
@@ -25399,7 +25711,7 @@ function createEngine2(options) {
25399
25711
  void flushed.catch(() => {
25400
25712
  });
25401
25713
  } else
25402
- schedule();
25714
+ schedule2();
25403
25715
  } catch {
25404
25716
  }
25405
25717
  }
@@ -25740,13 +26052,13 @@ function closeDebugStream(state) {
25740
26052
  state.logWriter = () => {
25741
26053
  };
25742
26054
  if (state.logFilePath) liveLogFilePaths.delete(state.logFilePath);
25743
- return new Promise((resolve18) => {
25744
- current.once("close", () => resolve18());
25745
- current.once("error", () => resolve18());
26055
+ return new Promise((resolve20) => {
26056
+ current.once("close", () => resolve20());
26057
+ current.once("error", () => resolve20());
25746
26058
  try {
25747
26059
  current.end();
25748
26060
  } catch {
25749
- resolve18();
26061
+ resolve20();
25750
26062
  }
25751
26063
  });
25752
26064
  }
@@ -26018,13 +26330,13 @@ function closeDebugLog() {
26018
26330
  if (!state || !current) return Promise.resolve();
26019
26331
  state.logStream = null;
26020
26332
  if (state.logFilePath) liveLogFilePaths.delete(state.logFilePath);
26021
- return new Promise((resolve18) => {
26022
- current.once("close", () => resolve18());
26023
- current.once("error", () => resolve18());
26333
+ return new Promise((resolve20) => {
26334
+ current.once("close", () => resolve20());
26335
+ current.once("error", () => resolve20());
26024
26336
  try {
26025
26337
  current.end();
26026
26338
  } catch {
26027
- resolve18();
26339
+ resolve20();
26028
26340
  }
26029
26341
  });
26030
26342
  }
@@ -26391,7 +26703,7 @@ var LegacyAccountPoolRetiredError = class extends Error {
26391
26703
  };
26392
26704
  async function assertLegacyPoolInUse(legacyPath) {
26393
26705
  try {
26394
- await assertLegacyAccountStorageWritable(resolve9(legacyPath));
26706
+ await assertLegacyAccountStorageWritable(resolve11(legacyPath));
26395
26707
  } catch (error) {
26396
26708
  throw new LegacyAccountPoolRetiredError(legacyPath, { cause: error });
26397
26709
  }
@@ -26411,7 +26723,7 @@ function refusalMessage(admission) {
26411
26723
  }
26412
26724
  async function bindingOf(options) {
26413
26725
  const now = options.now ?? (() => Date.now());
26414
- const legacyPath = resolve9(options.legacyPath ?? getStoragePath());
26726
+ const legacyPath = resolve11(options.legacyPath ?? getStoragePath());
26415
26727
  return {
26416
26728
  legacyPath,
26417
26729
  now,
@@ -26479,7 +26791,7 @@ async function openAccountStore(options) {
26479
26791
  }
26480
26792
  function initializeFreshAccountStoreFor(modules, options = {}) {
26481
26793
  return initializeFreshAccountStore(modules, {
26482
- legacyPath: resolve9(options.legacyPath ?? getStoragePath()),
26794
+ legacyPath: resolve11(options.legacyPath ?? getStoragePath()),
26483
26795
  now: options.now ?? (() => Date.now())
26484
26796
  });
26485
26797
  }
@@ -27102,7 +27414,7 @@ function drainSidebarWrites() {
27102
27414
  return sidebarWriteChain;
27103
27415
  }
27104
27416
  async function sleep3(ms) {
27105
- await new Promise((resolve18) => setTimeout(resolve18, ms));
27417
+ await new Promise((resolve20) => setTimeout(resolve20, ms));
27106
27418
  }
27107
27419
  async function acquireSidebarLockWithRetry(stateFile) {
27108
27420
  const start = Date.now();
@@ -27412,8 +27724,8 @@ var openCodeStore = {
27412
27724
  clear: async () => {
27413
27725
  }
27414
27726
  };
27415
- function defaultDiagnostic(message, fields) {
27416
- debugLogToFile(fields ? `${message} ${JSON.stringify(fields)}` : message);
27727
+ function defaultDiagnostic(message, fields2) {
27728
+ debugLogToFile(fields2 ? `${message} ${JSON.stringify(fields2)}` : message);
27417
27729
  }
27418
27730
  var AccountStoreNotReadyError = class extends Error {
27419
27731
  read;
@@ -27560,7 +27872,7 @@ function createLocationQuotaManager(options) {
27560
27872
  fetchTimeoutMs: options.fetchTimeoutMs
27561
27873
  });
27562
27874
  const sidebar = options.sidebar;
27563
- const logger2 = options.logger;
27875
+ const logger3 = options.logger;
27564
27876
  return withSidebarPushAfterRefresh(
27565
27877
  manager,
27566
27878
  sidebar ? (account) => pushSidebarQuotaSnapshot(
@@ -27569,7 +27881,7 @@ function createLocationQuotaManager(options) {
27569
27881
  sidebar.getActiveIndexByFamily,
27570
27882
  {
27571
27883
  write: sidebar.write,
27572
- logger: logger2,
27884
+ logger: logger3,
27573
27885
  healthScore: sidebar.healthScore ?? null,
27574
27886
  now: sidebar.now
27575
27887
  }
@@ -27933,14 +28245,14 @@ var LocalQuotaGrantStaleError = class extends Error {
27933
28245
  name = "LocalQuotaGrantStaleError";
27934
28246
  };
27935
28247
  function untilQuotaAborted(pending, signal) {
27936
- return new Promise((resolve18, reject) => {
28248
+ return new Promise((resolve20, reject) => {
27937
28249
  const abort = () => reject(signal.reason);
27938
28250
  if (signal.aborted) abort();
27939
28251
  else signal.addEventListener("abort", abort, { once: true });
27940
28252
  void pending.then(
27941
28253
  (value) => {
27942
28254
  signal.removeEventListener("abort", abort);
27943
- resolve18(value);
28255
+ resolve20(value);
27944
28256
  },
27945
28257
  (error) => {
27946
28258
  signal.removeEventListener("abort", abort);
@@ -28300,7 +28612,7 @@ function heldAccount(manager, ref) {
28300
28612
  );
28301
28613
  }
28302
28614
  function createStoreQuotaService(options) {
28303
- const { manager, logger: logger2 } = options;
28615
+ const { manager, logger: logger3 } = options;
28304
28616
  const credentials = options.credentials ?? createLocalAccountCredentials(manager, { repository: options.repository });
28305
28617
  const authorize = async (account, _signal, purpose = "required") => {
28306
28618
  const ref = account.rowRef;
@@ -28373,11 +28685,11 @@ function createStoreQuotaService(options) {
28373
28685
  };
28374
28686
  const fetchAccountQuota = createAuthorizedFetchAccountQuota({
28375
28687
  authorize: (account) => authorize(account),
28376
- logger: logger2,
28688
+ logger: logger3,
28377
28689
  transport: options.transport
28378
28690
  });
28379
28691
  const quotaManager = createLocationQuotaManager({
28380
- logger: logger2,
28692
+ logger: logger3,
28381
28693
  fetchAccountQuota,
28382
28694
  // Backoff and cache are per credential: a re-authenticated row starts
28383
28695
  // fresh instead of inheriting its predecessor's state.
@@ -28450,7 +28762,7 @@ function createStoreQuotaService(options) {
28450
28762
  (failure2) => failure2.rowId
28451
28763
  );
28452
28764
  failedRows = report === void 0 || failedIds.length === 0 || failedIds.some((id) => id === void 0) ? "all" : new Set(failedIds.filter((id) => id !== void 0));
28453
- logger2.debug("quota readings were not all persisted", {
28765
+ logger3.debug("quota readings were not all persisted", {
28454
28766
  error: error instanceof Error ? error.message : String(error)
28455
28767
  });
28456
28768
  }
@@ -28561,12 +28873,12 @@ async function startOAuthListener({
28561
28873
  let resolveCallback;
28562
28874
  let rejectCallback;
28563
28875
  let timeoutHandle;
28564
- const callbackPromise = new Promise((resolve18, reject) => {
28876
+ const callbackPromise = new Promise((resolve20, reject) => {
28565
28877
  resolveCallback = (url) => {
28566
28878
  if (settled) return;
28567
28879
  settled = true;
28568
28880
  if (timeoutHandle) clearTimeout(timeoutHandle);
28569
- resolve18(url);
28881
+ resolve20(url);
28570
28882
  };
28571
28883
  rejectCallback = (error) => {
28572
28884
  if (settled) return;
@@ -28725,7 +29037,7 @@ async function startOAuthListener({
28725
29037
  });
28726
29038
  });
28727
29039
  const bindAddress = getBindAddress();
28728
- await new Promise((resolve18, reject) => {
29040
+ await new Promise((resolve20, reject) => {
28729
29041
  const handleError = (error) => {
28730
29042
  server.off("error", handleError);
28731
29043
  if (error.code === "EADDRINUSE") {
@@ -28741,7 +29053,7 @@ async function startOAuthListener({
28741
29053
  server.once("error", handleError);
28742
29054
  server.listen(port, bindAddress, () => {
28743
29055
  server.off("error", handleError);
28744
- resolve18();
29056
+ resolve20();
28745
29057
  });
28746
29058
  });
28747
29059
  server.on("error", (error) => {
@@ -28749,7 +29061,7 @@ async function startOAuthListener({
28749
29061
  });
28750
29062
  return {
28751
29063
  waitForCallback: () => callbackPromise,
28752
- close: () => new Promise((resolve18, reject) => {
29064
+ close: () => new Promise((resolve20, reject) => {
28753
29065
  server.close((error) => {
28754
29066
  if (error && error.code !== "ERR_SERVER_NOT_RUNNING") {
28755
29067
  reject(error);
@@ -28758,7 +29070,7 @@ async function startOAuthListener({
28758
29070
  if (!settled) {
28759
29071
  rejectCallback(new Error("OAuth listener closed before callback"));
28760
29072
  }
28761
- resolve18();
29073
+ resolve20();
28762
29074
  });
28763
29075
  })
28764
29076
  };
@@ -28770,7 +29082,7 @@ async function startOAuthListener({
28770
29082
 
28771
29083
  // src/setup.ts
28772
29084
  import { lstat as lstat5, readFile as readFile13 } from "node:fs/promises";
28773
- import { join as join16, resolve as resolve11 } from "node:path";
29085
+ import { join as join16, resolve as resolve13 } from "node:path";
28774
29086
 
28775
29087
  // src/auth-method-labels.ts
28776
29088
  var OPENCODE2_POOL_AUTH_LABEL = "Google (antigravity-auth pool, browser)";
@@ -28942,7 +29254,7 @@ async function select2(terminal, items, options) {
28942
29254
  writeLine("");
28943
29255
  renderedLines = lines;
28944
29256
  };
28945
- return new Promise((resolve18) => {
29257
+ return new Promise((resolve20) => {
28946
29258
  const wasRaw = stdin.isRaw ?? false;
28947
29259
  const cleanup2 = () => {
28948
29260
  if (cleaned)
@@ -28962,7 +29274,7 @@ async function select2(terminal, items, options) {
28962
29274
  };
28963
29275
  const finish = (value) => {
28964
29276
  cleanup2();
28965
- resolve18(value);
29277
+ resolve20(value);
28966
29278
  };
28967
29279
  const onSignal = () => finish(null);
28968
29280
  const onKey = (data) => {
@@ -29002,7 +29314,7 @@ async function select2(terminal, items, options) {
29002
29314
  stdin.setRawMode(true);
29003
29315
  } catch {
29004
29316
  cleanup2();
29005
- resolve18(null);
29317
+ resolve20(null);
29006
29318
  return;
29007
29319
  }
29008
29320
  stdin.resume();
@@ -29016,7 +29328,7 @@ async function select2(terminal, items, options) {
29016
29328
  import { createHash as createHash10, randomBytes as randomBytes5, randomUUID as randomUUID16 } from "node:crypto";
29017
29329
  import { constants as fsConstants2 } from "node:fs";
29018
29330
  import { chmod as chmod3, mkdir as mkdir12, open as open10, readFile as readFile10, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
29019
- import { basename as basename4, dirname as dirname17, extname as extname2, isAbsolute as isAbsolute3, join as join11, resolve as resolve10 } from "node:path";
29331
+ import { basename as basename4, dirname as dirname17, extname as extname2, isAbsolute as isAbsolute3, join as join11, resolve as resolve12 } from "node:path";
29020
29332
  import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
29021
29333
 
29022
29334
  // src/common-auth-embedded/fs/lock-constants.js
@@ -29081,8 +29393,8 @@ async function acquireRefreshFileLockWithClock2(options) {
29081
29393
  let releaseConfirmed = false;
29082
29394
  let loss;
29083
29395
  let resolveLoss;
29084
- const lostPromise = new Promise((resolve18) => {
29085
- resolveLoss = resolve18;
29396
+ const lostPromise = new Promise((resolve20) => {
29397
+ resolveLoss = resolve20;
29086
29398
  });
29087
29399
  function notifyTimerStep(event) {
29088
29400
  try {
@@ -29239,7 +29551,7 @@ async function acquireRefreshFileLockWithClock2(options) {
29239
29551
  }
29240
29552
  }
29241
29553
  async function backoff() {
29242
- await new Promise((resolve18) => setTimeout(resolve18, Math.floor(Math.random() * 4)));
29554
+ await new Promise((resolve20) => setTimeout(resolve20, Math.floor(Math.random() * 4)));
29243
29555
  }
29244
29556
  async function readLockState(notifyReady = true) {
29245
29557
  if (notifyReady && options.onStep)
@@ -29725,7 +30037,7 @@ function hostEnrollmentPaths2(input2) {
29725
30037
  const override = input2.override?.trim();
29726
30038
  if (override && !isAbsolute3(override) && !input2.cwd)
29727
30039
  throw new ClaustrumConsumerError2("invalid-state", "A relative Claustrum enrollment override needs a base directory");
29728
- const tokenPath = override ? isAbsolute3(override) ? override : resolve10(input2.cwd, override) : join11(input2.stateDir, `${input2.host}-enrollment.json`);
30040
+ const tokenPath = override ? isAbsolute3(override) ? override : resolve12(input2.cwd, override) : join11(input2.stateDir, `${input2.host}-enrollment.json`);
29729
30041
  return getClaustrumEnrollmentPaths2(tokenPath);
29730
30042
  }
29731
30043
  function isRecord10(value) {
@@ -29854,13 +30166,13 @@ async function readBoundedJson2(path5) {
29854
30166
  await descriptor.close();
29855
30167
  }
29856
30168
  }
29857
- function accountRecords2(text2, fields) {
30169
+ function accountRecords2(text2, fields2) {
29858
30170
  const records = [];
29859
30171
  for (const line of text2.split("\n")) {
29860
30172
  if (line.trim() === "" || line.startsWith("#"))
29861
30173
  continue;
29862
30174
  const parts = line.split(":");
29863
- 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] ?? ""))
30175
+ 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] ?? ""))
29864
30176
  return void 0;
29865
30177
  records.push(parts);
29866
30178
  }
@@ -30320,7 +30632,7 @@ var ByteTail = class {
30320
30632
  };
30321
30633
  var defaultCommandRunner = {
30322
30634
  run(file, args, options = {}) {
30323
- return new Promise((resolve18) => {
30635
+ return new Promise((resolve20) => {
30324
30636
  const started = performance.now();
30325
30637
  const timeoutMs = options.timeoutMs ?? 15e3;
30326
30638
  const stderr = new ByteTail();
@@ -30338,7 +30650,7 @@ var defaultCommandRunner = {
30338
30650
  stdio: ["ignore", "pipe", "pipe"]
30339
30651
  });
30340
30652
  } catch {
30341
- resolve18({
30653
+ resolve20({
30342
30654
  exitCode: 1,
30343
30655
  stdout: "",
30344
30656
  stderr: "",
@@ -30373,7 +30685,7 @@ var defaultCommandRunner = {
30373
30685
  settled = true;
30374
30686
  if (timer)
30375
30687
  clearTimeout(timer);
30376
- resolve18({
30688
+ resolve20({
30377
30689
  exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
30378
30690
  stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
30379
30691
  stderr: stderr.toString(),
@@ -30802,6 +31114,7 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);
30802
31114
  };
30803
31115
  async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
30804
31116
  const windows2 = (options.platform ?? process.platform) === "win32";
31117
+ const selfPid = options.selfPid ?? process.pid;
30805
31118
  let inspection = {
30806
31119
  step: windows2 ? "tasklist" : "ps",
30807
31120
  exitCode: null,
@@ -30870,7 +31183,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
30870
31183
  }
30871
31184
  if (!processes.length)
30872
31185
  throw new ProcessInspectionError(inspection);
30873
- const runtimes = processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command));
31186
+ const runtimes = processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command));
30874
31187
  if (windows2 && runtimes.length && options.inspectRuntimes !== false) {
30875
31188
  const details = await inspect("CIM", "powershell.exe", [
30876
31189
  "-NoProfile",
@@ -30903,7 +31216,8 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
30903
31216
  }
30904
31217
  }
30905
31218
  function createProcessFence(runner = defaultCommandRunner, options = {}) {
30906
- const isHost = (entry) => entry.pid !== process.pid && hostName(entry.command) !== null;
31219
+ const selfPid = options.selfPid ?? process.pid;
31220
+ const isHost = (entry) => entry.pid !== selfPid && hostName(entry.command) !== null;
30907
31221
  return {
30908
31222
  async listRunningHosts(env3) {
30909
31223
  return (await listSetupProcesses(runner, { ...options, env: env3 })).filter(isHost);
@@ -30917,7 +31231,7 @@ function createProcessFence(runner = defaultCommandRunner, options = {}) {
30917
31231
  const windows2 = (options.platform ?? process.platform) === "win32";
30918
31232
  return {
30919
31233
  hosts: processes.filter(isHost),
30920
- uncheckedRuntimes: windows2 ? processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
31234
+ uncheckedRuntimes: windows2 ? processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
30921
31235
  };
30922
31236
  }
30923
31237
  };
@@ -31661,7 +31975,7 @@ function createVaultSelectionState(options) {
31661
31975
  report(error);
31662
31976
  }
31663
31977
  };
31664
- const flush = () => {
31978
+ const flush2 = () => {
31665
31979
  writing = writing.then(async () => {
31666
31980
  for (const row of [...changed]) await writeRow(row);
31667
31981
  });
@@ -31677,7 +31991,7 @@ function createVaultSelectionState(options) {
31677
31991
  accessVerdict: mark,
31678
31992
  fingerprint: mark,
31679
31993
  requestSave: () => {
31680
- void flush();
31994
+ void flush2();
31681
31995
  }
31682
31996
  },
31683
31997
  admitted(row, attribution) {
@@ -31700,7 +32014,7 @@ function createVaultSelectionState(options) {
31700
32014
  }
31701
32015
  }
31702
32016
  },
31703
- flush,
32017
+ flush: flush2,
31704
32018
  recordQuota(attribution, quota, signal) {
31705
32019
  return options.source.commitState(
31706
32020
  attribution,
@@ -32099,11 +32413,11 @@ function createOpenCodeVaultCustody(options) {
32099
32413
  ].join("\n");
32100
32414
  const waitForApproval = async () => {
32101
32415
  while (!closed) {
32102
- await new Promise((resolve18) => {
32416
+ await new Promise((resolve20) => {
32103
32417
  const done = () => {
32104
32418
  clearTimeout(timer);
32105
32419
  cancelWait = void 0;
32106
- resolve18();
32420
+ resolve20();
32107
32421
  };
32108
32422
  const timer = setTimeout(done, 2e3);
32109
32423
  timer.unref?.();
@@ -32444,7 +32758,7 @@ async function writeNativeSlot(host, slot, context, expectedAuthority = "local")
32444
32758
  beforeRename: async () => {
32445
32759
  await assertSetupHostsStopped();
32446
32760
  const claustrum = await loadCommonAuthClaustrum();
32447
- const stateDir = host === "opencode" ? openCodeVaultPaths(resolve11(getStoragePath())).dir : getPiAntigravityVaultDir();
32761
+ const stateDir = host === "opencode" ? openCodeVaultPaths(resolve13(getStoragePath())).dir : getPiAntigravityVaultDir();
32448
32762
  if (await claustrum.enrollmentAuthority(
32449
32763
  claustrum.hostEnrollmentPaths({ stateDir, host }),
32450
32764
  `antigravity-auth-${host}`
@@ -32474,7 +32788,7 @@ async function persistPiSetupLogin(result, context) {
32474
32788
  }
32475
32789
  async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
32476
32790
  const claustrum = await loadCommonAuthClaustrum();
32477
- const opencode = openCodeVaultPaths(resolve11(getStoragePath()));
32791
+ const opencode = openCodeVaultPaths(resolve13(getStoragePath()));
32478
32792
  const piDir = getPiAntigravityVaultDir();
32479
32793
  const hosts = {
32480
32794
  opencode: {
@@ -32493,7 +32807,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
32493
32807
  const assertLocal = async (host, context) => {
32494
32808
  if (host === "opencode")
32495
32809
  return assertLocalOpenCodeLogin(
32496
- resolve11(getStoragePath()),
32810
+ resolve13(getStoragePath()),
32497
32811
  context.opencodeGeneration
32498
32812
  );
32499
32813
  if (await authority(host) !== "local")
@@ -33025,7 +33339,7 @@ function createDefaultCliDependencies() {
33025
33339
  throw new Error(
33026
33340
  "Pi setup requires its detected native agent directory."
33027
33341
  );
33028
- const legacyPath = resolve12(getStoragePath());
33342
+ const legacyPath = resolve14(getStoragePath());
33029
33343
  const repository = host === "pi" ? void 0 : await prepareCliLoginStore(legacyPath, context?.opencodeGeneration);
33030
33344
  try {
33031
33345
  return await performOAuthLogin(request, {
@@ -33185,7 +33499,7 @@ async function readAccountStore(legacyPath) {
33185
33499
  function createDefaultAccountStoreOperations() {
33186
33500
  const offline = { processesStopped: true };
33187
33501
  return {
33188
- legacyPath: () => resolve12(getStoragePath()),
33502
+ legacyPath: () => resolve14(getStoragePath()),
33189
33503
  migrate: async (legacyPath) => createAccountMigrationFactory(await loadCommonAuthStoreModules())({
33190
33504
  legacyPath,
33191
33505
  offline,
@@ -33686,14 +34000,14 @@ function isTuiConnected(sessionId) {
33686
34000
  // src/rpc/rpc-dir.ts
33687
34001
  import { createHash as createHash11 } from "node:crypto";
33688
34002
  import { homedir as homedir8, tmpdir as tmpdir2 } from "node:os";
33689
- import { isAbsolute as isAbsolute4, join as join20, resolve as resolve13 } from "node:path";
34003
+ import { isAbsolute as isAbsolute4, join as join20, resolve as resolve15 } from "node:path";
33690
34004
  var RPC_DIR_ENV = "ANTIGRAVITY_AUTH_RPC_DIR";
33691
34005
  function getRpcDir(projectDirectory) {
33692
34006
  const override = process.env[RPC_DIR_ENV]?.trim();
33693
34007
  if (override) {
33694
- return isAbsolute4(override) ? override : resolve13(projectDirectory, override);
34008
+ return isAbsolute4(override) ? override : resolve15(projectDirectory, override);
33695
34009
  }
33696
- const projectHash = createHash11("sha256").update(resolve13(projectDirectory)).digest("hex").slice(0, 16);
34010
+ const projectHash = createHash11("sha256").update(resolve15(projectDirectory)).digest("hex").slice(0, 16);
33697
34011
  const stateHome = process.env.XDG_STATE_HOME ?? join20(homedir8(), ".local", "state");
33698
34012
  return join20(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
33699
34013
  }
@@ -33706,7 +34020,7 @@ function isSessionId(value) {
33706
34020
  // src/common-auth-embedded/rpc/port-file.js
33707
34021
  import { createHash as createHash12, randomUUID as randomUUID18 } from "node:crypto";
33708
34022
  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";
33709
- import { join as join21, resolve as resolve14 } from "node:path";
34023
+ import { join as join21, resolve as resolve16 } from "node:path";
33710
34024
  function isProbeablePid(pid) {
33711
34025
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
33712
34026
  }
@@ -33793,7 +34107,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
33793
34107
  return;
33794
34108
  throw error;
33795
34109
  }
33796
- const active2 = resolve14(activeDir);
34110
+ const active2 = resolve16(activeDir);
33797
34111
  for (const projectDir of projectDirs) {
33798
34112
  if (!projectDir.isDirectory() || !isManagedDir(projectDir.name)) {
33799
34113
  continue;
@@ -33837,7 +34151,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
33837
34151
  await unlink11(portFile).catch(() => {
33838
34152
  });
33839
34153
  }
33840
- if (resolve14(dir) !== active2)
34154
+ if (resolve16(dir) !== active2)
33841
34155
  await rmdir2(dir).catch(() => {
33842
34156
  });
33843
34157
  }
@@ -33867,7 +34181,7 @@ var BodyTooLargeError = class extends Error {
33867
34181
  }
33868
34182
  };
33869
34183
  function readBody(req) {
33870
- return new Promise((resolve18, reject) => {
34184
+ return new Promise((resolve20, reject) => {
33871
34185
  const tooLarge = (declaredOversize = false) => {
33872
34186
  req.removeAllListeners("data");
33873
34187
  req.on("data", () => {
@@ -33890,7 +34204,7 @@ function readBody(req) {
33890
34204
  }
33891
34205
  chunks.push(chunk);
33892
34206
  });
33893
- req.on("end", () => resolve18(Buffer.concat(chunks).toString("utf8")));
34207
+ req.on("end", () => resolve20(Buffer.concat(chunks).toString("utf8")));
33894
34208
  req.on("error", reject);
33895
34209
  });
33896
34210
  }
@@ -34058,12 +34372,12 @@ async function startRpcServer(options) {
34058
34372
  json(500, { error: "internal error" });
34059
34373
  }
34060
34374
  }
34061
- const port = await new Promise((resolve18, reject) => {
34375
+ const port = await new Promise((resolve20, reject) => {
34062
34376
  server.on("error", reject);
34063
34377
  server.listen(0, "127.0.0.1", () => {
34064
34378
  const addr = server.address();
34065
34379
  if (addr && typeof addr === "object")
34066
- resolve18(addr.port);
34380
+ resolve20(addr.port);
34067
34381
  else
34068
34382
  reject(new Error("no port"));
34069
34383
  });
@@ -34086,16 +34400,16 @@ async function startRpcServer(options) {
34086
34400
  rpcPort: port
34087
34401
  });
34088
34402
  } catch (error) {
34089
- await new Promise((resolve18) => server.close(() => resolve18()));
34403
+ await new Promise((resolve20) => server.close(() => resolve20()));
34090
34404
  throw error;
34091
34405
  }
34092
34406
  return {
34093
34407
  port,
34094
34408
  token,
34095
34409
  async stop() {
34096
- await new Promise((resolve18) => {
34410
+ await new Promise((resolve20) => {
34097
34411
  server.closeAllConnections?.();
34098
- server.close(() => resolve18());
34412
+ server.close(() => resolve20());
34099
34413
  for (const socket of connections)
34100
34414
  socket.destroy();
34101
34415
  });
@@ -34169,21 +34483,21 @@ function parsePending(value) {
34169
34483
  function present4(value) {
34170
34484
  return value === null ? void 0 : value;
34171
34485
  }
34172
- function accessBlockOf(fields) {
34173
- if (fields === void 0) return { kind: "none" };
34174
- if (fields.accountIneligible === true) {
34175
- const reason = present4(fields.accountIneligibleReason);
34176
- const at = present4(fields.accountIneligibleAt);
34486
+ function accessBlockOf(fields2) {
34487
+ if (fields2 === void 0) return { kind: "none" };
34488
+ if (fields2.accountIneligible === true) {
34489
+ const reason = present4(fields2.accountIneligibleReason);
34490
+ const at = present4(fields2.accountIneligibleAt);
34177
34491
  return {
34178
34492
  kind: "ineligible",
34179
34493
  ...reason !== void 0 ? { reason } : {},
34180
34494
  ...at !== void 0 ? { at } : {}
34181
34495
  };
34182
34496
  }
34183
- if (fields.verificationRequired === true) {
34184
- const reason = present4(fields.verificationRequiredReason);
34185
- const verificationUrl = present4(fields.verificationUrl);
34186
- const at = present4(fields.verificationRequiredAt);
34497
+ if (fields2.verificationRequired === true) {
34498
+ const reason = present4(fields2.verificationRequiredReason);
34499
+ const verificationUrl = present4(fields2.verificationUrl);
34500
+ const at = present4(fields2.verificationRequiredAt);
34187
34501
  return {
34188
34502
  kind: "verification-required",
34189
34503
  ...reason !== void 0 ? { reason } : {},
@@ -35438,7 +35752,7 @@ async function select3(items, options) {
35438
35752
  }
35439
35753
  renderedLines = linesWritten;
35440
35754
  };
35441
- return new Promise((resolve18) => {
35755
+ return new Promise((resolve20) => {
35442
35756
  const wasRaw = stdin.isRaw ?? false;
35443
35757
  const cleanup2 = () => {
35444
35758
  if (isCleanedUp) return;
@@ -35459,11 +35773,11 @@ async function select3(items, options) {
35459
35773
  };
35460
35774
  const onSignal = () => {
35461
35775
  cleanup2();
35462
- resolve18(null);
35776
+ resolve20(null);
35463
35777
  };
35464
35778
  const finishWithValue = (value) => {
35465
35779
  cleanup2();
35466
- resolve18(value);
35780
+ resolve20(value);
35467
35781
  };
35468
35782
  const findNextSelectable = (from, direction) => {
35469
35783
  if (items.length === 0) return from;
@@ -35509,7 +35823,7 @@ async function select3(items, options) {
35509
35823
  stdin.setRawMode(true);
35510
35824
  } catch {
35511
35825
  cleanup2();
35512
- resolve18(null);
35826
+ resolve20(null);
35513
35827
  return;
35514
35828
  }
35515
35829
  stdin.resume();
@@ -38265,7 +38579,7 @@ var SignatureCache = class {
38265
38579
  // src/plugin/config/loader.ts
38266
38580
  import { existsSync as existsSync10, readFileSync as readFileSync10, realpathSync as realpathSync3 } from "node:fs";
38267
38581
  import { homedir as homedir11 } from "node:os";
38268
- import { basename as basename6, dirname as dirname23, join as join25, resolve as resolve15 } from "node:path";
38582
+ import { basename as basename6, dirname as dirname23, join as join25, resolve as resolve17 } from "node:path";
38269
38583
 
38270
38584
  // src/plugin/config/schema.ts
38271
38585
  import { z } from "zod";
@@ -38823,7 +39137,7 @@ function loadConfigWithLogger(directory, log16) {
38823
39137
  return config;
38824
39138
  }
38825
39139
  function canonicalizeOwnedPath(path5) {
38826
- const absolute = resolve15(path5);
39140
+ const absolute = resolve17(path5);
38827
39141
  const missing = [];
38828
39142
  let current = absolute;
38829
39143
  for (; ; ) {
@@ -41744,6 +42058,7 @@ var NATIVE_GOOGLE_ERROR_MESSAGES = {
41744
42058
  operator_policy: "Antigravity account pool is unavailable under the operator quota policy. Adjust /antigravity-killswitch or refresh quota.",
41745
42059
  soft_quota: "Antigravity account pool is unavailable under the quota protection policy. Add accounts, wait for quota reset, or disable soft quota protection.",
41746
42060
  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.",
42061
+ model_unavailable: "The requested Antigravity model is not available to the configured accounts. Choose another model.",
41747
42062
  missing_access_token: "Missing access token. Run `opencode auth login` to reauthenticate.",
41748
42063
  empty_response: "Antigravity returned an empty response after the internal retry attempts."
41749
42064
  };
@@ -43740,10 +44055,10 @@ async function retainResponseLifetime(response, cancellation) {
43740
44055
  cancellation.release();
43741
44056
  throw error;
43742
44057
  }
43743
- let resolve18 = () => {
44058
+ let resolve20 = () => {
43744
44059
  };
43745
44060
  const settled = new Promise((done) => {
43746
- resolve18 = done;
44061
+ resolve20 = done;
43747
44062
  });
43748
44063
  let stopping = false;
43749
44064
  let finished = false;
@@ -43753,7 +44068,7 @@ async function retainResponseLifetime(response, cancellation) {
43753
44068
  finished = true;
43754
44069
  cancellation.signal.removeEventListener("abort", abort);
43755
44070
  cancellation.release();
43756
- resolve18();
44071
+ resolve20();
43757
44072
  };
43758
44073
  const abort = () => {
43759
44074
  if (finished || stopping) return;
@@ -43822,8 +44137,8 @@ function createAfterHandoff(work, signals, onFailure) {
43822
44137
  let running = false;
43823
44138
  let resolveCompletion = () => {
43824
44139
  };
43825
- const completion = new Promise((resolve18) => {
43826
- resolveCompletion = resolve18;
44140
+ const completion = new Promise((resolve20) => {
44141
+ resolveCompletion = resolve20;
43827
44142
  });
43828
44143
  const finish = () => {
43829
44144
  if (finished) return;
@@ -43870,14 +44185,14 @@ function createAfterHandoff(work, signals, onFailure) {
43870
44185
  };
43871
44186
  }
43872
44187
  function publishResponse(dispatch) {
43873
- return new Promise((resolve18, reject) => {
44188
+ return new Promise((resolve20, reject) => {
43874
44189
  let acknowledge;
43875
44190
  void Promise.resolve().then(
43876
44191
  () => dispatch((callback) => {
43877
44192
  acknowledge = callback;
43878
44193
  })
43879
44194
  ).then((response) => {
43880
- resolve18(response);
44195
+ resolve20(response);
43881
44196
  acknowledge?.();
43882
44197
  }, reject);
43883
44198
  });
@@ -45666,10 +45981,10 @@ function resolvePluginDependencies(overrides = {}) {
45666
45981
  }
45667
45982
  async function defaultSleep(ms, signal) {
45668
45983
  if (ms <= 0) return;
45669
- await new Promise((resolve18, reject) => {
45984
+ await new Promise((resolve20, reject) => {
45670
45985
  const timer = setTimeout(() => {
45671
45986
  signal?.removeEventListener("abort", onAbort);
45672
- resolve18();
45987
+ resolve20();
45673
45988
  }, ms);
45674
45989
  timer.unref?.();
45675
45990
  const onAbort = () => {
@@ -45691,7 +46006,7 @@ function createEventHandler({
45691
46006
  sessionRegistry,
45692
46007
  sessionRecovery,
45693
46008
  updateChecker,
45694
- logger: logger2
46009
+ logger: logger3
45695
46010
  }) {
45696
46011
  return async (input2) => {
45697
46012
  await updateChecker.event(input2);
@@ -45703,14 +46018,14 @@ function createEventHandler({
45703
46018
  sessionRegistry.register(sessionId, parentSessionId);
45704
46019
  }
45705
46020
  if (parentSessionId) {
45706
- logger2.debug("child-session-detected", {
46021
+ logger3.debug("child-session-detected", {
45707
46022
  sessionId,
45708
46023
  parentID: parentSessionId
45709
46024
  });
45710
46025
  } else {
45711
46026
  const previousSummary = lifecycle.getAccountManager()?.getSessionSummary();
45712
46027
  if (previousSummary && (previousSummary.totalClaude > 0 || previousSummary.totalGemini > 0)) {
45713
- logger2.debug("prev-session-quota-summary", {
46028
+ logger3.debug("prev-session-quota-summary", {
45714
46029
  durationMinutes: previousSummary.durationMinutes,
45715
46030
  totalClaude: previousSummary.totalClaude,
45716
46031
  totalGemini: previousSummary.totalGemini,
@@ -45718,7 +46033,7 @@ function createEventHandler({
45718
46033
  accountsUsed: previousSummary.accountsUsed
45719
46034
  });
45720
46035
  }
45721
- logger2.debug("root-session-detected", { sessionId });
46036
+ logger3.debug("root-session-detected", { sessionId });
45722
46037
  }
45723
46038
  }
45724
46039
  if (input2.event.type === "session.deleted") {
@@ -45727,7 +46042,7 @@ function createEventHandler({
45727
46042
  if (sessionId) {
45728
46043
  sessionRegistry.delete(sessionId);
45729
46044
  lifecycle.getAccountManager()?.deleteSessionState(sessionId);
45730
- const eventLogger = logger2;
46045
+ const eventLogger = logger3;
45731
46046
  void removeSidebarActiveRouting(sessionId).catch((error2) => {
45732
46047
  eventLogger.debug("sidebar-route-remove-failed", {
45733
46048
  sessionId,
@@ -45763,7 +46078,7 @@ function createEventHandler({
45763
46078
  });
45764
46079
  const successToast = getRecoverySuccessToast();
45765
46080
  const isChildSession = sessionRegistry.getParentSessionId(sessionID) !== null;
45766
- logger2.debug("recovery-toast", {
46081
+ logger3.debug("recovery-toast", {
45767
46082
  ...successToast,
45768
46083
  isChildSession,
45769
46084
  toastScope: config.toast_scope
@@ -46246,7 +46561,7 @@ function throwIfAllKilled(input2) {
46246
46561
  }
46247
46562
 
46248
46563
  // src/plugin/session-context.ts
46249
- import { resolve as resolve16 } from "node:path";
46564
+ import { resolve as resolve18 } from "node:path";
46250
46565
  import { pathToFileURL } from "node:url";
46251
46566
  var FALLBACK_SESSION_KEY = "__default__";
46252
46567
  function extractOpenCodeSessionIdentity(headers) {
@@ -46260,7 +46575,7 @@ var AgySessionRegistry = class {
46260
46575
  requestSessions;
46261
46576
  parentSessionIds = /* @__PURE__ */ new Map();
46262
46577
  constructor(directory, options = {}) {
46263
- const workspaceUri = directory ? pathToFileURL(resolve16(directory)).href : "";
46578
+ const workspaceUri = directory ? pathToFileURL(resolve18(directory)).href : "";
46264
46579
  this.requestSessions = new AgyRequestSessionStore(workspaceUri, options);
46265
46580
  }
46266
46581
  getOrCreate(identity) {
@@ -46408,7 +46723,7 @@ function formatWaitTime(ms) {
46408
46723
  return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
46409
46724
  }
46410
46725
  function sleep4(ms, signal) {
46411
- return new Promise((resolve18, reject) => {
46726
+ return new Promise((resolve20, reject) => {
46412
46727
  if (signal?.aborted) {
46413
46728
  reject(
46414
46729
  signal.reason instanceof Error ? signal.reason : new Error("Aborted")
@@ -46417,7 +46732,7 @@ function sleep4(ms, signal) {
46417
46732
  }
46418
46733
  const timeout = setTimeout(() => {
46419
46734
  cleanup2();
46420
- resolve18();
46735
+ resolve20();
46421
46736
  }, ms);
46422
46737
  const onAbort = () => {
46423
46738
  cleanup2();
@@ -46673,6 +46988,7 @@ function createRequestExecutor(deps) {
46673
46988
  let localRecaptureUsed = false;
46674
46989
  const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1e3;
46675
46990
  let allAccountsBlockedAt;
46991
+ const modelUnavailableIndexes = /* @__PURE__ */ new Set();
46676
46992
  while (true) {
46677
46993
  await assertAdmission();
46678
46994
  checkAborted();
@@ -46736,6 +47052,26 @@ function createRequestExecutor(deps) {
46736
47052
  const killedIndexes = eligibleIndexes === null ? void 0 : new Set(
46737
47053
  accountManager.getAccounts().map((entry) => entry.index).filter((index) => !eligibleIndexes.has(index))
46738
47054
  );
47055
+ if (modelUnavailableIndexes.size > 0) {
47056
+ const candidates = accountManager.getEnabledAccounts().filter(
47057
+ (entry) => eligibleIndexes === null || eligibleIndexes.has(entry.index)
47058
+ );
47059
+ if (candidates.length > 0 && candidates.every((entry) => modelUnavailableIndexes.has(entry.index))) {
47060
+ pushDebug(
47061
+ `model-unavailable: all ${candidates.length} eligible account(s) skipped`
47062
+ );
47063
+ log16.warn("model-unavailable-all-accounts", {
47064
+ family,
47065
+ model,
47066
+ accounts: candidates.length
47067
+ });
47068
+ return createNativeGoogleErrorResponse({
47069
+ status: 412,
47070
+ reason: "model_unavailable"
47071
+ });
47072
+ }
47073
+ }
47074
+ const excludedIndexes = modelUnavailableIndexes.size === 0 ? killedIndexes : /* @__PURE__ */ new Set([...killedIndexes ?? [], ...modelUnavailableIndexes]);
46739
47075
  let account = accountManager.getCurrentOrNextForFamily(
46740
47076
  family,
46741
47077
  model,
@@ -46744,7 +47080,7 @@ function createRequestExecutor(deps) {
46744
47080
  config.soft_quota_threshold_percent,
46745
47081
  softQuotaCacheTtlMs,
46746
47082
  accountSessionIdentity,
46747
- killedIndexes
47083
+ excludedIndexes
46748
47084
  );
46749
47085
  if (account && eligibleIndexes !== null && !eligibleIndexes.has(account.index)) {
46750
47086
  pushDebug(
@@ -47211,6 +47547,7 @@ function createRequestExecutor(deps) {
47211
47547
  };
47212
47548
  let apiRequestCount = 0;
47213
47549
  let shouldSwitchAccount = false;
47550
+ let skippedForModelUnavailable = false;
47214
47551
  if (account.fingerprint) {
47215
47552
  pushDebug(
47216
47553
  `fingerprint: deviceId=${account.fingerprint.deviceId.slice(0, 8)}...`
@@ -47590,6 +47927,37 @@ function createRequestExecutor(deps) {
47590
47927
  shouldSwitchAccount = true;
47591
47928
  break;
47592
47929
  }
47930
+ if (response.status === 404 && currentEndpoint === ANTIGRAVITY_ENDPOINT_DAILY) {
47931
+ const notFoundBody = await deadline.wait(
47932
+ () => response.clone().text().catch(() => "")
47933
+ );
47934
+ const unavailable = parseModelUnavailableError(notFoundBody);
47935
+ if (unavailable) {
47936
+ if (tokenConsumed) {
47937
+ trackers.token.refund(account.index);
47938
+ tokenConsumed = false;
47939
+ }
47940
+ const reasonCodes = unavailable.reasons.length > 0 ? unavailable.reasons.join(",") : "none";
47941
+ const note = `model-unavailable idx=${account.index} status=${unavailable.status} reasons=${reasonCodes}`;
47942
+ pushDebug(note);
47943
+ debug.logAntigravityDebugResponse(debugContext, response, {
47944
+ note
47945
+ });
47946
+ log16.info("model-unavailable", {
47947
+ accountIndex: account.index,
47948
+ family,
47949
+ model,
47950
+ status: unavailable.status,
47951
+ reasons: unavailable.reasons
47952
+ });
47953
+ void response.body?.cancel().catch(() => {
47954
+ });
47955
+ modelUnavailableIndexes.add(account.index);
47956
+ skippedForModelUnavailable = true;
47957
+ shouldSwitchAccount = true;
47958
+ break;
47959
+ }
47960
+ }
47593
47961
  const quotaKey = getQuotaKey(family, model);
47594
47962
  retryState.resetRateLimitState(account.index, quotaKey);
47595
47963
  retryState.resetAccountFailureState(account.index);
@@ -47656,7 +48024,7 @@ function createRequestExecutor(deps) {
47656
48024
  break;
47657
48025
  }
47658
48026
  }
47659
- const shouldRetryEndpoint = response.status === 403 || response.status === 404 || response.status >= 500;
48027
+ const shouldRetryEndpoint = response.status === 404 || response.status >= 500;
47660
48028
  if (shouldRetryEndpoint && i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
47661
48029
  await logResponseBody2(debugContext, response, response.status);
47662
48030
  lastFailure = createFailureContext(response);
@@ -47907,6 +48275,9 @@ function createRequestExecutor(deps) {
47907
48275
  }
47908
48276
  }
47909
48277
  }
48278
+ if (shouldSwitchAccount && skippedForModelUnavailable) {
48279
+ continue;
48280
+ }
47910
48281
  if (shouldSwitchAccount) {
47911
48282
  accountSwitchCount++;
47912
48283
  if (accountSwitchCount > maxAccountSwitches) {
@@ -48109,6 +48480,32 @@ function createRequestExecutor(deps) {
48109
48480
  dispose
48110
48481
  };
48111
48482
  }
48483
+ var ERROR_REASON_CODE = /^[A-Za-z0-9_.-]{1,128}$/;
48484
+ function parseModelUnavailableError(bodyText) {
48485
+ let body;
48486
+ try {
48487
+ body = JSON.parse(bodyText);
48488
+ } catch {
48489
+ return null;
48490
+ }
48491
+ const envelope = Array.isArray(body) ? body[0] : body;
48492
+ if (!envelope || typeof envelope !== "object") return null;
48493
+ const error = envelope.error;
48494
+ if (!error || typeof error !== "object") return null;
48495
+ if (error.status !== "NOT_FOUND") return null;
48496
+ const details = error.details;
48497
+ const reasons = [];
48498
+ if (Array.isArray(details)) {
48499
+ for (const detail of details) {
48500
+ if (!detail || typeof detail !== "object") continue;
48501
+ const reason = detail.reason;
48502
+ if (typeof reason === "string" && ERROR_REASON_CODE.test(reason)) {
48503
+ reasons.push(reason);
48504
+ }
48505
+ }
48506
+ }
48507
+ return { status: "NOT_FOUND", reasons };
48508
+ }
48112
48509
  function extractRateLimitBodyInfo(body) {
48113
48510
  if (!body || typeof body !== "object") return { retryDelayMs: null };
48114
48511
  const error = body.error;
@@ -48803,8 +49200,8 @@ function createPluginLifecycle(options) {
48803
49200
  };
48804
49201
  let failDisposal = () => {
48805
49202
  };
48806
- disposal = new Promise((resolve18, reject) => {
48807
- finishDisposal = resolve18;
49203
+ disposal = new Promise((resolve20, reject) => {
49204
+ finishDisposal = resolve20;
48808
49205
  failDisposal = reject;
48809
49206
  });
48810
49207
  void (async () => {
@@ -48917,7 +49314,7 @@ function createVaultAccountMenuSections(pool, selectorOf, checkQuota) {
48917
49314
  }
48918
49315
 
48919
49316
  // src/plugin/index.ts
48920
- var logger = createLogger4("plugin");
49317
+ var logger2 = createLogger4("plugin");
48921
49318
  function quotaAccountIdentity4(refreshToken) {
48922
49319
  return createHash20("sha256").update(refreshToken).digest("hex").slice(0, 16);
48923
49320
  }
@@ -48986,7 +49383,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
48986
49383
  });
48987
49384
  let vaultQuotaPoller;
48988
49385
  const vaultCustody = createOpenCodeVaultCustody({
48989
- accountFile: resolve17(getStoragePath()),
49386
+ accountFile: resolve19(getStoragePath()),
48990
49387
  insulaQuota: true,
48991
49388
  readHostSlot: async () => {
48992
49389
  if (!cachedGetAuth)
@@ -49110,7 +49507,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
49110
49507
  });
49111
49508
  function scheduleSidebarPublication() {
49112
49509
  void sidebarPublisher.publish().catch(
49113
- (error) => logger.debug("sidebar-source-publish-failed", {
49510
+ (error) => logger2.debug("sidebar-source-publish-failed", {
49114
49511
  error: error instanceof Error ? error.name : "unknown"
49115
49512
  })
49116
49513
  );
@@ -49140,7 +49537,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
49140
49537
  }
49141
49538
  );
49142
49539
  })().catch(
49143
- (error) => logger.debug("sidebar-routing-publish-failed", {
49540
+ (error) => logger2.debug("sidebar-routing-publish-failed", {
49144
49541
  error: error instanceof Error ? error.name : "unknown"
49145
49542
  })
49146
49543
  );
@@ -49185,8 +49582,8 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
49185
49582
  readProviderState: () => vaultCustody.readState(),
49186
49583
  publishSidebar: () => sidebarPublisher.publish(),
49187
49584
  transport: vaultQuotaTransport,
49188
- logger,
49189
- onOutcome: (level, outcome) => (level === "warn" ? quotaOutcomeLogger : logger)[level](
49585
+ logger: logger2,
49586
+ onOutcome: (level, outcome) => (level === "warn" ? quotaOutcomeLogger : logger2)[level](
49190
49587
  "vault-quota-tick",
49191
49588
  { ...outcome }
49192
49589
  ),
@@ -49222,7 +49619,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
49222
49619
  sessionRegistry,
49223
49620
  sessionRecovery,
49224
49621
  updateChecker,
49225
- logger
49622
+ logger: logger2
49226
49623
  });
49227
49624
  let storeQuota = null;
49228
49625
  const currentStoreQuota = async (knownRepository) => {
@@ -49328,7 +49725,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
49328
49725
  source,
49329
49726
  ref,
49330
49727
  signal: check,
49331
- logger,
49728
+ logger: logger2,
49332
49729
  transport: vaultQuotaTransport
49333
49730
  })
49334
49731
  },
@@ -49588,7 +49985,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
49588
49985
  if (await readAuthority() === "local")
49589
49986
  await lifecycle.getAccountManager()?.refreshFromRepository();
49590
49987
  } catch (error) {
49591
- logger.warn("menu-routing-refresh-failed", { error: String(error) });
49988
+ logger2.warn("menu-routing-refresh-failed", { error: String(error) });
49592
49989
  pushNotification(
49593
49990
  {
49594
49991
  command: ANTIGRAVITY_MENU_COMMAND,