-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcodex-manager.ts
More file actions
5007 lines (4666 loc) · 137 KB
/
codex-manager.ts
File metadata and controls
5007 lines (4666 loc) · 137 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 { existsSync, promises as fs } from "node:fs";
import { dirname, resolve } from "node:path";
import { stdin as input, stdout as output } from "node:process";
import { createInterface } from "node:readline/promises";
import {
extractAccountEmail,
extractAccountId,
formatAccountLabel,
formatCooldown,
formatWaitTime,
getAccountIdCandidates,
resolveRequestAccountId,
sanitizeEmail,
selectBestAccountCandidate,
} from "./accounts.js";
import {
createAuthorizationFlow,
exchangeAuthorizationCode,
parseAuthorizationInput,
REDIRECT_URI,
} from "./auth/auth.js";
import { copyTextToClipboard, openBrowserUrl } from "./auth/browser.js";
import { startLocalOAuthServer } from "./auth/server.js";
import {
type ExistingAccountInfo,
isInteractiveLoginMenuAvailable,
promptAddAnotherAccount,
promptLoginMode,
} from "./cli.js";
import {
getCodexCliAuthPath,
getCodexCliConfigPath,
loadCodexCliState,
} from "./codex-cli/state.js";
import { setCodexCliActiveSelection } from "./codex-cli/writer.js";
import {
applyUiThemeFromDashboardSettings,
configureUnifiedSettings,
resolveMenuLayoutMode,
} from "./codex-manager/settings-hub.js";
import { ACCOUNT_LIMITS } from "./constants.js";
import {
type DashboardAccountSortMode,
type DashboardDisplaySettings,
DEFAULT_DASHBOARD_DISPLAY_SETTINGS,
loadDashboardDisplaySettings,
} from "./dashboard-settings.js";
import {
DESTRUCTIVE_ACTION_COPY,
deleteAccountAtIndex,
deleteSavedAccounts,
resetLocalState,
} from "./destructive-actions.js";
import {
evaluateForecastAccounts,
type ForecastAccountResult,
isHardRefreshFailure,
recommendForecastAccount,
summarizeForecast,
} from "./forecast.js";
import { MODEL_FAMILIES, type ModelFamily } from "./prompts/codex.js";
import {
loadQuotaCache,
type QuotaCacheData,
type QuotaCacheEntry,
saveQuotaCache,
} from "./quota-cache.js";
import {
type CodexQuotaSnapshot,
fetchCodexQuotaSnapshot,
formatQuotaSnapshotLine,
} from "./quota-probe.js";
import { queuedRefresh } from "./refresh-queue.js";
import {
type AccountMetadataV3,
type AccountStorageV3,
assessNamedBackupRestore,
type FlaggedAccountMetadataV1,
type FlaggedAccountStorageV1,
getActionableNamedBackupRestores,
getNamedBackupsDirectoryPath,
getStoragePath,
listNamedBackups,
listRotatingBackups,
loadAccounts,
loadFlaggedAccounts,
restoreNamedBackup,
saveAccounts,
saveFlaggedAccounts,
setStoragePath,
} from "./storage.js";
import type { AccountIdSource, TokenFailure, TokenResult } from "./types.js";
import { ANSI } from "./ui/ansi.js";
import { confirm } from "./ui/confirm.js";
import { UI_COPY } from "./ui/copy.js";
import { paintUiText, quotaToneFromLeftPercent } from "./ui/format.js";
import { getUiRuntimeOptions } from "./ui/runtime.js";
import { type MenuItem, select } from "./ui/select.js";
type TokenSuccess = Extract<TokenResult, { type: "success" }>;
type TokenSuccessWithAccount = TokenSuccess & {
accountIdOverride?: string;
accountIdSource?: AccountIdSource;
accountLabel?: string;
};
type PromptTone = "accent" | "success" | "warning" | "danger" | "muted";
function stylePromptText(text: string, tone: PromptTone): string {
if (!output.isTTY) return text;
const ui = getUiRuntimeOptions();
if (ui.v2Enabled) {
if (tone === "muted") {
return `${ui.theme.colors.dim}${paintUiText(ui, text, "muted")}${ui.theme.colors.reset}`;
}
const mapped = tone === "accent" ? "primary" : tone;
return paintUiText(ui, text, mapped);
}
const legacyCode =
tone === "accent"
? ANSI.green
: tone === "success"
? ANSI.green
: tone === "warning"
? ANSI.yellow
: tone === "danger"
? ANSI.red
: ANSI.dim;
return `${legacyCode}${text}${ANSI.reset}`;
}
function collapseWhitespace(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function formatReasonLabel(reason: string | undefined): string | undefined {
if (!reason) return undefined;
const normalized = collapseWhitespace(reason.replace(/_/g, " "));
return normalized.length > 0 ? normalized : undefined;
}
function formatRelativeDateShort(
timestamp: number | null | undefined,
): string | null {
if (!timestamp) return null;
const days = Math.floor((Date.now() - timestamp) / 86_400_000);
if (days <= 0) return "today";
if (days === 1) return "yesterday";
if (days < 7) return `${days}d ago`;
return new Date(timestamp).toLocaleDateString();
}
function formatDateTimeLong(timestamp: number | null | undefined): string {
if (!timestamp) return "unknown";
return new Date(timestamp).toLocaleString();
}
function formatFileSize(sizeBytes: number | null | undefined): string {
if (
typeof sizeBytes !== "number" ||
!Number.isFinite(sizeBytes) ||
sizeBytes < 0
) {
return "unknown";
}
if (sizeBytes < 1024) {
return `${sizeBytes} B`;
}
if (sizeBytes < 1024 * 1024) {
return `${(sizeBytes / 1024).toFixed(1)} KB`;
}
return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`;
}
function extractErrorMessageFromPayload(payload: unknown): string | undefined {
if (!payload || typeof payload !== "object") return undefined;
const record = payload as Record<string, unknown>;
const directMessage =
typeof record.message === "string"
? collapseWhitespace(record.message)
: "";
const directCode =
typeof record.code === "string" ? collapseWhitespace(record.code) : "";
if (directMessage) {
if (
directCode &&
!directMessage.toLowerCase().includes(directCode.toLowerCase())
) {
return `${directMessage} [${directCode}]`;
}
return directMessage;
}
const nested = record.error;
if (nested && typeof nested === "object") {
return extractErrorMessageFromPayload(nested);
}
return undefined;
}
function parseStructuredErrorMessage(raw: string): string | undefined {
const trimmed = raw.trim();
if (!trimmed) return undefined;
const candidates = new Set<string>([trimmed]);
const firstBrace = trimmed.indexOf("{");
const lastBrace = trimmed.lastIndexOf("}");
if (firstBrace >= 0 && lastBrace > firstBrace) {
candidates.add(trimmed.slice(firstBrace, lastBrace + 1));
}
for (const candidate of candidates) {
try {
const parsed = JSON.parse(candidate) as unknown;
const message = extractErrorMessageFromPayload(parsed);
if (message) return message;
} catch {
// ignore non-JSON candidates
}
}
return undefined;
}
function normalizeFailureDetail(
message: string | undefined,
reason: string | undefined,
): string {
const reasonLabel = formatReasonLabel(reason);
const raw = message?.trim() || reasonLabel || "refresh failed";
const structured = parseStructuredErrorMessage(raw);
const normalized = collapseWhitespace(structured ?? raw);
const bounded =
normalized.length > 260 ? `${normalized.slice(0, 257)}...` : normalized;
return bounded.length > 0 ? bounded : "refresh failed";
}
function joinStyledSegments(parts: string[]): string {
if (parts.length === 0) return "";
const separator = stylePromptText(" | ", "muted");
return parts.join(separator);
}
function formatResultSummary(
segments: ReadonlyArray<{ text: string; tone: PromptTone }>,
): string {
const rendered = segments.map((segment) =>
stylePromptText(segment.text, segment.tone),
);
return `${stylePromptText("Result:", "accent")} ${joinStyledSegments(rendered)}`;
}
function styleQuotaSummary(summary: string): string {
const normalized = collapseWhitespace(summary);
if (!normalized) return stylePromptText(summary, "muted");
const segments = normalized
.split("|")
.map((segment) => segment.trim())
.filter(Boolean);
if (segments.length === 0) return stylePromptText(normalized, "muted");
const rendered = segments.map((segment) => {
if (/rate-limited/i.test(segment)) {
return stylePromptText(segment, "danger");
}
const match = segment.match(/^([0-9a-zA-Z]+)\s+(\d{1,3})%$/);
if (!match) {
return stylePromptText(segment, "muted");
}
const windowLabel = match[1] ?? "";
const leftPercent = Number.parseInt(match[2] ?? "", 10);
if (!Number.isFinite(leftPercent)) {
return stylePromptText(segment, "muted");
}
const tone = quotaToneFromLeftPercent(leftPercent);
return `${stylePromptText(windowLabel, "muted")} ${stylePromptText(`${leftPercent}%`, tone)}`;
});
return joinStyledSegments(rendered);
}
function styleAccountDetailText(
detail: string,
fallbackTone: PromptTone = "muted",
): string {
const compact = collapseWhitespace(detail);
if (!compact) return stylePromptText("", fallbackTone);
const quotaMatch = compact.match(/^(.*?)\(([^()]*\d{1,3}%[^()]*)\)(.*)$/);
if (quotaMatch) {
const prefix = (quotaMatch[1] ?? "").trim();
const quota = (quotaMatch[2] ?? "").trim();
const suffix = (quotaMatch[3] ?? "").trim();
const prefixTone: PromptTone = /failed|error/i.test(prefix)
? "danger"
: /ok|working|succeeded|valid/i.test(prefix)
? "success"
: fallbackTone;
const suffixTone: PromptTone =
/re-login|stale|warning|retry|fallback/i.test(suffix)
? "warning"
: /failed|error/i.test(suffix)
? "danger"
: "muted";
const chunks: string[] = [];
if (prefix) chunks.push(stylePromptText(prefix, prefixTone));
chunks.push(`(${styleQuotaSummary(quota)})`);
if (suffix) chunks.push(stylePromptText(suffix, suffixTone));
return chunks.join(" ");
}
if (/rate-limited/i.test(compact)) return stylePromptText(compact, "danger");
if (/re-login|stale|warning|fallback/i.test(compact))
return stylePromptText(compact, "warning");
if (/failed|error/i.test(compact)) return stylePromptText(compact, "danger");
if (/ok|working|succeeded|valid/i.test(compact))
return stylePromptText(compact, "success");
return stylePromptText(compact, fallbackTone);
}
function riskTone(
level: ForecastAccountResult["riskLevel"],
): "success" | "warning" | "danger" {
if (level === "low") return "success";
if (level === "medium") return "warning";
return "danger";
}
function availabilityTone(
availability: ForecastAccountResult["availability"],
): "success" | "warning" | "danger" {
if (availability === "ready") return "success";
if (availability === "delayed") return "warning";
return "danger";
}
function formatQuotaSnapshotForDashboard(
snapshot: Awaited<ReturnType<typeof fetchCodexQuotaSnapshot>>,
settings: DashboardDisplaySettings,
): string {
if (!settings.showQuotaDetails) return "live session OK";
return `live session OK (${formatCompactQuotaSnapshot(snapshot)})`;
}
function isAbortError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const maybe = error as Error & { code?: string };
return maybe.name === "AbortError" || maybe.code === "ABORT_ERR";
}
function isUserCancelledOAuth(result: TokenResult): boolean {
if (result.type !== "failed") return false;
const message = (result.message ?? "").toLowerCase();
return message.includes("cancelled");
}
function printUsage(): void {
console.log(
[
"Codex Multi-Auth CLI",
"",
"Usage:",
" codex auth login",
" codex auth list",
" codex auth status",
" codex auth switch <index>",
" codex auth check",
" codex auth features",
" codex auth verify-flagged [--dry-run] [--json] [--no-restore]",
" codex auth forecast [--live] [--json] [--model <model>]",
" codex auth report [--live] [--json] [--model <model>] [--out <path>]",
" codex auth fix [--dry-run] [--json] [--live] [--model <model>]",
" codex auth doctor [--json] [--fix] [--dry-run]",
"",
"Notes:",
" - Uses ~/.codex/multi-auth/openai-codex-accounts.json",
" - Syncs active account into Codex CLI auth state",
].join("\n"),
);
}
interface ImplementedFeature {
id: number;
name: string;
}
const IMPLEMENTED_FEATURES: ImplementedFeature[] = [
{ id: 1, name: "Multi-account OAuth login dashboard" },
{ id: 2, name: "Account add/update dedupe by token/id/email" },
{ id: 3, name: "Set current account command" },
{ id: 4, name: "Per-family active index handling" },
{ id: 5, name: "Quick health check command" },
{ id: 6, name: "Full refresh check command" },
{ id: 7, name: "Flagged account verification command" },
{ id: 8, name: "Flagged account restore flow" },
{ id: 9, name: "Best account forecast engine" },
{ id: 10, name: "Forecast live quota probing" },
{ id: 11, name: "Auto-fix command (safe mode)" },
{ id: 12, name: "Doctor diagnostics command" },
{ id: 13, name: "JSON outputs for machine automation" },
{ id: 14, name: "Report generation command" },
{ id: 15, name: "Storage v3 normalization and migration" },
{ id: 16, name: "Storage backup and recovery journal" },
{ id: 17, name: "Project-scoped and global storage paths" },
{ id: 18, name: "Quota cache storage" },
{ id: 19, name: "Live account sync watcher" },
{ id: 20, name: "Session affinity store" },
{ id: 21, name: "Refresh queue dedupe (in-process)" },
{ id: 22, name: "Refresh lease dedupe (cross-process)" },
{ id: 23, name: "Token rotation mapping in refresh queue" },
{ id: 24, name: "Refresh guardian (proactive refresh)" },
{ id: 25, name: "Preemptive quota scheduler" },
{ id: 26, name: "Entitlement cache for unsupported models" },
{ id: 27, name: "Capability policy scoring store" },
{ id: 28, name: "Failure policy evaluation module" },
{ id: 29, name: "Streaming failover pipeline" },
{ id: 30, name: "Rate-limit backoff and cooldown handling" },
{ id: 31, name: "Host request transformer bridge" },
{ id: 32, name: "Prompt template sync with cache" },
{ id: 33, name: "Codex CLI active-account state sync" },
{ id: 34, name: "TUI quick-switch hotkeys (1-9)" },
{ id: 35, name: "TUI search and help toggles" },
{ id: 36, name: "TUI account detail hotkeys (S/R/E/D)" },
{ id: 37, name: "TUI settings hub (list/summary/behavior/theme)" },
{ id: 38, name: "Dashboard display customization" },
{ id: 39, name: "Unified color/theme runtime (v2 UI)" },
{ id: 40, name: "OAuth browser-first flow with manual callback fallback" },
];
function runFeaturesReport(): number {
console.log(`Implemented features (${IMPLEMENTED_FEATURES.length})`);
console.log("");
for (const feature of IMPLEMENTED_FEATURES) {
console.log(`${feature.id}. ${feature.name}`);
}
return 0;
}
function resolveActiveIndex(
storage: AccountStorageV3,
family: ModelFamily = "codex",
): number {
const total = storage.accounts.length;
if (total === 0) return 0;
const rawCandidate =
storage.activeIndexByFamily?.[family] ?? storage.activeIndex;
const raw = Number.isFinite(rawCandidate) ? rawCandidate : 0;
return Math.max(0, Math.min(raw, total - 1));
}
function getRateLimitResetTimeForFamily(
account: { rateLimitResetTimes?: Record<string, number | undefined> },
now: number,
family: ModelFamily,
): number | null {
const times = account.rateLimitResetTimes;
if (!times) return null;
let minReset: number | null = null;
const prefix = `${family}:`;
for (const [key, value] of Object.entries(times)) {
if (typeof value !== "number") continue;
if (value <= now) continue;
if (key !== family && !key.startsWith(prefix)) continue;
if (minReset === null || value < minReset) {
minReset = value;
}
}
return minReset;
}
function formatRateLimitEntry(
account: { rateLimitResetTimes?: Record<string, number | undefined> },
now: number,
family: ModelFamily = "codex",
): string | null {
const resetAt = getRateLimitResetTimeForFamily(account, now, family);
if (typeof resetAt !== "number") return null;
const remaining = resetAt - now;
if (remaining <= 0) return null;
return `resets in ${formatWaitTime(remaining)}`;
}
function normalizeQuotaEmail(email: string | undefined): string | null {
const normalized = sanitizeEmail(email);
return normalized && normalized.length > 0 ? normalized : null;
}
function quotaCacheEntryToSnapshot(entry: QuotaCacheEntry): CodexQuotaSnapshot {
return {
status: entry.status,
planType: entry.planType,
model: entry.model,
primary: {
usedPercent: entry.primary.usedPercent,
windowMinutes: entry.primary.windowMinutes,
resetAtMs: entry.primary.resetAtMs,
},
secondary: {
usedPercent: entry.secondary.usedPercent,
windowMinutes: entry.secondary.windowMinutes,
resetAtMs: entry.secondary.resetAtMs,
},
};
}
function formatCompactQuotaWindowLabel(
windowMinutes: number | undefined,
): string {
if (!windowMinutes || !Number.isFinite(windowMinutes) || windowMinutes <= 0) {
return "quota";
}
if (windowMinutes % 1440 === 0) return `${windowMinutes / 1440}d`;
if (windowMinutes % 60 === 0) return `${windowMinutes / 60}h`;
return `${windowMinutes}m`;
}
function formatCompactQuotaPart(
windowMinutes: number | undefined,
usedPercent: number | undefined,
): string | null {
const label = formatCompactQuotaWindowLabel(windowMinutes);
if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent)) {
return null;
}
const left = quotaLeftPercentFromUsed(usedPercent);
return `${label} ${left}%`;
}
function quotaLeftPercentFromUsed(
usedPercent: number | undefined,
): number | undefined {
if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent)) {
return undefined;
}
return Math.max(0, Math.min(100, Math.round(100 - usedPercent)));
}
function formatCompactQuotaSnapshot(snapshot: CodexQuotaSnapshot): string {
const parts = [
formatCompactQuotaPart(
snapshot.primary.windowMinutes,
snapshot.primary.usedPercent,
),
formatCompactQuotaPart(
snapshot.secondary.windowMinutes,
snapshot.secondary.usedPercent,
),
].filter(
(value): value is string => typeof value === "string" && value.length > 0,
);
if (snapshot.status === 429) {
parts.push("rate-limited");
}
if (parts.length > 0) {
return parts.join(" | ");
}
return formatQuotaSnapshotLine(snapshot);
}
function formatAccountQuotaSummary(entry: QuotaCacheEntry): string {
const parts = [
formatCompactQuotaPart(
entry.primary.windowMinutes,
entry.primary.usedPercent,
),
formatCompactQuotaPart(
entry.secondary.windowMinutes,
entry.secondary.usedPercent,
),
].filter(
(value): value is string => typeof value === "string" && value.length > 0,
);
if (entry.status === 429) {
parts.push("rate-limited");
}
if (parts.length > 0) {
return parts.join(" | ");
}
return formatQuotaSnapshotLine(quotaCacheEntryToSnapshot(entry));
}
function getQuotaCacheEntryForAccount(
cache: QuotaCacheData,
account: Pick<AccountMetadataV3, "accountId" | "email">,
): QuotaCacheEntry | null {
if (account.accountId && cache.byAccountId[account.accountId]) {
return cache.byAccountId[account.accountId] ?? null;
}
const email = normalizeQuotaEmail(account.email);
if (email && cache.byEmail[email]) {
return cache.byEmail[email] ?? null;
}
return null;
}
function updateQuotaCacheForAccount(
cache: QuotaCacheData,
account: Pick<AccountMetadataV3, "accountId" | "email">,
snapshot: CodexQuotaSnapshot,
): boolean {
const nextEntry: QuotaCacheEntry = {
updatedAt: Date.now(),
status: snapshot.status,
model: snapshot.model,
planType: snapshot.planType,
primary: {
usedPercent: snapshot.primary.usedPercent,
windowMinutes: snapshot.primary.windowMinutes,
resetAtMs: snapshot.primary.resetAtMs,
},
secondary: {
usedPercent: snapshot.secondary.usedPercent,
windowMinutes: snapshot.secondary.windowMinutes,
resetAtMs: snapshot.secondary.resetAtMs,
},
};
let changed = false;
if (account.accountId) {
cache.byAccountId[account.accountId] = nextEntry;
changed = true;
}
const email = normalizeQuotaEmail(account.email);
if (email) {
cache.byEmail[email] = nextEntry;
changed = true;
}
return changed;
}
const DEFAULT_MENU_QUOTA_REFRESH_TTL_MS = 5 * 60_000;
const MENU_QUOTA_REFRESH_MODEL = "gpt-5-codex";
interface MenuQuotaProbeTarget {
account: AccountMetadataV3;
accountId: string;
accessToken: string;
}
function resolveMenuQuotaProbeInput(
account: AccountMetadataV3,
cache: QuotaCacheData,
maxAgeMs: number,
now: number,
): { accountId: string; accessToken: string } | null {
if (account.enabled === false) return null;
if (!hasUsableAccessToken(account, now)) return null;
const existing = getQuotaCacheEntryForAccount(cache, account);
if (
existing &&
typeof existing.updatedAt === "number" &&
Number.isFinite(existing.updatedAt) &&
now - existing.updatedAt < maxAgeMs
) {
return null;
}
const accessToken = account.accessToken;
const accountId = accessToken
? (account.accountId ?? extractAccountId(accessToken))
: account.accountId;
if (!accountId || !accessToken) return null;
return { accountId, accessToken };
}
function collectMenuQuotaRefreshTargets(
storage: AccountStorageV3,
cache: QuotaCacheData,
maxAgeMs: number,
now = Date.now(),
): MenuQuotaProbeTarget[] {
const targets: MenuQuotaProbeTarget[] = [];
for (const account of storage.accounts) {
const probeInput = resolveMenuQuotaProbeInput(
account,
cache,
maxAgeMs,
now,
);
if (!probeInput) continue;
targets.push({
account,
accountId: probeInput.accountId,
accessToken: probeInput.accessToken,
});
}
return targets;
}
function countMenuQuotaRefreshTargets(
storage: AccountStorageV3,
cache: QuotaCacheData,
maxAgeMs: number,
now = Date.now(),
): number {
let count = 0;
for (const account of storage.accounts) {
if (resolveMenuQuotaProbeInput(account, cache, maxAgeMs, now)) {
count += 1;
}
}
return count;
}
async function refreshQuotaCacheForMenu(
storage: AccountStorageV3,
cache: QuotaCacheData,
maxAgeMs: number,
onProgress?: (current: number, total: number) => void,
): Promise<QuotaCacheData> {
if (storage.accounts.length === 0) {
return cache;
}
const now = Date.now();
const targets = collectMenuQuotaRefreshTargets(storage, cache, maxAgeMs, now);
const total = targets.length;
let processed = 0;
onProgress?.(processed, total);
let changed = false;
for (const target of targets) {
processed += 1;
onProgress?.(processed, total);
try {
const snapshot = await fetchCodexQuotaSnapshot({
accountId: target.accountId,
accessToken: target.accessToken,
model: MENU_QUOTA_REFRESH_MODEL,
});
changed =
updateQuotaCacheForAccount(cache, target.account, snapshot) || changed;
} catch {
// Keep existing cached values if probing fails.
}
}
if (changed) {
await saveQuotaCache(cache);
}
return cache;
}
const ACCESS_TOKEN_FRESH_WINDOW_MS = 5 * 60 * 1000;
function hasUsableAccessToken(
account: Pick<AccountMetadataV3, "accessToken" | "expiresAt">,
now: number,
): boolean {
if (!account.accessToken) return false;
if (
typeof account.expiresAt !== "number" ||
!Number.isFinite(account.expiresAt)
)
return false;
return account.expiresAt - now > ACCESS_TOKEN_FRESH_WINDOW_MS;
}
function hasLikelyInvalidRefreshToken(
refreshToken: string | undefined,
): boolean {
if (!refreshToken) return true;
const trimmed = refreshToken.trim();
if (trimmed.length < 20) return true;
return trimmed.startsWith("token-");
}
function mapAccountStatus(
account: AccountMetadataV3,
index: number,
activeIndex: number,
now: number,
): ExistingAccountInfo["status"] {
if (account.enabled === false) return "disabled";
if (
typeof account.coolingDownUntil === "number" &&
account.coolingDownUntil > now
) {
return "cooldown";
}
const rateLimit = formatRateLimitEntry(account, now, "codex");
if (rateLimit) return "rate-limited";
if (index === activeIndex) return "active";
return "ok";
}
function parseLeftPercentFromQuotaSummary(
summary: string | undefined,
windowLabel: "5h" | "7d",
): number {
if (!summary) return -1;
const match = summary.match(
new RegExp(`(?:^|\\|)\\s*${windowLabel}\\s+(\\d{1,3})%`, "i"),
);
const value = Number.parseInt(match?.[1] ?? "", 10);
if (!Number.isFinite(value)) return -1;
return Math.max(0, Math.min(100, value));
}
function readQuotaLeftPercent(
account: ExistingAccountInfo,
windowLabel: "5h" | "7d",
): number {
const direct =
windowLabel === "5h"
? account.quota5hLeftPercent
: account.quota7dLeftPercent;
if (typeof direct === "number" && Number.isFinite(direct)) {
return Math.max(0, Math.min(100, Math.round(direct)));
}
return parseLeftPercentFromQuotaSummary(account.quotaSummary, windowLabel);
}
function accountStatusSortBucket(
status: ExistingAccountInfo["status"],
): number {
switch (status) {
case "active":
case "ok":
return 0;
case "unknown":
return 1;
case "cooldown":
case "rate-limited":
return 2;
case "disabled":
case "error":
case "flagged":
return 3;
default:
return 1;
}
}
function compareReadyFirstAccounts(
left: ExistingAccountInfo,
right: ExistingAccountInfo,
): number {
const left5h = readQuotaLeftPercent(left, "5h");
const right5h = readQuotaLeftPercent(right, "5h");
if (left5h !== right5h) return right5h - left5h;
const left7d = readQuotaLeftPercent(left, "7d");
const right7d = readQuotaLeftPercent(right, "7d");
if (left7d !== right7d) return right7d - left7d;
const bucketDelta =
accountStatusSortBucket(left.status) -
accountStatusSortBucket(right.status);
if (bucketDelta !== 0) return bucketDelta;
const leftLastUsed = left.lastUsed ?? 0;
const rightLastUsed = right.lastUsed ?? 0;
if (leftLastUsed !== rightLastUsed) return rightLastUsed - leftLastUsed;
const leftSource = left.sourceIndex ?? left.index;
const rightSource = right.sourceIndex ?? right.index;
return leftSource - rightSource;
}
function applyAccountMenuOrdering(
accounts: ExistingAccountInfo[],
displaySettings: DashboardDisplaySettings,
): ExistingAccountInfo[] {
const sortEnabled =
displaySettings.menuSortEnabled ??
DEFAULT_DASHBOARD_DISPLAY_SETTINGS.menuSortEnabled ??
true;
const sortMode: DashboardAccountSortMode =
displaySettings.menuSortMode ??
DEFAULT_DASHBOARD_DISPLAY_SETTINGS.menuSortMode ??
"ready-first";
if (!sortEnabled || sortMode !== "ready-first") {
return [...accounts];
}
const sorted = [...accounts].sort(compareReadyFirstAccounts);
const pinCurrent =
displaySettings.menuSortPinCurrent ??
DEFAULT_DASHBOARD_DISPLAY_SETTINGS.menuSortPinCurrent ??
false;
if (pinCurrent) {
const currentIndex = sorted.findIndex(
(account) => account.isCurrentAccount,
);
if (currentIndex > 0) {
const current = sorted.splice(currentIndex, 1)[0];
const first = sorted[0];
if (current && first && compareReadyFirstAccounts(current, first) <= 0) {
sorted.unshift(current);
} else if (current) {
sorted.splice(currentIndex, 0, current);
}
}
}
return sorted;
}
function toExistingAccountInfo(
storage: AccountStorageV3,
quotaCache: QuotaCacheData | null,
displaySettings: DashboardDisplaySettings,
): ExistingAccountInfo[] {
const now = Date.now();
const activeIndex = resolveActiveIndex(storage, "codex");
const layoutMode = resolveMenuLayoutMode(displaySettings);
const baseAccounts = storage.accounts.map((account, index) => {
const entry = quotaCache
? getQuotaCacheEntryForAccount(quotaCache, account)
: null;
return {
index,
sourceIndex: index,
accountId: account.accountId,
accountLabel: account.accountLabel,
email: account.email,
addedAt: account.addedAt,
lastUsed: account.lastUsed,
status: mapAccountStatus(account, index, activeIndex, now),
quotaSummary:
(displaySettings.menuShowQuotaSummary ?? true) && entry
? formatAccountQuotaSummary(entry)
: undefined,
quota5hLeftPercent: quotaLeftPercentFromUsed(entry?.primary.usedPercent),
quota5hResetAtMs: entry?.primary.resetAtMs,
quota7dLeftPercent: quotaLeftPercentFromUsed(
entry?.secondary.usedPercent,
),
quota7dResetAtMs: entry?.secondary.resetAtMs,
quotaRateLimited: entry?.status === 429,
isCurrentAccount: index === activeIndex,
enabled: account.enabled !== false,
showStatusBadge: displaySettings.menuShowStatusBadge ?? true,
showCurrentBadge: displaySettings.menuShowCurrentBadge ?? true,
showLastUsed: displaySettings.menuShowLastUsed ?? true,
showQuotaCooldown: displaySettings.menuShowQuotaCooldown ?? true,
showHintsForUnselectedRows: layoutMode === "expanded-rows",
highlightCurrentRow: displaySettings.menuHighlightCurrentRow ?? true,
focusStyle: displaySettings.menuFocusStyle ?? "row-invert",
statuslineFields: displaySettings.menuStatuslineFields ?? [
"last-used",
"limits",
"status",
],
};
});
const orderedAccounts = applyAccountMenuOrdering(
baseAccounts,
displaySettings,
);
const quickSwitchUsesVisibleRows =
displaySettings.menuSortQuickSwitchVisibleRow ?? true;
return orderedAccounts.map((account, displayIndex) => ({
...account,
index: displayIndex,
quickSwitchNumber: quickSwitchUsesVisibleRows
? displayIndex + 1
: (account.sourceIndex ?? displayIndex) + 1,
}));
}
function resolveAccountSelection(
tokens: TokenSuccess,
): TokenSuccessWithAccount {
const override = (process.env.CODEX_AUTH_ACCOUNT_ID ?? "").trim();
if (override) {
return {
...tokens,
accountIdOverride: override,
accountIdSource: "manual",
};
}
const candidates = getAccountIdCandidates(tokens.access, tokens.idToken);
if (candidates.length === 0) {
return tokens;
}
if (candidates.length === 1) {
const [candidate] = candidates;
if (candidate) {
return {
...tokens,
accountIdOverride: candidate.accountId,
accountIdSource: candidate.source,
accountLabel: candidate.label,
};
}
}
const best = selectBestAccountCandidate(candidates);
if (!best) {
return tokens;
}
return {