-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcli.ts
More file actions
436 lines (410 loc) · 12.1 KB
/
cli.ts
File metadata and controls
436 lines (410 loc) · 12.1 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
import { stdin as input, stdout as output } from "node:process";
import { createInterface } from "node:readline/promises";
import { DESTRUCTIVE_ACTION_COPY } from "./destructive-actions.js";
import type { AccountIdSource } from "./types.js";
import {
type AccountStatus,
isTTY,
showAccountDetails,
showAuthMenu,
} from "./ui/auth-menu.js";
import { UI_COPY } from "./ui/copy.js";
/**
* Detect if running in host Desktop/TUI mode where readline prompts don't work.
* In TUI mode, stdin/stdout are controlled by the TUI renderer, so readline breaks.
* Exported for testing purposes.
*/
export function isNonInteractiveMode(): boolean {
if (process.env.FORCE_INTERACTIVE_MODE === "1") return false;
if (!input.isTTY || !output.isTTY) return true;
if (process.env.CODEX_TUI === "1") return true;
if (process.env.CODEX_DESKTOP === "1") return true;
if ((process.env.TERM_PROGRAM ?? "").trim().toLowerCase() === "codex")
return true;
if (process.env.ELECTRON_RUN_AS_NODE === "1") return true;
return false;
}
export function isInteractiveLoginMenuAvailable(): boolean {
return !isNonInteractiveMode() && isTTY();
}
export async function promptAddAnotherAccount(
currentCount: number,
): Promise<boolean> {
if (isNonInteractiveMode()) {
return false;
}
const rl = createInterface({ input, output });
try {
console.log(`\n${UI_COPY.fallback.addAnotherTip}\n`);
const answer = await rl.question(
UI_COPY.fallback.addAnotherQuestion(currentCount),
);
const normalized = answer.trim().toLowerCase();
return normalized === "y" || normalized === "yes";
} finally {
rl.close();
}
}
export type LoginMode =
| "add"
| "forecast"
| "fix"
| "settings"
| "fresh"
| "reset"
| "manage"
| "check"
| "deep-check"
| "verify-flagged"
| "restore-backup"
| "cancel";
export interface ExistingAccountInfo {
accountId?: string;
accountLabel?: string;
email?: string;
index: number;
sourceIndex?: number;
quickSwitchNumber?: number;
addedAt?: number;
lastUsed?: number;
status?: AccountStatus;
quotaSummary?: string;
quota5hLeftPercent?: number;
quota5hResetAtMs?: number;
quota7dLeftPercent?: number;
quota7dResetAtMs?: number;
quotaRateLimited?: boolean;
isCurrentAccount?: boolean;
enabled?: boolean;
showStatusBadge?: boolean;
showCurrentBadge?: boolean;
showLastUsed?: boolean;
showQuotaCooldown?: boolean;
showHintsForUnselectedRows?: boolean;
highlightCurrentRow?: boolean;
focusStyle?: "row-invert" | "chip";
statuslineFields?: string[];
}
export interface LoginMenuOptions {
flaggedCount?: number;
statusMessage?: string | (() => string | undefined);
}
export interface LoginMenuResult {
mode: LoginMode;
deleteAccountIndex?: number;
refreshAccountIndex?: number;
toggleAccountIndex?: number;
switchAccountIndex?: number;
deleteAll?: boolean;
}
function formatAccountLabel(
account: ExistingAccountInfo,
index: number,
): string {
const num = index + 1;
const label = account.accountLabel?.trim();
if (account.email?.trim()) {
return label
? `${num}. ${label} (${account.email})`
: `${num}. ${account.email}`;
}
if (label) {
return `${num}. ${label}`;
}
if (account.accountId?.trim()) {
const suffix =
account.accountId.length > 6
? account.accountId.slice(-6)
: account.accountId;
return `${num}. ${suffix}`;
}
return `${num}. Account`;
}
function resolveAccountSourceIndex(account: ExistingAccountInfo): number {
const sourceIndex =
typeof account.sourceIndex === "number" &&
Number.isFinite(account.sourceIndex)
? Math.max(0, Math.floor(account.sourceIndex))
: undefined;
if (typeof sourceIndex === "number") return sourceIndex;
if (typeof account.index === "number" && Number.isFinite(account.index)) {
return Math.max(0, Math.floor(account.index));
}
return -1;
}
function warnUnresolvableAccountSelection(account: ExistingAccountInfo): void {
const label =
account.email?.trim() ||
account.accountId?.trim() ||
`index ${account.index + 1}`;
console.log(`Unable to resolve saved account for action: ${label}`);
}
async function promptDeleteAllTypedConfirm(): Promise<boolean> {
const rl = createInterface({ input, output });
try {
const answer = await rl.question(
DESTRUCTIVE_ACTION_COPY.deleteSavedAccounts.typedConfirm,
);
return answer.trim() === "DELETE";
} finally {
rl.close();
}
}
async function promptResetTypedConfirm(): Promise<boolean> {
const rl = createInterface({ input, output });
try {
const answer = await rl.question(
DESTRUCTIVE_ACTION_COPY.resetLocalState.typedConfirm,
);
return answer.trim() === "RESET";
} finally {
rl.close();
}
}
async function promptLoginModeFallback(
existingAccounts: ExistingAccountInfo[],
): Promise<LoginMenuResult> {
const rl = createInterface({ input, output });
try {
if (existingAccounts.length > 0) {
console.log(`\n${existingAccounts.length} account(s) saved:`);
for (const account of existingAccounts) {
console.log(` ${formatAccountLabel(account, account.index)}`);
}
console.log("");
}
while (true) {
const answer = await rl.question(UI_COPY.fallback.selectModePrompt);
const normalized = answer.trim().toLowerCase();
if (normalized === "a" || normalized === "add") return { mode: "add" };
if (
normalized === "b" ||
normalized === "p" ||
normalized === "forecast"
) {
return { mode: "forecast" };
}
if (normalized === "x" || normalized === "fix") return { mode: "fix" };
if (
normalized === "s" ||
normalized === "settings" ||
normalized === "configure"
) {
return { mode: "settings" };
}
if (
normalized === "f" ||
normalized === "fresh" ||
normalized === "clear"
) {
if (!(await promptDeleteAllTypedConfirm())) {
console.log("\nDelete saved accounts cancelled.\n");
continue;
}
return { mode: "fresh", deleteAll: true };
}
if (normalized === "r" || normalized === "reset") {
if (!(await promptResetTypedConfirm())) {
console.log("\nReset local state cancelled.\n");
continue;
}
return { mode: "reset" };
}
if (normalized === "c" || normalized === "check")
return { mode: "check" };
if (normalized === "d" || normalized === "deep") {
return { mode: "deep-check" };
}
if (
normalized === "g" ||
normalized === "flagged" ||
normalized === "verify-flagged" ||
normalized === "verify"
) {
return { mode: "verify-flagged" };
}
if (
normalized === "u" ||
normalized === "backup" ||
normalized === "restore" ||
normalized === "restore-backup"
) {
return { mode: "restore-backup" };
}
if (normalized === "q" || normalized === "quit")
return { mode: "cancel" };
console.log(UI_COPY.fallback.invalidModePrompt);
}
} finally {
rl.close();
}
}
export async function promptLoginMode(
existingAccounts: ExistingAccountInfo[],
options: LoginMenuOptions = {},
): Promise<LoginMenuResult> {
if (isNonInteractiveMode()) {
return { mode: "add" };
}
if (!isInteractiveLoginMenuAvailable()) {
return promptLoginModeFallback(existingAccounts);
}
while (true) {
const action = await showAuthMenu(existingAccounts, {
flaggedCount: options.flaggedCount ?? 0,
statusMessage: options.statusMessage,
});
switch (action.type) {
case "add":
return { mode: "add" };
case "forecast":
return { mode: "forecast" };
case "fix":
return { mode: "fix" };
case "settings":
return { mode: "settings" };
case "fresh":
if (!(await promptDeleteAllTypedConfirm())) {
console.log("\nDelete saved accounts cancelled.\n");
continue;
}
return { mode: "fresh", deleteAll: true };
case "reset-all":
if (!(await promptResetTypedConfirm())) {
console.log("\nReset local state cancelled.\n");
continue;
}
return { mode: "reset" };
case "check":
return { mode: "check" };
case "deep-check":
return { mode: "deep-check" };
case "verify-flagged":
return { mode: "verify-flagged" };
case "restore-backup":
return { mode: "restore-backup" };
case "select-account": {
const accountAction = await showAccountDetails(action.account);
if (accountAction === "delete") {
const index = resolveAccountSourceIndex(action.account);
if (index >= 0) return { mode: "manage", deleteAccountIndex: index };
warnUnresolvableAccountSelection(action.account);
continue;
}
if (accountAction === "set-current") {
const index = resolveAccountSourceIndex(action.account);
if (index >= 0) return { mode: "manage", switchAccountIndex: index };
warnUnresolvableAccountSelection(action.account);
continue;
}
if (accountAction === "refresh") {
const index = resolveAccountSourceIndex(action.account);
if (index >= 0) return { mode: "manage", refreshAccountIndex: index };
warnUnresolvableAccountSelection(action.account);
continue;
}
if (accountAction === "toggle") {
const index = resolveAccountSourceIndex(action.account);
if (index >= 0) return { mode: "manage", toggleAccountIndex: index };
warnUnresolvableAccountSelection(action.account);
continue;
}
continue;
}
case "set-current-account": {
const index = resolveAccountSourceIndex(action.account);
if (index >= 0) return { mode: "manage", switchAccountIndex: index };
warnUnresolvableAccountSelection(action.account);
continue;
}
case "refresh-account": {
const index = resolveAccountSourceIndex(action.account);
if (index >= 0) return { mode: "manage", refreshAccountIndex: index };
warnUnresolvableAccountSelection(action.account);
continue;
}
case "toggle-account": {
const index = resolveAccountSourceIndex(action.account);
if (index >= 0) return { mode: "manage", toggleAccountIndex: index };
warnUnresolvableAccountSelection(action.account);
continue;
}
case "delete-account": {
const index = resolveAccountSourceIndex(action.account);
if (index >= 0) return { mode: "manage", deleteAccountIndex: index };
warnUnresolvableAccountSelection(action.account);
continue;
}
case "search":
// Search is handled in showAuthMenu; keep the main loop active.
continue;
case "delete-all":
if (!(await promptDeleteAllTypedConfirm())) {
console.log("\nDelete saved accounts cancelled.\n");
continue;
}
return { mode: "fresh", deleteAll: true };
case "cancel":
return { mode: "cancel" };
}
}
}
export interface AccountSelectionCandidate {
accountId: string;
label: string;
source?: AccountIdSource;
isDefault?: boolean;
}
export interface AccountSelectionOptions {
defaultIndex?: number;
title?: string;
}
export async function promptAccountSelection(
candidates: AccountSelectionCandidate[],
options: AccountSelectionOptions = {},
): Promise<AccountSelectionCandidate | null> {
if (candidates.length === 0) return null;
const defaultIndex =
typeof options.defaultIndex === "number" &&
Number.isFinite(options.defaultIndex)
? Math.max(0, Math.min(options.defaultIndex, candidates.length - 1))
: 0;
if (isNonInteractiveMode()) {
return candidates[defaultIndex] ?? candidates[0] ?? null;
}
const rl = createInterface({ input, output });
try {
console.log(
`\n${options.title ?? "Multiple workspaces detected for this account:"}`,
);
candidates.forEach((candidate, index) => {
const isDefault = candidate.isDefault ? " (default)" : "";
console.log(` ${index + 1}. ${candidate.label}${isDefault}`);
});
console.log("");
while (true) {
const answer = await rl.question(
`Select workspace [${defaultIndex + 1}]: `,
);
const normalized = answer.trim().toLowerCase();
if (!normalized) {
return candidates[defaultIndex] ?? candidates[0] ?? null;
}
if (normalized === "q" || normalized === "quit") {
return candidates[defaultIndex] ?? candidates[0] ?? null;
}
const parsed = Number.parseInt(normalized, 10);
if (Number.isFinite(parsed)) {
const idx = parsed - 1;
if (idx >= 0 && idx < candidates.length) {
return candidates[idx] ?? null;
}
}
console.log(`Please enter a number between 1 and ${candidates.length}.`);
}
} finally {
rl.close();
}
}
export { isTTY };
export type { AccountStatus };