@cortexkit/opencode-antigravity-auth 3.0.19 → 3.0.20

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 (71) hide show
  1. package/README.md +3 -1
  2. package/dist/cli.js +202 -118
  3. package/dist/cli.js.map +3 -3
  4. package/dist/cli.meta.json +18 -18
  5. package/dist/index.js +256 -172
  6. package/dist/index.js.map +3 -3
  7. package/dist/index.meta.json +18 -18
  8. package/dist/server.js +269 -185
  9. package/dist/server.js.map +3 -3
  10. package/dist/server.meta.json +1 -1
  11. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +10 -0
  12. package/dist/src/common-auth-embedded/claustrum/consumer.js +25 -0
  13. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +6 -2
  14. package/dist/src/common-auth-embedded/claustrum/custody.js +20 -6
  15. package/dist/src/common-auth-embedded/claustrum/hub.d.ts +3 -1
  16. package/dist/src/common-auth-embedded/claustrum/hub.js +55 -5
  17. package/dist/src/common-auth-embedded/claustrum/roster.js +1 -1
  18. package/dist/src/common-auth-embedded/fs/refresh-file-lock.d.ts +2 -1
  19. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +3 -1
  20. package/dist/src/common-auth-embedded/fs/with-lock.js +1 -1
  21. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  22. package/dist/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  23. package/dist/src/common-auth-embedded/opencode2/install.js +144 -17
  24. package/dist/src/common-auth-embedded/opencode2/types.d.ts +52 -1
  25. package/dist/src/common-auth-embedded/source-output.json +48 -48
  26. package/dist/src/ga/tui/host-ga.d.ts.map +1 -1
  27. package/dist/src/ga/tui/host-ga.js +0 -1
  28. package/dist/src/ga/tui/host-ga.js.map +1 -1
  29. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  30. package/dist/src/server.d.ts +4 -4
  31. package/dist/src/server.js +4 -4
  32. package/dist/src/tui/sidebar-frame.d.ts +3 -4
  33. package/dist/src/tui/sidebar-frame.d.ts.map +1 -1
  34. package/dist/src/tui/sidebar-frame.js +4 -8
  35. package/dist/src/tui/sidebar-frame.js.map +1 -1
  36. package/dist/src/tui.js +1 -1
  37. package/dist/tui-build-map.json +9 -9
  38. package/dist/tui-ga-build-map.json +9 -9
  39. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +10 -0
  40. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +6 -2
  41. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +3 -1
  42. package/dist/types/src/common-auth-embedded/fs/refresh-file-lock.d.ts +2 -1
  43. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  44. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  45. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +52 -1
  46. package/dist/types/src/server.d.ts +4 -4
  47. package/package.json +3 -3
  48. package/src/common-auth-embedded/claustrum/consumer.d.ts +10 -0
  49. package/src/common-auth-embedded/claustrum/consumer.js +25 -0
  50. package/src/common-auth-embedded/claustrum/custody.d.ts +6 -2
  51. package/src/common-auth-embedded/claustrum/custody.js +20 -6
  52. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -1
  53. package/src/common-auth-embedded/claustrum/hub.js +55 -5
  54. package/src/common-auth-embedded/claustrum/roster.js +1 -1
  55. package/src/common-auth-embedded/fs/refresh-file-lock.d.ts +2 -1
  56. package/src/common-auth-embedded/fs/refresh-file-lock.js +3 -1
  57. package/src/common-auth-embedded/fs/with-lock.js +1 -1
  58. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  59. package/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  60. package/src/common-auth-embedded/opencode2/install.js +144 -17
  61. package/src/common-auth-embedded/opencode2/types.d.ts +52 -1
  62. package/src/common-auth-embedded/source-output.json +48 -48
  63. package/src/tui-compiled/tui/sidebar-frame.js +35 -72
  64. package/src/tui-compiled/tui.js +1 -1
  65. package/src/tui-ga-compiled/host-ga.js +0 -1
  66. package/src/tui-ga-compiled/shared/ced204104a639c9c-sidebar-frame.js +35 -72
  67. package/src/tui-ga-raw/host-ga.tsx +0 -1
  68. package/src/tui-ga-raw/shared/ced204104a639c9c-sidebar-frame.tsx +7 -29
  69. package/src/tui-raw/tui/sidebar-frame.tsx +7 -29
  70. package/src/tui-raw/tui.tsx +1 -1
  71. package/src/tui.tsx +1 -1
