// One short non-interactive Claude call (`claude -p --output-format json`) on a Claude // subscription of the project's pool (PEP-67). Used by the incident triager (PEP-58) and the // reviewer agent (PEP-26); tests point `bin` at mock-triage / mock-reviewer. import { spawn } from "node:child_process"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { claudeTokenForProject, mayUseMachineLogin, type Project } from "@peppa/core"; import { projects, type Db } from "@peppa/db"; import { eq } from "drizzle-orm"; export interface ClaudePrintOptions { bin: string; model: string; prompt: string; timeoutMs: number; /** For error messages: "триажёр", "ревьюер". */ who: string; } export type ClaudePrintResult = { ok: true; text: string } | { ok: false; error: string }; /** Text answer from the CLI's JSON envelope (or the raw output when it isn't one); null on an error envelope. */ export function envelopeText(stdout: string): string | null { const text = stdout.trim(); try { const env = JSON.parse(text) as { result?: unknown; is_error?: boolean }; if (env && typeof env === "object" && "result" in env) return env.is_error ? null : String(env.result ?? ""); } catch {} return text; } export async function claudePrint(db: Db, project: Pick, o: ClaudePrintOptions): Promise { const token = await claudeTokenForProject(db, project).catch(() => null); // PEP-84: without a Claude subscription in the pool the CLI would run on this machine's own // login — fine for the platform's and allowlisted owners' projects, never for a self-registered one. if (!token) { const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, project.id)); if (!(await mayUseMachineLogin(db, p?.ownerId ?? null))) return { ok: false, error: `${o.who}: у проекта нет подписки Claude` }; } // An empty cwd: no project CLAUDE.md, MCP servers or hooks get pulled in. const cwd = mkdtempSync(join(tmpdir(), "peppa-print-")); try { const out = await new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => { const child = spawn(o.bin, ["-p", "--output-format", "json", "--max-turns", "1", "--model", o.model], { cwd, env: { ...process.env, ...(token ? { CLAUDE_CODE_OAUTH_TOKEN: token } : {}) }, stdio: ["pipe", "pipe", "pipe"], // Own process group: a timeout kills the CLI with whatever it spawned. detached: true, }); let stdout = ""; let stderr = ""; const timer = setTimeout(() => { try { process.kill(-child.pid!, "SIGKILL"); } catch { child.kill("SIGKILL"); } child.stdout.destroy(); child.stderr.destroy(); reject(new Error(`${o.who} не ответил за ${Math.round(o.timeoutMs / 1000)} с`)); }, o.timeoutMs); child.stdout.on("data", (d) => (stdout += d)); child.stderr.on("data", (d) => (stderr += d)); child.on("error", (e) => (clearTimeout(timer), reject(e))); child.on("close", (code) => (clearTimeout(timer), resolve({ code, stdout, stderr }))); child.stdin.on("error", () => {}); // the CLI may exit before reading a large prompt child.stdin.end(o.prompt); }); if (out.code !== 0) return { ok: false, error: `${o.who} завершился с кодом ${out.code}: ${out.stderr.trim().slice(0, 200)}` }; const text = envelopeText(out.stdout); return text === null ? { ok: false, error: `${o.who} ответил ошибкой` } : { ok: true, text }; } catch (e) { return { ok: false, error: (e as Error).message }; } finally { rmSync(cwd, { recursive: true, force: true }); } }