@cortexkit/common-auth 0.21.0 → 0.22.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.
@@ -26,28 +26,24 @@ export interface MenuLogin {
26
26
  signal?: AbortSignal;
27
27
  }): Promise<LoginFlow>;
28
28
  /**
29
- * Opens the URL in a browser; false or a throw means no browser could be
30
- * opened. Defaults to `openBrowserForMenu`.
29
+ * Opens the URL in a browser; false or a throw means its opener could not be
30
+ * started. Defaults to `openBrowserForMenu`.
31
31
  */
32
32
  openBrowser?(url: string): boolean | undefined | Promise<boolean | undefined>;
33
33
  }
34
- type BrowserExec = (file: string, args: string[], options: {
35
- stdio: 'ignore';
36
- timeout: number;
37
- }) => unknown;
38
34
  type BrowserSpawn = (file: string, args: string[], options: {
39
35
  stdio: 'ignore';
40
- windowsHide: true;
36
+ windowsHide?: true;
41
37
  }) => {
42
38
  pid?: number;
43
39
  unref(): void;
44
40
  on(event: 'error', listener: () => void): unknown;
45
41
  };
46
- /** Opens a URL with the platform's opener; false when that fails. */
47
- export declare function openBrowserForMenu(url: string, platform?: NodeJS.Platform, execFileSync?: BrowserExec, spawn?: BrowserSpawn): boolean;
42
+ /** Opens a URL with the platform's opener; false when it could not start. */
43
+ export declare function openBrowserForMenu(url: string, platform?: NodeJS.Platform, spawn?: BrowserSpawn): boolean;
48
44
  /**
49
45
  * Runs a login for the menu: a browser login first and, when no browser can
50
- * be opened, a device-code login instead, so a headless machine can still
46
+ * be started, a device-code login instead, so a headless machine can still
51
47
  * add an account. The URL is always printed, so an operator can open it by
52
48
  * hand when the opener reports success but nothing appears.
53
49
  */
