@cortexkit/opencode-antigravity-auth 3.0.7 → 3.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/dist/cli.js +1097 -78
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +128 -36
  4. package/dist/index.js +1523 -285
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +183 -64
  7. package/dist/server.js +1448 -189
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/auth-menu/login.d.ts +6 -10
  11. package/dist/src/common-auth-embedded/auth-menu/login.js +14 -11
  12. package/dist/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  13. package/dist/src/common-auth-embedded/claustrum/availability.js +106 -0
  14. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +36 -2
  15. package/dist/src/common-auth-embedded/claustrum/consumer.js +154 -6
  16. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +106 -14
  17. package/dist/src/common-auth-embedded/claustrum/custody.js +294 -16
  18. package/dist/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  19. package/dist/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  20. package/dist/src/common-auth-embedded/claustrum/index.js +4 -1
  21. package/dist/src/common-auth-embedded/claustrum/insula.d.ts +71 -0
  22. package/dist/src/common-auth-embedded/claustrum/insula.js +348 -21
  23. package/dist/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  24. package/dist/src/common-auth-embedded/claustrum/watch.js +254 -0
  25. package/dist/src/common-auth-embedded/fs/private-files.js +10 -2
  26. package/dist/src/common-auth-embedded/quota/format.d.ts +3 -0
  27. package/dist/src/common-auth-embedded/quota/format.js +69 -1
  28. package/dist/src/common-auth-embedded/quota/index.d.ts +1 -1
  29. package/dist/src/common-auth-embedded/quota/projection.d.ts +16 -0
  30. package/dist/src/common-auth-embedded/source-output.json +87 -55
  31. package/dist/src/ga/server/index.d.ts +2 -0
  32. package/dist/src/ga/server/index.d.ts.map +1 -1
  33. package/dist/src/ga/server/index.js +14 -1
  34. package/dist/src/ga/server/index.js.map +1 -1
  35. package/dist/src/plugin/auth-loader.d.ts +2 -1
  36. package/dist/src/plugin/auth-loader.d.ts.map +1 -1
  37. package/dist/src/plugin/auth-loader.js +5 -4
  38. package/dist/src/plugin/auth-loader.js.map +1 -1
  39. package/dist/src/plugin/background-vault-quota-refresh.d.ts.map +1 -1
  40. package/dist/src/plugin/background-vault-quota-refresh.js +8 -1
  41. package/dist/src/plugin/background-vault-quota-refresh.js.map +1 -1
  42. package/dist/src/plugin/fetch-interceptor.d.ts +2 -1
  43. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  44. package/dist/src/plugin/fetch-interceptor.js +8 -6
  45. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  46. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  47. package/dist/src/plugin/ga-location-services.js +3 -0
  48. package/dist/src/plugin/ga-location-services.js.map +1 -1
  49. package/dist/src/plugin/index.d.ts.map +1 -1
  50. package/dist/src/plugin/index.js +1 -0
  51. package/dist/src/plugin/index.js.map +1 -1
  52. package/dist/src/plugin/quota.d.ts +1 -1
  53. package/dist/src/plugin/quota.d.ts.map +1 -1
  54. package/dist/src/plugin/quota.js +17 -5
  55. package/dist/src/plugin/quota.js.map +1 -1
  56. package/dist/src/plugin/shared/after-handoff.d.ts +14 -0
  57. package/dist/src/plugin/shared/after-handoff.d.ts.map +1 -0
  58. package/dist/src/plugin/shared/after-handoff.js +89 -0
  59. package/dist/src/plugin/shared/after-handoff.js.map +1 -0
  60. package/dist/src/plugin/shared/request-services.d.ts +8 -2
  61. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  62. package/dist/src/plugin/shared/request-services.js +57 -36
  63. package/dist/src/plugin/shared/request-services.js.map +1 -1
  64. package/dist/src/plugin/shared/vault-request-credentials.d.ts +11 -8
  65. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  66. package/dist/src/plugin/shared/vault-request-credentials.js +23 -5
  67. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  68. package/dist/src/plugin/vault-custody.d.ts +4 -0
  69. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  70. package/dist/src/plugin/vault-custody.js +12 -0
  71. package/dist/src/plugin/vault-custody.js.map +1 -1
  72. package/dist/src/plugin/vault-insula-quota.d.ts +6 -0
  73. package/dist/src/plugin/vault-insula-quota.d.ts.map +1 -0
  74. package/dist/src/plugin/vault-insula-quota.js +50 -0
  75. package/dist/src/plugin/vault-insula-quota.js.map +1 -0
  76. package/dist/src/plugin/vault-quota-outcome.d.ts +1 -1
  77. package/dist/src/plugin/vault-quota-outcome.d.ts.map +1 -1
  78. package/dist/src/plugin/vault-quota-outcome.js.map +1 -1
  79. package/dist/src/tui.d.ts.map +1 -1
  80. package/dist/src/tui.js +82 -66
  81. package/dist/src/tui.js.map +1 -1
  82. package/dist/tui-build-map.json +27 -27
  83. package/dist/tui-ga-build-map.json +5 -5
  84. package/dist/types/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  85. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +36 -2
  86. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +106 -14
  87. package/dist/types/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  88. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  89. package/dist/types/src/common-auth-embedded/claustrum/insula.d.ts +71 -0
  90. package/dist/types/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  91. package/dist/types/src/common-auth-embedded/quota/format.d.ts +3 -0
  92. package/dist/types/src/common-auth-embedded/quota/index.d.ts +1 -1
  93. package/dist/types/src/common-auth-embedded/quota/projection.d.ts +16 -0
  94. package/dist/types/src/ga/server/index.d.ts +2 -0
  95. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  96. package/dist/types/src/plugin/auth-loader.d.ts +2 -1
  97. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  98. package/dist/types/src/plugin/background-vault-quota-refresh.d.ts.map +1 -1
  99. package/dist/types/src/plugin/fetch-interceptor.d.ts +2 -1
  100. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  101. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  102. package/dist/types/src/plugin/index.d.ts.map +1 -1
  103. package/dist/types/src/plugin/quota.d.ts +1 -1
  104. package/dist/types/src/plugin/quota.d.ts.map +1 -1
  105. package/dist/types/src/plugin/shared/after-handoff.d.ts +14 -0
  106. package/dist/types/src/plugin/shared/after-handoff.d.ts.map +1 -0
  107. package/dist/types/src/plugin/shared/request-services.d.ts +8 -2
  108. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  109. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +11 -8
  110. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  111. package/dist/types/src/plugin/vault-custody.d.ts +4 -0
  112. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  113. package/dist/types/src/plugin/vault-insula-quota.d.ts +6 -0
  114. package/dist/types/src/plugin/vault-insula-quota.d.ts.map +1 -0
  115. package/dist/types/src/plugin/vault-quota-outcome.d.ts +1 -1
  116. package/dist/types/src/plugin/vault-quota-outcome.d.ts.map +1 -1
  117. package/package.json +4 -4
  118. package/src/common-auth-embedded/auth-menu/login.d.ts +6 -10
  119. package/src/common-auth-embedded/auth-menu/login.js +14 -11
  120. package/src/common-auth-embedded/claustrum/availability.d.ts +89 -0
  121. package/src/common-auth-embedded/claustrum/availability.js +106 -0
  122. package/src/common-auth-embedded/claustrum/consumer.d.ts +36 -2
  123. package/src/common-auth-embedded/claustrum/consumer.js +154 -6
  124. package/src/common-auth-embedded/claustrum/custody.d.ts +106 -14
  125. package/src/common-auth-embedded/claustrum/custody.js +294 -16
  126. package/src/common-auth-embedded/claustrum/errors.d.ts +1 -0
  127. package/src/common-auth-embedded/claustrum/index.d.ts +5 -3
  128. package/src/common-auth-embedded/claustrum/index.js +4 -1
  129. package/src/common-auth-embedded/claustrum/insula.d.ts +71 -0
  130. package/src/common-auth-embedded/claustrum/insula.js +348 -21
  131. package/src/common-auth-embedded/claustrum/watch.d.ts +141 -0
  132. package/src/common-auth-embedded/claustrum/watch.js +254 -0
  133. package/src/common-auth-embedded/fs/private-files.js +10 -2
  134. package/src/common-auth-embedded/quota/format.d.ts +3 -0
  135. package/src/common-auth-embedded/quota/format.js +69 -1
  136. package/src/common-auth-embedded/quota/index.d.ts +1 -1
  137. package/src/common-auth-embedded/quota/projection.d.ts +16 -0
  138. package/src/common-auth-embedded/source-output.json +87 -55
  139. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +10 -2
  140. package/src/tui-compiled/common-auth-embedded/quota/format.js +69 -1
  141. package/src/tui-compiled/tui.js +123 -97
  142. package/src/tui-ga-compiled/shared/aef2402f8fc342f0-format.js +69 -1
  143. package/src/tui-ga-raw/shared/aef2402f8fc342f0-format.js +69 -1
  144. package/src/tui-raw/common-auth-embedded/fs/private-files.js +10 -2
  145. package/src/tui-raw/common-auth-embedded/quota/format.js +69 -1
  146. package/src/tui-raw/tui.tsx +126 -107
  147. package/src/tui.tsx +126 -107
