import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { readFile } from "node:fs/promises"; import { join } from "node:path"; const TRUNCATION_SUFFIX = "…[truncated]"; const MAX_EVIDENCE_BYTES = 8 * 1024; const MAX_RESPONSE_BYTES = 64 * 1024; const MAX_CHECKER_INPUT_BYTES = 1024 * 1024; const MAX_STREAM_BYTES = 64 * 1024; const TERMINATION_GRACE_MS = 100; export const REQUIRED_SUITE_FILES = [ "check.mjs", "test/items.json", "train/items.json", "val/items.json", ] as const; export type RequiredSuiteFile = (typeof REQUIRED_SUITE_FILES)[number]; export type ToolEvidence = { name: string; input: unknown; outputText: string; isError: boolean; }; export type CheckerInputOptions = { item: Record; response: string; assistantTexts: readonly string[]; toolCalls: readonly ToolEvidence[]; }; export type CheckerResult = { score: number; passed: boolean; feedback?: string; checks?: Array<{ type: string; passed: boolean }>; }; export class CheckerInfrastructureError extends Error {} export function canonicalJson(value: unknown): string { if (value === null || typeof value === "string" || typeof value === "boolean") return JSON.stringify(value); if (typeof value === "number") { if (!Number.isFinite(value)) throw new Error("canonical JSON requires finite numbers"); return JSON.stringify(value); } if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; if (typeof value === "object") { const object = value as Record; return `{${Object.keys(object) .sort() .map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`) .join(",")}}`; } throw new Error("canonical JSON only supports JSON values"); } export function truncateUtf8(value: string, maximumBytes: number): string { if (Buffer.byteLength(value, "utf8") <= maximumBytes) return value; const suffixBytes = Buffer.byteLength(TRUNCATION_SUFFIX, "utf8"); if (maximumBytes <= suffixBytes) return TRUNCATION_SUFFIX; let result = ""; let size = 0; for (const character of value) { const characterBytes = Buffer.byteLength(character, "utf8"); if (size + characterBytes + suffixBytes > maximumBytes) break; result += character; size += characterBytes; } return result + TRUNCATION_SUFFIX; } function boundedInput( options: CheckerInputOptions, assistantTexts: string[], toolCalls: ToolEvidence[], ): Record { const calls = toolCalls.map((call) => ({ name: call.name, inputJson: truncateUtf8(canonicalJson(call.input), MAX_EVIDENCE_BYTES), outputText: truncateUtf8(call.outputText, MAX_EVIDENCE_BYTES), isError: call.isError, })); return { item: options.item, response: truncateUtf8(options.response, MAX_RESPONSE_BYTES), trajectory: { assistantTexts: assistantTexts.map((text) => truncateUtf8(text, MAX_EVIDENCE_BYTES), ), toolCalls: calls, }, calledTools: calls.map((call) => call.name), }; } export function buildCheckerInput(options: CheckerInputOptions): string { const assistantTexts = options.assistantTexts.slice(-64); const toolCalls = options.toolCalls.slice(-64); let value = boundedInput(options, assistantTexts, toolCalls); let serialized = canonicalJson(value); while ( Buffer.byteLength(serialized, "utf8") > MAX_CHECKER_INPUT_BYTES && assistantTexts.length > 1 ) { assistantTexts.shift(); value = boundedInput(options, assistantTexts, toolCalls); serialized = canonicalJson(value); } while ( Buffer.byteLength(serialized, "utf8") > MAX_CHECKER_INPUT_BYTES && toolCalls.length > 0 ) { toolCalls.shift(); value = boundedInput(options, assistantTexts, toolCalls); serialized = canonicalJson(value); } if (Buffer.byteLength(serialized, "utf8") > MAX_CHECKER_INPUT_BYTES) { throw new CheckerInfrastructureError("bounded checker input exceeds 1 MiB"); } return serialized; } export function fingerprintSource(source: Buffer): string { return createHash("sha256").update(source).digest("hex"); } export function fingerprintSuiteBytes( files: ReadonlyMap, ): string { const hash = createHash("sha256"); for (const file of REQUIRED_SUITE_FILES) { const bytes = files.get(file); if (!bytes) throw new Error(`suite snapshot is missing ${file}`); hash .update(file) .update(Buffer.from([0])) .update(bytes) .update(Buffer.from([0])); } return hash.digest("hex"); } export async function fingerprintSuite(suitePath: string): Promise { const files = new Map(); for (const file of REQUIRED_SUITE_FILES) files.set(file, await readFile(join(suitePath, file))); return fingerprintSuiteBytes(files); } function parseCheckerResult(stdout: Buffer): CheckerResult { let output: unknown; try { output = JSON.parse(stdout.toString("utf8").trim()); } catch { throw new CheckerInfrastructureError( "checker stdout must be exactly one JSON object", ); } if (typeof output !== "object" || output === null || Array.isArray(output)) { throw new CheckerInfrastructureError( "checker stdout must be a JSON object", ); } const record = output as Record; for (const key of Object.keys(record)) { if (key !== "score" && key !== "passed" && key !== "feedback") throw new CheckerInfrastructureError( "checker stdout contains unknown fields", ); } if ( typeof record.score !== "number" || !Number.isFinite(record.score) || record.score < 0 || record.score > 1 ) { throw new CheckerInfrastructureError( "checker score must be finite and in [0, 1]", ); } if (typeof record.passed !== "boolean") throw new CheckerInfrastructureError("checker passed must be Boolean"); if ( record.feedback !== undefined && (typeof record.feedback !== "string" || Buffer.byteLength(record.feedback, "utf8") > MAX_EVIDENCE_BYTES) ) { throw new CheckerInfrastructureError( "checker feedback must be a string no larger than 8 KiB", ); } return record.feedback === undefined ? { score: record.score, passed: record.passed } : { score: record.score, passed: record.passed, feedback: record.feedback as string, }; } export async function executeChecker(options: { checkerPath: string; suitePath: string; input: string; expectedSuiteFingerprint?: string; timeoutMs?: number; signal?: AbortSignal; }): Promise { if (options.signal?.aborted) throw new CheckerInfrastructureError("checker cancelled"); const revalidateSuite = async () => { if ( options.expectedSuiteFingerprint !== undefined && (await fingerprintSuite(options.suitePath)) !== options.expectedSuiteFingerprint ) throw new CheckerInfrastructureError("suite fingerprint changed"); }; await revalidateSuite(); try { return await new Promise((resolve, reject) => { let child: ChildProcessWithoutNullStreams; try { child = spawn(process.execPath, [options.checkerPath], { cwd: options.suitePath, env: process.env, stdio: ["pipe", "pipe", "pipe"], // A checker can spawn descendants retaining stdio; isolate its process // group so timeout/cancellation remains bounded. detached: process.platform !== "win32", }); } catch (error) { reject( new CheckerInfrastructureError( `checker spawn failed: ${String(error)}`, ), ); return; } let settled = false; let terminationError: CheckerInfrastructureError | undefined; let terminationTimer: ReturnType | undefined; const stdout: Buffer[] = []; const stderr: Buffer[] = []; let stdoutBytes = 0; let stderrBytes = 0; const finish = (error?: Error, result?: CheckerResult) => { if (settled) return; settled = true; clearTimeout(timeout); if (terminationTimer) clearTimeout(terminationTimer); options.signal?.removeEventListener("abort", cancel); if (error) { reject(error); return; } if (!result) { reject( new CheckerInfrastructureError("checker ended without a result"), ); return; } resolve(result); }; const killGroup = (signal: NodeJS.Signals) => { if (process.platform !== "win32" && child.pid !== undefined) { try { process.kill(-child.pid, signal); return; } catch { // The child may have already exited; the direct fallback is safe. } } if (!child.killed) child.kill(signal); }; const stop = (error: CheckerInfrastructureError) => { if (settled || terminationError) return; terminationError = error; killGroup("SIGTERM"); terminationTimer = setTimeout(() => { if (settled) return; killGroup("SIGKILL"); // Descendants can retain inherited pipes after the parent exits, so // never wait indefinitely for the child's close event. finish(terminationError); }, TERMINATION_GRACE_MS); }; const cancel = () => stop(new CheckerInfrastructureError("checker cancelled")); const timeout = setTimeout( () => stop(new CheckerInfrastructureError("checker timed out")), options.timeoutMs ?? 10_000, ); options.signal?.addEventListener("abort", cancel, { once: true }); child.stdout.on("data", (chunk: Buffer) => { stdoutBytes += chunk.byteLength; if (stdoutBytes > MAX_STREAM_BYTES) { stop(new CheckerInfrastructureError("checker stdout cap exceeded")); return; } stdout.push(chunk); }); child.stderr.on("data", (chunk: Buffer) => { stderrBytes += chunk.byteLength; if (stderrBytes > MAX_STREAM_BYTES) { stop(new CheckerInfrastructureError("checker stderr cap exceeded")); return; } stderr.push(chunk); }); child.once("error", (error) => finish( new CheckerInfrastructureError( `checker spawn failed: ${error.message}`, ), ), ); child.once("close", (code) => { if (settled) return; if (terminationError) { finish(terminationError); return; } if (code !== 0) { finish( new CheckerInfrastructureError( `checker exited with code ${code ?? "unknown"}`, ), ); return; } try { finish(undefined, parseCheckerResult(Buffer.concat(stdout))); } catch (error) { finish( error instanceof Error ? error : new CheckerInfrastructureError(String(error)), ); } }); child.stdin.once("error", (error) => stop( new CheckerInfrastructureError( `checker stdin failed: ${error.message}`, ), ), ); try { child.stdin.end(`${options.input}\n`); } catch (error) { stop( new CheckerInfrastructureError( `checker stdin failed: ${error instanceof Error ? error.message : String(error)}`, ), ); } }); } finally { await revalidateSuite(); } }