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