@cortexkit/common-auth 0.15.0 → 0.17.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.
Files changed (46) hide show
  1. package/dist/claustrum/consumer.d.ts +33 -3
  2. package/dist/claustrum/consumer.js +96 -1
  3. package/dist/claustrum/custody.d.ts +4 -1
  4. package/dist/claustrum/enrollment.d.ts +6 -1
  5. package/dist/claustrum/enrollment.js +6 -1
  6. package/dist/claustrum/index.d.ts +2 -1
  7. package/dist/claustrum/index.js +5 -3
  8. package/dist/claustrum/insula.d.ts +69 -0
  9. package/dist/claustrum/insula.js +152 -0
  10. package/dist/claustrum/roster.d.ts +13 -0
  11. package/dist/claustrum/roster.js +33 -3
  12. package/dist/quota/codec.d.ts +2 -0
  13. package/dist/quota/codec.js +2 -1
  14. package/dist/quota/index.d.ts +2 -2
  15. package/dist/quota/index.js +1 -1
  16. package/dist/quota/map.d.ts +11 -0
  17. package/dist/quota/map.js +36 -1
  18. package/dist/quota/merge.d.ts +3 -1
  19. package/dist/quota/merge.js +21 -5
  20. package/dist/quota/projection.d.ts +2 -1
  21. package/dist/quota/projection.js +3 -1
  22. package/dist/setup/command-runner.d.ts +4 -0
  23. package/dist/setup/command-runner.js +49 -0
  24. package/dist/setup/command.d.ts +3 -0
  25. package/dist/setup/command.js +203 -0
  26. package/dist/setup/config-write.d.ts +11 -0
  27. package/dist/setup/config-write.js +60 -0
  28. package/dist/setup/detect.d.ts +6 -0
  29. package/dist/setup/detect.js +224 -0
  30. package/dist/setup/enroll.d.ts +4 -0
  31. package/dist/setup/enroll.js +70 -0
  32. package/dist/setup/index.d.ts +5 -0
  33. package/dist/setup/index.js +4 -0
  34. package/dist/setup/paths.d.ts +11 -0
  35. package/dist/setup/paths.js +33 -0
  36. package/dist/setup/process-fence.d.ts +43 -0
  37. package/dist/setup/process-fence.js +270 -0
  38. package/dist/setup/prompts.d.ts +4 -0
  39. package/dist/setup/prompts.js +26 -0
  40. package/dist/setup/register.d.ts +11 -0
  41. package/dist/setup/register.js +130 -0
  42. package/dist/setup/types.d.ts +136 -0
  43. package/dist/setup/types.js +1 -0
  44. package/dist/store/schema.d.ts +2 -0
  45. package/dist/store/schema.js +3 -2
  46. package/package.json +11 -1
@@ -3,8 +3,9 @@ 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 } from './custody.js';
5
5
  import { type ClaustrumLogger } from './errors.js';
6
+ import { type InsulaQuotaOptions } from './insula.js';
6
7
  import { type AccountMapper, type QuotaReceipt, type VaultRosterFile } from './roster.js';
7
- export interface ClaustrumConsumerOptions {
8
+ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
8
9
  /**
9
10
  * The roster file: one row per vault account (route id, credential id,
10
11
  * account identity, state, quota), plus the accounts the user declined. It
@@ -45,6 +46,8 @@ export interface ClaustrumConsumerOptions {
45
46
  clearTimeoutImpl?: typeof clearTimeout;
46
47
  now?: () => number;
47
48
  logger?: ClaustrumLogger;
49
+ /** Optional background quota source. In-band readings still use recordQuota. */
50
+ insula?: InsulaQuotaOptions<Q>;
48
51
  }
