@cortexkit/common-auth 0.26.0 → 0.27.1

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 (43) hide show
  1. package/README.md +0 -16
  2. package/dist/claustrum/consumer.d.ts +77 -2
  3. package/dist/claustrum/consumer.js +320 -35
  4. package/dist/claustrum/custody.d.ts +36 -1
  5. package/dist/claustrum/custody.js +95 -11
  6. package/dist/claustrum/enrollment.js +37 -12
  7. package/dist/claustrum/hub.d.ts +195 -0
  8. package/dist/claustrum/hub.js +988 -0
  9. package/dist/claustrum/index.d.ts +13 -3
  10. package/dist/claustrum/index.js +37 -4
  11. package/dist/claustrum/quota-writer.d.ts +8 -1
  12. package/dist/claustrum/quota-writer.js +34 -12
  13. package/dist/claustrum/roster.d.ts +49 -1
  14. package/dist/claustrum/roster.js +187 -12
  15. package/dist/claustrum/shutdown.d.ts +8 -0
  16. package/dist/claustrum/shutdown.js +42 -0
  17. package/dist/fs/file-read-cache.d.ts +8 -0
  18. package/dist/fs/file-read-cache.js +57 -0
  19. package/dist/fs/refresh-file-lock.d.ts +1 -1
  20. package/dist/fs/refresh-file-lock.js +20 -11
  21. package/dist/opencode2/errors.d.ts +4 -1
  22. package/dist/opencode2/index.d.ts +2 -2
  23. package/dist/opencode2/index.js +1 -1
  24. package/dist/opencode2/install.d.ts +7 -5
  25. package/dist/opencode2/install.js +139 -13
  26. package/dist/opencode2/types.d.ts +42 -10
  27. package/dist/quota/commit-interval.d.ts +9 -0
  28. package/dist/quota/commit-interval.js +18 -0
  29. package/dist/redaction/index.d.ts +8 -0
  30. package/dist/redaction/index.js +490 -0
  31. package/dist/rpc/rpc-server.js +29 -19
  32. package/dist/setup/command.js +52 -14
  33. package/dist/setup/register.d.ts +2 -0
  34. package/dist/setup/register.js +90 -11
  35. package/dist/store/mutate.d.ts +2 -0
  36. package/dist/store/mutate.js +4 -0
  37. package/dist/store/pool.d.ts +6 -1
  38. package/dist/store/pool.js +1 -1
  39. package/dist/store/quota-writer.d.ts +5 -1
  40. package/dist/store/quota-writer.js +27 -13
  41. package/dist/store/settings.d.ts +1 -1
  42. package/dist/store/settings.js +16 -6
  43. package/package.json +6 -2
