peppa/packages/runner/src/claude-print.ts
2026-11-16 21:25:21 +05:00

91 lines
4.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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 { m } from "@peppa/shared/i18n";
import { spawn } from "node:child_process";
import { copyFileSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { claudeTokenForProject, isProjectPaused, 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;
/**
* PEP-112: files copied into the (otherwise empty) working directory under these names; the
* CLI then may read them (`Read` only, a few turns) — screenshots for the product agent.
*/
files?: Array<{ name: string; path: 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<Project, "id">, o: ClaudePrintOptions): Promise<ClaudePrintResult> {
// PEP-174: a project on pause spends nothing — the roles' ticks skip it; this is the last guard.
if (await isProjectPaused(db, project.id)) return { ok: false, error: m("{who}: проект на паузе", { who: o.who }) };
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: m("{who}: у проекта нет подписки Claude", { who: o.who }) };
}
// An empty cwd: no project CLAUDE.md, MCP servers or hooks get pulled in.
const cwd = mkdtempSync(join(tmpdir(), "peppa-print-"));
try {
const files = (o.files ?? []).filter((f) => /^[\w.-]+$/.test(f.name));
for (const f of files) copyFileSync(f.path, join(cwd, f.name));
const turns = files.length ? ["--max-turns", String(files.length + 2), "--allowedTools", "Read"] : ["--max-turns", "1"];
const out = await new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
const child = spawn(o.bin, ["-p", "--output-format", "json", ...turns, "--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(m("{who} не ответил за {n} с", { who: o.who, n: 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: m("{who} завершился с кодом {code}: {error}", { who: o.who, code: out.code, error: out.stderr.trim().slice(0, 200) }) };
const text = envelopeText(out.stdout);
return text === null ? { ok: false, error: m("{who} ответил ошибкой", { who: o.who }) } : { ok: true, text };
} catch (e) {
return { ok: false, error: (e as Error).message };
} finally {
rmSync(cwd, { recursive: true, force: true });
}
}