@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
305 lines • 14.7 kB
JavaScript
import { stampLogin } from "@earendil-works/pi-ai/auth/pool/login-id";
import { accountLabel } from "@earendil-works/pi-ai/auth/pool/slots";
import { describeAccountBlock } from "../../../credential-account-status.js";
import { emitProviderAccountsChanged } from "../anthropic-subscription/account-events.js";
import { emptyCredential, listAccounts, pinAccount, removeAccount, } from "./accounts.js";
import { selectAccount } from "./affinity.js";
import { collectCursorCliStatus, NATIVE_CURSOR_PROVIDER_ID, registerCursorCliShutdownSafety, renderCursorCliStatus, } from "./diagnostics.js";
import { CURSOR_CLI_OAUTH_PROVIDER_ID, confirmCursorCliNoApprovalAcknowledgement, importLocalCursorCredential, importNativeCursorCredential, } from "./oauth-login.js";
import { cursorCliSessionRouter } from "./session-router.js";
import { loadCursorCliOauthProviderSettingsFromDisk, persistCursorCliNoApprovalAcknowledgement, persistCursorCliOauthEnabled, } from "./settings.js";
const USAGE = "Usage: /cursor-account [list | add | remove <name> | pin <name> | unpin | import [local | native] | acknowledge | status]";
function asCursorCredential(value) {
return value !== undefined && value.type === "oauth" ? value : emptyCredential();
}
function parseArgs(rawArgs) {
return rawArgs.trim().split(/\s+/).filter(Boolean);
}
function slotStatus(slot, now) {
if (slot.blockReason === "auth_error")
return describeAccountBlock({ blocked: true, blockedReason: "auth_error" });
if (slot.blockedUntil !== undefined && slot.blockedUntil > now) {
return describeAccountBlock({ blocked: true, blockedReason: "rate_limit", blockedUntil: slot.blockedUntil });
}
return "available";
}
function authEventMessage(event) {
if (event === null || typeof event !== "object")
return "Cursor CLI (OAuth) authentication update.";
const value = event;
if (value.type === "auth_url" && typeof value.url === "string") {
return `Open this URL to authorize Cursor CLI (OAuth):\n${value.url}`;
}
if (value.type === "device_code" && typeof value.verificationUri === "string") {
return `Open this URL to authorize Cursor CLI (OAuth):\n${value.verificationUri}`;
}
return typeof value.message === "string" ? value.message : "Cursor CLI (OAuth) authentication update.";
}
/**
* Registers `/cursor-account` plus the reload/shutdown teardown for this
* extension generation: the command reads account state fresh from the
* credential store on every invocation, and every deferred continuation is
* fenced so a retired generation is never touched after a reload.
*/
export function registerCursorCliAccountCommand(pi, deps = {}) {
const loadSettings = deps.loadSettings ?? ((cwd) => loadCursorCliOauthProviderSettingsFromDisk(cwd));
const now = deps.now ?? Date.now;
// One guard per registration: a reload rebuilds the extension and gets a
// fresh fence, while the child registry stays process-wide.
const generation = registerCursorCliShutdownSafety(pi, { generation: deps.generation });
pi.registerCommand("cursor-account", {
description: "List and manage Cursor CLI (OAuth) accounts.",
argumentHint: "[list | add | remove <name> | pin <name> | unpin | import | acknowledge | status]",
requiresArguments: false,
handler: async (rawArgs, ctx) => {
try {
const args = parseArgs(rawArgs);
const action = args[0] ?? "list";
if (action === "list") {
showAccounts(ctx, loadSettings(ctx.cwd), generation, now);
return;
}
if (action === "add") {
await addAccount(ctx);
return;
}
if (action === "remove") {
await removeNamedAccount(ctx, args[1]);
return;
}
if (action === "pin" && args[1] !== undefined) {
await pinNamedAccount(ctx, args[1]);
return;
}
if (action === "unpin") {
await unpinAccount(ctx);
return;
}
if (action === "import") {
const source = args[1] ?? "local";
if (source !== "local" && source !== "native") {
ctx.ui.notify(USAGE, "error");
return;
}
await importAccount(ctx, deps, source);
return;
}
if (action === "acknowledge") {
await acknowledgeNoApproval(ctx, deps, generation);
return;
}
if (action === "status") {
await showStatus(ctx, deps, { loadSettings, generation, now });
return;
}
ctx.ui.notify(USAGE, "error");
}
catch (error) {
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
}
},
});
}
function showAccounts(ctx, settings, generation, now) {
const credential = asCursorCredential(ctx.modelRegistry.authStorage.get(CURSOR_CLI_OAUTH_PROVIDER_ID));
const accounts = listAccounts(credential);
const pinned = settings.pinnedAccount ?? credential.pinned;
const pinSource = settings.pinnedAccount !== undefined ? "settings" : "stored";
let affinityPick;
let affinityError;
if (accounts.length > 0) {
try {
affinityPick = selectAccount(accounts, {
sessionId: ctx.sessionManager.getSessionId(),
pinnedAccount: pinned,
...(credential.order === undefined ? {} : { accountOrder: credential.order }),
now: now(),
}).name;
}
catch (error) {
affinityError = error instanceof Error ? error.message : String(error);
}
}
const lines = ["Cursor CLI (OAuth) accounts:"];
if (accounts.length === 0)
lines.push(" (none)");
for (const account of accounts) {
const states = [accountLabel(account), account.source, slotStatus(account, now())];
if (account.name === pinned)
states.push("pinned");
if (account.name === affinityPick)
states.push("affinity pick");
lines.push(` ${states.join(" | ")}`);
}
const labelFor = (name) => accountLabel(accounts.find((account) => account.name === name) ?? { name });
lines.push(`Pinned account: ${pinned === undefined ? "none" : `${labelFor(pinned)} (${pinSource})`}`);
lines.push(`Affinity pick: ${affinityPick === undefined ? (affinityError ? `unavailable - ${affinityError}` : "none") : labelFor(affinityPick)}`);
generation.runFencedSync(ctx, () => ctx.ui.notify(lines.join("\n"), "info"));
}
async function addAccount(ctx) {
if (!ctx.hasUI) {
ctx.ui.notify("/cursor-account add requires an interactive UI.", "error");
return;
}
try {
await ctx.modelRegistry.modelRuntime.login(CURSOR_CLI_OAUTH_PROVIDER_ID, "oauth", {
signal: ctx.signal,
prompt: async (prompt) => {
const answer = await ctx.ui.input(prompt.message);
if (answer === undefined)
throw new Error("Login cancelled");
return answer;
},
notify: (event) => ctx.ui.notify(authEventMessage(event), "info"),
});
emitProviderAccountsChanged(CURSOR_CLI_OAUTH_PROVIDER_ID);
ctx.ui.notify("Cursor CLI (OAuth) account added.", "info");
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (message !== "Login cancelled") {
ctx.ui.notify(`Failed to add Cursor CLI (OAuth) account: ${message}`, "error");
}
}
}
async function removeNamedAccount(ctx, name) {
if (!name) {
ctx.ui.notify("Usage: /cursor-account remove <name>", "error");
return;
}
let removed = false;
try {
await ctx.modelRegistry.authStorage.modify(CURSOR_CLI_OAUTH_PROVIDER_ID, async (current) => {
const credential = asCursorCredential(current);
if (!listAccounts(credential).some((account) => account.name === name))
return current;
removed = true;
return removeAccount(credential, name);
});
}
catch (error) {
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
return;
}
if (!removed) {
ctx.ui.notify(`Cursor CLI (OAuth) account '${name}' does not exist.`, "error");
return;
}
emitProviderAccountsChanged(CURSOR_CLI_OAUTH_PROVIDER_ID);
ctx.ui.notify(`Removed Cursor CLI (OAuth) account: ${name}.`, "info");
}
async function pinNamedAccount(ctx, name) {
try {
await ctx.modelRegistry.authStorage.modify(CURSOR_CLI_OAUTH_PROVIDER_ID, async (current) => {
const credential = asCursorCredential(current);
if (!listAccounts(credential).some((account) => account.name === name)) {
throw new Error(`Cursor CLI (OAuth) account '${name}' does not exist.`);
}
return pinAccount(credential, name);
});
}
catch (error) {
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
return;
}
emitProviderAccountsChanged(CURSOR_CLI_OAUTH_PROVIDER_ID);
ctx.ui.notify(`Pinned Cursor CLI (OAuth) account: ${name}.`, "info");
}
async function unpinAccount(ctx) {
let hadPin = false;
try {
await ctx.modelRegistry.authStorage.modify(CURSOR_CLI_OAUTH_PROVIDER_ID, async (current) => {
const credential = asCursorCredential(current);
if (credential.pinned === undefined)
return current;
hadPin = true;
const { pinned: _pinned, ...unpinned } = credential;
return unpinned;
});
}
catch (error) {
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
return;
}
if (!hadPin) {
ctx.ui.notify("No stored Cursor CLI (OAuth) account pin is set.", "info");
return;
}
emitProviderAccountsChanged(CURSOR_CLI_OAUTH_PROVIDER_ID);
ctx.ui.notify("Unpinned Cursor CLI (OAuth) account.", "info");
}
async function importAccount(ctx, deps, source) {
const importCredential = deps.importCredential ?? importLocalCursorCredential;
const importNativeCredential = deps.importNativeCredential ?? importNativeCursorCredential;
const importDeps = { ...deps.importDeps };
if (importDeps.onPrompt === undefined && ctx.hasUI) {
importDeps.onPrompt = async (prompt) => {
const answer = await ctx.ui.input(prompt.message);
if (answer === undefined)
throw new Error("Import cancelled");
return answer;
};
}
let importedName;
try {
await ctx.modelRegistry.authStorage.modify(CURSOR_CLI_OAUTH_PROVIDER_ID, async (current) => {
const before = asCursorCredential(current);
const updated = source === "native"
? await importNativeCredential(before, deps.readNativeCredential ?? (() => ctx.modelRegistry.authStorage.get(NATIVE_CURSOR_PROVIDER_ID)))
: await importCredential(before, importDeps);
const existing = new Set(listAccounts(before).map((account) => account.name));
importedName = listAccounts(updated).find((account) => !existing.has(account.name))?.name;
// An import adds a signed-in account, so it stamps a login id like a login (senpi#4099).
return stampLogin(updated);
});
}
catch (error) {
ctx.ui.notify(`Failed to import local Cursor credential: ${error instanceof Error ? error.message : String(error)}`, "error");
return;
}
const persistEnabled = deps.persistEnabled ?? persistCursorCliOauthEnabled;
try {
persistEnabled(ctx.cwd, true);
await ctx.modelRegistry.modelRuntime.refresh({
allowNetwork: false,
providers: [CURSOR_CLI_OAUTH_PROVIDER_ID],
});
}
catch (error) {
ctx.ui.notify(`Imported ${source === "native" ? "native " : ""}Cursor credential, but provider activation failed: ${error instanceof Error ? error.message : String(error)}`, "warning");
return;
}
emitProviderAccountsChanged(CURSOR_CLI_OAUTH_PROVIDER_ID);
ctx.ui.notify(`Imported ${source === "native" ? "native " : "local "}Cursor credential as '${importedName ?? "a new account"}' (copied into this provider's store).`, "info");
}
async function acknowledgeNoApproval(ctx, deps, generation) {
if (!ctx.hasUI) {
ctx.ui.notify("/cursor-account acknowledge requires an interactive UI.", "error");
return;
}
const persist = deps.persistAcknowledgement ?? persistCursorCliNoApprovalAcknowledgement;
const acknowledgedAt = await confirmCursorCliNoApprovalAcknowledgement(async (ask) => (await ctx.ui.input(ask.message)) ?? "", () => new Date((deps.now ?? Date.now)()));
if (acknowledgedAt === undefined) {
generation.runFencedSync(ctx, () => ctx.ui.notify("No acknowledgement written: unattended Cursor CLI execution stays off until you acknowledge.", "info"));
return;
}
persist(ctx.cwd, acknowledgedAt);
generation.runFencedSync(ctx, () => ctx.ui.notify(`Acknowledged unattended Cursor CLI tool execution at ${acknowledgedAt}.`, "info"));
}
async function showStatus(ctx, deps, bound) {
// Context reads happen before any await; the render continuation is fenced
// so a reload during the version probe can never touch a retired context.
const sessionId = ctx.sessionManager.getSessionId();
const report = await collectCursorCliStatus({
sessionId,
settings: bound.loadSettings(ctx.cwd),
readCredential: () => ctx.modelRegistry.authStorage.get(CURSOR_CLI_OAUTH_PROVIDER_ID),
readNativeCredential: deps.readNativeCredential ?? (() => ctx.modelRegistry.authStorage.get(NATIVE_CURSOR_PROVIDER_ID)),
router: deps.router ?? cursorCliSessionRouter,
resolveExecutable: deps.resolveExecutable,
probeVersion: deps.probeVersion,
now: bound.now,
});
bound.generation.runFencedSync(ctx, () => ctx.ui.notify(renderCursorCliStatus(report), "info"));
}
//# sourceMappingURL=account-command.js.map