@@ -0,0 +1,42 @@
1
+ /** Retired generations report separately until their owner closes and shares one warning. */
2
+ export function shutdownWarning(logger, shutdown) {
3
+ let warned = false;
4
+ return (pendingOperations) => {
5
+ if (warned)
6
+ return;
7
+ if (!shutdown || shutdown.aborted)
8
+ warned = true;
9
+ logger.warn('claustrum shutdown drain timed out', { pendingOperations });
10
+ };
11
+ }
12
+ /**
13
+ * Give cancelled background work two seconds to release its handles without letting
14
+ * an unresponsive connector or disk hold the host's shutdown indefinitely.
15
+ */
16
+ export async function drainShutdown(pending, onTimeout) {
17
+ if (!pending.size)
18
+ return;
19
+ let timer;
20
+ let expired = false;
21
+ const drained = (async () => {
22
+ while (!expired && pending.size)
23
+ await Promise.allSettled([...pending]);
24
+ })();
25
+ try {
26
+ await Promise.race([
27
+ drained,
28
+ new Promise((resolve) => {
29
+ timer = setTimeout(() => {
30
+ expired = true;
31
+ resolve();
32
+ }, 2_000);
33
+ }),
34
+ ]);
35
+ if (expired && pending.size)
36
+ onTimeout(pending.size);
37
+ }
38
+ finally {
39
+ expired = true;
40
+ clearTimeout(timer);
41
+ }
42
+ }
@@ -0,0 +1,8 @@
1
+ import type { Stats } from 'node:fs';
2
+ type FileIdentity = Stats | 'absent';
3
+ /** Process-local reads, capped at 64 path sets with one value per resolved set. */
4
+ export declare class FileReadCache<T> {
5
+ #private;
6
+ read(paths: readonly string[], read: (resolvedPaths: string[]) => Promise<T>, validateHit?: (identities: readonly FileIdentity[]) => void): Promise<T>;
7
+ }
8
+ export {};
@@ -0,0 +1,57 @@
1
+ import { lstat } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ async function identity(path) {
4
+ try {
5
+ const metadata = await lstat(path);
6
+ // Do not follow a symlink: its target can change without changing the link.
7
+ return metadata.isFile() ? metadata : undefined;
8
+ }
9
+ catch (error) {
10
+ return error.code === 'ENOENT'
11
+ ? 'absent'
12
+ : undefined;
13
+ }
14
+ }
15
+ function sameIdentity(left, right) {
16
+ if (left === 'absent' || right === 'absent')
17
+ return left === right;
18
+ return (left.dev === right.dev &&
19
+ left.ino === right.ino &&
20
+ left.size === right.size &&
21
+ left.mtimeMs === right.mtimeMs &&
22
+ left.ctimeMs === right.ctimeMs);
23
+ }
24
+ /** Process-local reads, capped at 64 path sets with one value per resolved set. */
25
+ export class FileReadCache {
26
+ #entries = new Map();
27
+ async read(paths, read, validateHit) {
28
+ const resolvedPaths = paths.map((path) => resolve(path));
29
+ const key = JSON.stringify(resolvedPaths);
30
+ const probed = await Promise.all(resolvedPaths.map(identity));
31
+ const identities = probed.every((entry) => entry !== undefined)
32
+ ? probed
33
+ : undefined;
34
+ const cached = this.#entries.get(key);
35
+ if (identities &&
36
+ cached &&
37
+ identities.every((entry, index) => {
38
+ const previous = cached.identities[index];
39
+ return previous !== undefined && sameIdentity(entry, previous);
40
+ })) {
41
+ validateHit?.(identities);
42
+ return cached.value;
43
+ }
44
+ // A failed probe or read must not leave a previous successful value reusable.
45
+ this.#entries.delete(key);
46
+ const value = await read(resolvedPaths);
47
+ if (identities) {
48
+ if (this.#entries.size >= 64) {
49
+ const oldest = this.#entries.keys().next().value;
50
+ if (oldest !== undefined)
51
+ this.#entries.delete(oldest);
52
+ }
53
+ this.#entries.set(key, { identities, value });
54
+ }
55
+ return value;
56
+ }
57
+ }
@@ -28,7 +28,7 @@ type RefreshFileLockOptions = {
28
28
  onContended?: () => void;
29
29
  /** Synchronous, never awaited; throws and returned promise/thenable rejections are isolated. */
30
30
  onRenewalTimer?: (event: 'scheduled' | 'cancelled') => void;
31
- onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-observed' | 'lock-read-ready' | 'lock-missing' | 'stale-lock-confirmed' | 'stale-lock-removed' | 'stale-lock-recreated' | 'eviction-marker-acquired' | 'renewal-owner-confirmed' | 'renewal-marker-unavailable' | 'renewal-write-fenced' | 'renewal-write-ready' | 'renewal-write-finished' | 'relinquish-read' | 'renewal-finished' | 'release-owner-confirmed') => void | Promise<void>;
31
+ onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-observed' | 'lease-contention-read-ready' | 'lock-read-ready' | 'lock-missing' | 'stale-lock-confirmed' | 'stale-lock-removed' | 'stale-lock-recreated' | 'eviction-marker-acquired' | 'renewal-owner-confirmed' | 'renewal-marker-unavailable' | 'renewal-write-fenced' | 'renewal-write-ready' | 'renewal-write-finished' | 'relinquish-read' | 'renewal-finished' | 'release-owner-confirmed') => void | Promise<void>;
32
32
  };
33
33
  /** Filesystem leases share wall time across all callers and processes. */
34
34
  export declare function acquireRefreshFileLock(options: RefreshFileLockOptions): Promise<RefreshFileLock | null>;
@@ -178,19 +178,28 @@ export async function acquireRefreshFileLockWithClock(options) {
178
178
  }
