@maxiaochao/pi-background-tasks 0.1.1 → 0.2.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 +14 -0
- package/README.md +33 -21
- package/TESTING.md +23 -5
- 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 +47 -11
- package/package.json +2 -2
- package/src/herdr.ts +38 -0
- package/src/viewer.ts +201 -0
- package/src/widget.ts +15 -2
- package/tests/extension.mjs +5 -4
- package/tests/fixtures/media-job.py +22 -0
- package/tests/fixtures/notifications.ts +46 -36
- package/tests/fixtures/provider.ts +43 -21
- package/tests/media.mjs +54 -0
- package/tests/notifications.mjs +48 -22
- package/tests/tui-smoke.py +11 -4
- package/tests/viewer.mjs +252 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2026-10-29 - v0.2.0
|
|
4
|
+
|
|
5
|
+
- Add live read-only Herdr task views, exact widget navigation and real two-task terminal media
|
|
6
|
+
- Re-record the real Pi/Herdr walkthrough with two live jobs, widget-row clicks focusing each pane, command headers, streaming progress, terminal results and automatic tab cleanup. Publish parent/task-pane screenshots, an animated GIF and the full WebM; use isolated offline fixtures without credentials.
|
|
7
|
+
- Inside Herdr, show each background task in a read-only pane of one per-session **Background tasks** tab: command header, live log via `tail -f`, and a final result line. Execution, logs, limits and notifications are unchanged.
|
|
8
|
+
- Open the tab without focus on the first start, reuse finished panes, and close the tab when no task runs, waiting while the user looks at it. Close it immediately on session shutdown, reload and replacement.
|
|
9
|
+
- Add `/bg watch <id>`, and in fullscreen mode a click on a widget task row, to reopen a closed pane and focus that task's pane. Closing a pane never cancels its task. Herdr subagent children and non-Herdr sessions open no view; Herdr failures warn once and leave tasks running.
|
|
10
|
+
|
|
11
|
+
## 2026-10-26 - v0.1.2
|
|
12
|
+
|
|
13
|
+
- restrict background tasks to model-only and use concise automatic-notification guidance
|
|
14
|
+
- Fix `background_task` exposure to `model-only`; reject Codemode and other nested callers without adding a configuration file.
|
|
15
|
+
- Use concise English startup guidance emphasizing automatic notification without sleep or polling.
|
|
16
|
+
|
|
3
17
|
## 2026-10-22 - v0.1.1
|
|
4
18
|
|
|
5
19
|
- batch unread completions at tool boundaries, preserve interrupted runs, and provide non-polling startup guidance
|
package/README.md
CHANGED
|
@@ -2,15 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
Run shell commands in the background, then notify the main agent when they finish. These are local processes, not subagents.
|
|
4
4
|
|
|
5
|
-

|
|
6
6
|
|
|
7
|
-

