-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathindex.ts
More file actions
5447 lines (5175 loc) · 210 KB
/
Copy pathindex.ts
File metadata and controls
5447 lines (5175 loc) · 210 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
/**
* OpenAI ChatGPT (Codex) OAuth Authentication Plugin for opencode
*
* COMPLIANCE NOTICE:
* This plugin uses OpenAI's official OAuth authentication flow (the same method
* used by OpenAI's official Codex CLI at https://github.com/openai/codex).
*
* INTENDED USE: Personal development and coding assistance with your own
* ChatGPT Plus/Pro subscription.
*
* NOT INTENDED FOR: Commercial resale, multi-user services, high-volume
* automated extraction, or any use that violates OpenAI's Terms of Service.
*
* Users are responsible for ensuring their usage complies with:
* - OpenAI Terms of Use: https://openai.com/policies/terms-of-use/
* - OpenAI Usage Policies: https://openai.com/policies/usage-policies/
*
* For production applications, use the OpenAI Platform API: https://platform.openai.com/
*
* @license MIT (see LICENSE file)
* @author ndycode
* @repository https://github.com/ndycode/oc-codex-multi-auth
*/
import { mkdir, readFile } from "node:fs/promises";
import { watchFile, unwatchFile } from "node:fs";
import { writeFileAtomic } from "./lib/storage/atomic-write.js";
import { consumeLastWrittenAccountsDigest } from "./lib/storage/load-save.js";
import { subscribeToStoragePathChanges } from "./lib/storage/state.js";
import { isKeychainOptInEnabled } from "./lib/storage/keychain.js";
import { AnyAccountStorageSchema } from "./lib/schemas.js";
import { registerCleanup, unregisterCleanup } from "./lib/shutdown.js";
import { createHash } from "node:crypto";
import { homedir } from "node:os";
import { isAbsolute, join } from "node:path";
import type { Plugin, PluginInput, Hooks } from "@opencode-ai/plugin";
import type { Auth } from "@opencode-ai/sdk";
import {
type AuthorizationInputParseResult,
createAuthorizationFlow,
exchangeAuthorizationCode,
parseAuthorizationInput,
REDIRECT_URI,
} from "./lib/auth/auth.js";
import { formatPlanType } from "./lib/auth/plan-tier.js";
import {
startLoopbackFlow,
type LoopbackFlowUnavailable,
} from "./lib/auth/loopback-flow.js";
import {
buildDeviceCodeInstructions,
completeDeviceCodeSession,
createDeviceCodeSession,
} from "./lib/auth/device-code.js";
import {
applyAccountSelectionFallbacks,
persistResolvedAccountSelection,
persistAccountPool,
resolveAndPersistAccountSelection,
resolveAccountSelection,
type AccountSelectionResult,
type TokenSuccessWithAccount,
} from "./lib/auth/login-runner.js";
import {
coordinateFlaggedPersistedRefresh,
coordinatePersistedRefresh,
} from "./lib/storage/coordinated-refresh.js";
import { promptAddAnotherAccount, promptLoginMode } from "./lib/cli.js";
import {
getCodexMode,
getRequestTransformMode,
getFastSession,
getFastSessionStrategy,
getFastSessionMaxInputItems,
getRetryProfile,
getRetryBudgetOverrides,
getRateLimitToastDebounceMs,
getRetryAllAccountsMaxRetries,
getRetryAllAccountsMaxWaitMs,
getRetryAllAccountsRateLimited,
getFallbackToGpt52OnUnsupportedGpt53,
getUnsupportedCodexPolicy,
getUnsupportedCodexFallbackChain,
getTokenRefreshSkewMs,
getSessionRecovery,
getAutoResume,
getAutoUpdate,
getToastDurationMs,
getAccountToastsEnabled,
getPerProjectAccounts,
getEmptyResponseMaxRetries,
getEmptyResponseRetryDelayMs,
getPidOffsetEnabled,
getRotationStrategy,
getModelAccountPool,
getModelAccountPoolMode,
getFetchTimeoutMs,
getStreamStallTimeoutMs,
getMaxStreamDurationMs,
getCodexTuiV2,
getCodexTuiColorProfile,
getCodexTuiGlyphMode,
getBeginnerSafeMode,
getCodexTuiMaskEmail,
getQuotaDisplay,
loadPluginConfig,
} from "./lib/config.js";
import {
AUTH_LABELS,
CODEX_BASE_URL,
DUMMY_API_KEY,
LOG_STAGES,
PLUGIN_NAME,
PROVIDER_ID,
ACCOUNT_LIMITS,
MAX_QUOTA_FALLBACK_SWITCHES,
} from "./lib/constants.js";
import {
initLogger,
LOG_DIR,
logRequest,
logDebug,
logInfo,
logWarn,
logError,
setCorrelationId,
clearCorrelationId,
} from "./lib/logger.js";
import { createQuotaMonitor } from "./lib/quota-notifications.js";
import { checkAndNotify } from "./lib/auto-update-checker.js";
import { describePluginOrigin, getPluginOrigin, recordPluginOrigin } from "./lib/plugin-origin.js";
import { handleContextOverflow } from "./lib/context-overflow.js";
import {
AccountManager,
type AccountSelectionExplainability,
type ManagedAccount,
extractAccountEmail,
extractAccountId,
formatAccountLabel,
formatWaitTime,
sanitizeEmail,
shouldUpdateAccountIdFromToken,
resolveRequestAccountId,
parseRateLimitReason,
lookupCodexCliTokensByEmail,
} from "./lib/accounts.js";
import {
getModelPoolAccountKey,
matchesModelPoolAccountKey,
type ModelPoolAccount,
} from "./lib/accounts/pool-identity.js";
import {
formatSeatSuffix,
maskIdentityValue,
resolveDisplayEmail,
seatIsDisclosable,
} from "./lib/account-display.js";
import { extractAccountUserId } from "./lib/auth/token-utils.js";
import { CodexAuthError, StorageTransactionContentionError } from "./lib/errors.js";
import {
getStoragePath,
loadAccounts,
withAccountStorageTransaction,
clearAccounts,
setStoragePath,
loadFlaggedAccounts,
withFlaggedAccountStorageTransaction,
clearFlaggedAccounts,
StorageError,
formatStorageErrorHint,
type AccountStorageV3,
type FlaggedAccountMetadataV1,
} from "./lib/storage.js";
import { getWorkspaceIdentityKey } from "./lib/storage/identity.js";
import {
createCodexHeaders,
extractRequestUrl,
handleErrorResponse,
handleSuccessResponse,
isDeactivatedWorkspaceError,
isInvalidatedAuthTokenError,
createAbortError,
getUnsupportedCodexModelInfo,
resolveUnsupportedCodexFallbackModel,
isDefaultAutoFallbackModel,
pickFallbackChainTarget,
refreshAndUpdateToken,
rewriteUrlForCodex,
shouldRefreshToken,
transformRequestForCodex,
} from "./lib/request/fetch-helpers.js";
import { shapeBodyForModel } from "./lib/request/helpers/responses-lite.js";
import {
DEACTIVATED_WORKSPACE_ERROR_CODE,
isDeactivatedWorkspaceErrorMessage,
isInvalidatedAuthTokenMessage,
} from "./lib/error-sentinels.js";
import {
applyFastSessionDefaults,
clampReasoningForModel,
upsertBackendModelIdentityMessage,
} from "./lib/request/request-transformer.js";
import {
getRateLimitBackoff,
RATE_LIMIT_SHORT_RETRY_THRESHOLD_MS,
resetRateLimitBackoff,
} from "./lib/request/rate-limit-backoff.js";
import { isEmptyResponse } from "./lib/request/response-handler.js";
import { getCircuitBreaker } from "./lib/circuit-breaker.js";
import {
RetryBudgetTracker,
resolveRetryBudgetLimits,
type RetryBudgetClass,
} from "./lib/request/retry-budget.js";
import { addJitter } from "./lib/rotation.js";
import { setUiRuntimeOptions, type UiRuntimeOptions } from "./lib/ui/runtime.js";
import { sanitizeDisplayText } from "./lib/ui/display-text.js";
import { formatUiBadge, formatUiHeader, formatUiItem, formatUiKeyValue, formatUiSection } from "./lib/ui/format.js";
import {
buildBeginnerChecklist,
recommendBeginnerNextAction,
summarizeBeginnerAccounts,
type BeginnerAccountSnapshot,
type BeginnerDiagnosticSeverity,
type BeginnerRuntimeSnapshot,
} from "./lib/ui/beginner.js";
import {
ensureInstructionIdentity,
getModelFamily,
getCodexInstructions,
MODEL_FAMILIES,
prewarmCodexInstructions,
type ModelFamily,
} from "./lib/prompts/codex.js";
import { prewarmOpenCodeCodexPrompt } from "./lib/prompts/opencode-codex.js";
import type {
OAuthAuthDetails,
RequestBody,
TokenResult,
UserConfig,
} from "./lib/types.js";
import {
createSessionRecoveryHook,
isRecoverableError,
detectErrorType,
getRecoveryToastContent,
} from "./lib/recovery.js";
import {
matchesWorkspaceIdentity,
upsertFlaggedAccountRecord,
createRetryBudgetUsage,
serializeSelectionExplainability,
formatRoutingValue,
formatExplainabilitySummary,
type RoutingVisibilitySnapshot,
type RuntimeMetrics,
} from "./lib/runtime.js";
import {
createToolRegistry,
type ToolContext,
} from "./lib/tools/index.js";
import {
createUsageAccountFingerprint,
fetchCodexUsage,
formatUsageLimitSummary,
formatUsageLimitTitle,
hasUsageWindow,
parseCodexUsagePayload,
type CodexUsageSummary,
} from "./lib/codex-usage.js";
import { getQuotaExhaustedResetAtMs } from "./lib/quota-windows.js";
import {
clearTuiQuotaSnapshot,
parseTuiQuotaSnapshotFromHeaders,
writeTuiQuotaSnapshot,
} from "./lib/tui-quota-cache.js";
/**
* IPv6 loopback literal. WHATWG URL parsing compresses every equivalent
* spelling (`0:0:0:0:0:0:0:1` -> `::1`), so only the canonical form is listed.
*/
const LOOPBACK_GATEWAY_HOSTS = new Set(["::1"]);
const IPV4_LITERAL_PATTERN = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
/**
* IPv4-mapped IPv6, which WHATWG serializes in hex rather than dotted form:
* `::ffff:127.0.0.1` -> `::ffff:7f00:1`, `::ffff:127.1.1.1` -> `::ffff:7f01:101`.
* The high byte of the first group is the first IPv4 octet.
*/
const IPV4_MAPPED_PATTERN = /^::ffff:([0-9a-f]{1,4}):[0-9a-f]{1,4}$/;
/**
* Cleartext HTTP is only safe for a peer that cannot leave the host, so the check
* is deliberately restricted to *literal* loopback addresses. Hostnames such as
* `localhost` are rejected even though they usually resolve to 127.0.0.1: a host
* file or resolver can point them at a remote peer, which would leak the ChatGPT
* OAuth access token over the wire.
*
* The whole 127.0.0.0/8 range is accepted, not just 127.0.0.1 — running several
* local services on 127.0.0.2, 127.0.1.1, and friends is a common pattern, and
* every address in the block is equally unroutable.
*/
function isLoopbackGatewayHost(hostname: string): boolean {
const ipv4 = IPV4_LITERAL_PATTERN.exec(hostname);
if (ipv4) {
const octets = ipv4.slice(1).map((part) => Number(part));
if (octets.some((octet) => !Number.isInteger(octet) || octet > 255)) return false;
return octets[0] === 127;
}
const mapped = IPV4_MAPPED_PATTERN.exec(hostname);
if (mapped?.[1]) {
// `::ffff:7f00:2` is 127.0.0.2 — just as unroutable as the dotted
// spelling, so rejecting it would be an inconsistency, not a safeguard.
return Number.parseInt(mapped[1], 16) >>> 8 === 0x7f;
}
return LOOPBACK_GATEWAY_HOSTS.has(hostname);
}
/** Stable per-seat identity used only for in-memory traversal diagnostics. */
function getAccountDiagnosticsKey(account: ManagedAccount): string {
return JSON.stringify([
getModelPoolAccountKey(account) ?? "unresolved",
account.organizationId ?? null,
account.email ?? null,
account.addedAt,
]);
}
/** Configured pool keys matching no live account (typo, or account removed). */
function countUnresolvedPoolKeys(
accounts: readonly ModelPoolAccount[],
poolKeys: readonly string[],
): number {
return poolKeys.filter(
(key) => !accounts.some((account) => matchesModelPoolAccountKey(account, key)),
).length;
}
function invalidBaseURL(reason: string): Error {
return new Error(
`[oc-codex-multi-auth] OPENAI_BASE_URL is invalid: ${reason}. Fix the value, or unset ` +
"CODEX_AUTH_ALLOW_OPENAI_BASE_URL to fall back to the default ChatGPT Codex endpoint.",
);
}
function resolveOpenAIBaseURL(): string | undefined {
if (process.env.CODEX_AUTH_ALLOW_OPENAI_BASE_URL !== "1") return undefined;
const raw = process.env.OPENAI_BASE_URL?.trim();
if (!raw) return undefined;
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
// `new URL()` throws a bare `TypeError: Invalid URL` that names neither the
// plugin nor the variable, which is useless when it surfaces out of the
// auth loader. A scheme-less value such as `gateway.example/v1` is the
// common way to hit this. The value itself is NOT echoed: it can carry a
// token in a query string, and this message reaches a toast.
throw invalidBaseURL(
"the value is not a valid absolute URL (an explicit https:// or http:// scheme is required)",
);
}
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
throw invalidBaseURL("it must use http:// or https://");
}
if (parsed.username || parsed.password) {
throw invalidBaseURL("it must not embed credentials");
}
if (parsed.search || parsed.hash || raw.includes("?") || raw.includes("#")) {
throw invalidBaseURL("it must not include a query string or fragment");
}
const hostname = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, "");
if (parsed.protocol === "http:" && !isLoopbackGatewayHost(hostname)) {
throw invalidBaseURL(
`https:// is required for non-loopback host "${hostname}" so the ChatGPT OAuth ` +
"access token is never sent in cleartext",
);
}
return parsed.toString().replace(/\/+$/, "");
}
/**
* Refcounted `fs.watchFile` registry for the accounts-store watcher.
*
* Every `watchFile` call installs its own `StatWatcher` (a `change` listener
* plus a periodic stat poll) on the path. Before this registry, each armed
* plugin runtime subscribed independently, so runtimes that were never
* disposed accumulated watchers on the same file — measured at one extra
* listener and one fan-out stat loop per live runtime. One watcher per path
* now serves every subscriber; the underlying `unwatchFile` runs when the
* last subscriber releases.
*/
const fileWatchSubscribers = new Map<string, Set<() => void>>();
const fileWatchDispatchers = new Map<string, () => void>();
function acquireFileWatch(path: string, listener: () => void): () => void {
let subscribers = fileWatchSubscribers.get(path);
if (!subscribers) {
subscribers = new Set();
fileWatchSubscribers.set(path, subscribers);
const dispatcher = (): void => {
// Snapshot the set: a subscriber released mid-dispatch must not
// starve the subscribers after it.
for (const subscriber of [...(fileWatchSubscribers.get(path) ?? [])]) {
try {
subscriber();
} catch {
// One throwing subscriber must not starve the rest.
}
}
};
fileWatchDispatchers.set(path, dispatcher);
watchFile(path, { interval: 1500, persistent: false }, dispatcher);
}
subscribers.add(listener);
let released = false;
return () => {
if (released) return;
released = true;
const current = fileWatchSubscribers.get(path);
if (!current) return;
current.delete(listener);
if (current.size === 0) {
fileWatchSubscribers.delete(path);
const dispatcher = fileWatchDispatchers.get(path);
fileWatchDispatchers.delete(path);
if (dispatcher) unwatchFile(path, dispatcher);
}
};
}
/**
* True for failures where the credential store itself could not be read —
* never an upstream auth rejection, so it must not count toward
* `MAX_AUTH_FAILURES` removal.
*
* The refresh pipeline reaches the store through `coordinatePersistedRefresh`
* and surfaces three shapes: a typed {@link StorageError} from the load path,
* a {@link StorageTransactionContentionError} when the lockfile stays held,
* and the bare `Error("Account storage is unavailable")` that
* `runAccountTransaction` raises when `loadAccounts()` resolves to null.
*/
function isStorageUnavailableError(error: unknown): boolean {
if (error instanceof StorageError) return true;
if (error instanceof StorageTransactionContentionError) return true;
return (
error instanceof Error &&
/account storage is unavailable/i.test(error.message)
);
}
/**
* Suffix appended to terminal request-failure responses so a bare
* "All N account(s) failed" is diagnosable instead of a dead end.
*/
const REQUEST_LOG_HINT = `Request logs live in ${LOG_DIR} (enable with ENABLE_PLUGIN_REQUEST_LOGGING=1).`;
/**
* The plugin's hook surface, plus an explicit teardown for hosts and tests
* that cannot wait for the `server.instance.disposed` event.
*/
type PluginRuntimeHooks = Hooks & {
/**
* Dispose this runtime: stops the quota monitor and the accounts-file
* watcher, then flushes and retires the cached account manager.
* Idempotent; equivalent to the `server.instance.disposed` event path.
*/
dispose: () => Promise<void>;
};
/**
* OpenAI Codex OAuth authentication plugin for opencode
*
* This plugin enables opencode to use OpenAI's Codex backend via ChatGPT Plus/Pro
* OAuth authentication, allowing users to leverage their ChatGPT subscription
* instead of OpenAI Platform API credits.
*
* @example
* ```json
* {
* "plugin": ["oc-codex-multi-auth"],
* "model": "openai/gpt-5-codex"
* }
* ```
*/
// `directory` (falling back to `worktree`) binds per-project account storage,
// so it must come from the host, not the process: under `opencode serve` and
// other multi-project daemons the process cwd is the launch directory and
// every project would otherwise share one pool. When the host supplies
// neither, `createPluginRuntime` still defaults to `process.cwd()`.
export const OpenAIOAuthPlugin: Plugin = async ({ client, directory, worktree }: PluginInput) =>
createPluginRuntime({ client, directory: directory ?? worktree });
/**
* Shared request/account runtime; V2 has no V1 client or host auth.json.
*
* Not exported: V1 hosts call every function this module exports as a plugin,
* so an exported factory would boot a second runtime beside the real one. The
* V2 entry receives it through `setup` instead.
*/
async function createPluginRuntime({ client, directory = process.cwd() }: {
client?: PluginInput["client"];
directory?: string;
}): Promise<PluginRuntimeHooks> {
initLogger(client ?? {});
let customBaseURLWarningShown = false;
let customBaseURLErrorShown = false;
let cachedAccountManager: AccountManager | null = null;
let accountManagerPromise: Promise<AccountManager> | null = null;
let loaderMutex: Promise<void> | null = null;
let startupPrewarmTriggered = false;
let startupOriginRecorded = false;
let startupPreflightShown = false;
let beginnerSafeModeEnabled = false;
const MIN_BACKOFF_MS = 100;
// An all-accounts rate-limit wait can run for days, and the local accounts
// file is its only wake-up. A quota reset granted server-side leaves that file
// untouched, so such a wait would be slept straight through. Long waits
// therefore re-probe upstream: first after a minute, doubling to a quarter
// hour, so a multi-day sleep costs a handful of usage requests rather than one
// per countdown tick.
const UPSTREAM_REPROBE_MIN_WAIT_MS = 60_000;
const UPSTREAM_REPROBE_FIRST_DELAY_MS = 60_000;
const UPSTREAM_REPROBE_MAX_DELAY_MS = 15 * 60_000;
// `retryAllAccountsMaxWaitMs: 0` lets an all-accounts rate-limit wait run as
// long as the backend asks — and quota blocks can stretch for days, which an
// interactive request must not sit through. `0` therefore means "bounded by
// this ceiling" unless the operator restores truly unbounded waits with
// CODEX_RETRY_ALL_UNBOUNDED=1.
const INTERACTIVE_ALL_LIMITED_CEILING_MS = 10 * 60_000;
const runtimeMetrics: RuntimeMetrics = {
startedAt: Date.now(),
totalRequests: 0,
successfulRequests: 0,
failedRequests: 0,
rateLimitedResponses: 0,
serverErrors: 0,
networkErrors: 0,
authRefreshFailures: 0,
emptyResponseRetries: 0,
accountRotations: 0,
cumulativeLatencyMs: 0,
retryBudgetExhaustions: 0,
retryBudgetUsage: createRetryBudgetUsage(),
retryBudgetLimits: resolveRetryBudgetLimits("balanced"),
retryProfile: "balanced",
lastRetryBudgetExhaustedClass: null,
lastRetryBudgetReason: null,
lastRequestAt: null,
lastError: null,
lastErrorCategory: null,
promptCacheEnabledRequests: 0,
promptCacheMissingRequests: 0,
lastPromptCacheKey: null,
lastSelectedAccountIndex: null,
lastQuotaKey: null,
lastSelectionSnapshot: null,
};
const buildRoutingVisibilitySnapshot = (
options: {
modelFamily?: ModelFamily | null;
effectiveModel?: string | null;
quotaKey?: string | null;
selectedAccountIndex?: number | null;
selectionExplainability?: AccountSelectionExplainability[];
} = {},
): RoutingVisibilitySnapshot => {
const snapshot = runtimeMetrics.lastSelectionSnapshot;
const rawSelectedAccountIndex =
options.selectedAccountIndex ??
snapshot?.selectedAccountIndex ??
runtimeMetrics.lastSelectedAccountIndex;
return {
requestedModel: snapshot?.requestedModel ?? null,
effectiveModel:
options.effectiveModel ?? snapshot?.effectiveModel ?? snapshot?.model ?? null,
modelFamily: options.modelFamily ?? snapshot?.family ?? null,
quotaKey: options.quotaKey ?? snapshot?.quotaKey ?? runtimeMetrics.lastQuotaKey,
selectedAccountIndex:
rawSelectedAccountIndex === null || rawSelectedAccountIndex === undefined
? null
: rawSelectedAccountIndex + 1,
zeroBasedSelectedAccountIndex: rawSelectedAccountIndex ?? null,
lastErrorCategory: runtimeMetrics.lastErrorCategory,
fallbackApplied: snapshot?.fallbackApplied ?? false,
fallbackFrom: snapshot?.fallbackFrom ?? null,
fallbackTo: snapshot?.fallbackTo ?? null,
fallbackReason: snapshot?.fallbackReason ?? null,
accountPoolMode: snapshot?.accountPoolMode ?? null,
configuredAccountPoolSize: snapshot?.configuredAccountPoolSize ?? 0,
selectionExplainability: serializeSelectionExplainability(
options.selectionExplainability ?? snapshot?.explainability ?? [],
),
};
};
const buildJsonAccountIdentity = (
index: number,
options: {
includeSensitive?: boolean;
account?: {
email?: string;
accountId?: string;
accountUserId?: string;
accountLabel?: string;
accountTags?: string[];
accountNote?: string;
};
label?: string;
peerAccounts?: readonly ({ accountUserId?: string } | undefined)[];
} = {},
): Record<string, unknown> => {
const includeSensitive = options.includeSensitive ?? false;
const accountUserId = options.account?.accountUserId?.trim() || undefined;
return {
index: index + 1,
zeroBasedIndex: index,
...(includeSensitive
? {
label:
options.label ??
formatCommandAccountLabel(options.account, index, {
peerAccounts: options.peerAccounts,
}),
email: options.account?.email ?? null,
accountId: options.account?.accountId ?? null,
}
: {}),
// Members of one Business workspace share `accountId`, so the seat is
// the field a JSON consumer can tell them apart by. It rides in both
// modes - the member id masked when sensitive output is off, and the
// suffix withheld when the id is too short to excerpt without
// disclosing it - under the same field names the standalone CLI emits.
accountUserId: maskIdentityValue(accountUserId, includeSensitive) ?? null,
seatSuffix: seatIsDisclosable(accountUserId, includeSensitive)
? (formatSeatSuffix(
accountUserId,
options.peerAccounts?.map((peer) => peer?.accountUserId),
) ?? null)
: null,
};
};
const appendRoutingVisibilityText = (
lines: string[],
routing: RoutingVisibilitySnapshot,
options: { includeExplainability?: boolean } = {},
): void => {
lines.push("Routing visibility:");
lines.push(` Requested model: ${formatRoutingValue(routing.requestedModel)}`);
lines.push(` Effective model: ${formatRoutingValue(routing.effectiveModel)}`);
lines.push(` Model family: ${formatRoutingValue(routing.modelFamily)}`);
lines.push(` Quota key: ${formatRoutingValue(routing.quotaKey)}`);
lines.push(
` Selected account: ${
routing.selectedAccountIndex === null
? "-"
: String(routing.selectedAccountIndex)
}`,
);
lines.push(
` Last error category: ${formatRoutingValue(routing.lastErrorCategory)}`,
);
lines.push(` Fallback applied: ${formatRoutingValue(routing.fallbackApplied)}`);
lines.push(` Fallback from: ${formatRoutingValue(routing.fallbackFrom)}`);
lines.push(` Fallback to: ${formatRoutingValue(routing.fallbackTo)}`);
lines.push(` Fallback reason: ${formatRoutingValue(routing.fallbackReason)}`);
lines.push(` Account pool: ${formatRoutingValue(routing.accountPoolMode)}`);
lines.push(` Configured pool size: ${routing.configuredAccountPoolSize}`);
if (options.includeExplainability) {
lines.push(" Selection explainability:");
if (routing.selectionExplainability.length === 0) {
lines.push(" - none");
} else {
for (const entry of routing.selectionExplainability) {
lines.push(` - ${formatExplainabilitySummary(entry)}`);
}
}
}
};
const appendRoutingVisibilityUi = (
ui: UiRuntimeOptions,
lines: string[],
routing: RoutingVisibilitySnapshot,
options: { includeExplainability?: boolean } = {},
): void => {
lines.push(...formatUiSection(ui, "Routing visibility"));
lines.push(
formatUiKeyValue(
ui,
"Requested model",
formatRoutingValue(routing.requestedModel),
"muted",
),
);
lines.push(
formatUiKeyValue(
ui,
"Effective model",
formatRoutingValue(routing.effectiveModel),
"muted",
),
);
lines.push(
formatUiKeyValue(
ui,
"Model family",
formatRoutingValue(routing.modelFamily),
"muted",
),
);
lines.push(
formatUiKeyValue(ui, "Quota key", formatRoutingValue(routing.quotaKey), "muted"),
);
lines.push(
formatUiKeyValue(
ui,
"Selected account",
routing.selectedAccountIndex === null
? "-"
: String(routing.selectedAccountIndex),
routing.selectedAccountIndex === null ? "muted" : "accent",
),
);
lines.push(
formatUiKeyValue(
ui,
"Last error category",
formatRoutingValue(routing.lastErrorCategory),
routing.lastErrorCategory ? "warning" : "muted",
),
);
lines.push(
formatUiKeyValue(
ui,
"Fallback applied",
formatRoutingValue(routing.fallbackApplied),
routing.fallbackApplied ? "accent" : "muted",
),
);
lines.push(
formatUiKeyValue(
ui,
"Fallback from",
formatRoutingValue(routing.fallbackFrom),
"muted",
),
);
lines.push(
formatUiKeyValue(
ui,
"Fallback to",
formatRoutingValue(routing.fallbackTo),
"muted",
),
);
lines.push(
formatUiKeyValue(
ui,
"Fallback reason",
formatRoutingValue(routing.fallbackReason),
routing.fallbackReason ? "warning" : "muted",
),
);
lines.push(
formatUiKeyValue(
ui,
"Account pool",
formatRoutingValue(routing.accountPoolMode),
routing.accountPoolMode === "general-fallback" ||
routing.accountPoolMode === "strict-unavailable"
? "warning"
: "muted",
),
);
lines.push(
formatUiKeyValue(
ui,
"Configured pool size",
String(routing.configuredAccountPoolSize),
"muted",
),
);
if (options.includeExplainability) {
lines.push("");
lines.push(...formatUiSection(ui, "Selection explainability"));
if (routing.selectionExplainability.length === 0) {
lines.push(formatUiItem(ui, "none", "muted"));
} else {
for (const entry of routing.selectionExplainability) {
lines.push(formatUiItem(ui, formatExplainabilitySummary(entry)));
}
}
}
};
const listenerUnavailableMessage = (): string =>
`OAuth callback server failed to start on localhost loopback port 1455. ` +
`Retry with "${AUTH_LABELS.OAUTH_DEVICE_CODE}" or "${AUTH_LABELS.OAUTH_MANUAL}".`;
const callbackCancelledMessage = (): string =>
`OAuth callback timed out or was cancelled. ` +
`If you are on SSH, WSL, or a headless machine, retry with "${AUTH_LABELS.OAUTH_DEVICE_CODE}" or "${AUTH_LABELS.OAUTH_MANUAL}".`;
// The login is still live when this fires: the listener is bound and
// waiting, so opening the URL printed above finishes it. That is the
// whole recovery path on a host with no opener on PATH.
const browserOpenFailedMessage = (): string =>
`Could not launch your default browser. Open the OAuth URL above in any browser to finish signing in; ` +
`this login is still waiting on the localhost callback. ` +
`"${AUTH_LABELS.OAUTH_MANUAL_BROWSER}" does the same thing without trying to launch a browser, ` +
`and "${AUTH_LABELS.OAUTH_DEVICE_CODE}" or "${AUTH_LABELS.OAUTH_MANUAL}" avoid the callback entirely.`;
const unavailableMessage = (
lifecycle: LoopbackFlowUnavailable["lifecycle"],
): string => {
switch (lifecycle) {
case "listener_unavailable":
return listenerUnavailableMessage();
default: {
const unreachable: never = lifecycle;
return unreachable;
}
}
};
/**
* Every accepted paste must carry this attempt's `state`, a raw code
* included.
*
* That comparison is the manual flow's only in-plugin binding between
* the pasted value and this login. Accepting a bare code delegates the
* binding entirely to the authorization server's PKCE enforcement, and
* hands anything a user is talked into pasting to
* `exchangeAuthorizationCode` with this attempt's verifier — which is
* the shape of the attack the state check exists to stop. The raw
* branch of `parseAuthorizationInput` also returns the whole trimmed
* input as the code, so a noisy paste would be forwarded verbatim.
*/
const manualInputRejection = (
parsed: AuthorizationInputParseResult,
expectedState: string,
): string | undefined => {
if (!parsed.code) {
return "No authorization code found. Paste the full callback URL (e.g., http://localhost:1455/auth/callback?code=...&state=...). If browser callback keeps failing, retry with Device Code.";
}
switch (parsed.source) {
case "raw":
return "That is a bare authorization code. This flow needs the full callback URL, including the state parameter (e.g., http://localhost:1455/auth/callback?code=...&state=...), which is what ties the code to this login attempt. If needed, retry with Device Code.";
case "url":
case "query":
case "fragment":
if (!parsed.state) {
return "That callback URL carries no OAuth state, so it cannot be matched to this login attempt. Paste the complete callback URL including its state parameter, or retry with Device Code.";
}
if (parsed.state !== expectedState) {
return "OAuth state mismatch. Restart login and paste the callback URL generated for this login attempt, or retry with Device Code.";
}
return undefined;
default: {
const unreachable: never = parsed;
return unreachable;
}
}
};
const buildManualOAuthFlow = (
pkce: { verifier: string },
url: string,
expectedState: string,
replaceAll: boolean,
) => ({
url,
method: "code" as const,
instructions: AUTH_LABELS.INSTRUCTIONS_MANUAL,
validate: (input: string): string | undefined =>
manualInputRejection(parseAuthorizationInput(input), expectedState),
callback: async (input: string) => {
const parsed = parseAuthorizationInput(input);
const rejection = manualInputRejection(parsed, expectedState);
if (rejection !== undefined || !parsed.code) {
return {
type: "failed" as const,
reason: "invalid_response" as const,
message: rejection ?? "Missing authorization code",
};
}
const tokens = await exchangeAuthorizationCode(
parsed.code,
pkce.verifier,
REDIRECT_URI,
);
if (tokens?.type === "success") {
const resolved = await resolveAndPersistAccountSelection(tokens, {
persistSelections: persistAuthenticatedSelections,
replaceAll,
});
return resolved.primary;
}
return tokens?.type === "failed"
? tokens
: { type: "failed" as const };
},
});
const runOAuthFlow = async (
forceNewLogin: boolean = false,
): Promise<TokenResult> => {
const session = await startLoopbackFlow({
openBrowser: true,
forceNewLogin,
});
if (session.type === "unavailable") {
const message = unavailableMessage(session.lifecycle);
logWarn(`\n[${PLUGIN_NAME}] ${message}\n`);
return {
type: "failed" as const,
reason: "invalid_response" as const,
message,
};
}
logInfo(`OAuth URL: ${session.url}`);
// Printed first, so the recovery instruction points at a URL the
// user can already see. The session stays open either way.
if (!session.browserOpened) {
logWarn(`\n[${PLUGIN_NAME}] ${browserOpenFailedMessage()}\n`);
}
const result = await session.waitAndExchange();
if (result.type === "cancelled") {
return {
type: "failed" as const,
reason: "unknown" as const,
message: callbackCancelledMessage(),
};
}
return result;
};
const showToast = async (
message: string,
variant: "info" | "success" | "warning" | "error" = "success",
options?: { title?: string; duration?: number },
): Promise<void> => {
try {
await client?.tui.showToast({
body: {
message,
variant,
...(options?.title && { title: options.title }),
...(options?.duration && { duration: options.duration }),
},
});
} catch {
// Ignore when TUI is not available.
}
};
type TuiQuotaAccount = Parameters<typeof createUsageAccountFingerprint>[0] & {
index: number;
email?: string;
accountLabel?: string;
};
const clearPromptQuotaCache = async (): Promise<void> => {
try {
await clearTuiQuotaSnapshot();
} catch (error) {
logDebug(
`[${PLUGIN_NAME}] Failed to clear TUI quota cache: ${error instanceof Error ? error.message : String(error)}`,
);
}
};
const recordPromptQuotaHeaders = async (
response: Response,
account: TuiQuotaAccount,
accountCount: number,
peerAccounts: readonly ({ accountUserId?: string } | undefined)[],
): Promise<void> => {
try {
const snapshot = parseTuiQuotaSnapshotFromHeaders(response.headers, {
fingerprint: createUsageAccountFingerprint(account),
accountIndex: account.index + 1,
accountCount,
accountEmail: account.email?.trim() || undefined,
accountLabel: formatAccountLabel(account, account.index, {
peerAccounts,
}),
});
if (!snapshot) return;
await writeTuiQuotaSnapshot(snapshot);
} catch (error) {
logDebug(
`[${PLUGIN_NAME}] Failed to record TUI quota headers: ${error instanceof Error ? error.message : String(error)}`,