179
179
  async function leaseContention(error) {
180
180
  const code = error.code;
181
- if (code === 'EEXIST') {
182
- if (windowsPrivateFiles)
183
- await readOwner();
184
- return true;
185
- }
186
- if (code === 'EISDIR') {
187
- if (windowsPrivateFiles) {
188
- await verifyPrivate(lockPath, 'directory', true);
189
- await readPrivateText(legacyOwnerPath, true);
181
+ if (code !== 'EEXIST' && code !== 'EISDIR')
182
+ return false;
183
+ if (windowsPrivateFiles) {
184
+ if (options.onStep)
185
+ await options.onStep('lease-contention-read-ready');
186
+ try {
187
+ if (code === 'EISDIR') {
188
+ await verifyPrivate(lockPath, 'directory', true);
189
+ await readPrivateText(legacyOwnerPath, true);
190
+ }
191
+ else
192
+ await readOwner();
193
+ }
194
+ catch (readError) {
195
+ // The holder can release after exclusive creation reports a collision.
196
+ // Only absence permits another acquisition attempt; security and sharing
197
+ // refusals must still escape rather than being treated as contention.
198
+ if (readError.code !== 'ENOENT')
199
+ throw readError;
190
200
  }
191
- return true;
192
201
  }
193
- return false;
202
+ return true;
194
203
  }
195
204
  async function tryAcquire() {
196
205
  if (windowsPrivateFiles)
@@ -8,8 +8,11 @@
8
8
  * - `host-credential-on-wire`: after every rewrite, a header still carried
9
9
  * one of the host's placeholder credentials. Sending it would leak a
10
10
  * non-routable value to the provider and fail with a confusing error.
11
+ * - `placement-refused`: an opt-in placeholder gate found the placeholder in
12
+ * multiple headers or outside the credential location it can serve. No
13
+ * account has been selected and no account headers have been read.
11
14
  */
12
- export type OpenCode2AuthFailureKind = 'no-account' | 'host-credential-on-wire';
15
+ export type OpenCode2AuthFailureKind = 'no-account' | 'host-credential-on-wire' | 'placement-refused';
13
16
  export declare class OpenCode2AuthError extends Error {
14
17
  readonly kind: OpenCode2AuthFailureKind;
15
18
  readonly providerID: string;
@@ -1,8 +1,8 @@
1
1
  export type { OpenCode2AuthFailureKind } from './errors.js';
2
2
  export { OpenCode2AuthError } from './errors.js';
3
- export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, } from './install.js';
3
+ export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, MAX_RETRY_HOLD_MS, } from './install.js';
4
4
  export type { FormAnswer, LoginContext, PoolAuthorization, PoolLoginMethod, RegisterOpenCode2AuthMethodsOptions, VaultActivationMethod, } from './integration.js';
5
5
  export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, VAULT_ACTIVATION_INSTRUCTIONS, } from './integration.js';
6
6
  export type { ServerSentEvent } from './sse.js';
7
7
  export { watchServerSentEvents } from './sse.js';
8
- export type { AccountHeadersResult, AccountRequest, Attempt, AttemptEndReason, AttemptOutcome, ChooseAccountInput, EventVerdict, HeaderEdits, HostError, InstallOpenCode2AuthOptions, LimitSignal, OpenCode2AuthAdapter, OpenCode2AuthEventName, OpenCode2AuthEvents, OpenCode2AuthInstallation, OpenCode2AuthLogger, OpenCode2HookContext, RequestKind, RequestScope, ResponseAccount, RetryReason, SelectingHook, Transport, } from './types.js';
8
+ export type { AccountHeadersResult, AccountRequest, Attempt, AttemptEndReason, AttemptOutcome, ChooseAccountInput, ChooseAccountResult, EventVerdict, HeaderEdits, HostError, InstallOpenCode2AuthOptions, LimitSignal, OpenCode2AuthAdapter, OpenCode2AuthEventName, OpenCode2AuthEvents, OpenCode2AuthInstallation, OpenCode2AuthLogger, OpenCode2HookContext, RequestKind, RequestScope, ResponseAccount, RetryHold, RetryReason, SelectingHook, Transport, } from './types.js';
@@ -1,4 +1,4 @@
1
1
  export { OpenCode2AuthError } from './errors.js';
2
- export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, } from './install.js';
2
+ export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, MAX_RETRY_HOLD_MS, } from './install.js';
3
3
  export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, VAULT_ACTIVATION_INSTRUCTIONS, } from './integration.js';
4
4
  export { watchServerSentEvents } from './sse.js';
@@ -1,5 +1,7 @@
1
- import type { HeaderEdits, InstallOpenCode2AuthOptions, OpenCode2AuthAdapter, OpenCode2AuthInstallation, OpenCode2HookContext } from './types.js';
1
+ import type { ChooseAccountResult, HeaderEdits, InstallOpenCode2AuthOptions, OpenCode2AuthAdapter, OpenCode2AuthInstallation, OpenCode2HookContext } from './types.js';
2
2
  export declare const DEFAULT_MAX_RECORDS = 512;