@@ -3,8 +3,9 @@ import { combineAbortSignals } from '../util/any-signal.js';
3
3
  import { ClaustrumScopedCustody, decideScopedRetryAfter401, } from './custody.js';
4
4
  import { readClaustrumEnrollmentToken } from './enrollment.js';
5
5
  import { ClaustrumConsumerError } from './errors.js';
6
- import { acquireInsulaQuotaSource } from './insula.js';
6
+ import { acquireInsulaQuotaSource, } from './insula.js';
7
7
  import { acceptVaultRoute, declineVaultRoute, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, vaultRoutingRows, } from './roster.js';
8
+ import { SAFETY_POLL_MS } from './watch.js';
8
9
  /**
9
10
  * One plugin host's view of its vault accounts. It turns vault credentials
10
11
  * into rows for `/routing`, authorizes each physical send with the vault, and
@@ -29,6 +30,11 @@ export class ClaustrumConsumer {
29
30
  #timer;
30
31
  #started = false;
31
32
  #insula;
33
+ #vaultWatch;
34
+ #releaseInsulaWatch;
35
+ #insulaSkips = new Map();
36
+ /** When this instance last completed a discovery, by `now`. */
37
+ #discoveredAt;
32
38
  constructor(options) {
33
39
  this.#options = options;
34
40
  this.#logger = options.logger ?? createLogger('claustrum');
@@ -91,6 +97,8 @@ export class ClaustrumConsumer {
91
97
  requireAssertion: this.#options.requireAssertion,
92
98
  now: this.#options.now,
93
99
  logger: this.#logger,
100
+ setTimeoutImpl: this.#options.setTimeoutImpl,
101
+ clearTimeoutImpl: this.#options.clearTimeoutImpl,
94
102
  });