49
52
  export interface SendOptions {
50
53
  /**
@@ -63,15 +66,34 @@ export interface SendOptions {
63
66
  * never are. It never enrolls: a missing token is an error here, and setup
64
67
  * is where enrollment happens.
65
68
  */
66
- export declare class ClaustrumConsumer {
69
+ export declare class ClaustrumConsumer<Q = QuotaObservation> {
67
70
  #private;
68
- constructor(options: ClaustrumConsumerOptions);
71
+ constructor(options: ClaustrumConsumerOptions<Q>);
69
72
  /** The last committed roster this instance saw, without any I/O. */
70
73
  snapshot(): VaultRosterFile | undefined;
71
74
  /** Rows for `/routing`, from the last committed roster. */
72
75
  routingRows(): RoutingRow[];
73
76
  refresh(): Promise<VaultRosterFile | undefined>;
74
77
  start(): void;
78
+ /**
79
+ * Fetch on a background tick, at most once per minute across projects with
80
+ * the same daemon and enrollment token path. Admission must use the cache
81
+ * instead, so an optional quota daemon never delays a provider request.
82
+ */
83
+ refreshInsulaQuota(): Promise<void>;
84
+ /**
85
+ * Cache-only, for unknown-quota admission with a served receipt. Undefined
86
+ * means poll the provider normally. Only get_scoped's asserted account_id
87
+ * joins insula; parsed identities and display metadata cannot substitute.
88
+ * Background polling should use cachedInsulaQuotaForRoute instead.
89
+ */
90
+ cachedInsulaQuota(receipt: Pick<ClaustrumScopedAttempt, 'assertedAccountIdentity'>): Promise<Q | undefined>;
91
+ /**
92
+ * Background cache lookup without fetching a credential. Re-read the roster
93
+ * so a peer's account replacement invalidates the old route immediately.
94
+ * A route without a known provider account cannot join an insula entry.
95
+ */
96
+ cachedInsulaQuotaForRoute(routeId: string): Promise<Q | undefined>;
75
97
  /**
76
98
  * Authorize one physical send on a vault route. The roster file is re-read
77
99
  * first, so a decline committed by another process applies before the next
@@ -98,5 +120,13 @@ export declare class ClaustrumConsumer {
98
120
  * (see `recordVaultQuota`), so a reading for a replaced account is dropped.
99
121
  */
100
122
  recordQuota(routeId: string, observation: QuotaObservation, attempt: QuotaReceipt): Promise<boolean>;
123
+ /**
124
+ * Store a background observation that belongs to an account rather than to
125
+ * a served credential (an insula reading from `cachedInsulaQuotaForRoute`).
126
+ * It lands only while the route is still bound to that known account, so no
127
+ * credential fetch is needed and a replaced account's reading is dropped.
128
+ * The in-memory roster is reloaded from the file, without a vault call.
129
+ */
130
+ recordAccountQuota(routeId: string, accountIdentity: string, observation: QuotaObservation): Promise<boolean>;
101
131
  close(): void;
102
132
  }
@@ -1,8 +1,10 @@
1
1
  import { createLogger } from '../logger/index.js';
2
2
  import { combineAbortSignals } from '../util/any-signal.js';
3
3
  import { ClaustrumScopedCustody, decideScopedRetryAfter401, } from './custody.js';
4
+ import { readClaustrumEnrollmentToken } from './enrollment.js';
4
5
  import { ClaustrumConsumerError } from './errors.js';
5
- import { acceptVaultRoute, declineVaultRoute, readVaultRoster, recordVaultQuota, refreshVaultRoster, vaultRoutingRows, } from './roster.js';
6
+ import { acquireInsulaQuotaSource } from './insula.js';
7
+ import { acceptVaultRoute, declineVaultRoute, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, vaultRoutingRows, } from './roster.js';
6
8
  /**
7
9
  * One plugin host's view of its vault accounts. It turns vault credentials
8
10
  * into rows for `/routing`, authorizes each physical send with the vault, and
@@ -21,6 +23,7 @@ export class ClaustrumConsumer {
21
23
  #roster;
22
24
  #timer;
23
25
  #started = false;
26
+ #insula;
24
27
  constructor(options) {
25
28
  this.#options = options;
26
29
  this.#logger = options.logger ?? createLogger('claustrum');
@@ -84,6 +87,9 @@ export class ClaustrumConsumer {
84
87
  now: this.#options.now,
85
88
  logger: this.#logger,
86
89
  });
90
+ if (this.#options.insula && client.insula) {
91
+ this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
92
+ }
87
93
  return this.#custody;
88
94
  })
89
95
  .finally(() => {
@@ -109,6 +115,8 @@ export class ClaustrumConsumer {
109
115
  this.#roster = undefined;
110
116
  this.#custody?.close();
111
117
  this.#custody = undefined;
118
+ this.#insula?.release();
119
+ this.#insula = undefined;
112
120
  return undefined;
113
121
  }
114
122
  const custody = await this.#getCustody();
@@ -145,6 +153,7 @@ export class ClaustrumConsumer {
145
153
  const tick = async () => {
146
154
  try {
147
155
  await this.refresh();
156
+ await this.refreshInsulaQuota();
148
157
  }
149
158
  catch (error) {
150
159
  if (!this.#shutdown.signal.aborted)
@@ -163,6 +172,72 @@ export class ClaustrumConsumer {
163
172
  };
164
173
  void tick();
165
174
  }
175
+ /**
176
+ * Fetch on a background tick, at most once per minute across projects with
177
+ * the same daemon and enrollment token path. Admission must use the cache
178
+ * instead, so an optional quota daemon never delays a provider request.
179
+ */
180
+ async refreshInsulaQuota() {
181
+ if (!this.#options.insula ||
182
+ this.#shutdown.signal.aborted ||
183
+ !(await this.#active()))
184
+ return;
185
+ try {
186
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
187
+ await this.#getCustody();
188
+ await this.#insula?.source.refresh((this.#options.now ?? Date.now)());
189
+ }
190
+ catch {
191
+ // An optional source must never prevent the plugin's own quota poll.
192
+ }
193
+ }
194
+ /**
195
+ * Cache-only, for unknown-quota admission with a served receipt. Undefined
196
+ * means poll the provider normally. Only get_scoped's asserted account_id
197
+ * joins insula; parsed identities and display metadata cannot substitute.
198
+ * Background polling should use cachedInsulaQuotaForRoute instead.
199
+ */
200
+ async cachedInsulaQuota(receipt) {
201
+ if (!this.#options.insula ||
202
+ this.#shutdown.signal.aborted ||
203
+ !(await this.#active()))
204
+ return undefined;
205
+ try {
206
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
207
+ return this.#normalizeInsulaQuota(receipt.assertedAccountIdentity);
208
+ }
209
+ catch {
210
+ return undefined;
211
+ }
212
+ }
213
+ /**
214
+ * Background cache lookup without fetching a credential. Re-read the roster
215
+ * so a peer's account replacement invalidates the old route immediately.
216
+ * A route without a known provider account cannot join an insula entry.
217
+ */
218
+ async cachedInsulaQuotaForRoute(routeId) {
219
+ if (!this.#options.insula ||
220
+ this.#shutdown.signal.aborted ||
221
+ !(await this.#active()))
222
+ return undefined;
223
+ try {
224
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
225
+ const roster = await readVaultRoster(this.#options.rosterPath);
226
+ const row = roster?.rows.find((entry) => entry.routeId === routeId);
227
+ return this.#normalizeInsulaQuota(row?.accountIdentity);
228
+ }
229
+ catch {
230
+ return undefined;
231
+ }
232
+ }
233
+ #normalizeInsulaQuota(accountIdentity) {
234
+ if (!this.#options.insula || !accountIdentity)
235
+ return undefined;
236
+ const current = this.#insula?.source.current(this.#options.insula.provider, accountIdentity, (this.#options.now ?? Date.now)());
237
+ return current
238
+ ? this.#options.insula.normalize(current.entry, current.context)
239
+ : undefined;
240
+ }
166
241
  /**
167
242
  * Authorize one physical send on a vault route. The roster file is re-read
168
243
  * first, so a decline committed by another process applies before the next
@@ -285,6 +360,24 @@ export class ClaustrumConsumer {
285
360
  this.#roster = await readVaultRoster(this.#options.rosterPath);
286
361
  return kept;
287
362
  }
363
+ /**
364
+ * Store a background observation that belongs to an account rather than to
365
+ * a served credential (an insula reading from `cachedInsulaQuotaForRoute`).
366
+ * It lands only while the route is still bound to that known account, so no
367
+ * credential fetch is needed and a replaced account's reading is dropped.
368
+ * The in-memory roster is reloaded from the file, without a vault call.
369
+ */
370
+ async recordAccountQuota(routeId, accountIdentity, observation) {
371
+ this.#assertOpen();
372
+ const kept = await recordVaultAccountQuota(this.#options.rosterPath, {
373
+ routeId,
374
+ accountIdentity,
375
+ observation,
376
+ });
377
+ if (kept)
378
+ this.#roster = await readVaultRoster(this.#options.rosterPath);
379
+ return kept;
380
+ }
288
381
  close() {
289
382
  if (this.#shutdown.signal.aborted)
290
383
  return;
@@ -293,6 +386,8 @@ export class ClaustrumConsumer {
293
386
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
294
387
  this.#timer = undefined;
295
388
  this.#custody?.close();
389
+ this.#insula?.release();
390
+ this.#insula = undefined;
296
391
  this.#roster = undefined;
297
392
  }
298
393
  }
@@ -1,6 +1,9 @@
1
1
  import { type ClaustrumClient, type ClaustrumReporterSource, type EnrollmentTokenFile } from '@cortexkit/claustrum-client';
2
2
  import { type ClaustrumLogger } from './errors.js';
3
- export type ClaustrumScopedClient = Pick<ClaustrumClient, 'listScoped' | 'getScoped' | 'reportAuthFailureScoped' | 'close'>;
3
+ import type { InsulaUsageTransport } from './insula.js';
4
+ export type ClaustrumScopedClient = Pick<ClaustrumClient, 'listScoped' | 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
5
+ insula?: InsulaUsageTransport;
6
+ };
4
7
  /** The two credential types a plugin's family can hold; routing differs by type. */
5
8
  export type VaultCredentialType = 'oauth' | 'api_key';
6
9
  /**
@@ -103,7 +103,12 @@ export interface EnrollmentAncestorOptions {
103
103
  */
104
104
  export declare function refuseWritableAncestor(parent: string, options?: EnrollmentAncestorOptions): Promise<void>;
105
105
  export declare function readClaustrumEnrollmentStatus(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<ClaustrumEnrollmentStatus>;
106
- /** Resolve the host's account mode from its enrollment files without writing. */
106
+ /**
107
+ * Resolve the host's account mode from its enrollment files. It never changes
108
+ * their contents or the host's mode. On Windows, reading them may create a
109
+ * missing private state folder and tighten an enrollment file's permissions to
110
+ * owner-only, as every private-file read there does.
111
+ */
107
112
  export declare function enrollmentAuthority(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<'vault' | 'local' | 'unreadable'>;
108
113
  /**
109
114
  * Read fresh bearer material for one scoped operation; never publish it.
@@ -419,7 +419,12 @@ export async function readClaustrumEnrollmentStatus(paths, proposedName) {
419
419
  }
420
420
  return statusFromState(state);
421
421
  }
422
- /** Resolve the host's account mode from its enrollment files without writing. */
422
+ /**
423
+ * Resolve the host's account mode from its enrollment files. It never changes
424
+ * their contents or the host's mode. On Windows, reading them may create a
425
+ * missing private state folder and tighten an enrollment file's permissions to
426
+ * owner-only, as every private-file read there does.
427
+ */
423
428
  export async function enrollmentAuthority(paths, proposedName) {
424
429
  let status;
425
430
  try {
@@ -6,8 +6,9 @@ export { type AccountIdentitySource, type ClaustrumFamily, type ClaustrumScopedA
6
6
  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
7
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
8
8
  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';
9
10
  export { acceptAccount, type DeclinedAccount, declineAccount, isDeclined, } from './interlock.js';
10
- export { type AccountMapper, acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, type MutateVaultRosterOptions, mutateVaultRoster, type ProjectionOptions, projectVaultRoster, type QuotaReceipt, readVaultRoster, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, type VaultPrimary, type VaultPrimaryBinding, type VaultPrimaryUnavailableReason, type VaultRosterFile, type VaultRosterLockContext, type VaultRosterRow, vaultRoutingRows, } from './roster.js';
11
+ 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';
11
12
  /**
12
13
  * Connect the client that lists and fetches this consumer's vault credentials
13
14
  * on the request path. `connectionFile` is required: this library
@@ -4,6 +4,7 @@
4
4
  // declined-account interlock and the host-slot guard. Needs the optional
5
5
  // peer `@cortexkit/claustrum-client`.
6
6
  import { ClaustrumClient, } from '@cortexkit/claustrum-client';
7
+ import { insulaUsageTransport } from './insula.js';
7
8
  export { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
8
9
  export { ClaustrumConsumer, } from './consumer.js';
9
10
  export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, SERVING_MARGIN_MS, } from './custody.js';
@@ -11,12 +12,13 @@ export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEn
11
12
  export { ClaustrumConsumerError, } from './errors.js';
12
13
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
13
14
  export { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
14
- export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from './roster.js';
15
+ export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from './roster.js';
15
16
  /**
16
17
  * Connect the client that lists and fetches this consumer's vault credentials
17
18
  * on the request path. `connectionFile` is required: this library
18
19
  * reads no environment, so the plugin resolves the vault's connection file.
19
20
  */
20
- export function connectClaustrumScopedClient(options) {
21
- return ClaustrumClient.connect(options);
21
+ export async function connectClaustrumScopedClient(options) {
22
+ const client = await ClaustrumClient.connect(options);
23
+ return Object.assign(client, { insula: insulaUsageTransport(options) });
22
24
  }
@@ -0,0 +1,69 @@
1
+ import type { ClaustrumClientOptions } from '@cortexkit/claustrum-client';
2
+ /** Insula's window fields are open: plugins choose which limits they understand. */
3
+ export interface InsulaUsageWindow {
4
+ usedPercent: number;
5
+ rawUsedPercent?: number;
6
+ resetsAt?: string;
7
+ windowMinutes?: number;
8
+ windowKind?: string;
9
+ [field: string]: unknown;
10
+ }
11
+ export interface InsulaUsageEntry {
12
+ provider: string;
13
+ account?: string;
14
+ fetchedAt?: string;
15
+ source?: string;
16
+ stale?: unknown;
17
+ errorClass?: unknown;
18
+ usage?: {
19
+ primary?: InsulaUsageWindow;
20
+ secondary?: InsulaUsageWindow;
21
+ tertiary?: InsulaUsageWindow;
22
+ extraRateWindows?: Array<{
23
+ id?: string;
24
+ title?: string;
25
+ window?: InsulaUsageWindow;
26
+ }>;
27
+ [field: string]: unknown;
28
+ };
29
+ [field: string]: unknown;
30
+ }
31
+ export interface InsulaQuotaContext {
32
+ /** Milliseconds since the epoch, parsed from the producer's fetchedAt. */
33
+ fetchedAt: number;
34
+ source?: string;
35
+ }
36
+ export interface InsulaQuotaOptions<Q> {
37
+ provider: 'codex' | 'claude' | 'antigravity';
38
+ /**
39
+ * Set every converted window's reading time to context.fetchedAt, not poll
40
+ * time. Return undefined for entries the plugin cannot use. Antigravity can
41
+ * receive its own sidebar reading back from insula: accept it only from the
42
+ * vault or when fetchedAt is newer than the plugin's last reading.
43
+ */
44
+ normalize: (entry: InsulaUsageEntry, context: InsulaQuotaContext) => Q | undefined;
45
+ }
46
+ /** Optional transport for custom scoped clients; getUsage must not retry refusals. */
47
+ export interface InsulaUsageTransport {
48
+ connectionFile: string;
49
+ getUsage(): Promise<unknown>;
50
+ }
51
+ /** Constructing this transport opens no connection; getUsage opens one per call. */
52
+ export declare function insulaUsageTransport(options: ClaustrumClientOptions & {
53
+ connectionFile: string;
54
+ }): InsulaUsageTransport;
55
+ export declare class InsulaQuotaSource {
56
+ #private;
57
+ private readonly transport;
58
+ private readonly key;
59
+ constructor(transport: InsulaUsageTransport, key: string);
60
+ refresh(now: number): Promise<void>;
61
+ current(provider: string, accountId: string, now: number): {
62
+ entry: InsulaUsageEntry;
63
+ context: InsulaQuotaContext;
64
+ } | undefined;
65
+ }
66
+ export declare function acquireInsulaQuotaSource(transport: InsulaUsageTransport, tokenPath: string): {
67
+ source: InsulaQuotaSource;
68
+ release(): void;
69
+ };
@@ -0,0 +1,152 @@
1
+ import { resolve } from 'node:path';
2
+ import { storeIdentity } from '@cortexkit/claustrum-client';
3
+ // A static import: claustrum-client already loads subc-client whenever
4
+ // /claustrum is imported, so loading it lazily saves nothing, and a dynamic
5
+ // import makes bundlers emit a separate chunk that a running host loses when
6
+ // its dist folder is rebuilt underneath it.
7
+ import { SubcClient } from '@cortexkit/subc-client';
8
+ /** Constructing this transport opens no connection; getUsage opens one per call. */
9
+ export function insulaUsageTransport(options) {
10
+ const identity = options.identity ??
11
+ storeIdentity(options.projectRoot ?? process.cwd(), options.storagePath ?? process.cwd());
12
+ return {
13
+ connectionFile: options.connectionFile,
14
+ async getUsage() {
15
+ let client;
16
+ let expired = false;
17
+ let timer;
18
+ const timeout = new Promise((_resolve, reject) => {
19
+ timer = setTimeout(() => reject(new Error('insula usage timeout')), 3_000);
20
+ timer.unref?.();
21
+ });
22
+ const request = (async () => {
23
+ client = options.connector
24
+ ? await options.connector({
25
+ connectionFile: options.connectionFile,
26
+ handshakeTimeoutMs: Math.min(options.handshakeTimeoutMs ?? 3_000, 3_000),
27
+ })
28
+ : await SubcClient.connect({
29
+ connectionFile: options.connectionFile,
30
+ handshakeTimeoutMs: Math.min(options.handshakeTimeoutMs ?? 3_000, 3_000),
31
+ });
32
+ // A slow connector may resolve after the whole-call deadline. It still
33
+ // owns a socket, which must not survive or open a route after fallback.
34
+ if (expired) {
35
+ client.close();
36
+ throw new Error('insula usage timeout');
37
+ }
38
+ // Managed call() retries warming routes. A single routeOpen/request
39
+ // instead lets the plugin fall back as soon as the daemon refuses.
40
+ const route = await client.routeOpen({ kind: 'management_surface', module_id: 'insula' }, identity);
41
+ return await client.request(route, { method: 'usage.get', params: {} });
42
+ })();
43
+ try {
44
+ return await Promise.race([request, timeout]);
45
+ }
46
+ finally {
47
+ expired = true;
48
+ clearTimeout(timer);
49
+ client?.close();
50
+ }
51
+ },
52
+ };
53
+ }
54
+ const MINUTE = 60_000;
55
+ const MAX_AGE = 4 * MINUTE;
56
+ const sources = new Map();
57
+ // Keep only the minute budget after the last owner closes, so project churn
58
+ // cannot reset the bound. Expired budgets are pruned on the next tick.
59
+ const attempts = new Map();
60
+ function record(value) {
61
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
62
+ }
63
+ export class InsulaQuotaSource {
64
+ transport;
65
+ key;
66
+ #entries = [];
67
+ #pending;
68
+ constructor(transport, key) {
69
+ this.transport = transport;
70
+ this.key = key;
71
+ }
72
+ refresh(now) {
73
+ if (this.#pending)
74
+ return this.#pending;
75
+ for (const [key, time] of attempts) {
76
+ if (now - time >= MINUTE)
77
+ attempts.delete(key);
78
+ }
79
+ const lastAttempt = attempts.get(this.key);
80
+ if (lastAttempt !== undefined && now - lastAttempt < MINUTE)
81
+ return Promise.resolve();
82
+ // Reserve the minute before I/O, so concurrent projects cannot each poll.
83
+ attempts.set(this.key, now);
84
+ this.#pending = (async () => {
85
+ try {
86
+ const reply = await this.transport.getUsage();
87
+ if (!record(reply) ||
88
+ !Array.isArray(reply.result) ||
89
+ reply.error !== undefined)
90
+ throw new Error('unavailable insula usage');
91
+ // Each response is a snapshot, not a delta. Missing accounts fall back;
92
+ // neither pending nor the entry count asserts provider completeness.
93
+ this.#entries = reply.result.filter((entry) => record(entry) && typeof entry.provider === 'string');
94
+ }
95
+ catch {
96
+ // Refusal is absence, even if the previous reading was still young.
97
+ this.#entries = [];
98
+ }
99
+ })().finally(() => {
100
+ this.#pending = undefined;
101
+ });
102
+ return this.#pending;
103
+ }
104
+ current(provider, accountId, now) {
105
+ for (const entry of this.#entries) {
106
+ if (entry.provider !== provider ||
107
+ typeof entry.account !== 'string' ||
108
+ entry.account.trim() !== accountId)
109
+ continue;
110
+ if (entry.stale !== undefined ||
111
+ entry.errorClass !== undefined ||
112
+ !record(entry.usage))
113
+ continue;
114
+ const fetchedAt = typeof entry.fetchedAt === 'string'
115
+ ? Date.parse(entry.fetchedAt)
116
+ : Number.NaN;
117
+ if (!Number.isFinite(fetchedAt) || now - fetchedAt >= MAX_AGE)
118
+ continue;
119
+ return {
120
+ entry,
121
+ context: {
122
+ fetchedAt,
123
+ ...(typeof entry.source === 'string' && { source: entry.source }),
124
+ },
125
+ };
126
+ }
127
+ return undefined;
128
+ }
129
+ }
130
+ export function acquireInsulaQuotaSource(transport, tokenPath) {
131
+ const key = JSON.stringify([
132
+ resolve(transport.connectionFile),
133
+ resolve(tokenPath),
134
+ ]);
135
+ let shared = sources.get(key);
136
+ if (!shared) {
137
+ shared = { source: new InsulaQuotaSource(transport, key), refs: 0 };
138
+ sources.set(key, shared);
139
+ }
140
+ shared.refs++;
141
+ let released = false;
142
+ return {
143
+ source: shared.source,
144
+ release() {
145
+ if (released)
146
+ return;
147
+ released = true;
148
+ if (--shared.refs === 0)
149
+ sources.delete(key);
150
+ },
151
+ };
152
+ }
@@ -133,6 +133,19 @@ export declare function recordVaultQuota(path: string, input: QuotaReceipt & {
133
133
  routeId: string;
134
134
  observation: QuotaObservation;
135
135
  }): Promise<boolean>;
136
+ /**
137
+ * Merge a quota observation that belongs to an account rather than to a
138
+ * served credential, such as a background reading from insula. The write
139
+ * lands only while the row is still bound to that exact known account, so a
140
+ * reading taken before a replacement never reaches the successor. Unlike
141
+ * `recordVaultQuota` it never binds an account: a row without a known account
142
+ * is refused. Returns whether the observation was kept.
143
+ */
144
+ export declare function recordVaultAccountQuota(path: string, input: {
145
+ routeId: string;
146
+ accountIdentity: string;
147
+ observation: QuotaObservation;
148
+ }): Promise<boolean>;
136
149
  /**
137
150
  * Discover and commit the roster. The lease covers the list call and the
138
151
  * commit, not just the write: an opaque view cannot tell a delayed old reply
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { acquireRefreshFileLock, withLock, writeJsonAtomic, } from '../fs/index.js';
3
3
  import { readPrivateText, windowsPrivateFiles } from '../fs/private-files.js';
4
- import { isQuotaMap, mergeQuotaObservation, } from '../quota/index.js';
4
+ import { decodeQuotaMap, mergeQuotaObservation, } from '../quota/index.js';
5
5
  import { ClaustrumConsumerError } from './errors.js';
6
6
  import { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
7
7
  export const DEFAULT_ROUTE_PREFIX = 'vault:';
@@ -210,6 +210,7 @@ function optionalString(value) {
210
210
  return value === undefined || typeof value === 'string';
211
211
  }
212
212
  function decodeRow(value) {
213
+ const quota = isRecord(value) ? decodeQuotaMap(value.quota) : undefined;
213
214
  if (!isRecord(value) ||
214
215
  typeof value.routeId !== 'string' ||
215
216
  typeof value.credentialId !== 'string' ||
@@ -224,11 +225,14 @@ function decodeRow(value) {
224
225
  (value.aliases !== undefined &&
225
226
  (!Array.isArray(value.aliases) ||
226
227
  !value.aliases.every((alias) => typeof alias === 'string'))) ||
227
- (value.quota !== undefined && !isQuotaMap(value.quota)) ||
228
+ (value.quota !== undefined && quota === undefined) ||
228
229
  (value.stale !== undefined && value.stale !== true) ||
229
230
  (value.unclaimed !== undefined && value.unclaimed !== true))
230
231
  return undefined;
231
- return value;
232
+ return {
233
+ ...value,
234
+ ...(quota === undefined ? {} : { quota }),
235
+ };
232
236
  }
233
237
  const SKIPPED_REASONS = new Set([
234
238
  'empty credential id',
@@ -435,6 +439,32 @@ export function recordVaultQuota(path, input) {
435
439
  };
436
440
  });
437
441
  }
442
+ /**
443
+ * Merge a quota observation that belongs to an account rather than to a
444
+ * served credential, such as a background reading from insula. The write
445
+ * lands only while the row is still bound to that exact known account, so a
446
+ * reading taken before a replacement never reaches the successor. Unlike
447
+ * `recordVaultQuota` it never binds an account: a row without a known account
448
+ * is refused. Returns whether the observation was kept.
449
+ */
450
+ export function recordVaultAccountQuota(path, input) {
451
+ return mutateVaultRoster(path, (current) => {
452
+ const row = current?.rows.find((entry) => entry.routeId === input.routeId);
453
+ if (!current ||
454
+ !row ||
455
+ row.accountIdentity === undefined ||
456
+ row.accountIdentity !== input.accountIdentity)
457
+ return { result: false };
458
+ const quota = mergeQuotaObservation(row.quota, input.observation);
459
+ return {
460
+ next: {
461
+ ...current,
462
+ rows: current.rows.map((entry) => entry === row ? { ...entry, quota } : entry),
463
+ },
464
+ result: true,
465
+ };
466
+ });
467
+ }
438
468
  /**
439
469
  * Discover and commit the roster. The lease covers the list call and the
440
470
  * commit, not just the write: an opaque view cannot tell a delayed old reply
@@ -1,5 +1,7 @@
1
1
  export interface QuotaCodec {
2
2
  readonly validate: (value: unknown) => boolean;
3
+ /** Normalize persisted data before validation; older codecs may omit this. */
4
+ readonly decode?: (value: unknown) => unknown;
3
5
  readonly merge: (stored: unknown, observation: unknown) => unknown;
4
6
  }
5
7
  /**
@@ -1,4 +1,4 @@
1
- import { isQuotaMap } from './map.js';
1
+ import { decodeQuotaMap, isQuotaMap } from './map.js';
2
2
  import { mergeQuotaObservation } from './merge.js';
3
3
  /**
4
4
  * The quota codec the account-pool store (the `/store` subpath) takes when it
@@ -8,5 +8,6 @@ import { mergeQuotaObservation } from './merge.js';
8
8
  */
9
9
  export const quotaCodec = Object.freeze({
10
10
  validate: isQuotaMap,
11
+ decode: decodeQuotaMap,
11
12
  merge: mergeQuotaObservation,
12
13
  });
@@ -2,8 +2,8 @@ export type { QuotaCodec } from './codec.js';
2
2
  export { quotaCodec } from './codec.js';
3
3
  export type { QuotaTextForm, QuotaTextOptions } from './format.js';
4
4
  export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from './format.js';
5
- export type { CreditBudgetCleared, CreditBudgetEntry, CreditBudgetReading, QuotaAbsentEntry, QuotaEntry, QuotaMap, QuotaReadingEntry, QuotaRetiredEntry, } from './map.js';
6
- export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, emptyQuotaMap, isQuotaMap, } from './map.js';
5
+ export type { CreditBudgetCleared, CreditBudgetEntry, CreditBudgetReading, QuotaAbsentEntry, QuotaCounter, QuotaEntry, QuotaMap, QuotaReadingEntry, QuotaRetiredEntry, } from './map.js';
6
+ export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, decodeQuotaMap, emptyQuotaMap, isQuotaMap, } from './map.js';
7
7
  export type { ObservedBudget, ObservedPair, ObservedReading, QuotaObservation, } from './merge.js';
8
8
  export { isQuotaObservation, mergeQuotaObservation, QuotaCodecError, } from './merge.js';
9
9
  export type { ExhaustionReset, ProjectedBudget, ProjectedLimit, ProjectedQuota, } from './projection.js';
@@ -1,5 +1,5 @@
1
1
  export { quotaCodec } from './codec.js';
2
2
  export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from './format.js';
3
- export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, emptyQuotaMap, isQuotaMap, } from './map.js';
3
+ export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, decodeQuotaMap, emptyQuotaMap, isQuotaMap, } from './map.js';
4
4
  export { isQuotaObservation, mergeQuotaObservation, QuotaCodecError, } from './merge.js';
5
5
  export { budgetExhaustedResetAt, futureResetAt, projectQuota, readsExhausted, } from './projection.js';