3
+ /** Bound adapter waits while allowing a 15-minute reset plus session jitter. */
4
+ export declare const MAX_RETRY_HOLD_MS: number;
3
5
  /**
4
6
  * The request header `model.request` sets to the attempt it started. The
5
7
  * host builds the HTTP request and the WebSocket handshake from the headers
@@ -49,8 +51,8 @@ export declare function applyHeaderEdits(target: Record<string, string>, edits:
49
51
  * compares the host-prepared secret exactly, then selects a fresh attempt only
50
52
  * for an owned send. Request-object attribution therefore needs no attempt
51
53
  * header. Frames are owned by the latest handshake of their session and kind;
52
- * retry runs only when the session's latest transport was owned. The host's
53
- * retry hook has no request identity, so concurrent mixed-ownership calls
54
- * cannot be distinguished there; owned retries retain the heuristic above.
54
+ * retry runs only when the session's latest transport was owned and the session
55
+ * has never mixed owned and foreign transports. The host's retry hook has no
56
+ * request identity, so a mixed session must keep the host's retry decision.
55
57
  */
56
- export declare function installOpenCode2Auth<Q, A = unknown>(ctx: OpenCode2HookContext, adapter: OpenCode2AuthAdapter<Q, A>, options?: InstallOpenCode2AuthOptions): Promise<OpenCode2AuthInstallation<Q, A>>;
58
+ export declare function installOpenCode2Auth<Q, A = unknown>(ctx: OpenCode2HookContext, adapter: OpenCode2AuthAdapter<Q, A, ChooseAccountResult>, options?: InstallOpenCode2AuthOptions): Promise<OpenCode2AuthInstallation<Q, A>>;
@@ -2,6 +2,8 @@ import { OpenCode2AuthError } from './errors.js';
2
2
  import { placeholderSecret } from './integration.js';
3
3
  import { watchServerSentEvents } from './sse.js';
4
4
  export const DEFAULT_MAX_RECORDS = 512;
5
+ /** Bound adapter waits while allowing a 15-minute reset plus session jitter. */
6
+ export const MAX_RETRY_HOLD_MS = 20 * 60 * 1000;
5
7
  /**
6
8
  * The request header `model.request` sets to the attempt it started. The
7
9
  * host builds the HTTP request and the WebSocket handshake from the headers
@@ -120,9 +122,9 @@ function applyHeaderEditsTo(target, edits) {
120
122
  * compares the host-prepared secret exactly, then selects a fresh attempt only
121
123
  * for an owned send. Request-object attribution therefore needs no attempt
122
124
  * header. Frames are owned by the latest handshake of their session and kind;
123
- * retry runs only when the session's latest transport was owned. The host's
124
- * retry hook has no request identity, so concurrent mixed-ownership calls
125
- * cannot be distinguished there; owned retries retain the heuristic above.
125
+ * retry runs only when the session's latest transport was owned and the session
126
+ * has never mixed owned and foreign transports. The host's retry hook has no
127
+ * request identity, so a mixed session must keep the host's retry decision.
126
128
  */
127
129
  export async function installOpenCode2Auth(ctx, adapter, options = {}) {
128
130
  const { providerID } = adapter;
@@ -142,10 +144,50 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
142
144
  const byRequest = new WeakMap();
143
145
  /** Retries the retry hook asked for, by `sessionID:kind`. */
144
146
  const pendingRetries = new Map();
147
+ // A shared clock orders each session's retries without retaining idle session state.
148
+ let retryOrder = 0;
145
149
  // The host names only session/kind for frames and only session for retry.
146
150
  // A transport's prepared credential, never global login state, owns these.
147
151
  const ownedSockets = new Set();
148
152
  const latestTransportOwned = new Map();
153
+ const transportSeen = new Map();
154
+ const mixed = (sessionID) => {
155
+ const seen = transportSeen.get(sessionID);
156
+ return seen?.ownedSeen === true && seen.foreignSeen;
157
+ };
158
+ const recordTransport = (sessionID, owned) => {
159
+ latestTransportOwned.set(sessionID, owned);
160
+ const seen = transportSeen.get(sessionID) ?? {
161
+ ownedSeen: false,
162
+ foreignSeen: false,
163
+ };
164
+ if (owned)
165
+ seen.ownedSeen = true;
166
+ else
167
+ seen.foreignSeen = true;
168
+ transportSeen.set(sessionID, seen);
169
+ };
170
+ const transportOwned = (scope, headers) => {
171
+ const refuse = ownership?.refuseMisplaced;
172
+ const carriers = refuse
173
+ ? [...headers].filter(([, value]) => value.includes(placeholderSecret(providerID)))
174
+ : [];
175
+ const owned = owns(headers) && (!refuse || carriers.length > 0);
176
+ if (refuse) {
177
+ if (carriers.length > 0 && (carriers.length !== 1 || !owned)) {
178
+ recordTransport(scope.sessionID, false);
179
+ throw new OpenCode2AuthError({
180
+ kind: 'placement-refused',
181
+ providerID,
182
+ sessionID: scope.sessionID,
183
+ requestKind: scope.kind,
184
+ message: refuse(carriers[0]?.[0] ?? ''),
185
+ });
186
+ }
187
+ }
188
+ recordTransport(scope.sessionID, owned);
189
+ return owned;
190
+ };
149
191
  let warnedUnprovenResponse = false;
150
192
  let warnedUnmarkedSend = false;
151
193
  const listeners = new Map();
@@ -358,9 +400,10 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
358
400
  await inChoiceOrder(scope.sessionID, () => releaseChoice(next));
359
401
  assertActive();
360
402
  }