|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
[Watch the full recording (WebM)](docs/demo.webm).
|
|
12
|
+
|
|
13
|
+
The recording uses an offline fixture provider to start two real local demo jobs: an in-place build counter and a streaming test log. It captures the production extension in a real Pi TUI and a temporary Herdr workspace, including clicks on both widget rows, the exact pane focus, success/failure results, and automatic tab cleanup. No paid model or user credentials are used.
|
|
8
14
|
|
|
9
15
|
## Why
|
|
10
16
|
|
|
11
17
|
A command such as `sleep 60; python3 ...` can spend most of its time waiting to check a build log. A normal Bash call keeps waiting for that command. This package returns a task ID immediately so the main agent can do other work.
|
|
12
18
|
|
|
13
|
-
It uses Pi's public `createLocalBashOperations()` backend for shell execution and process-group cancellation. It adds session ownership, bounded logs, status, and completion messages. It neither replaces Bash nor starts another model
|
|
19
|
+
It uses Pi's public `createLocalBashOperations()` backend for shell execution and process-group cancellation. It adds session ownership, bounded logs, status, and completion messages. It neither replaces Bash nor starts another model. Inside Herdr, it also opens a read-only pane per task so the user can watch the command and its live output; the command still runs locally, not in that pane.
|
|
14
20
|
|
|
15
21
|
Completion delivery follows [oh-my-pi's yield-queue approach](https://github.com/can1357/oh-my-pi/blob/3a2758b68f7c8e6bdf22c3a76b86c8675e5e0c9e/packages/coding-agent/src/session/yield-queue.ts): retain results, combine them at a safe boundary, and filter consumed results before delivery. This package uses Pi's public extension API, not patched host code; a local idle retry covers busy operations that expose no final agent boundary.
|
|
16
22
|
|
|
@@ -31,9 +37,11 @@ The complete `@maxiaochao/pi-toolkit` package **bundles and enables Background T
|
|
|
31
37
|
background_task({ action: "start", command: "sleep 10; printf 'checks complete\\n'", description: "Delayed check", timeout: 120 })
|
|
32
38
|
```
|
|
33
39
|
|
|
34
|
-
|
|
40
|
+
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.
|
|
35
41
|
|
|
36
|
-
|
|
42
|
+
Each accepted start includes this guidance in the tool description, result text and `structuredContent.guidance`:
|
|
43
|
+
|
|
44
|
+
> Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.
|
|
37
45
|
|
|
38
46
|
After the completion notification, read the result:
|
|
39
47
|
|
|
@@ -67,19 +75,34 @@ List shows running tasks and the latest 20 finished tasks, with total and omitte
|
|
|
67
75
|
/bg list
|
|
68
76
|
/bg output <returned-task-id>
|
|
69
77
|
/bg cancel <returned-task-id>
|
|
78
|
+
/bg watch <returned-task-id>
|
|
70
79
|
```
|
|
71
80
|
|
|
72
81
|
The commands inspect the same jobs without asking a model to perform the operation. Start a command through the agent tool; there is no second shell parser in `/bg`.
|
|
73
82
|
|
|
74
83
|
A fixed widget **above the editor** shows each task's ID, status, elapsed time, runtime limit and description. It coexists with Scheduler, Todo, and Herdr widgets. Finished rows remain for five seconds; hiding a row does not delete its record. RPC gets a compact active count; non-interactive tools work without the widget.
|
|
75
84
|
|
|
85
|
+
## Herdr task view
|
|
86
|
+
|
|
87
|
+
When Pi runs inside Herdr (`HERDR_ENV=1` and `HERDR_WORKSPACE_ID` set), each started task also gets a pane in one **Background tasks** tab:
|
|
88
|
+
|
|
89
|
+
- The tab is created on the first start without taking focus, and holds at most two panes, one per running task. A new task reuses the pane of a finished one.
|
|
90
|
+
- Each pane prints the command (`$ ...`), cwd and runtime limit, then follows the task's captured log with `tail -f`. Line output and `\r` progress updates appear live. When the task ends, the pane prints a result line such as `[failed · exit 4 · 6s]`.
|
|
91
|
+
- The pane is a **viewer only**. The task runs through the same local backend as outside Herdr, with the same logs, limits, status and notifications. The command has no TTY, so tools that detect one may drop colour or animated progress bars.
|
|
92
|
+
- Closing a pane, or the whole tab, does not cancel the task. Clicking a task row in the widget (Pi 1.4+ fullscreen mode) or `/bg watch <id>` reopens the pane if needed and focuses that tab and pane; use `/bg cancel <id>` to stop the task.
|
|
93
|
+
- When no task runs any more, the tab closes. If the user is looking at it, it closes after focus moves to another tab. Session shutdown, reload and replacement close it immediately, together with the logs.
|
|
94
|
+
- Herdr subagent children (`PI_HERDR_SUBAGENTS_CHILD=1`) open no view; their tasks remain visible in the child's own widget. RPC and print modes open no view either.
|
|
95
|
+
- A failed Herdr call shows one warning. Tasks keep running and the widget stays current.
|
|
96
|
+
|
|
97
|
+
There is no setting to turn the view off.
|
|
98
|
+
|
|
76
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:
|
|
77
100
|
|
|
78
101
|
- While the main agent is busy, completions are combined into one message after the current tool batch returns, before the next model request. This includes waiting for a synchronous Herdr subagent; it does not cancel or interrupt that subagent.
|
|
79
102
|
- While idle, pending completions are combined on the next event-loop tick and wake the main agent once. Jobs that finish after that batch can produce another notification. Pi's global steering/follow-up queue settings are unchanged.
|
|
80
103
|
- If another operation such as manual compaction keeps the session busy without an agent boundary, one local timer retries after 1, 2, 4, 8, 16, then 30 seconds, staying at 30 seconds thereafter. There is no retry-count limit or expiry that discards unread results. This does not call a model or poll shell output.
|
|
81
104
|
- Normal tool/settlement boundaries still deliver immediately, without waiting for the retry timer. Without a boundary, an idle session can wait up to the current retry interval (at most 30 seconds, subject to native timer delays). Once a batch is delivered or fully consumed, the next batch starts with an immediate check and fresh backoff.
|
|
82
|
-
- A successful tool `output` read of a finished task consumes its pending reminder, including failed tasks.
|
|
105
|
+
- A successful tool `output` read of a finished task consumes its pending reminder, including failed tasks. A running snapshot, `list`, a failed log read, or a user `/bg output` inspection does not consume the main agent's reminder. Consumption does not mean the task passed validation.
|
|
83
106
|
- Aborted/error boundaries do not request continuation or replay a previously scheduled wake. An error does not suppress later completions.
|
|
84
107
|
- A user interrupt keeps the agent stopped: accepted jobs still run, but even later completions cannot restart it. Unread results remain queryable and are handed to the next user-message run before its first model request. Another extension's custom wake does not release this interrupt state; a new user-message run or session replacement does. This adds no notification pause switch.
|
|
85
108
|
- Cancelling manual compaction is separate from interrupting the agent. Pending completions still wake an otherwise-idle session after compaction succeeds, fails or is cancelled.
|
|
@@ -95,7 +118,7 @@ Pi reports asynchronous message/run-start failures through its extension error c
|
|
|
95
118
|
| View | Limit |
|
|
96
119
|
| --- | --- |
|
|
97
120
|
| Model-visible output | Last 2000 lines or 50 KiB, whichever is reached first, like Bash |
|
|
98
|
-
|
|
|
121
|
+
| Internal `structuredContent.output` | Up to 1 MiB of raw log bytes; larger logs keep their first and last 512 KiB with an omission marker |
|
|
99
122
|
| Disk capture | 32 MiB per task, 256 MiB total per session |
|
|
100
123
|
|
|
101
124
|
Display/program-view truncation does **not** stop the command. Disk limits **do** stop the overflowing task with `output_limit`; a full session budget rejects new starts. Nothing silently evicts old logs.
|
|
@@ -104,22 +127,11 @@ Output includes a log path for further reads. `truncated` describes the program
|
|
|
104
127
|
|
|
105
128
|
Output streams to private temporary logs (directory 0700, files 0600 on Unix), with bounded memory and range-limited reads. Log errors stop the task and are reported. Stdout and stderr are merged; strict ordering across the two streams is not promised. Logs and command arguments can contain secrets: choose commands accordingly.
|
|
106
129
|
|
|
107
|
-
##
|
|
108
|
-
|
|
109
|
-
Use Bash when you need a command's result before proceeding. Codemode composes tool calls and filters their results; it does not itself own background jobs.
|
|
130
|
+
## Bash and background execution
|
|
110
131
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
```javascript
|
|
114
|
-
const started = await tools.background_task({
|
|
115
|
-
action: "start",
|
|
116
|
-
command: "sleep 10; printf 'done\\n'",
|
|
117
|
-
timeout: 120,
|
|
118
|
-
});
|
|
119
|
-
text(started);
|
|
120
|
-
```
|
|
132
|
+
Use Bash when you need a command's result before proceeding. Use `background_task` directly when the command should keep running after the model's turn ends. Completion notifies the model automatically; do not add sleep or polling calls to wait for it.
|
|
121
133
|
|
|
122
|
-
|
|
134
|
+
Codemode cannot call this model-only tool. Starting an unawaited Bash call in Codemode is not a substitute: Codemode cancels unfinished nested calls when its script ends.
|
|
123
135
|
|
|
124
136
|
The tool description is compact. This package adds no `promptGuidelines` or extra global system-prompt rules.
|
|
125
137
|
|
package/TESTING.md
CHANGED
|
@@ -13,8 +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 both output views with the real host Bash tool. 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.
|
|
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, command 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, no output in notifications, above-editor placement, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. Checks the
|
|
17
|
-
- `
|
|
16
|
+
- `extension.mjs`: real extension registration with fake execution/clock; schema errors, command 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, no output in notifications, above-editor placement, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. Checks fixed `model-only` exposure and the concise English startup guidance in both return paths and the tool description; verifies 24-hour retention after an interrupt, output consumption while stopped, custom-wake isolation and restoration of automatic delivery by a new user-message run.
|
|
17
|
+
- `viewer.mjs`: the Herdr task view with an in-memory Herdr CLI. One unfocused tab with one pane per running task, command header and log paths passed as arguments (never command text as shell syntax), result line, pane reuse, tab closing after the last task and after focus moves away, user-closed panes not cancelling tasks, `/bg watch` and widget-row clicks reopening and focusing the right pane, one warning for Herdr failures, immediate close on shutdown, and no Herdr calls outside Herdr or in subagent children. Also runs the real view script against a log file. `extension.mjs` and `tui-smoke.py` run without Herdr so their widget assertions stay independent of the host terminal.
|
|
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 zero, one or two first-wave terminal outputs read directly by the model before the boundary; no extra requests follow the final report. Complete pending-batch consumption remains covered by the deterministic extension tests. Also verifies that the model receives the English guidance without a Codemode suffix, and that native Codemode cannot discover or call `background_task`. The blocking tool is a fixture, not a real Herdr child. `BG_TEST_EXTENSION=/absolute/path/to/background-tasks.ts` can run the queue regressions against an older implementation.
|
|
18
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 it 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.
|
|
19
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.
|
|
20
22
|
|
|
@@ -32,7 +34,7 @@ Requires Python 3 with the existing `pexpect` module; process fixtures use Bash,
|
|
|
32
34
|
python3 packages/background-tasks/tests/tui-smoke.py .cache/verification/background-tui
|
|
33
35
|
```
|
|
34
36
|
|
|
35
|
-
This starts a real Pi in a PTY with the production extension, Scheduler, the built-in Codemode tool and a deterministic fixture provider. It checks two jobs, rejection of a third,
|
|
37
|
+
This starts a real Pi in a PTY with the production extension, Scheduler, the built-in Codemode tool and a deterministic fixture provider. It checks two jobs, rejection of a third, model turn completion while jobs remain alive and rejection of Codemode background calls, explicit output, cancellation, automatic main-agent notification, reload/new/quit cleanup and log removal. It observes both persisted boundary entries and idle custom messages by unique session-entry ID, and rejects duplicate notifications. No network model calls occur. Mocked UI tests separately verify the exact five-second boundary.
|
|
36
38
|
|
|
37
39
|
Results and the actual ANSI stream are stored under the chosen evidence directory. Real screenshots require an isolated X11 terminal window, `gnome-terminal.real`, `xwininfo` and ImageMagick `import`:
|
|
38
40
|
|
|
@@ -44,12 +46,22 @@ gnome-terminal.real --wait --window --title='Pi Background Tasks Smoke' --geomet
|
|
|
44
46
|
|
|
45
47
|
It relays the real PTY output, captures only the test window, then closes it. Inspect the running, completed and history screenshots; check the widget has disappeared in the last one. Provider decisions are fixtures; tool execution, shell jobs, queues, TUI and cleanup are real.
|
|
46
48
|
|
|
49
|
+
## Real Herdr view
|
|
50
|
+
|
|
51
|
+
Run from a Pi or shell inside Herdr (`HERDR_ENV=1`). Start two real tasks through the production extension, for example one `printf 'tick %s\r'` loop that succeeds and one `sleep 6; exit 4` that fails. Check with `herdr tab list`, `herdr pane list` and `herdr pane read`:
|
|
52
|
+
|
|
53
|
+
- One unfocused **Background tasks** tab with two panes while both run.
|
|
54
|
+
- Each pane shows the command header, live output and a final result line (`[succeeded · exit 0 · …]`, `[failed · exit 4 · …]`).
|
|
55
|
+
- With the tab focused after both tasks end, it stays open; after focus returns to another tab, it closes.
|
|
56
|
+
- In a fullscreen Pi started in its own Herdr pane, an SGR click on each widget task row (`herdr pane send-text <pane> $'\e[<0;10;<row>M\e[<0;10;<row>m'`) focuses the tab and that task's pane (`herdr pane list`).
|
|
57
|
+
- No warning is shown, and the private log directory is removed after session shutdown.
|
|
58
|
+
|
|
47
59
|
For the original delayed-check scenario, also run one 60-second sleep + Python heredoc check against temporary build log/exit files. The normal regression uses a one-second delay to keep the suite short.
|
|
48
60
|
|
|
49
61
|
## Media and workspace checks
|
|
50
62
|
|
|
51
63
|
```bash
|
|
52
|
-
node scripts/capture-package-media.mjs background-tasks
|
|
64
|
+
HERDR_MEDIA_WINDOW_ID=<visible-herdr-window-id> node scripts/capture-package-media.mjs background-tasks
|
|
53
65
|
node tests/package-layout.mjs
|
|
54
66
|
node tests/release-check.mjs
|
|
55
67
|
npm test
|
|
@@ -58,6 +70,12 @@ npm pack --dry-run
|
|
|
58
70
|
git diff --check
|
|
59
71
|
```
|
|
60
72
|
|
|
61
|
-
The media command requires the real-TUI screenshot prerequisites above,
|
|
73
|
+
The media command requires the real-TUI screenshot prerequisites above, Pillow, and GStreamer (`ximagesrc`, VP8/WebM encoding/decoding, and PNG encoding). Select the X11 window that already displays a working Herdr client with `HERDR_MEDIA_WINDOW_ID`; the GNOME desktop must be unlocked. The recorder checks the lock state before starting and at each screenshot; hidden windows can return stale pixels.
|
|
74
|
+
|
|
75
|
+
The command first reruns the existing real TUI checks, then invokes `scripts/capture-background-tasks-media.mjs`. The recorder creates only a temporary workspace, launches the production extension with an isolated offline provider and an explicit `dark` theme, and starts two actual Python demo jobs. It sends real fullscreen SGR mouse press/release events to both task rows, verifies each exact focused pane, checks live output and both terminal results, and verifies that a focused completed tab stays open until focus leaves. Demo-job release files control completion; output intervals and viewing holds only make the recording readable.
|
|
76
|
+
|
|
77
|
+
The recorder captures the selected client window continuously, rejects uniform/blank screenshot centres, restores the original workspace/tab, and removes its own workspace. It never starts paid models or copies credentials. `result.json`, tool events and diagnostic frames are stored under `.cache/package-media/background-herdr`. The renderer publishes `docs/screenshot.png` (parent widget), `docs/task-panes.png` (actual task panes), `docs/demo.gif` (frames decoded from the recording), and the complete `docs/demo.webm`. No synthetic UI is drawn.
|
|
78
|
+
|
|
79
|
+
Inspect both screenshots, the GIF and actual video playback through `docs/package-media-gallery.html` with Chrome. Check the click transitions and final parent view, not only media decoding. The root tarball must include all four media files under `packages/background-tasks/docs/`; the root default loadout must enable its extension exactly once. The standalone tarball remains independently loadable.
|
|
62
80
|
|
|
63
81
|
Record actual checks and any missing prerequisites in `docs/verification.md`. A missing GUI, skipped browser check or unavailable Pi does not count as a successful end-to-end verification.
|
package/docs/demo.gif
CHANGED
|
Binary file
|
package/docs/demo.webm
ADDED
|
Binary file
|
package/docs/screenshot.png
CHANGED
|
Binary file
|
|
Binary file
|
|
@@ -4,10 +4,12 @@ import { Text } from "@earendil-works/pi-tui";
|
|
|
4
4
|
import { stripVTControlCharacters } from "node:util";
|
|
5
5
|
import { Type } from "typebox";
|
|
6
6
|
import { BackgroundTasks, errorText, summary, systemClock, type Clock, type TaskSnapshot } from "../src/background-tasks.ts";
|
|
7
|
+
import { cliHerdr, type HerdrCall } from "../src/herdr.ts";
|
|
8
|
+
import { HerdrViewer } from "../src/viewer.ts";
|
|
7
9
|
import { BackgroundWidget, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
|
|
8
10
|
|
|
9
11
|
const actions = ["start", "list", "output", "cancel"] as const;
|
|
10
|
-
const startGuidance = "
|
|
12
|
+
const startGuidance = "Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.";
|
|
11
13
|
type Action = typeof actions[number];
|
|
12
14
|
interface Params {
|
|
13
15
|
action: Action;
|
|
@@ -23,7 +25,7 @@ const Parameters = Type.Object({
|
|
|
23
25
|
description: Type.Optional(Type.String({ description: "Short display label for start" })),
|
|
24
26
|
cwd: Type.Optional(Type.String({ description: "Working directory for start; defaults to the session directory. Relative paths resolve from it." })),
|
|
25
27
|
timeout: Type.Optional(Type.Integer({ minimum: 1, maximum: 7200, description: "Runtime limit for start, in seconds: default 1800 (30 minutes), maximum 7200 (2 hours); no unlimited mode" })),
|
|
26
|
-
id: Type.Optional(Type.String({ description: "Task ID for output or cancel; output shows the last 2000 lines or 50 KiB
|
|
28
|
+
id: Type.Optional(Type.String({ description: "Task ID for output or cancel; output shows the last 2000 lines or 50 KiB, plus a log path." })),
|
|
27
29
|
}, { additionalProperties: false });
|
|
28
30
|
const TaskSchema = Type.Object({
|
|
29
31
|
id: Type.String(), status: StringEnum(["running", "succeeded", "failed", "cancelled", "timed_out", "output_limit"] as const),
|
|
@@ -51,14 +53,20 @@ function validate(params: Params): void {
|
|
|
51
53
|
function formatTask(task: TaskSnapshot): string {
|
|
52
54
|
return `${task.id} · ${task.status} · ${duration(task.elapsed_seconds)} / ${duration(task.timeout)}${task.exit_code === undefined ? "" : ` · exit ${task.exit_code}`} · ${JSON.stringify(task.description)}`;
|
|
53
55
|
}
|
|
54
|
-
function parseCommand(input: string): Params {
|
|
56
|
+
function parseCommand(input: string): Params | { action: "watch"; id: string } {
|
|
55
57
|
const parts = input.trim().split(/\s+/).filter(Boolean);
|
|
56
58
|
if (parts.length === 0 || (parts.length === 1 && parts[0] === "list")) return { action: "list" };
|
|
57
|
-
if (parts.length === 2 && (parts[0] === "output" || parts[0] === "cancel")) return { action: parts[0], id: parts[1] };
|
|
58
|
-
throw new Error("usage: /bg [list | output <id> | cancel <id>]");
|
|
59
|
+
if (parts.length === 2 && (parts[0] === "output" || parts[0] === "cancel" || parts[0] === "watch")) return { action: parts[0], id: parts[1] };
|
|
60
|
+
throw new Error("usage: /bg [list | output <id> | cancel <id> | watch <id>]");
|
|
59
61
|
}
|
|
60
62
|
|
|
61
|
-
|
|
63
|
+
/** Herdr panes are a view for the user's own Pi session; subagent children keep only their widget. */
|
|
64
|
+
function herdrWorkspace(env: NodeJS.ProcessEnv): string | undefined {
|
|
65
|
+
if (env.HERDR_ENV !== "1" || env.PI_HERDR_SUBAGENTS_CHILD === "1") return;
|
|
66
|
+
return env.HERDR_WORKSPACE_ID?.trim() || undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export default function (pi: ExtensionAPI, dependencies: { operations?: BashOperations; clock?: Clock; logRoot?: string; herdr?: HerdrCall; env?: NodeJS.ProcessEnv; sleep?: (ms: number) => Promise<void> } = {}) {
|
|
62
70
|
const clock = dependencies.clock ?? systemClock;
|
|
63
71
|
let manager: BackgroundTasks | undefined;
|
|
64
72
|
let context: ExtensionContext | undefined;
|
|
@@ -69,6 +77,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
69
77
|
let interrupted = false;
|
|
70
78
|
const pending = new Map<string, TaskSnapshot>();
|
|
71
79
|
let mounted: { widget: BackgroundWidget; tui: { requestRender(): void } } | undefined;
|
|
80
|
+
let viewer: HerdrViewer | undefined;
|
|
72
81
|
|
|
73
82
|
const clearNotificationTimer = () => {
|
|
74
83
|
if (notificationTimer !== undefined) clock.clearTimeout(notificationTimer);
|
|
@@ -136,6 +145,11 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
136
145
|
if (!event.aborted && completedNormally) scheduleNotification();
|
|
137
146
|
});
|
|
138
147
|
|
|
148
|
+
const watch = (id: string) => {
|
|
149
|
+
const current = context;
|
|
150
|
+
if (!manager || !viewer || !current) return;
|
|
151
|
+
viewer.watch(manager.get(id)).catch((error) => current.ui.notify(`Cannot show task ${id}: ${errorText(error)}`, "error"));
|
|
152
|
+
};
|
|
139
153
|
const clearTimer = () => {
|
|
140
154
|
if (timer !== undefined) clock.clearTimeout(timer);
|
|
141
155
|
timer = undefined;
|
|
@@ -162,7 +176,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
162
176
|
mounted.tui.requestRender();
|
|
163
177
|
} else {
|
|
164
178
|
context.ui.setWidget(WIDGET_KEY, (tui, theme) => {
|
|
165
|
-
const widget = new BackgroundWidget(() => manager?.list().tasks ?? [], clock, theme);
|
|
179
|
+
const widget = new BackgroundWidget(() => manager?.list().tasks ?? [], clock, theme, viewer ? watch : undefined);
|
|
166
180
|
mounted = { widget, tui };
|
|
167
181
|
return widget;
|
|
168
182
|
}, { placement: "aboveEditor" });
|
|
@@ -176,8 +190,10 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
176
190
|
generation++;
|
|
177
191
|
const previous = manager;
|
|
178
192
|
const previousContext = context;
|
|
193
|
+
const previousViewer = viewer;
|
|
179
194
|
manager = undefined;
|
|
180
195
|
context = undefined;
|
|
196
|
+
viewer = undefined;
|
|
181
197
|
clearTimer();
|
|
182
198
|
clearNotificationTimer();
|
|
183
199
|
pending.clear();
|
|
@@ -189,17 +205,27 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
189
205
|
if (previousContext.mode === "tui") previousContext.ui.setWidget(WIDGET_KEY, undefined);
|
|
190
206
|
}
|
|
191
207
|
mounted = undefined;
|
|
192
|
-
} finally {
|
|
208
|
+
} finally {
|
|
209
|
+
// Cancel tasks first and synchronously; closing the view tab must not delay that.
|
|
210
|
+
await Promise.all([previous?.shutdown(), previousViewer?.dispose()]);
|
|
211
|
+
}
|
|
193
212
|
};
|
|
194
213
|
pi.on("session_start", async (_event, ctx) => {
|
|
195
214
|
await dispose();
|
|
196
215
|
context = ctx;
|
|
197
216
|
const epoch = generation;
|
|
217
|
+
const workspaceId = ctx.mode === "tui" && ctx.hasUI ? herdrWorkspace(dependencies.env ?? process.env) : undefined;
|
|
218
|
+
viewer = workspaceId ? new HerdrViewer({
|
|
219
|
+
call: dependencies.herdr ?? cliHerdr(), workspaceId, sleep: dependencies.sleep,
|
|
220
|
+
tasks: () => manager?.list().tasks ?? [],
|
|
221
|
+
warn: (message) => { if (generation === epoch) ctx.ui.notify(message, "warning"); },
|
|
222
|
+
}) : undefined;
|
|
198
223
|
manager = new BackgroundTasks({
|
|
199
224
|
operations: dependencies.operations ?? createLocalBashOperations(), clock, logRoot: dependencies.logRoot,
|
|
200
225
|
onChange() { if (generation === epoch) refresh(); },
|
|
201
226
|
onComplete(task) {
|
|
202
227
|
if (generation !== epoch || !context) return;
|
|
228
|
+
viewer?.finished(task);
|
|
203
229
|
pending.set(task.id, task);
|
|
204
230
|
scheduleNotification();
|
|
205
231
|
},
|
|
@@ -212,6 +238,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
212
238
|
if (!manager) throw new Error("Background tasks session is not ready");
|
|
213
239
|
if (params.action === "start") {
|
|
214
240
|
const task = manager.start({ command: params.command!, description: params.description, cwd: params.cwd, timeout: params.timeout }, cwd);
|
|
241
|
+
void viewer?.show(task, params.command!);
|
|
215
242
|
return {
|
|
216
243
|
text: `Started ${formatTask(task)}\n${startGuidance}\nLog: ${task.log_path}\nAt most 2 tasks run at once. Tasks stop on session changes, reload, or exit; captured logs are then removed.`,
|
|
217
244
|
data: { action: params.action, task, guidance: startGuidance }, details: { action: params.action, task }, isError: false,
|
|
@@ -240,6 +267,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
240
267
|
|
|
241
268
|
pi.registerTool({
|
|
242
269
|
name: "background_task", label: "Background task",
|
|
270
|
+
exposure: "model-only",
|
|
243
271
|
description: `Start shell commands as background tasks and return task IDs immediately. Supports status, output, and cancellation. After start: ${startGuidance}`,
|
|
244
272
|
parameters: Parameters, outputSchema: OutputSchema,
|
|
245
273
|
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
@@ -247,7 +275,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
247
275
|
try {
|
|
248
276
|
if (signal?.aborted) throw new Error("Tool call aborted before task acceptance");
|
|
249
277
|
const result = await perform(params, ctx?.cwd ?? context?.cwd ?? process.cwd());
|
|
250
|
-
// A terminal result was consumed by
|
|
278
|
+
// A terminal result was consumed by the model.
|
|
251
279
|
// User /bg inspections and running snapshots do not acknowledge completion.
|
|
252
280
|
if (params.action === "output" && "task" in result.data && result.data.task.status !== "running") {
|
|
253
281
|
pending.delete(result.data.task.id);
|
|
@@ -269,10 +297,18 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
|
|
|
269
297
|
},
|
|
270
298
|
});
|
|
271
299
|
pi.registerCommand("bg", {
|
|
272
|
-
description: "List background shell tasks, read output,
|
|
300
|
+
description: "List background shell tasks, read output, cancel a task, or watch it in Herdr",
|
|
273
301
|
handler: async (args, ctx) => {
|
|
274
302
|
try {
|
|
275
|
-
const
|
|
303
|
+
const params = parseCommand(args);
|
|
304
|
+
if (params.action === "watch") {
|
|
305
|
+
if (!manager) throw new Error("Background tasks session is not ready");
|
|
306
|
+
const task = manager.get(params.id);
|
|
307
|
+
if (!viewer) throw new Error("/bg watch needs this Pi session to run inside Herdr");
|
|
308
|
+
await viewer.watch(task);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
const result = await perform(params, ctx.cwd);
|
|
276
312
|
pi.sendMessage({ customType: "background-task-inspect", content: result.text, display: true, details: result.details }, { triggerTurn: false });
|
|
277
313
|
} catch (error) { ctx.ui.notify(errorText(error), "error"); }
|
|
278
314
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maxiaochao/pi-background-tasks",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Session-scoped background shell tasks with completion notifications for Pi.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"typebox": "*"
|
|
35
35
|
},
|
|
36
36
|
"scripts": {
|
|
37
|
-
"test": "node --experimental-strip-types --import ./tests/runtime.mjs --test tests/tasks.mjs tests/output.mjs tests/processes.mjs tests/extension.mjs tests/notifications.mjs tests/compaction.mjs tests/interruptions.mjs",
|
|
37
|
+
"test": "node --experimental-strip-types --import ./tests/runtime.mjs --test tests/tasks.mjs tests/output.mjs tests/processes.mjs tests/extension.mjs tests/notifications.mjs tests/compaction.mjs tests/interruptions.mjs tests/viewer.mjs tests/media.mjs",
|
|
38
38
|
"load-test": "node --experimental-strip-types tests/load.mjs"
|
|
39
39
|
},
|
|
40
40
|
"publishConfig": {
|
package/src/herdr.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
/** One Herdr CLI call: arguments in, parsed `result` object out. */
|
|
4
|
+
export type HerdrCall = (args: string[]) => Promise<Record<string, any>>;
|
|
5
|
+
|
|
6
|
+
export class HerdrError extends Error {
|
|
7
|
+
readonly code?: string;
|
|
8
|
+
constructor(message: string, code?: string) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "HerdrError";
|
|
11
|
+
this.code = code;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function isMissing(error: unknown): boolean {
|
|
16
|
+
return error instanceof HerdrError && /^(tab|pane)_not_found$/.test(error.code ?? "");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Spawns the Herdr CLI without a shell. A hung call fails after `timeoutMs`. */
|
|
20
|
+
export function cliHerdr(binary = "herdr", timeoutMs = 10_000): HerdrCall {
|
|
21
|
+
return (args) => new Promise((resolve, reject) => {
|
|
22
|
+
let stdout = "";
|
|
23
|
+
let stderr = "";
|
|
24
|
+
const child = spawn(binary, args, { stdio: ["ignore", "pipe", "pipe"], shell: false, signal: AbortSignal.timeout(timeoutMs) });
|
|
25
|
+
child.stdout.on("data", (chunk) => { stdout += chunk; });
|
|
26
|
+
child.stderr.on("data", (chunk) => { stderr += chunk; });
|
|
27
|
+
child.once("error", (error) => reject(new HerdrError(`herdr ${args[0]} ${args[1]}: ${error.message}`)));
|
|
28
|
+
child.once("close", (code) => {
|
|
29
|
+
let parsed: { result?: Record<string, any>; error?: { code?: string; message?: string } } | undefined;
|
|
30
|
+
try { parsed = JSON.parse(stdout); } catch { /* Reported below. */ }
|
|
31
|
+
if (code === 0 && parsed?.result) return resolve(parsed.result);
|
|
32
|
+
// Some commands, such as `pane run`, succeed without printing a response.
|
|
33
|
+
if (code === 0 && !stdout.trim()) return resolve({});
|
|
34
|
+
const detail = parsed?.error?.message ?? (stderr.trim() || stdout.trim() || `exit code ${code}`);
|
|
35
|
+
reject(new HerdrError(`herdr ${args[0]} ${args[1]}: ${detail}`, parsed?.error?.code));
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
}
|