Skip to content
This repository was archived by the owner on Feb 23, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
209 changes: 162 additions & 47 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ import { getHealthTracker, getTokenTracker } from "./lib/rotation.js";
import { RateLimitTracker } from "./lib/rate-limit.js";
import { codexStatus, type CodexRateLimitSnapshot } from "./lib/codex-status.js";
import { renderObsidianDashboard } from "./lib/codex-status-ui.js";
import { renderQuotaReport } from "./lib/ui/codex-quota-report.js";
import { runAuthMenuOnce } from "./lib/ui/auth-menu-runner.js";
import type { AuthMenuAccount } from "./lib/ui/auth-menu.js";
import {
ProactiveRefreshQueue,
createRefreshScheduler,
Expand Down Expand Up @@ -649,6 +652,103 @@ export const OpenAIAuthPlugin: Plugin = async ({ client }: PluginInput) => {
enabled: account.enabled,
}));

const buildAuthMenuAccounts = (
accounts: ReturnType<AccountManager["getAccountsSnapshot"]>,
activeIndex: number,
): AuthMenuAccount[] =>
accounts.map((account) => ({
index: account.index,
accountId: account.accountId,
email: account.email,
plan: account.plan,
enabled: account.enabled,
lastUsed: account.lastUsed,
rateLimitResetTimes: account.rateLimitResetTimes,
coolingDownUntil: account.coolingDownUntil,
cooldownReason: account.cooldownReason,
isActive: account.index === activeIndex,
}));

const runInteractiveAuthMenu = async (options: { allowExit: boolean }): Promise<"add" | "exit"> => {
while (true) {
const accountManager = await AccountManager.loadFromDisk();
const accounts = accountManager.getAccountsSnapshot();
const activeIndex = accountManager.getActiveIndexForFamily(DEFAULT_MODEL_FAMILY);
const menuAccounts = buildAuthMenuAccounts(accounts, activeIndex);
const now = Date.now();

const result = await runAuthMenuOnce({
accounts: menuAccounts,
now,
input: process.stdin,
output: process.stdout,
handlers: {
onCheckQuotas: async () => {
await Promise.all(
accounts.map(async (acc, index) => {
if (acc.enabled === false) return;
const live = accountManager.getAccountByIndex(index);
if (!live) return;
const auth = accountManager.toAuthDetails(live);
if (auth.access && auth.expires > Date.now()) {
await codexStatus.fetchFromBackend(live, auth.access);
}
}),
);
const snapshots = await codexStatus.getAllSnapshots();
const report = renderQuotaReport(menuAccounts, snapshots, Date.now());
process.stdout.write(report.join("\n") + "\n");
},
onConfigureModels: async () => {
process.stdout.write(
"Edit your opencode.jsonc (or opencode.json) to configure models.\n",
);
},
onDeleteAll: async () => {
await updateStorageWithLock(() => createEmptyStorage());
},
onToggleAccount: async (account) => {
await updateStorageWithLock((current) =>
toggleAccountFromStorage(current, account),
);
},
onRefreshAccount: async (account) => {
const live = accountManager.getAccountByIndex(account.index);
if (!live || live.enabled === false) return;
const refreshed = await accountManager.refreshAccountWithFallback(live);
if (refreshed.type === "success") {
if (refreshed.headers) {
await codexStatus.updateFromHeaders(
live,
Object.fromEntries(refreshed.headers.entries()),
);
}
const refreshedAuth = {
type: "oauth" as const,
access: refreshed.access,
refresh: refreshed.refresh,
expires: refreshed.expires,
};
accountManager.updateFromAuth(live, refreshedAuth);
await accountManager.saveToDisk();
}
},
onDeleteAccount: async (account) => {
await updateStorageWithLock((current) =>
removeAccountFromStorage(current, account),
);
},
},
});

if (result === "add") return "add";
if (result === "exit") {
if (options.allowExit) return "exit";
continue;
}
}
};

const storedAccountsForMethods = await loadAccounts();
const hasStoredAccounts = (storedAccountsForMethods?.accounts.length ?? 0) > 0;

