@cortexkit/common-auth 0.24.0 → 0.25.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.
@@ -4,7 +4,7 @@ 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
6
  import { type InsulaQuotaOptions, type InsulaQuotaResult } from './insula.js';
7
- import { type AccountMapper, type QuotaReceipt, type VaultRosterFile } from './roster.js';
7
+ import { type AccountMapper, type QuotaReceipt, type ReorderVaultRosterResult, type VaultRosterFile } from './roster.js';
8
8
  import { type WatchMode } from './watch.js';
9
9
  export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
10
10
  /**
@@ -157,6 +157,12 @@ export declare class ClaustrumConsumer<Q = QuotaObservation> {
157
157
  /** Decline a vault account: it stays listed and never routes until accepted. */
158
158
  decline(routeId: string): Promise<void>;
159
159
  accept(routeId: string): Promise<void>;
160
+ /**
161
+ * Set the order vault accounts are tried in (`reorderVaultRoster`), then
162
+ * re-read the roster, so the next routing decision in this process uses
163
+ * the new order without waiting for a discovery. Never contacts the vault.
164
+ */
165
+ reorder(routeIds: readonly string[]): Promise<ReorderVaultRosterResult>;
160
166
  /**
161
167
  * Store a quota or profile observation for a vault route. The receipt the
162
168
  * reading was taken with is required: the observation lands only while the
@@ -5,7 +5,7 @@ import { readClaustrumEnrollmentToken } from './enrollment.js';
5
5
  import { ClaustrumConsumerError } from './errors.js';
6
6
  import { acquireInsulaQuotaSource, } from './insula.js';
7
7
  import { pendingVaultQuota, retainVaultQuotaWriter } from './quota-writer.js';
8
- import { acceptVaultRoute, applyVaultQuota, declineVaultRoute, forgetPendingVaultDiscovery, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, vaultRoutingRows, } from './roster.js';
8
+ import { acceptVaultRoute, applyVaultQuota, declineVaultRoute, forgetPendingVaultDiscovery, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, vaultRoutingRows, } from './roster.js';
9
9
  import { SAFETY_POLL_MS } from './watch.js';
10
10
  /**
11
11
  * One plugin host's view of its vault accounts. It turns vault credentials
@@ -485,8 +485,12 @@ export class ClaustrumConsumer {
485
485
  let current;
486
486
  try {
487
487
  current = await this.authorize(routeId, signal);
488
+ // Cancellation can land after authorize settles, before this continuation.
489
+ signal?.throwIfAborted();
488
490
  }
489
- catch {
491
+ catch (error) {
492
+ if (signal?.aborted)
493
+ throw error;
490
494
  // Re-authorization failed: keep this 401 and report it against the
491
495
  // receipt (served record version) this request was sent with.
492
496
  }
@@ -522,6 +526,17 @@ export class ClaustrumConsumer {
522
526
  await acceptVaultRoute(this.#options.rosterPath, routeId);
523
527
  this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
524
528
  }
529
+ /**
530
+ * Set the order vault accounts are tried in (`reorderVaultRoster`), then
531
+ * re-read the roster, so the next routing decision in this process uses
532
+ * the new order without waiting for a discovery. Never contacts the vault.
533
+ */
534
+ async reorder(routeIds) {
535
+ this.#assertOpen();
536
+ const result = await reorderVaultRoster(this.#options.rosterPath, routeIds);
537
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
538
+ return result;
539
+ }
525
540
  /**
526
541
  * Store a quota or profile observation for a vault route. The receipt the
527
542
  * reading was taken with is required: the observation lands only while the
@@ -4,7 +4,7 @@
4
4
  * `code`, a `class` and an `action`), so callers can tell the vault's verdict
5
5
  * apart from a check made on this side.
6
6
  */
7
- export type ClaustrumConsumerFailureKind = 'closed' | 'not-enrolled' | 'invalid-token' | 'unavailable' | 'identity-changed' | 'identity-unasserted' | 'insufficient-validity' | 'invalid-material' | 'not-active' | 'route-unavailable' | 'route-declined' | 'no-receipt' | 'unsafe-file' | 'invalid-state' | 'wrong-consumer' | 'roster-busy' | 'host-slot-login' | 'host-slot-placeholder' | 'placeholder-refresh';
7
+ export type ClaustrumConsumerFailureKind = 'closed' | 'not-enrolled' | 'invalid-token' | 'unavailable' | 'identity-changed' | 'identity-unasserted' | 'insufficient-validity' | 'invalid-material' | 'not-active' | 'route-unavailable' | 'route-declined' | 'no-receipt' | 'unsafe-file' | 'invalid-state' | 'wrong-consumer' | 'roster-busy' | 'host-slot-login' | 'host-slot-placeholder' | 'placeholder-refresh' | 'invalid-order';
8
8
  export declare class ClaustrumConsumerError extends Error {
9
9
  readonly kind: ClaustrumConsumerFailureKind;
10
10
  constructor(kind: ClaustrumConsumerFailureKind, message: string);
@@ -10,7 +10,7 @@ export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHO
10
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 { drainVaultQuota } from './quota-writer.js';
13
- 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 AccountMapper, acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, type MutateVaultRosterOptions, mutateVaultRoster, type ProjectionOptions, projectVaultRoster, type QuotaReceipt, type ReorderVaultRosterOptions, type ReorderVaultRosterResult, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, type VaultPrimary, type VaultPrimaryBinding, type VaultPrimaryUnavailableReason, type VaultRosterFile, type VaultRosterLockContext, type VaultRosterRow, vaultRoutingRows, } from './roster.js';
14
14
  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';
15
15
  /**
16
16
  * Connect the client that lists and fetches this consumer's vault credentials
@@ -15,7 +15,7 @@ export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHO
15
15
  export { acquireInsulaQuotaSource, } from './insula.js';
16
16
  export { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
17
17
  export { drainVaultQuota } from './quota-writer.js';
18
- export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from './roster.js';
18
+ export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, reorderVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from './roster.js';
19
19
  export { ChangeNoticeReader, RESUBSCRIBE_BACKOFF_MS, SAFETY_POLL_MS, ScopedRosterWatch, WATCH_RETRY_MS, } from './watch.js';
20
20
  /**
21
21
  * Connect the client that lists and fetches this consumer's vault credentials
@@ -119,6 +119,37 @@ export declare function mutateVaultRoster<T>(path: string, change: (current: Vau
119
119
  export declare function declineVaultRoute(path: string, routeId: string): Promise<undefined>;
120
120
  /** Lift the user's decline for a vault account and every alias of it. */
121
121
  export declare function acceptVaultRoute(path: string, routeId: string): Promise<undefined>;
122
+ /** Options of `reorderVaultRoster`. */
123
+ export interface ReorderVaultRosterOptions {
124
+ /** Aborts the wait for the roster's write lock. */
125
+ signal?: AbortSignal;
126
+ }
127
+ export interface ReorderVaultRosterResult {
128
+ /** The route id order now on disk. */
129
+ ids: string[];
130
+ /** `unchanged` when the roster was already in this order; nothing was written. */
131
+ outcome: 'reordered' | 'unchanged';
132
+ }
133
+ /**
134
+ * Set the order vault accounts are tried in. Routing reads that order from
135
+ * the roster's row order (`vaultRoutingRows`), and a later discovery keeps
136
+ * each account at its position, so the order lasts until the next reorder.
137
+ * The order is this host's routing preference: the vault has no order of its
138
+ * own, and this never contacts it.
139
+ *
140
+ * `routeIds` must name every roster route id exactly once; anything else
141
+ * (an unknown, missing or repeated id) refuses with `invalid-order` and
142
+ * writes nothing. It runs under the roster's write lock, like every other
143
+ * roster write, so a quota reading or decline committed meanwhile is kept.
144
+ * Each row is kept as the same object, so only the positions change: every
145
+ * row's fields and the rest of the file stay as they were. An order equal to
146
+ * the current one writes nothing. A host with no roster file yet has no
147
+ * routes, so only the empty order is accepted.
148
+ *
149
+ * A `ClaustrumConsumer` in the same process does not see the new order until
150
+ * it re-reads the file: call `consumer.reorder` instead to update both.
151
+ */
152
+ export declare function reorderVaultRoster(path: string, routeIds: readonly string[], options?: ReorderVaultRosterOptions): Promise<ReorderVaultRosterResult>;
122
153
  /**
123
154
  * The receipt fields a quota or profile observation must carry to say which
124
155
  * send (credential and account) it came from. Pass the
@@ -378,6 +378,78 @@ export function acceptVaultRoute(path, routeId) {
378
378
  };
379
379
  });
380
380
  }
381
+ function invalidOrder(message) {
382
+ return new ClaustrumConsumerError('invalid-order', message);
383
+ }
384
+ /**
385
+ * Why `routeIds` is not an order of these rows: it must name every distinct
386
+ * route id exactly once and nothing else. The message quotes only ids the
387
+ * caller supplied; route ids it left out are counted, not named.
388
+ */
389
+ function vaultOrderProblem(rows, routeIds) {
390
+ if (!Array.isArray(routeIds))
391
+ return 'route ids must be an array of route ids';
392
+ const rosterIds = new Set(rows.map((row) => row.routeId));
393
+ const given = new Set();
394
+ for (const id of routeIds) {
395
+ if (typeof id !== 'string')
396
+ return 'route ids must be an array of route ids';
397
+ if (given.has(id))
398
+ return `route id ${id} appears more than once`;
399
+ if (!rosterIds.has(id))
400
+ return `route id ${id} is not in the roster`;
401
+ given.add(id);
402
+ }
403
+ const missing = [...rosterIds].filter((id) => !given.has(id)).length;
404
+ if (missing > 0)
405
+ return `the order leaves out ${missing} roster route id${missing === 1 ? '' : 's'}`;
406
+ return undefined;
407
+ }
408
+ /**
409
+ * Set the order vault accounts are tried in. Routing reads that order from
410
+ * the roster's row order (`vaultRoutingRows`), and a later discovery keeps
411
+ * each account at its position, so the order lasts until the next reorder.
412
+ * The order is this host's routing preference: the vault has no order of its
413
+ * own, and this never contacts it.
414
+ *
415
+ * `routeIds` must name every roster route id exactly once; anything else
416
+ * (an unknown, missing or repeated id) refuses with `invalid-order` and
417
+ * writes nothing. It runs under the roster's write lock, like every other
418
+ * roster write, so a quota reading or decline committed meanwhile is kept.
419
+ * Each row is kept as the same object, so only the positions change: every
420
+ * row's fields and the rest of the file stay as they were. An order equal to
421
+ * the current one writes nothing. A host with no roster file yet has no
422
+ * routes, so only the empty order is accepted.
423
+ *
424
+ * A `ClaustrumConsumer` in the same process does not see the new order until
425
+ * it re-reads the file: call `consumer.reorder` instead to update both.
426
+ */
427
+ export function reorderVaultRoster(path, routeIds, options = {}) {
428
+ return mutateVaultRoster(path, (current) => {
429
+ const rows = current?.rows ?? [];
430
+ const problem = vaultOrderProblem(rows, routeIds);
431
+ if (problem)
432
+ throw invalidOrder(problem);
433
+ // Group by route id so a hand-edited file that repeats one keeps every
434
+ // copy: the later copies travel right after the first.
435
+ const byId = new Map();
436
+ for (const row of rows) {
437
+ const group = byId.get(row.routeId);
438
+ if (group)
439
+ group.push(row);
440
+ else
441
+ byId.set(row.routeId, [row]);
442
+ }
443
+ const ids = [...routeIds];
444
+ const next = ids.flatMap((id) => byId.get(id) ?? []);
445
+ if (!current || next.every((row, index) => row === rows[index]))
446
+ return { result: { ids, outcome: 'unchanged' } };
447
+ return {
448
+ next: { ...current, rows: next },
449
+ result: { ids, outcome: 'reordered' },
450
+ };
451
+ }, { ...(options.signal && { signal: options.signal }) });
452
+ }
381
453
  /**
382
454
  * What a receipt may do to a row's quota: `hold` (the row holds the receipt's
383
455
  * credential and account), `bind` (the row has never had a known account and
@@ -48,6 +48,43 @@ export interface RoutingSectionOptions {
48
48
  */
49
49
  orderedVariants?: MenuChoice[];
50
50
  formerMainId?: string;
51
+ /**
52
+ * The vault accounts' routing order, for a plugin that can run in vault
53
+ * mode. Called on each build; return the order while the plugin routes
54
+ * through vault accounts and undefined otherwise. While it returns one, the
55
+ * section shows and sets the vault accounts' order (by the name the menu
56
+ * shows for each account) instead of the pool roster's. Wire it to
57
+ * `ClaustrumConsumer.snapshot()` and `ClaustrumConsumer.reorder`, or to
58
+ * `readVaultRoster` and `reorderVaultRoster` for a plugin without a
59
+ * consumer.
60
+ */
61
+ vaultOrder?: () => VaultRoutingOrder | undefined | Promise<VaultRoutingOrder | undefined>;
62
+ }
63
+ /**
64
+ * The order vault accounts are tried in, as the Routing section reads and
65
+ * sets it in vault mode. Shaped after `/claustrum`'s roster, without
66
+ * importing it, so the menu does not need the vault client.
67
+ */
68
+ export interface VaultRoutingOrder {
69
+ /**
70
+ * Every vault roster row, in roster (routing) order: its route id and the
71
+ * name the plugin shows for that account (the roster row's `label`, or its
72
+ * email). Route ids are long and opaque, so the section shows and accepts
73
+ * labels; a route id is still accepted wherever a label is.
74
+ */
75
+ rows: readonly {
76
+ id: string;
77
+ label: string;
78
+ }[];
79
+ /**
80
+ * Sets the order. `ids` are route ids, every one exactly once. Wire it to
81
+ * `ClaustrumConsumer.reorder` or `reorderVaultRoster`, which refuse any
82
+ * other list without writing.
83
+ */
84
+ reorder(ids: readonly string[]): Promise<{
85
+ ids: readonly string[];
86
+ outcome: 'reordered' | 'unchanged';
87
+ }>;
51
88
  }
