@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/cli.js CHANGED
@@ -65,6 +65,12 @@ function isQuotaCounter(value) {
65
65
  function isQuotaCounters(value) {
66
66
  return isRecord2(value) && Object.values(value).every(isQuotaCounter);
67
67
  }
68
+ function isBoolean(value) {
69
+ return typeof value === "boolean";
70
+ }
71
+ function isQuotaCredits(value) {
72
+ return isRecord2(value) && typeof value.hasCredits === "boolean" && typeof value.unlimited === "boolean" && optional2(value, "balance", isFiniteNumber) && optional2(value, "overageLimitReached", isBoolean) && isFiniteNumber(value.checkedAt);
73
+ }
68
74
  function readQuotaCounters(value) {
69
75
  if (!isRecord2(value))
70
76
  return void 0;
@@ -76,11 +82,16 @@ function decodeQuotaMap(value) {
76
82
  return value;
77
83
  if (!isRecord2(value))
78
84
  return void 0;
79
- const { counters: rawCounters, ...rest } = value;
85
+ const { counters: rawCounters, credits: rawCredits, ...rest } = value;
80
86
  if (!isQuotaMap(rest))
81
87
  return void 0;
82
88
  const counters = readQuotaCounters(rawCounters);
83
- return { ...rest, ...counters === void 0 ? {} : { counters } };
89
+ const credits = isQuotaCredits(rawCredits) ? rawCredits : void 0;
90
+ return {
91
+ ...rest,
92
+ ...counters === void 0 ? {} : { counters },
93
+ ...credits === void 0 ? {} : { credits }
94
+ };
84
95
  }
85
96
  function isQuotaMap(value) {
86
97
  if (!isRecord2(value) || !Array.isArray(value.limits))
@@ -94,7 +105,7 @@ function isQuotaMap(value) {
94
105
  return false;
95
106
  seen.add(key);
96
107
  }
97
- return optional2(value, "budget", isCreditBudgetEntry) && optional2(value, "counters", isQuotaCounters);
108
+ return optional2(value, "budget", isCreditBudgetEntry) && optional2(value, "counters", isQuotaCounters) && optional2(value, "credits", isQuotaCredits);
98
109
  }
99
110
  var ALL_SCOPE, DEFAULT_REQUIRED_LABELS;
100
111
  var init_map = __esm({
@@ -157,7 +168,7 @@ function isQuotaObservation(value) {
157
168
  }
158
169
  if (!coverage.every(isObservedPair))
159
170
  return false;
160
- return (value.budget === void 0 || isObservedBudget(value.budget)) && (value.counters === void 0 || isQuotaCounters(value.counters));
171
+ return (value.budget === void 0 || isObservedBudget(value.budget)) && (value.counters === void 0 || isQuotaCounters(value.counters)) && (value.credits === void 0 || isQuotaCredits(value.credits));
161
172
  }
162
173
  function compareEntries(left, right) {
163
174
  if (left.scope !== right.scope)
@@ -183,6 +194,14 @@ function mergeCounters(stored, observed) {
183
194
  }
184
195
  return counters.size === 0 ? void 0 : Object.fromEntries(counters);
185
196
  }
197
+ function mergeCredits(stored, observed) {
198
+ if (observed === void 0)
199
+ return stored;
200
+ if (stored !== void 0 && observed.checkedAt < stored.checkedAt) {
201
+ return stored;
202
+ }
203
+ return { ...observed };
204
+ }
186
205
  function mergeQuotaObservation(stored, observation) {
187
206
  const decoded = stored === void 0 ? void 0 : decodeQuotaMap(stored);
188
207
  if (stored !== void 0 && decoded === void 0) {
@@ -226,14 +245,16 @@ function mergeQuotaObservation(stored, observation) {
226
245
  const existing = entries.get(key);
227
246
  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 });
228
247
  }
229
- const { limits: _limits, budget: _budget, counters: _counters, ...unknownKeys } = base;
248
+ const { limits: _limits, budget: _budget, counters: _counters, credits: _credits, ...unknownKeys } = base;
230
249
  const budget = mergeBudget(base.budget, observation.budget, at);
231
250
  const counters = mergeCounters(base.counters, observation.counters);
251
+ const credits = mergeCredits(base.credits, observation.credits);
232
252
  return {
233
253
  ...unknownKeys,
234
254
  limits: [...entries.values()].sort(compareEntries),
235
255
  ...budget === void 0 ? {} : { budget },
236
- ...counters === void 0 ? {} : { counters }
256
+ ...counters === void 0 ? {} : { counters },
257
+ ...credits === void 0 ? {} : { credits }
237
258
  };
238
259
  }
239
260
  var QuotaCodecError;
@@ -328,6 +349,13 @@ function quotaWindowParts(quota, options) {
328
349
  const parts = windows.map(({ part }) => part);
329
350
  return age === void 0 ? { windows: parts } : { windows: parts, age };
330
351
  }
352
+ function withShortNames(windows) {
353
+ const abbreviations = scopeAbbreviations(windows.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE).map(({ scope }) => scope));
354
+ for (const window of windows) {
355
+ window.part.short = window.part.kind === "budget" ? "cr" : window.scope === ALL_SCOPE ? window.part.name : abbreviations.get(window.scope) ?? window.scope;
356
+ }
357
+ return windows;
358
+ }
331
359
  function scopedWindowParts(quota, options) {
332
360
  if (!quota)
333
361
  return { windows: [] };
@@ -341,6 +369,7 @@ function scopedWindowParts(quota, options) {
341
369
  part: {
342
370
  kind: "window",
343
371
  name: quotaWindowName(limit),
372
+ short: "",
344
373
  figure: percentLeft(limit.remainingPercent ?? 0),
345
374
  remainingPercent,
346
375
  checkedAt: limit.checkedAt,
@@ -358,6 +387,7 @@ function scopedWindowParts(quota, options) {
358
387
  part: {
359
388
  kind: "budget",
360
389
  name: "credits",
390
+ short: "",
361
391
  figure,
362
392
  ...remainingPercent === void 0 ? {} : { remainingPercent: clampPercent(remainingPercent) },
363
393
  checkedAt: budget.checkedAt,
@@ -365,6 +395,7 @@ function scopedWindowParts(quota, options) {
365
395
  }
366
396
  });
367
397
  }
398
+ withShortNames(windows);
368
399
  if (windows.length > 0) {
369
400
  const age = now - Math.min(...windows.map(({ part }) => part.checkedAt));
370
401
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
@@ -444,15 +475,14 @@ function narrowTextParts(quota, options) {
444
475
  return grouped;
445
476
  const general = windows.filter(({ part, scope }) => part.kind === "window" && scope === ALL_SCOPE);
446
477
  const scoped = windows.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE);
447
- const abbreviations = scopeAbbreviations(scoped.map(({ scope }) => scope));
448
478
  const budget = windows.find(({ part }) => part.kind === "budget");
449
479
  const budgetLeft = budget?.spent ? 0 : budget?.part.remainingPercent;
450
480
  const extras = [
451
- ...scoped.map(({ scope, part }) => ({
452
- label: abbreviations.get(scope) ?? scope,
481
+ ...scoped.map(({ part }) => ({
482
+ label: part.short,
453
483
  remaining: part.remainingPercent ?? 0
454
484
  })),
455
- ...budgetLeft === void 0 ? [] : [{ label: "cr", remaining: budgetLeft }]
485
+ ...budgetLeft === void 0 || budget === void 0 ? [] : [{ label: budget.part.short, remaining: budgetLeft }]
456
486
  ];
457
487
  const tightest = extras.reduce((best, item) => best === void 0 || item.remaining < best.remaining ? item : best, void 0);
458
488
  const pieces = general.map(({ part }) => `${part.name} ${wholePercent(part.remainingPercent ?? 0)}%`);
@@ -480,6 +510,16 @@ function formatQuota(quota, options) {
480
510
  return parts.join(" \xB7 ");
481
511
  return quota && quota.limits.length > 0 ? NO_LIMITS_REPORTED : NO_QUOTA_READING;
482
512
  }
513
+ function quotaCreditsText(credits) {
514
+ if (credits === void 0)
515
+ return void 0;
516
+ if (credits.unlimited)
517
+ return "Unlimited";
518
+ if (!credits.hasCredits)
519
+ return void 0;
520
+ const { balance } = credits;
521
+ return typeof balance === "number" && Number.isFinite(balance) && balance > 0 ? `${Math.round(balance)} credits` : "Available";
522
+ }
483
523
  var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED, NARROW_GROUP_LIMIT;
484
524
  var init_format = __esm({
485
525
  "../core/dist/common-auth-embedded/quota/format.js"() {
@@ -561,12 +601,14 @@ function projectQuota(map, scope = ALL_SCOPE) {
561
601
  const checkedAt = stamped.length > 0 ? Math.min(...stamped.map((limit) => limit.checkedAt)) : void 0;
562
602
  const budget = map?.budget?.kind === "reading" ? projectBudget(map.budget) : void 0;
563
603
  const counters = readQuotaCounters(map?.counters);
604
+ const credits = isQuotaCredits(map?.credits) ? map.credits : void 0;
564
605
  return {
565
606
  scope,
566
607
  limits,
567
608
  ...checkedAt === void 0 ? {} : { checkedAt },
568
609
  ...budget === void 0 ? {} : { budget },
569
- ...counters === void 0 ? {} : { counters }
610
+ ...counters === void 0 ? {} : { counters },
611
+ ...credits === void 0 ? {} : { credits }
570
612
  };
571
613
  }
572
614
  function budgetExhaustedResetAt(quota, now) {
@@ -609,12 +651,14 @@ __export(quota_exports, {
609
651
  emptyQuotaMap: () => emptyQuotaMap,
610
652
  formatQuota: () => formatQuota,
611
653
  futureResetAt: () => futureResetAt,
654
+ isQuotaCredits: () => isQuotaCredits,
612
655
  isQuotaMap: () => isQuotaMap,
613
656
  isQuotaObservation: () => isQuotaObservation,
614
657
  isQuotaStale: () => isQuotaStale,
615
658
  mergeQuotaObservation: () => mergeQuotaObservation,
616
659
  projectQuota: () => projectQuota,
617
660
  quotaCodec: () => quotaCodec2,
661
+ quotaCreditsText: () => quotaCreditsText,
618
662
  quotaTextParts: () => quotaTextParts,
619
663
  quotaWindowName: () => quotaWindowName,
620
664
  quotaWindowParts: () => quotaWindowParts,
@@ -1115,8 +1159,8 @@ async function acquireRefreshFileLockWithClock(options) {
1115
1159
  let releaseConfirmed = false;
1116
1160
  let loss;
1117
1161
  let resolveLoss;
1118
- const lostPromise = new Promise((resolve13) => {
1119
- resolveLoss = resolve13;
1162
+ const lostPromise = new Promise((resolve15) => {
1163
+ resolveLoss = resolve15;
1120
1164
  });
1121
1165
  function notifyTimerStep(event) {
1122
1166
  try {
@@ -1273,7 +1317,7 @@ async function acquireRefreshFileLockWithClock(options) {
1273
1317
  }
1274
1318
  }
1275
1319
  async function backoff() {
1276
- await new Promise((resolve13) => setTimeout(resolve13, Math.floor(Math.random() * 4)));
1320
+ await new Promise((resolve15) => setTimeout(resolve15, Math.floor(Math.random() * 4)));
1277
1321
  }
1278
1322
  async function readLockState(notifyReady = true) {
1279
1323
  if (notifyReady && options.onStep)
@@ -1723,6 +1767,7 @@ function lockPathFor(target, name) {
1723
1767
  async function withLock(target, options, fn) {
1724
1768
  const started = performance.now();
1725
1769
  for (; ; ) {
1770
+ options.signal?.throwIfAborted();
1726
1771
  const lock = await acquireRefreshFileLock({
1727
1772
  path: target,
1728
1773
  name: options.name,
@@ -1733,6 +1778,7 @@ async function withLock(target, options, fn) {
1733
1778
  });
1734
1779
  if (lock) {
1735
1780
  try {
1781
+ options.signal?.throwIfAborted();
1736
1782
  return await fn(lock);
1737
1783
  } finally {
1738
1784
  await lock.release();
@@ -1746,7 +1792,7 @@ async function withLock(target, options, fn) {
1746
1792
  timeoutMs: options.timeoutMs
1747
1793
  });
1748
1794
  }
1749
- await new Promise((resolve13) => setTimeout(resolve13, Math.min(25, Math.ceil(remaining))));
1795
+ await new Promise((resolve15) => setTimeout(resolve15, Math.min(25, Math.ceil(remaining))));
1750
1796
  }
1751
1797
  }
1752
1798
  var LockContentionError, LockOwnershipError;
@@ -1782,13 +1828,13 @@ function assertNotInsideHook(operation) {
1782
1828
  function runInsideHook(operation, fn) {
1783
1829
  return insideHook.run(operation, async () => await fn());
1784
1830
  }
1785
- async function callFailureHook(operation, hook, rowId2, error, logger) {
1831
+ async function callFailureHook(operation, hook, rowId2, error, logger2) {
1786
1832
  if (!hook)
1787
1833
  return;
1788
1834
  try {
1789
1835
  await runInsideHook(operation, () => hook(rowId2, error));
1790
1836
  } catch (hookError) {
1791
- logger?.warn("store failure hook threw; the original failure stands", {
1837
+ logger2?.warn("store failure hook threw; the original failure stands", {
1792
1838
  operation,
1793
1839
  rowId: rowId2,
1794
1840
  error: hookError instanceof Error ? hookError.message : String(hookError)
@@ -1865,7 +1911,7 @@ async function acquirePoolLock(spec, defaults, env3) {
1865
1911
  });
1866
1912
  }
1867
1913
  const jitter = Math.floor(Math.random() * (options.retryMs + 1));
1868
- await new Promise((resolve13) => setTimeout(resolve13, Math.min(options.retryMs + jitter, remaining)));
1914
+ await new Promise((resolve15) => setTimeout(resolve15, Math.min(options.retryMs + jitter, remaining)));
1869
1915
  }
1870
1916
  }
1871
1917
  function definedOnly(spec) {
@@ -2943,11 +2989,11 @@ var init_mutate = __esm({
2943
2989
  if (isRecord4(this.state.accounts) && Object.hasOwn(this.state.accounts, id))
2944
2990
  delete this.state.accounts[id];
2945
2991
  }
2946
- setStateAccount(id, fields) {
2992
+ setStateAccount(id, fields2) {
2947
2993
  if (!isRecord4(this.state.accounts))
2948
2994
  this.state.accounts = {};
2949
2995
  Object.defineProperty(this.state.accounts, id, {
2950
- value: fields,
2996
+ value: fields2,
2951
2997
  enumerable: true,
2952
2998
  writable: true,
2953
2999
  configurable: true
@@ -4496,12 +4542,12 @@ var init_pull = __esm({
4496
4542
  firedAtLoad;
4497
4543
  logger;
4498
4544
  inflight = /* @__PURE__ */ new Set();
4499
- constructor(rt, hook, onFailure, firedAtLoad, logger) {
4545
+ constructor(rt, hook, onFailure, firedAtLoad, logger2) {
4500
4546
  this.rt = rt;
4501
4547
  this.hook = hook;
4502
4548
  this.onFailure = onFailure;
4503
4549
  this.firedAtLoad = firedAtLoad;
4504
- this.logger = logger;
4550
+ this.logger = logger2;
4505
4551
  }
4506
4552
  fire(id, reason) {
4507
4553
  if (!this.hook)
@@ -5583,15 +5629,15 @@ function createRedactor(options = {}) {
5583
5629
  return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
5584
5630
  }
5585
5631
  function errorEntries(error) {
5586
- const fields = error;
5632
+ const fields2 = error;
5587
5633
  const entries = [
5588
5634
  ["name", error.name],
5589
5635
  ["message", error.message],
5590
5636
  ["stack", error.stack]
5591
5637
  ];
5592
5638
  for (const key of ["code", "status", "cause"])
5593
- if (fields[key] !== void 0)
5594
- entries.push([key, fields[key]]);
5639
+ if (fields2[key] !== void 0)
5640
+ entries.push([key, fields2[key]]);
5595
5641
  const listed = new Set(entries.map(([key]) => key));
5596
5642
  for (const entry of Object.entries(error))
5597
5643
  if (!listed.has(entry[0]))
@@ -5833,7 +5879,7 @@ function createEngine(options) {
5833
5879
  } catch {
5834
5880
  }
5835
5881
  }
5836
- function schedule() {
5882
+ function schedule2() {
5837
5883
  if (!timer)
5838
5884
  timer = setTimeout(() => {
5839
5885
  timer = void 0;
@@ -5875,7 +5921,7 @@ function createEngine(options) {
5875
5921
  void flushed.catch(() => {
5876
5922
  });
5877
5923
  } else
5878
- schedule();
5924
+ schedule2();
5879
5925
  } catch {
5880
5926
  }
5881
5927
  }
@@ -6746,9 +6792,9 @@ function findAction(sections, request) {
6746
6792
  return actions?.find((action) => action.id === request.actionId);
6747
6793
  }
6748
6794
  function createCommandMenu(options) {
6749
- const logger = options.logger ?? createLogger2("commands");
6795
+ const logger2 = options.logger ?? createLogger2("commands");
6750
6796
  const redact3 = createTextRedactor(options.redaction);
6751
- const seam = { logger, redact: redact3 };
6797
+ const seam = { logger: logger2, redact: redact3 };
6752
6798
  const now = options.now ?? Date.now;
6753
6799
  const extras = options.extras ?? [];
6754
6800
  const replaced = options.replace ?? {};
@@ -6775,7 +6821,7 @@ function createCommandMenu(options) {
6775
6821
  content: await section.build(invocation)
6776
6822
  };
6777
6823
  } catch (error) {
6778
- logger.warn("command menu section failed to build", {
6824
+ logger2.warn("command menu section failed to build", {
6779
6825
  command: options.command,
6780
6826
  section: id,
6781
6827
  error: redact3(error instanceof Error ? error.message : String(error))
@@ -6862,7 +6908,7 @@ function createCommandMenu(options) {
6862
6908
  };
6863
6909
  } catch (error) {
6864
6910
  const failure = projectFailure(error);
6865
- logger.warn("command menu action failed", {
6911
+ logger2.warn("command menu action failed", {
6866
6912
  command: options.command,
6867
6913
  section: request.sectionId,
6868
6914
  action: request.actionId,
@@ -7474,7 +7520,7 @@ async function select(terminal, items, options) {
7474
7520
  writeLine("");
7475
7521
  renderedLines = lines;
7476
7522
  };
7477
- return new Promise((resolve13) => {
7523
+ return new Promise((resolve15) => {
7478
7524
  const wasRaw = stdin.isRaw ?? false;
7479
7525
  const cleanup2 = () => {
7480
7526
  if (cleaned)
@@ -7494,7 +7540,7 @@ async function select(terminal, items, options) {
7494
7540
  };
7495
7541
  const finish = (value) => {
7496
7542
  cleanup2();
7497
- resolve13(value);
7543
+ resolve15(value);
7498
7544
  };
7499
7545
  const onSignal = () => finish(null);
7500
7546
  const onKey = (data) => {
@@ -7534,7 +7580,7 @@ async function select(terminal, items, options) {
7534
7580
  stdin.setRawMode(true);
7535
7581
  } catch {
7536
7582
  cleanup2();
7537
- resolve13(null);
7583
+ resolve15(null);
7538
7584
  return;
7539
7585
  }
7540
7586
  stdin.resume();
@@ -8980,13 +9026,13 @@ async function readBoundedJson(path2) {
8980
9026
  await descriptor.close();
8981
9027
  }
8982
9028
  }
8983
- function accountRecords(text2, fields) {
9029
+ function accountRecords(text2, fields2) {
8984
9030
  const records = [];
8985
9031
  for (const line of text2.split("\n")) {
8986
9032
  if (line.trim() === "" || line.startsWith("#"))
8987
9033
  continue;
8988
9034
  const parts = line.split(":");
8989
- 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] ?? ""))
9035
+ 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] ?? ""))
8990
9036
  return void 0;
8991
9037
  records.push(parts);
8992
9038
  }
@@ -9536,9 +9582,9 @@ function scopedRetryReason(served, current) {
9536
9582
  return "version-unchanged";
9537
9583
  return "rotated";
9538
9584
  }
9539
- function decideScopedRetryAfter401(site, served, current, logger = defaultLogger) {
9585
+ function decideScopedRetryAfter401(site, served, current, logger2 = defaultLogger) {
9540
9586
  const retry = isScopedCredentialRotation(served, current);
9541
- logger.debug("scoped 401 re-authorized", {
9587
+ logger2.debug("scoped 401 re-authorized", {
9542
9588
  site,
9543
9589
  credentialId: served.credentialId,
9544
9590
  servedVersion: served.recordVersion,
@@ -10111,6 +10157,7 @@ var init_interlock = __esm({
10111
10157
 
10112
10158
  // ../core/dist/common-auth-embedded/claustrum/roster.js
10113
10159
  import { createHash as createHash6 } from "node:crypto";
10160
+ import { resolve as resolve6 } from "node:path";
10114
10161
  function hash(value) {
10115
10162
  return createHash6("sha256").update(value).digest("hex");
10116
10163
  }
@@ -10331,7 +10378,7 @@ async function readVaultRoster(path2) {
10331
10378
  return decodeRoster(value);
10332
10379
  }
10333
10380
  async function mutateVaultRoster(path2, change, options = {}) {
10334
- return withLock(path2, WRITE_LOCK, async (lock) => {
10381
+ return withLock(path2, { ...WRITE_LOCK, signal: options.signal }, async (lock) => {
10335
10382
  const current = await readVaultRoster(path2);
10336
10383
  const { next, result } = await change(current, {
10337
10384
  assertOwned: () => lock.assertOwned()
@@ -10341,6 +10388,7 @@ async function mutateVaultRoster(path2, change, options = {}) {
10341
10388
  await writeJsonAtomic2(path2, next, {
10342
10389
  beforeRename: async () => {
10343
10390
  await options.beforePublish?.();
10391
+ options.signal?.throwIfAborted();
10344
10392
  await lock.assertOwned();
10345
10393
  }
10346
10394
  });
@@ -10390,43 +10438,51 @@ function receiptFence(row, receipt2) {
10390
10438
  return "bind";
10391
10439
  return "refuse";
10392
10440
  }
10393
- function recordVaultQuota(path2, input) {
10394
- return mutateVaultRoster(path2, (current) => {
10395
- const row = current?.rows.find((entry) => entry.routeId === input.routeId);
10396
- const fence = !current || !row ? "refuse" : receiptFence(row, input);
10397
- if (!current || !row || fence === "refuse")
10398
- return { result: false };
10399
- const quota = mergeQuotaObservation(row.quota, input.observation);
10400
- const bound = fence === "bind" ? { accountIdentity: input.accountIdentity, unclaimed: true } : {};
10401
- return {
10402
- next: {
10403
- ...current,
10404
- rows: current.rows.map((entry) => entry === row ? { ...entry, ...bound, quota } : entry)
10405
- },
10406
- result: true
10407
- };
10441
+ async function recordVaultQuota(path2, input) {
10442
+ const { routeId, observation, ...receipt2 } = input;
10443
+ return enqueueFencedVaultQuota(path2, {
10444
+ routeId,
10445
+ observation,
10446
+ accountIdentity: receipt2.accountIdentity,
10447
+ receipt: receipt2
10408
10448
  });
10409
10449
  }
10450
+ async function enqueueFencedVaultQuota(path2, publication2) {
10451
+ if (!isQuotaObservation(publication2.observation))
10452
+ return false;
10453
+ const current = pendingVaultQuota(path2, await readVaultRoster(path2));
10454
+ if (!applyVaultQuota(current, publication2).kept)
10455
+ return false;
10456
+ return enqueueVaultQuota(path2, publication2);
10457
+ }
10410
10458
  function recordVaultAccountQuota(path2, input) {
10411
- return mutateVaultRoster(path2, (current) => {
10412
- const row = current?.rows.find((entry) => entry.routeId === input.routeId);
10413
- if (!current || !row || row.accountIdentity === void 0 || row.accountIdentity !== input.accountIdentity)
10414
- return { result: false };
10415
- const quota = mergeQuotaObservation(row.quota, input.observation);
10416
- return {
10417
- next: {
10418
- ...current,
10419
- rows: current.rows.map((entry) => entry === row ? { ...entry, quota } : entry)
10420
- },
10421
- result: true
10422
- };
10423
- });
10459
+ return enqueueFencedVaultQuota(path2, input);
10460
+ }
10461
+ function applyVaultQuota(current, input) {
10462
+ const row = current?.rows.find((entry) => entry.routeId === input.routeId);
10463
+ const fence = !row ? "refuse" : input.receipt ? receiptFence(row, input.receipt) : row.accountIdentity !== void 0 && row.accountIdentity === input.accountIdentity ? "hold" : "refuse";
10464
+ if (!current || !row || fence === "refuse")
10465
+ return { roster: current, kept: false };
10466
+ const quota = mergeQuotaObservation(row.quota, input.observation);
10467
+ const bound = fence === "bind" ? { accountIdentity: input.accountIdentity, unclaimed: true } : {};
10468
+ return {
10469
+ roster: {
10470
+ ...current,
10471
+ rows: current.rows.map((entry) => entry === row ? { ...entry, ...bound, quota } : entry)
10472
+ },
10473
+ kept: true
10474
+ };
10475
+ }
10476
+ function forgetPendingVaultDiscovery(path2) {
10477
+ pendingDiscoveries.delete(resolve6(path2));
10424
10478
  }
10425
10479
  async function refreshVaultRoster(options) {
10426
10480
  options.signal?.throwIfAborted();
10427
10481
  const active2 = async () => await options.isActive?.() ?? true;
10428
- if (!await active2())
10482
+ if (!await active2()) {
10483
+ forgetPendingVaultDiscovery(options.path);
10429
10484
  return void 0;
10485
+ }
10430
10486
  const lease = await acquireRefreshFileLock({
10431
10487
  ...DISCOVERY_LEASE,
10432
10488
  path: options.path,
@@ -10439,8 +10495,18 @@ async function refreshVaultRoster(options) {
10439
10495
  throw new ClaustrumConsumerError("roster-busy", "Claustrum account discovery is already in progress");
10440
10496
  return persisted;
10441
10497
  }
10498
+ const key = resolve6(options.path);
10499
+ let discovered;
10442
10500
  try {
10443
- const inventory = await options.custody.discover(options.signal);
10501
+ const previous = await readVaultRoster(options.path);
10502
+ const pending = pendingDiscoveries.get(key);
10503
+ discovered = pending && (pending.previousView === previous?.view || pending.inventory.view === previous?.view) ? pending : {
10504
+ inventory: await options.custody.discover(options.signal),
10505
+ previousView: previous?.view
10506
+ };
10507
+ pendingDiscoveries.delete(key);
10508
+ const { inventory } = discovered;
10509
+ options.onInventory?.(inventory);
10444
10510
  options.signal?.throwIfAborted();
10445
10511
  return await mutateVaultRoster(options.path, async (current) => {
10446
10512
  if (!await active2())
@@ -10451,7 +10517,16 @@ async function refreshVaultRoster(options) {
10451
10517
  const next = projectVaultRoster(current, inventory, projection);
10452
10518
  const changed = JSON.stringify(current) !== JSON.stringify(next);
10453
10519
  return { ...changed && { next }, result: next };
10520
+ }, {
10521
+ beforePublish: async () => {
10522
+ options.signal?.throwIfAborted();
10523
+ await lease.assertOwned();
10524
+ }
10454
10525
  });
10526
+ } catch (error) {
10527
+ if (error instanceof LockContentionError && discovered && !options.signal?.aborted && await active2())
10528
+ pendingDiscoveries.set(key, discovered);
10529
+ throw error;
10455
10530
  } finally {
10456
10531
  await lease.release();
10457
10532
  }
@@ -10488,7 +10563,7 @@ function resolveVaultPrimary(input) {
10488
10563
  ...previous && previous.accountIdentity !== identity && { replaced: previous }
10489
10564
  };
10490
10565
  }
10491
- var DEFAULT_ROUTE_PREFIX, SKIPPED_REASONS, WRITE_LOCK, DISCOVERY_LEASE;
10566
+ var DEFAULT_ROUTE_PREFIX, SKIPPED_REASONS, WRITE_LOCK, DISCOVERY_LEASE, pendingDiscoveries;
10492
10567
  var init_roster = __esm({
10493
10568
  "../core/dist/common-auth-embedded/claustrum/roster.js"() {
10494
10569
  "use strict";
@@ -10497,6 +10572,8 @@ var init_roster = __esm({
10497
10572
  init_quota();
10498
10573
  init_errors2();
10499
10574
  init_interlock();
10575
+ init_quota_writer();
10576
+ init_quota_writer();
10500
10577
  DEFAULT_ROUTE_PREFIX = "vault:";
10501
10578
  SKIPPED_REASONS = /* @__PURE__ */ new Set([
10502
10579
  "empty credential id",
@@ -10507,9 +10584,238 @@ var init_roster = __esm({
10507
10584
  WRITE_LOCK = {
10508
10585
  name: "claustrum-roster-write",
10509
10586
  ttlMs: 1e4,
10510
- timeoutMs: 5e3
10587
+ timeoutMs: 5e3,
10588
+ renew: true
10511
10589
  };
10512
10590
  DISCOVERY_LEASE = { name: "claustrum-roster", ttlMs: 3e4 };
10591
+ pendingDiscoveries = /* @__PURE__ */ new Map();
10592
+ }
10593
+ });
10594
+
10595
+ // ../core/dist/common-auth-embedded/claustrum/quota-writer.js
10596
+ import { resolve as resolve7 } from "node:path";
10597
+ function writerFor(path2) {
10598
+ const key = resolve7(path2);
10599
+ let writer = writers.get(key);
10600
+ if (!writer) {
10601
+ writer = {
10602
+ path: key,
10603
+ pending: /* @__PURE__ */ new Map(),
10604
+ listeners: /* @__PURE__ */ new Set(),
10605
+ wake: /* @__PURE__ */ new Set(),
10606
+ abort: new AbortController(),
10607
+ failures: 0,
10608
+ draining: false,
10609
+ order: 0
10610
+ };
10611
+ writers.set(key, writer);
10612
+ }
10613
+ return writer;
10614
+ }
10615
+ function retainVaultQuotaWriter(path2, listener) {
10616
+ const writer = writerFor(path2);
10617
+ writer.listeners.add(listener);
10618
+ let released;
10619
+ return () => released ??= (() => {
10620
+ writer.listeners.delete(listener);
10621
+ return writer.listeners.size ? Promise.resolve() : drainVaultQuota(path2);
10622
+ })();
10623
+ }
10624
+ function fields(publication2) {
10625
+ const result = /* @__PURE__ */ new Map();
10626
+ const { observation } = publication2;
10627
+ const witness = JSON.stringify([
10628
+ publication2.routeId,
10629
+ publication2.receipt?.credentialId,
10630
+ publication2.receipt?.accountIdentitySource,
10631
+ publication2.receipt?.expectedAccountIdentity
10632
+ ]);
10633
+ const add = (key, at, part) => result.set(`${witness}:${key}`, {
10634
+ at,
10635
+ order: 0,
10636
+ publication: { ...publication2, observation: part }
10637
+ });
10638
+ const keyFor = (scope, label) => JSON.stringify([scope ?? "all", label]);
10639
+ const read = /* @__PURE__ */ new Set();
10640
+ for (const reading of observation.readings ?? []) {
10641
+ const key = keyFor(reading.scope, reading.label);
10642
+ read.add(key);
10643
+ add(key, observation.checkedAt, {
10644
+ checkedAt: observation.checkedAt,
10645
+ readings: [{ ...reading }]
10646
+ });
10647
+ }
10648
+ for (const pair of observation.coverage ?? []) {
10649
+ const key = keyFor(pair.scope, pair.label);
10650
+ if (!read.has(key))
10651
+ add(key, observation.checkedAt, {
10652
+ checkedAt: observation.checkedAt,
10653
+ coverage: [{ ...pair }]
10654
+ });
10655
+ }
10656
+ if (observation.budget)
10657
+ add("budget", observation.checkedAt, {
10658
+ checkedAt: observation.checkedAt,
10659
+ budget: { ...observation.budget }
10660
+ });
10661
+ for (const [name, counter] of Object.entries(observation.counters ?? {})) {
10662
+ add(`counter:${name}`, counter.checkedAt, {
10663
+ checkedAt: observation.checkedAt,
10664
+ counters: { [name]: { ...counter } }
10665
+ });
10666
+ }
10667
+ if (observation.credits)
10668
+ add("credits", observation.credits.checkedAt, {
10669
+ checkedAt: observation.checkedAt,
10670
+ credits: { ...observation.credits }
10671
+ });
10672
+ if (!result.size)
10673
+ add("empty", observation.checkedAt, { checkedAt: observation.checkedAt });
10674
+ return result;
10675
+ }
10676
+ function enqueueVaultQuota(path2, publication2) {
10677
+ if (!isQuotaObservation(publication2.observation))
10678
+ return Promise.resolve(false);
10679
+ const writer = writerFor(path2);
10680
+ const account = JSON.stringify([
10681
+ publication2.accountIdentity ?? null,
10682
+ publication2.accountIdentity === void 0 ? publication2.routeId : null
10683
+ ]);
10684
+ const pending = writer.pending.get(account) ?? /* @__PURE__ */ new Map();
10685
+ for (const [key, field] of fields(publication2)) {
10686
+ const previous = pending.get(key);
10687
+ if (!previous || field.at >= previous.at) {
10688
+ field.order = ++writer.order;
10689
+ if (field.publication.observation.coverage)
10690
+ field.priorReading = previous?.publication.observation.readings ? previous.publication : previous?.priorReading;
10691
+ pending.set(key, field);
10692
+ }
10693
+ }
10694
+ if (pending.size)
10695
+ writer.pending.set(account, pending);
10696
+ for (const listener of writer.listeners)
10697
+ listener(publication2);
10698
+ schedule(writer, COALESCE_MS);
10699
+ return Promise.resolve(true);
10700
+ }
10701
+ function orderedFields(pending) {
10702
+ return [...pending.values()].flatMap((account) => [...account.values()]).sort((a, b) => a.order - b.order);
10703
+ }
10704
+ function pendingVaultQuota(path2, roster) {
10705
+ const writer = writers.get(resolve7(path2));
10706
+ if (writer) {
10707
+ for (const field of orderedFields(writer.pending)) {
10708
+ if (field.priorReading)
10709
+ roster = applyVaultQuota(roster, field.priorReading).roster;
10710
+ roster = applyVaultQuota(roster, field.publication).roster;
10711
+ }
10712
+ }
10713
+ return roster;
10714
+ }
10715
+ function schedule(writer, delay3) {
10716
+ if (writer.running || writer.timer || !writer.pending.size || writer.abort.signal.aborted)
10717
+ return;
10718
+ writer.timer = setTimeout(() => {
10719
+ writer.timer = void 0;
10720
+ flush(writer);
10721
+ }, delay3);
10722
+ if (!writer.draining)
10723
+ writer.timer.unref?.();
10724
+ }
10725
+ function flush(writer) {
10726
+ if (writer.running || writer.abort.signal.aborted)
10727
+ return;
10728
+ const batch = new Map([...writer.pending].map(([account, pending]) => [
10729
+ account,
10730
+ new Map(pending)
10731
+ ]));
10732
+ writer.running = (async () => {
10733
+ try {
10734
+ await mutateVaultRoster(writer.path, (current) => {
10735
+ let next = current;
10736
+ for (const field of orderedFields(batch)) {
10737
+ if (field.priorReading)
10738
+ next = applyVaultQuota(next, field.priorReading).roster;
10739
+ next = applyVaultQuota(next, field.publication).roster;
10740
+ }
10741
+ return { ...next !== current && { next }, result: void 0 };
10742
+ }, { signal: writer.abort.signal });
10743
+ for (const [account, fields2] of batch) {
10744
+ const pending = writer.pending.get(account);
10745
+ for (const [key, field] of fields2) {
10746
+ if (pending?.get(key) === field)
10747
+ pending.delete(key);
10748
+ }
10749
+ if (!pending?.size)
10750
+ writer.pending.delete(account);
10751
+ }
10752
+ writer.failures = 0;
10753
+ } catch (error) {
10754
+ if (!writer.abort.signal.aborted && writer.failures++ === 0) {
10755
+ logger.warn("vault quota publication delayed; retrying", {
10756
+ error: error instanceof Error ? error.message : String(error)
10757
+ });
10758
+ }
10759
+ } finally {
10760
+ writer.running = void 0;
10761
+ for (const wake of writer.wake)
10762
+ wake();
10763
+ const backoff = writer.failures ? Math.min(5e3, 100 * 2 ** Math.min(writer.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
10764
+ schedule(writer, backoff);
10765
+ }
10766
+ })();
10767
+ }
10768
+ async function drainVaultQuota(path2, timeoutMs = 1e3) {
10769
+ const key = resolve7(path2);
10770
+ const writer = writers.get(key);
10771
+ if (!writer)
10772
+ return;
10773
+ writer.draining = true;
10774
+ clearTimeout(writer.timer);
10775
+ writer.timer = void 0;
10776
+ let deadline;
10777
+ let wake;
10778
+ const drained = new Promise((done) => {
10779
+ wake = () => {
10780
+ if (!writer.pending.size || writer.abort.signal.aborted)
10781
+ done();
10782
+ };
10783
+ writer.wake.add(wake);
10784
+ wake();
10785
+ });
10786
+ try {
10787
+ if (writer.pending.size)
10788
+ flush(writer);
10789
+ await Promise.race([
10790
+ drained,
10791
+ new Promise((done) => {
10792
+ deadline = setTimeout(done, Math.max(0, timeoutMs));
10793
+ })
10794
+ ]);
10795
+ } finally {
10796
+ clearTimeout(deadline);
10797
+ if (wake)
10798
+ writer.wake.delete(wake);
10799
+ writer.draining = false;
10800
+ if (!writer.listeners.size) {
10801
+ writer.abort.abort();
10802
+ clearTimeout(writer.timer);
10803
+ writer.pending.clear();
10804
+ if (writers.get(key) === writer)
10805
+ writers.delete(key);
10806
+ }
10807
+ }
10808
+ }
10809
+ var writers, logger, COALESCE_MS;
10810
+ var init_quota_writer = __esm({
10811
+ "../core/dist/common-auth-embedded/claustrum/quota-writer.js"() {
10812
+ "use strict";
10813
+ init_logger();
10814
+ init_quota();
10815
+ init_roster();
10816
+ writers = /* @__PURE__ */ new Map();
10817
+ logger = createLogger2("claustrum");
10818
+ COALESCE_MS = 100;
10513
10819
  }
10514
10820
  });
10515
10821
 
@@ -10524,6 +10830,7 @@ var init_consumer = __esm({
10524
10830
  init_enrollment();
10525
10831
  init_errors2();
10526
10832
  init_insula();
10833
+ init_quota_writer();
10527
10834
  init_roster();
10528
10835
  init_watch();
10529
10836
  ClaustrumConsumer = class {
@@ -10547,9 +10854,13 @@ var init_consumer = __esm({
10547
10854
  #insulaSkips = /* @__PURE__ */ new Map();
10548
10855
  /** When this instance last completed a discovery, by `now`. */
10549
10856
  #discoveredAt;
10857
+ #releaseQuotaWriter;
10550
10858
  constructor(options) {
10551
10859
  this.#options = options;
10552
10860
  this.#logger = options.logger ?? createLogger2("claustrum");
10861
+ this.#releaseQuotaWriter = retainVaultQuotaWriter(options.rosterPath, (publication2) => {
10862
+ this.#roster = applyVaultQuota(this.#roster, publication2).roster;
10863
+ });
10553
10864
  }
10554
10865
  #assertOpen(signal) {
10555
10866
  this.#shutdown.signal.throwIfAborted();
@@ -10563,7 +10874,7 @@ var init_consumer = __esm({
10563
10874
  this.#shutdown.signal,
10564
10875
  ...signal ? [signal] : []
10565
10876
  ]);
10566
- return new Promise((resolve13, reject) => {
10877
+ return new Promise((resolve15, reject) => {
10567
10878
  const cleanup2 = () => {
10568
10879
  combined.signal.removeEventListener("abort", abort);
10569
10880
  combined.dispose();
@@ -10578,7 +10889,7 @@ var init_consumer = __esm({
10578
10889
  if (combined.signal.aborted)
10579
10890
  reject(combined.signal.reason);
10580
10891
  else
10581
- resolve13(value);
10892
+ resolve15(value);
10582
10893
  }, (error) => {
10583
10894
  cleanup2();
10584
10895
  reject(error);
@@ -10678,11 +10989,9 @@ var init_consumer = __esm({
10678
10989
  let discovered;
10679
10990
  const roster = await refreshVaultRoster({
10680
10991
  path: this.#options.rosterPath,
10681
- custody: {
10682
- discover: async (signal) => {
10683
- discovered = await custody.discover(signal);
10684
- return discovered;
10685
- }
10992
+ custody,
10993
+ onInventory: (inventory) => {
10994
+ discovered = inventory;
10686
10995
  },
10687
10996
  isActive: () => this.#active(),
10688
10997
  signal: this.#shutdown.signal,
@@ -10695,7 +11004,7 @@ var init_consumer = __esm({
10695
11004
  });
10696
11005
  this.#assertOpen();
10697
11006
  const changed = roster?.view !== this.#roster?.view;
10698
- this.#roster = roster;
11007
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, roster);
10699
11008
  custody.retain(roster?.rows ?? []);
10700
11009
  if (discovered && roster?.view !== void 0)
10701
11010
  this.#grantReach = discovered.grantReach ? { view: roster.view, reach: discovered.grantReach } : void 0;
@@ -10831,7 +11140,7 @@ var init_consumer = __esm({
10831
11140
  return void 0;
10832
11141
  try {
10833
11142
  await readClaustrumEnrollmentToken(this.#options.tokenPath);
10834
- const roster = await readVaultRoster(this.#options.rosterPath);
11143
+ const roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10835
11144
  const row = roster?.rows.find((entry) => entry.routeId === routeId);
10836
11145
  return this.#normalizeInsulaQuota(row?.accountIdentity);
10837
11146
  } catch {
@@ -10845,7 +11154,7 @@ var init_consumer = __esm({
10845
11154
  return { miss: "unreachable" };
10846
11155
  try {
10847
11156
  await readClaustrumEnrollmentToken(this.#options.tokenPath);
10848
- const roster = await readVaultRoster(this.#options.rosterPath);
11157
+ const roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10849
11158
  const account = roster?.rows.find((row) => row.routeId === routeId)?.accountIdentity;
10850
11159
  if (!account || !this.#insula)
10851
11160
  return { miss: "unreachable" };
@@ -10895,7 +11204,7 @@ var init_consumer = __esm({
10895
11204
  this.#insula = void 0;
10896
11205
  throw new ClaustrumConsumerError("not-active", "Claustrum scoped custody is not active");
10897
11206
  }
10898
- const current = await readVaultRoster(this.#options.rosterPath);
11207
+ const current = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10899
11208
  this.#assertOpen(signal);
10900
11209
  const observed = roster.rows.find((row) => row.routeId === routeId);
10901
11210
  const configured = current?.rows.find((row) => row.routeId === routeId);
@@ -10974,13 +11283,13 @@ var init_consumer = __esm({
10974
11283
  async decline(routeId) {
10975
11284
  this.#assertOpen();
10976
11285
  await declineVaultRoute(this.#options.rosterPath, routeId);
10977
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11286
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10978
11287
  this.#custody?.retain(this.#roster?.rows ?? []);
10979
11288
  }
10980
11289
  async accept(routeId) {
10981
11290
  this.#assertOpen();
10982
11291
  await acceptVaultRoute(this.#options.rosterPath, routeId);
10983
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11292
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
10984
11293
  }
10985
11294
  /**
10986
11295
  * Store a quota or profile observation for a vault route. The receipt the
@@ -10990,7 +11299,7 @@ var init_consumer = __esm({
10990
11299
  */
10991
11300
  async recordQuota(routeId, observation, attempt) {
10992
11301
  this.#assertOpen();
10993
- const kept = await recordVaultQuota(this.#options.rosterPath, {
11302
+ return recordVaultQuota(this.#options.rosterPath, {
10994
11303
  routeId,
10995
11304
  observation,
10996
11305
  credentialId: attempt.credentialId,
@@ -11002,27 +11311,21 @@ var init_consumer = __esm({
11002
11311
  expectedAccountIdentity: attempt.expectedAccountIdentity
11003
11312
  }
11004
11313
  });
11005
- if (kept)
11006
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11007
- return kept;
11008
11314
  }
11009
11315
  /**
11010
11316
  * Store a background observation that belongs to an account rather than to
11011
11317
  * a served credential (an insula reading from `cachedInsulaQuotaForRoute`).
11012
11318
  * It lands only while the route is still bound to that known account, so no
11013
11319
  * credential fetch is needed and a replaced account's reading is dropped.
11014
- * The in-memory roster is reloaded from the file, without a vault call.
11320
+ * Memory updates immediately; durable publication is detached and coalesced.
11015
11321
  */
11016
11322
  async recordAccountQuota(routeId, accountIdentity, observation) {
11017
11323
  this.#assertOpen();
11018
- const kept = await recordVaultAccountQuota(this.#options.rosterPath, {
11324
+ return recordVaultAccountQuota(this.#options.rosterPath, {
11019
11325
  routeId,
11020
11326
  accountIdentity,
11021
11327
  observation
11022
11328
  });
11023
- if (kept)
11024
- this.#roster = await readVaultRoster(this.#options.rosterPath);
11025
- return kept;
11026
11329
  }
11027
11330
  close() {
11028
11331
  if (this.#shutdown.signal.aborted)
@@ -11037,6 +11340,13 @@ var init_consumer = __esm({
11037
11340
  this.#insula = void 0;
11038
11341
  this.#roster = void 0;
11039
11342
  this.#grantReach = void 0;
11343
+ void this.#releaseQuotaWriter();
11344
+ forgetPendingVaultDiscovery(this.#options.rosterPath);
11345
+ }
11346
+ /** Close immediately; the last consumer also waits for the writer's bounded drain. */
11347
+ async dispose() {
11348
+ this.close();
11349
+ await this.#releaseQuotaWriter();
11040
11350
  }
11041
11351
  };
11042
11352
  }
@@ -11079,6 +11389,7 @@ __export(claustrum_exports, {
11079
11389
  declineAccount: () => declineAccount,
11080
11390
  declineVaultRoute: () => declineVaultRoute,
11081
11391
  disconnectClaustrumEnrollment: () => disconnectClaustrumEnrollment,
11392
+ drainVaultQuota: () => drainVaultQuota,
11082
11393
  enrollmentAuthority: () => enrollmentAuthority,
11083
11394
  enrollmentName: () => enrollmentName,
11084
11395
  getClaustrumEnrollmentPaths: () => getClaustrumEnrollmentPaths,
@@ -11117,6 +11428,7 @@ var init_claustrum = __esm({
11117
11428
  init_host_slot();
11118
11429
  init_insula();
11119
11430
  init_interlock();
11431
+ init_quota_writer();
11120
11432
  init_roster();
11121
11433
  init_watch();
11122
11434
  }
@@ -11197,7 +11509,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11197
11509
  if (!released && lastUpdate + RENEWAL_STALE < Date.now())
11198
11510
  compromise();
11199
11511
  }
11200
- function schedule(delay3 = UPDATE) {
11512
+ function schedule2(delay3 = UPDATE) {
11201
11513
  if (released)
11202
11514
  return;
11203
11515
  timer = setTimeout(() => {
@@ -11211,7 +11523,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11211
11523
  if (errorCode(error) === "ENOENT" || lastUpdate + RENEWAL_STALE < Date.now())
11212
11524
  compromise();
11213
11525
  else
11214
- schedule(1e3);
11526
+ schedule2(1e3);
11215
11527
  }
11216
11528
  async function update() {
11217
11529
  assertFresh();
@@ -11244,14 +11556,14 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11244
11556
  mtime = next.getTime();
11245
11557
  lastUpdate = Date.now();
11246
11558
  active.set(path2, { ...identity, mtime, renewedAt: lastUpdate });
11247
- schedule();
11559
+ schedule2();
11248
11560
  }
11249
11561
  onRenew?.(async () => {
11250
11562
  if (timer)
11251
11563
  clearTimeout(timer);
11252
11564
  await update();
11253
11565
  });
11254
- schedule();
11566
+ schedule2();
11255
11567
  return {
11256
11568
  assertFresh,
11257
11569
  async release() {
@@ -11310,7 +11622,7 @@ var init_lock = __esm({
11310
11622
  import { createHash as createHash7 } from "node:crypto";
11311
11623
  import { constants as constants2 } from "node:fs";
11312
11624
  import { lstat as lstat3, mkdir as mkdir10, open as open7, unlink as unlink7 } from "node:fs/promises";
11313
- import { dirname as dirname10, resolve as resolve6 } from "node:path";
11625
+ import { dirname as dirname10, resolve as resolve8 } from "node:path";
11314
11626
  import { setTimeout as sleep2 } from "node:timers/promises";
11315
11627
  function rootSpans(text2) {
11316
11628
  let i = text2.indexOf("{") + 1;
@@ -11511,8 +11823,8 @@ function createPiSlot(options, onStep, hooks) {
11511
11823
  if (!provider2 || !options.authPath || !options.stashPath || !placeholderKey || placeholderKey.startsWith("!") || placeholderKey.includes("$") || !Number.isFinite(timeout) || timeout < 0) {
11512
11824
  throw new PiSlotError("invalid-options");
11513
11825
  }
11514
- const authPath = resolve6(options.authPath);
11515
- const stashPath = resolve6(options.stashPath);
11826
+ const authPath = resolve8(options.authPath);
11827
+ const stashPath = resolve8(options.stashPath);
11516
11828
  if (authPath === stashPath || stashPath === `${authPath}.lock`) {
11517
11829
  throw new PiSlotError("invalid-options");
11518
11830
  }
@@ -11682,7 +11994,7 @@ var init_pi_slot = __esm({
11682
11994
  // src/cli.ts
11683
11995
  import { execFile } from "node:child_process";
11684
11996
  import { realpathSync as realpathSync2 } from "node:fs";
11685
- import { resolve as resolve12 } from "node:path";
11997
+ import { resolve as resolve14 } from "node:path";
11686
11998
  import { createInterface } from "node:readline/promises";
11687
11999
  import { fileURLToPath as fileURLToPath2 } from "node:url";
11688
12000
  import { promisify } from "node:util";
@@ -16524,7 +16836,7 @@ async function rmEvictingDir(evictingPath) {
16524
16836
  });
16525
16837
  }
16526
16838
  async function sleep(ms) {
16527
- await new Promise((resolve13) => setTimeout(resolve13, ms));
16839
+ await new Promise((resolve15) => setTimeout(resolve15, ms));
16528
16840
  }
16529
16841
  async function acquireFencedFileLock(options) {
16530
16842
  const lockPath = `${options.path}.${options.name}.lock`;
@@ -16640,8 +16952,8 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
16640
16952
  let released = false;
16641
16953
  let lost = false;
16642
16954
  let lostResolve = null;
16643
- let lostPromise = new Promise((resolve13) => {
16644
- lostResolve = resolve13;
16955
+ let lostPromise = new Promise((resolve15) => {
16956
+ lostResolve = resolve15;
16645
16957
  });
16646
16958
  const markLost = () => {
16647
16959
  if (lost)
@@ -16651,9 +16963,9 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
16651
16963
  clearInterval(renewTimer);
16652
16964
  renewTimer = null;
16653
16965
  }
16654
- const resolve13 = lostResolve;
16966
+ const resolve15 = lostResolve;
16655
16967
  lostResolve = null;
16656
- resolve13?.();
16968
+ resolve15?.();
16657
16969
  };
16658
16970
  const setupRenew = () => {
16659
16971
  if (options.renew === false)
@@ -16877,7 +17189,7 @@ var AccountStorageUnreadableError = class extends Error {
16877
17189
  }
16878
17190
  };
16879
17191
  var RETRY_DELAYS_MS = [100, 200, 400, 800, 1e3];
16880
- var DEFAULT_SLEEP = (ms) => new Promise((resolve13) => setTimeout(resolve13, ms));
17192
+ var DEFAULT_SLEEP = (ms) => new Promise((resolve15) => setTimeout(resolve15, ms));
16881
17193
  var DEFAULT_BUILD_BACKUP_PATH = (path2, now) => `${path2}.corrupt-${now.toISOString().replace(/[:.]/g, "-")}`;
16882
17194
  async function ensureSecurePermissions(path2) {
16883
17195
  try {
@@ -17388,7 +17700,7 @@ function getHttpsProxy(url) {
17388
17700
  }
17389
17701
  }
17390
17702
  function waitForHead(socket, timeoutMs, onTimeout) {
17391
- return new Promise((resolve13, reject) => {
17703
+ return new Promise((resolve15, reject) => {
17392
17704
  let buffer = Buffer2.alloc(0);
17393
17705
  const timeout = setTimeout(() => {
17394
17706
  onTimeout();
@@ -17411,7 +17723,7 @@ function waitForHead(socket, timeoutMs, onTimeout) {
17411
17723
  return;
17412
17724
  const head = buffer.subarray(0, marker).toString("latin1");
17413
17725
  const leftover = buffer.subarray(marker + 4);
17414
- cleanup2(() => resolve13({ head, leftover }));
17726
+ cleanup2(() => resolve15({ head, leftover }));
17415
17727
  };
17416
17728
  socket.on("data", onData);
17417
17729
  socket.once("error", onError);
@@ -17425,7 +17737,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
17425
17737
  port: Number(proxyUrl.port || DEFAULT_PROXY_PORT),
17426
17738
  signal: signal ?? void 0
17427
17739
  });
17428
- await new Promise((resolve13, reject) => {
17740
+ await new Promise((resolve15, reject) => {
17429
17741
  const timeout = setTimeout(() => {
17430
17742
  onDebug?.(`agy transport proxy connect timeout after ${timeoutMs}ms`);
17431
17743
  proxySocket.destroy();
@@ -17434,7 +17746,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
17434
17746
  const cleanup2 = () => clearTimeout(timeout);
17435
17747
  proxySocket.once("connect", () => {
17436
17748
  cleanup2();
17437
- resolve13();
17749
+ resolve15();
17438
17750
  });
17439
17751
  proxySocket.once("error", (error) => {
17440
17752
  cleanup2();
@@ -17459,7 +17771,7 @@ Host: ${targetHost}:${targetPort}\r
17459
17771
  if (leftover.length > 0) {
17460
17772
  proxySocket.unshift(leftover);
17461
17773
  }
17462
- return await new Promise((resolve13, reject) => {
17774
+ return await new Promise((resolve15, reject) => {
17463
17775
  const tlsOptions = {
17464
17776
  socket: proxySocket,
17465
17777
  servername: targetHost,
@@ -17474,7 +17786,7 @@ Host: ${targetHost}:${targetPort}\r
17474
17786
  const cleanup2 = () => clearTimeout(timeout);
17475
17787
  tlsSocket.once("secureConnect", () => {
17476
17788
  cleanup2();
17477
- resolve13(tlsSocket);
17789
+ resolve15(tlsSocket);
17478
17790
  });
17479
17791
  tlsSocket.once("error", (error) => {
17480
17792
  cleanup2();
@@ -17483,7 +17795,7 @@ Host: ${targetHost}:${targetPort}\r
17483
17795
  });
17484
17796
  }
17485
17797
  async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
17486
- return await new Promise((resolve13, reject) => {
17798
+ return await new Promise((resolve15, reject) => {
17487
17799
  const tlsOptions = {
17488
17800
  host: targetUrl.hostname,
17489
17801
  port: Number(targetUrl.port || DEFAULT_HTTPS_PORT),
@@ -17499,7 +17811,7 @@ async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
17499
17811
  const cleanup2 = () => clearTimeout(timeout);
17500
17812
  socket.once("secureConnect", () => {
17501
17813
  cleanup2();
17502
- resolve13(socket);
17814
+ resolve15(socket);
17503
17815
  });
17504
17816
  socket.once("error", (error) => {
17505
17817
  cleanup2();
@@ -18172,8 +18484,8 @@ function getDefaultTierId(allowedTiers) {
18172
18484
  return allowedTiers[0]?.id;
18173
18485
  }
18174
18486
  function wait(ms) {
18175
- return new Promise((resolve13) => {
18176
- setTimeout(resolve13, ms);
18487
+ return new Promise((resolve15) => {
18488
+ setTimeout(resolve15, ms);
18177
18489
  });
18178
18490
  }
18179
18491
  function extractManagedProjectId(payload) {
@@ -19014,17 +19326,17 @@ import {
19014
19326
  writeFileSync
19015
19327
  } from "node:fs";
19016
19328
  import { homedir as homedir3 } from "node:os";
19017
- import { dirname as dirname14, join as join8, resolve as resolve9 } from "node:path";
19329
+ import { dirname as dirname14, join as join8, resolve as resolve11 } from "node:path";
19018
19330
 
19019
19331
  // src/common-auth-embedded/logger/engine.js
19020
19332
  import { appendFileSync as appendFileSync2, chmodSync as chmodSync2, existsSync as existsSync2, renameSync as renameSync2, statSync as statSync3 } from "node:fs";
19021
19333
  import { open as open8 } from "node:fs/promises";
19022
- import { dirname as dirname13, resolve as resolve8 } from "node:path";
19334
+ import { dirname as dirname13, resolve as resolve10 } from "node:path";
19023
19335
 
19024
19336
  // src/common-auth-embedded/fs/private-files.js
19025
19337
  import { randomUUID as randomUUID11 } from "node:crypto";
19026
19338
  import { lstat as lstat4, readFile as readFile7, rename as rename7, unlink as unlink8 } from "node:fs/promises";
19027
- import { dirname as dirname12, resolve as resolve7 } from "node:path";
19339
+ import { dirname as dirname12, resolve as resolve9 } from "node:path";
19028
19340
  var windowsPrivateFiles2 = process.platform === "win32";
19029
19341
  var migrationNotices2 = /* @__PURE__ */ new Set();
19030
19342
  function ioCode2(detail) {
@@ -19075,7 +19387,7 @@ async function privateOperation2(path2, stage, operation) {
19075
19387
  }
19076
19388
  var safeParentOptionsForTest2;
19077
19389
  async function verifySafeDirectory2(path2, options) {
19078
- path2 = resolve7(path2);
19390
+ path2 = resolve9(path2);
19079
19391
  options ??= safeParentOptionsForTest2;
19080
19392
  await privateOperation2(path2, "safe-parent", async () => {
19081
19393
  const result = await (await loadBackend2()).verifySafeParent(path2, options);
@@ -19090,7 +19402,7 @@ async function verifySafeDirectory2(path2, options) {
19090
19402
  });
19091
19403
  }
19092
19404
  async function verifyPrivate2(path2, kind, migrate = false) {
19093
- path2 = resolve7(path2);
19405
+ path2 = resolve9(path2);
19094
19406
  if (kind === "directory")
19095
19407
  return verifySafeDirectory2(path2);
19096
19408
  await privateOperation2(path2, "verify", async () => {
@@ -19125,7 +19437,7 @@ async function verifyPrivate2(path2, kind, migrate = false) {
19125
19437
  });
19126
19438
  }
19127
19439
  async function ensurePrivateDirectory3(path2, _migrate = false, options) {
19128
- path2 = resolve7(path2);
19440
+ path2 = resolve9(path2);
19129
19441
  await privateOperation2(path2, "directory", async () => {
19130
19442
  const api = await loadBackend2();
19131
19443
  try {
@@ -19156,7 +19468,7 @@ async function readPrivateText2(path2, migrate = false) {
19156
19468
  async function readPrivateBuffer2(path2, migrate = false) {
19157
19469
  if (!windowsPrivateFiles2)
19158
19470
  return readFile7(path2);
19159
- path2 = resolve7(path2);
19471
+ path2 = resolve9(path2);
19160
19472
  if (migrate) {
19161
19473
  await verifySafeDirectory2(dirname12(path2));
19162
19474
  await verifyPrivate2(path2, "file", true);
@@ -19164,20 +19476,20 @@ async function readPrivateBuffer2(path2, migrate = false) {
19164
19476
  return privateOperation2(path2, "read", async () => (await loadBackend2()).readOwnerOnly(path2));
19165
19477
  }
19166
19478
  async function createPrivateBytes2(path2, bytes) {
19167
- await verifySafeDirectory2(dirname12(resolve7(path2)));
19479
+ await verifySafeDirectory2(dirname12(resolve9(path2)));
19168
19480
  await privateOperation2(path2, "create", async () => {
19169
- await (await loadBackend2()).createPrivateFile(resolve7(path2), bytes);
19481
+ await (await loadBackend2()).createPrivateFile(resolve9(path2), bytes);
19170
19482
  });
19171
19483
  }
19172
19484
  async function createPrivateDirectoryExclusive2(path2) {
19173
- await verifySafeDirectory2(dirname12(resolve7(path2)));
19485
+ await verifySafeDirectory2(dirname12(resolve9(path2)));
19174
19486
  await privateOperation2(path2, "directory-create", async () => {
19175
- await (await loadBackend2()).createOwnerOnly(resolve7(path2), { kind: "dir" });
19487
+ await (await loadBackend2()).createOwnerOnly(resolve9(path2), { kind: "dir" });
19176
19488
  });
19177
19489
  }
19178
19490
  async function replaceWindowsFile2(from, to, options = {}) {
19179
- from = resolve7(from);
19180
- to = resolve7(to);
19491
+ from = resolve9(from);
19492
+ to = resolve9(to);
19181
19493
  const now = options.now ?? (() => performance.now());
19182
19494
  const start = now();
19183
19495
  const leaseDeadline = options.deadline ?? Infinity;
@@ -19220,7 +19532,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
19220
19532
  throw error;
19221
19533
  }
19222
19534
  async function writePrivateAtomic2(path2, bytes, options = {}) {
19223
- path2 = resolve7(path2);
19535
+ path2 = resolve9(path2);
19224
19536
  await ensurePrivateDirectory3(dirname12(path2));
19225
19537
  try {
19226
19538
  await verifyPrivate2(path2, "file", true);
@@ -19228,7 +19540,7 @@ async function writePrivateAtomic2(path2, bytes, options = {}) {
19228
19540
  if (error.code !== "ENOENT")
19229
19541
  throw error;
19230
19542
  }
19231
- const stage = resolve7(options.stagePath ?? `${path2}.${randomUUID11()}.tmp`);
19543
+ const stage = resolve9(options.stagePath ?? `${path2}.${randomUUID11()}.tmp`);
19232
19544
  if (dirname12(stage) !== dirname12(path2))
19233
19545
  throw new PrivateFileError2(path2, "stage-directory", { code: "EXDEV" });
19234
19546
  let created = false;
@@ -19304,15 +19616,15 @@ function createRedactor2(options = {}) {
19304
19616
  return SECRET_KEY_EXACT2.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
19305
19617
  }
19306
19618
  function errorEntries(error) {
19307
- const fields = error;
19619
+ const fields2 = error;
19308
19620
  const entries = [
19309
19621
  ["name", error.name],
19310
19622
  ["message", error.message],
19311
19623
  ["stack", error.stack]
19312
19624
  ];
19313
19625
  for (const key of ["code", "status", "cause"])
19314
- if (fields[key] !== void 0)
19315
- entries.push([key, fields[key]]);
19626
+ if (fields2[key] !== void 0)
19627
+ entries.push([key, fields2[key]]);
19316
19628
  const listed = new Set(entries.map(([key]) => key));
19317
19629
  for (const entry of Object.entries(error))
19318
19630
  if (!listed.has(entry[0]))
@@ -19413,7 +19725,7 @@ async function openWindowsFile2(sink, file) {
19413
19725
  return sink.handle;
19414
19726
  }
19415
19727
  async function flushWindowsFile2(sink, file, text2) {
19416
- file = resolve8(file);
19728
+ file = resolve10(file);
19417
19729
  try {
19418
19730
  if (sink.file !== file)
19419
19731
  await closeWindowsFile2(sink);
@@ -19550,7 +19862,7 @@ function createEngine2(options) {
19550
19862
  } catch {
19551
19863
  }
19552
19864
  }
19553
- function schedule() {
19865
+ function schedule2() {
19554
19866
  if (!timer)
19555
19867
  timer = setTimeout(() => {
19556
19868
  timer = void 0;
@@ -19592,7 +19904,7 @@ function createEngine2(options) {
19592
19904
  void flushed.catch(() => {
19593
19905
  });
19594
19906
  } else
19595
- schedule();
19907
+ schedule2();
19596
19908
  } catch {
19597
19909
  }
19598
19910
  }
@@ -20151,13 +20463,13 @@ function closeDebugLog() {
20151
20463
  if (!state || !current) return Promise.resolve();
20152
20464
  state.logStream = null;
20153
20465
  if (state.logFilePath) liveLogFilePaths.delete(state.logFilePath);
20154
- return new Promise((resolve13) => {
20155
- current.once("close", () => resolve13());
20156
- current.once("error", () => resolve13());
20466
+ return new Promise((resolve15) => {
20467
+ current.once("close", () => resolve15());
20468
+ current.once("error", () => resolve15());
20157
20469
  try {
20158
20470
  current.end();
20159
20471
  } catch {
20160
- resolve13();
20472
+ resolve15();
20161
20473
  }
20162
20474
  });
20163
20475
  }
@@ -20455,7 +20767,7 @@ var LegacyAccountPoolRetiredError = class extends Error {
20455
20767
  };
20456
20768
  async function assertLegacyPoolInUse(legacyPath) {
20457
20769
  try {
20458
- await assertLegacyAccountStorageWritable(resolve9(legacyPath));
20770
+ await assertLegacyAccountStorageWritable(resolve11(legacyPath));
20459
20771
  } catch (error) {
20460
20772
  throw new LegacyAccountPoolRetiredError(legacyPath, { cause: error });
20461
20773
  }
@@ -20475,7 +20787,7 @@ function refusalMessage(admission) {
20475
20787
  }
20476
20788
  async function bindingOf(options) {
20477
20789
  const now = options.now ?? (() => Date.now());
20478
- const legacyPath = resolve9(options.legacyPath ?? getStoragePath());
20790
+ const legacyPath = resolve11(options.legacyPath ?? getStoragePath());
20479
20791
  return {
20480
20792
  legacyPath,
20481
20793
  now,
@@ -20543,7 +20855,7 @@ async function openAccountStore(options) {
20543
20855
  }
20544
20856
  function initializeFreshAccountStoreFor(modules, options = {}) {
20545
20857
  return initializeFreshAccountStore(modules, {
20546
- legacyPath: resolve9(options.legacyPath ?? getStoragePath()),
20858
+ legacyPath: resolve11(options.legacyPath ?? getStoragePath()),
20547
20859
  now: options.now ?? (() => Date.now())
20548
20860
  });
20549
20861
  }
@@ -20873,14 +21185,14 @@ async function fetchQuotaPayloads(options) {
20873
21185
  };
20874
21186
  }
20875
21187
  function untilQuotaAborted(pending, signal) {
20876
- return new Promise((resolve13, reject) => {
21188
+ return new Promise((resolve15, reject) => {
20877
21189
  const abort = () => reject(signal.reason);
20878
21190
  if (signal.aborted) abort();
20879
21191
  else signal.addEventListener("abort", abort, { once: true });
20880
21192
  void pending.then(
20881
21193
  (value) => {
20882
21194
  signal.removeEventListener("abort", abort);
20883
- resolve13(value);
21195
+ resolve15(value);
20884
21196
  },
20885
21197
  (error) => {
20886
21198
  signal.removeEventListener("abort", abort);
@@ -21162,12 +21474,12 @@ async function startOAuthListener({
21162
21474
  let resolveCallback;
21163
21475
  let rejectCallback;
21164
21476
  let timeoutHandle;
21165
- const callbackPromise = new Promise((resolve13, reject) => {
21477
+ const callbackPromise = new Promise((resolve15, reject) => {
21166
21478
  resolveCallback = (url) => {
21167
21479
  if (settled) return;
21168
21480
  settled = true;
21169
21481
  if (timeoutHandle) clearTimeout(timeoutHandle);
21170
- resolve13(url);
21482
+ resolve15(url);
21171
21483
  };
21172
21484
  rejectCallback = (error) => {
21173
21485
  if (settled) return;
@@ -21326,7 +21638,7 @@ async function startOAuthListener({
21326
21638
  });
21327
21639
  });
21328
21640
  const bindAddress = getBindAddress();
21329
- await new Promise((resolve13, reject) => {
21641
+ await new Promise((resolve15, reject) => {
21330
21642
  const handleError = (error) => {
21331
21643
  server.off("error", handleError);
21332
21644
  if (error.code === "EADDRINUSE") {
@@ -21342,7 +21654,7 @@ async function startOAuthListener({
21342
21654
  server.once("error", handleError);
21343
21655
  server.listen(port, bindAddress, () => {
21344
21656
  server.off("error", handleError);
21345
- resolve13();
21657
+ resolve15();
21346
21658
  });
21347
21659
  });
21348
21660
  server.on("error", (error) => {
@@ -21350,7 +21662,7 @@ async function startOAuthListener({
21350
21662
  });
21351
21663
  return {
21352
21664
  waitForCallback: () => callbackPromise,
21353
- close: () => new Promise((resolve13, reject) => {
21665
+ close: () => new Promise((resolve15, reject) => {
21354
21666
  server.close((error) => {
21355
21667
  if (error && error.code !== "ERR_SERVER_NOT_RUNNING") {
21356
21668
  reject(error);
@@ -21359,7 +21671,7 @@ async function startOAuthListener({
21359
21671
  if (!settled) {
21360
21672
  rejectCallback(new Error("OAuth listener closed before callback"));
21361
21673
  }
21362
- resolve13();
21674
+ resolve15();
21363
21675
  });
21364
21676
  })
21365
21677
  };
@@ -21371,7 +21683,7 @@ async function startOAuthListener({
21371
21683
 
21372
21684
  // src/setup.ts
21373
21685
  import { lstat as lstat5, readFile as readFile10 } from "node:fs/promises";
21374
- import { join as join15, resolve as resolve11 } from "node:path";
21686
+ import { join as join15, resolve as resolve13 } from "node:path";
21375
21687
 
21376
21688
  // src/auth-method-labels.ts
21377
21689
  var OPENCODE2_POOL_AUTH_LABEL = "Google (antigravity-auth pool, browser)";
@@ -21543,7 +21855,7 @@ async function select2(terminal, items, options) {
21543
21855
  writeLine("");
21544
21856
  renderedLines = lines;
21545
21857
  };
21546
- return new Promise((resolve13) => {
21858
+ return new Promise((resolve15) => {
21547
21859
  const wasRaw = stdin.isRaw ?? false;
21548
21860
  const cleanup2 = () => {
21549
21861
  if (cleaned)
@@ -21563,7 +21875,7 @@ async function select2(terminal, items, options) {
21563
21875
  };
21564
21876
  const finish = (value) => {
21565
21877
  cleanup2();
21566
- resolve13(value);
21878
+ resolve15(value);
21567
21879
  };
21568
21880
  const onSignal = () => finish(null);
21569
21881
  const onKey = (data) => {
@@ -21603,7 +21915,7 @@ async function select2(terminal, items, options) {
21603
21915
  stdin.setRawMode(true);
21604
21916
  } catch {
21605
21917
  cleanup2();
21606
- resolve13(null);
21918
+ resolve15(null);
21607
21919
  return;
21608
21920
  }
21609
21921
  stdin.resume();
@@ -21617,7 +21929,7 @@ async function select2(terminal, items, options) {
21617
21929
  import { createHash as createHash9, randomBytes as randomBytes3, randomUUID as randomUUID14 } from "node:crypto";
21618
21930
  import { constants as fsConstants2 } from "node:fs";
21619
21931
  import { chmod as chmod3, mkdir as mkdir12, open as open10, readFile as readFile9, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
21620
- import { basename as basename4, dirname as dirname16, extname as extname2, isAbsolute as isAbsolute3, join as join10, resolve as resolve10 } from "node:path";
21932
+ import { basename as basename4, dirname as dirname16, extname as extname2, isAbsolute as isAbsolute3, join as join10, resolve as resolve12 } from "node:path";
21621
21933
  import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
21622
21934
 
21623
21935
  // src/common-auth-embedded/fs/lock-constants.js
@@ -21682,8 +21994,8 @@ async function acquireRefreshFileLockWithClock2(options) {
21682
21994
  let releaseConfirmed = false;
21683
21995
  let loss;
21684
21996
  let resolveLoss;
21685
- const lostPromise = new Promise((resolve13) => {
21686
- resolveLoss = resolve13;
21997
+ const lostPromise = new Promise((resolve15) => {
21998
+ resolveLoss = resolve15;
21687
21999
  });
21688
22000
  function notifyTimerStep(event) {
21689
22001
  try {
@@ -21840,7 +22152,7 @@ async function acquireRefreshFileLockWithClock2(options) {
21840
22152
  }
21841
22153
  }
21842
22154
  async function backoff() {
21843
- await new Promise((resolve13) => setTimeout(resolve13, Math.floor(Math.random() * 4)));
22155
+ await new Promise((resolve15) => setTimeout(resolve15, Math.floor(Math.random() * 4)));
21844
22156
  }
21845
22157
  async function readLockState(notifyReady = true) {
21846
22158
  if (notifyReady && options.onStep)
@@ -22326,7 +22638,7 @@ function hostEnrollmentPaths2(input) {
22326
22638
  const override = input.override?.trim();
22327
22639
  if (override && !isAbsolute3(override) && !input.cwd)
22328
22640
  throw new ClaustrumConsumerError2("invalid-state", "A relative Claustrum enrollment override needs a base directory");
22329
- const tokenPath = override ? isAbsolute3(override) ? override : resolve10(input.cwd, override) : join10(input.stateDir, `${input.host}-enrollment.json`);
22641
+ const tokenPath = override ? isAbsolute3(override) ? override : resolve12(input.cwd, override) : join10(input.stateDir, `${input.host}-enrollment.json`);
22330
22642
  return getClaustrumEnrollmentPaths2(tokenPath);
22331
22643
  }
22332
22644
  function isRecord9(value) {
@@ -22455,13 +22767,13 @@ async function readBoundedJson2(path2) {
22455
22767
  await descriptor.close();
22456
22768
  }
22457
22769
  }
22458
- function accountRecords2(text2, fields) {
22770
+ function accountRecords2(text2, fields2) {
22459
22771
  const records = [];
22460
22772
  for (const line of text2.split("\n")) {
22461
22773
  if (line.trim() === "" || line.startsWith("#"))
22462
22774
  continue;
22463
22775
  const parts = line.split(":");
22464
- 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] ?? ""))
22776
+ 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] ?? ""))
22465
22777
  return void 0;
22466
22778
  records.push(parts);
22467
22779
  }
@@ -22921,7 +23233,7 @@ var ByteTail = class {
22921
23233
  };
22922
23234
  var defaultCommandRunner = {
22923
23235
  run(file, args, options = {}) {
22924
- return new Promise((resolve13) => {
23236
+ return new Promise((resolve15) => {
22925
23237
  const started = performance.now();
22926
23238
  const timeoutMs = options.timeoutMs ?? 15e3;
22927
23239
  const stderr = new ByteTail();
@@ -22939,7 +23251,7 @@ var defaultCommandRunner = {
22939
23251
  stdio: ["ignore", "pipe", "pipe"]
22940
23252
  });
22941
23253
  } catch {
22942
- resolve13({
23254
+ resolve15({
22943
23255
  exitCode: 1,
22944
23256
  stdout: "",
22945
23257
  stderr: "",
@@ -22974,7 +23286,7 @@ var defaultCommandRunner = {
22974
23286
  settled = true;
22975
23287
  if (timer)
22976
23288
  clearTimeout(timer);
22977
- resolve13({
23289
+ resolve15({
22978
23290
  exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
22979
23291
  stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
22980
23292
  stderr: stderr.toString(),
@@ -23403,6 +23715,7 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);
23403
23715
  };
23404
23716
  async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
23405
23717
  const windows = (options.platform ?? process.platform) === "win32";
23718
+ const selfPid = options.selfPid ?? process.pid;
23406
23719
  let inspection = {
23407
23720
  step: windows ? "tasklist" : "ps",
23408
23721
  exitCode: null,
@@ -23471,7 +23784,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
23471
23784
  }
23472
23785
  if (!processes.length)
23473
23786
  throw new ProcessInspectionError(inspection);
23474
- const runtimes = processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command));
23787
+ const runtimes = processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command));
23475
23788
  if (windows && runtimes.length && options.inspectRuntimes !== false) {
23476
23789
  const details = await inspect("CIM", "powershell.exe", [
23477
23790
  "-NoProfile",
@@ -23504,7 +23817,8 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
23504
23817
  }
23505
23818
  }
23506
23819
  function createProcessFence(runner = defaultCommandRunner, options = {}) {
23507
- const isHost = (entry) => entry.pid !== process.pid && hostName(entry.command) !== null;
23820
+ const selfPid = options.selfPid ?? process.pid;
23821
+ const isHost = (entry) => entry.pid !== selfPid && hostName(entry.command) !== null;
23508
23822
  return {
23509
23823
  async listRunningHosts(env3) {
23510
23824
  return (await listSetupProcesses(runner, { ...options, env: env3 })).filter(isHost);
@@ -23518,7 +23832,7 @@ function createProcessFence(runner = defaultCommandRunner, options = {}) {
23518
23832
  const windows = (options.platform ?? process.platform) === "win32";
23519
23833
  return {
23520
23834
  hosts: processes.filter(isHost),
23521
- uncheckedRuntimes: windows ? processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
23835
+ uncheckedRuntimes: windows ? processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
23522
23836
  };
23523
23837
  }
23524
23838
  };
@@ -24100,7 +24414,7 @@ async function writeNativeSlot(host, slot, context, expectedAuthority = "local")
24100
24414
  beforeRename: async () => {
24101
24415
  await assertSetupHostsStopped();
24102
24416
  const claustrum = await loadCommonAuthClaustrum();
24103
- const stateDir = host === "opencode" ? openCodeVaultPaths(resolve11(getStoragePath())).dir : getPiAntigravityVaultDir();
24417
+ const stateDir = host === "opencode" ? openCodeVaultPaths(resolve13(getStoragePath())).dir : getPiAntigravityVaultDir();
24104
24418
  if (await claustrum.enrollmentAuthority(
24105
24419
  claustrum.hostEnrollmentPaths({ stateDir, host }),
24106
24420
  `antigravity-auth-${host}`
@@ -24130,7 +24444,7 @@ async function persistPiSetupLogin(result, context) {
24130
24444
  }
24131
24445
  async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
24132
24446
  const claustrum = await loadCommonAuthClaustrum();
24133
- const opencode = openCodeVaultPaths(resolve11(getStoragePath()));
24447
+ const opencode = openCodeVaultPaths(resolve13(getStoragePath()));
24134
24448
  const piDir = getPiAntigravityVaultDir();
24135
24449
  const hosts = {
24136
24450
  opencode: {
@@ -24149,7 +24463,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
24149
24463
  const assertLocal = async (host, context) => {
24150
24464
  if (host === "opencode")
24151
24465
  return assertLocalOpenCodeLogin(
24152
- resolve11(getStoragePath()),
24466
+ resolve13(getStoragePath()),
24153
24467
  context.opencodeGeneration
24154
24468
  );
24155
24469
  if (await authority(host) !== "local")
@@ -24681,7 +24995,7 @@ function createDefaultCliDependencies() {
24681
24995
  throw new Error(
24682
24996
  "Pi setup requires its detected native agent directory."
24683
24997
  );
24684
- const legacyPath = resolve12(getStoragePath());
24998
+ const legacyPath = resolve14(getStoragePath());
24685
24999
  const repository = host === "pi" ? void 0 : await prepareCliLoginStore(legacyPath, context?.opencodeGeneration);
24686
25000
  try {
24687
25001
  return await performOAuthLogin(request, {
@@ -24841,7 +25155,7 @@ async function readAccountStore(legacyPath) {
24841
25155
  function createDefaultAccountStoreOperations() {
24842
25156
  const offline = { processesStopped: true };
24843
25157
  return {
24844
- legacyPath: () => resolve12(getStoragePath()),
25158
+ legacyPath: () => resolve14(getStoragePath()),
24845
25159
  migrate: async (legacyPath) => createAccountMigrationFactory(await loadCommonAuthStoreModules())({
24846
25160
  legacyPath,
24847
25161
  offline,