import assert from "node:assert/strict"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; import type { AgentConfig } from "../src/agents.ts"; import { ProcessRunner, type ProcessRunnerOptions } from "../src/runner.ts"; import type { DispatchDefaults, PreparedTask, RunOptions, RunResult } from "../src/types.ts"; const fixturePath = fileURLToPath(new URL("./fixtures/fake-pi.mjs", import.meta.url)); const stderrLimit = 64 * 1024; const baseAgent: AgentConfig = { name: "scout", description: "Test agent", systemPrompt: "Test prompt", source: "user", filePath: "/tmp/scout.md", }; function makeAgent(overrides: Partial = {}): AgentConfig { return { ...baseAgent, ...overrides }; } function makeTask(overrides: Partial = {}): PreparedTask { return { agent: makeAgent(), task: "do the thing", cwd: process.cwd(), ...overrides, }; } function makeRunner(env: NodeJS.ProcessEnv = {}, options: ProcessRunnerOptions = {}): ProcessRunner { return new ProcessRunner({ invocation: (args) => ({ command: process.execPath, args: [fixturePath, ...args] }), killGraceMs: 150, env: { ...process.env, ...env }, ...options, }); } function runOptions(overrides: Partial = {}): RunOptions { return { signal: new AbortController().signal, ...overrides }; } function delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } async function waitFor(condition: () => T | null | undefined | false, timeoutMs = 5000): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const value = condition(); if (value) return value; await delay(10); } throw new Error("Timed out waiting for condition"); } function processIsAlive(pid: number): boolean { try { process.kill(pid, 0); } catch { return false; } if (process.platform === "linux") { try { const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8"); const closeParen = stat.lastIndexOf(")"); if (stat.slice(closeParen + 2, closeParen + 3) === "Z") return false; } catch { // Fall through to the kill(0) result. } } return true; } test("collects message_end JSONL, ignores tool_result_end, aggregates usage and returns final output", async (t) => { const runner = makeRunner({ FAKE_PI_MODE: "success" }); const updates: RunResult[] = []; const result = await runner.run(makeTask(), {}, runOptions({ onUpdate: (partial) => updates.push(partial) })); assert.equal(result.exitCode, 0); assert.equal(result.terminationSignal, undefined); assert.equal(result.output, "final answer"); assert.equal(result.model, "fake-model"); assert.equal(result.stopReason, "stop"); assert.equal(result.stderr, ""); assert.equal(result.stderrTruncated, false); assert.deepEqual( result.messages.map((message) => message.role), ["assistant", "toolResult", "assistant"], ); const toolResult = result.messages[1]; assert.equal(toolResult.role, "toolResult"); if (toolResult.role === "toolResult") { assert.deepEqual(toolResult.content, [{ type: "text", text: "tool output" }]); } assert.equal(JSON.stringify(result.messages).includes("STALE"), false); assert.deepEqual(result.usage, { input: 30, output: 12, cacheRead: 5, cacheWrite: 3, cost: 1, contextTokens: 30, turns: 2, }); assert.ok(updates.length > 0); assert.equal( updates.some((partial) => partial.messages.some((message) => message.role === "toolResult")), true, ); t.diagnostic(`onUpdate calls: ${updates.length}`); }); test("preserves a nonzero exit and assistant error diagnostics", async () => { const runner = makeRunner({ FAKE_PI_MODE: "failure" }); const result = await runner.run(makeTask(), {}, runOptions()); assert.equal(result.exitCode, 7); assert.equal(result.output, ""); assert.equal(result.stderr, "diagnostic\n"); assert.equal(result.stopReason, "error"); assert.equal(result.errorMessage, "model exploded"); assert.equal(result.terminationSignal, undefined); }); test("reports spawn failures instead of throwing or synthesising success", async () => { let promptPath: string | undefined; const missing = path.join(os.tmpdir(), `pi-subagent-missing-${process.pid}-${Date.now()}`); const runner = new ProcessRunner({ invocation: (args) => { const promptIndex = args.indexOf("--append-system-prompt"); if (promptIndex >= 0) promptPath = args[promptIndex + 1]; return { command: missing, args }; }, killGraceMs: 100, env: process.env, }); const result = await runner.run(makeTask(), {}, runOptions()); assert.notEqual(result.exitCode, 0); assert.match(result.errorMessage ?? "", /ENOENT|not found|not recognized/i); assert.equal(result.output, ""); assert.equal(result.stderr, ""); assert.equal(result.terminationSignal, undefined); assert.ok(promptPath); assert.equal(fs.existsSync(promptPath), false); assert.equal(fs.existsSync(path.dirname(promptPath)), false); }); test("bounds stderr to a valid UTF-8 64 KiB tail", async () => { const runner = makeRunner({ FAKE_PI_MODE: "stderr" }); const result = await runner.run(makeTask(), {}, runOptions()); assert.equal(result.exitCode, 0); assert.equal(result.stderrTruncated, true); assert.ok(Buffer.byteLength(result.stderr, "utf8") <= stderrLimit); assert.equal(result.stderr.endsWith("STDERR-END"), true); assert.equal(result.stderr.includes("STDERR-START"), false); assert.equal(result.stderr.includes("\uFFFD"), false); assert.equal(Buffer.from(result.stderr, "utf8").toString("utf8"), result.stderr); }); test("child arguments exclude subagent and workflow tools and do not inherit thinking with an explicit model", async () => { let captured: string[] = []; let promptPath: string | undefined; let promptContent: string | undefined; const runner = makeRunner( { FAKE_PI_MODE: "success" }, { invocation: (args) => { captured = args; const promptIndex = args.indexOf("--append-system-prompt"); if (promptIndex >= 0) { promptPath = args[promptIndex + 1]; promptContent = fs.readFileSync(promptPath, "utf8"); } return { command: process.execPath, args: [fixturePath, ...args] }; }, }, ); const agent = makeAgent({ model: "agent-model", tools: ["read", "bash"], systemPrompt: "Prompt body", }); const defaults: DispatchDefaults = { model: "dispatch-model", thinkingLevel: "high" }; const result = await runner.run(makeTask({ agent, task: "do the thing" }), defaults, runOptions()); assert.equal(result.exitCode, 0); assert.deepEqual(captured.slice(0, 6), [ "--mode", "json", "-p", "--no-session", "--exclude-tools", "subagent*,workflow", ]); assert.equal(captured[captured.indexOf("--model") + 1], "agent-model"); assert.equal(captured.includes("--thinking"), false); assert.equal(captured[captured.indexOf("--tools") + 1], "read,bash"); const promptFile = promptPath; assert.ok(promptFile); assert.equal(promptContent, "Prompt body"); assert.equal(captured[captured.indexOf("--append-system-prompt") + 1], promptFile); assert.equal(captured.at(-1), "Task: do the thing"); assert.equal(fs.existsSync(promptFile), false); assert.equal(fs.existsSync(path.dirname(promptFile)), false); }); test("child arguments inherit the dispatch model and thinking only without an explicit model", async () => { let captured: string[] = []; const runner = makeRunner( { FAKE_PI_MODE: "success" }, { invocation: (args) => { captured = args; return { command: process.execPath, args: [fixturePath, ...args] }; }, }, ); const agent = makeAgent({ model: undefined, tools: undefined, systemPrompt: " " }); const defaults: DispatchDefaults = { model: "dispatch-model", thinkingLevel: "high" }; const result = await runner.run(makeTask({ agent }), defaults, runOptions()); assert.equal(result.exitCode, 0); assert.deepEqual(captured.slice(0, 6), [ "--mode", "json", "-p", "--no-session", "--exclude-tools", "subagent*,workflow", ]); assert.equal(captured[captured.indexOf("--model") + 1], "dispatch-model"); assert.equal(captured[captured.indexOf("--thinking") + 1], "high"); assert.equal(captured.includes("--tools"), false); assert.equal(captured.includes("--append-system-prompt"), false); assert.equal(captured.at(-1), "Task: do the thing"); }); test("child arguments omit optional model and thinking flags when nothing is configured", async () => { let captured: string[] = []; const runner = makeRunner( { FAKE_PI_MODE: "success" }, { invocation: (args) => { captured = args; return { command: process.execPath, args: [fixturePath, ...args] }; }, }, ); const result = await runner.run(makeTask({ agent: makeAgent({ model: undefined }) }), {}, runOptions()); assert.equal(result.exitCode, 0); assert.equal(captured.includes("--model"), false); assert.equal(captured.includes("--thinking"), false); assert.equal(captured.includes("--exclude-tools"), true); const excluded = captured[captured.indexOf("--exclude-tools") + 1].split(","); assert.ok(excluded.includes("subagent*"), "child cannot dispatch subagents"); assert.ok(excluded.includes("workflow"), "child cannot start workflow runs"); assert.equal(captured.at(-1), "Task: do the thing"); }); test( "abort reports the terminating signal instead of turning it into exit code 0", { skip: process.platform === "win32", timeout: 15000 }, async () => { const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-runner-term-")); const readyFile = path.join(dir, "ready"); try { const controller = new AbortController(); const runner = makeRunner( { FAKE_PI_MODE: "wait", FAKE_PI_READY_FILE: readyFile }, { killGraceMs: 500 }, ); const pending = runner.run(makeTask(), {}, { signal: controller.signal }); await waitFor(() => fs.existsSync(readyFile)); controller.abort(); const result = await pending; assert.equal(result.exitCode, null); assert.equal(result.terminationSignal, "SIGTERM"); assert.equal(result.stopReason, "aborted"); assert.match(result.errorMessage ?? "", /aborted/i); assert.equal(result.output, ""); } finally { await fs.promises.rm(dir, { recursive: true, force: true }); } }, ); test( "abort escalates SIGTERM to SIGKILL after the grace period and kills the process tree", { skip: process.platform === "win32", timeout: 15000 }, async () => { const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-runner-tree-")); const readyFile = path.join(dir, "ready"); const parentSignalFile = path.join(dir, "parent-signals"); const childReadyFile = path.join(dir, "child-ready"); const childSignalFile = path.join(dir, "child-signals"); const childPidFile = path.join(dir, "child-pid"); const pids: number[] = []; try { const controller = new AbortController(); const killGraceMs = 250; const runner = makeRunner( { FAKE_PI_MODE: "tree-term", FAKE_PI_READY_FILE: readyFile, FAKE_PI_PARENT_SIGNAL_FILE: parentSignalFile, FAKE_PI_CHILD_READY_FILE: childReadyFile, FAKE_PI_CHILD_SIGNAL_FILE: childSignalFile, FAKE_PI_CHILD_PID_FILE: childPidFile, }, { killGraceMs }, ); const pending = runner.run(makeTask(), {}, { signal: controller.signal }); const ready = await waitFor(() => { try { const parsed = JSON.parse(fs.readFileSync(readyFile, "utf8")) as { parentPid: number; childPid: number; }; return parsed.parentPid && parsed.childPid ? parsed : null; } catch { return null; } }); pids.push(ready.parentPid, ready.childPid); const abortedAt = Date.now(); controller.abort(); const result = await pending; const elapsed = Date.now() - abortedAt; assert.equal(result.exitCode, null); assert.equal(result.terminationSignal, "SIGKILL"); assert.equal(result.stopReason, "aborted"); assert.ok( elapsed >= killGraceMs * 0.7, `expected SIGKILL after the grace period, got completion after ${elapsed}ms`, ); assert.match(fs.readFileSync(parentSignalFile, "utf8"), /SIGTERM/); assert.match(fs.readFileSync(childSignalFile, "utf8"), /SIGTERM/); assert.equal(fs.readFileSync(childPidFile, "utf8"), String(ready.childPid)); await waitFor(() => pids.every((pid) => !processIsAlive(pid))); } finally { for (const pid of pids) { try { process.kill(pid, "SIGKILL"); } catch { // Already gone. } } await fs.promises.rm(dir, { recursive: true, force: true }); } }, ); test("a step model overrides the agent and dispatch model without inheriting thinking", async () => { let captured: string[] = []; const runner = makeRunner( { FAKE_PI_MODE: "success" }, { invocation: (args) => { captured = args; return { command: process.execPath, args: [fixturePath, ...args] }; }, }, ); const agent = makeAgent({ model: "agent-model" }); const defaults: DispatchDefaults = { model: "dispatch-model", thinkingLevel: "high" }; const result = await runner.run(makeTask({ agent, model: "step-model", stepId: "scan" }), defaults, runOptions()); assert.equal(result.exitCode, 0); assert.equal(captured[captured.indexOf("--model") + 1], "step-model"); assert.equal(captured.includes("--thinking"), false); assert.equal(result.model, "step-model"); assert.equal(result.stepId, "scan"); });