@maxiaochao/pi-background-tasks 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,55 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { BackgroundTasks } from "../src/background-tasks.ts";
5
+
6
+ export class FakeClock {
7
+ time = 1000;
8
+ next = 0;
9
+ timers = new Map();
10
+ now = () => this.time;
11
+ setTimeout = (callback, delay) => {
12
+ const id = ++this.next;
13
+ this.timers.set(id, { at: this.time + delay, callback });
14
+ return id;
15
+ };
16
+ clearTimeout = (id) => this.timers.delete(id);
17
+ advance(ms) {
18
+ const target = this.time + ms;
19
+ for (;;) {
20
+ const due = [...this.timers].filter(([, t]) => t.at <= target).sort((a, b) => a[1].at - b[1].at)[0];
21
+ if (!due) break;
22
+ this.time = due[1].at;
23
+ this.timers.delete(due[0]);
24
+ due[1].callback();
25
+ }
26
+ this.time = target;
27
+ }
28
+ }
29
+
30
+ export function fixture(options = {}) {
31
+ const root = mkdtempSync(join(tmpdir(), "pi-bg-test-"));
32
+ const clock = new FakeClock();
33
+ const calls = [];
34
+ const completed = [];
35
+ const operations = {
36
+ exec(command, cwd, opts) {
37
+ return new Promise((resolve, reject) => {
38
+ calls.push({ command, cwd, ...opts, resolve: (exitCode = 0) => resolve({ exitCode }), reject });
39
+ });
40
+ },
41
+ };
42
+ const tasks = new BackgroundTasks({ operations, clock, logRoot: root, onComplete: (task) => completed.push(task), ...options });
43
+ return {
44
+ root, clock, calls, completed, tasks, operations,
45
+ async close() {
46
+ for (const call of calls) call.resolve();
47
+ await tasks.shutdown();
48
+ rmSync(root, { recursive: true, force: true });
49
+ },
50
+ };
51
+ }
52
+
53
+ export async function flush() {
54
+ for (let i = 0; i < 8; i++) await Promise.resolve();
55
+ }
@@ -0,0 +1,140 @@
1
+ import assert from "node:assert/strict";
2
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { test } from "node:test";
7
+ import { pathToFileURL } from "node:url";
8
+ import "./runtime.mjs";
9
+
10
+ const { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } = await import("@earendil-works/pi-coding-agent");
11
+ const { createAssistantMessageEventStream } = await import("@earendil-works/pi-ai");
12
+ const { Type } = await import("typebox");
13
+ const { default: register } = await import(process.env.BG_TEST_EXTENSION
14
+ ? pathToFileURL(process.env.BG_TEST_EXTENSION).href : new URL("../extensions/background-tasks.ts", import.meta.url).href);
15
+
16
+ for (const timing of ["before interrupt", "after interrupt", "after active compaction"]) {
17
+ test(`real Pi completion ${timing} stays stopped until the next user prompt, then delivers once`, { timeout: 20000 }, async (t) => {
18
+ const directory = mkdtempSync(join(tmpdir(), "pi-bg-interrupt-"));
19
+ const release = join(directory, "release");
20
+ const exited = join(directory, "exited");
21
+ const requests = [], settlements = [], errors = [];
22
+ let session, task, output, holding = false, summaries = 0;
23
+ const waitFor = async (check, label) => {
24
+ for (let i = 0; i < 1000; i++) {
25
+ if (check()) return;
26
+ await delay(10);
27
+ }
28
+ throw new Error(`Timed out waiting for ${label}`);
29
+ };
30
+ try {
31
+ const modelRuntime = await ModelRuntime.create({ authPath: join(directory, "auth.json"), modelsPath: join(directory, "models.json"), refreshOnCreate: false });
32
+ modelRuntime.registerProvider("bg-interrupt", {
33
+ name: "Offline interrupt fixture", baseUrl: "http://127.0.0.1:1", api: "bg-interrupt", apiKey: "fixture-not-a-secret",
34
+ models: [{ id: "deterministic", name: "Offline fixture", reasoning: false, input: ["text"], contextWindow: 128000, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
35
+ streamSimple(model, context) {
36
+ const compacting = session.isCompacting;
37
+ if (compacting) summaries++;
38
+ else requests.push(context.messages);
39
+ const stream = createAssistantMessageEventStream();
40
+ queueMicrotask(() => {
41
+ const message = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: "toolUse",
42
+ usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
43
+ if (compacting) {
44
+ message.stopReason = "stop";
45
+ message.content.push({ type: "text", text: "## Goal\nKeep the interrupted agent stopped. A shell job remains owned by this session." });
46
+ } else if (requests.length === 1) message.content.push({ type: "toolCall", id: "start-job", name: "background_task", arguments: {
47
+ action: "start", command: "while [ ! -f release ]; do sleep 0.01; done; printf 'late shell result\\n'; printf done > exited; exit 7", timeout: 10,
48
+ } });
49
+ else if (requests.length === 2) message.content.push({ type: "toolCall", id: "hold-turn", name: "interrupt_fixture", arguments: {} });
50
+ else if (requests.length === 3) message.content.push({ type: "toolCall", id: "read-result", name: "background_task", arguments: { action: "output", id: task.id } });
51
+ else {
52
+ message.stopReason = "stop";
53
+ message.content.push({ type: "text", text: "RESUMED_RESULT_ACK" });
54
+ }
55
+ stream.push({ type: "start", partial: message });
56
+ stream.push({ type: "done", reason: message.stopReason, message });
57
+ });
58
+ return stream;
59
+ },
60
+ });
61
+ const settingsManager = SettingsManager.inMemory({ compaction: { enabled: false, keepRecentTokens: 128 }, retry: { enabled: false }, cacheWarming: "off" });
62
+ const resourceLoader = new DefaultResourceLoader({
63
+ cwd: directory, agentDir: directory, settingsManager,
64
+ noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
65
+ extensionFactories: [register, (pi) => {
66
+ pi.on("agent_settled", (event) => { settlements.push(event.aborted); });
67
+ pi.registerTool({
68
+ name: "interrupt_fixture", label: "Interrupt fixture", description: "Hold a real tool until the user interrupts the agent.",
69
+ parameters: Type.Object({}),
70
+ async execute(_id, _params, signal) {
71
+ holding = true;
72
+ assert.ok(signal);
73
+ if (!signal.aborted) await new Promise((resolve) => signal.addEventListener("abort", resolve, { once: true }));
74
+ return { content: [{ type: "text", text: "User interrupted the held tool." }], details: undefined };
75
+ },
76
+ });
77
+ }],
78
+ });
79
+ await resourceLoader.reload();
80
+ const created = await createAgentSession({ cwd: directory, agentDir: directory, modelRuntime, model: modelRuntime.getModel("bg-interrupt", "deterministic"), thinkingLevel: "off", resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(directory), tools: ["background_task", "interrupt_fixture"] });
81
+ session = created.session;
82
+ assert.deepEqual(created.extensionsResult.errors, []);
83
+ session.extensionRunner.onError((error) => errors.push(error));
84
+ session.subscribe((event) => {
85
+ if (event.type !== "tool_execution_end" || event.toolName !== "background_task") return;
86
+ if (event.result.structuredContent.action === "start") task = event.result.structuredContent.task;
87
+ else if (event.result.structuredContent.action === "output") output = event.result.structuredContent;
88
+ });
89
+ await session.bindExtensions({});
90
+ const prompting = session.prompt("Start a job and hold the agent so the user can interrupt. " + "Prior history to compact. ".repeat(200));
91
+ await waitFor(() => holding, "the real blocking tool");
92
+ assert.equal(task.status, "running");
93
+ if (timing === "before interrupt") {
94
+ writeFileSync(release, "finish while the tool is held");
95
+ await waitFor(() => existsSync(exited), "the background shell exit marker");
96
+ await delay(100);
97
+ }
98
+ const interruptRequestedAt = Date.now();
99
+ if (timing === "after active compaction") {
100
+ await session.compact();
101
+ assert.equal(summaries, 1, "manual compaction must run its native summary after interrupting the active agent");
102
+ } else await session.abort();
103
+ await prompting;
104
+ const interruptedAt = Date.now();
105
+ assert.deepEqual(settlements, [true], "native settlement must confirm the user interrupt");
106
+ assert.equal(session.isIdle, true);
107
+ writeFileSync(release, "finish after user interruption");
108
+ await waitFor(() => existsSync(exited), "the background shell surviving the interrupt");
109
+ await delay(1250);
110
+ assert.equal(requests.length, 2, "late completion must not start a model request");
111
+ assert.match(readFileSync(task.log_path, "utf8"), /late shell result/);
112
+ assert.equal(session.isIdle, true);
113
+ await session.prompt("Continue and inspect the completed job.");
114
+ assert.equal(requests.length, 4);
115
+ const resumedContext = JSON.stringify(requests[2]);
116
+ assert.equal((resumedContext.match(/\[Background task finished\]/g) ?? []).length, 1, "retained completion enters context before the resumed model request");
117
+ assert.ok(resumedContext.includes(task.id));
118
+ assert.equal(output.task.exit_code, 7);
119
+ assert.equal(output.output, "late shell result\n");
120
+ await delay(50);
121
+ assert.equal(requests.length, 4, "consumed completion must not trigger another turn");
122
+ const notifications = session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === "background-task-finished");
123
+ assert.equal(notifications.length, 1);
124
+ assert.equal(notifications[0].details.tasks[0].id, task.id);
125
+ assert.equal(notifications[0].details.tasks[0].status, "failed");
126
+ if (timing === "before interrupt") assert.ok(notifications[0].details.tasks[0].ended_at <= interruptRequestedAt);
127
+ else assert.ok(notifications[0].details.tasks[0].ended_at >= interruptedAt);
128
+ assert.equal(session.getLastAssistantText(), "RESUMED_RESULT_ACK");
129
+ assert.deepEqual(errors, []);
130
+ t.diagnostic(JSON.stringify({ timing, requestsBeforeResume: 2, requestsAfterResume: 4, pendingDeliveredOnce: true, lateResultRecovered: true }));
131
+ } finally {
132
+ if (session) {
133
+ await session.abort();
134
+ await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
135
+ session.dispose();
136
+ }
137
+ rmSync(directory, { recursive: true, force: true });
138
+ }
139
+ });
140
+ }
package/tests/load.mjs ADDED
@@ -0,0 +1,28 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { piBinary } from "./runtime.mjs";
8
+
9
+ const directory = mkdtempSync(join(tmpdir(), "pi-bg-load-"));
10
+ const pkg = fileURLToPath(new URL("..", import.meta.url));
11
+ const toolkit = process.argv.includes("--toolkit");
12
+ const source = toolkit ? resolve(pkg, "../..") : resolve(pkg, "extensions/background-tasks.ts");
13
+ try {
14
+ writeFileSync(join(directory, "settings.json"), JSON.stringify({ quietStartup: true, defaultTools: ["+codemode"] }));
15
+ const output = execFileSync(piBinary, [
16
+ "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files",
17
+ "--no-session", "--offline", "-e", source,
18
+ "-e", resolve(pkg, "tests/fixtures/provider.ts"), "--model", "bg-fixture/deterministic", "-p", "ping",
19
+ ], { cwd: directory, encoding: "utf8", timeout: 30000, env: { ...process.env, PI_CODING_AGENT_DIR: directory, PI_OFFLINE: "1", BG_SMOKE_EVENTS: join(directory, "events.jsonl") }, stdio: ["ignore", "pipe", "pipe"] });
20
+ assert.match(output, /Main agent is ready/);
21
+ assert.doesNotMatch(output, /Failed to load|Error loading/);
22
+ const events = readFileSync(join(directory, "events.jsonl"), "utf8").trim().split("\n").map((line) => JSON.parse(line));
23
+ const loaded = events.find((entry) => entry.event === "loaded");
24
+ assert.equal(loaded.tools.filter((name) => name === "background_task").length, 1, "the real host registered exactly one background-task tool");
25
+ const request = events.find((entry) => entry.event === "request");
26
+ assert.equal(request.tools.filter((name) => name === "background_task").length, 1, "background_task is active in the model request without manual activation");
27
+ console.log(`Real Pi loaded ${toolkit ? "the toolkit default loadout" : "the standalone background-task extension"} with exactly one background-task tool and an offline fixture provider.`);
28
+ } finally { rmSync(directory, { recursive: true, force: true }); }
@@ -0,0 +1,80 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { test } from "node:test";
8
+ import { piBinary } from "./runtime.mjs";
9
+
10
+ test("native Codemode receives start guidance and exposes it to the model", () => {
11
+ const directory = mkdtempSync(join(tmpdir(), "pi-bg-guidance-"));
12
+ try {
13
+ const events = join(directory, "events.jsonl");
14
+ const output = execFileSync(piBinary, [
15
+ "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-session", "--offline",
16
+ "-e", "builtin:codemode", "-e", fileURLToPath(new URL("../extensions/background-tasks.ts", import.meta.url)),
17
+ "-e", fileURLToPath(new URL("fixtures/provider.ts", import.meta.url)),
18
+ "--tools", "codemode,background_task", "--model", "bg-fixture/deterministic", "-p", "SMOKE_GUIDANCE",
19
+ ], { cwd: directory, encoding: "utf8", timeout: 30000,
20
+ env: { ...process.env, PI_CODING_AGENT_DIR: directory, PI_OFFLINE: "1", BG_SMOKE_EVENTS: events }, stdio: ["ignore", "pipe", "pipe"] });
21
+ assert.match(output, /Main agent is ready/);
22
+ const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
23
+ const started = records.find((entry) => entry.event === "tool_end" && entry.name === "background_task");
24
+ assert.equal(started.isError, false);
25
+ const guidance = started.result.structuredContent.guidance;
26
+ assert.equal(guidance, "完成会自动通知。现在不要查询等待;继续其他独立工作,没有其他工作就结束当前轮,收到通知后再取结果。");
27
+ const codemode = records.find((entry) => entry.event === "tool_end" && entry.name === "codemode");
28
+ assert.equal(codemode.isError, false);
29
+ assert.ok(codemode.result.content.some((block) => block.type === "text" && block.text.includes(guidance)));
30
+ const requests = records.filter((entry) => entry.event === "request");
31
+ assert.ok(requests[0].backgroundDescription.includes(guidance));
32
+ assert.ok(requests[1].text.includes(guidance), "the next model request sees guidance printed from the programmatic result");
33
+ } finally { rmSync(directory, { recursive: true, force: true }); }
34
+ });
35
+
36
+ for (const mode of ["codemode", "direct"]) {
37
+ for (const reads of [0, 1, 4]) {
38
+ test(`real Pi ${mode} merges four completions before the next model call, excluding ${reads} consumed results`, () => {
39
+ const directory = mkdtempSync(join(tmpdir(), "pi-bg-notifications-"));
40
+ try {
41
+ const events = join(directory, "events.jsonl");
42
+ writeFileSync(join(directory, "settings.json"), JSON.stringify({ quietStartup: true, followUpMode: "one-at-a-time", steeringMode: "one-at-a-time" }));
43
+ const output = execFileSync(piBinary, [
44
+ "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-session", "--offline",
45
+ "-e", "builtin:codemode", "-e", process.env.BG_TEST_EXTENSION ?? fileURLToPath(new URL("../extensions/background-tasks.ts", import.meta.url)),
46
+ "-e", fileURLToPath(new URL("fixtures/notifications.ts", import.meta.url)),
47
+ "--tools", "codemode,background_task,synchronous_subagent_fixture", "--model", "bg-notifications/deterministic", "--mode", "json", "-p", "Run the synchronous subagent scenario",
48
+ ], { cwd: directory, encoding: "utf8", timeout: 30000, env: { ...process.env, PI_CODING_AGENT_DIR: directory, PI_OFFLINE: "1", BG_NOTIFICATION_EVENTS: events, BG_NOTIFICATION_READS: String(reads), BG_NOTIFICATION_MODE: mode }, stdio: ["ignore", "pipe", "pipe"] });
49
+ assert.doesNotMatch(output, /Failed to load|Error loading|Fixture shell jobs did not finish/);
50
+ const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
51
+ const returned = records.find((entry) => entry.event === "returned");
52
+ assert.ok(returned, `the blocking tool finished all real shell jobs\n${output}`);
53
+ assert.equal(returned.tasks.length, 4);
54
+ assert.ok(returned.tasks.every((task) => task.status === "failed" && task.exit_code === 7));
55
+ const transcript = output.trim().split("\n").map((line) => JSON.parse(line));
56
+ const notifications = transcript.filter((entry) =>
57
+ (entry.type === "entry_appended" && entry.entry.customType === "background-task-finished") ||
58
+ (entry.type === "message_start" && entry.message.customType === "background-task-finished")
59
+ );
60
+ assert.equal(notifications.length, reads === 4 ? 0 : 1);
61
+ if (reads !== 4) {
62
+ const message = notifications[0].entry ?? notifications[0].message;
63
+ const tasks = message.details.tasks;
64
+ assert.equal(tasks.length, 4 - reads);
65
+ assert.ok(tasks.every((task) => !returned.consumed.includes(task.id)));
66
+ const toolEnd = transcript.findIndex((entry) => entry.type === "tool_execution_end" && entry.toolName === "synchronous_subagent_fixture");
67
+ assert.ok(toolEnd >= 0 && transcript.indexOf(notifications[0]) > toolEnd, "the notification cannot interrupt the synchronous tool");
68
+ assert.match(message.content, /Ended at: \d{4}-/);
69
+ }
70
+ const requests = records.filter((entry) => entry.event === "request");
71
+ assert.equal(requests.length, mode === "direct" ? 3 : 2, "no extra model turns after the final report");
72
+ const nextContext = JSON.stringify(requests.at(-1).messages);
73
+ assert.equal((nextContext.match(/\[Background task finished\]/g) ?? []).length, reads === 4 ? 0 : 1);
74
+ assert.doesNotMatch(nextContext, /FINAL_REPORT/, "completion is delivered before, not after, the final report");
75
+ const contextText = requests.at(-1).messages.flatMap((message) => typeof message.content === "string" ? [message.content] : (message.content ?? []).filter((block) => block.type === "text").map((block) => block.text)).join("\n");
76
+ for (const task of returned.tasks.filter((task) => !returned.consumed.includes(task.id))) assert.ok(contextText.includes(task.id));
77
+ } finally { rmSync(directory, { recursive: true, force: true }); }
78
+ });
79
+ }
80
+ }
@@ -0,0 +1,55 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { createBashTool } from "@earendil-works/pi-coding-agent";
6
+ import { fixture, flush } from "./helpers.mjs";
7
+
8
+ const cases = [
9
+ ["empty", Buffer.alloc(0)],
10
+ ["small", Buffer.from("first\nsecond\n")],
11
+ ["no-newline", Buffer.from("last")],
12
+ ["line-limit", Buffer.from(Array.from({ length: 2500 }, (_, i) => `line ${i}`).join("\n"))],
13
+ ["byte-limit", Buffer.from(("x".repeat(200) + "\n").repeat(500))],
14
+ ["long-last-line", Buffer.from("before\n" + "z".repeat(300000))],
15
+ ["long-line-with-newline", Buffer.from("z".repeat(150000) + "\n")],
16
+ ["huge-utf8", Buffer.from("中文🙂\n".repeat(160000))],
17
+ ["utf8-long-line", Buffer.from("中文🙂".repeat(130000))],
18
+ ["invalid-utf8", Buffer.from([65, 0xf0, 0x9f])],
19
+ ];
20
+ for (const [name, data] of cases) {
21
+ test(`output matches native bash model/structured views: ${name}`, async () => {
22
+ const f = fixture();
23
+ try {
24
+ const path = join(f.root, "fixture.log");
25
+ writeFileSync(path, data);
26
+ const native = await createBashTool(f.root).execute("reference", { command: `cat '${path}'` });
27
+ const job = f.tasks.start({ command: "fixture" }, f.root);
28
+ // Deliberately split multi-byte UTF-8 across chunks.
29
+ for (let offset = 0; offset < data.length; offset += 8191) f.calls[0].onData(data.subarray(offset, offset + 8191));
30
+ f.calls[0].resolve();
31
+ await flush();
32
+ const actual = f.tasks.output(job.id);
33
+ const normalize = (text) => text.replace(/Full output: [^\]]+/g, "Full output: <log>");
34
+ assert.equal(normalize(actual.text), normalize(native.content[0].text));
35
+ assert.equal(actual.output, native.structuredContent.output);
36
+ assert.equal(actual.truncated, native.structuredContent.truncated);
37
+ assert.equal(actual.capture_complete, true);
38
+ assert.ok(Buffer.byteLength(actual.truncation.content) <= 51200);
39
+ assert.ok(Buffer.byteLength(actual.output) < 1024 * 1024 + 100);
40
+ } finally { await f.close(); }
41
+ });
42
+ }
43
+
44
+ test("running output is a consistent snapshot and does not flush incomplete UTF-8", async () => {
45
+ const f = fixture();
46
+ try {
47
+ const job = f.tasks.start({ command: "stream" }, f.root);
48
+ const bytes = Buffer.from("中文");
49
+ f.calls[0].onData(bytes.subarray(0, 2));
50
+ assert.equal(f.tasks.output(job.id).output, "");
51
+ f.calls[0].onData(bytes.subarray(2));
52
+ assert.equal(f.tasks.output(job.id).output, "中文");
53
+ assert.equal(f.tasks.output(job.id).capture_complete, false);
54
+ } finally { await f.close(); }
55
+ });
@@ -0,0 +1,96 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { createLocalBashOperations } from "@earendil-works/pi-coding-agent";
8
+ import { BackgroundTasks } from "../src/background-tasks.ts";
9
+
10
+ async function waitFor(check) {
11
+ const deadline = Date.now() + 5000;
12
+ while (!check()) {
13
+ if (Date.now() > deadline) throw new Error("Real process did not reach expected state within 5 seconds");
14
+ await delay(20);
15
+ }
16
+ }
17
+ function alive(pid) {
18
+ try {
19
+ process.kill(pid, 0);
20
+ // A reaped parent can temporarily leave a zombie child owned by PID 1.
21
+ if (existsSync(`/proc/${pid}/stat`) && readFileSync(`/proc/${pid}/stat`, "utf8").split(") ")[1].startsWith("Z ")) return false;
22
+ return true;
23
+ } catch (error) { if (error.code === "ESRCH") return false; throw error; }
24
+ }
25
+
26
+ test("native backend starts immediately and executes heredoc/PID/exit-file checks", async () => {
27
+ const root = mkdtempSync(join(tmpdir(), "pi-bg-process-"));
28
+ const completed = [];
29
+ const tasks = new BackgroundTasks({ operations: createLocalBashOperations(), onComplete: (task) => completed.push(task) });
30
+ try {
31
+ writeFileSync(join(root, "build.log"), "> Task :compile\nnoise\nBUILD SUCCESSFUL\n");
32
+ writeFileSync(join(root, "build.exit"), "0\n");
33
+ const task = tasks.start({ command: `sleep 1; python3 - <<'PY'
34
+ from pathlib import Path
35
+ p=Path('build.log')
36
+ lines=p.read_text(errors='replace').splitlines()
37
+ s=[x for x in lines if x.startswith('> Task') or 'BUILD SUCCESS' in x]
38
+ print('\\n'.join(s[-35:])); print('log bytes:',p.stat().st_size)
39
+ PY
40
+ ps -p $$ -o pid,etime; test ! -f build.exit || cat build.exit` }, root);
41
+ assert.equal(task.status, "running");
42
+ const other = tasks.start({ command: "printf concurrent" }, root);
43
+ await waitFor(() => tasks.get(other.id).status !== "running");
44
+ assert.equal(tasks.get(task.id).status, "running", "other work completed before the sleeping job");
45
+ await waitFor(() => tasks.get(task.id).status !== "running");
46
+ assert.equal(tasks.get(task.id).status, "succeeded");
47
+ assert.match(tasks.output(task.id).output, /> Task :compile\nBUILD SUCCESSFUL\nlog bytes:/);
48
+ assert.equal(completed.length, 2);
49
+ } finally { await tasks.shutdown(); rmSync(root, { recursive: true, force: true }); }
50
+ });
51
+
52
+ for (const stop of ["timeout", "cancel", "shutdown"]) {
53
+ test(`native ${stop} stops silent shell and its waiting child`, async () => {
54
+ const root = mkdtempSync(join(tmpdir(), "pi-bg-tree-"));
55
+ const tasks = new BackgroundTasks({ operations: createLocalBashOperations() });
56
+ let pids = [];
57
+ try {
58
+ const task = tasks.start({
59
+ command: `echo $$ > shell.pid; sleep 300 & echo $! > child.pid; wait`,
60
+ timeout: stop === "timeout" ? 1 : 30,
61
+ }, root);
62
+ await waitFor(() => existsSync(join(root, "child.pid")));
63
+ pids = ["shell.pid", "child.pid"].map((file) => Number(readFileSync(join(root, file), "utf8").trim()));
64
+ if (stop === "shutdown") await tasks.shutdown();
65
+ else if (stop === "cancel") await tasks.cancel(task.id);
66
+ else await waitFor(() => tasks.get(task.id).status !== "running");
67
+ await waitFor(() => pids.every((pid) => !alive(pid)));
68
+ assert.equal(tasks.get(task.id).status, stop === "timeout" ? "timed_out" : "cancelled");
69
+ } finally { await tasks.shutdown(); rmSync(root, { recursive: true, force: true }); }
70
+ });
71
+ }
72
+
73
+ test("silent busy loop times out without any agent polling or output", async () => {
74
+ const tasks = new BackgroundTasks({ operations: createLocalBashOperations() });
75
+ try {
76
+ const job = tasks.start({ command: "while :; do :; done", timeout: 1 }, process.cwd());
77
+ await waitFor(() => tasks.get(job.id).status !== "running");
78
+ assert.equal(tasks.get(job.id).status, "timed_out");
79
+ assert.equal(tasks.output(job.id).output, "");
80
+ } finally { await tasks.shutdown(); }
81
+ });
82
+
83
+ test("native large output truncates display, then stops at the 32 MiB disk budget", async () => {
84
+ const tasks = new BackgroundTasks({ operations: createLocalBashOperations() });
85
+ try {
86
+ const job = tasks.start({ command: "python3 -c \"import sys; sys.stdout.buffer.write(b'x' * (40 * 1024 * 1024))\"" }, process.cwd());
87
+ await waitFor(() => tasks.get(job.id).status !== "running");
88
+ const result = tasks.output(job.id);
89
+ assert.equal(result.status, "output_limit");
90
+ assert.equal(result.bytes, 32 * 1024 * 1024);
91
+ assert.equal(result.capture_complete, false);
92
+ assert.equal(result.truncated, true);
93
+ assert.ok(result.truncation.outputBytes <= 51200);
94
+ assert.ok(Buffer.byteLength(result.output) < 1024 * 1024 + 100);
95
+ } finally { await tasks.shutdown(); }
96
+ });
@@ -0,0 +1,30 @@
1
+ // Resolve host peers from the selected installed Pi; never install a second runtime.
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
4
+ import { registerHooks } from "node:module";
5
+ import { delimiter, dirname, join } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+
8
+ // npm prepends workspace .bin paths, which may contain an older development Pi.
9
+ const hostPath = (process.env.PATH ?? "").split(delimiter).filter((entry) => !entry.endsWith("node_modules/.bin")).join(delimiter);
10
+ const binary = process.env.PI_TEST_BINARY || execFileSync("sh", ["-c", "command -v pi"], { encoding: "utf8", env: { ...process.env, PATH: hostPath } }).trim();
11
+ let root = dirname(realpathSync(binary));
12
+ while (!existsSync(join(root, "package.json")) || JSON.parse(readFileSync(join(root, "package.json"), "utf8")).name !== "@earendil-works/pi-coding-agent") {
13
+ const parent = dirname(root);
14
+ if (parent === root) throw new Error(`Cannot locate Pi runtime next to ${binary}`);
15
+ root = parent;
16
+ }
17
+ const version = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version;
18
+ const [major, minor] = version.split(".").map(Number);
19
+ if (major < 1 || (major === 1 && minor < 3)) throw new Error(`Background Tasks checks require Pi >=1.3.0; selected ${version} at ${binary}. Set PI_TEST_BINARY to a supported host.`);
20
+ export const piBinary = binary;
21
+ export const piEntry = join(root, "dist/index.js");
22
+ const hostURL = pathToFileURL(piEntry).href;
23
+ const peers = new Set(["@earendil-works/pi-coding-agent", "@earendil-works/pi-ai", "@earendil-works/pi-tui", "typebox"]);
24
+ registerHooks({
25
+ resolve(specifier, context, nextResolve) {
26
+ return peers.has(specifier)
27
+ ? nextResolve(specifier, { ...context, parentURL: hostURL })
28
+ : nextResolve(specifier, context);
29
+ },
30
+ });