@cortexkit/opencode-openai-auth 1.21.0 → 1.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.
Files changed (42) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{index-qx3zz6dw.js → index-0wh22s62.js} +1 -1
  3. package/dist/{index-zd0hham5.js → index-1k8a281v.js} +2 -2
  4. package/dist/{index-vhn0n16s.js → index-677jqrrt.js} +1 -1
  5. package/dist/{index-ewbggf3b.js → index-67twdyyz.js} +11 -11
  6. package/dist/{index-14m8qtpx.js → index-6afhs2jq.js} +2 -2
  7. package/dist/{index-1arphj0y.js → index-8bt81cys.js} +2 -2
  8. package/dist/index-9tg5xx9a.js +2 -0
  9. package/dist/{index-h41zc747.js → index-b3bgqy7r.js} +2 -2
  10. package/dist/index-dw1nh7dk.js +60 -0
  11. package/dist/{index-4vgtvqfc.js → index-mepr345k.js} +1 -1
  12. package/dist/index-ney54jhs.js +79 -0
  13. package/dist/{index-8kg9h2zj.js → index-vaf4mqd1.js} +2 -2
  14. package/dist/index-w6kars9d.js +1 -0
  15. package/dist/{index-4xa80px1.js → index-xbhtpa9s.js} +2 -2
  16. package/dist/index.d.ts +4 -25
  17. package/dist/index.js +1 -1
  18. package/dist/map-D5PHhv4z.d.ts +72 -0
  19. package/dist/rpc/port-file.js +1 -1
  20. package/dist/rpc/protocol.js +1 -1
  21. package/dist/rpc/rpc-client.js +1 -1
  22. package/dist/rpc/rpc-dir.js +1 -1
  23. package/dist/{codex-request-NjUd_A0U.d.ts → runtime-layout-DdxprfY1.d.ts} +664 -643
  24. package/dist/{sidebar-state-CrRiE9hw.d.ts → sidebar-state--OTpRzFd.d.ts} +2 -72
  25. package/dist/sidebar-state.d.ts +1 -1
  26. package/dist/sidebar-state.js +1 -1
  27. package/dist/{token-01hgthyy.js → token-92yc9q7w.js} +1 -1
  28. package/dist/token-util-g8e70a6j.js +1 -0
  29. package/dist/tui-preferences.js +1 -1
  30. package/dist/tui.d.ts +1 -1
  31. package/dist/v2/server.d.ts +10 -3
  32. package/dist/v2/server.js +4 -4
  33. package/package.json +1 -1
  34. package/src/tui-compiled/raw/logger.js +5 -22
  35. package/src/tui-compiled/raw/shared/d669d72c40e9e116-logger.js +30 -1
  36. package/src/tui-compiled/runtime/logger.js +5 -22
  37. package/src/tui-compiled/runtime/shared/d669d72c40e9e116-logger.js +30 -1
  38. package/dist/index-60v2qzqm.js +0 -75
  39. package/dist/index-cqmzvf2k.js +0 -1
  40. package/dist/index-ksfxd8p5.js +0 -64
  41. package/dist/index-rvphtptz.js +0 -2
  42. package/dist/token-util-29yt43da.js +0 -1
@@ -1,4 +1,4 @@
1
- import { gt as QuotaMap } from "./sidebar-state-CrRiE9hw.js";
1
+ import { r as QuotaMap } from "./map-D5PHhv4z.js";
2
2
  import "@cortexkit/private-files";
3
3
  import { ClaustrumClient, EnrollmentPollOutcome, ScopedInventoryRow } from "@cortexkit/claustrum-client";
4
4
  import { Plugin } from "@opencode/plugin";
@@ -419,698 +419,663 @@ type AccountStorage = {
419
419
  accounts: FallbackAccount[];
420
420
  };
421
421
  declare function loadAccounts(paths: AccountPaths): Promise<AccountStorage | null>;
