@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/cli.js CHANGED
@@ -337,6 +337,7 @@ function scopedWindowParts(quota, options) {
337
337
  const remainingPercent = clampPercent(limit.remainingPercent ?? 0);
338
338
  return {
339
339
  scope: limit.scope,
340
+ ...limit.windowMinutes === void 0 ? {} : { windowMinutes: limit.windowMinutes },
340
341
  part: {
341
342
  kind: "window",
342
343
  name: quotaWindowName(limit),
@@ -405,8 +406,42 @@ function scopeAbbreviations(scopes) {
405
406
  }
406
407
  return new Map(scopes.map((scope) => [scope, short(scopeDisplayName(scope))]));
407
408
  }
409
+ function groupShortNames(groups) {
410
+ const labels = groups.map((group) => group.label.trim() || group.scope);
411
+ const short = scopeAbbreviations(labels);
412
+ return labels.map((label) => short.get(label) ?? label);
413
+ }
414
+ function groupedNarrowPieces(groups, windows) {
415
+ if (!groups || groups.length === 0)
416
+ return void 0;
417
+ const reported = windows.filter(({ part }) => part.kind === "window");
418
+ if (reported.some(({ scope }) => scope === ALL_SCOPE))
419
+ return void 0;
420
+ const candidates = groups.flatMap((group, listed) => {
421
+ const inGroup = reported.filter(({ scope }) => scope === group.scope);
422
+ const groupTightest = inGroup.reduce((least, window) => least === void 0 || (window.part.remainingPercent ?? 0) < (least.part.remainingPercent ?? 0) ? window : least, void 0);
423
+ return groupTightest ? [{ group, listed, window: groupTightest }] : [];
424
+ });
425
+ if (candidates.length === 0)
426
+ return void 0;
427
+ const names = groupShortNames(groups);
428
+ const left = (candidate) => candidate.window.part.remainingPercent ?? 0;
429
+ 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);
430
+ return shown.map((candidate, index) => {
431
+ const { windowMinutes } = candidate.window;
432
+ const piece = [
433
+ names[candidate.listed] ?? candidate.group.scope,
434
+ ...windowMinutes === void 0 ? [] : [lengthName(windowMinutes)],
435
+ `${wholePercent(left(candidate))}%`
436
+ ].join(" ");
437
+ return index === shown.length - 1 ? `${piece} left` : piece;
438
+ });
439
+ }
408
440
  function narrowTextParts(quota, options) {
409
441
  const { windows } = scopedWindowParts(quota, options);
442
+ const grouped = groupedNarrowPieces(quota?.groups, windows);
443
+ if (grouped)
444
+ return grouped;
410
445
  const general = windows.filter(({ part, scope }) => part.kind === "window" && scope === ALL_SCOPE);
411
446
  const scoped = windows.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE);
412
447
  const abbreviations = scopeAbbreviations(scoped.map(({ scope }) => scope));
@@ -445,7 +480,7 @@ function formatQuota(quota, options) {
445
480
  return parts.join(" \xB7 ");
446
481
  return quota && quota.limits.length > 0 ? NO_LIMITS_REPORTED : NO_QUOTA_READING;
447
482
  }
448
- var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED;
483
+ var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED, NARROW_GROUP_LIMIT;
449
484
  var init_format = __esm({
450
485
  "../core/dist/common-auth-embedded/quota/format.js"() {
451
486
  "use strict";
@@ -453,6 +488,7 @@ var init_format = __esm({
453
488
  QUOTA_STALE_AFTER_MS = 15 * 6e4;
454
489
  NO_QUOTA_READING = "no quota reading yet";
455
490
  NO_LIMITS_REPORTED = "no limits reported";
491
+ NARROW_GROUP_LIMIT = 2;
456
492
  }
457
493
  });
458
494
 
@@ -814,19 +850,24 @@ async function replaceWindowsFile(from, to, options = {}) {
814
850
  to = resolve2(to);
815
851
  const now = options.now ?? (() => performance.now());
816
852
  const start = now();
817
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
853
+ const leaseDeadline = options.deadline ?? Infinity;
854
+ let retryDeadline;
818
855
  const delays = [0, 10, 20, 40, 80, 100];
819
856
  let original;
820
857
  let attempts2 = 0;
821
858
  for (const delay3 of delays) {
859
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
822
860
  if (now() >= deadline)
823
861
  break;
824
862
  if (delay3)
825
863
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
826
864
  if (now() >= deadline)
827
865
  break;
866
+ const fenceStart = now();
828
867
  await options.beforeRename?.();
829
- if (now() >= deadline)
868
+ if (retryDeadline !== void 0)
869
+ retryDeadline += now() - fenceStart;
870
+ if (now() >= leaseDeadline)
830
871
  break;
831
872
  attempts2++;
832
873
  try {
@@ -838,6 +879,7 @@ async function replaceWindowsFile(from, to, options = {}) {
838
879
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
839
880
  if (!candidate)
840
881
  break;
882
+ retryDeadline ??= now() + 500;
841
883
  }
842
884
  }
843
885
  const error = new PrivateFileError(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -7186,12 +7228,12 @@ var init_doctor = __esm({
7186
7228
  });
7187
7229
 
7188
7230
  // ../core/dist/common-auth-embedded/auth-menu/login.js
7189
- import { execFileSync as defaultExecFileSync, spawn as defaultSpawn } from "node:child_process";
7190
- function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn2 = defaultSpawn) {
7231
+ import { spawn as defaultSpawn } from "node:child_process";
7232
+ function openBrowserForMenu(url, platform = process.platform, spawn2 = defaultSpawn) {
7191
7233
  try {
7192
7234
  if (platform === "win32") {
7193
7235
  const command = `Start-Process '${url.replaceAll("'", "''")}'`;
7194
- const child = spawn2("powershell.exe", [
7236
+ const child2 = spawn2("powershell.exe", [
7195
7237
  "-NoProfile",
7196
7238
  "-NonInteractive",
7197
7239
  "-WindowStyle",
@@ -7199,17 +7241,18 @@ function openBrowserForMenu(url, platform = process.platform, execFileSync = def
7199
7241
  "-EncodedCommand",
7200
7242
  Buffer.from(command, "utf16le").toString("base64")
7201
7243
  ], { stdio: "ignore", windowsHide: true });
7202
- child.on("error", () => {
7203
- });
7204
- child.unref();
7205
- return child.pid !== void 0;
7206
- } else {
7207
- execFileSync(platform === "darwin" ? "open" : "xdg-open", [url], {
7208
- stdio: "ignore",
7209
- timeout: 3e3
7244
+ child2.on("error", () => {
7210
7245
  });
7246
+ child2.unref();
7247
+ return child2.pid !== void 0;
7211
7248
  }
7212
- return true;
7249
+ const child = spawn2(platform === "darwin" ? "open" : "xdg-open", [url], {
7250
+ stdio: "ignore"
7251
+ });
7252
+ child.on("error", () => {
7253
+ });
7254
+ child.unref();
7255
+ return child.pid !== void 0;
7213
7256
  } catch {
7214
7257
  return false;
7215
7258
  }
@@ -8012,6 +8055,326 @@ var init_auth_menu = __esm({
8012
8055
  }
8013
8056
  });
8014
8057
 
8058
+ // ../core/dist/common-auth-embedded/claustrum/errors.js
8059
+ var ClaustrumConsumerError;
8060
+ var init_errors2 = __esm({
8061
+ "../core/dist/common-auth-embedded/claustrum/errors.js"() {
8062
+ "use strict";
8063
+ ClaustrumConsumerError = class extends Error {
8064
+ kind;
8065
+ constructor(kind, message) {
8066
+ super(message);
8067
+ this.name = "ClaustrumConsumerError";
8068
+ this.kind = kind;
8069
+ }
8070
+ };
8071
+ }
8072
+ });
8073
+
8074
+ // ../core/dist/common-auth-embedded/claustrum/availability.js
8075
+ import { ClaustrumCredentialError } from "@cortexkit/claustrum-client";
8076
+ import { SocketClosedError, SocketTimeoutError, SubcCallError } from "@cortexkit/subc-client";
8077
+ function classifyVaultFailure(error) {
8078
+ if (error instanceof ClaustrumUnreachableError || error instanceof SocketClosedError || error instanceof SocketTimeoutError)
8079
+ return "unreachable";
8080
+ const code2 = error instanceof ClaustrumCredentialError || error instanceof SubcCallError ? error.code : error instanceof Error && "code" in error ? error.code : void 0;
8081
+ if (typeof code2 !== "string" || !Object.hasOwn(VAULT_FAILURE_CLASSES, code2))
8082
+ return "answered";
8083
+ return VAULT_FAILURE_CLASSES[code2];
8084
+ }
8085
+ var VAULT_FAILURE_CLASSES, ClaustrumUnreachableError;
8086
+ var init_availability = __esm({
8087
+ "../core/dist/common-auth-embedded/claustrum/availability.js"() {
8088
+ "use strict";
8089
+ init_errors2();
8090
+ VAULT_FAILURE_CLASSES = Object.freeze({
8091
+ ECONNREFUSED: "unreachable",
8092
+ ENOENT: "unreachable",
8093
+ ECONNRESET: "unreachable",
8094
+ EPIPE: "unreachable",
8095
+ ETIMEDOUT: "unreachable",
8096
+ transport_error: "unreachable",
8097
+ unavailable: "unreachable",
8098
+ timeout: "unreachable",
8099
+ route_closed: "unreachable",
8100
+ daemon_draining: "unreachable",
8101
+ connection_closed: "unreachable",
8102
+ connection_dropped: "unreachable",
8103
+ request_deadline: "unreachable",
8104
+ deadline_exceeded_no_drop_observed: "unreachable",
8105
+ module_reloading: "unreachable",
8106
+ module_warming: "unreachable",
8107
+ target_unavailable: "unreachable",
8108
+ module_timeout: "unreachable",
8109
+ invalid_response: "answered",
8110
+ invalid_record_version: "answered",
8111
+ invalid_expiry: "answered",
8112
+ invalid_status: "answered",
8113
+ invalid_params: "answered",
8114
+ ttl_unsatisfiable: "answered",
8115
+ not_found: "answered",
8116
+ enrollment_revoked: "answered",
8117
+ enrollment_invalid: "answered",
8118
+ grant_denied: "answered",
8119
+ credential_unavailable: "answered",
8120
+ needs_reauth: "answered",
8121
+ declined: "answered",
8122
+ disabled: "answered",
8123
+ identity_changed: "answered",
8124
+ closed: "answered",
8125
+ client_closed: "answered",
8126
+ pending_exists: "answered",
8127
+ pending_queue_full: "answered",
8128
+ already_consumed: "answered",
8129
+ superseded: "answered",
8130
+ stale_generation: "answered",
8131
+ missing_identity: "answered",
8132
+ invalid_control_body: "answered",
8133
+ unknown_module: "answered",
8134
+ module_removed: "answered",
8135
+ capability_denied: "answered",
8136
+ unknown_channel: "unreachable",
8137
+ stale_route_epoch: "unreachable",
8138
+ capability_forbidden: "answered",
8139
+ capability_unprovided: "answered",
8140
+ capability_ambiguous: "answered",
8141
+ invalid_capability_identifier: "answered",
8142
+ binary_body_required: "answered",
8143
+ binary_call_requires_call_binary: "answered",
8144
+ corr_exhausted: "answered",
8145
+ late_route_cleanup_failed: "answered",
8146
+ reverse_request_capability_not_declared: "answered",
8147
+ stale_route_handle: "answered",
8148
+ reverse_request_unhandled: "answered",
8149
+ handler_error: "answered",
8150
+ health_error: "answered",
8151
+ duplicate_module_id: "answered",
8152
+ route_rejected: "answered",
8153
+ lock_busy: "answered",
8154
+ owner_invalid: "answered",
8155
+ renewal_failed: "answered",
8156
+ unsupported_platform: "answered",
8157
+ EACCES: "answered",
8158
+ EPERM: "answered",
8159
+ ERR_PRIVATE_FILES_SECURITY: "answered"
8160
+ });
8161
+ ClaustrumUnreachableError = class extends ClaustrumConsumerError {
8162
+ constructor() {
8163
+ super("unavailable", "Claustrum scoped operation unavailable");
8164
+ this.name = "ClaustrumUnreachableError";
8165
+ }
8166
+ };
8167
+ }
8168
+ });
8169
+
8170
+ // ../core/dist/common-auth-embedded/claustrum/watch.js
8171
+ var SAFETY_POLL_MS, WATCH_RETRY_MS, RESUBSCRIBE_BACKOFF_MS, ChangeNoticeReader, CoalescedRead, ScopedRosterWatch;
8172
+ var init_watch = __esm({
8173
+ "../core/dist/common-auth-embedded/claustrum/watch.js"() {
8174
+ "use strict";
8175
+ SAFETY_POLL_MS = 5 * 6e4;
8176
+ WATCH_RETRY_MS = 5 * 6e4;
8177
+ RESUBSCRIBE_BACKOFF_MS = 1e3;
8178
+ ChangeNoticeReader = class {
8179
+ #epoch;
8180
+ #seq = 0;
8181
+ /**
8182
+ * Begin a new watch, whose first notice is seq 1 again. The epoch is kept,
8183
+ * so a module restart between two watches still reads as a break.
8184
+ */
8185
+ restart() {
8186
+ this.#seq = 0;
8187
+ }
8188
+ continuous(notice) {
8189
+ const continuous = notice.kind === "changed" && notice.seq === this.#seq + 1 && (this.#epoch === void 0 || notice.epoch === this.#epoch);
8190
+ this.#epoch = notice.epoch;
8191
+ this.#seq = notice.seq;
8192
+ return continuous;
8193
+ }
8194
+ };
8195
+ CoalescedRead = class {
8196
+ #read;
8197
+ #onError;
8198
+ #running;
8199
+ #queued = false;
8200
+ constructor(read, onError) {
8201
+ this.#read = read;
8202
+ this.#onError = onError;
8203
+ }
8204
+ /** The read in flight (including its queued follow-up), if any. */
8205
+ get running() {
8206
+ return this.#running;
8207
+ }
8208
+ request() {
8209
+ if (this.#running) {
8210
+ this.#queued = true;
8211
+ return this.#running;
8212
+ }
8213
+ this.#running = (async () => {
8214
+ do {
8215
+ this.#queued = false;
8216
+ try {
8217
+ await this.#read();
8218
+ } catch (error) {
8219
+ this.#onError(error);
8220
+ }
8221
+ } while (this.#queued);
8222
+ })().finally(() => {
8223
+ this.#running = void 0;
8224
+ });
8225
+ return this.#running;
8226
+ }
8227
+ };
8228
+ ScopedRosterWatch = class {
8229
+ #options;
8230
+ #reader = new ChangeNoticeReader();
8231
+ #reads;
8232
+ #mode = "polling";
8233
+ #watch;
8234
+ #timer;
8235
+ #stopped = false;
8236
+ #latestView;
8237
+ #force = false;
8238
+ /**
8239
+ * How many accepted watches in a row have closed; each one doubles the wait
8240
+ * before the next re-subscribe. Reset once a watch stays up five minutes.
8241
+ */
8242
+ #closes = 0;
8243
+ constructor(options) {
8244
+ this.#options = options;
8245
+ this.#reads = new CoalescedRead(async () => {
8246
+ const force = this.#force;
8247
+ this.#force = false;
8248
+ if (force || this.#latestView !== this.#options.view())
8249
+ await this.#options.discover(this.#latestView ?? "");
8250
+ }, (error) => {
8251
+ if (!this.#stopped)
8252
+ this.#options.onError?.(error);
8253
+ });
8254
+ }
8255
+ get mode() {
8256
+ return this.#mode;
8257
+ }
8258
+ start() {
8259
+ if (this.#stopped || this.#watch || this.#timer)
8260
+ return;
8261
+ if (typeof this.#options.client.watchScoped !== "function") {
8262
+ this.#setMode("fallback", "client-without-watch");
8263
+ return;
8264
+ }
8265
+ void this.#open(false);
8266
+ }
8267
+ stop() {
8268
+ if (this.#stopped)
8269
+ return;
8270
+ this.#stopped = true;
8271
+ if (this.#timer)
8272
+ (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
8273
+ this.#timer = void 0;
8274
+ const watch = this.#watch;
8275
+ this.#watch = void 0;
8276
+ watch?.handle.stop();
8277
+ }
8278
+ #setMode(mode, reason) {
8279
+ if (this.#mode === mode)
8280
+ return;
8281
+ this.#mode = mode;
8282
+ this.#options.logger?.debug("claustrum vault watch", { mode, reason });
8283
+ this.#options.onMode?.(mode);
8284
+ }
8285
+ #later(delay3, run) {
8286
+ this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
8287
+ this.#timer = void 0;
8288
+ if (!this.#stopped)
8289
+ run();
8290
+ }, delay3);
8291
+ this.#timer.unref?.();
8292
+ }
8293
+ async #open(resubscribed) {
8294
+ let token;
8295
+ try {
8296
+ token = await this.#options.enrollmentToken();
8297
+ } catch (error) {
8298
+ if (this.#stopped)
8299
+ return;
8300
+ this.#options.onError?.(error);
8301
+ this.#fallback("token-unreadable");
8302
+ return;
8303
+ }
8304
+ const watchScoped = this.#options.client.watchScoped;
8305
+ if (this.#stopped || this.#watch || !watchScoped)
8306
+ return;
8307
+ this.#reader.restart();
8308
+ this.#force = resubscribed;
8309
+ let watch;
8310
+ let handle;
8311
+ try {
8312
+ handle = watchScoped.call(this.#options.client, (notice) => {
8313
+ if (this.#stopped || !watch || this.#watch !== watch)
8314
+ return;
8315
+ watch.notices++;
8316
+ if (watch.notices === 1) {
8317
+ this.#options.onReachable?.();
8318
+ watch.acceptedAt = (this.#options.now ?? Date.now)();
8319
+ this.#setMode("watching", "accepted");
8320
+ }
8321
+ if (!this.#reader.continuous(notice))
8322
+ this.#force = true;
8323
+ this.#latestView = notice.view;
8324
+ void this.#reads.request();
8325
+ }, { enrollmentToken: token });
8326
+ } catch (error) {
8327
+ this.#options.onError?.(error);
8328
+ this.#fallback("watch-failed");
8329
+ return;
8330
+ }
8331
+ watch = { handle, notices: 0 };
8332
+ this.#watch = watch;
8333
+ this.#setMode("polling", resubscribed ? "resubscribing" : "opening");
8334
+ const opened = watch;
8335
+ handle.closed.then((end) => this.#closed(opened, end), (error) => this.#closed(opened, { kind: "transport_lost", error }));
8336
+ }
8337
+ #closed(watch, end) {
8338
+ if (this.#stopped || this.#watch !== watch)
8339
+ return;
8340
+ this.#watch = void 0;
8341
+ if (end.kind === "stopped")
8342
+ return;
8343
+ if (end.kind === "transport_lost")
8344
+ this.#options.onTransportLost?.();
8345
+ if (end.kind === "unsupported") {
8346
+ this.#setMode("fallback", "vault-without-watch");
8347
+ return;
8348
+ }
8349
+ if (end.kind === "refused") {
8350
+ this.#fallback("refused");
8351
+ try {
8352
+ this.#options.onRefused(end.error);
8353
+ } catch (error) {
8354
+ this.#options.onError?.(error);
8355
+ }
8356
+ return;
8357
+ }
8358
+ if (watch.notices > 0) {
8359
+ const now = (this.#options.now ?? Date.now)();
8360
+ if (watch.acceptedAt !== void 0 && now - watch.acceptedAt >= SAFETY_POLL_MS)
8361
+ this.#closes = 0;
8362
+ const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
8363
+ this.#closes++;
8364
+ this.#setMode("polling", "resubscribing");
8365
+ this.#later(delay3, () => void this.#open(true));
8366
+ return;
8367
+ }
8368
+ this.#fallback(end.kind);
8369
+ }
8370
+ #fallback(reason) {
8371
+ this.#setMode("fallback", reason);
8372
+ this.#later(WATCH_RETRY_MS, () => void this.#open(false));
8373
+ }
8374
+ };
8375
+ }
8376
+ });
8377
+
8015
8378
  // ../core/dist/common-auth-embedded/claustrum/insula.js
8016
8379
  import { resolve as resolve4 } from "node:path";
8017
8380
  import { storeIdentity } from "@cortexkit/claustrum-client";
@@ -8050,12 +8413,95 @@ function insulaUsageTransport(options) {
8050
8413
  clearTimeout(timer);
8051
8414
  client?.close();
8052
8415
  }
8416
+ },
8417
+ watchUsage(onNotice) {
8418
+ let client;
8419
+ let subscription;
8420
+ let stopped = false;
8421
+ const closed = (async () => {
8422
+ let deadline;
8423
+ const timeout = new Promise((_resolve, reject) => {
8424
+ deadline = setTimeout(
8425
+ // Coded as a timeout, so InsulaQuotaSource treats a watch that could
8426
+ // not open in time as an unreachable insula and tries again later,
8427
+ // not as a refusal.
8428
+ () => reject(Object.assign(new Error("insula watch timeout"), {
8429
+ code: "timeout"
8430
+ })),
8431
+ 3e3
8432
+ );
8433
+ deadline.unref?.();
8434
+ });
8435
+ const open12 = (async () => {
8436
+ const handshakeTimeoutMs = Math.min(options.handshakeTimeoutMs ?? 3e3, 3e3);
8437
+ const connected = options.connector ? await options.connector({
8438
+ connectionFile: options.connectionFile,
8439
+ handshakeTimeoutMs
8440
+ }) : await SubcClient.connect({
8441
+ connectionFile: options.connectionFile,
8442
+ handshakeTimeoutMs
8443
+ });
8444
+ client = connected;
8445
+ if (stopped) {
8446
+ connected.close();
8447
+ return;
8448
+ }
8449
+ const route = await connected.routeOpen({ kind: "management_surface", module_id: "insula" }, identity);
8450
+ if (stopped) {
8451
+ connected.close();
8452
+ return;
8453
+ }
8454
+ subscription = connected.subscribe(route, { method: "usage.watch" }, onNotice);
8455
+ })();
8456
+ try {
8457
+ await Promise.race([open12, timeout]);
8458
+ } catch (error) {
8459
+ stopped = true;
8460
+ throw error;
8461
+ } finally {
8462
+ clearTimeout(deadline);
8463
+ }
8464
+ if (subscription)
8465
+ await subscription.closed;
8466
+ })().finally(() => {
8467
+ stopped = true;
8468
+ client?.close();
8469
+ });
8470
+ return {
8471
+ stop() {
8472
+ if (stopped)
8473
+ return;
8474
+ stopped = true;
8475
+ subscription?.unsubscribe();
8476
+ client?.close();
8477
+ },
8478
+ closed
8479
+ };
8053
8480
  }
8054
8481
  };
8055
8482
  }
8056
8483
  function record2(value) {
8057
8484
  return typeof value === "object" && value !== null && !Array.isArray(value);
8058
8485
  }
8486
+ function decodeUsageNotice(body) {
8487
+ let value;
8488
+ try {
8489
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
8490
+ } catch {
8491
+ return void 0;
8492
+ }
8493
+ 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")
8494
+ return void 0;
8495
+ return {
8496
+ kind: value.kind,
8497
+ epoch: value.epoch,
8498
+ seq: value.seq,
8499
+ ...typeof value.provider === "string" && { provider: value.provider }
8500
+ };
8501
+ }
8502
+ function refusalCode(error) {
8503
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : void 0;
8504
+ }
8059
8505
  function acquireInsulaQuotaSource(transport, tokenPath) {
8060
8506
  const key = JSON.stringify([
8061
8507
  resolve4(transport.connectionFile),
@@ -8079,26 +8525,76 @@ function acquireInsulaQuotaSource(transport, tokenPath) {
8079
8525
  }
8080
8526
  };
8081
8527
  }
8082
- var MINUTE, MAX_AGE, sources, attempts, InsulaQuotaSource;
8528
+ var MINUTE, MAX_AGE, COLD_WAIT, sources, attempts, InsulaQuotaSource;
8083
8529
  var init_insula = __esm({
8084
8530
  "../core/dist/common-auth-embedded/claustrum/insula.js"() {
8085
8531
  "use strict";
8532
+ init_availability();
8533
+ init_watch();
8086
8534
  MINUTE = 6e4;
8087
8535
  MAX_AGE = 4 * MINUTE;
8536
+ COLD_WAIT = 2 * MINUTE;
8088
8537
  sources = /* @__PURE__ */ new Map();
8089
8538
  attempts = /* @__PURE__ */ new Map();
8090
8539
  InsulaQuotaSource = class {
8091
8540
  transport;
8092
8541
  key;
8093
8542
  #entries = [];
8094
- #pending;
8543
+ #available = false;
8544
+ #completeProviders = /* @__PURE__ */ new Set();
8545
+ #coldSince = /* @__PURE__ */ new Map();
8546
+ /** Every usage.get, polled or watch-driven, shares this one slot. */
8547
+ #reads = new CoalescedRead(async () => {
8548
+ try {
8549
+ const reply = await this.transport.getUsage();
8550
+ if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== void 0)
8551
+ throw new Error("unavailable insula usage");
8552
+ this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
8553
+ this.#available = this.#entries.length === reply.result.length && (reply.completeProviders === void 0 || Array.isArray(reply.completeProviders) && reply.completeProviders.every((value) => typeof value === "string"));
8554
+ this.#completeProviders = new Set(this.#available && Array.isArray(reply.completeProviders) ? reply.completeProviders : []);
8555
+ for (const provider2 of this.#completeProviders)
8556
+ this.#coldSince.delete(provider2);
8557
+ } catch {
8558
+ this.#entries = [];
8559
+ this.#available = false;
8560
+ this.#completeProviders.clear();
8561
+ }
8562
+ }, () => {
8563
+ });
8564
+ #reader = new ChangeNoticeReader();
8565
+ #mode = "polling";
8566
+ #watchers = 0;
8567
+ /**
8568
+ * How many registered watchers read every provider. Watchers limited to one
8569
+ * provider are counted per provider in `#providers` instead.
8570
+ */
8571
+ #everyProvider = 0;
8572
+ #providers = /* @__PURE__ */ new Map();
8573
+ #watch;
8574
+ #timer;
8575
+ #timers = {};
8576
+ /**
8577
+ * How many accepted watches in a row have closed; each one doubles the wait
8578
+ * before the next re-subscribe. Reset once a watch brings a second notice.
8579
+ */
8580
+ #closes = 0;
8095
8581
  constructor(transport, key) {
8096
8582
  this.transport = transport;
8097
8583
  this.key = key;
8098
8584
  }
8585
+ /**
8586
+ * The background poll: at most one usage.get per minute per daemon and
8587
+ * enrollment token. While a watch is open it reads nothing, because insula's
8588
+ * notices announce every new reading. If insula stops announcing an account,
8589
+ * that account's last entry grows older than the freshness limit `current()`
8590
+ * applies, `current()` returns nothing for it, and the plugin falls back to
8591
+ * its own provider poll for that account.
8592
+ */
8099
8593
  refresh(now) {
8100
- if (this.#pending)
8101
- return this.#pending;
8594
+ if (this.#reads.running)
8595
+ return this.#reads.running;
8596
+ if (this.#mode === "watching")
8597
+ return Promise.resolve();
8102
8598
  for (const [key, time] of attempts) {
8103
8599
  if (now - time >= MINUTE)
8104
8600
  attempts.delete(key);
@@ -8107,19 +8603,119 @@ var init_insula = __esm({
8107
8603
  if (lastAttempt !== void 0 && now - lastAttempt < MINUTE)
8108
8604
  return Promise.resolve();
8109
8605
  attempts.set(this.key, now);
8110
- this.#pending = (async () => {
8111
- try {
8112
- const reply = await this.transport.getUsage();
8113
- if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== void 0)
8114
- throw new Error("unavailable insula usage");
8115
- this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
8116
- } catch {
8117
- this.#entries = [];
8606
+ return this.#reads.request();
8607
+ }
8608
+ /** How this source currently learns about usage changes, for logs. */
8609
+ watchMode() {
8610
+ return this.#mode;
8611
+ }
8612
+ /**
8613
+ * Hold a `usage.watch` open while any watcher wants it, and re-read
8614
+ * usage.get when a notice says something changed. Watchers of one source
8615
+ * share one watch, since insula admits only 64 per process. Returns the
8616
+ * release; the last release closes the watch.
8617
+ */
8618
+ watch(options = {}) {
8619
+ this.#watchers++;
8620
+ const provider2 = options.provider;
8621
+ if (provider2 === void 0)
8622
+ this.#everyProvider++;
8623
+ else
8624
+ this.#providers.set(provider2, (this.#providers.get(provider2) ?? 0) + 1);
8625
+ if (this.#watchers === 1) {
8626
+ this.#timers = options;
8627
+ this.#open();
8628
+ }
8629
+ let released = false;
8630
+ return () => {
8631
+ if (released)
8632
+ return;
8633
+ released = true;
8634
+ if (provider2 === void 0)
8635
+ this.#everyProvider--;
8636
+ else {
8637
+ const left = (this.#providers.get(provider2) ?? 1) - 1;
8638
+ if (left > 0)
8639
+ this.#providers.set(provider2, left);
8640
+ else
8641
+ this.#providers.delete(provider2);
8118
8642
  }
8119
- })().finally(() => {
8120
- this.#pending = void 0;
8121
- });
8122
- return this.#pending;
8643
+ if (--this.#watchers === 0)
8644
+ this.#stopWatch();
8645
+ };
8646
+ }
8647
+ #stopWatch() {
8648
+ if (this.#timer)
8649
+ (this.#timers.clearTimeoutImpl ?? clearTimeout)(this.#timer);
8650
+ this.#timer = void 0;
8651
+ const watch = this.#watch;
8652
+ this.#watch = void 0;
8653
+ watch?.handle?.stop();
8654
+ this.#mode = "polling";
8655
+ }
8656
+ #later(delay3) {
8657
+ this.#timer = (this.#timers.setTimeoutImpl ?? setTimeout)(() => {
8658
+ this.#timer = void 0;
8659
+ if (this.#watchers > 0 && !this.#watch)
8660
+ this.#open();
8661
+ }, delay3);
8662
+ this.#timer.unref?.();
8663
+ }
8664
+ #open() {
8665
+ const watchUsage = this.transport.watchUsage;
8666
+ if (!watchUsage) {
8667
+ this.#mode = "fallback";
8668
+ return;
8669
+ }
8670
+ this.#mode = "polling";
8671
+ this.#reader.restart();
8672
+ const watch = { notices: 0 };
8673
+ this.#watch = watch;
8674
+ let handle;
8675
+ try {
8676
+ handle = watchUsage.call(this.transport, (body) => this.#notice(watch, body));
8677
+ } catch (error) {
8678
+ this.#closed(watch, error);
8679
+ return;
8680
+ }
8681
+ watch.handle = handle;
8682
+ handle.closed.then(() => this.#closed(watch, void 0), (error) => this.#closed(watch, error));
8683
+ }
8684
+ #notice(watch, body) {
8685
+ if (this.#watch !== watch)
8686
+ return;
8687
+ watch.notices++;
8688
+ if (watch.notices === 1)
8689
+ this.#mode = "watching";
8690
+ if (watch.notices === 2)
8691
+ this.#closes = 0;
8692
+ const notice = decodeUsageNotice(body);
8693
+ if (!notice)
8694
+ this.#reader.restart();
8695
+ const continuous = notice ? this.#reader.continuous(notice) : false;
8696
+ if (!continuous || notice?.provider === void 0 || this.#everyProvider > 0 || this.#providers.has(notice.provider))
8697
+ void this.#reads.request();
8698
+ }
8699
+ #closed(watch, error) {
8700
+ if (this.#watch !== watch)
8701
+ return;
8702
+ this.#watch = void 0;
8703
+ const code2 = refusalCode(error);
8704
+ if (code2 === "unknown_method" || code2 === "usage_watch_limit") {
8705
+ this.#mode = "fallback";
8706
+ return;
8707
+ }
8708
+ if (watch.notices > 0) {
8709
+ const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
8710
+ this.#closes++;
8711
+ this.#mode = "polling";
8712
+ this.#later(delay3);
8713
+ return;
8714
+ }
8715
+ this.#mode = "fallback";
8716
+ void this.#reads.request();
8717
+ if (error === void 0 || classifyVaultFailure(error) === "unreachable")
8718
+ this.#later(WATCH_RETRY_MS);
8123
8719
  }
8124
8720
  current(provider2, accountId, now) {
8125
8721
  for (const entry of this.#entries) {
@@ -8140,6 +8736,37 @@ var init_insula = __esm({
8140
8736
  }
8141
8737
  return void 0;
8142
8738
  }
8739
+ /** Cache-only background lookup; current() retains its original miss behavior. */
8740
+ lookup(provider2, accountId, now) {
8741
+ if (!this.#available)
8742
+ return { miss: "unreachable" };
8743
+ const entry = this.#entries.find((value) => value.provider === provider2 && typeof value.account === "string" && value.account.trim() === accountId);
8744
+ const errorClass = (entry ?? this.#entries.find((value) => value.provider === provider2 && value.account === void 0 && value.errorClass !== void 0))?.errorClass;
8745
+ if (errorClass === "upstream_failed")
8746
+ return { miss: "upstream-failed" };
8747
+ if (errorClass === "credential_absent" || errorClass === "credential_unusable" || errorClass === "credential_rejected")
8748
+ return { miss: "credential" };
8749
+ if (errorClass !== void 0)
8750
+ return { miss: "unreachable" };
8751
+ if (entry) {
8752
+ const fetchedAt = typeof entry.fetchedAt === "string" ? Date.parse(entry.fetchedAt) : Number.NaN;
8753
+ if (!record2(entry.usage) || !Number.isFinite(fetchedAt))
8754
+ return { miss: "unreachable" };
8755
+ const reading = {
8756
+ entry,
8757
+ context: {
8758
+ fetchedAt,
8759
+ ...typeof entry.source === "string" && { source: entry.source }
8760
+ }
8761
+ };
8762
+ return now >= fetchedAt + MAX_AGE || entry.stale !== void 0 ? { miss: "stale", reading } : { reading };
8763
+ }
8764
+ if (this.#completeProviders.has(provider2))
8765
+ return { miss: "absent" };
8766
+ const since = this.#coldSince.get(provider2) ?? now;
8767
+ this.#coldSince.set(provider2, since);
8768
+ return { miss: now - since >= COLD_WAIT ? "unreachable" : "cold" };
8769
+ }
8143
8770
  };
8144
8771
  }
8145
8772
  });
@@ -8186,30 +8813,14 @@ var init_any_signal = __esm({
8186
8813
  }
8187
8814
  });
8188
8815
 
8189
- // ../core/dist/common-auth-embedded/claustrum/errors.js
8190
- var ClaustrumConsumerError;
8191
- var init_errors2 = __esm({
8192
- "../core/dist/common-auth-embedded/claustrum/errors.js"() {
8193
- "use strict";
8194
- ClaustrumConsumerError = class extends Error {
8195
- kind;
8196
- constructor(kind, message) {
8197
- super(message);
8198
- this.name = "ClaustrumConsumerError";
8199
- this.kind = kind;
8200
- }
8201
- };
8202
- }
8203
- });
8204
-
8205
8816
  // ../core/dist/common-auth-embedded/claustrum/enrollment.js
8206
8817
  import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID10 } from "node:crypto";
8207
8818
  import { constants as fsConstants } from "node:fs";
8208
8819
  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";
8209
8820
  import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join5, resolve as resolve5 } from "node:path";
8210
- import { ClaustrumCredentialError, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8821
+ import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8211
8822
  function classifyEnrollmentError(error) {
8212
- if (!(error instanceof ClaustrumCredentialError))
8823
+ if (!(error instanceof ClaustrumCredentialError2))
8213
8824
  return void 0;
8214
8825
  if (TERMINAL_ENROLLMENT_CODES.has(error.code))
8215
8826
  return { code: error.code, disposition: "terminal" };
@@ -8910,9 +9521,9 @@ var init_host_slot = __esm({
8910
9521
  });
8911
9522
 
8912
9523
  // ../core/dist/common-auth-embedded/claustrum/custody.js
8913
- import { ClaustrumCredentialError as ClaustrumCredentialError2 } from "@cortexkit/claustrum-client";
9524
+ import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
8914
9525
  function isScopedCredentialRotation(served, current) {
8915
- return current !== void 0 && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
9526
+ return current !== void 0 && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
8916
9527
  }
8917
9528
  function scopedRetryReason(served, current) {
8918
9529
  if (current === void 0)
@@ -8980,16 +9591,19 @@ function grantReachOf(listed) {
8980
9591
  tuples: Object.freeze(grantTuples.map(({ selectorKind, selector, operation }) => Object.freeze({ selectorKind, selector, operation })))
8981
9592
  });
8982
9593
  }
8983
- var defaultLogger, SERVING_MARGIN_MS, ClaustrumScopedCustody;
9594
+ var defaultLogger, SERVING_MARGIN_MS, KEPT_RECEIPT_MARGIN_MS, ClaustrumScopedCustody;
8984
9595
  var init_custody = __esm({
8985
9596
  "../core/dist/common-auth-embedded/claustrum/custody.js"() {
8986
9597
  "use strict";
8987
9598
  init_logger();
9599
+ init_availability();
8988
9600
  init_enrollment();
8989
9601
  init_errors2();
8990
9602
  init_host_slot();
9603
+ init_watch();
8991
9604
  defaultLogger = createLogger2("claustrum");
8992
9605
  SERVING_MARGIN_MS = 3e5;
9606
+ KEPT_RECEIPT_MARGIN_MS = 6e4;
8993
9607
  ClaustrumScopedCustody = class {
8994
9608
  #client;
8995
9609
  #readToken;
@@ -9000,7 +9614,20 @@ var init_custody = __esm({
9000
9614
  #logger;
9001
9615
  #provenance = /* @__PURE__ */ new WeakMap();
9002
9616
  #reports = /* @__PURE__ */ new WeakMap();
9617
+ #kept = /* @__PURE__ */ new Map();
9618
+ #keptAttempts = /* @__PURE__ */ new WeakMap();
9619
+ #setTimeout;
9620
+ #clearTimeout;
9621
+ #outage = false;
9622
+ #outageError = new ClaustrumUnreachableError();
9623
+ #probeTimer;
9624
+ #probing = false;
9625
+ #lastProbeAt = -Infinity;
9626
+ #probeDelay = 2e3;
9003
9627
  #closed = false;
9628
+ /** The view of the last successful `discover()`, for `watchRoster`. */
9629
+ #discoveredView;
9630
+ #watches = /* @__PURE__ */ new Set();
9004
9631
  constructor(options) {
9005
9632
  const tokenPath = options.tokenPath;
9006
9633
  if (options.readToken) {
@@ -9016,6 +9643,56 @@ var init_custody = __esm({
9016
9643
  this.#requireAssertion = options.requireAssertion ?? false;
9017
9644
  this.#now = options.now ?? Date.now;
9018
9645
  this.#logger = options.logger ?? defaultLogger;
9646
+ this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
9647
+ this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
9648
+ }
9649
+ /** A watch losing its transport is the same outage as an unreachable read. */
9650
+ transportLost(error) {
9651
+ if (this.#closed || this.#outage)
9652
+ return;
9653
+ this.#outage = true;
9654
+ this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError();
9655
+ this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
9656
+ this.#scheduleProbe();
9657
+ }
9658
+ /** Any vault answer ends transport fallback, even when it refuses access. */
9659
+ reachable() {
9660
+ if (this.#closed || !this.#outage)
9661
+ return;
9662
+ this.#outage = false;
9663
+ if (this.#probeTimer)
9664
+ this.#clearTimeout(this.#probeTimer);
9665
+ this.#probeTimer = void 0;
9666
+ this.#probeDelay = 2e3;
9667
+ for (const kept of this.#kept.values())
9668
+ kept.since = null;
9669
+ (this.#logger.info ?? defaultLogger.info)("vault receipt serving resumed", { reason: "reachable" });
9670
+ }
9671
+ #scheduleProbe() {
9672
+ if (this.#closed || !this.#outage || this.#probeTimer || this.#probing)
9673
+ return;
9674
+ this.#probeTimer = this.#setTimeout(() => {
9675
+ this.#probeTimer = void 0;
9676
+ this.#probe(true);
9677
+ }, this.#probeDelay);
9678
+ this.#probeTimer.unref?.();
9679
+ }
9680
+ #probe(idle = false) {
9681
+ if (this.#closed || !this.#outage || this.#probing)
9682
+ return;
9683
+ if (this.#now() - this.#lastProbeAt < 1e3) {
9684
+ this.#scheduleProbe();
9685
+ return;
9686
+ }
9687
+ this.#lastProbeAt = this.#now();
9688
+ this.#probing = true;
9689
+ void this.#list().catch(() => {
9690
+ if (idle && this.#outage)
9691
+ this.#probeDelay = Math.min(this.#probeDelay * 2, 3e4);
9692
+ }).finally(() => {
9693
+ this.#probing = false;
9694
+ this.#scheduleProbe();
9695
+ });
9019
9696
  }
9020
9697
  #check(signal) {
9021
9698
  if (this.#closed)
@@ -9049,13 +9726,20 @@ var init_custody = __esm({
9049
9726
  ]) : await pending;
9050
9727
  } catch (error) {
9051
9728
  this.#check(signal);
9052
- if (error instanceof ClaustrumCredentialError2)
9729
+ if (classifyVaultFailure(error) === "unreachable")
9730
+ this.transportLost(error);
9731
+ else
9732
+ this.reachable();
9733
+ if (error instanceof ClaustrumCredentialError3)
9053
9734
  throw error;
9735
+ if (classifyVaultFailure(error) === "unreachable")
9736
+ throw new ClaustrumUnreachableError();
9054
9737
  throw new ClaustrumConsumerError("unavailable", "Claustrum scoped operation unavailable");
9055
9738
  } finally {
9056
9739
  removeAbortListener?.();
9057
9740
  }
9058
9741
  this.#check(signal);
9742
+ this.reachable();
9059
9743
  return result;
9060
9744
  }
9061
9745
  /**
@@ -9065,8 +9749,25 @@ var init_custody = __esm({
9065
9749
  * skipped records: they simply are not this consumer's.
9066
9750
  */
9067
9751
  async discover(signal) {
9068
- const token = await this.#token(signal);
9069
- const inventory = await this.#call(() => this.#client.listScoped(token), signal);
9752
+ const inventory = await this.#list(signal);
9753
+ this.#discoveredView = inventory.view;
9754
+ return inventory;
9755
+ }
9756
+ async #list(signal) {
9757
+ let inventory;
9758
+ let token;
9759
+ try {
9760
+ token = await this.#token(signal);
9761
+ } catch (error) {
9762
+ this.#kept.clear();
9763
+ throw error;
9764
+ }
9765
+ try {
9766
+ inventory = await this.#call(() => this.#client.listScoped(token), signal);
9767
+ } catch (error) {
9768
+ this.listFailed(error);
9769
+ throw error;
9770
+ }
9070
9771
  const skipped = [];
9071
9772
  const candidates = [];
9072
9773
  const counts = /* @__PURE__ */ new Map();
@@ -9114,21 +9815,105 @@ var init_custody = __esm({
9114
9815
  };
9115
9816
  }
9116
9817
  /**
9117
- * Fetch the credential for one physical send and wrap it in a fresh receipt.
9118
- * The vault's served identity (or, without one, the plugin's parse of the
9119
- * token) must equal the roster's when both are present. Without
9120
- * `requireAssertion`, absence on either side proves nothing and does not
9121
- * refuse; the receipt records what the vault asserted separately from what
9122
- * the roster expected. With it, a reply that does not itself name the
9123
- * credential id and the expected account is refused.
9818
+ * Apply a failed account listing: any answer from the vault (a refusal such
9819
+ * as a revoked enrollment's `not_found`) drops every kept receipt, while an
9820
+ * unreachable vault keeps them. A vault watch that ends with the same
9821
+ * refusal calls this too, so both paths treat it alike.
9822
+ */
9823
+ listFailed(error) {
9824
+ if (classifyVaultFailure(error) === "unreachable")
9825
+ this.transportLost(error);
9826
+ else {
9827
+ this.reachable();
9828
+ this.#kept.clear();
9829
+ }
9830
+ }
9831
+ /** Discard bearer material when a route is removed, declined or rebound. */
9832
+ forget(credentialId) {
9833
+ this.#kept.delete(credentialId);
9834
+ }
9835
+ /** Apply an already-held roster; this never fetches credentials or writes it. */
9836
+ retain(identities) {
9837
+ const current = new Map(identities.map((identity) => [identity.credentialId, identity]));
9838
+ for (const [id, kept] of this.#kept) {
9839
+ const identity = current.get(id);
9840
+ if (!identity?.enabled || identity.state !== "active" || identity.credentialType !== kept.attempt.credentialType || identity.accountIdentity !== kept.attempt.expectedAccountIdentity)
9841
+ this.forget(id);
9842
+ }
9843
+ }
9844
+ /** A frozen, non-secret summary for a plugin's status display. */
9845
+ keptReceiptState() {
9846
+ let since = null;
9847
+ for (const [id, kept] of this.#kept) {
9848
+ if (!this.#usable(kept.attempt)) {
9849
+ this.forget(id);
9850
+ continue;
9851
+ }
9852
+ if (kept.since !== null)
9853
+ since = Math.min(since ?? kept.since, kept.since);
9854
+ }
9855
+ return Object.freeze({ active: since !== null, since });
9856
+ }
9857
+ #usable(attempt) {
9858
+ return attempt.expiresAtMs === null ? attempt.credentialType === "api_key" : attempt.expiresAtMs - this.#now() > KEPT_RECEIPT_MARGIN_MS;
9859
+ }
9860
+ /** Ask the vault while reachable; retain one validated receipt in memory only. */
9861
+ async authorize(identity, signal, routeId = "vault") {
9862
+ this.#check(signal);
9863
+ const { credentialId, credentialType, accountIdentity } = identity;
9864
+ let kept = this.#kept.get(credentialId);
9865
+ if (kept && (kept.attempt.credentialType !== credentialType || kept.attempt.expectedAccountIdentity !== accountIdentity)) {
9866
+ this.forget(credentialId);
9867
+ kept = void 0;
9868
+ }
9869
+ let token;
9870
+ try {
9871
+ token = await this.#token(signal);
9872
+ } catch (error) {
9873
+ this.#kept.clear();
9874
+ throw error;
9875
+ }
9876
+ if (this.#outage && kept) {
9877
+ this.#probe();
9878
+ return this.#serveKept(credentialId, kept, token, routeId);
9879
+ }
9880
+ try {
9881
+ const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
9882
+ this.#kept.set(credentialId, { attempt, routeId, since: null });
9883
+ return attempt;
9884
+ } catch (error) {
9885
+ this.#check(signal);
9886
+ if (classifyVaultFailure(error) !== "unreachable") {
9887
+ this.forget(credentialId);
9888
+ throw error;
9889
+ }
9890
+ return this.#serveKept(credentialId, kept, token, routeId, error);
9891
+ }
9892
+ }
9893
+ #serveKept(credentialId, kept, token, routeId, error = this.#outageError) {
9894
+ if (!kept || this.#kept.get(credentialId) !== kept || !this.#usable(kept.attempt)) {
9895
+ this.forget(credentialId);
9896
+ throw error;
9897
+ }
9898
+ if (kept.since === null)
9899
+ kept.since = this.#now();
9900
+ const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, "accessToken", { value: kept.attempt.accessToken, enumerable: false }));
9901
+ this.#provenance.set(attempt, token);
9902
+ this.#keptAttempts.set(attempt, routeId);
9903
+ return attempt;
9904
+ }
9905
+ /**
9906
+ * Fetch and validate a fresh receipt before retaining it. The vault assertion
9907
+ * (or the plugin's token parse) must agree with the roster when both exist.
9908
+ * With requireAssertion, an absent assertion also refuses rather than
9909
+ * treating the roster's expectation as proof of the served account.
9124
9910
  */
9125
- async authorize(identity, signal) {
9911
+ async #authorizeFresh(identity, token, signal) {
9126
9912
  if (!identity.credentialId)
9127
9913
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum dispatch requires a credential id");
9128
9914
  const { credentialId, credentialType, accountIdentity } = identity;
9129
9915
  if (this.#requireAssertion && accountIdentity === void 0)
9130
9916
  throw new ClaustrumConsumerError("identity-unasserted", "Claustrum dispatch requires a known account identity");
9131
- const token = await this.#token(signal);
9132
9917
  const served = await this.#call(() => this.#client.getScoped({
9133
9918
  credentialId,
9134
9919
  enrollmentToken: token,
@@ -9191,6 +9976,18 @@ var init_custody = __esm({
9191
9976
  const token = this.#provenance.get(attempt);
9192
9977
  if (!token)
9193
9978
  throw new ClaustrumConsumerError("no-receipt", "Claustrum failure report requires an original dispatch receipt");
9979
+ const keptRoute = this.#keptAttempts.get(attempt);
9980
+ if (keptRoute !== void 0) {
9981
+ this.forget(attempt.credentialId);
9982
+ this.#logger.debug("scoped 401 not reported", {
9983
+ routeId: keptRoute,
9984
+ reason: "kept-receipt"
9985
+ });
9986
+ return;
9987
+ }
9988
+ const kept = this.#kept.get(attempt.credentialId);
9989
+ if (kept && kept.attempt.recordVersion === attempt.recordVersion)
9990
+ this.forget(attempt.credentialId);
9194
9991
  const pending = this.#reports.get(attempt);
9195
9992
  if (pending)
9196
9993
  return pending;
@@ -9214,10 +10011,70 @@ var init_custody = __esm({
9214
10011
  throw error;
9215
10012
  }
9216
10013
  }
10014
+ /**
10015
+ * Watch this consumer's visible vault accounts instead of listing them on a
10016
+ * short timer. Opens one `watchScoped` on this custody's client and calls
10017
+ * `onView` when the host must run its discovery (see
10018
+ * `ClaustrumRosterWatchOptions`). A claustrum-client without `watchScoped`
10019
+ * (before 0.12.0) or a vault that answers `unknown_method` reports
10020
+ * `fallback` and opens nothing. A watch that closes before any notice was
10021
+ * never accepted: the client reads once to learn why, and the watch reports
10022
+ * `fallback` and tries one new watch after `WATCH_RETRY_MS`, never in a
10023
+ * loop. A watch that closes after notices is re-opened after
10024
+ * `RESUBSCRIBE_BACKOFF_MS`, doubling per close in a row. A lost transport
10025
+ * starts this custody's outage, exactly as an unreachable call does, and
10026
+ * the first notice of a watch ends it. Timers are unreferenced; `close()`
10027
+ * on the returned watch or on this custody stops it.
10028
+ *
10029
+ * The watch keeps no history, so the host still lists on a slow timer while
10030
+ * the mode is `watching`: every `SAFETY_POLL_MS` (five minutes). In any
10031
+ * other mode the host keeps its usual list timer.
10032
+ */
10033
+ watchRoster(options) {
10034
+ this.#check();
10035
+ const watch = new ScopedRosterWatch({
10036
+ client: this.#client,
10037
+ enrollmentToken: () => this.#token(),
10038
+ view: options.view ?? (() => this.#discoveredView),
10039
+ discover: async (view) => {
10040
+ await options.onView(view);
10041
+ },
10042
+ onRefused: (error) => {
10043
+ this.listFailed(error);
10044
+ options.onRefused?.(error);
10045
+ },
10046
+ onTransportLost: () => this.transportLost(),
10047
+ onReachable: () => this.reachable(),
10048
+ onError: options.onError,
10049
+ onMode: options.onMode,
10050
+ logger: this.#logger,
10051
+ now: this.#now,
10052
+ setTimeoutImpl: this.#setTimeout,
10053
+ clearTimeoutImpl: this.#clearTimeout
10054
+ });
10055
+ this.#watches.add(watch);
10056
+ watch.start();
10057
+ return {
10058
+ get mode() {
10059
+ return watch.mode;
10060
+ },
10061
+ close: () => {
10062
+ this.#watches.delete(watch);
10063
+ watch.stop();
10064
+ }
10065
+ };
10066
+ }
9217
10067
  close() {
9218
10068
  if (this.#closed)
9219
10069
  return;
9220
10070
  this.#closed = true;
10071
+ if (this.#probeTimer)
10072
+ this.#clearTimeout(this.#probeTimer);
10073
+ this.#probeTimer = void 0;
10074
+ for (const watch of this.#watches)
10075
+ watch.stop();
10076
+ this.#watches.clear();
10077
+ this.#kept.clear();
9221
10078
  this.#client.close();
9222
10079
  }
9223
10080
  };
@@ -9668,6 +10525,7 @@ var init_consumer = __esm({
9668
10525
  init_errors2();
9669
10526
  init_insula();
9670
10527
  init_roster();
10528
+ init_watch();
9671
10529
  ClaustrumConsumer = class {
9672
10530
  #options;
9673
10531
  #shutdown = new AbortController();
@@ -9684,6 +10542,11 @@ var init_consumer = __esm({
9684
10542
  #timer;
9685
10543
  #started = false;
9686
10544
  #insula;
10545
+ #vaultWatch;
10546
+ #releaseInsulaWatch;
10547
+ #insulaSkips = /* @__PURE__ */ new Map();
10548
+ /** When this instance last completed a discovery, by `now`. */
10549
+ #discoveredAt;
9687
10550
  constructor(options) {
9688
10551
  this.#options = options;
9689
10552
  this.#logger = options.logger ?? createLogger2("claustrum");
@@ -9741,7 +10604,9 @@ var init_consumer = __esm({
9741
10604
  parseIdentity: this.#options.parseIdentity,
9742
10605
  requireAssertion: this.#options.requireAssertion,
9743
10606
  now: this.#options.now,
9744
- logger: this.#logger
10607
+ logger: this.#logger,
10608
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10609
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
9745
10610
  });
9746
10611
  if (this.#options.insula && client.insula) {
9747
10612
  this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
@@ -9770,6 +10635,26 @@ var init_consumer = __esm({
9770
10635
  const latest2 = this.#grantReach;
9771
10636
  return latest2 && this.#roster?.view === latest2.view ? latest2.reach : void 0;
9772
10637
  }
10638
+ /** How this consumer currently learns about changes, without I/O. */
10639
+ watchState() {
10640
+ return Object.freeze({
10641
+ vault: this.#vaultWatch?.mode ?? "polling",
10642
+ ...this.#options.insula && {
10643
+ insula: this.#insula?.source.watchMode() ?? "polling"
10644
+ }
10645
+ });
10646
+ }
10647
+ /** Close the watches with the connection they belong to. */
10648
+ #stopWatch() {
10649
+ this.#vaultWatch?.close();
10650
+ this.#vaultWatch = void 0;
10651
+ this.#releaseInsulaWatch?.();
10652
+ this.#releaseInsulaWatch = void 0;
10653
+ }
10654
+ /** Whether any account is using an in-memory outage receipt, without I/O. */
10655
+ keptReceiptState() {
10656
+ return this.#custody?.keptReceiptState() ?? Object.freeze({ active: false, since: null });
10657
+ }
9773
10658
  /** Rows for `/routing`, from the last committed roster. */
9774
10659
  routingRows() {
9775
10660
  return vaultRoutingRows(this.#roster);
@@ -9782,6 +10667,7 @@ var init_consumer = __esm({
9782
10667
  if (!await this.#active()) {
9783
10668
  this.#roster = void 0;
9784
10669
  this.#grantReach = void 0;
10670
+ this.#stopWatch();
9785
10671
  this.#custody?.close();
9786
10672
  this.#custody = void 0;
9787
10673
  this.#insula?.release();
@@ -9810,16 +10696,28 @@ var init_consumer = __esm({
9810
10696
  this.#assertOpen();
9811
10697
  const changed = roster?.view !== this.#roster?.view;
9812
10698
  this.#roster = roster;
10699
+ custody.retain(roster?.rows ?? []);
9813
10700
  if (discovered && roster?.view !== void 0)
9814
10701
  this.#grantReach = discovered.grantReach ? { view: roster.view, reach: discovered.grantReach } : void 0;
9815
10702
  if (roster && changed)
9816
10703
  this.#options.onRoster?.(roster);
10704
+ this.#discoveredAt = (this.#options.now ?? Date.now)();
9817
10705
  return roster;
9818
10706
  })().finally(() => {
9819
10707
  this.#refreshing = void 0;
9820
10708
  });
9821
10709
  return this.#refreshing;
9822
10710
  }
10711
+ /**
10712
+ * Poll in the background and open the vault and insula watches. Until the
10713
+ * vault watch is accepted, and whenever it is unavailable, every tick lists
10714
+ * the vault exactly as before watches existed. While it is open a tick
10715
+ * lists only when five minutes have passed since the last discovery, since
10716
+ * the watch keeps no history; it still checks `isCustodyActive`, so a switch
10717
+ * to local mode closes the connection as quickly as before. Insula is
10718
+ * polled on the tick only while its own watch is not open. A host not in
10719
+ * vault mode makes no request.
10720
+ */
9823
10721
  start() {
9824
10722
  if (this.#started)
9825
10723
  return;
@@ -9827,8 +10725,10 @@ var init_consumer = __esm({
9827
10725
  this.#started = true;
9828
10726
  const tick = async () => {
9829
10727
  try {
9830
- await this.refresh();
10728
+ if (await this.#listDue())
10729
+ await this.refresh();
9831
10730
  await this.refreshInsulaQuota();
10731
+ this.#openWatch();
9832
10732
  } catch (error) {
9833
10733
  if (!this.#shutdown.signal.aborted)
9834
10734
  this.#options.onError?.(error);
@@ -9846,6 +10746,50 @@ var init_consumer = __esm({
9846
10746
  };
9847
10747
  void tick();
9848
10748
  }
10749
+ /** Whether a background tick must list the vault now. */
10750
+ async #listDue() {
10751
+ if (this.#vaultWatch?.mode !== "watching")
10752
+ return true;
10753
+ const now = (this.#options.now ?? Date.now)();
10754
+ if (this.#discoveredAt === void 0 || now - this.#discoveredAt >= SAFETY_POLL_MS)
10755
+ return true;
10756
+ return !await this.#active();
10757
+ }
10758
+ /**
10759
+ * Open the vault and insula watches once a vault connection exists. Only
10760
+ * reached in vault mode: a host in local mode never connects.
10761
+ */
10762
+ #openWatch() {
10763
+ const custody = this.#custody;
10764
+ if (this.#shutdown.signal.aborted || !custody)
10765
+ return;
10766
+ this.#vaultWatch ??= custody.watchRoster({
10767
+ view: () => this.#roster?.view,
10768
+ // The existing discovery, so a watched change commits the roster and
10769
+ // re-applies it to kept receipts exactly as a poll does. A refresh
10770
+ // already in flight may have listed before the change was announced,
10771
+ // so wait for it and list again.
10772
+ onView: async () => {
10773
+ while (this.#refreshing)
10774
+ await this.#refreshing.catch(() => {
10775
+ });
10776
+ await this.refresh();
10777
+ },
10778
+ // Custody has dropped kept receipts, as a poll meeting the same
10779
+ // refusal from list_scoped would.
10780
+ onRefused: (error) => this.#options.onError?.(error),
10781
+ onError: (error) => {
10782
+ if (!this.#shutdown.signal.aborted)
10783
+ this.#options.onError?.(error);
10784
+ }
10785
+ });
10786
+ if (this.#options.insula && this.#insula && !this.#releaseInsulaWatch)
10787
+ this.#releaseInsulaWatch = this.#insula.source.watch({
10788
+ provider: this.#options.insula.provider,
10789
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10790
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
10791
+ });
10792
+ }
9849
10793
  /**
9850
10794
  * Fetch on a background tick, at most once per minute across projects with
9851
10795
  * the same daemon and enrollment token path. Admission must use the cache
@@ -9894,6 +10838,41 @@ var init_consumer = __esm({
9894
10838
  return void 0;
9895
10839
  }
9896
10840
  }
10841
+ /** Cache-only background lookup, preserving the reason a route has no reading. */
10842
+ async lookupInsulaQuotaForRoute(routeId) {
10843
+ const options = this.#options.insula;
10844
+ if (!options || this.#shutdown.signal.aborted || !await this.#active())
10845
+ return { miss: "unreachable" };
10846
+ try {
10847
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
10848
+ const roster = await readVaultRoster(this.#options.rosterPath);
10849
+ const account = roster?.rows.find((row) => row.routeId === routeId)?.accountIdentity;
10850
+ if (!account || !this.#insula)
10851
+ return { miss: "unreachable" };
10852
+ const result = this.#insula.source.lookup(options.provider, account, (this.#options.now ?? Date.now)());
10853
+ const reading = result.reading && options.normalize(result.reading.entry, result.reading.context);
10854
+ if (result.miss)
10855
+ return { miss: result.miss, ...reading !== void 0 && { reading } };
10856
+ return reading === void 0 ? { miss: "unreachable" } : { reading };
10857
+ } catch {
10858
+ return { miss: "unreachable" };
10859
+ }
10860
+ }
10861
+ /** Skip the fallback poll while insula is cold or its upstream fetch failed. */
10862
+ async pollInsulaQuotaForRoute(routeId, fallback) {
10863
+ const result = await this.lookupInsulaQuotaForRoute(routeId);
10864
+ if (result.miss === "cold" || result.miss === "upstream-failed") {
10865
+ if (this.#insulaSkips.get(routeId) !== result.miss) {
10866
+ this.#insulaSkips.set(routeId, result.miss);
10867
+ this.#logger.warn("skipped insula provider poll", {
10868
+ reason: result.miss
10869
+ });
10870
+ }
10871
+ return void 0;
10872
+ }
10873
+ this.#insulaSkips.delete(routeId);
10874
+ return result.miss ? fallback() : result.reading;
10875
+ }
9897
10876
  #normalizeInsulaQuota(accountIdentity) {
9898
10877
  if (!this.#options.insula || !accountIdentity)
9899
10878
  return void 0;
@@ -9908,16 +10887,28 @@ var init_consumer = __esm({
9908
10887
  async authorize(routeId, signal) {
9909
10888
  this.#assertOpen(signal);
9910
10889
  const roster = this.#roster ?? await this.#wait(this.refresh(), signal);
9911
- if (!roster || !await this.#active())
10890
+ if (!roster || !await this.#active()) {
10891
+ this.#custody?.close();
10892
+ this.#custody = void 0;
10893
+ this.#stopWatch();
10894
+ this.#insula?.release();
10895
+ this.#insula = void 0;
9912
10896
  throw new ClaustrumConsumerError("not-active", "Claustrum scoped custody is not active");
10897
+ }
9913
10898
  const current = await readVaultRoster(this.#options.rosterPath);
9914
10899
  this.#assertOpen(signal);
9915
10900
  const observed = roster.rows.find((row) => row.routeId === routeId);
9916
10901
  const configured = current?.rows.find((row) => row.routeId === routeId);
9917
- if (configured && !configured.enabled)
10902
+ if (configured && !configured.enabled) {
10903
+ if (observed)
10904
+ this.#custody?.forget(observed.credentialId);
9918
10905
  throw new ClaustrumConsumerError("route-declined", "Claustrum route is disabled");
9919
- if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity)
10906
+ }
10907
+ if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity || configured.credentialType !== observed.credentialType) {
10908
+ if (observed)
10909
+ this.#custody?.forget(observed.credentialId);
9920
10910
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum route is disabled, removed or changed");
10911
+ }
9921
10912
  const custody = await this.#wait(this.#getCustody(), signal);
9922
10913
  const combined = combineAbortSignals([
9923
10914
  this.#shutdown.signal,
@@ -9930,7 +10921,7 @@ var init_consumer = __esm({
9930
10921
  ...configured.accountIdentity !== void 0 && {
9931
10922
  accountIdentity: configured.accountIdentity
9932
10923
  }
9933
- }, combined.signal);
10924
+ }, combined.signal, routeId);
9934
10925
  } finally {
9935
10926
  combined.dispose();
9936
10927
  }
@@ -9953,6 +10944,10 @@ var init_consumer = __esm({
9953
10944
  const signal = options.signal;
9954
10945
  let served = await this.authorize(routeId, signal);
9955
10946
  let response = await dispatch(served, signal);
10947
+ if (response.status === 401 && served.fromKeptReceipt) {
10948
+ await this.reportFailure(served, 401, options.reporterSource ?? "direct");
10949
+ return response;
10950
+ }
9956
10951
  if (response.status === 401 && !signal?.aborted) {
9957
10952
  let current;
9958
10953
  try {
@@ -9980,6 +10975,7 @@ var init_consumer = __esm({
9980
10975
  this.#assertOpen();
9981
10976
  await declineVaultRoute(this.#options.rosterPath, routeId);
9982
10977
  this.#roster = await readVaultRoster(this.#options.rosterPath);
10978
+ this.#custody?.retain(this.#roster?.rows ?? []);
9983
10979
  }
9984
10980
  async accept(routeId) {
9985
10981
  this.#assertOpen();
@@ -10035,6 +11031,7 @@ var init_consumer = __esm({
10035
11031
  if (this.#timer)
10036
11032
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
10037
11033
  this.#timer = void 0;
11034
+ this.#stopWatch();
10038
11035
  this.#custody?.close();
10039
11036
  this.#insula?.release();
10040
11037
  this.#insula = void 0;
@@ -10049,21 +11046,31 @@ var init_consumer = __esm({
10049
11046
  var claustrum_exports = {};
10050
11047
  __export(claustrum_exports, {
10051
11048
  CUSTODY_PLACEHOLDER_PREFIX: () => CUSTODY_PLACEHOLDER_PREFIX,
11049
+ ChangeNoticeReader: () => ChangeNoticeReader,
10052
11050
  ClaustrumConsumer: () => ClaustrumConsumer,
10053
11051
  ClaustrumConsumerError: () => ClaustrumConsumerError,
10054
- ClaustrumCredentialError: () => ClaustrumCredentialError3,
11052
+ ClaustrumCredentialError: () => ClaustrumCredentialError4,
10055
11053
  ClaustrumEnrollmentManager: () => ClaustrumEnrollmentManager,
10056
11054
  ClaustrumScopedCustody: () => ClaustrumScopedCustody,
11055
+ ClaustrumUnreachableError: () => ClaustrumUnreachableError,
10057
11056
  DEFAULT_ROUTE_PREFIX: () => DEFAULT_ROUTE_PREFIX,
11057
+ KEPT_RECEIPT_MARGIN_MS: () => KEPT_RECEIPT_MARGIN_MS,
11058
+ RESUBSCRIBE_BACKOFF_MS: () => RESUBSCRIBE_BACKOFF_MS,
10058
11059
  RETRYABLE_ENROLLMENT_CODES: () => RETRYABLE_ENROLLMENT_CODES,
11060
+ SAFETY_POLL_MS: () => SAFETY_POLL_MS,
10059
11061
  SERVING_MARGIN_MS: () => SERVING_MARGIN_MS,
11062
+ ScopedRosterWatch: () => ScopedRosterWatch,
10060
11063
  TERMINAL_ENROLLMENT_CODES: () => TERMINAL_ENROLLMENT_CODES,
11064
+ VAULT_FAILURE_CLASSES: () => VAULT_FAILURE_CLASSES,
11065
+ WATCH_RETRY_MS: () => WATCH_RETRY_MS,
10061
11066
  acceptAccount: () => acceptAccount,
10062
11067
  acceptVaultRoute: () => acceptVaultRoute,
11068
+ acquireInsulaQuotaSource: () => acquireInsulaQuotaSource,
10063
11069
  assertHostSlotMatchesMode: () => assertHostSlotMatchesMode,
10064
11070
  assertNotCustodyPlaceholder: () => assertNotCustodyPlaceholder,
10065
11071
  classifyEnrollmentError: () => classifyEnrollmentError,
10066
11072
  classifyHostSlot: () => classifyHostSlot,
11073
+ classifyVaultFailure: () => classifyVaultFailure,
10067
11074
  connectClaustrumEnrollmentClient: () => connectClaustrumEnrollmentClient,
10068
11075
  connectClaustrumScopedClient: () => connectClaustrumScopedClient,
10069
11076
  custodyPlaceholder: () => custodyPlaceholder,
@@ -10093,7 +11100,7 @@ __export(claustrum_exports, {
10093
11100
  vaultRoutingRows: () => vaultRoutingRows
10094
11101
  });
10095
11102
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
10096
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
11103
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
10097
11104
  async function connectClaustrumScopedClient(options) {
10098
11105
  const client = await ClaustrumClient.connect(options);
10099
11106
  return Object.assign(client, { insula: insulaUsageTransport(options) });
@@ -10102,13 +11109,16 @@ var init_claustrum = __esm({
10102
11109
  "../core/dist/common-auth-embedded/claustrum/index.js"() {
10103
11110
  "use strict";
10104
11111
  init_insula();
11112
+ init_availability();
10105
11113
  init_consumer();
10106
11114
  init_custody();
10107
11115
  init_enrollment();
10108
11116
  init_errors2();
10109
11117
  init_host_slot();
11118
+ init_insula();
10110
11119
  init_interlock();
10111
11120
  init_roster();
11121
+ init_watch();
10112
11122
  }
10113
11123
  });
10114
11124
 
@@ -16751,6 +17761,7 @@ var ANTIGRAVITY_SCOPES = [
16751
17761
  var ANTIGRAVITY_REDIRECT_URI = "http://localhost:51121/oauth-callback";
16752
17762
  var ANTIGRAVITY_ENDPOINT_DAILY = "https://daily-cloudcode-pa.googleapis.com";
16753
17763
  var ANTIGRAVITY_ENDPOINT_PROD = "https://cloudcode-pa.googleapis.com";
17764
+ var ANTIGRAVITY_QUOTA_ENDPOINT = ANTIGRAVITY_ENDPOINT_DAILY;
16754
17765
  var ANTIGRAVITY_ENDPOINT_FALLBACKS = [
16755
17766
  ANTIGRAVITY_ENDPOINT_DAILY,
16756
17767
  ANTIGRAVITY_ENDPOINT_PROD
@@ -18169,19 +19180,24 @@ async function replaceWindowsFile2(from, to, options = {}) {
18169
19180
  to = resolve7(to);
18170
19181
  const now = options.now ?? (() => performance.now());
18171
19182
  const start = now();
18172
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
19183
+ const leaseDeadline = options.deadline ?? Infinity;
19184
+ let retryDeadline;
18173
19185
  const delays = [0, 10, 20, 40, 80, 100];
18174
19186
  let original;
18175
19187
  let attempts2 = 0;
18176
19188
  for (const delay3 of delays) {
19189
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
18177
19190
  if (now() >= deadline)
18178
19191
  break;
18179
19192
  if (delay3)
18180
19193
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
18181
19194
  if (now() >= deadline)
18182
19195
  break;
19196
+ const fenceStart = now();
18183
19197
  await options.beforeRename?.();
18184
- if (now() >= deadline)
19198
+ if (retryDeadline !== void 0)
19199
+ retryDeadline += now() - fenceStart;
19200
+ if (now() >= leaseDeadline)
18185
19201
  break;
18186
19202
  attempts2++;
18187
19203
  try {
@@ -18193,6 +19209,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
18193
19209
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
18194
19210
  if (!candidate)
18195
19211
  break;
19212
+ retryDeadline ??= now() + 500;
18196
19213
  }
18197
19214
  }
18198
19215
  const error = new PrivateFileError2(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -19800,7 +20817,7 @@ async function fetchLegacyModelsFallback(options) {
19800
20817
  const modelsResponse = await fetchAvailableModels({
19801
20818
  accessToken: options.accessToken,
19802
20819
  projectId: options.projectId,
19803
- endpoints: ANTIGRAVITY_ENDPOINT_FALLBACKS,
20820
+ endpoints: [ANTIGRAVITY_QUOTA_ENDPOINT],
19804
20821
  userAgent: buildAntigravityHarnessUserAgent(),
19805
20822
  timeoutMs: 1e4,
19806
20823
  ...options.fetchVia ? { fetchVia: options.fetchVia } : {}
@@ -19829,7 +20846,7 @@ async function fetchQuotaPayloads(options) {
19829
20846
  accessToken,
19830
20847
  managedProjectId,
19831
20848
  projectId,
19832
- endpoints: ANTIGRAVITY_ENDPOINT_FALLBACKS,
20849
+ endpoints: [ANTIGRAVITY_QUOTA_ENDPOINT],
19833
20850
  userAgent: buildAntigravityHarnessUserAgent(),
19834
20851
  timeoutMs: 1e4,
19835
20852
  ...fetchVia ? { fetchVia } : {}
@@ -19934,6 +20951,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
19934
20951
  }),
19935
20952
  signal
19936
20953
  );
20954
+ if (payloads.quota.error) throw new Error(payloads.quota.error);
19937
20955
  return {
19938
20956
  index,
19939
20957
  email: account.email,
@@ -19989,6 +21007,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
19989
21007
  logger: log7
19990
21008
  });
19991
21009
  quotaResult = payloads.quota;
21010
+ if (quotaResult.error) throw new Error(quotaResult.error);
19992
21011
  fellBackToLegacy = payloads.fellBackToLegacy;
19993
21012
  for (const [family, groupQuota] of Object.entries(quotaResult.groups)) {
19994
21013
  const remainingPercent = (groupQuota.remainingFraction ?? 0) * 100;
@@ -20599,7 +21618,7 @@ import { createHash as createHash9, randomBytes as randomBytes3, randomUUID as r
20599
21618
  import { constants as fsConstants2 } from "node:fs";
20600
21619
  import { chmod as chmod3, mkdir as mkdir12, open as open10, readFile as readFile9, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
20601
21620
  import { basename as basename4, dirname as dirname16, extname as extname2, isAbsolute as isAbsolute3, join as join10, resolve as resolve10 } from "node:path";
20602
- import { ClaustrumCredentialError as ClaustrumCredentialError4, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
21621
+ import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
20603
21622
 
20604
21623
  // src/common-auth-embedded/fs/lock-constants.js
20605
21624
  var WRITER_LOCK_CONSTANTS2 = Object.freeze({
@@ -21281,7 +22300,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
21281
22300
  "pending_queue_full"
21282
22301
  ]);
21283
22302
  function classifyEnrollmentError2(error) {
21284
- if (!(error instanceof ClaustrumCredentialError4))
22303
+ if (!(error instanceof ClaustrumCredentialError5))
21285
22304
  return void 0;
21286
22305
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
21287
22306
  return { code: error.code, disposition: "terminal" };