@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.
@@ -1,4 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
+ import { unlinkSync } from "node:fs";
2
3
  import { test } from "node:test";
3
4
  import { visibleWidth } from "@earendil-works/pi-tui";
4
5
  import register from "../extensions/background-tasks.ts";
@@ -13,10 +14,11 @@ function harness(mode = "tui", hasUI = true) {
13
14
  const widgets = new Map([["scheduler", { render: () => ["Scheduler"] }], ["herdr-subagents", { render: () => ["Fleet"] }]]);
14
15
  const placements = new Map();
15
16
  const statuses = new Map();
16
- let tool, renders = 0;
17
+ const idleChecks = [];
18
+ let tool, renders = 0, idle = true;
17
19
  const theme = { fg: (_color, text) => text, bold: (text) => text };
18
20
  const ctx = {
19
- cwd: f.root, mode, hasUI,
21
+ cwd: f.root, mode, hasUI, isIdle: () => { idleChecks.push(f.clock.now()); return idle; },
20
22
  ui: {
21
23
  setWidget(key, factory, options) {
22
24
  if (!factory) { widgets.delete(key); return; }
@@ -35,7 +37,8 @@ function harness(mode = "tui", hasUI = true) {
35
37
  };
36
38
  register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root });
37
39
  return {
38
- ...f, handlers, commands, messages, notices, widgets, placements, statuses, ctx,
40
+ ...f, handlers, commands, messages, notices, widgets, placements, statuses, idleChecks, ctx,
41
+ setIdle(value) { idle = value; },
39
42
  get tool() { return tool; }, get renders() { return renders; },
40
43
  async close() {
41
44
  const closing = handlers.get("session_shutdown")({}, ctx);
@@ -46,24 +49,319 @@ function harness(mode = "tui", hasUI = true) {
46
49
  };
47
50
  }
48
51
 
52
+ test("completions during a synchronous tool are merged before the next model request", async () => {
53
+ const h = harness();
54
+ try {
55
+ await h.handlers.get("session_start")({}, h.ctx);
56
+ h.setIdle(false);
57
+ for (const command of ["first", "second"]) await h.tool.execute(command, { action: "start", command });
58
+ h.calls[0].resolve(1);
59
+ h.calls[1].resolve(2);
60
+ await flush();
61
+ assert.equal(h.messages.length, 0, "busy completions must not enter an irrevocable host queue");
62
+ assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /failed/);
63
+ const existing = { type: "custom", customType: "other-extension", data: { preserved: true } };
64
+ const boundary = h.handlers.get("turn_end")({ entries: [existing], continue: true, outcome: "completed" }, h.ctx);
65
+ assert.equal(boundary.continue, true);
66
+ assert.equal(boundary.entries.length, 2);
67
+ assert.deepEqual(boundary.entries[0], existing);
68
+ assert.equal(boundary.entries[1].details.tasks.length, 2);
69
+ assert.match(boundary.entries[1].content, /Ended at: 1970-01-01T00:00:01.000Z/);
70
+ assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx), undefined);
71
+ } finally { await h.close(); }
72
+ });
73
+
74
+ test("a completion during manual compaction wakes after idle without another agent boundary", async () => {
75
+ const h = harness("print", false);
76
+ try {
77
+ await h.handlers.get("session_start")({}, h.ctx);
78
+ await h.tool.execute("start", { action: "start", command: "first" });
79
+ h.setIdle(false);
80
+ h.calls[0].resolve();
81
+ await flush();
82
+ h.clock.advance(0);
83
+ h.clock.advance(1000);
84
+ assert.equal(h.messages.length, 0);
85
+ h.setIdle(true); // Manual compaction succeeds, fails or is cancelled; none emits agent_settled.
86
+ h.clock.advance(2000);
87
+ assert.equal(h.messages.length, 1);
88
+ assert.equal(h.clock.timers.size, 0);
89
+ } finally { await h.close(); }
90
+ });
91
+
92
+ test("busy notification checks back off to 30 seconds without expiring unread results", async () => {
93
+ const h = harness("print", false);
94
+ try {
95
+ await h.handlers.get("session_start")({}, h.ctx);
96
+ h.setIdle(false);
97
+ await h.tool.execute("start", { action: "start", command: "first" });
98
+ h.calls[0].resolve();
99
+ await flush();
100
+ const started = h.clock.now();
101
+ h.clock.advance(91000);
102
+ assert.deepEqual(h.idleChecks.map((time) => time - started), [0, 1000, 3000, 7000, 15000, 31000, 61000, 91000]);
103
+ assert.equal(h.messages.length, 0);
104
+ assert.equal(h.clock.timers.size, 1);
105
+ h.clock.advance(24 * 60 * 60 * 1000);
106
+ assert.equal(h.messages.length, 0, "no timeout may silently drop the unread batch");
107
+ assert.equal(h.clock.timers.size, 1);
108
+ h.setIdle(true);
109
+ const checks = h.idleChecks.length;
110
+ h.clock.advance(29999);
111
+ assert.equal(h.idleChecks.length, checks);
112
+ h.clock.advance(1);
113
+ assert.equal(h.messages.length, 1);
114
+ assert.equal(h.clock.timers.size, 0);
115
+ } finally { await h.close(); }
116
+ });
117
+
118
+ test("new completions share the backed-off timer, while tool boundaries deliver immediately and reset backoff", async () => {
119
+ const h = harness("print", false);
120
+ try {
121
+ await h.handlers.get("session_start")({}, h.ctx);
122
+ h.setIdle(false);
123
+ await h.tool.execute("start", { action: "start", command: "first" });
124
+ h.calls[0].resolve();
125
+ await flush();
126
+ h.clock.advance(61000);
127
+ await h.tool.execute("second", { action: "start", command: "second" });
128
+ h.calls[1].resolve();
129
+ await flush();
130
+ assert.equal(h.clock.timers.size, 1);
131
+ const checks = h.idleChecks.length;
132
+ h.clock.advance(0);
133
+ assert.equal(h.idleChecks.length, checks, "a new completion must not restart an active backoff");
134
+ const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
135
+ assert.equal(boundary.entries[0].details.tasks.length, 2);
136
+ assert.equal(h.clock.timers.size, 0, "the boundary must not wait for the 30-second timer");
137
+ await h.tool.execute("third", { action: "start", command: "third" });
138
+ h.calls[2].resolve();
139
+ await flush();
140
+ h.clock.advance(0);
141
+ assert.equal(h.idleChecks.length, checks + 1, "a fresh batch starts with an immediate check");
142
+ h.clock.advance(999);
143
+ assert.equal(h.idleChecks.length, checks + 1);
144
+ h.clock.advance(1);
145
+ assert.equal(h.idleChecks.length, checks + 2, "a fresh batch retries after one second, not thirty");
146
+ } finally { await h.close(); }
147
+ });
148
+
149
+ for (const action of ["agent_before_settle", "output", "aborted", "error", "session_shutdown"]) {
150
+ test(`${action} clears a capped notification retry without stale wakes`, async () => {
151
+ const h = harness("print", false);
152
+ try {
153
+ await h.handlers.get("session_start")({}, h.ctx);
154
+ h.setIdle(false);
155
+ const task = (await h.tool.execute("start", { action: "start", command: "first" })).structuredContent.task;
156
+ h.calls[0].resolve();
157
+ await flush();
158
+ h.clock.advance(61000);
159
+ assert.equal(h.clock.timers.size, 1);
160
+ if (action === "output") {
161
+ await h.tool.execute("read", { action, id: task.id });
162
+ } else if (action === "session_shutdown") {
163
+ await h.handlers.get(action)({}, h.ctx);
164
+ await h.handlers.get("session_start")({}, h.ctx);
165
+ } else {
166
+ const event = { entries: [], outcome: action === "agent_before_settle" ? "completed" : action };
167
+ const boundary = h.handlers.get("agent_before_settle")(event, h.ctx);
168
+ if (action === "agent_before_settle") assert.equal(boundary.entries[0].details.tasks[0].id, task.id);
169
+ else assert.equal(boundary, undefined);
170
+ }
171
+ assert.equal(h.clock.timers.size, 0);
172
+ h.setIdle(true);
173
+ const checks = h.idleChecks.length;
174
+ h.clock.advance(24 * 60 * 60 * 1000);
175
+ assert.equal(h.idleChecks.length, checks);
176
+ assert.equal(h.messages.length, 0);
177
+ } finally { await h.close(); }
178
+ });
179
+ }
180
+
181
+ test("failed terminal log reads do not consume pending completion", async () => {
182
+ const h = harness("print", false);
183
+ try {
184
+ await h.handlers.get("session_start")({}, h.ctx);
185
+ h.setIdle(false);
186
+ const task = (await h.tool.execute("start", { action: "start", command: "first" })).structuredContent.task;
187
+ h.calls[0].resolve();
188
+ await flush();
189
+ unlinkSync(task.log_path);
190
+ const result = await h.tool.execute("read", { action: "output", id: task.id });
191
+ assert.equal(result.isError, true);
192
+ assert.match(result.structuredContent.error, /Cannot read task log/);
193
+ const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
194
+ assert.equal(boundary.entries[0].details.tasks[0].id, task.id);
195
+ } finally { await h.close(); }
196
+ });
197
+
198
+ test("terminal output consumed by the agent removes only that pending reminder", async () => {
199
+ const h = harness();
200
+ try {
201
+ await h.handlers.get("session_start")({}, h.ctx);
202
+ h.setIdle(false);
203
+ const a = (await h.tool.execute("a", { action: "start", command: "first" })).structuredContent.task;
204
+ const b = (await h.tool.execute("b", { action: "start", command: "second" })).structuredContent.task;
205
+ await h.tool.execute("running", { action: "output", id: b.id });
206
+ h.calls[0].resolve(7);
207
+ h.calls[1].resolve();
208
+ await flush();
209
+ await h.tool.execute("list", { action: "list" });
210
+ await h.commands.get("bg").handler(`output ${b.id}`, h.ctx);
211
+ const output = await h.tool.execute("read", { action: "output", id: a.id });
212
+ assert.equal(output.isError, true, "a nonzero command is still a successful log read");
213
+ const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
214
+ assert.deepEqual(boundary.entries[0].details.tasks.map((task) => task.id), [b.id]);
215
+ assert.equal(h.messages.length, 1, "only the user's inspection message was sent");
216
+ } finally { await h.close(); }
217
+ });
218
+
219
+ test("idle completions coalesce, but a newly busy session receives them at its next boundary", async () => {
220
+ const h = harness();
221
+ try {
222
+ await h.handlers.get("session_start")({}, h.ctx);
223
+ for (const command of ["first", "second"]) await h.tool.execute(command, { action: "start", command });
224
+ h.calls[0].resolve();
225
+ h.calls[1].resolve(1);
226
+ await flush();
227
+ assert.equal(h.messages.length, 0);
228
+ h.setIdle(false);
229
+ h.clock.advance(0);
230
+ assert.equal(h.messages.length, 0, "idle wake must recheck state before sending");
231
+ const boundary = h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx);
232
+ assert.equal(boundary.entries[0].details.tasks.length, 2);
233
+ assert.equal(boundary.continue, true);
234
+ assert.equal(h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx), undefined);
235
+ } finally { await h.close(); }
236
+ });
237
+
238
+ test("idle wake batches current completions and a terminal read can remove the whole batch", async () => {
239
+ const h = harness("print", false);
240
+ try {
241
+ await h.handlers.get("session_start")({}, h.ctx);
242
+ for (const command of ["first", "second"]) await h.tool.execute(command, { action: "start", command });
243
+ h.calls[0].resolve();
244
+ h.calls[1].resolve(1);
245
+ await flush();
246
+ h.clock.advance(0);
247
+ assert.equal(h.messages.length, 1);
248
+ assert.equal(h.messages[0].message.details.tasks.length, 2);
249
+ const task = (await h.tool.execute("third", { action: "start", command: "third" })).structuredContent.task;
250
+ h.calls[2].resolve();
251
+ await flush();
252
+ await h.tool.execute("read", { action: "output", id: task.id });
253
+ h.clock.advance(0);
254
+ assert.equal(h.messages.length, 1);
255
+ assert.equal(h.clock.timers.size, 0);
256
+ } finally { await h.close(); }
257
+ });
258
+
259
+ for (const outcome of ["aborted", "error"]) {
260
+ test(`${outcome} boundaries do not force continuation or replay a scheduled idle wake`, async () => {
261
+ const h = harness();
262
+ try {
263
+ await h.handlers.get("session_start")({}, h.ctx);
264
+ await h.tool.execute("start", { action: "start", command: "first" });
265
+ h.calls[0].resolve();
266
+ await flush();
267
+ h.setIdle(false);
268
+ assert.equal(h.handlers.get("turn_end")({ entries: [], outcome }, h.ctx), undefined);
269
+ assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome }, h.ctx), undefined);
270
+ h.handlers.get("agent_settled")({ aborted: outcome === "aborted" }, h.ctx);
271
+ h.setIdle(true);
272
+ h.clock.advance(0);
273
+ assert.equal(h.messages.length, 0);
274
+ if (outcome === "aborted") {
275
+ const resumed = h.handlers.get("before_agent_start")({ messageType: "user", prompt: "Continue" }, h.ctx);
276
+ assert.equal(resumed.message.details.tasks.length, 1, "the next user prompt receives retained results");
277
+ assert.equal(h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx), undefined);
278
+ return;
279
+ }
280
+ const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
281
+ assert.equal(boundary.entries[0].details.tasks.length, 1, "unread results remain available");
282
+ } finally { await h.close(); }
283
+ });
284
+ }
285
+
286
+ test("jobs finishing after a user interrupt stay queryable without restarting the agent until the next user prompt", async () => {
287
+ const h = harness("print", false);
288
+ try {
289
+ await h.handlers.get("session_start")({}, h.ctx);
290
+ const tasks = [];
291
+ for (const command of ["first", "second"]) {
292
+ tasks.push((await h.tool.execute(command, { action: "start", command })).structuredContent.task);
293
+ }
294
+ h.setIdle(false);
295
+ h.handlers.get("turn_end")({ entries: [], outcome: "aborted" }, h.ctx);
296
+ h.handlers.get("agent_before_settle")({ entries: [], outcome: "aborted" }, h.ctx);
297
+ h.handlers.get("agent_settled")({ aborted: true }, h.ctx);
298
+ h.setIdle(true);
299
+ for (const call of h.calls) {
300
+ assert.equal(call.signal.aborted, false, "interrupting the agent must not cancel accepted jobs");
301
+ call.resolve(7);
302
+ }
303
+ await flush();
304
+ h.clock.advance(24 * 60 * 60 * 1000);
305
+ assert.equal(h.messages.length, 0, "late completions must not restart the interrupted agent");
306
+ assert.equal(h.clock.timers.size, 0);
307
+ const list = await h.tool.execute("list", { action: "list" });
308
+ assert.ok(list.structuredContent.tasks.every((task) => task.status === "failed"));
309
+ assert.equal(h.handlers.get("before_agent_start")?.({ messageType: "custom" }, h.ctx), undefined);
310
+ assert.equal(h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx), undefined, "another extension's run must not release the interrupt");
311
+ const output = await h.tool.execute("read", { action: "output", id: tasks[0].id });
312
+ assert.equal(output.structuredContent.task.exit_code, 7);
313
+ const resumed = h.handlers.get("before_agent_start")({ messageType: "user", prompt: "Continue" }, h.ctx);
314
+ assert.deepEqual(resumed.message.details.tasks.map((task) => task.id), [tasks[1].id]);
315
+ assert.equal(h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx), undefined);
316
+ await h.tool.execute("new", { action: "start", command: "new" });
317
+ h.calls[2].resolve();
318
+ await flush();
319
+ h.clock.advance(0);
320
+ assert.equal(h.messages.length, 1, "the user prompt restores normal automatic delivery");
321
+ } finally { await h.close(); }
322
+ });
323
+
49
324
  test("registration is compact, does not inject prompt rules or start session resources", async () => {
50
325
  const h = harness();
51
326
  try {
52
327
  assert.equal(h.tool.name, "background_task");
328
+ assert.equal(h.tool.exposure, "model-only");
53
329
  assert.match(h.tool.description, /return task IDs immediately/);
54
- assert.ok(h.tool.description.length < 200);
330
+ assert.ok(h.tool.description.length < 500);
55
331
  assert.equal(h.tool.promptGuidelines, undefined);
56
332
  assert.ok(h.tool.outputSchema);
57
333
  assert.equal(h.tool.annotations.readOnlyHint, false);
58
334
  assert.equal(h.tool.annotations.destructiveHint, true);
59
- assert.ok(!h.handlers.has("before_agent_start"));
60
335
  assert.equal(h.clock.timers.size, 0);
61
336
  assert.equal(h.calls.length, 0);
62
337
  assert.equal((await h.tool.execute("early", { action: "list" })).isError, true);
63
338
  } finally { await h.close(); }
64
339
  });
65
340
 
66
- test("tools, commands, widget and followUp share the same session jobs", async () => {
341
+ test("start provides non-blocking next steps in both model text and structured results", async () => {
342
+ const h = harness();
343
+ try {
344
+ await h.handlers.get("session_start")({}, h.ctx);
345
+ const started = await h.tool.execute("start", { action: "start", command: "sleep 60" });
346
+ const { task, guidance } = started.structuredContent;
347
+ assert.equal(task.status, "running");
348
+ assert.equal(guidance, "Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.");
349
+ assert.ok(started.content[0].text.includes(guidance), "the start result must include the guidance");
350
+ assert.ok(h.tool.description.includes(guidance), "the tool description must include the same guidance");
351
+ assert.equal(h.tool.outputSchema.properties.guidance.type, "string");
352
+ assert.equal(h.tool.outputSchema.required?.includes("guidance") ?? false, false);
353
+ const list = await h.tool.execute("list", { action: "list" });
354
+ const output = await h.tool.execute("output", { action: "output", id: task.id });
355
+ assert.equal(list.structuredContent.guidance, undefined);
356
+ assert.equal(output.structuredContent.guidance, undefined);
357
+ h.calls[0].resolve();
358
+ await flush();
359
+ h.clock.advance(0);
360
+ assert.equal(h.messages.filter((entry) => entry.message.customType === "background-task-finished").length, 1);
361
+ } finally { await h.close(); }
362
+ });
363
+
364
+ test("tools, commands, widget and idle notifications share the same session jobs", async () => {
67
365
  const h = harness();
68
366
  try {
69
367
  await h.handlers.get("session_start")({}, h.ctx);
@@ -91,9 +389,10 @@ test("tools, commands, widget and followUp share the same session jobs", async (
91
389
 
92
390
  h.calls[0].resolve(7);
93
391
  await flush();
392
+ h.clock.advance(0);
94
393
  const completed = h.messages.filter((m) => m.message.customType === "background-task-finished");
95
394
  assert.equal(completed.length, 1);
96
- assert.deepEqual(completed[0].options, { triggerTurn: true, deliverAs: "followUp" });
395
+ assert.deepEqual(completed[0].options, { triggerTurn: true, deliverAs: "steer" });
97
396
  assert.match(completed[0].message.content, /failed.*exit 7/);
98
397
  assert.ok(!completed[0].message.content.includes("logs only"));
99
398
  assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /failed/);
@@ -117,6 +416,7 @@ test("cancel and shutdown are idempotent; new sessions cannot receive old comple
117
416
  const cancel = h.tool.execute("cancel", { action: "cancel", id: a.id });
118
417
  h.calls[0].reject(new Error("aborted"));
119
418
  assert.equal((await cancel).structuredContent.task.status, "cancelled");
419
+ h.clock.advance(0);
120
420
  const count = h.messages.length;
121
421
  await h.commands.get("bg").handler(`cancel ${a.id}`, h.ctx);
122
422
  assert.equal(h.messages.filter((m) => m.message.customType === "background-task-finished").length, 1);
@@ -145,9 +445,10 @@ for (const [mode, hasUI] of [["rpc", true], ["print", false], ["json", false]])
145
445
  if (hasUI) assert.match(h.statuses.get("background-tasks"), /1\/2/);
146
446
  h.calls[0].resolve();
147
447
  await flush();
448
+ h.clock.advance(0);
148
449
  assert.equal(h.clock.timers.size, 0);
149
450
  assert.equal(h.statuses.has("background-tasks"), false);
150
- assert.equal(h.messages.at(-1).options.deliverAs, "followUp");
451
+ assert.equal(h.messages.at(-1).options.deliverAs, "steer");
151
452
  } finally { await h.close(); }
152
453
  });
153
454
  }
@@ -157,7 +458,7 @@ test("bad actions, irrelevant fields, aborted acceptance and command syntax fail
157
458
  try {
158
459
  await h.handlers.get("session_start")({}, h.ctx);
159
460
  for (const params of [
160
- { action: "other" }, { action: "start" }, { action: "list", command: "ignored" },
461
+ { action: "other" }, { action: "notifications", enabled: false }, { action: "start" }, { action: "list", command: "ignored" },
161
462
  { action: "output" }, { action: "cancel", id: "unknown" },
162
463
  { action: "start", command: "x", id: "irrelevant" },
163
464
  ]) {
@@ -0,0 +1,87 @@
1
+ // Sequential fixture tools hold one native batch open; background calls remain model-issued.
2
+ import { appendFileSync, existsSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
6
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
+ import { Type } from "typebox";
8
+
9
+ export default function (pi: ExtensionAPI) {
10
+ const record = (entry: unknown) => appendFileSync(process.env.BG_NOTIFICATION_EVENTS!, JSON.stringify(entry) + "\n");
11
+ const tasks = new Map<string, any>();
12
+ const consumed: string[] = [];
13
+ let finished = false;
14
+ pi.registerTool({
15
+ name: "synchronous_subagent_fixture", label: "Synchronous subagent fixture",
16
+ description: "Wait for two real shell jobs while holding one synchronous tool call open.",
17
+ parameters: Type.Object({ wave: Type.Number() }), executionMode: "sequential",
18
+ async execute(_id, { wave }, _signal, _update, ctx) {
19
+ record({ event: "waiting", wave });
20
+ writeFileSync(join(ctx.cwd, `release-${wave}`), "ready");
21
+ for (let i = 0; i < 1000; i++) {
22
+ if ([0, 1].every((job) => existsSync(join(ctx.cwd, `exited-${wave}-${job}`)))) {
23
+ // Exit markers precede process exit. Let the native shell backend settle.
24
+ await delay(100);
25
+ if (wave === 1) finished = true;
26
+ return { content: [{ type: "text", text: "Synchronous subagent returned; shell wave finished." }], details: undefined };
27
+ }
28
+ await delay(5);
29
+ }
30
+ throw new Error("Fixture shell jobs did not finish");
31
+ },
32
+ });
33
+ pi.on("tool_execution_end", (event) => {
34
+ if (event.toolName !== "background_task") return;
35
+ const data = event.result.structuredContent as any;
36
+ if (data?.task) tasks.set(data.task.id, data.task);
37
+ if (data?.action === "output" && data.task.status !== "running") consumed.push(data.task.id);
38
+ });
39
+ pi.on("context", () => {
40
+ if (finished) {
41
+ record({ event: "returned", tasks: [...tasks.values()], consumed });
42
+ finished = false;
43
+ }
44
+ });
45
+ let requests = 0;
46
+ pi.registerProvider("bg-notifications", {
47
+ name: "Offline notification fixture", baseUrl: "http://127.0.0.1:1", api: "bg-notifications", apiKey: "fixture-not-a-secret",
48
+ models: [{ id: "deterministic", name: "Offline notification fixture", reasoning: false, input: ["text"], contextWindow: 128000, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
49
+ streamSimple(model, context) {
50
+ const stream = createAssistantMessageEventStream();
51
+ queueMicrotask(() => {
52
+ requests++;
53
+ record({ event: "request", number: requests, messages: context.messages });
54
+ const message: any = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: requests <= 2 ? "toolUse" : "stop",
55
+ usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
56
+ stream.push({ type: "start", partial: message });
57
+ if (requests <= 2) {
58
+ // First start a pair to obtain IDs. The second native batch waits, starts
59
+ // another pair, waits again, and reads selected outputs before its boundary.
60
+ const wave = requests - 1;
61
+ if (requests === 2) message.content.push({ type: "toolCall", id: "wait-first-wave", name: "synchronous_subagent_fixture", arguments: { wave: 0 } });
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,
64
+ } });
65
+ if (requests === 2) {
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 }));" } });
67
+ else message.content.push({ type: "toolCall", id: "wait-second-wave", name: "synchronous_subagent_fixture", arguments: { wave: 1 } });
68
+ // Only first-wave IDs are known to the model before this batch returns.
69
+ const reads = Number(process.env.BG_NOTIFICATION_READS);
70
+ for (const task of [...tasks.values()].slice(0, reads)) message.content.push({ type: "toolCall", id: `read-${task.id}`, name: "background_task", arguments: { action: "output", id: task.id } });
71
+ }
72
+ for (let i = 0; i < message.content.length; i++) {
73
+ stream.push({ type: "toolcall_start", contentIndex: i, partial: message });
74
+ stream.push({ type: "toolcall_end", contentIndex: i, toolCall: message.content[i], partial: message });
75
+ }
76
+ } else {
77
+ message.content.push({ type: "text", text: "FINAL_REPORT" });
78
+ stream.push({ type: "text_start", contentIndex: 0, partial: message });
79
+ stream.push({ type: "text_delta", contentIndex: 0, delta: "FINAL_REPORT", partial: message });
80
+ stream.push({ type: "text_end", contentIndex: 0, content: "FINAL_REPORT", partial: message });
81
+ }
82
+ stream.push({ type: "done", reason: message.stopReason, message });
83
+ });
84
+ return stream;
85
+ },
86
+ });
87
+ }
@@ -8,6 +8,8 @@ export default function (pi: ExtensionAPI) {
8
8
  if (process.env.BG_SMOKE_EVENTS) appendFileSync(process.env.BG_SMOKE_EVENTS, JSON.stringify(entry) + "\n");
9
9
  };
10
10
  let sequence = 0;
11
+ const tasks = new Map<string, any>();
12
+ const observedNotifications = new Set<string>();
11
13
  pi.registerProvider("bg-fixture", {
12
14
  name: "Offline background-task fixture", baseUrl: "http://127.0.0.1:1", api: "bg-fixture",
13
15
  apiKey: "fixture-not-a-secret",
@@ -17,31 +19,43 @@ export default function (pi: ExtensionAPI) {
17
19
  queueMicrotask(() => {
18
20
  const last = context.messages.at(-1) as any;
19
21
  const text = typeof last?.content === "string" ? last.content : (last?.content ?? []).filter((block: any) => block.type === "text").map((block: any) => block.text).join("\n");
20
- record({ event: "request", lastRole: last?.role, text: text.slice(0, 2000), tools: getCurrentTools(context.messages).map((tool) => tool.name) });
21
- let code: string | undefined;
22
+ const tools = getCurrentTools(context.messages);
23
+ record({ event: "request", lastRole: last?.role, text: text.slice(0, 2000), tools: tools.map((tool) => tool.name),
24
+ backgroundDescription: tools.find((tool) => tool.name === "background_task")?.description });
25
+ const calls: { name: string; arguments: any }[] = [];
26
+ const call = (args: any) => calls.push({ name: "background_task", arguments: args });
22
27
  if (last?.role !== "toolResult") {
23
- if (text.includes("SMOKE_START")) code = `const a = await tools.background_task({ action: "start", command: "sleep 9; printf 'BUILD SUCCESSFUL\\\\n'", description: "Release build", timeout: 30 });
24
- const b = await tools.background_task({ action: "start", command: "sleep 300", description: "Cancel this task", timeout: 300 });
25
- const c = await tools.background_task({ action: "start", command: "printf third" });
26
- text({ first: a.task.id, second: b.task.id, third: c });`;
27
- else if (text.includes("SMOKE_CANCEL")) code = `const list = await tools.background_task({ action: "list" });
28
- const task = list.tasks.find(t => t.description === "Cancel this task");
29
- text(await tools.background_task({ action: "cancel", id: task.id }));`;
30
- else if (text.includes("SMOKE_OUTPUT")) code = `const list = await tools.background_task({ action: "list" });
31
- const task = list.tasks.find(t => t.description === "Release build");
32
- const result = await tools.background_task({ action: "output", id: task.id });
33
- text({ status: result.task.status, output: result.output });`;
34
- else if (text.includes("SMOKE_LONG")) code = `text(await tools.background_task({ action: "start", command: "echo $$ > shell.pid; sleep 300 & echo $! > child.pid; wait", description: "Lifecycle cleanup check", timeout: 300 }));`;
28
+ if (text.includes("SMOKE_START")) {
29
+ call({ action: "start", command: "sleep 9; printf 'BUILD SUCCESSFUL\\n'", description: "Release build", timeout: 30 });
30
+ call({ action: "start", command: "sleep 300", description: "Cancel this task", timeout: 300 });
31
+ call({ action: "start", command: "printf third" });
32
+ } else if (text.includes("SMOKE_CANCEL")) {
33
+ call({ action: "cancel", id: tasks.get("Cancel this task").id });
34
+ } else if (text.includes("SMOKE_OUTPUT")) {
35
+ call({ action: "output", id: tasks.get("Release build").id });
36
+ } else if (text.includes("SMOKE_LONG")) {
37
+ call({ action: "start", command: "echo $$ > shell.pid; sleep 300 & echo $! > child.pid; wait", description: "Lifecycle cleanup check", timeout: 300 });
38
+ } else if (text.includes("SMOKE_GUIDANCE")) {
39
+ call({ action: "start", command: "sleep 300", description: "Guidance check", timeout: 300 });
40
+ } else if (text.includes("SMOKE_EXPOSURE")) {
41
+ calls.push({ name: "codemode", arguments: { code: `
42
+ text({ discovered: ALL_TOOLS.some(t => t.name === "background_task"), available: "background_task" in tools });
43
+ try { await tools.background_task({ action: "start", command: "touch should-not-exist" }); text("UNEXPECTED_SUCCESS"); }
44
+ catch { text("BACKGROUND_CALL_BLOCKED"); }` } });
45
+ }
35
46
  }
36
- const message: any = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: code ? "toolUse" : "stop",
47
+ const message: any = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: calls.length ? "toolUse" : "stop",
37
48
  usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
38
49
  stream.push({ type: "start", partial: message });
39
- if (code) {
40
- message.content.push({ type: "toolCall", id: `fixture-${++sequence}`, name: "codemode", arguments: { code } });
41
- stream.push({ type: "toolcall_start", contentIndex: 0, partial: message });
42
- stream.push({ type: "toolcall_end", contentIndex: 0, toolCall: message.content[0], partial: message });
50
+ if (calls.length) {
51
+ for (const call of calls) {
52
+ const index = message.content.length;
53
+ message.content.push({ type: "toolCall", id: `fixture-${++sequence}`, ...call });
54
+ stream.push({ type: "toolcall_start", contentIndex: index, partial: message });
55
+ stream.push({ type: "toolcall_end", contentIndex: index, toolCall: message.content[index], partial: message });
56
+ }
43
57
  } else {
44
- const reply = text.includes("[Background task finished]") ? "BACKGROUND_FOLLOWUP_RECEIVED" : "Main agent is ready; accepted background tasks keep running.";
58
+ const reply = text.includes("[Background task finished]") ? "BACKGROUND_NOTIFICATION_RECEIVED" : "Main agent is ready; accepted background tasks keep running.";
45
59
  message.content.push({ type: "text", text: reply });
46
60
  stream.push({ type: "text_start", contentIndex: 0, partial: message });
47
61
  stream.push({ type: "text_delta", contentIndex: 0, delta: reply, partial: message });
@@ -56,8 +70,19 @@ text({ status: result.task.status, output: result.output });`;
56
70
  record({ event: "loaded", tools: pi.getAllTools().map((tool) => tool.name) });
57
71
  if (ctx.hasUI) ctx.ui.setTitle("Pi Background Tasks Smoke");
58
72
  });
59
- pi.on("tool_execution_end", (event) => record({ event: "tool_end", name: event.toolName, isError: event.isError, result: event.result }));
60
- pi.on("message_start", (event) => {
61
- if (event.message.role === "custom") record({ event: "custom", type: event.message.customType, details: event.message.details });
73
+ pi.on("agent_settled", () => record({ event: "settled" }));
74
+ pi.on("tool_execution_end", (event) => {
75
+ const data = event.result.structuredContent as any;
76
+ if (event.toolName === "background_task" && data?.action === "start" && data.task) tasks.set(data.task.description, data.task);
77
+ record({ event: "tool_end", name: event.toolName, isError: event.isError, result: event.result });
78
+ });
79
+ pi.on("context", (_event, ctx) => {
80
+ // Both boundary entries and idle messages are persisted before the provider request.
81
+ // Key by entry ID so two actual notifications for the same tasks remain observable.
82
+ for (const entry of ctx.sessionManager.getBranch()) {
83
+ if (entry.type !== "custom_message" || observedNotifications.has(entry.id)) continue;
84
+ observedNotifications.add(entry.id);
85
+ record({ event: "custom", entryId: entry.id, type: entry.customType, details: entry.details });
86
+ }
62
87
  });
63
88
  }