@cortexkit/opencode-antigravity-auth 3.0.7 → 3.0.8

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 (118) hide show
  1. package/dist/cli.js +1001 -63
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +112 -30
  4. package/dist/index.js +1270 -219
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +154 -48
  7. package/dist/server.js +1190 -120
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  11. package/dist/src/common-auth-embedded/claustrum/availability.js +106 -0
  12. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +31 -1
  13. package/dist/src/common-auth-embedded/claustrum/consumer.js +114 -5
  14. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +106 -14
  15. package/dist/src/common-auth-embedded/claustrum/custody.js +294 -16
  16. package/dist/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  17. package/dist/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  18. package/dist/src/common-auth-embedded/claustrum/index.js +4 -1
  19. package/dist/src/common-auth-embedded/claustrum/insula.d.ts +48 -0
  20. package/dist/src/common-auth-embedded/claustrum/insula.js +286 -21
  21. package/dist/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  22. package/dist/src/common-auth-embedded/claustrum/watch.js +254 -0
  23. package/dist/src/common-auth-embedded/fs/private-files.js +10 -2
  24. package/dist/src/common-auth-embedded/quota/format.d.ts +3 -0
  25. package/dist/src/common-auth-embedded/quota/format.js +69 -1
  26. package/dist/src/common-auth-embedded/quota/index.d.ts +1 -1
  27. package/dist/src/common-auth-embedded/quota/projection.d.ts +16 -0
  28. package/dist/src/common-auth-embedded/source-output.json +81 -49
  29. package/dist/src/ga/server/index.d.ts +2 -0
  30. package/dist/src/ga/server/index.d.ts.map +1 -1
  31. package/dist/src/ga/server/index.js +14 -1
  32. package/dist/src/ga/server/index.js.map +1 -1
  33. package/dist/src/plugin/auth-loader.d.ts +2 -1
  34. package/dist/src/plugin/auth-loader.d.ts.map +1 -1
  35. package/dist/src/plugin/auth-loader.js +5 -4
  36. package/dist/src/plugin/auth-loader.js.map +1 -1
  37. package/dist/src/plugin/fetch-interceptor.d.ts +2 -1
  38. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  39. package/dist/src/plugin/fetch-interceptor.js +8 -6
  40. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  41. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  42. package/dist/src/plugin/ga-location-services.js +3 -0
  43. package/dist/src/plugin/ga-location-services.js.map +1 -1
  44. package/dist/src/plugin/shared/after-handoff.d.ts +14 -0
  45. package/dist/src/plugin/shared/after-handoff.d.ts.map +1 -0
  46. package/dist/src/plugin/shared/after-handoff.js +89 -0
  47. package/dist/src/plugin/shared/after-handoff.js.map +1 -0
  48. package/dist/src/plugin/shared/request-services.d.ts +8 -2
  49. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  50. package/dist/src/plugin/shared/request-services.js +57 -36
  51. package/dist/src/plugin/shared/request-services.js.map +1 -1
  52. package/dist/src/plugin/shared/vault-request-credentials.d.ts +2 -2
  53. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  54. package/dist/src/plugin/shared/vault-request-credentials.js +14 -1
  55. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  56. package/dist/src/plugin/vault-custody.d.ts +2 -0
  57. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  58. package/dist/src/plugin/vault-custody.js +3 -0
  59. package/dist/src/plugin/vault-custody.js.map +1 -1
  60. package/dist/src/tui.d.ts.map +1 -1
  61. package/dist/src/tui.js +82 -66
  62. package/dist/src/tui.js.map +1 -1
  63. package/dist/tui-build-map.json +27 -27
  64. package/dist/tui-ga-build-map.json +5 -5
  65. package/dist/types/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  66. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +31 -1
  67. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +106 -14
  68. package/dist/types/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  69. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  70. package/dist/types/src/common-auth-embedded/claustrum/insula.d.ts +48 -0
  71. package/dist/types/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  72. package/dist/types/src/common-auth-embedded/quota/format.d.ts +3 -0
  73. package/dist/types/src/common-auth-embedded/quota/index.d.ts +1 -1
  74. package/dist/types/src/common-auth-embedded/quota/projection.d.ts +16 -0
  75. package/dist/types/src/ga/server/index.d.ts +2 -0
  76. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  77. package/dist/types/src/plugin/auth-loader.d.ts +2 -1
  78. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  79. package/dist/types/src/plugin/fetch-interceptor.d.ts +2 -1
  80. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  81. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  82. package/dist/types/src/plugin/shared/after-handoff.d.ts +14 -0
  83. package/dist/types/src/plugin/shared/after-handoff.d.ts.map +1 -0
  84. package/dist/types/src/plugin/shared/request-services.d.ts +8 -2
  85. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  86. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +2 -2
  87. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  88. package/dist/types/src/plugin/vault-custody.d.ts +2 -0
  89. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  90. package/package.json +4 -4
  91. package/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  92. package/src/common-auth-embedded/claustrum/availability.js +106 -0
  93. package/src/common-auth-embedded/claustrum/consumer.d.ts +31 -1
  94. package/src/common-auth-embedded/claustrum/consumer.js +114 -5
  95. package/src/common-auth-embedded/claustrum/custody.d.ts +106 -14
  96. package/src/common-auth-embedded/claustrum/custody.js +294 -16
  97. package/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  98. package/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  99. package/src/common-auth-embedded/claustrum/index.js +4 -1
  100. package/src/common-auth-embedded/claustrum/insula.d.ts +48 -0
  101. package/src/common-auth-embedded/claustrum/insula.js +286 -21
  102. package/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  103. package/src/common-auth-embedded/claustrum/watch.js +254 -0
  104. package/src/common-auth-embedded/fs/private-files.js +10 -2
  105. package/src/common-auth-embedded/quota/format.d.ts +3 -0
  106. package/src/common-auth-embedded/quota/format.js +69 -1
  107. package/src/common-auth-embedded/quota/index.d.ts +1 -1
  108. package/src/common-auth-embedded/quota/projection.d.ts +16 -0
  109. package/src/common-auth-embedded/source-output.json +81 -49
  110. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +10 -2
  111. package/src/tui-compiled/common-auth-embedded/quota/format.js +69 -1
  112. package/src/tui-compiled/tui.js +123 -97
  113. package/src/tui-ga-compiled/shared/aef2402f8fc342f0-format.js +69 -1
  114. package/src/tui-ga-raw/shared/aef2402f8fc342f0-format.js +69 -1
  115. package/src/tui-raw/common-auth-embedded/fs/private-files.js +10 -2
  116. package/src/tui-raw/common-auth-embedded/quota/format.js +69 -1
  117. package/src/tui-raw/tui.tsx +126 -107
  118. 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"), {
