@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/index.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.
9821
+ */
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.
9123
9909
  */
9124
- async authorize(identity, signal) {
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
 
@@ -20074,6 +21084,7 @@ var ANTIGRAVITY_SCOPES = [
20074
21084
  var ANTIGRAVITY_REDIRECT_URI = "http://localhost:51121/oauth-callback";
20075
21085
  var ANTIGRAVITY_ENDPOINT_DAILY = "https://daily-cloudcode-pa.googleapis.com";
20076
21086
  var ANTIGRAVITY_ENDPOINT_PROD = "https://cloudcode-pa.googleapis.com";
21087
+ var ANTIGRAVITY_QUOTA_ENDPOINT = ANTIGRAVITY_ENDPOINT_DAILY;
20077
21088
  var ANTIGRAVITY_ENDPOINT_FALLBACKS = [
20078
21089
  ANTIGRAVITY_ENDPOINT_DAILY,
20079
21090
  ANTIGRAVITY_ENDPOINT_PROD
@@ -20475,9 +21486,9 @@ function projectAntigravityQuota(quota) {
20475
21486
  const model = MODEL_LABELS[scope];
20476
21487
  if (!model)
20477
21488
  continue;
20478
- const windows = group.windows ?? [];
20479
- if (windows.length) {
20480
- for (const window of windows) {
21489
+ const windows2 = group.windows ?? [];
21490
+ if (windows2.length) {
21491
+ for (const window of windows2) {
20481
21492
  if (!Number.isFinite(window.remainingFraction))
20482
21493
  continue;
20483
21494
  const duration = window.window === "weekly" ? "7d" : "5h";
@@ -20502,7 +21513,15 @@ function projectAntigravityQuota(quota) {
20502
21513
  });
20503
21514
  }
20504
21515
  }
20505
- return { scope: "all", limits, checkedAt };
21516
+ return {
21517
+ scope: "all",
21518
+ limits,
21519
+ checkedAt,
21520
+ groups: [
21521
+ { scope: "gemini", label: "Gemini" },
21522
+ { scope: "non-gemini", label: "Other models" }
21523
+ ]
21524
+ };
20506
21525
  }
20507
21526
  function formatAntigravityQuota(quota, options) {
20508
21527
  return formatQuota(projectAntigravityQuota(quota), options);
@@ -21891,13 +22910,13 @@ function aggregateQuota(models) {
21891
22910
  perModel.sort((a, b) => a.modelId.localeCompare(b.modelId));
21892
22911
  return { groups, perModel, modelCount: totalCount };
21893
22912
  }
21894
- function mostConstrainedWindow(windows) {
21895
- if (windows.length === 0)
22913
+ function mostConstrainedWindow(windows2) {
22914
+ if (windows2.length === 0)
21896
22915
  return void 0;
21897
- let best = windows[0];
21898
- for (let i = 1; i < windows.length; i++) {
21899
- if (windows[i].remainingFraction < best.remainingFraction) {
21900
- best = windows[i];
22916
+ let best = windows2[0];
22917
+ for (let i = 1; i < windows2.length; i++) {
22918
+ if (windows2[i].remainingFraction < best.remainingFraction) {
22919
+ best = windows2[i];
21901
22920
  }
21902
22921
  }
21903
22922
  return {
@@ -21934,21 +22953,21 @@ function aggregateQuotaSummary(response) {
21934
22953
  const groups = {};
21935
22954
  let totalCount = 0;
21936
22955
  for (const group of response.groups) {
21937
- const windows = [];
22956
+ const windows2 = [];
21938
22957
  for (const bucket of group.buckets) {
21939
22958
  const pool2 = poolForBucketId(bucket.bucketId);
21940
22959
  if (!pool2)
21941
22960
  continue;
21942
- windows.push({
22961
+ windows2.push({
21943
22962
  window: bucket.window,
21944
22963
  remainingFraction: normalizeRemainingFraction(bucket.remainingFraction),
21945
22964
  resetTime: bucket.resetTime
21946
22965
  });
21947
22966
  }
21948
- if (windows.length === 0)
22967
+ if (windows2.length === 0)
21949
22968
  continue;
21950
- windows.sort((a, b) => windowDurationMs(a.window) - windowDurationMs(b.window));
21951
- const constrained = mostConstrainedWindow(windows);
22969
+ windows2.sort((a, b) => windowDurationMs(a.window) - windowDurationMs(b.window));
22970
+ const constrained = mostConstrainedWindow(windows2);
21952
22971
  const recognizedBucket = group.buckets.find((bucket) => poolForBucketId(bucket.bucketId));
21953
22972
  if (!recognizedBucket)
21954
22973
  continue;
@@ -21960,7 +22979,7 @@ function aggregateQuotaSummary(response) {
21960
22979
  remainingFraction: constrained.remainingFraction,
21961
22980
  resetTime: constrained.resetTime,
21962
22981
  modelCount,
21963
- windows
22982
+ windows: windows2
21964
22983
  };
21965
22984
  totalCount += modelCount;
21966
22985
  }
@@ -23436,7 +24455,8 @@ function admissionFromReceipt(ref, receipt2) {
23436
24455
  accountIdentity: receipt2.assertedAccountIdentity,
23437
24456
  recordVersion: receipt2.recordVersion,
23438
24457
  projectId: receipt2.projectId,
23439
- expiresAtMs: receipt2.expiresAtMs
24458
+ expiresAtMs: receipt2.expiresAtMs,
24459
+ fromKeptReceipt: receipt2.fromKeptReceipt
23440
24460
  };
23441
24461
  Object.defineProperty(admission, "accessToken", {
23442
24462
  value: receipt2.accessToken,
@@ -23465,7 +24485,8 @@ function createAntigravityVaultAccountSource(options) {
23465
24485
  pollIntervalMs: options.pollIntervalMs
23466
24486
  },
23467
24487
  ...options.now && { now: options.now },
23468
- ...options.logger && { logger: options.logger }
24488
+ ...options.logger && { logger: options.logger },
24489
+ ...options.insula && { insula: options.insula }
23469
24490
  });
23470
24491
  const issued = /* @__PURE__ */ new WeakMap();
23471
24492
  const isDeclined2 = claustrum.isDeclined.bind(claustrum);
@@ -23509,7 +24530,7 @@ function createAntigravityVaultAccountSource(options) {
23509
24530
  assertOpen();
23510
24531
  entry.reported = true;
23511
24532
  await consumer.reportFailure(entry.receipt, 401, reporterSource ?? options.reporterSource);
23512
- return true;
24533
+ return entry.receipt.fromKeptReceipt !== true;
23513
24534
  };
23514
24535
  const verifyAttribution = async (attribution, signal) => {
23515
24536
  await assertServing(signal);
@@ -23538,10 +24559,15 @@ function createAntigravityVaultAccountSource(options) {
23538
24559
  },
23539
24560
  routes: () => closed ? [] : routeRefs(consumer.snapshot(), isDeclined2),
23540
24561
  admit: admit2,
24562
+ retryAfter401: (served, current, site) => claustrum.decideScopedRetryAfter401(site, issuedEntry(served).receipt, current && issuedEntry(current).receipt, options.logger),
23541
24563
  send: async (ref, dispatch, sendOptions) => {
23542
24564
  const signal = sendOptions.signal;
23543
24565
  let admission = await admit2(ref, signal);
23544
24566
  let response = await dispatch(admission, signal);
24567
+ if (response.status === 401 && admission.fromKeptReceipt) {
24568
+ await reportServedStatus(admission, 401, sendOptions.reporterSource);
24569
+ return response;
24570
+ }
23545
24571
  if (response.status === 401 && !signal?.aborted) {
23546
24572
  let current;
23547
24573
  try {
@@ -23572,6 +24598,37 @@ function createAntigravityVaultAccountSource(options) {
23572
24598
  recordVersion: admission.recordVersion
23573
24599
  });
23574
24600
  },
24601
+ pollInsulaQuotaForRoute: async (ref, fallback, signal, onSkip) => {
24602
+ await assertServing(signal);
24603
+ assertCurrentRoute(ref);
24604
+ if (!consumer.pollInsulaQuotaForRoute)
24605
+ return fallback();
24606
+ let usedFallback = false;
24607
+ const reading = await untilAborted(consumer.pollInsulaQuotaForRoute(ref.routeId, () => {
24608
+ usedFallback = true;
24609
+ return fallback();
24610
+ }), signal);
24611
+ if (reading === void 0) {
24612
+ const result = consumer.lookupInsulaQuotaForRoute ? await untilAborted(consumer.lookupInsulaQuotaForRoute(ref.routeId), signal) : void 0;
24613
+ if (result?.miss === "cold" || result?.miss === "upstream-failed")
24614
+ onSkip?.(result.miss);
24615
+ return void 0;
24616
+ }
24617
+ if (usedFallback)
24618
+ return reading;
24619
+ if (reading.accountIdentity !== ref.accountIdentity)
24620
+ throw new AntigravityVaultSourceError("identity-contradicted", "The background quota reading belongs to another vault account");
24621
+ const admission = await admit2(ref, signal);
24622
+ return {
24623
+ ...reading,
24624
+ quotaAttribution: {
24625
+ routeId: admission.routeId,
24626
+ credentialId: admission.credentialId,
24627
+ accountIdentity: admission.accountIdentity,
24628
+ recordVersion: admission.recordVersion
24629
+ }
24630
+ };
24631
+ },
23575
24632
  commitState: async (attribution, update, signal) => {
23576
24633
  assertOpen(signal);
23577
24634
  if (!options.state)
@@ -23930,19 +24987,24 @@ async function replaceWindowsFile2(from, to, options = {}) {
23930
24987
  to = resolve7(to);
23931
24988
  const now = options.now ?? (() => performance.now());
23932
24989
  const start = now();
23933
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
24990
+ const leaseDeadline = options.deadline ?? Infinity;
24991
+ let retryDeadline;
23934
24992
  const delays = [0, 10, 20, 40, 80, 100];
23935
24993
  let original;
23936
24994
  let attempts2 = 0;
23937
24995
  for (const delay3 of delays) {
24996
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
23938
24997
  if (now() >= deadline)
23939
24998
  break;
23940
24999
  if (delay3)
23941
25000
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
23942
25001
  if (now() >= deadline)
23943
25002
  break;
25003
+ const fenceStart = now();
23944
25004
  await options.beforeRename?.();
23945
- if (now() >= deadline)
25005
+ if (retryDeadline !== void 0)
25006
+ retryDeadline += now() - fenceStart;
25007
+ if (now() >= leaseDeadline)
23946
25008
  break;
23947
25009
  attempts2++;
23948
25010
  try {
@@ -23954,6 +25016,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
23954
25016
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
23955
25017
  if (!candidate)
23956
25018
  break;
25019
+ retryDeadline ??= now() + 500;
23957
25020
  }
23958
25021
  }
23959
25022
  const error = new PrivateFileError2(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -25808,7 +26871,7 @@ function normalizeQuota(input2) {
25808
26871
  const resetAt = toFiniteNumber(record3.resetAt) ?? void 0;
25809
26872
  const checkedAt = toFiniteNumber(record3.checkedAt) ?? void 0;
25810
26873
  const windowsRaw = record3.windows;
25811
- let windows;
26874
+ let windows2;
25812
26875
  if (Array.isArray(windowsRaw)) {
25813
26876
  const parsed = windowsRaw.filter(isObject).map((w) => {
25814
26877
  const win = w.window;
@@ -25827,14 +26890,14 @@ function normalizeQuota(input2) {
25827
26890
  ...ca !== null && ca >= 0 ? { checkedAt: ca } : {}
25828
26891
  };
25829
26892
  }).filter((v) => v !== null);
25830
- if (parsed.length > 0) windows = parsed;
26893
+ if (parsed.length > 0) windows2 = parsed;
25831
26894
  }
25832
26895
  return {
25833
26896
  remainingPercent: clampNumber(remaining, 0, 100),
25834
26897
  ...fraction !== null ? { remainingFraction: clampNumber(fraction, 0, 1) } : {},
25835
26898
  resetAt,
25836
26899
  ...checkedAt !== void 0 ? { checkedAt } : {},
25837
- windows
26900
+ windows: windows2
25838
26901
  };
25839
26902
  }
25840
26903
  function normalizeRouting(input2) {
@@ -25954,7 +27017,7 @@ function projectQuotaPoolForSidebar(source, checkedAt) {
25954
27017
  const parsed = Date.parse(source.resetTime);
25955
27018
  if (Number.isFinite(parsed)) resetAt = parsed;
25956
27019
  }
25957
- const windows = source.windows?.length ? source.windows.map((w) => ({
27020
+ const windows2 = source.windows?.length ? source.windows.map((w) => ({
25958
27021
  window: w.window,
25959
27022
  ...readingAt !== void 0 ? { checkedAt: readingAt } : {},
25960
27023
  remainingPercent: clampNumber(
@@ -25972,7 +27035,7 @@ function projectQuotaPoolForSidebar(source, checkedAt) {
25972
27035
  remainingPercent,
25973
27036
  remainingFraction: clampNumber(fraction, 0, 1),
25974
27037
  resetAt,
25975
- windows,
27038
+ windows: windows2,
25976
27039
  ...readingAt !== void 0 ? { checkedAt: readingAt } : {}
25977
27040
  };
25978
27041
  }
@@ -26643,7 +27706,7 @@ async function fetchLegacyModelsFallback(options) {
26643
27706
  const modelsResponse = await fetchAvailableModels({
26644
27707
  accessToken: options.accessToken,
26645
27708
  projectId: options.projectId,
26646
- endpoints: ANTIGRAVITY_ENDPOINT_FALLBACKS,
27709
+ endpoints: [ANTIGRAVITY_QUOTA_ENDPOINT],
26647
27710
  userAgent: buildAntigravityHarnessUserAgent(),
26648
27711
  timeoutMs: 1e4,
26649
27712
  ...options.fetchVia ? { fetchVia: options.fetchVia } : {}
@@ -26672,7 +27735,7 @@ async function fetchQuotaPayloads(options) {
26672
27735
  accessToken,
26673
27736
  managedProjectId,
26674
27737
  projectId,
26675
- endpoints: ANTIGRAVITY_ENDPOINT_FALLBACKS,
27738
+ endpoints: [ANTIGRAVITY_QUOTA_ENDPOINT],
26676
27739
  userAgent: buildAntigravityHarnessUserAgent(),
26677
27740
  timeoutMs: 1e4,
26678
27741
  ...fetchVia ? { fetchVia } : {}
@@ -26789,7 +27852,7 @@ async function fetchVaultAccountQuota(options) {
26789
27852
  return result;
26790
27853
  };
26791
27854
  const fetchSummary = async () => {
26792
- for (const endpoint of ANTIGRAVITY_ENDPOINT_FALLBACKS) {
27855
+ for (const endpoint of [ANTIGRAVITY_QUOTA_ENDPOINT]) {
26793
27856
  const result = await attempt(
26794
27857
  async (grant, fetchVia) => aggregateQuotaSummary(
26795
27858
  (await fetchQuotaSummary({
@@ -26811,7 +27874,7 @@ async function fetchVaultAccountQuota(options) {
26811
27874
  }
26812
27875
  if (result.refused) break;
26813
27876
  }
26814
- for (const endpoint of ANTIGRAVITY_ENDPOINT_FALLBACKS) {
27877
+ for (const endpoint of [ANTIGRAVITY_QUOTA_ENDPOINT]) {
26815
27878
  for (const withProject of [true, false]) {
26816
27879
  const result = await attempt(
26817
27880
  (grant, fetchVia) => fetchAvailableModels({
@@ -26954,6 +28017,14 @@ function createAuthorizedFetchAccountQuota(options) {
26954
28017
  error: `quota check refused (stale grant: ${staleReason})`
26955
28018
  };
26956
28019
  }
28020
+ if (payloads.quota.error) {
28021
+ return {
28022
+ ...base,
28023
+ status: "error",
28024
+ disabled: false,
28025
+ error: payloads.quota.error
28026
+ };
28027
+ }
26957
28028
  return {
26958
28029
  ...base,
26959
28030
  status: "ok",
@@ -27029,6 +28100,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
27029
28100
  }),
27030
28101
  signal
27031
28102
  );
28103
+ if (payloads.quota.error) throw new Error(payloads.quota.error);
27032
28104
  return {
27033
28105
  index,
27034
28106
  email: account.email,
@@ -27084,6 +28156,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
27084
28156
  logger: log7
27085
28157
  });
27086
28158
  quotaResult = payloads.quota;
28159
+ if (quotaResult.error) throw new Error(quotaResult.error);
27087
28160
  fellBackToLegacy = payloads.fellBackToLegacy;
27088
28161
  for (const [family, groupQuota] of Object.entries(quotaResult.groups)) {
27089
28162
  const remainingPercent = (groupQuota.remainingFraction ?? 0) * 100;
@@ -27944,7 +29017,7 @@ import { createHash as createHash10, randomBytes as randomBytes5, randomUUID as
27944
29017
  import { constants as fsConstants2 } from "node:fs";
27945
29018
  import { chmod as chmod3, mkdir as mkdir12, open as open10, readFile as readFile10, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
27946
29019
  import { basename as basename4, dirname as dirname17, extname as extname2, isAbsolute as isAbsolute3, join as join11, resolve as resolve10 } from "node:path";
27947
- import { ClaustrumCredentialError as ClaustrumCredentialError4, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
29020
+ import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
27948
29021
 
27949
29022
  // src/common-auth-embedded/fs/lock-constants.js
27950
29023
  var WRITER_LOCK_CONSTANTS2 = Object.freeze({
@@ -28626,7 +29699,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
28626
29699
  "pending_queue_full"
28627
29700
  ]);
28628
29701
  function classifyEnrollmentError2(error) {
28629
- if (!(error instanceof ClaustrumCredentialError4))
29702
+ if (!(error instanceof ClaustrumCredentialError5))
28630
29703
  return void 0;
28631
29704
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
28632
29705
  return { code: error.code, disposition: "terminal" };
@@ -29728,9 +30801,9 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);
29728
30801
  }
29729
30802
  };
29730
30803
  async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
29731
- const windows = (options.platform ?? process.platform) === "win32";
30804
+ const windows2 = (options.platform ?? process.platform) === "win32";
29732
30805
  let inspection = {
29733
- step: windows ? "tasklist" : "ps",
30806
+ step: windows2 ? "tasklist" : "ps",
29734
30807
  exitCode: null,
29735
30808
  signal: null,
29736
30809
  timedOut: false,
@@ -29765,7 +30838,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
29765
30838
  }
29766
30839
  };
29767
30840
  try {
29768
- const result = await inspect(windows ? "tasklist" : "ps", windows ? "tasklist.exe" : "ps", windows ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
30841
+ const result = await inspect(windows2 ? "tasklist" : "ps", windows2 ? "tasklist.exe" : "ps", windows2 ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
29769
30842
  if (result.exitCode !== 0)
29770
30843
  throw new ProcessInspectionError(inspection);
29771
30844
  const processes = [];
@@ -29775,7 +30848,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
29775
30848
  continue;
29776
30849
  let pid;
29777
30850
  let command;
29778
- if (windows) {
30851
+ if (windows2) {
29779
30852
  const match = /^"([^"]+)","(\d+)"(?:,|$)/.exec(trimmed);
29780
30853
  if (!match)
29781
30854
  throw new ProcessInspectionError(inspection);
@@ -29798,7 +30871,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
29798
30871
  if (!processes.length)
29799
30872
  throw new ProcessInspectionError(inspection);
29800
30873
  const runtimes = processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command));
29801
- if (windows && runtimes.length && options.inspectRuntimes !== false) {
30874
+ if (windows2 && runtimes.length && options.inspectRuntimes !== false) {
29802
30875
  const details = await inspect("CIM", "powershell.exe", [
29803
30876
  "-NoProfile",
29804
30877
  "-NonInteractive",
@@ -29841,10 +30914,10 @@ function createProcessFence(runner = defaultCommandRunner, options = {}) {
29841
30914
  env: env3,
29842
30915
  inspectRuntimes: false
29843
30916
  });
29844
- const windows = (options.platform ?? process.platform) === "win32";
30917
+ const windows2 = (options.platform ?? process.platform) === "win32";
29845
30918
  return {
29846
30919
  hosts: processes.filter(isHost),
29847
- uncheckedRuntimes: windows ? processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
30920
+ uncheckedRuntimes: windows2 ? processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command)).length : 0
29848
30921
  };
29849
30922
  }
29850
30923
  };
@@ -29955,11 +31028,11 @@ import { mkdir as mkdir13, open as open11, rename as rename10, stat as stat9, un
29955
31028
  import { basename as basename5, dirname as dirname18, join as join13 } from "node:path";
29956
31029
  import { setTimeout as delay2 } from "node:timers/promises";
29957
31030
  async function writeHostConfigAtomic(file, content, options = {}) {
29958
- const windows = (options.platform ?? process.platform) === "win32";
31031
+ const windows2 = (options.platform ?? process.platform) === "win32";
29959
31032
  const parent = dirname18(file);
29960
31033
  await mkdir13(parent, { recursive: true });
29961
31034
  let mode;
29962
- if (!windows) {
31035
+ if (!windows2) {
29963
31036
  try {
29964
31037
  mode = (await stat9(file)).mode & 4095;
29965
31038
  } catch (error) {
@@ -29990,7 +31063,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
29990
31063
  } catch (error) {
29991
31064
  const code2 = error.code;
29992
31065
  const remaining = 2e3 - (now() - started);
29993
- if (!windows || !["EPERM", "EBUSY", "EACCES"].includes(code2 ?? "") || remaining <= 0 || attempt >= 40)
31066
+ if (!windows2 || !["EPERM", "EBUSY", "EACCES"].includes(code2 ?? "") || remaining <= 0 || attempt >= 40)
29994
31067
  throw new Error(`Unable to replace host config ${file}. Close editors or other programs using the file, then rerun setup.`);
29995
31068
  await (options.wait ?? delay2)(Math.min(remaining, 25 * 2 ** Math.min(attempt, 2)));
29996
31069
  }
@@ -30412,6 +31485,7 @@ function refreshVaultAccountRow(prior, fresh) {
30412
31485
  else prior.email = fresh.email;
30413
31486
  }
30414
31487
  var VaultSendGrant = class {
31488
+ fromKeptReceipt;
30415
31489
  credentialId;
30416
31490
  accountIdentity;
30417
31491
  recordVersion;
@@ -30426,20 +31500,36 @@ var VaultSendGrant = class {
30426
31500
  this.accountIdentity = admission.accountIdentity;
30427
31501
  this.recordVersion = admission.recordVersion;
30428
31502
  this.projectId = admission.projectId;
31503
+ this.fromKeptReceipt = admission.fromKeptReceipt;
30429
31504
  this.report401 = report;
30430
31505
  }
30431
31506
  };
30432
31507
  function createVaultRequestCredentials(source, onAdmitted) {
31508
+ const issued = /* @__PURE__ */ new WeakMap();
30433
31509
  return {
30434
31510
  domain: "vault",
31511
+ ...source.retryAfter401 && {
31512
+ retryAfter401(served, current, site) {
31513
+ const original = issued.get(served);
31514
+ if (!original)
31515
+ throw new Error("Retry requires an original vault admission");
31516
+ return source.retryAfter401(
31517
+ original,
31518
+ current && issued.get(current),
31519
+ site
31520
+ );
31521
+ }
31522
+ },
30435
31523
  async admit({ account, signal }) {
30436
31524
  const admission = await source.admit(account.route, signal);
30437
31525
  if (onAdmitted)
30438
31526
  onAdmitted.admitted(account, onAdmitted.source.attribution(admission));
30439
- return new VaultSendGrant(
31527
+ const grant = new VaultSendGrant(
30440
31528
  admission,
30441
31529
  (status) => source.reportServedStatus(admission, status)
30442
31530
  );
31531
+ issued.set(grant, admission);
31532
+ return grant;
30443
31533
  }
30444
31534
  };
30445
31535
  }
@@ -30737,6 +31827,10 @@ async function checkVaultQuota(input2) {
30737
31827
  input2.onStage?.("fetch");
30738
31828
  const answer = await input2.fetchReading(row.route, input2.signal);
30739
31829
  input2.signal.throwIfAborted();
31830
+ if (answer === void 0) {
31831
+ input2.onOutcome?.("fetch-failed");
31832
+ continue;
31833
+ }
30740
31834
  const attribution = answer.quotaAttribution;
30741
31835
  if (answer.quota.error !== void 0) {
30742
31836
  input2.onOutcome?.("fetch-failed");
@@ -30746,7 +31840,7 @@ async function checkVaultQuota(input2) {
30746
31840
  input2.onOutcome?.("unattributed");
30747
31841
  continue;
30748
31842
  }
30749
- const reading = vaultQuotaState(answer.quota, now());
31843
+ const reading = vaultQuotaState(answer.quota, answer.observedAt ?? now());
30750
31844
  input2.onStage?.("commit");
30751
31845
  input2.signal.throwIfAborted();
30752
31846
  const result = await state.recordQuota(attribution, reading, input2.signal);
@@ -30777,6 +31871,48 @@ async function checkVaultQuota(input2) {
30777
31871
  return { checked, notChecked: rows.length - checked };
30778
31872
  }
30779
31873
 
31874
+ // src/plugin/vault-insula-quota.ts
31875
+ var windows = [
31876
+ ["gemini-5h", "gemini", "5h"],
31877
+ ["gemini-weekly", "gemini", "weekly"],
31878
+ ["3p-5h", "non-gemini", "5h"],
31879
+ ["3p-weekly", "non-gemini", "weekly"]
31880
+ ];
31881
+ var normalizeVaultInsulaQuota = (entry, context) => {
31882
+ if (entry.source !== "vault") return void 0;
31883
+ if (entry.provider !== "antigravity" || !entry.account?.trim() || !Number.isFinite(context.fetchedAt))
31884
+ return void 0;
31885
+ const groups = {};
31886
+ for (const [id, group, window] of windows) {
31887
+ const reading = entry.usage?.extraRateWindows?.find(
31888
+ (extra) => extra.id === id
31889
+ )?.window;
31890
+ if (!reading || !Number.isFinite(reading.usedPercent) || reading.usedPercent < 0 || reading.usedPercent > 100)
31891
+ continue;
31892
+ const normalized = {
31893
+ window,
31894
+ remainingFraction: 1 - reading.usedPercent / 100,
31895
+ resetTime: reading.resetsAt ?? ""
31896
+ };
31897
+ let summary = groups[group];
31898
+ if (summary === void 0) {
31899
+ summary = { modelCount: 0, windows: [] };
31900
+ groups[group] = summary;
31901
+ }
31902
+ summary.windows?.push(normalized);
31903
+ if (summary.remainingFraction === void 0 || normalized.remainingFraction < summary.remainingFraction) {
31904
+ summary.remainingFraction = normalized.remainingFraction;
31905
+ summary.resetTime = normalized.resetTime;
31906
+ }
31907
+ }
31908
+ if (Object.keys(groups).length === 0) return void 0;
31909
+ return {
31910
+ quota: { groups, modelCount: 0 },
31911
+ accountIdentity: entry.account.trim(),
31912
+ observedAt: context.fetchedAt
31913
+ };
31914
+ };
31915
+
30780
31916
  // src/plugin/vault-custody.ts
30781
31917
  var OPENCODE_VAULT_PROVIDER = "google";
30782
31918
  var OPENCODE_VAULT_HOST = "opencode";
@@ -30885,8 +32021,15 @@ function createOpenCodeVaultCustody(options) {
30885
32021
  onError: () => options.onRosterChanged?.(),
30886
32022
  reporterSource: options.reporterSource,
30887
32023
  state: { path: paths.stateFile, fs: await loadCommonAuthFs() },
32024
+ ...options.insulaQuota ? {
32025
+ insula: {
32026
+ provider: "antigravity",
32027
+ normalize: normalizeVaultInsulaQuota
32028
+ }
32029
+ } : {},
30888
32030
  ...options.logger ? { logger: options.logger } : {},
30889
- ...options.now ? { now: options.now } : {}
32031
+ ...options.now ? { now: options.now } : {},
32032
+ ...options.pollIntervalMs !== void 0 ? { pollIntervalMs: options.pollIntervalMs } : {}
30890
32033
  });
30891
32034
  const activeSource = {
30892
32035
  ...created,
@@ -42561,6 +43704,185 @@ function transformAntigravityResponse(...args) {
42561
43704
  return transformAntigravityResponseIn(openCode1WireLocation, ...args);
42562
43705
  }
42563
43706
 
43707
+ // src/plugin/shared/request-cancellation.ts
43708
+ function createRequestCancellation(signals) {
43709
+ const controller = new AbortController();
43710
+ const remove2 = [];
43711
+ const release = () => {
43712
+ for (const detach of remove2.splice(0)) detach();
43713
+ };
43714
+ for (const source of signals) {
43715
+ if (source.aborted) {
43716
+ controller.abort(source.reason);
43717
+ release();
43718
+ break;
43719
+ }
43720
+ const forward = () => {
43721
+ controller.abort(source.reason);
43722
+ release();
43723
+ };
43724
+ remove2.push(() => source.removeEventListener("abort", forward));
43725
+ source.addEventListener("abort", forward, { once: true });
43726
+ if (source.aborted) forward();
43727
+ if (controller.signal.aborted) break;
43728
+ }
43729
+ return { signal: controller.signal, release };
43730
+ }
43731
+ async function retainResponseLifetime(response, cancellation) {
43732
+ if (!response.body) {
43733
+ cancellation.release();
43734
+ return { response, settled: Promise.resolve() };
43735
+ }
43736
+ let reader;
43737
+ try {
43738
+ reader = response.body.getReader();
43739
+ } catch (error) {
43740
+ cancellation.release();
43741
+ throw error;
43742
+ }
43743
+ let resolve18 = () => {
43744
+ };
43745
+ const settled = new Promise((done) => {
43746
+ resolve18 = done;
43747
+ });
43748
+ let stopping = false;
43749
+ let finished = false;
43750
+ let controller;
43751
+ const finish = () => {
43752
+ if (finished) return;
43753
+ finished = true;
43754
+ cancellation.signal.removeEventListener("abort", abort);
43755
+ cancellation.release();
43756
+ resolve18();
43757
+ };
43758
+ const abort = () => {
43759
+ if (finished || stopping) return;
43760
+ stopping = true;
43761
+ const reason = cancellation.signal.reason;
43762
+ controller.error(reason);
43763
+ void reader.cancel(reason).then(finish, finish);
43764
+ };
43765
+ const body = new ReadableStream({
43766
+ start(output2) {
43767
+ controller = output2;
43768
+ cancellation.signal.addEventListener("abort", abort, { once: true });
43769
+ if (cancellation.signal.aborted) abort();
43770
+ },
43771
+ async pull(output2) {
43772
+ try {
43773
+ const next = await reader.read();
43774
+ if (stopping) return;
43775
+ if (next.done) {
43776
+ output2.close();
43777
+ finish();
43778
+ } else {
43779
+ output2.enqueue(next.value);
43780
+ }
43781
+ } catch (error) {
43782
+ if (stopping) return;
43783
+ output2.error(error);
43784
+ finish();
43785
+ }
43786
+ },
43787
+ async cancel(reason) {
43788
+ stopping = true;
43789
+ try {
43790
+ await reader.cancel(reason);
43791
+ } finally {
43792
+ finish();
43793
+ }
43794
+ }
43795
+ });
43796
+ try {
43797
+ return {
43798
+ response: new Response(body, {
43799
+ status: response.status,
43800
+ statusText: response.statusText,
43801
+ headers: response.headers
43802
+ }),
43803
+ settled
43804
+ };
43805
+ } catch (error) {
43806
+ stopping = true;
43807
+ await reader.cancel(error).then(finish, finish);
43808
+ throw error;
43809
+ }
43810
+ }
43811
+
43812
+ // src/plugin/shared/after-handoff.ts
43813
+ function createAfterHandoff(work, signals, onFailure) {
43814
+ const controller = new AbortController();
43815
+ const cancellation = createRequestCancellation([
43816
+ ...signals,
43817
+ controller.signal
43818
+ ]);
43819
+ let run;
43820
+ let acknowledged = false;
43821
+ let finished = false;
43822
+ let running = false;
43823
+ let resolveCompletion = () => {
43824
+ };
43825
+ const completion = new Promise((resolve18) => {
43826
+ resolveCompletion = resolve18;
43827
+ });
43828
+ const finish = () => {
43829
+ if (finished) return;
43830
+ finished = true;
43831
+ run = void 0;
43832
+ cancellation.signal.removeEventListener("abort", onAbort);
43833
+ cancellation.release();
43834
+ work.delete(completion);
43835
+ resolveCompletion();
43836
+ };
43837
+ const onAbort = () => {
43838
+ if (!running) finish();
43839
+ };
43840
+ cancellation.signal.addEventListener("abort", onAbort, { once: true });
43841
+ if (cancellation.signal.aborted) onAbort();
43842
+ return {
43843
+ register(callback) {
43844
+ if (finished || run) return;
43845
+ run = callback;
43846
+ work.add(completion);
43847
+ },
43848
+ acknowledge() {
43849
+ if (finished || acknowledged || !run) return;
43850
+ acknowledged = true;
43851
+ void Promise.resolve().then(async () => {
43852
+ if (finished || cancellation.signal.aborted) return;
43853
+ running = true;
43854
+ try {
43855
+ await run?.(cancellation.signal);
43856
+ } catch {
43857
+ try {
43858
+ onFailure();
43859
+ } catch {
43860
+ }
43861
+ } finally {
43862
+ finish();
43863
+ }
43864
+ });
43865
+ },
43866
+ cancel() {
43867
+ controller.abort();
43868
+ onAbort();
43869
+ }
43870
+ };
43871
+ }
43872
+ function publishResponse(dispatch) {
43873
+ return new Promise((resolve18, reject) => {
43874
+ let acknowledge;
43875
+ void Promise.resolve().then(
43876
+ () => dispatch((callback) => {
43877
+ acknowledge = callback;
43878
+ })
43879
+ ).then((response) => {
43880
+ resolve18(response);
43881
+ acknowledge?.();
43882
+ }, reject);
43883
+ });
43884
+ }
43885
+
42564
43886
  // src/plugin/auth-loader.ts
42565
43887
  var log12 = createLogger4("auth-loader");
42566
43888
  function refreshTokenIdentity(refreshToken) {
@@ -42930,7 +44252,7 @@ function createAuthLoader({
42930
44252
  // through the OLD interceptor after an OAuth add. The wrapper
42931
44253
  // matches the host's `LoaderResult.fetch` signature exactly
42932
44254
  // (no `this` binding) so behavior is preserved.
42933
- fetch: async (input2, init) => {
44255
+ fetch: (input2, init) => publishResponse(async (onResponseHandoff) => {
42934
44256
  assertOpen();
42935
44257
  const authority = await readAuthority?.() ?? "local";
42936
44258
  assertOpen();
@@ -42944,7 +44266,7 @@ function createAuthLoader({
42944
44266
  });
42945
44267
  const vaultRuntime = await vaultFetchRuntime;
42946
44268
  assertOpen();
42947
- return vaultRuntime.fetch(input2, init);
44269
+ return vaultRuntime.fetch(input2, init, onResponseHandoff);
42948
44270
  }
42949
44271
  if (localUnavailable) {
42950
44272
  return fetchWithoutLocalAccounts(input2, init, fetchImpl);
@@ -42968,8 +44290,8 @@ function createAuthLoader({
42968
44290
  return fetchWithoutLocalAccounts(input2, init, fetchImpl);
42969
44291
  if (currentRequestSource !== "local" || !fetchRuntime)
42970
44292
  throw new Error("The local account runtime is unavailable");
42971
- return fetchRuntime.fetch(input2, init);
42972
- }
44293
+ return fetchRuntime.fetch(input2, init, onResponseHandoff);
44294
+ })
42973
44295
  };
42974
44296
  }
42975
44297
  reloadRuntime = async (getAuth) => {
@@ -43549,7 +44871,7 @@ var BackgroundVaultQuotaRefresh = class {
43549
44871
  fetchReading: async (ref, signal) => {
43550
44872
  rowFailure = "fetch-failed";
43551
44873
  await this.assertActive(controller);
43552
- const reading = await fetchVaultAccountQuota({
44874
+ const fallback = () => fetchVaultAccountQuota({
43553
44875
  source,
43554
44876
  ref,
43555
44877
  signal,
@@ -43559,7 +44881,10 @@ var BackgroundVaultQuotaRefresh = class {
43559
44881
  if (kind !== "unknown" || outcome.errorKind === void 0)
43560
44882
  outcome.errorKind = kind;
43561
44883
  if (refused)
43562
- rowFailure = vaultQuotaErrorReason(error, "admission-refused");
44884
+ rowFailure = vaultQuotaErrorReason(
44885
+ error,
44886
+ "admission-refused"
44887
+ );
43563
44888
  },
43564
44889
  transport: async (url, init, extra) => {
43565
44890
  await this.assertActive(controller);
@@ -43582,6 +44907,16 @@ var BackgroundVaultQuotaRefresh = class {
43582
44907
  }
43583
44908
  }
43584
44909
  });
44910
+ const reading = source.pollInsulaQuotaForRoute ? await source.pollInsulaQuotaForRoute(
44911
+ ref,
44912
+ fallback,
44913
+ signal,
44914
+ (reason) => {
44915
+ rowFailure = `insula-${reason}`;
44916
+ }
44917
+ ) : await fallback();
44918
+ if (reading === void 0 && rowFailure === "fetch-failed")
44919
+ rowFailure = "insula-skipped";
43585
44920
  await this.assertActive(controller);
43586
44921
  await lock.assertOwned();
43587
44922
  return reading;
@@ -44242,7 +45577,7 @@ function toCommandAccountRow(entry) {
44242
45577
  const parsed = Date.parse(cachedEntry.resetTime);
44243
45578
  if (Number.isFinite(parsed)) resetAt = parsed;
44244
45579
  }
44245
- const windows = cachedEntry.windows?.length ? cachedEntry.windows.map((w) => ({
45580
+ const windows2 = cachedEntry.windows?.length ? cachedEntry.windows.map((w) => ({
44246
45581
  window: w.window,
44247
45582
  remainingPercent: Math.round(w.remainingFraction * 100),
44248
45583
  resetAt: typeof w.resetTime === "string" && w.resetTime.length > 0 ? (() => {
@@ -44255,7 +45590,7 @@ function toCommandAccountRow(entry) {
44255
45590
  label: QUOTA_GROUP_LABELS[key],
44256
45591
  remainingPercent,
44257
45592
  resetAt,
44258
- windows
45593
+ windows: windows2
44259
45594
  });
44260
45595
  }
44261
45596
  const label = `Account ${entry.index + 1}`;
@@ -44977,111 +46312,6 @@ var AgySessionRegistry = class {
44977
46312
  }
44978
46313
  };
44979
46314
 
44980
- // src/plugin/shared/request-cancellation.ts
44981
- function createRequestCancellation(signals) {
44982
- const controller = new AbortController();
44983
- const remove2 = [];
44984
- const release = () => {
44985
- for (const detach of remove2.splice(0)) detach();
44986
- };
44987
- for (const source of signals) {
44988
- if (source.aborted) {
44989
- controller.abort(source.reason);
44990
- release();
44991
- break;
44992
- }
44993
- const forward = () => {
44994
- controller.abort(source.reason);
44995
- release();
44996
- };
44997
- remove2.push(() => source.removeEventListener("abort", forward));
44998
- source.addEventListener("abort", forward, { once: true });
44999
- if (source.aborted) forward();
45000
- if (controller.signal.aborted) break;
45001
- }
45002
- return { signal: controller.signal, release };
45003
- }
45004
- async function retainResponseLifetime(response, cancellation) {
45005
- if (!response.body) {
45006
- cancellation.release();
45007
- return { response, settled: Promise.resolve() };
45008
- }
45009
- let reader;
45010
- try {
45011
- reader = response.body.getReader();
45012
- } catch (error) {
45013
- cancellation.release();
45014
- throw error;
45015
- }
45016
- let resolve18 = () => {
45017
- };
45018
- const settled = new Promise((done) => {
45019
- resolve18 = done;
45020
- });
45021
- let stopping = false;
45022
- let finished = false;
45023
- let controller;
45024
- const finish = () => {
45025
- if (finished) return;
45026
- finished = true;
45027
- cancellation.signal.removeEventListener("abort", abort);
45028
- cancellation.release();
45029
- resolve18();
45030
- };
45031
- const abort = () => {
45032
- if (finished || stopping) return;
45033
- stopping = true;
45034
- const reason = cancellation.signal.reason;
45035
- controller.error(reason);
45036
- void reader.cancel(reason).then(finish, finish);
45037
- };
45038
- const body = new ReadableStream({
45039
- start(output2) {
45040
- controller = output2;
45041
- cancellation.signal.addEventListener("abort", abort, { once: true });
45042
- if (cancellation.signal.aborted) abort();
45043
- },
45044
- async pull(output2) {
45045
- try {
45046
- const next = await reader.read();
45047
- if (stopping) return;
45048
- if (next.done) {
45049
- output2.close();
45050
- finish();
45051
- } else {
45052
- output2.enqueue(next.value);
45053
- }
45054
- } catch (error) {
45055
- if (stopping) return;
45056
- output2.error(error);
45057
- finish();
45058
- }
45059
- },
45060
- async cancel(reason) {
45061
- stopping = true;
45062
- try {
45063
- await reader.cancel(reason);
45064
- } finally {
45065
- finish();
45066
- }
45067
- }
45068
- });
45069
- try {
45070
- return {
45071
- response: new Response(body, {
45072
- status: response.status,
45073
- statusText: response.statusText,
45074
- headers: response.headers
45075
- }),
45076
- settled
45077
- };
45078
- } catch (error) {
45079
- stopping = true;
45080
- await reader.cancel(error).then(finish, finish);
45081
- throw error;
45082
- }
45083
- }
45084
-
45085
46315
  // src/plugin/shared/request-services.ts
45086
46316
  var FIRST_RETRY_DELAY_MS = 1e3;
45087
46317
  function prepareAgyWireRequest(wire, request) {
@@ -46131,24 +47361,17 @@ function createRequestExecutor(deps) {
46131
47361
  );
46132
47362
  noteGeminiDumpResponse(dumpContext, response);
46133
47363
  if (credentials.domain === "vault" && sendAdmission && response.status === 401) {
46134
- try {
46135
- await deadline.wait(
46136
- () => sendAdmission.report401(response.status)
46137
- );
46138
- } catch (error) {
46139
- checkAborted();
46140
- log16.debug("send-admission-401-report-failed", {
46141
- error: String(error)
46142
- });
46143
- }
46144
- if (!vault401Retried) {
46145
- const next = await deadline.wait(
46146
- () => credentials.admit({
46147
- account,
46148
- signal: abortSignal
46149
- })
46150
- );
46151
- if (next.credentialId === sendAdmission.credentialId && next.accountIdentity === sendAdmission.accountIdentity && next.recordVersion > sendAdmission.recordVersion) {
47364
+ if (!sendAdmission.fromKeptReceipt && !vault401Retried && !abortSignal?.aborted) {
47365
+ let next;
47366
+ try {
47367
+ next = await deadline.wait(
47368
+ () => credentials.admit({ account, signal: abortSignal })
47369
+ );
47370
+ } catch {
47371
+ checkAborted();
47372
+ }
47373
+ const retry = credentials.retryAfter401 ? credentials.retryAfter401(sendAdmission, next, "model") : next && !next.fromKeptReceipt && next.credentialId === sendAdmission.credentialId && next.accountIdentity === sendAdmission.accountIdentity && next.recordVersion > sendAdmission.recordVersion;
47374
+ if (next && retry) {
46152
47375
  vault401Retried = true;
46153
47376
  rotatedAdmission = next;
46154
47377
  void response.body?.cancel().catch(() => {
@@ -46160,6 +47383,16 @@ function createRequestExecutor(deps) {
46160
47383
  continue;
46161
47384
  }
46162
47385
  }
47386
+ try {
47387
+ await deadline.wait(
47388
+ () => sendAdmission.report401(response.status)
47389
+ );
47390
+ } catch (error) {
47391
+ checkAborted();
47392
+ log16.debug("send-admission-401-report-failed", {
47393
+ error: String(error)
47394
+ });
47395
+ }
46163
47396
  }
46164
47397
  const sessionKey = requestSessionIdentity.sessionId;
46165
47398
  if (sessionKey) {
@@ -46434,23 +47667,6 @@ function createRequestExecutor(deps) {
46434
47667
  trackers.health.recordSuccess(account.index);
46435
47668
  if (!advisoryClosing)
46436
47669
  accountManager.markAccountUsed(account.index);
46437
- if (credentials.domain === "local" && !advisoryClosing && credentials.refreshQuotaAfterSuccess) {
46438
- const quotaCancellation = createRequestCancellation(
46439
- init?.signal ? [init.signal, shutdown.signal] : [shutdown.signal]
46440
- );
46441
- const work = credentials.refreshQuotaAfterSuccess(
46442
- account,
46443
- config.quota_refresh_interval_minutes,
46444
- quotaCancellation.signal
46445
- ).catch(() => {
46446
- log16.debug("post-response-advisory-work-failed");
46447
- }).finally(() => quotaCancellation.release());
46448
- advisoryWork.add(work);
46449
- void work.then(
46450
- () => advisoryWork.delete(work),
46451
- () => advisoryWork.delete(work)
46452
- );
46453
- }
46454
47670
  const proactiveThreshold = config.proactive_rotation_threshold_percent ?? 20;
46455
47671
  if (!advisoryClosing && proactiveThreshold > 0 && accountManager.shouldProactivelyRotate(
46456
47672
  family,
@@ -46598,6 +47814,10 @@ function createRequestExecutor(deps) {
46598
47814
  );
46599
47815
  }
46600
47816
  }
47817
+ if (response.ok && transformedResponse.ok && credentials.domain === "local" && !advisoryClosing && credentials.refreshQuotaAfterSuccess) {
47818
+ const refresh = credentials.refreshQuotaAfterSuccess;
47819
+ waitPolicy.quota = (signal) => refresh(account, config.quota_refresh_interval_minutes, signal);
47820
+ }
46601
47821
  return transformedResponse;
46602
47822
  } catch (error) {
46603
47823
  if (error instanceof PreResponseTimeoutError) throw error;
@@ -46798,6 +48018,11 @@ function createRequestExecutor(deps) {
46798
48018
  deps.preResponseClock
46799
48019
  );
46800
48020
  log16.debug("pre-response-start", { limitMs: PRE_RESPONSE_DEADLINE_MS });
48021
+ const handoff = createAfterHandoff(
48022
+ advisoryWork,
48023
+ requestedSignal ? [requestedSignal, shutdown.signal] : [shutdown.signal],
48024
+ () => log16.debug("post-response-advisory-work-failed")
48025
+ );
46801
48026
  const waitPolicy = {};
46802
48027
  const selectedCredentials = /* @__PURE__ */ new Set();
46803
48028
  const selectedProjectIds = /* @__PURE__ */ new Set();
@@ -46822,6 +48047,7 @@ function createRequestExecutor(deps) {
46822
48047
  async (response) => {
46823
48048
  deadline.acceptTerminalResponse();
46824
48049
  if (bufferedOverflow.has(response)) {
48050
+ handoff.cancel();
46825
48051
  deadline.dispose();
46826
48052
  cancellation.release();
46827
48053
  return redactCredentialResponse(
@@ -46838,14 +48064,22 @@ function createRequestExecutor(deps) {
46838
48064
  inFlight.add(retained.settled);
46839
48065
  void retained.settled.then(() => inFlight.delete(retained.settled));
46840
48066
  void retained.settled.then(() => deadline.dispose());
46841
- return redactCredentialResponse(
48067
+ const published = await redactCredentialResponse(
46842
48068
  preserveResponseMetadata2(retained.response, response),
46843
48069
  [...selectedCredentials],
46844
48070
  void 0,
46845
48071
  [...selectedProjectIds]
46846
48072
  );
48073
+ if (published.ok && waitPolicy.quota && requestOptions?.onResponseHandoff) {
48074
+ handoff.register(waitPolicy.quota);
48075
+ requestOptions.onResponseHandoff(handoff.acknowledge);
48076
+ } else {
48077
+ handoff.cancel();
48078
+ }
48079
+ return published;
46847
48080
  },
46848
48081
  (error) => {
48082
+ handoff.cancel();
46849
48083
  deadline.dispose();
46850
48084
  cancellation.release();
46851
48085
  throw redactCredentialError(
@@ -46855,6 +48089,7 @@ function createRequestExecutor(deps) {
46855
48089
  );
46856
48090
  }
46857
48091
  ).catch((error) => {
48092
+ handoff.cancel();
46858
48093
  deadline.dispose();
46859
48094
  cancellation.release();
46860
48095
  throw redactCredentialError(
@@ -47094,9 +48329,11 @@ function createFetchInterceptor(context) {
47094
48329
  body: { type: "oauth", refresh: "", access: "", expires: 0 }
47095
48330
  });
47096
48331
  },
47097
- refreshQuotaAfterSuccess: async (account, intervalMinutes) => {
48332
+ refreshQuotaAfterSuccess: async (account, intervalMinutes, signal) => {
48333
+ signal?.throwIfAborted();
47098
48334
  await context.assertAdmission?.();
47099
- await refreshQuotaAfterSuccess(account, intervalMinutes);
48335
+ signal?.throwIfAborted();
48336
+ await refreshQuotaAfterSuccess(account, intervalMinutes, signal);
47100
48337
  }
47101
48338
  },
47102
48339
  // The trackers the manager selects with: its own for a store-backed
@@ -47115,7 +48352,7 @@ function createFetchInterceptor(context) {
47115
48352
  let retired = false;
47116
48353
  let retirePromise;
47117
48354
  const entering = /* @__PURE__ */ new Set();
47118
- async function intercept(input2, init) {
48355
+ async function intercept(input2, init, onResponseHandoff) {
47119
48356
  await context.assertAdmission?.();
47120
48357
  if (disposed) throw new Error("The local request runtime is disposed");
47121
48358
  if (accountSource.kind === "pool-file") {
@@ -47123,9 +48360,9 @@ function createFetchInterceptor(context) {
47123
48360
  if (disposed) throw new Error("The local request runtime is disposed");
47124
48361
  if (!isOAuthAuth(latestAuth)) return upstreamFetch(input2, init);
47125
48362
  }
47126
- return executor.execute(input2, init);
48363
+ return executor.execute(input2, init, { onResponseHandoff });
47127
48364
  }
47128
- async function fetch(input2, init) {
48365
+ async function fetch(input2, init, onResponseHandoff) {
47129
48366
  if (disposed) {
47130
48367
  return upstreamFetch(input2, init);
47131
48368
  }
@@ -47133,7 +48370,7 @@ function createFetchInterceptor(context) {
47133
48370
  return upstreamFetch(input2, init);
47134
48371
  }
47135
48372
  if (retired) throw new Error("The local request runtime is retired");
47136
- const pending = intercept(input2, init);
48373
+ const pending = intercept(input2, init, onResponseHandoff);
47137
48374
  entering.add(pending);
47138
48375
  void pending.then(
47139
48376
  () => entering.delete(pending),
@@ -47750,6 +48987,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
47750
48987
  let vaultQuotaPoller;
47751
48988
  const vaultCustody = createOpenCodeVaultCustody({
47752
48989
  accountFile: resolve17(getStoragePath()),
48990
+ insulaQuota: true,
47753
48991
  readHostSlot: async () => {
47754
48992
  if (!cachedGetAuth)
47755
48993
  throw new Error("OpenCode has not provided its sign-in yet");