@cortexkit/opencode-antigravity-auth 3.0.7 → 3.0.9

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 (147) hide show
  1. package/dist/cli.js +1097 -78
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +128 -36
  4. package/dist/index.js +1523 -285
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +183 -64
  7. package/dist/server.js +1448 -189
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/auth-menu/login.d.ts +6 -10
  11. package/dist/src/common-auth-embedded/auth-menu/login.js +14 -11
  12. package/dist/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  13. package/dist/src/common-auth-embedded/claustrum/availability.js +106 -0
  14. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +36 -2
  15. package/dist/src/common-auth-embedded/claustrum/consumer.js +154 -6
  16. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +106 -14
  17. package/dist/src/common-auth-embedded/claustrum/custody.js +294 -16
  18. package/dist/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  19. package/dist/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  20. package/dist/src/common-auth-embedded/claustrum/index.js +4 -1
  21. package/dist/src/common-auth-embedded/claustrum/insula.d.ts +71 -0
  22. package/dist/src/common-auth-embedded/claustrum/insula.js +348 -21
  23. package/dist/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  24. package/dist/src/common-auth-embedded/claustrum/watch.js +254 -0
  25. package/dist/src/common-auth-embedded/fs/private-files.js +10 -2
  26. package/dist/src/common-auth-embedded/quota/format.d.ts +3 -0
  27. package/dist/src/common-auth-embedded/quota/format.js +69 -1
  28. package/dist/src/common-auth-embedded/quota/index.d.ts +1 -1
  29. package/dist/src/common-auth-embedded/quota/projection.d.ts +16 -0
  30. package/dist/src/common-auth-embedded/source-output.json +87 -55
  31. package/dist/src/ga/server/index.d.ts +2 -0
  32. package/dist/src/ga/server/index.d.ts.map +1 -1
  33. package/dist/src/ga/server/index.js +14 -1
  34. package/dist/src/ga/server/index.js.map +1 -1
  35. package/dist/src/plugin/auth-loader.d.ts +2 -1
  36. package/dist/src/plugin/auth-loader.d.ts.map +1 -1
  37. package/dist/src/plugin/auth-loader.js +5 -4
  38. package/dist/src/plugin/auth-loader.js.map +1 -1
  39. package/dist/src/plugin/background-vault-quota-refresh.d.ts.map +1 -1
  40. package/dist/src/plugin/background-vault-quota-refresh.js +8 -1
  41. package/dist/src/plugin/background-vault-quota-refresh.js.map +1 -1
  42. package/dist/src/plugin/fetch-interceptor.d.ts +2 -1
  43. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  44. package/dist/src/plugin/fetch-interceptor.js +8 -6
  45. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  46. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  47. package/dist/src/plugin/ga-location-services.js +3 -0
  48. package/dist/src/plugin/ga-location-services.js.map +1 -1
  49. package/dist/src/plugin/index.d.ts.map +1 -1
  50. package/dist/src/plugin/index.js +1 -0
  51. package/dist/src/plugin/index.js.map +1 -1
  52. package/dist/src/plugin/quota.d.ts +1 -1
  53. package/dist/src/plugin/quota.d.ts.map +1 -1
  54. package/dist/src/plugin/quota.js +17 -5
  55. package/dist/src/plugin/quota.js.map +1 -1
  56. package/dist/src/plugin/shared/after-handoff.d.ts +14 -0
  57. package/dist/src/plugin/shared/after-handoff.d.ts.map +1 -0
  58. package/dist/src/plugin/shared/after-handoff.js +89 -0
  59. package/dist/src/plugin/shared/after-handoff.js.map +1 -0
  60. package/dist/src/plugin/shared/request-services.d.ts +8 -2
  61. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  62. package/dist/src/plugin/shared/request-services.js +57 -36
  63. package/dist/src/plugin/shared/request-services.js.map +1 -1
  64. package/dist/src/plugin/shared/vault-request-credentials.d.ts +11 -8
  65. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  66. package/dist/src/plugin/shared/vault-request-credentials.js +23 -5
  67. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  68. package/dist/src/plugin/vault-custody.d.ts +4 -0
  69. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  70. package/dist/src/plugin/vault-custody.js +12 -0
  71. package/dist/src/plugin/vault-custody.js.map +1 -1
  72. package/dist/src/plugin/vault-insula-quota.d.ts +6 -0
  73. package/dist/src/plugin/vault-insula-quota.d.ts.map +1 -0
  74. package/dist/src/plugin/vault-insula-quota.js +50 -0
  75. package/dist/src/plugin/vault-insula-quota.js.map +1 -0
  76. package/dist/src/plugin/vault-quota-outcome.d.ts +1 -1
  77. package/dist/src/plugin/vault-quota-outcome.d.ts.map +1 -1
  78. package/dist/src/plugin/vault-quota-outcome.js.map +1 -1
  79. package/dist/src/tui.d.ts.map +1 -1
  80. package/dist/src/tui.js +82 -66
  81. package/dist/src/tui.js.map +1 -1
  82. package/dist/tui-build-map.json +27 -27
  83. package/dist/tui-ga-build-map.json +5 -5
  84. package/dist/types/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  85. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +36 -2
  86. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +106 -14
  87. package/dist/types/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  88. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  89. package/dist/types/src/common-auth-embedded/claustrum/insula.d.ts +71 -0
  90. package/dist/types/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  91. package/dist/types/src/common-auth-embedded/quota/format.d.ts +3 -0
  92. package/dist/types/src/common-auth-embedded/quota/index.d.ts +1 -1
  93. package/dist/types/src/common-auth-embedded/quota/projection.d.ts +16 -0
  94. package/dist/types/src/ga/server/index.d.ts +2 -0
  95. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  96. package/dist/types/src/plugin/auth-loader.d.ts +2 -1
  97. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  98. package/dist/types/src/plugin/background-vault-quota-refresh.d.ts.map +1 -1
  99. package/dist/types/src/plugin/fetch-interceptor.d.ts +2 -1
  100. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  101. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  102. package/dist/types/src/plugin/index.d.ts.map +1 -1
  103. package/dist/types/src/plugin/quota.d.ts +1 -1
  104. package/dist/types/src/plugin/quota.d.ts.map +1 -1
  105. package/dist/types/src/plugin/shared/after-handoff.d.ts +14 -0
  106. package/dist/types/src/plugin/shared/after-handoff.d.ts.map +1 -0
  107. package/dist/types/src/plugin/shared/request-services.d.ts +8 -2
  108. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  109. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +11 -8
  110. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  111. package/dist/types/src/plugin/vault-custody.d.ts +4 -0
  112. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  113. package/dist/types/src/plugin/vault-insula-quota.d.ts +6 -0
  114. package/dist/types/src/plugin/vault-insula-quota.d.ts.map +1 -0
  115. package/dist/types/src/plugin/vault-quota-outcome.d.ts +1 -1
  116. package/dist/types/src/plugin/vault-quota-outcome.d.ts.map +1 -1
  117. package/package.json +4 -4
  118. package/src/common-auth-embedded/auth-menu/login.d.ts +6 -10
  119. package/src/common-auth-embedded/auth-menu/login.js +14 -11
  120. package/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  121. package/src/common-auth-embedded/claustrum/availability.js +106 -0
  122. package/src/common-auth-embedded/claustrum/consumer.d.ts +36 -2
  123. package/src/common-auth-embedded/claustrum/consumer.js +154 -6
  124. package/src/common-auth-embedded/claustrum/custody.d.ts +106 -14
  125. package/src/common-auth-embedded/claustrum/custody.js +294 -16
  126. package/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  127. package/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  128. package/src/common-auth-embedded/claustrum/index.js +4 -1
  129. package/src/common-auth-embedded/claustrum/insula.d.ts +71 -0
  130. package/src/common-auth-embedded/claustrum/insula.js +348 -21
  131. package/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  132. package/src/common-auth-embedded/claustrum/watch.js +254 -0
  133. package/src/common-auth-embedded/fs/private-files.js +10 -2
  134. package/src/common-auth-embedded/quota/format.d.ts +3 -0
  135. package/src/common-auth-embedded/quota/format.js +69 -1
  136. package/src/common-auth-embedded/quota/index.d.ts +1 -1
  137. package/src/common-auth-embedded/quota/projection.d.ts +16 -0
  138. package/src/common-auth-embedded/source-output.json +87 -55
  139. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +10 -2
  140. package/src/tui-compiled/common-auth-embedded/quota/format.js +69 -1
  141. package/src/tui-compiled/tui.js +123 -97
  142. package/src/tui-ga-compiled/shared/aef2402f8fc342f0-format.js +69 -1
  143. package/src/tui-ga-raw/shared/aef2402f8fc342f0-format.js +69 -1
  144. package/src/tui-raw/common-auth-embedded/fs/private-files.js +10 -2
  145. package/src/tui-raw/common-auth-embedded/quota/format.js +69 -1
  146. package/src/tui-raw/tui.tsx +126 -107
  147. package/src/tui.tsx +126 -107
package/dist/server.js CHANGED
@@ -323,8 +323,8 @@ function displayOrder(left, right) {
323
323
  return left.label < right.label ? -1 : left.label > right.label ? 1 : 0;
324
324
  }
325
325
  function quotaWindowParts(quota, options) {
326
- const { windows, age } = scopedWindowParts(quota, options);
327
- const parts = windows.map(({ part }) => part);
326
+ const { windows: windows2, age } = scopedWindowParts(quota, options);
327
+ const parts = windows2.map(({ part }) => part);
328
328
  return age === void 0 ? { windows: parts } : { windows: parts, age };
329
329
  }
