@cortexkit/opencode-openai-auth 1.17.2 → 1.18.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 (49) hide show
  1. package/dist/bin.js +8 -8
  2. package/dist/{codex-request-DYqSE0ti.d.ts → codex-request-CTIOw2EZ.d.ts} +322 -322
  3. package/dist/index-177kc3f1.js +64 -0
  4. package/dist/{index-emcf633z.js → index-1r7zznds.js} +1 -1
  5. package/dist/{index-y1b9ka54.js → index-2ecf254a.js} +21 -21
  6. package/dist/{index-qjh3h3wr.js → index-5czcaan0.js} +3 -3
  7. package/dist/index-5vh4jgb7.js +12 -0
  8. package/dist/index-96p0myg1.js +2 -0
  9. package/dist/{index-t09qaj5w.js → index-9sh2xnwr.js} +2 -2
  10. package/dist/{index-6pakkcrn.js → index-h7xxfm12.js} +1 -1
  11. package/dist/{index-b2pc3ze2.js → index-hrv1msdb.js} +1 -1
  12. package/dist/{index-7ea4dbe9.js → index-m6sq5g7q.js} +7 -7
  13. package/dist/{index-srdm5a4d.js → index-nkgxq9a6.js} +1 -1
  14. package/dist/{index-2dqwctzp.js → index-raj3tyyz.js} +1 -1
  15. package/dist/{index-vjk4wv2b.js → index-rs8z3per.js} +1 -1
  16. package/dist/index-smekt6zv.js +2 -0
  17. package/dist/index.d.ts +24 -24
  18. package/dist/index.js +1 -1
  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/sidebar-state.js +1 -1
  24. package/dist/{token-6ya278eg.js → token-kdjmv82a.js} +1 -1
  25. package/dist/token-util-71r7z2vr.js +1 -0
  26. package/dist/tui-preferences.js +1 -1
  27. package/dist/tui.d.ts +1 -1
  28. package/dist/v2/server.d.ts +1 -1
  29. package/dist/v2/server.js +3 -2
  30. package/package.json +2 -2
  31. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +1 -1
  32. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +3 -1
  33. package/src/tui-compiled/raw/shared/54eba94fd64c8c3c-index.js +1 -1
  34. package/src/tui-compiled/raw/shared/836fc615de6afbd9-settings.js +14 -4
  35. package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +1 -1
  36. package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +55 -49
  37. package/src/tui-compiled/raw/shared/cf4c37f3975c3a8d-canonical-file-path.js +6 -2
  38. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +1 -1
  39. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +3 -1
  40. package/src/tui-compiled/runtime/shared/54eba94fd64c8c3c-index.js +1 -1
  41. package/src/tui-compiled/runtime/shared/836fc615de6afbd9-settings.js +14 -4
  42. package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +1 -1
  43. package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +55 -49
  44. package/src/tui-compiled/runtime/shared/cf4c37f3975c3a8d-canonical-file-path.js +6 -2
  45. package/dist/index-4thkhwyp.js +0 -12
  46. package/dist/index-h8ychf80.js +0 -2
  47. package/dist/index-jmzh060w.js +0 -64
  48. package/dist/index-q7d43xxn.js +0 -2
  49. package/dist/token-util-ynanp4np.js +0 -1
@@ -3,128 +3,6 @@ import "@cortexkit/private-files";
3
3
  import { ClaustrumClient, EnrollmentPollOutcome } from "@cortexkit/claustrum-client";
4
4
  import { Plugin } from "@opencode/plugin";
5
5
  import "@opencode/plugin/promise/session";