52
89
  export interface LimitsSectionOptions {
53
90
  /**
@@ -4,7 +4,7 @@
4
4
  // the same locks as any other writer of those files.
5
5
  import { formatQuota, isQuotaMap, projectQuota, quotaWindowName, } from '../quota/index.js';
6
6
  import { DEFAULT_FORMER_MAIN_ID, orderForPlacement, resolveRoutingMode, } from '../routing/index.js';
7
- import { projectFailure, } from './seam.js';
7
+ import { CommandError, projectFailure, } from './seam.js';
8
8
  /** `disabledReason` recorded when the user disables an account from the menu. */
9
9
  export const MENU_DISABLED_REASON = 'disabled from the command menu';
10
10
  function isRecord(value) {
@@ -65,13 +65,16 @@ function addedText(name, result) {
65
65
  function failureMessage(error) {
66
66
  return projectFailure(error).text;
67
67
  }
68
- async function snapshot(store) {
68
+ async function snapshot(options) {
69
+ const { store } = options;
69
70
  const load = await store.read();
70
71
  const read = await store.readSettings();
72
+ const vault = await options.routing?.vaultOrder?.();
71
73
  return {
72
74
  load,
73
75
  rows: distinctRows(load),
74
76
  settings: read.status === 'error' ? {} : read.settings,
77
+ ...(vault ? { vault } : {}),
75
78
  };
76
79
  }
77
80
  function accountView(row, options) {
@@ -323,6 +326,73 @@ function quotaSection(options, snap) {
323
326
  },
324
327
  };
325
328
  }
329
+ /**
330
+ * Sets the vault order. The roster's own refusal of the list (`invalid-order`:
331
+ * an account left out, which it counts without naming) is shown with its own
332
+ * message; any other failure is projected as usual. The kind is read from
333
+ * the error object so the menu does not import the vault client.
334
+ */
335
+ async function reorderVault(vault, order) {
336
+ try {
337
+ return await vault.reorder(order);
338
+ }
339
+ catch (error) {
340
+ if (error instanceof Error &&
341
+ error.name === 'ClaustrumConsumerError' &&
342
+ error.kind === 'invalid-order')
343
+ throw new CommandError('vault-invalid-order', error.message, {
344
+ cause: error,
345
+ });
346
+ throw error;
347
+ }
348
+ }
349
+ function invalidVaultOrder(message) {
350
+ return new CommandError('vault-invalid-order', message);
351
+ }
352
+ /**
353
+ * How the Routing section names vault accounts: by label, since route ids
354
+ * are long and opaque. A typed entry may be a label or a route id, and must
355
+ * name exactly one account. Refusals quote only the entry the user typed.
356
+ */
357
+ function vaultNames(vault) {
358
+ const rows = vault.rows.map((row) => ({
359
+ id: row.id,
360
+ label: row.label.trim() || row.id,
361
+ }));
362
+ const matches = (entry) => rows.filter((row) => row.id === entry || row.label === entry);
363
+ return {
364
+ ids: rows.map((row) => row.id),
365
+ nameOf: (id) => rows.find((row) => row.id === id)?.label ?? id,
366
+ /**
367
+ * What the order input starts with for an account: its label when
368
+ * typing that label back names this account alone, else its route id
369
+ * (two accounts sharing a label, or a label with a comma or line break
370
+ * in it, either of which would split it into two entries).
371
+ */
372
+ entryOf: (id) => {
373
+ const row = rows.find((entry) => entry.id === id);
374
+ return row && !/[,\n]/.test(row.label) && matches(row.label).length === 1
375
+ ? row.label
376
+ : id;
377
+ },
378
+ /** The route ids the typed entries name, in order; refuses before any write. */
379
+ resolve: (entries) => {
380
+ const ids = [];
381
+ for (const entry of entries) {
382
+ const found = matches(entry);
383
+ if (found.length === 0)
384
+ throw invalidVaultOrder(`"${entry}" is not a vault account.`);
385
+ if (found.length > 1)
386
+ throw invalidVaultOrder(`"${entry}" matches more than one vault account; enter those accounts by route id.`);
387
+ const id = found[0].id;
388
+ if (ids.includes(id))
389
+ throw invalidVaultOrder(`"${entry}" names an account already in the order.`);
390
+ ids.push(id);
391
+ }
392
+ return ids;
393
+ },
394
+ };
395
+ }
326
396
  function routingSection(options, snap) {
327
397
  const { store, extraLocks } = options;
328
398
  const locks = extraLocks ? { extraLocks } : {};
@@ -336,14 +406,18 @@ function routingSection(options, snap) {
336
406
  ? raw
337
407
  : 'ordered';
338
408
  const resolved = resolveRoutingMode(current);
339
- const ids = snap.rows.map((row) => row.id);
409
+ // In vault mode routing tries the vault accounts, so their order is the
410
+ // one shown and set here; the pool roster's order is not used.
411
+ const vault = snap.vault ? vaultNames(snap.vault) : undefined;
412
+ const ids = vault ? vault.ids : snap.rows.map((row) => row.id);
413
+ const nameOf = (id) => (vault ? vault.nameOf(id) : id);
340
414
  const tried = orderForPlacement(ids, resolved.placement, options.routing?.formerMainId ?? DEFAULT_FORMER_MAIN_ID);
341
415
  const label = choices.find((choice) => choice.value === current)?.label ?? current;
342
416
  const lines = [`Mode: ${label}`];
343
417
  if (ids.length > 0)
344
- lines.push(`Roster order: ${ids.join(', ')}`);
418
+ lines.push(`${vault ? 'Vault account order' : 'Roster order'}: ${ids.map(nameOf).join(', ')}`);
345
419
  if (resolved.mode === 'ordered' && tried.join() !== ids.join())
346
- lines.push(`Tried in order: ${tried.join(', ')}`);
420
+ lines.push(`Tried in order: ${tried.map(nameOf).join(', ')}`);
347
421
  const actions = [
348
422
  {
349
423
  id: 'mode',
@@ -371,19 +445,27 @@ function routingSection(options, snap) {
371
445
  {
372
446
  kind: 'text',
373
447
  id: 'order',
374
- label: 'Account ids, first to last',
375
- value: ids.join(', '),
448
+ label: vault
449
+ ? 'Vault accounts, first to last, separated by commas'
450
+ : 'Account ids, first to last',
451
+ value: vault ? ids.map(vault.entryOf).join(', ') : ids.join(', '),
376
452
  required: true,
377
453
  },
378
454
  ],
379
455
  run: async ({ values }) => {
380
- const order = String(values.order)
381
- .split(/[\s,]+/)
382
- .filter((id) => id.length > 0);
383
- const result = await store.reorder(order, locks);
456
+ const text = String(values.order);
457
+ // A vault label may contain spaces, so vault entries are separated by
458
+ // commas or line breaks, not spaces; pool ids never contain spaces.
459
+ const entries = text
460
+ .split(vault ? /[,\n]+/ : /[\s,]+/)
461
+ .map((entry) => entry.trim())
462
+ .filter((entry) => entry.length > 0);
463
+ const result = snap.vault && vault
464
+ ? await reorderVault(snap.vault, vault.resolve(entries))
465
+ : await store.reorder(entries, locks);
384
466
  return result.outcome === 'unchanged'
385
467
  ? 'The order is unchanged.'
386
- : `Order set to ${result.ids.join(', ')}.`;
468
+ : `Order set to ${result.ids.map(nameOf).join(', ')}.`;
387
469
  },
388
470
  });
389
471
  return {
@@ -524,7 +606,7 @@ function limitsSection(options, snap) {
524
606
  }
525
607
  /** The four built-in sections, in their fixed order, from one read of the store. */
526
608
  export async function builtinSections(options) {
527
- const snap = await snapshot(options.store);
609
+ const snap = await snapshot(options);
528
610
  return [
529
611
  accountsSection(options, snap),
530
612
  quotaSection(options, snap),
@@ -1,4 +1,4 @@
1
- export type { AccountsSectionOptions, LimitsSectionOptions, LoginOutcome, QuotaSectionOptions, RoutingSectionOptions, } from './builtins.js';
1
+ export type { AccountsSectionOptions, LimitsSectionOptions, LoginOutcome, QuotaSectionOptions, RoutingSectionOptions, VaultRoutingOrder, } from './builtins.js';
2
2
  export { MENU_DISABLED_REASON } from './builtins.js';
3
3
  export type { CommandMenu, CommandMenuOptions, StoreSectionSlot, } from './menu.js';
4
4
  export { createCommandMenu, parseApplyRequest } from './menu.js';
@@ -26,8 +26,9 @@ export declare function applyHeaderEdits(target: Record<string, string>, edits:
26
26
  * whether output has started and when the response ended, attributed to
27
27
  * an attempt by the rules below;
28
28
  * - `retry` asks the host to retry at once when an account was refused
29
- * before any output, so `model.request` runs again and can pick another
30
- * account, and refuses to retry once output has started.
29
+ * before any output and `chooseAccount` names another account for the
30
+ * next attempt, keeps the host's decision when the refused account was the
31
+ * last one that can serve, and refuses to retry once output has started.
31
32
  *
32
33
  * Attribution. A send belongs to the attempt named by the mark
33
34
  * `model.request` left on it, so several attempts of one session and kind
@@ -97,8 +97,9 @@ function applyHeaderEditsTo(target, edits) {
97
97
  * whether output has started and when the response ended, attributed to
98
98
  * an attempt by the rules below;
99
99
  * - `retry` asks the host to retry at once when an account was refused
100
- * before any output, so `model.request` runs again and can pick another
101
- * account, and refuses to retry once output has started.
100
+ * before any output and `chooseAccount` names another account for the
101
+ * next attempt, keeps the host's decision when the refused account was the
102
+ * last one that can serve, and refuses to retry once output has started.
102
103
  *
103
104
  * Attribution. A send belongs to the attempt named by the mark
104
105
  * `model.request` left on it, so several attempts of one session and kind
@@ -159,6 +160,42 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
159
160
  catch { }
160
161
  };
161
162
  const describe = (error) => error instanceof Error ? error.message : String(error);
163
+ // Adapter choices may enqueue work by session. Serialize their consumption
164
+ // and release so a new choice cannot overtake cleanup, even after forgetting.
165
+ const choiceWork = new Map();
166
+ const inChoiceOrder = (sessionID, run) => {
167
+ const result = (choiceWork.get(sessionID) ?? Promise.resolve()).then(run);
168
+ const settled = result.then(() => { }, () => { });
169
+ choiceWork.set(sessionID, settled);
170
+ void settled.then(() => {
171
+ if (choiceWork.get(sessionID) === settled)
172
+ choiceWork.delete(sessionID);
173
+ });
174
+ return result;
175
+ };
176
+ const afterChoiceWork = (sessionID, run) => {
177
+ const pending = choiceWork.get(sessionID);
178
+ return pending ? pending.then(() => afterChoiceWork(sessionID, run)) : run();
179
+ };
180
+ const releaseChoice = async (next) => {
181
+ try {
182
+ await adapter.dropChoice?.({ ...next.input, accountId: next.accountId });
183
+ }
184
+ catch (error) {
185
+ warn('opencode2 auth dropChoice threw; the request is unaffected', {
186
+ sessionID: next.input.sessionID,
187
+ error: describe(error),
188
+ });
189
+ }
190
+ };
191
+ const discardPending = (key) => {
192
+ const pending = pendingRetries.get(key);
193
+ pendingRetries.delete(key);
194
+ if (pending?.next) {
195
+ const next = pending.next;
196
+ void inChoiceOrder(pending.sessionID, () => releaseChoice(next));
197
+ }
198
+ };
162
199
  const emit = async (event, payload) => {
163
200
  const set = listeners.get(event);
164
201
  if (!set || set.size === 0)
@@ -204,11 +241,12 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
204
241
  /** The attempts of one session and kind, oldest first. */
205
242
  const attemptsOf = (key) => [...attempts.values()].filter((rec) => rec.key === key);
206
243
  const newestOf = (key) => attemptsOf(key).at(-1);
207
- /** Forgets an attempt, and its key's pending retry once nothing else holds the key. */
244
+ /** Forgets an attempt and any pending retry it owns, or whose key is no longer held. */
208
245
  const drop = (rec) => {
209
246
  attempts.delete(rec.id);
210
- if (!attemptsOf(rec.key).length)
211
- pendingRetries.delete(rec.key);
247
+ if (pendingRetries.get(rec.key)?.attemptId === rec.id ||
248
+ !attemptsOf(rec.key).length)
249
+ discardPending(rec.key);
212
250
  };
213
251
  const remember = (rec) => {
214
252
  attempts.set(rec.id, rec);
@@ -300,18 +338,31 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
300
338
  };
301
339
  const select = async (scope, hook, assertActive, transport) => {
302
340
  const key = keyOf(scope.sessionID, scope.kind);
303
- const retried = pendingRetries.get(key);
304
- pendingRetries.delete(key);
305
- const previousAccountId = retried?.accountId ?? newestOf(key)?.accountId;
306
- supersede(key);
307
- const input = {
308
- ...scope,
309
- ...(previousAccountId === undefined ? {} : { previousAccountId }),
310
- ...(retried?.rerouteFrom === undefined
311
- ? {}
312
- : { rerouteFrom: retried.rerouteFrom }),
313
- };
314
- const accountId = await adapter.chooseAccount(input);
341
+ const { input, accountId } = await afterChoiceWork(scope.sessionID, async () => {
342
+ assertActive();
343
+ const retried = pendingRetries.get(key);
344
+ pendingRetries.delete(key);
345
+ const previousAccountId = retried?.accountId ?? newestOf(key)?.accountId;
346
+ supersede(key);
347
+ const next = retried?.next;
348
+ const matches = next !== undefined &&
349
+ next.input.modelID === scope.modelID &&
350
+ next.input.agent === scope.agent;
351
+ const input = {
352
+ ...scope,
353
+ phase: 'request',
354
+ ...(previousAccountId === undefined ? {} : { previousAccountId }),
355
+ ...(retried?.rerouteFrom ? { rerouteFrom: retried.rerouteFrom } : {}),
356
+ };
357
+ if (next && !matches) {
358
+ await inChoiceOrder(scope.sessionID, () => releaseChoice(next));
359
+ assertActive();
360
+ }
361
+ const accountId = matches
362
+ ? next.accountId
363
+ : await adapter.chooseAccount(input);
364
+ return { input, accountId };
365
+ });
315
366
  assertActive();
316
367
  let headers = {};
317
368
  let data;
@@ -730,62 +781,130 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
730
781
  }
731
782
  const rec = picked;
732
783
  await withSelection(rec.scope, async (assertActive) => {
784
+ const checkRetryActive = assertActive;
733
785
  rec.judged = true;
734
- let decision = hostDecision;
735
- let reason;
736
- let rerouteFrom;
737
786
  const attempt = rec.attempt;
738
- if (rec.accountId === undefined || !attempt) {
739
- decision = { retry: false };
740
- reason = 'no-account';
741
- }
742
- else if (rec.outputStarted) {
743
- // The user has already seen part of this answer; a retry would
744
- // send it again.
745
- decision = { retry: false };
746
- reason = 'output-started';
747
- }
748
- else {
787
+ if (attempt && !rec.outputStarted) {
749
788
  if (!rec.limit) {
750
789
  const signal = adapter.limitFromError?.(draft.error, attempt);
751
790
  if (signal)
752
791
  noteLimit(rec, signal, 'error');
753
792
  }
754
- // The next `chooseAccount` should see whatever the plugin learnt
755
- // from how this attempt ended.
756
- if (rec.ended) {
793
+ // Account selection must observe all feedback from the refused send.
794
+ if (rec.ended)
757
795
  await rec.ended;
758
- assertActive();
759
- }
760
- if (rec.limit) {
796
+ if (rec.limit)
761
797
  await rec.limit.delivered;
762
- assertActive();
763
- rec.rerouted = true;
764
- rerouteFrom = {
765
- accountId: rec.accountId,
766
- limit: rec.limit.signal,
767
- };
768
- // No delay: the next attempt goes to another account, and the
769
- // host would otherwise wait out the refused account's backoff,
770
- // or not retry at all for errors it deems final.
771
- decision = { retry: true, delay: 0 };
772
- reason = 'reroute';
798
+ }
799
+ checkRetryActive();
800
+ const { decision, reason } = await inChoiceOrder(rec.scope.sessionID, async () => {
801
+ checkRetryActive();
802
+ const old = pendingRetries.get(rec.key);
803
+ pendingRetries.delete(rec.key);
804
+ if (old?.next)
805
+ await releaseChoice(old.next);
806
+ checkRetryActive();
807
+ let decision = hostDecision;
808
+ let reason;
809
+ let rerouteFrom;
810
+ let next;
811
+ if (rec.accountId === undefined || !attempt) {
812
+ decision = { retry: false };
813
+ reason = 'no-account';
814
+ }
815
+ else if (rec.outputStarted) {
816
+ // The user has already seen part of this answer; a retry would
817
+ // send it again.
818
+ decision = { retry: false };
819
+ reason = 'output-started';
773
820
  }
774
821
  else {
775
- reason = 'host-decides';
822
+ if (rec.limit) {
823
+ const refused = {
824
+ accountId: rec.accountId,
825
+ limit: rec.limit.signal,
826
+ };
827
+ // Ask the adapter now, with the same input the next attempt
828
+ // would give it, which account serves that attempt. Rerouting
829
+ // is right only when that is another account: otherwise the
830
+ // next attempt would find no account (a `no-account` refusal
831
+ // the host treats as a defect and does not retry) or go back
832
+ // at once to the account that just refused.
833
+ let accountId;
834
+ const input = {
835
+ ...rec.scope,
836
+ phase: 'retry',
837
+ previousAccountId: rec.accountId,
838
+ rerouteFrom: refused,
839
+ };
840
+ try {
841
+ accountId = await adapter.chooseAccount(input);
842
+ }
843
+ catch (error) {
844
+ // Treated as no other account: the host's own decision
845
+ // stands, and the next attempt asks the adapter again.
846
+ warn('opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry', {
847
+ sessionID: rec.scope.sessionID,
848
+ error: describe(error),
849
+ });
850
+ }
851
+ if (accountId !== undefined)
852
+ next = { accountId, input };
853
+ try {
854
+ checkRetryActive();
855
+ }
856
+ catch (error) {
857
+ // A selection revoked while the adapter was choosing cannot be used.
858
+ if (next)
859
+ await releaseChoice(next);
860
+ throw error;
861
+ }
862
+ if (accountId !== undefined && accountId !== rec.accountId) {
863
+ rec.rerouted = true;
864
+ rerouteFrom = refused;
865
+ // The next attempt takes this choice rather than asking
866
+ // again, so an account limited between here and the host's
867
+ // retry costs one refused send, which this hook judges
868
+ // again, rather than a `no-account` refusal.
869
+ // No delay: the next attempt goes to another account, and the
870
+ // host would otherwise wait out the refused account's backoff,
871
+ // or not retry at all for errors it deems final.
872
+ decision = { retry: true, delay: 0 };
873
+ reason = 'reroute';
874
+ }
875
+ else {
876
+ // The refused account keeps the host's wait and serves the
877
+ // retry. Undefined or a throw commits nothing: choose later.
878
+ reason = 'host-decides-last-account';
879
+ }
880
+ }
881
+ else {
882
+ reason = 'host-decides';
883
+ }
776
884
  }
777
- }
778
- draft.decision = decision;
779
- // The host's retry runs `model.request` again for this attempt's
780
- // session and kind; that next attempt, and no other attempt of the
781
- // session, is told what this one ended with.
782
- if (decision.retry && rec.accountId !== undefined) {
783
- pendingRetries.set(rec.key, {
784
- sessionID: rec.scope.sessionID,
785
- accountId: rec.accountId,
786
- ...(rerouteFrom === undefined ? {} : { rerouteFrom }),
787
- });
788
- }
885
+ draft.decision = decision;
886
+ // The host's retry runs `model.request` again for this attempt's
887
+ // session and kind; that next attempt, and no other attempt of the
888
+ // session, is told what this one ended with.
889
+ if (decision.retry &&
890
+ rec.accountId !== undefined &&
891
+ attempts.has(rec.id)) {
892
+ pendingRetries.set(rec.key, {
893
+ attemptId: rec.id,
894
+ sessionID: rec.scope.sessionID,
895
+ accountId: rec.accountId,
896
+ ...(rerouteFrom === undefined ? {} : { rerouteFrom }),
897
+ ...(next === undefined ? {} : { next }),
898
+ });
899
+ }
900
+ else if (next) {
901
+ // Only the computed decision is final here: an incoming veto may
902
+ // have been overridden by a reroute to another account.
903
+ await releaseChoice(next);
904
+ }
905
+ return { decision, reason };
906
+ });
907
+ checkRetryActive();
789
908
  await emit('retry', {
790
909
  sessionID: draft.sessionID,
791
910
  ...(rec.accountId === undefined
@@ -815,7 +934,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
815
934
  }
816
935
  for (const [key, pending] of pendingRetries) {
817
936
  if (pending.sessionID === sessionID)
818
- pendingRetries.delete(key);
937
+ discardPending(key);
819
938
  }
820
939
  };
821
940
  const abort = new AbortController();
@@ -867,10 +986,12 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
867
986
  for (const rec of attempts.values())
868
987
  abandon(rec, 'the installation was disposed');
869
988
  attempts.clear();
870
- pendingRetries.clear();
989
+ for (const key of pendingRetries.keys())
990
+ discardPending(key);
871
991
  ownedSockets.clear();
872
992
  latestTransportOwned.clear();
873
993
  listeners.clear();
994
+ await Promise.all(choiceWork.values());
874
995
  await Promise.all(registrations.map(async (registration) => {
875
996
  try {
876
997
  await registration.dispose();
@@ -53,6 +53,8 @@ export interface EventVerdict<Q> {
53
53
  */
54
54
  export type HeaderEdits = Readonly<Record<string, string | null>>;
55
55
  export interface ChooseAccountInput extends RequestScope {
56
+ /** Informational: the retry hook's advance choice, or a request's own choice. */
57
+ readonly phase: 'retry' | 'request';
56
58
  /**
57
59
  * The account of the attempt this one retries, when the retry hook just
58
60
  * asked the host to retry an attempt of this session and kind; otherwise
@@ -61,8 +63,9 @@ export interface ChooseAccountInput extends RequestScope {
61
63
  readonly previousAccountId?: string;
62
64
  /**
63
65
  * Set when the attempt this one retries was refused for a limit before any
64
- * output and the retry hook asked the host to try again. The adapter
65
- * should not pick `accountId` again unless it has nothing else.
66
+ * output. The adapter should not pick `accountId` again unless it has
67
+ * nothing else; returning it, or `undefined`, tells the retry hook that no
68
+ * other account can serve, so the host's own retry decision stands.
66
69
  */
67
70
  readonly rerouteFrom?: {
68
71
  readonly accountId: string;
@@ -166,11 +169,32 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown> {
166
169
  /** Every hook is scoped to this provider; other providers are untouched. */
167
170
  readonly providerID: string;
168
171
  /**
169
- * Picks the account for one model request. Called again for every retry,
170
- * so a refused account can be skipped. Returning `undefined` stops the
171
- * request with `OpenCode2AuthError` kind `no-account`.
172
+ * Commits an account for one attempt. An undefined answer commits nothing
173
+ * to routing state: no consumed retry entry, no queued choice, and no session
174
+ * pin created, moved or deleted. Idempotent maintenance (credential refresh
175
+ * to check usability and recording quota readings) is allowed. On a request,
176
+ * undefined stops with kind `no-account`.
177
+ *
178
+ * After a limit before any output, the retry hook makes this call itself,
179
+ * with `phase: 'retry'` and `rerouteFrom` set. Every returned account,
180
+ * including the refused one, is kept for the next attempt of that session
181
+ * and kind: it does not choose again. Another account retries at once;
182
+ * the refused account keeps the host's decision and wait. `undefined` or a
183
+ * throw commits nothing: the host decides, and the next attempt chooses
184
+ * with `phase: 'request'`, `previousAccountId` and no `rerouteFrom`.
172
185
  */
173
186
  chooseAccount(input: ChooseAccountInput): Promise<string | undefined> | string | undefined;
187
+ /**
188
+ * Releases a kept retry choice that will not be used: no retry, a changed
189
+ * model or agent, session forgetting/deletion, disposal or record eviction.
190
+ * Called once with the original choose input plus its returned accountId,
191
+ * never for a used choice. Awaited before any later chooseAccount for the
192
+ * same session; errors are logged and swallowed. A model/agent change
193
+ * releases the old choice before choosing afresh.
194
+ */
195
+ dropChoice?(input: ChooseAccountInput & {
196
+ readonly accountId: string;
197
+ }): Promise<void> | void;
174
198
  /**
175
199
  * The credential and per-account headers for an account, applied in
176
200
  * `model.request`, `http.request` and `experimental.ws.handshake`. The last
@@ -337,7 +361,20 @@ export interface InstallOpenCode2AuthOptions {
337
361
  readonly maxRecords?: number;
338
362
  readonly logger?: OpenCode2AuthLogger;
339
363
  }
340
- export type RetryReason = 'reroute' | 'output-started' | 'no-account' | 'host-decides';
364
+ /**
365
+ * Why the retry hook decided as it did:
366
+ *
367
+ * - `reroute`: refused for a limit before any output, and `chooseAccount`
368
+ * named another account for the next attempt, so the host retries at once;
369
+ * - `output-started`: output had reached the user, so no retry;
370
+ * - `no-account`: the attempt had no account, so no retry;
371
+ * - `host-decides-last-account`: refused for a limit before any output, but
372
+ * no other account can serve the next attempt, so the host's own decision
373
+ * (its wait, or its refusal to retry) stands and the next attempt may go
374
+ * to the refused account again;
375
+ * - `host-decides`: no limit was recognised, so the host's decision stands.
376
+ */
377
+ export type RetryReason = 'reroute' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
341
378
  /**
342
379
  * The hook that picked an account. Normally `model.request`; a transport hook
343
380
  * picks only when the host skipped `model.request` for that request, which a
@@ -1,7 +1,7 @@
1
1
  import { type MenuTerminal } from '../auth-menu/terminal.js';
2
2
  import type { SetupHost, SetupIO, SetupPlugin } from './types.js';
3
3
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
4
- export declare const UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.";
4
+ export declare const UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read \"Upgrading from v0.1.3\" in its release notes first), or run setup without --claustrum to use local accounts.";
5
5
  /**
6
6
  * The longest setup waits, in total, for the vault to create the enrollment
7
7
  * request and for an operator to approve it. It matches the wait setup always
@@ -5,7 +5,7 @@ import { ClaustrumEnrollmentManager, connectClaustrumEnrollmentClient, hostEnrol
5
5
  import { ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
6
6
  const ENROLLMENT_INCOMPLETE_MESSAGE = 'Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.';
7
7
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
8
- export const UNSUPPORTED_VAULT_MESSAGE = 'This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.';
8
+ export const UNSUPPORTED_VAULT_MESSAGE = 'This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.';
9
9
  /**
10
10
  * The longest setup waits, in total, for the vault to create the enrollment
11
11
  * request and for an operator to approve it. It matches the wait setup always
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.24.0",
3
+ "version": "0.25.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": {
@@ -140,7 +140,7 @@
140
140
  },
141
141
  "devDependencies": {
142
142
  "@biomejs/biome": "2.5.14",
143
- "@cortexkit/claustrum-client": "^0.12.0",
143
+ "@cortexkit/claustrum-client": "^0.13.0",
144
144
  "@cortexkit/subc-client": "0.22.2",
145
145
  "@earendil-works/pi-coding-agent": "1.0.4",
146
146
  "@opencode/plugin": "2.0.21",