@bitkyc08/opencodex 2.7.28 → 2.7.29-preview.20260721

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,282 @@
1
+ import { loadConfig } from "../config";
2
+ import {
3
+ apiError,
4
+ apiJson,
5
+ classifyAccount,
6
+ fetchCodexRows,
7
+ fetchProviderQuotaReport,
8
+ fetchRows,
9
+ proxyUnreachable,
10
+ resolveBaseUrl,
11
+ type AccountDeps, type AccountStdin, type FamilyRows,
12
+ type ProviderQuotaDto, type ProviderQuotaReportDto,
13
+ } from "./account-api";
14
+
15
+ const MAIN_ID = "__main__";
16
+ const AUTO_NOTE = "auto (no pin — lowest-usage account is selected per request)";
17
+ const EXTENDED_USAGE = `Usage:
18
+ ocx account refresh <provider> [--json]
19
+ ocx account auto-switch <provider> <on|off|status|threshold <0-100>> [--json]
20
+ ocx account remove <provider> <id|main> --yes [--json]
21
+ ocx account add-key <provider> [--label <label>] [--json]`;
22
+ const PIPE_GUIDANCE = `Pipe the API key on stdin, for example:
23
+ ocx account add-key <provider> <<< "$MY_KEY"
24
+ security find-generic-password -w <item> | ocx account add-key <provider>`;
25
+
26
+ function flag(args: string[], value: string): boolean {
27
+ const index = args.indexOf(value);
28
+ if (index < 0) return false;
29
+ args.splice(index, 1);
30
+ return true;
31
+ }
32
+
33
+ function flagValue(args: string[], value: string): { found: boolean; value?: string } {
34
+ const index = args.indexOf(value);
35
+ if (index < 0) return { found: false };
36
+ if (index + 1 >= args.length) return { found: true };
37
+ const result = args[index + 1];
38
+ args.splice(index, 2);
39
+ return { found: true, value: result };
40
+ }
41
+
42
+ function usage(message?: string): number {
43
+ if (message) console.error(message);
44
+ console.error(EXTENDED_USAGE);
45
+ return 1;
46
+ }
47
+
48
+ function configAndType(deps: AccountDeps, name: string) {
49
+ return classifyAccount(deps.loadConfigImpl?.() ?? loadConfig(), name);
50
+ }
51
+
52
+ function familyFailure(result: FamilyRows, fallback: string): number | null {
53
+ if (result.networkDown) return proxyUnreachable();
54
+ if (result.errorJson) return apiError(result.errorJson, fallback);
55
+ return null;
56
+ }
57
+
58
+ function errorText(json: Record<string, unknown> | undefined, fallback: string): string {
59
+ return typeof json?.error === "string" ? json.error : fallback;
60
+ }
61
+
62
+ function resetIso(value: number | undefined): string | null {
63
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
64
+ const date = new Date(value < 10_000_000_000 ? value * 1000 : value);
65
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
66
+ }
67
+
68
+ function refreshLine(row: FamilyRows["rows"][number]): string {
69
+ const parts = [row.id === MAIN_ID ? "main" : row.id, row.email, row.plan];
70
+ const quota = row.quota;
71
+ if (!quota || (quota.weeklyPercent === undefined && quota.monthlyPercent === undefined)) {
72
+ parts.push("quota: unknown");
73
+ } else {
74
+ if (quota.weeklyPercent !== undefined) parts.push(`weekly ${quota.weeklyPercent}%`);
75
+ const weeklyReset = resetIso(quota.weeklyResetAt);
76
+ if (weeklyReset) parts.push(`resets ${weeklyReset}`);
77
+ if (quota.monthlyPercent !== undefined) parts.push(`monthly ${quota.monthlyPercent}%`);
78
+ const monthlyReset = resetIso(quota.monthlyResetAt);
79
+ if (monthlyReset) parts.push(`resets ${monthlyReset}`);
80
+ }
81
+ if (row.needsReauth) parts.push("needs-reauth");
82
+ return parts.filter(Boolean).join(" ");
83
+ }
84
+
85
+ function quotaParts(quota: ProviderQuotaDto): string[] {
86
+ const parts: string[] = [];
87
+ const add = (label: string, percent: number | undefined, resetAt?: number) => {
88
+ if (percent === undefined) return;
89
+ parts.push(`${label} ${percent}%`);
90
+ const reset = resetIso(resetAt);
91
+ if (reset) parts.push(`resets ${reset}`);
92
+ };
93
+ add("5h", quota.fiveHourPercent, quota.fiveHourResetAt);
94
+ add("weekly", quota.weeklyPercent, quota.weeklyResetAt);
95
+ add("monthly", quota.monthlyPercent, quota.monthlyResetAt);
96
+ for (const window of quota.customWindows ?? []) add(window.label, window.percent, window.resetAt);
97
+ return parts;
98
+ }
99
+
100
+ function providerQuotaLine(name: string, report: ProviderQuotaReportDto): string {
101
+ return [name, ...quotaParts(report.quota)].join(" ");
102
+ }
103
+
104
+ export async function readStdinLine(deps: AccountDeps): Promise<string> {
105
+ const input: AccountStdin = deps.stdinImpl ?? process.stdin;
106
+ const timeoutMs = deps.stdinTimeoutMs ?? 15_000;
107
+ return await new Promise<string>((resolve, reject) => {
108
+ let buffer = "";
109
+ let settled = false;
110
+ const cleanup = () => {
111
+ clearTimeout(timer);
112
+ input.removeListener("data", onData);
113
+ input.removeListener("end", onEnd);
114
+ input.removeListener("error", onError);
115
+ };
116
+ const finish = (fn: () => void) => {
117
+ if (settled) return;
118
+ settled = true;
119
+ cleanup();
120
+ fn();
121
+ };
122
+ const onData = (chunk: unknown) => {
123
+ buffer += Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
124
+ const newline = buffer.search(/[\r\n]/);
125
+ if (newline >= 0) finish(() => resolve(buffer.slice(0, newline).trim()));
126
+ };
127
+ const onEnd = () => finish(() => resolve(buffer.trim()));
128
+ const onError = (error: Error) => finish(() => reject(error));
129
+ const timer = setTimeout(() => finish(() => reject(new Error("timed out waiting for API key on stdin"))), timeoutMs);
130
+ input.on("data", onData);
131
+ input.on("end", onEnd);
132
+ input.on("error", onError);
133
+ });
134
+ }
135
+
136
+ export async function cmdRefresh(args: string[], deps: AccountDeps): Promise<number> {
137
+ const wantsJson = flag(args, "--json");
138
+ const name = args.shift();
139
+ if (!name || args.length) return usage();
140
+ const classified = configAndType(deps, name);
141
+ if ("error" in classified) return usage(`Error: ${classified.error}`);
142
+ const baseUrl = await resolveBaseUrl(deps);
143
+ if (!baseUrl) return proxyUnreachable();
144
+ if (classified.type !== "codex") {
145
+ const result = await fetchProviderQuotaReport(deps, baseUrl, name);
146
+ if (result.status === 0) return proxyUnreachable();
147
+ if (result.status !== 200) return apiError(result.errorJson ?? {}, `failed to refresh ${name}`);
148
+ if (wantsJson) console.log(JSON.stringify({ provider: name, report: result.report }, null, 2));
149
+ else console.log(result.report ? providerQuotaLine(name, result.report) : `no quota report available for ${name}`);
150
+ return 0;
151
+ }
152
+ const result = await fetchCodexRows(deps, baseUrl, true);
153
+ const failed = familyFailure(result, `failed to refresh ${name}`);
154
+ if (failed !== null) return failed;
155
+ if (wantsJson) console.log(JSON.stringify({ accounts: result.rows }, null, 2));
156
+ else for (const row of result.rows) console.log(refreshLine(row));
157
+ return 0;
158
+ }
159
+
160
+ export async function cmdAutoSwitch(args: string[], deps: AccountDeps): Promise<number> {
161
+ const wantsJson = flag(args, "--json");
162
+ const name = args.shift();
163
+ const action = args.shift();
164
+ if (!name || !action) return usage();
165
+ const classified = configAndType(deps, name);
166
+ if ("error" in classified || classified.type !== "codex") {
167
+ return usage("Error: auto-switch only applies to the openai Codex account pool");
168
+ }
169
+ let threshold: number | undefined;
170
+ if (action === "on" && args.length === 0) threshold = 80;
171
+ else if (action === "off" && args.length === 0) threshold = 0;
172
+ else if (action === "threshold" && args.length === 1 && /^\d+$/.test(args[0]!)) threshold = Number(args[0]);
173
+ else if (action !== "status" || args.length !== 0) return usage();
174
+ if (threshold !== undefined && (!Number.isInteger(threshold) || threshold < 0 || threshold > 100)) {
175
+ return usage("Error: threshold must be an integer 0-100");
176
+ }
177
+ const baseUrl = await resolveBaseUrl(deps);
178
+ if (!baseUrl) return proxyUnreachable();
179
+ if (action === "status") {
180
+ const response = await apiJson(deps, baseUrl, "GET", "/api/codex-auth/active");
181
+ if (response.status === 0) return proxyUnreachable();
182
+ if (response.status !== 200 || typeof response.json.autoSwitchThreshold !== "number") {
183
+ return apiError(response.json, "failed to read auto-switch status");
184
+ }
185
+ threshold = response.json.autoSwitchThreshold;
186
+ } else {
187
+ const response = await apiJson(deps, baseUrl, "PUT", "/api/codex-auth/auto-switch", { threshold });
188
+ if (response.status === 0) return proxyUnreachable();
189
+ if (response.status !== 200) return apiError(response.json, "failed to update auto-switch");
190
+ }
191
+ const enabled = threshold! > 0;
192
+ if (wantsJson) console.log(JSON.stringify({ provider: name, autoSwitchThreshold: threshold, enabled }, null, 2));
193
+ else console.log(enabled ? `auto-switch: on (threshold ${threshold}%)` : "auto-switch: off");
194
+ return 0;
195
+ }
196
+
197
+ function deletePath(type: "codex" | "oauth" | "api-key", name: string, id: string): string {
198
+ if (type === "codex") return `/api/codex-auth/accounts?id=${encodeURIComponent(id)}`;
199
+ if (type === "oauth") return `/api/oauth/accounts?provider=${encodeURIComponent(name)}&id=${encodeURIComponent(id)}`;
200
+ return `/api/providers/keys?name=${encodeURIComponent(name)}&id=${encodeURIComponent(id)}`;
201
+ }
202
+
203
+ export async function cmdRemove(args: string[], deps: AccountDeps): Promise<number> {
204
+ const wantsJson = flag(args, "--json");
205
+ const fail = (message: string): number => {
206
+ if (wantsJson) console.error(JSON.stringify({ error: message }));
207
+ else console.error(`Error: ${message}`);
208
+ return 1;
209
+ };
210
+ const confirmed = flag(args, "--yes");
211
+ const name = args.shift();
212
+ const requestedId = args.shift();
213
+ if (!name || !requestedId || args.length) return wantsJson ? fail("provider and account id are required") : usage();
214
+ if (!confirmed) {
215
+ const message = `Confirmation required. Re-run: ocx account remove ${name} ${requestedId} --yes`;
216
+ return wantsJson ? fail(message) : usage(message);
217
+ }
218
+ const classified = configAndType(deps, name);
219
+ if ("error" in classified) return wantsJson ? fail(classified.error) : usage(`Error: ${classified.error}`);
220
+ const id = classified.type === "codex" && requestedId === "main" ? MAIN_ID : requestedId;
221
+ if (classified.type === "codex" && id === MAIN_ID) return wantsJson
222
+ ? fail("the main Codex App login cannot be removed")
223
+ : usage("Error: the main Codex App login cannot be removed");
224
+ const baseUrl = await resolveBaseUrl(deps);
225
+ if (!baseUrl) return fail("Proxy not reachable. Start it with 'ocx start' or 'ocx ensure'.");
226
+ const before = await fetchRows(deps, baseUrl, name, classified.type);
227
+ if (before.networkDown) return fail("Proxy not reachable. Start it with 'ocx start' or 'ocx ensure'.");
228
+ if (before.errorJson) return fail(errorText(before.errorJson, `failed to verify ${name} before removal`));
229
+ if (!before.rows.some(row => row.id === id)) return wantsJson
230
+ ? fail(`account or key "${requestedId}" was not found`)
231
+ : usage(`Error: account or key "${requestedId}" was not found`);
232
+ const response = await apiJson(deps, baseUrl, "DELETE", deletePath(classified.type, name, id));
233
+ if (response.status === 0) return fail("Proxy not reachable. Start it with 'ocx start' or 'ocx ensure'.");
234
+ if (response.status !== 200) return fail(errorText(response.json, `failed to remove ${requestedId}`));
235
+ const after = await fetchRows(deps, baseUrl, name, classified.type);
236
+ if (after.networkDown || after.errorJson) {
237
+ const detail = after.networkDown ? "proxy not reachable" : typeof after.errorJson?.error === "string" ? after.errorJson.error : "unknown error";
238
+ return fail(`post-delete verification failed; delete may have succeeded: ${detail}`);
239
+ }
240
+ const removedActive = before.activeId === id;
241
+ const result = { ok: true, provider: name, id, removedActive, promotedActiveId: after.activeId };
242
+ if (wantsJson) console.log(JSON.stringify(result, null, 2));
243
+ else if (classified.type === "codex" && removedActive && after.activeId === null) console.log(`openai: ${AUTO_NOTE}`);
244
+ else if (classified.type === "oauth") console.log(after.rows.length ? `${name}: active account is now ${after.activeId}` : `${name}: no accounts remaining`);
245
+ else if (classified.type === "api-key") console.log(after.rows.length ? `${name}: active key is now ${after.activeId}` : `${name}: no keys remaining`);
246
+ else console.log(`${name}: removed account ${requestedId}`);
247
+ return 0;
248
+ }
249
+
250
+ export async function cmdAddKey(args: string[], deps: AccountDeps): Promise<number> {
251
+ const wantsJson = flag(args, "--json");
252
+ const labelArg = flagValue(args, "--label");
253
+ const name = args.shift();
254
+ if (!name || args.length || (labelArg.found && labelArg.value === undefined)) return usage();
255
+ const classified = configAndType(deps, name);
256
+ if ("error" in classified || classified.type !== "api-key") return usage("Error: add-key only applies to API-key providers");
257
+ const input: AccountStdin = deps.stdinImpl ?? process.stdin;
258
+ if (input.isTTY) return usage(PIPE_GUIDANCE);
259
+ let key: string;
260
+ try {
261
+ key = await readStdinLine(deps);
262
+ } catch (error) {
263
+ return usage(`Error: ${error instanceof Error ? error.message : String(error)}\n${PIPE_GUIDANCE}`);
264
+ }
265
+ if (!key) return usage(`Error: API key input was empty\n${PIPE_GUIDANCE}`);
266
+ const label = labelArg.value?.trim();
267
+ const baseUrl = await resolveBaseUrl(deps);
268
+ if (!baseUrl) return proxyUnreachable();
269
+ const response = await apiJson(deps, baseUrl, "POST", "/api/providers/keys", { name, key, ...(label ? { label } : {}) });
270
+ if (response.status === 0) return proxyUnreachable();
271
+ if (response.status !== 201) return apiError(response.json, `failed to add a key for ${name}`);
272
+ const id = typeof response.json.id === "string" ? response.json.id : null;
273
+ // Redact the key inside the label BEFORE serialization — a key containing
274
+ // JSON-escaped characters (" or \) would otherwise survive the whole-output
275
+ // pass in escaped form (audit finding, Carver WP3-C).
276
+ const safeLabel = label ? label.replaceAll(key, "[redacted]") : undefined;
277
+ const result = { ok: true, id, ...(safeLabel ? { label: safeLabel } : {}) };
278
+ const output = wantsJson ? JSON.stringify(result, null, 2)
279
+ : `${name}: added API key ${id ?? ""}${safeLabel ? ` (${safeLabel})` : ""}`.trim();
280
+ console.log(output.replaceAll(key, "[redacted]"));
281
+ return 0;
282
+ }
@@ -0,0 +1,265 @@
1
+ /** `ocx account` — list and switch provider credentials (issue #180). */
2
+ import { loadConfig } from "../config";
3
+ import { providerCodexAccountMode } from "../providers/registry";
4
+ import type { OcxConfig } from "../types";
5
+ import { cmdAddKey, cmdAutoSwitch, cmdRefresh, cmdRemove } from "./account-extended";
6
+ import { apiError, apiJson, classifyAccount, fetchRows, proxyUnreachable, resolveBaseUrl, type AccountDeps, type AccountRow, type AccountType, type ApiResult }
7
+ from "./account-api";
8
+
9
+ export { classifyAccount } from "./account-api";
10
+ export type { AccountDeps, AccountRow, AccountType, ClassifyResult } from "./account-api";
11
+ type TargetProvenance = "live-oauth-list" | "config" | "codex";
12
+
13
+ const MAIN_ALIAS = "main";
14
+ const MAIN_CODEX_ID = "__main__";
15
+ /** Replacement-style single-slot OAuth (no stable identity; not HTTP-derivable). */
16
+ const REPLACEMENT_STYLE_OAUTH = new Set(["kiro"]);
17
+
18
+ const ACCOUNT_USAGE = `Usage:
19
+ ocx account list [provider] [--json] [--all]
20
+ ocx account current <provider> [--json]
21
+ ocx account use <provider> <account-or-key-id|main> [--json]
22
+ ocx account refresh <provider> [--json]
23
+ ocx account auto-switch <provider> <on|off|status|threshold <0-100>> [--json]
24
+ ocx account remove <provider> <account-or-key-id|main> --yes [--json]
25
+ ocx account add-key <provider> [--label <label>] [--json]
26
+
27
+ List and switch provider accounts and API-key pools (masked output only).
28
+ 'main' selects the Codex App login for the openai account pool.`;
29
+
30
+ function consumeFlag(args: string[], flag: string): boolean {
31
+ const idx = args.indexOf(flag);
32
+ if (idx === -1) return false;
33
+ args.splice(idx, 1);
34
+ return true;
35
+ }
36
+
37
+ /** Returns an error message for leftover args, or null when clean. */
38
+ function leftoverArgsError(args: string[]): string | null {
39
+ if (args.length === 0) return null;
40
+ const unknown = args.filter(a => a.startsWith("-"));
41
+ return unknown.length > 0
42
+ ? `Unknown flag(s): ${unknown.join(", ")}`
43
+ : `Unexpected argument(s): ${args.join(", ")}`;
44
+ }
45
+
46
+ function candidateNames(config: OcxConfig): string {
47
+ const names = new Set<string>(["openai"]);
48
+ for (const n of Object.keys(config.providers ?? {})) names.add(n);
49
+ return [...names].join(", ");
50
+ }
51
+
52
+ function displayId(id: string): string {
53
+ return id === MAIN_CODEX_ID ? MAIN_ALIAS : id;
54
+ }
55
+
56
+ function statusText(row: AccountRow): string {
57
+ const parts: string[] = [];
58
+ if (row.active) parts.push(row.type === "codex" ? "next session" : "active");
59
+ if (row.needsReauth) parts.push("needs-reauth");
60
+ return parts.join(" ");
61
+ }
62
+
63
+ export function formatAccountTable(rows: AccountRow[]): string {
64
+ const header = ["PROVIDER", "TYPE", "ID", "PLAN/LABEL", "STATUS"];
65
+ const data = rows.map(r => {
66
+ const keyLabel = r.masked && r.label !== r.masked ? `${r.masked} (${r.label})` : r.masked;
67
+ return [r.provider, r.type, displayId(r.id), r.type === "api-key" ? keyLabel ?? "-" : r.label ?? "-", statusText(r)];
68
+ });
69
+ const widths = header.map((h, i) => Math.max(h.length, ...data.map(d => d[i]!.length)));
70
+ const line = (cols: string[]) => cols.map((c, i) => c.padEnd(widths[i]!)).join(" ").trimEnd();
71
+ return [line(header), ...data.map(line)].join("\n");
72
+ }
73
+
74
+ async function cmdList(rest: string[], deps: AccountDeps): Promise<number> {
75
+ const wantsJson = consumeFlag(rest, "--json");
76
+ const showAll = consumeFlag(rest, "--all");
77
+ const name = rest.shift();
78
+ const leftover = leftoverArgsError(rest);
79
+ if (leftover) {
80
+ console.error(leftover);
81
+ console.error(ACCOUNT_USAGE);
82
+ return 1;
83
+ }
84
+ const config = deps.loadConfigImpl?.() ?? loadConfig();
85
+ const baseUrl = await resolveBaseUrl(deps);
86
+ if (!baseUrl) return proxyUnreachable();
87
+
88
+ const targets: { name: string; type: AccountType; provenance: TargetProvenance }[] = [];
89
+ if (name) {
90
+ const c = classifyAccount(config, name);
91
+ if ("error" in c) {
92
+ console.error(`Error: ${c.error}. Known candidates: ${candidateNames(config)}`);
93
+ return 1;
94
+ }
95
+ targets.push({ name, type: c.type, provenance: "config" });
96
+ } else {
97
+ const seen = new Set<string>();
98
+ const push = (n: string, provenance: TargetProvenance) => {
99
+ if (seen.has(n)) return;
100
+ seen.add(n);
101
+ const c = classifyAccount(config, n);
102
+ if ("error" in c) return; // fan-out silently skips no-credential providers
103
+ targets.push({ name: n, type: c.type, provenance });
104
+ };
105
+ push("openai", "codex");
106
+ const providersRes = await apiJson(deps, baseUrl, "GET", "/api/oauth/providers");
107
+ if (providersRes.status === 0) return proxyUnreachable();
108
+ if (providersRes.status !== 200) return apiError(providersRes.json, "failed to list OAuth providers");
109
+ if (Array.isArray(providersRes.json.providers)) {
110
+ for (const p of providersRes.json.providers) {
111
+ if (typeof p === "string") push(p, "live-oauth-list");
112
+ }
113
+ }
114
+ for (const n of Object.keys(config.providers ?? {})) push(n, "config");
115
+ }
116
+
117
+ const rows: AccountRow[] = [];
118
+ const notes: string[] = [];
119
+ for (const t of targets) {
120
+ const r = await fetchRows(deps, baseUrl, t.name, t.type);
121
+ if (r.networkDown) return proxyUnreachable();
122
+ if (r.errorJson) {
123
+ if (name) return apiError(r.errorJson, `failed to list ${t.name}`);
124
+ const errorText = typeof r.errorJson.error === "string" ? r.errorJson.error : "";
125
+ const skipUnknownKey = t.type === "api-key"
126
+ && r.status === 404
127
+ && errorText.includes("unknown provider");
128
+ const skipConfigOAuth = t.type === "oauth"
129
+ && t.provenance === "config"
130
+ && r.status === 400
131
+ && errorText.includes("unknown oauth provider");
132
+ if (skipUnknownKey || skipConfigOAuth) continue;
133
+ return apiError(r.errorJson, `failed to list ${t.name}`);
134
+ }
135
+ if (r.rows.length === 0) {
136
+ if (showAll) notes.push(`${t.name}: no stored accounts or keys`);
137
+ continue;
138
+ }
139
+ rows.push(...r.rows);
140
+ if (t.type === "codex") {
141
+ if (r.activeId === null) notes.push("openai: auto (no pin — lowest-usage account is selected per request)");
142
+ if (providerCodexAccountMode("openai", config.providers?.openai) === "direct") {
143
+ notes.push("openai is in direct mode — the selection takes effect when pool mode is enabled");
144
+ }
145
+ }
146
+ if (t.type === "oauth" && REPLACEMENT_STYLE_OAUTH.has(t.name)) {
147
+ notes.push(`${t.name}: single login slot — re-login replaces the current account`);
148
+ }
149
+ }
150
+
151
+ if (wantsJson) {
152
+ console.log(JSON.stringify({ accounts: rows, notes }, null, 2));
153
+ return 0;
154
+ }
155
+ if (rows.length > 0) console.log(formatAccountTable(rows));
156
+ for (const n of notes) console.log(n);
157
+ if (rows.length === 0 && notes.length === 0) console.log("No stored accounts or keys.");
158
+ return 0;
159
+ }
160
+
161
+ async function cmdCurrent(rest: string[], deps: AccountDeps): Promise<number> {
162
+ const wantsJson = consumeFlag(rest, "--json");
163
+ const name = rest.shift();
164
+ const leftover = leftoverArgsError(rest);
165
+ if (!name || leftover) {
166
+ if (leftover) console.error(leftover);
167
+ console.error(ACCOUNT_USAGE);
168
+ return 1;
169
+ }
170
+ const config = deps.loadConfigImpl?.() ?? loadConfig();
171
+ const c = classifyAccount(config, name);
172
+ if ("error" in c) {
173
+ console.error(`Error: ${c.error}. Known candidates: ${candidateNames(config)}`);
174
+ return 1;
175
+ }
176
+ const baseUrl = await resolveBaseUrl(deps);
177
+ if (!baseUrl) return proxyUnreachable();
178
+ const r = await fetchRows(deps, baseUrl, name, c.type);
179
+ if (r.networkDown) return proxyUnreachable();
180
+ if (r.errorJson) return apiError(r.errorJson, `failed to read ${name}`);
181
+
182
+ const activeRow = r.rows.find(row => row.active) ?? null;
183
+ if (wantsJson) {
184
+ console.log(JSON.stringify({
185
+ provider: name,
186
+ type: c.type,
187
+ activeId: r.activeId,
188
+ autoSwitchThreshold: r.autoSwitchThreshold,
189
+ account: activeRow,
190
+ }, null, 2));
191
+ return 0;
192
+ }
193
+ if (activeRow) {
194
+ console.log(formatAccountTable([activeRow]));
195
+ } else if (c.type === "codex" && r.activeId === null) {
196
+ console.log("openai: auto (no pin — lowest-usage account is selected per request)");
197
+ } else {
198
+ console.log(`${name}: no active account or key`);
199
+ }
200
+ return 0;
201
+ }
202
+
203
+ async function cmdUse(rest: string[], deps: AccountDeps): Promise<number> {
204
+ const wantsJson = consumeFlag(rest, "--json");
205
+ const name = rest.shift();
206
+ const id = rest.shift();
207
+ const leftover = leftoverArgsError(rest);
208
+ if (!name || !id || leftover) {
209
+ if (leftover) console.error(leftover);
210
+ console.error(ACCOUNT_USAGE);
211
+ return 1;
212
+ }
213
+ const config = deps.loadConfigImpl?.() ?? loadConfig();
214
+ const c = classifyAccount(config, name);
215
+ if ("error" in c) {
216
+ console.error(`Error: ${c.error}. Known candidates: ${candidateNames(config)}`);
217
+ return 1;
218
+ }
219
+ const baseUrl = await resolveBaseUrl(deps);
220
+ if (!baseUrl) return proxyUnreachable();
221
+
222
+ let res: ApiResult;
223
+ let activeId: string;
224
+ if (c.type === "codex") {
225
+ activeId = id === MAIN_ALIAS ? MAIN_CODEX_ID : id;
226
+ res = await apiJson(deps, baseUrl, "PUT", "/api/codex-auth/active", { accountId: activeId });
227
+ } else if (c.type === "oauth") {
228
+ activeId = id;
229
+ res = await apiJson(deps, baseUrl, "PUT", "/api/oauth/accounts/active", { provider: name, accountId: id });
230
+ } else {
231
+ activeId = id;
232
+ res = await apiJson(deps, baseUrl, "PUT", "/api/providers/keys/active", { name, id });
233
+ }
234
+ if (res.status === 0) return proxyUnreachable();
235
+ if (res.status !== 200) return apiError(res.json, `failed to switch ${name}`);
236
+
237
+ if (wantsJson) console.log(JSON.stringify({ ok: true, provider: name, type: c.type, activeId }, null, 2));
238
+ else console.log(`${name}: active ${c.type === "api-key" ? "key" : "account"} is now ${displayId(activeId)}`);
239
+ if (c.type === "codex") {
240
+ console.error("Applies to new Codex sessions; running threads keep their current account.");
241
+ const active = await apiJson(deps, baseUrl, "GET", "/api/codex-auth/active");
242
+ if (active.status === 200 && typeof active.json.autoSwitchThreshold === "number" && active.json.autoSwitchThreshold > 0) {
243
+ console.error(`Note: auto-switch (threshold ${active.json.autoSwitchThreshold}%) may override this pin.`);
244
+ }
245
+ }
246
+ return 0;
247
+ }
248
+
249
+ export async function cmdAccount(args: string[], deps: AccountDeps = {}): Promise<number> {
250
+ const [sub, ...rest] = args;
251
+ try {
252
+ if (sub === "list") return await cmdList(rest, deps);
253
+ if (sub === "current") return await cmdCurrent(rest, deps);
254
+ if (sub === "use") return await cmdUse(rest, deps);
255
+ if (sub === "refresh") return await cmdRefresh(rest, deps);
256
+ if (sub === "auto-switch") return await cmdAutoSwitch(rest, deps);
257
+ if (sub === "remove") return await cmdRemove(rest, deps);
258
+ if (sub === "add-key") return await cmdAddKey(rest, deps);
259
+ console.error(ACCOUNT_USAGE);
260
+ return 1;
261
+ } catch (err) {
262
+ console.error(`account: ${err instanceof Error ? err.message : String(err)}`);
263
+ return 1;
264
+ }
265
+ }
package/src/cli/claude.ts CHANGED
@@ -135,7 +135,9 @@ export async function fetchClaudeContextWindows(config: OcxConfig, port: number,
135
135
  async function ensureProxyForClaude(): Promise<number | null> {
136
136
  const live = await findLiveProxy();
137
137
  if (live) return live.port;
138
- const child = spawn(process.execPath, [process.argv[1], "start"], {
138
+ const cfgPort = loadConfig().port;
139
+ const pinPort = typeof cfgPort === "number" && cfgPort > 0 ? cfgPort : 10100;
140
+ const child = spawn(process.execPath, [process.argv[1], "start", "--port", String(pinPort)], {
139
141
  detached: true,
140
142
  stdio: "ignore",
141
143
  windowsHide: true,
package/src/cli/help.ts CHANGED
@@ -79,6 +79,20 @@ const helpEntries: Record<string, HelpEntry> = {
79
79
  "Run `ocx provider --help` for full usage and examples.",
80
80
  ],
81
81
  },
82
+ account: {
83
+ usage: "ocx account <list|current|use|refresh|auto-switch|remove|add-key> ...",
84
+ summary: "List and switch provider accounts and API-key pools (GUI parity).",
85
+ details: [
86
+ "list [provider] Codex account pool, OAuth accounts and API keys (identifiers shown masked as the API returns them).",
87
+ "current <provider> Show the active account or key.",
88
+ "use <provider> <id> Switch the active credential; 'main' selects the Codex App login.",
89
+ "refresh <provider> Force-refresh Codex or provider quota reports.",
90
+ "auto-switch <provider> <on|off|status|threshold N> Control the Codex pool threshold.",
91
+ "remove <provider> <id> --yes Remove a stored account or key after an existence check.",
92
+ "add-key <provider> [--label <label>] Add a key read only from piped stdin.",
93
+ "Codex pool switches apply to new sessions; running threads keep their account.",
94
+ ],
95
+ },
82
96
  models: {
83
97
  usage: "ocx models [--provider <name>] [--json]",
84
98
  summary: "List available models from configured providers.",
@@ -144,6 +158,7 @@ Usage:
144
158
  ocx restart Stop and restart the proxy
145
159
  ocx health [--json] Check proxy health (exit 0=healthy, 1=not)
146
160
  ocx provider <sub> Manage providers (list|add|remove|show|set-default)
161
+ ocx account <sub> Accounts/keys (list|current|use|refresh|auto-switch|remove|add-key)
147
162
  ocx models [--json] List available models from configured providers
148
163
  ocx claude [args...] Launch Claude Code wired to the proxy (model discovery on)
149
164
  ocx help [command] Show help