@maxiaochao/pi-background-tasks 0.1.0 → 0.1.2

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,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
+ }
@@ -0,0 +1,106 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, 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 model receives concise start guidance without Codemode instructions", () => {
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, "Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.");
27
+ assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "codemode"), false);
28
+ const requests = records.filter((entry) => entry.event === "request");
29
+ assert.ok(requests[0].backgroundDescription.includes(guidance));
30
+ assert.ok(!requests[0].backgroundDescription.includes("Codemode:"));
31
+ assert.ok(requests[1].text.includes(guidance), "the next model request sees the startup guidance");
32
+ } finally { rmSync(directory, { recursive: true, force: true }); }
33
+ });
34
+
35
+ test("native Codemode cannot discover or call the model-only background tool", () => {
36
+ const directory = mkdtempSync(join(tmpdir(), "pi-bg-exposure-"));
37
+ try {
38
+ const events = join(directory, "events.jsonl");
39
+ const output = execFileSync(piBinary, [
40
+ "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-session", "--offline",
41
+ "-e", "builtin:codemode", "-e", fileURLToPath(new URL("../extensions/background-tasks.ts", import.meta.url)),
42
+ "-e", fileURLToPath(new URL("fixtures/provider.ts", import.meta.url)),
43
+ "--tools", "codemode,background_task", "--model", "bg-fixture/deterministic", "-p", "SMOKE_EXPOSURE",
44
+ ], { cwd: directory, encoding: "utf8", timeout: 30000,
45
+ env: { ...process.env, PI_CODING_AGENT_DIR: directory, PI_OFFLINE: "1", BG_SMOKE_EVENTS: events }, stdio: ["ignore", "pipe", "pipe"] });
46
+ assert.match(output, /Main agent is ready/);
47
+ const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
48
+ const codemode = records.find((entry) => entry.event === "tool_end" && entry.name === "codemode");
49
+ assert.equal(codemode.isError, false);
50
+ const text = codemode.result.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
51
+ assert.match(text, /"discovered":false/);
52
+ assert.match(text, /"available":false/);
53
+ assert.match(text, /BACKGROUND_CALL_BLOCKED/);
54
+ assert.doesNotMatch(text, /UNEXPECTED_SUCCESS/);
55
+ assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "background_task"), false);
56
+ assert.equal(existsSync(join(directory, "should-not-exist")), false);
57
+ assert.ok(records.find((entry) => entry.event === "request").tools.includes("background_task"));
58
+ } finally { rmSync(directory, { recursive: true, force: true }); }
59
+ });
60
+
61
+ for (const mode of ["codemode", "direct"]) {
62
+ for (const reads of [0, 1, 2]) {
63
+ test(`real Pi ${mode} blocker merges four completions, excluding ${reads} model-read results`, () => {
64
+ const directory = mkdtempSync(join(tmpdir(), "pi-bg-notifications-"));
65
+ try {
66
+ const events = join(directory, "events.jsonl");
67
+ writeFileSync(join(directory, "settings.json"), JSON.stringify({ quietStartup: true, followUpMode: "one-at-a-time", steeringMode: "one-at-a-time" }));
68
+ const output = execFileSync(piBinary, [
69
+ "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-session", "--offline",
70
+ "-e", "builtin:codemode", "-e", process.env.BG_TEST_EXTENSION ?? fileURLToPath(new URL("../extensions/background-tasks.ts", import.meta.url)),
71
+ "-e", fileURLToPath(new URL("fixtures/notifications.ts", import.meta.url)),
72
+ "--tools", "codemode,background_task,synchronous_subagent_fixture", "--model", "bg-notifications/deterministic", "--mode", "json", "-p", "Run the synchronous subagent scenario",
73
+ ], { 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"] });
74
+ assert.doesNotMatch(output, /Failed to load|Error loading|Fixture shell jobs did not finish/);
75
+ const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
76
+ const returned = records.find((entry) => entry.event === "returned");
77
+ assert.ok(returned, `the blocking tool finished all real shell jobs\n${output}`);
78
+ assert.equal(returned.tasks.length, 4);
79
+ assert.equal(returned.consumed.length, reads);
80
+ assert.ok(returned.tasks.filter((task) => returned.consumed.includes(task.id)).every((task) => task.status === "failed" && task.exit_code === 7));
81
+ const transcript = output.trim().split("\n").map((line) => JSON.parse(line));
82
+ const notifications = transcript.filter((entry) =>
83
+ (entry.type === "entry_appended" && entry.entry.customType === "background-task-finished") ||
84
+ (entry.type === "message_start" && entry.message.customType === "background-task-finished")
85
+ );
86
+ assert.equal(notifications.length, 1);
87
+ const message = notifications[0].entry ?? notifications[0].message;
88
+ const tasks = message.details.tasks;
89
+ assert.equal(tasks.length, 4 - reads);
90
+ assert.ok(tasks.every((task) => task.status === "failed" && task.exit_code === 7));
91
+ assert.ok(tasks.every((task) => !returned.consumed.includes(task.id)));
92
+ assert.deepEqual([...returned.consumed, ...tasks.map((task) => task.id)].sort(), returned.tasks.map((task) => task.id).sort());
93
+ const toolEnd = transcript.findLastIndex((entry) => entry.type === "tool_execution_end" && ["synchronous_subagent_fixture", "codemode"].includes(entry.toolName));
94
+ assert.ok(toolEnd >= 0 && transcript.indexOf(notifications[0]) > toolEnd, "the notification cannot interrupt the synchronous tool");
95
+ assert.match(message.content, /Ended at: \d{4}-/);
96
+ const requests = records.filter((entry) => entry.event === "request");
97
+ assert.equal(requests.length, 3, "no extra model turns after the final report");
98
+ const nextContext = JSON.stringify(requests.at(-1).messages);
99
+ assert.equal((nextContext.match(/\[Background task finished\]/g) ?? []).length, 1);
100
+ assert.doesNotMatch(nextContext, /FINAL_REPORT/, "completion is delivered before, not after, the final report");
101
+ 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");
102
+ for (const task of returned.tasks.filter((task) => !returned.consumed.includes(task.id))) assert.ok(contextText.includes(task.id));
103
+ } finally { rmSync(directory, { recursive: true, force: true }); }
104
+ });
105
+ }
106
+ }
@@ -126,24 +126,33 @@ try:
126
126
  assert loaded['tools'].count('background_task') == 1
127
127
  send('/schedule add 1h Check release status')
128
128
  wait(lambda: 'active schedule' in raw, 'Scheduler widget')
129
+ send('SMOKE_EXPOSURE')
130
+ wait(lambda: bool(tools('codemode')), 'Codemode exposure check')
131
+ assert 'BACKGROUND_CALL_BLOCKED' in str(tools('codemode')[-1]['result'])
132
+ assert not (work / 'should-not-exist').exists()
133
+ wait(lambda: any(e.get('event') == 'settled' for e in events()), 'exposure turn completion')
134
+ settled_count = len([e for e in events() if e.get('event') == 'settled'])
129
135
  send('SMOKE_START')
130
- wait(lambda: len(tools()) >= 3 and any(e.get('name') == 'codemode' for e in tools('codemode')), 'Codemode startup batch')
136
+ wait(lambda: len(tools()) >= 3, 'model startup batch')
131
137
  starts = tools()[:3]
132
138
  assert not starts[0]['isError'] and not starts[1]['isError'] and starts[2]['isError'], starts
133
139
  first = starts[0]['result']['structuredContent']['task']
134
140
  second = starts[1]['result']['structuredContent']['task']
135
141
  assert first['status'] == second['status'] == 'running'
136
- assert any('Script completed' in str(e.get('result')) for e in tools('codemode')), tools('codemode')
137
- assert not finished('succeeded'), 'Sleeping job must survive Codemode completion'
142
+ wait(lambda: len([e for e in events() if e.get('event') == 'settled']) > settled_count, 'foreground turn completion')
143
+ assert not finished('succeeded'), 'Sleeping job must survive foreground turn completion'
138
144
  shot('running')
139
145
  send('/bg output ' + first['id'])
140
146
  send('SMOKE_CANCEL')
141
- wait(lambda: bool(finished('cancelled')), 'cancel follow-up')
142
- wait(lambda: bool(finished('succeeded')), 'successful background follow-up')
147
+ wait(lambda: bool(finished('cancelled')), 'cancel notification')
148
+ wait(lambda: bool(finished('succeeded')), 'successful background notification')
143
149
  shot('completed')
144
150
  send('SMOKE_OUTPUT')
145
151
  wait(lambda: any(e.get('result', {}).get('structuredContent', {}).get('output') == 'BUILD SUCCESSFUL\n' for e in tools()), 'explicit output query')
146
- wait(lambda: 'BACKGROUND_FOLLOWUP_RECEIVED' in raw, 'main agent automatic response')
152
+ wait(lambda: 'BACKGROUND_NOTIFICATION_RECEIVED' in raw, 'main agent automatic response')
153
+ pump(0.5)
154
+ notifications = [e for e in events() if e.get('event') == 'custom' and e.get('type') == 'background-task-finished']
155
+ assert len(notifications) == 2, 'Duplicate persisted busy/idle notifications'
147
156
  pump(5.3)
148
157
  shot('history')
149
158
 
@@ -173,8 +182,9 @@ try:
173
182
  assert all(not Path(path).exists() for path in logs), 'Session logs were not removed'
174
183
  (OUT / 'events.jsonl').write_text('\n'.join(json.dumps(e) for e in records) + '\n')
175
184
  (OUT / 'result.json').write_text(json.dumps({'passed': True, 'screenshots': screens,
176
- 'checks': ['two jobs', 'third rejected', 'Codemode returns while jobs live', 'Scheduler coexistence', '/bg output',
177
- 'cancel notification', 'success notification', 'main agent follow-up', '5-second terminal row', 'reload cleanup', 'new-session cleanup', 'quit cleanup']}, indent=2))
185
+ 'checks': ['two jobs', 'third rejected', 'Codemode background calls blocked', 'model returns while jobs live', 'Scheduler coexistence', '/bg output',
186
+ 'cancel notification', 'success notification', 'main agent notification', 'no duplicate persisted notifications',
187
+ '5-second terminal row', 'reload cleanup', 'new-session cleanup', 'quit cleanup']}, indent=2))
178
188
  except Exception:
179
189
  (OUT / 'error.txt').write_text(traceback.format_exc())
180
190
  raise