@@ -50,6 +50,12 @@ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
50
50
  * routine token refresh, which never moves the view.
51
51
  */
52
52
  onRoster?: (roster: VaultRosterFile) => void;
53
+ /**
54
+ * Called once when a coalesced discovery starts, with its completion promise.
55
+ * Covers explicit refresh, poll, watch and send-triggered discovery, even when
56
+ * the view does not change. Observe rejection when attaching async work.
57
+ */
58
+ onDiscovery?: (promise: Promise<VaultRosterFile | undefined>) => void;
53
59
  onError?: (error: unknown) => void;
54
60
  /**
55
61
  * How often `start()` ticks. A tick lists the vault when no vault watch is
@@ -104,6 +110,8 @@ export interface HubMemberPort {
104
110
  keptReceiptState(): KeptReceiptState;
105
111
  /** Apply the union of every member's roster in memory to kept receipts. */
106
112
  retainUnion(): void;
113
+ /** Share a committed preference change with live members using this roster file. */
114
+ publishRoster(roster: VaultRosterFile): void;
107
115
  forget(credentialId: string): void;
108
116
  /** The member closed: the hub stops committing and pushing to it. */
109
117
  detach(): void;
@@ -113,6 +121,8 @@ export interface HubRefreshOutcome {
113
121
  }
114
122
  /** What the hub may do to one member's memory. Package-internal. */
