@maxiaochao/pi-background-tasks 0.2.0 β 0.3.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.
- package/CHANGELOG.md +16 -0
- package/README.md +33 -19
- package/TESTING.md +11 -7
- package/docs/demo.gif +0 -0
- package/docs/demo.webm +0 -0
- package/docs/screenshot.png +0 -0
- package/docs/task-panes.png +0 -0
- package/extensions/background-tasks.ts +34 -13
- package/package.json +1 -1
- package/src/output.ts +14 -25
- package/src/viewer.ts +22 -11
- package/tests/compaction.mjs +5 -1
- package/tests/extension.mjs +163 -14
- package/tests/fixtures/notifications.ts +1 -1
- package/tests/fixtures/provider.ts +8 -3
- package/tests/interruptions.mjs +19 -10
- package/tests/media.mjs +16 -0
- package/tests/notifications.mjs +18 -6
- package/tests/output.mjs +32 -8
- package/tests/processes.mjs +2 -2
- package/tests/runtime.mjs +12 -0
- package/tests/viewer.mjs +91 -3
package/tests/extension.mjs
CHANGED
|
@@ -15,7 +15,7 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
15
15
|
const placements = new Map();
|
|
16
16
|
const statuses = new Map();
|
|
17
17
|
const idleChecks = [];
|
|
18
|
-
let tool, renders = 0, idle = true;
|
|
18
|
+
let tool, renders = 0, idle = true, failSend = false;
|
|
19
19
|
const theme = { fg: (_color, text) => text, bold: (text) => text };
|
|
20
20
|
const ctx = {
|
|
21
21
|
cwd: f.root, mode, hasUI, isIdle: () => { idleChecks.push(f.clock.now()); return idle; },
|
|
@@ -33,12 +33,16 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
33
33
|
on(name, handler) { handlers.set(name, handler); },
|
|
34
34
|
registerTool(value) { tool = value; },
|
|
35
35
|
registerCommand(name, value) { commands.set(name, value); },
|
|
36
|
-
sendMessage(message, options) {
|
|
36
|
+
sendMessage(message, options) {
|
|
37
|
+
if (failSend) { failSend = false; throw new Error("Fixture delivery rejected"); }
|
|
38
|
+
messages.push({ message, options });
|
|
39
|
+
},
|
|
37
40
|
};
|
|
38
41
|
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root, env: {} });
|
|
39
42
|
return {
|
|
40
43
|
...f, handlers, commands, messages, notices, widgets, placements, statuses, idleChecks, ctx,
|
|
41
44
|
setIdle(value) { idle = value; },
|
|
45
|
+
failNextSend() { failSend = true; },
|
|
42
46
|
get tool() { return tool; }, get renders() { return renders; },
|
|
43
47
|
async close() {
|
|
44
48
|
const closing = handlers.get("session_shutdown")({}, ctx);
|
|
@@ -71,6 +75,139 @@ test("completions during a synchronous tool are merged before the next model req
|
|
|
71
75
|
} finally { await h.close(); }
|
|
72
76
|
});
|
|
73
77
|
|
|
78
|
+
test("completion sends only status and log location with progressive-inspection guidance", async () => {
|
|
79
|
+
const h = harness("print", false);
|
|
80
|
+
try {
|
|
81
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
82
|
+
h.setIdle(false);
|
|
83
|
+
const task = (await h.tool.execute("start", { action: "start", command: "build" })).structuredContent.task;
|
|
84
|
+
h.calls[0].onData(Buffer.from("BUILD RESULT: done\n"));
|
|
85
|
+
h.calls[0].resolve();
|
|
86
|
+
await flush();
|
|
87
|
+
const message = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
|
|
88
|
+
assert.doesNotMatch(message.content, /BUILD RESULT: done|Untrusted shell output/);
|
|
89
|
+
assert.ok(message.content.includes(`Captured log: ${task.log_path}`));
|
|
90
|
+
assert.match(message.content, /Inspect logs progressively as needed/);
|
|
91
|
+
assert.match(message.content, /search for relevant terms or read bounded ranges/);
|
|
92
|
+
assert.doesNotMatch(message.content, /do not repeatedly|Do not sleep|Inspect:/);
|
|
93
|
+
const inspected = await h.tool.execute("inspect", { action: "output", id: task.id });
|
|
94
|
+
assert.equal(inspected.structuredContent.output, "BUILD RESULT: done\n");
|
|
95
|
+
assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx), undefined);
|
|
96
|
+
} finally { await h.close(); }
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("status-only completion batches stay bounded without reading or injecting large UTF-8 logs", async () => {
|
|
100
|
+
const h = harness("print", false);
|
|
101
|
+
try {
|
|
102
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
103
|
+
h.setIdle(false);
|
|
104
|
+
const ids = [];
|
|
105
|
+
const data = Buffer.from("π".repeat(3000));
|
|
106
|
+
for (let i = 0; i < 10; i++) {
|
|
107
|
+
const task = (await h.tool.execute(`start-${i}`, { action: "start", command: `build-${i}`, description: "η".repeat(200) })).structuredContent.task;
|
|
108
|
+
ids.push(task.id);
|
|
109
|
+
h.calls[i].onData(data);
|
|
110
|
+
h.calls[i].reject(new Error("ι".repeat(500)));
|
|
111
|
+
await flush();
|
|
112
|
+
}
|
|
113
|
+
const delivered = [];
|
|
114
|
+
let batches = 0;
|
|
115
|
+
for (;;) {
|
|
116
|
+
const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
|
|
117
|
+
if (!boundary) break;
|
|
118
|
+
assert.ok(++batches <= ids.length, "every batch must make progress");
|
|
119
|
+
const message = boundary.entries[0];
|
|
120
|
+
assert.ok(Buffer.byteLength(message.content) <= 16384);
|
|
121
|
+
assert.ok(!message.content.includes("\uFFFD"), "budget cuts must preserve UTF-8");
|
|
122
|
+
assert.ok(!message.content.includes("π"), "captured log bodies must not enter notifications");
|
|
123
|
+
assert.doesNotMatch(message.content, /Untrusted shell output|Output preview/);
|
|
124
|
+
delivered.push(...message.details.tasks.map((task) => task.id));
|
|
125
|
+
}
|
|
126
|
+
assert.ok(batches > 1, "long metadata must split the pending batch");
|
|
127
|
+
assert.deepEqual(delivered, ids);
|
|
128
|
+
assert.equal(h.messages.length, 0);
|
|
129
|
+
const inspected = await h.tool.execute("inspect", { action: "output", id: ids[0] });
|
|
130
|
+
assert.equal(inspected.structuredContent.task.bytes, data.length);
|
|
131
|
+
assert.equal(inspected.structuredContent.task.capture_complete, true);
|
|
132
|
+
} finally { await h.close(); }
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("notification does not open missing logs; later explicit inspections report errors independently", async () => {
|
|
136
|
+
const h = harness("print", false);
|
|
137
|
+
try {
|
|
138
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
139
|
+
h.setIdle(false);
|
|
140
|
+
const broken = (await h.tool.execute("broken", { action: "start", command: "broken" })).structuredContent.task;
|
|
141
|
+
const healthy = (await h.tool.execute("healthy", { action: "start", command: "healthy" })).structuredContent.task;
|
|
142
|
+
h.calls[0].onData(Buffer.from("unavailable log\n"));
|
|
143
|
+
h.calls[1].onData(Buffer.from("healthy result\n"));
|
|
144
|
+
h.calls[0].resolve(7);
|
|
145
|
+
h.calls[1].resolve();
|
|
146
|
+
await flush();
|
|
147
|
+
unlinkSync(broken.log_path);
|
|
148
|
+
const message = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
|
|
149
|
+
assert.deepEqual(message.details.tasks.map((task) => task.id), [broken.id, healthy.id]);
|
|
150
|
+
assert.equal(message.details.tasks[0].status, "failed");
|
|
151
|
+
assert.equal(message.details.tasks[0].capture_complete, true, "notification must not inspect the file or mutate capture state");
|
|
152
|
+
assert.ok(message.content.includes(broken.log_path));
|
|
153
|
+
assert.ok(message.content.includes(healthy.log_path));
|
|
154
|
+
assert.doesNotMatch(message.content, /healthy result|unavailable log|Output unavailable/);
|
|
155
|
+
const missing = await h.tool.execute("read-broken", { action: "output", id: broken.id });
|
|
156
|
+
assert.equal(missing.isError, true);
|
|
157
|
+
assert.match(missing.structuredContent.error, /Cannot read task log/);
|
|
158
|
+
const present = await h.tool.execute("read-healthy", { action: "output", id: healthy.id });
|
|
159
|
+
assert.equal(present.structuredContent.output, "healthy result\n");
|
|
160
|
+
assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx), undefined);
|
|
161
|
+
} finally { await h.close(); }
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test("a rejected idle delivery retains its result for the next safe boundary", async () => {
|
|
165
|
+
const h = harness("print", false);
|
|
166
|
+
try {
|
|
167
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
168
|
+
const task = (await h.tool.execute("start", { action: "start", command: "build" })).structuredContent.task;
|
|
169
|
+
h.calls[0].onData(Buffer.from("retained result\n"));
|
|
170
|
+
h.calls[0].resolve();
|
|
171
|
+
await flush();
|
|
172
|
+
h.failNextSend();
|
|
173
|
+
h.clock.advance(0);
|
|
174
|
+
assert.equal(h.messages.length, 0);
|
|
175
|
+
const message = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
|
|
176
|
+
assert.equal(message.details.tasks[0].id, task.id);
|
|
177
|
+
assert.ok(message.content.includes(task.log_path));
|
|
178
|
+
assert.doesNotMatch(message.content, /retained result/);
|
|
179
|
+
assert.equal((await h.tool.execute("inspect", { action: "output", id: task.id })).structuredContent.output, "retained result\n");
|
|
180
|
+
assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx), undefined);
|
|
181
|
+
} finally { await h.close(); }
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test("timeout and empty-result notifications contain status and paths, not captured output", async () => {
|
|
185
|
+
const h = harness("print", false);
|
|
186
|
+
try {
|
|
187
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
188
|
+
h.setIdle(false);
|
|
189
|
+
await h.tool.execute("slow", { action: "start", command: "slow", timeout: 1 });
|
|
190
|
+
h.calls[0].onData(Buffer.from("partial before deadline\n"));
|
|
191
|
+
h.clock.advance(1000);
|
|
192
|
+
h.calls[0].reject(new Error("aborted"));
|
|
193
|
+
await flush();
|
|
194
|
+
const timedOut = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
|
|
195
|
+
assert.equal(timedOut.details.tasks[0].status, "timed_out");
|
|
196
|
+
assert.match(timedOut.content, /Runtime limit of 1 seconds reached/);
|
|
197
|
+
assert.doesNotMatch(timedOut.content, /partial before deadline/);
|
|
198
|
+
assert.ok(timedOut.content.includes(timedOut.details.tasks[0].log_path));
|
|
199
|
+
assert.equal((await h.tool.execute("read-slow", { action: "output", id: timedOut.details.tasks[0].id })).structuredContent.output, "partial before deadline\n");
|
|
200
|
+
await h.tool.execute("empty", { action: "start", command: "empty" });
|
|
201
|
+
h.calls[1].resolve();
|
|
202
|
+
await flush();
|
|
203
|
+
const empty = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
|
|
204
|
+
assert.ok(empty.content.includes(empty.details.tasks[0].log_path));
|
|
205
|
+
assert.doesNotMatch(empty.content, /\(no output\)/);
|
|
206
|
+
assert.equal((await h.tool.execute("read-empty", { action: "output", id: empty.details.tasks[0].id })).structuredContent.output, "");
|
|
207
|
+
assert.doesNotMatch(empty.content, /For logs:|For more logs:/);
|
|
208
|
+
} finally { await h.close(); }
|
|
209
|
+
});
|
|
210
|
+
|
|
74
211
|
test("a completion during manual compaction wakes after idle without another agent boundary", async () => {
|
|
75
212
|
const h = harness("print", false);
|
|
76
213
|
try {
|
|
@@ -326,7 +463,9 @@ test("registration is compact, does not inject prompt rules or start session res
|
|
|
326
463
|
try {
|
|
327
464
|
assert.equal(h.tool.name, "background_task");
|
|
328
465
|
assert.equal(h.tool.exposure, "model-only");
|
|
329
|
-
assert.match(h.tool.description, /
|
|
466
|
+
assert.match(h.tool.description, /up to two concurrent background shell tasks/);
|
|
467
|
+
assert.match(h.tool.parameters.properties.action.description, /start returns a task ID immediately/);
|
|
468
|
+
assert.equal(h.tool.parameters.properties.command.description, "Shell command for start; may be multi-line. Runs locally, with stdin closed. Stdout/stderr are saved to a unique per-task log; its path is reported on completion.");
|
|
330
469
|
assert.ok(h.tool.description.length < 500);
|
|
331
470
|
assert.equal(h.tool.promptGuidelines, undefined);
|
|
332
471
|
assert.ok(h.tool.outputSchema);
|
|
@@ -338,20 +477,28 @@ test("registration is compact, does not inject prompt rules or start session res
|
|
|
338
477
|
} finally { await h.close(); }
|
|
339
478
|
});
|
|
340
479
|
|
|
341
|
-
test("start
|
|
480
|
+
test("start keeps only task-specific guidance while the declaration describes lifecycle and running queries", async () => {
|
|
342
481
|
const h = harness();
|
|
343
482
|
try {
|
|
344
483
|
await h.handlers.get("session_start")({}, h.ctx);
|
|
345
484
|
const started = await h.tool.execute("start", { action: "start", command: "sleep 60" });
|
|
346
|
-
const { task
|
|
485
|
+
const { task } = started.structuredContent;
|
|
486
|
+
const notice = "Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.";
|
|
347
487
|
assert.equal(task.status, "running");
|
|
348
|
-
assert.
|
|
349
|
-
assert.ok(started.content[0].text.includes(
|
|
350
|
-
assert.ok(
|
|
351
|
-
assert.
|
|
352
|
-
assert.
|
|
488
|
+
assert.ok(started.content[0].text.includes(notice));
|
|
489
|
+
assert.ok(!started.content[0].text.includes(task.log_path));
|
|
490
|
+
assert.ok(!started.content[0].text.includes("session changes"));
|
|
491
|
+
assert.ok(!h.tool.description.includes(notice), "declaration must not duplicate the whole start reminder");
|
|
492
|
+
assert.match(h.tool.description, /automatic completion notifications/);
|
|
493
|
+
assert.match(h.tool.description, /session changes, reload, or exit/);
|
|
494
|
+
assert.match(h.tool.parameters.properties.action.description, /list and output also work while tasks are running/);
|
|
495
|
+
assert.equal(started.structuredContent.guidance, undefined);
|
|
496
|
+
assert.equal(h.tool.outputSchema.properties.guidance, undefined);
|
|
353
497
|
const list = await h.tool.execute("list", { action: "list" });
|
|
354
498
|
const output = await h.tool.execute("output", { action: "output", id: task.id });
|
|
499
|
+
assert.equal(list.structuredContent.tasks[0].status, "running", "status inspection does not require a completion notification");
|
|
500
|
+
assert.equal(output.structuredContent.task.status, "running", "log inspection is allowed before completion");
|
|
501
|
+
assert.equal(h.messages.length, 0, "running-task inspection does not wait for or create a notification");
|
|
355
502
|
assert.equal(list.structuredContent.guidance, undefined);
|
|
356
503
|
assert.equal(output.structuredContent.guidance, undefined);
|
|
357
504
|
h.calls[0].resolve();
|
|
@@ -379,12 +526,12 @@ test("tools, commands, widget and idle notifications share the same session jobs
|
|
|
379
526
|
for (const width of [1, 8, 40, 80]) assert.ok(widget.render(width).every((line) => visibleWidth(line) <= width));
|
|
380
527
|
assert.ok(h.widgets.has("scheduler") && h.widgets.has("herdr-subagents"));
|
|
381
528
|
|
|
382
|
-
h.calls[0].onData(Buffer.from("
|
|
529
|
+
h.calls[0].onData(Buffer.from("captured build output\n"));
|
|
383
530
|
await h.commands.get("bg").handler(`output ${job.id}`, h.ctx);
|
|
384
|
-
assert.match(h.messages.at(-1).message.content, /
|
|
531
|
+
assert.match(h.messages.at(-1).message.content, /captured build output/);
|
|
385
532
|
assert.equal(h.messages.at(-1).options.triggerTurn, false);
|
|
386
533
|
const output = await h.tool.execute("output", { action: "output", id: job.id });
|
|
387
|
-
assert.equal(output.structuredContent.output, "
|
|
534
|
+
assert.equal(output.structuredContent.output, "captured build output\n");
|
|
388
535
|
assert.equal(output.details.output, undefined);
|
|
389
536
|
|
|
390
537
|
h.calls[0].resolve(7);
|
|
@@ -394,7 +541,9 @@ test("tools, commands, widget and idle notifications share the same session jobs
|
|
|
394
541
|
assert.equal(completed.length, 1);
|
|
395
542
|
assert.deepEqual(completed[0].options, { triggerTurn: true, deliverAs: "steer" });
|
|
396
543
|
assert.match(completed[0].message.content, /failed.*exit 7/);
|
|
397
|
-
assert.
|
|
544
|
+
assert.doesNotMatch(completed[0].message.content, /captured build output/);
|
|
545
|
+
assert.ok(!completed[0].message.content.includes(`background_task({action:"output",id:"${job.id}"})`), "complete small output needs no follow-up query");
|
|
546
|
+
assert.ok(completed[0].message.content.includes(job.log_path), "completion points at the log for progressive inspection");
|
|
398
547
|
assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /failed/);
|
|
399
548
|
h.clock.advance(4999);
|
|
400
549
|
assert.ok(h.widgets.has("background-tasks"));
|
|
@@ -60,7 +60,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
60
60
|
const wave = requests - 1;
|
|
61
61
|
if (requests === 2) message.content.push({ type: "toolCall", id: "wait-first-wave", name: "synchronous_subagent_fixture", arguments: { wave: 0 } });
|
|
62
62
|
for (let i = 0; i < 2; i++) message.content.push({ type: "toolCall", id: `start-${wave}-${i}`, name: "background_task", arguments: {
|
|
63
|
-
action: "start", command: `while [ ! -f release-${wave} ]; do sleep 0.01; done; printf 'wave ${wave}\\n'; touch exited-${wave}-${i}; exit 7`, description: `wave ${wave} job ${i}`, timeout: 10,
|
|
63
|
+
action: "start", command: `while [ ! -f release-${wave} ]; do sleep 0.01; done; printf 'RESULT wave ${wave} job ${i}\\n'; touch exited-${wave}-${i}; exit 7`, description: `wave ${wave} job ${i}`, timeout: 10,
|
|
64
64
|
} });
|
|
65
65
|
if (requests === 2) {
|
|
66
66
|
if (process.env.BG_NOTIFICATION_MODE === "codemode") message.content.push({ type: "toolCall", id: "wait-second-wave", name: "codemode", arguments: { code: "text(await tools.synchronous_subagent_fixture({ wave: 1 }));" } });
|
|
@@ -19,16 +19,21 @@ export default function (pi: ExtensionAPI) {
|
|
|
19
19
|
queueMicrotask(() => {
|
|
20
20
|
const last = context.messages.at(-1) as any;
|
|
21
21
|
const text = typeof last?.content === "string" ? last.content : (last?.content ?? []).filter((block: any) => block.type === "text").map((block: any) => block.text).join("\n");
|
|
22
|
-
const media = context.messages.some((message: any) => JSON.stringify(message.content).includes("
|
|
22
|
+
const media = context.messages.some((message: any) => JSON.stringify(message.content).includes("background demo job"));
|
|
23
23
|
const tools = getCurrentTools(context.messages);
|
|
24
24
|
record({ event: "request", lastRole: last?.role, text: text.slice(0, 2000), tools: tools.map((tool) => tool.name),
|
|
25
|
-
backgroundDescription: tools.find((tool) => tool.name === "background_task")?.description
|
|
25
|
+
backgroundDescription: tools.find((tool) => tool.name === "background_task")?.description,
|
|
26
|
+
backgroundCommandDescription: tools.find((tool) => tool.name === "background_task")?.parameters?.properties?.command?.description });
|
|
26
27
|
const calls: { name: string; arguments: any }[] = [];
|
|
27
28
|
const call = (args: any) => calls.push({ name: "background_task", arguments: args });
|
|
28
29
|
if (last?.role !== "toolResult") {
|
|
29
30
|
if (text.includes("Start two background demo jobs")) {
|
|
30
31
|
call({ action: "start", command: "python3 demo-job.py build", description: "Build progress", timeout: 120 });
|
|
31
32
|
call({ action: "start", command: "python3 demo-job.py tests", description: "Test suite", timeout: 120 });
|
|
33
|
+
} else if (text.includes("Start one background demo job")) {
|
|
34
|
+
call({ action: "start", command: "python3 demo-job.py build", description: "Build progress", timeout: 120 });
|
|
35
|
+
} else if (text.includes("Start the second background demo job")) {
|
|
36
|
+
call({ action: "start", command: "python3 demo-job.py tests", description: "Test suite", timeout: 120 });
|
|
32
37
|
} else if (text.includes("SMOKE_START")) {
|
|
33
38
|
call({ action: "start", command: "sleep 9; printf 'BUILD SUCCESSFUL\\n'", description: "Release build", timeout: 30 });
|
|
34
39
|
call({ action: "start", command: "sleep 300", description: "Cancel this task", timeout: 300 });
|
|
@@ -61,7 +66,7 @@ catch { text("BACKGROUND_CALL_BLOCKED"); }` } });
|
|
|
61
66
|
} else {
|
|
62
67
|
const reply = text.includes("[Background task finished]") ? (media ? "Background jobs finished. Their status and captured logs remain available with /bg." : "BACKGROUND_NOTIFICATION_RECEIVED")
|
|
63
68
|
: media
|
|
64
|
-
? "Both demo jobs are running. Click a task row below to open its live Herdr pane; closing the pane does not stop the job
|
|
69
|
+
? `${tasks.size === 1 ? "One demo job is" : "Both demo jobs are"} running. Click a task row below to open its live Herdr pane; closing the pane does not stop the job.`
|
|
65
70
|
: "Main agent is ready; accepted background tasks keep running.";
|
|
66
71
|
message.content.push({ type: "text", text: reply });
|
|
67
72
|
stream.push({ type: "text_start", contentIndex: 0, partial: message });
|
package/tests/interruptions.mjs
CHANGED
|
@@ -19,6 +19,7 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
|
|
|
19
19
|
const release = join(directory, "release");
|
|
20
20
|
const exited = join(directory, "exited");
|
|
21
21
|
const requests = [], settlements = [], errors = [];
|
|
22
|
+
const warmupRequests = timing === "after active compaction" ? 1 : 0;
|
|
22
23
|
let session, task, output, holding = false, summaries = 0;
|
|
23
24
|
const waitFor = async (check, label) => {
|
|
24
25
|
for (let i = 0; i < 1000; i++) {
|
|
@@ -43,11 +44,14 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
|
|
|
43
44
|
if (compacting) {
|
|
44
45
|
message.stopReason = "stop";
|
|
45
46
|
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
|
|
47
|
-
|
|
47
|
+
} else if (requests.length <= warmupRequests) {
|
|
48
|
+
message.stopReason = "stop";
|
|
49
|
+
message.content.push({ type: "text", text: "WARMUP_ACK" });
|
|
50
|
+
} else if (requests.length === warmupRequests + 1) message.content.push({ type: "toolCall", id: "start-job", name: "background_task", arguments: {
|
|
51
|
+
action: "start", command: "while [ ! -f release ]; do sleep 0.01; done; printf 'late shell result\\n'; printf done > exited; exit 7", description: "Interrupted shell fixture", timeout: 10,
|
|
48
52
|
} });
|
|
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 } });
|
|
53
|
+
else if (requests.length === warmupRequests + 2) message.content.push({ type: "toolCall", id: "hold-turn", name: "interrupt_fixture", arguments: {} });
|
|
54
|
+
else if (requests.length === warmupRequests + 3) message.content.push({ type: "toolCall", id: "read-result", name: "background_task", arguments: { action: "output", id: task.id } });
|
|
51
55
|
else {
|
|
52
56
|
message.stopReason = "stop";
|
|
53
57
|
message.content.push({ type: "text", text: "RESUMED_RESULT_ACK" });
|
|
@@ -87,6 +91,9 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
|
|
|
87
91
|
else if (event.result.structuredContent.action === "output") output = event.result.structuredContent;
|
|
88
92
|
});
|
|
89
93
|
await session.bindExtensions({});
|
|
94
|
+
// Native compaction needs an earlier completed turn; do not depend
|
|
95
|
+
// on how verbose the background tool's start result happens to be.
|
|
96
|
+
if (warmupRequests) await session.prompt("Warmup history to summarize. ".repeat(200));
|
|
90
97
|
const prompting = session.prompt("Start a job and hold the agent so the user can interrupt. " + "Prior history to compact. ".repeat(200));
|
|
91
98
|
await waitFor(() => holding, "the real blocking tool");
|
|
92
99
|
assert.equal(task.status, "running");
|
|
@@ -102,32 +109,34 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
|
|
|
102
109
|
} else await session.abort();
|
|
103
110
|
await prompting;
|
|
104
111
|
const interruptedAt = Date.now();
|
|
105
|
-
assert.deepEqual(settlements, [true], "native settlement must confirm the user interrupt");
|
|
112
|
+
assert.deepEqual(settlements, [...Array(warmupRequests).fill(false), true], "native settlement must confirm the user interrupt");
|
|
106
113
|
assert.equal(session.isIdle, true);
|
|
107
114
|
writeFileSync(release, "finish after user interruption");
|
|
108
115
|
await waitFor(() => existsSync(exited), "the background shell surviving the interrupt");
|
|
109
116
|
await delay(1250);
|
|
110
|
-
assert.equal(requests.length, 2, "late completion must not start a model request");
|
|
117
|
+
assert.equal(requests.length, warmupRequests + 2, "late completion must not start a model request");
|
|
111
118
|
assert.match(readFileSync(task.log_path, "utf8"), /late shell result/);
|
|
112
119
|
assert.equal(session.isIdle, true);
|
|
113
120
|
await session.prompt("Continue and inspect the completed job.");
|
|
114
|
-
assert.equal(requests.length, 4);
|
|
115
|
-
const resumedContext = JSON.stringify(requests[2]);
|
|
121
|
+
assert.equal(requests.length, warmupRequests + 4);
|
|
122
|
+
const resumedContext = JSON.stringify(requests[warmupRequests + 2]);
|
|
116
123
|
assert.equal((resumedContext.match(/\[Background task finished\]/g) ?? []).length, 1, "retained completion enters context before the resumed model request");
|
|
117
124
|
assert.ok(resumedContext.includes(task.id));
|
|
118
125
|
assert.equal(output.task.exit_code, 7);
|
|
119
126
|
assert.equal(output.output, "late shell result\n");
|
|
120
127
|
await delay(50);
|
|
121
|
-
assert.equal(requests.length, 4, "consumed completion must not trigger another turn");
|
|
128
|
+
assert.equal(requests.length, warmupRequests + 4, "consumed completion must not trigger another turn");
|
|
122
129
|
const notifications = session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === "background-task-finished");
|
|
123
130
|
assert.equal(notifications.length, 1);
|
|
131
|
+
assert.doesNotMatch(notifications[0].content, /late shell result/);
|
|
132
|
+
assert.ok(notifications[0].content.includes(task.log_path));
|
|
124
133
|
assert.equal(notifications[0].details.tasks[0].id, task.id);
|
|
125
134
|
assert.equal(notifications[0].details.tasks[0].status, "failed");
|
|
126
135
|
if (timing === "before interrupt") assert.ok(notifications[0].details.tasks[0].ended_at <= interruptRequestedAt);
|
|
127
136
|
else assert.ok(notifications[0].details.tasks[0].ended_at >= interruptedAt);
|
|
128
137
|
assert.equal(session.getLastAssistantText(), "RESUMED_RESULT_ACK");
|
|
129
138
|
assert.deepEqual(errors, []);
|
|
130
|
-
t.diagnostic(JSON.stringify({ timing, requestsBeforeResume: 2, requestsAfterResume: 4, pendingDeliveredOnce: true, lateResultRecovered: true }));
|
|
139
|
+
t.diagnostic(JSON.stringify({ timing, warmupRequests, requestsBeforeResume: warmupRequests + 2, requestsAfterResume: warmupRequests + 4, pendingDeliveredOnce: true, lateResultRecovered: true }));
|
|
131
140
|
} finally {
|
|
132
141
|
if (session) {
|
|
133
142
|
await session.abort();
|
package/tests/media.mjs
CHANGED
|
@@ -52,3 +52,19 @@ test("offline media provider issues exactly two direct background starts, then r
|
|
|
52
52
|
assert.equal(next.filter((event) => event.type === "toolcall_end").length, 0);
|
|
53
53
|
assert.match(next.find((event) => event.type === "text_end").content, /Click a task row/);
|
|
54
54
|
});
|
|
55
|
+
|
|
56
|
+
for (const [prompt, kind] of [
|
|
57
|
+
["Start one background demo job: build progress.", "build"],
|
|
58
|
+
["Start the second background demo job: a test suite.", "tests"],
|
|
59
|
+
]) {
|
|
60
|
+
test(`offline media provider can start the ${kind} job separately for single-pane verification`, async () => {
|
|
61
|
+
let provider;
|
|
62
|
+
register({ registerProvider(_name, value) { provider = value; }, on() {} });
|
|
63
|
+
const events = [];
|
|
64
|
+
for await (const event of provider.streamSimple({ api: "bg-fixture", provider: "bg-fixture", id: "deterministic" }, { messages: [{ role: "user", content: prompt }] })) events.push(event);
|
|
65
|
+
const calls = events.filter((event) => event.type === "toolcall_end").map((event) => event.toolCall);
|
|
66
|
+
assert.equal(calls.length, 1);
|
|
67
|
+
assert.equal(calls[0].name, "background_task");
|
|
68
|
+
assert.equal(calls[0].arguments.command, `python3 demo-job.py ${kind}`);
|
|
69
|
+
});
|
|
70
|
+
}
|
package/tests/notifications.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import { fileURLToPath } from "node:url";
|
|
|
7
7
|
import { test } from "node:test";
|
|
8
8
|
import { piBinary } from "./runtime.mjs";
|
|
9
9
|
|
|
10
|
-
test("native model receives
|
|
10
|
+
test("native model receives distinct declaration and start guidance without Codemode instructions", () => {
|
|
11
11
|
const directory = mkdtempSync(join(tmpdir(), "pi-bg-guidance-"));
|
|
12
12
|
try {
|
|
13
13
|
const events = join(directory, "events.jsonl");
|
|
@@ -22,13 +22,17 @@ test("native model receives concise start guidance without Codemode instructions
|
|
|
22
22
|
const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
|
|
23
23
|
const started = records.find((entry) => entry.event === "tool_end" && entry.name === "background_task");
|
|
24
24
|
assert.equal(started.isError, false);
|
|
25
|
-
const
|
|
26
|
-
assert.equal(guidance,
|
|
25
|
+
const notice = "Completion is reported automatically. Continue other work, or end the turn if nothing else remains; do not sleep, tail logs or query just to wait.";
|
|
26
|
+
assert.equal(started.result.structuredContent.guidance, undefined);
|
|
27
27
|
assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "codemode"), false);
|
|
28
28
|
const requests = records.filter((entry) => entry.event === "request");
|
|
29
|
-
assert.
|
|
29
|
+
assert.match(requests[0].backgroundCommandDescription, /Stdout\/stderr are saved to a unique per-task log; its path is reported on completion\./);
|
|
30
|
+
assert.match(requests[0].backgroundDescription, /automatic completion notifications/);
|
|
31
|
+
assert.match(requests[0].backgroundDescription, /session changes, reload, or exit/);
|
|
32
|
+
assert.ok(!requests[0].backgroundDescription.includes(notice));
|
|
30
33
|
assert.ok(!requests[0].backgroundDescription.includes("Codemode:"));
|
|
31
|
-
assert.ok(requests[1].text.includes(
|
|
34
|
+
assert.ok(requests[1].text.includes(notice), "the next model request sees the task-specific reminder");
|
|
35
|
+
assert.ok(!started.result.content[0].text.includes(started.result.structuredContent.task.log_path));
|
|
32
36
|
} finally { rmSync(directory, { recursive: true, force: true }); }
|
|
33
37
|
});
|
|
34
38
|
|
|
@@ -89,6 +93,11 @@ for (const mode of ["codemode", "direct"]) {
|
|
|
89
93
|
assert.equal(tasks.length, 4 - reads);
|
|
90
94
|
assert.ok(tasks.every((task) => task.status === "failed" && task.exit_code === 7));
|
|
91
95
|
assert.ok(tasks.every((task) => !returned.consumed.includes(task.id)));
|
|
96
|
+
for (const task of tasks) assert.ok(message.content.includes(task.log_path), "completion provides the captured output location");
|
|
97
|
+
assert.doesNotMatch(message.content, /RESULT wave/, "command output is not injected automatically");
|
|
98
|
+
assert.match(message.content, /Inspect logs progressively as needed/);
|
|
99
|
+
for (const task of returned.tasks.filter((task) => returned.consumed.includes(task.id))) assert.ok(!message.content.includes(`RESULT ${task.description}`), "consumed output is not delivered twice");
|
|
100
|
+
assert.ok(Buffer.byteLength(message.content) <= 16384);
|
|
92
101
|
assert.deepEqual([...returned.consumed, ...tasks.map((task) => task.id)].sort(), returned.tasks.map((task) => task.id).sort());
|
|
93
102
|
const toolEnd = transcript.findLastIndex((entry) => entry.type === "tool_execution_end" && ["synchronous_subagent_fixture", "codemode"].includes(entry.toolName));
|
|
94
103
|
assert.ok(toolEnd >= 0 && transcript.indexOf(notifications[0]) > toolEnd, "the notification cannot interrupt the synchronous tool");
|
|
@@ -99,7 +108,10 @@ for (const mode of ["codemode", "direct"]) {
|
|
|
99
108
|
assert.equal((nextContext.match(/\[Background task finished\]/g) ?? []).length, 1);
|
|
100
109
|
assert.doesNotMatch(nextContext, /FINAL_REPORT/, "completion is delivered before, not after, the final report");
|
|
101
110
|
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)))
|
|
111
|
+
for (const task of returned.tasks.filter((task) => !returned.consumed.includes(task.id))) {
|
|
112
|
+
assert.ok(contextText.includes(task.id));
|
|
113
|
+
assert.ok(contextText.includes(task.log_path), "the next model request can locate output for on-demand inspection");
|
|
114
|
+
}
|
|
103
115
|
} finally { rmSync(directory, { recursive: true, force: true }); }
|
|
104
116
|
});
|
|
105
117
|
}
|
package/tests/output.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { test } from "node:test";
|
|
3
|
-
import { writeFileSync } from "node:fs";
|
|
3
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { createBashTool } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { createBashTool, truncateTail } from "@earendil-works/pi-coding-agent";
|
|
6
6
|
import { fixture, flush } from "./helpers.mjs";
|
|
7
7
|
|
|
8
8
|
const cases = [
|
|
@@ -17,8 +17,27 @@ const cases = [
|
|
|
17
17
|
["utf8-long-line", Buffer.from("δΈζπ".repeat(130000))],
|
|
18
18
|
["invalid-utf8", Buffer.from([65, 0xf0, 0x9f])],
|
|
19
19
|
];
|
|
20
|
+
|
|
21
|
+
test("output exposes one bounded tail in both views while the full log remains on disk", async () => {
|
|
22
|
+
const f = fixture();
|
|
23
|
+
try {
|
|
24
|
+
const job = f.tasks.start({ command: "fixture" }, f.root);
|
|
25
|
+
const data = Array.from({ length: 110 }, (_, i) => `line-${i}`).join("\n");
|
|
26
|
+
f.calls[0].onData(Buffer.from(data));
|
|
27
|
+
f.calls[0].resolve();
|
|
28
|
+
await flush();
|
|
29
|
+
const result = f.tasks.output(job.id);
|
|
30
|
+
assert.equal(result.output, Array.from({ length: 100 }, (_, i) => `line-${i + 10}`).join("\n"));
|
|
31
|
+
assert.equal(result.output, result.truncation.content);
|
|
32
|
+
assert.ok(result.text.startsWith(result.output));
|
|
33
|
+
assert.equal(result.truncated, true);
|
|
34
|
+
assert.equal(result.truncation.totalLines, 110);
|
|
35
|
+
assert.equal(result.bytes, Buffer.byteLength(data));
|
|
36
|
+
} finally { await f.close(); }
|
|
37
|
+
});
|
|
38
|
+
|
|
20
39
|
for (const [name, data] of cases) {
|
|
21
|
-
test(`output
|
|
40
|
+
test(`bounded output compared with native bash model/structured views: ${name}`, async () => {
|
|
22
41
|
const f = fixture();
|
|
23
42
|
try {
|
|
24
43
|
const path = join(f.root, "fixture.log");
|
|
@@ -31,12 +50,17 @@ for (const [name, data] of cases) {
|
|
|
31
50
|
await flush();
|
|
32
51
|
const actual = f.tasks.output(job.id);
|
|
33
52
|
const normalize = (text) => text.replace(/Full output: [^\]]+/g, "Full output: <log>");
|
|
34
|
-
|
|
35
|
-
assert.equal(actual.output,
|
|
36
|
-
assert.equal(actual.
|
|
53
|
+
const expected = truncateTail(native.structuredContent.output, { maxLines: 100, maxBytes: 8192 });
|
|
54
|
+
assert.equal(actual.output, expected.content);
|
|
55
|
+
assert.equal(actual.output, actual.truncation.content);
|
|
56
|
+
assert.equal(actual.truncated, native.structuredContent.truncated || expected.truncated);
|
|
57
|
+
if (!actual.truncated) assert.equal(normalize(actual.text), normalize(native.content[0].text));
|
|
58
|
+
else assert.match(actual.text, /Showing .*Full output:/);
|
|
59
|
+
if (name === "long-line-with-newline") assert.match(actual.text, /line is 146\.5KB/);
|
|
60
|
+
assert.deepEqual(readFileSync(actual.log_path), data);
|
|
37
61
|
assert.equal(actual.capture_complete, true);
|
|
38
|
-
assert.ok(Buffer.byteLength(actual.truncation.content) <=
|
|
39
|
-
assert.ok(Buffer.byteLength(actual.output)
|
|
62
|
+
assert.ok(Buffer.byteLength(actual.truncation.content) <= 8192);
|
|
63
|
+
assert.ok(Buffer.byteLength(actual.output) <= 8192);
|
|
40
64
|
} finally { await f.close(); }
|
|
41
65
|
});
|
|
42
66
|
}
|
package/tests/processes.mjs
CHANGED
|
@@ -90,7 +90,7 @@ test("native large output truncates display, then stops at the 32 MiB disk budge
|
|
|
90
90
|
assert.equal(result.bytes, 32 * 1024 * 1024);
|
|
91
91
|
assert.equal(result.capture_complete, false);
|
|
92
92
|
assert.equal(result.truncated, true);
|
|
93
|
-
assert.ok(result.truncation.outputBytes <=
|
|
94
|
-
assert.ok(Buffer.byteLength(result.output)
|
|
93
|
+
assert.ok(result.truncation.outputBytes <= 8192);
|
|
94
|
+
assert.ok(Buffer.byteLength(result.output) <= 8192);
|
|
95
95
|
} finally { await tasks.shutdown(); }
|
|
96
96
|
});
|
package/tests/runtime.mjs
CHANGED
|
@@ -7,10 +7,22 @@ import { pathToFileURL } from "node:url";
|
|
|
7
7
|
|
|
8
8
|
// npm prepends workspace .bin paths, which may contain an older development Pi.
|
|
9
9
|
const hostPath = (process.env.PATH ?? "").split(delimiter).filter((entry) => !entry.endsWith("node_modules/.bin")).join(delimiter);
|
|
10
|
+
// The managed installer's launcher is a shell script outside the Pi package. Like
|
|
11
|
+
// that launcher, read install/current-version on each run so Pi updates need no change.
|
|
12
|
+
function managedPiModules(launcher) {
|
|
13
|
+
const install = join(dirname(launcher), "..", "install");
|
|
14
|
+
try {
|
|
15
|
+
const version = readFileSync(join(install, "current-version"), "utf8").trim();
|
|
16
|
+
const modules = join(install, "releases", version, "node_modules");
|
|
17
|
+
return existsSync(join(modules, "@earendil-works", "pi-coding-agent", "package.json")) ? modules : undefined;
|
|
18
|
+
} catch { return undefined; }
|
|
19
|
+
}
|
|
10
20
|
const binary = process.env.PI_TEST_BINARY || execFileSync("sh", ["-c", "command -v pi"], { encoding: "utf8", env: { ...process.env, PATH: hostPath } }).trim();
|
|
11
21
|
let root = dirname(realpathSync(binary));
|
|
12
22
|
while (!existsSync(join(root, "package.json")) || JSON.parse(readFileSync(join(root, "package.json"), "utf8")).name !== "@earendil-works/pi-coding-agent") {
|
|
13
23
|
const parent = dirname(root);
|
|
24
|
+
const managed = parent === root ? managedPiModules(realpathSync(binary)) : undefined;
|
|
25
|
+
if (managed) { root = join(managed, "@earendil-works", "pi-coding-agent"); break; }
|
|
14
26
|
if (parent === root) throw new Error(`Cannot locate Pi runtime next to ${binary}`);
|
|
15
27
|
root = parent;
|
|
16
28
|
}
|