422
- type OAuthCredential = {
423
- type: 'oauth';
424
- access?: string;
425
- refresh: string;
426
- expires?: number;
427
- };
428
- type ApiKeyCredential = {
429
- type: 'api';
430
- apiKey: string;
431
- baseURL: string;
432
- authHeader?: 'authorization-bearer' | 'x-api-key';
422
+ type TimerHandle = ReturnType<typeof setInterval>;
423
+ interface BackgroundQuotaRefreshOptions {
424
+ setIntervalFn?: (callback: () => void, intervalMs: number) => TimerHandle;
425
+ clearIntervalFn?: (timer: TimerHandle) => void;
426
+ random?: () => number;
427
+ onError?: (error: unknown) => void;
428
+ }
429
+ declare class BackgroundQuotaRefresh {
430
+ private readonly setIntervalFn;
431
+ private readonly clearIntervalFn;
432
+ private readonly random;
433
+ private onError;
434
+ private run;
435
+ private timer;
436
+ private tickPromise;
437
+ private stopped;
438
+ constructor(options?: BackgroundQuotaRefreshOptions);
439
+ start(run: () => Promise<void>, onError?: ((error: unknown) => void) | undefined): void;
440
+ stop(): void;
441
+ isStopped(): boolean;
442
+ }
443
+ /**
444
+ * How a host currently learns about changes, for logs and status displays.
445
+ * `watching`: a watch was accepted and is open, so polling is reduced to a
446
+ * slow safety read. `polling`: no watch is open yet (not started, opening, or
447
+ * re-subscribing after a close), so the host polls at its usual interval.
448
+ * `fallback`: the watch is unavailable (an older module or client, a refusal,
449
+ * the watch limit, or repeated failures), so the host polls at its usual
450
+ * interval and may try a watch again later. Never carries secrets.
451
+ */
452
+ type WatchMode = 'watching' | 'polling' | 'fallback';
453
+ /**
454
+ * The fields every change notice carries, from the vault's watchScoped and
455
+ * insula's usage.watch alike.
456
+ */
457
+ interface ChangeNotice {
458
+ readonly kind: string;
459
+ readonly epoch: string;
460
+ readonly seq: number;
461
+ }
462
+ /** A vault watch notice: `view` is the same digest `list_scoped` returns. */
463
+ interface ScopedWatchNoticeShape extends ChangeNotice {
464
+ readonly view: string;
465
+ }
466
+ /**
467
+ * How a vault watch ended, as claustrum-client 0.12.0 reports it. `refused`
468
+ * and `not_accepting` both mean the watch closed before its first notice; the
469
+ * client then made one `list_scoped` read to learn why, and `refused` carries
470
+ * that read's refusal.
471
+ */
472
+ type ScopedWatchEnd = {
473
+ readonly kind: 'refused';
474
+ readonly error: unknown;
475
+ } | {
476
+ readonly kind: 'transport_lost';
477
+ readonly error: unknown;
478
+ } | {
479
+ readonly kind: 'ended' | 'not_accepting' | 'unsupported' | 'stopped';
433
480
  };
434
- /** A credential as stored: an OAuth credential also carries its refresh stamp. */
435
- type StoredCredential = (OAuthCredential & {
436
- lastRefreshedAt?: number;
437
- }) | ApiKeyCredential;
438
- /** Quota codec supplied by `/quota`: the store never interprets the map itself. */
439
- interface QuotaCodec {
440
- validate(value: unknown): boolean;
441
- /** Normalize persisted quota before validation, when the codec supports it. */
442
- decode?(value: unknown): unknown;
443
- merge(stored: unknown | undefined, observation: unknown): unknown;
481
+ interface ScopedWatchHandle {
482
+ stop(): void;
483
+ readonly closed: Promise<ScopedWatchEnd>;
444
484
  }
445
485
  /**
446
- * What `ProviderStateCodec.onReplace` is told about a replacement: the row id,
447
- * the credential epoch the new credential starts, `previousIdentity` (the
448
- * identity the locked row recorded before the replace), `identity` (the
449
- * identity the replace records), and the provider state the caller handed to
450
- * `replace`, if any. Each identity is absent when none was recorded.
486
+ * The part of a vault client that can watch. claustrum-client added
487
+ * `watchScoped` in 0.12.0; the peer range still admits 0.6.2, so it is
488
+ * optional and detected at run time.
451
489
  */
452
- interface ProviderStateReplacement {
453
- id: string;
454
- credentialEpoch: number;
455
- previousIdentity?: string;
456
- identity?: string;
457
- incoming?: unknown;
490
+ interface ScopedWatchSource {
491
+ watchScoped?(onNotice: (notice: ScopedWatchNoticeShape) => void, options?: {
492
+ enrollmentToken?: string;
493
+ }): ScopedWatchHandle;
458
494
  }
459
495
  /**
460
- * Codec for the provider state a plugin keeps beside each row's credential
461
- * (a project id, a device fingerprint, eligibility times: whatever belongs to
462
- * that credential). The store never interprets the value: it stores it as
463
- * JSON, asks `validate` before every write and on every load, and calls the
464
- * hooks below where two values meet. Every hook is synchronous and runs
465
- * under the store locks.
496
+ * A held-open `usage.watch` stream. `closed` resolves when insula ends the
497
+ * stream (STREAM_END at shutdown, or a reply that ends it) or after `stop()`,
498
+ * and rejects with insula's refusal (an error with a `code`, such as
499
+ * `unknown_method` from an insula that predates the method, or
500
+ * `usage_watch_limit` when 64 watches are already open) or with the
501
+ * transport failure.
466
502
  */
467
- interface ProviderStateCodec {
468
- validate(value: unknown): boolean;
469
- /**
470
- * The part of a (valid) value that belongs to the credential: what is true
471
- * of the account the credential signs in to, such as a project id or a
472
- * device fingerprint, as opposed to what the plugin merely tracks about
473
- * its use, such as a cooldown or a cursor. The credential stamp covers the
474
- * digest of exactly this projection, so a foreign edit of it hides the
475
- * value, while the rest may change through `updateProviderState` without
476
- * the stamp being rewritten. It must be a pure function of the value that
477
- * returns JSON with a deterministic key order. Without it the whole value
478
- * is credential-bound.
479
- */
480
- credentialBound?(value: unknown): unknown;
481
- /**
482
- * Combines the value on disk with one a write brings (`add` of a secret the
483
- * pool already holds, `rotate`, or a refresh whose provider returned a
484
- * state). Called only when the row has a value on disk; without it the
485
- * incoming value replaces the stored one. Its result is validated.
486
- */
487
- merge?(onDisk: unknown, incoming: unknown): unknown;
503
+ interface InsulaUsageWatch {
504
+ stop(): void;
505
+ readonly closed: Promise<void>;
506
+ }
507
+ /** Optional transport for custom scoped clients; getUsage must not retry refusals. */
508
+ interface InsulaUsageTransport {
509
+ connectionFile: string;
510
+ getUsage(): Promise<unknown>;
488
511
  /**
489
- * The provider state of a row once `replace` gives it a new credential
490
- * epoch. `previous` is the old credential's value (undefined when the row
491
- * shows none). Returning undefined clears it. Without this hook a replace
492
- * keeps the value handed to `replace` and otherwise clears the state.
512
+ * Open a `usage.watch` stream, passing each notice's raw JSON body to
513
+ * `onNotice`. Optional: a transport without it is polled as before.
493
514
  */
494
- onReplace?(previous: unknown | undefined, replacement: ProviderStateReplacement): unknown | undefined;
515
+ watchUsage?(onNotice: (body: Uint8Array) => void): InsulaUsageWatch;
495
516
  }
496
- /** Every library operation that can fail, as named in the failure value. */
497
- type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'updateLimitsNamespace' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
517
+ /** Structural to also typecheck with the claustrum-client 0.6.2 peer minimum. */
518
+ interface ScopedUsageSource {
519
+ reportUsageScoped?(input: {
520
+ credentialId: string;
521
+ reading: Record<string, unknown>;
522
+ enrollmentToken?: string;
523
+ }): Promise<void>;
524
+ }
525
+ type ScopedRow = Omit<ScopedInventoryRow, 'authMethod' | 'condition'> & {
526
+ readonly authMethod?: string;
527
+ readonly condition?: {
528
+ readonly reason: string;
529
+ readonly sinceMs: number;
530
+ };
531
+ };
532
+ type ScopedInventory = Omit<Awaited<ReturnType<ClaustrumClient['listScoped']>>, 'rows'> & {
533
+ readonly rows: readonly ScopedRow[];
534
+ };
498
535
  /**
499
- * How far an operation got before it failed.
500
- *
501
- * `before-first-write`: nothing was written; both files are as they were.
502
- * `after-first-write`: the operation's first file write landed and a later one
503
- * did not; what that first write left is on disk and is never rolled back
504
- * (add: a state entry no roster row names, which no reader loads; replace:
505
- * the new credential stamped ahead of the config, which readers show as a
506
- * torn row and the next store write on it completes; rotate: the rotated
507
- * credential beside the old per-row entry). `pull`: a quota pull, or the
508
- * recording of its result, failed.
536
+ * claustrum-client adds watchScoped in 0.12.0 and reportUsageScoped in 0.14.0.
537
+ * Older clients keep polling and simply do not send reply quota readings.
538
+ * The optional login condition methods match 0.21.0 without requiring it.
509
539
  */
510
- type PoolFailurePhase = 'before-first-write' | 'after-first-write' | 'pull';
540
+ type ClaustrumScopedClient = Pick<ClaustrumClient, 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
541
+ listScoped(enrollmentToken?: string): Promise<ScopedInventory>;
542
+ reportCondition?(input: {
543
+ credentialId: string;
544
+ recordVersion: number;
545
+ reason: string;
546
+ providerStatus: number;
547
+ actionUrl?: string;
548
+ enrollmentToken?: string;
549
+ }): Promise<void>;
550
+ clearCondition?(input: {
551
+ credentialId: string;
552
+ recordVersion: number;
553
+ enrollmentToken?: string;
554
+ }): Promise<boolean>;
555
+ insula?: InsulaUsageTransport;
556
+ } & ScopedWatchSource & ScopedUsageSource;
557
+ /** The two credential types a plugin's family can hold; routing differs by type. */
558
+ type VaultCredentialType = 'oauth' | 'api_key';
511
559
  /**
512
- * Why an operation failed. `lock-contention` and `lock-ownership` are the two
513
- * lock outcomes (a wait that ran out, and a lease found lost); the rest are
514
- * refusals and failures of the operation itself.
560
+ * Why a listed vault record could not be used. A closed set of fixed codes, so
561
+ * a log line or a roster file that carries one never echoes vault data.
515
562
  */
516
- type PoolFailureKind = 'lock-contention' | 'lock-ownership' | 'pending-migration' | 'load-error' | 'snapshot-contended' | 'publication-sync' | 'publication-incomplete' | 'unknown-row' | 'invalid-row' | 'invalid-input' | 'id-exists' | 'id-removed' | 'type-mismatch' | 'no-credential' | 'row-disabled' | 'row-protected' | 'row-staged' | 'credential-exists' | 'publication-mismatch' | 'duplicate-identity' | 'identity-mismatch' | 'identity-contradicted' | 'endpoint-mismatch' | 'row-key-changed' | 'invalid-order' | 'refresh-stamp-ahead' | 'unbound-credential' | 'attribution' | 'provider' | 'pull' | 'invalid-quota' | 'invalid-provider-state' | 'after-persist-hook' | 'unexpected';
563
+ type SkippedVaultReason = 'empty credential id' | 'duplicate credential id' | 'blank account identity' | 'empty state';
517
564
  /**
518
- * The single failure value of every store operation. `committed` is present
519
- * only when the operation had already written a credential to the state file
520
- * before it failed (a partial rotation or refresh): it is the credential now
521
- * on disk, so a caller never has to re-read the files to learn it.
565
+ * A vault record this consumer could not use. `credentialId` is absent when
566
+ * the record's id itself was unusable, so nothing can say which account the
567
+ * record was.
522
568
  */
523
- declare class PoolOperationError extends Error {
524
- readonly operation: PoolOperation;
525
- readonly rowId: string | undefined;
526
- readonly phase: PoolFailurePhase;
527
- readonly retryable: boolean;
528
- readonly kind: PoolFailureKind;
529
- readonly committed: StoredCredential | undefined;
530
- constructor(details: {
531
- operation: PoolOperation;
532
- rowId?: string;
533
- phase: PoolFailurePhase;
534
- retryable: boolean;
535
- kind: PoolFailureKind;
536
- committed?: StoredCredential;
537
- message?: string;
538
- cause?: unknown;
539
- });
540
- }
541
- interface PoolLogger {
542
- warn(message: string, data?: unknown): void;
569
+ interface SkippedVaultRecord {
570
+ readonly credentialId?: string;
571
+ readonly member?: string;
572
+ readonly reason: SkippedVaultReason;
543
573
  }
544
- type LockStep = NonNullable<Parameters<typeof acquireRefreshFileLock>[0]['onStep']> extends ((step: infer S) => unknown) ? S : never;
545
- /** Tuning shared by every lock the store takes; each field is overridable. */
546
- interface PoolLockOptions {
547
- ttlMs: number;
548
- timeoutMs: number;
549
- retryMs: number;
550
- renew: boolean;
551
- renewIntervalMs?: number;
574
+ /**
575
+ * One grant this consumer's enrollment holds, as the vault's list reply names
576
+ * it: for example `{ selectorKind: 'category', selector: 'openai-native',
577
+ * operation: 'read' }`. `selectorKind` is `exact` (the selector is a credential
578
+ * id) or `category` (a bare category name); both open strings.
579
+ */
580
+ interface VaultGrantTuple {
581
+ readonly selectorKind: string;
582
+ readonly selector: string;
583
+ readonly operation: string;
552
584
  }
553
- /** A lock: the (name, path) pair naming its file plus optional tuning. */
554
- interface PoolLockSpec extends Partial<PoolLockOptions> {
555
- name: string;
556
- path: string;
585
+ /**
586
+ * What this consumer is granted, independent of what those grants currently
587
+ * reach. It is what tells two empty listings apart: no rows with `grants === 0`
588
+ * means no grant at all (the fix is `ck auth grant`), while no rows with
589
+ * `grants > 0` means a grant that reaches no credential, usually logins that
590
+ * lack the category (`ck auth reclassify --from-registry`); `tuples` names the
591
+ * selector that matched nothing. Never written to the roster file.
592
+ */
593
+ interface VaultGrantReach {
594
+ /** How many grants the consumer holds, deposit grants excluded. */
595
+ readonly grants: number;
596
+ readonly tuples: readonly VaultGrantTuple[];
557
597
  }
558
- type LockEvent = {
559
- type: 'acquired' | 'released' | 'contended';
560
- name: string;
561
- path: string;
562
- };
563
- interface LockEnvironment {
564
- onLockEvent?: (event: LockEvent) => void;
565
- onLockStep?: (lock: {
566
- name: string;
567
- path: string;
568
- }, step: LockStep) => void | Promise<void>;
569
- onRenewalTimer?: (lock: {
570
- name: string;
571
- path: string;
572
- }, event: 'scheduled' | 'cancelled') => void;
573
- }
574
- /** Named points on the write path, for crash and ownership injection. */
575
- type WriteStep = 'before-config-write' | 'after-config-write' | 'before-state-write' | 'after-state-write';
576
- /** Awaitable pause points on the pull and refresh paths. */
577
- type HoldPoint = 'refresh-before-provider' | 'pull-before-request';
578
- interface StoreContext {
579
- provider: string;
580
- configPath: string;
581
- statePath: string;
582
- codec: QuotaCodec;
583
- /** The provider-state codec; without one no row shows a provider state. */
584
- providerState?: ProviderStateCodec;
585
- now: () => number;
586
- storeLocks: readonly PoolLockSpec[];
587
- lockDefaults: PoolLockOptions;
588
- lockEnv: LockEnvironment;
589
- logger?: PoolLogger;
590
- onStep?: (step: WriteStep, info: {
591
- operation: PoolOperation;
592
- rowId: string | undefined;
593
- }) => void | Promise<void>;
594
- hold?: (point: HoldPoint, rowId: string) => void | Promise<void>;
595
- /** Ids whose per-row entry a library write dropped in this process. */
596
- removedIds: Set<string>;
598
+ /**
599
+ * Where a receipt's `accountIdentity` came from: the vault asserted it in the
600
+ * served reply, the plugin's `parseIdentity` read it from the served token, or
601
+ * neither did and it is only the roster's expectation (`none`: no identity at
602
+ * all).
603
+ */
604
+ type AccountIdentitySource = 'asserted' | 'parsed' | 'expected' | 'none';
605
+ /**
606
+ * A receipt: what the vault served for one physical send. Each attempt gets
607
+ * its own. It records the exact record version served, because a 401 for
608
+ * this send is reported to the vault against that version.
609
+ */
610
+ interface ClaustrumScopedAttempt {
611
+ readonly credentialId: string;
612
+ readonly credentialType: VaultCredentialType;
597
613
  /**
598
- * When true, rows whose credential stamp is not bound load `unbound` and
599
- * the operations that use a credential refuse them (see
600
- * `OpenPoolStoreOptions.requireCredentialStamps`).
614
+ * The account this receipt is bound to: the vault's assertion, else the
615
+ * plugin's parse of the token, else the roster's expectation. Check
616
+ * `accountIdentitySource` before treating it as proof.
601
617
  */
602
- requireCredentialStamps?: boolean;
603
- requireRemovedFingerprint?: boolean;
604
- }
605
- /** Where a pull was fired from; `load` fires at most once per process per row. */
606
- type PullReason = 'load' | 'add' | 'replace' | 'admission';
607
- interface QuotaCommitTimer {
608
- now(): number;
609
- schedule(delayMs: number, run: () => Promise<void>): {
610
- cancel(): void;
611
- unref?(): void;
612
- };
613
- }
614
- /** What a pull is issued with: the credential and its attribution tuple. */
615
- interface PullRequest {
616
- id: string;
617
- credential: StoredCredential;
618
- credentialEpoch: number;
619
- identity?: string;
620
- reason: PullReason;
621
- }
622
- type PullHook = (request: PullRequest) => Promise<unknown>;
623
- interface OpenPoolStoreOptions {
624
- /** The provider every row of this pool belongs to; keys the provider-wide lock. */
625
- provider: string;
626
- configPath: string;
627
- statePath: string;
628
- quota: QuotaCodec;
618
+ readonly accountIdentity?: string;
619
+ readonly accountIdentitySource: AccountIdentitySource;
620
+ /** The account the roster row named when this receipt was requested. */
621
+ readonly expectedAccountIdentity?: string;
622
+ /** The credential id the vault itself put in the served reply, if any. */
623
+ readonly assertedCredentialId?: string;
629
624
  /**
630
- * Opt in to detached, coalesced quota publication, with any `quota` codec.
631
- * Each accepted observation is queued whole for its row and binding, and
632
- * the queue is applied in arrival order through `quota.merge` under the
633
- * store locks, so the codec's own merge decides which fields a newer or
634
- * older reading replaces. Accepted readings appear in read/load
635
- * immediately, merged the same way; the returned promise still rejects
636
- * current-row refusals before queueing. Await dispose or close at shutdown
637
- * to attempt a bounded drain; readings still pending at its timeout are
638
- * discarded. Normal quota commits are at least 30 seconds apart; a full
639
- * queue commits early so response handling never waits for that interval.
625
+ * The account the vault itself put in the served reply, if any. Never filled
626
+ * in from the roster or from a token parse.
640
627
  */
641
- coalesceQuota?: boolean;
642
- /** Bounded quota drain on close/dispose, in milliseconds; defaults to 1,000. */
643
- quotaDrainTimeoutMs?: number;
644
- /** Monotonic clock and scheduling seam for detached quota commits. */
645
- quotaCommitTimer?: QuotaCommitTimer;
628
+ readonly assertedAccountIdentity?: string;
646
629
  /**
647
- * The codec of the provider state kept beside each row's credential (see
648
- * `ProviderStateCodec`). Without it no row shows a provider state, and
649
- * every write that would set one refuses (`invalid-input`); writes that
650
- * leave it alone keep the value on disk as it is, and `replace` clears it.
630
+ * The non-secret Google Cloud project id the vault served in get_scoped for
631
+ * this attempt, if any. Never filled in from list_scoped, the roster or a
632
+ * token parse. A project change in the vault takes effect on the next send.
651
633
  */
652
- providerState?: ProviderStateCodec;
634
+ readonly projectId?: string;
653
635
  /**
654
- * Refuse every credential this store did not stamp (default false, which
655
- * loads unstamped and mis-stamped credentials as older writers left them).
656
- * When true, a row whose `stamp` is not `bound` loads `unbound` and is no
657
- * candidate, and every operation that would use or keep its credential or
658
- * what was observed about it (`refresh`, quota pulls, `recordQuota`,
659
- * `recordIdentity`, `rotate`, and an `add` of the same secret or onto the
660
- * same credential-less row) refuses with `unbound-credential` before any
661
- * provider call or write, checked again under the locks and at commit.
662
- * Nothing makes such a row bound except `replace`, which starts a new
663
- * credential epoch and drops what was observed about the old one.
664
- * An interrupted add's state-only orphan is recovered only when its stamp
665
- * binds the stored and incoming material, including a supplied identity and
666
- * an API key's endpoint/header. Otherwise add refuses `unbound-credential`
667
- * without writing; `remove(id)` explicitly discards the orphan.
636
+ * Kept in memory only and hidden from JSON.stringify and object spreads, so
637
+ * logging a receipt never leaks it. Authorize again for every dispatch and retry.
668
638
  */
669
- requireCredentialStamps?: boolean;
670
- /** Require an exact secret fingerprint for every roster-publication removal. */
671
- requireRemovedFingerprint?: boolean;
672
- /** Logical clock for refresh stamps and `addedAt`; filesystem leases always use wall time. */
673
- now?: () => number;
639
+ readonly accessToken: string;
640
+ readonly recordVersion: number;
641
+ readonly expiresAtMs: number | null;
674
642
  /**
675
- * Ordered store-lock list held across every read-modify-write. Defaults to
676
- * the older writers' `save` lock at the config path, then at the state path.
643
+ * True when this receipt was not freshly served but is the last token kept
644
+ * from an earlier read, used because the vault could not be reached. A 401
645
+ * with such a receipt must not be retried and is not reported to the vault,
646
+ * which is unreachable.
677
647
  */
678
- storeLocks?: readonly PoolLockSpec[];
679
- /** Defaults for every lock the store takes (see `POOL_LOCK_DEFAULTS`). */
680
- lockOptions?: Partial<PoolLockOptions>;
681
- /** Overrides for the row locks only. */
682
- rowLockOptions?: Partial<PoolLockOptions>;
683
- /** The provider-wide lock; defaults to `provider-<provider>` beside the state file. */
684
- providerLock?: PoolLockSpec;
685
- /** Quota pull hook, fired without being awaited. */
686
- pull?: PullHook;
687
- /** Receives every pull failure, since no caller awaits a pull. */
688
- onPullFailure?: (rowId: string, error: PoolOperationError) => void | Promise<void>;
689
- logger?: PoolLogger;
690
- /** Named write steps, awaited; a test seam for crash and ownership rows. */
691
- onStep?: StoreContext['onStep'];
692
- /** Awaitable hold points on the refresh and pull paths; a test seam. */
693
- hold?: (point: HoldPoint, rowId: string) => void | Promise<void>;
694
- onLockEvent?: LockEnvironment['onLockEvent'];
695
- onLockStep?: LockEnvironment['onLockStep'];
696
- onRenewalTimer?: LockEnvironment['onRenewalTimer'];
648
+ readonly fromKeptReceipt?: true;
697
649
  }
698
- interface IdTokenClaims {
699
- chatgpt_account_id?: string;
700
- email?: string;
701
- organizations?: Array<{
702
- id: string;
703
- }>;
704
- 'https://api.openai.com/auth'?: {
705
- chatgpt_account_id?: string;
706
- };
650
+ interface KeptReceiptState {
651
+ readonly active: boolean;
652
+ readonly since: number | null;
707
653
  }
708
- declare function parseJwtClaims(token: string): IdTokenClaims | undefined;
709
- declare function extractAccountIdFromClaims(claims: IdTokenClaims): string | undefined;
710
- interface TokenResponse {
711
- id_token: string;
712
- access_token: string;
713
- refresh_token: string;
714
- expires_in?: number;
654
+ /**
655
+ * The declined-account interlock: the user's "do not use this vault account",
656
+ * kept on the consumer side because the vault has no notion of it.
657
+ *
658
+ * A decline follows the provider account, not the vault record: an entry made
659
+ * while the account was known matches any credential id or alias that logs
660
+ * into that same account, so relabelling, adding an alias or removing and
661
+ * re-adding the account never lifts it. A credential id that now logs into a
662
+ * different known account does not match, because that account has its own
663
+ * policy. While either side's account is unknown the entry falls back to the
664
+ * credential id, so an adapter that makes no identity claim cannot slip past
665
+ * it. Never keyed on the record version, so a token refresh cannot lift it.
666
+ */
667
+ interface DeclinedAccount {
668
+ readonly credentialId: string;
669
+ readonly accountIdentity?: string;
670
+ }
671
+ interface QuotaCommitTimer {
672
+ now(): number;
673
+ schedule(delayMs: number, run: () => Promise<void>): {
674
+ cancel(): void;
675
+ unref?(): void;
676
+ };
715
677
  }
716
678
  /**
717
- * Minimal shape of a fallback OAuth account for ingestion. Matches the
718
- * fields used by upsertAccount and beginAccountLogin, compatible with
719
- * the full OAuthAccount type in accounts.ts.
679
+ * One vault account as the pool sees it. It carries no bearer material: the
680
+ * access token is fetched from the vault for every send. Several vault
681
+ * records logged into the same provider account collapse into one row, so
682
+ * duplicate logins never count as extra quota.
720
683
  */
721
- interface IngestAccount {
722
- id: string;
723
- label?: string;
724
- type: 'oauth';
725
- access?: string;
726
- refresh: string;
727
- expires?: number;
684
+ interface VaultRosterRow {
685
+ routeId: string;
686
+ credentialId: string;
687
+ credentialType: VaultCredentialType;
688
+ accountIdentity?: string;
689
+ /** Other credential ids logged into the same provider account. */
690
+ aliases?: string[];
691
+ state: string;
692
+ label: string;
693
+ email?: string;
694
+ orgName?: string;
728
695
  enabled: boolean;
729
696
  addedAt: number;
730
- lastUsed: number;
697
+ quota?: QuotaMap;
731
698
  /**
732
- * When the token was obtained. Stamped at login so a freshly added account
733
- * carries a refresh marker — without it, the runtime-state merge cannot tell a
734
- * rotated token from a stale one (both default to 0) and a concurrent stale
735
- * save could roll the token back.
699
+ * The vault listed this record in a form this consumer could not use, so the
700
+ * row is the last good projection kept as it was rather than dropped.
736
701
  */
737
- lastRefreshedAt?: number;
738
- /** Stable ChatGPT account identifier from the OAuth token claims. */
739
- accountId?: string;
702
+ stale?: true;
703
+ /**
704
+ * The vault's latest list named no account for `credentialId`, so
705
+ * `accountIdentity` is the last account that credential was known to log
706
+ * into, kept until the vault names one again. It proves neither that the
707
+ * credential still logs into that account nor that it changed accounts.
708
+ */
709
+ unclaimed?: true;
740
710
  }
741
- interface BeginAccountLoginOptions {
742
- label?: string;
743
- headless?: boolean;
744
- signal?: AbortSignal;
745
- /** Host package version, sent as the version half of the `User-Agent`. */
746
- version: string;
711
+ interface VaultRosterFile {
712
+ version: 1;
713
+ view?: string;
714
+ /**
715
+ * False when the vault's reply carried records this consumer could not use.
716
+ * An incomplete reply never removes an account it may still hold: every
717
+ * previous member it does not account for is kept.
718
+ */
719
+ complete: boolean;
720
+ /** The unusable records of an incomplete reply: a safe id and a fixed reason. */
721
+ rejected?: SkippedVaultRecord[];
722
+ /** Opaque limits data; roster-only writers preserve even newer schemas. */
723
+ limits?: unknown;
724
+ rows: VaultRosterRow[];
725
+ declined: DeclinedAccount[];
747
726
  }
748
- interface BeginAccountLoginResult {
749
- url: string;
750
- instructions: string;
751
- /** Resolves after the user completes the OAuth flow with a ready-to-ingest account. */
752
- completion: Promise<IngestAccount>;
727
+ interface ReorderVaultRosterResult {
728
+ /** The route id order now on disk. */
729
+ ids: string[];
730
+ /** `unchanged` when the roster was already in this order; nothing was written. */
731
+ outcome: 'reordered' | 'unchanged';
753
732
  }
754
733
  /**
755
- * How a host currently learns about changes, for logs and status displays.
756
- * `watching`: a watch was accepted and is open, so polling is reduced to a
757
- * slow safety read. `polling`: no watch is open yet (not started, opening, or
758
- * re-subscribing after a close), so the host polls at its usual interval.
759
- * `fallback`: the watch is unavailable (an older module or client, a refusal,
760
- * the watch limit, or repeated failures), so the host polls at its usual
761
- * interval and may try a watch again later. Never carries secrets.
734
+ * The receipt fields a quota or profile observation must carry to say which
735
+ * send (credential and account) it came from. Pass the
736
+ * `ClaustrumScopedAttempt` that send was authorized with.
762
737
  */
763
- type WatchMode = 'watching' | 'polling' | 'fallback';
738
+ type QuotaReceipt = Pick<ClaustrumScopedAttempt, 'credentialId' | 'accountIdentity' | 'accountIdentitySource' | 'expectedAccountIdentity'>;
764
739
  /**
765
- * The fields every change notice carries, from the vault's watchScoped and
766
- * insula's usage.watch alike.
740
+ * How a started consumer learns about changes, for logs and status displays.
741
+ * `insula` is present when the consumer was given an insula source. Never
742
+ * carries secrets.
767
743
  */
768
- interface ChangeNotice {
769
- readonly kind: string;
770
- readonly epoch: string;
771
- readonly seq: number;
744
+ interface ClaustrumWatchState {
745
+ readonly vault: WatchMode;
746
+ readonly insula?: WatchMode;
772
747
  }
773
- /** A vault watch notice: `view` is the same digest `list_scoped` returns. */
774
- interface ScopedWatchNoticeShape extends ChangeNotice {
775
- readonly view: string;
748
+ type ClaustrumRequestedGrant = {
749
+ selector: {
750
+ category: string;
751
+ exact?: never;
752
+ } | {
753
+ exact: string;
754
+ category?: never;
755
+ };
756
+ operation: 'read' | 'list';
757
+ };
758
+ interface EnrollmentGrantProposal {
759
+ requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
760
+ /** Sent is not proof of access: the operator can approve without grants. */
761
+ requestedGrantsStatus?: 'sent' | 'dropped';
776
762
  }
777
- /**
778
- * How a vault watch ended, as claustrum-client 0.12.0 reports it. `refused`
779
- * and `not_accepting` both mean the watch closed before its first notice; the
780
- * client then made one `list_scoped` read to learn why, and `refused` carries
781
- * that read's refusal.
782
- */
783
- type ScopedWatchEnd = {
784
- readonly kind: 'refused';
785
- readonly error: unknown;
763
+ interface ClaustrumEnrollmentClient {
764
+ enrollPropose(input: {
765
+ name: string;
766
+ requestSecretHash: string;
767
+ displayName?: string;
768
+ requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
769
+ }): Promise<{
770
+ requestId: string;
771
+ }>;
772
+ enrollPoll(input: {
773
+ requestId: string;
774
+ requestSecret: string;
775
+ }): Promise<EnrollmentPollOutcome>;
776
+ }
777
+ interface ClaustrumEnrollmentConnection extends ClaustrumEnrollmentClient {
778
+ close(): void;
779
+ listScoped?: ClaustrumClient['listScoped'];
780
+ }
781
+ type ClaustrumEnrollmentStatus = {
782
+ state: 'idle';
783
+ } | (EnrollmentGrantProposal & {
784
+ state: 'pending';
785
+ proposedName: string;
786
+ requestId?: string;
787
+ retryCode?: string;
788
+ }) | (EnrollmentGrantProposal & {
789
+ state: 'approved';
790
+ proposedName: string;
791
+ approvedName?: string;
792
+ tokenGeneration: number;
793
+ }) | {
794
+ state: 'denied';
795
+ proposedName: string;
786
796
  } | {
787
- readonly kind: 'transport_lost';
788
- readonly error: unknown;
797
+ state: 'blocked';
798
+ proposedName: string;
799
+ code: string;
789
800
  } | {
790
- readonly kind: 'ended' | 'not_accepting' | 'unsupported' | 'stopped';
801
+ state: 'unavailable';
802
+ proposedName: string;
803
+ code: string;
804
+ } | {
805
+ state: 'busy';
791
806
  };
792
- interface ScopedWatchHandle {
793
- stop(): void;
794
- readonly closed: Promise<ScopedWatchEnd>;
807
+ interface ClaustrumEnrollmentPaths {
808
+ statePath: string;
809
+ tokenPath: string;
810
+ }
811
+ type OAuthCredential = {
812
+ type: 'oauth';
813
+ access?: string;
814
+ refresh: string;
815
+ expires?: number;
816
+ };
817
+ type ApiKeyCredential = {
818
+ type: 'api';
819
+ apiKey: string;
820
+ baseURL: string;
821
+ authHeader?: 'authorization-bearer' | 'x-api-key';
822
+ };
823
+ /** A credential as stored: an OAuth credential also carries its refresh stamp. */
824
+ type StoredCredential = (OAuthCredential & {
825
+ lastRefreshedAt?: number;
826
+ }) | ApiKeyCredential;
827
+ /** Quota codec supplied by `/quota`: the store never interprets the map itself. */
828
+ interface QuotaCodec {
829
+ validate(value: unknown): boolean;
830
+ /** Normalize persisted quota before validation, when the codec supports it. */
831
+ decode?(value: unknown): unknown;
832
+ merge(stored: unknown | undefined, observation: unknown): unknown;
795
833
  }
796
834
  /**
797
- * The part of a vault client that can watch. claustrum-client added
798
- * `watchScoped` in 0.12.0; the peer range still admits 0.6.2, so it is
799
- * optional and detected at run time.
835
+ * What `ProviderStateCodec.onReplace` is told about a replacement: the row id,
836
+ * the credential epoch the new credential starts, `previousIdentity` (the
837
+ * identity the locked row recorded before the replace), `identity` (the
838
+ * identity the replace records), and the provider state the caller handed to
839
+ * `replace`, if any. Each identity is absent when none was recorded.
800
840
  */
801
- interface ScopedWatchSource {
802
- watchScoped?(onNotice: (notice: ScopedWatchNoticeShape) => void, options?: {
803
- enrollmentToken?: string;
804
- }): ScopedWatchHandle;
841
+ interface ProviderStateReplacement {
842
+ id: string;
843
+ credentialEpoch: number;
844
+ previousIdentity?: string;
845
+ identity?: string;
846
+ incoming?: unknown;
805
847
  }
806
848
  /**
807
- * A held-open `usage.watch` stream. `closed` resolves when insula ends the
808
- * stream (STREAM_END at shutdown, or a reply that ends it) or after `stop()`,
809
- * and rejects with insula's refusal (an error with a `code`, such as
810
- * `unknown_method` from an insula that predates the method, or
811
- * `usage_watch_limit` when 64 watches are already open) or with the
812
- * transport failure.
849
+ * Codec for the provider state a plugin keeps beside each row's credential
850
+ * (a project id, a device fingerprint, eligibility times: whatever belongs to
851
+ * that credential). The store never interprets the value: it stores it as
852
+ * JSON, asks `validate` before every write and on every load, and calls the
853
+ * hooks below where two values meet. Every hook is synchronous and runs
854
+ * under the store locks.
813
855
  */
814
- interface InsulaUsageWatch {
815
- stop(): void;
816
- readonly closed: Promise<void>;
817
- }
818
- /** Optional transport for custom scoped clients; getUsage must not retry refusals. */
819
- interface InsulaUsageTransport {
820
- connectionFile: string;
821
- getUsage(): Promise<unknown>;
856
+ interface ProviderStateCodec {
857
+ validate(value: unknown): boolean;
822
858
  /**
823
- * Open a `usage.watch` stream, passing each notice's raw JSON body to
824
- * `onNotice`. Optional: a transport without it is polled as before.
859
+ * The part of a (valid) value that belongs to the credential: what is true
860
+ * of the account the credential signs in to, such as a project id or a
861
+ * device fingerprint, as opposed to what the plugin merely tracks about
862
+ * its use, such as a cooldown or a cursor. The credential stamp covers the
863
+ * digest of exactly this projection, so a foreign edit of it hides the
864
+ * value, while the rest may change through `updateProviderState` without
865
+ * the stamp being rewritten. It must be a pure function of the value that
866
+ * returns JSON with a deterministic key order. Without it the whole value
867
+ * is credential-bound.
825
868
  */
826
- watchUsage?(onNotice: (body: Uint8Array) => void): InsulaUsageWatch;
827
- }
828
- /** Structural to also typecheck with the claustrum-client 0.6.2 peer minimum. */
829
- interface ScopedUsageSource {
830
- reportUsageScoped?(input: {
831
- credentialId: string;
832
- reading: Record<string, unknown>;
833
- enrollmentToken?: string;
834
- }): Promise<void>;
869
+ credentialBound?(value: unknown): unknown;
870
+ /**
871
+ * Combines the value on disk with one a write brings (`add` of a secret the
872
+ * pool already holds, `rotate`, or a refresh whose provider returned a
873
+ * state). Called only when the row has a value on disk; without it the
874
+ * incoming value replaces the stored one. Its result is validated.
875
+ */
876
+ merge?(onDisk: unknown, incoming: unknown): unknown;
877
+ /**
878
+ * The provider state of a row once `replace` gives it a new credential
879
+ * epoch. `previous` is the old credential's value (undefined when the row
880
+ * shows none). Returning undefined clears it. Without this hook a replace
881
+ * keeps the value handed to `replace` and otherwise clears the state.
882
+ */
883
+ onReplace?(previous: unknown | undefined, replacement: ProviderStateReplacement): unknown | undefined;
835
884
  }
836
- type ScopedRow = Omit<ScopedInventoryRow, 'authMethod' | 'condition'> & {
837
- readonly authMethod?: string;
838
- readonly condition?: {
839
- readonly reason: string;
840
- readonly sinceMs: number;
841
- };
842
- };
843
- type ScopedInventory = Omit<Awaited<ReturnType<ClaustrumClient['listScoped']>>, 'rows'> & {
844
- readonly rows: readonly ScopedRow[];
845
- };
885
+ /** Every library operation that can fail, as named in the failure value. */
886
+ type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'updateLimitsNamespace' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
846
887
  /**
847
- * claustrum-client adds watchScoped in 0.12.0 and reportUsageScoped in 0.14.0.
848
- * Older clients keep polling and simply do not send reply quota readings.
849
- * The optional login condition methods match 0.21.0 without requiring it.
888
+ * How far an operation got before it failed.
889
+ *
890
+ * `before-first-write`: nothing was written; both files are as they were.
891
+ * `after-first-write`: the operation's first file write landed and a later one
892
+ * did not; what that first write left is on disk and is never rolled back
893
+ * (add: a state entry no roster row names, which no reader loads; replace:
894
+ * the new credential stamped ahead of the config, which readers show as a
895
+ * torn row and the next store write on it completes; rotate: the rotated
896
+ * credential beside the old per-row entry). `pull`: a quota pull, or the
897
+ * recording of its result, failed.
850
898
  */
851
- type ClaustrumScopedClient = Pick<ClaustrumClient, 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
852
- listScoped(enrollmentToken?: string): Promise<ScopedInventory>;
853
- reportCondition?(input: {
854
- credentialId: string;
855
- recordVersion: number;
856
- reason: string;
857
- providerStatus: number;
858
- actionUrl?: string;
859
- enrollmentToken?: string;
860
- }): Promise<void>;
861
- clearCondition?(input: {
862
- credentialId: string;
863
- recordVersion: number;
864
- enrollmentToken?: string;
865
- }): Promise<boolean>;
866
- insula?: InsulaUsageTransport;
867
- } & ScopedWatchSource & ScopedUsageSource;
868
- /** The two credential types a plugin's family can hold; routing differs by type. */
869
- type VaultCredentialType = 'oauth' | 'api_key';
899
+ type PoolFailurePhase = 'before-first-write' | 'after-first-write' | 'pull';
870
900
  /**
871
- * Why a listed vault record could not be used. A closed set of fixed codes, so
872
- * a log line or a roster file that carries one never echoes vault data.
901
+ * Why an operation failed. `lock-contention` and `lock-ownership` are the two
902
+ * lock outcomes (a wait that ran out, and a lease found lost); the rest are
903
+ * refusals and failures of the operation itself.
873
904
  */
874
- type SkippedVaultReason = 'empty credential id' | 'duplicate credential id' | 'blank account identity' | 'empty state';
905
+ type PoolFailureKind = 'lock-contention' | 'lock-ownership' | 'pending-migration' | 'load-error' | 'snapshot-contended' | 'publication-sync' | 'publication-incomplete' | 'unknown-row' | 'invalid-row' | 'invalid-input' | 'id-exists' | 'id-removed' | 'type-mismatch' | 'no-credential' | 'row-disabled' | 'row-protected' | 'row-staged' | 'credential-exists' | 'publication-mismatch' | 'duplicate-identity' | 'identity-mismatch' | 'identity-contradicted' | 'endpoint-mismatch' | 'row-key-changed' | 'invalid-order' | 'refresh-stamp-ahead' | 'unbound-credential' | 'attribution' | 'provider' | 'pull' | 'invalid-quota' | 'invalid-provider-state' | 'after-persist-hook' | 'unexpected';
875
906
  /**
876
- * A vault record this consumer could not use. `credentialId` is absent when
877
- * the record's id itself was unusable, so nothing can say which account the
878
- * record was.
907
+ * The single failure value of every store operation. `committed` is present
908
+ * only when the operation had already written a credential to the state file
909
+ * before it failed (a partial rotation or refresh): it is the credential now
910
+ * on disk, so a caller never has to re-read the files to learn it.
879
911
  */
880
- interface SkippedVaultRecord {
881
- readonly credentialId?: string;
882
- readonly member?: string;
883
- readonly reason: SkippedVaultReason;
912
+ declare class PoolOperationError extends Error {
913
+ readonly operation: PoolOperation;
914
+ readonly rowId: string | undefined;
915
+ readonly phase: PoolFailurePhase;
916
+ readonly retryable: boolean;
917
+ readonly kind: PoolFailureKind;
918
+ readonly committed: StoredCredential | undefined;
919
+ constructor(details: {
920
+ operation: PoolOperation;
921
+ rowId?: string;
922
+ phase: PoolFailurePhase;
923
+ retryable: boolean;
924
+ kind: PoolFailureKind;
925
+ committed?: StoredCredential;
926
+ message?: string;
927
+ cause?: unknown;
928
+ });
884
929
  }
885
- /**
886
- * One grant this consumer's enrollment holds, as the vault's list reply names
887
- * it: for example `{ selectorKind: 'category', selector: 'openai-native',
888
- * operation: 'read' }`. `selectorKind` is `exact` (the selector is a credential
889
- * id) or `category` (a bare category name); both open strings.
890
- */
891
- interface VaultGrantTuple {
892
- readonly selectorKind: string;
893
- readonly selector: string;
894
- readonly operation: string;
930
+ interface PoolLogger {
931
+ warn(message: string, data?: unknown): void;
895
932
  }
896
- /**
897
- * What this consumer is granted, independent of what those grants currently
898
- * reach. It is what tells two empty listings apart: no rows with `grants === 0`
899
- * means no grant at all (the fix is `ck auth grant`), while no rows with
900
- * `grants > 0` means a grant that reaches no credential, usually logins that
901
- * lack the category (`ck auth reclassify --from-registry`); `tuples` names the
902
- * selector that matched nothing. Never written to the roster file.
903
- */
904
- interface VaultGrantReach {
905
- /** How many grants the consumer holds, deposit grants excluded. */
906
- readonly grants: number;
907
- readonly tuples: readonly VaultGrantTuple[];
933
+ type LockStep = NonNullable<Parameters<typeof acquireRefreshFileLock>[0]['onStep']> extends ((step: infer S) => unknown) ? S : never;
934
+ /** Tuning shared by every lock the store takes; each field is overridable. */
935
+ interface PoolLockOptions {
936
+ ttlMs: number;
937
+ timeoutMs: number;
938
+ retryMs: number;
939
+ renew: boolean;
940
+ renewIntervalMs?: number;
908
941
  }
909
- /**
910
- * Where a receipt's `accountIdentity` came from: the vault asserted it in the
911
- * served reply, the plugin's `parseIdentity` read it from the served token, or
912
- * neither did and it is only the roster's expectation (`none`: no identity at
913
- * all).
914
- */
915
- type AccountIdentitySource = 'asserted' | 'parsed' | 'expected' | 'none';
916
- /**
917
- * A receipt: what the vault served for one physical send. Each attempt gets
918
- * its own. It records the exact record version served, because a 401 for
919
- * this send is reported to the vault against that version.
920
- */
921
- interface ClaustrumScopedAttempt {
922
- readonly credentialId: string;
923
- readonly credentialType: VaultCredentialType;
924
- /**
925
- * The account this receipt is bound to: the vault's assertion, else the
926
- * plugin's parse of the token, else the roster's expectation. Check
927
- * `accountIdentitySource` before treating it as proof.
928
- */
929
- readonly accountIdentity?: string;
930
- readonly accountIdentitySource: AccountIdentitySource;
931
- /** The account the roster row named when this receipt was requested. */
932
- readonly expectedAccountIdentity?: string;
933
- /** The credential id the vault itself put in the served reply, if any. */
934
- readonly assertedCredentialId?: string;
935
- /**
936
- * The account the vault itself put in the served reply, if any. Never filled
937
- * in from the roster or from a token parse.
938
- */
939
- readonly assertedAccountIdentity?: string;
940
- /**
941
- * The non-secret Google Cloud project id the vault served in get_scoped for
942
- * this attempt, if any. Never filled in from list_scoped, the roster or a
943
- * token parse. A project change in the vault takes effect on the next send.
944
- */
945
- readonly projectId?: string;
946
- /**
947
- * Kept in memory only and hidden from JSON.stringify and object spreads, so
948
- * logging a receipt never leaks it. Authorize again for every dispatch and retry.
949
- */
950
- readonly accessToken: string;
951
- readonly recordVersion: number;
952
- readonly expiresAtMs: number | null;
942
+ /** A lock: the (name, path) pair naming its file plus optional tuning. */
943
+ interface PoolLockSpec extends Partial<PoolLockOptions> {
944
+ name: string;
945
+ path: string;
946
+ }
947
+ type LockEvent = {
948
+ type: 'acquired' | 'released' | 'contended';
949
+ name: string;
950
+ path: string;
951
+ };
952
+ interface LockEnvironment {
953
+ onLockEvent?: (event: LockEvent) => void;
954
+ onLockStep?: (lock: {
955
+ name: string;
956
+ path: string;
957
+ }, step: LockStep) => void | Promise<void>;
958
+ onRenewalTimer?: (lock: {
959
+ name: string;
960
+ path: string;
961
+ }, event: 'scheduled' | 'cancelled') => void;
962
+ }
963
+ /** Named points on the write path, for crash and ownership injection. */
964
+ type WriteStep = 'before-config-write' | 'after-config-write' | 'before-state-write' | 'after-state-write';
965
+ /** Awaitable pause points on the pull and refresh paths. */
966
+ type HoldPoint = 'refresh-before-provider' | 'pull-before-request';
967
+ interface StoreContext {
968
+ provider: string;
969
+ configPath: string;
970
+ statePath: string;
971
+ codec: QuotaCodec;
972
+ /** The provider-state codec; without one no row shows a provider state. */
973
+ providerState?: ProviderStateCodec;
974
+ now: () => number;
975
+ storeLocks: readonly PoolLockSpec[];
976
+ lockDefaults: PoolLockOptions;
977
+ lockEnv: LockEnvironment;
978
+ logger?: PoolLogger;
979
+ onStep?: (step: WriteStep, info: {
980
+ operation: PoolOperation;
981
+ rowId: string | undefined;
982
+ }) => void | Promise<void>;
983
+ hold?: (point: HoldPoint, rowId: string) => void | Promise<void>;
984
+ /** Ids whose per-row entry a library write dropped in this process. */
985
+ removedIds: Set<string>;
953
986
  /**
954
- * True when this receipt was not freshly served but is the last token kept
955
- * from an earlier read, used because the vault could not be reached. A 401
956
- * with such a receipt must not be retried and is not reported to the vault,
957
- * which is unreachable.
987
+ * When true, rows whose credential stamp is not bound load `unbound` and
988
+ * the operations that use a credential refuse them (see
989
+ * `OpenPoolStoreOptions.requireCredentialStamps`).
958
990
  */
959
- readonly fromKeptReceipt?: true;
960
- }
961
- interface KeptReceiptState {
962
- readonly active: boolean;
963
- readonly since: number | null;
991
+ requireCredentialStamps?: boolean;
992
+ requireRemovedFingerprint?: boolean;
964
993
  }
965
- /**
966
- * The declined-account interlock: the user's "do not use this vault account",
967
- * kept on the consumer side because the vault has no notion of it.
968
- *
969
- * A decline follows the provider account, not the vault record: an entry made
970
- * while the account was known matches any credential id or alias that logs
971
- * into that same account, so relabelling, adding an alias or removing and
972
- * re-adding the account never lifts it. A credential id that now logs into a
973
- * different known account does not match, because that account has its own
974
- * policy. While either side's account is unknown the entry falls back to the
975
- * credential id, so an adapter that makes no identity claim cannot slip past
976
- * it. Never keyed on the record version, so a token refresh cannot lift it.
977
- */
978
- interface DeclinedAccount {
979
- readonly credentialId: string;
980
- readonly accountIdentity?: string;
994
+ /** Where a pull was fired from; `load` fires at most once per process per row. */
995
+ type PullReason = 'load' | 'add' | 'replace' | 'admission';
996
+ /** What a pull is issued with: the credential and its attribution tuple. */
997
+ interface PullRequest {
998
+ id: string;
999
+ credential: StoredCredential;
1000
+ credentialEpoch: number;
1001
+ identity?: string;
1002
+ reason: PullReason;
981
1003
  }
982
- /**
983
- * One vault account as the pool sees it. It carries no bearer material: the
984
- * access token is fetched from the vault for every send. Several vault
985
- * records logged into the same provider account collapse into one row, so
986
- * duplicate logins never count as extra quota.
987
- */
988
- interface VaultRosterRow {
989
- routeId: string;
990
- credentialId: string;
991
- credentialType: VaultCredentialType;
992
- accountIdentity?: string;
993
- /** Other credential ids logged into the same provider account. */
994
- aliases?: string[];
995
- state: string;
996
- label: string;
997
- email?: string;
998
- orgName?: string;
999
- enabled: boolean;
1000
- addedAt: number;
1001
- quota?: QuotaMap;
1004
+ type PullHook = (request: PullRequest) => Promise<unknown>;
1005
+ interface OpenPoolStoreOptions {
1006
+ /** The provider every row of this pool belongs to; keys the provider-wide lock. */
1007
+ provider: string;
1008
+ configPath: string;
1009
+ statePath: string;
1010
+ quota: QuotaCodec;
1011
+ /**
1012
+ * Opt in to detached, coalesced quota publication, with any `quota` codec.
1013
+ * Each accepted observation is queued whole for its row and binding, and
1014
+ * the queue is applied in arrival order through `quota.merge` under the
1015
+ * store locks, so the codec's own merge decides which fields a newer or
1016
+ * older reading replaces. Accepted readings appear in read/load
1017
+ * immediately, merged the same way; the returned promise still rejects
1018
+ * current-row refusals before queueing. Await dispose or close at shutdown
1019
+ * to attempt a bounded drain; readings still pending at its timeout are
1020
+ * discarded. Normal quota commits are at least 30 seconds apart; a full
1021
+ * queue commits early so response handling never waits for that interval.
1022
+ */
1023
+ coalesceQuota?: boolean;
1024
+ /** Bounded quota drain on close/dispose, in milliseconds; defaults to 1,000. */
1025
+ quotaDrainTimeoutMs?: number;
1026
+ /** Monotonic clock and scheduling seam for detached quota commits. */
1027
+ quotaCommitTimer?: QuotaCommitTimer;
1002
1028
  /**
1003
- * The vault listed this record in a form this consumer could not use, so the
1004
- * row is the last good projection kept as it was rather than dropped.
1029
+ * The codec of the provider state kept beside each row's credential (see
1030
+ * `ProviderStateCodec`). Without it no row shows a provider state, and
1031
+ * every write that would set one refuses (`invalid-input`); writes that
1032
+ * leave it alone keep the value on disk as it is, and `replace` clears it.
1005
1033
  */
1006
- stale?: true;
1034
+ providerState?: ProviderStateCodec;
1007
1035
  /**
1008
- * The vault's latest list named no account for `credentialId`, so
1009
- * `accountIdentity` is the last account that credential was known to log
1010
- * into, kept until the vault names one again. It proves neither that the
1011
- * credential still logs into that account nor that it changed accounts.
1036
+ * Refuse every credential this store did not stamp (default false, which
1037
+ * loads unstamped and mis-stamped credentials as older writers left them).
1038
+ * When true, a row whose `stamp` is not `bound` loads `unbound` and is no
1039
+ * candidate, and every operation that would use or keep its credential or
1040
+ * what was observed about it (`refresh`, quota pulls, `recordQuota`,
1041
+ * `recordIdentity`, `rotate`, and an `add` of the same secret or onto the
1042
+ * same credential-less row) refuses with `unbound-credential` before any
1043
+ * provider call or write, checked again under the locks and at commit.
1044
+ * Nothing makes such a row bound except `replace`, which starts a new
1045
+ * credential epoch and drops what was observed about the old one.
1046
+ * An interrupted add's state-only orphan is recovered only when its stamp
1047
+ * binds the stored and incoming material, including a supplied identity and
1048
+ * an API key's endpoint/header. Otherwise add refuses `unbound-credential`
1049
+ * without writing; `remove(id)` explicitly discards the orphan.
1012
1050
  */
1013
- unclaimed?: true;
1014
- }
1015
- interface VaultRosterFile {
1016
- version: 1;
1017
- view?: string;
1051
+ requireCredentialStamps?: boolean;
1052
+ /** Require an exact secret fingerprint for every roster-publication removal. */
1053
+ requireRemovedFingerprint?: boolean;
1054
+ /** Logical clock for refresh stamps and `addedAt`; filesystem leases always use wall time. */
1055
+ now?: () => number;
1018
1056
  /**
1019
- * False when the vault's reply carried records this consumer could not use.
1020
- * An incomplete reply never removes an account it may still hold: every
1021
- * previous member it does not account for is kept.
1057
+ * Ordered store-lock list held across every read-modify-write. Defaults to
1058
+ * the older writers' `save` lock at the config path, then at the state path.
1022
1059
  */
1023
- complete: boolean;
1024
- /** The unusable records of an incomplete reply: a safe id and a fixed reason. */
1025
- rejected?: SkippedVaultRecord[];
1026
- /** Opaque limits data; roster-only writers preserve even newer schemas. */
1027
- limits?: unknown;
1028
- rows: VaultRosterRow[];
1029
- declined: DeclinedAccount[];
1030
- }
1031
- interface ReorderVaultRosterResult {
1032
- /** The route id order now on disk. */
1033
- ids: string[];
1034
- /** `unchanged` when the roster was already in this order; nothing was written. */
1035
- outcome: 'reordered' | 'unchanged';
1036
- }
1037
- /**
1038
- * The receipt fields a quota or profile observation must carry to say which
1039
- * send (credential and account) it came from. Pass the
1040
- * `ClaustrumScopedAttempt` that send was authorized with.
1041
- */
1042
- type QuotaReceipt = Pick<ClaustrumScopedAttempt, 'credentialId' | 'accountIdentity' | 'accountIdentitySource' | 'expectedAccountIdentity'>;
1043
- /**
1044
- * How a started consumer learns about changes, for logs and status displays.
1045
- * `insula` is present when the consumer was given an insula source. Never
1046
- * carries secrets.
1047
- */
1048
- interface ClaustrumWatchState {
1049
- readonly vault: WatchMode;
1050
- readonly insula?: WatchMode;
1051
- }
1052
- type ClaustrumRequestedGrant = {
1053
- selector: {
1054
- category: string;
1055
- exact?: never;
1056
- } | {
1057
- exact: string;
1058
- category?: never;
1059
- };
1060
- operation: 'read' | 'list';
1061
- };
1062
- interface EnrollmentGrantProposal {
1063
- requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
1064
- /** Sent is not proof of access: the operator can approve without grants. */
1065
- requestedGrantsStatus?: 'sent' | 'dropped';
1066
- }
1067
- interface ClaustrumEnrollmentClient {
1068
- enrollPropose(input: {
1069
- name: string;
1070
- requestSecretHash: string;
1071
- displayName?: string;
1072
- requestedGrants?: ReadonlyArray<ClaustrumRequestedGrant>;
1073
- }): Promise<{
1074
- requestId: string;
1075
- }>;
1076
- enrollPoll(input: {
1077
- requestId: string;
1078
- requestSecret: string;
1079
- }): Promise<EnrollmentPollOutcome>;
1080
- }
1081
- interface ClaustrumEnrollmentConnection extends ClaustrumEnrollmentClient {
1082
- close(): void;
1083
- listScoped?: ClaustrumClient['listScoped'];
1084
- }
1085
- type ClaustrumEnrollmentStatus = {
1086
- state: 'idle';
1087
- } | (EnrollmentGrantProposal & {
1088
- state: 'pending';
1089
- proposedName: string;
1090
- requestId?: string;
1091
- retryCode?: string;
1092
- }) | (EnrollmentGrantProposal & {
1093
- state: 'approved';
1094
- proposedName: string;
1095
- approvedName?: string;
1096
- tokenGeneration: number;
1097
- }) | {
1098
- state: 'denied';
1099
- proposedName: string;
1100
- } | {
1101
- state: 'blocked';
1102
- proposedName: string;
1103
- code: string;
1104
- } | {
1105
- state: 'unavailable';
1106
- proposedName: string;
1107
- code: string;
1108
- } | {
1109
- state: 'busy';
1110
- };
1111
- interface ClaustrumEnrollmentPaths {
1112
- statePath: string;
1113
- tokenPath: string;
1060
+ storeLocks?: readonly PoolLockSpec[];
1061
+ /** Defaults for every lock the store takes (see `POOL_LOCK_DEFAULTS`). */
1062
+ lockOptions?: Partial<PoolLockOptions>;
1063
+ /** Overrides for the row locks only. */
1064
+ rowLockOptions?: Partial<PoolLockOptions>;
1065
+ /** The provider-wide lock; defaults to `provider-<provider>` beside the state file. */
1066
+ providerLock?: PoolLockSpec;
1067
+ /** Quota pull hook, fired without being awaited. */
1068
+ pull?: PullHook;
1069
+ /** Receives every pull failure, since no caller awaits a pull. */
1070
+ onPullFailure?: (rowId: string, error: PoolOperationError) => void | Promise<void>;
1071
+ logger?: PoolLogger;
1072
+ /** Named write steps, awaited; a test seam for crash and ownership rows. */
1073
+ onStep?: StoreContext['onStep'];
1074
+ /** Awaitable hold points on the refresh and pull paths; a test seam. */
1075
+ hold?: (point: HoldPoint, rowId: string) => void | Promise<void>;
1076
+ onLockEvent?: LockEnvironment['onLockEvent'];
1077
+ onLockStep?: LockEnvironment['onLockStep'];
1078
+ onRenewalTimer?: LockEnvironment['onRenewalTimer'];
1114
1079
  }
1115
1080
  /** Existing callbacks may return a promise for an in-progress quota poll. */
1116
1081
  type QuotaReadingRequest = ((id: string) => void) | ((id: string) => Promise<unknown> | undefined);
@@ -1354,6 +1319,89 @@ declare class OpenAiVault {
1354
1319
  /** Join the consumer's bounded drain so a restart cannot inherit a half-written lease. */
1355
1320
  dispose(): Promise<void>;
1356
1321
  }
1322
+ interface CodexEffortState {
1323
+ pinnedEffort?: string;
1324
+ effortUpdates?: Array<{
1325
+ anchor: number;
1326
+ fingerprint: string;
1327
+ effort: string;
1328
+ }>;
1329
+ }
1330
+ interface CanonicalInput {
1331
+ texts: string[];
1332
+ snapshots: unknown[];
1333
+ retainable: boolean;
1334
+ }
1335
+ declare const CODEX_VERSION = "0.166.0";
1336
+ declare const CODEX_USER_AGENT = "codex_exec/0.166.0 (Debian 12.0.0; aarch64) unknown (codex_exec; 0.166.0)";
1337
+ interface CodexSessionMetadata extends CodexEffortState {
1338
+ threadID: string;
1339
+ turnID: string;
1340
+ windowID: string;
1341
+ turnStartedAt?: number;
1342
+ input?: unknown[];
1343
+ canonicalInput?: CanonicalInput;
1344
+ }
1345
+ interface CodexRequestRuntime {
1346
+ now: () => number;
1347
+ uuid: () => string;
1348
+ }
1349
+ interface IdTokenClaims {
1350
+ chatgpt_account_id?: string;
1351
+ email?: string;
1352
+ organizations?: Array<{
1353
+ id: string;
1354
+ }>;
1355
+ 'https://api.openai.com/auth'?: {
1356
+ chatgpt_account_id?: string;
1357
+ };
1358
+ }
1359
+ declare function parseJwtClaims(token: string): IdTokenClaims | undefined;
1360
+ declare function extractAccountIdFromClaims(claims: IdTokenClaims): string | undefined;
1361
+ interface TokenResponse {
1362
+ id_token: string;
1363
+ access_token: string;
1364
+ refresh_token: string;
1365
+ expires_in?: number;
1366
+ }
1367
+ /**
1368
+ * Minimal shape of a fallback OAuth account for ingestion. Matches the
1369
+ * fields used by upsertAccount and beginAccountLogin, compatible with
1370
+ * the full OAuthAccount type in accounts.ts.
1371
+ */
1372
+ interface IngestAccount {
1373
+ id: string;
1374
+ label?: string;
1375
+ type: 'oauth';
1376
+ access?: string;
1377
+ refresh: string;
1378
+ expires?: number;
1379
+ enabled: boolean;
1380
+ addedAt: number;
1381
+ lastUsed: number;
1382
+ /**
1383
+ * When the token was obtained. Stamped at login so a freshly added account
1384
+ * carries a refresh marker — without it, the runtime-state merge cannot tell a
1385
+ * rotated token from a stale one (both default to 0) and a concurrent stale
1386
+ * save could roll the token back.
1387
+ */
1388
+ lastRefreshedAt?: number;
1389
+ /** Stable ChatGPT account identifier from the OAuth token claims. */
1390
+ accountId?: string;
1391
+ }
1392
+ interface BeginAccountLoginOptions {
1393
+ label?: string;
1394
+ headless?: boolean;
1395
+ signal?: AbortSignal;
1396
+ /** Host package version, sent as the version half of the `User-Agent`. */
1397
+ version: string;
1398
+ }
1399
+ interface BeginAccountLoginResult {
1400
+ url: string;
1401
+ instructions: string;
1402
+ /** Resolves after the user completes the OAuth flow with a ready-to-ingest account. */
1403
+ completion: Promise<IngestAccount>;
1404
+ }
1357
1405
  interface ResetTargetIdentity {
1358
1406
  accountKey: string;
1359
1407
  label: string;
@@ -1616,31 +1664,4 @@ interface RuntimeLayoutOptions {
1616
1664
  /** Test seam: how long to wait for the layout lock. */
1617
1665
  layoutLockWaitMs?: number;
1618
1666
  }
1619
- interface CanonicalInput {
1620
- texts: string[];
1621
- snapshots: unknown[];
1622
- retainable: boolean;
1623
- }
1624
- declare const RESPONSES_LITE_MODELS: ReadonlySet<string>;
1625
- declare const CODEX_VERSION = "0.166.0";
1626
- declare const CODEX_USER_AGENT = "codex_exec/0.166.0 (Debian 12.0.0; aarch64) unknown (codex_exec; 0.166.0)";
1627
- interface CodexSessionMetadata {
1628
- threadID: string;
1629
- turnID: string;
1630
- windowID: string;
1631
- turnStartedAt?: number;
1632
- input?: unknown[];
1633
- canonicalInput?: CanonicalInput;
1634
- /** Keep the opening effort fixed while later changes travel as input items. */
1635
- pinnedEffort?: string;
1636
- effortUpdates?: Array<{
1637
- anchor: number;
1638
- fingerprint: string;
1639
- effort: string;
1640
- }>;
1641
- }
1642
- interface CodexRequestRuntime {
1643
- now: () => number;
1644
- uuid: () => string;
1645
- }
1646
- export { AccountPaths as C, loadAccounts as S, parseJwtClaims as _, RESPONSES_LITE_MODELS as a, OAuthAccount as b, HostSlotAdapter as c, OpenAiVaultOptions as d, BeginAccountLoginOptions as f, extractAccountIdFromClaims as g, TokenResponse as h, CodexSessionMetadata as i, ResetTargetIdentity as l, IdTokenClaims as m, CODEX_VERSION as n, RuntimeLayoutOptions as o, BeginAccountLoginResult as p, CodexRequestRuntime as r, PoolLifecycleDeps as s, CODEX_USER_AGENT as t, OpenAiVault as u, AccountStorage as v, QuotaManager as w, OAuthQuotaSnapshot as x, FallbackAccount as y };
1667
+ export { AccountPaths as C, loadAccounts as S, BackgroundQuotaRefresh as _, BeginAccountLoginOptions as a, OAuthAccount as b, TokenResponse as c, CODEX_USER_AGENT as d, CODEX_VERSION as f, OpenAiVaultOptions as g, OpenAiVault as h, ResetTargetIdentity as i, extractAccountIdFromClaims as l, CodexSessionMetadata as m, PoolLifecycleDeps as n, BeginAccountLoginResult as o, CodexRequestRuntime as p, HostSlotAdapter as r, IdTokenClaims as s, RuntimeLayoutOptions as t, parseJwtClaims as u, AccountStorage as v, QuotaManager as w, OAuthQuotaSnapshot as x, FallbackAccount as y };