115
123
  export interface HubMemberHooks {
124
+ /** Observe a hub discovery without relying on member refresh overrides. */
125
+ discovery(promise: Promise<HubRefreshOutcome | undefined>): void;
116
126
  /**
117
127
  * Set the roster in memory as a consumer's own refresh does (pending quota
118
128
  * readings included) and notify `onRoster` when its view changed.
@@ -314,8 +314,17 @@ export class ClaustrumConsumer {
314
314
  this.#refreshing = undefined;
315
315
  });
316
316
  this.#track(this.#refreshing);
317
+ this.#notifyDiscovery(this.#refreshing);
317
318
  return this.#refreshing;
318
319
  }
320
+ #notifyDiscovery(promise) {
321
+ try {
322
+ this.#options.onDiscovery?.(promise);
323
+ }
324
+ catch (error) {
325
+ this.#options.onError?.(error);
326
+ }
327
+ }
319
328
  /**
320
329
  * Poll in the background and open the vault and insula watches. Until the
321
330
  * vault watch is accepted, and whenever it is unavailable, every tick lists
@@ -571,6 +580,13 @@ export class ClaustrumConsumer {
571
580
  /** The hub's handle on this member's memory. */
572
581
  #hubHooks() {
573
582
  return {
583
+ discovery: (promise) => {
584
+ const hub = this.#hub;
585
+ if (!hub || !this.#options.onDiscovery || this.#shutdown.signal.aborted)
586
+ return;
587
+ const discovery = this.#track(promise.then((outcome) => this.#hubOutcome(hub, outcome)));
588
+ this.#notifyDiscovery(discovery);
589
+ },
574
590
  install: (roster) => {
575
591
  if (this.#shutdown.signal.aborted)
576
592
  return;
@@ -607,6 +623,9 @@ export class ClaustrumConsumer {
607
623
  */
608
624
  async #hubRefresh(hub) {
609
625
  const outcome = await hub.refresh();
626
+ return this.#hubOutcome(hub, outcome);
627
+ }
628
+ #hubOutcome(hub, outcome) {
610
629
  this.#assertOpen();
611
630
  if (!outcome)
612
631
  return undefined;
@@ -788,6 +807,8 @@ export class ClaustrumConsumer {
788
807
  this.#assertOpen();
789
808
  await declineVaultRoute(this.#options.rosterPath, routeId);
790
809
  this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
810
+ if (this.#roster)
811
+ this.#hub?.publishRoster(this.#roster);
791
812
  // A hub member shares kept receipts with every other member, so they are
792
813
  // retained against all members' rosters, never against this one alone.
793
814
  if (this.#hub)
@@ -799,6 +820,8 @@ export class ClaustrumConsumer {
799
820
  this.#assertOpen();
800
821
  await acceptVaultRoute(this.#options.rosterPath, routeId);
801
822
  this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
823
+ if (this.#roster)
824
+ this.#hub?.publishRoster(this.#roster);
802
825
  }
803
826
  /**
804
827
  * Set the order vault accounts are tried in (`reorderVaultRoster`), then
@@ -809,6 +832,8 @@ export class ClaustrumConsumer {
809
832
  this.#assertOpen();
810
833
  const result = await reorderVaultRoster(this.#options.rosterPath, routeIds);
811
834
  this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
835
+ if (this.#roster)
836
+ this.#hub?.publishRoster(this.#roster);
812
837
  return result;
813
838
  }
814
839
  /**
@@ -25,7 +25,8 @@ export interface ClaustrumFamily {
25
25
  /** Non-secret classification facts, including rows decoded by older clients. */
26
26
  export interface VaultRowFacts {
27
27
  readonly credentialId: string;
28
- readonly credentialType: string;
28
+ /** Internal serving type derived from `authMethod`, not the id's type hint. */
29
+ readonly credentialType: VaultCredentialType;
29
30
  readonly authMethod?: string;
30
31
  readonly refreshAdapter?: string;
31
32
  readonly providerIds?: readonly string[];
@@ -108,7 +109,10 @@ export interface VaultInventory {
108
109
  readonly view: string;
109
110
  readonly credentials: readonly VaultCredential[];
110
111
  readonly skipped: readonly SkippedVaultRecord[];
111
- /** Classifying families only: fixed refusal codes, never classifier errors. */
112
+ /**
113
+ * Classifying families only: declared policy codes or the fixed library codes
114
+ * `unknown-auth-method`, `unmapped` and `unclassified`, never classifier errors.
115
+ */
112
116
  readonly refused?: readonly {
113
117
  credentialId?: string;
114
118
  code: string;
@@ -85,16 +85,28 @@ function credentialTypeOf(row, family) {
85
85
  return notMine;
86
86
  if (!row.categories.includes(family.category))
87
87
  return notMine;
88
- if (row.credentialType !== 'oauth' && row.credentialType !== 'api_key')
89
- return notMine;
90
88
  if ('classify' in family) {
91
- // Older clients omit these facts entirely; do not call a policy that needs them.
89
+ const metadata = rowFactsOf(row);
90
+ let type;
91
+ // The id's type is only a hint; the vault's auth method determines serving.
92
+ switch (metadata.authMethod) {
93
+ case 'apikey':
94
+ type = 'api_key';
95
+ break;
96
+ case 'chatgpt':
97
+ case 'antigravity':
98
+ case 'oauth':
99
+ type = 'oauth';
100
+ break;
101
+ default:
102
+ return { kind: 'refused', code: 'unknown-auth-method' };
103
+ }
92
104
  const facts = {
93
105
  credentialId: row.id,
94
- credentialType: row.credentialType,
106
+ credentialType: type,
95
107
  categories: row.categories,
96
108
  refreshAdapter: row.refreshAdapter,
97
- ...rowFactsOf(row),
109
+ ...metadata,
98
110
  };
99
111
  if (facts.providerIds === undefined)
100
112
  return { kind: 'refused', code: 'unmapped' };
@@ -103,7 +115,7 @@ function credentialTypeOf(row, family) {
103
115
  if (result.kind === 'not-mine')
104
116
  return notMine;
105
117
  if (result.kind === 'mine' && typeof result.member === 'string')
106
- return { kind: 'mine', type: row.credentialType, member: result.member };
118
+ return { kind: 'mine', type, member: result.member };
107
119
  if (result.kind === 'refused' &&
108
120
  typeof result.code === 'string' &&
109
121
  /^[a-z][a-z0-9-]{0,31}$/.test(result.code) &&
@@ -116,6 +128,8 @@ function credentialTypeOf(row, family) {
116
128
  }
117
129
  return { kind: 'refused', code: 'unclassified' };
118
130
  }
131
+ if (row.credentialType !== 'oauth' && row.credentialType !== 'api_key')
132
+ return notMine;
119
133
  if (row.credentialType === 'oauth')
120
134
  return row.refreshAdapter === family.refreshAdapter
121
135
  ? { kind: 'mine', type: 'oauth' }
@@ -1,5 +1,5 @@
1
1
  import type { QuotaObservation } from '../quota/index.js';
2
- import { type ClaustrumConsumer } from './consumer.js';
2
+ import { type ClaustrumConsumer, type ClaustrumConsumerOptions } from './consumer.js';
3
3
  import { type ClassifyingClaustrumFamily, type ClaustrumScopedClient, ClaustrumScopedCustody, type IdentityParser, type KeptReceiptState, type VaultGrantReach } from './custody.js';
4
4
  import { type ClaustrumLogger } from './errors.js';
5
5
  import { type AccountMapper, type VaultRosterFile } from './roster.js';
@@ -100,6 +100,8 @@ export interface ClaustrumHubMemberOptions<_Q = QuotaObservation> {
100
100
  reservedRouteIds?: () => Iterable<string>;
101
101
  /** As `ClaustrumConsumerOptions.onRoster`: once per change of view. */
102
102
  onRoster?: (roster: VaultRosterFile) => void;
103
+ /** Observe every hub discovery's member result, including background work. */
104
+ onDiscovery?: ClaustrumConsumerOptions<_Q>['onDiscovery'];
103
105
  /** This member's own failures, such as a roster commit that failed. */
104
106
  onError?: (error: unknown) => void;
105
107
  logger?: ClaustrumLogger;
@@ -12,7 +12,7 @@
12
12
  // never replaces a view another process committed after this hub listed.
13
13
  import { createHash } from 'node:crypto';
14
14
  import { readdir, stat } from 'node:fs/promises';
15
- import { dirname, join } from 'node:path';
15
+ import { dirname, join, resolve } from 'node:path';
16
16
  import { createLogger } from '../logger/index.js';
17
17
  import { combineAbortSignals } from '../util/any-signal.js';
18
18
  import { ClaustrumUnreachableError } from './availability.js';
@@ -23,6 +23,8 @@ import { ClaustrumConsumerError } from './errors.js';
23
23
  import { DEFAULT_ROUTE_PREFIX, decodedVaultRoster, forgetPendingVaultDiscovery, isVaultRosterLockRefusal, readVaultRoster, refreshVaultRoster, vaultRosterSeed, } from './roster.js';
24
24
  import { drainShutdown, shutdownWarning } from './shutdown.js';
25
25
  import { SAFETY_POLL_MS } from './watch.js';
26
+ /** Published rosters are shared only in memory; file locks still order commits. */
27
+ const sharedRosters = new Map();
26
28
  /** Lowercase ASCII, safe as a file name on every OS. */
27
29
  const FILE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
28
30
  /** Device names Windows reserves in every directory, with any extension. */
@@ -250,9 +252,11 @@ export class ClaustrumDiscoveryHub {
250
252
  watchMode: () => this.watchState(),
251
253
  keptReceiptState: () => this.keptReceiptState(),
252
254
  retainUnion: () => this.#retainUnion(),
255
+ publishRoster: (roster) => this.#publishRoster(entry, roster),
253
256
  forget: (credentialId) => this.#current?.custody?.forget(credentialId),
254
257
  detach: () => {
255
258
  entry.closed = true;
259
+ entry.releaseRoster?.();
256
260
  },
257
261
  };
258
262
  const consumerOptions = {
@@ -265,14 +269,58 @@ export class ClaustrumDiscoveryHub {
265
269
  }),
266
270
  ...(this.#options.mapAccount && { mapAccount: this.#options.mapAccount }),
267
271
  ...(options.onRoster && { onRoster: options.onRoster }),
272
+ ...(options.onDiscovery && { onDiscovery: options.onDiscovery }),
268
273
  ...(options.onError && { onError: options.onError }),
269
274
  logger: options.logger ?? this.#logger,
270
275
  ...(this.#options.now && { now: this.#options.now }),
271
276
  };
272
277
  const { consumer, hooks } = createHubMember(port, consumerOptions);
273
278
  entry.hooks = hooks;
279
+ const path = resolve(entry.path);
280
+ const subscribers = sharedRosters.get(path) ?? new Set();
281
+ const install = (roster) => {
282
+ // A peer cannot reactivate an off or closed member, or install routes
283
+ // that collide with this plugin instance's local pool.
284
+ if (entry.closed ||
285
+ this.#active !== true ||
286
+ !this.#current ||
287
+ !this.#live(this.#current) ||
288
+ !hooks.roster() ||
289
+ this.#collides(hooks, roster))
290
+ return;
291
+ entry.seen = JSON.stringify(decodedVaultRoster(roster));
292
+ hooks.install(roster);
293
+ if (roster.view !== this.#committed?.view)
294
+ entry.pending ??= { failures: 0, wait: 0 };
295
+ this.#retainUnion();
296
+ };
297
+ subscribers.add(install);
298
+ entry.receiveRoster = install;
299
+ sharedRosters.set(path, subscribers);
300
+ let subscribed = true;
301
+ entry.releaseRoster = () => {
302
+ if (!subscribed)
303
+ return;
304
+ subscribed = false;
305
+ subscribers.delete(install);
306
+ if (!subscribers.size)
307
+ sharedRosters.delete(path);
308
+ };
274
309
  return consumer;
275
310
  }
311
+ #publishRoster(entry, roster) {
312
+ const generation = this.#current;
313
+ if (entry.closed || !generation || !this.#live(generation))
314
+ return;
315
+ entry.seen = JSON.stringify(decodedVaultRoster(roster));
316
+ entry.hooks?.install(roster);
317
+ for (const install of sharedRosters.get(resolve(entry.path)) ?? []) {
318
+ if (!this.#live(generation))
319
+ return;
320
+ if (install !== entry.receiveRoster)
321
+ install(roster);
322
+ }
323
+ }
276
324
  // --- leases ---
277
325
  #startGeneration() {
278
326
  const generation = {
@@ -582,6 +630,8 @@ export class ClaustrumDiscoveryHub {
582
630
  }));
583
631
  run.promise = promise;
584
632
  this.#run = run;
633
+ for (const entry of this.#open())
634
+ entry.hooks?.discovery(promise);
585
635
  return promise;
586
636
  }
587
637
  /**
@@ -681,9 +731,7 @@ export class ClaustrumDiscoveryHub {
681
731
  continue;
682
732
  }
683
733
  // The push: memory holds the committed roster before refresh resolves.
684
- entry.seen = JSON.stringify(decodedVaultRoster(roster));
685
- if (!entry.closed)
686
- hooks.install(roster);
734
+ this.#publishRoster(entry, roster);
687
735
  }
688
736
  if (!this.#live(generation))
689
737
  return undefined;
@@ -850,7 +898,7 @@ export class ClaustrumDiscoveryHub {
850
898
  }
851
899
  const before = enabledRows(memory);
852
900
  entry.seen = content;
853
- hooks.install(file);
901
+ this.#publishRoster(entry, file);
854
902
  if (enabledRows(hooks.roster()) !== before)
855
903
  this.#retainUnion();
856
904
  }
@@ -1013,6 +1061,8 @@ export class ClaustrumDiscoveryHub {
1013
1061
  if (this.#shutdown.signal.aborted)
1014
1062
  return;
1015
1063
  this.#shutdown.abort(closed('Claustrum discovery hub is closed'));
1064
+ for (const entry of this.#members.values())
1065
+ entry.releaseRoster?.();
1016
1066
  if (this.#timer)
1017
1067
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
1018
1068
  this.#timer = undefined;
@@ -810,7 +810,7 @@ export async function refreshVaultRoster(options) {
810
810
  throw error;
811
811
  }
812
812
  finally {
813
- await lease.release();
813
+ await lease.release(options.signal);
814
814
  }
815
815
  }
816
816
  /**
@@ -21,7 +21,8 @@ export interface LockLoss {
21
21
  export interface RefreshFileLock {
22
22
  readonly ownerId: string;
23
23
  assertOwned(): Promise<void>;
24
- release(): Promise<void>;
24
+ /** Abort stops release retries; the unrenewed lease is left to expire by TTL. */
25
+ release(signal?: AbortSignal): Promise<void>;
25
26
  /** Resolves once on detected loss; remains pending after an owner's release. */
26
27
  whenLost(): Promise<LockLoss>;
27
28
  hasLost(): boolean;
@@ -836,7 +836,7 @@ export async function acquireRefreshFileLockWithClock(options) {
836
836
  : {}),
837
837
  });
838
838
  },
839
- release: async () => {
839
+ release: async (signal) => {
840
840
  if (windowsPrivateFiles && releaseConfirmed)
841
841
  return;
842
842
  released = true;
@@ -882,6 +882,8 @@ export async function acquireRefreshFileLockWithClock(options) {
882
882
  releaseConfirmed = removalConfirmed;
883
883
  return;
884
884
  }
885
+ if (signal?.aborted)
886
+ return;
885
887
  await recoverStaleEvictionMarker();
886
888
  }
887
889
  catch (error) {
@@ -38,7 +38,7 @@ export async function withLock(target, options, fn) {
38
38
  return await fn(lock);
39
39
  }
40
40
  finally {
41
- await lock.release();
41
+ await lock.release(options.signal);
42
42
  }
43
43
  }
44
44
  const remaining = options.timeoutMs - (performance.now() - started);
@@ -5,4 +5,4 @@ export type { FormAnswer, LoginContext, PoolAuthorization, PoolLoginMethod, Regi
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, ChooseAccountResult, EventVerdict, HeaderEdits, HostError, InstallOpenCode2AuthOptions, LimitSignal, OpenCode2AuthAdapter, OpenCode2AuthEventName, OpenCode2AuthEvents, OpenCode2AuthInstallation, OpenCode2AuthLogger, OpenCode2HookContext, RequestKind, RequestScope, ResponseAccount, RetryHold, 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, SameAccountRetryInput, SameAccountRetryResult, SelectingHook, Transport, } from './types.js';
@@ -51,8 +51,9 @@ export declare function applyHeaderEdits(target: Record<string, string>, edits:
51
51
  * compares the host-prepared secret exactly, then selects a fresh attempt only
52
52
  * for an owned send. Request-object attribution therefore needs no attempt
53
53
  * header. Frames are owned by the latest handshake of their session and kind;
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.
54
+ * retry runs only when the session's latest transport was owned. The host's
55
+ * retry hook has no request identity, so a session that has mixed owned and
56
+ * foreign transports leaves failover and holds to the host. Identity-preserving
57
+ * retries through `retrySameAccount` do not select an account and remain allowed.
57
58
  */
58
59
  export declare function installOpenCode2Auth<Q, A = unknown>(ctx: OpenCode2HookContext, adapter: OpenCode2AuthAdapter<Q, A, ChooseAccountResult>, options?: InstallOpenCode2AuthOptions): Promise<OpenCode2AuthInstallation<Q, A>>;
@@ -122,9 +122,10 @@ function applyHeaderEditsTo(target, edits) {
122
122
  * compares the host-prepared secret exactly, then selects a fresh attempt only
123
123
  * for an owned send. Request-object attribution therefore needs no attempt
124
124
  * header. Frames are owned by the latest handshake of their session and kind;
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.
125
+ * retry runs only when the session's latest transport was owned. The host's
126
+ * retry hook has no request identity, so a session that has mixed owned and
127
+ * foreign transports leaves failover and holds to the host. Identity-preserving
128
+ * retries through `retrySameAccount` do not select an account and remain allowed.
128
129
  */
129
130
  export async function installOpenCode2Auth(ctx, adapter, options = {}) {
130
131
  const { providerID } = adapter;
@@ -230,13 +231,31 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
230
231
  });
231
232
  }
232
233
  };
234
+ const releaseSameAccount = async (next) => {
235
+ try {
236
+ await adapter.dropSameAccountRetry?.({
237
+ ...next.input,
238
+ accountId: next.accountId,
239
+ });
240
+ }
241
+ catch (error) {
242
+ warn('opencode2 auth dropSameAccountRetry threw; the request is unaffected', {
243
+ sessionID: next.input.sessionID,
244
+ error: describe(error),
245
+ });
246
+ }
247
+ };
248
+ const releaseRetry = async (pending) => {
249
+ if (pending.next)
250
+ await releaseChoice(pending.next);
251
+ if (pending.sameAccount)
252
+ await releaseSameAccount(pending.sameAccount);
253
+ };
233
254
  const discardPending = (key) => {
234
255
  const pending = pendingRetries.get(key);
235
256
  pendingRetries.delete(key);
236
- if (pending?.next) {
237
- const next = pending.next;
238
- void inChoiceOrder(pending.sessionID, () => releaseChoice(next));
239
- }
257
+ if (pending)
258
+ void inChoiceOrder(pending.sessionID, () => releaseRetry(pending));
240
259
  };
241
260
  const emit = async (event, payload) => {
242
261
  const set = listeners.get(event);
@@ -380,13 +399,17 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
380
399
  };
381
400
  const select = async (scope, hook, assertActive, transport) => {
382
401
  const key = keyOf(scope.sessionID, scope.kind);
383
- const { input, accountId } = await afterChoiceWork(scope.sessionID, async () => {
402
+ const { input, accountId, sameAccountRetry } = await afterChoiceWork(scope.sessionID, async () => {
384
403
  assertActive();
385
404
  const retried = pendingRetries.get(key);
386
405
  pendingRetries.delete(key);
387
406
  const previousAccountId = retried?.accountId ?? newestOf(key)?.accountId;
388
407
  supersede(key);
389
408
  const next = retried?.next;
409
+ const sameAccount = retried?.sameAccount;
410
+ const sameRoute = sameAccount !== undefined &&
411
+ sameAccount.input.modelID === scope.modelID &&
412
+ sameAccount.input.agent === scope.agent;
390
413
  const matches = next !== undefined &&
391
414
  next.input.modelID === scope.modelID &&
392
415
  next.input.agent === scope.agent;
@@ -400,11 +423,17 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
400
423
  await inChoiceOrder(scope.sessionID, () => releaseChoice(next));
401
424
  assertActive();
402
425
  }
403
- const choice = matches
404
- ? next.accountId
405
- : await adapter.chooseAccount(input);
426
+ if (sameAccount && !sameRoute) {
427
+ await inChoiceOrder(scope.sessionID, () => releaseSameAccount(sameAccount));
428
+ assertActive();
429
+ }
430
+ const choice = sameRoute
431
+ ? sameAccount.accountId
432
+ : matches
433
+ ? next.accountId
434
+ : await adapter.chooseAccount(input);
406
435
  const accountId = typeof choice === 'string' ? choice : undefined;
407
- return { input, accountId };
436
+ return { input, accountId, sameAccountRetry: sameRoute };
408
437
  });
409
438
  assertActive();
410
439
  let headers = {};
@@ -438,6 +467,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
438
467
  },
439
468
  ...(transport === undefined ? {} : { transport }),
440
469
  outputStarted: false,
470
+ sameAccountRetry,
441
471
  };
442
472
  remember(rec);
443
473
  if (rec.attempt) {
@@ -815,7 +845,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
815
845
  hostDecision,
816
846
  decision: hostDecision,
817
847
  });
818
- if (mixed(draft.sessionID)) {
848
+ if (mixed(draft.sessionID) && !adapter.retrySameAccount) {
819
849
  await hostDecides();
820
850
  return;
821
851
  }
@@ -837,6 +867,104 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
837
867
  const rec = picked;
838
868
  await withSelection(rec.scope, async (assertActive) => {
839
869
  const checkRetryActive = assertActive;
870
+ const retrySameAccount = adapter.retrySameAccount?.bind(adapter);
871
+ const handle = rec.attempt;
872
+ if (retrySameAccount &&
873
+ handle &&
874
+ !rec.outputStarted &&
875
+ !rec.sameAccountRetry) {
876
+ if (rec.ended)
877
+ await rec.ended;
878
+ if (rec.limit)
879
+ await rec.limit.delivered;
880
+ const retried = await inChoiceOrder(rec.scope.sessionID, async () => {
881
+ checkRetryActive();
882
+ const accountId = handle.accountId;
883
+ const active = () => attempts.has(rec.id) &&
884
+ rec.accountId === accountId &&
885
+ pickForRetry(draft.sessionID) === rec &&
886
+ !rec.outputStarted &&
887
+ (!ownership ||
888
+ latestTransportOwned.get(draft.sessionID) === true);
889
+ if (!active() || rec.sameAccountRetry)
890
+ return false;
891
+ rec.sameAccountRetry = true;
892
+ const input = {
893
+ ...rec.scope,
894
+ accountId,
895
+ error: draft.error,
896
+ attempt: draft.attempt,
897
+ ...(rec.limit ? { limit: rec.limit.signal } : {}),
898
+ };
899
+ let result;
900
+ try {
901
+ result = await retrySameAccount(input);
902
+ }
903
+ catch (error) {
904
+ warn('opencode2 auth retrySameAccount threw; recovery declined', {
905
+ sessionID: draft.sessionID,
906
+ error: describe(error),
907
+ });
908
+ }
909
+ if (!result) {
910
+ checkRetryActive();
911
+ return false;
912
+ }
913
+ const sameAccount = { accountId: result.accountId, input };
914
+ try {
915
+ checkRetryActive();
916
+ }
917
+ catch (error) {
918
+ await releaseSameAccount(sameAccount);
919
+ throw error;
920
+ }
921
+ if (!active() || result.accountId !== accountId) {
922
+ await releaseSameAccount(sameAccount);
923
+ return false;
924
+ }
925
+ const old = pendingRetries.get(rec.key);
926
+ pendingRetries.delete(rec.key);
927
+ if (old)
928
+ await releaseRetry(old);
929
+ try {
930
+ checkRetryActive();
931
+ }
932
+ catch (error) {
933
+ await releaseSameAccount(sameAccount);
934
+ throw error;
935
+ }
936
+ if (!active()) {
937
+ await releaseSameAccount(sameAccount);
938
+ return false;
939
+ }
940
+ // Pin only this retry's route: choosing afresh could turn a token
941
+ // refresh or path recovery into an account switch in a mixed session.
942
+ pendingRetries.set(rec.key, {
943
+ attemptId: rec.id,
944
+ sessionID: rec.scope.sessionID,
945
+ order: ++retryOrder,
946
+ accountId,
947
+ sameAccount,
948
+ });
949
+ rec.judged = true;
950
+ draft.decision = { retry: true, delay: 0 };
951
+ return true;
952
+ });
953
+ checkRetryActive();
954
+ if (retried) {
955
+ await emit('retry', {
956
+ sessionID: draft.sessionID,
957
+ accountId: rec.accountId,
958
+ kind: rec.scope.kind,
959
+ attempt: draft.attempt,
960
+ reason: 'same-account',
961
+ hostDecision,
962
+ decision: draft.decision,
963
+ handle: rec.attempt,
964
+ });
965
+ return;
966
+ }
967
+ }
840
968
  // Recheck after entering selection before attributing an identity-less error.
841
969
  if (mixed(draft.sessionID)) {
842
970
  await hostDecides();
@@ -866,8 +994,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
866
994
  };
867
995
  const old = pendingRetries.get(rec.key);
868
996
  pendingRetries.delete(rec.key);
869
- if (old?.next)
870
- await releaseChoice(old.next);
997
+ if (old)
998
+ await releaseRetry(old);
871
999
  checkRetryActive();
872
1000
  if (mixed(draft.sessionID))
873
1001
  return {
@@ -1064,8 +1192,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1064
1192
  if (pending.sessionID === sessionID &&
1065
1193
  pending.order < idleOrder) {
1066
1194
  pendingRetries.delete(key);
1067
- if (pending.next)
1068
- await releaseChoice(pending.next);
1195
+ await releaseRetry(pending);
1069
1196
  }
1070
1197
  }
1071
1198
  });