@cortexkit/antigravity-auth-core 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 (34) hide show
  1. package/dist/common-auth-embedded/auth-menu/login.d.ts +6 -10
  2. package/dist/common-auth-embedded/auth-menu/login.js +14 -11
  3. package/dist/common-auth-embedded/claustrum/availability.d.ts +89 -0
  4. package/dist/common-auth-embedded/claustrum/availability.js +106 -0
  5. package/dist/common-auth-embedded/claustrum/consumer.d.ts +36 -2
  6. package/dist/common-auth-embedded/claustrum/consumer.js +154 -6
  7. package/dist/common-auth-embedded/claustrum/custody.d.ts +106 -14
  8. package/dist/common-auth-embedded/claustrum/custody.js +294 -16
  9. package/dist/common-auth-embedded/claustrum/errors.d.ts +1 -0
  10. package/dist/common-auth-embedded/claustrum/index.d.ts +5 -3
  11. package/dist/common-auth-embedded/claustrum/index.js +4 -1
  12. package/dist/common-auth-embedded/claustrum/insula.d.ts +71 -0
  13. package/dist/common-auth-embedded/claustrum/insula.js +348 -21
  14. package/dist/common-auth-embedded/claustrum/watch.d.ts +141 -0
  15. package/dist/common-auth-embedded/claustrum/watch.js +254 -0
  16. package/dist/common-auth-embedded/fs/private-files.js +10 -2
  17. package/dist/common-auth-embedded/quota/format.d.ts +3 -0
  18. package/dist/common-auth-embedded/quota/format.js +69 -1
  19. package/dist/common-auth-embedded/quota/index.d.ts +1 -1
  20. package/dist/common-auth-embedded/quota/projection.d.ts +16 -0
  21. package/dist/common-auth-embedded/source-output.json +87 -55
  22. package/dist/constants.d.ts +5 -0
  23. package/dist/constants.d.ts.map +1 -1
  24. package/dist/constants.js +5 -0
  25. package/dist/constants.js.map +1 -1
  26. package/dist/quota-presentation.d.ts.map +1 -1
  27. package/dist/quota-presentation.js +9 -1
  28. package/dist/quota-presentation.js.map +1 -1
  29. package/dist/vault-account-source.d.ts +20 -3
  30. package/dist/vault-account-source.d.ts.map +1 -1
  31. package/dist/vault-account-source.js +45 -1
  32. package/dist/vault-account-source.js.map +1 -1
  33. package/dist/vault-folder-refusal.js +3 -3
  34. package/package.json +3 -3
@@ -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
  }