@@ -8012,6 +8054,326 @@ var init_auth_menu = __esm({
8012
8054
  }
8013
8055
  });
8014
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
+
8015
8377
  // ../core/dist/common-auth-embedded/claustrum/insula.js
8016
8378
  import { resolve as resolve4 } from "node:path";
8017
8379
  import { storeIdentity } from "@cortexkit/claustrum-client";
@@ -8050,12 +8412,95 @@ function insulaUsageTransport(options) {
8050
8412
  clearTimeout(timer);
8051
8413
  client?.close();
8052
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 open12 = (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([open12, 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
+ };
8053
8479
  }
8054
8480
  };
8055
8481
  }
8056
8482
  function record2(value) {
8057
8483
  return typeof value === "object" && value !== null && !Array.isArray(value);
8058
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
+ }
8059
8504
  function acquireInsulaQuotaSource(transport, tokenPath) {
8060
8505
  const key = JSON.stringify([
8061
8506
  resolve4(transport.connectionFile),
@@ -8083,6 +8528,8 @@ var MINUTE, MAX_AGE, sources, attempts, InsulaQuotaSource;
8083
8528
  var init_insula = __esm({
8084
8529
  "../core/dist/common-auth-embedded/claustrum/insula.js"() {
8085
8530
  "use strict";
8531
+ init_availability();
8532
+ init_watch();
8086
8533
  MINUTE = 6e4;
8087
8534
  MAX_AGE = 4 * MINUTE;
8088
8535
  sources = /* @__PURE__ */ new Map();
@@ -8091,14 +8538,52 @@ var init_insula = __esm({
8091
8538
  transport;
8092
8539
  key;
8093
8540
  #entries = [];
8094
- #pending;
8541
+ /** Every usage.get, polled or watch-driven, shares this one slot. */
8542
+ #reads = new CoalescedRead(async () => {
8543
+ try {
8544
+ const reply = await this.transport.getUsage();
8545
+ if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== void 0)
8546
+ throw new Error("unavailable insula usage");
8547
+ this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
8548
+ } catch {
8549
+ this.#entries = [];
8550
+ }
8551
+ }, () => {
8552
+ });
8553
+ #reader = new ChangeNoticeReader();
8554
+ #mode = "polling";
8555
+ #watchers = 0;
8556
+ /**
8557
+ * How many registered watchers read every provider. Watchers limited to one
8558
+ * provider are counted per provider in `#providers` instead.
8559
+ */
8560
+ #everyProvider = 0;
8561
+ #providers = /* @__PURE__ */ new Map();
8562
+ #watch;
8563
+ #timer;
8564
+ #timers = {};
8565
+ /**
8566
+ * How many accepted watches in a row have closed; each one doubles the wait
8567
+ * before the next re-subscribe. Reset once a watch brings a second notice.
8568
+ */
8569
+ #closes = 0;
8095
8570
  constructor(transport, key) {
8096
8571
  this.transport = transport;
8097
8572
  this.key = key;
8098
8573
  }
8574
+ /**
8575
+ * The background poll: at most one usage.get per minute per daemon and
8576
+ * enrollment token. While a watch is open it reads nothing, because insula's
8577
+ * notices announce every new reading. If insula stops announcing an account,
8578
+ * that account's last entry grows older than the freshness limit `current()`
8579
+ * applies, `current()` returns nothing for it, and the plugin falls back to
8580
+ * its own provider poll for that account.
8581
+ */
8099
8582
  refresh(now) {
8100
- if (this.#pending)
8101
- return this.#pending;
8583
+ if (this.#reads.running)
8584
+ return this.#reads.running;
8585
+ if (this.#mode === "watching")
8586
+ return Promise.resolve();
8102
8587
  for (const [key, time] of attempts) {
8103
8588
  if (now - time >= MINUTE)
8104
8589
  attempts.delete(key);
@@ -8107,19 +8592,119 @@ var init_insula = __esm({
8107
8592
  if (lastAttempt !== void 0 && now - lastAttempt < MINUTE)
8108
8593
  return Promise.resolve();
8109
8594
  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 = [];
8595
+ return this.#reads.request();
8596
+ }
8597
+ /** How this source currently learns about usage changes, for logs. */
8598
+ watchMode() {
8599
+ return this.#mode;
8600
+ }
8601
+ /**
8602
+ * Hold a `usage.watch` open while any watcher wants it, and re-read
8603
+ * usage.get when a notice says something changed. Watchers of one source
8604
+ * share one watch, since insula admits only 64 per process. Returns the
8605
+ * release; the last release closes the watch.
8606
+ */
8607
+ watch(options = {}) {
8608
+ this.#watchers++;
8609
+ const provider2 = options.provider;
8610
+ if (provider2 === void 0)
8611
+ this.#everyProvider++;
8612
+ else
8613
+ this.#providers.set(provider2, (this.#providers.get(provider2) ?? 0) + 1);
8614
+ if (this.#watchers === 1) {
8615
+ this.#timers = options;
8616
+ this.#open();
8617
+ }
8618
+ let released = false;
8619
+ return () => {
8620
+ if (released)
8621
+ return;
8622
+ released = true;
8623
+ if (provider2 === void 0)
8624
+ this.#everyProvider--;
8625
+ else {
8626
+ const left = (this.#providers.get(provider2) ?? 1) - 1;
8627
+ if (left > 0)
8628
+ this.#providers.set(provider2, left);
8629
+ else
8630
+ this.#providers.delete(provider2);
8118
8631
  }
8119
- })().finally(() => {
8120
- this.#pending = void 0;
8121
- });
8122
- return this.#pending;
8632
+ if (--this.#watchers === 0)
8633
+ this.#stopWatch();
8634
+ };
8635
+ }
8636
+ #stopWatch() {
8637
+ if (this.#timer)
8638
+ (this.#timers.clearTimeoutImpl ?? clearTimeout)(this.#timer);
8639
+ this.#timer = void 0;
8640
+ const watch = this.#watch;
8641
+ this.#watch = void 0;
8642
+ watch?.handle?.stop();
8643
+ this.#mode = "polling";
8644
+ }
8645
+ #later(delay3) {
8646
+ this.#timer = (this.#timers.setTimeoutImpl ?? setTimeout)(() => {
8647
+ this.#timer = void 0;
8648
+ if (this.#watchers > 0 && !this.#watch)
8649
+ this.#open();
8650
+ }, delay3);
8651
+ this.#timer.unref?.();
8652
+ }
8653
+ #open() {
8654
+ const watchUsage = this.transport.watchUsage;
8655
+ if (!watchUsage) {
8656
+ this.#mode = "fallback";
8657
+ return;
8658
+ }
8659
+ this.#mode = "polling";
8660
+ this.#reader.restart();
8661
+ const watch = { notices: 0 };
8662
+ this.#watch = watch;
8663
+ let handle;
8664
+ try {
8665
+ handle = watchUsage.call(this.transport, (body) => this.#notice(watch, body));
8666
+ } catch (error) {
8667
+ this.#closed(watch, error);
8668
+ return;
8669
+ }
8670
+ watch.handle = handle;
8671
+ handle.closed.then(() => this.#closed(watch, void 0), (error) => this.#closed(watch, error));
8672
+ }
8673
+ #notice(watch, body) {
8674
+ if (this.#watch !== watch)
8675
+ return;
8676
+ watch.notices++;
8677
+ if (watch.notices === 1)
8678
+ this.#mode = "watching";
8679
+ if (watch.notices === 2)
8680
+ this.#closes = 0;
8681
+ const notice = decodeUsageNotice(body);
8682
+ if (!notice)
8683
+ this.#reader.restart();
8684
+ const continuous = notice ? this.#reader.continuous(notice) : false;
8685
+ if (!continuous || notice?.provider === void 0 || this.#everyProvider > 0 || this.#providers.has(notice.provider))
8686
+ void this.#reads.request();
8687
+ }
8688
+ #closed(watch, error) {
8689
+ if (this.#watch !== watch)
8690
+ return;
8691
+ this.#watch = void 0;
8692
+ const code2 = refusalCode(error);
8693
+ if (code2 === "unknown_method" || code2 === "usage_watch_limit") {
8694
+ this.#mode = "fallback";
8695
+ return;
8696
+ }
8697
+ if (watch.notices > 0) {
8698
+ const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
8699
+ this.#closes++;
8700
+ this.#mode = "polling";
8701
+ this.#later(delay3);
8702
+ return;
8703
+ }
8704
+ this.#mode = "fallback";
8705
+ void this.#reads.request();
8706
+ if (error === void 0 || classifyVaultFailure(error) === "unreachable")
8707
+ this.#later(WATCH_RETRY_MS);
8123
8708
  }
8124
8709
  current(provider2, accountId, now) {
8125
8710
  for (const entry of this.#entries) {
@@ -8186,30 +8771,14 @@ var init_any_signal = __esm({
8186
8771
  }
8187
8772
  });
8188
8773
 
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
8774
  // ../core/dist/common-auth-embedded/claustrum/enrollment.js
8206
8775
  import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID10 } from "node:crypto";
8207
8776
  import { constants as fsConstants } from "node:fs";
8208
8777
  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
8778
  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";
8779
+ import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8211
8780
  function classifyEnrollmentError(error) {
8212
- if (!(error instanceof ClaustrumCredentialError))
8781
+ if (!(error instanceof ClaustrumCredentialError2))
8213
8782
  return void 0;
8214
8783
  if (TERMINAL_ENROLLMENT_CODES.has(error.code))
8215
8784
  return { code: error.code, disposition: "terminal" };
@@ -8910,9 +9479,9 @@ var init_host_slot = __esm({
8910
9479
  });
8911
9480
 
8912
9481
  // ../core/dist/common-auth-embedded/claustrum/custody.js
8913
- import { ClaustrumCredentialError as ClaustrumCredentialError2 } from "@cortexkit/claustrum-client";
9482
+ import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
8914
9483
  function isScopedCredentialRotation(served, current) {
8915
- return current !== void 0 && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
9484
+ return current !== void 0 && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
8916
9485
  }
8917
9486
  function scopedRetryReason(served, current) {
8918
9487
  if (current === void 0)
@@ -8980,16 +9549,19 @@ function grantReachOf(listed) {
8980
9549
  tuples: Object.freeze(grantTuples.map(({ selectorKind, selector, operation }) => Object.freeze({ selectorKind, selector, operation })))
8981
9550
  });
8982
9551
  }
8983
- var defaultLogger, SERVING_MARGIN_MS, ClaustrumScopedCustody;
9552
+ var defaultLogger, SERVING_MARGIN_MS, KEPT_RECEIPT_MARGIN_MS, ClaustrumScopedCustody;
8984
9553
  var init_custody = __esm({
8985
9554
  "../core/dist/common-auth-embedded/claustrum/custody.js"() {
8986
9555
  "use strict";
8987
9556
  init_logger();
9557
+ init_availability();
8988
9558
  init_enrollment();
8989
9559
  init_errors2();
8990
9560
  init_host_slot();
9561
+ init_watch();
8991
9562
  defaultLogger = createLogger2("claustrum");
8992
9563
  SERVING_MARGIN_MS = 3e5;
9564
+ KEPT_RECEIPT_MARGIN_MS = 6e4;
8993
9565
  ClaustrumScopedCustody = class {
8994
9566
  #client;
8995
9567
  #readToken;
@@ -9000,7 +9572,20 @@ var init_custody = __esm({
9000
9572
  #logger;
9001
9573
  #provenance = /* @__PURE__ */ new WeakMap();
9002
9574
  #reports = /* @__PURE__ */ new WeakMap();
9575
+ #kept = /* @__PURE__ */ new Map();
9576
+ #keptAttempts = /* @__PURE__ */ new WeakMap();
9577
+ #setTimeout;
9578
+ #clearTimeout;
9579
+ #outage = false;
9580
+ #outageError = new ClaustrumUnreachableError();
9581
+ #probeTimer;
9582
+ #probing = false;
9583
+ #lastProbeAt = -Infinity;
9584
+ #probeDelay = 2e3;
9003
9585
  #closed = false;
9586
+ /** The view of the last successful `discover()`, for `watchRoster`. */
9587
+ #discoveredView;
9588
+ #watches = /* @__PURE__ */ new Set();
9004
9589
  constructor(options) {
9005
9590
  const tokenPath = options.tokenPath;
9006
9591
  if (options.readToken) {
@@ -9016,6 +9601,56 @@ var init_custody = __esm({
9016
9601
  this.#requireAssertion = options.requireAssertion ?? false;
9017
9602
  this.#now = options.now ?? Date.now;
9018
9603
  this.#logger = options.logger ?? defaultLogger;
9604
+ this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
9605
+ this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
9606
+ }
9607
+ /** A watch losing its transport is the same outage as an unreachable read. */
9608
+ transportLost(error) {
9609
+ if (this.#closed || this.#outage)
9610
+ return;
9611
+ this.#outage = true;
9612
+ this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError();
9613
+ this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
9614
+ this.#scheduleProbe();
9615
+ }
9616
+ /** Any vault answer ends transport fallback, even when it refuses access. */
9617
+ reachable() {
9618
+ if (this.#closed || !this.#outage)
9619
+ return;
9620
+ this.#outage = false;
9621
+ if (this.#probeTimer)
9622
+ this.#clearTimeout(this.#probeTimer);
9623
+ this.#probeTimer = void 0;
9624
+ this.#probeDelay = 2e3;
9625
+ for (const kept of this.#kept.values())
9626
+ kept.since = null;
9627
+ (this.#logger.info ?? defaultLogger.info)("vault receipt serving resumed", { reason: "reachable" });
9628
+ }
9629
+ #scheduleProbe() {
9630
+ if (this.#closed || !this.#outage || this.#probeTimer || this.#probing)
9631
+ return;
9632
+ this.#probeTimer = this.#setTimeout(() => {
9633
+ this.#probeTimer = void 0;
9634
+ this.#probe(true);
9635
+ }, this.#probeDelay);
9636
+ this.#probeTimer.unref?.();
9637
+ }
9638
+ #probe(idle = false) {
9639
+ if (this.#closed || !this.#outage || this.#probing)
9640
+ return;
9641
+ if (this.#now() - this.#lastProbeAt < 1e3) {
9642
+ this.#scheduleProbe();
9643
+ return;
9644
+ }
9645
+ this.#lastProbeAt = this.#now();
9646
+ this.#probing = true;
9647
+ void this.#list().catch(() => {
9648
+ if (idle && this.#outage)
9649
+ this.#probeDelay = Math.min(this.#probeDelay * 2, 3e4);
9650
+ }).finally(() => {
9651
+ this.#probing = false;
9652
+ this.#scheduleProbe();
9653
+ });
9019
9654
  }
9020
9655
  #check(signal) {
9021
9656
  if (this.#closed)
@@ -9049,13 +9684,20 @@ var init_custody = __esm({
9049
9684
  ]) : await pending;
9050
9685
  } catch (error) {
9051
9686
  this.#check(signal);
9052
- if (error instanceof ClaustrumCredentialError2)
9687
+ if (classifyVaultFailure(error) === "unreachable")
9688
+ this.transportLost(error);
9689
+ else
9690
+ this.reachable();
9691
+ if (error instanceof ClaustrumCredentialError3)
9053
9692
  throw error;
9693
+ if (classifyVaultFailure(error) === "unreachable")
9694
+ throw new ClaustrumUnreachableError();
9054
9695
  throw new ClaustrumConsumerError("unavailable", "Claustrum scoped operation unavailable");
9055
9696
  } finally {
9056
9697
  removeAbortListener?.();
9057
9698
  }
9058
9699
  this.#check(signal);
9700
+ this.reachable();
9059
9701
  return result;
9060
9702
  }
9061
9703
  /**
@@ -9065,8 +9707,25 @@ var init_custody = __esm({
9065
9707
  * skipped records: they simply are not this consumer's.
9066
9708
  */
9067
9709
  async discover(signal) {
9068
- const token = await this.#token(signal);
9069
- const inventory = await this.#call(() => this.#client.listScoped(token), signal);
9710
+ const inventory = await this.#list(signal);
9711
+ this.#discoveredView = inventory.view;
9712
+ return inventory;
9713
+ }
9714
+ async #list(signal) {
9715
+ let inventory;
9716
+ let token;
9717
+ try {
9718
+ token = await this.#token(signal);
9719
+ } catch (error) {
9720
+ this.#kept.clear();
9721
+ throw error;
9722
+ }
9723
+ try {
9724
+ inventory = await this.#call(() => this.#client.listScoped(token), signal);
9725
+ } catch (error) {
9726
+ this.listFailed(error);
9727
+ throw error;
9728
+ }
9070
9729
  const skipped = [];
9071
9730
  const candidates = [];
9072
9731
  const counts = /* @__PURE__ */ new Map();
@@ -9114,21 +9773,105 @@ var init_custody = __esm({
9114
9773
  };
9115
9774
  }
9116
9775
  /**
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.
9776
+ * Apply a failed account listing: any answer from the vault (a refusal such
9777
+ * as a revoked enrollment's `not_found`) drops every kept receipt, while an
9778
+ * unreachable vault keeps them. A vault watch that ends with the same
9779
+ * refusal calls this too, so both paths treat it alike.
9124
9780
  */
9125
- async authorize(identity, signal) {
9781
+ listFailed(error) {
9782
+ if (classifyVaultFailure(error) === "unreachable")
9783
+ this.transportLost(error);
9784
+ else {
9785
+ this.reachable();
9786
+ this.#kept.clear();
9787
+ }
9788
+ }
9789
+ /** Discard bearer material when a route is removed, declined or rebound. */
9790
+ forget(credentialId) {
9791
+ this.#kept.delete(credentialId);
9792
+ }
9793
+ /** Apply an already-held roster; this never fetches credentials or writes it. */
9794
+ retain(identities) {
9795
+ const current = new Map(identities.map((identity) => [identity.credentialId, identity]));
9796
+ for (const [id, kept] of this.#kept) {
9797
+ const identity = current.get(id);
9798
+ if (!identity?.enabled || identity.state !== "active" || identity.credentialType !== kept.attempt.credentialType || identity.accountIdentity !== kept.attempt.expectedAccountIdentity)
9799
+ this.forget(id);
9800
+ }
9801
+ }
9802
+ /** A frozen, non-secret summary for a plugin's status display. */
9803
+ keptReceiptState() {
9804
+ let since = null;
9805
+ for (const [id, kept] of this.#kept) {
9806
+ if (!this.#usable(kept.attempt)) {
9807
+ this.forget(id);
9808
+ continue;
9809
+ }
9810
+ if (kept.since !== null)
9811
+ since = Math.min(since ?? kept.since, kept.since);
9812
+ }
9813
+ return Object.freeze({ active: since !== null, since });
9814
+ }
9815
+ #usable(attempt) {
9816
+ return attempt.expiresAtMs === null ? attempt.credentialType === "api_key" : attempt.expiresAtMs - this.#now() > KEPT_RECEIPT_MARGIN_MS;
9817
+ }
9818
+ /** Ask the vault while reachable; retain one validated receipt in memory only. */
9819
+ async authorize(identity, signal, routeId = "vault") {
9820
+ this.#check(signal);
9821
+ const { credentialId, credentialType, accountIdentity } = identity;
9822
+ let kept = this.#kept.get(credentialId);
9823
+ if (kept && (kept.attempt.credentialType !== credentialType || kept.attempt.expectedAccountIdentity !== accountIdentity)) {
9824
+ this.forget(credentialId);
9825
+ kept = void 0;
9826
+ }
9827
+ let token;
9828
+ try {
9829
+ token = await this.#token(signal);
9830
+ } catch (error) {
9831
+ this.#kept.clear();
9832
+ throw error;
9833
+ }
9834
+ if (this.#outage && kept) {
9835
+ this.#probe();
9836
+ return this.#serveKept(credentialId, kept, token, routeId);
9837
+ }
9838
+ try {
9839
+ const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
9840
+ this.#kept.set(credentialId, { attempt, routeId, since: null });
9841
+ return attempt;
9842
+ } catch (error) {
9843
+ this.#check(signal);
9844
+ if (classifyVaultFailure(error) !== "unreachable") {
9845
+ this.forget(credentialId);
9846
+ throw error;
9847
+ }
9848
+ return this.#serveKept(credentialId, kept, token, routeId, error);
9849
+ }
9850
+ }
9851
+ #serveKept(credentialId, kept, token, routeId, error = this.#outageError) {
9852
+ if (!kept || this.#kept.get(credentialId) !== kept || !this.#usable(kept.attempt)) {
9853
+ this.forget(credentialId);
9854
+ throw error;
9855
+ }
9856
+ if (kept.since === null)
9857
+ kept.since = this.#now();
9858
+ const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, "accessToken", { value: kept.attempt.accessToken, enumerable: false }));
9859
+ this.#provenance.set(attempt, token);
9860
+ this.#keptAttempts.set(attempt, routeId);
9861
+ return attempt;
9862
+ }
9863
+ /**
9864
+ * Fetch and validate a fresh receipt before retaining it. The vault assertion
9865
+ * (or the plugin's token parse) must agree with the roster when both exist.
9866
+ * With requireAssertion, an absent assertion also refuses rather than
9867
+ * treating the roster's expectation as proof of the served account.
9868
+ */
9869
+ async #authorizeFresh(identity, token, signal) {
9126
9870
  if (!identity.credentialId)
9127
9871
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum dispatch requires a credential id");
9128
9872
  const { credentialId, credentialType, accountIdentity } = identity;
9129
9873
  if (this.#requireAssertion && accountIdentity === void 0)
9130
9874
  throw new ClaustrumConsumerError("identity-unasserted", "Claustrum dispatch requires a known account identity");
9131
- const token = await this.#token(signal);
9132
9875
  const served = await this.#call(() => this.#client.getScoped({
9133
9876
  credentialId,
9134
9877
  enrollmentToken: token,
@@ -9191,6 +9934,18 @@ var init_custody = __esm({
9191
9934
  const token = this.#provenance.get(attempt);
9192
9935
  if (!token)
9193
9936
  throw new ClaustrumConsumerError("no-receipt", "Claustrum failure report requires an original dispatch receipt");
9937
+ const keptRoute = this.#keptAttempts.get(attempt);
9938
+ if (keptRoute !== void 0) {
9939
+ this.forget(attempt.credentialId);
9940
+ this.#logger.debug("scoped 401 not reported", {
9941
+ routeId: keptRoute,
9942
+ reason: "kept-receipt"
9943
+ });
9944
+ return;
9945
+ }
9946
+ const kept = this.#kept.get(attempt.credentialId);
9947
+ if (kept && kept.attempt.recordVersion === attempt.recordVersion)
9948
+ this.forget(attempt.credentialId);
9194
9949
  const pending = this.#reports.get(attempt);
9195
9950
  if (pending)
9196
9951
  return pending;
@@ -9214,10 +9969,70 @@ var init_custody = __esm({
9214
9969
  throw error;
9215
9970
  }
9216
9971
  }
9972
+ /**
9973
+ * Watch this consumer's visible vault accounts instead of listing them on a
9974
+ * short timer. Opens one `watchScoped` on this custody's client and calls
9975
+ * `onView` when the host must run its discovery (see
9976
+ * `ClaustrumRosterWatchOptions`). A claustrum-client without `watchScoped`
9977
+ * (before 0.12.0) or a vault that answers `unknown_method` reports
9978
+ * `fallback` and opens nothing. A watch that closes before any notice was
9979
+ * never accepted: the client reads once to learn why, and the watch reports
9980
+ * `fallback` and tries one new watch after `WATCH_RETRY_MS`, never in a
9981
+ * loop. A watch that closes after notices is re-opened after
9982
+ * `RESUBSCRIBE_BACKOFF_MS`, doubling per close in a row. A lost transport
9983
+ * starts this custody's outage, exactly as an unreachable call does, and
9984
+ * the first notice of a watch ends it. Timers are unreferenced; `close()`
9985
+ * on the returned watch or on this custody stops it.
9986
+ *
9987
+ * The watch keeps no history, so the host still lists on a slow timer while
9988
+ * the mode is `watching`: every `SAFETY_POLL_MS` (five minutes). In any
9989
+ * other mode the host keeps its usual list timer.
9990
+ */
9991
+ watchRoster(options) {
9992
+ this.#check();
9993
+ const watch = new ScopedRosterWatch({
9994
+ client: this.#client,
9995
+ enrollmentToken: () => this.#token(),
9996
+ view: options.view ?? (() => this.#discoveredView),
9997
+ discover: async (view) => {
9998
+ await options.onView(view);
9999
+ },
10000
+ onRefused: (error) => {
10001
+ this.listFailed(error);
10002
+ options.onRefused?.(error);
10003
+ },
10004
+ onTransportLost: () => this.transportLost(),
10005
+ onReachable: () => this.reachable(),
10006
+ onError: options.onError,
10007
+ onMode: options.onMode,
10008
+ logger: this.#logger,
10009
+ now: this.#now,
10010
+ setTimeoutImpl: this.#setTimeout,
10011
+ clearTimeoutImpl: this.#clearTimeout
10012
+ });
10013
+ this.#watches.add(watch);
10014
+ watch.start();
10015
+ return {
10016
+ get mode() {
10017
+ return watch.mode;
10018
+ },
10019
+ close: () => {
10020
+ this.#watches.delete(watch);
10021
+ watch.stop();
10022
+ }
10023
+ };
10024
+ }
9217
10025
  close() {
9218
10026
  if (this.#closed)
9219
10027
  return;
9220
10028
  this.#closed = true;
10029
+ if (this.#probeTimer)
10030
+ this.#clearTimeout(this.#probeTimer);
10031
+ this.#probeTimer = void 0;
10032
+ for (const watch of this.#watches)
10033
+ watch.stop();
10034
+ this.#watches.clear();
10035
+ this.#kept.clear();
9221
10036
  this.#client.close();
9222
10037
  }
9223
10038
  };
@@ -9668,6 +10483,7 @@ var init_consumer = __esm({
9668
10483
  init_errors2();
9669
10484
  init_insula();
9670
10485
  init_roster();
10486
+ init_watch();
9671
10487
  ClaustrumConsumer = class {
9672
10488
  #options;
9673
10489
  #shutdown = new AbortController();
@@ -9684,6 +10500,10 @@ var init_consumer = __esm({
9684
10500
  #timer;
9685
10501
  #started = false;
9686
10502
  #insula;
10503
+ #vaultWatch;
10504
+ #releaseInsulaWatch;
10505
+ /** When this instance last completed a discovery, by `now`. */
10506
+ #discoveredAt;
9687
10507
  constructor(options) {
9688
10508
  this.#options = options;
9689
10509
  this.#logger = options.logger ?? createLogger2("claustrum");
@@ -9741,7 +10561,9 @@ var init_consumer = __esm({
9741
10561
  parseIdentity: this.#options.parseIdentity,
9742
10562
  requireAssertion: this.#options.requireAssertion,
9743
10563
  now: this.#options.now,
9744
- logger: this.#logger
10564
+ logger: this.#logger,
10565
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10566
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
9745
10567
  });
9746
10568
  if (this.#options.insula && client.insula) {
9747
10569
  this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
@@ -9770,6 +10592,26 @@ var init_consumer = __esm({
9770
10592
  const latest2 = this.#grantReach;
9771
10593
  return latest2 && this.#roster?.view === latest2.view ? latest2.reach : void 0;
9772
10594
  }
10595
+ /** How this consumer currently learns about changes, without I/O. */
10596
+ watchState() {
10597
+ return Object.freeze({
10598
+ vault: this.#vaultWatch?.mode ?? "polling",
10599
+ ...this.#options.insula && {
10600
+ insula: this.#insula?.source.watchMode() ?? "polling"
10601
+ }
10602
+ });
10603
+ }
10604
+ /** Close the watches with the connection they belong to. */
10605
+ #stopWatch() {
10606
+ this.#vaultWatch?.close();
10607
+ this.#vaultWatch = void 0;
10608
+ this.#releaseInsulaWatch?.();
10609
+ this.#releaseInsulaWatch = void 0;
10610
+ }
10611
+ /** Whether any account is using an in-memory outage receipt, without I/O. */
10612
+ keptReceiptState() {
10613
+ return this.#custody?.keptReceiptState() ?? Object.freeze({ active: false, since: null });
10614
+ }
9773
10615
  /** Rows for `/routing`, from the last committed roster. */
9774
10616
  routingRows() {
9775
10617
  return vaultRoutingRows(this.#roster);
@@ -9782,6 +10624,7 @@ var init_consumer = __esm({
9782
10624
  if (!await this.#active()) {
9783
10625
  this.#roster = void 0;
9784
10626
  this.#grantReach = void 0;
10627
+ this.#stopWatch();
9785
10628
  this.#custody?.close();
9786
10629
  this.#custody = void 0;
9787
10630
  this.#insula?.release();
@@ -9810,16 +10653,28 @@ var init_consumer = __esm({
9810
10653
  this.#assertOpen();
9811
10654
  const changed = roster?.view !== this.#roster?.view;
9812
10655
  this.#roster = roster;
10656
+ custody.retain(roster?.rows ?? []);
9813
10657
  if (discovered && roster?.view !== void 0)
9814
10658
  this.#grantReach = discovered.grantReach ? { view: roster.view, reach: discovered.grantReach } : void 0;
9815
10659
  if (roster && changed)
9816
10660
  this.#options.onRoster?.(roster);
10661
+ this.#discoveredAt = (this.#options.now ?? Date.now)();
9817
10662
  return roster;
9818
10663
  })().finally(() => {
9819
10664
  this.#refreshing = void 0;
9820
10665
  });
9821
10666
  return this.#refreshing;
9822
10667
  }
10668
+ /**
10669
+ * Poll in the background and open the vault and insula watches. Until the
10670
+ * vault watch is accepted, and whenever it is unavailable, every tick lists
10671
+ * the vault exactly as before watches existed. While it is open a tick
10672
+ * lists only when five minutes have passed since the last discovery, since
10673
+ * the watch keeps no history; it still checks `isCustodyActive`, so a switch
10674
+ * to local mode closes the connection as quickly as before. Insula is
10675
+ * polled on the tick only while its own watch is not open. A host not in
10676
+ * vault mode makes no request.
10677
+ */
9823
10678
  start() {
9824
10679
  if (this.#started)
9825
10680
  return;
@@ -9827,8 +10682,10 @@ var init_consumer = __esm({
9827
10682
  this.#started = true;
9828
10683
  const tick = async () => {
9829
10684
  try {
9830
- await this.refresh();
10685
+ if (await this.#listDue())
10686
+ await this.refresh();
9831
10687
  await this.refreshInsulaQuota();
10688
+ this.#openWatch();
9832
10689
  } catch (error) {
9833
10690
  if (!this.#shutdown.signal.aborted)
9834
10691
  this.#options.onError?.(error);
@@ -9846,6 +10703,50 @@ var init_consumer = __esm({
9846
10703
  };
9847
10704
  void tick();
9848
10705
  }
10706
+ /** Whether a background tick must list the vault now. */
10707
+ async #listDue() {
10708
+ if (this.#vaultWatch?.mode !== "watching")
10709
+ return true;
10710
+ const now = (this.#options.now ?? Date.now)();
10711
+ if (this.#discoveredAt === void 0 || now - this.#discoveredAt >= SAFETY_POLL_MS)
10712
+ return true;
10713
+ return !await this.#active();
10714
+ }
10715
+ /**
10716
+ * Open the vault and insula watches once a vault connection exists. Only
10717
+ * reached in vault mode: a host in local mode never connects.
10718
+ */
10719
+ #openWatch() {
10720
+ const custody = this.#custody;
10721
+ if (this.#shutdown.signal.aborted || !custody)
10722
+ return;
10723
+ this.#vaultWatch ??= custody.watchRoster({
10724
+ view: () => this.#roster?.view,
10725
+ // The existing discovery, so a watched change commits the roster and
10726
+ // re-applies it to kept receipts exactly as a poll does. A refresh
10727
+ // already in flight may have listed before the change was announced,
10728
+ // so wait for it and list again.
10729
+ onView: async () => {
10730
+ while (this.#refreshing)
10731
+ await this.#refreshing.catch(() => {
10732
+ });
10733
+ await this.refresh();
10734
+ },
10735
+ // Custody has dropped kept receipts, as a poll meeting the same
10736
+ // refusal from list_scoped would.
10737
+ onRefused: (error) => this.#options.onError?.(error),
10738
+ onError: (error) => {
10739
+ if (!this.#shutdown.signal.aborted)
10740
+ this.#options.onError?.(error);
10741
+ }
10742
+ });
10743
+ if (this.#options.insula && this.#insula && !this.#releaseInsulaWatch)
10744
+ this.#releaseInsulaWatch = this.#insula.source.watch({
10745
+ provider: this.#options.insula.provider,
10746
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10747
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
10748
+ });
10749
+ }
9849
10750
  /**
9850
10751
  * Fetch on a background tick, at most once per minute across projects with
9851
10752
  * the same daemon and enrollment token path. Admission must use the cache
@@ -9908,16 +10809,28 @@ var init_consumer = __esm({
9908
10809
  async authorize(routeId, signal) {
9909
10810
  this.#assertOpen(signal);
9910
10811
  const roster = this.#roster ?? await this.#wait(this.refresh(), signal);
9911
- if (!roster || !await this.#active())
10812
+ if (!roster || !await this.#active()) {
10813
+ this.#custody?.close();
10814
+ this.#custody = void 0;
10815
+ this.#stopWatch();
10816
+ this.#insula?.release();
10817
+ this.#insula = void 0;
9912
10818
  throw new ClaustrumConsumerError("not-active", "Claustrum scoped custody is not active");
10819
+ }
9913
10820
  const current = await readVaultRoster(this.#options.rosterPath);
9914
10821
  this.#assertOpen(signal);
9915
10822
  const observed = roster.rows.find((row) => row.routeId === routeId);
9916
10823
  const configured = current?.rows.find((row) => row.routeId === routeId);
9917
- if (configured && !configured.enabled)
10824
+ if (configured && !configured.enabled) {
10825
+ if (observed)
10826
+ this.#custody?.forget(observed.credentialId);
9918
10827
  throw new ClaustrumConsumerError("route-declined", "Claustrum route is disabled");
9919
- if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity)
10828
+ }
10829
+ if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity || configured.credentialType !== observed.credentialType) {
10830
+ if (observed)
10831
+ this.#custody?.forget(observed.credentialId);
9920
10832
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum route is disabled, removed or changed");
10833
+ }
9921
10834
  const custody = await this.#wait(this.#getCustody(), signal);
9922
10835
  const combined = combineAbortSignals([
9923
10836
  this.#shutdown.signal,
@@ -9930,7 +10843,7 @@ var init_consumer = __esm({
9930
10843
  ...configured.accountIdentity !== void 0 && {
9931
10844
  accountIdentity: configured.accountIdentity
9932
10845
  }
9933
- }, combined.signal);
10846
+ }, combined.signal, routeId);
9934
10847
  } finally {
9935
10848
  combined.dispose();
9936
10849
  }
@@ -9953,6 +10866,10 @@ var init_consumer = __esm({
9953
10866
  const signal = options.signal;
9954
10867
  let served = await this.authorize(routeId, signal);
9955
10868
  let response = await dispatch(served, signal);
10869
+ if (response.status === 401 && served.fromKeptReceipt) {
10870
+ await this.reportFailure(served, 401, options.reporterSource ?? "direct");
10871
+ return response;
10872
+ }
9956
10873
  if (response.status === 401 && !signal?.aborted) {
9957
10874
  let current;
9958
10875
  try {
@@ -9980,6 +10897,7 @@ var init_consumer = __esm({
9980
10897
  this.#assertOpen();
9981
10898
  await declineVaultRoute(this.#options.rosterPath, routeId);
9982
10899
  this.#roster = await readVaultRoster(this.#options.rosterPath);
10900
+ this.#custody?.retain(this.#roster?.rows ?? []);
9983
10901
  }
9984
10902
  async accept(routeId) {
9985
10903
  this.#assertOpen();
@@ -10035,6 +10953,7 @@ var init_consumer = __esm({
10035
10953
  if (this.#timer)
10036
10954
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
10037
10955
  this.#timer = void 0;
10956
+ this.#stopWatch();
10038
10957
  this.#custody?.close();
10039
10958
  this.#insula?.release();
10040
10959
  this.#insula = void 0;
@@ -10049,21 +10968,31 @@ var init_consumer = __esm({
10049
10968
  var claustrum_exports = {};
10050
10969
  __export(claustrum_exports, {
10051
10970
  CUSTODY_PLACEHOLDER_PREFIX: () => CUSTODY_PLACEHOLDER_PREFIX,
10971
+ ChangeNoticeReader: () => ChangeNoticeReader,
10052
10972
  ClaustrumConsumer: () => ClaustrumConsumer,
10053
10973
  ClaustrumConsumerError: () => ClaustrumConsumerError,
10054
- ClaustrumCredentialError: () => ClaustrumCredentialError3,
10974
+ ClaustrumCredentialError: () => ClaustrumCredentialError4,
10055
10975
  ClaustrumEnrollmentManager: () => ClaustrumEnrollmentManager,
10056
10976
  ClaustrumScopedCustody: () => ClaustrumScopedCustody,
10977
+ ClaustrumUnreachableError: () => ClaustrumUnreachableError,
10057
10978
  DEFAULT_ROUTE_PREFIX: () => DEFAULT_ROUTE_PREFIX,
10979
+ KEPT_RECEIPT_MARGIN_MS: () => KEPT_RECEIPT_MARGIN_MS,
10980
+ RESUBSCRIBE_BACKOFF_MS: () => RESUBSCRIBE_BACKOFF_MS,
10058
10981
  RETRYABLE_ENROLLMENT_CODES: () => RETRYABLE_ENROLLMENT_CODES,
10982
+ SAFETY_POLL_MS: () => SAFETY_POLL_MS,
10059
10983
  SERVING_MARGIN_MS: () => SERVING_MARGIN_MS,
10984
+ ScopedRosterWatch: () => ScopedRosterWatch,
10060
10985
  TERMINAL_ENROLLMENT_CODES: () => TERMINAL_ENROLLMENT_CODES,
10986
+ VAULT_FAILURE_CLASSES: () => VAULT_FAILURE_CLASSES,
10987
+ WATCH_RETRY_MS: () => WATCH_RETRY_MS,
10061
10988
  acceptAccount: () => acceptAccount,
10062
10989
  acceptVaultRoute: () => acceptVaultRoute,
10990
+ acquireInsulaQuotaSource: () => acquireInsulaQuotaSource,
10063
10991
  assertHostSlotMatchesMode: () => assertHostSlotMatchesMode,
10064
10992
  assertNotCustodyPlaceholder: () => assertNotCustodyPlaceholder,
10065
10993
  classifyEnrollmentError: () => classifyEnrollmentError,
10066
10994
  classifyHostSlot: () => classifyHostSlot,
10995
+ classifyVaultFailure: () => classifyVaultFailure,
10067
10996
  connectClaustrumEnrollmentClient: () => connectClaustrumEnrollmentClient,
10068
10997
  connectClaustrumScopedClient: () => connectClaustrumScopedClient,
10069
10998
  custodyPlaceholder: () => custodyPlaceholder,
@@ -10093,7 +11022,7 @@ __export(claustrum_exports, {
10093
11022
  vaultRoutingRows: () => vaultRoutingRows
10094
11023
  });
10095
11024
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
10096
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
11025
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
10097
11026
  async function connectClaustrumScopedClient(options) {
10098
11027
  const client = await ClaustrumClient.connect(options);
10099
11028
  return Object.assign(client, { insula: insulaUsageTransport(options) });
@@ -10102,13 +11031,16 @@ var init_claustrum = __esm({
10102
11031
  "../core/dist/common-auth-embedded/claustrum/index.js"() {
10103
11032
  "use strict";
10104
11033
  init_insula();
11034
+ init_availability();
10105
11035
  init_consumer();
10106
11036
  init_custody();
10107
11037
  init_enrollment();
10108
11038
  init_errors2();
10109
11039
  init_host_slot();
11040
+ init_insula();
10110
11041
  init_interlock();
10111
11042
  init_roster();
11043
+ init_watch();
10112
11044
  }
10113
11045
  });
10114
11046
 
@@ -18169,19 +19101,24 @@ async function replaceWindowsFile2(from, to, options = {}) {
18169
19101
  to = resolve7(to);
18170
19102
  const now = options.now ?? (() => performance.now());
18171
19103
  const start = now();
18172
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
19104
+ const leaseDeadline = options.deadline ?? Infinity;
19105
+ let retryDeadline;
18173
19106
  const delays = [0, 10, 20, 40, 80, 100];
18174
19107
  let original;
18175
19108
  let attempts2 = 0;
18176
19109
  for (const delay3 of delays) {
19110
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
18177
19111
  if (now() >= deadline)
18178
19112
  break;
18179
19113
  if (delay3)
18180
19114
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
18181
19115
  if (now() >= deadline)
18182
19116
  break;
19117
+ const fenceStart = now();
18183
19118
  await options.beforeRename?.();
18184
- if (now() >= deadline)
19119
+ if (retryDeadline !== void 0)
19120
+ retryDeadline += now() - fenceStart;
19121
+ if (now() >= leaseDeadline)
18185
19122
  break;
18186
19123
  attempts2++;
18187
19124
  try {
@@ -18193,6 +19130,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
18193
19130
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
18194
19131
  if (!candidate)
18195
19132
  break;
19133
+ retryDeadline ??= now() + 500;
18196
19134
  }
18197
19135
  }
18198
19136
  const error = new PrivateFileError2(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -20599,7 +21537,7 @@ import { createHash as createHash9, randomBytes as randomBytes3, randomUUID as r
20599
21537
  import { constants as fsConstants2 } from "node:fs";
20600
21538
  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
21539
  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";
21540
+ import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
20603
21541
 
20604
21542
  // src/common-auth-embedded/fs/lock-constants.js
20605
21543
  var WRITER_LOCK_CONSTANTS2 = Object.freeze({
@@ -21281,7 +22219,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
21281
22219
  "pending_queue_full"
21282
22220
  ]);
21283
22221
  function classifyEnrollmentError2(error) {
21284
- if (!(error instanceof ClaustrumCredentialError4))
22222
+ if (!(error instanceof ClaustrumCredentialError5))
21285
22223
  return void 0;
21286
22224
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
21287
22225
  return { code: error.code, disposition: "terminal" };