// PEP-76: the project owner's choice of what its agents run on — the platform's shared pool // («Общая подписка FORGE») or the owner's own Claude subscription (a `claude setup-token` token, // kept encrypted like every subscription, in the owner's personal pool). import { asIs, m } from "@peppa/shared/i18n"; import { askPmProject, deleteSetting, getProject, getSetting, platformProjectKey, setSetting, type Question, createPool, getPool, listLoans, 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"; import { onAnswer } from "./sessions.ts"; import { projects } from "@peppa/db"; import { eq } from "drizzle-orm"; async function requireOwner(db: Db, user: User, project: Project): Promise { if (project.ownerId !== user.id && !(await isSuperadmin(db, user))) throw new PeppaError(m("Подписку проекта выбирает его владелец")); } // ── «Подписка FORGE» (PEP-116) ─────────────────────────────────────── // The factory's subscription is the superadmin's own: a project gets it only after the // superadmin says yes. The owner's choice becomes a request — a question with buttons in the // platform project, which reaches the superadmin on the Home page and in Telegram. export const SHARED_APPROVE = m("✅ Разрешить"); export const SHARED_DENY = m("❌ Отказать"); export interface SharedRequest { userId: number; login: string; questionId: number; at: string; } const requestKey = (projectId: number) => `shared.request:${projectId}`; const questionKey = (questionId: number) => `shared.question:${questionId}`; /** The project's request for the factory's subscription that still waits for the superadmin. */ export async function sharedRequest(db: Db, projectId: number): Promise { return getSetting(db, requestKey(projectId)); } async function switchToShared(db: Db, project: Project, poolId: number, login: string, approvedBy?: string): Promise { await setProjectPool(db, project.id, poolId); await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login, choice: "shared", poolId, ...(approvedBy ? { approvedBy } : {}) } }); } /** * «Подписка FORGE»: a superadmin switches the project at once; an owner's choice is a * request the superadmin confirms ("requested" — one per project, asking again changes nothing). */ export async function chooseSharedSubscription(db: Db, user: User, project: Project): Promise<"switched" | "requested"> { await requireOwner(db, user, project); const pool = await sharedPool(db); if (!pool) throw new PeppaError(m("Подписка FORGE сейчас не предлагается — подключите свою")); if (await isSuperadmin(db, user)) { await switchToShared(db, project, pool.id, user.login); return "switched"; } if (await sharedRequest(db, project.id)) return "requested"; const platform = await getProject(db, platformProjectKey()).catch(() => null); if (!platform) throw new PeppaError(m("Подписку FORGE некому подтвердить — подключите свою")); const q = await askPmProject(db, platform, { kind: "question", options: [SHARED_APPROVE, SHARED_DENY], text: m("🔑 {login} просит подписку FORGE для проекта «{project}» ({key}).\nАгенты проекта будут работать на подписке фабрики и тратить её лимит.\nРазрешить?", { login: asIs(user.login), project: asIs(project.name), key: project.key }), }); await setSetting(db, requestKey(project.id), { userId: user.id, login: user.login, questionId: q.id, at: new Date().toISOString() } satisfies SharedRequest); await setSetting(db, questionKey(q.id), project.id); await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "shared_requested" } }); return "requested"; } /** The superadmin answered a request (web, Telegram, MCP): yes switches the project, anything else refuses. */ export async function onSharedAnswer(db: Db, q: Question, answer: string): Promise { if (q.taskId || q.sessionId || !(q.options ?? []).includes(SHARED_APPROVE)) return false; const projectId = await getSetting(db, questionKey(q.id)); if (projectId == null) return false; const req = await sharedRequest(db, projectId); await deleteSetting(db, questionKey(q.id)); await deleteSetting(db, requestKey(projectId)); const [project] = await db.select().from(projects).where(eq(projects.id, projectId)); if (!project || !req) return true; const web = process.env.PEPPA_WEB_URL ?? ""; const pool = await sharedPool(db); if (answer.trim() === SHARED_APPROVE && pool) { await switchToShared(db, project, pool.id, req.login, "superadmin"); await askPmProject(db, project, { kind: "attention", text: m("✅ {project}: подписка FORGE разрешена — агенты могут работать. Перейти на свою подписку можно в любой момент в настройках проекта.", { project: asIs(project.name) }) }); } else { await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: req.login, choice: "shared_denied" } }); await askPmProject(db, project, { kind: "attention", text: m("{project}: подписку FORGE для этого проекта не разрешили. Подключите свою подписку Claude или ChatGPT — {url}", { project: asIs(project.name), url: `${web}/p/${project.key}` }) }); } return true; } onAnswer(onSharedAnswer); 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(m("Своей подписки ещё нет — подключите Claude или ChatGPT")); } else { if (kind !== "codex_login" && kind !== "claude_login" && !secret.trim()) throw new PeppaError(kind === "claude" ? m("Вставьте ключ подписки: выполните `claude setup-token` на своём компьютере и скопируйте результат") : m("Вставьте ключ OpenAI API")); // PEP-128: a sign-in of this user that failed earlier (timed out, refused) is dropped before // the new attempt, so the pool does not fill with dead entries. const provider = kind === "claude_login" || kind === "claude" ? "claude" : "codex"; if (pool) { const stale = (await poolSubscriptions(db, pool.id)).filter((s) => s.status === "auth_error" && s.provider === provider && s.createdBy === user.id); for (const s of stale) await removeSubscription(db, s.id); } 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: m("Подписки — {login}", { login: 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(m("Подписка не найдена")); 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, account?: string | null): Promise { const sub = await ownPendingSubscription(db, user, project, subscriptionId); if (sub.provider !== "claude") throw new PeppaError(m("Код нужен только для Claude")); await finishClaudeLogin(db, sub.id, code, account); } /** «Отмена» 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(m("Эта подписка уже подключена")); 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); } /** * PEP-107: «Убрать» — the user's own subscription leaves the project's pool and is deleted * (its login with it). Not while agents run on it; a lent one goes back via the superadmin. */ export async function removeOwnSubscription(db: Db, user: User, project: Project, subscriptionId: number): Promise { await requireOwner(db, user, project); const pool = await projectPool(db, project.id); const sub = pool ? (await listSubscriptions(db)).find((s) => s.id === subscriptionId && s.poolIds.includes(pool.id)) : undefined; if (!pool || !sub || (sub.createdBy !== user.id && !(await isSuperadmin(db, user)))) throw new PeppaError(m("Подписка не найдена")); if ((await listLoans(db)).some((l) => l.poolId === pool.id && l.subscriptionId === sub.id)) throw new PeppaError(m("Это запасная подписка суперадмина — она вернётся сама по сроку")); if (sub.activeSessions > 0) throw new PeppaError(m("На этой подписке сейчас работают агенты. Сначала остановите агентов или добавьте другую подписку")); await removeSubscription(db, sub.id); await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "removed", subscriptionId: sub.id, name: sub.name, poolId: pool.id } }); }