@@ -1,11 +1,15 @@
1
1
  import { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
2
2
  import { createLogger } from '../logger/index.js';
3
+ import { ClaustrumUnreachableError, classifyVaultFailure, } from './availability.js';
3
4
  import { readClaustrumEnrollmentToken } from './enrollment.js';
4
5
  import { ClaustrumConsumerError } from './errors.js';
5
6
  import { CUSTODY_PLACEHOLDER_PREFIX } from './host-slot.js';
7
+ import { ScopedRosterWatch, } from './watch.js';
6
8
  /** Only a new version of the same account may replace an in-flight 401. */
7
9
  export function isScopedCredentialRotation(served, current) {
8
10
  return (current !== undefined &&
11
+ !current.fromKeptReceipt &&
12
+ !served.fromKeptReceipt &&
9
13
  current.credentialId === served.credentialId &&
10
14
  current.accountIdentity === served.accountIdentity &&
11
15
  current.recordVersion !== served.recordVersion);
@@ -45,6 +49,8 @@ export function decideScopedRetryAfter401(site, served, current, logger = defaul
45
49
  * so it cannot expire while a long request is still using it.
46
50
  */
47
51
  export const SERVING_MARGIN_MS = 300_000;
52
+ /** A kept receipt needs a minute of headroom, not the vault's refresh demand. */
53
+ export const KEPT_RECEIPT_MARGIN_MS = 60_000;
48
54
  function invalidMaterial() {
49
55
  return new ClaustrumConsumerError('invalid-material', 'Claustrum returned invalid credential material');
50
56
  }
@@ -100,11 +106,11 @@ function grantReachOf(listed) {
100
106
  }
101
107
  /**
102
108
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
103
- * enrollment token as authorization. Used by every host of a plugin. There is
104
- * deliberately no credential cache and no single-flight of credential reads:
105
- * each physical send is authorized by the vault, so a revoked enrollment or a
106
- * changed record takes effect on the next send. The enrollment token is
107
- * re-read per operation so an operator's reissue on disk is picked up.
109
+ * enrollment token as authorization. Used by every host of a plugin. Every
110
+ * physical send asks the vault first while reachable. Only an unreachable vault permits
111
+ * reuse of the last validated receipt, in memory and bounded by its expiry.
112
+ * The enrollment token is re-read per operation so revocation and disconnect
113
+ * still take effect without a process restart.
108
114
  */
109
115
  export class ClaustrumScopedCustody {
110
116
  #client;
@@ -116,7 +122,20 @@ export class ClaustrumScopedCustody {
116
122
  #logger;
117
123
  #provenance = new WeakMap();
118
124
  #reports = new WeakMap();
125
+ #kept = new Map();
126
+ #keptAttempts = new WeakMap();
127
+ #setTimeout;
128
+ #clearTimeout;
129
+ #outage = false;
130
+ #outageError = new ClaustrumUnreachableError();
131
+ #probeTimer;
132
+ #probing = false;
133
+ #lastProbeAt = -Infinity;
134
+ #probeDelay = 2_000;
119
135
  #closed = false;
136
+ /** The view of the last successful `discover()`, for `watchRoster`. */
137
+ #discoveredView;
138
+ #watches = new Set();
120
139
  constructor(options) {
121
140
  const tokenPath = options.tokenPath;
122
141
  if (options.readToken) {
@@ -134,6 +153,65 @@ export class ClaustrumScopedCustody {
134
153
  this.#requireAssertion = options.requireAssertion ?? false;
135
154
  this.#now = options.now ?? Date.now;
136
155
  this.#logger = options.logger ?? defaultLogger;
156
+ this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
157
+ this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
158
+ }
159
+ /** A watch losing its transport is the same outage as an unreachable read. */
160
+ transportLost(error) {
161
+ if (this.#closed || this.#outage)
162
+ return;
163
+ this.#outage = true;
164
+ this.#outageError =
165
+ error instanceof ClaustrumCredentialError
166
+ ? error
167
+ : new ClaustrumUnreachableError();
168
+ this.#logger.warn('serving kept vault receipt', { reason: 'unreachable' });
169
+ this.#scheduleProbe();
170
+ }
171
+ /** Any vault answer ends transport fallback, even when it refuses access. */
172
+ reachable() {
173
+ if (this.#closed || !this.#outage)
174
+ return;
175
+ this.#outage = false;
176
+ if (this.#probeTimer)
177
+ this.#clearTimeout(this.#probeTimer);
178
+ this.#probeTimer = undefined;
179
+ this.#probeDelay = 2_000;
180
+ for (const kept of this.#kept.values())
181
+ kept.since = null;
182
+ (this.#logger.info ?? defaultLogger.info)('vault receipt serving resumed', { reason: 'reachable' });
183
+ }
184
+ #scheduleProbe() {
185
+ if (this.#closed || !this.#outage || this.#probeTimer || this.#probing)
186
+ return;
187
+ this.#probeTimer = this.#setTimeout(() => {
188
+ this.#probeTimer = undefined;
189
+ this.#probe(true);
190
+ }, this.#probeDelay);
191
+ this.#probeTimer.unref?.();
192
+ }
193
+ #probe(idle = false) {
194
+ if (this.#closed || !this.#outage || this.#probing)
195
+ return;
196
+ if (this.#now() - this.#lastProbeAt < 1_000) {
197
+ this.#scheduleProbe();
198
+ return;
199
+ }
200
+ this.#lastProbeAt = this.#now();
201
+ this.#probing = true;
202
+ // Both triggers share list_scoped discovery, including its receipt-drop rules.
203
+ // Sends never await discovery or let idle backoff delay the next send probe.
204
+ // A probe commits no roster, so it is not the host's discovery and does
205
+ // not move the view a roster watch compares notices against.
206
+ void this.#list()
207
+ .catch(() => {
208
+ if (idle && this.#outage)
209
+ this.#probeDelay = Math.min(this.#probeDelay * 2, 30_000);
210
+ })
211
+ .finally(() => {
212
+ this.#probing = false;
213
+ this.#scheduleProbe();
214
+ });
137
215
  }
138
216
  #check(signal) {
139
217
  if (this.#closed)
@@ -172,17 +250,24 @@ export class ClaustrumScopedCustody {
172
250
  }
173
251
  catch (error) {
174
252
  this.#check(signal);
253
+ if (classifyVaultFailure(error) === 'unreachable')
254
+ this.transportLost(error);
255
+ else
256
+ this.reachable();
175
257
  // Keep the vault's own refusals (ClaustrumCredentialError, carrying
176
258
  // code, class and action); replace any other error, whose text may echo
177
259
  // request params that include the enrollment token.
178
260
  if (error instanceof ClaustrumCredentialError)
179
261
  throw error;
262
+ if (classifyVaultFailure(error) === 'unreachable')
263
+ throw new ClaustrumUnreachableError();
180
264
  throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation unavailable');
181
265
  }
182
266
  finally {
183
267
  removeAbortListener?.();
184
268
  }
185
269
  this.#check(signal);
270
+ this.reachable();
186
271
  return result;
187
272
  }
188
273
  /**
@@ -192,8 +277,27 @@ export class ClaustrumScopedCustody {
192
277
  * skipped records: they simply are not this consumer's.
193
278
  */
194
279
  async discover(signal) {
195
- const token = await this.#token(signal);
196
- const inventory = await this.#call(() => this.#client.listScoped(token), signal);
280
+ const inventory = await this.#list(signal);
281
+ this.#discoveredView = inventory.view;
282
+ return inventory;
283
+ }
284
+ async #list(signal) {
285
+ let inventory;
286
+ let token;
287
+ try {
288
+ token = await this.#token(signal);
289
+ }
290
+ catch (error) {
291
+ this.#kept.clear();
292
+ throw error;
293
+ }
294
+ try {
295
+ inventory = await this.#call(() => this.#client.listScoped(token), signal);
296
+ }
297
+ catch (error) {
298
+ this.listFailed(error);
299
+ throw error;
300
+ }
197
301
  const skipped = [];
198
302
  const candidates = [];
199
303
  const counts = new Map();
@@ -241,22 +345,119 @@ export class ClaustrumScopedCustody {
241
345
  };
242
346
  }
243
347
  /**
244
- * Fetch the credential for one physical send and wrap it in a fresh receipt.
245
- * The vault's served identity (or, without one, the plugin's parse of the
246
- * token) must equal the roster's when both are present. Without
247
- * `requireAssertion`, absence on either side proves nothing and does not
248
- * refuse; the receipt records what the vault asserted separately from what
249
- * the roster expected. With it, a reply that does not itself name the
250
- * credential id and the expected account is refused.
348
+ * Apply a failed account listing: any answer from the vault (a refusal such
349
+ * as a revoked enrollment's `not_found`) drops every kept receipt, while an
350
+ * unreachable vault keeps them. A vault watch that ends with the same
351
+ * refusal calls this too, so both paths treat it alike.
251
352
  */
252
- async authorize(identity, signal) {
353
+ listFailed(error) {
354
+ if (classifyVaultFailure(error) === 'unreachable')
355
+ this.transportLost(error);
356
+ else {
357
+ this.reachable();
358
+ this.#kept.clear();
359
+ }
360
+ }
361
+ /** Discard bearer material when a route is removed, declined or rebound. */
362
+ forget(credentialId) {
363
+ this.#kept.delete(credentialId);
364
+ }
365
+ /** Apply an already-held roster; this never fetches credentials or writes it. */
366
+ retain(identities) {
367
+ const current = new Map(identities.map((identity) => [identity.credentialId, identity]));
368
+ for (const [id, kept] of this.#kept) {
369
+ const identity = current.get(id);
370
+ if (!identity?.enabled ||
371
+ identity.state !== 'active' ||
372
+ identity.credentialType !== kept.attempt.credentialType ||
373
+ identity.accountIdentity !== kept.attempt.expectedAccountIdentity)
374
+ this.forget(id);
375
+ }
376
+ }
377
+ /** A frozen, non-secret summary for a plugin's status display. */
378
+ keptReceiptState() {
379
+ let since = null;
380
+ for (const [id, kept] of this.#kept) {
381
+ if (!this.#usable(kept.attempt)) {
382
+ this.forget(id);
383
+ continue;
384
+ }
385
+ if (kept.since !== null)
386
+ since = Math.min(since ?? kept.since, kept.since);
387
+ }
388
+ return Object.freeze({ active: since !== null, since });
389
+ }
390
+ #usable(attempt) {
391
+ return attempt.expiresAtMs === null
392
+ ? attempt.credentialType === 'api_key'
393
+ : attempt.expiresAtMs - this.#now() > KEPT_RECEIPT_MARGIN_MS;
394
+ }
395
+ /** Ask the vault while reachable; retain one validated receipt in memory only. */
396
+ async authorize(identity, signal, routeId = 'vault') {
397
+ this.#check(signal);
398
+ const { credentialId, credentialType, accountIdentity } = identity;
399
+ let kept = this.#kept.get(credentialId);
400
+ if (kept &&
401
+ (kept.attempt.credentialType !== credentialType ||
402
+ kept.attempt.expectedAccountIdentity !== accountIdentity)) {
403
+ this.forget(credentialId);
404
+ kept = undefined;
405
+ }
406
+ // A missing or invalid enrollment is not a transport outage.
407
+ let token;
408
+ try {
409
+ token = await this.#token(signal);
410
+ }
411
+ catch (error) {
412
+ this.#kept.clear();
413
+ throw error;
414
+ }
415
+ if (this.#outage && kept) {
416
+ this.#probe();
417
+ return this.#serveKept(credentialId, kept, token, routeId);
418
+ }
419
+ try {
420
+ const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
421
+ this.#kept.set(credentialId, { attempt, routeId, since: null });
422
+ return attempt;
423
+ }
424
+ catch (error) {
425
+ this.#check(signal);
426
+ if (classifyVaultFailure(error) !== 'unreachable') {
427
+ this.forget(credentialId);
428
+ throw error;
429
+ }
430
+ return this.#serveKept(credentialId, kept, token, routeId, error);
431
+ }
432
+ }
433
+ #serveKept(credentialId, kept, token, routeId, error = this.#outageError) {
434
+ // A concurrent refusal or 401 may already have discarded this entry.
435
+ if (!kept ||
436
+ this.#kept.get(credentialId) !== kept ||
437
+ !this.#usable(kept.attempt)) {
438
+ this.forget(credentialId);
439
+ throw error;
440
+ }
441
+ if (kept.since === null)
442
+ kept.since = this.#now();
443
+ const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, 'accessToken', { value: kept.attempt.accessToken, enumerable: false }));
444
+ this.#provenance.set(attempt, token);
445
+ this.#keptAttempts.set(attempt, routeId);
446
+ return attempt;
447
+ }
448
+ /**
449
+ * Fetch and validate a fresh receipt before retaining it. The vault assertion
450
+ * (or the plugin's token parse) must agree with the roster when both exist.
451
+ * With requireAssertion, an absent assertion also refuses rather than
452
+ * treating the roster's expectation as proof of the served account.
453
+ */
454
+ async #authorizeFresh(identity, token, signal) {
253
455
  if (!identity.credentialId)
254
456
  throw new ClaustrumConsumerError('route-unavailable', 'Claustrum dispatch requires a credential id');
255
457
  // Capture the caller's fields before yielding so a later mutation cannot move the fence.
256
458
  const { credentialId, credentialType, accountIdentity } = identity;
257
459
  if (this.#requireAssertion && accountIdentity === undefined)
258
460
  throw new ClaustrumConsumerError('identity-unasserted', 'Claustrum dispatch requires a known account identity');
259
- const token = await this.#token(signal);
260
461
  const served = await this.#call(() => this.#client.getScoped({
261
462
  credentialId,
262
463
  enrollmentToken: token,
@@ -338,6 +539,21 @@ export class ClaustrumScopedCustody {
338
539
  const token = this.#provenance.get(attempt);
339
540
  if (!token)
340
541
  throw new ClaustrumConsumerError('no-receipt', 'Claustrum failure report requires an original dispatch receipt');
542
+ const keptRoute = this.#keptAttempts.get(attempt);
543
+ if (keptRoute !== undefined) {
544
+ this.forget(attempt.credentialId);
545
+ this.#logger.debug('scoped 401 not reported', {
546
+ routeId: keptRoute,
547
+ reason: 'kept-receipt',
548
+ });
549
+ return;
550
+ }
551
+ // The provider rejected this token, so it must not come back as a kept
552
+ // receipt during a later outage. Drop it before reporting, so a report that
553
+ // fails because the vault is unreachable still drops it.
554
+ const kept = this.#kept.get(attempt.credentialId);
555
+ if (kept && kept.attempt.recordVersion === attempt.recordVersion)
556
+ this.forget(attempt.credentialId);
341
557
  const pending = this.#reports.get(attempt);
342
558
  if (pending)
343
559
  return pending;
@@ -362,10 +578,72 @@ export class ClaustrumScopedCustody {
362
578
  throw error;
363
579
  }
364
580
  }
581
+ /**
582
+ * Watch this consumer's visible vault accounts instead of listing them on a
583
+ * short timer. Opens one `watchScoped` on this custody's client and calls
584
+ * `onView` when the host must run its discovery (see
585
+ * `ClaustrumRosterWatchOptions`). A claustrum-client without `watchScoped`
586
+ * (before 0.12.0) or a vault that answers `unknown_method` reports
587
+ * `fallback` and opens nothing. A watch that closes before any notice was
588
+ * never accepted: the client reads once to learn why, and the watch reports
589
+ * `fallback` and tries one new watch after `WATCH_RETRY_MS`, never in a
590
+ * loop. A watch that closes after notices is re-opened after
591
+ * `RESUBSCRIBE_BACKOFF_MS`, doubling per close in a row. A lost transport
592
+ * starts this custody's outage, exactly as an unreachable call does, and
593
+ * the first notice of a watch ends it. Timers are unreferenced; `close()`
594
+ * on the returned watch or on this custody stops it.
595
+ *
596
+ * The watch keeps no history, so the host still lists on a slow timer while
597
+ * the mode is `watching`: every `SAFETY_POLL_MS` (five minutes). In any
598
+ * other mode the host keeps its usual list timer.
599
+ */
600
+ watchRoster(options) {
601
+ this.#check();
602
+ const watch = new ScopedRosterWatch({
603
+ client: this.#client,
604
+ enrollmentToken: () => this.#token(),
605
+ view: options.view ?? (() => this.#discoveredView),
606
+ discover: async (view) => {
607
+ await options.onView(view);
608
+ },
609
+ onRefused: (error) => {
610
+ // Apply a refused watch as discover() applies a refused account
611
+ // listing: every kept receipt is dropped.
612
+ this.listFailed(error);
613
+ options.onRefused?.(error);
614
+ },
615
+ onTransportLost: () => this.transportLost(),
616
+ onReachable: () => this.reachable(),
617
+ onError: options.onError,
618
+ onMode: options.onMode,
619
+ logger: this.#logger,
620
+ now: this.#now,
621
+ setTimeoutImpl: this.#setTimeout,
622
+ clearTimeoutImpl: this.#clearTimeout,
623
+ });
624
+ this.#watches.add(watch);
625
+ watch.start();
626
+ return {
627
+ get mode() {
628
+ return watch.mode;
629
+ },
630
+ close: () => {
631
+ this.#watches.delete(watch);
632
+ watch.stop();
633
+ },
634
+ };
635
+ }
365
636
  close() {
366
637
  if (this.#closed)
367
638
  return;
368
639
  this.#closed = true;
640
+ if (this.#probeTimer)
641
+ this.#clearTimeout(this.#probeTimer);
642
+ this.#probeTimer = undefined;
643
+ for (const watch of this.#watches)
644
+ watch.stop();
645
+ this.#watches.clear();
646
+ this.#kept.clear();
369
647
  this.#client.close();
370
648
  }
371
649
  }
@@ -11,6 +11,7 @@ export declare class ClaustrumConsumerError extends Error {
11
11
  }
12
12
  /** The structural logger every class here accepts; `/logger`'s `createLogger` satisfies it. */
13
13
  export interface ClaustrumLogger {
14
+ info?(message: string, data?: unknown): void;
14
15
  warn(message: string, data?: unknown): void;
15
16
  debug(message: string, data?: unknown): void;
16
17
  }
@@ -1,14 +1,16 @@
1
1
  import { type ClaustrumClientOptions } from '@cortexkit/claustrum-client';
2
2
  import type { ClaustrumScopedClient } from './custody.js';
3
3
  export { ClaustrumCredentialError, type ClaustrumReporterSource, type EnrollmentTokenFile, } from '@cortexkit/claustrum-client';
4
- export { ClaustrumConsumer, type ClaustrumConsumerOptions, type SendOptions, } from './consumer.js';
5
- export { type AccountIdentitySource, type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, } from './custody.js';
4
+ export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, type VaultFailureClass, } from './availability.js';
5
+ export { ClaustrumConsumer, type ClaustrumConsumerOptions, type ClaustrumWatchState, type SendOptions, } from './consumer.js';
6
+ export { type AccountIdentitySource, type ClaustrumFamily, type ClaustrumRosterWatch, type ClaustrumRosterWatchOptions, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, type KeptReceiptState, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, } from './custody.js';
6
7
  export { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentConnection, type ClaustrumEnrollmentDisconnectResult, ClaustrumEnrollmentManager, type ClaustrumEnrollmentPaths, type ClaustrumEnrollmentResetResult, type ClaustrumEnrollmentStatus, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, type EnrollmentDisposition, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
7
8
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
8
9
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, type HostSlotContent, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
9
- export type { InsulaQuotaContext, InsulaQuotaOptions, InsulaUsageEntry, InsulaUsageTransport, InsulaUsageWindow, } from './insula.js';
10
+ export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaLookup, type InsulaQuotaMiss, type InsulaQuotaOptions, type InsulaQuotaReading, type InsulaQuotaResult, type InsulaQuotaSource, type InsulaUsageEntry, type InsulaUsageTransport, type InsulaUsageWatch, type InsulaUsageWindow, type InsulaWatchOptions, } from './insula.js';
10
11
  export { acceptAccount, type DeclinedAccount, declineAccount, isDeclined, } from './interlock.js';
11
12
  export { type AccountMapper, acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, type MutateVaultRosterOptions, mutateVaultRoster, type ProjectionOptions, projectVaultRoster, type QuotaReceipt, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, type VaultPrimary, type VaultPrimaryBinding, type VaultPrimaryUnavailableReason, type VaultRosterFile, type VaultRosterLockContext, type VaultRosterRow, vaultRoutingRows, } from './roster.js';
13
+ export { type ChangeNotice, ChangeNoticeReader, RESUBSCRIBE_BACKOFF_MS, SAFETY_POLL_MS, ScopedRosterWatch, type ScopedRosterWatchOptions, type ScopedWatchEnd, type ScopedWatchHandle, type ScopedWatchNoticeShape, type ScopedWatchSource, WATCH_RETRY_MS, type WatchMode, } from './watch.js';
12
14
  /**
13
15
  * Connect the client that lists and fetches this consumer's vault credentials
14
16
  * on the request path. `connectionFile` is required: this library
@@ -6,13 +6,16 @@
6
6
  import { ClaustrumClient, } from '@cortexkit/claustrum-client';
7
7
  import { insulaUsageTransport } from './insula.js';
8
8
  export { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
9
+ export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, } from './availability.js';
9
10
  export { ClaustrumConsumer, } from './consumer.js';
10
- export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, SERVING_MARGIN_MS, } from './custody.js';
11
+ export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, KEPT_RECEIPT_MARGIN_MS, SERVING_MARGIN_MS, } from './custody.js';
11
12
  export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
12
13
  export { ClaustrumConsumerError, } from './errors.js';
13
14
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
15
+ export { acquireInsulaQuotaSource, } from './insula.js';
14
16
  export { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
15
17
  export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from './roster.js';
18
+ export { ChangeNoticeReader, RESUBSCRIBE_BACKOFF_MS, SAFETY_POLL_MS, ScopedRosterWatch, WATCH_RETRY_MS, } from './watch.js';
16
19
  /**
17
20
  * Connect the client that lists and fetches this consumer's vault credentials
18
21
  * on the request path. `connectionFile` is required: this library