95
103
  if (this.#options.insula && client.insula) {
96
104
  this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
@@ -122,6 +130,27 @@ export class ClaustrumConsumer {
122
130
  ? latest.reach
123
131
  : undefined;
124
132
  }
133
+ /** How this consumer currently learns about changes, without I/O. */
134
+ watchState() {
135
+ return Object.freeze({
136
+ vault: this.#vaultWatch?.mode ?? 'polling',
137
+ ...(this.#options.insula && {
138
+ insula: this.#insula?.source.watchMode() ?? 'polling',
139
+ }),
140
+ });
141
+ }
142
+ /** Close the watches with the connection they belong to. */
143
+ #stopWatch() {
144
+ this.#vaultWatch?.close();
145
+ this.#vaultWatch = undefined;
146
+ this.#releaseInsulaWatch?.();
147
+ this.#releaseInsulaWatch = undefined;
148
+ }
149
+ /** Whether any account is using an in-memory outage receipt, without I/O. */
150
+ keptReceiptState() {
151
+ return (this.#custody?.keptReceiptState() ??
152
+ Object.freeze({ active: false, since: null }));
153
+ }
125
154
  /** Rows for `/routing`, from the last committed roster. */
126
155
  routingRows() {
127
156
  return vaultRoutingRows(this.#roster);
@@ -134,6 +163,7 @@ export class ClaustrumConsumer {
134
163
  if (!(await this.#active())) {
135
164
  this.#roster = undefined;
136
165
  this.#grantReach = undefined;
166
+ this.#stopWatch();
137
167
  this.#custody?.close();
138
168
  this.#custody = undefined;
139
169
  this.#insula?.release();
@@ -164,6 +194,7 @@ export class ClaustrumConsumer {
164
194
  this.#assertOpen();
165
195
  const changed = roster?.view !== this.#roster?.view;
166
196
  this.#roster = roster;
197
+ custody.retain(roster?.rows ?? []);
167
198
  // Each discovery replaces the previous value, including with unknown. A
168
199
  // refresh that served a peer's roster discovered nothing and leaves it;
169
200
  // grantReach() hides it once the roster's view no longer matches.
@@ -175,12 +206,23 @@ export class ClaustrumConsumer {
175
206
  // notification, and the poll runs every few seconds.
176
207
  if (roster && changed)
177
208
  this.#options.onRoster?.(roster);
209
+ this.#discoveredAt = (this.#options.now ?? Date.now)();
178
210
  return roster;
179
211
  })().finally(() => {
180
212
  this.#refreshing = undefined;
181
213
  });
182
214
  return this.#refreshing;
183
215
  }
216
+ /**
217
+ * Poll in the background and open the vault and insula watches. Until the
218
+ * vault watch is accepted, and whenever it is unavailable, every tick lists
219
+ * the vault exactly as before watches existed. While it is open a tick
220
+ * lists only when five minutes have passed since the last discovery, since
221
+ * the watch keeps no history; it still checks `isCustodyActive`, so a switch
222
+ * to local mode closes the connection as quickly as before. Insula is
223
+ * polled on the tick only while its own watch is not open. A host not in
224
+ * vault mode makes no request.
225
+ */
184
226
  start() {
185
227
  if (this.#started)
186
228
  return;
@@ -188,8 +230,10 @@ export class ClaustrumConsumer {
188
230
  this.#started = true;
189
231
  const tick = async () => {
190
232
  try {
191
- await this.refresh();
233
+ if (await this.#listDue())
234
+ await this.refresh();
192
235
  await this.refreshInsulaQuota();
236
+ this.#openWatch();
193
237
  }
194
238
  catch (error) {
195
239
  if (!this.#shutdown.signal.aborted)
@@ -208,6 +252,53 @@ export class ClaustrumConsumer {
208
252
  };
209
253
  void tick();
210
254
  }
255
+ /** Whether a background tick must list the vault now. */
256
+ async #listDue() {
257
+ if (this.#vaultWatch?.mode !== 'watching')
258
+ return true;
259
+ const now = (this.#options.now ?? Date.now)();
260
+ if (this.#discoveredAt === undefined ||
261
+ now - this.#discoveredAt >= SAFETY_POLL_MS)
262
+ return true;
263
+ // refresh() is what closes the connection when the host left vault mode.
264
+ return !(await this.#active());
265
+ }
266
+ /**
267
+ * Open the vault and insula watches once a vault connection exists. Only
268
+ * reached in vault mode: a host in local mode never connects.
269
+ */
270
+ #openWatch() {
271
+ const custody = this.#custody;
272
+ if (this.#shutdown.signal.aborted || !custody)
273
+ return;
274
+ // The same entry point a host without a consumer uses, so both apply
275
+ // notices, refusals and outages alike.
276
+ this.#vaultWatch ??= custody.watchRoster({
277
+ view: () => this.#roster?.view,
278
+ // The existing discovery, so a watched change commits the roster and
279
+ // re-applies it to kept receipts exactly as a poll does. A refresh
280
+ // already in flight may have listed before the change was announced,
281
+ // so wait for it and list again.
282
+ onView: async () => {
283
+ while (this.#refreshing)
284
+ await this.#refreshing.catch(() => { });
285
+ await this.refresh();
286
+ },
287
+ // Custody has dropped kept receipts, as a poll meeting the same
288
+ // refusal from list_scoped would.
289
+ onRefused: (error) => this.#options.onError?.(error),
290
+ onError: (error) => {
291
+ if (!this.#shutdown.signal.aborted)
292
+ this.#options.onError?.(error);
293
+ },
294
+ });
295
+ if (this.#options.insula && this.#insula && !this.#releaseInsulaWatch)
296
+ this.#releaseInsulaWatch = this.#insula.source.watch({
297
+ provider: this.#options.insula.provider,
298
+ setTimeoutImpl: this.#options.setTimeoutImpl,
299
+ clearTimeoutImpl: this.#options.clearTimeoutImpl,
300
+ });
301
+ }
211
302
  /**
212
303
  * Fetch on a background tick, at most once per minute across projects with
213
304
  * the same daemon and enrollment token path. Admission must use the cache
@@ -266,6 +357,44 @@ export class ClaustrumConsumer {
266
357
  return undefined;
267
358
  }
268
359
  }
360
+ /** Cache-only background lookup, preserving the reason a route has no reading. */
361
+ async lookupInsulaQuotaForRoute(routeId) {
362
+ const options = this.#options.insula;
363
+ if (!options || this.#shutdown.signal.aborted || !(await this.#active()))
364
+ return { miss: 'unreachable' };
365
+ try {
366
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
367
+ const roster = await readVaultRoster(this.#options.rosterPath);
368
+ const account = roster?.rows.find((row) => row.routeId === routeId)?.accountIdentity;
369
+ if (!account || !this.#insula)
370
+ return { miss: 'unreachable' };
371
+ const result = this.#insula.source.lookup(options.provider, account, (this.#options.now ?? Date.now)());
372
+ const reading = result.reading &&
373
+ options.normalize(result.reading.entry, result.reading.context);
374
+ if (result.miss)
375
+ return { miss: result.miss, ...(reading !== undefined && { reading }) };
376
+ // Refusing an echo or unsupported window leaves the plugin's poll in charge.
377
+ return reading === undefined ? { miss: 'unreachable' } : { reading };
378
+ }
379
+ catch {
380
+ return { miss: 'unreachable' };
381
+ }
382
+ }
383
+ /** Skip the fallback poll while insula is cold or its upstream fetch failed. */
384
+ async pollInsulaQuotaForRoute(routeId, fallback) {
385
+ const result = await this.lookupInsulaQuotaForRoute(routeId);
386
+ if (result.miss === 'cold' || result.miss === 'upstream-failed') {
387
+ if (this.#insulaSkips.get(routeId) !== result.miss) {
388
+ this.#insulaSkips.set(routeId, result.miss);
389
+ this.#logger.warn('skipped insula provider poll', {
390
+ reason: result.miss,
391
+ });
392
+ }
393
+ return undefined;
394
+ }
395
+ this.#insulaSkips.delete(routeId);
396
+ return result.miss ? fallback() : result.reading;
397
+ }
269
398
  #normalizeInsulaQuota(accountIdentity) {
270
399
  if (!this.#options.insula || !accountIdentity)
271
400
  return undefined;
@@ -282,20 +411,33 @@ export class ClaustrumConsumer {
282
411
  async authorize(routeId, signal) {
283
412
  this.#assertOpen(signal);
284
413
  const roster = this.#roster ?? (await this.#wait(this.refresh(), signal));
285
- if (!roster || !(await this.#active()))
414
+ if (!roster || !(await this.#active())) {
415
+ this.#custody?.close();
416
+ this.#custody = undefined;
417
+ this.#stopWatch();
418
+ this.#insula?.release();
419
+ this.#insula = undefined;
286
420
  throw new ClaustrumConsumerError('not-active', 'Claustrum scoped custody is not active');
421
+ }
287
422
  const current = await readVaultRoster(this.#options.rosterPath);
288
423
  this.#assertOpen(signal);
289
424
  const observed = roster.rows.find((row) => row.routeId === routeId);
290
425
  const configured = current?.rows.find((row) => row.routeId === routeId);
291
- if (configured && !configured.enabled)
426
+ if (configured && !configured.enabled) {
427
+ if (observed)
428
+ this.#custody?.forget(observed.credentialId);
292
429
  throw new ClaustrumConsumerError('route-declined', 'Claustrum route is disabled');
430
+ }
293
431
  if (!observed ||
294
432
  !configured ||
295
433
  configured.state !== 'active' ||
296
434
  configured.credentialId !== observed.credentialId ||
297
- configured.accountIdentity !== observed.accountIdentity)
435
+ configured.accountIdentity !== observed.accountIdentity ||
436
+ configured.credentialType !== observed.credentialType) {
437
+ if (observed)
438
+ this.#custody?.forget(observed.credentialId);
298
439
  throw new ClaustrumConsumerError('route-unavailable', 'Claustrum route is disabled, removed or changed');
440
+ }
299
441
  const custody = await this.#wait(this.#getCustody(), signal);
300
442
  const combined = combineAbortSignals([
301
443
  this.#shutdown.signal,
@@ -308,7 +450,7 @@ export class ClaustrumConsumer {
308
450
  ...(configured.accountIdentity !== undefined && {
309
451
  accountIdentity: configured.accountIdentity,
310
452
  }),
311
- }, combined.signal);
453
+ }, combined.signal, routeId);
312
454
  }
313
455
  finally {
314
456
  combined.dispose();
@@ -332,6 +474,10 @@ export class ClaustrumConsumer {
332
474
  const signal = options.signal;
333
475
  let served = await this.authorize(routeId, signal);
334
476
  let response = await dispatch(served, signal);
477
+ if (response.status === 401 && served.fromKeptReceipt) {
478
+ await this.reportFailure(served, 401, options.reporterSource ?? 'direct');
479
+ return response;
480
+ }
335
481
  if (response.status === 401 && !signal?.aborted) {
336
482
  let current;
337
483
  try {
@@ -366,6 +512,7 @@ export class ClaustrumConsumer {
366
512
  this.#assertOpen();
367
513
  await declineVaultRoute(this.#options.rosterPath, routeId);
368
514
  this.#roster = await readVaultRoster(this.#options.rosterPath);
515
+ this.#custody?.retain(this.#roster?.rows ?? []);
369
516
  }
370
517
  async accept(routeId) {
371
518
  this.#assertOpen();
@@ -421,6 +568,7 @@ export class ClaustrumConsumer {
421
568
  if (this.#timer)
422
569
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
423
570
  this.#timer = undefined;
571
+ this.#stopWatch();
424
572
  this.#custody?.close();
425
573
  this.#insula?.release();
426
574
  this.#insula = undefined;
@@ -1,9 +1,14 @@
1
1
  import { type ClaustrumClient, type ClaustrumReporterSource, type EnrollmentTokenFile } from '@cortexkit/claustrum-client';
2
2
  import { type ClaustrumLogger } from './errors.js';
3
3
  import type { InsulaUsageTransport } from './insula.js';
4
+ import { type ScopedWatchSource, type WatchMode } from './watch.js';
5
+ /**
6
+ * `watchScoped` is present from claustrum-client 0.12.0. Hosts detect it at
7
+ * run time and keep polling without it.
8
+ */
4
9
  export type ClaustrumScopedClient = Pick<ClaustrumClient, 'listScoped' | 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
5
10
  insula?: InsulaUsageTransport;
6
- };
11
+ } & ScopedWatchSource;
7
12
  /** The two credential types a plugin's family can hold; routing differs by type. */
8
13
  export type VaultCredentialType = 'oauth' | 'api_key';
9
14
  /**
@@ -132,6 +137,57 @@ export interface ClaustrumScopedAttempt {
132
137
  readonly accessToken: string;
133
138
  readonly recordVersion: number;
134
139
  readonly expiresAtMs: number | null;
140
+ /**
141
+ * True when this receipt was not freshly served but is the last token kept
142
+ * from an earlier read, used because the vault could not be reached. A 401
143
+ * with such a receipt must not be retried and is not reported to the vault,
144
+ * which is unreachable.
145
+ */
146
+ readonly fromKeptReceipt?: true;
147
+ }
148
+ export interface KeptReceiptState {
149
+ readonly active: boolean;
150
+ readonly since: number | null;
151
+ }
152
+ export interface ClaustrumRosterWatchOptions {
153
+ /**
154
+ * Run the host's own discovery (`custody.discover()`, then its roster
155
+ * commit). Called with the newest notice's view when that view differs from
156
+ * the last discovered one, when a notice shows a sequence gap or a new
157
+ * epoch, and on the first notice of a watch re-opened after a close (the
158
+ * time between two watches was not observed). One call runs at a time;
159
+ * notices that arrive meanwhile earn at most one more call, which runs only
160
+ * if the view still differs. A rejection goes to `onError`.
161
+ */
162
+ onView: (view: string) => unknown;
163
+ /**
164
+ * The view of the roster the host last committed. Defaults to the view of
165
+ * the last successful `custody.discover()` (outage probes excluded). Pass it
166
+ * when the host can commit a roster it did not list itself (a peer process
167
+ * held the discovery lease) or can fail after listing.
168
+ */
169
+ view?: () => string | undefined;
170
+ /**
171
+ * Called whenever the mode changes. The watch starts in `polling`. Keep the
172
+ * host's own list timer at its usual pace unless the mode is `watching`.
173
+ */
174
+ onMode?: (mode: WatchMode) => void;
175
+ /**
176
+ * The vault refused the watch, and its confirming `list_scoped` read it with
177
+ * this error (a revoked enrollment answers `not_found`). Custody has already
178
+ * applied it as it applies a refused discovery (`listFailed`: every kept
179
+ * receipt is dropped); handle it as the host handles that refusal.
180
+ */
181
+ onRefused?: (error: unknown) => void;
182
+ /** A failed `onView`, or a watch that could not be opened. */
183
+ onError?: (error: unknown) => void;
184
+ }
185
+ /** A vault watch held by a custody; see `ClaustrumScopedCustody.watchRoster`. */
186
+ export interface ClaustrumRosterWatch {
187
+ /** How the host currently learns about changes. */
188
+ readonly mode: WatchMode;
189
+ /** Stop the watch and its timers. Safe to call more than once. */
190
+ close(): void;
135
191
  }
136
192
  /** Reads the provider identity a served token executes under, when the plugin can tell. */
137
193
  export type IdentityParser = (accessToken: string) => string | undefined;
@@ -151,13 +207,15 @@ export declare function decideScopedRetryAfter401(site: string, served: Claustru
151
207
  * so it cannot expire while a long request is still using it.
152
208
  */
153
209
  export declare const SERVING_MARGIN_MS = 300000;
210
+ /** A kept receipt needs a minute of headroom, not the vault's refresh demand. */
211
+ export declare const KEPT_RECEIPT_MARGIN_MS = 60000;
154
212
  /**
155
213
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
156
- * enrollment token as authorization. Used by every host of a plugin. There is
157
- * deliberately no credential cache and no single-flight of credential reads:
158
- * each physical send is authorized by the vault, so a revoked enrollment or a
159
- * changed record takes effect on the next send. The enrollment token is
160
- * re-read per operation so an operator's reissue on disk is picked up.
214
+ * enrollment token as authorization. Used by every host of a plugin. Every
215
+ * physical send asks the vault first while reachable. Only an unreachable vault permits
216
+ * reuse of the last validated receipt, in memory and bounded by its expiry.
217
+ * The enrollment token is re-read per operation so revocation and disconnect
218
+ * still take effect without a process restart.
161
219
  */
162
220
  export declare class ClaustrumScopedCustody {
163
221
  #private;
@@ -177,7 +235,13 @@ export declare class ClaustrumScopedCustody {
177
235
  requireAssertion?: boolean;
178
236
  now?: () => number;
179
237
  logger?: ClaustrumLogger;
238
+ setTimeoutImpl?: typeof setTimeout;
239
+ clearTimeoutImpl?: typeof clearTimeout;
180
240
  });
241
+ /** A watch losing its transport is the same outage as an unreachable read. */
242
+ transportLost(error?: unknown): void;
243
+ /** Any vault answer ends transport fallback, even when it refuses access. */
244
+ reachable(): void;
181
245
  /**
182
246
  * List this consumer's credentials. A record that cannot be used is skipped
183
247
  * and warned about rather than failing the whole list, so one bad record
@@ -186,15 +250,23 @@ export declare class ClaustrumScopedCustody {
186
250
  */
187
251
  discover(signal?: AbortSignal): Promise<VaultInventory>;
188
252
  /**
189
- * Fetch the credential for one physical send and wrap it in a fresh receipt.
190
- * The vault's served identity (or, without one, the plugin's parse of the
191
- * token) must equal the roster's when both are present. Without
192
- * `requireAssertion`, absence on either side proves nothing and does not
193
- * refuse; the receipt records what the vault asserted separately from what
194
- * the roster expected. With it, a reply that does not itself name the
195
- * credential id and the expected account is refused.
253
+ * Apply a failed account listing: any answer from the vault (a refusal such
254
+ * as a revoked enrollment's `not_found`) drops every kept receipt, while an
255
+ * unreachable vault keeps them. A vault watch that ends with the same
256
+ * refusal calls this too, so both paths treat it alike.
196
257
  */
197
- authorize(identity: ClaustrumScopedIdentity, signal?: AbortSignal): Promise<ClaustrumScopedAttempt>;
258
+ listFailed(error: unknown): void;
259
+ /** Discard bearer material when a route is removed, declined or rebound. */
260
+ forget(credentialId: string): void;
261
+ /** Apply an already-held roster; this never fetches credentials or writes it. */
262
+ retain(identities: readonly (ClaustrumScopedIdentity & {
263
+ enabled: boolean;
264
+ state: string;
265
+ })[]): void;
266
+ /** A frozen, non-secret summary for a plugin's status display. */
267
+ keptReceiptState(): KeptReceiptState;
268
+ /** Ask the vault while reachable; retain one validated receipt in memory only. */
269
+ authorize(identity: ClaustrumScopedIdentity, signal?: AbortSignal, routeId?: string): Promise<ClaustrumScopedAttempt>;
198
270
  /**
199
271
  * Report that a send this consumer actually made was rejected. Only a 401
200
272
  * is reported (the vault refuses 429, 402 and 5xx reports), addressed by
@@ -203,5 +275,25 @@ export declare class ClaustrumScopedCustody {
203
275
  * custody did not issue is refused rather than reported.
204
276
  */
205
277
  reportFailure(attempt: ClaustrumScopedAttempt, status: number, reporterSource: ClaustrumReporterSource): Promise<void>;
278
+ /**
279
+ * Watch this consumer's visible vault accounts instead of listing them on a
280
+ * short timer. Opens one `watchScoped` on this custody's client and calls
281
+ * `onView` when the host must run its discovery (see
282
+ * `ClaustrumRosterWatchOptions`). A claustrum-client without `watchScoped`
283
+ * (before 0.12.0) or a vault that answers `unknown_method` reports
284
+ * `fallback` and opens nothing. A watch that closes before any notice was
285
+ * never accepted: the client reads once to learn why, and the watch reports
286
+ * `fallback` and tries one new watch after `WATCH_RETRY_MS`, never in a
287
+ * loop. A watch that closes after notices is re-opened after
288
+ * `RESUBSCRIBE_BACKOFF_MS`, doubling per close in a row. A lost transport
289
+ * starts this custody's outage, exactly as an unreachable call does, and
290
+ * the first notice of a watch ends it. Timers are unreferenced; `close()`
291
+ * on the returned watch or on this custody stops it.
292
+ *
293
+ * The watch keeps no history, so the host still lists on a slow timer while
294
+ * the mode is `watching`: every `SAFETY_POLL_MS` (five minutes). In any
295
+ * other mode the host keeps its usual list timer.
296
+ */
297
+ watchRoster(options: ClaustrumRosterWatchOptions): ClaustrumRosterWatch;
206
298
  close(): void;
207
299
  }