@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/server.js CHANGED
@@ -64,6 +64,12 @@ function isQuotaCounter(value) {
64
64
  function isQuotaCounters(value) {
65
65
  return isRecord2(value) && Object.values(value).every(isQuotaCounter);
66
66
  }
67
+ function isBoolean(value) {
68
+ return typeof value === "boolean";
69
+ }
70
+ function isQuotaCredits(value) {
71
+ return isRecord2(value) && typeof value.hasCredits === "boolean" && typeof value.unlimited === "boolean" && optional2(value, "balance", isFiniteNumber) && optional2(value, "overageLimitReached", isBoolean) && isFiniteNumber(value.checkedAt);
72
+ }
67
73
  function readQuotaCounters(value) {
68
74
  if (!isRecord2(value))
69
75
  return void 0;
@@ -75,11 +81,16 @@ function decodeQuotaMap(value) {
75
81
  return value;
76
82
  if (!isRecord2(value))
77
83
  return void 0;
78
- const { counters: rawCounters, ...rest } = value;
84
+ const { counters: rawCounters, credits: rawCredits, ...rest } = value;
79
85
  if (!isQuotaMap(rest))
80
86
  return void 0;
81
87
  const counters = readQuotaCounters(rawCounters);
82
- return { ...rest, ...counters === void 0 ? {} : { counters } };
88
+ const credits = isQuotaCredits(rawCredits) ? rawCredits : void 0;
89
+ return {
90
+ ...rest,
91
+ ...counters === void 0 ? {} : { counters },
92
+ ...credits === void 0 ? {} : { credits }
93
+ };
83
94
  }
84
95
  function isQuotaMap(value) {
85
96
  if (!isRecord2(value) || !Array.isArray(value.limits))
@@ -93,7 +104,7 @@ function isQuotaMap(value) {
93
104
  return false;
94
105
  seen.add(key);
95
106
  }
96
- return optional2(value, "budget", isCreditBudgetEntry) && optional2(value, "counters", isQuotaCounters);
107
+ return optional2(value, "budget", isCreditBudgetEntry) && optional2(value, "counters", isQuotaCounters) && optional2(value, "credits", isQuotaCredits);
97
108
  }
98
109
  var ALL_SCOPE, DEFAULT_REQUIRED_LABELS;
99
110
  var init_map = __esm({
@@ -156,7 +167,7 @@ function isQuotaObservation(value) {
156
167
  }
157
168
  if (!coverage.every(isObservedPair))
158
169
  return false;
159
- return (value.budget === void 0 || isObservedBudget(value.budget)) && (value.counters === void 0 || isQuotaCounters(value.counters));
170
+ return (value.budget === void 0 || isObservedBudget(value.budget)) && (value.counters === void 0 || isQuotaCounters(value.counters)) && (value.credits === void 0 || isQuotaCredits(value.credits));
160
171
  }
161
172
  function compareEntries(left, right) {
162
173
  if (left.scope !== right.scope)
@@ -182,6 +193,14 @@ function mergeCounters(stored, observed) {
182
193
  }
183
194
  return counters.size === 0 ? void 0 : Object.fromEntries(counters);
184
195
  }
196
+ function mergeCredits(stored, observed) {
197
+ if (observed === void 0)
198
+ return stored;
199
+ if (stored !== void 0 && observed.checkedAt < stored.checkedAt) {
200
+ return stored;
201
+ }
202
+ return { ...observed };
203
+ }
185
204
  function mergeQuotaObservation(stored, observation) {
186
205
  const decoded = stored === void 0 ? void 0 : decodeQuotaMap(stored);
187
206
  if (stored !== void 0 && decoded === void 0) {
@@ -225,14 +244,16 @@ function mergeQuotaObservation(stored, observation) {
225
244
  const existing = entries.get(key);
226
245
  entries.set(key, existing === void 0 || existing.kind === "absent" ? { scope, label: pair.label, kind: "absent", checkedAt: at } : { scope, label: pair.label, kind: "retired", retiredAt: at });
227
246
  }
228
- const { limits: _limits, budget: _budget, counters: _counters, ...unknownKeys } = base;
247
+ const { limits: _limits, budget: _budget, counters: _counters, credits: _credits, ...unknownKeys } = base;
229
248
  const budget = mergeBudget(base.budget, observation.budget, at);
230
249
  const counters = mergeCounters(base.counters, observation.counters);
250
+ const credits = mergeCredits(base.credits, observation.credits);
231
251
  return {
232
252
  ...unknownKeys,
233
253
  limits: [...entries.values()].sort(compareEntries),
234
254
  ...budget === void 0 ? {} : { budget },
235
- ...counters === void 0 ? {} : { counters }
255
+ ...counters === void 0 ? {} : { counters },
256
+ ...credits === void 0 ? {} : { credits }
236
257
  };
237
258
  }
238
259
  var QuotaCodecError;
@@ -327,6 +348,13 @@ function quotaWindowParts(quota, options) {
327
348
  const parts = windows2.map(({ part }) => part);
328
349
  return age === void 0 ? { windows: parts } : { windows: parts, age };
329
350
  }
351
+ function withShortNames(windows2) {
352
+ const abbreviations = scopeAbbreviations(windows2.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE).map(({ scope }) => scope));
353
+ for (const window of windows2) {
354
+ window.part.short = window.part.kind === "budget" ? "cr" : window.scope === ALL_SCOPE ? window.part.name : abbreviations.get(window.scope) ?? window.scope;
355
+ }
356
+ return windows2;
357
+ }
330
358
  function scopedWindowParts(quota, options) {
331
359
  if (!quota)
332
360
  return { windows: [] };
@@ -340,6 +368,7 @@ function scopedWindowParts(quota, options) {
340
368
  part: {
341
369
  kind: "window",
342
370
  name: quotaWindowName(limit),
371
+ short: "",
343
372
  figure: percentLeft(limit.remainingPercent ?? 0),
344
373
  remainingPercent,
345
374
  checkedAt: limit.checkedAt,
@@ -357,6 +386,7 @@ function scopedWindowParts(quota, options) {
357
386
  part: {
358
387
  kind: "budget",
359
388
  name: "credits",
389
+ short: "",
360
390
  figure,
361
391
  ...remainingPercent === void 0 ? {} : { remainingPercent: clampPercent(remainingPercent) },
362
392
  checkedAt: budget.checkedAt,
@@ -364,6 +394,7 @@ function scopedWindowParts(quota, options) {
364
394
  }
365
395
  });
366
396
  }
397
+ withShortNames(windows2);
367
398
  if (windows2.length > 0) {
368
399
  const age = now - Math.min(...windows2.map(({ part }) => part.checkedAt));
369
400
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
@@ -443,15 +474,14 @@ function narrowTextParts(quota, options) {
443
474
  return grouped;
444
475
  const general = windows2.filter(({ part, scope }) => part.kind === "window" && scope === ALL_SCOPE);
445
476
  const scoped = windows2.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE);
446
- const abbreviations = scopeAbbreviations(scoped.map(({ scope }) => scope));
447
477
  const budget = windows2.find(({ part }) => part.kind === "budget");
448
478
  const budgetLeft = budget?.spent ? 0 : budget?.part.remainingPercent;
449
479
  const extras = [
450
- ...scoped.map(({ scope, part }) => ({
451
- label: abbreviations.get(scope) ?? scope,
480
+ ...scoped.map(({ part }) => ({
481
+ label: part.short,
452
482
  remaining: part.remainingPercent ?? 0
453
483
  })),
454
- ...budgetLeft === void 0 ? [] : [{ label: "cr", remaining: budgetLeft }]
484
+ ...budgetLeft === void 0 || budget === void 0 ? [] : [{ label: budget.part.short, remaining: budgetLeft }]
455
485
  ];
456
486
  const tightest = extras.reduce((best, item) => best === void 0 || item.remaining < best.remaining ? item : best, void 0);
457
487
  const pieces = general.map(({ part }) => `${part.name} ${wholePercent(part.remainingPercent ?? 0)}%`);
@@ -479,6 +509,16 @@ function formatQuota(quota, options) {
479
509
  return parts.join(" \xB7 ");
480
510
  return quota && quota.limits.length > 0 ? NO_LIMITS_REPORTED : NO_QUOTA_READING;
481
511
  }
512
+ function quotaCreditsText(credits) {
513
+ if (credits === void 0)
514
+ return void 0;
515
+ if (credits.unlimited)
516
+ return "Unlimited";
517
+ if (!credits.hasCredits)
518
+ return void 0;
519
+ const { balance } = credits;
520
+ return typeof balance === "number" && Number.isFinite(balance) && balance > 0 ? `${Math.round(balance)} credits` : "Available";
521
+ }
482
522
  var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED, NARROW_GROUP_LIMIT;
483
523
  var init_format = __esm({
484
524
  "../core/dist/common-auth-embedded/quota/format.js"() {
@@ -560,12 +600,14 @@ function projectQuota(map, scope = ALL_SCOPE) {
560
600
  const checkedAt = stamped.length > 0 ? Math.min(...stamped.map((limit) => limit.checkedAt)) : void 0;
561
601
  const budget = map?.budget?.kind === "reading" ? projectBudget(map.budget) : void 0;
562
602
  const counters = readQuotaCounters(map?.counters);
603
+ const credits = isQuotaCredits(map?.credits) ? map.credits : void 0;
563
604
  return {
564
605
  scope,
565
606
  limits,
566
607
  ...checkedAt === void 0 ? {} : { checkedAt },
567
608
  ...budget === void 0 ? {} : { budget },
568
- ...counters === void 0 ? {} : { counters }
609
+ ...counters === void 0 ? {} : { counters },
610
+ ...credits === void 0 ? {} : { credits }
569
611
  };
570
612
  }
571
613
  function budgetExhaustedResetAt(quota, now) {
@@ -608,12 +650,14 @@ __export(quota_exports, {
608
650
  emptyQuotaMap: () => emptyQuotaMap,
609
651
  formatQuota: () => formatQuota,
610
652
  futureResetAt: () => futureResetAt,
653
+ isQuotaCredits: () => isQuotaCredits,
611
654
  isQuotaMap: () => isQuotaMap,
612
655
  isQuotaObservation: () => isQuotaObservation,
613
656
  isQuotaStale: () => isQuotaStale,
614
657
  mergeQuotaObservation: () => mergeQuotaObservation,
615
658
  projectQuota: () => projectQuota,
616
659
  quotaCodec: () => quotaCodec2,
660
+ quotaCreditsText: () => quotaCreditsText,
617
661
  quotaTextParts: () => quotaTextParts,
618
662
  quotaWindowName: () => quotaWindowName,
619
663
  quotaWindowParts: () => quotaWindowParts,
@@ -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
  }
@@ -18230,7 +18542,7 @@ async function rmEvictingDir(evictingPath) {
18230
18542
  });
18231
18543
  }
18232
18544
  async function sleep(ms) {
18233
- await new Promise((resolve18) => setTimeout(resolve18, ms));
18545
+ await new Promise((resolve20) => setTimeout(resolve20, ms));
18234
18546
  }
18235
18547
  async function acquireFencedFileLock(options) {
18236
18548
  const lockPath = `${options.path}.${options.name}.lock`;
@@ -18346,8 +18658,8 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
18346
18658
  let released = false;
18347
18659
  let lost = false;
18348
18660
  let lostResolve = null;
18349
- let lostPromise = new Promise((resolve18) => {
18350
- lostResolve = resolve18;
18661
+ let lostPromise = new Promise((resolve20) => {
18662
+ lostResolve = resolve20;
18351
18663
  });
18352
18664
  const markLost = () => {
18353
18665
  if (lost)
@@ -18357,9 +18669,9 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
18357
18669
  clearInterval(renewTimer);
18358
18670
  renewTimer = null;
18359
18671
  }
18360
- const resolve18 = lostResolve;
18672
+ const resolve20 = lostResolve;
18361
18673
  lostResolve = null;
18362
- resolve18?.();
18674
+ resolve20?.();
18363
18675
  };
18364
18676
  const setupRenew = () => {
18365
18677
  if (options.renew === false)
@@ -18586,7 +18898,7 @@ var AccountStorageUnreadableError = class extends Error {
18586
18898
  }
18587
18899
  };
18588
18900
  var RETRY_DELAYS_MS = [100, 200, 400, 800, 1e3];
18589
- var DEFAULT_SLEEP = (ms) => new Promise((resolve18) => setTimeout(resolve18, ms));
18901
+ var DEFAULT_SLEEP = (ms) => new Promise((resolve20) => setTimeout(resolve20, ms));
18590
18902
  var DEFAULT_BUILD_BACKUP_PATH = (path5, now) => `${path5}.corrupt-${now.toISOString().replace(/[:.]/g, "-")}`;
18591
18903
  async function ensureSecurePermissions(path5) {
18592
18904
  try {
@@ -18977,7 +19289,7 @@ async function saveAccountStorageReplace(path5, incoming) {
18977
19289
  return mutateAccountStorage(path5, () => incoming);
18978
19290
  }
18979
19291
  async function clearAccountStorage(path5) {
18980
- const sleep5 = (ms) => new Promise((resolve18) => setTimeout(resolve18, ms));
19292
+ const sleep5 = (ms) => new Promise((resolve20) => setTimeout(resolve20, ms));
18981
19293
  const lock = await acquireWithRetry(path5, sleep5);
18982
19294
  try {
18983
19295
  await assertLegacyAccountStorageWritable(path5);
@@ -20168,8 +20480,8 @@ var AccountManager = class _AccountManager {
20168
20480
  await this.saveInFlight;
20169
20481
  return;
20170
20482
  }
20171
- return new Promise((resolve18, reject) => {
20172
- this.savePromiseResolvers.push({ resolve: resolve18, reject });
20483
+ return new Promise((resolve20, reject) => {
20484
+ this.savePromiseResolvers.push({ resolve: resolve20, reject });
20173
20485
  });
20174
20486
  }
20175
20487
  async dispose() {
@@ -20212,8 +20524,8 @@ var AccountManager = class _AccountManager {
20212
20524
  reject(error);
20213
20525
  throw error;
20214
20526
  }
20215
- for (const { resolve: resolve18 } of resolvers)
20216
- resolve18();
20527
+ for (const { resolve: resolve20 } of resolvers)
20528
+ resolve20();
20217
20529
  }
20218
20530
  async executeSave() {
20219
20531
  this.savePending = false;
@@ -20227,16 +20539,16 @@ var AccountManager = class _AccountManager {
20227
20539
  }
20228
20540
  try {
20229
20541
  await this.saveToDisk();
20230
- for (const { resolve: resolve18 } of resolvers) {
20231
- resolve18();
20542
+ for (const { resolve: resolve20 } of resolvers) {
20543
+ resolve20();
20232
20544
  }
20233
20545
  } catch (error) {
20234
20546
  if (isStorageLockContention(error)) {
20235
20547
  this.onDiagnostic?.("Skipped account-state persist due to storage lock contention", {
20236
20548
  error: String(error)
20237
20549
  });
20238
- for (const { resolve: resolve18 } of resolvers) {
20239
- resolve18();
20550
+ for (const { resolve: resolve20 } of resolvers) {
20551
+ resolve20();
20240
20552
  }
20241
20553
  return;
20242
20554
  }
@@ -20713,7 +21025,7 @@ function getHttpsProxy(url) {
20713
21025
  }
20714
21026
  }
20715
21027
  function waitForHead(socket, timeoutMs, onTimeout) {
20716
- return new Promise((resolve18, reject) => {
21028
+ return new Promise((resolve20, reject) => {
20717
21029
  let buffer = Buffer3.alloc(0);
20718
21030
  const timeout = setTimeout(() => {
20719
21031
  onTimeout();
@@ -20736,7 +21048,7 @@ function waitForHead(socket, timeoutMs, onTimeout) {
20736
21048
  return;
20737
21049
  const head = buffer.subarray(0, marker).toString("latin1");
20738
21050
  const leftover = buffer.subarray(marker + 4);
20739
- cleanup2(() => resolve18({ head, leftover }));
21051
+ cleanup2(() => resolve20({ head, leftover }));
20740
21052
  };
20741
21053
  socket.on("data", onData);
20742
21054
  socket.once("error", onError);
@@ -20750,7 +21062,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
20750
21062
  port: Number(proxyUrl.port || DEFAULT_PROXY_PORT),
20751
21063
  signal: signal ?? void 0
20752
21064
  });
20753
- await new Promise((resolve18, reject) => {
21065
+ await new Promise((resolve20, reject) => {
20754
21066
  const timeout = setTimeout(() => {
20755
21067
  onDebug?.(`agy transport proxy connect timeout after ${timeoutMs}ms`);
20756
21068
  proxySocket.destroy();
@@ -20759,7 +21071,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
20759
21071
  const cleanup2 = () => clearTimeout(timeout);
20760
21072
  proxySocket.once("connect", () => {
20761
21073
  cleanup2();
20762
- resolve18();
21074
+ resolve20();
20763
21075
  });
20764
21076
  proxySocket.once("error", (error) => {
20765
21077
  cleanup2();
@@ -20784,7 +21096,7 @@ Host: ${targetHost}:${targetPort}\r
20784
21096
  if (leftover.length > 0) {
20785
21097
  proxySocket.unshift(leftover);
20786
21098
  }
20787
- return await new Promise((resolve18, reject) => {
21099
+ return await new Promise((resolve20, reject) => {
20788
21100
  const tlsOptions = {
20789
21101
  socket: proxySocket,
20790
21102
  servername: targetHost,
@@ -20799,7 +21111,7 @@ Host: ${targetHost}:${targetPort}\r
20799
21111
  const cleanup2 = () => clearTimeout(timeout);
20800
21112
  tlsSocket.once("secureConnect", () => {
20801
21113
  cleanup2();
20802
- resolve18(tlsSocket);
21114
+ resolve20(tlsSocket);
20803
21115
  });
20804
21116
  tlsSocket.once("error", (error) => {
20805
21117
  cleanup2();
@@ -20808,7 +21120,7 @@ Host: ${targetHost}:${targetPort}\r
20808
21120
  });
20809
21121
  }
20810
21122
  async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
20811
- return await new Promise((resolve18, reject) => {
21123
+ return await new Promise((resolve20, reject) => {
20812
21124
  const tlsOptions = {
20813
21125
  host: targetUrl.hostname,
20814
21126
  port: Number(targetUrl.port || DEFAULT_HTTPS_PORT),
@@ -20824,7 +21136,7 @@ async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
20824
21136
  const cleanup2 = () => clearTimeout(timeout);
20825
21137
  socket.once("secureConnect", () => {
20826
21138
  cleanup2();
20827
- resolve18(socket);
21139
+ resolve20(socket);
20828
21140
  });
20829
21141
  socket.once("error", (error) => {
20830
21142
  cleanup2();
@@ -22027,11 +22339,11 @@ function containsCredential(value, credentials, projectIds, seen = /* @__PURE__
22027
22339
  function redactCredentialError(error, credentials, projectIds) {
22028
22340
  const source = error instanceof Error || error instanceof DOMException ? error : void 0;
22029
22341
  const message = redactCredentialText(source?.message ?? String(error), credentials, projectIds);
22030
- const fields = source ? Reflect.ownKeys(source).map((key) => ({
22342
+ const fields2 = source ? Reflect.ownKeys(source).map((key) => ({
22031
22343
  key,
22032
22344
  descriptor: Object.getOwnPropertyDescriptor(source, key)
22033
22345
  })) : [];
22034
- const cause = fields.find(({ key }) => key === "cause")?.descriptor;
22346
+ const cause = fields2.find(({ key }) => key === "cause")?.descriptor;
22035
22347
  const secretCause = cause && (!("value" in cause) || containsCredential(cause.value, credentials, projectIds));
22036
22348
  try {
22037
22349
  if (source) {
@@ -22041,7 +22353,7 @@ function redactCredentialError(error, credentials, projectIds) {
22041
22353
  configurable: true,
22042
22354
  writable: true
22043
22355
  });
22044
- for (const { key, descriptor } of fields) {
22356
+ for (const { key, descriptor } of fields2) {
22045
22357
  if (key === "message" || key === "cause" || !("value" in descriptor))
22046
22358
  continue;
22047
22359
  const value = scrub2(descriptor.value, credentials, projectIds);
@@ -22056,7 +22368,7 @@ function redactCredentialError(error, credentials, projectIds) {
22056
22368
  }
22057
22369
  const safe = new Error(message);
22058
22370
  safe.name = redactCredentialText(source?.name ?? "Error", credentials, projectIds);
22059
- for (const { key, descriptor } of fields) {
22371
+ for (const { key, descriptor } of fields2) {
22060
22372
  if (key === "message" || key === "cause" || !("value" in descriptor))
22061
22373
  continue;
22062
22374
  Object.defineProperty(safe, key, {
@@ -22367,8 +22679,8 @@ function getDefaultTierId(allowedTiers) {
22367
22679
  return allowedTiers[0]?.id;
22368
22680
  }
22369
22681
  function wait(ms) {
22370
- return new Promise((resolve18) => {
22371
- setTimeout(resolve18, ms);
22682
+ return new Promise((resolve20) => {
22683
+ setTimeout(resolve20, ms);
22372
22684
  });
22373
22685
  }
22374
22686
  function extractManagedProjectId(payload) {
@@ -24395,12 +24707,12 @@ async function commitVaultProviderState(input2) {
24395
24707
  function untilAborted(pending, signal) {
24396
24708
  if (!signal)
24397
24709
  return pending;
24398
- return new Promise((resolve18, reject) => {
24710
+ return new Promise((resolve20, reject) => {
24399
24711
  const abort = () => reject(signal.reason);
24400
24712
  signal.addEventListener("abort", abort, { once: true });
24401
24713
  if (signal.aborted)
24402
24714
  abort();
24403
- pending.then(resolve18, reject).finally(() => signal.removeEventListener("abort", abort));
24715
+ pending.then(resolve20, reject).finally(() => signal.removeEventListener("abort", abort));
24404
24716
  });
24405
24717
  }
24406
24718
  var AntigravityVaultSourceError = class extends Error {
@@ -24876,21 +25188,21 @@ import { randomBytes as randomBytes5 } from "node:crypto";
24876
25188
  function present2(value) {
24877
25189
  return value === null ? void 0 : value;
24878
25190
  }
24879
- function accessBlockOf(fields) {
24880
- if (fields === void 0) return { kind: "none" };
24881
- if (fields.accountIneligible === true) {
24882
- const reason = present2(fields.accountIneligibleReason);
24883
- const at = present2(fields.accountIneligibleAt);
25191
+ function accessBlockOf(fields2) {
25192
+ if (fields2 === void 0) return { kind: "none" };
25193
+ if (fields2.accountIneligible === true) {
25194
+ const reason = present2(fields2.accountIneligibleReason);
25195
+ const at = present2(fields2.accountIneligibleAt);
24884
25196
  return {
24885
25197
  kind: "ineligible",
24886
25198
  ...reason !== void 0 ? { reason } : {},
24887
25199
  ...at !== void 0 ? { at } : {}
24888
25200
  };
24889
25201
  }
24890
- if (fields.verificationRequired === true) {
24891
- const reason = present2(fields.verificationRequiredReason);
24892
- const verificationUrl = present2(fields.verificationUrl);
24893
- const at = present2(fields.verificationRequiredAt);
25202
+ if (fields2.verificationRequired === true) {
25203
+ const reason = present2(fields2.verificationRequiredReason);
25204
+ const verificationUrl = present2(fields2.verificationUrl);
25205
+ const at = present2(fields2.verificationRequiredAt);
24894
25206
  return {
24895
25207
  kind: "verification-required",
24896
25208
  ...reason !== void 0 ? { reason } : {},
@@ -25019,12 +25331,12 @@ function clearLegacyAccessBlocks(account, enableIfBlocked, now) {
25019
25331
  // src/common-auth-embedded/logger/engine.js
25020
25332
  import { appendFileSync as appendFileSync2, chmodSync as chmodSync2, existsSync as existsSync2, renameSync as renameSync2, statSync as statSync3 } from "node:fs";
25021
25333
  import { open as open8 } from "node:fs/promises";
25022
- import { dirname as dirname13, resolve as resolve8 } from "node:path";
25334
+ import { dirname as dirname13, resolve as resolve10 } from "node:path";
25023
25335
 
25024
25336
  // src/common-auth-embedded/fs/private-files.js
25025
25337
  import { randomUUID as randomUUID13 } from "node:crypto";
25026
25338
  import { lstat as lstat4, readFile as readFile8, rename as rename7, unlink as unlink8 } from "node:fs/promises";
25027
- import { dirname as dirname12, resolve as resolve7 } from "node:path";
25339
+ import { dirname as dirname12, resolve as resolve9 } from "node:path";
25028
25340
  var windowsPrivateFiles2 = process.platform === "win32";
25029
25341
  var migrationNotices2 = /* @__PURE__ */ new Set();
25030
25342
  function ioCode2(detail) {
@@ -25075,7 +25387,7 @@ async function privateOperation2(path5, stage, operation) {
25075
25387
  }
25076
25388
  var safeParentOptionsForTest2;
25077
25389
  async function verifySafeDirectory2(path5, options) {
25078
- path5 = resolve7(path5);
25390
+ path5 = resolve9(path5);
25079
25391
  options ??= safeParentOptionsForTest2;
25080
25392
  await privateOperation2(path5, "safe-parent", async () => {
25081
25393
  const result = await (await loadBackend2()).verifySafeParent(path5, options);
@@ -25090,7 +25402,7 @@ async function verifySafeDirectory2(path5, options) {
25090
25402
  });
25091
25403
  }
25092
25404
  async function verifyPrivate2(path5, kind, migrate = false) {
25093
- path5 = resolve7(path5);
25405
+ path5 = resolve9(path5);
25094
25406
  if (kind === "directory")
25095
25407
  return verifySafeDirectory2(path5);
25096
25408
  await privateOperation2(path5, "verify", async () => {
@@ -25125,7 +25437,7 @@ async function verifyPrivate2(path5, kind, migrate = false) {
25125
25437
  });
25126
25438
  }
25127
25439
  async function ensurePrivateDirectory3(path5, _migrate = false, options) {
25128
- path5 = resolve7(path5);
25440
+ path5 = resolve9(path5);
25129
25441
  await privateOperation2(path5, "directory", async () => {
25130
25442
  const api = await loadBackend2();
25131
25443
  try {
@@ -25156,7 +25468,7 @@ async function readPrivateText2(path5, migrate = false) {
25156
25468
  async function readPrivateBuffer2(path5, migrate = false) {
25157
25469
  if (!windowsPrivateFiles2)
25158
25470
  return readFile8(path5);
25159
- path5 = resolve7(path5);
25471
+ path5 = resolve9(path5);
25160
25472
  if (migrate) {
25161
25473
  await verifySafeDirectory2(dirname12(path5));
25162
25474
  await verifyPrivate2(path5, "file", true);
@@ -25164,20 +25476,20 @@ async function readPrivateBuffer2(path5, migrate = false) {
25164
25476
  return privateOperation2(path5, "read", async () => (await loadBackend2()).readOwnerOnly(path5));
25165
25477
  }
25166
25478
  async function createPrivateBytes2(path5, bytes) {
25167
- await verifySafeDirectory2(dirname12(resolve7(path5)));
25479
+ await verifySafeDirectory2(dirname12(resolve9(path5)));
25168
25480
  await privateOperation2(path5, "create", async () => {
25169
- await (await loadBackend2()).createPrivateFile(resolve7(path5), bytes);
25481
+ await (await loadBackend2()).createPrivateFile(resolve9(path5), bytes);
25170
25482
  });
25171
25483
  }
25172
25484
  async function createPrivateDirectoryExclusive2(path5) {
25173
- await verifySafeDirectory2(dirname12(resolve7(path5)));
25485
+ await verifySafeDirectory2(dirname12(resolve9(path5)));
25174
25486
  await privateOperation2(path5, "directory-create", async () => {
25175
- await (await loadBackend2()).createOwnerOnly(resolve7(path5), { kind: "dir" });
25487
+ await (await loadBackend2()).createOwnerOnly(resolve9(path5), { kind: "dir" });
25176
25488
  });
25177
25489
  }
25178
25490
  async function replaceWindowsFile2(from, to, options = {}) {
25179
- from = resolve7(from);
25180
- to = resolve7(to);
25491
+ from = resolve9(from);
25492
+ to = resolve9(to);
25181
25493
  const now = options.now ?? (() => performance.now());
25182
25494
  const start = now();
25183
25495
  const leaseDeadline = options.deadline ?? Infinity;
@@ -25220,7 +25532,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
25220
25532
  throw error;
25221
25533
  }
25222
25534
  async function writePrivateAtomic2(path5, bytes, options = {}) {
25223
- path5 = resolve7(path5);
25535
+ path5 = resolve9(path5);
25224
25536
  await ensurePrivateDirectory3(dirname12(path5));
25225
25537
  try {
25226
25538
  await verifyPrivate2(path5, "file", true);
@@ -25228,7 +25540,7 @@ async function writePrivateAtomic2(path5, bytes, options = {}) {
25228
25540
  if (error.code !== "ENOENT")
25229
25541
  throw error;
25230
25542
  }
25231
- const stage = resolve7(options.stagePath ?? `${path5}.${randomUUID13()}.tmp`);
25543
+ const stage = resolve9(options.stagePath ?? `${path5}.${randomUUID13()}.tmp`);
25232
25544
  if (dirname12(stage) !== dirname12(path5))
25233
25545
  throw new PrivateFileError2(path5, "stage-directory", { code: "EXDEV" });
25234
25546
  let created = false;
@@ -25304,15 +25616,15 @@ function createRedactor2(options = {}) {
25304
25616
  return SECRET_KEY_EXACT2.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
25305
25617
  }
25306
25618
  function errorEntries(error) {
25307
- const fields = error;
25619
+ const fields2 = error;
25308
25620
  const entries = [
25309
25621
  ["name", error.name],
25310
25622
  ["message", error.message],
25311
25623
  ["stack", error.stack]
25312
25624
  ];
25313
25625
  for (const key of ["code", "status", "cause"])
25314
- if (fields[key] !== void 0)
25315
- entries.push([key, fields[key]]);
25626
+ if (fields2[key] !== void 0)
25627
+ entries.push([key, fields2[key]]);
25316
25628
  const listed = new Set(entries.map(([key]) => key));
25317
25629
  for (const entry of Object.entries(error))
25318
25630
  if (!listed.has(entry[0]))
@@ -25413,7 +25725,7 @@ async function openWindowsFile2(sink, file) {
25413
25725
  return sink.handle;
25414
25726
  }
25415
25727
  async function flushWindowsFile2(sink, file, text2) {
25416
- file = resolve8(file);
25728
+ file = resolve10(file);
25417
25729
  try {
25418
25730
  if (sink.file !== file)
25419
25731
  await closeWindowsFile2(sink);
@@ -25550,7 +25862,7 @@ function createEngine2(options) {
25550
25862
  } catch {
25551
25863
  }
25552
25864
  }
25553
- function schedule() {
25865
+ function schedule2() {
25554
25866
  if (!timer)
25555
25867
  timer = setTimeout(() => {
25556
25868
  timer = void 0;
@@ -25592,7 +25904,7 @@ function createEngine2(options) {
25592
25904
  void flushed.catch(() => {
25593
25905
  });
25594
25906
  } else
25595
- schedule();
25907
+ schedule2();
25596
25908
  } catch {
25597
25909
  }
25598
25910
  }
@@ -25808,7 +26120,7 @@ import {
25808
26120
  writeFileSync
25809
26121
  } from "node:fs";
25810
26122
  import { homedir as homedir2 } from "node:os";
25811
- import { dirname as dirname14, join as join7, resolve as resolve9 } from "node:path";
26123
+ import { dirname as dirname14, join as join7, resolve as resolve11 } from "node:path";
25812
26124
  var log5 = createLogger4("storage");
25813
26125
  var mutateAccountStorage2 = async (path5, mutate) => {
25814
26126
  await assertLegacyPoolInUse(path5);
@@ -25996,7 +26308,7 @@ var LegacyAccountPoolRetiredError = class extends Error {
25996
26308
  };
25997
26309
  async function assertLegacyPoolInUse(legacyPath) {
25998
26310
  try {
25999
- await assertLegacyAccountStorageWritable(resolve9(legacyPath));
26311
+ await assertLegacyAccountStorageWritable(resolve11(legacyPath));
26000
26312
  } catch (error) {
26001
26313
  throw new LegacyAccountPoolRetiredError(legacyPath, { cause: error });
26002
26314
  }
@@ -26016,7 +26328,7 @@ function refusalMessage(admission) {
26016
26328
  }
26017
26329
  async function bindingOf(options) {
26018
26330
  const now = options.now ?? (() => Date.now());
26019
- const legacyPath = resolve9(options.legacyPath ?? getStoragePath());
26331
+ const legacyPath = resolve11(options.legacyPath ?? getStoragePath());
26020
26332
  return {
26021
26333
  legacyPath,
26022
26334
  now,
@@ -26084,7 +26396,7 @@ async function openAccountStore(options) {
26084
26396
  }
26085
26397
  function initializeFreshAccountStoreFor(modules, options = {}) {
26086
26398
  return initializeFreshAccountStore(modules, {
26087
- legacyPath: resolve9(options.legacyPath ?? getStoragePath()),
26399
+ legacyPath: resolve11(options.legacyPath ?? getStoragePath()),
26088
26400
  now: options.now ?? (() => Date.now())
26089
26401
  });
26090
26402
  }
@@ -26261,13 +26573,13 @@ function closeDebugStream(state) {
26261
26573
  state.logWriter = () => {
26262
26574
  };
26263
26575
  if (state.logFilePath) liveLogFilePaths.delete(state.logFilePath);
26264
- return new Promise((resolve18) => {
26265
- current.once("close", () => resolve18());
26266
- current.once("error", () => resolve18());
26576
+ return new Promise((resolve20) => {
26577
+ current.once("close", () => resolve20());
26578
+ current.once("error", () => resolve20());
26267
26579
  try {
26268
26580
  current.end();
26269
26581
  } catch {
26270
- resolve18();
26582
+ resolve20();
26271
26583
  }
26272
26584
  });
26273
26585
  }
@@ -26539,13 +26851,13 @@ function closeDebugLog() {
26539
26851
  if (!state || !current) return Promise.resolve();
26540
26852
  state.logStream = null;
26541
26853
  if (state.logFilePath) liveLogFilePaths.delete(state.logFilePath);
26542
- return new Promise((resolve18) => {
26543
- current.once("close", () => resolve18());
26544
- current.once("error", () => resolve18());
26854
+ return new Promise((resolve20) => {
26855
+ current.once("close", () => resolve20());
26856
+ current.once("error", () => resolve20());
26545
26857
  try {
26546
26858
  current.end();
26547
26859
  } catch {
26548
- resolve18();
26860
+ resolve20();
26549
26861
  }
26550
26862
  });
26551
26863
  }
@@ -27527,8 +27839,8 @@ var openCodeStore = {
27527
27839
  clear: async () => {
27528
27840
  }
27529
27841
  };
27530
- function defaultDiagnostic(message, fields) {
27531
- debugLogToFile(fields ? `${message} ${JSON.stringify(fields)}` : message);
27842
+ function defaultDiagnostic(message, fields2) {
27843
+ debugLogToFile(fields2 ? `${message} ${JSON.stringify(fields2)}` : message);
27532
27844
  }
27533
27845
  var AccountStoreNotReadyError = class extends Error {
27534
27846
  read;
@@ -27627,7 +27939,7 @@ import { z as z4 } from "zod";
27627
27939
  // src/plugin/config/loader.ts
27628
27940
  import { existsSync as existsSync4, readFileSync as readFileSync2, realpathSync } from "node:fs";
27629
27941
  import { homedir as homedir4 } from "node:os";
27630
- import { basename as basename4, dirname as dirname15, join as join9, resolve as resolve10 } from "node:path";
27942
+ import { basename as basename4, dirname as dirname15, join as join9, resolve as resolve12 } from "node:path";
27631
27943
 
27632
27944
  // src/plugin/config/schema.ts
27633
27945
  import { z } from "zod";
@@ -28185,13 +28497,13 @@ function loadConfigWithLogger(directory, log16) {
28185
28497
  return config;
28186
28498
  }
28187
28499
  function createLocationConfig(directory, options) {
28188
- const logger2 = options?.logger;
28189
- if (typeof logger2?.warn !== "function") {
28500
+ const logger3 = options?.logger;
28501
+ if (typeof logger3?.warn !== "function") {
28190
28502
  throw new TypeError(
28191
28503
  "createLocationConfig requires a logger with a warn function"
28192
28504
  );
28193
28505
  }
28194
- const config = loadConfigWithLogger(directory, logger2);
28506
+ const config = loadConfigWithLogger(directory, logger3);
28195
28507
  return {
28196
28508
  directory,
28197
28509
  config,
@@ -28201,7 +28513,7 @@ function createLocationConfig(directory, options) {
28201
28513
  };
28202
28514
  }
28203
28515
  function canonicalizeOwnedPath(path5) {
28204
- const absolute = resolve10(path5);
28516
+ const absolute = resolve12(path5);
28205
28517
  const missing = [];
28206
28518
  let current = absolute;
28207
28519
  for (; ; ) {
@@ -29162,7 +29474,7 @@ function drainSidebarWrites() {
29162
29474
  return sidebarWriteChain;
29163
29475
  }
29164
29476
  async function sleep3(ms) {
29165
- await new Promise((resolve18) => setTimeout(resolve18, ms));
29477
+ await new Promise((resolve20) => setTimeout(resolve20, ms));
29166
29478
  }
29167
29479
  async function acquireSidebarLockWithRetry(stateFile) {
29168
29480
  const start = Date.now();
@@ -29340,7 +29652,7 @@ function createLocationQuotaManager(options) {
29340
29652
  fetchTimeoutMs: options.fetchTimeoutMs
29341
29653
  });
29342
29654
  const sidebar = options.sidebar;
29343
- const logger2 = options.logger;
29655
+ const logger3 = options.logger;
29344
29656
  return withSidebarPushAfterRefresh(
29345
29657
  manager,
29346
29658
  sidebar ? (account) => pushSidebarQuotaSnapshot(
@@ -29349,7 +29661,7 @@ function createLocationQuotaManager(options) {
29349
29661
  sidebar.getActiveIndexByFamily,
29350
29662
  {
29351
29663
  write: sidebar.write,
29352
- logger: logger2,
29664
+ logger: logger3,
29353
29665
  healthScore: sidebar.healthScore ?? null,
29354
29666
  now: sidebar.now
29355
29667
  }
@@ -29713,14 +30025,14 @@ var LocalQuotaGrantStaleError = class extends Error {
29713
30025
  name = "LocalQuotaGrantStaleError";
29714
30026
  };
29715
30027
  function untilQuotaAborted(pending, signal) {
29716
- return new Promise((resolve18, reject) => {
30028
+ return new Promise((resolve20, reject) => {
29717
30029
  const abort = () => reject(signal.reason);
29718
30030
  if (signal.aborted) abort();
29719
30031
  else signal.addEventListener("abort", abort, { once: true });
29720
30032
  void pending.then(
29721
30033
  (value) => {
29722
30034
  signal.removeEventListener("abort", abort);
29723
- resolve18(value);
30035
+ resolve20(value);
29724
30036
  },
29725
30037
  (error) => {
29726
30038
  signal.removeEventListener("abort", abort);
@@ -30080,7 +30392,7 @@ function heldAccount(manager, ref) {
30080
30392
  );
30081
30393
  }
30082
30394
  function createStoreQuotaService(options) {
30083
- const { manager, logger: logger2 } = options;
30395
+ const { manager, logger: logger3 } = options;
30084
30396
  const credentials = options.credentials ?? createLocalAccountCredentials(manager, { repository: options.repository });
30085
30397
  const authorize = async (account, _signal, purpose = "required") => {
30086
30398
  const ref = account.rowRef;
@@ -30153,11 +30465,11 @@ function createStoreQuotaService(options) {
30153
30465
  };
30154
30466
  const fetchAccountQuota = createAuthorizedFetchAccountQuota({
30155
30467
  authorize: (account) => authorize(account),
30156
- logger: logger2,
30468
+ logger: logger3,
30157
30469
  transport: options.transport
30158
30470
  });
30159
30471
  const quotaManager = createLocationQuotaManager({
30160
- logger: logger2,
30472
+ logger: logger3,
30161
30473
  fetchAccountQuota,
30162
30474
  // Backoff and cache are per credential: a re-authenticated row starts
30163
30475
  // fresh instead of inheriting its predecessor's state.
@@ -30230,7 +30542,7 @@ function createStoreQuotaService(options) {
30230
30542
  (failure2) => failure2.rowId
30231
30543
  );
30232
30544
  failedRows = report === void 0 || failedIds.length === 0 || failedIds.some((id) => id === void 0) ? "all" : new Set(failedIds.filter((id) => id !== void 0));
30233
- logger2.debug("quota readings were not all persisted", {
30545
+ logger3.debug("quota readings were not all persisted", {
30234
30546
  error: error instanceof Error ? error.message : String(error)
30235
30547
  });
30236
30548
  }
@@ -33545,6 +33857,7 @@ var NATIVE_GOOGLE_ERROR_MESSAGES = {
33545
33857
  operator_policy: "Antigravity account pool is unavailable under the operator quota policy. Adjust /antigravity-killswitch or refresh quota.",
33546
33858
  soft_quota: "Antigravity account pool is unavailable under the quota protection policy. Add accounts, wait for quota reset, or disable soft quota protection.",
33547
33859
  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.",
33860
+ model_unavailable: "The requested Antigravity model is not available to the configured accounts. Choose another model.",
33548
33861
  missing_access_token: "Missing access token. Run `opencode auth login` to reauthenticate.",
33549
33862
  empty_response: "Antigravity returned an empty response after the internal retry attempts."
33550
33863
  };
@@ -35580,12 +35893,12 @@ async function startOAuthListener({
35580
35893
  let resolveCallback;
35581
35894
  let rejectCallback;
35582
35895
  let timeoutHandle;
35583
- const callbackPromise = new Promise((resolve18, reject) => {
35896
+ const callbackPromise = new Promise((resolve20, reject) => {
35584
35897
  resolveCallback = (url) => {
35585
35898
  if (settled) return;
35586
35899
  settled = true;
35587
35900
  if (timeoutHandle) clearTimeout(timeoutHandle);
35588
- resolve18(url);
35901
+ resolve20(url);
35589
35902
  };
35590
35903
  rejectCallback = (error) => {
35591
35904
  if (settled) return;
@@ -35744,7 +36057,7 @@ async function startOAuthListener({
35744
36057
  });
35745
36058
  });
35746
36059
  const bindAddress = getBindAddress();
35747
- await new Promise((resolve18, reject) => {
36060
+ await new Promise((resolve20, reject) => {
35748
36061
  const handleError = (error) => {
35749
36062
  server.off("error", handleError);
35750
36063
  if (error.code === "EADDRINUSE") {
@@ -35760,7 +36073,7 @@ async function startOAuthListener({
35760
36073
  server.once("error", handleError);
35761
36074
  server.listen(port, bindAddress, () => {
35762
36075
  server.off("error", handleError);
35763
- resolve18();
36076
+ resolve20();
35764
36077
  });
35765
36078
  });
35766
36079
  server.on("error", (error) => {
@@ -35768,7 +36081,7 @@ async function startOAuthListener({
35768
36081
  });
35769
36082
  return {
35770
36083
  waitForCallback: () => callbackPromise,
35771
- close: () => new Promise((resolve18, reject) => {
36084
+ close: () => new Promise((resolve20, reject) => {
35772
36085
  server.close((error) => {
35773
36086
  if (error && error.code !== "ERR_SERVER_NOT_RUNNING") {
35774
36087
  reject(error);
@@ -35777,7 +36090,7 @@ async function startOAuthListener({
35777
36090
  if (!settled) {
35778
36091
  rejectCallback(new Error("OAuth listener closed before callback"));
35779
36092
  }
35780
- resolve18();
36093
+ resolve20();
35781
36094
  });
35782
36095
  })
35783
36096
  };
@@ -35788,7 +36101,7 @@ async function startOAuthListener({
35788
36101
  }
35789
36102
 
35790
36103
  // src/plugin/session-context.ts
35791
- import { resolve as resolve11 } from "node:path";
36104
+ import { resolve as resolve13 } from "node:path";
35792
36105
  import { pathToFileURL } from "node:url";
35793
36106
  var FALLBACK_SESSION_KEY = "__default__";
35794
36107
  function extractOpenCodeSessionIdentity(headers) {
@@ -35802,7 +36115,7 @@ var AgySessionRegistry = class {
35802
36115
  requestSessions;
35803
36116
  parentSessionIds = /* @__PURE__ */ new Map();
35804
36117
  constructor(directory, options = {}) {
35805
- const workspaceUri = directory ? pathToFileURL(resolve11(directory)).href : "";
36118
+ const workspaceUri = directory ? pathToFileURL(resolve13(directory)).href : "";
35806
36119
  this.requestSessions = new AgyRequestSessionStore(workspaceUri, options);
35807
36120
  }
35808
36121
  getOrCreate(identity) {
@@ -36427,10 +36740,10 @@ async function retainResponseLifetime(response, cancellation) {
36427
36740
  cancellation.release();
36428
36741
  throw error;
36429
36742
  }
36430
- let resolve18 = () => {
36743
+ let resolve20 = () => {
36431
36744
  };
36432
36745
  const settled = new Promise((done) => {
36433
- resolve18 = done;
36746
+ resolve20 = done;
36434
36747
  });
36435
36748
  let stopping = false;
36436
36749
  let finished = false;
@@ -36440,7 +36753,7 @@ async function retainResponseLifetime(response, cancellation) {
36440
36753
  finished = true;
36441
36754
  cancellation.signal.removeEventListener("abort", abort);
36442
36755
  cancellation.release();
36443
- resolve18();
36756
+ resolve20();
36444
36757
  };
36445
36758
  const abort = () => {
36446
36759
  if (finished || stopping) return;
@@ -36509,8 +36822,8 @@ function createAfterHandoff(work, signals, onFailure) {
36509
36822
  let running = false;
36510
36823
  let resolveCompletion = () => {
36511
36824
  };
36512
- const completion = new Promise((resolve18) => {
36513
- resolveCompletion = resolve18;
36825
+ const completion = new Promise((resolve20) => {
36826
+ resolveCompletion = resolve20;
36514
36827
  });
36515
36828
  const finish = () => {
36516
36829
  if (finished) return;
@@ -36557,14 +36870,14 @@ function createAfterHandoff(work, signals, onFailure) {
36557
36870
  };
36558
36871
  }
36559
36872
  function publishResponse(dispatch) {
36560
- return new Promise((resolve18, reject) => {
36873
+ return new Promise((resolve20, reject) => {
36561
36874
  let acknowledge;
36562
36875
  void Promise.resolve().then(
36563
36876
  () => dispatch((callback) => {
36564
36877
  acknowledge = callback;
36565
36878
  })
36566
36879
  ).then((response) => {
36567
- resolve18(response);
36880
+ resolve20(response);
36568
36881
  acknowledge?.();
36569
36882
  }, reject);
36570
36883
  });
@@ -36666,7 +36979,7 @@ function formatWaitTime(ms) {
36666
36979
  return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
36667
36980
  }
36668
36981
  function sleep4(ms, signal) {
36669
- return new Promise((resolve18, reject) => {
36982
+ return new Promise((resolve20, reject) => {
36670
36983
  if (signal?.aborted) {
36671
36984
  reject(
36672
36985
  signal.reason instanceof Error ? signal.reason : new Error("Aborted")
@@ -36675,7 +36988,7 @@ function sleep4(ms, signal) {
36675
36988
  }
36676
36989
  const timeout = setTimeout(() => {
36677
36990
  cleanup2();
36678
- resolve18();
36991
+ resolve20();
36679
36992
  }, ms);
36680
36993
  const onAbort = () => {
36681
36994
  cleanup2();
@@ -36931,6 +37244,7 @@ function createRequestExecutor(deps) {
36931
37244
  let localRecaptureUsed = false;
36932
37245
  const maxWaitMs = (config.max_rate_limit_wait_seconds ?? 300) * 1e3;
36933
37246
  let allAccountsBlockedAt;
37247
+ const modelUnavailableIndexes = /* @__PURE__ */ new Set();
36934
37248
  while (true) {
36935
37249
  await assertAdmission();
36936
37250
  checkAborted();
@@ -36994,6 +37308,26 @@ function createRequestExecutor(deps) {
36994
37308
  const killedIndexes = eligibleIndexes === null ? void 0 : new Set(
36995
37309
  accountManager.getAccounts().map((entry) => entry.index).filter((index) => !eligibleIndexes.has(index))
36996
37310
  );
37311
+ if (modelUnavailableIndexes.size > 0) {
37312
+ const candidates = accountManager.getEnabledAccounts().filter(
37313
+ (entry) => eligibleIndexes === null || eligibleIndexes.has(entry.index)
37314
+ );
37315
+ if (candidates.length > 0 && candidates.every((entry) => modelUnavailableIndexes.has(entry.index))) {
37316
+ pushDebug(
37317
+ `model-unavailable: all ${candidates.length} eligible account(s) skipped`
37318
+ );
37319
+ log16.warn("model-unavailable-all-accounts", {
37320
+ family,
37321
+ model,
37322
+ accounts: candidates.length
37323
+ });
37324
+ return createNativeGoogleErrorResponse({
37325
+ status: 412,
37326
+ reason: "model_unavailable"
37327
+ });
37328
+ }
37329
+ }
37330
+ const excludedIndexes = modelUnavailableIndexes.size === 0 ? killedIndexes : /* @__PURE__ */ new Set([...killedIndexes ?? [], ...modelUnavailableIndexes]);
36997
37331
  let account = accountManager.getCurrentOrNextForFamily(
36998
37332
  family,
36999
37333
  model,
@@ -37002,7 +37336,7 @@ function createRequestExecutor(deps) {
37002
37336
  config.soft_quota_threshold_percent,
37003
37337
  softQuotaCacheTtlMs,
37004
37338
  accountSessionIdentity,
37005
- killedIndexes
37339
+ excludedIndexes
37006
37340
  );
37007
37341
  if (account && eligibleIndexes !== null && !eligibleIndexes.has(account.index)) {
37008
37342
  pushDebug(
@@ -37469,6 +37803,7 @@ function createRequestExecutor(deps) {
37469
37803
  };
37470
37804
  let apiRequestCount = 0;
37471
37805
  let shouldSwitchAccount = false;
37806
+ let skippedForModelUnavailable = false;
37472
37807
  if (account.fingerprint) {
37473
37808
  pushDebug(
37474
37809
  `fingerprint: deviceId=${account.fingerprint.deviceId.slice(0, 8)}...`
@@ -37848,6 +38183,37 @@ function createRequestExecutor(deps) {
37848
38183
  shouldSwitchAccount = true;
37849
38184
  break;
37850
38185
  }
38186
+ if (response.status === 404 && currentEndpoint === ANTIGRAVITY_ENDPOINT_DAILY) {
38187
+ const notFoundBody = await deadline.wait(
38188
+ () => response.clone().text().catch(() => "")
38189
+ );
38190
+ const unavailable = parseModelUnavailableError(notFoundBody);
38191
+ if (unavailable) {
38192
+ if (tokenConsumed) {
38193
+ trackers.token.refund(account.index);
38194
+ tokenConsumed = false;
38195
+ }
38196
+ const reasonCodes = unavailable.reasons.length > 0 ? unavailable.reasons.join(",") : "none";
38197
+ const note = `model-unavailable idx=${account.index} status=${unavailable.status} reasons=${reasonCodes}`;
38198
+ pushDebug(note);
38199
+ debug.logAntigravityDebugResponse(debugContext, response, {
38200
+ note
38201
+ });
38202
+ log16.info("model-unavailable", {
38203
+ accountIndex: account.index,
38204
+ family,
38205
+ model,
38206
+ status: unavailable.status,
38207
+ reasons: unavailable.reasons
38208
+ });
38209
+ void response.body?.cancel().catch(() => {
38210
+ });
38211
+ modelUnavailableIndexes.add(account.index);
38212
+ skippedForModelUnavailable = true;
38213
+ shouldSwitchAccount = true;
38214
+ break;
38215
+ }
38216
+ }
37851
38217
  const quotaKey = getQuotaKey(family, model);
37852
38218
  retryState.resetRateLimitState(account.index, quotaKey);
37853
38219
  retryState.resetAccountFailureState(account.index);
@@ -37914,7 +38280,7 @@ function createRequestExecutor(deps) {
37914
38280
  break;
37915
38281
  }
37916
38282
  }
37917
- const shouldRetryEndpoint = response.status === 403 || response.status === 404 || response.status >= 500;
38283
+ const shouldRetryEndpoint = response.status === 404 || response.status >= 500;
37918
38284
  if (shouldRetryEndpoint && i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
37919
38285
  await logResponseBody2(debugContext, response, response.status);
37920
38286
  lastFailure = createFailureContext(response);
@@ -38165,6 +38531,9 @@ function createRequestExecutor(deps) {
38165
38531
  }
38166
38532
  }
38167
38533
  }
38534
+ if (shouldSwitchAccount && skippedForModelUnavailable) {
38535
+ continue;
38536
+ }
38168
38537
  if (shouldSwitchAccount) {
38169
38538
  accountSwitchCount++;
38170
38539
  if (accountSwitchCount > maxAccountSwitches) {
@@ -38367,6 +38736,32 @@ function createRequestExecutor(deps) {
38367
38736
  dispose
38368
38737
  };
38369
38738
  }
38739
+ var ERROR_REASON_CODE = /^[A-Za-z0-9_.-]{1,128}$/;
38740
+ function parseModelUnavailableError(bodyText) {
38741
+ let body;
38742
+ try {
38743
+ body = JSON.parse(bodyText);
38744
+ } catch {
38745
+ return null;
38746
+ }
38747
+ const envelope = Array.isArray(body) ? body[0] : body;
38748
+ if (!envelope || typeof envelope !== "object") return null;
38749
+ const error = envelope.error;
38750
+ if (!error || typeof error !== "object") return null;
38751
+ if (error.status !== "NOT_FOUND") return null;
38752
+ const details = error.details;
38753
+ const reasons = [];
38754
+ if (Array.isArray(details)) {
38755
+ for (const detail of details) {
38756
+ if (!detail || typeof detail !== "object") continue;
38757
+ const reason = detail.reason;
38758
+ if (typeof reason === "string" && ERROR_REASON_CODE.test(reason)) {
38759
+ reasons.push(reason);
38760
+ }
38761
+ }
38762
+ }
38763
+ return { status: "NOT_FOUND", reasons };
38764
+ }
38370
38765
  function extractRateLimitBodyInfo(body) {
38371
38766
  if (!body || typeof body !== "object") return { retryDelayMs: null };
38372
38767
  const error = body.error;
@@ -39101,13 +39496,13 @@ async function buildLocationRuntime(options, scope) {
39101
39496
  );
39102
39497
  }
39103
39498
  let config;
39104
- const logger2 = createLocationLogger({
39499
+ const logger3 = createLocationLogger({
39105
39500
  sink: options.logSink,
39106
39501
  sinkEnabled: () => config?.config.debug_tui === true
39107
39502
  });
39108
- const log16 = logger2.createLogger("runtime");
39503
+ const log16 = logger3.createLogger("runtime");
39109
39504
  config = createLocationConfig(options.directory, {
39110
- logger: logger2.createLogger("config")
39505
+ logger: logger3.createLogger("config")
39111
39506
  });
39112
39507
  const debug = createLocationDebug(config.config);
39113
39508
  scope.add({ dispose: () => debug.close() }, "consumer");
@@ -39118,7 +39513,7 @@ async function buildLocationRuntime(options, scope) {
39118
39513
  });
39119
39514
  scope.add(operatorSettings, "consumer");
39120
39515
  const applyOperatorSettings = () => {
39121
- logger2.setLevel(operatorSettings.get().log_level);
39516
+ logger3.setLevel(operatorSettings.get().log_level);
39122
39517
  };
39123
39518
  applyOperatorSettings();
39124
39519
  const signatureOptions = {
@@ -39145,7 +39540,7 @@ async function buildLocationRuntime(options, scope) {
39145
39540
  }));
39146
39541
  };
39147
39542
  const quotaManager = createLocationQuotaManager({
39148
- logger: logger2.createLogger("quota"),
39543
+ logger: logger3.createLogger("quota"),
39149
39544
  fetchAccountQuota: options.mayRun ? async (account, signal, purpose) => {
39150
39545
  if (!await options.mayRun?.()) throw new Error(VAULT_ACCOUNT_REMEDY);
39151
39546
  return purpose === "advisory" ? options.fetchAccountQuota(account, signal, purpose) : options.fetchAccountQuota(account, signal);
@@ -39175,7 +39570,7 @@ async function buildLocationRuntime(options, scope) {
39175
39570
  ...options.random ? { random: options.random } : {},
39176
39571
  ...options.acquireLock ? { acquireLock: options.acquireLock } : {},
39177
39572
  healthScore: options.healthScore ?? null,
39178
- logger: logger2.createLogger("background-quota")
39573
+ logger: logger3.createLogger("background-quota")
39179
39574
  });
39180
39575
  const poller = backgroundQuotaRefresh;
39181
39576
  scope.add({ dispose: () => poller.dispose() }, "producer");
@@ -39207,7 +39602,7 @@ async function buildLocationRuntime(options, scope) {
39207
39602
  if (!view || !config?.config.proactive_token_refresh) return;
39208
39603
  const queue2 = createLocationProactiveRefreshQueue(
39209
39604
  {
39210
- logger: logger2.createLogger("refresh-queue"),
39605
+ logger: logger3.createLogger("refresh-queue"),
39211
39606
  refreshToken: options.refreshToken
39212
39607
  },
39213
39608
  {
@@ -39232,7 +39627,7 @@ async function buildLocationRuntime(options, scope) {
39232
39627
  const runtimeConfig2 = config;
39233
39628
  return {
39234
39629
  directory: options.directory,
39235
- logger: logger2,
39630
+ logger: logger3,
39236
39631
  config: runtimeConfig2,
39237
39632
  debug,
39238
39633
  dump,
@@ -39499,7 +39894,7 @@ function createVaultSelectionState(options) {
39499
39894
  report(error);
39500
39895
  }
39501
39896
  };
39502
- const flush = () => {
39897
+ const flush2 = () => {
39503
39898
  writing = writing.then(async () => {
39504
39899
  for (const row of [...changed]) await writeRow(row);
39505
39900
  });
@@ -39515,7 +39910,7 @@ function createVaultSelectionState(options) {
39515
39910
  accessVerdict: mark,
39516
39911
  fingerprint: mark,
39517
39912
  requestSave: () => {
39518
- void flush();
39913
+ void flush2();
39519
39914
  }
39520
39915
  },
39521
39916
  admitted(row, attribution) {
@@ -39538,7 +39933,7 @@ function createVaultSelectionState(options) {
39538
39933
  }
39539
39934
  }
39540
39935
  },
39541
- flush,
39936
+ flush: flush2,
39542
39937
  recordQuota(attribution, quota, signal) {
39543
39938
  return options.source.commitState(
39544
39939
  attribution,
@@ -39941,11 +40336,11 @@ function createOpenCodeVaultCustody(options) {
39941
40336
  ].join("\n");
39942
40337
  const waitForApproval = async () => {
39943
40338
  while (!closed) {
39944
- await new Promise((resolve18) => {
40339
+ await new Promise((resolve20) => {
39945
40340
  const done = () => {
39946
40341
  clearTimeout(timer);
39947
40342
  cancelWait = void 0;
39948
- resolve18();
40343
+ resolve20();
39949
40344
  };
39950
40345
  const timer = setTimeout(done, 2e3);
39951
40346
  timer.unref?.();
@@ -40574,7 +40969,7 @@ function createGaReauthorize(input2) {
40574
40969
  const continuations = /* @__PURE__ */ new Set();
40575
40970
  const shutdown = new AbortController();
40576
40971
  let disposed = false;
40577
- const waitForRedirect = (code2) => new Promise((resolve18, reject) => {
40972
+ const waitForRedirect = (code2) => new Promise((resolve20, reject) => {
40578
40973
  const detach = () => shutdown.signal.removeEventListener("abort", abort);
40579
40974
  const abort = () => {
40580
40975
  detach();
@@ -40585,7 +40980,7 @@ function createGaReauthorize(input2) {
40585
40980
  void code2.then(
40586
40981
  (value) => {
40587
40982
  detach();
40588
- resolve18(value);
40983
+ resolve20(value);
40589
40984
  },
40590
40985
  (error) => {
40591
40986
  detach();
@@ -40993,8 +41388,8 @@ function gaEngineCollaborators(input2) {
40993
41388
  async function createGaLocalRequestPipeline(input2) {
40994
41389
  const runtime = input2.runtime;
40995
41390
  await input2.assertAdmission?.();
40996
- const logger2 = runtime.logger.createLogger("request");
40997
- const advisory = createAdvisoryRepositoryOwner(input2.repository, logger2);
41391
+ const logger3 = runtime.logger.createLogger("request");
41392
+ const advisory = createAdvisoryRepositoryOwner(input2.repository, logger3);
40998
41393
  const manager = await loadAccountManagerFromRepository(advisory.repository, {
40999
41394
  onWriteError: advisory.owns
41000
41395
  });
@@ -41006,7 +41401,7 @@ async function createGaLocalRequestPipeline(input2) {
41006
41401
  runtime,
41007
41402
  overrides: input2.overrides,
41008
41403
  routes: input2.routes,
41009
- logger: logger2
41404
+ logger: logger3
41010
41405
  }),
41011
41406
  accounts: manager,
41012
41407
  ...input2.assertAdmission ? { assertAdmission: input2.assertAdmission } : {},
@@ -41016,7 +41411,7 @@ async function createGaLocalRequestPipeline(input2) {
41016
41411
  refreshQuotaAfterSuccess: createLocalQuotaRefresh(
41017
41412
  manager,
41018
41413
  runtime.quotaManager,
41019
- logger2
41414
+ logger3
41020
41415
  )
41021
41416
  }),
41022
41417
  // The trackers the manager selects with, so recorded outcomes steer
@@ -41060,13 +41455,13 @@ async function createGaVaultRequestPipeline(input2) {
41060
41455
  const { pool } = input2;
41061
41456
  await input2.assertAdmission?.();
41062
41457
  await pool.sync();
41063
- const logger2 = input2.runtime.logger.createLogger("request");
41458
+ const logger3 = input2.runtime.logger.createLogger("request");
41064
41459
  const executor = createRequestExecutor({
41065
41460
  ...gaEngineCollaborators({
41066
41461
  runtime: input2.runtime,
41067
41462
  overrides: input2.overrides,
41068
41463
  routes: input2.routes,
41069
- logger: logger2
41464
+ logger: logger3
41070
41465
  }),
41071
41466
  accounts: pool.selector,
41072
41467
  ...input2.assertAdmission ? { assertAdmission: input2.assertAdmission } : {},
@@ -43165,11 +43560,11 @@ var OPENCODE2_VAULT_AUTH_LABEL = "Use approved Antigravity vault";
43165
43560
  var GA_POOL_METHOD_ID = "antigravity-auth-pool-browser";
43166
43561
  var LOGIN_FAILED = "The Antigravity pool login could not be completed.";
43167
43562
  function abortable(pending, signal) {
43168
- return new Promise((resolve18, reject) => {
43563
+ return new Promise((resolve20, reject) => {
43169
43564
  const abort = () => reject(signal.reason);
43170
43565
  if (signal.aborted) abort();
43171
43566
  else signal.addEventListener("abort", abort, { once: true });
43172
- void pending.then(resolve18, reject).finally(() => {
43567
+ void pending.then(resolve20, reject).finally(() => {
43173
43568
  signal.removeEventListener("abort", abort);
43174
43569
  });
43175
43570
  });
@@ -43537,11 +43932,11 @@ async function startGaLoopbackBridge(options) {
43537
43932
  }
43538
43933
  }
43539
43934
  };
43540
- await new Promise((resolve18, reject) => {
43935
+ await new Promise((resolve20, reject) => {
43541
43936
  server.once("error", reject);
43542
43937
  server.listen(0, BRIDGE_HOST, () => {
43543
43938
  server.off("error", reject);
43544
- resolve18();
43939
+ resolve20();
43545
43940
  });
43546
43941
  });
43547
43942
  server.unref();
@@ -43645,8 +44040,8 @@ async function startGaLoopbackBridge(options) {
43645
44040
  disposal = (async () => {
43646
44041
  for (const { timer } of queued.values()) clearTimeout(timer);
43647
44042
  queued.clear();
43648
- const closed = new Promise((resolve18) => {
43649
- server.close(() => resolve18());
44043
+ const closed = new Promise((resolve20) => {
44044
+ server.close(() => resolve20());
43650
44045
  });
43651
44046
  for (const controller of running) {
43652
44047
  controller.abort(
@@ -43710,9 +44105,9 @@ async function pipeResponse(upstream, response, onFailure, onHandoff) {
43710
44105
  return;
43711
44106
  }
43712
44107
  if (!response.write(value) && !response.destroyed) {
43713
- await new Promise((resolve18) => {
43714
- response.once("drain", resolve18);
43715
- response.once("close", resolve18);
44108
+ await new Promise((resolve20) => {
44109
+ response.once("drain", resolve20);
44110
+ response.once("close", resolve20);
43716
44111
  });
43717
44112
  }
43718
44113
  if (response.destroyed) {
@@ -43899,9 +44294,9 @@ function createGaRpcActivation(options) {
43899
44294
  const { email: _email, quota, ...rest } = account;
43900
44295
  const entry = (value) => {
43901
44296
  if (value === void 0) return void 0;
43902
- const { remainingFraction: _fraction, windows: windows2, ...fields } = value;
43903
- return windows2 === void 0 ? fields : {
43904
- ...fields,
44297
+ const { remainingFraction: _fraction, windows: windows2, ...fields2 } = value;
44298
+ return windows2 === void 0 ? fields2 : {
44299
+ ...fields2,
43905
44300
  windows: windows2.map(
43906
44301
  ({ remainingFraction: _windowFraction, ...window }) => window
43907
44302
  )
@@ -44367,12 +44762,12 @@ function createGaAntigravityPlugin(overrides = {}) {
44367
44762
 
44368
44763
  // src/plugin/index.ts
44369
44764
  import { createHash as createHash20, randomUUID as randomUUID21 } from "node:crypto";
44370
- import { join as join31, resolve as resolve17 } from "node:path";
44765
+ import { join as join31, resolve as resolve19 } from "node:path";
44371
44766
 
44372
44767
  // src/cli.ts
44373
44768
  import { execFile } from "node:child_process";
44374
44769
  import { realpathSync as realpathSync3 } from "node:fs";
44375
- import { resolve as resolve14 } from "node:path";
44770
+ import { resolve as resolve16 } from "node:path";
44376
44771
  import { createInterface } from "node:readline/promises";
44377
44772
  import { fileURLToPath as fileURLToPath2 } from "node:url";
44378
44773
  import { promisify } from "node:util";
@@ -44416,7 +44811,7 @@ async function performOAuthLogin(request, deps) {
44416
44811
 
44417
44812
  // src/setup.ts
44418
44813
  import { lstat as lstat5, readFile as readFile13 } from "node:fs/promises";
44419
- import { join as join22, resolve as resolve13 } from "node:path";
44814
+ import { join as join22, resolve as resolve15 } from "node:path";
44420
44815
 
44421
44816
  // src/common-auth-embedded/auth-menu/ansi.js
44422
44817
  var ANSI2 = {
@@ -44584,7 +44979,7 @@ async function select2(terminal, items, options) {
44584
44979
  writeLine("");
44585
44980
  renderedLines = lines;
44586
44981
  };
44587
- return new Promise((resolve18) => {
44982
+ return new Promise((resolve20) => {
44588
44983
  const wasRaw = stdin.isRaw ?? false;
44589
44984
  const cleanup2 = () => {
44590
44985
  if (cleaned)
@@ -44604,7 +44999,7 @@ async function select2(terminal, items, options) {
44604
44999
  };
44605
45000
  const finish = (value) => {
44606
45001
  cleanup2();
44607
- resolve18(value);
45002
+ resolve20(value);
44608
45003
  };
44609
45004
  const onSignal = () => finish(null);
44610
45005
  const onKey = (data) => {
@@ -44644,7 +45039,7 @@ async function select2(terminal, items, options) {
44644
45039
  stdin.setRawMode(true);
44645
45040
  } catch {
44646
45041
  cleanup2();
44647
- resolve18(null);
45042
+ resolve20(null);
44648
45043
  return;
44649
45044
  }
44650
45045
  stdin.resume();
@@ -44658,7 +45053,7 @@ async function select2(terminal, items, options) {
44658
45053
  import { createHash as createHash15, randomBytes as randomBytes6, randomUUID as randomUUID17 } from "node:crypto";
44659
45054
  import { constants as fsConstants2 } from "node:fs";
44660
45055
  import { chmod as chmod4, mkdir as mkdir13, open as open10, readFile as readFile11, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
44661
- import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute3, join as join18, resolve as resolve12 } from "node:path";
45056
+ import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute3, join as join18, resolve as resolve14 } from "node:path";
44662
45057
  import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
44663
45058
 
44664
45059
  // src/common-auth-embedded/fs/lock-constants.js
@@ -44723,8 +45118,8 @@ async function acquireRefreshFileLockWithClock2(options) {
44723
45118
  let releaseConfirmed = false;
44724
45119
  let loss;
44725
45120
  let resolveLoss;
44726
- const lostPromise = new Promise((resolve18) => {
44727
- resolveLoss = resolve18;
45121
+ const lostPromise = new Promise((resolve20) => {
45122
+ resolveLoss = resolve20;
44728
45123
  });
44729
45124
  function notifyTimerStep(event) {
44730
45125
  try {
@@ -44881,7 +45276,7 @@ async function acquireRefreshFileLockWithClock2(options) {
44881
45276
  }
44882
45277
  }
44883
45278
  async function backoff() {
44884
- await new Promise((resolve18) => setTimeout(resolve18, Math.floor(Math.random() * 4)));
45279
+ await new Promise((resolve20) => setTimeout(resolve20, Math.floor(Math.random() * 4)));
44885
45280
  }
44886
45281
  async function readLockState(notifyReady = true) {
44887
45282
  if (notifyReady && options.onStep)
@@ -45367,7 +45762,7 @@ function hostEnrollmentPaths2(input2) {
45367
45762
  const override = input2.override?.trim();
45368
45763
  if (override && !isAbsolute3(override) && !input2.cwd)
45369
45764
  throw new ClaustrumConsumerError2("invalid-state", "A relative Claustrum enrollment override needs a base directory");
45370
- const tokenPath = override ? isAbsolute3(override) ? override : resolve12(input2.cwd, override) : join18(input2.stateDir, `${input2.host}-enrollment.json`);
45765
+ const tokenPath = override ? isAbsolute3(override) ? override : resolve14(input2.cwd, override) : join18(input2.stateDir, `${input2.host}-enrollment.json`);
45371
45766
  return getClaustrumEnrollmentPaths2(tokenPath);
45372
45767
  }
45373
45768
  function isRecord10(value) {
@@ -45496,13 +45891,13 @@ async function readBoundedJson2(path5) {
45496
45891
  await descriptor.close();
45497
45892
  }
45498
45893
  }
45499
- function accountRecords2(text2, fields) {
45894
+ function accountRecords2(text2, fields2) {
45500
45895
  const records = [];
45501
45896
  for (const line of text2.split("\n")) {
45502
45897
  if (line.trim() === "" || line.startsWith("#"))
45503
45898
  continue;
45504
45899
  const parts = line.split(":");
45505
- if (parts.length !== fields || !/^[^\s:,]+$/.test(parts[0] ?? "") || !/^\d+$/.test(parts[2] ?? "") || !Number.isSafeInteger(Number(parts[2])) || fields === 7 && (!/^\d+$/.test(parts[3] ?? "") || !Number.isSafeInteger(Number(parts[3]))) || fields === 4 && parts[3] !== "" && !/^[^\s:,]+(?:,[^\s:,]+)*$/.test(parts[3] ?? ""))
45900
+ if (parts.length !== fields2 || !/^[^\s:,]+$/.test(parts[0] ?? "") || !/^\d+$/.test(parts[2] ?? "") || !Number.isSafeInteger(Number(parts[2])) || fields2 === 7 && (!/^\d+$/.test(parts[3] ?? "") || !Number.isSafeInteger(Number(parts[3]))) || fields2 === 4 && parts[3] !== "" && !/^[^\s:,]+(?:,[^\s:,]+)*$/.test(parts[3] ?? ""))
45506
45901
  return void 0;
45507
45902
  records.push(parts);
45508
45903
  }
@@ -45962,7 +46357,7 @@ var ByteTail = class {
45962
46357
  };
45963
46358
  var defaultCommandRunner = {
45964
46359
  run(file, args, options = {}) {
45965
- return new Promise((resolve18) => {
46360
+ return new Promise((resolve20) => {
45966
46361
  const started = performance.now();
45967
46362
  const timeoutMs = options.timeoutMs ?? 15e3;
45968
46363
  const stderr = new ByteTail();
@@ -45980,7 +46375,7 @@ var defaultCommandRunner = {
45980
46375
  stdio: ["ignore", "pipe", "pipe"]
45981
46376
  });
45982
46377
  } catch {
45983
- resolve18({
46378
+ resolve20({
45984
46379
  exitCode: 1,
45985
46380
  stdout: "",
45986
46381
  stderr: "",
@@ -46015,7 +46410,7 @@ var defaultCommandRunner = {
46015
46410
  settled = true;
46016
46411
  if (timer)
46017
46412
  clearTimeout(timer);
46018
- resolve18({
46413
+ resolve20({
46019
46414
  exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
46020
46415
  stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
46021
46416
  stderr: stderr.toString(),
@@ -46444,6 +46839,7 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);
46444
46839
  };
46445
46840
  async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
46446
46841
  const windows2 = (options.platform ?? process.platform) === "win32";
46842
+ const selfPid = options.selfPid ?? process.pid;
46447
46843
  let inspection = {
46448
46844
  step: windows2 ? "tasklist" : "ps",
46449
46845
  exitCode: null,
@@ -46512,7 +46908,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
46512
46908
  }
46513
46909
  if (!processes.length)
46514
46910
  throw new ProcessInspectionError(inspection);
46515
- const runtimes = processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command));
46911
+ const runtimes = processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command));
46516
46912
  if (windows2 && runtimes.length && options.inspectRuntimes !== false) {
46517
46913
  const details = await inspect("CIM", "powershell.exe", [
46518
46914
  "-NoProfile",
@@ -46545,7 +46941,8 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
46545
46941
  }
46546
46942
  }
46547
46943
  function createProcessFence(runner = defaultCommandRunner, options = {}) {
46548
- const isHost = (entry) => entry.pid !== process.pid && hostName(entry.command) !== null;
46944
+ const selfPid = options.selfPid ?? process.pid;
46945
+ const isHost = (entry) => entry.pid !== selfPid && hostName(entry.command) !== null;
46549
46946
  return {
46550
46947
  async listRunningHosts(env3) {
46551
46948
  return (await listSetupProcesses(runner, { ...options, env: env3 })).filter(isHost);
@@ -46559,7 +46956,7 @@ function createProcessFence(runner = defaultCommandRunner, options = {}) {
46559
46956
  const windows2 = (options.platform ?? process.platform) === "win32";
46560
46957
  return {
46561
46958
  hosts: processes.filter(isHost),
46562
- uncheckedRuntimes: windows2 ? processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
46959
+ uncheckedRuntimes: windows2 ? processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
46563
46960
  };
46564
46961
  }
46565
46962
  };
@@ -47157,7 +47554,7 @@ async function writeNativeSlot(host, slot, context, expectedAuthority = "local")
47157
47554
  beforeRename: async () => {
47158
47555
  await assertSetupHostsStopped();
47159
47556
  const claustrum = await loadCommonAuthClaustrum();
47160
- const stateDir = host === "opencode" ? openCodeVaultPaths(resolve13(getStoragePath())).dir : getPiAntigravityVaultDir();
47557
+ const stateDir = host === "opencode" ? openCodeVaultPaths(resolve15(getStoragePath())).dir : getPiAntigravityVaultDir();
47161
47558
  if (await claustrum.enrollmentAuthority(
47162
47559
  claustrum.hostEnrollmentPaths({ stateDir, host }),
47163
47560
  `antigravity-auth-${host}`
@@ -47187,7 +47584,7 @@ async function persistPiSetupLogin(result, context) {
47187
47584
  }
47188
47585
  async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
47189
47586
  const claustrum = await loadCommonAuthClaustrum();
47190
- const opencode = openCodeVaultPaths(resolve13(getStoragePath()));
47587
+ const opencode = openCodeVaultPaths(resolve15(getStoragePath()));
47191
47588
  const piDir = getPiAntigravityVaultDir();
47192
47589
  const hosts = {
47193
47590
  opencode: {
@@ -47206,7 +47603,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
47206
47603
  const assertLocal = async (host, context) => {
47207
47604
  if (host === "opencode")
47208
47605
  return assertLocalOpenCodeLogin(
47209
- resolve13(getStoragePath()),
47606
+ resolve15(getStoragePath()),
47210
47607
  context.opencodeGeneration
47211
47608
  );
47212
47609
  if (await authority(host) !== "local")
@@ -47738,7 +48135,7 @@ function createDefaultCliDependencies() {
47738
48135
  throw new Error(
47739
48136
  "Pi setup requires its detected native agent directory."
47740
48137
  );
47741
- const legacyPath = resolve14(getStoragePath());
48138
+ const legacyPath = resolve16(getStoragePath());
47742
48139
  const repository = host === "pi" ? void 0 : await prepareCliLoginStore(legacyPath, context?.opencodeGeneration);
47743
48140
  try {
47744
48141
  return await performOAuthLogin(request, {
@@ -47898,7 +48295,7 @@ async function readAccountStore(legacyPath) {
47898
48295
  function createDefaultAccountStoreOperations() {
47899
48296
  const offline = { processesStopped: true };
47900
48297
  return {
47901
- legacyPath: () => resolve14(getStoragePath()),
48298
+ legacyPath: () => resolve16(getStoragePath()),
47902
48299
  migrate: async (legacyPath) => createAccountMigrationFactory(await loadCommonAuthStoreModules())({
47903
48300
  legacyPath,
47904
48301
  offline,
@@ -48399,14 +48796,14 @@ function isTuiConnected(sessionId) {
48399
48796
  // src/rpc/rpc-dir.ts
48400
48797
  import { createHash as createHash16 } from "node:crypto";
48401
48798
  import { homedir as homedir12, tmpdir as tmpdir4 } from "node:os";
48402
- import { isAbsolute as isAbsolute4, join as join26, resolve as resolve15 } from "node:path";
48799
+ import { isAbsolute as isAbsolute4, join as join26, resolve as resolve17 } from "node:path";
48403
48800
  var RPC_DIR_ENV = "ANTIGRAVITY_AUTH_RPC_DIR";
48404
48801
  function getRpcDir(projectDirectory) {
48405
48802
  const override = process.env[RPC_DIR_ENV]?.trim();
48406
48803
  if (override) {
48407
- return isAbsolute4(override) ? override : resolve15(projectDirectory, override);
48804
+ return isAbsolute4(override) ? override : resolve17(projectDirectory, override);
48408
48805
  }
48409
- const projectHash = createHash16("sha256").update(resolve15(projectDirectory)).digest("hex").slice(0, 16);
48806
+ const projectHash = createHash16("sha256").update(resolve17(projectDirectory)).digest("hex").slice(0, 16);
48410
48807
  const stateHome = process.env.XDG_STATE_HOME ?? join26(homedir12(), ".local", "state");
48411
48808
  return join26(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
48412
48809
  }
@@ -48419,7 +48816,7 @@ function isSessionId(value) {
48419
48816
  // src/common-auth-embedded/rpc/port-file.js
48420
48817
  import { createHash as createHash17, randomUUID as randomUUID19 } from "node:crypto";
48421
48818
  import { chmod as chmod5, mkdir as mkdir15, open as open12, readdir, rename as rename11, rmdir as rmdir2, stat as stat10, unlink as unlink11 } from "node:fs/promises";
48422
- import { join as join27, resolve as resolve16 } from "node:path";
48819
+ import { join as join27, resolve as resolve18 } from "node:path";
48423
48820
  function isProbeablePid(pid) {
48424
48821
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
48425
48822
  }
@@ -48506,7 +48903,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
48506
48903
  return;
48507
48904
  throw error;
48508
48905
  }
48509
- const active2 = resolve16(activeDir);
48906
+ const active2 = resolve18(activeDir);
48510
48907
  for (const projectDir of projectDirs) {
48511
48908
  if (!projectDir.isDirectory() || !isManagedDir(projectDir.name)) {
48512
48909
  continue;
@@ -48550,7 +48947,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
48550
48947
  await unlink11(portFile).catch(() => {
48551
48948
  });
48552
48949
  }
48553
- if (resolve16(dir) !== active2)
48950
+ if (resolve18(dir) !== active2)
48554
48951
  await rmdir2(dir).catch(() => {
48555
48952
  });
48556
48953
  }
@@ -48580,7 +48977,7 @@ var BodyTooLargeError = class extends Error {
48580
48977
  }
48581
48978
  };
48582
48979
  function readBody(req) {
48583
- return new Promise((resolve18, reject) => {
48980
+ return new Promise((resolve20, reject) => {
48584
48981
  const tooLarge = (declaredOversize = false) => {
48585
48982
  req.removeAllListeners("data");
48586
48983
  req.on("data", () => {
@@ -48603,7 +49000,7 @@ function readBody(req) {
48603
49000
  }
48604
49001
  chunks.push(chunk);
48605
49002
  });
48606
- req.on("end", () => resolve18(Buffer.concat(chunks).toString("utf8")));
49003
+ req.on("end", () => resolve20(Buffer.concat(chunks).toString("utf8")));
48607
49004
  req.on("error", reject);
48608
49005
  });
48609
49006
  }
@@ -48771,12 +49168,12 @@ async function startRpcServer(options) {
48771
49168
  json(500, { error: "internal error" });
48772
49169
  }
48773
49170
  }
48774
- const port = await new Promise((resolve18, reject) => {
49171
+ const port = await new Promise((resolve20, reject) => {
48775
49172
  server.on("error", reject);
48776
49173
  server.listen(0, "127.0.0.1", () => {
48777
49174
  const addr = server.address();
48778
49175
  if (addr && typeof addr === "object")
48779
- resolve18(addr.port);
49176
+ resolve20(addr.port);
48780
49177
  else
48781
49178
  reject(new Error("no port"));
48782
49179
  });
@@ -48799,16 +49196,16 @@ async function startRpcServer(options) {
48799
49196
  rpcPort: port
48800
49197
  });
48801
49198
  } catch (error) {
48802
- await new Promise((resolve18) => server.close(() => resolve18()));
49199
+ await new Promise((resolve20) => server.close(() => resolve20()));
48803
49200
  throw error;
48804
49201
  }
48805
49202
  return {
48806
49203
  port,
48807
49204
  token,
48808
49205
  async stop() {
48809
- await new Promise((resolve18) => {
49206
+ await new Promise((resolve20) => {
48810
49207
  server.closeAllConnections?.();
48811
- server.close(() => resolve18());
49208
+ server.close(() => resolve20());
48812
49209
  for (const socket of connections)
48813
49210
  socket.destroy();
48814
49211
  });
@@ -49392,7 +49789,7 @@ async function select3(items, options) {
49392
49789
  }
49393
49790
  renderedLines = linesWritten;
49394
49791
  };
49395
- return new Promise((resolve18) => {
49792
+ return new Promise((resolve20) => {
49396
49793
  const wasRaw = stdin.isRaw ?? false;
49397
49794
  const cleanup2 = () => {
49398
49795
  if (isCleanedUp) return;
@@ -49413,11 +49810,11 @@ async function select3(items, options) {
49413
49810
  };
49414
49811
  const onSignal = () => {
49415
49812
  cleanup2();
49416
- resolve18(null);
49813
+ resolve20(null);
49417
49814
  };
49418
49815
  const finishWithValue = (value) => {
49419
49816
  cleanup2();
49420
- resolve18(value);
49817
+ resolve20(value);
49421
49818
  };
49422
49819
  const findNextSelectable = (from, direction) => {
49423
49820
  if (items.length === 0) return from;
@@ -49463,7 +49860,7 @@ async function select3(items, options) {
49463
49860
  stdin.setRawMode(true);
49464
49861
  } catch {
49465
49862
  cleanup2();
49466
- resolve18(null);
49863
+ resolve20(null);
49467
49864
  return;
49468
49865
  }
49469
49866
  stdin.resume();
@@ -52758,10 +53155,10 @@ function resolvePluginDependencies(overrides = {}) {
52758
53155
  }
52759
53156
  async function defaultSleep(ms, signal) {
52760
53157
  if (ms <= 0) return;
52761
- await new Promise((resolve18, reject) => {
53158
+ await new Promise((resolve20, reject) => {
52762
53159
  const timer = setTimeout(() => {
52763
53160
  signal?.removeEventListener("abort", onAbort);
52764
- resolve18();
53161
+ resolve20();
52765
53162
  }, ms);
52766
53163
  timer.unref?.();
52767
53164
  const onAbort = () => {
@@ -52783,7 +53180,7 @@ function createEventHandler({
52783
53180
  sessionRegistry,
52784
53181
  sessionRecovery,
52785
53182
  updateChecker,
52786
- logger: logger2
53183
+ logger: logger3
52787
53184
  }) {
52788
53185
  return async (input2) => {
52789
53186
  await updateChecker.event(input2);
@@ -52795,14 +53192,14 @@ function createEventHandler({
52795
53192
  sessionRegistry.register(sessionId, parentSessionId);
52796
53193
  }
52797
53194
  if (parentSessionId) {
52798
- logger2.debug("child-session-detected", {
53195
+ logger3.debug("child-session-detected", {
52799
53196
  sessionId,
52800
53197
  parentID: parentSessionId
52801
53198
  });
52802
53199
  } else {
52803
53200
  const previousSummary = lifecycle.getAccountManager()?.getSessionSummary();
52804
53201
  if (previousSummary && (previousSummary.totalClaude > 0 || previousSummary.totalGemini > 0)) {
52805
- logger2.debug("prev-session-quota-summary", {
53202
+ logger3.debug("prev-session-quota-summary", {
52806
53203
  durationMinutes: previousSummary.durationMinutes,
52807
53204
  totalClaude: previousSummary.totalClaude,
52808
53205
  totalGemini: previousSummary.totalGemini,
@@ -52810,7 +53207,7 @@ function createEventHandler({
52810
53207
  accountsUsed: previousSummary.accountsUsed
52811
53208
  });
52812
53209
  }
52813
- logger2.debug("root-session-detected", { sessionId });
53210
+ logger3.debug("root-session-detected", { sessionId });
52814
53211
  }
52815
53212
  }
52816
53213
  if (input2.event.type === "session.deleted") {
@@ -52819,7 +53216,7 @@ function createEventHandler({
52819
53216
  if (sessionId) {
52820
53217
  sessionRegistry.delete(sessionId);
52821
53218
  lifecycle.getAccountManager()?.deleteSessionState(sessionId);
52822
- const eventLogger = logger2;
53219
+ const eventLogger = logger3;
52823
53220
  void removeSidebarActiveRouting(sessionId).catch((error2) => {
52824
53221
  eventLogger.debug("sidebar-route-remove-failed", {
52825
53222
  sessionId,
@@ -52855,7 +53252,7 @@ function createEventHandler({
52855
53252
  });
52856
53253
  const successToast = getRecoverySuccessToast();
52857
53254
  const isChildSession = sessionRegistry.getParentSessionId(sessionID) !== null;
52858
- logger2.debug("recovery-toast", {
53255
+ logger3.debug("recovery-toast", {
52859
53256
  ...successToast,
52860
53257
  isChildSession,
52861
53258
  toastScope: config.toast_scope
@@ -53459,8 +53856,8 @@ function createPluginLifecycle(options) {
53459
53856
  };
53460
53857
  let failDisposal = () => {
53461
53858
  };
53462
- disposal = new Promise((resolve18, reject) => {
53463
- finishDisposal = resolve18;
53859
+ disposal = new Promise((resolve20, reject) => {
53860
+ finishDisposal = resolve20;
53464
53861
  failDisposal = reject;
53465
53862
  });
53466
53863
  void (async () => {
@@ -53524,7 +53921,7 @@ function createSourceSidebarPublisher(options) {
53524
53921
  }
53525
53922
 
53526
53923
  // src/plugin/index.ts
53527
- var logger = createLogger4("plugin");
53924
+ var logger2 = createLogger4("plugin");
53528
53925
  function quotaAccountIdentity4(refreshToken) {
53529
53926
  return createHash20("sha256").update(refreshToken).digest("hex").slice(0, 16);
53530
53927
  }
@@ -53593,7 +53990,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53593
53990
  });
53594
53991
  let vaultQuotaPoller;
53595
53992
  const vaultCustody = createOpenCodeVaultCustody({
53596
- accountFile: resolve17(getStoragePath()),
53993
+ accountFile: resolve19(getStoragePath()),
53597
53994
  insulaQuota: true,
53598
53995
  readHostSlot: async () => {
53599
53996
  if (!cachedGetAuth)
@@ -53717,7 +54114,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53717
54114
  });
53718
54115
  function scheduleSidebarPublication() {
53719
54116
  void sidebarPublisher.publish().catch(
53720
- (error) => logger.debug("sidebar-source-publish-failed", {
54117
+ (error) => logger2.debug("sidebar-source-publish-failed", {
53721
54118
  error: error instanceof Error ? error.name : "unknown"
53722
54119
  })
53723
54120
  );
@@ -53747,7 +54144,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53747
54144
  }
53748
54145
  );
53749
54146
  })().catch(
53750
- (error) => logger.debug("sidebar-routing-publish-failed", {
54147
+ (error) => logger2.debug("sidebar-routing-publish-failed", {
53751
54148
  error: error instanceof Error ? error.name : "unknown"
53752
54149
  })
53753
54150
  );
@@ -53792,8 +54189,8 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53792
54189
  readProviderState: () => vaultCustody.readState(),
53793
54190
  publishSidebar: () => sidebarPublisher.publish(),
53794
54191
  transport: vaultQuotaTransport,
53795
- logger,
53796
- onOutcome: (level, outcome) => (level === "warn" ? quotaOutcomeLogger : logger)[level](
54192
+ logger: logger2,
54193
+ onOutcome: (level, outcome) => (level === "warn" ? quotaOutcomeLogger : logger2)[level](
53797
54194
  "vault-quota-tick",
53798
54195
  { ...outcome }
53799
54196
  ),
@@ -53829,7 +54226,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53829
54226
  sessionRegistry,
53830
54227
  sessionRecovery,
53831
54228
  updateChecker,
53832
- logger
54229
+ logger: logger2
53833
54230
  });
53834
54231
  let storeQuota = null;
53835
54232
  const currentStoreQuota = async (knownRepository) => {
@@ -53935,7 +54332,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
53935
54332
  source,
53936
54333
  ref,
53937
54334
  signal: check,
53938
- logger,
54335
+ logger: logger2,
53939
54336
  transport: vaultQuotaTransport
53940
54337
  })
53941
54338
  },
@@ -54195,7 +54592,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
54195
54592
  if (await readAuthority2() === "local")
54196
54593
  await lifecycle.getAccountManager()?.refreshFromRepository();
54197
54594
  } catch (error) {
54198
- logger.warn("menu-routing-refresh-failed", { error: String(error) });
54595
+ logger2.warn("menu-routing-refresh-failed", { error: String(error) });
54199
54596
  pushNotification(
54200
54597
  {
54201
54598
  command: ANTIGRAVITY_MENU_COMMAND,