-
Notifications
You must be signed in to change notification settings - Fork 952
Expand file tree
/
Copy pathindex.ts
More file actions
1570 lines (1493 loc) · 75.9 KB
/
Copy pathindex.ts
File metadata and controls
1570 lines (1493 loc) · 75.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { loginQoderCn, refreshQoderCnToken } from "./qodercn";
import type { KiroOAuthMetadata, OAuthController, OAuthCredentials } from "./types";
import { parseCallbackInput } from "./callback-server";
import type { OcxConfig, OcxProviderConfig, RefreshPolicy } from "../types";
import { loadConfig, resolveEnvValue, saveConfig } from "../config";
import { maskEmail } from "../lib/privacy";
import { KiroTokenRefreshError, environmentKiroRoutingMetadata, loginKiro, refreshKiroToken, settleKiroLoginTransaction } from "./kiro";
import { getAccountCredential, getAccountCredentialWithStatus, getAccountSet, removeAccount, saveAccountCredential, saveCredential, setActiveAccount, getCredential, credentialGeneration, createOAuthRefreshIntentLock, mergeAccountCredential, markAccountNeedsReauthIfGeneration, readOAuthRefreshIntent, writeOAuthRefreshIntent, markOAuthRefreshIntentStaleOwner, clearOAuthRefreshIntent, normalizeAuthStoreBuffer, OAuthMutationBusyError } from "./store";
import { loginXai, refreshXaiToken, XAI_LOCAL_CLI_DETACH_WARNING, XaiTokenRequestError } from "./xai";
import { ANTHROPIC_OAUTH_BETA, AnthropicTokenError, loginAnthropic, refreshAnthropicToken } from "./anthropic";
import { loginKimi, refreshKimiToken } from "./kimi";
import { loginNous, NousTokenError, refreshNousToken, clearNousRefreshIntent, RefreshIntentIOError } from "./nous";
import { loginChatGPT, refreshChatGPTToken } from "./chatgpt";
import { loginAntigravity, refreshAntigravityToken } from "./google-antigravity";
import { loginCursor, refreshCursorToken } from "./cursor";
import { loginGithubCopilot, refreshGithubCopilotToken, validateCopilotApiBaseUrl } from "./github-copilot";
import { loginCommandCode, refreshCommandCodeToken } from "./command-code";
import { ANTIGRAVITY_REQUEST_UA } from "../adapters/google-antigravity-wire";
import { deriveOAuthDefaultModel, deriveOAuthProviderConfig } from "../providers/derive";
import { apiKeyPoolEntryId, sanitizeApiKeyValue } from "../providers/api-keys";
import { effectiveGoogleMode, getProviderRegistryEntry, mergeRegistryStaticHeaders, providerMatchesRegistryTransport } from "../providers/registry";
import { resolveProviderModelDiscoveryUrl } from "../providers/model-discovery";
import { resolveProviderTransport } from "../providers/xai-transport";
import { detectClaudeCodeToken, detectGrokCliToken, hasComparableGrokIdentity, isSameGrokIdentity, shouldAdoptGrokGeneration } from "./local-token-detect";
import { logOAuthEvent } from "./log";
import { captureConfigGeneration, sweepExpiredOnWrite, type GenerationContext } from "../lib/state-store-sweeper";
import { retainedUtf8Bytes } from "../lib/admission";
import { randomUUID } from "node:crypto";
export {
CODEX_HEALTH_AUTH_FAILED_NOTE,
CODEX_HEALTH_MANAGEMENT_API_UNAVAILABLE_NOTE,
CODEX_HEALTH_UNAVAILABLE_NOTE,
MASKED_ACCOUNT_FALLBACK,
collectOAuthHealthEntries,
collectOAuthHealthEntriesForCli,
detectOAuthWarning,
oauthAccountHealthFields,
oauthHealthLabel,
oauthHealthSummary,
projectCodexAccountHealth,
projectOAuthAccountHealth,
projectStoredOAuthAccountHealth,
type CodexHealthSource,
type OAuthAccountHealth,
type OAuthAccountHealthFields,
type OAuthCliHealthReport,
type OAuthHealthEntry,
type OAuthHealthLabel,
} from "./health";
export { OAUTH_REFRESH_LOCK_WAIT_MS, peekAuthStore, peekOAuthRefreshIntent } from "./store";
import { codexAccountNamespaceProviderCollisionError } from "../codex/account-namespace-match";
const REFRESH_SKEW_MS = 60_000;
export interface OAuthAccessSnapshot {
provider: string;
accountId: string;
generation: string;
accessToken: string;
/** Cloud Code Assist project selected during Antigravity login. */
projectId?: string;
/** Safe request-routing subset; refresh-only Kiro client secrets never leave the credential store. */
kiro?: Pick<KiroOAuthMetadata, "profileArn" | "apiRegion" | "ssoRegion" | "authType">;
/**
* Allowlisted GitHub Copilot API origin belonging to THIS account.
*
* Copilot pins its bearer to an account-scoped regional host. Initial routing, 401 refresh, and
* account failover must resolve transport from this same snapshot; rereading the active account
* can pair account A's token with account B's origin during a concurrent switch (#2568d).
*/
apiBaseUrl?: string;
}
export interface ObservedOAuthAccessSnapshot extends OAuthAccessSnapshot {
/** Retained for callers that predate `apiBaseUrl` moving onto the base snapshot. */
apiBaseUrl?: string;
}
export type OAuthActiveTokenObservation =
| { readonly kind: "available"; readonly snapshot: ObservedOAuthAccessSnapshot }
| { readonly kind: "missing" }
| { readonly kind: "malformed" }
| { readonly kind: "needs-reauth" }
| { readonly kind: "expired" }
| { readonly kind: "near-expiry" }
| { readonly kind: "unsupported" };
const MAX_OAUTH_TOKEN_REFRESH_FLIGHTS = 32;
const OAUTH_TOKEN_REFRESH_FLIGHT_STALE_MS = 120_000;
interface OAuthRefreshFlightEvidence { flightId: string; dispatched: boolean }
interface OAuthTokenRefreshFlight extends OAuthRefreshFlightEvidence { promise: Promise<OAuthAccessSnapshot>; startedAt: number; abort: AbortController }
const tokenRefreshes = new Map<string, OAuthTokenRefreshFlight>();
export class OAuthTokenRefreshBusyError extends Error {
readonly code = "OAUTH_TOKEN_REFRESH_BUSY";
readonly retryable = true;
constructor() { super("OAuth token refresh capacity reached"); this.name = "OAuthTokenRefreshBusyError"; }
}
export class OAuthTokenRefreshStaleError extends Error {
readonly code = "OAUTH_TOKEN_REFRESH_STALE";
readonly retryable = true;
constructor() { super("OAuth token refresh owner became stale"); this.name = "OAuthTokenRefreshStaleError"; }
}
/** Focused owner-identity tests only. Synthetic owners retain no account data. */
export function seedOAuthTokenRefreshFlightsForTests(rows: Array<{ key: string; startedAt?: number; flightId?: string; dispatched?: boolean }>): {
promises: Promise<OAuthAccessSnapshot>[];
cleanup: () => void;
} {
const inserted: OAuthTokenRefreshFlight[] = [];
const promises = rows.map(({ key, startedAt, flightId, dispatched }) => {
const abort = new AbortController();
const promise = new Promise<OAuthAccessSnapshot>((_resolve, reject) => {
abort.signal.addEventListener("abort", () => reject(abort.signal.reason), { once: true });
});
const flight = { promise, startedAt: startedAt ?? Date.now(), abort, flightId: flightId ?? randomUUID(), dispatched: dispatched ?? false };
tokenRefreshes.set(key, flight);
inserted.push(flight);
return promise;
});
return {
promises,
cleanup() {
for (const [key, flight] of tokenRefreshes) {
if (!inserted.includes(flight)) continue;
tokenRefreshes.delete(key);
flight.abort.abort(new Error("test cleanup"));
}
},
};
}
const XAI_PERMANENT_FAILURE_TTL_MS=30_000;
const permanentRefreshFailures=new Map<string,number>();
interface XaiRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal }
interface AnthropicRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; flight?: OAuthRefreshFlightEvidence; replacedStaleFlight?: OAuthRefreshFlightEvidence }
interface GenericRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal }
function verdictKey(p:string,a:string,c:OAuthCredentials){return `${p}\0${a}\0${credentialGeneration(c)}`;}
function cached(p:string,a:string,c:OAuthCredentials,now:()=>number){const k=verdictKey(p,a,c),u=permanentRefreshFailures.get(k);if(u===undefined)return false;if(u<=now()){permanentRefreshFailures.delete(k);return false;}return true;}
export function sweepExpiredXaiPermanentFailureVerdicts(now=Date.now()):number{let removed=0;for(const[key,until]of permanentRefreshFailures){if(until>now)continue;permanentRefreshFailures.delete(key);removed+=1;}return removed;}
export interface LoginOpts { forceLogin?: boolean; /** When set, persist into this account slot and require matching identity. */ reauthAccountId?: string }
export interface LoginFlowLifecycle {
/** Runs after background credential/config persistence settles, before status becomes done. */
onSettled?: () => void | Promise<void>;
}
interface OAuthProviderDef {
login(ctrl: OAuthController, opts?: LoginOpts): Promise<OAuthCredentials>;
refresh(
refreshToken: string,
signal?: AbortSignal,
credential?: OAuthCredentials,
): Promise<OAuthCredentials>;
/** provider entry written into config.json on first login. */
providerConfig: OcxProviderConfig;
defaultModel: string;
/**
* Built-in proactive-refresh policy, risk-tiered by the provider's ToS exposure (devlog
* 260703_oauth-multi-account-refresh-and-tos). A user's per-provider `config.providers[x].refreshPolicy`
* overrides this. Default when unset here: "lazy-only".
*/
defaultRefreshPolicy?: RefreshPolicy;
}
function oauthConfig(id: string): OcxProviderConfig {
const config = deriveOAuthProviderConfig(id);
if (!config) throw new Error(`OAuth provider missing from registry: ${id}`);
return config;
}
function oauthDefaultModel(id: string): string {
const model = deriveOAuthDefaultModel(id);
if (!model) throw new Error(`OAuth provider missing default model in registry: ${id}`);
return model;
}
export const OAUTH_PROVIDERS: Record<string, OAuthProviderDef> = {
"command-code": {
// Add-account/reauth must not reimport the current local CLI credential.
login: (ctrl, opts) => loginCommandCode(ctrl, { importLocal: opts?.forceLogin ? "off" : "fallback" }),
refresh: refreshCommandCodeToken,
providerConfig: oauthConfig("command-code"),
defaultModel: oauthDefaultModel("command-code"),
defaultRefreshPolicy: "disabled",
},
xai: {
// forceLogin skips the local grok-cli import so a SECOND account can be chosen in the browser.
login: (ctrl, opts) => loginXai(ctrl, { importLocal: opts?.forceLogin ? "off" : "fallback" }),
refresh: refreshXaiToken,
providerConfig: oauthConfig("xai"),
defaultModel: oauthDefaultModel("xai"),
},
anthropic: {
login: (ctrl, opts) => loginAnthropic(ctrl, { importLocal: opts?.forceLogin ? "off" : "fallback" }),
refresh: refreshAnthropicToken,
providerConfig: oauthConfig("anthropic"),
defaultModel: oauthDefaultModel("anthropic"),
// Anthropic actively server-side-blocks subscription OAuth outside its own clients (Feb 2026).
// Never generate background refresh traffic for it — grade 20, highest ToS risk.
defaultRefreshPolicy: "disabled",
},
kimi: {
login: (ctrl) => loginKimi(ctrl),
refresh: refreshKimiToken,
providerConfig: oauthConfig("kimi"),
defaultModel: oauthDefaultModel("kimi"),
},
nous: {
// Nous Portal device-grant login (RFC 8628) against portal.nousresearch.com.
// The access token is the per-request inference JWT (scope inference:invoke).
// Refresh tokens are single-use and rotated server-side on every refresh:
// keep background refresh lazy-only (the default) so concurrent refreshes
// cannot trip the Portal's token-reuse revocation.
login: (ctrl) => loginNous(ctrl),
refresh: (rt, signal) => refreshNousToken(rt, signal),
providerConfig: oauthConfig("nous"),
defaultModel: oauthDefaultModel("nous"),
// Single-use rotating refresh tokens must never be background-refreshed
// proactively: concurrent refreshes would trip the Portal's reuse
// revocation. Anchor the lazy-only default explicitly so it cannot be
// silently overridden to proactive.
defaultRefreshPolicy: "lazy-only",
},
kiro: {
login: (ctrl, opts) => loginKiro(ctrl, { forceLogin: opts?.forceLogin }),
refresh: (rt, signal, credential) => refreshKiroToken(rt, signal, credential),
providerConfig: oauthConfig("kiro"),
defaultModel: oauthDefaultModel("kiro"),
},
"google-antigravity": {
login: (ctrl, opts) => loginAntigravity(ctrl, { forceAccountSelect: opts?.forceLogin === true }),
refresh: refreshAntigravityToken,
providerConfig: oauthConfig("google-antigravity"),
defaultModel: oauthDefaultModel("google-antigravity"),
},
cursor: {
login: (ctrl, opts) => loginCursor(ctrl, undefined, { forceLogin: opts?.forceLogin }),
refresh: refreshCursorToken,
providerConfig: oauthConfig("cursor"),
defaultModel: oauthDefaultModel("cursor"),
},
"github-copilot": {
login: (ctrl) => loginGithubCopilot(ctrl),
refresh: (rt, signal) => refreshGithubCopilotToken(rt, signal),
providerConfig: oauthConfig("github-copilot"),
defaultModel: oauthDefaultModel("github-copilot"),
// Unofficial Copilot bridge — keep proactive traffic lazy-only (no background guardian spam).
defaultRefreshPolicy: "lazy-only",
},
qodercn: {
login: (ctrl) => loginQoderCn(ctrl),
refresh: (rt, signal) => refreshQoderCnToken(rt, signal),
providerConfig: oauthConfig("qodercn"),
defaultModel: oauthDefaultModel("qodercn"),
},
chatgpt: {
login: loginChatGPT,
refresh: (rt) => refreshChatGPTToken(rt),
providerConfig: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward" as const },
defaultModel: "gpt-5.4",
},
};
export function isOAuthProvider(name: string): boolean {
return name in OAUTH_PROVIDERS;
}
export function isPublicOAuthProvider(name: string): boolean {
return name !== "chatgpt" && isOAuthProvider(name);
}
function isRefreshPolicy(value: unknown): value is RefreshPolicy {
return value === "proactive" || value === "lazy-only" || value === "disabled";
}
/**
* The effective proactive-refresh policy for a provider: the user's per-provider
* `config.providers[provider].refreshPolicy` if set, else the provider def's risk-tiered default,
* else "lazy-only". The guardian acts only when this resolves to "proactive".
*/
export function resolveRefreshPolicy(provider: string, config: OcxConfig): RefreshPolicy {
const override = config.providers[provider]?.refreshPolicy;
if (isRefreshPolicy(override)) return override;
const def = OAUTH_PROVIDERS[provider];
return def?.defaultRefreshPolicy ?? "lazy-only";
}
/** The discovered project id stored on an OAuth credential (Antigravity CCA), if any. */
export function getOAuthCredentialProjectId(provider: string): string | undefined {
return getCredential(provider)?.projectId;
}
/** Allowlisted Copilot API origin from the active credential, if still valid. */
export function getOAuthCredentialApiBaseUrl(provider: string): string | undefined {
return validateCopilotApiBaseUrl(getCredential(provider)?.apiBaseUrl);
}
/** Provider ids that support real OAuth login (drives the GUI's "Log in with …" buttons). */
export function listOAuthProviders(): string[] {
return Object.keys(OAUTH_PROVIDERS).filter(isPublicOAuthProvider);
}
export class UnsupportedOAuthProviderError extends Error {
constructor(provider: string) {
super(`Unsupported OAuth provider in config: ${provider}`);
this.name = "UnsupportedOAuthProviderError";
}
}
export class OAuthLoginRequiredError extends Error {
readonly provider: string;
constructor(provider: string) {
super(`Not logged in to ${provider}. Run: ocx login ${provider}`);
this.name = "OAuthLoginRequiredError";
this.provider = provider;
}
}
export class OAuthProviderPublicationError extends Error {
constructor() {
super("OAuth credential was saved, but the provider entry was not written. Resolve the account namespace collision, then retry login.");
this.name = "OAuthProviderPublicationError";
}
}
export class OAuthReauthIdentityMismatchError extends Error {
constructor() {
super("Signed-in account does not match the selected account. Sign in with the same account.");
this.name = "OAuthReauthIdentityMismatchError";
}
}
export class OAuthReauthIdentityUnverifiedError extends Error {
constructor() {
super("Could not verify signed-in account identity for reauth.");
this.name = "OAuthReauthIdentityUnverifiedError";
}
}
class OAuthLoginSupersededError extends Error {
constructor() {
super("OAuth login was superseded before credential persistence");
this.name = "OAuthLoginSupersededError";
}
}
/** Project arbitrary OAuth failures onto the small, stable public error vocabulary. */
export function publicOAuthAuthenticationErrorMessage(error: unknown): string {
if (error instanceof OAuthMutationBusyError) {
return error.message === "OAuth mutation queue wait timed out"
? "OAuth mutation queue wait timed out"
: "OAuth mutation queue is busy";
}
if (
(error instanceof OAuthLoginRequiredError && isOAuthProvider(error.provider))
|| error instanceof OAuthProviderPublicationError
// Reauth identity outcomes carry fixed, account-free remediation text. Dropping them to the
// generic message hides WHICH failure the user must fix (sign in with the selected account).
|| error instanceof OAuthReauthIdentityMismatchError
|| error instanceof OAuthReauthIdentityUnverifiedError
|| error instanceof OAuthTokenRefreshBusyError
|| error instanceof OAuthTokenRefreshStaleError
) return error.message;
return "OAuth authentication failed. Check the OpenCodex account status and retry.";
}
function accessSnapshot(provider: string, accountId: string, cred: OAuthCredentials): OAuthAccessSnapshot {
// Derived, not read back: a stored `authType` is trusted when present, but a credential imported
// before the field existed still routes correctly because the client pair implies SSO OIDC.
const kiroAuthType = cred.kiro?.authType
?? (cred.kiro?.clientId && cred.kiro?.clientSecret ? "aws_sso_oidc" as const : undefined);
const storedKiroRouting = {
...(cred.kiro?.profileArn ? { profileArn: cred.kiro.profileArn } : {}),
...(cred.kiro?.apiRegion ? { apiRegion: cred.kiro.apiRegion } : {}),
...(cred.kiro?.ssoRegion ? { ssoRegion: cred.kiro.ssoRegion } : {}),
};
// `authType` is a property OF the account, not routing the environment can substitute for, so it
// is merged after the environment fallback decision rather than counting as stored routing.
// Folding it into `storedKiroRouting` would make a client-pair-only credential look non-empty
// and silently disable `environmentKiroRoutingMetadata()` for it.
const kiroAuthTypeRouting = kiroAuthType ? { authType: kiroAuthType } : {};
// Validated here, not at the call site: an unvalidated origin from a legacy or crafted
// credential must never travel with a bearer, and dropping it makes the transport fall back to
// the canonical host rather than to whatever the previous account was using.
const copilotApiBaseUrl = provider === "github-copilot"
? validateCopilotApiBaseUrl(cred.apiBaseUrl)
: undefined;
return {
provider,
accountId,
generation: credentialGeneration(cred),
accessToken: cred.access,
...(cred.projectId ? { projectId: cred.projectId } : {}),
...(copilotApiBaseUrl ? { apiBaseUrl: copilotApiBaseUrl } : {}),
// Stored account metadata remains authoritative. Metadata-less legacy/environment credentials
// may use explicit environment routing, but never borrow the currently signed-in local CLI account.
...(provider === "kiro"
? {
kiro: {
...(Object.keys(storedKiroRouting).length > 0
? storedKiroRouting
: environmentKiroRoutingMetadata() ?? {}),
...kiroAuthTypeRouting,
},
}
: {}),
};
}
/**
* Observe the active OAuth token from an auth-store buffer supplied by its filesystem owner.
* Missing, malformed, reauth-required, and expiring credentials are typed no-token outcomes;
* this path never refreshes, locks, hardens, backs up, or persists credentials.
*/
export function observeActiveOAuthAccessToken(
provider: string,
authStoreBuffer: Uint8Array | null,
now = Date.now(),
): OAuthActiveTokenObservation {
const authStore = normalizeAuthStoreBuffer(authStoreBuffer);
if (authStore.kind === "absent") return { kind: "missing" };
if (authStore.kind === "malformed") return { kind: "malformed" };
if (!isOAuthProvider(provider)) return { kind: "unsupported" };
const accountSet = authStore.store[provider];
const account = accountSet?.accounts.find(candidate => candidate.id === accountSet.activeAccountId);
if (!account) return { kind: "missing" };
if (account.needsReauth) return { kind: "needs-reauth" };
if (account.credential.expires <= now) return { kind: "expired" };
if (account.credential.expires <= now + REFRESH_SKEW_MS) return { kind: "near-expiry" };
const apiBaseUrl = validateCopilotApiBaseUrl(account.credential.apiBaseUrl);
return {
kind: "available",
snapshot: {
...accessSnapshot(provider, account.id, account.credential),
...(apiBaseUrl ? { apiBaseUrl } : {}),
},
};
}
async function resolveAccessSnapshotForAccount(
provider: string,
accountId: string,
rejectedGeneration?: string,
requireUsableAccount = false,
): Promise<OAuthAccessSnapshot> {
const def = OAUTH_PROVIDERS[provider];
if (!def) throw new UnsupportedOAuthProviderError(provider);
// One store read answers both questions. A caller that opts in gets the account REJECTED
// when it needs reauthentication, which a bare credential read cannot detect: a revoked
// account keeps a readable credential, so resolution would otherwise succeed and the
// request would dispatch on an account already known to need a fresh login.
const row = getAccountCredentialWithStatus(provider, accountId);
if (!row) throw new OAuthLoginRequiredError(provider);
if (requireUsableAccount && row.needsReauth) throw new OAuthLoginRequiredError(provider);
const cred = row.credential;
const current = accessSnapshot(provider, accountId, cred);
if (rejectedGeneration !== undefined && current.generation !== rejectedGeneration) return current;
if (rejectedGeneration === undefined && cred.expires > Date.now() + REFRESH_SKEW_MS) return current;
const key = `${provider}\u0000${accountId}`;
let existing = tokenRefreshes.get(key);
let replacedStaleFlight: OAuthRefreshFlightEvidence | undefined;
if (existing && Date.now() - existing.startedAt <= OAUTH_TOKEN_REFRESH_FLIGHT_STALE_MS) {
logOAuthEvent("OAuth refresh joined existing operation", { provider, accountId });
return existing.promise;
}
if (existing) {
replacedStaleFlight = { flightId: existing.flightId, dispatched: existing.dispatched };
existing.abort.abort(new OAuthTokenRefreshStaleError());
if (tokenRefreshes.get(key) === existing) tokenRefreshes.delete(key);
existing = undefined;
}
if (tokenRefreshes.size >= MAX_OAUTH_TOKEN_REFRESH_FLIGHTS) throw new OAuthTokenRefreshBusyError();
const abort = new AbortController();
const flight: OAuthTokenRefreshFlight = {
promise: undefined as unknown as Promise<OAuthAccessSnapshot>,
startedAt: Date.now(),
abort,
flightId: randomUUID(),
dispatched: false,
};
const refresh = (async (): Promise<OAuthAccessSnapshot> => {
const accessToken = await refreshAndPersistAccessToken(provider, accountId, def, cred, abort.signal, flight, replacedStaleFlight);
const persisted = getAccountCredential(provider, accountId);
if (!persisted) throw new OAuthLoginRequiredError(provider);
if (persisted.access !== accessToken) {
throw new Error(`OAuth refresh persisted an unexpected access token for ${provider}`);
}
return accessSnapshot(provider, accountId, persisted);
})().catch(error => {
if (abort.signal.reason instanceof OAuthTokenRefreshStaleError) throw abort.signal.reason;
throw error;
}).finally(() => {
if (tokenRefreshes.get(key) === flight) tokenRefreshes.delete(key);
});
flight.promise = refresh;
tokenRefreshes.set(key, flight);
return refresh;
}
export async function getValidAccessTokenSnapshot(provider: string): Promise<OAuthAccessSnapshot> {
const set = getAccountSet(provider);
if (!set) throw new OAuthLoginRequiredError(provider);
return resolveAccessSnapshotForAccount(provider, set.activeAccountId);
}
/** Providers whose upstream-401 replay path may force a snapshot refresh. */
const FORCE_REFRESH_PROVIDERS = new Set(["xai", "github-copilot", "kiro"]);
export async function forceRefreshOAuthAccessSnapshot(
rejected: OAuthAccessSnapshot,
): Promise<OAuthAccessSnapshot> {
if (!FORCE_REFRESH_PROVIDERS.has(rejected.provider)) throw new UnsupportedOAuthProviderError(rejected.provider);
return resolveAccessSnapshotForAccount(rejected.provider, rejected.accountId, rejected.generation);
}
/** Return a valid access token for the ACTIVE account, refreshing + persisting if expired. */
export async function getValidAccessToken(provider: string): Promise<string> {
return (await getValidAccessTokenSnapshot(provider)).accessToken;
}
/**
* Account-scoped token resolver (multiauth): refresh is single-flighted per
* (provider, account), and the rotated credential is persisted for THAT account only —
* a guardian refresh of a background account never switches the active account.
*/
export async function getValidAccessTokenForAccount(provider: string, accountId: string): Promise<string> {
return (await resolveAccessSnapshotForAccount(provider, accountId)).accessToken;
}
/**
* Account-scoped resolver returning the FULL snapshot, not just the bearer.
*
* A rotator that swaps only the token silently mixes credential generations: Antigravity pairs
* an account-matched `projectId` with its token (see the pairing comment in
* server/responses/core.ts), Kiro carries routing metadata, and Copilot's observed snapshot
* carries an account-specific API origin. Reading those back from "whichever account is active"
* after a rotation is exactly the mixing this returns in one piece to prevent (#2568).
*/
export async function getValidAccessSnapshotForAccount(
provider: string,
accountId: string,
opts: { requireUsableAccount?: boolean } = {},
): Promise<OAuthAccessSnapshot> {
return resolveAccessSnapshotForAccount(provider, accountId, undefined, opts.requireUsableAccount === true);
}
/** Terminal refresh failures (revoked/rotated-away grants) — retrying cannot succeed. */
function isTerminalRefreshError(err: unknown): boolean {
const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
return msg.includes("invalid_grant")
|| msg.includes("refresh_token_reused")
|| msg.includes("revoked")
// GitHub Copilot refresh surfaces allowlisted OAuth codes (github-copilot.ts):
|| msg.includes("access_denied")
|| msg.includes("expired_token");
}
function terminal(error:unknown):boolean{
if(error instanceof XaiTokenRequestError)return ["invalid_grant","refresh_token_reused","revoked_token"].includes(error.oauthError??"");
if(error instanceof AnthropicTokenError)return (error.httpStatus===400||error.httpStatus===401)&&["invalid_grant","refresh_token_reused","revoked","revoked_token","refresh_token_revoked"].includes(error.oauthError??"");
if(error instanceof KiroTokenRefreshError)return (error.httpStatus===400||error.httpStatus===401)&&error.oauthError!==undefined;
if(error instanceof NousTokenError)return error.terminal===true||["invalid_grant","refresh_token_reused","revoked","revoked_token","expired_token"].includes(error.oauthError??"");
// Local durable-write/read/cleanup failures are operational, not credential
// death: the provider credential was never rejected or consumed. Never mark
// the account needsReauth for broken local persistence infrastructure.
if (error instanceof RefreshIntentIOError) return false;
return isTerminalRefreshError(error);
}
function authoritative(stored:OAuthCredentials,active:boolean,now:()=>number):OAuthCredentials{if(stored.source!=="local-cli")return stored;const disk=detectGrokCliToken();if(!disk)return stored;const allowed=isSameGrokIdentity(stored,disk)||(active&&!hasComparableGrokIdentity(stored,disk));return allowed&&shouldAdoptGrokGeneration(stored,disk,now(),REFRESH_SKEW_MS)?disk:stored;}
function merged(fresh: OAuthCredentials, previous: OAuthCredentials): OAuthCredentials {
return {
...fresh,
source: previous.source === "local-cli" ? "oauth" : fresh.source ?? previous.source ?? "oauth",
...(fresh.projectId === undefined && previous.projectId ? { projectId: previous.projectId } : {}),
...(fresh.apiBaseUrl === undefined && previous.apiBaseUrl ? { apiBaseUrl: previous.apiBaseUrl } : {}),
...(fresh.email === undefined && previous.email ? { email: previous.email } : {}),
...(fresh.accountId === undefined && previous.accountId ? { accountId: previous.accountId } : {}),
...(fresh.kiro === undefined && previous.kiro ? { kiro: previous.kiro } : {}),
};
}
export async function refreshXaiAccountWithLock(provider:string,accountId:string,def:OAuthProviderDef,callerCredential:OAuthCredentials,deps:XaiRefreshDeps={}):Promise<string>{const writerGeneration=captureConfigGeneration();const now=deps.now??Date.now;const guard=await(deps.intentLock??createOAuthRefreshIntentLock(provider,accountId)).acquire();try{const stored=getAccountCredential(provider,accountId);if(!stored)throw new OAuthLoginRequiredError(provider);const active=getAccountSet(provider)?.activeAccountId===accountId,candidate=authoritative(stored,active,now);if(credentialGeneration(candidate)!==credentialGeneration(callerCredential)&&candidate.expires>now()+REFRESH_SKEW_MS){if(credentialGeneration(candidate)!==credentialGeneration(stored)){const o=await mergeAccountCredential(provider,accountId,candidate,{expectedGeneration:credentialGeneration(stored),afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}}return candidate.access;}if(cached(provider,accountId,candidate,now))throw new OAuthLoginRequiredError(provider);const generation=credentialGeneration(candidate);try{const fresh=merged(await def.refresh(candidate.refresh,deps.signal),candidate);const o=await mergeAccountCredential(provider,accountId,fresh,{expectedGeneration:generation,afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));if(candidate.source==="local-cli")console.warn(XAI_LOCAL_CLI_DETACH_WARNING);return fresh.access;}catch(error){if(error instanceof OAuthMutationBusyError){permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));throw error;}if(!terminal(error))throw error;const failedAt=now();permanentRefreshFailures.set(verdictKey(provider,accountId,candidate),failedAt+XAI_PERMANENT_FAILURE_TTL_MS);sweepExpiredOnWrite(failedAt);await markAccountNeedsReauthIfGeneration(provider,accountId,generation,writerGeneration);throw new OAuthLoginRequiredError(provider);}}finally{guard.release();}}
function newerClaudeCredential(stored: OAuthCredentials, now: number): OAuthCredentials | undefined {
if (stored.source !== "local-cli") return undefined;
const disk = detectClaudeCodeToken();
if (!disk || disk.expires <= now + REFRESH_SKEW_MS) return undefined;
return credentialGeneration(disk) !== credentialGeneration(stored) ? disk : undefined;
}
/**
* Preserve an already-rotated Nous refresh token (RT-B) after a terminal refresh
* error (e.g. the returned access JWT lacked `inference:invoke`). The unusable
* access token is NOT persisted as valid: the recovery credential carries an
* empty access placeholder with a past expiry so it can never be routed, and the
* account is marked needsReauth by the caller. Generation-safe: a concurrent
* newer write wins and is never overwritten.
*/
async function preserveNousRotatedRefresh(
provider: string,
accountId: string,
rotatedRefresh: string,
expectedGeneration: string,
previous: OAuthCredentials,
): Promise<{ kind: "persisted"; generation: string } | { kind: "superseded" } | { kind: "failed" }> {
try {
const recovery: OAuthCredentials = {
refresh: rotatedRefresh,
// Never persist the unusable access token: an empty placeholder with a
// past expiry can never be observed as a valid credential.
access: "",
expires: 0,
...(previous.accountId ? { accountId: previous.accountId } : {}),
...(previous.email ? { email: previous.email } : {}),
...(previous.source ? { source: previous.source } : {}),
};
const outcome = await mergeAccountCredential(provider, accountId, recovery, { expectedGeneration });
if (outcome.superseded) return { kind: "superseded" };
// Return the exact generation this write produced, so the caller never
// re-reads the store (a concurrent writer could otherwise supply a different
// credential generation and be marked needsReauth by mistake).
return { kind: "persisted", generation: credentialGeneration(recovery) };
} catch (error) {
// A store-mutation busy outcome is transient and retryable; surface it
// unchanged so the caller can retry rather than treating it as a permanent
// RT-B persistence failure.
if (error instanceof OAuthMutationBusyError) throw error;
return { kind: "failed" };
}
}
export async function refreshAnthropicAccountWithLock(
provider: string,
accountId: string,
def: OAuthProviderDef,
callerCredential: OAuthCredentials,
deps: AnthropicRefreshDeps = {},
): Promise<string> {
const writerGeneration = captureConfigGeneration();
const now = deps.now ?? Date.now;
const guard = await (deps.intentLock ?? createOAuthRefreshIntentLock(provider, accountId)).acquire();
try {
const stored = getAccountCredential(provider, accountId);
if (!stored) throw new OAuthLoginRequiredError(provider);
const account = getAccountSet(provider)?.accounts.find(candidate => candidate.id === accountId);
const generation = credentialGeneration(stored);
let pendingIntent = readOAuthRefreshIntent(provider, accountId);
const disk = newerClaudeCredential(stored, now());
if (disk) {
const outcome = await mergeAccountCredential(provider, accountId, disk, {
expectedGeneration: credentialGeneration(stored),
afterPrePersistRead: deps.afterPrePersistRead,
});
if (outcome.superseded) {
if (pendingIntent) clearOAuthRefreshIntent(provider, accountId, pendingIntent.generation);
if (outcome.stored.expires > now() + REFRESH_SKEW_MS) return outcome.stored.access;
throw new OAuthLoginRequiredError(provider);
}
if (pendingIntent) clearOAuthRefreshIntent(provider, accountId, pendingIntent.generation);
return disk.access;
}
if (!pendingIntent?.uncertain && pendingIntent?.generation === generation) {
if (pendingIntent.staleOwner) throw new OAuthTokenRefreshStaleError();
if (deps.replacedStaleFlight && pendingIntent.flightId === deps.replacedStaleFlight.flightId) {
if (deps.replacedStaleFlight.dispatched) {
markOAuthRefreshIntentStaleOwner(provider, accountId, generation, deps.replacedStaleFlight.flightId);
throw new OAuthTokenRefreshStaleError();
}
clearOAuthRefreshIntent(provider, accountId, generation);
pendingIntent = undefined;
}
}
if (pendingIntent?.uncertain || pendingIntent?.generation === generation) {
await markAccountNeedsReauthIfGeneration(provider, accountId, generation, writerGeneration);
throw new OAuthLoginRequiredError(provider);
}
if (pendingIntent) clearOAuthRefreshIntent(provider, accountId, pendingIntent.generation);
if (account?.needsReauth) {
throw new OAuthLoginRequiredError(provider);
}
if (credentialGeneration(stored) !== credentialGeneration(callerCredential) && stored.expires > now() + REFRESH_SKEW_MS) {
return stored.access;
}
try {
writeOAuthRefreshIntent(provider, accountId, generation, now(), deps.flight?.flightId);
if (deps.signal?.aborted) throw deps.signal.reason;
if (deps.flight) deps.flight.dispatched = true;
const fresh = merged(await def.refresh(stored.refresh, deps.signal), stored);
const outcome = await mergeAccountCredential(provider, accountId, fresh, {
expectedGeneration: generation,
afterPrePersistRead: deps.afterPrePersistRead,
});
if (outcome.superseded) {
clearOAuthRefreshIntent(provider, accountId, generation);
if (outcome.stored.expires > now() + REFRESH_SKEW_MS) return outcome.stored.access;
throw new OAuthLoginRequiredError(provider);
}
clearOAuthRefreshIntent(provider, accountId, generation);
return fresh.access;
} catch (error) {
if (error instanceof OAuthMutationBusyError) throw error;
if (!terminal(error)) throw error;
await markAccountNeedsReauthIfGeneration(provider, accountId, generation, writerGeneration);
clearOAuthRefreshIntent(provider, accountId, generation);
throw new OAuthLoginRequiredError(provider);
}
} finally {
guard.release();
}
}
export async function refreshGenericAccountWithLock(
provider: string,
accountId: string,
def: OAuthProviderDef,
callerCredential: OAuthCredentials,
deps: GenericRefreshDeps = {},
): Promise<string> {
const writerGeneration = captureConfigGeneration();
logOAuthEvent("OAuth refresh started", { provider, accountId });
const guard = await (deps.intentLock ?? createOAuthRefreshIntentLock(provider, accountId)).acquire();
try {
const stored = getAccountCredential(provider, accountId);
if (!stored) throw new OAuthLoginRequiredError(provider);
if (
credentialGeneration(stored) !== credentialGeneration(callerCredential)
&& stored.expires > Date.now() + REFRESH_SKEW_MS
) {
logOAuthEvent("OAuth refresh joined existing operation", { provider, accountId });
return stored.access;
}
const generation = credentialGeneration(stored);
try {
const fresh = merged(await def.refresh(stored.refresh, deps.signal, stored), stored);
const outcome = await mergeAccountCredential(provider, accountId, fresh, {
expectedGeneration: generation,
afterPrePersistRead: deps.afterPrePersistRead,
});
if (outcome.superseded) {
if (outcome.stored.expires > Date.now() + REFRESH_SKEW_MS) return outcome.stored.access;
throw new OAuthLoginRequiredError(provider);
}
logOAuthEvent("OAuth credentials rotated and persisted", { provider, accountId });
// Best-effort bookkeeping cleanup: the rotated credential is already
// durably persisted. A failure to unlink the old-token intent file
// (EACCES/EPERM/EBUSY/EROFS) must not turn a committed rotation into a
// failed refresh. The stale intent keys the OLD token, which is no longer
// stored, so leaving it behind blocks nothing and is safe. It must also
// never route through the generic refresh error path (no needsReauth).
if (provider === "nous") {
try {
clearNousRefreshIntent(stored.refresh);
} catch (cleanupErr) {
logOAuthEvent("OAuth refresh intent cleanup failed (non-fatal)", {
provider,
accountId,
cause: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
});
}
}
return fresh.access;
} catch (error) {
if (error instanceof OAuthMutationBusyError) throw error;
if (!terminal(error)) throw error;
// Nous-specific failure-atomicity: a terminal refresh error that carries
// an already-issued rotated refresh token (e.g. the access JWT lacked the
// required `inference:invoke` scope) means the server consumed RT-A and
// issued RT-B. RT-B must be preserved generation-safely BEFORE forcing
// reauthentication; discarding it would lose the only usable refresh
// material and force a full re-auth for no reason.
if (provider === "nous" && error instanceof NousTokenError) {
const rotated = error.getRotatedRefresh();
if (rotated !== undefined && rotated !== stored.refresh) {
const outcome = await preserveNousRotatedRefresh(
provider,
accountId,
rotated,
generation,
stored,
);
if (outcome.kind === "persisted") {
// RT-A's intent is cleared only after RT-B is durably persisted;
// cleanup itself stays best-effort (a stale RT-A intent keys a token
// that is no longer stored).
try {
clearNousRefreshIntent(stored.refresh);
} catch (cleanupErr) {
logOAuthEvent("OAuth refresh intent cleanup failed (non-fatal)", {
provider,
accountId,
cause: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),
});
}
// Mark exactly the generation this write produced — never a
// credential written by a concurrent login between the merge and
// this step.
await markAccountNeedsReauthIfGeneration(provider, accountId, outcome.generation, writerGeneration);
} else {
// RT-B persistence failed or a newer generation superseded it:
// never clear RT-A's intent (RT-A was consumed), and mark the old
// generation needsReauth (a no-op if a newer generation won).
await markAccountNeedsReauthIfGeneration(provider, accountId, generation, writerGeneration);
}
throw new OAuthLoginRequiredError(provider);
}
}
await markAccountNeedsReauthIfGeneration(provider, accountId, generation, writerGeneration);
throw new OAuthLoginRequiredError(provider);
}
} finally {
guard.release();
}
}
async function refreshAndPersistAccessToken(
provider: string,
accountId: string,
def: OAuthProviderDef,
cred: OAuthCredentials,
signal?: AbortSignal,
flight?: OAuthRefreshFlightEvidence,
replacedStaleFlight?: OAuthRefreshFlightEvidence,
): Promise<string> {
if (provider === "xai") return refreshXaiAccountWithLock(provider, accountId, def, cred, { signal });
if (provider === "anthropic") return refreshAnthropicAccountWithLock(provider, accountId, def, cred, { signal, flight, replacedStaleFlight });
return refreshGenericAccountWithLock(provider, accountId, def, cred, { signal });
}
/**
* Shared bearer-token resolver for /models listing — used by BOTH server.ts:fetchAllModels and
* codex-catalog.ts:fetchProviderModels so OAuth providers' models are listed once logged in.
* Returns undefined for forward-mode or oauth-not-logged-in (caller skips).
*/
export async function resolveModelsAuthToken(name: string, prov: OcxProviderConfig): Promise<string | undefined> {
if (prov.authMode === "forward") return undefined;
if (prov.authMode === "oauth") {
try {
return await getValidAccessToken(name);
} catch {
return undefined;
}
}
return resolveEnvValue(prov.apiKey);
}
function modelDiscoveryTransportSeed(providerName: string, prov: OcxProviderConfig): OcxProviderConfig {
const entry = getProviderRegistryEntry(providerName);
if (
prov.authMode !== "oauth"
|| entry?.authKind !== "oauth"
|| entry.allowBaseUrlOverride === true
|| /\{[^}]*\}/.test(entry.baseUrl)
|| !providerMatchesRegistryTransport(providerName, prov)
) {
return prov;
}
// Normal routing pins fixed OAuth presets before adapter-specific transport resolution.
// Discovery must do the same so a stale or modified config baseUrl never receives a token.
return { ...prov, adapter: entry.adapter, baseUrl: entry.baseUrl };
}
/**
* Provider-correct model-discovery request (URL + headers), so both model-listing paths fetch the
* LIVE catalog correctly per adapter. Anthropic is the special case: its endpoint is `/v1/models`
* (not `/models`), it needs `anthropic-version`, and it authenticates with `x-api-key` by default
* (or `Authorization: Bearer` when `apiKeyTransport = "bearer"`), plus the OAuth beta for oauth
* mode — not a bare Bearer. Google (ai-studio mode)
* is the other special case: `x-goog-api-key` + `/v1beta/models`, returning `{ models: [...] }`.
* The catalog authority gate intentionally degrades that non-OpenAI shape to stale/static data.
* Antigravity uses its CCA `:fetchAvailableModels` RPC; everyone else uses the OpenAI-style
* `/models` + Bearer with a `{ data: [{ id, owned_by? }] }` response.
*/
export interface ModelsRequestObservedAuth {
readonly oauthApiBaseUrl?: string;
}
export function buildModelsRequest(
prov: OcxProviderConfig,
apiKey: string | undefined,
providerName = "",
observedAuth?: ModelsRequestObservedAuth,
): { method?: "POST"; url: string; headers: Record<string, string> } {
const transportSeed = modelDiscoveryTransportSeed(providerName, prov);
const copilotApiBaseUrl = observedAuth === undefined
? (providerName === "github-copilot" ? getOAuthCredentialApiBaseUrl(providerName) : undefined)
: observedAuth.oauthApiBaseUrl;
const effectiveProvider = resolveProviderTransport(
providerName,
transportSeed,
undefined,
copilotApiBaseUrl,
);
// Model discovery is an upstream request like any other, so it carries the same registry
// static headers the inference path does. Without this a provider is identified correctly
// when it answers a completion but anonymously when it lists its own models, which is the
// kind of split fingerprint an upstream rate limiter reads as two different clients.
const registryStaticHeaders = providerMatchesRegistryTransport(providerName, effectiveProvider)
? getProviderRegistryEntry(providerName)?.staticHeaders
: undefined;
const headers: Record<string, string> = {
...(mergeRegistryStaticHeaders(registryStaticHeaders, effectiveProvider.headers) ?? {}),
};
const discoveryUrl = (defaultUrl: string): string => resolveProviderModelDiscoveryUrl(
providerName,
prov,
effectiveProvider.baseUrl,
defaultUrl,
);
if (effectiveGoogleMode(providerName, effectiveProvider) === "cloud-code-assist") {
headers.Accept = "application/json";
headers["Content-Type"] = "application/json";
headers["User-Agent"] = ANTIGRAVITY_REQUEST_UA;
if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
return {
method: "POST",
url: discoveryUrl(`${effectiveProvider.baseUrl.replace(/\/+$/, "")}/v1internal:fetchAvailableModels`),
headers,
};
}
if (effectiveGoogleMode(providerName, effectiveProvider) === "ai-studio") {
// Generative Language API: API key goes in x-goog-api-key (never Authorization: Bearer),
// models live under /v1beta (v1 misses preview models), and pageSize maxes at 1000 —
// enough to list everything without a pageToken loop. Vertex/antigravity keep the
// generic branch (they fall back to their static model lists).
if (apiKey) headers["x-goog-api-key"] = apiKey;
return { url: discoveryUrl(`${effectiveProvider.baseUrl}/v1beta/models?pageSize=1000`), headers };
}
if (effectiveProvider.adapter === "anthropic") {
const base = effectiveProvider.baseUrl.replace(/\/v1\/?$/, "");
headers["anthropic-version"] = "2023-06-01";
if (effectiveProvider.authMode === "oauth") {
headers["anthropic-beta"] = ANTHROPIC_OAUTH_BETA;
if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
} else if (apiKey) {
if (effectiveProvider.apiKeyTransport === "bearer") headers["Authorization"] = `Bearer ${apiKey}`;
else headers["x-api-key"] = apiKey;
}
return { url: discoveryUrl(`${base}/v1/models?limit=1000`), headers };
}
if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
return { url: discoveryUrl(`${effectiveProvider.baseUrl}/models`), headers };
}
/**
* Refresh OAuth-managed provider presets (`models`, `noReasoningModels`, and a stale `defaultModel`)
* from the registry so a proxy update that revises a provider's models — e.g. dropping deprecated
* Claude snapshots or adding a new grok endpoint not in the live `/models` — reaches EXISTING
* configs on the next `ocx start`, instead of only fresh installs. The live `/models` fetch stays
* the primary source; this keeps the static fallback (and models-not-in-/models) current.
*
* Only touches providers that are registry-managed AND still `authMode: "oauth"`. Preset fields
* are refreshed, while the registry's `liveModels` default is normally filled only when no value
* is stored. Persists + returns true when anything changed.
*/
function cloneProviderField(value: unknown): unknown {
if (Array.isArray(value)) return [...value];
if (value && typeof value === "object") return JSON.parse(JSON.stringify(value));
return value;
}
const OAUTH_RECONCILE_FIELDS: (keyof OcxProviderConfig)[] = [
"models",
"contextWindow",
"modelContextWindows",
"defaultMaxOutputTokens",
"modelMaxOutputTokens",
"modelInputModalities",
"noReasoningModels",
"noVisionModels",
"reasoningEfforts",
"modelReasoningEfforts",
"reasoningEffortMap",
"modelReasoningEffortMap",
"noTemperatureModels",
"noTopPModels",
"noPenaltyModels",
"autoToolChoiceOnlyModels",
"preserveReasoningContentModels",
];
// `requiresReasoningPlaceholderModels` is deliberately NOT reconciled here: no
// OAuth preset seeds it, so the delete-when-preset-undefined branch would wipe
// an explicit user opt-out (`[]`) on every startup. Registry seeds still reach
// existing rows through enrichProviderFromRegistry, which is fill-only and
// preserves explicit saved values.
const GOOGLE_ANTIGRAVITY_PROVIDER = "google-antigravity";
const GOOGLE_ANTIGRAVITY_LIVE_DISCOVERY_VERSION = 2 as const;
/** Only migrate the three-model experimental seed; an operator's later `liveModels: false` wins. */
function isLegacyCommandCodeStaticCatalog(provider: OcxProviderConfig): boolean {
return provider.liveModels === false
&& provider.defaultModel === "deepseek-v4-flash"
&& JSON.stringify(provider.models) === JSON.stringify(["deepseek-v4-flash", "kimi-k3", "glm-5.2"]);
}
function isLegacyAntigravityStaticCatalog(provider: OcxProviderConfig): boolean {
// A fingerprint of the shape version 1 actually shipped, NOT of the current registry.