Files
crosscode-platform/apps/agent/src/runner.ts
T
joshuaandClaude Opus 5.5 8542d19be0 Agent 1.4.0 + contracts 1.15.0: frp config anywhere, edited from the Hub; ports probed before installs
- The agent finds frps/frpc's config (Hub path, systemd -c, usual places) and reads INI and TOML.
- New jobs frp-read, frp-write (secrets kept on the server, verify, backup, restart, roll back)
  and probe-ports (which ports are free here), on central and church servers.
- Stats report frpConfigPath; crosscode gets FRPC_INI on church servers.
- Website plan versions move up to contracts 1.16.0 and Hub 2.12.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:07:50 +02:00

119 lines
4.6 KiB
TypeScript

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<string, unknown>;
message?: string;
log: string[];
startedAt: string;
finishedAt: string;
}
export interface RunOptions {
args: string[];
sealedConfig?: agent.Sealed | null;
x25519Pem: string;
timeLimitMinutes: number;
/** Extra environment for crosscode (FRPC_INI). */
env?: Record<string, string>;
/** 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<RunResult> {
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<RunResult>((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, ...opts.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;
}