// Agent subscriptions on this machine (PEP-67): the environment an agent CLI gets for a // subscription, and «Проверить» — a short trial run that updates the subscription's status. import { m } from "@peppa/shared/i18n"; import { spawn } from "node:child_process"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createSubscription, getSubscription, OPENCODE_KEY_ENV, PeppaError, subscriptionSecret, updateSubscription, type Subscription, getPool, listSubscriptions, poolSubscriptions, updatePool, getUser } from "@peppa/core"; import type { Db } from "@peppa/db"; import { parseResetTime } from "./limits.ts"; import { codexHome, mask, removeSubscription, setClaudeSubscriptionToken, setCodexApiKey, startClaudeLogin, startCodexLogin } from "./subscription-login.ts"; /** Environment for the agent CLI running on this subscription. */ export function subscriptionEnv(s: Subscription): Record { switch (s.provider) { case "claude": { const token = subscriptionSecret(s); return token ? { CLAUDE_CODE_OAUTH_TOKEN: token } : {}; } case "codex": return { CODEX_HOME: codexHome(s.id) }; case "opencode": { const key = subscriptionSecret(s); const env = s.keyProvider ? OPENCODE_KEY_ENV[s.keyProvider] : undefined; return key && env ? { [env]: key } : {}; } } } export interface NewSubscription { provider: Subscription["provider"]; name: string; /** claude: "login" (setup-token) | "token"; codex: "device" | "api_key"; opencode: key. */ method: string; secret?: string; keyProvider?: string; createdBy: number; } /** * Adds a subscription the way the superadmin chose: Claude/Codex sign-in starts right away * (the page then shows the link), a pasted token or key makes it active at once. */ export async function addSubscription(db: Db, n: NewSubscription): Promise { if (n.provider === "opencode") { if (!n.secret?.trim()) throw new PeppaError(m("Вставьте ключ доступа")); const s = await createSubscription(db, { provider: "opencode", name: n.name, authKind: "api_key", secret: n.secret.trim(), keyProvider: n.keyProvider, createdBy: n.createdBy }); return updateSubscription(db, s.id, { status: "active" }); } const authKind = n.method === "api_key" ? "api_key" : n.method === "device" ? "device" : "oauth"; const s = await createSubscription(db, { provider: n.provider, name: n.name, authKind, createdBy: n.createdBy }); try { if (n.provider === "claude" && n.method === "token") await setClaudeSubscriptionToken(db, s.id, n.secret ?? ""); else if (n.provider === "claude") await startClaudeLogin(db, s.id); else if (n.method === "api_key") await setCodexApiKey(db, s.id, n.secret ?? ""); else await startCodexLogin(db, s.id); } catch (e) { await removeSubscription(db, s.id); throw e; } return getSubscription(db, s.id); } /** * PEP-164: «Добавить ещё Claude / ChatGPT» in a pool — a new subscription that is already a member * of the pool and waits for its sign-in (link, then the code for Claude). Two or more working * subscriptions of a provider in a pool are what lets a runner move on when one hits its limit. */ export async function addPoolSubscription(db: Db, o: { poolId: number; provider: "claude" | "codex"; createdBy: number }): Promise { const pool = await getPool(db, o.poolId); const members = await poolSubscriptions(db, pool.id); const label = o.provider === "claude" ? "Claude" : "ChatGPT"; const taken = new Set((await listSubscriptions(db)).map((x) => x.name)); let n = members.filter((x) => x.provider === o.provider).length + 1; while (taken.has(`${label} ${n} — ${pool.name}`)) n++; // PEP-177: the name says whose it is — «Claude 2 — asel», not the pool's name. const who = (await getUser(db, o.createdBy).catch(() => null))?.login ?? pool.name; const s = await addSubscription(db, { provider: o.provider, name: `${label} ${n} — ${who}`, method: o.provider === "codex" ? "device" : "oauth", createdBy: o.createdBy }); await updatePool(db, pool.id, { subscriptionIds: [...members.map((m) => m.id), s.id] }); return s; } const LIMIT_RE = /(usage limit|rate limit|limit reached|hit your limit|limit will reset|quota exceeded|too many requests|\b429\b)/i; const PROBE_PROMPT = "Ответь одним словом: ok"; function probeArgs(s: Subscription): { bin: string; args: string[] } { switch (s.provider) { case "claude": return { bin: process.env.PEPPA_CLAUDE_BIN ?? "claude", args: ["-p", PROBE_PROMPT, "--max-turns", "1"] }; case "codex": return { bin: process.env.PEPPA_CODEX_BIN ?? "codex", args: ["exec", "--skip-git-repo-check", PROBE_PROMPT] }; case "opencode": return { bin: process.env.PEPPA_OPENCODE_BIN ?? "opencode", args: ["run", PROBE_PROMPT] }; } } export interface CheckResult { status: Subscription["status"]; message: string; } /** * «Проверить»: a short non-interactive run of the CLI on this subscription in an empty dir. * Exit 0 → active; a limit message → limited (until the reset time, else for an hour); * anything else → auth error with the CLI's last lines (secrets masked). */ export async function checkSubscription(db: Db, id: number, now = new Date()): Promise { const s = await getSubscription(db, id); if (s.status === "pending") throw new PeppaError(m("Сначала завершите вход")); const { bin, args } = probeArgs(s); const env = subscriptionEnv(s); const timeoutMs = Number(process.env.PEPPA_SUBSCRIPTION_CHECK_TIMEOUT_MS ?? 60_000); const cwd = mkdtempSync(join(tmpdir(), "peppa-sub-check-")); let out: { code: number | null; text: string }; try { out = await new Promise((resolve) => { const child = spawn(bin, args, { cwd, env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"], detached: true }); let text = ""; const timer = setTimeout(() => { try { process.kill(-child.pid!, "SIGKILL"); } catch { child.kill("SIGKILL"); } resolve({ code: null, text: `${text}\n${m("не ответил за {n} с", { n: Math.round(timeoutMs / 1000) })}` }); }, timeoutMs); child.stdout.on("data", (d) => (text += d)); child.stderr.on("data", (d) => (text += d)); child.on("error", (e) => (clearTimeout(timer), resolve({ code: 127, text: e.message }))); child.on("close", (code) => (clearTimeout(timer), resolve({ code, text }))); }); } finally { rmSync(cwd, { recursive: true, force: true }); } const text = mask(out.text, Object.values(env)).trim(); const tail = text.split("\n").filter(Boolean).slice(-2).join(" ").slice(0, 300); if (LIMIT_RE.test(out.text)) { const until = parseResetTime(out.text, now) ?? new Date(now.getTime() + 60 * 60_000); await updateSubscription(db, id, { status: "limited", limitedUntil: until, lastError: tail, checkedAt: now }); return { status: "limited", message: tail }; } if (out.code === 0) { await updateSubscription(db, id, { status: "active", checkedAt: now }); return { status: "active", message: tail }; } await updateSubscription(db, id, { status: "auth_error", lastError: tail || m("код {code}", { code: out.code }), checkedAt: now }); return { status: "auth_error", message: tail }; }