6
- type OAuthCredential = {
7
- type: 'oauth';
8
- access?: string;
9
- refresh: string;
10
- expires?: number;
11
- };
12
- type ApiKeyCredential = {
13
- type: 'api';
14
- apiKey: string;
15
- baseURL: string;
16
- authHeader?: 'authorization-bearer' | 'x-api-key';
17
- };
18
- /** A credential as stored: an OAuth credential also carries its refresh stamp. */
19
- type StoredCredential = (OAuthCredential & {
20
- lastRefreshedAt?: number;
21
- }) | ApiKeyCredential;
22
- /** Quota codec supplied by `/quota`: the store never interprets the map itself. */
23
- interface QuotaCodec {
24
- validate(value: unknown): boolean;
25
- /** Normalize persisted quota before validation, when the codec supports it. */
26
- decode?(value: unknown): unknown;
27
- merge(stored: unknown | undefined, observation: unknown): unknown;
28
- }
29
- /**
30
- * What `ProviderStateCodec.onReplace` is told about a replacement: the row id,
31
- * the credential epoch the new credential starts, `previousIdentity` (the
32
- * identity the locked row recorded before the replace), `identity` (the
33
- * identity the replace records), and the provider state the caller handed to
34
- * `replace`, if any. Each identity is absent when none was recorded.
35
- */
36
- interface ProviderStateReplacement {
37
- id: string;
38
- credentialEpoch: number;
39
- previousIdentity?: string;
40
- identity?: string;
41
- incoming?: unknown;
42
- }
43
- /**
44
- * Codec for the provider state a plugin keeps beside each row's credential
45
- * (a project id, a device fingerprint, eligibility times: whatever belongs to
46
- * that credential). The store never interprets the value: it stores it as
47
- * JSON, asks `validate` before every write and on every load, and calls the
48
- * hooks below where two values meet. Every hook is synchronous and runs
49
- * under the store locks.
50
- */
51
- interface ProviderStateCodec {
52
- validate(value: unknown): boolean;
53
- /**
54
- * The part of a (valid) value that belongs to the credential: what is true
55
- * of the account the credential signs in to, such as a project id or a
56
- * device fingerprint, as opposed to what the plugin merely tracks about
57
- * its use, such as a cooldown or a cursor. The credential stamp covers the
58
- * digest of exactly this projection, so a foreign edit of it hides the
59
- * value, while the rest may change through `updateProviderState` without
60
- * the stamp being rewritten. It must be a pure function of the value that
61
- * returns JSON with a deterministic key order. Without it the whole value
62
- * is credential-bound.
63
- */
64
- credentialBound?(value: unknown): unknown;
65
- /**
66
- * Combines the value on disk with one a write brings (`add` of a secret the
67
- * pool already holds, `rotate`, or a refresh whose provider returned a
68
- * state). Called only when the row has a value on disk; without it the
69
- * incoming value replaces the stored one. Its result is validated.
70
- */
71
- merge?(onDisk: unknown, incoming: unknown): unknown;
72
- /**
73
- * The provider state of a row once `replace` gives it a new credential
74
- * epoch. `previous` is the old credential's value (undefined when the row
75
- * shows none). Returning undefined clears it. Without this hook a replace
76
- * keeps the value handed to `replace` and otherwise clears the state.
77
- */
78
- onReplace?(previous: unknown | undefined, replacement: ProviderStateReplacement): unknown | undefined;
79
- }
80
- /** Every library operation that can fail, as named in the failure value. */
81
- type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'updateLimitsNamespace' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
82
- /**
83
- * How far an operation got before it failed.
84
- *
85
- * `before-first-write`: nothing was written; both files are as they were.
86
- * `after-first-write`: the operation's first file write landed and a later one
87
- * did not; what that first write left is on disk and is never rolled back
88
- * (add: a state entry no roster row names, which no reader loads; replace:
89
- * the new credential stamped ahead of the config, which readers show as a
90
- * torn row and the next store write on it completes; rotate: the rotated
91
- * credential beside the old per-row entry). `pull`: a quota pull, or the
92
- * recording of its result, failed.
93
- */
94
- type PoolFailurePhase = 'before-first-write' | 'after-first-write' | 'pull';
95
- /**
96
- * Why an operation failed. `lock-contention` and `lock-ownership` are the two
97
- * lock outcomes (a wait that ran out, and a lease found lost); the rest are
98
- * refusals and failures of the operation itself.
99
- */
100
- 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';
101
- /**
102
- * The single failure value of every store operation. `committed` is present
103
- * only when the operation had already written a credential to the state file
104
- * before it failed (a partial rotation or refresh): it is the credential now
105
- * on disk, so a caller never has to re-read the files to learn it.
106
- */
107
- declare class PoolOperationError extends Error {
108
- readonly operation: PoolOperation;
109
- readonly rowId: string | undefined;
110
- readonly phase: PoolFailurePhase;
111
- readonly retryable: boolean;
112
- readonly kind: PoolFailureKind;
113
- readonly committed: StoredCredential | undefined;
114
- constructor(details: {
115
- operation: PoolOperation;
116
- rowId?: string;
117
- phase: PoolFailurePhase;
118
- retryable: boolean;
119
- kind: PoolFailureKind;
120
- committed?: StoredCredential;
121
- message?: string;
122
- cause?: unknown;
123
- });
124
- }
125
- interface PoolLogger {
126
- warn(message: string, data?: unknown): void;
127
- }
128
6
  interface LockLoss {
129
7
  readonly reason: 'taken-over' | 'expired' | 'unreadable' | 'renewal-failed' | 'marker-lost';
130
8
  readonly expectedOwnerId: string;
@@ -159,210 +37,56 @@ type RefreshFileLockOptions = {
159
37
  };
160
38
  /** Filesystem leases share wall time across all callers and processes. */
161
39
  declare function acquireRefreshFileLock(options: RefreshFileLockOptions): Promise<RefreshFileLock | null>;
162
- type LockStep = NonNullable<Parameters<typeof acquireRefreshFileLock>[0]['onStep']> extends ((step: infer S) => unknown) ? S : never;
163
- /** Tuning shared by every lock the store takes; each field is overridable. */
164
- interface PoolLockOptions {
165
- ttlMs: number;
166
- timeoutMs: number;
167
- retryMs: number;
168
- renew: boolean;
169
- renewIntervalMs?: number;
170
- }
171
- /** A lock: the (name, path) pair naming its file plus optional tuning. */
172
- interface PoolLockSpec extends Partial<PoolLockOptions> {
173
- name: string;
174
- path: string;
175
- }
176
- type LockEvent = {
177
- type: 'acquired' | 'released' | 'contended';
178
- name: string;
179
- path: string;
180
- };
181
- interface LockEnvironment {
182
- onLockEvent?: (event: LockEvent) => void;
183
- onLockStep?: (lock: {
184
- name: string;
185
- path: string;
186
- }, step: LockStep) => void | Promise<void>;
187
- onRenewalTimer?: (lock: {
188
- name: string;
189
- path: string;
190
- }, event: 'scheduled' | 'cancelled') => void;
191
- }
192
- /** Named points on the write path, for crash and ownership injection. */
193
- type WriteStep = 'before-config-write' | 'after-config-write' | 'before-state-write' | 'after-state-write';
194
- /** Awaitable pause points on the pull and refresh paths. */
195
- type HoldPoint = 'refresh-before-provider' | 'pull-before-request';
196
- interface StoreContext {
197
- provider: string;
198
- configPath: string;
199
- statePath: string;
200
- codec: QuotaCodec;
201
- /** The provider-state codec; without one no row shows a provider state. */
202
- providerState?: ProviderStateCodec;
40
+ type QuotaWindowName = string;
41
+ type ProviderQuotaFn = (input: {
42
+ accessToken: string;
43
+ fetchImpl: typeof fetch;
203
44
  now: () => number;
204
- storeLocks: readonly PoolLockSpec[];
205
- lockDefaults: PoolLockOptions;
206
- lockEnv: LockEnvironment;
207
- logger?: PoolLogger;
208
- onStep?: (step: WriteStep, info: {
209
- operation: PoolOperation;
210
- rowId: string | undefined;
211
- }) => void | Promise<void>;
212
- hold?: (point: HoldPoint, rowId: string) => void | Promise<void>;
213
- /** Ids whose per-row entry a library write dropped in this process. */
214
- removedIds: Set<string>;
45
+ }) => Promise<OAuthQuotaSnapshot>;
46
+ type QuotaEntry = {
47
+ quota: OAuthQuotaSnapshot;
48
+ refreshAfter: number;
49
+ checkedAt: number;
50
+ accountId?: string;
51
+ };
52
+ type QuotaManagerOptions = {
53
+ storage: AccountStorage | null;
54
+ fetchImpl?: typeof fetch;
215
55
  /**
216
- * When true, rows whose credential stamp is not bound load `unbound` and
217
- * the operations that use a credential refuse them (see
218
- * `OpenPoolStoreOptions.requireCredentialStamps`).
56
+ * Account config file this manager's cross-process refresh locks are named
57
+ * after. Host-resolved and required, so two hosts pointing at different
58
+ * stores never contend on one another's lock.
219
59
  */
220
- requireCredentialStamps?: boolean;
221
- requireRemovedFingerprint?: boolean;
222
- }
223
- /** Where a pull was fired from; `load` fires at most once per process per row. */
224
- type PullReason = 'load' | 'add' | 'replace' | 'admission';
225
- interface QuotaCommitTimer {
226
- now(): number;
227
- schedule(delayMs: number, run: () => Promise<void>): {
228
- cancel(): void;
229
- unref?(): void;
230
- };
231
- }
232
- /** What a pull is issued with: the credential and its attribution tuple. */
233
- interface PullRequest {
234
- id: string;
235
- credential: StoredCredential;
236
- credentialEpoch: number;
237
- identity?: string;
238
- reason: PullReason;
239
- }
240
- type PullHook = (request: PullRequest) => Promise<unknown>;
241
- interface OpenPoolStoreOptions {
242
- /** The provider every row of this pool belongs to; keys the provider-wide lock. */
243
- provider: string;
244
60
  configPath: string;
245
- statePath: string;
246
- quota: QuotaCodec;
247
- /**
248
- * Opt in to detached, coalesced quota publication, with any `quota` codec.
249
- * Each accepted observation is queued whole for its row and binding, and
250
- * the queue is applied in arrival order through `quota.merge` under the
251
- * store locks, so the codec's own merge decides which fields a newer or
252
- * older reading replaces. Accepted readings appear in read/load
253
- * immediately, merged the same way; the returned promise still rejects
254
- * current-row refusals before queueing. Await dispose or close at shutdown
255
- * to attempt a bounded drain; readings still pending at its timeout are
256
- * discarded. Normal quota commits are at least 30 seconds apart; a full
257
- * queue commits early so response handling never waits for that interval.
258
- */
259
- coalesceQuota?: boolean;
260
- /** Bounded quota drain on close/dispose, in milliseconds; defaults to 1,000. */
261
- quotaDrainTimeoutMs?: number;
262
- /** Monotonic clock and scheduling seam for detached quota commits. */
263
- quotaCommitTimer?: QuotaCommitTimer;
264
- /**
265
- * The codec of the provider state kept beside each row's credential (see
266
- * `ProviderStateCodec`). Without it no row shows a provider state, and
267
- * every write that would set one refuses (`invalid-input`); writes that
268
- * leave it alone keep the value on disk as it is, and `replace` clears it.
269
- */
270
- providerState?: ProviderStateCodec;
271
- /**
272
- * Refuse every credential this store did not stamp (default false, which
273
- * loads unstamped and mis-stamped credentials as older writers left them).
274
- * When true, a row whose `stamp` is not `bound` loads `unbound` and is no
275
- * candidate, and every operation that would use or keep its credential or
276
- * what was observed about it (`refresh`, quota pulls, `recordQuota`,
277
- * `recordIdentity`, `rotate`, and an `add` of the same secret or onto the
278
- * same credential-less row) refuses with `unbound-credential` before any
279
- * provider call or write, checked again under the locks and at commit.
280
- * Nothing makes such a row bound except `replace`, which starts a new
281
- * credential epoch and drops what was observed about the old one.
282
- * An interrupted add's state-only orphan is recovered only when its stamp
283
- * binds the stored and incoming material, including a supplied identity and
284
- * an API key's endpoint/header. Otherwise add refuses `unbound-credential`
285
- * without writing; `remove(id)` explicitly discards the orphan.
286
- */
287
- requireCredentialStamps?: boolean;
288
- /** Require an exact secret fingerprint for every roster-publication removal. */
289
- requireRemovedFingerprint?: boolean;
290
- /** Logical clock for refresh stamps and `addedAt`; filesystem leases always use wall time. */
291
- now?: () => number;
292
- /**
293
- * Ordered store-lock list held across every read-modify-write. Defaults to
294
- * the older writers' `save` lock at the config path, then at the state path.
295
- */
296
- storeLocks?: readonly PoolLockSpec[];
297
- /** Defaults for every lock the store takes (see `POOL_LOCK_DEFAULTS`). */
298
- lockOptions?: Partial<PoolLockOptions>;
299
- /** Overrides for the row locks only. */
300
- rowLockOptions?: Partial<PoolLockOptions>;
301
- /** The provider-wide lock; defaults to `provider-<provider>` beside the state file. */
302
- providerLock?: PoolLockSpec;
303
- /** Quota pull hook, fired without being awaited. */
304
- pull?: PullHook;
305
- /** Receives every pull failure, since no caller awaits a pull. */
306
- onPullFailure?: (rowId: string, error: PoolOperationError) => void | Promise<void>;
307
- logger?: PoolLogger;
308
- /** Named write steps, awaited; a test seam for crash and ownership rows. */
309
- onStep?: StoreContext['onStep'];
310
- /** Awaitable hold points on the refresh and pull paths; a test seam. */
311
- hold?: (point: HoldPoint, rowId: string) => void | Promise<void>;
312
- onLockEvent?: LockEnvironment['onLockEvent'];
313
- onLockStep?: LockEnvironment['onLockStep'];
314
- onRenewalTimer?: LockEnvironment['onRenewalTimer'];
315
- }
316
- type QuotaWindowName = string;
317
- type ProviderQuotaFn = (input: {
318
- accessToken: string;
319
- fetchImpl: typeof fetch;
320
- now: () => number;
321
- }) => Promise<OAuthQuotaSnapshot>;
322
- type QuotaEntry = {
323
- quota: OAuthQuotaSnapshot;
324
- refreshAfter: number;
325
- checkedAt: number;
326
- accountId?: string;
327
- };
328
- type QuotaManagerOptions = {
329
- storage: AccountStorage | null;
330
- fetchImpl?: typeof fetch;
331
- /**
332
- * Account config file this manager's cross-process refresh locks are named
333
- * after. Host-resolved and required, so two hosts pointing at different
334
- * stores never contend on one another's lock.
335
- */
336
- configPath: string;
337
- now?: () => number;
338
- /** Injected quota-fetch function — replaces the hard-imported Anthropic fetchOAuthQuotaSnapshot */
339
- fetchQuotaFn?: ProviderQuotaFn;
340
- onMainQuotaFetched?: (quota: OAuthQuotaSnapshot, checkedAt: number, fingerprint: string, fetchStartedAt: number) => void;
341
- onApiError?: (error: AccountOperationError) => void;
342
- };
343
- declare class QuotaManager {
344
- private main;
345
- private mainTokenFp;
346
- private mainQuotaAccountId;
347
- private fallbacks;
348
- private fallbackTokenFps;
349
- private inflightMain;
350
- private inflightMainFp;
351
- private inflightFallbacks;
352
- private mainLastApiError;
353
- private fallbackApiErrors;
354
- private fallbackErrorTokenFps;
355
- private rateLimitedUntilMap;
356
- private apiGate;
357
- private lastApiCallAt;
358
- private storage;
359
- private readonly fetchImpl;
360
- private readonly now;
361
- private readonly fetchQuotaFn;
362
- private readonly onMainQuotaFetched;
363
- private readonly onApiError;
364
- private readonly configPath;
365
- constructor(opts: QuotaManagerOptions);
61
+ now?: () => number;
62
+ /** Injected quota-fetch function — replaces the hard-imported Anthropic fetchOAuthQuotaSnapshot */
63
+ fetchQuotaFn?: ProviderQuotaFn;
64
+ onMainQuotaFetched?: (quota: OAuthQuotaSnapshot, checkedAt: number, fingerprint: string, fetchStartedAt: number) => void;
65
+ onApiError?: (error: AccountOperationError) => void;
66
+ };
67
+ declare class QuotaManager {
68
+ private main;
69
+ private mainTokenFp;
70
+ private mainQuotaAccountId;
71
+ private fallbacks;
72
+ private fallbackTokenFps;
73
+ private inflightMain;
74
+ private inflightMainFp;
75
+ private inflightFallbacks;
76
+ private mainLastApiError;
77
+ private fallbackApiErrors;
78
+ private fallbackErrorTokenFps;
79
+ private rateLimitedUntilMap;
80
+ private apiGate;
81
+ private lastApiCallAt;
82
+ private storage;
83
+ private readonly fetchImpl;
84
+ private readonly now;
85
+ private readonly fetchQuotaFn;
86
+ private readonly onMainQuotaFetched;
87
+ private readonly onApiError;
88
+ private readonly configPath;
89
+ constructor(opts: QuotaManagerOptions);
366
90
  /**
367
91
  * Cached main quota entry. Pass the live access token to enforce token
368
92
  * binding: if the cached entry was produced by a different token (main
@@ -695,6 +419,282 @@ type AccountStorage = {
695
419
  accounts: FallbackAccount[];
696
420
  };
697
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';
433
+ };
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;
444
+ }
445
+ /**
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.
451
+ */
452
+ interface ProviderStateReplacement {
453
+ id: string;
454
+ credentialEpoch: number;
455
+ previousIdentity?: string;
456
+ identity?: string;
457
+ incoming?: unknown;
458
+ }
459
+ /**
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.
466
+ */
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;
488
+ /**
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.
493
+ */
494
+ onReplace?(previous: unknown | undefined, replacement: ProviderStateReplacement): unknown | undefined;
495
+ }
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';
498
+ /**
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.
509
+ */
510
+ type PoolFailurePhase = 'before-first-write' | 'after-first-write' | 'pull';
511
+ /**
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.
515
+ */
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';
517
+ /**
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.
522
+ */
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;
543
+ }
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;
552
+ }
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;
557
+ }
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>;
597
+ /**
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`).
601
+ */
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;
629
+ /**
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.
640
+ */
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;
646
+ /**
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.
651
+ */
652
+ providerState?: ProviderStateCodec;
653
+ /**
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.
668
+ */
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;
674
+ /**
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.
677
+ */
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'];
697
+ }
698
698
  interface IdTokenClaims {
699
699
  chatgpt_account_id?: string;
700
700
  email?: string;