// PEP-76: the project owner's choice of what its agents run on — the platform's shared pool // («Общая подписка Пеппы») or the owner's own Claude subscription (a `claude setup-token` token, // kept encrypted like every subscription, in the owner's personal pool). import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, poolSubscriptions, projectPool, type Project, type User } from "@peppa/core"; import type { Db } from "@peppa/db"; import { finishClaudeLogin, pendingLogin, pollCodexLogin, removeSubscription } from "./subscription-login.ts"; import { addSubscription } from "./subscriptions.ts"; async function requireOwner(db: Db, user: User, project: Project): Promise { if (project.ownerId !== user.id && !(await isSuperadmin(db, user))) throw new PeppaError("Подписку проекта выбирает его владелец"); } /** «Общая подписка Пеппы»: the project runs on the platform's shared pool. */ export async function chooseSharedSubscription(db: Db, user: User, project: Project): Promise { await requireOwner(db, user, project); const pool = await sharedPool(db); if (!pool) throw new PeppaError("Общая подписка не настроена — подключите свою или попросите администратора"); await setProjectPool(db, project.id, pool.id); await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "shared", poolId: pool.id } }); } export type OwnSubscriptionKind = "claude_login" | "claude" | "codex_login" | "codex_key" | "existing"; const OWN_NAMES: Record, string> = { claude_login: "Claude", claude: "Claude", codex_login: "ChatGPT", codex_key: "Codex API" }; /** * «Своя подписка» (PEP-76/80): a new subscription of the user goes into their own pool (created on * first use) — Claude by a `claude setup-token` token, ChatGPT by the Codex device login (the * page then shows the link and the one-time code), Codex by an OpenAI API key; "existing" just * moves the project to the pool the user already has. */ export async function connectOwnSubscription(db: Db, user: User, project: Project, kind: OwnSubscriptionKind, secret = ""): Promise<{ subscriptionId: number | null }> { await requireOwner(db, user, project); let pool = await ownPool(db, user.id); let subscriptionId: number | null = null; if (kind === "existing") { if (!pool) throw new PeppaError("Своей подписки ещё нет — подключите Claude или ChatGPT"); } else { if (kind !== "codex_login" && kind !== "claude_login" && !secret.trim()) throw new PeppaError(kind === "claude" ? "Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат" : "Вставьте ключ OpenAI API"); const taken = new Set((await listSubscriptions(db)).map((s) => s.name)); const base = `${OWN_NAMES[kind]} — ${user.login}`; let name = base; for (let n = 2; taken.has(name); n++) name = `${base} ${n}`; const sub = kind === "claude_login" ? await addSubscription(db, { provider: "claude", name, method: "login", createdBy: user.id }) : kind === "claude" ? await addSubscription(db, { provider: "claude", name, method: "token", secret, createdBy: user.id }) : await addSubscription(db, { provider: "codex", name, method: kind === "codex_key" ? "api_key" : "device", secret: secret || undefined, createdBy: user.id }); subscriptionId = sub.id; if (pool) { const cur = (await listPools(db)).find((p) => p.id === pool!.id); await updatePool(db, pool.id, { subscriptionIds: [...(cur?.subscriptionIds ?? []), sub.id] }); } else { pool = await createPool(db, { name: `Подписки — ${user.login}`, subscriptionIds: [sub.id], createdBy: user.id }); } } await getPool(db, pool.id); await setProjectPool(db, project.id, pool.id); await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "own", kind, poolId: pool.id } }); return { subscriptionId }; } export interface OwnLogin { subscriptionId: number; provider: "claude" | "codex"; name: string; url: string; /** ChatGPT: the one-time code to enter on the page behind the link. */ code: string | null; } /** * Sign-ins of the pool's subscriptions still waiting for the user. Claude: open the link, sign * in, paste the code Claude shows (`finishOwnClaudeLogin`). ChatGPT: open the link and enter the * code — Codex is polled first, so a finished login turns the subscription active. */ export async function ownPendingLogins(db: Db, poolId: number): Promise { const out: OwnLogin[] = []; for (const s of await poolSubscriptions(db, poolId)) { if (s.status !== "pending" || s.provider === "opencode") continue; if (s.provider === "codex" && (await pollCodexLogin(db, s.id).catch(() => "pending")) !== "pending") continue; const l = await pendingLogin(db, s.id); if (l) out.push({ subscriptionId: s.id, provider: s.provider, name: s.name, url: l.url, code: l.code ?? null }); } return out; } /** The user's own pending subscription of the project's pool, or an error. */ async function ownPendingSubscription(db: Db, user: User, project: Project, subscriptionId: number) { await requireOwner(db, user, project); const pool = await projectPool(db, project.id); const sub = pool ? (await poolSubscriptions(db, pool.id)).find((s) => s.id === subscriptionId) : undefined; if (!sub || (sub.createdBy !== user.id && !(await isSuperadmin(db, user)))) throw new PeppaError("Подписка не найдена"); return sub; } /** Step 3 of the Claude sign-in: the code Claude showed after the user signed in. */ export async function finishOwnClaudeLogin(db: Db, user: User, project: Project, subscriptionId: number, code: string): Promise { const sub = await ownPendingSubscription(db, user, project, subscriptionId); if (sub.provider !== "claude") throw new PeppaError("Код нужен только для Claude"); await finishClaudeLogin(db, sub.id, code); } /** «Отмена» of a sign-in that was not finished: the pending subscription goes away. */ export async function cancelOwnLogin(db: Db, user: User, project: Project, subscriptionId: number): Promise { const sub = await ownPendingSubscription(db, user, project, subscriptionId); if (sub.status !== "pending") throw new PeppaError("Эта подписка уже подключена"); await removeSubscription(db, sub.id); const pool = await projectPool(db, project.id); // The last one is gone: back to "no subscription", so the page offers to connect again. if (pool && !(await poolSubscriptions(db, pool.id)).length && pool.createdBy === user.id) await setProjectPool(db, project.id, null); }