361
- const accountId = matches
403
+ const choice = matches
362
404
  ? next.accountId
363
405
  : await adapter.chooseAccount(input);
406
+ const accountId = typeof choice === 'string' ? choice : undefined;
364
407
  return { input, accountId };
365
408
  });
366
409
  assertActive();
@@ -570,8 +613,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
570
613
  }, scoped));
571
614
  registrations.push(await ctx.session.hook('http.request', (draft) => {
572
615
  if (ownership) {
573
- const owned = owns(draft.request.headers);
574
- latestTransportOwned.set(draft.sessionID, owned);
616
+ const owned = transportOwned(scopeOf(draft), draft.request.headers);
575
617
  if (!owned)
576
618
  return;
577
619
  }
@@ -688,12 +730,11 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
688
730
  }, scoped));
689
731
  registrations.push(await ctx.session.hook('experimental.ws.handshake', (draft) => {
690
732
  if (ownership) {
691
- const owned = owns(new Headers(draft.headers));
692
733
  const key = keyOf(draft.sessionID, draft.kind);
693
- latestTransportOwned.set(draft.sessionID, owned);
694
734
  // Clear the previous handshake's ownership before selecting: if no
695
735
  // account can serve, subsequent frames must not use the old attempt.
696
736
  ownedSockets.delete(key);
737
+ const owned = transportOwned(scopeOf(draft), new Headers(draft.headers));
697
738
  if (!owned)
698
739
  return;
699
740
  }
@@ -714,7 +755,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
714
755
  if (!account || !attempt)
715
756
  throw noAccount(rec.scope);
716
757
  await failing(rec, async () => {
717
- applyHeaderEdits(draft.headers, rec.headers);
758
+ if (!ownership?.refuseMisplaced)
759
+ applyHeaderEdits(draft.headers, rec.headers);
718
760
  const url = adapter.rewriteHandshakeURL?.({
719
761
  ...account,
720
762
  url: draft.url,
@@ -722,6 +764,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
722
764
  });
723
765
  if (url !== undefined)
724
766
  draft.url = url;
767
+ if (ownership?.refuseMisplaced)
768
+ applyHeaderEdits(draft.headers, rec.headers);
725
769
  guard(rec.scope, Object.entries(draft.headers));
726
770
  if (ownership)
727
771
  ownedSockets.add(rec.key);
@@ -763,10 +807,21 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
763
807
  registrations.push(await ctx.session.hook('retry', async (draft) => {
764
808
  if (ownership && latestTransportOwned.get(draft.sessionID) !== true)
765
809
  return;
810
+ const hostDecision = draft.decision;
811
+ const hostDecides = () => emit('retry', {
812
+ sessionID: draft.sessionID,
813
+ attempt: draft.attempt,
814
+ reason: 'host-decides',
815
+ hostDecision,
816
+ decision: hostDecision,
817
+ });
818
+ if (mixed(draft.sessionID)) {
819
+ await hostDecides();
820
+ return;
821
+ }
766
822
  const picked = pickForRetry(draft.sessionID);
767
823
  if (!picked)
768
824
  return;
769
- const hostDecision = draft.decision;
770
825
  if (picked === 'ambiguous') {
771
826
  // Nothing tells which open attempt failed: keep the host's
772
827
  // decision and leave every attempt as it is.
@@ -782,6 +837,11 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
782
837
  const rec = picked;
783
838
  await withSelection(rec.scope, async (assertActive) => {
784
839
  const checkRetryActive = assertActive;
840
+ // Recheck after entering selection before attributing an identity-less error.
841
+ if (mixed(draft.sessionID)) {
842
+ await hostDecides();
843
+ return;
844
+ }
785
845
  rec.judged = true;
786
846
  const attempt = rec.attempt;
787
847
  if (attempt && !rec.outputStarted) {
@@ -799,11 +859,21 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
799
859
  checkRetryActive();
800
860
  const { decision, reason } = await inChoiceOrder(rec.scope.sessionID, async () => {
801
861
  checkRetryActive();
862
+ if (mixed(draft.sessionID))
863
+ return {
864
+ decision: hostDecision,
865
+ reason: 'host-decides',
866
+ };
802
867
  const old = pendingRetries.get(rec.key);
803
868
  pendingRetries.delete(rec.key);
804
869
  if (old?.next)
805
870
  await releaseChoice(old.next);
806
871
  checkRetryActive();
872
+ if (mixed(draft.sessionID))
873
+ return {
874
+ decision: hostDecision,
875
+ reason: 'host-decides',
876
+ };
807
877
  let decision = hostDecision;
808
878
  let reason;
809
879
  let rerouteFrom;
@@ -830,7 +900,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
830
900
  // next attempt would find no account (a `no-account` refusal
831
901
  // the host treats as a defect and does not retry) or go back
832
902
  // at once to the account that just refused.
833
- let accountId;
903
+ let choice;
834
904
  const input = {
835
905
  ...rec.scope,
836
906
  phase: 'retry',
@@ -838,7 +908,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
838
908
  rerouteFrom: refused,
839
909
  };
840
910
  try {
841
- accountId = await adapter.chooseAccount(input);
911
+ choice = await adapter.chooseAccount(input);
842
912
  }
843
913
  catch (error) {
844
914
  // Treated as no other account: the host's own decision
@@ -848,6 +918,12 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
848
918
  error: describe(error),
849
919
  });
850
920
  }
921
+ const hold = typeof choice === 'object' ? choice.hold : undefined;
922
+ const accountId = typeof choice === 'string'
923
+ ? choice
924
+ : hold
925
+ ? rec.accountId
926
+ : undefined;
851
927
  if (accountId !== undefined)
852
928
  next = { accountId, input };
853
929
  try {
@@ -859,7 +935,30 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
859
935
  await releaseChoice(next);
860
936
  throw error;
861
937
  }
862
- if (accountId !== undefined && accountId !== rec.accountId) {
938
+ // A foreign transport may have arrived while choosing. Do not
939
+ // publish or retain a retry choice for an unidentified call.
940
+ if (mixed(draft.sessionID)) {
941
+ if (next)
942
+ await releaseChoice(next);
943
+ return {
944
+ decision: hostDecision,
945
+ reason: 'host-decides',
946
+ };
947
+ }
948
+ if (hold &&
949
+ Number.isFinite(hold.delayMs) &&
950
+ hold.delayMs >= 0) {
951
+ // A recognised account limit can be recoverable even when
952
+ // the host treats its provider error as final.
953
+ decision = {
954
+ retry: true,
955
+ delay: Math.min(hold.delayMs, MAX_RETRY_HOLD_MS),
956
+ };
957
+ reason = 'hold';
958
+ }
959
+ else if (!hold &&
960
+ accountId !== undefined &&
961
+ accountId !== rec.accountId) {
863
962
  rec.rerouted = true;
864
963
  rerouteFrom = refused;
865
964
  // The next attempt takes this choice rather than asking
@@ -873,6 +972,10 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
873
972
  reason = 'reroute';
874
973
  }
875
974
  else {
975
+ if (hold && next) {
976
+ await releaseChoice(next);
977
+ next = undefined;
978
+ }
876
979
  // The refused account keeps the host's wait and serves the
877
980
  // retry. Undefined or a throw commits nothing: choose later.
878
981
  reason = 'host-decides-last-account';
@@ -892,6 +995,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
892
995
  pendingRetries.set(rec.key, {
893
996
  attemptId: rec.id,
894
997
  sessionID: rec.scope.sessionID,
998
+ order: ++retryOrder,
895
999
  accountId: rec.accountId,
896
1000
  ...(rerouteFrom === undefined ? {} : { rerouteFrom }),
897
1001
  ...(next === undefined ? {} : { next }),
@@ -922,6 +1026,10 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
922
1026
  const forgetSession = (sessionID) => {
923
1027
  revokeSelections(sessionID);
924
1028
  latestTransportOwned.delete(sessionID);
1029
+ // A foreign send can retry after forgetting and reuse of this session id.
1030
+ // Retain its ownership history until disposal; owned-only ids need no tombstone.
1031
+ if (!transportSeen.get(sessionID)?.foreignSeen)
1032
+ transportSeen.delete(sessionID);
925
1033
  for (const key of ownedSockets) {
926
1034
  if (JSON.parse(key)[0] === sessionID)
927
1035
  ownedSockets.delete(key);
@@ -945,6 +1053,23 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
945
1053
  for await (const event of events.subscribe({ signal: abort.signal })) {
946
1054
  if (event.type === 'session.deleted')
947
1055
  forgetSession(event.data.sessionID);
1056
+ else if (event.type === 'session.status' &&
1057
+ event.data.status.type === 'idle') {
1058
+ const sessionID = event.data.sessionID;
1059
+ const idleOrder = ++retryOrder;
1060
+ // Idle can arrive late from an earlier turn. Release only choices
1061
+ // already queued when observed, never a selection still in flight.
1062
+ void inChoiceOrder(sessionID, async () => {
1063
+ for (const [key, pending] of pendingRetries) {
1064
+ if (pending.sessionID === sessionID &&
1065
+ pending.order < idleOrder) {
1066
+ pendingRetries.delete(key);
1067
+ if (pending.next)
1068
+ await releaseChoice(pending.next);
1069
+ }
1070
+ }
1071
+ });
1072
+ }
948
1073
  }
949
1074
  }
950
1075
  catch (error) {
@@ -990,6 +1115,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
990
1115
  discardPending(key);
991
1116
  ownedSockets.clear();
992
1117
  latestTransportOwned.clear();
1118
+ transportSeen.clear();
993
1119
  listeners.clear();
994
1120
  await Promise.all(choiceWork.values());
995
1121
  await Promise.all(registrations.map(async (registration) => {
@@ -18,7 +18,7 @@ export interface RequestScope {
18
18
  /** Where a reading or a refusal was seen. */
19
19
  export type Transport = 'http' | 'ws';
20
20
  /**
21
- * A provider refusal that should move the request to another account: a rate
21
+ * A provider refusal that should wait or move the request to another account: a rate
22
22
  * limit, an exhausted usage window, or anything else the adapter decides is
23
23
  * tied to the account rather than to the request.
24
24
  */
@@ -53,7 +53,7 @@ export interface EventVerdict<Q> {
53
53
  */
54
54
  export type HeaderEdits = Readonly<Record<string, string | null>>;
55
55
  export interface ChooseAccountInput extends RequestScope {
56
- /** Informational: the retry hook's advance choice, or a request's own choice. */
56
+ /** The retry hook's advance choice (which may hold), or a request's own choice. */
57
57
  readonly phase: 'retry' | 'request';
58
58
  /**
59
59
  * The account of the attempt this one retries, when the retry hook just
@@ -64,8 +64,8 @@ export interface ChooseAccountInput extends RequestScope {
64
64
  /**
65
65
  * Set when the attempt this one retries was refused for a limit before any
66
66
  * output. The adapter should not pick `accountId` again unless it has
67
- * nothing else; returning it, or `undefined`, tells the retry hook that no
68
- * other account can serve, so the host's own retry decision stands.
67
+ * nothing else; returning it, or `undefined`, keeps the host's own retry
68
+ * decision. An explicit hold instead retains this account with its own wait.
69
69
  */
70
70
  readonly rerouteFrom?: {
71
71
  readonly accountId: string;
@@ -75,6 +75,19 @@ export interface ChooseAccountInput extends RequestScope {
75
75
  export interface AccountRequest extends RequestScope {
76
76
  readonly accountId: string;
77
77
  }
78
+ /** An explicit retry on the refused account, without moving its routing pin. */
79
+ export interface RetryHold {
80
+ readonly hold: {
81
+ /**
82
+ * Adapter-computed wait in milliseconds, including per-session jitter.
83
+ * Finite, non-negative values are clamped to MAX_RETRY_HOLD_MS (20 minutes).
84
+ * Invalid values keep the host's decision and release the choice.
85
+ */
86
+ readonly delayMs: number;
87
+ };
88
+ }
89
+ /** Holds are valid only in phase `retry`, with a recognised account limit. */
90
+ export type ChooseAccountResult = string | RetryHold | undefined;
78
91
  /**
79
92
  * One physical send: created when an account is chosen for a request, and
80
93
  * handed back on every hook call and event that belongs to that send, so a
@@ -164,8 +177,10 @@ export interface HostError {
164
177
  * Everything provider-specific the installer needs. `Q` is the plugin's own
165
178
  * quota reading type; the installer only carries it to the `quota` event.
166
179
  * `A` is the plugin's per-attempt value (see `Attempt`).
180
+ * `Choice` defaults to the legacy ID-only result so existing adapters' direct
181
+ * callers still see IDs. Opt into holds with `ChooseAccountResult`.
167
182
  */
168
- export interface OpenCode2AuthAdapter<Q = unknown, A = unknown> {
183
+ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends ChooseAccountResult = string | undefined> {
169
184
  /** Every hook is scoped to this provider; other providers are untouched. */
170
185
  readonly providerID: string;
171
186
  /**
@@ -179,14 +194,19 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown> {
179
194
  * with `phase: 'retry'` and `rerouteFrom` set. Every returned account,
180
195
  * including the refused one, is kept for the next attempt of that session
181
196
  * and kind: it does not choose again. Another account retries at once;
182
- * the refused account keeps the host's decision and wait. `undefined` or a
197
+ * the refused account keeps the host's decision and wait. `{ hold: { delayMs } }`
198
+ * commits the refused account without changing its pin and replaces the host's
199
+ * wait, even its no-retry decision, only for a recognised account limit before
200
+ * output in an untainted session. Holds returned in phase `request` cannot
201
+ * select an account and are treated as undefined. `undefined` or a
183
202
  * throw commits nothing: the host decides, and the next attempt chooses
184
203
  * with `phase: 'request'`, `previousAccountId` and no `rerouteFrom`.
185
204
  */
186
- chooseAccount(input: ChooseAccountInput): Promise<string | undefined> | string | undefined;
205
+ chooseAccount(input: ChooseAccountInput): Promise<Choice> | Choice;
187
206
  /**
188
207
  * Releases a kept retry choice that will not be used: no retry, a changed
189
- * model or agent, session forgetting/deletion, disposal or record eviction.
208
+ * model or agent, cancellation of a queued retry (session idle), session forgetting/deletion,
209
+ * disposal or record eviction. A hold releases the refused account's choice.
190
210
  * Called once with the original choose input plus its returned accountId,
191
211
  * never for a used choice. Awaited before any later chooseAccount for the
192
212
  * same session; errors are logged and swallowed. A model/agent change
@@ -349,6 +369,13 @@ export interface InstallOpenCode2AuthOptions {
349
369
  */
350
370
  readonly gateOnPlaceholder?: {
351
371
  readonly credential: (headers: Headers) => string | undefined;
372
+ /**
373
+ * Refuse misplaced placeholders before selecting an account. The placeholder
374
+ * must occur in exactly one header and be the extracted secret. Receives a
375
+ * carrier header name for the refusal message. Also runs the handshake URL
376
+ * rewrite before applying account headers to the draft. Opt-in only.
377
+ */
378
+ readonly refuseMisplaced?: (header: string) => string;
352
379
  };
353
380
  /**
354
381
  * Values that must never reach the wire, normally the placeholder the host
@@ -372,9 +399,12 @@ export interface InstallOpenCode2AuthOptions {
372
399
  * no other account can serve the next attempt, so the host's own decision
373
400
  * (its wait, or its refusal to retry) stands and the next attempt may go
374
401
  * to the refused account again;
375
- * - `host-decides`: no limit was recognised, so the host's decision stands.
402
+ * - `hold`: an explicit adapter wait on the refused account, before output;
403
+ * - `host-decides`: no limit was recognised, or the failing call cannot be
404
+ * attributed safely (ambiguous attempts or mixed ownership in a gated
405
+ * session), so the host's decision stands.
376
406
  */
377
- export type RetryReason = 'reroute' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
407
+ export type RetryReason = 'reroute' | 'hold' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
378
408
  /**
379
409
  * The hook that picked an account. Normally `model.request`; a transport hook
380
410
  * picks only when the host skipped `model.request` for that request, which a
@@ -441,6 +471,8 @@ export interface OpenCode2AuthInstallation<Q, A = unknown> {
441
471
  /**
442
472
  * Drops every attempt and revokes in-flight auth selections of a session.
443
473
  * Session deletion does this itself. Later requests may reuse the session id.
474
+ * Foreign transport history survives until dispose: an old foreign call can
475
+ * still retry under that reused id, so forgetting cannot clear retry taint.
444
476
  */
445
477
  forgetSession(sessionID: string): void;
446
478
  /** Number of attempts held. */
@@ -0,0 +1,9 @@
1
+ export declare const QUOTA_COMMIT_INTERVAL_MS = 30000;
2
+ export interface QuotaCommitTimer {
3
+ now(): number;
4
+ schedule(delayMs: number, run: () => Promise<void>): {
5
+ cancel(): void;
6
+ unref?(): void;
7
+ };
8
+ }
9
+ export declare const quotaCommitTimer: QuotaCommitTimer;