@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/index.js CHANGED
@@ -336,6 +336,7 @@ function scopedWindowParts(quota, options) {
336
336
  const remainingPercent = clampPercent(limit.remainingPercent ?? 0);
337
337
  return {
338
338
  scope: limit.scope,
339
+ ...limit.windowMinutes === void 0 ? {} : { windowMinutes: limit.windowMinutes },
339
340
  part: {
340
341
  kind: "window",
341
342
  name: quotaWindowName(limit),
@@ -404,8 +405,42 @@ function scopeAbbreviations(scopes) {
404
405
  }
405
406
  return new Map(scopes.map((scope) => [scope, short(scopeDisplayName(scope))]));
406
407
  }
408
+ function groupShortNames(groups) {
409
+ const labels = groups.map((group) => group.label.trim() || group.scope);
410
+ const short = scopeAbbreviations(labels);
411
+ return labels.map((label) => short.get(label) ?? label);
412
+ }
413
+ function groupedNarrowPieces(groups, windows) {
414
+ if (!groups || groups.length === 0)
415
+ return void 0;
416
+ const reported = windows.filter(({ part }) => part.kind === "window");
417
+ if (reported.some(({ scope }) => scope === ALL_SCOPE))
418
+ return void 0;
419
+ const candidates = groups.flatMap((group, listed) => {
420
+ const inGroup = reported.filter(({ scope }) => scope === group.scope);
421
+ const groupTightest = inGroup.reduce((least, window) => least === void 0 || (window.part.remainingPercent ?? 0) < (least.part.remainingPercent ?? 0) ? window : least, void 0);
422
+ return groupTightest ? [{ group, listed, window: groupTightest }] : [];
423
+ });
424
+ if (candidates.length === 0)
425
+ return void 0;
426
+ const names = groupShortNames(groups);
427
+ const left = (candidate) => candidate.window.part.remainingPercent ?? 0;
428
+ const shown = [...candidates].sort((a, b) => left(a) - left(b) || a.listed - b.listed).slice(0, NARROW_GROUP_LIMIT).sort((a, b) => a.listed - b.listed);
429
+ return shown.map((candidate, index) => {
430
+ const { windowMinutes } = candidate.window;
431
+ const piece = [
432
+ names[candidate.listed] ?? candidate.group.scope,
433
+ ...windowMinutes === void 0 ? [] : [lengthName(windowMinutes)],
434
+ `${wholePercent(left(candidate))}%`
435
+ ].join(" ");
436
+ return index === shown.length - 1 ? `${piece} left` : piece;
437
+ });
438
+ }
407
439
  function narrowTextParts(quota, options) {
408
440
  const { windows } = scopedWindowParts(quota, options);
441
+ const grouped = groupedNarrowPieces(quota?.groups, windows);
442
+ if (grouped)
443
+ return grouped;
409
444
  const general = windows.filter(({ part, scope }) => part.kind === "window" && scope === ALL_SCOPE);
410
445
  const scoped = windows.filter(({ part, scope }) => part.kind === "window" && scope !== ALL_SCOPE);
411
446
  const abbreviations = scopeAbbreviations(scoped.map(({ scope }) => scope));
@@ -444,7 +479,7 @@ function formatQuota(quota, options) {
444
479
  return parts.join(" \xB7 ");
445
480
  return quota && quota.limits.length > 0 ? NO_LIMITS_REPORTED : NO_QUOTA_READING;
446
481
  }
447
- var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED;
482
+ var QUOTA_STALE_AFTER_MS, NO_QUOTA_READING, NO_LIMITS_REPORTED, NARROW_GROUP_LIMIT;
448
483
  var init_format = __esm({
449
484
  "../core/dist/common-auth-embedded/quota/format.js"() {
450
485
  "use strict";
@@ -452,6 +487,7 @@ var init_format = __esm({
452
487
  QUOTA_STALE_AFTER_MS = 15 * 6e4;
453
488
  NO_QUOTA_READING = "no quota reading yet";
454
489
  NO_LIMITS_REPORTED = "no limits reported";
490
+ NARROW_GROUP_LIMIT = 2;
455
491
  }
456
492
  });
457
493
 
@@ -813,19 +849,24 @@ async function replaceWindowsFile(from, to, options = {}) {
813
849
  to = resolve2(to);
814
850
  const now = options.now ?? (() => performance.now());
815
851
  const start = now();
816
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
852
+ const leaseDeadline = options.deadline ?? Infinity;
853
+ let retryDeadline;
817
854
  const delays = [0, 10, 20, 40, 80, 100];
818
855
  let original;
819
856
  let attempts2 = 0;
820
857
  for (const delay3 of delays) {
858
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
821
859
  if (now() >= deadline)
822
860
  break;
823
861
  if (delay3)
824
862
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
825
863
  if (now() >= deadline)
826
864
  break;
865
+ const fenceStart = now();
827
866
  await options.beforeRename?.();
828
- if (now() >= deadline)
867
+ if (retryDeadline !== void 0)
868
+ retryDeadline += now() - fenceStart;
869
+ if (now() >= leaseDeadline)
829
870
  break;
830
871
  attempts2++;
831
872
  try {
@@ -837,6 +878,7 @@ async function replaceWindowsFile(from, to, options = {}) {
837
878
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
838
879
  if (!candidate)
839
880
  break;
881
+ retryDeadline ??= now() + 500;
840
882
  }
841
883
  }
842
884
  const error = new PrivateFileError(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -8011,6 +8053,326 @@ var init_auth_menu = __esm({
8011
8053
  }
8012
8054
  });
8013
8055
 
8056
+ // ../core/dist/common-auth-embedded/claustrum/errors.js
8057
+ var ClaustrumConsumerError;
8058
+ var init_errors2 = __esm({
8059
+ "../core/dist/common-auth-embedded/claustrum/errors.js"() {
8060
+ "use strict";
8061
+ ClaustrumConsumerError = class extends Error {
8062
+ kind;
8063
+ constructor(kind, message) {
8064
+ super(message);
8065
+ this.name = "ClaustrumConsumerError";
8066
+ this.kind = kind;
8067
+ }
8068
+ };
8069
+ }
8070
+ });
8071
+
8072
+ // ../core/dist/common-auth-embedded/claustrum/availability.js
8073
+ import { ClaustrumCredentialError } from "@cortexkit/claustrum-client";
8074
+ import { SocketClosedError, SocketTimeoutError, SubcCallError } from "@cortexkit/subc-client";
8075
+ function classifyVaultFailure(error) {
8076
+ if (error instanceof ClaustrumUnreachableError || error instanceof SocketClosedError || error instanceof SocketTimeoutError)
8077
+ return "unreachable";
8078
+ const code2 = error instanceof ClaustrumCredentialError || error instanceof SubcCallError ? error.code : error instanceof Error && "code" in error ? error.code : void 0;
8079
+ if (typeof code2 !== "string" || !Object.hasOwn(VAULT_FAILURE_CLASSES, code2))
8080
+ return "answered";
8081
+ return VAULT_FAILURE_CLASSES[code2];
8082
+ }
8083
+ var VAULT_FAILURE_CLASSES, ClaustrumUnreachableError;
8084
+ var init_availability = __esm({
8085
+ "../core/dist/common-auth-embedded/claustrum/availability.js"() {
8086
+ "use strict";
8087
+ init_errors2();
8088
+ VAULT_FAILURE_CLASSES = Object.freeze({
8089
+ ECONNREFUSED: "unreachable",
8090
+ ENOENT: "unreachable",
8091
+ ECONNRESET: "unreachable",
8092
+ EPIPE: "unreachable",
8093
+ ETIMEDOUT: "unreachable",
8094
+ transport_error: "unreachable",
8095
+ unavailable: "unreachable",
8096
+ timeout: "unreachable",
8097
+ route_closed: "unreachable",
8098
+ daemon_draining: "unreachable",
8099
+ connection_closed: "unreachable",
8100
+ connection_dropped: "unreachable",
8101
+ request_deadline: "unreachable",
8102
+ deadline_exceeded_no_drop_observed: "unreachable",
8103
+ module_reloading: "unreachable",
8104
+ module_warming: "unreachable",
8105
+ target_unavailable: "unreachable",
8106
+ module_timeout: "unreachable",
8107
+ invalid_response: "answered",
8108
+ invalid_record_version: "answered",
8109
+ invalid_expiry: "answered",
8110
+ invalid_status: "answered",
8111
+ invalid_params: "answered",
8112
+ ttl_unsatisfiable: "answered",
8113
+ not_found: "answered",
8114
+ enrollment_revoked: "answered",
8115
+ enrollment_invalid: "answered",
8116
+ grant_denied: "answered",
8117
+ credential_unavailable: "answered",
8118
+ needs_reauth: "answered",
8119
+ declined: "answered",
8120
+ disabled: "answered",
8121
+ identity_changed: "answered",
8122
+ closed: "answered",
8123
+ client_closed: "answered",
8124
+ pending_exists: "answered",
8125
+ pending_queue_full: "answered",
8126
+ already_consumed: "answered",
8127
+ superseded: "answered",
8128
+ stale_generation: "answered",
8129
+ missing_identity: "answered",
8130
+ invalid_control_body: "answered",
8131
+ unknown_module: "answered",
8132
+ module_removed: "answered",
8133
+ capability_denied: "answered",
8134
+ unknown_channel: "unreachable",
8135
+ stale_route_epoch: "unreachable",
8136
+ capability_forbidden: "answered",
8137
+ capability_unprovided: "answered",
8138
+ capability_ambiguous: "answered",
8139
+ invalid_capability_identifier: "answered",
8140
+ binary_body_required: "answered",
8141
+ binary_call_requires_call_binary: "answered",
8142
+ corr_exhausted: "answered",
8143
+ late_route_cleanup_failed: "answered",
8144
+ reverse_request_capability_not_declared: "answered",
8145
+ stale_route_handle: "answered",
8146
+ reverse_request_unhandled: "answered",
8147
+ handler_error: "answered",
8148
+ health_error: "answered",
8149
+ duplicate_module_id: "answered",
8150
+ route_rejected: "answered",
8151
+ lock_busy: "answered",
8152
+ owner_invalid: "answered",
8153
+ renewal_failed: "answered",
8154
+ unsupported_platform: "answered",
8155
+ EACCES: "answered",
8156
+ EPERM: "answered",
8157
+ ERR_PRIVATE_FILES_SECURITY: "answered"
8158
+ });
8159
+ ClaustrumUnreachableError = class extends ClaustrumConsumerError {
8160
+ constructor() {
8161
+ super("unavailable", "Claustrum scoped operation unavailable");
8162
+ this.name = "ClaustrumUnreachableError";
8163
+ }
8164
+ };
8165
+ }
8166
+ });
8167
+
8168
+ // ../core/dist/common-auth-embedded/claustrum/watch.js
8169
+ var SAFETY_POLL_MS, WATCH_RETRY_MS, RESUBSCRIBE_BACKOFF_MS, ChangeNoticeReader, CoalescedRead, ScopedRosterWatch;
8170
+ var init_watch = __esm({
8171
+ "../core/dist/common-auth-embedded/claustrum/watch.js"() {
8172
+ "use strict";
8173
+ SAFETY_POLL_MS = 5 * 6e4;
8174
+ WATCH_RETRY_MS = 5 * 6e4;
8175
+ RESUBSCRIBE_BACKOFF_MS = 1e3;
8176
+ ChangeNoticeReader = class {
8177
+ #epoch;
8178
+ #seq = 0;
8179
+ /**
8180
+ * Begin a new watch, whose first notice is seq 1 again. The epoch is kept,
8181
+ * so a module restart between two watches still reads as a break.
8182
+ */
8183
+ restart() {
8184
+ this.#seq = 0;
8185
+ }
8186
+ continuous(notice) {
8187
+ const continuous = notice.kind === "changed" && notice.seq === this.#seq + 1 && (this.#epoch === void 0 || notice.epoch === this.#epoch);
8188
+ this.#epoch = notice.epoch;
8189
+ this.#seq = notice.seq;
8190
+ return continuous;
8191
+ }
8192
+ };
8193
+ CoalescedRead = class {
8194
+ #read;
8195
+ #onError;
8196
+ #running;
8197
+ #queued = false;
8198
+ constructor(read, onError) {
8199
+ this.#read = read;
8200
+ this.#onError = onError;
8201
+ }
8202
+ /** The read in flight (including its queued follow-up), if any. */
8203
+ get running() {
8204
+ return this.#running;
8205
+ }
8206
+ request() {
8207
+ if (this.#running) {
8208
+ this.#queued = true;
8209
+ return this.#running;
8210
+ }
8211
+ this.#running = (async () => {
8212
+ do {
8213
+ this.#queued = false;
8214
+ try {
8215
+ await this.#read();
8216
+ } catch (error) {
8217
+ this.#onError(error);
8218
+ }
8219
+ } while (this.#queued);
8220
+ })().finally(() => {
8221
+ this.#running = void 0;
8222
+ });
8223
+ return this.#running;
8224
+ }
8225
+ };
8226
+ ScopedRosterWatch = class {
8227
+ #options;
8228
+ #reader = new ChangeNoticeReader();
8229
+ #reads;
8230
+ #mode = "polling";
8231
+ #watch;
8232
+ #timer;
8233
+ #stopped = false;
8234
+ #latestView;
8235
+ #force = false;
8236
+ /**
8237
+ * How many accepted watches in a row have closed; each one doubles the wait
8238
+ * before the next re-subscribe. Reset once a watch stays up five minutes.
8239
+ */
8240
+ #closes = 0;
8241
+ constructor(options) {
8242
+ this.#options = options;
8243
+ this.#reads = new CoalescedRead(async () => {
8244
+ const force = this.#force;
8245
+ this.#force = false;
8246
+ if (force || this.#latestView !== this.#options.view())
8247
+ await this.#options.discover(this.#latestView ?? "");
8248
+ }, (error) => {
8249
+ if (!this.#stopped)
8250
+ this.#options.onError?.(error);
8251
+ });
8252
+ }
8253
+ get mode() {
8254
+ return this.#mode;
8255
+ }
8256
+ start() {
8257
+ if (this.#stopped || this.#watch || this.#timer)
8258
+ return;
8259
+ if (typeof this.#options.client.watchScoped !== "function") {
8260
+ this.#setMode("fallback", "client-without-watch");
8261
+ return;
8262
+ }
8263
+ void this.#open(false);
8264
+ }
8265
+ stop() {
8266
+ if (this.#stopped)
8267
+ return;
8268
+ this.#stopped = true;
8269
+ if (this.#timer)
8270
+ (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
8271
+ this.#timer = void 0;
8272
+ const watch = this.#watch;
8273
+ this.#watch = void 0;
8274
+ watch?.handle.stop();
8275
+ }
8276
+ #setMode(mode, reason) {
8277
+ if (this.#mode === mode)
8278
+ return;
8279
+ this.#mode = mode;
8280
+ this.#options.logger?.debug("claustrum vault watch", { mode, reason });
8281
+ this.#options.onMode?.(mode);
8282
+ }
8283
+ #later(delay3, run) {
8284
+ this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
8285
+ this.#timer = void 0;
8286
+ if (!this.#stopped)
8287
+ run();
8288
+ }, delay3);
8289
+ this.#timer.unref?.();
8290
+ }
8291
+ async #open(resubscribed) {
8292
+ let token;
8293
+ try {
8294
+ token = await this.#options.enrollmentToken();
8295
+ } catch (error) {
8296
+ if (this.#stopped)
8297
+ return;
8298
+ this.#options.onError?.(error);
8299
+ this.#fallback("token-unreadable");
8300
+ return;
8301
+ }
8302
+ const watchScoped = this.#options.client.watchScoped;
8303
+ if (this.#stopped || this.#watch || !watchScoped)
8304
+ return;
8305
+ this.#reader.restart();
8306
+ this.#force = resubscribed;
8307
+ let watch;
8308
+ let handle;
8309
+ try {
8310
+ handle = watchScoped.call(this.#options.client, (notice) => {
8311
+ if (this.#stopped || !watch || this.#watch !== watch)
8312
+ return;
8313
+ watch.notices++;
8314
+ if (watch.notices === 1) {
8315
+ this.#options.onReachable?.();
8316
+ watch.acceptedAt = (this.#options.now ?? Date.now)();
8317
+ this.#setMode("watching", "accepted");
8318
+ }
8319
+ if (!this.#reader.continuous(notice))
8320
+ this.#force = true;
8321
+ this.#latestView = notice.view;
8322
+ void this.#reads.request();
8323
+ }, { enrollmentToken: token });
8324
+ } catch (error) {
8325
+ this.#options.onError?.(error);
8326
+ this.#fallback("watch-failed");
8327
+ return;
8328
+ }
8329
+ watch = { handle, notices: 0 };
8330
+ this.#watch = watch;
8331
+ this.#setMode("polling", resubscribed ? "resubscribing" : "opening");
8332
+ const opened = watch;
8333
+ handle.closed.then((end) => this.#closed(opened, end), (error) => this.#closed(opened, { kind: "transport_lost", error }));
8334
+ }
8335
+ #closed(watch, end) {
8336
+ if (this.#stopped || this.#watch !== watch)
8337
+ return;
8338
+ this.#watch = void 0;
8339
+ if (end.kind === "stopped")
8340
+ return;
8341
+ if (end.kind === "transport_lost")
8342
+ this.#options.onTransportLost?.();
8343
+ if (end.kind === "unsupported") {
8344
+ this.#setMode("fallback", "vault-without-watch");
8345
+ return;
8346
+ }
8347
+ if (end.kind === "refused") {
8348
+ this.#fallback("refused");
8349
+ try {
8350
+ this.#options.onRefused(end.error);
8351
+ } catch (error) {
8352
+ this.#options.onError?.(error);
8353
+ }
8354
+ return;
8355
+ }
8356
+ if (watch.notices > 0) {
8357
+ const now = (this.#options.now ?? Date.now)();
8358
+ if (watch.acceptedAt !== void 0 && now - watch.acceptedAt >= SAFETY_POLL_MS)
8359
+ this.#closes = 0;
8360
+ const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
8361
+ this.#closes++;
8362
+ this.#setMode("polling", "resubscribing");
8363
+ this.#later(delay3, () => void this.#open(true));
8364
+ return;
8365
+ }
8366
+ this.#fallback(end.kind);
8367
+ }
8368
+ #fallback(reason) {
8369
+ this.#setMode("fallback", reason);
8370
+ this.#later(WATCH_RETRY_MS, () => void this.#open(false));
8371
+ }
8372
+ };
8373
+ }
8374
+ });
8375
+
8014
8376
  // ../core/dist/common-auth-embedded/claustrum/insula.js
8015
8377
  import { resolve as resolve4 } from "node:path";
8016
8378
  import { storeIdentity } from "@cortexkit/claustrum-client";
@@ -8049,12 +8411,95 @@ function insulaUsageTransport(options) {
8049
8411
  clearTimeout(timer);
8050
8412
  client?.close();
8051
8413
  }
8414
+ },
8415
+ watchUsage(onNotice) {
8416
+ let client;
8417
+ let subscription;
8418
+ let stopped = false;
8419
+ const closed = (async () => {
8420
+ let deadline;
8421
+ const timeout = new Promise((_resolve, reject) => {
8422
+ deadline = setTimeout(
8423
+ // Coded as a timeout, so InsulaQuotaSource treats a watch that could
8424
+ // not open in time as an unreachable insula and tries again later,
8425
+ // not as a refusal.
8426
+ () => reject(Object.assign(new Error("insula watch timeout"), {
8427
+ code: "timeout"
8428
+ })),
8429
+ 3e3
8430
+ );
8431
+ deadline.unref?.();
8432
+ });
8433
+ const open13 = (async () => {
8434
+ const handshakeTimeoutMs = Math.min(options.handshakeTimeoutMs ?? 3e3, 3e3);
8435
+ const connected = options.connector ? await options.connector({
8436
+ connectionFile: options.connectionFile,
8437
+ handshakeTimeoutMs
8438
+ }) : await SubcClient.connect({
8439
+ connectionFile: options.connectionFile,
8440
+ handshakeTimeoutMs
8441
+ });
8442
+ client = connected;
8443
+ if (stopped) {
8444
+ connected.close();
8445
+ return;
8446
+ }
8447
+ const route = await connected.routeOpen({ kind: "management_surface", module_id: "insula" }, identity);
8448
+ if (stopped) {
8449
+ connected.close();
8450
+ return;
8451
+ }
8452
+ subscription = connected.subscribe(route, { method: "usage.watch" }, onNotice);
8453
+ })();
8454
+ try {
8455
+ await Promise.race([open13, timeout]);
8456
+ } catch (error) {
8457
+ stopped = true;
8458
+ throw error;
8459
+ } finally {
8460
+ clearTimeout(deadline);
8461
+ }
8462
+ if (subscription)
8463
+ await subscription.closed;
8464
+ })().finally(() => {
8465
+ stopped = true;
8466
+ client?.close();
8467
+ });
8468
+ return {
8469
+ stop() {
8470
+ if (stopped)
8471
+ return;
8472
+ stopped = true;
8473
+ subscription?.unsubscribe();
8474
+ client?.close();
8475
+ },
8476
+ closed
8477
+ };
8052
8478
  }
8053
8479
  };
8054
8480
  }
8055
8481
  function record2(value) {
8056
8482
  return typeof value === "object" && value !== null && !Array.isArray(value);
8057
8483
  }
8484
+ function decodeUsageNotice(body) {
8485
+ let value;
8486
+ try {
8487
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
8488
+ } catch {
8489
+ return void 0;
8490
+ }
8491
+ 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")
8492
+ return void 0;
8493
+ return {
8494
+ kind: value.kind,
8495
+ epoch: value.epoch,
8496
+ seq: value.seq,
8497
+ ...typeof value.provider === "string" && { provider: value.provider }
8498
+ };
8499
+ }
8500
+ function refusalCode(error) {
8501
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : void 0;
8502
+ }
8058
8503
  function acquireInsulaQuotaSource(transport, tokenPath) {
8059
8504
  const key = JSON.stringify([
8060
8505
  resolve4(transport.connectionFile),
@@ -8082,6 +8527,8 @@ var MINUTE, MAX_AGE, sources, attempts, InsulaQuotaSource;
8082
8527
  var init_insula = __esm({
8083
8528
  "../core/dist/common-auth-embedded/claustrum/insula.js"() {
8084
8529
  "use strict";
8530
+ init_availability();
8531
+ init_watch();
8085
8532
  MINUTE = 6e4;
8086
8533
  MAX_AGE = 4 * MINUTE;
8087
8534
  sources = /* @__PURE__ */ new Map();
@@ -8090,14 +8537,52 @@ var init_insula = __esm({
8090
8537
  transport;
8091
8538
  key;
8092
8539
  #entries = [];
8093
- #pending;
8540
+ /** Every usage.get, polled or watch-driven, shares this one slot. */
8541
+ #reads = new CoalescedRead(async () => {
8542
+ try {
8543
+ const reply = await this.transport.getUsage();
8544
+ if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== void 0)
8545
+ throw new Error("unavailable insula usage");
8546
+ this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
8547
+ } catch {
8548
+ this.#entries = [];
8549
+ }
8550
+ }, () => {
8551
+ });
8552
+ #reader = new ChangeNoticeReader();
8553
+ #mode = "polling";
8554
+ #watchers = 0;
8555
+ /**
8556
+ * How many registered watchers read every provider. Watchers limited to one
8557
+ * provider are counted per provider in `#providers` instead.
8558
+ */
8559
+ #everyProvider = 0;
8560
+ #providers = /* @__PURE__ */ new Map();
8561
+ #watch;
8562
+ #timer;
8563
+ #timers = {};
8564
+ /**
8565
+ * How many accepted watches in a row have closed; each one doubles the wait
8566
+ * before the next re-subscribe. Reset once a watch brings a second notice.
8567
+ */
8568
+ #closes = 0;
8094
8569
  constructor(transport, key) {
8095
8570
  this.transport = transport;
8096
8571
  this.key = key;
8097
8572
  }
8573
+ /**
8574
+ * The background poll: at most one usage.get per minute per daemon and
8575
+ * enrollment token. While a watch is open it reads nothing, because insula's
8576
+ * notices announce every new reading. If insula stops announcing an account,
8577
+ * that account's last entry grows older than the freshness limit `current()`
8578
+ * applies, `current()` returns nothing for it, and the plugin falls back to
8579
+ * its own provider poll for that account.
8580
+ */
8098
8581
  refresh(now) {
8099
- if (this.#pending)
8100
- return this.#pending;
8582
+ if (this.#reads.running)
8583
+ return this.#reads.running;
8584
+ if (this.#mode === "watching")
8585
+ return Promise.resolve();
8101
8586
  for (const [key, time] of attempts) {
8102
8587
  if (now - time >= MINUTE)
8103
8588
  attempts.delete(key);
@@ -8106,19 +8591,119 @@ var init_insula = __esm({
8106
8591
  if (lastAttempt !== void 0 && now - lastAttempt < MINUTE)
8107
8592
  return Promise.resolve();
8108
8593
  attempts.set(this.key, now);
8109
- this.#pending = (async () => {
8110
- try {
8111
- const reply = await this.transport.getUsage();
8112
- if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== void 0)
8113
- throw new Error("unavailable insula usage");
8114
- this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
8115
- } catch {
8116
- this.#entries = [];
8594
+ return this.#reads.request();
8595
+ }
8596
+ /** How this source currently learns about usage changes, for logs. */
8597
+ watchMode() {
8598
+ return this.#mode;
8599
+ }
8600
+ /**
8601
+ * Hold a `usage.watch` open while any watcher wants it, and re-read
8602
+ * usage.get when a notice says something changed. Watchers of one source
8603
+ * share one watch, since insula admits only 64 per process. Returns the
8604
+ * release; the last release closes the watch.
8605
+ */
8606
+ watch(options = {}) {
8607
+ this.#watchers++;
8608
+ const provider2 = options.provider;
8609
+ if (provider2 === void 0)
8610
+ this.#everyProvider++;
8611
+ else
8612
+ this.#providers.set(provider2, (this.#providers.get(provider2) ?? 0) + 1);
8613
+ if (this.#watchers === 1) {
8614
+ this.#timers = options;
8615
+ this.#open();
8616
+ }
8617
+ let released = false;
8618
+ return () => {
8619
+ if (released)
8620
+ return;
8621
+ released = true;
8622
+ if (provider2 === void 0)
8623
+ this.#everyProvider--;
8624
+ else {
8625
+ const left = (this.#providers.get(provider2) ?? 1) - 1;
8626
+ if (left > 0)
8627
+ this.#providers.set(provider2, left);
8628
+ else
8629
+ this.#providers.delete(provider2);
8117
8630
  }
8118
- })().finally(() => {
8119
- this.#pending = void 0;
8120
- });
8121
- return this.#pending;
8631
+ if (--this.#watchers === 0)
8632
+ this.#stopWatch();
8633
+ };
8634
+ }
8635
+ #stopWatch() {
8636
+ if (this.#timer)
8637
+ (this.#timers.clearTimeoutImpl ?? clearTimeout)(this.#timer);
8638
+ this.#timer = void 0;
8639
+ const watch = this.#watch;
8640
+ this.#watch = void 0;
8641
+ watch?.handle?.stop();
8642
+ this.#mode = "polling";
8643
+ }
8644
+ #later(delay3) {
8645
+ this.#timer = (this.#timers.setTimeoutImpl ?? setTimeout)(() => {
8646
+ this.#timer = void 0;
8647
+ if (this.#watchers > 0 && !this.#watch)
8648
+ this.#open();
8649
+ }, delay3);
8650
+ this.#timer.unref?.();
8651
+ }
8652
+ #open() {
8653
+ const watchUsage = this.transport.watchUsage;
8654
+ if (!watchUsage) {
8655
+ this.#mode = "fallback";
8656
+ return;
8657
+ }
8658
+ this.#mode = "polling";
8659
+ this.#reader.restart();
8660
+ const watch = { notices: 0 };
8661
+ this.#watch = watch;
8662
+ let handle;
8663
+ try {
8664
+ handle = watchUsage.call(this.transport, (body) => this.#notice(watch, body));
8665
+ } catch (error) {
8666
+ this.#closed(watch, error);
8667
+ return;
8668
+ }
8669
+ watch.handle = handle;
8670
+ handle.closed.then(() => this.#closed(watch, void 0), (error) => this.#closed(watch, error));
8671
+ }
8672
+ #notice(watch, body) {
8673
+ if (this.#watch !== watch)
8674
+ return;
8675
+ watch.notices++;
8676
+ if (watch.notices === 1)
8677
+ this.#mode = "watching";
8678
+ if (watch.notices === 2)
8679
+ this.#closes = 0;
8680
+ const notice = decodeUsageNotice(body);
8681
+ if (!notice)
8682
+ this.#reader.restart();
8683
+ const continuous = notice ? this.#reader.continuous(notice) : false;
8684
+ if (!continuous || notice?.provider === void 0 || this.#everyProvider > 0 || this.#providers.has(notice.provider))
8685
+ void this.#reads.request();
8686
+ }
8687
+ #closed(watch, error) {
8688
+ if (this.#watch !== watch)
8689
+ return;
8690
+ this.#watch = void 0;
8691
+ const code2 = refusalCode(error);
8692
+ if (code2 === "unknown_method" || code2 === "usage_watch_limit") {
8693
+ this.#mode = "fallback";
8694
+ return;
8695
+ }
8696
+ if (watch.notices > 0) {
8697
+ const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
8698
+ this.#closes++;
8699
+ this.#mode = "polling";
8700
+ this.#later(delay3);
8701
+ return;
8702
+ }
8703
+ this.#mode = "fallback";
8704
+ void this.#reads.request();
8705
+ if (error === void 0 || classifyVaultFailure(error) === "unreachable")
8706
+ this.#later(WATCH_RETRY_MS);
8122
8707
  }
8123
8708
  current(provider2, accountId, now) {
8124
8709
  for (const entry of this.#entries) {
@@ -8185,30 +8770,14 @@ var init_any_signal = __esm({
8185
8770
  }
8186
8771
  });
8187
8772
 
8188
- // ../core/dist/common-auth-embedded/claustrum/errors.js
8189
- var ClaustrumConsumerError;
8190
- var init_errors2 = __esm({
8191
- "../core/dist/common-auth-embedded/claustrum/errors.js"() {
8192
- "use strict";
8193
- ClaustrumConsumerError = class extends Error {
8194
- kind;
8195
- constructor(kind, message) {
8196
- super(message);
8197
- this.name = "ClaustrumConsumerError";
8198
- this.kind = kind;
8199
- }
8200
- };
8201
- }
8202
- });
8203
-
8204
8773
  // ../core/dist/common-auth-embedded/claustrum/enrollment.js
8205
8774
  import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID12 } from "node:crypto";
8206
8775
  import { constants as fsConstants } from "node:fs";
8207
8776
  import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename6, stat as stat4, unlink as unlink6 } from "node:fs/promises";
8208
8777
  import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join5, resolve as resolve5 } from "node:path";
8209
- import { ClaustrumCredentialError, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8778
+ import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8210
8779
  function classifyEnrollmentError(error) {
8211
- if (!(error instanceof ClaustrumCredentialError))
8780
+ if (!(error instanceof ClaustrumCredentialError2))
8212
8781
  return void 0;
8213
8782
  if (TERMINAL_ENROLLMENT_CODES.has(error.code))
8214
8783
  return { code: error.code, disposition: "terminal" };
@@ -8909,9 +9478,9 @@ var init_host_slot = __esm({
8909
9478
  });
8910
9479
 
8911
9480
  // ../core/dist/common-auth-embedded/claustrum/custody.js
8912
- import { ClaustrumCredentialError as ClaustrumCredentialError2 } from "@cortexkit/claustrum-client";
9481
+ import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
8913
9482
  function isScopedCredentialRotation(served, current) {
8914
- return current !== void 0 && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
9483
+ return current !== void 0 && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
8915
9484
  }
8916
9485
  function scopedRetryReason(served, current) {
8917
9486
  if (current === void 0)
@@ -8979,16 +9548,19 @@ function grantReachOf(listed) {
8979
9548
  tuples: Object.freeze(grantTuples.map(({ selectorKind, selector, operation }) => Object.freeze({ selectorKind, selector, operation })))
8980
9549
  });
8981
9550
  }
8982
- var defaultLogger, SERVING_MARGIN_MS, ClaustrumScopedCustody;
9551
+ var defaultLogger, SERVING_MARGIN_MS, KEPT_RECEIPT_MARGIN_MS, ClaustrumScopedCustody;
8983
9552
  var init_custody = __esm({
8984
9553
  "../core/dist/common-auth-embedded/claustrum/custody.js"() {
8985
9554
  "use strict";
8986
9555
  init_logger();
9556
+ init_availability();
8987
9557
  init_enrollment();
8988
9558
  init_errors2();
8989
9559
  init_host_slot();
9560
+ init_watch();
8990
9561
  defaultLogger = createLogger2("claustrum");
8991
9562
  SERVING_MARGIN_MS = 3e5;
9563
+ KEPT_RECEIPT_MARGIN_MS = 6e4;
8992
9564
  ClaustrumScopedCustody = class {
8993
9565
  #client;
8994
9566
  #readToken;
@@ -8999,7 +9571,20 @@ var init_custody = __esm({
8999
9571
  #logger;
9000
9572
  #provenance = /* @__PURE__ */ new WeakMap();
9001
9573
  #reports = /* @__PURE__ */ new WeakMap();
9574
+ #kept = /* @__PURE__ */ new Map();
9575
+ #keptAttempts = /* @__PURE__ */ new WeakMap();
9576
+ #setTimeout;
9577
+ #clearTimeout;
9578
+ #outage = false;
9579
+ #outageError = new ClaustrumUnreachableError();
9580
+ #probeTimer;
9581
+ #probing = false;
9582
+ #lastProbeAt = -Infinity;
9583
+ #probeDelay = 2e3;
9002
9584
  #closed = false;
9585
+ /** The view of the last successful `discover()`, for `watchRoster`. */
9586
+ #discoveredView;
9587
+ #watches = /* @__PURE__ */ new Set();
9003
9588
  constructor(options) {
9004
9589
  const tokenPath = options.tokenPath;
9005
9590
  if (options.readToken) {
@@ -9015,6 +9600,56 @@ var init_custody = __esm({
9015
9600
  this.#requireAssertion = options.requireAssertion ?? false;
9016
9601
  this.#now = options.now ?? Date.now;
9017
9602
  this.#logger = options.logger ?? defaultLogger;
9603
+ this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
9604
+ this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
9605
+ }
9606
+ /** A watch losing its transport is the same outage as an unreachable read. */
9607
+ transportLost(error) {
9608
+ if (this.#closed || this.#outage)
9609
+ return;
9610
+ this.#outage = true;
9611
+ this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError();
9612
+ this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
9613
+ this.#scheduleProbe();
9614
+ }
9615
+ /** Any vault answer ends transport fallback, even when it refuses access. */
9616
+ reachable() {
9617
+ if (this.#closed || !this.#outage)
9618
+ return;
9619
+ this.#outage = false;
9620
+ if (this.#probeTimer)
9621
+ this.#clearTimeout(this.#probeTimer);
9622
+ this.#probeTimer = void 0;
9623
+ this.#probeDelay = 2e3;
9624
+ for (const kept of this.#kept.values())
9625
+ kept.since = null;
9626
+ (this.#logger.info ?? defaultLogger.info)("vault receipt serving resumed", { reason: "reachable" });
9627
+ }
9628
+ #scheduleProbe() {
9629
+ if (this.#closed || !this.#outage || this.#probeTimer || this.#probing)
9630
+ return;
9631
+ this.#probeTimer = this.#setTimeout(() => {
9632
+ this.#probeTimer = void 0;
9633
+ this.#probe(true);
9634
+ }, this.#probeDelay);
9635
+ this.#probeTimer.unref?.();
9636
+ }
9637
+ #probe(idle = false) {
9638
+ if (this.#closed || !this.#outage || this.#probing)
9639
+ return;
9640
+ if (this.#now() - this.#lastProbeAt < 1e3) {
9641
+ this.#scheduleProbe();
9642
+ return;
9643
+ }
9644
+ this.#lastProbeAt = this.#now();
9645
+ this.#probing = true;
9646
+ void this.#list().catch(() => {
9647
+ if (idle && this.#outage)
9648
+ this.#probeDelay = Math.min(this.#probeDelay * 2, 3e4);
9649
+ }).finally(() => {
9650
+ this.#probing = false;
9651
+ this.#scheduleProbe();
9652
+ });
9018
9653
  }
9019
9654
  #check(signal) {
9020
9655
  if (this.#closed)
@@ -9048,13 +9683,20 @@ var init_custody = __esm({
9048
9683
  ]) : await pending;
9049
9684
  } catch (error) {
9050
9685
  this.#check(signal);
9051
- if (error instanceof ClaustrumCredentialError2)
9686
+ if (classifyVaultFailure(error) === "unreachable")
9687
+ this.transportLost(error);
9688
+ else
9689
+ this.reachable();
9690
+ if (error instanceof ClaustrumCredentialError3)
9052
9691
  throw error;
9692
+ if (classifyVaultFailure(error) === "unreachable")
9693
+ throw new ClaustrumUnreachableError();
9053
9694
  throw new ClaustrumConsumerError("unavailable", "Claustrum scoped operation unavailable");
9054
9695
  } finally {
9055
9696
  removeAbortListener?.();
9056
9697
  }
9057
9698
  this.#check(signal);
9699
+ this.reachable();
9058
9700
  return result;
9059
9701
  }
9060
9702
  /**
@@ -9064,8 +9706,25 @@ var init_custody = __esm({
9064
9706
  * skipped records: they simply are not this consumer's.
9065
9707
  */
9066
9708
  async discover(signal) {
9067
- const token = await this.#token(signal);
9068
- const inventory = await this.#call(() => this.#client.listScoped(token), signal);
9709
+ const inventory = await this.#list(signal);
9710
+ this.#discoveredView = inventory.view;
9711
+ return inventory;
9712
+ }
9713
+ async #list(signal) {
9714
+ let inventory;
9715
+ let token;
9716
+ try {
9717
+ token = await this.#token(signal);
9718
+ } catch (error) {
9719
+ this.#kept.clear();
9720
+ throw error;
9721
+ }
9722
+ try {
9723
+ inventory = await this.#call(() => this.#client.listScoped(token), signal);
9724
+ } catch (error) {
9725
+ this.listFailed(error);
9726
+ throw error;
9727
+ }
9069
9728
  const skipped = [];
9070
9729
  const candidates = [];
9071
9730
  const counts = /* @__PURE__ */ new Map();
@@ -9113,21 +9772,105 @@ var init_custody = __esm({
9113
9772
  };
9114
9773
  }
9115
9774
  /**
9116
- * Fetch the credential for one physical send and wrap it in a fresh receipt.
9117
- * The vault's served identity (or, without one, the plugin's parse of the
9118
- * token) must equal the roster's when both are present. Without
9119
- * `requireAssertion`, absence on either side proves nothing and does not
9120
- * refuse; the receipt records what the vault asserted separately from what
9121
- * the roster expected. With it, a reply that does not itself name the
9122
- * credential id and the expected account is refused.
9775
+ * Apply a failed account listing: any answer from the vault (a refusal such
9776
+ * as a revoked enrollment's `not_found`) drops every kept receipt, while an
9777
+ * unreachable vault keeps them. A vault watch that ends with the same
9778
+ * refusal calls this too, so both paths treat it alike.
9123
9779
  */
9124
- async authorize(identity, signal) {
9780
+ listFailed(error) {
9781
+ if (classifyVaultFailure(error) === "unreachable")
9782
+ this.transportLost(error);
9783
+ else {
9784
+ this.reachable();
9785
+ this.#kept.clear();
9786
+ }
9787
+ }
9788
+ /** Discard bearer material when a route is removed, declined or rebound. */
9789
+ forget(credentialId) {
9790
+ this.#kept.delete(credentialId);
9791
+ }
9792
+ /** Apply an already-held roster; this never fetches credentials or writes it. */
9793
+ retain(identities) {
9794
+ const current = new Map(identities.map((identity) => [identity.credentialId, identity]));
9795
+ for (const [id, kept] of this.#kept) {
9796
+ const identity = current.get(id);
9797
+ if (!identity?.enabled || identity.state !== "active" || identity.credentialType !== kept.attempt.credentialType || identity.accountIdentity !== kept.attempt.expectedAccountIdentity)
9798
+ this.forget(id);
9799
+ }
9800
+ }
9801
+ /** A frozen, non-secret summary for a plugin's status display. */
9802
+ keptReceiptState() {
9803
+ let since = null;
9804
+ for (const [id, kept] of this.#kept) {
9805
+ if (!this.#usable(kept.attempt)) {
9806
+ this.forget(id);
9807
+ continue;
9808
+ }
9809
+ if (kept.since !== null)
9810
+ since = Math.min(since ?? kept.since, kept.since);
9811
+ }
9812
+ return Object.freeze({ active: since !== null, since });
9813
+ }
9814
+ #usable(attempt) {
9815
+ return attempt.expiresAtMs === null ? attempt.credentialType === "api_key" : attempt.expiresAtMs - this.#now() > KEPT_RECEIPT_MARGIN_MS;
9816
+ }
9817
+ /** Ask the vault while reachable; retain one validated receipt in memory only. */
9818
+ async authorize(identity, signal, routeId = "vault") {
9819
+ this.#check(signal);
9820
+ const { credentialId, credentialType, accountIdentity } = identity;
9821
+ let kept = this.#kept.get(credentialId);
9822
+ if (kept && (kept.attempt.credentialType !== credentialType || kept.attempt.expectedAccountIdentity !== accountIdentity)) {
9823
+ this.forget(credentialId);
9824
+ kept = void 0;
9825
+ }
9826
+ let token;
9827
+ try {
9828
+ token = await this.#token(signal);
9829
+ } catch (error) {
9830
+ this.#kept.clear();
9831
+ throw error;
9832
+ }
9833
+ if (this.#outage && kept) {
9834
+ this.#probe();
9835
+ return this.#serveKept(credentialId, kept, token, routeId);
9836
+ }
9837
+ try {
9838
+ const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
9839
+ this.#kept.set(credentialId, { attempt, routeId, since: null });
9840
+ return attempt;
9841
+ } catch (error) {
9842
+ this.#check(signal);
9843
+ if (classifyVaultFailure(error) !== "unreachable") {
9844
+ this.forget(credentialId);
9845
+ throw error;
9846
+ }
9847
+ return this.#serveKept(credentialId, kept, token, routeId, error);
9848
+ }
9849
+ }
9850
+ #serveKept(credentialId, kept, token, routeId, error = this.#outageError) {
9851
+ if (!kept || this.#kept.get(credentialId) !== kept || !this.#usable(kept.attempt)) {
9852
+ this.forget(credentialId);
9853
+ throw error;
9854
+ }
9855
+ if (kept.since === null)
9856
+ kept.since = this.#now();
9857
+ const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, "accessToken", { value: kept.attempt.accessToken, enumerable: false }));
9858
+ this.#provenance.set(attempt, token);
9859
+ this.#keptAttempts.set(attempt, routeId);
9860
+ return attempt;
9861
+ }
9862
+ /**
9863
+ * Fetch and validate a fresh receipt before retaining it. The vault assertion
9864
+ * (or the plugin's token parse) must agree with the roster when both exist.
9865
+ * With requireAssertion, an absent assertion also refuses rather than
9866
+ * treating the roster's expectation as proof of the served account.
9867
+ */
9868
+ async #authorizeFresh(identity, token, signal) {
9125
9869
  if (!identity.credentialId)
9126
9870
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum dispatch requires a credential id");
9127
9871
  const { credentialId, credentialType, accountIdentity } = identity;
9128
9872
  if (this.#requireAssertion && accountIdentity === void 0)
9129
9873
  throw new ClaustrumConsumerError("identity-unasserted", "Claustrum dispatch requires a known account identity");
9130
- const token = await this.#token(signal);
9131
9874
  const served = await this.#call(() => this.#client.getScoped({
9132
9875
  credentialId,
9133
9876
  enrollmentToken: token,
@@ -9190,6 +9933,18 @@ var init_custody = __esm({
9190
9933
  const token = this.#provenance.get(attempt);
9191
9934
  if (!token)
9192
9935
  throw new ClaustrumConsumerError("no-receipt", "Claustrum failure report requires an original dispatch receipt");
9936
+ const keptRoute = this.#keptAttempts.get(attempt);
9937
+ if (keptRoute !== void 0) {
9938
+ this.forget(attempt.credentialId);
9939
+ this.#logger.debug("scoped 401 not reported", {
9940
+ routeId: keptRoute,
9941
+ reason: "kept-receipt"
9942
+ });
9943
+ return;
9944
+ }
9945
+ const kept = this.#kept.get(attempt.credentialId);
9946
+ if (kept && kept.attempt.recordVersion === attempt.recordVersion)
9947
+ this.forget(attempt.credentialId);
9193
9948
  const pending = this.#reports.get(attempt);
9194
9949
  if (pending)
9195
9950
  return pending;
@@ -9213,10 +9968,70 @@ var init_custody = __esm({
9213
9968
  throw error;
9214
9969
  }
9215
9970
  }
9971
+ /**
9972
+ * Watch this consumer's visible vault accounts instead of listing them on a
9973
+ * short timer. Opens one `watchScoped` on this custody's client and calls
9974
+ * `onView` when the host must run its discovery (see
9975
+ * `ClaustrumRosterWatchOptions`). A claustrum-client without `watchScoped`
9976
+ * (before 0.12.0) or a vault that answers `unknown_method` reports
9977
+ * `fallback` and opens nothing. A watch that closes before any notice was
9978
+ * never accepted: the client reads once to learn why, and the watch reports
9979
+ * `fallback` and tries one new watch after `WATCH_RETRY_MS`, never in a
9980
+ * loop. A watch that closes after notices is re-opened after
9981
+ * `RESUBSCRIBE_BACKOFF_MS`, doubling per close in a row. A lost transport
9982
+ * starts this custody's outage, exactly as an unreachable call does, and
9983
+ * the first notice of a watch ends it. Timers are unreferenced; `close()`
9984
+ * on the returned watch or on this custody stops it.
9985
+ *
9986
+ * The watch keeps no history, so the host still lists on a slow timer while
9987
+ * the mode is `watching`: every `SAFETY_POLL_MS` (five minutes). In any
9988
+ * other mode the host keeps its usual list timer.
9989
+ */
9990
+ watchRoster(options) {
9991
+ this.#check();
9992
+ const watch = new ScopedRosterWatch({
9993
+ client: this.#client,
9994
+ enrollmentToken: () => this.#token(),
9995
+ view: options.view ?? (() => this.#discoveredView),
9996
+ discover: async (view) => {
9997
+ await options.onView(view);
9998
+ },
9999
+ onRefused: (error) => {
10000
+ this.listFailed(error);
10001
+ options.onRefused?.(error);
10002
+ },
10003
+ onTransportLost: () => this.transportLost(),
10004
+ onReachable: () => this.reachable(),
10005
+ onError: options.onError,
10006
+ onMode: options.onMode,
10007
+ logger: this.#logger,
10008
+ now: this.#now,
10009
+ setTimeoutImpl: this.#setTimeout,
10010
+ clearTimeoutImpl: this.#clearTimeout
10011
+ });
10012
+ this.#watches.add(watch);
10013
+ watch.start();
10014
+ return {
10015
+ get mode() {
10016
+ return watch.mode;
10017
+ },
10018
+ close: () => {
10019
+ this.#watches.delete(watch);
10020
+ watch.stop();
10021
+ }
10022
+ };
10023
+ }
9216
10024
  close() {
9217
10025
  if (this.#closed)
9218
10026
  return;
9219
10027
  this.#closed = true;
10028
+ if (this.#probeTimer)
10029
+ this.#clearTimeout(this.#probeTimer);
10030
+ this.#probeTimer = void 0;
10031
+ for (const watch of this.#watches)
10032
+ watch.stop();
10033
+ this.#watches.clear();
10034
+ this.#kept.clear();
9220
10035
  this.#client.close();
9221
10036
  }
9222
10037
  };
@@ -9667,6 +10482,7 @@ var init_consumer = __esm({
9667
10482
  init_errors2();
9668
10483
  init_insula();
9669
10484
  init_roster();
10485
+ init_watch();
9670
10486
  ClaustrumConsumer = class {
9671
10487
  #options;
9672
10488
  #shutdown = new AbortController();
@@ -9683,6 +10499,10 @@ var init_consumer = __esm({
9683
10499
  #timer;
9684
10500
  #started = false;
9685
10501
  #insula;
10502
+ #vaultWatch;
10503
+ #releaseInsulaWatch;
10504
+ /** When this instance last completed a discovery, by `now`. */
10505
+ #discoveredAt;
9686
10506
  constructor(options) {
9687
10507
  this.#options = options;
9688
10508
  this.#logger = options.logger ?? createLogger2("claustrum");
@@ -9740,7 +10560,9 @@ var init_consumer = __esm({
9740
10560
  parseIdentity: this.#options.parseIdentity,
9741
10561
  requireAssertion: this.#options.requireAssertion,
9742
10562
  now: this.#options.now,
9743
- logger: this.#logger
10563
+ logger: this.#logger,
10564
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10565
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
9744
10566
  });
9745
10567
  if (this.#options.insula && client.insula) {
9746
10568
  this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
@@ -9769,6 +10591,26 @@ var init_consumer = __esm({
9769
10591
  const latest2 = this.#grantReach;
9770
10592
  return latest2 && this.#roster?.view === latest2.view ? latest2.reach : void 0;
9771
10593
  }
10594
+ /** How this consumer currently learns about changes, without I/O. */
10595
+ watchState() {
10596
+ return Object.freeze({
10597
+ vault: this.#vaultWatch?.mode ?? "polling",
10598
+ ...this.#options.insula && {
10599
+ insula: this.#insula?.source.watchMode() ?? "polling"
10600
+ }
10601
+ });
10602
+ }
10603
+ /** Close the watches with the connection they belong to. */
10604
+ #stopWatch() {
10605
+ this.#vaultWatch?.close();
10606
+ this.#vaultWatch = void 0;
10607
+ this.#releaseInsulaWatch?.();
10608
+ this.#releaseInsulaWatch = void 0;
10609
+ }
10610
+ /** Whether any account is using an in-memory outage receipt, without I/O. */
10611
+ keptReceiptState() {
10612
+ return this.#custody?.keptReceiptState() ?? Object.freeze({ active: false, since: null });
10613
+ }
9772
10614
  /** Rows for `/routing`, from the last committed roster. */
9773
10615
  routingRows() {
9774
10616
  return vaultRoutingRows(this.#roster);
@@ -9781,6 +10623,7 @@ var init_consumer = __esm({
9781
10623
  if (!await this.#active()) {
9782
10624
  this.#roster = void 0;
9783
10625
  this.#grantReach = void 0;
10626
+ this.#stopWatch();
9784
10627
  this.#custody?.close();
9785
10628
  this.#custody = void 0;
9786
10629
  this.#insula?.release();
@@ -9809,16 +10652,28 @@ var init_consumer = __esm({
9809
10652
  this.#assertOpen();
9810
10653
  const changed = roster?.view !== this.#roster?.view;
9811
10654
  this.#roster = roster;
10655
+ custody.retain(roster?.rows ?? []);
9812
10656
  if (discovered && roster?.view !== void 0)
9813
10657
  this.#grantReach = discovered.grantReach ? { view: roster.view, reach: discovered.grantReach } : void 0;
9814
10658
  if (roster && changed)
9815
10659
  this.#options.onRoster?.(roster);
10660
+ this.#discoveredAt = (this.#options.now ?? Date.now)();
9816
10661
  return roster;
9817
10662
  })().finally(() => {
9818
10663
  this.#refreshing = void 0;
9819
10664
  });
9820
10665
  return this.#refreshing;
9821
10666
  }
10667
+ /**
10668
+ * Poll in the background and open the vault and insula watches. Until the
10669
+ * vault watch is accepted, and whenever it is unavailable, every tick lists
10670
+ * the vault exactly as before watches existed. While it is open a tick
10671
+ * lists only when five minutes have passed since the last discovery, since
10672
+ * the watch keeps no history; it still checks `isCustodyActive`, so a switch
10673
+ * to local mode closes the connection as quickly as before. Insula is
10674
+ * polled on the tick only while its own watch is not open. A host not in
10675
+ * vault mode makes no request.
10676
+ */
9822
10677
  start() {
9823
10678
  if (this.#started)
9824
10679
  return;
@@ -9826,8 +10681,10 @@ var init_consumer = __esm({
9826
10681
  this.#started = true;
9827
10682
  const tick = async () => {
9828
10683
  try {
9829
- await this.refresh();
10684
+ if (await this.#listDue())
10685
+ await this.refresh();
9830
10686
  await this.refreshInsulaQuota();
10687
+ this.#openWatch();
9831
10688
  } catch (error) {
9832
10689
  if (!this.#shutdown.signal.aborted)
9833
10690
  this.#options.onError?.(error);
@@ -9845,6 +10702,50 @@ var init_consumer = __esm({
9845
10702
  };
9846
10703
  void tick();
9847
10704
  }
10705
+ /** Whether a background tick must list the vault now. */
10706
+ async #listDue() {
10707
+ if (this.#vaultWatch?.mode !== "watching")
10708
+ return true;
10709
+ const now = (this.#options.now ?? Date.now)();
10710
+ if (this.#discoveredAt === void 0 || now - this.#discoveredAt >= SAFETY_POLL_MS)
10711
+ return true;
10712
+ return !await this.#active();
10713
+ }
10714
+ /**
10715
+ * Open the vault and insula watches once a vault connection exists. Only
10716
+ * reached in vault mode: a host in local mode never connects.
10717
+ */
10718
+ #openWatch() {
10719
+ const custody = this.#custody;
10720
+ if (this.#shutdown.signal.aborted || !custody)
10721
+ return;
10722
+ this.#vaultWatch ??= custody.watchRoster({
10723
+ view: () => this.#roster?.view,
10724
+ // The existing discovery, so a watched change commits the roster and
10725
+ // re-applies it to kept receipts exactly as a poll does. A refresh
10726
+ // already in flight may have listed before the change was announced,
10727
+ // so wait for it and list again.
10728
+ onView: async () => {
10729
+ while (this.#refreshing)
10730
+ await this.#refreshing.catch(() => {
10731
+ });
10732
+ await this.refresh();
10733
+ },
10734
+ // Custody has dropped kept receipts, as a poll meeting the same
10735
+ // refusal from list_scoped would.
10736
+ onRefused: (error) => this.#options.onError?.(error),
10737
+ onError: (error) => {
10738
+ if (!this.#shutdown.signal.aborted)
10739
+ this.#options.onError?.(error);
10740
+ }
10741
+ });
10742
+ if (this.#options.insula && this.#insula && !this.#releaseInsulaWatch)
10743
+ this.#releaseInsulaWatch = this.#insula.source.watch({
10744
+ provider: this.#options.insula.provider,
10745
+ setTimeoutImpl: this.#options.setTimeoutImpl,
10746
+ clearTimeoutImpl: this.#options.clearTimeoutImpl
10747
+ });
10748
+ }
9848
10749
  /**
9849
10750
  * Fetch on a background tick, at most once per minute across projects with
9850
10751
  * the same daemon and enrollment token path. Admission must use the cache
@@ -9907,16 +10808,28 @@ var init_consumer = __esm({
9907
10808
  async authorize(routeId, signal) {
9908
10809
  this.#assertOpen(signal);
9909
10810
  const roster = this.#roster ?? await this.#wait(this.refresh(), signal);
9910
- if (!roster || !await this.#active())
10811
+ if (!roster || !await this.#active()) {
10812
+ this.#custody?.close();
10813
+ this.#custody = void 0;
10814
+ this.#stopWatch();
10815
+ this.#insula?.release();
10816
+ this.#insula = void 0;
9911
10817
  throw new ClaustrumConsumerError("not-active", "Claustrum scoped custody is not active");
10818
+ }
9912
10819
  const current = await readVaultRoster(this.#options.rosterPath);
9913
10820
  this.#assertOpen(signal);
9914
10821
  const observed = roster.rows.find((row) => row.routeId === routeId);
9915
10822
  const configured = current?.rows.find((row) => row.routeId === routeId);
9916
- if (configured && !configured.enabled)
10823
+ if (configured && !configured.enabled) {
10824
+ if (observed)
10825
+ this.#custody?.forget(observed.credentialId);
9917
10826
  throw new ClaustrumConsumerError("route-declined", "Claustrum route is disabled");
9918
- if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity)
10827
+ }
10828
+ if (!observed || !configured || configured.state !== "active" || configured.credentialId !== observed.credentialId || configured.accountIdentity !== observed.accountIdentity || configured.credentialType !== observed.credentialType) {
10829
+ if (observed)
10830
+ this.#custody?.forget(observed.credentialId);
9919
10831
  throw new ClaustrumConsumerError("route-unavailable", "Claustrum route is disabled, removed or changed");
10832
+ }
9920
10833
  const custody = await this.#wait(this.#getCustody(), signal);
9921
10834
  const combined = combineAbortSignals([
9922
10835
  this.#shutdown.signal,
@@ -9929,7 +10842,7 @@ var init_consumer = __esm({
9929
10842
  ...configured.accountIdentity !== void 0 && {
9930
10843
  accountIdentity: configured.accountIdentity
9931
10844
  }
9932
- }, combined.signal);
10845
+ }, combined.signal, routeId);
9933
10846
  } finally {
9934
10847
  combined.dispose();
9935
10848
  }
@@ -9952,6 +10865,10 @@ var init_consumer = __esm({
9952
10865
  const signal = options.signal;
9953
10866
  let served = await this.authorize(routeId, signal);
9954
10867
  let response = await dispatch(served, signal);
10868
+ if (response.status === 401 && served.fromKeptReceipt) {
10869
+ await this.reportFailure(served, 401, options.reporterSource ?? "direct");
10870
+ return response;
10871
+ }
9955
10872
  if (response.status === 401 && !signal?.aborted) {
9956
10873
  let current;
9957
10874
  try {
@@ -9979,6 +10896,7 @@ var init_consumer = __esm({
9979
10896
  this.#assertOpen();
9980
10897
  await declineVaultRoute(this.#options.rosterPath, routeId);
9981
10898
  this.#roster = await readVaultRoster(this.#options.rosterPath);
10899
+ this.#custody?.retain(this.#roster?.rows ?? []);
9982
10900
  }
9983
10901
  async accept(routeId) {
9984
10902
  this.#assertOpen();
@@ -10034,6 +10952,7 @@ var init_consumer = __esm({
10034
10952
  if (this.#timer)
10035
10953
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
10036
10954
  this.#timer = void 0;
10955
+ this.#stopWatch();
10037
10956
  this.#custody?.close();
10038
10957
  this.#insula?.release();
10039
10958
  this.#insula = void 0;
@@ -10048,21 +10967,31 @@ var init_consumer = __esm({
10048
10967
  var claustrum_exports = {};
10049
10968
  __export(claustrum_exports, {
10050
10969
  CUSTODY_PLACEHOLDER_PREFIX: () => CUSTODY_PLACEHOLDER_PREFIX,
10970
+ ChangeNoticeReader: () => ChangeNoticeReader,
10051
10971
  ClaustrumConsumer: () => ClaustrumConsumer,
10052
10972
  ClaustrumConsumerError: () => ClaustrumConsumerError,
10053
- ClaustrumCredentialError: () => ClaustrumCredentialError3,
10973
+ ClaustrumCredentialError: () => ClaustrumCredentialError4,
10054
10974
  ClaustrumEnrollmentManager: () => ClaustrumEnrollmentManager,
10055
10975
  ClaustrumScopedCustody: () => ClaustrumScopedCustody,
10976
+ ClaustrumUnreachableError: () => ClaustrumUnreachableError,
10056
10977
  DEFAULT_ROUTE_PREFIX: () => DEFAULT_ROUTE_PREFIX,
10978
+ KEPT_RECEIPT_MARGIN_MS: () => KEPT_RECEIPT_MARGIN_MS,
10979
+ RESUBSCRIBE_BACKOFF_MS: () => RESUBSCRIBE_BACKOFF_MS,
10057
10980
  RETRYABLE_ENROLLMENT_CODES: () => RETRYABLE_ENROLLMENT_CODES,
10981
+ SAFETY_POLL_MS: () => SAFETY_POLL_MS,
10058
10982
  SERVING_MARGIN_MS: () => SERVING_MARGIN_MS,
10983
+ ScopedRosterWatch: () => ScopedRosterWatch,
10059
10984
  TERMINAL_ENROLLMENT_CODES: () => TERMINAL_ENROLLMENT_CODES,
10985
+ VAULT_FAILURE_CLASSES: () => VAULT_FAILURE_CLASSES,
10986
+ WATCH_RETRY_MS: () => WATCH_RETRY_MS,
10060
10987
  acceptAccount: () => acceptAccount,
10061
10988
  acceptVaultRoute: () => acceptVaultRoute,
10989
+ acquireInsulaQuotaSource: () => acquireInsulaQuotaSource,
10062
10990
  assertHostSlotMatchesMode: () => assertHostSlotMatchesMode,
10063
10991
  assertNotCustodyPlaceholder: () => assertNotCustodyPlaceholder,
10064
10992
  classifyEnrollmentError: () => classifyEnrollmentError,
10065
10993
  classifyHostSlot: () => classifyHostSlot,
10994
+ classifyVaultFailure: () => classifyVaultFailure,
10066
10995
  connectClaustrumEnrollmentClient: () => connectClaustrumEnrollmentClient,
10067
10996
  connectClaustrumScopedClient: () => connectClaustrumScopedClient,
10068
10997
  custodyPlaceholder: () => custodyPlaceholder,
@@ -10092,7 +11021,7 @@ __export(claustrum_exports, {
10092
11021
  vaultRoutingRows: () => vaultRoutingRows
10093
11022
  });
10094
11023
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
10095
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
11024
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
10096
11025
  async function connectClaustrumScopedClient(options) {
10097
11026
  const client = await ClaustrumClient.connect(options);
10098
11027
  return Object.assign(client, { insula: insulaUsageTransport(options) });
@@ -10101,13 +11030,16 @@ var init_claustrum = __esm({
10101
11030
  "../core/dist/common-auth-embedded/claustrum/index.js"() {
10102
11031
  "use strict";
10103
11032
  init_insula();
11033
+ init_availability();
10104
11034
  init_consumer();
10105
11035
  init_custody();
10106
11036
  init_enrollment();
10107
11037
  init_errors2();
10108
11038
  init_host_slot();
11039
+ init_insula();
10109
11040
  init_interlock();
10110
11041
  init_roster();
11042
+ init_watch();
10111
11043
  }
10112
11044
  });
10113
11045
 
@@ -20502,7 +21434,15 @@ function projectAntigravityQuota(quota) {
20502
21434
  });
20503
21435
  }
20504
21436
  }
20505
- return { scope: "all", limits, checkedAt };
21437
+ return {
21438
+ scope: "all",
21439
+ limits,
21440
+ checkedAt,
21441
+ groups: [
21442
+ { scope: "gemini", label: "Gemini" },
21443
+ { scope: "non-gemini", label: "Other models" }
21444
+ ]
21445
+ };
20506
21446
  }
20507
21447
  function formatAntigravityQuota(quota, options) {
20508
21448
  return formatQuota(projectAntigravityQuota(quota), options);
@@ -23436,7 +24376,8 @@ function admissionFromReceipt(ref, receipt2) {
23436
24376
  accountIdentity: receipt2.assertedAccountIdentity,
23437
24377
  recordVersion: receipt2.recordVersion,
23438
24378
  projectId: receipt2.projectId,
23439
- expiresAtMs: receipt2.expiresAtMs
24379
+ expiresAtMs: receipt2.expiresAtMs,
24380
+ fromKeptReceipt: receipt2.fromKeptReceipt
23440
24381
  };
23441
24382
  Object.defineProperty(admission, "accessToken", {
23442
24383
  value: receipt2.accessToken,
@@ -23509,7 +24450,7 @@ function createAntigravityVaultAccountSource(options) {
23509
24450
  assertOpen();
23510
24451
  entry.reported = true;
23511
24452
  await consumer.reportFailure(entry.receipt, 401, reporterSource ?? options.reporterSource);
23512
- return true;
24453
+ return entry.receipt.fromKeptReceipt !== true;
23513
24454
  };
23514
24455
  const verifyAttribution = async (attribution, signal) => {
23515
24456
  await assertServing(signal);
@@ -23538,10 +24479,15 @@ function createAntigravityVaultAccountSource(options) {
23538
24479
  },
23539
24480
  routes: () => closed ? [] : routeRefs(consumer.snapshot(), isDeclined2),
23540
24481
  admit: admit2,
24482
+ retryAfter401: (served, current, site) => claustrum.decideScopedRetryAfter401(site, issuedEntry(served).receipt, current && issuedEntry(current).receipt, options.logger),
23541
24483
  send: async (ref, dispatch, sendOptions) => {
23542
24484
  const signal = sendOptions.signal;
23543
24485
  let admission = await admit2(ref, signal);
23544
24486
  let response = await dispatch(admission, signal);
24487
+ if (response.status === 401 && admission.fromKeptReceipt) {
24488
+ await reportServedStatus(admission, 401, sendOptions.reporterSource);
24489
+ return response;
24490
+ }
23545
24491
  if (response.status === 401 && !signal?.aborted) {
23546
24492
  let current;
23547
24493
  try {
@@ -23930,19 +24876,24 @@ async function replaceWindowsFile2(from, to, options = {}) {
23930
24876
  to = resolve7(to);
23931
24877
  const now = options.now ?? (() => performance.now());
23932
24878
  const start = now();
23933
- const deadline = Math.min(start + 500, options.deadline ?? Infinity);
24879
+ const leaseDeadline = options.deadline ?? Infinity;
24880
+ let retryDeadline;
23934
24881
  const delays = [0, 10, 20, 40, 80, 100];
23935
24882
  let original;
23936
24883
  let attempts2 = 0;
23937
24884
  for (const delay3 of delays) {
24885
+ const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
23938
24886
  if (now() >= deadline)
23939
24887
  break;
23940
24888
  if (delay3)
23941
24889
  await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
23942
24890
  if (now() >= deadline)
23943
24891
  break;
24892
+ const fenceStart = now();
23944
24893
  await options.beforeRename?.();
23945
- if (now() >= deadline)
24894
+ if (retryDeadline !== void 0)
24895
+ retryDeadline += now() - fenceStart;
24896
+ if (now() >= leaseDeadline)
23946
24897
  break;
23947
24898
  attempts2++;
23948
24899
  try {
@@ -23954,6 +24905,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
23954
24905
  const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
23955
24906
  if (!candidate)
23956
24907
  break;
24908
+ retryDeadline ??= now() + 500;
23957
24909
  }
23958
24910
  }
23959
24911
  const error = new PrivateFileError2(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
@@ -27944,7 +28896,7 @@ import { createHash as createHash10, randomBytes as randomBytes5, randomUUID as
27944
28896
  import { constants as fsConstants2 } from "node:fs";
27945
28897
  import { chmod as chmod3, mkdir as mkdir12, open as open10, readFile as readFile10, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
27946
28898
  import { basename as basename4, dirname as dirname17, extname as extname2, isAbsolute as isAbsolute3, join as join11, resolve as resolve10 } from "node:path";
27947
- import { ClaustrumCredentialError as ClaustrumCredentialError4, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
28899
+ import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
27948
28900
 
27949
28901
  // src/common-auth-embedded/fs/lock-constants.js
27950
28902
  var WRITER_LOCK_CONSTANTS2 = Object.freeze({
@@ -28626,7 +29578,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
28626
29578
  "pending_queue_full"
28627
29579
  ]);
28628
29580
  function classifyEnrollmentError2(error) {
28629
- if (!(error instanceof ClaustrumCredentialError4))
29581
+ if (!(error instanceof ClaustrumCredentialError5))
28630
29582
  return void 0;
28631
29583
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
28632
29584
  return { code: error.code, disposition: "terminal" };
@@ -30412,6 +31364,7 @@ function refreshVaultAccountRow(prior, fresh) {
30412
31364
  else prior.email = fresh.email;
30413
31365
  }
30414
31366
  var VaultSendGrant = class {
31367
+ fromKeptReceipt;
30415
31368
  credentialId;
30416
31369
  accountIdentity;
30417
31370
  recordVersion;
@@ -30426,20 +31379,36 @@ var VaultSendGrant = class {
30426
31379
  this.accountIdentity = admission.accountIdentity;
30427
31380
  this.recordVersion = admission.recordVersion;
30428
31381
  this.projectId = admission.projectId;
31382
+ this.fromKeptReceipt = admission.fromKeptReceipt;
30429
31383
  this.report401 = report;
30430
31384
  }
30431
31385
  };
30432
31386
  function createVaultRequestCredentials(source, onAdmitted) {
31387
+ const issued = /* @__PURE__ */ new WeakMap();
30433
31388
  return {
30434
31389
  domain: "vault",
31390
+ ...source.retryAfter401 && {
31391
+ retryAfter401(served, current, site) {
31392
+ const original = issued.get(served);
31393
+ if (!original)
31394
+ throw new Error("Retry requires an original vault admission");
31395
+ return source.retryAfter401(
31396
+ original,
31397
+ current && issued.get(current),
31398
+ site
31399
+ );
31400
+ }
31401
+ },
30435
31402
  async admit({ account, signal }) {
30436
31403
  const admission = await source.admit(account.route, signal);
30437
31404
  if (onAdmitted)
30438
31405
  onAdmitted.admitted(account, onAdmitted.source.attribution(admission));
30439
- return new VaultSendGrant(
31406
+ const grant = new VaultSendGrant(
30440
31407
  admission,
30441
31408
  (status) => source.reportServedStatus(admission, status)
30442
31409
  );
31410
+ issued.set(grant, admission);
31411
+ return grant;
30443
31412
  }
30444
31413
  };
30445
31414
  }
@@ -30886,7 +31855,8 @@ function createOpenCodeVaultCustody(options) {
30886
31855
  reporterSource: options.reporterSource,
30887
31856
  state: { path: paths.stateFile, fs: await loadCommonAuthFs() },
30888
31857
  ...options.logger ? { logger: options.logger } : {},
30889
- ...options.now ? { now: options.now } : {}
31858
+ ...options.now ? { now: options.now } : {},
31859
+ ...options.pollIntervalMs !== void 0 ? { pollIntervalMs: options.pollIntervalMs } : {}
30890
31860
  });
30891
31861
  const activeSource = {
30892
31862
  ...created,
@@ -42561,6 +43531,185 @@ function transformAntigravityResponse(...args) {
42561
43531
  return transformAntigravityResponseIn(openCode1WireLocation, ...args);
42562
43532
  }
42563
43533
 
43534
+ // src/plugin/shared/request-cancellation.ts
43535
+ function createRequestCancellation(signals) {
43536
+ const controller = new AbortController();
43537
+ const remove2 = [];
43538
+ const release = () => {
43539
+ for (const detach of remove2.splice(0)) detach();
43540
+ };
43541
+ for (const source of signals) {
43542
+ if (source.aborted) {
43543
+ controller.abort(source.reason);
43544
+ release();
43545
+ break;
43546
+ }
43547
+ const forward = () => {
43548
+ controller.abort(source.reason);
43549
+ release();
43550
+ };
43551
+ remove2.push(() => source.removeEventListener("abort", forward));
43552
+ source.addEventListener("abort", forward, { once: true });
43553
+ if (source.aborted) forward();
43554
+ if (controller.signal.aborted) break;
43555
+ }
43556
+ return { signal: controller.signal, release };
43557
+ }
43558
+ async function retainResponseLifetime(response, cancellation) {
43559
+ if (!response.body) {
43560
+ cancellation.release();
43561
+ return { response, settled: Promise.resolve() };
43562
+ }
43563
+ let reader;
43564
+ try {
43565
+ reader = response.body.getReader();
43566
+ } catch (error) {
43567
+ cancellation.release();
43568
+ throw error;
43569
+ }
43570
+ let resolve18 = () => {
43571
+ };
43572
+ const settled = new Promise((done) => {
43573
+ resolve18 = done;
43574
+ });
43575
+ let stopping = false;
43576
+ let finished = false;
43577
+ let controller;
43578
+ const finish = () => {
43579
+ if (finished) return;
43580
+ finished = true;
43581
+ cancellation.signal.removeEventListener("abort", abort);
43582
+ cancellation.release();
43583
+ resolve18();
43584
+ };
43585
+ const abort = () => {
43586
+ if (finished || stopping) return;
43587
+ stopping = true;
43588
+ const reason = cancellation.signal.reason;
43589
+ controller.error(reason);
43590
+ void reader.cancel(reason).then(finish, finish);
43591
+ };
43592
+ const body = new ReadableStream({
43593
+ start(output2) {
43594
+ controller = output2;
43595
+ cancellation.signal.addEventListener("abort", abort, { once: true });
43596
+ if (cancellation.signal.aborted) abort();
43597
+ },
43598
+ async pull(output2) {
43599
+ try {
43600
+ const next = await reader.read();
43601
+ if (stopping) return;
43602
+ if (next.done) {
43603
+ output2.close();
43604
+ finish();
43605
+ } else {
43606
+ output2.enqueue(next.value);
43607
+ }
43608
+ } catch (error) {
43609
+ if (stopping) return;
43610
+ output2.error(error);
43611
+ finish();
43612
+ }
43613
+ },
43614
+ async cancel(reason) {
43615
+ stopping = true;
43616
+ try {
43617
+ await reader.cancel(reason);
43618
+ } finally {
43619
+ finish();
43620
+ }
43621
+ }
43622
+ });
43623
+ try {
43624
+ return {
43625
+ response: new Response(body, {
43626
+ status: response.status,
43627
+ statusText: response.statusText,
43628
+ headers: response.headers
43629
+ }),
43630
+ settled
43631
+ };
43632
+ } catch (error) {
43633
+ stopping = true;
43634
+ await reader.cancel(error).then(finish, finish);
43635
+ throw error;
43636
+ }
43637
+ }
43638
+
43639
+ // src/plugin/shared/after-handoff.ts
43640
+ function createAfterHandoff(work, signals, onFailure) {
43641
+ const controller = new AbortController();
43642
+ const cancellation = createRequestCancellation([
43643
+ ...signals,
43644
+ controller.signal
43645
+ ]);
43646
+ let run;
43647
+ let acknowledged = false;
43648
+ let finished = false;
43649
+ let running = false;
43650
+ let resolveCompletion = () => {
43651
+ };
43652
+ const completion = new Promise((resolve18) => {
43653
+ resolveCompletion = resolve18;
43654
+ });
43655
+ const finish = () => {
43656
+ if (finished) return;
43657
+ finished = true;
43658
+ run = void 0;
43659
+ cancellation.signal.removeEventListener("abort", onAbort);
43660
+ cancellation.release();
43661
+ work.delete(completion);
43662
+ resolveCompletion();
43663
+ };
43664
+ const onAbort = () => {
43665
+ if (!running) finish();
43666
+ };
43667
+ cancellation.signal.addEventListener("abort", onAbort, { once: true });
43668
+ if (cancellation.signal.aborted) onAbort();
43669
+ return {
43670
+ register(callback) {
43671
+ if (finished || run) return;
43672
+ run = callback;
43673
+ work.add(completion);
43674
+ },
43675
+ acknowledge() {
43676
+ if (finished || acknowledged || !run) return;
43677
+ acknowledged = true;
43678
+ void Promise.resolve().then(async () => {
43679
+ if (finished || cancellation.signal.aborted) return;
43680
+ running = true;
43681
+ try {
43682
+ await run?.(cancellation.signal);
43683
+ } catch {
43684
+ try {
43685
+ onFailure();
43686
+ } catch {
43687
+ }
43688
+ } finally {
43689
+ finish();
43690
+ }
43691
+ });
43692
+ },
43693
+ cancel() {
43694
+ controller.abort();
43695
+ onAbort();
43696
+ }
43697
+ };
43698
+ }
43699
+ function publishResponse(dispatch) {
43700
+ return new Promise((resolve18, reject) => {
43701
+ let acknowledge;
43702
+ void Promise.resolve().then(
43703
+ () => dispatch((callback) => {
43704
+ acknowledge = callback;
43705
+ })
43706
+ ).then((response) => {
43707
+ resolve18(response);
43708
+ acknowledge?.();
43709
+ }, reject);
43710
+ });
43711
+ }
43712
+
42564
43713
  // src/plugin/auth-loader.ts
42565
43714
  var log12 = createLogger4("auth-loader");
42566
43715
  function refreshTokenIdentity(refreshToken) {
@@ -42930,7 +44079,7 @@ function createAuthLoader({
42930
44079
  // through the OLD interceptor after an OAuth add. The wrapper
42931
44080
  // matches the host's `LoaderResult.fetch` signature exactly
42932
44081
  // (no `this` binding) so behavior is preserved.
42933
- fetch: async (input2, init) => {
44082
+ fetch: (input2, init) => publishResponse(async (onResponseHandoff) => {
42934
44083
  assertOpen();
42935
44084
  const authority = await readAuthority?.() ?? "local";
42936
44085
  assertOpen();
@@ -42944,7 +44093,7 @@ function createAuthLoader({
42944
44093
  });
42945
44094
  const vaultRuntime = await vaultFetchRuntime;
42946
44095
  assertOpen();
42947
- return vaultRuntime.fetch(input2, init);
44096
+ return vaultRuntime.fetch(input2, init, onResponseHandoff);
42948
44097
  }
42949
44098
  if (localUnavailable) {
42950
44099
  return fetchWithoutLocalAccounts(input2, init, fetchImpl);
@@ -42968,8 +44117,8 @@ function createAuthLoader({
42968
44117
  return fetchWithoutLocalAccounts(input2, init, fetchImpl);
42969
44118
  if (currentRequestSource !== "local" || !fetchRuntime)
42970
44119
  throw new Error("The local account runtime is unavailable");
42971
- return fetchRuntime.fetch(input2, init);
42972
- }
44120
+ return fetchRuntime.fetch(input2, init, onResponseHandoff);
44121
+ })
42973
44122
  };
42974
44123
  }
42975
44124
  reloadRuntime = async (getAuth) => {
@@ -44977,111 +46126,6 @@ var AgySessionRegistry = class {
44977
46126
  }
44978
46127
  };
44979
46128
 
44980
- // src/plugin/shared/request-cancellation.ts
44981
- function createRequestCancellation(signals) {
44982
- const controller = new AbortController();
44983
- const remove2 = [];
44984
- const release = () => {
44985
- for (const detach of remove2.splice(0)) detach();
44986
- };
44987
- for (const source of signals) {
44988
- if (source.aborted) {
44989
- controller.abort(source.reason);
44990
- release();
44991
- break;
44992
- }
44993
- const forward = () => {
44994
- controller.abort(source.reason);
44995
- release();
44996
- };
44997
- remove2.push(() => source.removeEventListener("abort", forward));
44998
- source.addEventListener("abort", forward, { once: true });
44999
- if (source.aborted) forward();
45000
- if (controller.signal.aborted) break;
45001
- }
45002
- return { signal: controller.signal, release };
45003
- }
45004
- async function retainResponseLifetime(response, cancellation) {
45005
- if (!response.body) {
45006
- cancellation.release();
45007
- return { response, settled: Promise.resolve() };
45008
- }
45009
- let reader;
45010
- try {
45011
- reader = response.body.getReader();
45012
- } catch (error) {
45013
- cancellation.release();
45014
- throw error;
45015
- }
45016
- let resolve18 = () => {
45017
- };
45018
- const settled = new Promise((done) => {
45019
- resolve18 = done;
45020
- });
45021
- let stopping = false;
45022
- let finished = false;
45023
- let controller;
45024
- const finish = () => {
45025
- if (finished) return;
45026
- finished = true;
45027
- cancellation.signal.removeEventListener("abort", abort);
45028
- cancellation.release();
45029
- resolve18();
45030
- };
45031
- const abort = () => {
45032
- if (finished || stopping) return;
45033
- stopping = true;
45034
- const reason = cancellation.signal.reason;
45035
- controller.error(reason);
45036
- void reader.cancel(reason).then(finish, finish);
45037
- };
45038
- const body = new ReadableStream({
45039
- start(output2) {
45040
- controller = output2;
45041
- cancellation.signal.addEventListener("abort", abort, { once: true });
45042
- if (cancellation.signal.aborted) abort();
45043
- },
45044
- async pull(output2) {
45045
- try {
45046
- const next = await reader.read();
45047
- if (stopping) return;
45048
- if (next.done) {
45049
- output2.close();
45050
- finish();
45051
- } else {
45052
- output2.enqueue(next.value);
45053
- }
45054
- } catch (error) {
45055
- if (stopping) return;
45056
- output2.error(error);
45057
- finish();
45058
- }
45059
- },
45060
- async cancel(reason) {
45061
- stopping = true;
45062
- try {
45063
- await reader.cancel(reason);
45064
- } finally {
45065
- finish();
45066
- }
45067
- }
45068
- });
45069
- try {
45070
- return {
45071
- response: new Response(body, {
45072
- status: response.status,
45073
- statusText: response.statusText,
45074
- headers: response.headers
45075
- }),
45076
- settled
45077
- };
45078
- } catch (error) {
45079
- stopping = true;
45080
- await reader.cancel(error).then(finish, finish);
45081
- throw error;
45082
- }
45083
- }
45084
-
45085
46129
  // src/plugin/shared/request-services.ts
45086
46130
  var FIRST_RETRY_DELAY_MS = 1e3;
45087
46131
  function prepareAgyWireRequest(wire, request) {
@@ -46131,24 +47175,17 @@ function createRequestExecutor(deps) {
46131
47175
  );
46132
47176
  noteGeminiDumpResponse(dumpContext, response);
46133
47177
  if (credentials.domain === "vault" && sendAdmission && response.status === 401) {
46134
- try {
46135
- await deadline.wait(
46136
- () => sendAdmission.report401(response.status)
46137
- );
46138
- } catch (error) {
46139
- checkAborted();
46140
- log16.debug("send-admission-401-report-failed", {
46141
- error: String(error)
46142
- });
46143
- }
46144
- if (!vault401Retried) {
46145
- const next = await deadline.wait(
46146
- () => credentials.admit({
46147
- account,
46148
- signal: abortSignal
46149
- })
46150
- );
46151
- if (next.credentialId === sendAdmission.credentialId && next.accountIdentity === sendAdmission.accountIdentity && next.recordVersion > sendAdmission.recordVersion) {
47178
+ if (!sendAdmission.fromKeptReceipt && !vault401Retried && !abortSignal?.aborted) {
47179
+ let next;
47180
+ try {
47181
+ next = await deadline.wait(
47182
+ () => credentials.admit({ account, signal: abortSignal })
47183
+ );
47184
+ } catch {
47185
+ checkAborted();
47186
+ }
47187
+ const retry = credentials.retryAfter401 ? credentials.retryAfter401(sendAdmission, next, "model") : next && !next.fromKeptReceipt && next.credentialId === sendAdmission.credentialId && next.accountIdentity === sendAdmission.accountIdentity && next.recordVersion > sendAdmission.recordVersion;
47188
+ if (next && retry) {
46152
47189
  vault401Retried = true;
46153
47190
  rotatedAdmission = next;
46154
47191
  void response.body?.cancel().catch(() => {
@@ -46160,6 +47197,16 @@ function createRequestExecutor(deps) {
46160
47197
  continue;
46161
47198
  }
46162
47199
  }
47200
+ try {
47201
+ await deadline.wait(
47202
+ () => sendAdmission.report401(response.status)
47203
+ );
47204
+ } catch (error) {
47205
+ checkAborted();
47206
+ log16.debug("send-admission-401-report-failed", {
47207
+ error: String(error)
47208
+ });
47209
+ }
46163
47210
  }
46164
47211
  const sessionKey = requestSessionIdentity.sessionId;
46165
47212
  if (sessionKey) {
@@ -46434,23 +47481,6 @@ function createRequestExecutor(deps) {
46434
47481
  trackers.health.recordSuccess(account.index);
46435
47482
  if (!advisoryClosing)
46436
47483
  accountManager.markAccountUsed(account.index);
46437
- if (credentials.domain === "local" && !advisoryClosing && credentials.refreshQuotaAfterSuccess) {
46438
- const quotaCancellation = createRequestCancellation(
46439
- init?.signal ? [init.signal, shutdown.signal] : [shutdown.signal]
46440
- );
46441
- const work = credentials.refreshQuotaAfterSuccess(
46442
- account,
46443
- config.quota_refresh_interval_minutes,
46444
- quotaCancellation.signal
46445
- ).catch(() => {
46446
- log16.debug("post-response-advisory-work-failed");
46447
- }).finally(() => quotaCancellation.release());
46448
- advisoryWork.add(work);
46449
- void work.then(
46450
- () => advisoryWork.delete(work),
46451
- () => advisoryWork.delete(work)
46452
- );
46453
- }
46454
47484
  const proactiveThreshold = config.proactive_rotation_threshold_percent ?? 20;
46455
47485
  if (!advisoryClosing && proactiveThreshold > 0 && accountManager.shouldProactivelyRotate(
46456
47486
  family,
@@ -46598,6 +47628,10 @@ function createRequestExecutor(deps) {
46598
47628
  );
46599
47629
  }
46600
47630
  }
47631
+ if (response.ok && transformedResponse.ok && credentials.domain === "local" && !advisoryClosing && credentials.refreshQuotaAfterSuccess) {
47632
+ const refresh = credentials.refreshQuotaAfterSuccess;
47633
+ waitPolicy.quota = (signal) => refresh(account, config.quota_refresh_interval_minutes, signal);
47634
+ }
46601
47635
  return transformedResponse;
46602
47636
  } catch (error) {
46603
47637
  if (error instanceof PreResponseTimeoutError) throw error;
@@ -46798,6 +47832,11 @@ function createRequestExecutor(deps) {
46798
47832
  deps.preResponseClock
46799
47833
  );
46800
47834
  log16.debug("pre-response-start", { limitMs: PRE_RESPONSE_DEADLINE_MS });
47835
+ const handoff = createAfterHandoff(
47836
+ advisoryWork,
47837
+ requestedSignal ? [requestedSignal, shutdown.signal] : [shutdown.signal],
47838
+ () => log16.debug("post-response-advisory-work-failed")
47839
+ );
46801
47840
  const waitPolicy = {};
46802
47841
  const selectedCredentials = /* @__PURE__ */ new Set();
46803
47842
  const selectedProjectIds = /* @__PURE__ */ new Set();
@@ -46822,6 +47861,7 @@ function createRequestExecutor(deps) {
46822
47861
  async (response) => {
46823
47862
  deadline.acceptTerminalResponse();
46824
47863
  if (bufferedOverflow.has(response)) {
47864
+ handoff.cancel();
46825
47865
  deadline.dispose();
46826
47866
  cancellation.release();
46827
47867
  return redactCredentialResponse(
@@ -46838,14 +47878,22 @@ function createRequestExecutor(deps) {
46838
47878
  inFlight.add(retained.settled);
46839
47879
  void retained.settled.then(() => inFlight.delete(retained.settled));
46840
47880
  void retained.settled.then(() => deadline.dispose());
46841
- return redactCredentialResponse(
47881
+ const published = await redactCredentialResponse(
46842
47882
  preserveResponseMetadata2(retained.response, response),
46843
47883
  [...selectedCredentials],
46844
47884
  void 0,
46845
47885
  [...selectedProjectIds]
46846
47886
  );
47887
+ if (published.ok && waitPolicy.quota && requestOptions?.onResponseHandoff) {
47888
+ handoff.register(waitPolicy.quota);
47889
+ requestOptions.onResponseHandoff(handoff.acknowledge);
47890
+ } else {
47891
+ handoff.cancel();
47892
+ }
47893
+ return published;
46847
47894
  },
46848
47895
  (error) => {
47896
+ handoff.cancel();
46849
47897
  deadline.dispose();
46850
47898
  cancellation.release();
46851
47899
  throw redactCredentialError(
@@ -46855,6 +47903,7 @@ function createRequestExecutor(deps) {
46855
47903
  );
46856
47904
  }
46857
47905
  ).catch((error) => {
47906
+ handoff.cancel();
46858
47907
  deadline.dispose();
46859
47908
  cancellation.release();
46860
47909
  throw redactCredentialError(
@@ -47094,9 +48143,11 @@ function createFetchInterceptor(context) {
47094
48143
  body: { type: "oauth", refresh: "", access: "", expires: 0 }
47095
48144
  });
47096
48145
  },
47097
- refreshQuotaAfterSuccess: async (account, intervalMinutes) => {
48146
+ refreshQuotaAfterSuccess: async (account, intervalMinutes, signal) => {
48147
+ signal?.throwIfAborted();
47098
48148
  await context.assertAdmission?.();
47099
- await refreshQuotaAfterSuccess(account, intervalMinutes);
48149
+ signal?.throwIfAborted();
48150
+ await refreshQuotaAfterSuccess(account, intervalMinutes, signal);
47100
48151
  }
47101
48152
  },
47102
48153
  // The trackers the manager selects with: its own for a store-backed
@@ -47115,7 +48166,7 @@ function createFetchInterceptor(context) {
47115
48166
  let retired = false;
47116
48167
  let retirePromise;
47117
48168
  const entering = /* @__PURE__ */ new Set();
47118
- async function intercept(input2, init) {
48169
+ async function intercept(input2, init, onResponseHandoff) {
47119
48170
  await context.assertAdmission?.();
47120
48171
  if (disposed) throw new Error("The local request runtime is disposed");
47121
48172
  if (accountSource.kind === "pool-file") {
@@ -47123,9 +48174,9 @@ function createFetchInterceptor(context) {
47123
48174
  if (disposed) throw new Error("The local request runtime is disposed");
47124
48175
  if (!isOAuthAuth(latestAuth)) return upstreamFetch(input2, init);
47125
48176
  }
47126
- return executor.execute(input2, init);
48177
+ return executor.execute(input2, init, { onResponseHandoff });
47127
48178
  }
47128
- async function fetch(input2, init) {
48179
+ async function fetch(input2, init, onResponseHandoff) {
47129
48180
  if (disposed) {
47130
48181
  return upstreamFetch(input2, init);
47131
48182
  }
@@ -47133,7 +48184,7 @@ function createFetchInterceptor(context) {
47133
48184
  return upstreamFetch(input2, init);
47134
48185
  }
47135
48186
  if (retired) throw new Error("The local request runtime is retired");
47136
- const pending = intercept(input2, init);
48187
+ const pending = intercept(input2, init, onResponseHandoff);
47137
48188
  entering.add(pending);
47138
48189
  void pending.then(
47139
48190
  () => entering.delete(pending),