@cortexkit/common-auth 0.19.1 → 0.21.0

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.
@@ -1,11 +1,14 @@
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';
6
7
  /** Only a new version of the same account may replace an in-flight 401. */
7
8
  export function isScopedCredentialRotation(served, current) {
8
9
  return (current !== undefined &&
10
+ !current.fromKeptReceipt &&
11
+ !served.fromKeptReceipt &&
9
12
  current.credentialId === served.credentialId &&
10
13
  current.accountIdentity === served.accountIdentity &&
11
14
  current.recordVersion !== served.recordVersion);
@@ -45,6 +48,8 @@ export function decideScopedRetryAfter401(site, served, current, logger = defaul
45
48
  * so it cannot expire while a long request is still using it.
46
49
  */
47
50
  export const SERVING_MARGIN_MS = 300_000;
51
+ /** A kept receipt needs a minute of headroom, not the vault's refresh demand. */
52
+ export const KEPT_RECEIPT_MARGIN_MS = 60_000;
48
53
  function invalidMaterial() {
49
54
  return new ClaustrumConsumerError('invalid-material', 'Claustrum returned invalid credential material');
50
55
  }
@@ -100,11 +105,11 @@ function grantReachOf(listed) {
100
105
  }
101
106
  /**
102
107
  * 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.
108
+ * enrollment token as authorization. Used by every host of a plugin. Every
109
+ * physical send asks the vault first while reachable. Only an unreachable vault permits
110
+ * reuse of the last validated receipt, in memory and bounded by its expiry.
111
+ * The enrollment token is re-read per operation so revocation and disconnect
112
+ * still take effect without a process restart.
108
113
  */
109
114
  export class ClaustrumScopedCustody {
110
115
  #client;
@@ -116,6 +121,16 @@ export class ClaustrumScopedCustody {
116
121
  #logger;
117
122
  #provenance = new WeakMap();
118
123
  #reports = new WeakMap();
124
+ #kept = new Map();
125
+ #keptAttempts = new WeakMap();
126
+ #setTimeout;
127
+ #clearTimeout;
128
+ #outage = false;
129
+ #outageError = new ClaustrumUnreachableError();
130
+ #probeTimer;
131
+ #probing = false;
132
+ #lastProbeAt = -Infinity;
133
+ #probeDelay = 2_000;
119
134
  #closed = false;
120
135
  constructor(options) {
121
136
  const tokenPath = options.tokenPath;
@@ -134,6 +149,63 @@ export class ClaustrumScopedCustody {
134
149
  this.#requireAssertion = options.requireAssertion ?? false;
135
150
  this.#now = options.now ?? Date.now;
136
151
  this.#logger = options.logger ?? defaultLogger;
152
+ this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
153
+ this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
154
+ }
155
+ /** A watch losing its transport is the same outage as an unreachable read. */
156
+ transportLost(error) {
157
+ if (this.#closed || this.#outage)
158
+ return;
159
+ this.#outage = true;
160
+ this.#outageError =
161
+ error instanceof ClaustrumCredentialError
162
+ ? error
163
+ : new ClaustrumUnreachableError();
164
+ this.#logger.warn('serving kept vault receipt', { reason: 'unreachable' });
165
+ this.#scheduleProbe();
166
+ }
167
+ /** Any vault answer ends transport fallback, even when it refuses access. */
168
+ reachable() {
169
+ if (this.#closed || !this.#outage)
170
+ return;
171
+ this.#outage = false;
172
+ if (this.#probeTimer)
173
+ this.#clearTimeout(this.#probeTimer);
174
+ this.#probeTimer = undefined;
175
+ this.#probeDelay = 2_000;
176
+ for (const kept of this.#kept.values())
177
+ kept.since = null;
178
+ (this.#logger.info ?? defaultLogger.info)('vault receipt serving resumed', { reason: 'reachable' });
179
+ }
180
+ #scheduleProbe() {
181
+ if (this.#closed || !this.#outage || this.#probeTimer || this.#probing)
182
+ return;
183
+ this.#probeTimer = this.#setTimeout(() => {
184
+ this.#probeTimer = undefined;
185
+ this.#probe(true);
186
+ }, this.#probeDelay);
187
+ this.#probeTimer.unref?.();
188
+ }
189
+ #probe(idle = false) {
190
+ if (this.#closed || !this.#outage || this.#probing)
191
+ return;
192
+ if (this.#now() - this.#lastProbeAt < 1_000) {
193
+ this.#scheduleProbe();
194
+ return;
195
+ }
196
+ this.#lastProbeAt = this.#now();
197
+ this.#probing = true;
198
+ // Both triggers share list_scoped discovery, including its receipt-drop rules.
199
+ // Sends never await discovery or let idle backoff delay the next send probe.
200
+ void this.discover()
201
+ .catch(() => {
202
+ if (idle && this.#outage)
203
+ this.#probeDelay = Math.min(this.#probeDelay * 2, 30_000);
204
+ })
205
+ .finally(() => {
206
+ this.#probing = false;
207
+ this.#scheduleProbe();
208
+ });
137
209
  }
138
210
  #check(signal) {
139
211
  if (this.#closed)
@@ -172,17 +244,24 @@ export class ClaustrumScopedCustody {
172
244
  }
173
245
  catch (error) {
174
246
  this.#check(signal);
247
+ if (classifyVaultFailure(error) === 'unreachable')
248
+ this.transportLost(error);
249
+ else
250
+ this.reachable();
175
251
  // Keep the vault's own refusals (ClaustrumCredentialError, carrying
176
252
  // code, class and action); replace any other error, whose text may echo
177
253
  // request params that include the enrollment token.
178
254
  if (error instanceof ClaustrumCredentialError)
179
255
  throw error;
256
+ if (classifyVaultFailure(error) === 'unreachable')
257
+ throw new ClaustrumUnreachableError();
180
258
  throw new ClaustrumConsumerError('unavailable', 'Claustrum scoped operation unavailable');
181
259
  }
182
260
  finally {
183
261
  removeAbortListener?.();
184
262
  }
185
263
  this.#check(signal);
264
+ this.reachable();
186
265
  return result;
187
266
  }
188
267
  /**
@@ -192,8 +271,22 @@ export class ClaustrumScopedCustody {
192
271
  * skipped records: they simply are not this consumer's.
193
272
  */
194
273
  async discover(signal) {
195
- const token = await this.#token(signal);
196
- const inventory = await this.#call(() => this.#client.listScoped(token), signal);
274
+ let inventory;
275
+ let token;
276
+ try {
277
+ token = await this.#token(signal);
278
+ }
279
+ catch (error) {
280
+ this.#kept.clear();
281
+ throw error;
282
+ }
283
+ try {
284
+ inventory = await this.#call(() => this.#client.listScoped(token), signal);
285
+ }
286
+ catch (error) {
287
+ this.listFailed(error);
288
+ throw error;
289
+ }
197
290
  const skipped = [];
198
291
  const candidates = [];
199
292
  const counts = new Map();
@@ -241,22 +334,119 @@ export class ClaustrumScopedCustody {
241
334
  };
242
335
  }
243
336
  /**
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.
337
+ * Apply a failed account listing: any answer from the vault (a refusal such
338
+ * as a revoked enrollment's `not_found`) drops every kept receipt, while an
339
+ * unreachable vault keeps them. A vault watch that ends with the same
340
+ * refusal calls this too, so both paths treat it alike.
341
+ */
342
+ listFailed(error) {
343
+ if (classifyVaultFailure(error) === 'unreachable')
344
+ this.transportLost(error);
345
+ else {
346
+ this.reachable();
347
+ this.#kept.clear();
348
+ }
349
+ }
350
+ /** Discard bearer material when a route is removed, declined or rebound. */
351
+ forget(credentialId) {
352
+ this.#kept.delete(credentialId);
353
+ }
354
+ /** Apply an already-held roster; this never fetches credentials or writes it. */
355
+ retain(identities) {
356
+ const current = new Map(identities.map((identity) => [identity.credentialId, identity]));
357
+ for (const [id, kept] of this.#kept) {
358
+ const identity = current.get(id);
359
+ if (!identity?.enabled ||
360
+ identity.state !== 'active' ||
361
+ identity.credentialType !== kept.attempt.credentialType ||
362
+ identity.accountIdentity !== kept.attempt.expectedAccountIdentity)
363
+ this.forget(id);
364
+ }
365
+ }
366
+ /** A frozen, non-secret summary for a plugin's status display. */
367
+ keptReceiptState() {
368
+ let since = null;
369
+ for (const [id, kept] of this.#kept) {
370
+ if (!this.#usable(kept.attempt)) {
371
+ this.forget(id);
372
+ continue;
373
+ }
374
+ if (kept.since !== null)
375
+ since = Math.min(since ?? kept.since, kept.since);
376
+ }
377
+ return Object.freeze({ active: since !== null, since });
378
+ }
379
+ #usable(attempt) {
380
+ return attempt.expiresAtMs === null
381
+ ? attempt.credentialType === 'api_key'
382
+ : attempt.expiresAtMs - this.#now() > KEPT_RECEIPT_MARGIN_MS;
383
+ }
384
+ /** Ask the vault while reachable; retain one validated receipt in memory only. */
385
+ async authorize(identity, signal, routeId = 'vault') {
386
+ this.#check(signal);
387
+ const { credentialId, credentialType, accountIdentity } = identity;
388
+ let kept = this.#kept.get(credentialId);
389
+ if (kept &&
390
+ (kept.attempt.credentialType !== credentialType ||
391
+ kept.attempt.expectedAccountIdentity !== accountIdentity)) {
392
+ this.forget(credentialId);
393
+ kept = undefined;
394
+ }
395
+ // A missing or invalid enrollment is not a transport outage.
396
+ let token;
397
+ try {
398
+ token = await this.#token(signal);
399
+ }
400
+ catch (error) {
401
+ this.#kept.clear();
402
+ throw error;
403
+ }
404
+ if (this.#outage && kept) {
405
+ this.#probe();
406
+ return this.#serveKept(credentialId, kept, token, routeId);
407
+ }
408
+ try {
409
+ const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
410
+ this.#kept.set(credentialId, { attempt, routeId, since: null });
411
+ return attempt;
412
+ }
413
+ catch (error) {
414
+ this.#check(signal);
415
+ if (classifyVaultFailure(error) !== 'unreachable') {
416
+ this.forget(credentialId);
417
+ throw error;
418
+ }
419
+ return this.#serveKept(credentialId, kept, token, routeId, error);
420
+ }
421
+ }
422
+ #serveKept(credentialId, kept, token, routeId, error = this.#outageError) {
423
+ // A concurrent refusal or 401 may already have discarded this entry.
424
+ if (!kept ||
425
+ this.#kept.get(credentialId) !== kept ||
426
+ !this.#usable(kept.attempt)) {
427
+ this.forget(credentialId);
428
+ throw error;
429
+ }
430
+ if (kept.since === null)
431
+ kept.since = this.#now();
432
+ const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, 'accessToken', { value: kept.attempt.accessToken, enumerable: false }));
433
+ this.#provenance.set(attempt, token);
434
+ this.#keptAttempts.set(attempt, routeId);
435
+ return attempt;
436
+ }
437
+ /**
438
+ * Fetch and validate a fresh receipt before retaining it. The vault assertion
439
+ * (or the plugin's token parse) must agree with the roster when both exist.
440
+ * With requireAssertion, an absent assertion also refuses rather than
441
+ * treating the roster's expectation as proof of the served account.
251
442
  */
252
- async authorize(identity, signal) {
443
+ async #authorizeFresh(identity, token, signal) {
253
444
  if (!identity.credentialId)
254
445
  throw new ClaustrumConsumerError('route-unavailable', 'Claustrum dispatch requires a credential id');
255
446
  // Capture the caller's fields before yielding so a later mutation cannot move the fence.
256
447
  const { credentialId, credentialType, accountIdentity } = identity;
257
448
  if (this.#requireAssertion && accountIdentity === undefined)
258
449
  throw new ClaustrumConsumerError('identity-unasserted', 'Claustrum dispatch requires a known account identity');
259
- const token = await this.#token(signal);
260
450
  const served = await this.#call(() => this.#client.getScoped({
261
451
  credentialId,
262
452
  enrollmentToken: token,
@@ -338,6 +528,21 @@ export class ClaustrumScopedCustody {
338
528
  const token = this.#provenance.get(attempt);
339
529
  if (!token)
340
530
  throw new ClaustrumConsumerError('no-receipt', 'Claustrum failure report requires an original dispatch receipt');
531
+ const keptRoute = this.#keptAttempts.get(attempt);
532
+ if (keptRoute !== undefined) {
533
+ this.forget(attempt.credentialId);
534
+ this.#logger.debug('scoped 401 not reported', {
535
+ routeId: keptRoute,
536
+ reason: 'kept-receipt',
537
+ });
538
+ return;
539
+ }
540
+ // The provider rejected this token, so it must not come back as a kept
541
+ // receipt during a later outage. Drop it before reporting, so a report that
542
+ // fails because the vault is unreachable still drops it.
543
+ const kept = this.#kept.get(attempt.credentialId);
544
+ if (kept && kept.attempt.recordVersion === attempt.recordVersion)
545
+ this.forget(attempt.credentialId);
341
546
  const pending = this.#reports.get(attempt);
342
547
  if (pending)
343
548
  return pending;
@@ -366,6 +571,10 @@ export class ClaustrumScopedCustody {
366
571
  if (this.#closed)
367
572
  return;
368
573
  this.#closed = true;
574
+ if (this.#probeTimer)
575
+ this.#clearTimeout(this.#probeTimer);
576
+ this.#probeTimer = undefined;
577
+ this.#kept.clear();
369
578
  this.#client.close();
370
579
  }
371
580
  }
@@ -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 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 { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaOptions, type InsulaQuotaSource, type InsulaUsageEntry, type InsulaUsageTransport, type InsulaUsageWindow, } from './insula.js';
10
+ export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaOptions, 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,14 +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';
14
15
  export { acquireInsulaQuotaSource, } from './insula.js';
15
16
  export { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
16
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';
17
19
  /**
18
20
  * Connect the client that lists and fetches this consumer's vault credentials
19
21
  * on the request path. `connectionFile` is required: this library
@@ -1,4 +1,5 @@
1
1
  import type { ClaustrumClientOptions } from '@cortexkit/claustrum-client';
2
+ import { type WatchMode } from './watch.js';
2
3
  /** Insula's window fields are open: plugins choose which limits they understand. */
3
4
  export interface InsulaUsageWindow {
4
5
  usedPercent: number;
@@ -43,21 +44,68 @@ export interface InsulaQuotaOptions<Q> {
43
44
  */
44
45
  normalize: (entry: InsulaUsageEntry, context: InsulaQuotaContext) => Q | undefined;
45
46
  }
47
+ /**
48
+ * A held-open `usage.watch` stream. `closed` resolves when insula ends the
49
+ * stream (STREAM_END at shutdown, or a reply that ends it) or after `stop()`,
50
+ * and rejects with insula's refusal (an error with a `code`, such as
51
+ * `unknown_method` from an insula that predates the method, or
52
+ * `usage_watch_limit` when 64 watches are already open) or with the
53
+ * transport failure.
54
+ */
55
+ export interface InsulaUsageWatch {
56
+ stop(): void;
57
+ readonly closed: Promise<void>;
58
+ }
46
59
  /** Optional transport for custom scoped clients; getUsage must not retry refusals. */
47
60
  export interface InsulaUsageTransport {
48
61
  connectionFile: string;
49
62
  getUsage(): Promise<unknown>;
63
+ /**
64
+ * Open a `usage.watch` stream, passing each notice's raw JSON body to
65
+ * `onNotice`. Optional: a transport without it is polled as before.
66
+ */
67
+ watchUsage?(onNotice: (body: Uint8Array) => void): InsulaUsageWatch;
50
68
  }
51
69
  /** Constructing this transport opens no connection; getUsage opens one per call. */
52
70
  export declare function insulaUsageTransport(options: ClaustrumClientOptions & {
53
71
  connectionFile: string;
54
72
  }): InsulaUsageTransport;
73
+ export interface InsulaWatchOptions {
74
+ /**
75
+ * The provider this watcher reads. A notice that names only other
76
+ * providers then needs no read; unset means every notice does.
77
+ */
78
+ provider?: string;
79
+ /**
80
+ * setTimeout and clearTimeout for the waits before re-subscribing or retrying
81
+ * a watch. Defaults to the global timers; tests inject virtual ones.
82
+ */
83
+ setTimeoutImpl?: typeof setTimeout;
84
+ clearTimeoutImpl?: typeof clearTimeout;
85
+ }
55
86
  export declare class InsulaQuotaSource {
56
87
  #private;
57
88
  private readonly transport;
58
89
  private readonly key;
59
90
  constructor(transport: InsulaUsageTransport, key: string);
91
+ /**
92
+ * The background poll: at most one usage.get per minute per daemon and
93
+ * enrollment token. While a watch is open it reads nothing, because insula's
94
+ * notices announce every new reading. If insula stops announcing an account,
95
+ * that account's last entry grows older than the freshness limit `current()`
96
+ * applies, `current()` returns nothing for it, and the plugin falls back to
97
+ * its own provider poll for that account.
98
+ */
60
99
  refresh(now: number): Promise<void>;
100
+ /** How this source currently learns about usage changes, for logs. */
101
+ watchMode(): WatchMode;
102
+ /**
103
+ * Hold a `usage.watch` open while any watcher wants it, and re-read
104
+ * usage.get when a notice says something changed. Watchers of one source
105
+ * share one watch, since insula admits only 64 per process. Returns the
106
+ * release; the last release closes the watch.
107
+ */
108
+ watch(options?: InsulaWatchOptions): () => void;
61
109
  current(provider: string, accountId: string, now: number): {
62
110
  entry: InsulaUsageEntry;
63
111
  context: InsulaQuotaContext;