import { spawn } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; import { agent } from "@crosscode/contracts"; import { openConfig } from "@crosscode/contracts/signing"; import { paths } from "./paths"; import { LogTail, redact } from "./redact"; /** * Runs `crosscode … --json` for a job: argument array (no shell), the job's config opened to a * file only root can read and removed as soon as the job ends, a time limit per type (the whole * process group is stopped past it), and the last 200 log lines, redacted. */ export interface RunResult { status: agent.JobStatus; steps: agent.ReportStep[]; result: Record; message?: string; log: string[]; startedAt: string; finishedAt: string; } export interface RunOptions { args: string[]; sealedConfig?: agent.Sealed | null; x25519Pem: string; timeLimitMinutes: number; /** For tests. */ bin?: string; } const iso = (d = new Date()) => d.toISOString(); function writeConfig(sealed: agent.Sealed, x25519Pem: string): string { const opened = agent.jobConfigSchema.parse(openConfig(sealed, x25519Pem)); fs.mkdirSync(paths.runDir, { recursive: true, mode: 0o700 }); const file = path.join(paths.runDir, `config-${process.pid}-${Date.now()}.json`); fs.writeFileSync(file, JSON.stringify(opened), { mode: 0o600 }); return file; } export async function runCrosscode(opts: RunOptions): Promise { const startedAt = iso(); let configFile: string | null = null; try { if (opts.sealedConfig) { try { configFile = writeConfig(opts.sealedConfig, opts.x25519Pem); } catch (e) { return { status: "refused", steps: [], result: {}, message: `The job's config couldn't be opened with this server's key: ${(e as Error).message}`, log: [], startedAt, finishedAt: iso() }; } } const args = [...opts.args, "--json", ...(configFile ? ["--config", configFile] : [])]; return await new Promise((resolve) => { const tail = new LogTail(200); let stdout = ""; const child = spawn(opts.bin ?? paths.crosscode, args, { detached: true, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" }, }); let timedOut = false; const timer = setTimeout(() => { timedOut = true; try { process.kill(-child.pid!, "SIGTERM"); } catch { /* already gone */ } setTimeout(() => { try { process.kill(-child.pid!, "SIGKILL"); } catch { /* gone */ } }, 10_000).unref(); }, opts.timeLimitMinutes * 60_000); child.stdout.setEncoding("utf8").on("data", (d: string) => { stdout += d; if (stdout.length > 5_000_000) stdout = stdout.slice(-1_000_000); }); child.stderr.setEncoding("utf8").on("data", (d: string) => tail.push(d)); child.on("error", (e) => { clearTimeout(timer); resolve({ status: "failed", steps: [], result: {}, message: `crosscode couldn't be started: ${e.message}`, log: tail.end(), startedAt, finishedAt: iso() }); }); child.on("close", (code) => { clearTimeout(timer); const log = tail.end(); const report = parseReport(stdout); if (timedOut) { resolve({ status: "failed", steps: report?.steps ?? [], result: report?.result ?? {}, message: `Stopped after the time limit (${opts.timeLimitMinutes} minutes).`, log, startedAt, finishedAt: iso() }); return; } if (!report) { resolve({ status: code === 0 ? "succeeded" : "failed", steps: [], result: {}, message: code === 0 ? undefined : `crosscode ended with code ${code} without a report.`, log, startedAt, finishedAt: iso() }); return; } resolve({ status: report.status, steps: report.steps, result: report.result, message: report.message ? redact(report.message) : undefined, log, startedAt: report.startedAt, finishedAt: report.finishedAt, }); }); }); } finally { if (configFile) fs.rmSync(configFile, { force: true }); } } /** The last line of stdout that's a valid script report. */ export function parseReport(stdout: string): agent.ScriptReport | null { const lines = stdout.trim().split("\n").reverse(); for (const line of lines) { try { const parsed = agent.scriptReportSchema.safeParse(JSON.parse(line)); if (parsed.success) return parsed.data; } catch { // not JSON } } return null; }