Expand All @@ -661,35 +761,39 @@ export const OpenAIAuthPlugin: Plugin = async ({ client }: PluginInput) => {
if (inputs) {
let existingStorage = await loadAccounts();
if (existingStorage?.accounts?.length) {
while (true) {
const existingLabels = buildExistingAccountLabels(existingStorage);
const mode = await promptLoginMode(existingLabels);

if (mode === "manage") {
const action = await promptManageAccounts(existingLabels);
if (!action) {
if (process.stdin.isTTY && process.stdout.isTTY) {
await runInteractiveAuthMenu({ allowExit: false });
} else {
while (true) {
const existingLabels = buildExistingAccountLabels(existingStorage);
const mode = await promptLoginMode(existingLabels);

if (mode === "manage") {
const action = await promptManageAccounts(existingLabels);
if (!action) {
continue;
}

if (action.action === "toggle") {
existingStorage = await updateStorageWithLock((current) =>
toggleAccountFromStorage(current, action.target),
);
} else {
existingStorage = await updateStorageWithLock((current) =>
removeAccountFromStorage(current, action.target),
);
}

if (existingStorage.accounts.length === 0) {
replaceExisting = true;
break;
}
continue;
}

if (action.action === "toggle") {
existingStorage = await updateStorageWithLock((current) =>
toggleAccountFromStorage(current, action.target),
);
} else {
existingStorage = await updateStorageWithLock((current) =>
removeAccountFromStorage(current, action.target),
);
}

if (existingStorage.accounts.length === 0) {
replaceExisting = true;
break;
}
continue;
replaceExisting = mode === "fresh";
break;
}

replaceExisting = mode === "fresh";
break;
}
}
}
Expand Down Expand Up @@ -888,35 +992,46 @@ async fetch(input: Request | string | URL, init?: RequestInit): Promise<Response
}

cfg.command = cfg.command || {};
cfg.command["codex-status"] = {
template: "Run the codex-status tool and output the result EXACTLY as returned by the tool, without any additional text or commentary.",
description: "List all configured OpenAI Codex accounts and their current rate limits.",
};
cfg.command["codex-switch-accounts"] = {
template: "Run the codex-switch-accounts tool with index $ARGUMENTS and output the result EXACTLY as returned by the tool, without any additional text or commentary.",
description: "Switch active OpenAI account by index (1-based).",
};
cfg.command["codex-toggle-account"] = {
template: "Run the codex-toggle-account tool with index $ARGUMENTS and output the result EXACTLY as returned by the tool, without any additional text or commentary.",
description: "Enable or disable an OpenAI account by index (1-based).",
};
cfg.command["codex-remove-account"] = {
template: "Run the codex-remove-account tool with index $ARGUMENTS and confirm: true.",
description: "Remove an OpenAI account by index (1-based).",
delete cfg.command["codex-status"];
delete cfg.command["codex-switch-accounts"];
delete cfg.command["codex-toggle-account"];
delete cfg.command["codex-remove-account"];
cfg.command["codex-auth"] = {
template:
"Run the codex-auth tool and output the result EXACTLY as returned by the tool, without any additional text or commentary.",
description: "Open the interactive Codex auth menu.",
};

cfg.experimental = cfg.experimental || {};
cfg.experimental.primary_tools = cfg.experimental.primary_tools || [];
for (const t of ["codex-status", "codex-switch-accounts", "codex-toggle-account", "codex-remove-account"]) {
if (!cfg.experimental.primary_tools.includes(t)) {
cfg.experimental.primary_tools.push(t);
}
cfg.experimental.primary_tools = cfg.experimental.primary_tools.filter(
(toolName) =>
!new Set(["codex-status", "codex-switch-accounts", "codex-toggle-account", "codex-remove-account"]).has(
toolName,
),
);
if (!cfg.experimental.primary_tools.includes("codex-auth")) {
cfg.experimental.primary_tools.push("codex-auth");
}
},
tool: {
"codex-status": tool({
description: "List all configured OpenAI Codex accounts and their current rate limits.",
args: {},
"codex-auth": tool({
description: "Open the interactive Codex auth menu.",
args: {},
async execute() {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
return "Interactive auth menu requires a TTY. Run `opencode auth login`.";
}
const result = await runInteractiveAuthMenu({ allowExit: true });
if (result === "add") {
return "Add accounts with `opencode auth login`.";
}
return "Done.";
},
}),
"codex-status": tool({
description: "List all configured OpenAI Codex accounts and their current rate limits.",
args: {},
async execute() {
configureStorageForCurrentCwd();
const accountManager = await AccountManager.loadFromDisk();
Expand Down
61 changes: 61 additions & 0 deletions lib/ui/auth-menu-flow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import type { AuthMenuAction, AuthMenuAccount, AccountAction } from "./auth-menu.js";
import { buildAccountActionItems, buildAuthMenuItems, buildAccountSelectItems } from "./auth-menu.js";
import { runSelect } from "./tty/select.js";

type SelectContext = {
input?: NodeJS.ReadStream;
output?: NodeJS.WriteStream;
};

export async function chooseAuthMenuAction(
args: SelectContext & {
accounts: AuthMenuAccount[];
now?: number;
},
): Promise<AuthMenuAction | null> {
const items = buildAuthMenuItems(args.accounts, args.now);
const selected = await runSelect({
title: "Manage accounts",
subtitle: "Select account",
items,
input: args.input,
output: args.output,
useColor: false,
});
return selected?.value ?? null;
}

export async function chooseAccountAction(
args: SelectContext & {
account: AuthMenuAccount;
},
): Promise<AccountAction | null> {
const items = buildAccountActionItems(args.account);
const selected = await runSelect({
title: "Account options",
subtitle: "Select action",
items,
input: args.input,
output: args.output,
useColor: false,
});
return selected?.value ?? null;
}

export async function chooseAccountFromList(
args: SelectContext & {
accounts: AuthMenuAccount[];
now?: number;
},
): Promise<AuthMenuAccount | null> {
const items = buildAccountSelectItems(args.accounts, args.now);
const selected = await runSelect({
title: "Manage accounts",
subtitle: "Select account",
items,
input: args.input,
output: args.output,
useColor: false,
});
return selected?.value ?? null;
}
Loading