UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

198 lines • 9.85 kB
import { accountLabel } from "@earendil-works/pi-ai/auth/pool/slots"; import { describeCredentialAccount } from "../../../core/credential-account-status.js"; import { unblockPooledAccount } from "../../../core/credential-account-unblock.js"; import { accountLimitsFor, describeAccountLimits } from "../../subscription-limits/limit-summary.js"; import { getCredentialAccounts, pinCredentialAccount, removeCredentialAccount, selectedOAuthAccount, } from "../../../core/credential-accounts.js"; import { accountDisplayNameCommand, promptAccountDisplayName } from "./account-display-name.js"; import { emitProviderAccountsChanged } from "./anthropic-subscription/account-events.js"; import { createExtensionLoginInteraction, LOGIN_CANCELLED_MESSAGE } from "./oauth-login-interaction.js"; const CHATGPT_SUBSCRIPTION_PROVIDER_ID = "chatgpt-subscription"; const CHATGPT_SUBSCRIPTION_PROVIDER_LABEL = "ChatGPT Subscription OAuth"; const USAGE_ACTIONS = "[add | reauthorize <id> | signout <id> | remove <id> | pin <id> | unpin | unblock <id> | rename <id> <display name...> | clear-name <id>]"; function parseArgs(rawArgs) { return rawArgs.trim().split(/\s+/).filter(Boolean); } function usage(ctx) { ctx.ui.notify(`Usage: /gpt-account ${USAGE_ACTIONS}`, "error"); } async function showAccounts(ctx) { const activeName = ctx.modelRegistry.modelRuntime?.getActiveCredentialAccount?.(CHATGPT_SUBSCRIPTION_PROVIDER_ID, ctx.sessionManager.getSessionId()); const accounts = await getCredentialAccounts(ctx.modelRegistry.authStorage, CHATGPT_SUBSCRIPTION_PROVIDER_ID, process.env, undefined, activeName); const lines = ["ChatGPT Subscription OAuth accounts:"]; if (accounts.length === 0) lines.push(" (none)"); const now = Date.now(); for (const account of accounts) { // SIWC states that replace the health column; otherwise main's row (block reason, per-model limits, pin). // A paused account keeps main's row, so its per-model limits stay listed beside the pause. const override = account.signedOut ? "signed out" : account.planUsageEnabled === false ? "plan usage not enabled: enable it or use an API key" : undefined; const states = override === undefined ? [ describeCredentialAccount(account, `run /gpt-account reauthorize ${account.name}`), ...(account.paused ? ["paused"] : []), ] : [accountLabel(account), account.source, override, ...(account.pinned ? ["pinned"] : [])]; if (account.active) states.push("active"); if (account.route) states.push(account.route === "siwc" ? "SIWC" : "legacy"); if (!account.signedOut && account.planUsageEnabled === true) states.push("Using ChatGPT plan"); lines.push(` ${states.join(" | ")}`); const limits = accountLimitsFor(CHATGPT_SUBSCRIPTION_PROVIDER_ID, account.name); lines.push(` ${describeAccountLimits(limits, now)}`); } lines.push("Manage usage: https://chatgpt.com/settings/usage (ChatGPT Settings > Usage)"); ctx.ui.notify(lines.join("\n"), "info"); } async function addAccount(ctx, deps, name) { if (!ctx.hasUI) { ctx.ui.notify(`/gpt-account ${name === undefined ? "add" : "reauthorize"} requires an interactive UI.`, "error"); return; } try { let receipt; const reauthorize = name === undefined ? undefined : selectedOAuthAccount(ctx.modelRegistry.authStorage, CHATGPT_SUBSCRIPTION_PROVIDER_ID, name); await ctx.modelRegistry.modelRuntime.login(CHATGPT_SUBSCRIPTION_PROVIDER_ID, "oauth", { ...createExtensionLoginInteraction(ctx, { providerLabel: CHATGPT_SUBSCRIPTION_PROVIDER_LABEL, providerId: CHATGPT_SUBSCRIPTION_PROVIDER_ID, openBrowser: deps.openBrowser, }), onAccountCommitted: (committed) => { receipt = committed; }, }, reauthorize === undefined ? undefined : { reauthorize, reauthorizeSlot: name }); emitProviderAccountsChanged(CHATGPT_SUBSCRIPTION_PROVIDER_ID); ctx.ui.notify(name === undefined ? "ChatGPT Subscription OAuth account added." : `ChatGPT Subscription OAuth account '${name}' reauthorized.`, "info"); if (name === undefined) await promptAccountDisplayName(ctx, receipt); } catch (error) { const message = error instanceof Error ? error.message : String(error); if (message === LOGIN_CANCELLED_MESSAGE) return; ctx.ui.notify(message, "error"); } } async function signOutAccount(ctx, name) { selectedOAuthAccount(ctx.modelRegistry.authStorage, CHATGPT_SUBSCRIPTION_PROVIDER_ID, name); const result = await ctx.modelRegistry.modelRuntime.logout(CHATGPT_SUBSCRIPTION_PROVIDER_ID, { slotId: name }); emitProviderAccountsChanged(CHATGPT_SUBSCRIPTION_PROVIDER_ID); if (result?.status === "remote_revocation_unconfirmed") { ctx.ui.notify("remote revocation not confirmed; disconnect the app in ChatGPT Settings", "warning"); } else { ctx.ui.notify(`Signed out ChatGPT Subscription OAuth account '${name}'.`, "info"); } } async function removeAccount(ctx, name) { if (!name) { usage(ctx); return; } await removeCredentialAccount(ctx.modelRegistry.authStorage, CHATGPT_SUBSCRIPTION_PROVIDER_ID, name); ctx.ui.notify(`Removed ChatGPT Subscription OAuth account '${name}'.`, "info"); } async function pinAccount(ctx, name) { if (!name) { usage(ctx); return; } await pinCredentialAccount(ctx.modelRegistry.authStorage, CHATGPT_SUBSCRIPTION_PROVIDER_ID, name); ctx.ui.notify(`Pinned ChatGPT Subscription OAuth account '${name}'.`, "info"); } const STILL_BLOCKED_REASON = { auth_error: "the credential was rejected; sign in again to clear it", disabled: "the account is disabled until its credential is replaced", rate_limit: "another cooldown on it is still running", }; /** * Lifts a usage-limit block the user knows is gone (the limit reset on the provider side), like * `/claude-account unblock` (senpi#4600). The lift is `unblockPooledAccount`, which clears only a * live account-level usage or rate-limit block and reports the MERGED state afterwards, so a lift * that leaves an auth block standing is never announced as "usable again". */ async function unblockAccount(ctx, name) { if (!name) { ctx.ui.notify("Usage: /gpt-account unblock <id>", "error"); return; } const accounts = await getCredentialAccounts(ctx.modelRegistry.authStorage, CHATGPT_SUBSCRIPTION_PROVIDER_ID); if (!accounts.some((candidate) => candidate.name === name)) { ctx.ui.notify(`ChatGPT Subscription OAuth account '${name}' does not exist.`, "error"); return; } const outcome = await unblockPooledAccount(ctx.modelRegistry.authStorage, CHATGPT_SUBSCRIPTION_PROVIDER_ID, name); if (!outcome.lifted) { ctx.ui.notify(`ChatGPT Subscription OAuth account '${name}' has no usage block to lift.`, "info"); return; } if (outcome.blocked) { const reason = outcome.blockedReason === undefined ? undefined : STILL_BLOCKED_REASON[outcome.blockedReason]; ctx.ui.notify(`Lifted the usage block on ChatGPT Subscription OAuth account '${name}', but it is still blocked${reason === undefined ? "" : `: ${reason}`}.`, "warning"); return; } ctx.ui.notify(`Unblocked ChatGPT Subscription OAuth account '${name}'. The next turn may use it.`, "info"); } export default function gptAccountExtension(pi, deps = {}) { pi.registerCommand("gpt-account", { description: "List and manage ChatGPT Subscription OAuth accounts.", argumentHint: USAGE_ACTIONS, requiresArguments: false, handler: async (rawArgs, ctx) => { if (await accountDisplayNameCommand(ctx, CHATGPT_SUBSCRIPTION_PROVIDER_ID, rawArgs)) return; const args = parseArgs(rawArgs); const action = args[0] ?? "list"; try { if (action === "list") { await showAccounts(ctx); return; } if (action === "add") { await addAccount(ctx, deps); return; } if (action === "reauthorize" && args[1]) { await addAccount(ctx, deps, args[1]); return; } if (action === "signout" && args[1]) { await signOutAccount(ctx, args[1]); return; } if (action === "remove") { await removeAccount(ctx, args[1]); return; } if (action === "unblock") { await unblockAccount(ctx, args[1]); return; } if (action === "pin" && args[1] !== "unpin") { await pinAccount(ctx, args[1]); return; } if (action === "unpin" || (action === "pin" && args[1] === "unpin")) { await pinCredentialAccount(ctx.modelRegistry.authStorage, CHATGPT_SUBSCRIPTION_PROVIDER_ID, null); ctx.ui.notify("Unpinned ChatGPT Subscription OAuth account.", "info"); return; } usage(ctx); } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); } }, }); } //# sourceMappingURL=gpt-account.js.map