@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
206 lines • 9.53 kB
JavaScript
import { accountDisplayNameCommand, promptAccountDisplayName } from "../account-display-name.js";
import { createExtensionLoginInteraction, LOGIN_CANCELLED_MESSAGE } from "../oauth-login-interaction.js";
import { ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, pinProviderAccount, removeProviderAccount, unblockProviderAccount, } from "./account-management.js";
import { formatClaudeAccountList } from "./account-list.js";
import { emptyCredential, listAccounts } from "./accounts.js";
import { selectAccount } from "./affinity.js";
import { loadAnthropicSubscriptionProviderSettingsFromDisk, } from "./settings.js";
const cliPinsBySession = new Map();
const ANTHROPIC_SUBSCRIPTION_PROVIDER_LABEL = "Anthropic Subscription";
function asCredential(value) {
return value?.type === "oauth" ? value : undefined;
}
function readAccounts(ctx, environment) {
const credential = asCredential(ctx.modelRegistry.authStorage.get(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID));
return {
credential,
accounts: listAccounts(credential ?? emptyCredential(), environment),
};
}
function accountError(ctx, name) {
ctx.ui.notify(`Anthropic Subscription account '${name}' does not exist.`, "error");
}
function parseArgs(rawArgs) {
return rawArgs.trim().split(/\s+/).filter(Boolean);
}
export function getSessionClaudeAccountPin(sessionId) {
return sessionId === undefined ? undefined : cliPinsBySession.get(sessionId);
}
/** CLI pins are request-local overrides; settings and stored pins remain fallback choices. */
export function resolveClaudeAccountPin(cliPinnedAccount, settingsPinnedAccount, storedPinnedAccount) {
return cliPinnedAccount ?? settingsPinnedAccount ?? storedPinnedAccount;
}
export function registerClaudeAccountCommand(pi, deps = {}) {
const loadSettings = deps.loadSettings ?? loadAnthropicSubscriptionProviderSettingsFromDisk;
const environment = deps.environment ?? ((name) => process.env[name]);
pi.registerFlag("claude-account", {
type: "string",
description: "Pin Anthropic Subscription account for this session.",
});
pi.on("session_start", (_event, ctx) => {
const flag = pi.getFlag("claude-account");
const sessionId = ctx.sessionManager.getSessionId();
if (typeof flag === "string" && flag.length > 0)
cliPinsBySession.set(sessionId, flag);
else
cliPinsBySession.delete(sessionId);
});
pi.on("session_shutdown", (_event, ctx) => {
cliPinsBySession.delete(ctx.sessionManager.getSessionId());
});
pi.registerCommand("claude-account", {
description: "List and manage Anthropic Subscription accounts.",
argumentHint: "[add | remove <id> | pin <id> | unpin | unblock <id> | rename <id> <display name...> | clear-name <id>]",
requiresArguments: false,
handler: async (rawArgs, ctx) => {
if (await accountDisplayNameCommand(ctx, ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, rawArgs))
return;
const args = parseArgs(rawArgs);
const action = args[0] ?? "list";
if (action === "list") {
showAccounts(ctx, loadSettings(ctx.cwd), environment);
return;
}
if (action === "add") {
await addAccount(ctx, deps);
return;
}
if (action === "remove") {
await removeNamedAccount(ctx, args[1], environment);
return;
}
if (action === "pin" && args[1] !== "unpin") {
await pinNamedAccount(ctx, args[1], environment);
return;
}
if (action === "unpin" || (action === "pin" && args[1] === "unpin")) {
await unpinAccount(ctx);
return;
}
if (action === "unblock") {
await unblockNamedAccount(ctx, args[1], environment);
return;
}
ctx.ui.notify("Usage: /claude-account [add | remove <id> | pin <id> | unpin | unblock <id> | rename <id> <display name...> | clear-name <id>]", "error");
},
});
}
function showAccounts(ctx, settings, environment) {
const { credential, accounts } = readAccounts(ctx, environment);
const cliPin = getSessionClaudeAccountPin(ctx.sessionManager.getSessionId());
const pinned = resolveClaudeAccountPin(cliPin, settings.pinnedAccount, credential?.pinned);
const pinSource = cliPin !== undefined ? "CLI" : settings.pinnedAccount !== undefined ? "settings" : "stored";
let affinityPick;
let affinityError;
if (accounts.length > 0) {
try {
affinityPick = selectAccount(accounts, {
sessionId: ctx.sessionManager.getSessionId(),
pinnedAccount: pinned,
...(pinned === undefined ? {} : { pinSource: pinSource === "CLI" ? "cli" : pinSource }),
accountFallback: settings.accountFallback,
accountStrategy: settings.accountStrategy,
...(credential?.order === undefined ? {} : { accountOrder: credential.order }),
}).name;
}
catch (error) {
affinityError = error instanceof Error ? error.message : String(error);
}
}
ctx.ui.notify(formatClaudeAccountList({ accounts, pinned, pinSource, affinityPick, affinityError, now: Date.now() }), "info");
}
async function addAccount(ctx, deps) {
if (!ctx.hasUI) {
ctx.ui.notify("/claude-account add requires an interactive UI.", "error");
return;
}
try {
let receipt;
await ctx.modelRegistry.modelRuntime.login(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, "oauth", {
...createExtensionLoginInteraction(ctx, {
providerLabel: ANTHROPIC_SUBSCRIPTION_PROVIDER_LABEL,
openBrowser: deps.openBrowser,
}),
onAccountCommitted: (committed) => {
receipt = committed;
},
});
// senpi#5116: ModelRuntime.login already emits accounts_changed (with
// the "login" remedy); a second emit here sent RPC clients a duplicate
// auth_accounts_changed event.
ctx.ui.notify("Anthropic Subscription account added.", "info");
await promptAccountDisplayName(ctx, receipt);
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (message !== LOGIN_CANCELLED_MESSAGE) {
ctx.ui.notify(`Failed to add Anthropic Subscription account: ${message}`, "error");
}
}
}
async function removeNamedAccount(ctx, name, environment) {
if (!name) {
ctx.ui.notify("Usage: /claude-account remove <name>", "error");
return;
}
const { accounts } = readAccounts(ctx, environment);
const target = accounts.find((account) => account.name === name);
if (!target)
return accountError(ctx, name);
if (target.source === "env") {
ctx.ui.notify(`Anthropic Subscription account '${name}' comes from the environment and cannot be removed.`, "error");
return;
}
try {
const { notice } = await removeProviderAccount(ctx.modelRegistry.authStorage, ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, name);
ctx.ui.notify(notice ?? `Removed Anthropic Subscription account: ${name}.`, notice ? "warning" : "info");
}
catch (error) {
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
}
}
async function pinNamedAccount(ctx, name, environment) {
if (!name) {
ctx.ui.notify("Usage: /claude-account pin <name>", "error");
return;
}
if (!readAccounts(ctx, environment).accounts.some((account) => account.name === name)) {
return accountError(ctx, name);
}
try {
await pinProviderAccount(ctx.modelRegistry.authStorage, ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, name);
ctx.ui.notify(`Pinned Anthropic Subscription account: ${name}.`, "info");
}
catch (error) {
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
}
}
async function unblockNamedAccount(ctx, name, environment) {
if (!name) {
ctx.ui.notify("Usage: /claude-account unblock <name>", "error");
return;
}
if (!readAccounts(ctx, environment).accounts.some((account) => account.name === name)) {
return accountError(ctx, name);
}
try {
const env = new Proxy({}, { get: (_target, key) => environment(String(key)) });
const lifted = await unblockProviderAccount(ctx.modelRegistry.authStorage, ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, name, env);
ctx.ui.notify(lifted
? `Unblocked Anthropic Subscription account: ${name}. The next turn may use it.`
: `Anthropic Subscription account '${name}' has no usage block to lift.`, "info");
}
catch (error) {
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
}
}
async function unpinAccount(ctx) {
const credential = asCredential(ctx.modelRegistry.authStorage.get(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID));
if (!credential?.pinned) {
ctx.ui.notify("No stored Anthropic Subscription account pin is set.", "info");
return;
}
await pinProviderAccount(ctx.modelRegistry.authStorage, ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, null);
ctx.ui.notify("Unpinned Anthropic Subscription account.", "info");
}
//# sourceMappingURL=account-command.js.map