@@ -1,6 +1,6 @@
1
- import { execFileSync as defaultExecFileSync, spawn as defaultSpawn, } from 'node:child_process';
2
- /** Opens a URL with the platform's opener; false when that fails. */
3
- export function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn = defaultSpawn) {
1
+ import { spawn as defaultSpawn } from 'node:child_process';
2
+ /** Opens a URL with the platform's opener; false when it could not start. */
3
+ export function openBrowserForMenu(url, platform = process.platform, spawn = defaultSpawn) {
4
4
  try {
5
5
  if (platform === 'win32') {
6
6
  // Start-Process opens the URL with its associated app. Base64 UTF-16LE
@@ -28,15 +28,18 @@ export function openBrowserForMenu(url, platform = process.platform, execFileSyn
28
28
  // Node leaves pid undefined when the process could not be started.
29
29
  return child.pid !== undefined;
30
30
  }
31
- else {
32
- execFileSync(platform === 'darwin' ? 'open' : 'xdg-open', [url], {
33
- stdio: 'ignore',
34
- timeout: 3000,
35
- });
36
- }
37
- return true;
31
+ const child = spawn(platform === 'darwin' ? 'open' : 'xdg-open', [url], {
32
+ stdio: 'ignore',
33
+ });
34
+ // A failed launch reports asynchronously; without a listener it would
35
+ // become an uncaught exception after this function has returned.
36
+ child.on('error', () => { });
37
+ child.unref();
38
+ // The URL handler's process may outlive the caller; a pid means launch began.
39
+ return child.pid !== undefined;
38
40
  }
39
41
  catch {
42
+ // Browser launch is best effort; the printed URL remains the fallback.
40
43
  return false;
41
44
  }
42
45
  }
@@ -53,7 +56,7 @@ function printFlow(context, flow) {
53
56
  }
54
57
  /**
55
58
  * Runs a login for the menu: a browser login first and, when no browser can
56
- * be opened, a device-code login instead, so a headless machine can still
59
+ * be started, a device-code login instead, so a headless machine can still
57
60
  * add an account. The URL is always printed, so an operator can open it by
58
61
  * hand when the opener reports success but nothing appears.
59
62
  */
@@ -3,7 +3,7 @@ import type { QuotaObservation } from '../quota/index.js';
3
3
  import type { RoutingRow } from '../routing/index.js';
4
4
  import { type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, type IdentityParser, type KeptReceiptState, type VaultGrantReach } from './custody.js';
5
5
  import { type ClaustrumLogger } from './errors.js';
6
- import { type InsulaQuotaOptions } from './insula.js';
6
+ import { type InsulaQuotaOptions, type InsulaQuotaResult } from './insula.js';
7
7
  import { type AccountMapper, type QuotaReceipt, type VaultRosterFile } from './roster.js';
8
8
  import { type WatchMode } from './watch.js';
9
9
  export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
@@ -134,6 +134,10 @@ export declare class ClaustrumConsumer<Q = QuotaObservation> {
134
134
  * A route without a known provider account cannot join an insula entry.
135
135
  */
136
136
  cachedInsulaQuotaForRoute(routeId: string): Promise<Q | undefined>;
137
+ /** Cache-only background lookup, preserving the reason a route has no reading. */
138
+ lookupInsulaQuotaForRoute(routeId: string): Promise<InsulaQuotaResult<Q>>;
139
+ /** Skip the fallback poll while insula is cold or its upstream fetch failed. */
140
+ pollInsulaQuotaForRoute(routeId: string, fallback: () => Promise<Q | undefined>): Promise<Q | undefined>;
137
141
  /**
138
142
  * Authorize one physical send on a vault route. The roster file is re-read
139
143
  * first, so a decline committed by another process applies before the next
@@ -3,9 +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, ScopedRosterWatch } from './watch.js';
8
+ import { SAFETY_POLL_MS } from './watch.js';
9
9
  /**
10
10
  * One plugin host's view of its vault accounts. It turns vault credentials
11
11
  * into rows for `/routing`, authorizes each physical send with the vault, and
@@ -19,8 +19,6 @@ export class ClaustrumConsumer {
19
19
  #shutdown = new AbortController();
20
20
  #logger;
21
21
  #custody;
22
- /** The custody's client, kept so `start()` can open its vault watch. */
23
- #client;
24
22
  #connecting;
25
23
  #refreshing;
26
24
  #roster;
@@ -34,6 +32,7 @@ export class ClaustrumConsumer {
34
32
  #insula;
35
33
  #vaultWatch;
36
34
  #releaseInsulaWatch;
35
+ #insulaSkips = new Map();
37
36
  /** When this instance last completed a discovery, by `now`. */
38
37
  #discoveredAt;
39
38
  constructor(options) {
@@ -90,7 +89,6 @@ export class ClaustrumConsumer {
90
89
  client.close();
91
90
  this.#assertOpen();
92
91
  }
93
- this.#client = client;
94
92
  this.#custody = new ClaustrumScopedCustody({
95
93
  client,
96
94
  family: this.#options.family,
@@ -143,9 +141,8 @@ export class ClaustrumConsumer {
143
141
  }
144
142
  /** Close the watches with the connection they belong to. */
145
143
  #stopWatch() {
146
- this.#vaultWatch?.stop();
144
+ this.#vaultWatch?.close();
147
145
  this.#vaultWatch = undefined;
148
- this.#client = undefined;
149
146
  this.#releaseInsulaWatch?.();
150
147
  this.#releaseInsulaWatch = undefined;
151
148
  }
@@ -271,42 +268,30 @@ export class ClaustrumConsumer {
271
268
  * reached in vault mode: a host in local mode never connects.
272
269
  */
273
270
  #openWatch() {
274
- const client = this.#client;
275
- if (this.#shutdown.signal.aborted || !client || !this.#custody)
271
+ const custody = this.#custody;
272
+ if (this.#shutdown.signal.aborted || !custody)
276
273
  return;
277
- if (!this.#vaultWatch) {
278
- const watch = new ScopedRosterWatch({
279
- client,
280
- enrollmentToken: async () => (await readClaustrumEnrollmentToken(this.#options.tokenPath)).token,
281
- view: () => this.#roster?.view,
282
- // The existing discovery, so a watched change commits the roster and
283
- // re-applies it to kept receipts exactly as a poll does. A refresh
284
- // already in flight may have listed before the change was announced,
285
- // so wait for it and list again.
286
- discover: async () => {
287
- while (this.#refreshing)
288
- await this.#refreshing.catch(() => { });
289
- await this.refresh();
290
- },
291
- onRefused: (error) => {
292
- // As a poll that met the same refusal from list_scoped would.
293
- this.#custody?.listFailed(error);
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)
294
292
  this.#options.onError?.(error);
295
- },
296
- onTransportLost: () => this.#custody?.transportLost(),
297
- onReachable: () => this.#custody?.reachable(),
298
- onError: (error) => {
299
- if (!this.#shutdown.signal.aborted)
300
- this.#options.onError?.(error);
301
- },
302
- logger: this.#logger,
303
- now: this.#options.now,
304
- setTimeoutImpl: this.#options.setTimeoutImpl,
305
- clearTimeoutImpl: this.#options.clearTimeoutImpl,
306
- });
307
- this.#vaultWatch = watch;
308
- watch.start();
309
- }
293
+ },
294
+ });
310
295
  if (this.#options.insula && this.#insula && !this.#releaseInsulaWatch)
311
296
  this.#releaseInsulaWatch = this.#insula.source.watch({
312
297
  provider: this.#options.insula.provider,
@@ -372,6 +357,44 @@ export class ClaustrumConsumer {
372
357
  return undefined;
373
358
  }
374
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
+ }
375
398
  #normalizeInsulaQuota(accountIdentity) {
376
399
  if (!this.#options.insula || !accountIdentity)
377
400
  return undefined;
@@ -1,7 +1,7 @@
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 } from './watch.js';
4
+ import { type ScopedWatchSource, type WatchMode } from './watch.js';
5
5
  /**
6
6
  * `watchScoped` is present from claustrum-client 0.12.0. Hosts detect it at
7
7
  * run time and keep polling without it.
@@ -149,6 +149,46 @@ export interface KeptReceiptState {
149
149
  readonly active: boolean;
150
150
  readonly since: number | null;
151
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;
191
+ }
152
192
  /** Reads the provider identity a served token executes under, when the plugin can tell. */
153
193
  export type IdentityParser = (accessToken: string) => string | undefined;
154
194
  /** Only a new version of the same account may replace an in-flight 401. */
@@ -235,5 +275,25 @@ export declare class ClaustrumScopedCustody {
235
275
  * custody did not issue is refused rather than reported.
236
276
  */
237
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;
238
298
  close(): void;
239
299
  }
@@ -4,6 +4,7 @@ import { ClaustrumUnreachableError, classifyVaultFailure, } from './availability
4
4
  import { readClaustrumEnrollmentToken } from './enrollment.js';
5
5
  import { ClaustrumConsumerError } from './errors.js';
6
6
  import { CUSTODY_PLACEHOLDER_PREFIX } from './host-slot.js';
7
+ import { ScopedRosterWatch, } from './watch.js';
7
8
  /** Only a new version of the same account may replace an in-flight 401. */
8
9
  export function isScopedCredentialRotation(served, current) {
9
10
  return (current !== undefined &&
@@ -132,6 +133,9 @@ export class ClaustrumScopedCustody {
132
133
  #lastProbeAt = -Infinity;
133
134
  #probeDelay = 2_000;
134
135
  #closed = false;
136
+ /** The view of the last successful `discover()`, for `watchRoster`. */
137
+ #discoveredView;
138
+ #watches = new Set();
135
139
  constructor(options) {
136
140
  const tokenPath = options.tokenPath;
137
141
  if (options.readToken) {
@@ -197,7 +201,9 @@ export class ClaustrumScopedCustody {
197
201
  this.#probing = true;
198
202
  // Both triggers share list_scoped discovery, including its receipt-drop rules.
199
203
  // Sends never await discovery or let idle backoff delay the next send probe.
200
- void this.discover()
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()
201
207
  .catch(() => {
202
208
  if (idle && this.#outage)
203
209
  this.#probeDelay = Math.min(this.#probeDelay * 2, 30_000);
@@ -271,6 +277,11 @@ export class ClaustrumScopedCustody {
271
277
  * skipped records: they simply are not this consumer's.
272
278
  */
273
279
  async discover(signal) {
280
+ const inventory = await this.#list(signal);
281
+ this.#discoveredView = inventory.view;
282
+ return inventory;
283
+ }
284
+ async #list(signal) {
274
285
  let inventory;
275
286
  let token;
276
287
  try {
@@ -567,6 +578,61 @@ export class ClaustrumScopedCustody {
567
578
  throw error;
568
579
  }
569
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
+ }
570
636
  close() {
571
637
  if (this.#closed)
572
638
  return;
@@ -574,6 +640,9 @@ export class ClaustrumScopedCustody {
574
640
  if (this.#probeTimer)
575
641
  this.#clearTimeout(this.#probeTimer);
576
642
  this.#probeTimer = undefined;
643
+ for (const watch of this.#watches)
644
+ watch.stop();
645
+ this.#watches.clear();
577
646
  this.#kept.clear();
578
647
  this.#client.close();
579
648
  }
@@ -3,11 +3,11 @@ import type { ClaustrumScopedClient } from './custody.js';
3
3
  export { ClaustrumCredentialError, type ClaustrumReporterSource, type EnrollmentTokenFile, } from '@cortexkit/claustrum-client';
4
4
  export { ClaustrumUnreachableError, classifyVaultFailure, VAULT_FAILURE_CLASSES, type VaultFailureClass, } from './availability.js';
5
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
+ 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';
7
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';
8
8
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
9
9
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, type HostSlotContent, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
10
- export { acquireInsulaQuotaSource, type InsulaQuotaContext, type InsulaQuotaOptions, type InsulaQuotaSource, type InsulaUsageEntry, type InsulaUsageTransport, type InsulaUsageWatch, type InsulaUsageWindow, type InsulaWatchOptions, } 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';
11
11
  export { acceptAccount, type DeclinedAccount, declineAccount, isDeclined, } from './interlock.js';
12
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
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';
@@ -34,6 +34,27 @@ export interface InsulaQuotaContext {
34
34
  fetchedAt: number;
35
35
  source?: string;
36
36
  }
37
+ export type InsulaQuotaMiss = 'cold' | 'stale' | 'absent' | 'upstream-failed' | 'credential' | 'unreachable';
38
+ export interface InsulaQuotaReading {
39
+ entry: InsulaUsageEntry;
40
+ context: InsulaQuotaContext;
41
+ }
42
+ /** A miss may retain a dated reading; it is not a current quota observation. */
43
+ export type InsulaQuotaLookup = {
44
+ reading: InsulaQuotaReading;
45
+ miss?: never;
46
+ } | {
47
+ miss: InsulaQuotaMiss;
48
+ reading?: InsulaQuotaReading;
49
+ };
50
+ /** The normalized equivalent of a source lookup, for a plugin's quota type. */
51
+ export type InsulaQuotaResult<Q> = {
52
+ reading: Q;
53
+ miss?: never;
54
+ } | {
55
+ miss: InsulaQuotaMiss;
56
+ reading?: Q;
57
+ };
37
58
  export interface InsulaQuotaOptions<Q> {
38
59
  provider: 'codex' | 'claude' | 'antigravity';
39
60
  /**
@@ -110,6 +131,8 @@ export declare class InsulaQuotaSource {
110
131
  entry: InsulaUsageEntry;
111
132
  context: InsulaQuotaContext;
112
133
  } | undefined;
134
+ /** Cache-only background lookup; current() retains its original miss behavior. */
135
+ lookup(provider: string, accountId: string, now: number): InsulaQuotaLookup;
113
136
  }
114
137
  export declare function acquireInsulaQuotaSource(transport: InsulaUsageTransport, tokenPath: string): {
115
138
  source: InsulaQuotaSource;
@@ -128,6 +128,9 @@ export function insulaUsageTransport(options) {
128
128
  }
129
129
  const MINUTE = 60_000;
130
130
  const MAX_AGE = 4 * MINUTE;
131
+ // consumer-contract.md:331 refetches a slot after 60 s. Two such intervals
132
+ // bound our willingness to wait, not a claim that insula completed its sweep.
133
+ const COLD_WAIT = 2 * MINUTE;
131
134
  const sources = new Map();
132
135
  // Keep only the minute budget after the last owner closes, so project churn
133
136
  // cannot reset the bound. Expired budgets are pruned on the next tick.
@@ -170,6 +173,9 @@ export class InsulaQuotaSource {
170
173
  transport;
171
174
  key;
172
175
  #entries = [];
176
+ #available = false;
177
+ #completeProviders = new Set();
178
+ #coldSince = new Map();
173
179
  /** Every usage.get, polled or watch-driven, shares this one slot. */
174
180
  #reads = new CoalescedRead(async () => {
175
181
  try {
@@ -178,13 +184,25 @@ export class InsulaQuotaSource {
178
184
  !Array.isArray(reply.result) ||
179
185
  reply.error !== undefined)
180
186
  throw new Error('unavailable insula usage');
181
- // Each response is a snapshot, not a delta. Missing accounts fall back;
182
- // neither pending nor the entry count asserts provider completeness.
187
+ // Each response is a snapshot, not a delta. Only completeProviders
188
+ // asserts completeness; neither pending nor the entry count does.
183
189
  this.#entries = reply.result.filter((entry) => record(entry) && typeof entry.provider === 'string');
190
+ this.#available =
191
+ this.#entries.length === reply.result.length &&
192
+ (reply.completeProviders === undefined ||
193
+ (Array.isArray(reply.completeProviders) &&
194
+ reply.completeProviders.every((value) => typeof value === 'string')));
195
+ this.#completeProviders = new Set(this.#available && Array.isArray(reply.completeProviders)
196
+ ? reply.completeProviders
197
+ : []);
198
+ for (const provider of this.#completeProviders)
199
+ this.#coldSince.delete(provider);
184
200
  }
185
201
  catch {
186
202
  // Refusal is absence, even if the previous reading was still young.
187
203
  this.#entries = [];
204
+ this.#available = false;
205
+ this.#completeProviders.clear();
188
206
  }
189
207
  }, () => { });
190
208
  #reader = new ChangeNoticeReader();
@@ -391,6 +409,50 @@ export class InsulaQuotaSource {
391
409
  }
392
410
  return undefined;
393
411
  }
412
+ /** Cache-only background lookup; current() retains its original miss behavior. */
413
+ lookup(provider, accountId, now) {
414
+ if (!this.#available)
415
+ return { miss: 'unreachable' };
416
+ const entry = this.#entries.find((value) => value.provider === provider &&
417
+ typeof value.account === 'string' &&
418
+ value.account.trim() === accountId);
419
+ // An unlabelled error describes the provider's credential path, not an
420
+ // unrelated labelled account. Never borrow another account's verdict.
421
+ const errorClass = (entry ??
422
+ this.#entries.find((value) => value.provider === provider &&
423
+ value.account === undefined &&
424
+ value.errorClass !== undefined))?.errorClass;
425
+ if (errorClass === 'upstream_failed')
426
+ return { miss: 'upstream-failed' };
427
+ if (errorClass === 'credential_absent' ||
428
+ errorClass === 'credential_unusable' ||
429
+ errorClass === 'credential_rejected')
430
+ return { miss: 'credential' };
431
+ if (errorClass !== undefined)
432
+ return { miss: 'unreachable' };
433
+ if (entry) {
434
+ const fetchedAt = typeof entry.fetchedAt === 'string'
435
+ ? Date.parse(entry.fetchedAt)
436
+ : Number.NaN;
437
+ if (!record(entry.usage) || !Number.isFinite(fetchedAt))
438
+ return { miss: 'unreachable' };
439
+ const reading = {
440
+ entry,
441
+ context: {
442
+ fetchedAt,
443
+ ...(typeof entry.source === 'string' && { source: entry.source }),
444
+ },
445
+ };
446
+ return now >= fetchedAt + MAX_AGE || entry.stale !== undefined
447
+ ? { miss: 'stale', reading }
448
+ : { reading };
449
+ }
450
+ if (this.#completeProviders.has(provider))
451
+ return { miss: 'absent' };
452
+ const since = this.#coldSince.get(provider) ?? now;
453
+ this.#coldSince.set(provider, since);
454
+ return { miss: now - since >= COLD_WAIT ? 'unreachable' : 'cold' };
455
+ }
394
456
  }
395
457
  export function acquireInsulaQuotaSource(transport, tokenPath) {
396
458
  const key = JSON.stringify([
@@ -106,8 +106,9 @@ export interface ScopedRosterWatchOptions {
106
106
  /**
107
107
  * The host's existing discovery: `list_scoped`, the roster commit and
108
108
  * everything that follows it. The watch never reads the vault list itself.
109
+ * `view` is the view the newest notice carried.
109
110
  */
110
- discover: () => Promise<unknown>;
111
+ discover: (view: string) => Promise<unknown>;
111
112
  /**
112
113
  * The vault refused the watch, and the confirming `list_scoped` read it
113
114
  * with this error (a revoked enrollment ends both with `not_found`). Handle
@@ -109,8 +109,9 @@ export class ScopedRosterWatch {
109
109
  this.#reads = new CoalescedRead(async () => {
110
110
  const force = this.#force;
111
111
  this.#force = false;
112
+ // A read is only ever requested by a notice, which set #latestView.
112
113
  if (force || this.#latestView !== this.#options.view())
113
- await this.#options.discover();
114
+ await this.#options.discover(this.#latestView ?? '');
114
115
  }, (error) => {
115
116
  if (!this.#stopped)
116
117
  this.#options.onError?.(error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {