@maxiaochao/pi-background-tasks 0.4.2 → 0.5.0
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 +9 -0
- package/README.md +17 -4
- package/TESTING.md +3 -3
- package/docs/demo.gif +0 -0
- package/docs/screenshot.png +0 -0
- package/docs/shell-list.png +0 -0
- package/extensions/background-tasks.ts +70 -6
- package/package.json +2 -2
- package/tests/extension.mjs +113 -7
- package/tests/notifications.mjs +86 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2026-11-25 - v0.5.0
|
|
4
|
+
|
|
5
|
+
- Add 30-minute aggregate progress turns and concise automatic-completion guidance
|
|
6
|
+
- Keep the start reminder action-oriented: continue independent work or end the turn while automatic completion delivery handles the wait. Remove the running-query prompt that encouraged status polling.
|
|
7
|
+
- Add one combined progress turn after every 30 idle minutes while background tasks remain active.
|
|
8
|
+
- Report task status, elapsed time, timeout, description, captured bytes and byte growth without injecting log contents.
|
|
9
|
+
- Reset progress timing around parent runs, preserve interrupt suppression and completion precedence, and keep `promptGuidelines` undefined.
|
|
10
|
+
- Put long-running-command selection guidance in the concise model-visible tool description.
|
|
11
|
+
|
|
3
12
|
## 2026-11-17 - v0.4.2
|
|
4
13
|
|
|
5
14
|
- Keep multiline shell previews compact without changing script execution
|
package/README.md
CHANGED
|
@@ -37,9 +37,13 @@ background_task({ action: "start", command: "sleep 10; printf 'checks complete\\
|
|
|
37
37
|
|
|
38
38
|
The tool is fixed to `exposure: "model-only"`: the model calls it directly; Codemode and other tools cannot call it. There is no exposure setting.
|
|
39
39
|
|
|
40
|
-
The tool
|
|
40
|
+
The model-visible tool description is:
|
|
41
41
|
|
|
42
|
-
>
|
|
42
|
+
> Use background_task for long-running commands or standalone waits. Run up to two concurrent background shell tasks with automatic completion notifications. Tasks and logs are session-scoped and do not survive reload or exit.
|
|
43
|
+
|
|
44
|
+
Each accepted start returns only its task data and this short, task-specific reminder:
|
|
45
|
+
|
|
46
|
+
> Completion is reported automatically. Continue independent work, or end the turn if none remains.
|
|
43
47
|
|
|
44
48
|
The whole reminder is not duplicated in the tool description or a `structuredContent.guidance` field. Start text does not advertise a full-log path; structured task metadata still retains `log_path`.
|
|
45
49
|
|
|
@@ -49,7 +53,7 @@ Inspect a running or finished task whenever its output is needed; no completion
|
|
|
49
53
|
background_task({ action: "output", id: "<returned-task-id>" })
|
|
50
54
|
```
|
|
51
55
|
|
|
52
|
-
Use `list`
|
|
56
|
+
Use `list` when the current task status is needed. These actions are agent-callable. After completion, use the reported log path to search relevant terms or read selected ranges; avoid loading the entire log by default. The tool also supports cancellation:
|
|
53
57
|
|
|
54
58
|
```text
|
|
55
59
|
background_task({ action: "list" })
|
|
@@ -82,6 +86,14 @@ The preview is intentionally bounded, not a full log viewer. Use the retained lo
|
|
|
82
86
|
|
|
83
87
|
The extension wraps Pi's exported native `FooterComponent`, found through the public TUI container tree; it does not copy usage accounting or patch host methods. A temporary zero-line widget captures that component before `setFooter()` clears its container, then is removed. Pi has no public footer-composition getter. Extensions that also replace the entire footer are therefore not composable: a replacement present at startup produces an explicit extension error, and one installed later can replace this footer. Use the built-in footer with `setStatus()` extensions such as Codex Edit. A host-provided composable/clickable status API would remove this constraint.
|
|
84
88
|
|
|
89
|
+
## Progress turns
|
|
90
|
+
|
|
91
|
+
After the parent agent settles, one session-scoped timer starts when one or more tasks are still running. If the parent stays idle for 30 minutes, the extension sends one combined progress turn for all running tasks. Each row includes the task ID, status, elapsed time, timeout, description, captured bytes, and byte growth since the previous progress report. It does not include log contents or log tails.
|
|
92
|
+
|
|
93
|
+
> No action is required. Completion will be reported automatically.
|
|
94
|
+
|
|
95
|
+
A new agent run clears the deadline. The timer restarts after that run settles if work remains. Completion delivery takes precedence over progress. A user interrupt suppresses both automatic progress and completion wakes until the next real user message. Terminal tasks, session replacement, reload, and shutdown remove progress scheduling.
|
|
96
|
+
|
|
85
97
|
## Completion delivery
|
|
86
98
|
|
|
87
99
|
Completion, failure, cancellation, timeout and output-limit termination update the widget immediately. The extension holds pending completion metadata until it can deliver it safely:
|
|
@@ -115,6 +127,7 @@ Pi reports asynchronous message/run-start failures through its extension error c
|
|
|
115
127
|
| --- | --- |
|
|
116
128
|
| Model-visible output body | Last 100 lines or 8 KiB, whichever is reached first |
|
|
117
129
|
| `structuredContent.output` | The same bounded tail; no separate 1 MiB program view |
|
|
130
|
+
| Automatic progress log bodies | None; one combined 30-minute status and captured-byte delta |
|
|
118
131
|
| Automatic completion log bodies | None; only status, log paths and progressive-inspection guidance |
|
|
119
132
|
| Completion status/path text | 16 KiB defensive batch cap; remaining tasks stay pending |
|
|
120
133
|
| Disk capture | 32 MiB per task, 256 MiB total per session |
|
|
@@ -140,7 +153,7 @@ The tool description is compact. This package adds no `promptGuidelines` or extr
|
|
|
140
153
|
- Cancellation and runtime limits stop the native shell process group. Scripts must wait for their own work. Daemonized/detached commands (`nohup`, `setsid`, self-backgrounding processes), existing PID adoption, PTYs and interactive stdin are not supported.
|
|
141
154
|
- This is a distinct **local execution** tool. A third-party sandbox or remote backend installed only for Bash does not automatically cover it. Enable it only where direct local shell execution is permitted.
|
|
142
155
|
- It is not an OS sandbox: CPU/memory quotas, cleanup after SIGKILL/power loss, automatic retries, deadline renewal and persistence are out of scope. Native signal delivery and timers are best-effort.
|
|
143
|
-
- Pending reminders and notification timers are cleared on session shutdown. Once a completion is delivered into conversation history, reading output does not erase that history. Messages queued by an older installed version cannot be selectively withdrawn by this version.
|
|
156
|
+
- Pending reminders, progress timers and notification timers are cleared on session shutdown. Once a completion is delivered into conversation history, reading output does not erase that history. Messages queued by an older installed version cannot be selectively withdrawn by this version.
|
|
144
157
|
|
|
145
158
|
## Remove
|
|
146
159
|
|
package/TESTING.md
CHANGED
|
@@ -13,10 +13,10 @@ Tests use Node's built-in test runner. They resolve host peers from the installe
|
|
|
13
13
|
- `tasks.mjs`: fake execution and clock at the task-manager interface; immediate return, two slots, validation, timeout/cancel races, final failure, disk budgets, write errors, bounded history and shutdown.
|
|
14
14
|
- `output.mjs`: compares the shared 100-line/8-KiB preview with the real host Bash tool’s output, retaining unchanged small-output display parity and deliberately tighter truncation for large output. Covers line/byte limits, long lines, empty output, missing final newline, UTF-8 split across chunks, invalid UTF-8 and logs larger than 1 MiB. Checks both return paths carry the same tail, omission metadata reports total size, and full captured bytes remain on disk. The former Bash-sized display/1-MiB structured contract is retired; each retained fixture now verifies the bounded replacement.
|
|
15
15
|
- `processes.mjs`: the native backend, a multi-line Python log check, non-blocking concurrency, PID-observed process-tree cleanup, silent busy-loop timeout and the default 32 MiB disk limit.
|
|
16
|
-
- `extension.mjs`: real extension registration with fake execution/clock; schema errors, local panel inspection parity, parent-signal independence, merged busy/idle notifications, terminal-output consumption and failed-read retention, abort/error boundaries, manual-compaction-style busy intervals without agent boundaries, other extensions' draft preservation, status-only completion text with log paths and progressive-inspection guidance, no automatic stdout/stderr injection or log-file reads, a 16-KiB status/path batch cap, lossless splitting of large metadata batches, explicit timeout/empty-result status, independent missing-log and healthy-sibling manual inspections, synchronous delivery-failure retention, bottom-footer placement beside editor status, complete footer hiding/restoration around the panel, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. Checks
|
|
16
|
+
- `extension.mjs`: real extension registration with fake execution/clock; schema errors, local panel inspection parity, parent-signal independence, merged busy/idle notifications, terminal-output consumption and failed-read retention, abort/error boundaries, manual-compaction-style busy intervals without agent boundaries, other extensions' draft preservation, status-only completion text with log paths and progressive-inspection guidance, no automatic stdout/stderr injection or log-file reads, a 16-KiB status/path batch cap, lossless splitting of large metadata batches, explicit timeout/empty-result status, independent missing-log and healthy-sibling manual inspections, synchronous delivery-failure retention, bottom-footer placement beside editor status, complete footer hiding/restoration around the panel, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. Checks one aggregate progress turn after 30 fake minutes, byte deltas without log contents, timer reset by a new parent run, completion precedence, interruption cleanup, the exact three-sentence tool description, fixed `model-only` exposure, no prompt guidelines, and explicit running-task `list`/`output` availability.
|
|
17
17
|
- `panel.mjs`: singular/plural counter, mouse hit region, screenshot-style field alignment, compact continuous command previews, unchanged execution of original multiline scripts, CR/LF and indentation folding, preserved inline spaces, post-folding length limits, one-second refresh, empty/output-error states, bounded sanitized output, long commands, narrow/CJK widths, arrows/Enter/click selection, selected-ID stability across completion, `x` cancellation, closing without stopping, history paging and timer disposal. The old `viewer.mjs` was removed because all of its Herdr tab/pane/follow-script contracts are retired; local execution, process-tree cleanup and notification assertions remain in their existing suites. `extension.mjs` additionally checks no slash commands, one panel at a time, inspection not consuming reminders, and shutdown closing the panel.
|
|
18
18
|
- `media.mjs`: actual demo Python jobs stream in-place/line output and exit with 0/3 only after explicit release files; the offline provider issues exactly two direct starts, then returns without polling. This tests the fixtures used by the real recorder, not an invented screen.
|
|
19
|
-
- `notifications.mjs`: isolated real Pi with model-issued background calls, default one-at-a-time queues and an offline provider. Sequential blocking fixtures hold one native tool batch open across two waves of actual failing shell jobs. The blocking fixture runs directly or through native Codemode, but background calls always come from the model. The next model request gets one merged notification for four completions, excluding reminders for zero, one or two first-wave terminal outputs read directly by the model before the boundary; no output bodies are attached to any completion notice; no extra requests follow the final report.
|
|
19
|
+
- `notifications.mjs`: isolated real Pi with model-issued background calls, default one-at-a-time queues and an offline provider. Sequential blocking fixtures hold one native tool batch open across two waves of actual failing shell jobs. The blocking fixture runs directly or through native Codemode, but background calls always come from the model. The next model request gets one merged notification for four completions, excluding reminders for zero, one or two first-wave terminal outputs read directly by the model before the boundary; no output bodies are attached to any completion notice; no extra requests follow the final report. An accelerated production registration also proves that real Pi receives repeated idle progress turns before the real shell completes, then receives one completion turn. Also verifies distinct declaration/start guidance without a Codemode suffix and that native Codemode cannot discover or call `background_task`. `BG_TEST_EXTENSION=/absolute/path/to/background-tasks.ts` can run the queue regressions against an older implementation.
|
|
20
20
|
- `compaction.mjs`: isolated native Pi SDK sessions call `session.compact()`, the same manual-compaction entry point used by `/compact` and RPC. Real shell jobs exit during a held offline summary request. Covers successful native compaction, a provider summary error and `abortCompaction()` cancellation; each must retain the pending completion while busy and automatically deliver status/log-location metadata once afterward, without another user prompt. Checks actual compaction lifecycle/events, saved compaction entries, completion timestamps/logs and exactly one automatic conversation request. Uses real timers and native `isIdle`/`isCompacting`, not injected busy state or replacement compaction results; no paid model call or TUI keyboard invocation of `/compact`. `BG_TEST_EXTENSION` also supports a negative-control extension.
|
|
21
21
|
- `interruptions.mjs`: isolated native Pi SDK sessions call the real `session.abort()` while a foreground tool is held. A real shell finishes before or after the interrupt; terminal timestamps verify the ordering. Native `agent_settled.aborted` must confirm the stop; no completion may start another model request. A new user prompt sees the retained completion in its first request, reads the real failed task's output, and finishes without duplicate delivery or extension errors. A third case starts actual manual compaction while the foreground tool is held: Pi itself interrupts the active agent, which must stay stopped even after compaction and background completion. The public abort event has no reason field, so the extension preserves this native interruption rather than guessing its source. `BG_TEST_EXTENSION` supports a negative control without interrupt suppression.
|
|
22
22
|
|
|
@@ -24,7 +24,7 @@ The compaction fixtures seed a completed earlier turn and sufficient recent cont
|
|
|
24
24
|
|
|
25
25
|
Compaction cancellation assertions use native lifecycle `aborted` flags and the absence of a saved compaction entry, not version-dependent error strings. Agent interruption is a different state and is tested separately.
|
|
26
26
|
|
|
27
|
-
Notification retry tests use the injected clock and session-idle interface. They check the 1/2/4/8/16/30-second delays
|
|
27
|
+
Notification retry tests use the injected clock and session-idle interface. They check the 1/2/4/8/16/30-second completion delays and the separate 30-minute progress deadline, retention across 24 hours of busy time, one aggregate progress turn for all running tasks, immediate boundary delivery, fresh-batch reset, and cleanup on terminal reads, abort/error boundaries and session replacement. No compression-event subscription or notification pause action is introduced. Offline fixtures prove guidance delivery, not that a live model always obeys it; no paid/live-model anti-polling evaluation is part of this suite.
|
|
28
28
|
|
|
29
29
|
Load-test uses an isolated temporary agent directory, the production extension and an offline fixture provider. It does not access real provider credentials or alter the user's installed packages. From the workspace, `npm --prefix packages/background-tasks run load-test -- --toolkit` loads the complete toolkit directory through its manifest and verifies exactly one background-task tool; the root load-test runs this check too.
|
|
30
30
|
|
package/docs/demo.gif
CHANGED
|
Binary file
|
package/docs/screenshot.png
CHANGED
|
Binary file
|
package/docs/shell-list.png
CHANGED
|
Binary file
|
|
@@ -8,7 +8,8 @@ import { BackgroundPanel } from "../src/panel.ts";
|
|
|
8
8
|
import { BackgroundFooter, findNativeFooter, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
|
|
9
9
|
|
|
10
10
|
const actions = ["start", "list", "output", "cancel"] as const;
|
|
11
|
-
const startNotice = "Completion is reported automatically. Continue
|
|
11
|
+
const startNotice = "Completion is reported automatically. Continue independent work, or end the turn if none remains.";
|
|
12
|
+
const PROGRESS_INTERVAL_MS = 30 * 60_000;
|
|
12
13
|
// Bound model-visible status text when many completions accumulate.
|
|
13
14
|
const NOTIFICATION_MAX_BYTES = 16 * 1024;
|
|
14
15
|
type Action = typeof actions[number];
|
|
@@ -21,7 +22,7 @@ interface Params {
|
|
|
21
22
|
id?: string;
|
|
22
23
|
}
|
|
23
24
|
const Parameters = Type.Object({
|
|
24
|
-
action: StringEnum(actions, { description: "start returns a task ID immediately; list checks status; output reads a bounded tail; cancel stops one task.
|
|
25
|
+
action: StringEnum(actions, { description: "start returns a task ID immediately; list checks status; output reads a bounded tail; cancel stops one task." }),
|
|
25
26
|
command: Type.Optional(Type.String({ 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." })),
|
|
26
27
|
description: Type.Optional(Type.String({ description: "Short display label for start" })),
|
|
27
28
|
cwd: Type.Optional(Type.String({ description: "Working directory for start; defaults to the session directory. Relative paths resolve from it." })),
|
|
@@ -62,16 +63,25 @@ function completionText(task: TaskSnapshot): string {
|
|
|
62
63
|
return lines.join("\n");
|
|
63
64
|
}
|
|
64
65
|
|
|
65
|
-
export default function (pi: ExtensionAPI, dependencies: {
|
|
66
|
+
export default function (pi: ExtensionAPI, dependencies: {
|
|
67
|
+
operations?: BashOperations;
|
|
68
|
+
clock?: Clock;
|
|
69
|
+
logRoot?: string;
|
|
70
|
+
progressIntervalMs?: number;
|
|
71
|
+
} = {}) {
|
|
66
72
|
const clock = dependencies.clock ?? systemClock;
|
|
73
|
+
const progressIntervalMs = dependencies.progressIntervalMs ?? PROGRESS_INTERVAL_MS;
|
|
74
|
+
if (!Number.isFinite(progressIntervalMs) || progressIntervalMs <= 0) throw new Error("Progress interval must be positive");
|
|
67
75
|
let manager: BackgroundTasks | undefined;
|
|
68
76
|
let context: ExtensionContext | undefined;
|
|
69
77
|
let generation = 0;
|
|
70
78
|
let timer: unknown;
|
|
71
79
|
let notificationTimer: unknown;
|
|
80
|
+
let progressTimer: unknown;
|
|
72
81
|
let completedNormally = true;
|
|
73
82
|
let interrupted = false;
|
|
74
83
|
const pending = new Map<string, TaskSnapshot>();
|
|
84
|
+
const progressBytes = new Map<string, number>();
|
|
75
85
|
let mounted: { footer: BackgroundFooter; tui: { requestRender(): void } } | undefined;
|
|
76
86
|
let panel: { close(): void } | undefined;
|
|
77
87
|
|
|
@@ -79,6 +89,44 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
79
89
|
if (notificationTimer !== undefined) clock.clearTimeout(notificationTimer);
|
|
80
90
|
notificationTimer = undefined;
|
|
81
91
|
};
|
|
92
|
+
const clearProgressTimer = () => {
|
|
93
|
+
if (progressTimer !== undefined) clock.clearTimeout(progressTimer);
|
|
94
|
+
progressTimer = undefined;
|
|
95
|
+
};
|
|
96
|
+
const runningTasks = () => manager?.list().tasks.filter((task) => task.status === "running") ?? [];
|
|
97
|
+
const scheduleProgress = () => {
|
|
98
|
+
clearProgressTimer();
|
|
99
|
+
if (interrupted || pending.size > 0 || runningTasks().length === 0) return;
|
|
100
|
+
const epoch = generation;
|
|
101
|
+
progressTimer = clock.setTimeout(() => {
|
|
102
|
+
progressTimer = undefined;
|
|
103
|
+
if (generation !== epoch || !context || !manager || interrupted || pending.size > 0) return;
|
|
104
|
+
const tasks = runningTasks();
|
|
105
|
+
if (tasks.length === 0) return;
|
|
106
|
+
if (!context.isIdle()) {
|
|
107
|
+
scheduleProgress();
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const deltas = new Map(tasks.map((task) => [task.id, task.bytes - (progressBytes.get(task.id) ?? 0)]));
|
|
111
|
+
const content = [
|
|
112
|
+
"[Background tasks still running]",
|
|
113
|
+
"",
|
|
114
|
+
...tasks.map((task) => `${formatTask(task)} · ${task.bytes} captured bytes (+${deltas.get(task.id)} since last report)`),
|
|
115
|
+
"",
|
|
116
|
+
"No action is required. Completion will be reported automatically.",
|
|
117
|
+
].join("\n");
|
|
118
|
+
try {
|
|
119
|
+
pi.sendMessage({
|
|
120
|
+
customType: "background-task-progress", display: true,
|
|
121
|
+
details: { tasks, byteDeltas: Object.fromEntries(deltas) },
|
|
122
|
+
content,
|
|
123
|
+
}, { triggerTurn: true, deliverAs: "steer" });
|
|
124
|
+
for (const task of tasks) progressBytes.set(task.id, task.bytes);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
console.error(`Background progress notification failed: ${errorText(error)}`);
|
|
127
|
+
}
|
|
128
|
+
}, progressIntervalMs);
|
|
129
|
+
};
|
|
82
130
|
const takeNotification = () => {
|
|
83
131
|
clearNotificationTimer();
|
|
84
132
|
if (pending.size === 0) return;
|
|
@@ -144,12 +192,17 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
144
192
|
const message = takeNotification();
|
|
145
193
|
if (message) return { message };
|
|
146
194
|
});
|
|
195
|
+
pi.on("agent_start", clearProgressTimer);
|
|
147
196
|
pi.on("agent_settled", (event) => {
|
|
148
197
|
if (event.aborted) {
|
|
149
198
|
interrupted = true;
|
|
150
199
|
clearNotificationTimer();
|
|
200
|
+
clearProgressTimer();
|
|
201
|
+
return;
|
|
151
202
|
}
|
|
152
|
-
if (!
|
|
203
|
+
if (!completedNormally) return;
|
|
204
|
+
scheduleNotification();
|
|
205
|
+
scheduleProgress();
|
|
153
206
|
});
|
|
154
207
|
|
|
155
208
|
const openPanel = async () => {
|
|
@@ -206,7 +259,9 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
206
259
|
context = undefined;
|
|
207
260
|
clearTimer();
|
|
208
261
|
clearNotificationTimer();
|
|
262
|
+
clearProgressTimer();
|
|
209
263
|
pending.clear();
|
|
264
|
+
progressBytes.clear();
|
|
210
265
|
completedNormally = true;
|
|
211
266
|
interrupted = false;
|
|
212
267
|
try {
|
|
@@ -225,9 +280,18 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
225
280
|
const epoch = generation;
|
|
226
281
|
manager = new BackgroundTasks({
|
|
227
282
|
operations: dependencies.operations ?? createLocalBashOperations(), clock, logRoot: dependencies.logRoot,
|
|
228
|
-
onChange() {
|
|
283
|
+
onChange() {
|
|
284
|
+
if (generation !== epoch) return;
|
|
285
|
+
refresh();
|
|
286
|
+
if (manager?.list().running === 0) {
|
|
287
|
+
clearProgressTimer();
|
|
288
|
+
progressBytes.clear();
|
|
289
|
+
}
|
|
290
|
+
},
|
|
229
291
|
onComplete(task) {
|
|
230
292
|
if (generation !== epoch || !context) return;
|
|
293
|
+
clearProgressTimer();
|
|
294
|
+
progressBytes.delete(task.id);
|
|
231
295
|
pending.set(task.id, task);
|
|
232
296
|
scheduleNotification();
|
|
233
297
|
},
|
|
@@ -288,7 +352,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
288
352
|
pi.registerTool({
|
|
289
353
|
name: "background_task", label: "Background task",
|
|
290
354
|
exposure: "model-only",
|
|
291
|
-
description: "Run up to two concurrent background shell tasks with automatic completion notifications. Tasks
|
|
355
|
+
description: "Use background_task for long-running commands or standalone waits. Run up to two concurrent background shell tasks with automatic completion notifications. Tasks and logs are session-scoped and do not survive reload or exit.",
|
|
292
356
|
parameters: Parameters, outputSchema: OutputSchema,
|
|
293
357
|
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
294
358
|
async execute(_id, params, signal, _onUpdate, ctx) {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maxiaochao/pi-background-tasks",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Session-scoped background shell tasks with completion notifications for Pi.",
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "Session-scoped background shell tasks with progress and completion notifications for Pi.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"pi-package",
|
package/tests/extension.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { fixture, flush } from "./helpers.mjs";
|
|
|
8
8
|
|
|
9
9
|
const keys = new KeybindingsManager(TUI_KEYBINDINGS);
|
|
10
10
|
|
|
11
|
-
function harness(mode = "tui", hasUI = true) {
|
|
11
|
+
function harness(mode = "tui", hasUI = true, dependencies = {}) {
|
|
12
12
|
const f = fixture();
|
|
13
13
|
const handlers = new Map();
|
|
14
14
|
const commands = new Map();
|
|
@@ -62,7 +62,7 @@ function harness(mode = "tui", hasUI = true) {
|
|
|
62
62
|
messages.push({ message, options });
|
|
63
63
|
},
|
|
64
64
|
};
|
|
65
|
-
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root });
|
|
65
|
+
register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root, ...dependencies });
|
|
66
66
|
return {
|
|
67
67
|
...f, handlers, commands, messages, notices, widgets, statuses, idleChecks, ctx, tui, native,
|
|
68
68
|
setIdle(value) { idle = value; },
|
|
@@ -424,6 +424,112 @@ test("idle wake batches current completions and a terminal read can remove the w
|
|
|
424
424
|
} finally { await h.close(); }
|
|
425
425
|
});
|
|
426
426
|
|
|
427
|
+
test("running tasks send one merged progress turn per 30 minutes of parent inactivity", async () => {
|
|
428
|
+
const interval = 30 * 60_000;
|
|
429
|
+
const h = harness("print", false);
|
|
430
|
+
try {
|
|
431
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
432
|
+
for (const command of ["first", "second"]) {
|
|
433
|
+
await h.tool.execute(command, { action: "start", command, timeout: 7200 });
|
|
434
|
+
}
|
|
435
|
+
h.calls[0].onData(Buffer.from("first output"));
|
|
436
|
+
h.calls[1].onData(Buffer.from("two"));
|
|
437
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
438
|
+
h.clock.advance(interval - 1);
|
|
439
|
+
assert.equal(h.messages.length, 0);
|
|
440
|
+
h.clock.advance(1);
|
|
441
|
+
assert.equal(h.messages.length, 1);
|
|
442
|
+
const first = h.messages[0];
|
|
443
|
+
assert.equal(first.message.customType, "background-task-progress");
|
|
444
|
+
assert.equal(first.options.triggerTurn, true);
|
|
445
|
+
assert.equal(first.options.deliverAs, "steer");
|
|
446
|
+
assert.equal(first.message.details.tasks.length, 2);
|
|
447
|
+
assert.deepEqual(Object.values(first.message.details.byteDeltas).sort((a, b) => a - b), [3, 12]);
|
|
448
|
+
assert.match(first.message.content, /30m \/ 2h · "first" · 12 captured bytes \(\+12 since last report\)/);
|
|
449
|
+
assert.match(first.message.content, /30m \/ 2h · "second" · 3 captured bytes \(\+3 since last report\)/);
|
|
450
|
+
assert.match(first.message.content, /No action is required\. Completion will be reported automatically\./);
|
|
451
|
+
assert.doesNotMatch(first.message.content, /first output|Untrusted shell output|Captured log:/);
|
|
452
|
+
|
|
453
|
+
// The progress-triggered parent run settles and starts the next deadline.
|
|
454
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
455
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
456
|
+
h.calls[0].onData(Buffer.from(" more"));
|
|
457
|
+
h.clock.advance(interval - 1);
|
|
458
|
+
// A new parent run must clear an already-armed progress deadline.
|
|
459
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
460
|
+
h.clock.advance(interval);
|
|
461
|
+
assert.equal(h.messages.length, 1, "an active parent run clears the progress deadline");
|
|
462
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
463
|
+
h.clock.advance(interval);
|
|
464
|
+
assert.equal(h.messages.length, 2);
|
|
465
|
+
assert.equal(h.messages[1].message.details.tasks.length, 2);
|
|
466
|
+
assert.equal(h.messages[1].message.details.byteDeltas[first.message.details.tasks[0].id], 5);
|
|
467
|
+
assert.equal(h.messages[1].message.details.byteDeltas[first.message.details.tasks[1].id], 0);
|
|
468
|
+
} finally { await h.close(); }
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
test("busy sessions defer progress and error boundaries do not wake them later", async () => {
|
|
472
|
+
const interval = 30 * 60_000;
|
|
473
|
+
const h = harness("print", false, { progressIntervalMs: interval });
|
|
474
|
+
try {
|
|
475
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
476
|
+
await h.tool.execute("start", { action: "start", command: "busy", timeout: 7200 });
|
|
477
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
478
|
+
h.setIdle(false);
|
|
479
|
+
h.clock.advance(interval);
|
|
480
|
+
assert.equal(h.messages.length, 0);
|
|
481
|
+
h.setIdle(true);
|
|
482
|
+
h.clock.advance(interval);
|
|
483
|
+
assert.equal(h.messages.filter(({ message }) => message.customType === "background-task-progress").length, 1);
|
|
484
|
+
|
|
485
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
486
|
+
h.handlers.get("turn_end")({ entries: [], continue: false, outcome: "error" }, h.ctx);
|
|
487
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
488
|
+
h.clock.advance(interval * 2);
|
|
489
|
+
assert.equal(h.messages.filter(({ message }) => message.customType === "background-task-progress").length, 1);
|
|
490
|
+
} finally { await h.close(); }
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
test("an interrupted parent suppresses progress until the next user message", async () => {
|
|
494
|
+
const interval = 30 * 60_000;
|
|
495
|
+
const h = harness("print", false, { progressIntervalMs: interval });
|
|
496
|
+
try {
|
|
497
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
498
|
+
await h.tool.execute("start", { action: "start", command: "interrupted", timeout: 7200 });
|
|
499
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
500
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
501
|
+
h.handlers.get("agent_settled")({ aborted: true }, h.ctx);
|
|
502
|
+
h.clock.advance(interval * 2);
|
|
503
|
+
assert.equal(h.messages.length, 0);
|
|
504
|
+
h.handlers.get("before_agent_start")({ messageType: "custom", prompt: "other wake" }, h.ctx);
|
|
505
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
506
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
507
|
+
h.clock.advance(interval);
|
|
508
|
+
assert.equal(h.messages.length, 0, "custom wakes do not release an interrupted parent");
|
|
509
|
+
h.handlers.get("before_agent_start")({ messageType: "user", prompt: "continue" }, h.ctx);
|
|
510
|
+
h.handlers.get("agent_start")({}, h.ctx);
|
|
511
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
512
|
+
h.clock.advance(interval);
|
|
513
|
+
assert.equal(h.messages.filter(({ message }) => message.customType === "background-task-progress").length, 1);
|
|
514
|
+
} finally { await h.close(); }
|
|
515
|
+
});
|
|
516
|
+
|
|
517
|
+
test("completion cancels the pending progress deadline", async () => {
|
|
518
|
+
const interval = 30 * 60_000;
|
|
519
|
+
const h = harness("print", false, { progressIntervalMs: interval });
|
|
520
|
+
try {
|
|
521
|
+
await h.handlers.get("session_start")({}, h.ctx);
|
|
522
|
+
await h.tool.execute("start", { action: "start", command: "finishes", timeout: 7200 });
|
|
523
|
+
h.handlers.get("agent_settled")({ aborted: false }, h.ctx);
|
|
524
|
+
h.clock.advance(interval - 1);
|
|
525
|
+
h.calls[0].resolve();
|
|
526
|
+
await flush();
|
|
527
|
+
h.clock.advance(interval + 1);
|
|
528
|
+
assert.equal(h.messages.filter(({ message }) => message.customType === "background-task-progress").length, 0);
|
|
529
|
+
assert.equal(h.messages.filter(({ message }) => message.customType === "background-task-finished").length, 1);
|
|
530
|
+
} finally { await h.close(); }
|
|
531
|
+
});
|
|
532
|
+
|
|
427
533
|
for (const outcome of ["aborted", "error"]) {
|
|
428
534
|
test(`${outcome} boundaries do not force continuation or replay a scheduled idle wake`, async () => {
|
|
429
535
|
const h = harness();
|
|
@@ -494,7 +600,7 @@ test("registration is compact, does not inject prompt rules or start session res
|
|
|
494
600
|
try {
|
|
495
601
|
assert.equal(h.tool.name, "background_task");
|
|
496
602
|
assert.equal(h.tool.exposure, "model-only");
|
|
497
|
-
assert.
|
|
603
|
+
assert.equal(h.tool.description, "Use background_task for long-running commands or standalone waits. Run up to two concurrent background shell tasks with automatic completion notifications. Tasks and logs are session-scoped and do not survive reload or exit.");
|
|
498
604
|
assert.match(h.tool.parameters.properties.action.description, /start returns a task ID immediately/);
|
|
499
605
|
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.");
|
|
500
606
|
assert.ok(h.tool.description.length < 500);
|
|
@@ -508,21 +614,21 @@ test("registration is compact, does not inject prompt rules or start session res
|
|
|
508
614
|
} finally { await h.close(); }
|
|
509
615
|
});
|
|
510
616
|
|
|
511
|
-
test("start keeps
|
|
617
|
+
test("start keeps concise task-specific guidance while the declaration describes lifecycle", async () => {
|
|
512
618
|
const h = harness();
|
|
513
619
|
try {
|
|
514
620
|
await h.handlers.get("session_start")({}, h.ctx);
|
|
515
621
|
const started = await h.tool.execute("start", { action: "start", command: "sleep 60" });
|
|
516
622
|
const { task } = started.structuredContent;
|
|
517
|
-
const notice = "Completion is reported automatically. Continue
|
|
623
|
+
const notice = "Completion is reported automatically. Continue independent work, or end the turn if none remains.";
|
|
518
624
|
assert.equal(task.status, "running");
|
|
519
625
|
assert.ok(started.content[0].text.includes(notice));
|
|
520
626
|
assert.ok(!started.content[0].text.includes(task.log_path));
|
|
521
627
|
assert.ok(!started.content[0].text.includes("session changes"));
|
|
522
628
|
assert.ok(!h.tool.description.includes(notice), "declaration must not duplicate the whole start reminder");
|
|
523
629
|
assert.match(h.tool.description, /automatic completion notifications/);
|
|
524
|
-
assert.match(h.tool.description, /session
|
|
525
|
-
assert.
|
|
630
|
+
assert.match(h.tool.description, /session-scoped and do not survive reload or exit/);
|
|
631
|
+
assert.doesNotMatch(h.tool.parameters.properties.action.description, /while tasks are running/);
|
|
526
632
|
assert.equal(started.structuredContent.guidance, undefined);
|
|
527
633
|
assert.equal(h.tool.outputSchema.properties.guidance, undefined);
|
|
528
634
|
const list = await h.tool.execute("list", { action: "list" });
|
package/tests/notifications.mjs
CHANGED
|
@@ -3,10 +3,24 @@ import { execFileSync } from "node:child_process";
|
|
|
3
3
|
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
|
-
import {
|
|
6
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
8
|
import { test } from "node:test";
|
|
8
9
|
import { piBinary } from "./runtime.mjs";
|
|
9
10
|
|
|
11
|
+
const { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } = await import("@earendil-works/pi-coding-agent");
|
|
12
|
+
const { createAssistantMessageEventStream } = await import("@earendil-works/pi-ai");
|
|
13
|
+
const { default: registerBackgroundTasks } = 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
|
+
async function waitFor(check, label) {
|
|
17
|
+
for (let i = 0; i < 1000; i++) {
|
|
18
|
+
if (check()) return;
|
|
19
|
+
await delay(10);
|
|
20
|
+
}
|
|
21
|
+
throw new Error(`Timed out waiting for ${label}`);
|
|
22
|
+
}
|
|
23
|
+
|
|
10
24
|
test("native model receives distinct declaration and start guidance without Codemode instructions", () => {
|
|
11
25
|
const directory = mkdtempSync(join(tmpdir(), "pi-bg-guidance-"));
|
|
12
26
|
try {
|
|
@@ -22,13 +36,14 @@ test("native model receives distinct declaration and start guidance without Code
|
|
|
22
36
|
const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
|
|
23
37
|
const started = records.find((entry) => entry.event === "tool_end" && entry.name === "background_task");
|
|
24
38
|
assert.equal(started.isError, false);
|
|
25
|
-
const notice = "Completion is reported automatically. Continue
|
|
39
|
+
const notice = "Completion is reported automatically. Continue independent work, or end the turn if none remains.";
|
|
26
40
|
assert.equal(started.result.structuredContent.guidance, undefined);
|
|
27
41
|
assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "codemode"), false);
|
|
28
42
|
const requests = records.filter((entry) => entry.event === "request");
|
|
29
43
|
assert.match(requests[0].backgroundCommandDescription, /Stdout\/stderr are saved to a unique per-task log; its path is reported on completion\./);
|
|
30
44
|
assert.match(requests[0].backgroundDescription, /automatic completion notifications/);
|
|
31
|
-
assert.match(requests[0].backgroundDescription, /
|
|
45
|
+
assert.match(requests[0].backgroundDescription, /Use background_task for long-running commands or standalone waits/);
|
|
46
|
+
assert.match(requests[0].backgroundDescription, /session-scoped and do not survive reload or exit/);
|
|
32
47
|
assert.ok(!requests[0].backgroundDescription.includes(notice));
|
|
33
48
|
assert.ok(!requests[0].backgroundDescription.includes("Codemode:"));
|
|
34
49
|
assert.ok(requests[1].text.includes(notice), "the next model request sees the task-specific reminder");
|
|
@@ -36,6 +51,74 @@ test("native model receives distinct declaration and start guidance without Code
|
|
|
36
51
|
} finally { rmSync(directory, { recursive: true, force: true }); }
|
|
37
52
|
});
|
|
38
53
|
|
|
54
|
+
test("real Pi receives accelerated progress turns until the background task completes", { timeout: 20000 }, async () => {
|
|
55
|
+
const directory = mkdtempSync(join(tmpdir(), "pi-bg-progress-"));
|
|
56
|
+
const requests = [];
|
|
57
|
+
let session;
|
|
58
|
+
try {
|
|
59
|
+
const modelRuntime = await ModelRuntime.create({ authPath: join(directory, "auth.json"), modelsPath: join(directory, "models.json"), refreshOnCreate: false });
|
|
60
|
+
modelRuntime.registerProvider("bg-progress", {
|
|
61
|
+
name: "Offline progress fixture", baseUrl: "http://127.0.0.1:1", api: "bg-progress", apiKey: "fixture-not-a-secret",
|
|
62
|
+
models: [{ id: "deterministic", name: "Offline fixture", reasoning: false, input: ["text"], contextWindow: 128000, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
|
|
63
|
+
streamSimple(model, context) {
|
|
64
|
+
const stream = createAssistantMessageEventStream();
|
|
65
|
+
queueMicrotask(() => {
|
|
66
|
+
const last = context.messages.at(-1);
|
|
67
|
+
const text = typeof last.content === "string" ? last.content : last.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
|
|
68
|
+
requests.push(text);
|
|
69
|
+
const start = last.role === "user" && text.includes("SMOKE_PROGRESS");
|
|
70
|
+
const message = { role: "assistant", api: model.api, provider: model.provider, model: model.id, timestamp: Date.now(), content: [], stopReason: start ? "toolUse" : "stop",
|
|
71
|
+
usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
|
|
72
|
+
if (start) message.content.push({ type: "toolCall", id: "progress-start", name: "background_task", arguments: {
|
|
73
|
+
action: "start", command: "sleep 0.6; printf 'PROGRESS COMPLETE\\n'", description: "Progress check", timeout: 5,
|
|
74
|
+
} });
|
|
75
|
+
else message.content.push({ type: "text", text: text.includes("[Background task finished]") ? "COMPLETION_ACK" : "PROGRESS_ACK" });
|
|
76
|
+
stream.push({ type: "start", partial: message });
|
|
77
|
+
stream.push({ type: "done", reason: message.stopReason, message });
|
|
78
|
+
});
|
|
79
|
+
return stream;
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
const settingsManager = SettingsManager.inMemory({ compaction: { enabled: false }, retry: { enabled: false }, cacheWarming: "off" });
|
|
83
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
84
|
+
cwd: directory, agentDir: directory, settingsManager,
|
|
85
|
+
noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
|
|
86
|
+
extensionFactories: [(pi) => registerBackgroundTasks(pi, { progressIntervalMs: 100 })],
|
|
87
|
+
});
|
|
88
|
+
await resourceLoader.reload();
|
|
89
|
+
const created = await createAgentSession({
|
|
90
|
+
cwd: directory, agentDir: directory, modelRuntime, model: modelRuntime.getModel("bg-progress", "deterministic"),
|
|
91
|
+
thinkingLevel: "off", resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(directory), tools: ["background_task"],
|
|
92
|
+
});
|
|
93
|
+
session = created.session;
|
|
94
|
+
assert.deepEqual(created.extensionsResult.errors, []);
|
|
95
|
+
await session.bindExtensions({});
|
|
96
|
+
await session.prompt("SMOKE_PROGRESS");
|
|
97
|
+
const entries = (type) => session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === type);
|
|
98
|
+
await waitFor(() => entries("background-task-progress").length >= 1, "accelerated progress notification");
|
|
99
|
+
await waitFor(() => entries("background-task-finished").length === 1, "completion notification");
|
|
100
|
+
await session.waitForIdle();
|
|
101
|
+
const progress = entries("background-task-progress");
|
|
102
|
+
assert.ok(progress.length >= 2, "the accelerated fixture must prove repeated progress turns");
|
|
103
|
+
for (const message of progress) {
|
|
104
|
+
assert.equal(message.details.tasks.length, 1);
|
|
105
|
+
assert.match(message.content, /Progress check/);
|
|
106
|
+
assert.match(message.content, /No action is required/);
|
|
107
|
+
assert.doesNotMatch(message.content, /PROGRESS COMPLETE|Captured log:|Untrusted shell output/);
|
|
108
|
+
}
|
|
109
|
+
assert.ok(requests.some((text) => text.includes("[Background tasks still running]")));
|
|
110
|
+
assert.ok(requests.some((text) => text.includes("[Background task finished]")));
|
|
111
|
+
assert.equal(entries("background-task-finished").length, 1);
|
|
112
|
+
} finally {
|
|
113
|
+
if (session) {
|
|
114
|
+
await session.abort();
|
|
115
|
+
await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
|
|
116
|
+
session.dispose();
|
|
117
|
+
}
|
|
118
|
+
rmSync(directory, { recursive: true, force: true });
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
|
|
39
122
|
test("native Codemode cannot discover or call the model-only background tool", () => {
|
|
40
123
|
const directory = mkdtempSync(join(tmpdir(), "pi-bg-exposure-"));
|
|
41
124
|
try {
|