330
330
  function scopedWindowParts(quota, options) {
@@ -332,10 +332,11 @@ function scopedWindowParts(quota, options) {
332
332
  return { windows: [] };
333
333
  const { now } = options;
334
334
  const readings = quota.limits.filter((limit) => limit.kind === "reading" && limit.remainingPercent !== void 0).sort(displayOrder);
335
- const windows = readings.map((limit) => {
335
+ const windows2 = readings.map((limit) => {
336
336
  const remainingPercent = clampPercent(limit.remainingPercent ?? 0);
337
337
  return {
338
338
  scope: limit.scope,
339
+ ...limit.windowMinutes === void 0 ? {} : { windowMinutes: limit.windowMinutes },
339
340
  part: {
340
341
  kind: "window",
341
342
  name: quotaWindowName(limit),
@@ -350,7 +351,7 @@ function scopedWindowParts(quota, options) {
350
351
  if (budget) {
351
352
  const remainingPercent = budget.remainingPercent;
352
353
  const figure = budget.reached ? "credits spent" : remainingPercent !== void 0 ? `credits ${percentLeft(remainingPercent)}` : "credits available";
353
- windows.push({
354
+ windows2.push({
354
355
  scope: ALL_SCOPE,
355
356
  spent: budget.reached,
356
357
  part: {
@@ -363,13 +364,13 @@ function scopedWindowParts(quota, options) {
363
364
  }
364
365
  });
365
366
  }
366
- if (windows.length > 0) {
367
- const age = now - Math.min(...windows.map(({ part }) => part.checkedAt));
367
+ if (windows2.length > 0) {
368
+ const age = now - Math.min(...windows2.map(({ part }) => part.checkedAt));
368
369
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
369
- return { windows, age: `checked ${shortSpan(age)} ago` };
370
+ return { windows: windows2, age: `checked ${shortSpan(age)} ago` };
370
371
  }
371
372
  }
372
- return { windows };
373
+ return { windows: windows2 };
373
374
  }
374
375
  function isQuotaStale(quota, options) {
375
376
  return scopedWindowParts(quota, options).age !== void 0;
@@ -404,12 +405,46 @@ function scopeAbbreviations(scopes) {
404
405
  }
405
406
  return new Map(scopes.map((scope) => [scope, short(scopeDisplayName(scope))]));
406
407
  }
408
+ function groupShortNames(groups) {
409
+ const labels = groups.map((group) => group.label.trim() || group.scope);
410
+ const short = scopeAbbreviations(labels);
411
+ return labels.map((label) => short.get(label) ?? label);
412
+ }
413
+ function groupedNarrowPieces(groups, windows2) {
414
+ if (!groups || groups.length === 0)
415
+ return void 0;
416
+ const reported = windows2.filter(({ part }) => part.kind === "window");
417
+ if (reported.some(({ scope }) => scope === ALL_SCOPE))
418
+ return void 0;
419
+ const candidates = groups.flatMap((group, listed) => {
420
+ const inGroup = reported.filter(({ scope }) => scope === group.scope);
421
+ const groupTightest = inGroup.reduce((least, window) => least === void 0 || (window.part.remainingPercent ?? 0) < (least.part.remainingPercent ?? 0) ? window : least, void 0);
422
+ return groupTightest ? [{ group, listed, window: groupTightest }] : [];
423
+ });
424
+ if (candidates.length === 0)
425
+ return void 0;
426
+ const names = groupShortNames(groups);
427
+ const left = (candidate) => candidate.window.part.remainingPercent ?? 0;
428
+ const shown = [...candidates].sort((a, b) => left(a) - left(b) || a.listed - b.listed).slice(0, NARROW_GROUP_LIMIT).sort((a, b) => a.listed - b.listed);
429
+ return shown.map((candidate, index) => {
430
+ const { windowMinutes } = candidate.window;
431
+ const piece = [
432
+ names[candidate.listed] ?? candidate.group.scope,
433
+ ...windowMinutes === void 0 ? [] : [lengthName(windowMinutes)],
434
+ `${wholePercent(left(candidate))}%`
435
+ ].join(" ");
436
+ return index === shown.length - 1 ? `${piece} left` : piece;
437
+ });
438
+ }
407
439
  function narrowTextParts(quota, options) {
408
- const { windows } = scopedWindowParts(quota, options);
409
- const general = windows.filter(({ part, scope }) => part.kind === "window" && scope === ALL_SCOPE);
410
- const scoped = windows.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE);
440
+ const { windows: windows2 } = scopedWindowParts(quota, options);
441
+ const grouped = groupedNarrowPieces(quota?.groups, windows2);
442
+ if (grouped)
443
+ return grouped;
444
+ const general = windows2.filter(({ part, scope }) => part.kind === "window" && scope === ALL_SCOPE);
445
+ const scoped = windows2.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE);
411
446
  const abbreviations = scopeAbbreviations(scoped.map(({ scope }) => scope));
412
- const budget = windows.find(({ part }) => part.kind === "budget");
447
+ const budget = windows2.find(({ part }) => part.kind === "budget");
413
448
  const budgetLeft = budget?.spent ? 0 : budget?.part.remainingPercent;
414
449
  const extras = [
415
450
  ...scoped.map(({ scope, part }) => ({
@@ -424,7 +459,7 @@ function narrowTextParts(quota, options) {
424
459
  pieces.push(`${tightest.label} ${wholePercent(tightest.remaining)}%`);
425
460
  }
426
461
  if (pieces.length === 0)
427
- return windows.map(({ part }) => part.figure);
462
+ return windows2.map(({ part }) => part.figure);
428
463
  return pieces.map((piece, index) => index === pieces.length - 1 ? `${piece} left` : piece);
429
464
  }
430
465
  function quotaTextParts(quota, options) {
@@ -444,7 +479,7 @@ function formatQuota(quota, options) {
444
479
  return parts.join(" \xB7 ");
445
480
  return quota && quota.limits.length > 0 ? NO_LIMITS_REPORTED : NO_QUOTA_READING;
446
481
  }
447
- var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED;
482
+ var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED, NARROW_GROUP_LIMIT;
448
483
  var init_format = __esm({
449
484
  "../core/dist/common-auth-embedded/quota/format.js"() {
450
485
  "use strict";
@@ -452,6 +487,7 @@ var init_format = __esm({
452
487
  QUOTA_STALE_AFTER_MS = 15 * 6e4;
453
488
  NO_QUOTA_READING = "no quota reading yet";
454
489
  NO_LIMITS_REPORTED = "no limits reported";
490
+ NARROW_GROUP_LIMIT = 2;
455
491
  }
456
492
  });
457
493
 
@@ -813,19 +849,24 @@ async function replaceWindowsFile(from, to, options = {}) {
813
849
  to = resolve2(to);
814
850
  const now = options.now ?? (() => performance.now());
815
851
  const start = now();
816
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
852
+ const leaseDeadline = options.deadline ?? Infinity;
853
+ let retryDeadline;
817
854
  const delays = [0, 10, 20, 40, 80, 100];
818
855
  let original;
819
856
  let attempts2 = 0;
820
857
  for (const delay3 of delays) {
858
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
821
859
  if (now() >= deadline)
822
860
  break;
823
861
  if (delay3)
824
862
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
825
863
  if (now() >= deadline)
826
864
  break;
865
+ const fenceStart = now();
827
866
  await options.beforeRename?.();
828
- if (now() >= deadline)
867
+ if (retryDeadline !== void 0)
868
+ retryDeadline += now() - fenceStart;
869
+ if (now() >= leaseDeadline)
829
870
  break;
830
871
  attempts2++;
831
872
  try {
@@ -837,6 +878,7 @@ async function replaceWindowsFile(from, to, options = {}) {
837
878
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
838
879
  if (!candidate)
839
880
  break;
881
+ retryDeadline ??= now() + 500;
840
882
  }
841
883
  }
842
884
  const error = new PrivateFileError(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -7185,12 +7227,12 @@ var init_doctor = __esm({
7185
7227
  });
7186
7228
 
7187
7229
  // ../core/dist/common-auth-embedded/auth-menu/login.js
7188
- import { execFileSync as defaultExecFileSync, spawn as defaultSpawn } from "node:child_process";
7189
- function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn2 = defaultSpawn) {
7230
+ import { spawn as defaultSpawn } from "node:child_process";
7231
+ function openBrowserForMenu(url, platform = process.platform, spawn2 = defaultSpawn) {
7190
7232
  try {
7191
7233
  if (platform === "win32") {
7192
7234
  const command = `Start-Process '${url.replaceAll("'", "''")}'`;
7193
- const child = spawn2("powershell.exe", [
7235
+ const child2 = spawn2("powershell.exe", [
7194
7236
  "-NoProfile",
7195
7237
  "-NonInteractive",
7196
7238
  "-WindowStyle",
@@ -7198,17 +7240,18 @@ function openBrowserForMenu(url, platform = process.platform, execFileSync = def
7198
7240
  "-EncodedCommand",
7199
7241
  Buffer.from(command, "utf16le").toString("base64")
7200
7242
  ], { stdio: "ignore", windowsHide: true });
7201
- child.on("error", () => {
7202
- });
7203
- child.unref();
7204
- return child.pid !== void 0;
7205
- } else {
7206
- execFileSync(platform === "darwin" ? "open" : "xdg-open", [url], {
7207
- stdio: "ignore",
7208
- timeout: 3e3
7243
+ child2.on("error", () => {
7209
7244
  });
7245
+ child2.unref();
7246
+ return child2.pid !== void 0;
7210
7247
  }
7211
- return true;
7248
+ const child = spawn2(platform === "darwin" ? "open" : "xdg-open", [url], {
7249
+ stdio: "ignore"
7250
+ });
7251
+ child.on("error", () => {
7252
+ });
7253
+ child.unref();
7254
+ return child.pid !== void 0;
7212
7255
  } catch {
7213
7256
  return false;
7214
7257
  }
@@ -8011,6 +8054,326 @@ var init_auth_menu = __esm({
8011
8054
  }
8012
8055
  });
8013
8056
 
8057
+ // ../core/dist/common-auth-embedded/claustrum/errors.js
8058
+ var ClaustrumConsumerError;
8059
+ var init_errors2 = __esm({
8060
+ "../core/dist/common-auth-embedded/claustrum/errors.js"() {
8061
+ "use strict";
8062
+ ClaustrumConsumerError = class extends Error {
8063
+ kind;
8064
+ constructor(kind, message) {
8065
+ super(message);
8066
+ this.name = "ClaustrumConsumerError";
8067
+ this.kind = kind;
8068
+ }
8069
+ };
8070
+ }
8071
+ });
8072
+
8073
+ // ../core/dist/common-auth-embedded/claustrum/availability.js
8074
+ import { ClaustrumCredentialError } from "@cortexkit/claustrum-client";
8075
+ import { SocketClosedError, SocketTimeoutError, SubcCallError } from "@cortexkit/subc-client";
8076
+ function classifyVaultFailure(error) {
8077
+ if (error instanceof ClaustrumUnreachableError || error instanceof SocketClosedError || error instanceof SocketTimeoutError)
8078
+ return "unreachable";
8079
+ const code2 = error instanceof ClaustrumCredentialError || error instanceof SubcCallError ? error.code : error instanceof Error && "code" in error ? error.code : void 0;
8080
+ if (typeof code2 !== "string" || !Object.hasOwn(VAULT_FAILURE_CLASSES, code2))
8081
+ return "answered";
8082
+ return VAULT_FAILURE_CLASSES[code2];
8083
+ }
8084
+ var VAULT_FAILURE_CLASSES, ClaustrumUnreachableError;
8085
+ var init_availability = __esm({
8086
+ "../core/dist/common-auth-embedded/claustrum/availability.js"() {
8087
+ "use strict";
8088
+ init_errors2();
8089
+ VAULT_FAILURE_CLASSES = Object.freeze({
8090
+ ECONNREFUSED: "unreachable",
8091
+ ENOENT: "unreachable",
8092
+ ECONNRESET: "unreachable",
8093
+ EPIPE: "unreachable",
8094
+ ETIMEDOUT: "unreachable",
8095
+ transport_error: "unreachable",
8096
+ unavailable: "unreachable",
8097
+ timeout: "unreachable",
8098
+ route_closed: "unreachable",
8099
+ daemon_draining: "unreachable",
8100
+ connection_closed: "unreachable",
8101
+ connection_dropped: "unreachable",
8102
+ request_deadline: "unreachable",
8103
+ deadline_exceeded_no_drop_observed: "unreachable",
8104
+ module_reloading: "unreachable",
8105
+ module_warming: "unreachable",
8106
+ target_unavailable: "unreachable",
8107
+ module_timeout: "unreachable",
8108
+ invalid_response: "answered",
8109
+ invalid_record_version: "answered",
8110
+ invalid_expiry: "answered",
8111
+ invalid_status: "answered",
8112
+ invalid_params: "answered",
8113
+ ttl_unsatisfiable: "answered",
8114
+ not_found: "answered",
8115
+ enrollment_revoked: "answered",
8116
+ enrollment_invalid: "answered",
8117
+ grant_denied: "answered",
8118
+ credential_unavailable: "answered",
8119
+ needs_reauth: "answered",
8120
+ declined: "answered",
8121
+ disabled: "answered",
8122
+ identity_changed: "answered",
8123
+ closed: "answered",
8124
+ client_closed: "answered",
8125
+ pending_exists: "answered",
8126
+ pending_queue_full: "answered",
8127
+ already_consumed: "answered",
8128
+ superseded: "answered",
8129
+ stale_generation: "answered",
8130
+ missing_identity: "answered",
8131
+ invalid_control_body: "answered",
8132
+ unknown_module: "answered",
8133
+ module_removed: "answered",
8134
+ capability_denied: "answered",
8135
+ unknown_channel: "unreachable",
8136
+ stale_route_epoch: "unreachable",
8137
+ capability_forbidden: "answered",
8138
+ capability_unprovided: "answered",
8139
+ capability_ambiguous: "answered",
8140
+ invalid_capability_identifier: "answered",
8141
+ binary_body_required: "answered",
8142
+ binary_call_requires_call_binary: "answered",
8143
+ corr_exhausted: "answered",
8144
+ late_route_cleanup_failed: "answered",
8145
+ reverse_request_capability_not_declared: "answered",
8146
+ stale_route_handle: "answered",
8147
+ reverse_request_unhandled: "answered",
8148
+ handler_error: "answered",
8149
+ health_error: "answered",
8150
+ duplicate_module_id: "answered",
8151
+ route_rejected: "answered",
8152
+ lock_busy: "answered",
8153
+ owner_invalid: "answered",
8154
+ renewal_failed: "answered",
8155
+ unsupported_platform: "answered",
8156
+ EACCES: "answered",
8157
+ EPERM: "answered",
8158
+ ERR_PRIVATE_FILES_SECURITY: "answered"
8159
+ });
8160
+ ClaustrumUnreachableError = class extends ClaustrumConsumerError {
8161
+ constructor() {
8162
+ super("unavailable", "Claustrum scoped operation unavailable");
8163
+ this.name = "ClaustrumUnreachableError";
8164
+ }
8165
+ };
8166
+ }
8167
+ });
8168
+
8169
+ // ../core/dist/common-auth-embedded/claustrum/watch.js
8170
+ var SAFETY_POLL_MS, WATCH_RETRY_MS, RESUBSCRIBE_BACKOFF_MS, ChangeNoticeReader, CoalescedRead, ScopedRosterWatch;
8171
+ var init_watch = __esm({
8172
+ "../core/dist/common-auth-embedded/claustrum/watch.js"() {
8173
+ "use strict";
8174
+ SAFETY_POLL_MS = 5 * 6e4;
8175
+ WATCH_RETRY_MS = 5 * 6e4;
8176
+ RESUBSCRIBE_BACKOFF_MS = 1e3;
8177
+ ChangeNoticeReader = class {
8178
+ #epoch;
8179
+ #seq = 0;
8180
+ /**
8181
+ * Begin a new watch, whose first notice is seq 1 again. The epoch is kept,
8182
+ * so a module restart between two watches still reads as a break.
8183
+ */
8184
+ restart() {
8185
+ this.#seq = 0;
8186
+ }
8187
+ continuous(notice) {
8188
+ const continuous = notice.kind === "changed" && notice.seq === this.#seq + 1 && (this.#epoch === void 0 || notice.epoch === this.#epoch);
8189
+ this.#epoch = notice.epoch;
8190
+ this.#seq = notice.seq;
8191
+ return continuous;
8192
+ }
8193
+ };
8194
+ CoalescedRead = class {
8195
+ #read;
8196
+ #onError;
8197
+ #running;
8198
+ #queued = false;
8199
+ constructor(read, onError) {
8200
+ this.#read = read;
8201
+ this.#onError = onError;
8202
+ }
8203
+ /** The read in flight (including its queued follow-up), if any. */
8204
+ get running() {
8205
+ return this.#running;
8206
+ }
8207
+ request() {
8208
+ if (this.#running) {
8209
+ this.#queued = true;
8210
+ return this.#running;
8211
+ }
8212
+ this.#running = (async () => {
8213
+ do {
8214
+ this.#queued = false;
8215
+ try {
8216
+ await this.#read();
8217
+ } catch (error) {
8218
+ this.#onError(error);
8219
+ }
8220
+ } while (this.#queued);
8221
+ })().finally(() => {
8222
+ this.#running = void 0;
8223
+ });
8224
+ return this.#running;
8225
+ }
8226
+ };
8227
+ ScopedRosterWatch = class {
8228
+ #options;
8229
+ #reader = new ChangeNoticeReader();
8230
+ #reads;
8231
+ #mode = "polling";
8232
+ #watch;
8233
+ #timer;
8234
+ #stopped = false;
8235
+ #latestView;
8236
+ #force = false;
8237
+ /**
8238
+ * How many accepted watches in a row have closed; each one doubles the wait
8239
+ * before the next re-subscribe. Reset once a watch stays up five minutes.
8240
+ */
8241
+ #closes = 0;
8242
+ constructor(options) {
8243
+ this.#options = options;
8244
+ this.#reads = new CoalescedRead(async () => {
8245
+ const force = this.#force;
8246
+ this.#force = false;
8247
+ if (force || this.#latestView !== this.#options.view())
8248
+ await this.#options.discover(this.#latestView ?? "");
8249
+ }, (error) => {
8250
+ if (!this.#stopped)
8251
+ this.#options.onError?.(error);
8252
+ });
8253
+ }
8254
+ get mode() {
8255
+ return this.#mode;
8256
+ }
8257
+ start() {
8258
+ if (this.#stopped || this.#watch || this.#timer)
8259
+ return;
8260
+ if (typeof this.#options.client.watchScoped !== "function") {
8261
+ this.#setMode("fallback", "client-without-watch");
8262
+ return;
8263
+ }
8264
+ void this.#open(false);
8265
+ }
8266
+ stop() {
8267
+ if (this.#stopped)
8268
+ return;
8269
+ this.#stopped = true;
8270
+ if (this.#timer)
8271
+ (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
8272
+ this.#timer = void 0;
8273
+ const watch = this.#watch;
8274
+ this.#watch = void 0;
8275
+ watch?.handle.stop();
8276
+ }
8277
+ #setMode(mode, reason) {
8278
+ if (this.#mode === mode)
8279
+ return;
8280
+ this.#mode = mode;
8281
+ this.#options.logger?.debug("claustrum vault watch", { mode, reason });
8282
+ this.#options.onMode?.(mode);
8283
+ }
8284
+ #later(delay3, run) {
8285
+ this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
8286
+ this.#timer = void 0;
8287
+ if (!this.#stopped)
8288
+ run();
8289
+ }, delay3);
8290
+ this.#timer.unref?.();
8291
+ }
8292
+ async #open(resubscribed) {
8293
+ let token;
8294
+ try {
8295
+ token = await this.#options.enrollmentToken();
8296
+ } catch (error) {
8297
+ if (this.#stopped)
8298
+ return;
8299
+ this.#options.onError?.(error);
8300
+ this.#fallback("token-unreadable");
8301
+ return;
8302
+ }
8303
+ const watchScoped = this.#options.client.watchScoped;
8304
+ if (this.#stopped || this.#watch || !watchScoped)
8305
+ return;
8306
+ this.#reader.restart();
8307
+ this.#force = resubscribed;
8308
+ let watch;
8309
+ let handle;
8310
+ try {
8311
+ handle = watchScoped.call(this.#options.client, (notice) => {
8312
+ if (this.#stopped || !watch || this.#watch !== watch)
8313
+ return;
8314
+ watch.notices++;
8315
+ if (watch.notices === 1) {
8316
+ this.#options.onReachable?.();
8317
+ watch.acceptedAt = (this.#options.now ?? Date.now)();
8318
+ this.#setMode("watching", "accepted");
8319
+ }
8320
+ if (!this.#reader.continuous(notice))
8321
+ this.#force = true;
8322
+ this.#latestView = notice.view;
8323
+ void this.#reads.request();
8324
+ }, { enrollmentToken: token });
8325
+ } catch (error) {
8326
+ this.#options.onError?.(error);
8327
+ this.#fallback("watch-failed");
8328
+ return;
8329
+ }
8330
+ watch = { handle, notices: 0 };
8331
+ this.#watch = watch;
8332
+ this.#setMode("polling", resubscribed ? "resubscribing" : "opening");
8333
+ const opened = watch;
8334
+ handle.closed.then((end) => this.#closed(opened, end), (error) => this.#closed(opened, { kind: "transport_lost", error }));
8335
+ }
8336
+ #closed(watch, end) {
8337
+ if (this.#stopped || this.#watch !== watch)
8338
+ return;
8339
+ this.#watch = void 0;
8340
+ if (end.kind === "stopped")
8341
+ return;
8342
+ if (end.kind === "transport_lost")
8343
+ this.#options.onTransportLost?.();
8344
+ if (end.kind === "unsupported") {
8345
+ this.#setMode("fallback", "vault-without-watch");
8346
+ return;
8347
+ }
8348
+ if (end.kind === "refused") {
8349
+ this.#fallback("refused");
8350
+ try {
8351
+ this.#options.onRefused(end.error);
8352
+ } catch (error) {
8353
+ this.#options.onError?.(error);
8354
+ }
8355
+ return;
8356
+ }
8357
+ if (watch.notices > 0) {
8358
+ const now = (this.#options.now ?? Date.now)();
8359
+ if (watch.acceptedAt !== void 0 && now - watch.acceptedAt >= SAFETY_POLL_MS)
8360
+ this.#closes = 0;
8361
+ const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
8362
+ this.#closes++;
8363
+ this.#setMode("polling", "resubscribing");
8364
+ this.#later(delay3, () => void this.#open(true));
8365
+ return;
8366
+ }
8367
+ this.#fallback(end.kind);
8368
+ }
8369
+ #fallback(reason) {
8370
+ this.#setMode("fallback", reason);
8371
+ this.#later(WATCH_RETRY_MS, () => void this.#open(false));
8372
+ }
8373
+ };
8374
+ }
8375
+ });
8376
+
8014
8377
  // ../core/dist/common-auth-embedded/claustrum/insula.js
8015
8378
  import { resolve as resolve4 } from "node:path";
8016
8379
  import { storeIdentity } from "@cortexkit/claustrum-client";
@@ -8049,12 +8412,95 @@ function insulaUsageTransport(options) {
8049
8412
  clearTimeout(timer);
8050
8413
  client?.close();
8051
8414
  }
8415
+ },
8416
+ watchUsage(onNotice) {
8417
+ let client;
8418
+ let subscription;
8419
+ let stopped = false;
8420
+ const closed = (async () => {
8421
+ let deadline;
8422
+ const timeout = new Promise((_resolve, reject) => {
8423
+ deadline = setTimeout(
8424
+ // Coded as a timeout, so InsulaQuotaSource treats a watch that could
8425
+ // not open in time as an unreachable insula and tries again later,
8426
+ // not as a refusal.
8427
+ () => reject(Object.assign(new Error("insula watch timeout"), {
8428
+ code: "timeout"
8429
+ })),
8430
+ 3e3
8431
+ );
8432
+ deadline.unref?.();
8433
+ });
8434
+ const open13 = (async () => {
8435
+ const handshakeTimeoutMs = Math.min(options.handshakeTimeoutMs ?? 3e3, 3e3);
8436
+ const connected = options.connector ? await options.connector({
8437
+ connectionFile: options.connectionFile,
8438
+ handshakeTimeoutMs
8439
+ }) : await SubcClient.connect({
8440
+ connectionFile: options.connectionFile,
8441
+ handshakeTimeoutMs
8442
+ });
8443
+ client = connected;
8444
+ if (stopped) {
8445
+ connected.close();
8446
+ return;
8447
+ }
8448
+ const route = await connected.routeOpen({ kind: "management_surface", module_id: "insula" }, identity);
8449
+ if (stopped) {
8450
+ connected.close();
8451
+ return;
8452
+ }
8453
+ subscription = connected.subscribe(route, { method: "usage.watch" }, onNotice);
8454
+ })();
8455
+ try {
8456
+ await Promise.race([open13, timeout]);
8457
+ } catch (error) {
8458
+ stopped = true;
8459
+ throw error;
8460
+ } finally {
8461
+ clearTimeout(deadline);
8462
+ }
8463
+ if (subscription)
8464
+ await subscription.closed;
8465
+ })().finally(() => {
8466
+ stopped = true;
8467
+ client?.close();
8468
+ });
8469
+ return {
8470
+ stop() {
8471
+ if (stopped)
8472
+ return;
8473
+ stopped = true;
8474
+ subscription?.unsubscribe();
8475
+ client?.close();
8476
+ },
8477
+ closed
8478
+ };
8052
8479
  }
8053
8480
  };
8054
8481
  }
8055
8482
  function record2(value) {
8056
8483
  return typeof value === "object" && value !== null && !Array.isArray(value);
8057
8484
  }
8485
+ function decodeUsageNotice(body) {
8486
+ let value;
8487
+ try {
8488
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
8489
+ } catch {
8490
+ return void 0;
8491
+ }
8492
+ if (!record2(value) || typeof value.kind !== "string" || typeof value.epoch !== "string" || value.epoch.length === 0 || typeof value.seq !== "number" || !Number.isSafeInteger(value.seq) || value.seq < 1 || value.provider !== void 0 && typeof value.provider !== "string")
8493
+ return void 0;
8494
+ return {
8495
+ kind: value.kind,
8496
+ epoch: value.epoch,
8497
+ seq: value.seq,
8498
+ ...typeof value.provider === "string" && { provider: value.provider }
8499
+ };
8500
+ }
8501
+ function refusalCode(error) {
8502
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : void 0;
8503
+ }
8058
8504
  function acquireInsulaQuotaSource(transport, tokenPath) {
8059
8505
  const key = JSON.stringify([
8060
8506
  resolve4(transport.connectionFile),
@@ -8078,26 +8524,76 @@ function acquireInsulaQuotaSource(transport, tokenPath) {
8078
8524
  }
8079
8525
  };
8080
8526
  }
8081
- var MINUTE, MAX_AGE, sources, attempts, InsulaQuotaSource;
8527
+ var MINUTE, MAX_AGE, COLD_WAIT, sources, attempts, InsulaQuotaSource;
8082
8528
  var init_insula = __esm({
8083
8529
  "../core/dist/common-auth-embedded/claustrum/insula.js"() {
8084
8530
  "use strict";
8531
+ init_availability();
8532
+ init_watch();
8085
8533
  MINUTE = 6e4;
8086
8534
  MAX_AGE = 4 * MINUTE;
8535
+ COLD_WAIT = 2 * MINUTE;
8087
8536
  sources = /* @__PURE__ */ new Map();
8088
8537
  attempts = /* @__PURE__ */ new Map();
8089
8538
  InsulaQuotaSource = class {
8090
8539
  transport;
8091
8540
  key;
8092
8541
  #entries = [];
8093
- #pending;
8542
+ #available = false;
8543
+ #completeProviders = /* @__PURE__ */ new Set();
8544
+ #coldSince = /* @__PURE__ */ new Map();
8545
+ /** Every usage.get, polled or watch-driven, shares this one slot. */
8546
+ #reads = new CoalescedRead(async () => {
8547
+ try {
8548
+ const reply = await this.transport.getUsage();
8549
+ if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== void 0)
8550
+ throw new Error("unavailable insula usage");
8551
+ this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
8552
+ this.#available = this.#entries.length === reply.result.length && (reply.completeProviders === void 0 || Array.isArray(reply.completeProviders) && reply.completeProviders.every((value) => typeof value === "string"));
8553
+ this.#completeProviders = new Set(this.#available && Array.isArray(reply.completeProviders) ? reply.completeProviders : []);
8554
+ for (const provider2 of this.#completeProviders)
8555
+ this.#coldSince.delete(provider2);
8556
+ } catch {
8557
+ this.#entries = [];
8558
+ this.#available = false;
8559
+ this.#completeProviders.clear();
8560
+ }
8561
+ }, () => {
8562
+ });
8563
+ #reader = new ChangeNoticeReader();
8564
+ #mode = "polling";
8565
+ #watchers = 0;
8566
+ /**
8567
+ * How many registered watchers read every provider. Watchers limited to one
8568
+ * provider are counted per provider in `#providers` instead.
8569
+ */
8570
+ #everyProvider = 0;
8571
+ #providers = /* @__PURE__ */ new Map();
8572
+ #watch;
8573
+ #timer;
8574
+ #timers = {};
8575
+ /**
8576
+ * How many accepted watches in a row have closed; each one doubles the wait
8577
+ * before the next re-subscribe. Reset once a watch brings a second notice.
8578
+ */
8579
+ #closes = 0;
8094
8580
  constructor(transport, key) {
8095
8581
  this.transport = transport;
8096
8582
  this.key = key;
8097
8583
  }
8584
+ /**
8585
+ * The background poll: at most one usage.get per minute per daemon and
8586
+ * enrollment token. While a watch is open it reads nothing, because insula's
8587
+ * notices announce every new reading. If insula stops announcing an account,
8588
+ * that account's last entry grows older than the freshness limit `current()`
8589
+ * applies, `current()` returns nothing for it, and the plugin falls back to
8590
+ * its own provider poll for that account.
8591
+ */
8098
8592
  refresh(now) {
8099
- if (this.#pending)
8100
- return this.#pending;
8593
+ if (this.#reads.running)
8594
+ return this.#reads.running;
8595
+ if (this.#mode === "watching")
8596
+ return Promise.resolve();
8101
8597
  for (const [key, time] of attempts) {
8102
8598
  if (now - time >= MINUTE)
8103
8599
  attempts.delete(key);
@@ -8106,19 +8602,119 @@ var init_insula = __esm({
8106
8602
  if (lastAttempt !== void 0 && now - lastAttempt < MINUTE)
8107
8603
  return Promise.resolve();
8108
8604
  attempts.set(this.key, now);
8109
- this.#pending = (async () => {
8110
- try {
8111
- const reply = await this.transport.getUsage();
8112
- if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== void 0)
8113
- throw new Error("unavailable insula usage");
8114
- this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
8115
- } catch {
8116
- this.#entries = [];
8605
+ return this.#reads.request();
8606
+ }
8607
+ /** How this source currently learns about usage changes, for logs. */
8608
+ watchMode() {
8609
+ return this.#mode;
8610
+ }
8611
+ /**
8612
+ * Hold a `usage.watch` open while any watcher wants it, and re-read
8613
+ * usage.get when a notice says something changed. Watchers of one source
8614
+ * share one watch, since insula admits only 64 per process. Returns the
8615
+ * release; the last release closes the watch.
8616
+ */
8617
+ watch(options = {}) {
8618
+ this.#watchers++;
8619
+ const provider2 = options.provider;
8620
+ if (provider2 === void 0)
8621
+ this.#everyProvider++;
8622
+ else
8623
+ this.#providers.set(provider2, (this.#providers.get(provider2) ?? 0) + 1);
8624
+ if (this.#watchers === 1) {
8625
+ this.#timers = options;
8626
+ this.#open();
8627
+ }
8628
+ let released = false;
8629
+ return () => {
8630
+ if (released)
8631
+ return;
8632
+ released = true;
8633
+ if (provider2 === void 0)
8634
+ this.#everyProvider--;
8635
+ else {
8636
+ const left = (this.#providers.get(provider2) ?? 1) - 1;
8637
+ if (left > 0)
8638
+ this.#providers.set(provider2, left);
8639
+ else
8640
+ this.#providers.delete(provider2);
8117
8641
  }
8118
- })().finally(() => {
8119
- this.#pending = void 0;
8120
- });
8121
- return this.#pending;
8642
+ if (--this.#watchers === 0)
8643
+ this.#stopWatch();
8644
+ };
8645
+ }
8646
+ #stopWatch() {
8647
+ if (this.#timer)
8648
+ (this.#timers.clearTimeoutImpl ?? clearTimeout)(this.#timer);
8649
+ this.#timer = void 0;
8650
+ const watch = this.#watch;
8651
+ this.#watch = void 0;
8652
+ watch?.handle?.stop();
8653
+ this.#mode = "polling";
8654
+ }
8655
+ #later(delay3) {
8656
+ this.#timer = (this.#timers.setTimeoutImpl ?? setTimeout)(() => {
8657
+ this.#timer = void 0;
8658
+ if (this.#watchers > 0 && !this.#watch)
8659
+ this.#open();
8660
+ }, delay3);
8661
+ this.#timer.unref?.();
8662
+ }
8663
+ #open() {
8664
+ const watchUsage = this.transport.watchUsage;
8665
+ if (!watchUsage) {
8666
+ this.#mode = "fallback";
8667
+ return;
8668
+ }
8669
+ this.#mode = "polling";
8670
+ this.#reader.restart();
8671
+ const watch = { notices: 0 };
8672
+ this.#watch = watch;
8673
+ let handle;
8674
+ try {
8675
+ handle = watchUsage.call(this.transport, (body) => this.#notice(watch, body));
8676
+ } catch (error) {
8677
+ this.#closed(watch, error);
8678
+ return;
8679
+ }
8680
+ watch.handle = handle;
8681
+ handle.closed.then(() => this.#closed(watch, void 0), (error) => this.#closed(watch, error));
8682
+ }
8683
+ #notice(watch, body) {
8684
+ if (this.#watch !== watch)
8685
+ return;
8686
+ watch.notices++;
8687
+ if (watch.notices === 1)
8688
+ this.#mode = "watching";
8689
+ if (watch.notices === 2)
8690
+ this.#closes = 0;
8691
+ const notice = decodeUsageNotice(body);
8692
+ if (!notice)
8693
+ this.#reader.restart();
8694
+ const continuous = notice ? this.#reader.continuous(notice) : false;
8695
+ if (!continuous || notice?.provider === void 0 || this.#everyProvider > 0 || this.#providers.has(notice.provider))
8696
+ void this.#reads.request();
8697
+ }
8698
+ #closed(watch, error) {
8699
+ if (this.#watch !== watch)
8700
+ return;
8701
+ this.#watch = void 0;
8702
+ const code2 = refusalCode(error);
8703
+ if (code2 === "unknown_method" || code2 === "usage_watch_limit") {
8704
+ this.#mode = "fallback";
8705
+ return;
8706
+ }
8707
+ if (watch.notices > 0) {
8708
+ const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
8709
+ this.#closes++;
8710
+ this.#mode = "polling";
8711
+ this.#later(delay3);
8712
+ return;
8713
+ }
8714
+ this.#mode = "fallback";
8715
+ void this.#reads.request();
8716
+ if (error === void 0 || classifyVaultFailure(error) === "unreachable")
8717
+ this.#later(WATCH_RETRY_MS);
8122
8718
  }
8123
8719
  current(provider2, accountId, now) {
8124
8720
  for (const entry of this.#entries) {
@@ -8139,6 +8735,37 @@ var init_insula = __esm({
8139
8735
  }
8140
8736
  return void 0;
8141
8737
  }
8738
+ /** Cache-only background lookup; current() retains its original miss behavior. */
8739
+ lookup(provider2, accountId, now) {
8740
+ if (!this.#available)
8741
+ return { miss: "unreachable" };
8742
+ const entry = this.#entries.find((value) => value.provider === provider2 && typeof value.account === "string" && value.account.trim() === accountId);
8743
+ const errorClass = (entry ?? this.#entries.find((value) => value.provider === provider2 && value.account === void 0 && value.errorClass !== void 0))?.errorClass;
8744
+ if (errorClass === "upstream_failed")
8745
+ return { miss: "upstream-failed" };
8746
+ if (errorClass === "credential_absent" || errorClass === "credential_unusable" || errorClass === "credential_rejected")
8747
+ return { miss: "credential" };
8748
+ if (errorClass !== void 0)
8749
+ return { miss: "unreachable" };
8750
+ if (entry) {
8751
+ const fetchedAt = typeof entry.fetchedAt === "string" ? Date.parse(entry.fetchedAt) : Number.NaN;
8752
+ if (!record2(entry.usage) || !Number.isFinite(fetchedAt))
8753
+ return { miss: "unreachable" };
8754
+ const reading = {
8755
+ entry,
8756
+ context: {
8757
+ fetchedAt,
8758
+ ...typeof entry.source === "string" && { source: entry.source }
8759
+ }
8760
+ };
8761
+ return now >= fetchedAt + MAX_AGE || entry.stale !== void 0 ? { miss: "stale", reading } : { reading };
8762
+ }
8763
+ if (this.#completeProviders.has(provider2))
8764
+ return { miss: "absent" };
8765
+ const since = this.#coldSince.get(provider2) ?? now;
8766
+ this.#coldSince.set(provider2, since);
8767
+ return { miss: now - since >= COLD_WAIT ? "unreachable" : "cold" };
8768
+ }
8142
8769
  };
8143
8770
  }
8144
8771
  });
@@ -8185,30 +8812,14 @@ var init_any_signal = __esm({
8185
8812
  }
8186
8813
  });
8187
8814
 
8188
- // ../core/dist/common-auth-embedded/claustrum/errors.js
8189
- var ClaustrumConsumerError;
8190
- var init_errors2 = __esm({
8191
- "../core/dist/common-auth-embedded/claustrum/errors.js"() {
8192
- "use strict";
8193
- ClaustrumConsumerError = class extends Error {
8194
- kind;
8195
- constructor(kind, message) {
8196
- super(message);
8197
- this.name = "ClaustrumConsumerError";
8198
- this.kind = kind;
8199
- }
8200
- };
8201
- }
8202
- });
8203
-
8204
8815
  // ../core/dist/common-auth-embedded/claustrum/enrollment.js
8205
8816
  import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID12 } from "node:crypto";
8206
8817
  import { constants as fsConstants } from "node:fs";
8207
8818
  import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename6, stat as stat4, unlink as unlink6 } from "node:fs/promises";
8208
8819
  import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join5, resolve as resolve5 } from "node:path";
8209
- import { ClaustrumCredentialError, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8820
+ import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8210
8821
  function classifyEnrollmentError(error) {
8211
- if (!(error instanceof ClaustrumCredentialError))
8822
+ if (!(error instanceof ClaustrumCredentialError2))
8212
8823
  return void 0;
8213
8824
  if (TERMINAL_ENROLLMENT_CODES.has(error.code))
8214
8825
  return { code: error.code, disposition: "terminal" };
@@ -8909,9 +9520,9 @@ var init_host_slot = __esm({
8909
9520
  });
8910
9521
 
8911
9522
  // ../core/dist/common-auth-embedded/claustrum/custody.js
8912
- import { ClaustrumCredentialError as ClaustrumCredentialError2 } from "@cortexkit/claustrum-client";
9523
+ import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
8913
9524
  function isScopedCredentialRotation(served, current) {
8914
- return current !== void 0 && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
9525
+ return current !== void 0 && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
8915
9526
  }
8916
9527
  function scopedRetryReason(served, current) {
8917
9528
  if (current === void 0)
@@ -8979,16 +9590,19 @@ function grantReachOf(listed) {
8979
9590
  tuples: Object.freeze(grantTuples.map(({ selectorKind, selector, operation }) => Object.freeze({ selectorKind, selector, operation })))
8980
9591
  });
8981
9592
  }
8982
- var defaultLogger, SERVING_MARGIN_MS, ClaustrumScopedCustody;
9593
+ var defaultLogger, SERVING_MARGIN_MS, KEPT_RECEIPT_MARGIN_MS, ClaustrumScopedCustody;
8983
9594
  var init_custody = __esm({
8984
9595
  "../core/dist/common-auth-embedded/claustrum/custody.js"() {
8985
9596
  "use strict";
8986
9597
  init_logger();
9598
+ init_availability();
8987
9599
  init_enrollment();
8988
9600
  init_errors2();
8989
9601
  init_host_slot();
9602
+ init_watch();
8990
9603
  defaultLogger = createLogger2("claustrum");
8991
9604
  SERVING_MARGIN_MS = 3e5;
9605
+ KEPT_RECEIPT_MARGIN_MS = 6e4;
8992
9606
  ClaustrumScopedCustody = class {
8993
9607
  #client;
8994
9608
  #readToken;
@@ -8999,7 +9613,20 @@ var init_custody = __esm({
8999
9613
  #logger;
9000
9614
  #provenance = /* @__PURE__ */ new WeakMap();
9001
9615
  #reports = /* @__PURE__ */ new WeakMap();
9616
+ #kept = /* @__PURE__ */ new Map();
9617
+ #keptAttempts = /* @__PURE__ */ new WeakMap();
9618
+ #setTimeout;
9619
+ #clearTimeout;
9620
+ #outage = false;
9621
+ #outageError = new ClaustrumUnreachableError();
9622
+ #probeTimer;
9623
+ #probing = false;
9624
+ #lastProbeAt = -Infinity;
9625
+ #probeDelay = 2e3;
9002
9626
  #closed = false;
9627
+ /** The view of the last successful `discover()`, for `watchRoster`. */
9628
+ #discoveredView;
9629
+ #watches = /* @__PURE__ */ new Set();
9003
9630
  constructor(options) {
9004
9631
  const tokenPath = options.tokenPath;
9005
9632
  if (options.readToken) {
@@ -9015,6 +9642,56 @@ var init_custody = __esm({
9015
9642
  this.#requireAssertion = options.requireAssertion ?? false;
9016
9643
  this.#now = options.now ?? Date.now;
9017
9644
  this.#logger = options.logger ?? defaultLogger;
9645
+ this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
9646
+ this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
9647
+ }
9648
+ /** A watch losing its transport is the same outage as an unreachable read. */
9649
+ transportLost(error) {
9650
+ if (this.#closed || this.#outage)
9651
+ return;
9652
+ this.#outage = true;
9653
+ this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError();
9654
+ this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
9655
+ this.#scheduleProbe();
9656
+ }
9657
+ /** Any vault answer ends transport fallback, even when it refuses access. */
9658
+ reachable() {
9659
+ if (this.#closed || !this.#outage)
9660
+ return;
9661
+ this.#outage = false;
9662
+ if (this.#probeTimer)
9663
+ this.#clearTimeout(this.#probeTimer);
9664
+ this.#probeTimer = void 0;
9665
+ this.#probeDelay = 2e3;
9666
+ for (const kept of this.#kept.values())
9667
+ kept.since = null;
9668
+ (this.#logger.info ?? defaultLogger.info)("vault receipt serving resumed", { reason: "reachable" });
9669
+ }
9670
+ #scheduleProbe() {
9671
+ if (this.#closed || !this.#outage || this.#probeTimer || this.#probing)
9672
+ return;
9673
+ this.#probeTimer = this.#setTimeout(() => {
9674
+ this.#probeTimer = void 0;
9675
+ this.#probe(true);
9676
+ }, this.#probeDelay);
9677
+ this.#probeTimer.unref?.();
9678
+ }
9679
+ #probe(idle = false) {
9680
+ if (this.#closed || !this.#outage || this.#probing)
9681
+ return;
9682
+ if (this.#now() - this.#lastProbeAt < 1e3) {
9683
+ this.#scheduleProbe();
9684
+ return;
9685
+ }
9686
+ this.#lastProbeAt = this.#now();
9687
+ this.#probing = true;
9688
+ void this.#list().catch(() => {
9689
+ if (idle && this.#outage)
9690
+ this.#probeDelay = Math.min(this.#probeDelay * 2, 3e4);
9691
+ }).finally(() => {
9692
+ this.#probing = false;
9693
+ this.#scheduleProbe();
9694
+ });
9018
9695
  }
9019
9696
  #check(signal) {
9020
9697
  if (this.#closed)
@@ -9048,13 +9725,20 @@ var init_custody = __esm({
9048
9725
  ]) : await pending;
9049
9726
  } catch (error) {
9050
9727
  this.#check(signal);
9051
- if (error instanceof ClaustrumCredentialError2)
9728
+ if (classifyVaultFailure(error) === "unreachable")
9729
+ this.transportLost(error);
9730
+ else
9731
+ this.reachable();
9732
+ if (error instanceof ClaustrumCredentialError3)
9052
9733
  throw error;
9734
+ if (classifyVaultFailure(error) === "unreachable")
9735
+ throw new ClaustrumUnreachableError();
9053
9736
  throw new ClaustrumConsumerError("unavailable", "Claustrum scoped operation unavailable");
9054
9737
  } finally {
9055
9738
  removeAbortListener?.();
9056
9739
  }
9057
9740
  this.#check(signal);
9741
+ this.reachable();
9058
9742
  return result;
9059
9743
  }
9060
9744
  /**
@@ -9064,8 +9748,25 @@ var init_custody = __esm({
9064
9748
  * skipped records: they simply are not this consumer's.
9065
9749
  */
9066
9750
  async discover(signal) {
9067
- const token = await this.#token(signal);
9068
- const inventory = await this.#call(() => this.#client.listScoped(token), signal);
9751
+ const inventory = await this.#list(signal);
9752
+ this.#discoveredView = inventory.view;
9753
+ return inventory;
9754
+ }
9755
+ async #list(signal) {
9756
+ let inventory;
9757
+ let token;
9758
+ try {
9759
+ token = await this.#token(signal);
9760
+ } catch (error) {
9761
+ this.#kept.clear();
9762
+ throw error;
9763
+ }
9764
+ try {
9765
+ inventory = await this.#call(() => this.#client.listScoped(token), signal);
9766
+ } catch (error) {
9767
+ this.listFailed(error);
9768
+ throw error;
9769
+ }
9069
9770
  const skipped = [];
9070
9771
  const candidates = [];
9071
9772
  const counts = /* @__PURE__ */ new Map();
@@ -9113,21 +9814,105 @@ var init_custody = __esm({
9113
9814
  };
9114
9815
  }
9115
9816
  /**
9116
- * Fetch the credential for one physical send and wrap it in a fresh receipt.
9117
- * The vault's served identity (or, without one, the plugin's parse of the
9118
- * token) must equal the roster's when both are present. Without
9119
- * `requireAssertion`, absence on either side proves nothing and does not
9120
- * refuse; the receipt records what the vault asserted separately from what
9121
- * the roster expected. With it, a reply that does not itself name the
9122
- * credential id and the expected account is refused.
9817
+ * Apply a failed account listing: any answer from the vault (a refusal such
9818
+ * as a revoked enrollment's `not_found`) drops every kept receipt, while an
9819
+ * unreachable vault keeps them. A vault watch that ends with the same
9820
+ * refusal calls this too, so both paths treat it alike.
9123
9821
  */
9124
- async authorize(identity, signal) {
9822
+ listFailed(error) {
9823
+ if (classifyVaultFailure(error) === "unreachable")
9824
+ this.transportLost(error);
9825
+ else {
9826
+ this.reachable();
9827
+ this.#kept.clear();
9828
+ }
9829
+ }
9830
+ /** Discard bearer material when a route is removed, declined or rebound. */
9831
+ forget(credentialId) {
9832
+ this.#kept.delete(credentialId);
9833
+ }
9834
+ /** Apply an already-held roster; this never fetches credentials or writes it. */
9835
+ retain(identities) {
9836
+ const current = new Map(identities.map((identity) => [identity.credentialId, identity]));
9837
+ for (const [id, kept] of this.#kept) {
9838
+ const identity = current.get(id);
9839
+ if (!identity?.enabled || identity.state !== "active" || identity.credentialType !== kept.attempt.credentialType || identity.accountIdentity !== kept.attempt.expectedAccountIdentity)
9840
+ this.forget(id);
9841
+ }
9842
+ }
9843
+ /** A frozen, non-secret summary for a plugin's status display. */
9844
+ keptReceiptState() {
9845
+ let since = null;
9846
+ for (const [id, kept] of this.#kept) {
9847
+ if (!this.#usable(kept.attempt)) {
9848
+ this.forget(id);
9849
+ continue;
9850
+ }
9851
+ if (kept.since !== null)
9852
+ since = Math.min(since ?? kept.since, kept.since);
9853
+ }
9854
+ return Object.freeze({ active: since !== null, since });
9855
+ }
9856
+ #usable(attempt) {
9857
+ return attempt.expiresAtMs === null ? attempt.credentialType === "api_key" : attempt.expiresAtMs - this.#now() > KEPT_RECEIPT_MARGIN_MS;
9858
+ }
9859
+ /** Ask the vault while reachable; retain one validated receipt in memory only. */
9860
+ async authorize(identity, signal, routeId = "vault") {
9861
+ this.#check(signal);
9862
+ const { credentialId, credentialType, accountIdentity } = identity;
9863
+ let kept = this.#kept.get(credentialId);
9864
+ if (kept && (kept.attempt.credentialType !== credentialType || kept.attempt.expectedAccountIdentity !== accountIdentity)) {
9865
+ this.forget(credentialId);
9866
+ kept = void 0;
9867
+ }
9868
+ let token;
9869
+ try {
9870
+ token = await this.#token(signal);
9871
+ } catch (error) {
9872
+ this.#kept.clear();
9873
+ throw error;
9874
+ }
9875
+ if (this.#outage && kept) {
9876
+ this.#probe();
9877
+ return this.#serveKept(credentialId, kept, token, routeId);
9878
+ }
9879
+ try {
9880
+ const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
9881
+ this.#kept.set(credentialId, { attempt, routeId, since: null });
9882
+ return attempt;
9883
+ } catch (error) {
9884
+ this.#check(signal);
9885
+ if (classifyVaultFailure(error) !== "unreachable") {
9886
+ this.forget(credentialId);
9887
+ throw error;
9888
+ }
9889
+ return this.#serveKept(credentialId, kept, token, routeId, error);
9890
+ }
9891
+ }
9892
+ #serveKept(credentialId, kept, token, routeId, error = this.#outageError) {
9893
+ if (!kept || this.#kept.get(credentialId) !== kept || !this.#usable(kept.attempt)) {
9894
+ this.forget(credentialId);
9895
+ throw error;
9896
+ }
9897
+ if (kept.since === null)
9898
+ kept.since = this.#now();
9899
+ const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, "accessToken", { value: kept.attempt.accessToken, enumerable: false }));
9900
+ this.#provenance.set(attempt, token);
9901
+ this.#keptAttempts.set(attempt, routeId);
9902
+ return attempt;
9903
+ }
9904
+ /**
9905
+ * Fetch and validate a fresh receipt before retaining it. The vault assertion
9906
+ * (or the plugin's token parse) must agree with the roster when both exist.
9907
+ * With requireAssertion, an absent assertion also refuses rather than
9908
+ * treating the roster's expectation as proof of the served account.
9909
+ */
9910
+ async #authorizeFresh(identity, token, signal) {
9125
9911
  if (!identity.credentialId)
9126
9912
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum dispatch requires a credential id");
9127
9913
  const { credentialId, credentialType, accountIdentity } = identity;
9128
9914
  if (this.#requireAssertion && accountIdentity === void 0)
9129
9915
  throw new ClaustrumConsumerError("identity-unasserted", "Claustrum dispatch requires a known account identity");
9130
- const token = await this.#token(signal);
9131
9916
  const served = await this.#call(() => this.#client.getScoped({
9132
9917
  credentialId,
9133
9918
  enrollmentToken: token,
@@ -9190,6 +9975,18 @@ var init_custody = __esm({
9190
9975
  const token = this.#provenance.get(attempt);
9191
9976
  if (!token)
9192
9977
  throw new ClaustrumConsumerError("no-receipt", "Claustrum failure report requires an original dispatch receipt");
9978
+ const keptRoute = this.#keptAttempts.get(attempt);
9979
+ if (keptRoute !== void 0) {
9980
+ this.forget(attempt.credentialId);
9981
+ this.#logger.debug("scoped 401 not reported", {
9982
+ routeId: keptRoute,
9983
+ reason: "kept-receipt"
9984
+ });
9985
+ return;
9986
+ }
9987
+ const kept = this.#kept.get(attempt.credentialId);
9988
+ if (kept && kept.attempt.recordVersion === attempt.recordVersion)
9989
+ this.forget(attempt.credentialId);
9193
9990
  const pending = this.#reports.get(attempt);
9194
9991
  if (pending)
9195
9992
  return pending;
@@ -9213,10 +10010,70 @@ var init_custody = __esm({
9213
10010
  throw error;
9214
10011
  }
9215
10012
  }
10013
+ /**
10014
+ * Watch this consumer's visible vault accounts instead of listing them on a
10015
+ * short timer. Opens one `watchScoped` on this custody's client and calls
10016
+ * `onView` when the host must run its discovery (see
10017
+ * `ClaustrumRosterWatchOptions`). A claustrum-client without `watchScoped`
10018
+ * (before 0.12.0) or a vault that answers `unknown_method` reports
10019
+ * `fallback` and opens nothing. A watch that closes before any notice was
10020
+ * never accepted: the client reads once to learn why, and the watch reports
10021
+ * `fallback` and tries one new watch after `WATCH_RETRY_MS`, never in a
10022
+ * loop. A watch that closes after notices is re-opened after
10023
+ * `RESUBSCRIBE_BACKOFF_MS`, doubling per close in a row. A lost transport
10024
+ * starts this custody's outage, exactly as an unreachable call does, and
10025
+ * the first notice of a watch ends it. Timers are unreferenced; `close()`
10026
+ * on the returned watch or on this custody stops it.
10027
+ *
10028
+ * The watch keeps no history, so the host still lists on a slow timer while
10029
+ * the mode is `watching`: every `SAFETY_POLL_MS` (five minutes). In any
10030
+ * other mode the host keeps its usual list timer.
10031
+ */
10032
+ watchRoster(options) {
10033
+ this.#check();
10034
+ const watch = new ScopedRosterWatch({
10035
+ client: this.#client,
10036
+ enrollmentToken: () => this.#token(),
10037
+ view: options.view ?? (() => this.#discoveredView),
10038
+ discover: async (view) => {
10039
+ await options.onView(view);
10040
+ },
10041
+ onRefused: (error) => {
10042
+ this.listFailed(error);
10043
+ options.onRefused?.(error);
10044
+ },
10045
+ onTransportLost: () => this.transportLost(),
10046
+ onReachable: () => this.reachable(),
10047
+ onError: options.onError,
10048
+ onMode: options.onMode,
10049
+ logger: this.#logger,
10050
+ now: this.#now,
10051
+ setTimeoutImpl: this.#setTimeout,
10052
+ clearTimeoutImpl: this.#clearTimeout
10053
+ });
10054
+ this.#watches.add(watch);
10055
+ watch.start();
10056
+ return {
10057
+ get mode() {
10058
+ return watch.mode;
10059
+ },
10060
+ close: () => {
10061
+ this.#watches.delete(watch);
10062
+ watch.stop();
10063
+ }
10064
+ };
10065
+ }
9216
10066
  close() {
9217
10067
  if (this.#closed)
9218
10068
  return;
9219
10069
  this.#closed = true;
10070
+ if (this.#probeTimer)
10071
+ this.#clearTimeout(this.#probeTimer);
10072
+ this.#probeTimer = void 0;
10073
+ for (const watch of this.#watches)
10074
+ watch.stop();
10075
+ this.#watches.clear();
10076
+ this.#kept.clear();
9220
10077
  this.#client.close();
9221
10078
  }
9222
10079
  };
@@ -9667,6 +10524,7 @@ var init_consumer = __esm({
9667
10524
  init_errors2();
9668
10525
  init_insula();
9669
10526
  init_roster();
10527
+ init_watch();
9670
10528
  ClaustrumConsumer = class {
9671
10529
  #options;
9672
10530
  #shutdown = new AbortController();
@@ -9683,6 +10541,11 @@ var init_consumer = __esm({
9683
10541
  #timer;
9684
10542
  #started = false;
9685
10543
  #insula;
10544
+ #vaultWatch;
10545
+ #releaseInsulaWatch;
10546
+ #insulaSkips = /* @__PURE__ */ new Map();
10547
+ /** When this instance last completed a discovery, by `now`. */
10548
+ #discoveredAt;
9686
10549
  constructor(options) {
9687
10550
  this.#options = options;
9688
10551
  this.#logger = options.logger ?? createLogger2("claustrum");
@@ -9740,7 +10603,9 @@ var init_consumer = __esm({
9740
10603
  parseIdentity: this.#options.parseIdentity,
9741
10604
  requireAssertion: this.#options.requireAssertion,
9742
10605
  now: this.#options.now,
9743
- logger: this.#logger
10606
+ logger: this.#logger,
10607
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10608
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
9744
10609
  });
9745
10610
  if (this.#options.insula && client.insula) {
9746
10611
  this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
@@ -9769,6 +10634,26 @@ var init_consumer = __esm({
9769
10634
  const latest2 = this.#grantReach;
9770
10635
  return latest2 && this.#roster?.view === latest2.view ? latest2.reach : void 0;
9771
10636
  }
10637
+ /** How this consumer currently learns about changes, without I/O. */
10638
+ watchState() {
10639
+ return Object.freeze({
10640
+ vault: this.#vaultWatch?.mode ?? "polling",
10641
+ ...this.#options.insula && {
10642
+ insula: this.#insula?.source.watchMode() ?? "polling"
10643
+ }
10644
+ });
10645
+ }
10646
+ /** Close the watches with the connection they belong to. */
10647
+ #stopWatch() {
10648
+ this.#vaultWatch?.close();
10649
+ this.#vaultWatch = void 0;
10650
+ this.#releaseInsulaWatch?.();
10651
+ this.#releaseInsulaWatch = void 0;
10652
+ }
10653
+ /** Whether any account is using an in-memory outage receipt, without I/O. */
10654
+ keptReceiptState() {
10655
+ return this.#custody?.keptReceiptState() ?? Object.freeze({ active: false, since: null });
10656
+ }
9772
10657
  /** Rows for `/routing`, from the last committed roster. */
9773
10658
  routingRows() {
9774
10659
  return vaultRoutingRows(this.#roster);
@@ -9781,6 +10666,7 @@ var init_consumer = __esm({
9781
10666
  if (!await this.#active()) {
9782
10667
  this.#roster = void 0;
9783
10668
  this.#grantReach = void 0;
10669
+ this.#stopWatch();
9784
10670
  this.#custody?.close();
9785
10671
  this.#custody = void 0;
9786
10672
  this.#insula?.release();
@@ -9809,16 +10695,28 @@ var init_consumer = __esm({
9809
10695
  this.#assertOpen();
9810
10696
  const changed = roster?.view !== this.#roster?.view;
9811
10697
  this.#roster = roster;
10698
+ custody.retain(roster?.rows ?? []);
9812
10699
  if (discovered && roster?.view !== void 0)
9813
10700
  this.#grantReach = discovered.grantReach ? { view: roster.view, reach: discovered.grantReach } : void 0;
9814
10701
  if (roster && changed)
9815
10702
  this.#options.onRoster?.(roster);
10703
+ this.#discoveredAt = (this.#options.now ?? Date.now)();
9816
10704
  return roster;
9817
10705
  })().finally(() => {
9818
10706
  this.#refreshing = void 0;
9819
10707
  });
9820
10708
  return this.#refreshing;
9821
10709
  }
10710
+ /**
10711
+ * Poll in the background and open the vault and insula watches. Until the
10712
+ * vault watch is accepted, and whenever it is unavailable, every tick lists
10713
+ * the vault exactly as before watches existed. While it is open a tick
10714
+ * lists only when five minutes have passed since the last discovery, since
10715
+ * the watch keeps no history; it still checks `isCustodyActive`, so a switch
10716
+ * to local mode closes the connection as quickly as before. Insula is
10717
+ * polled on the tick only while its own watch is not open. A host not in
10718
+ * vault mode makes no request.
10719
+ */
9822
10720
  start() {
9823
10721
  if (this.#started)
9824
10722
  return;
@@ -9826,8 +10724,10 @@ var init_consumer = __esm({
9826
10724
  this.#started = true;
9827
10725
  const tick = async () => {
9828
10726
  try {
9829
- await this.refresh();
10727
+ if (await this.#listDue())
10728
+ await this.refresh();
9830
10729
  await this.refreshInsulaQuota();
10730
+ this.#openWatch();
9831
10731
  } catch (error) {
9832
10732
  if (!this.#shutdown.signal.aborted)
9833
10733
  this.#options.onError?.(error);
@@ -9845,6 +10745,50 @@ var init_consumer = __esm({
9845
10745
  };
9846
10746
  void tick();
9847
10747
  }
10748
+ /** Whether a background tick must list the vault now. */
10749
+ async #listDue() {
10750
+ if (this.#vaultWatch?.mode !== "watching")
10751
+ return true;
10752
+ const now = (this.#options.now ?? Date.now)();
10753
+ if (this.#discoveredAt === void 0 || now - this.#discoveredAt >= SAFETY_POLL_MS)
10754
+ return true;
10755
+ return !await this.#active();
10756
+ }
10757
+ /**
10758
+ * Open the vault and insula watches once a vault connection exists. Only
10759
+ * reached in vault mode: a host in local mode never connects.
10760
+ */
10761
+ #openWatch() {
10762
+ const custody = this.#custody;
10763
+ if (this.#shutdown.signal.aborted || !custody)
10764
+ return;
10765
+ this.#vaultWatch ??= custody.watchRoster({
10766
+ view: () => this.#roster?.view,
10767
+ // The existing discovery, so a watched change commits the roster and
10768
+ // re-applies it to kept receipts exactly as a poll does. A refresh
10769
+ // already in flight may have listed before the change was announced,
10770
+ // so wait for it and list again.
10771
+ onView: async () => {
10772
+ while (this.#refreshing)
10773
+ await this.#refreshing.catch(() => {
10774
+ });
10775
+ await this.refresh();
10776
+ },
10777
+ // Custody has dropped kept receipts, as a poll meeting the same
10778
+ // refusal from list_scoped would.
10779
+ onRefused: (error) => this.#options.onError?.(error),
10780
+ onError: (error) => {
10781
+ if (!this.#shutdown.signal.aborted)
10782
+ this.#options.onError?.(error);
10783
+ }
10784
+ });
10785
+ if (this.#options.insula && this.#insula && !this.#releaseInsulaWatch)
10786
+ this.#releaseInsulaWatch = this.#insula.source.watch({
10787
+ provider: this.#options.insula.provider,
10788
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10789
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
10790
+ });
10791
+ }
9848
10792
  /**
9849
10793
  * Fetch on a background tick, at most once per minute across projects with
9850
10794
  * the same daemon and enrollment token path. Admission must use the cache
@@ -9893,6 +10837,41 @@ var init_consumer = __esm({
9893
10837
  return void 0;
9894
10838
  }
9895
10839
  }
10840
+ /** Cache-only background lookup, preserving the reason a route has no reading. */
10841
+ async lookupInsulaQuotaForRoute(routeId) {
10842
+ const options = this.#options.insula;
10843
+ if (!options || this.#shutdown.signal.aborted || !await this.#active())
10844
+ return { miss: "unreachable" };
10845
+ try {
10846
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
10847
+ const roster = await readVaultRoster(this.#options.rosterPath);
10848
+ const account = roster?.rows.find((row) => row.routeId === routeId)?.accountIdentity;
10849
+ if (!account || !this.#insula)
10850
+ return { miss: "unreachable" };
10851
+ const result = this.#insula.source.lookup(options.provider, account, (this.#options.now ?? Date.now)());
10852
+ const reading = result.reading && options.normalize(result.reading.entry, result.reading.context);
10853
+ if (result.miss)
10854
+ return { miss: result.miss, ...reading !== void 0 && { reading } };
10855
+ return reading === void 0 ? { miss: "unreachable" } : { reading };
10856
+ } catch {
10857
+ return { miss: "unreachable" };
10858
+ }
10859
+ }
10860
+ /** Skip the fallback poll while insula is cold or its upstream fetch failed. */
10861
+ async pollInsulaQuotaForRoute(routeId, fallback) {
10862
+ const result = await this.lookupInsulaQuotaForRoute(routeId);
10863
+ if (result.miss === "cold" || result.miss === "upstream-failed") {
10864
+ if (this.#insulaSkips.get(routeId) !== result.miss) {
10865
+ this.#insulaSkips.set(routeId, result.miss);
10866
+ this.#logger.warn("skipped insula provider poll", {
10867
+ reason: result.miss
10868
+ });
10869
+ }
10870
+ return void 0;
10871
+ }
10872
+ this.#insulaSkips.delete(routeId);
10873
+ return result.miss ? fallback() : result.reading;
10874
+ }
9896
10875
  #normalizeInsulaQuota(accountIdentity) {
9897
10876
  if (!this.#options.insula || !accountIdentity)
9898
10877
  return void 0;
@@ -9907,16 +10886,28 @@ var init_consumer = __esm({
9907
10886
  async authorize(routeId, signal) {
9908
10887
  this.#assertOpen(signal);
9909
10888
  const roster = this.#roster ?? await this.#wait(this.refresh(), signal);
9910
- if (!roster || !await this.#active())
10889
+ if (!roster || !await this.#active()) {
10890
+ this.#custody?.close();
10891
+ this.#custody = void 0;
10892
+ this.#stopWatch();
10893
+ this.#insula?.release();
10894
+ this.#insula = void 0;
9911
10895
  throw new ClaustrumConsumerError("not-active", "Claustrum scoped custody is not active");
10896
+ }
9912
10897
  const current = await readVaultRoster(this.#options.rosterPath);
9913
10898
  this.#assertOpen(signal);
9914
10899
  const observed = roster.rows.find((row) => row.routeId === routeId);
9915
10900
  const configured = current?.rows.find((row) => row.routeId === routeId);
9916
- if (configured && !configured.enabled)
10901
+ if (configured && !configured.enabled) {
10902
+ if (observed)
10903
+ this.#custody?.forget(observed.credentialId);
9917
10904
  throw new ClaustrumConsumerError("route-declined", "Claustrum route is disabled");
9918
- if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity)
10905
+ }
10906
+ if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity || configured.credentialType !== observed.credentialType) {
10907
+ if (observed)
10908
+ this.#custody?.forget(observed.credentialId);
9919
10909
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum route is disabled, removed or changed");
10910
+ }
9920
10911
  const custody = await this.#wait(this.#getCustody(), signal);
9921
10912
  const combined = combineAbortSignals([
9922
10913
  this.#shutdown.signal,
@@ -9929,7 +10920,7 @@ var init_consumer = __esm({
9929
10920
  ...configured.accountIdentity !== void 0 && {
9930
10921
  accountIdentity: configured.accountIdentity
9931
10922
  }
9932
- }, combined.signal);
10923
+ }, combined.signal, routeId);
9933
10924
  } finally {
9934
10925
  combined.dispose();
9935
10926
  }
@@ -9952,6 +10943,10 @@ var init_consumer = __esm({
9952
10943
  const signal = options.signal;
9953
10944
  let served = await this.authorize(routeId, signal);
9954
10945
  let response = await dispatch(served, signal);
10946
+ if (response.status === 401 && served.fromKeptReceipt) {
10947
+ await this.reportFailure(served, 401, options.reporterSource ?? "direct");
10948
+ return response;
10949
+ }
9955
10950
  if (response.status === 401 && !signal?.aborted) {
9956
10951
  let current;
9957
10952
  try {
@@ -9979,6 +10974,7 @@ var init_consumer = __esm({
9979
10974
  this.#assertOpen();
9980
10975
  await declineVaultRoute(this.#options.rosterPath, routeId);
9981
10976
  this.#roster = await readVaultRoster(this.#options.rosterPath);
10977
+ this.#custody?.retain(this.#roster?.rows ?? []);
9982
10978
  }
9983
10979
  async accept(routeId) {
9984
10980
  this.#assertOpen();
@@ -10034,6 +11030,7 @@ var init_consumer = __esm({
10034
11030
  if (this.#timer)
10035
11031
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
10036
11032
  this.#timer = void 0;
11033
+ this.#stopWatch();
10037
11034
  this.#custody?.close();
10038
11035
  this.#insula?.release();
10039
11036
  this.#insula = void 0;
@@ -10048,21 +11045,31 @@ var init_consumer = __esm({
10048
11045
  var claustrum_exports = {};
10049
11046
  __export(claustrum_exports, {
10050
11047
  CUSTODY_PLACEHOLDER_PREFIX: () => CUSTODY_PLACEHOLDER_PREFIX,
11048
+ ChangeNoticeReader: () => ChangeNoticeReader,
10051
11049
  ClaustrumConsumer: () => ClaustrumConsumer,
10052
11050
  ClaustrumConsumerError: () => ClaustrumConsumerError,
10053
- ClaustrumCredentialError: () => ClaustrumCredentialError3,
11051
+ ClaustrumCredentialError: () => ClaustrumCredentialError4,
10054
11052
  ClaustrumEnrollmentManager: () => ClaustrumEnrollmentManager,
10055
11053
  ClaustrumScopedCustody: () => ClaustrumScopedCustody,
11054
+ ClaustrumUnreachableError: () => ClaustrumUnreachableError,
10056
11055
  DEFAULT_ROUTE_PREFIX: () => DEFAULT_ROUTE_PREFIX,
11056
+ KEPT_RECEIPT_MARGIN_MS: () => KEPT_RECEIPT_MARGIN_MS,
11057
+ RESUBSCRIBE_BACKOFF_MS: () => RESUBSCRIBE_BACKOFF_MS,
10057
11058
  RETRYABLE_ENROLLMENT_CODES: () => RETRYABLE_ENROLLMENT_CODES,
11059
+ SAFETY_POLL_MS: () => SAFETY_POLL_MS,
10058
11060
  SERVING_MARGIN_MS: () => SERVING_MARGIN_MS,
11061
+ ScopedRosterWatch: () => ScopedRosterWatch,
10059
11062
  TERMINAL_ENROLLMENT_CODES: () => TERMINAL_ENROLLMENT_CODES,
11063
+ VAULT_FAILURE_CLASSES: () => VAULT_FAILURE_CLASSES,
11064
+ WATCH_RETRY_MS: () => WATCH_RETRY_MS,
10060
11065
  acceptAccount: () => acceptAccount,
10061
11066
  acceptVaultRoute: () => acceptVaultRoute,
11067
+ acquireInsulaQuotaSource: () => acquireInsulaQuotaSource,
10062
11068
  assertHostSlotMatchesMode: () => assertHostSlotMatchesMode,
10063
11069
  assertNotCustodyPlaceholder: () => assertNotCustodyPlaceholder,
10064
11070
  classifyEnrollmentError: () => classifyEnrollmentError,
10065
11071
  classifyHostSlot: () => classifyHostSlot,
11072
+ classifyVaultFailure: () => classifyVaultFailure,
10066
11073
  connectClaustrumEnrollmentClient: () => connectClaustrumEnrollmentClient,
10067
11074
  connectClaustrumScopedClient: () => connectClaustrumScopedClient,
10068
11075
  custodyPlaceholder: () => custodyPlaceholder,
@@ -10092,7 +11099,7 @@ __export(claustrum_exports, {
10092
11099
  vaultRoutingRows: () => vaultRoutingRows
10093
11100
  });
10094
11101
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
10095
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
11102
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
10096
11103
  async function connectClaustrumScopedClient(options) {
10097
11104
  const client = await ClaustrumClient.connect(options);
10098
11105
  return Object.assign(client, { insula: insulaUsageTransport(options) });
@@ -10101,13 +11108,16 @@ var init_claustrum = __esm({
10101
11108
  "../core/dist/common-auth-embedded/claustrum/index.js"() {
10102
11109
  "use strict";
10103
11110
  init_insula();
11111
+ init_availability();
10104
11112
  init_consumer();
10105
11113
  init_custody();
10106
11114
  init_enrollment();
10107
11115
  init_errors2();
10108
11116
  init_host_slot();
11117
+ init_insula();
10109
11118
  init_interlock();
10110
11119
  init_roster();
11120
+ init_watch();
10111
11121
  }
10112
11122
  });
10113
11123
 
@@ -20076,6 +21086,7 @@ var ANTIGRAVITY_SCOPES = [
20076
21086
  var ANTIGRAVITY_REDIRECT_URI = "http://localhost:51121/oauth-callback";
20077
21087
  var ANTIGRAVITY_ENDPOINT_DAILY = "https://daily-cloudcode-pa.googleapis.com";
20078
21088
  var ANTIGRAVITY_ENDPOINT_PROD = "https://cloudcode-pa.googleapis.com";
21089
+ var ANTIGRAVITY_QUOTA_ENDPOINT = ANTIGRAVITY_ENDPOINT_DAILY;
20079
21090
  var ANTIGRAVITY_ENDPOINT_FALLBACKS = [
20080
21091
  ANTIGRAVITY_ENDPOINT_DAILY,
20081
21092
  ANTIGRAVITY_ENDPOINT_PROD
@@ -20477,9 +21488,9 @@ function projectAntigravityQuota(quota) {
20477
21488
  const model = MODEL_LABELS[scope];
20478
21489
  if (!model)
20479
21490
  continue;
20480
- const windows = group.windows ?? [];
20481
- if (windows.length) {
20482
- for (const window of windows) {
21491
+ const windows2 = group.windows ?? [];
21492
+ if (windows2.length) {
21493
+ for (const window of windows2) {
20483
21494
  if (!Number.isFinite(window.remainingFraction))
20484
21495
  continue;
20485
21496
  const duration = window.window === "weekly" ? "7d" : "5h";
@@ -20504,7 +21515,15 @@ function projectAntigravityQuota(quota) {
20504
21515
  });
20505
21516
  }
20506
21517
  }
20507
- return { scope: "all", limits, checkedAt };
21518
+ return {
21519
+ scope: "all",
21520
+ limits,
21521
+ checkedAt,
21522
+ groups: [
21523
+ { scope: "gemini", label: "Gemini" },
21524
+ { scope: "non-gemini", label: "Other models" }
21525
+ ]
21526
+ };
20508
21527
  }
20509
21528
  function formatAntigravityQuota(quota, options) {
20510
21529
  return formatQuota(projectAntigravityQuota(quota), options);
@@ -21893,13 +22912,13 @@ function aggregateQuota(models) {
21893
22912
  perModel.sort((a, b) => a.modelId.localeCompare(b.modelId));
21894
22913
  return { groups, perModel, modelCount: totalCount };
21895
22914
  }
21896
- function mostConstrainedWindow(windows) {
21897
- if (windows.length === 0)
22915
+ function mostConstrainedWindow(windows2) {
22916
+ if (windows2.length === 0)
21898
22917
  return void 0;
21899
- let best = windows[0];
21900
- for (let i = 1; i < windows.length; i++) {
21901
- if (windows[i].remainingFraction < best.remainingFraction) {
21902
- best = windows[i];
22918
+ let best = windows2[0];
22919
+ for (let i = 1; i < windows2.length; i++) {
22920
+ if (windows2[i].remainingFraction < best.remainingFraction) {
22921
+ best = windows2[i];
21903
22922
  }
21904
22923
  }
21905
22924
  return {
@@ -21936,21 +22955,21 @@ function aggregateQuotaSummary(response) {
21936
22955
  const groups = {};
21937
22956
  let totalCount = 0;
21938
22957
  for (const group of response.groups) {
21939
- const windows = [];
22958
+ const windows2 = [];
21940
22959
  for (const bucket of group.buckets) {
21941
22960
  const pool2 = poolForBucketId(bucket.bucketId);
21942
22961
  if (!pool2)
21943
22962
  continue;
21944
- windows.push({
22963
+ windows2.push({
21945
22964
  window: bucket.window,
21946
22965
  remainingFraction: normalizeRemainingFraction(bucket.remainingFraction),
21947
22966
  resetTime: bucket.resetTime
21948
22967
  });
21949
22968
  }
21950
- if (windows.length === 0)
22969
+ if (windows2.length === 0)
21951
22970
  continue;
21952
- windows.sort((a, b) => windowDurationMs(a.window) - windowDurationMs(b.window));
21953
- const constrained = mostConstrainedWindow(windows);
22971
+ windows2.sort((a, b) => windowDurationMs(a.window) - windowDurationMs(b.window));
22972
+ const constrained = mostConstrainedWindow(windows2);
21954
22973
  const recognizedBucket = group.buckets.find((bucket) => poolForBucketId(bucket.bucketId));
21955
22974
  if (!recognizedBucket)
21956
22975
  continue;
@@ -21962,7 +22981,7 @@ function aggregateQuotaSummary(response) {
21962
22981
  remainingFraction: constrained.remainingFraction,
21963
22982
  resetTime: constrained.resetTime,
21964
22983
  modelCount,
21965
- windows
22984
+ windows: windows2
21966
22985
  };
21967
22986
  totalCount += modelCount;
21968
22987
  }
@@ -23438,7 +24457,8 @@ function admissionFromReceipt(ref, receipt2) {
23438
24457
  accountIdentity: receipt2.assertedAccountIdentity,
23439
24458
  recordVersion: receipt2.recordVersion,
23440
24459
  projectId: receipt2.projectId,
23441
- expiresAtMs: receipt2.expiresAtMs
24460
+ expiresAtMs: receipt2.expiresAtMs,
24461
+ fromKeptReceipt: receipt2.fromKeptReceipt
23442
24462
  };
23443
24463
  Object.defineProperty(admission, "accessToken", {
23444
24464
  value: receipt2.accessToken,
@@ -23467,7 +24487,8 @@ function createAntigravityVaultAccountSource(options) {
23467
24487
  pollIntervalMs: options.pollIntervalMs
23468
24488
  },
23469
24489
  ...options.now && { now: options.now },
23470
- ...options.logger && { logger: options.logger }
24490
+ ...options.logger && { logger: options.logger },
24491
+ ...options.insula && { insula: options.insula }
23471
24492
  });
23472
24493
  const issued = /* @__PURE__ */ new WeakMap();
23473
24494
  const isDeclined2 = claustrum.isDeclined.bind(claustrum);
@@ -23511,7 +24532,7 @@ function createAntigravityVaultAccountSource(options) {
23511
24532
  assertOpen();
23512
24533
  entry.reported = true;
23513
24534
  await consumer.reportFailure(entry.receipt, 401, reporterSource ?? options.reporterSource);
23514
- return true;
24535
+ return entry.receipt.fromKeptReceipt !== true;
23515
24536
  };
23516
24537
  const verifyAttribution = async (attribution, signal) => {
23517
24538
  await assertServing(signal);
@@ -23540,10 +24561,15 @@ function createAntigravityVaultAccountSource(options) {
23540
24561
  },
23541
24562
  routes: () => closed ? [] : routeRefs(consumer.snapshot(), isDeclined2),
23542
24563
  admit: admit2,
24564
+ retryAfter401: (served, current, site) => claustrum.decideScopedRetryAfter401(site, issuedEntry(served).receipt, current && issuedEntry(current).receipt, options.logger),
23543
24565
  send: async (ref, dispatch, sendOptions) => {
23544
24566
  const signal = sendOptions.signal;
23545
24567
  let admission = await admit2(ref, signal);
23546
24568
  let response = await dispatch(admission, signal);
24569
+ if (response.status === 401 && admission.fromKeptReceipt) {
24570
+ await reportServedStatus(admission, 401, sendOptions.reporterSource);
24571
+ return response;
24572
+ }
23547
24573
  if (response.status === 401 && !signal?.aborted) {
23548
24574
  let current;
23549
24575
  try {
@@ -23574,6 +24600,37 @@ function createAntigravityVaultAccountSource(options) {
23574
24600
  recordVersion: admission.recordVersion
23575
24601
  });
23576
24602
  },
24603
+ pollInsulaQuotaForRoute: async (ref, fallback, signal, onSkip) => {
24604
+ await assertServing(signal);
24605
+ assertCurrentRoute(ref);
24606
+ if (!consumer.pollInsulaQuotaForRoute)
24607
+ return fallback();
24608
+ let usedFallback = false;
24609
+ const reading = await untilAborted(consumer.pollInsulaQuotaForRoute(ref.routeId, () => {
24610
+ usedFallback = true;
24611
+ return fallback();
24612
+ }), signal);
24613
+ if (reading === void 0) {
24614
+ const result = consumer.lookupInsulaQuotaForRoute ? await untilAborted(consumer.lookupInsulaQuotaForRoute(ref.routeId), signal) : void 0;
24615
+ if (result?.miss === "cold" || result?.miss === "upstream-failed")
24616
+ onSkip?.(result.miss);
24617
+ return void 0;
24618
+ }
24619
+ if (usedFallback)
24620
+ return reading;
24621
+ if (reading.accountIdentity !== ref.accountIdentity)
24622
+ throw new AntigravityVaultSourceError("identity-contradicted", "The background quota reading belongs to another vault account");
24623
+ const admission = await admit2(ref, signal);
24624
+ return {
24625
+ ...reading,
24626
+ quotaAttribution: {
24627
+ routeId: admission.routeId,
24628
+ credentialId: admission.credentialId,
24629
+ accountIdentity: admission.accountIdentity,
24630
+ recordVersion: admission.recordVersion
24631
+ }
24632
+ };
24633
+ },
23577
24634
  commitState: async (attribution, update, signal) => {
23578
24635
  assertOpen(signal);
23579
24636
  if (!options.state)
@@ -24123,19 +25180,24 @@ async function replaceWindowsFile2(from, to, options = {}) {
24123
25180
  to = resolve7(to);
24124
25181
  const now = options.now ?? (() => performance.now());
24125
25182
  const start = now();
24126
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
25183
+ const leaseDeadline = options.deadline ?? Infinity;
25184
+ let retryDeadline;
24127
25185
  const delays = [0, 10, 20, 40, 80, 100];
24128
25186
  let original;
24129
25187
  let attempts2 = 0;
24130
25188
  for (const delay3 of delays) {
25189
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
24131
25190
  if (now() >= deadline)
24132
25191
  break;
24133
25192
  if (delay3)
24134
25193
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
24135
25194
  if (now() >= deadline)
24136
25195
  break;
25196
+ const fenceStart = now();
24137
25197
  await options.beforeRename?.();
24138
- if (now() >= deadline)
25198
+ if (retryDeadline !== void 0)
25199
+ retryDeadline += now() - fenceStart;
25200
+ if (now() >= leaseDeadline)
24139
25201
  break;
24140
25202
  attempts2++;
24141
25203
  try {
@@ -24147,6 +25209,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
24147
25209
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
24148
25210
  if (!candidate)
24149
25211
  break;
25212
+ retryDeadline ??= now() + 500;
24150
25213
  }
24151
25214
  }
24152
25215
  const error = new PrivateFileError2(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -27868,7 +28931,7 @@ function normalizeQuota(input2) {
27868
28931
  const resetAt = toFiniteNumber(record3.resetAt) ?? void 0;
27869
28932
  const checkedAt = toFiniteNumber(record3.checkedAt) ?? void 0;
27870
28933
  const windowsRaw = record3.windows;
27871
- let windows;
28934
+ let windows2;
27872
28935
  if (Array.isArray(windowsRaw)) {
27873
28936
  const parsed = windowsRaw.filter(isObject).map((w) => {
27874
28937
  const win = w.window;
@@ -27887,14 +28950,14 @@ function normalizeQuota(input2) {
27887
28950
  ...ca !== null && ca >= 0 ? { checkedAt: ca } : {}
27888
28951
  };
27889
28952
  }).filter((v) => v !== null);
27890
- if (parsed.length > 0) windows = parsed;
28953
+ if (parsed.length > 0) windows2 = parsed;
27891
28954
  }
27892
28955
  return {
27893
28956
  remainingPercent: clampNumber(remaining, 0, 100),
27894
28957
  ...fraction !== null ? { remainingFraction: clampNumber(fraction, 0, 1) } : {},
27895
28958
  resetAt,
27896
28959
  ...checkedAt !== void 0 ? { checkedAt } : {},
27897
- windows
28960
+ windows: windows2
27898
28961
  };
27899
28962
  }
27900
28963
  function normalizeRouting(input2) {
@@ -28014,7 +29077,7 @@ function projectQuotaPoolForSidebar(source, checkedAt) {
28014
29077
  const parsed = Date.parse(source.resetTime);
28015
29078
  if (Number.isFinite(parsed)) resetAt = parsed;
28016
29079
  }
28017
- const windows = source.windows?.length ? source.windows.map((w) => ({
29080
+ const windows2 = source.windows?.length ? source.windows.map((w) => ({
28018
29081
  window: w.window,
28019
29082
  ...readingAt !== void 0 ? { checkedAt: readingAt } : {},
28020
29083
  remainingPercent: clampNumber(
@@ -28032,7 +29095,7 @@ function projectQuotaPoolForSidebar(source, checkedAt) {
28032
29095
  remainingPercent,
28033
29096
  remainingFraction: clampNumber(fraction, 0, 1),
28034
29097
  resetAt,
28035
- windows,
29098
+ windows: windows2,
28036
29099
  ...readingAt !== void 0 ? { checkedAt: readingAt } : {}
28037
29100
  };
28038
29101
  }
@@ -28423,7 +29486,7 @@ async function fetchLegacyModelsFallback(options) {
28423
29486
  const modelsResponse = await fetchAvailableModels({
28424
29487
  accessToken: options.accessToken,
28425
29488
  projectId: options.projectId,
28426
- endpoints: ANTIGRAVITY_ENDPOINT_FALLBACKS,
29489
+ endpoints: [ANTIGRAVITY_QUOTA_ENDPOINT],
28427
29490
  userAgent: buildAntigravityHarnessUserAgent(),
28428
29491
  timeoutMs: 1e4,
28429
29492
  ...options.fetchVia ? { fetchVia: options.fetchVia } : {}
@@ -28452,7 +29515,7 @@ async function fetchQuotaPayloads(options) {
28452
29515
  accessToken,
28453
29516
  managedProjectId,
28454
29517
  projectId,
28455
- endpoints: ANTIGRAVITY_ENDPOINT_FALLBACKS,
29518
+ endpoints: [ANTIGRAVITY_QUOTA_ENDPOINT],
28456
29519
  userAgent: buildAntigravityHarnessUserAgent(),
28457
29520
  timeoutMs: 1e4,
28458
29521
  ...fetchVia ? { fetchVia } : {}
@@ -28569,7 +29632,7 @@ async function fetchVaultAccountQuota(options) {
28569
29632
  return result;
28570
29633
  };
28571
29634
  const fetchSummary = async () => {
28572
- for (const endpoint of ANTIGRAVITY_ENDPOINT_FALLBACKS) {
29635
+ for (const endpoint of [ANTIGRAVITY_QUOTA_ENDPOINT]) {
28573
29636
  const result = await attempt(
28574
29637
  async (grant, fetchVia) => aggregateQuotaSummary(
28575
29638
  (await fetchQuotaSummary({
@@ -28591,7 +29654,7 @@ async function fetchVaultAccountQuota(options) {
28591
29654
  }
28592
29655
  if (result.refused) break;
28593
29656
  }
28594
- for (const endpoint of ANTIGRAVITY_ENDPOINT_FALLBACKS) {
29657
+ for (const endpoint of [ANTIGRAVITY_QUOTA_ENDPOINT]) {
28595
29658
  for (const withProject of [true, false]) {
28596
29659
  const result = await attempt(
28597
29660
  (grant, fetchVia) => fetchAvailableModels({
@@ -28734,6 +29797,14 @@ function createAuthorizedFetchAccountQuota(options) {
28734
29797
  error: `quota check refused (stale grant: ${staleReason})`
28735
29798
  };
28736
29799
  }
29800
+ if (payloads.quota.error) {
29801
+ return {
29802
+ ...base,
29803
+ status: "error",
29804
+ disabled: false,
29805
+ error: payloads.quota.error
29806
+ };
29807
+ }
28737
29808
  return {
28738
29809
  ...base,
28739
29810
  status: "ok",
@@ -28809,6 +29880,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
28809
29880
  }),
28810
29881
  signal
28811
29882
  );
29883
+ if (payloads.quota.error) throw new Error(payloads.quota.error);
28812
29884
  return {
28813
29885
  index,
28814
29886
  email: account.email,
@@ -28864,6 +29936,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
28864
29936
  logger: log7
28865
29937
  });
28866
29938
  quotaResult = payloads.quota;
29939
+ if (quotaResult.error) throw new Error(quotaResult.error);
28867
29940
  fellBackToLegacy = payloads.fellBackToLegacy;
28868
29941
  for (const [family, groupQuota] of Object.entries(quotaResult.groups)) {
28869
29942
  const remainingPercent = (groupQuota.remainingFraction ?? 0) * 100;
@@ -35423,6 +36496,80 @@ async function retainResponseLifetime(response, cancellation) {
35423
36496
  }
35424
36497
  }
35425
36498
 
36499
+ // src/plugin/shared/after-handoff.ts
36500
+ function createAfterHandoff(work, signals, onFailure) {
36501
+ const controller = new AbortController();
36502
+ const cancellation = createRequestCancellation([
36503
+ ...signals,
36504
+ controller.signal
36505
+ ]);
36506
+ let run;
36507
+ let acknowledged = false;
36508
+ let finished = false;
36509
+ let running = false;
36510
+ let resolveCompletion = () => {
36511
+ };
36512
+ const completion = new Promise((resolve18) => {
36513
+ resolveCompletion = resolve18;
36514
+ });
36515
+ const finish = () => {
36516
+ if (finished) return;
36517
+ finished = true;
36518
+ run = void 0;
36519
+ cancellation.signal.removeEventListener("abort", onAbort);
36520
+ cancellation.release();
36521
+ work.delete(completion);
36522
+ resolveCompletion();
36523
+ };
36524
+ const onAbort = () => {
36525
+ if (!running) finish();
36526
+ };
36527
+ cancellation.signal.addEventListener("abort", onAbort, { once: true });
36528
+ if (cancellation.signal.aborted) onAbort();
36529
+ return {
36530
+ register(callback) {
36531
+ if (finished || run) return;
36532
+ run = callback;
36533
+ work.add(completion);
36534
+ },
36535
+ acknowledge() {
36536
+ if (finished || acknowledged || !run) return;
36537
+ acknowledged = true;
36538
+ void Promise.resolve().then(async () => {
36539
+ if (finished || cancellation.signal.aborted) return;
36540
+ running = true;
36541
+ try {
36542
+ await run?.(cancellation.signal);
36543
+ } catch {
36544
+ try {
36545
+ onFailure();
36546
+ } catch {
36547
+ }
36548
+ } finally {
36549
+ finish();
36550
+ }
36551
+ });
36552
+ },
36553
+ cancel() {
36554
+ controller.abort();
36555
+ onAbort();
36556
+ }
36557
+ };
36558
+ }
36559
+ function publishResponse(dispatch) {
36560
+ return new Promise((resolve18, reject) => {
36561
+ let acknowledge;
36562
+ void Promise.resolve().then(
36563
+ () => dispatch((callback) => {
36564
+ acknowledge = callback;
36565
+ })
36566
+ ).then((response) => {
36567
+ resolve18(response);
36568
+ acknowledge?.();
36569
+ }, reject);
36570
+ });
36571
+ }
36572
+
35426
36573
  // src/plugin/shared/request-services.ts
35427
36574
  var FIRST_RETRY_DELAY_MS = 1e3;
35428
36575
  function prepareAgyWireRequest(wire, request) {
@@ -36472,24 +37619,17 @@ function createRequestExecutor(deps) {
36472
37619
  );
36473
37620
  noteGeminiDumpResponse(dumpContext, response);
36474
37621
  if (credentials.domain === "vault" && sendAdmission && response.status === 401) {
36475
- try {
36476
- await deadline.wait(
36477
- () => sendAdmission.report401(response.status)
36478
- );
36479
- } catch (error) {
36480
- checkAborted();
36481
- log16.debug("send-admission-401-report-failed", {
36482
- error: String(error)
36483
- });
36484
- }
36485
- if (!vault401Retried) {
36486
- const next = await deadline.wait(
36487
- () => credentials.admit({
36488
- account,
36489
- signal: abortSignal
36490
- })
36491
- );
36492
- if (next.credentialId === sendAdmission.credentialId && next.accountIdentity === sendAdmission.accountIdentity && next.recordVersion > sendAdmission.recordVersion) {
37622
+ if (!sendAdmission.fromKeptReceipt && !vault401Retried && !abortSignal?.aborted) {
37623
+ let next;
37624
+ try {
37625
+ next = await deadline.wait(
37626
+ () => credentials.admit({ account, signal: abortSignal })
37627
+ );
37628
+ } catch {
37629
+ checkAborted();
37630
+ }
37631
+ const retry = credentials.retryAfter401 ? credentials.retryAfter401(sendAdmission, next, "model") : next && !next.fromKeptReceipt && next.credentialId === sendAdmission.credentialId && next.accountIdentity === sendAdmission.accountIdentity && next.recordVersion > sendAdmission.recordVersion;
37632
+ if (next && retry) {
36493
37633
  vault401Retried = true;
36494
37634
  rotatedAdmission = next;
36495
37635
  void response.body?.cancel().catch(() => {
@@ -36501,6 +37641,16 @@ function createRequestExecutor(deps) {
36501
37641
  continue;
36502
37642
  }
36503
37643
  }
37644
+ try {
37645
+ await deadline.wait(
37646
+ () => sendAdmission.report401(response.status)
37647
+ );
37648
+ } catch (error) {
37649
+ checkAborted();
37650
+ log16.debug("send-admission-401-report-failed", {
37651
+ error: String(error)
37652
+ });
37653
+ }
36504
37654
  }
36505
37655
  const sessionKey = requestSessionIdentity.sessionId;
36506
37656
  if (sessionKey) {
@@ -36775,23 +37925,6 @@ function createRequestExecutor(deps) {
36775
37925
  trackers.health.recordSuccess(account.index);
36776
37926
  if (!advisoryClosing)
36777
37927
  accountManager.markAccountUsed(account.index);
36778
- if (credentials.domain === "local" && !advisoryClosing && credentials.refreshQuotaAfterSuccess) {
36779
- const quotaCancellation = createRequestCancellation(
36780
- init?.signal ? [init.signal, shutdown.signal] : [shutdown.signal]
36781
- );
36782
- const work = credentials.refreshQuotaAfterSuccess(
36783
- account,
36784
- config.quota_refresh_interval_minutes,
36785
- quotaCancellation.signal
36786
- ).catch(() => {
36787
- log16.debug("post-response-advisory-work-failed");
36788
- }).finally(() => quotaCancellation.release());
36789
- advisoryWork.add(work);
36790
- void work.then(
36791
- () => advisoryWork.delete(work),
36792
- () => advisoryWork.delete(work)
36793
- );
36794
- }
36795
37928
  const proactiveThreshold = config.proactive_rotation_threshold_percent ?? 20;
36796
37929
  if (!advisoryClosing && proactiveThreshold > 0 && accountManager.shouldProactivelyRotate(
36797
37930
  family,
@@ -36939,6 +38072,10 @@ function createRequestExecutor(deps) {
36939
38072
  );
36940
38073
  }
36941
38074
  }
38075
+ if (response.ok && transformedResponse.ok && credentials.domain === "local" && !advisoryClosing && credentials.refreshQuotaAfterSuccess) {
38076
+ const refresh = credentials.refreshQuotaAfterSuccess;
38077
+ waitPolicy.quota = (signal) => refresh(account, config.quota_refresh_interval_minutes, signal);
38078
+ }
36942
38079
  return transformedResponse;
36943
38080
  } catch (error) {
36944
38081
  if (error instanceof PreResponseTimeoutError) throw error;
@@ -37139,6 +38276,11 @@ function createRequestExecutor(deps) {
37139
38276
  deps.preResponseClock
37140
38277
  );
37141
38278
  log16.debug("pre-response-start", { limitMs: PRE_RESPONSE_DEADLINE_MS });
38279
+ const handoff = createAfterHandoff(
38280
+ advisoryWork,
38281
+ requestedSignal ? [requestedSignal, shutdown.signal] : [shutdown.signal],
38282
+ () => log16.debug("post-response-advisory-work-failed")
38283
+ );
37142
38284
  const waitPolicy = {};
37143
38285
  const selectedCredentials = /* @__PURE__ */ new Set();
37144
38286
  const selectedProjectIds = /* @__PURE__ */ new Set();
@@ -37163,6 +38305,7 @@ function createRequestExecutor(deps) {
37163
38305
  async (response) => {
37164
38306
  deadline.acceptTerminalResponse();
37165
38307
  if (bufferedOverflow.has(response)) {
38308
+ handoff.cancel();
37166
38309
  deadline.dispose();
37167
38310
  cancellation.release();
37168
38311
  return redactCredentialResponse(
@@ -37179,14 +38322,22 @@ function createRequestExecutor(deps) {
37179
38322
  inFlight.add(retained.settled);
37180
38323
  void retained.settled.then(() => inFlight.delete(retained.settled));
37181
38324
  void retained.settled.then(() => deadline.dispose());
37182
- return redactCredentialResponse(
38325
+ const published = await redactCredentialResponse(
37183
38326
  preserveResponseMetadata2(retained.response, response),
37184
38327
  [...selectedCredentials],
37185
38328
  void 0,
37186
38329
  [...selectedProjectIds]
37187
38330
  );
38331
+ if (published.ok && waitPolicy.quota && requestOptions?.onResponseHandoff) {
38332
+ handoff.register(waitPolicy.quota);
38333
+ requestOptions.onResponseHandoff(handoff.acknowledge);
38334
+ } else {
38335
+ handoff.cancel();
38336
+ }
38337
+ return published;
37188
38338
  },
37189
38339
  (error) => {
38340
+ handoff.cancel();
37190
38341
  deadline.dispose();
37191
38342
  cancellation.release();
37192
38343
  throw redactCredentialError(
@@ -37196,6 +38347,7 @@ function createRequestExecutor(deps) {
37196
38347
  );
37197
38348
  }
37198
38349
  ).catch((error) => {
38350
+ handoff.cancel();
37199
38351
  deadline.dispose();
37200
38352
  cancellation.release();
37201
38353
  throw redactCredentialError(
@@ -38171,6 +39323,7 @@ function refreshVaultAccountRow(prior, fresh) {
38171
39323
  else prior.email = fresh.email;
38172
39324
  }
38173
39325
  var VaultSendGrant = class {
39326
+ fromKeptReceipt;
38174
39327
  credentialId;
38175
39328
  accountIdentity;
38176
39329
  recordVersion;
@@ -38185,20 +39338,36 @@ var VaultSendGrant = class {
38185
39338
  this.accountIdentity = admission.accountIdentity;
38186
39339
  this.recordVersion = admission.recordVersion;
38187
39340
  this.projectId = admission.projectId;
39341
+ this.fromKeptReceipt = admission.fromKeptReceipt;
38188
39342
  this.report401 = report;
38189
39343
  }
38190
39344
  };
38191
39345
  function createVaultRequestCredentials(source, onAdmitted) {
39346
+ const issued = /* @__PURE__ */ new WeakMap();
38192
39347
  return {
38193
39348
  domain: "vault",
39349
+ ...source.retryAfter401 && {
39350
+ retryAfter401(served, current, site) {
39351
+ const original = issued.get(served);
39352
+ if (!original)
39353
+ throw new Error("Retry requires an original vault admission");
39354
+ return source.retryAfter401(
39355
+ original,
39356
+ current && issued.get(current),
39357
+ site
39358
+ );
39359
+ }
39360
+ },
38194
39361
  async admit({ account, signal }) {
38195
39362
  const admission = await source.admit(account.route, signal);
38196
39363
  if (onAdmitted)
38197
39364
  onAdmitted.admitted(account, onAdmitted.source.attribution(admission));
38198
- return new VaultSendGrant(
39365
+ const grant = new VaultSendGrant(
38199
39366
  admission,
38200
39367
  (status) => source.reportServedStatus(admission, status)
38201
39368
  );
39369
+ issued.set(grant, admission);
39370
+ return grant;
38202
39371
  }
38203
39372
  };
38204
39373
  }
@@ -38496,6 +39665,10 @@ async function checkVaultQuota(input2) {
38496
39665
  input2.onStage?.("fetch");
38497
39666
  const answer = await input2.fetchReading(row.route, input2.signal);
38498
39667
  input2.signal.throwIfAborted();
39668
+ if (answer === void 0) {
39669
+ input2.onOutcome?.("fetch-failed");
39670
+ continue;
39671
+ }
38499
39672
  const attribution = answer.quotaAttribution;
38500
39673
  if (answer.quota.error !== void 0) {
38501
39674
  input2.onOutcome?.("fetch-failed");
@@ -38505,7 +39678,7 @@ async function checkVaultQuota(input2) {
38505
39678
  input2.onOutcome?.("unattributed");
38506
39679
  continue;
38507
39680
  }
38508
- const reading = vaultQuotaState(answer.quota, now());
39681
+ const reading = vaultQuotaState(answer.quota, answer.observedAt ?? now());
38509
39682
  input2.onStage?.("commit");
38510
39683
  input2.signal.throwIfAborted();
38511
39684
  const result = await state.recordQuota(attribution, reading, input2.signal);
@@ -38539,6 +39712,50 @@ async function checkVaultQuota(input2) {
38539
39712
  // src/plugin/vault-custody.ts
38540
39713
  import { chmod as chmod3, mkdir as mkdir11, readFile as readFile9 } from "node:fs/promises";
38541
39714
  import { dirname as dirname18, join as join16 } from "node:path";
39715
+
39716
+ // src/plugin/vault-insula-quota.ts
39717
+ var windows = [
39718
+ ["gemini-5h", "gemini", "5h"],
39719
+ ["gemini-weekly", "gemini", "weekly"],
39720
+ ["3p-5h", "non-gemini", "5h"],
39721
+ ["3p-weekly", "non-gemini", "weekly"]
39722
+ ];
39723
+ var normalizeVaultInsulaQuota = (entry, context) => {
39724
+ if (entry.source !== "vault") return void 0;
39725
+ if (entry.provider !== "antigravity" || !entry.account?.trim() || !Number.isFinite(context.fetchedAt))
39726
+ return void 0;
39727
+ const groups = {};
39728
+ for (const [id, group, window] of windows) {
39729
+ const reading = entry.usage?.extraRateWindows?.find(
39730
+ (extra) => extra.id === id
39731
+ )?.window;
39732
+ if (!reading || !Number.isFinite(reading.usedPercent) || reading.usedPercent < 0 || reading.usedPercent > 100)
39733
+ continue;
39734
+ const normalized = {
39735
+ window,
39736
+ remainingFraction: 1 - reading.usedPercent / 100,
39737
+ resetTime: reading.resetsAt ?? ""
39738
+ };
39739
+ let summary = groups[group];
39740
+ if (summary === void 0) {
39741
+ summary = { modelCount: 0, windows: [] };
39742
+ groups[group] = summary;
39743
+ }
39744
+ summary.windows?.push(normalized);
39745
+ if (summary.remainingFraction === void 0 || normalized.remainingFraction < summary.remainingFraction) {
39746
+ summary.remainingFraction = normalized.remainingFraction;
39747
+ summary.resetTime = normalized.resetTime;
39748
+ }
39749
+ }
39750
+ if (Object.keys(groups).length === 0) return void 0;
39751
+ return {
39752
+ quota: { groups, modelCount: 0 },
39753
+ accountIdentity: entry.account.trim(),
39754
+ observedAt: context.fetchedAt
39755
+ };
39756
+ };
39757
+
39758
+ // src/plugin/vault-custody.ts
38542
39759
  var OPENCODE_VAULT_PROVIDER = "google";
38543
39760
  var OPENCODE_VAULT_HOST = "opencode";
38544
39761
  var OPENCODE_VAULT_ENROLLMENT_NAME = getAntigravityVaultEnrollmentName(OPENCODE_VAULT_HOST);
@@ -38646,8 +39863,15 @@ function createOpenCodeVaultCustody(options) {
38646
39863
  onError: () => options.onRosterChanged?.(),
38647
39864
  reporterSource: options.reporterSource,
38648
39865
  state: { path: paths.stateFile, fs: await loadCommonAuthFs() },
39866
+ ...options.insulaQuota ? {
39867
+ insula: {
39868
+ provider: "antigravity",
39869
+ normalize: normalizeVaultInsulaQuota
39870
+ }
39871
+ } : {},
38649
39872
  ...options.logger ? { logger: options.logger } : {},
38650
- ...options.now ? { now: options.now } : {}
39873
+ ...options.now ? { now: options.now } : {},
39874
+ ...options.pollIntervalMs !== void 0 ? { pollIntervalMs: options.pollIntervalMs } : {}
38651
39875
  });
38652
39876
  const activeSource = {
38653
39877
  ...created,
@@ -39705,6 +40929,7 @@ function createGaJobExecutor(executor, overrides = {}) {
39705
40929
  {
39706
40930
  kind: job.kind,
39707
40931
  variant: job.variant ?? void 0,
40932
+ ...context.onResponseHandoff ? { onResponseHandoff: context.onResponseHandoff } : {},
39708
40933
  session: {
39709
40934
  sessionId: job.sessionID,
39710
40935
  parentSessionId: job.parentSessionID
@@ -42270,18 +43495,34 @@ async function startGaLoopbackBridge(options) {
42270
43495
  });
42271
43496
  try {
42272
43497
  let upstream;
43498
+ let acknowledge;
42273
43499
  try {
42274
43500
  upstream = await options.execute(entry.job, {
42275
43501
  signal: controller.signal,
42276
- send: options.send
43502
+ send: options.send,
43503
+ onResponseHandoff: (callback) => {
43504
+ acknowledge = callback;
43505
+ }
42277
43506
  });
42278
43507
  } catch (error) {
43508
+ acknowledge = void 0;
42279
43509
  upstream = gaPreHeaderFailureResponse(error);
42280
43510
  }
42281
- await pipeResponse(upstream, response, (error) => {
42282
- if (!state.released && (state.claimed || !closing))
42283
- state.failure = error;
42284
- });
43511
+ await pipeResponse(
43512
+ upstream,
43513
+ response,
43514
+ (error) => {
43515
+ if (!state.released && (state.claimed || !closing))
43516
+ state.failure = error;
43517
+ },
43518
+ () => {
43519
+ if (!response.destroyed && !controller.signal.aborted && !closing) {
43520
+ const callback = acknowledge;
43521
+ acknowledge = void 0;
43522
+ callback?.();
43523
+ }
43524
+ }
43525
+ );
42285
43526
  } finally {
42286
43527
  running.delete(controller);
42287
43528
  if (!closing && !state.claimed && !state.released) {
@@ -42436,7 +43677,7 @@ function writeResponseHead(response, status, contentType) {
42436
43677
  "cache-control": "no-cache"
42437
43678
  });
42438
43679
  }
42439
- async function pipeResponse(upstream, response, onFailure) {
43680
+ async function pipeResponse(upstream, response, onFailure, onHandoff) {
42440
43681
  const contentType = upstream.headers.get("content-type") ?? "application/octet-stream";
42441
43682
  if (response.destroyed) {
42442
43683
  await upstream.body?.cancel().catch(() => {
@@ -42444,6 +43685,8 @@ async function pipeResponse(upstream, response, onFailure) {
42444
43685
  return;
42445
43686
  }
42446
43687
  writeResponseHead(response, upstream.status, contentType);
43688
+ response.flushHeaders();
43689
+ onHandoff();
42447
43690
  if (!upstream.body) {
42448
43691
  response.end();
42449
43692
  return;
@@ -42656,10 +43899,10 @@ function createGaRpcActivation(options) {
42656
43899
  const { email: _email, quota, ...rest } = account;
42657
43900
  const entry = (value) => {
42658
43901
  if (value === void 0) return void 0;
42659
- const { remainingFraction: _fraction, windows, ...fields } = value;
42660
- return windows === void 0 ? fields : {
43902
+ const { remainingFraction: _fraction, windows: windows2, ...fields } = value;
43903
+ return windows2 === void 0 ? fields : {
42661
43904
  ...fields,
42662
- windows: windows.map(
43905
+ windows: windows2.map(
42663
43906
  ({ remainingFraction: _windowFraction, ...window }) => window
42664
43907
  )
42665
43908
  };
@@ -43416,7 +44659,7 @@ import { createHash as createHash15, randomBytes as randomBytes6, randomUUID as
43416
44659
  import { constants as fsConstants2 } from "node:fs";
43417
44660
  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";
43418
44661
  import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute3, join as join18, resolve as resolve12 } from "node:path";
43419
- import { ClaustrumCredentialError as ClaustrumCredentialError4, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
44662
+ import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
43420
44663
 
43421
44664
  // src/common-auth-embedded/fs/lock-constants.js
43422
44665
  var WRITER_LOCK_CONSTANTS2 = Object.freeze({
@@ -44098,7 +45341,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
44098
45341
  "pending_queue_full"
44099
45342
  ]);
44100
45343
  function classifyEnrollmentError2(error) {
44101
- if (!(error instanceof ClaustrumCredentialError4))
45344
+ if (!(error instanceof ClaustrumCredentialError5))
44102
45345
  return void 0;
44103
45346
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
44104
45347
  return { code: error.code, disposition: "terminal" };
@@ -45200,9 +46443,9 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);
45200
46443
  }
45201
46444
  };
45202
46445
  async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
45203
- const windows = (options.platform ?? process.platform) === "win32";
46446
+ const windows2 = (options.platform ?? process.platform) === "win32";
45204
46447
  let inspection = {
45205
- step: windows ? "tasklist" : "ps",
46448
+ step: windows2 ? "tasklist" : "ps",
45206
46449
  exitCode: null,
45207
46450
  signal: null,
45208
46451
  timedOut: false,
@@ -45237,7 +46480,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
45237
46480
  }
45238
46481
  };
45239
46482
  try {
45240
- const result = await inspect(windows ? "tasklist" : "ps", windows ? "tasklist.exe" : "ps", windows ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
46483
+ const result = await inspect(windows2 ? "tasklist" : "ps", windows2 ? "tasklist.exe" : "ps", windows2 ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
45241
46484
  if (result.exitCode !== 0)
45242
46485
  throw new ProcessInspectionError(inspection);
45243
46486
  const processes = [];
@@ -45247,7 +46490,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
45247
46490
  continue;
45248
46491
  let pid;
45249
46492
  let command;
45250
- if (windows) {
46493
+ if (windows2) {
45251
46494
  const match = /^"([^"]+)","(\d+)"(?:,|$)/.exec(trimmed);
45252
46495
  if (!match)
45253
46496
  throw new ProcessInspectionError(inspection);
@@ -45270,7 +46513,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
45270
46513
  if (!processes.length)
45271
46514
  throw new ProcessInspectionError(inspection);
45272
46515
  const runtimes = processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command));
45273
- if (windows && runtimes.length && options.inspectRuntimes !== false) {
46516
+ if (windows2 && runtimes.length && options.inspectRuntimes !== false) {
45274
46517
  const details = await inspect("CIM", "powershell.exe", [
45275
46518
  "-NoProfile",
45276
46519
  "-NonInteractive",
@@ -45313,10 +46556,10 @@ function createProcessFence(runner = defaultCommandRunner, options = {}) {
45313
46556
  env: env3,
45314
46557
  inspectRuntimes: false
45315
46558
  });
45316
- const windows = (options.platform ?? process.platform) === "win32";
46559
+ const windows2 = (options.platform ?? process.platform) === "win32";
45317
46560
  return {
45318
46561
  hosts: processes.filter(isHost),
45319
- uncheckedRuntimes: windows ? processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
46562
+ uncheckedRuntimes: windows2 ? processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
45320
46563
  };
45321
46564
  }
45322
46565
  };
@@ -45427,11 +46670,11 @@ import { mkdir as mkdir14, open as open11, rename as rename10, stat as stat9, un
45427
46670
  import { basename as basename6, dirname as dirname21, join as join20 } from "node:path";
45428
46671
  import { setTimeout as delay2 } from "node:timers/promises";
45429
46672
  async function writeHostConfigAtomic(file, content, options = {}) {
45430
- const windows = (options.platform ?? process.platform) === "win32";
46673
+ const windows2 = (options.platform ?? process.platform) === "win32";
45431
46674
  const parent = dirname21(file);
45432
46675
  await mkdir14(parent, { recursive: true });
45433
46676
  let mode;
45434
- if (!windows) {
46677
+ if (!windows2) {
45435
46678
  try {
45436
46679
  mode = (await stat9(file)).mode & 4095;
45437
46680
  } catch (error) {
@@ -45462,7 +46705,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
45462
46705
  } catch (error) {
45463
46706
  const code2 = error.code;
45464
46707
  const remaining = 2e3 - (now() - started);
45465
- if (!windows || !["EPERM", "EBUSY", "EACCES"].includes(code2 ?? "") || remaining <= 0 || attempt >= 40)
46708
+ if (!windows2 || !["EPERM", "EBUSY", "EACCES"].includes(code2 ?? "") || remaining <= 0 || attempt >= 40)
45466
46709
  throw new Error(`Unable to replace host config ${file}. Close editors or other programs using the file, then rerun setup.`);
45467
46710
  await (options.wait ?? delay2)(Math.min(remaining, 25 * 2 ** Math.min(attempt, 2)));
45468
46711
  }
@@ -50710,7 +51953,7 @@ function createAuthLoader({
50710
51953
  // through the OLD interceptor after an OAuth add. The wrapper
50711
51954
  // matches the host's `LoaderResult.fetch` signature exactly
50712
51955
  // (no `this` binding) so behavior is preserved.
50713
- fetch: async (input2, init) => {
51956
+ fetch: (input2, init) => publishResponse(async (onResponseHandoff) => {
50714
51957
  assertOpen();
50715
51958
  const authority = await readAuthority2?.() ?? "local";
50716
51959
  assertOpen();
@@ -50724,7 +51967,7 @@ function createAuthLoader({
50724
51967
  });
50725
51968
  const vaultRuntime = await vaultFetchRuntime;
50726
51969
  assertOpen();
50727
- return vaultRuntime.fetch(input2, init);
51970
+ return vaultRuntime.fetch(input2, init, onResponseHandoff);
50728
51971
  }
50729
51972
  if (localUnavailable) {
50730
51973
  return fetchWithoutLocalAccounts(input2, init, fetchImpl);
@@ -50748,8 +51991,8 @@ function createAuthLoader({
50748
51991
  return fetchWithoutLocalAccounts(input2, init, fetchImpl);
50749
51992
  if (currentRequestSource !== "local" || !fetchRuntime)
50750
51993
  throw new Error("The local account runtime is unavailable");
50751
- return fetchRuntime.fetch(input2, init);
50752
- }
51994
+ return fetchRuntime.fetch(input2, init, onResponseHandoff);
51995
+ })
50753
51996
  };
50754
51997
  }
50755
51998
  reloadRuntime = async (getAuth) => {
@@ -51050,7 +52293,7 @@ var BackgroundVaultQuotaRefresh = class {
51050
52293
  fetchReading: async (ref, signal) => {
51051
52294
  rowFailure = "fetch-failed";
51052
52295
  await this.assertActive(controller);
51053
- const reading = await fetchVaultAccountQuota({
52296
+ const fallback = () => fetchVaultAccountQuota({
51054
52297
  source,
51055
52298
  ref,
51056
52299
  signal,
@@ -51060,7 +52303,10 @@ var BackgroundVaultQuotaRefresh = class {
51060
52303
  if (kind !== "unknown" || outcome.errorKind === void 0)
51061
52304
  outcome.errorKind = kind;
51062
52305
  if (refused)
51063
- rowFailure = vaultQuotaErrorReason(error, "admission-refused");
52306
+ rowFailure = vaultQuotaErrorReason(
52307
+ error,
52308
+ "admission-refused"
52309
+ );
51064
52310
  },
51065
52311
  transport: async (url, init, extra) => {
51066
52312
  await this.assertActive(controller);
@@ -51083,6 +52329,16 @@ var BackgroundVaultQuotaRefresh = class {
51083
52329
  }
51084
52330
  }
51085
52331
  });
52332
+ const reading = source.pollInsulaQuotaForRoute ? await source.pollInsulaQuotaForRoute(
52333
+ ref,
52334
+ fallback,
52335
+ signal,
52336
+ (reason) => {
52337
+ rowFailure = `insula-${reason}`;
52338
+ }
52339
+ ) : await fallback();
52340
+ if (reading === void 0 && rowFailure === "fetch-failed")
52341
+ rowFailure = "insula-skipped";
51086
52342
  await this.assertActive(controller);
51087
52343
  await lock.assertOwned();
51088
52344
  return reading;
@@ -51413,7 +52669,7 @@ function toCommandAccountRow(entry) {
51413
52669
  const parsed = Date.parse(cachedEntry.resetTime);
51414
52670
  if (Number.isFinite(parsed)) resetAt = parsed;
51415
52671
  }
51416
- const windows = cachedEntry.windows?.length ? cachedEntry.windows.map((w) => ({
52672
+ const windows2 = cachedEntry.windows?.length ? cachedEntry.windows.map((w) => ({
51417
52673
  window: w.window,
51418
52674
  remainingPercent: Math.round(w.remainingFraction * 100),
51419
52675
  resetAt: typeof w.resetTime === "string" && w.resetTime.length > 0 ? (() => {
@@ -51426,7 +52682,7 @@ function toCommandAccountRow(entry) {
51426
52682
  label: QUOTA_GROUP_LABELS[key],
51427
52683
  remainingPercent,
51428
52684
  resetAt,
51429
- windows
52685
+ windows: windows2
51430
52686
  });
51431
52687
  }
51432
52688
  const label = `Account ${entry.index + 1}`;
@@ -51729,9 +52985,11 @@ function createFetchInterceptor(context) {
51729
52985
  body: { type: "oauth", refresh: "", access: "", expires: 0 }
51730
52986
  });
51731
52987
  },
51732
- refreshQuotaAfterSuccess: async (account, intervalMinutes) => {
52988
+ refreshQuotaAfterSuccess: async (account, intervalMinutes, signal) => {
52989
+ signal?.throwIfAborted();
51733
52990
  await context.assertAdmission?.();
51734
- await refreshQuotaAfterSuccess(account, intervalMinutes);
52991
+ signal?.throwIfAborted();
52992
+ await refreshQuotaAfterSuccess(account, intervalMinutes, signal);
51735
52993
  }
51736
52994
  },
51737
52995
  // The trackers the manager selects with: its own for a store-backed
@@ -51750,7 +53008,7 @@ function createFetchInterceptor(context) {
51750
53008
  let retired = false;
51751
53009
  let retirePromise;
51752
53010
  const entering = /* @__PURE__ */ new Set();
51753
- async function intercept(input2, init) {
53011
+ async function intercept(input2, init, onResponseHandoff) {
51754
53012
  await context.assertAdmission?.();
51755
53013
  if (disposed) throw new Error("The local request runtime is disposed");
51756
53014
  if (accountSource.kind === "pool-file") {
@@ -51758,9 +53016,9 @@ function createFetchInterceptor(context) {
51758
53016
  if (disposed) throw new Error("The local request runtime is disposed");
51759
53017
  if (!isOAuthAuth(latestAuth)) return upstreamFetch(input2, init);
51760
53018
  }
51761
- return executor.execute(input2, init);
53019
+ return executor.execute(input2, init, { onResponseHandoff });
51762
53020
  }
51763
- async function fetch(input2, init) {
53021
+ async function fetch(input2, init, onResponseHandoff) {
51764
53022
  if (disposed) {
51765
53023
  return upstreamFetch(input2, init);
51766
53024
  }
@@ -51768,7 +53026,7 @@ function createFetchInterceptor(context) {
51768
53026
  return upstreamFetch(input2, init);
51769
53027
  }
51770
53028
  if (retired) throw new Error("The local request runtime is retired");
51771
- const pending = intercept(input2, init);
53029
+ const pending = intercept(input2, init, onResponseHandoff);
51772
53030
  entering.add(pending);
51773
53031
  void pending.then(
51774
53032
  () => entering.delete(pending),
@@ -52336,6 +53594,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
52336
53594
  let vaultQuotaPoller;
52337
53595
  const vaultCustody = createOpenCodeVaultCustody({
52338
53596
  accountFile: resolve17(getStoragePath()),
53597
+ insulaQuota: true,
52339
53598
  readHostSlot: async () => {
52340
53599
  if (!cachedGetAuth)
52341
53600
  throw new Error("OpenCode has not provided its sign-in yet");