import { closeSync, readFileSync } from "node:fs"; import { readFile } from "node:fs/promises"; import { join, resolve } from "node:path"; import type { Credential } from "@earendil-works/pi-ai"; import { runCanary } from "./canary.ts"; import { CASES, credentialRuntime, DEFAULT_MODEL, EvalBlocker, INPUT_HASH, liveRuntime, rootPath, sandbox, setup, snapshot, type Thinking, trial, type Variant, } from "./harness.ts"; import { isolatedCanary } from "./native-process.ts"; import { verifyCanaryQueries } from "./verify-query.ts"; const [command, ...args] = process.argv.slice(2); try { if (command === "capture") { process.stdout.write( `${await setup( args[0] ? resolve(args[0]) : undefined, args[1] ?? DEFAULT_MODEL, )}\n`, ); } else if (command === "candidate") { const root = rootPath(args[0] ?? ""); if (!args[1]) throw new Error("Candidate source directory required"); await snapshot(root, "candidate", resolve(args[1])); process.stdout.write(`${join(root, "candidate.json")}\n`); } else if (command === "selection") { const root = rootPath(args[0] ?? ""); const authPath = args[1]; if (!authPath) throw new Error("Explicit real auth path required"); const repeats = Number(args[2] ?? 1); if (!Number.isInteger(repeats) || repeats < 1 || repeats > 10) throw new Error("Repeat count must be 1..10"); const variants = (args[3] ?? "baseline").split(","); if (variants.some((v) => v !== "baseline" && v !== "candidate")) throw new Error("Variants: baseline,candidate"); const thinking = args[4] ?? "low"; const requested = args[5]?.split(","); const cases = requested ? CASES.filter((scenario) => requested.includes(scenario.id)) : CASES.filter((scenario) => scenario.id !== "held-out-query"); if ( !cases.length || requested?.some((id) => !CASES.some((scenario) => scenario.id === id)) ) throw new Error("Unknown evaluation case"); if ( !["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes( thinking, ) ) throw new Error("Invalid thinking level"); const manifest = JSON.parse( await readFile(join(root, "manifest.json"), "utf8"), ); if (manifest.inputHash !== INPUT_HASH) throw new EvalBlocker( "BLOCKER: fixed scenario/fixture inputs changed since capture", ); const restore = await sandbox(root); // Hard backstop beyond per-trial SDK abort, with no raw error/provider output. const watchdog = setTimeout( () => { process.stderr.write( "BLOCKER: evaluation exceeded hard deadline; unfinished\n", ); process.exit(2); }, repeats * variants.length * cases.length * 125_000, ); try { const runtime = await liveRuntime(manifest.model.split("/")[0], authPath); for (let repeat = 0; repeat < repeats; repeat++) for (const scenario of cases) for (const variant of variants) { const hardStop = setTimeout(() => { process.stderr.write( "BLOCKER: trial exceeded 125s; status.json remains unfinished\n", ); process.exit(2); }, 125_000); try { process.stdout.write( `${JSON.stringify( await trial( root, variant as Variant, scenario, repeat, runtime, manifest.model, thinking as Thinking, ), )}\n`, ); } finally { clearTimeout(hardStop); } } } finally { clearTimeout(watchdog); restore(); } } else if (command === "verify-query") { if (!args[0] || !args[1]) throw new Error("Root and trial required"); process.stdout.write( `${JSON.stringify(await verifyCanaryQueries(args[0], args[1]))}\n`, ); } else if (command === "canary") { if (!args[0] || !args[1] || !args[2]) throw new Error("Root, captured trial and auth path required"); await isolatedCanary(args[0], args[1], args[2]); } else if (command === "canary-child") { if (!args[0] || !args[1] || !args[2]) throw new Error("Child inputs missing"); const credential = JSON.parse(readFileSync(0, "utf8")) as Credential; closeSync(0); const runtime = await credentialRuntime(args[2], credential); const report = await runCanary(args[0], args[1], { runtime }); process.stdout.write( `${JSON.stringify({ status: report["status"], requests: report["requests"], phaseCounts: report["phaseCounts"], toolNameCounts: report["toolNameCounts"], consumerCallsCompleted: report["consumerCallsCompleted"], reportPath: join(resolve(args[1]), "canary.json"), })}\n`, ); } else throw new Error("Expected capture | candidate | selection | canary"); } catch (error) { // SDK/provider failures can embed credentials or raw response bodies. process.stderr.write( `${ error instanceof EvalBlocker ? error.message : "BLOCKER: evaluation failed; check arguments, static model availability, credential validity, and package loadability. No credential refresh or write fallback attempted." }\n`, ); process.exitCode = 1; }