@maxiaochao/pi-background-tasks 0.2.0 → 0.3.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 CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026-11-03 - v0.3.0
4
+
5
+ - Report completion status and log paths for progressive inspection with bounded explicit output
6
+ - Send only terminal status, timestamps, reason and captured log paths on completion, with guidance to search relevant terms or read bounded ranges progressively as needed. Do not automatically read, summarize or inject stdout/stderr.
7
+ - Keep a defensive 16-KiB model-visible status/path batch cap and retain overflow tasks for later boundaries; remove the automatic log-preview pipeline and its separate output budget.
8
+ - Keep a short task-specific completion-notification reminder separate from the capability/lifecycle declaration. Preserve running-task list/output inspection; remove start-text log paths and the redundant structured guidance field.
9
+ - Preserve consumption filtering, interrupt/compaction behavior and synchronous send-failure retention. Verify that missing logs are not opened during notification and explicit inspections diagnose them independently.
10
+ - Use one 100-line/8-KiB tail for explicit model and structured output, with truncation metadata and targeted full-log access; retire the separate 1-MiB program view.
11
+
3
12
  ## 2026-10-29 - v0.2.0
4
13
 
5
14
  - Add live read-only Herdr task views, exact widget navigation and real two-task terminal media
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Pi Background Tasks
2
2
 
3
- Run shell commands in the background, then notify the main agent when they finish. These are local processes, not subagents.
3
+ Run shell commands in the background, then notify the main agent of completion and the captured log location. These are local processes, not subagents.
4
4
 
5
5
  ![Real parent Pi: click either background task row to watch it in Herdr](docs/screenshot.png)
6
6
 
@@ -18,7 +18,7 @@ A command such as `sleep 60; python3 ...` can spend most of its time waiting to
18
18
 
19
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.
20
20
 
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.
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. Prompt timing is informed by [OMP’s background-start notice](https://github.com/can1357/oh-my-pi/blob/256b3211bca7458391866a8bcc9369902664be55/packages/tui/src/tools/bash.ts#L36-L48), but delivery is deliberately different: this package sends status and log paths only, not OMP-style automatic command-output injection. Agents inspect captured logs progressively when needed.
22
22
 
23
23
  ## Install and update
24
24
 
@@ -39,24 +39,26 @@ background_task({ action: "start", command: "sleep 10; printf 'checks complete\\
39
39
 
40
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.
41
41
 
42
- Each accepted start includes this guidance in the tool description, result text and `structuredContent.guidance`:
42
+ The tool declaration describes automatic completion notifications, concurrency and session lifetime. The action parameter explicitly permits `list` and `output` while tasks are still running. Each accepted start returns only its task data and this short, task-specific reminder:
43
43
 
44
- > Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.
44
+ > Completion is reported automatically. Continue other work or end the turn; do not repeatedly query just to wait for completion.
45
45
 
46
- After the completion notification, read the result:
46
+ 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`.
47
+
48
+ Inspect a running or finished task whenever its output is needed; no completion or timeout notification is required:
47
49
 
48
50
  ```text
49
51
  background_task({ action: "output", id: "<returned-task-id>" })
50
52
  ```
51
53
 
52
- The tool also supports listing and cancellation:
54
+ Use `list` to inspect task status at any time, including while tasks are running. These are agent-callable actions, not only user `/bg` commands. Query on demand rather than repeatedly checking just to wait. 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
55
 
54
56
  ```text
55
57
  background_task({ action: "list" })
56
58
  background_task({ action: "cancel", id: "<returned-task-id>" })
57
59
  ```
58
60
 
59
- Start returns a running task's ID, log path and runtime limit, not the command's final output. An invalid start is rejected before execution. A later execution error becomes a failed task.
61
+ Start returns a running task's ID and runtime limit, not the command's final output. An invalid start is rejected before execution. A later execution error becomes a failed task.
60
62
 
61
63
  - `command`: unchanged multi-line shell script; only for start.
62
64
  - `description`: optional display label, shortened to 200 characters.
@@ -98,8 +100,8 @@ There is no setting to turn the view off.
98
100
 
99
101
  Completion, failure, cancellation, timeout and output-limit termination update the widget immediately. The extension holds pending completion metadata until it can deliver it safely:
100
102
 
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.
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.
103
+ - While the main agent is busy, completions are combined into a bounded 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.
104
+ - While idle, pending completions are combined on the next event-loop tick and wake the main agent once. Oversized metadata batches remain pending for later safe boundaries rather than being dropped. Jobs that finish after that batch can produce another notification. Pi's global steering/follow-up queue settings are unchanged.
103
105
  - 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.
104
106
  - 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.
105
107
  - 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.
@@ -109,7 +111,15 @@ Completion, failure, cancellation, timeout and output-limit termination update t
109
111
 
110
112
  Pi's public interrupted-run event does not include the abort reason. In particular, starting `/compact` during an active run first interrupts that run. This package preserves that interruption until the next user-message run; it does not infer that compaction grants permission to restart the agent. Compaction started while already idle does not create this interrupted-run state.
111
113
 
112
- Each message includes actual completion times, statuses and log paths, **not the output body**. The agent can call output when it needs details. Completions that arrive near final settlement are checked again before the run settles. No per-task `followUp` messages are left behind the main agent's final report.
114
+ Each completion message includes task status, exit code when available, actual end time, reason when applicable and **the captured log path**, followed by:
115
+
116
+ > Inspect logs progressively as needed: search for relevant terms or read bounded ranges; avoid loading the whole log by default.
117
+
118
+ No stdout/stderr body, automatic preview or generated log summary is included. Building a notification does not open the log file. Agents may filter the reported file directly or call `output` for a bounded snapshot; no notification is required for running-task inspection either. Missing log files are reported only when an inspection is requested, not by silently changing task status during notification.
119
+
120
+ Status/path batches have a defensive **16-KiB model-visible text cap**. Tasks that cannot fit remain pending for the next safe boundary; this is a metadata backlog guard, not a log-preview allowance. There is no automatic log-output budget because no log bodies are attached. Captured files remain until session cleanup.
121
+
122
+ Completions that arrive near final settlement are checked again before the run settles. No per-task `followUp` messages are left behind the main agent’s final report.
113
123
 
114
124
  Pi reports asynchronous message/run-start failures through its extension error channel. This extension does not automatically replay a message after such a failure; task metadata and captured logs remain queryable for the lifetime of the session.
115
125
 
@@ -117,19 +127,21 @@ Pi reports asynchronous message/run-start failures through its extension error c
117
127
 
118
128
  | View | Limit |
119
129
  | --- | --- |
120
- | Model-visible output | Last 2000 lines or 50 KiB, whichever is reached first, like Bash |
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 |
130
+ | Model-visible output body | Last 100 lines or 8 KiB, whichever is reached first |
131
+ | `structuredContent.output` | The same bounded tail; no separate 1 MiB program view |
132
+ | Automatic completion log bodies | None; only status, log paths and progressive-inspection guidance |
133
+ | Completion status/path text | 16 KiB defensive batch cap; remaining tasks stay pending |
122
134
  | Disk capture | 32 MiB per task, 256 MiB total per session |
123
135
 
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.
136
+ Preview 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.
125
137
 
126
- Output includes a log path for further reads. `truncated` describes the program view, not disk capture. `task.capture_complete` is false while running or when log data was lost. The states are `running`, `succeeded`, `failed`, `cancelled`, `timed_out` and `output_limit`.
138
+ Output includes a log path for further reads. `truncated` describes the shared preview, not disk capture. The preview includes omission information and total lines/bytes; the task includes captured byte count and a full-log path for targeted follow-up reads. A smaller preview can miss an earlier root cause; use a focused search when it does. `task.capture_complete` is false while running or when log data was lost. The states are `running`, `succeeded`, `failed`, `cancelled`, `timed_out` and `output_limit`.
127
139
 
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.
140
+ 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: avoid commands that print credentials or other sensitive data, and inspect captured content only when needed.
129
141
 
130
142
  ## Bash and background execution
131
143
 
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.
144
+ 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. Inspect status with `list` or logs with `output` on demand, including while running and before any notification; do not add sleep or repeated polling to wait for completion.
133
145
 
134
146
  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.
135
147
 
package/TESTING.md CHANGED
@@ -11,15 +11,17 @@ npm pack ./packages/background-tasks --dry-run
11
11
  Tests use Node's built-in test runner. They resolve host peers from the installed Pi rather than installing another copy. npm's workspace `node_modules/.bin` directories are excluded from this lookup because they can contain an older development Pi. Set `PI_TEST_BINARY=/absolute/path/to/pi` to choose a specific host.
12
12
 
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
- - `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.
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, 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.
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, 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, above-editor placement, five-second retention, narrow/CJK rendering, coexistence and non-TUI modes. Checks fixed `model-only` exposure and separate concise declaration and task-specific start guidance, no start-text log path or redundant structured guidance field, and explicit running-task `list`/`output` availability; 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
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
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.
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
+ - `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. Complete pending-batch consumption remains covered by the deterministic extension tests. Also verifies that the model receives distinct declaration/start guidance without a Codemode suffix, and that the next request receives status/log locations without command output, 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.
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
 
23
+ The compaction fixtures seed a completed earlier turn and sufficient recent context explicitly; their ability to compact must not depend on how verbose the start result is. Active-compaction interrupt cases count their completed warm-up request separately.
24
+
23
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.
24
26
 
25
27
  Notification retry tests use the injected clock and session-idle interface. They check the 1/2/4/8/16/30-second delays, the repeated 30-second cap, retention across 24 hours of busy time, one timer shared by new completions, 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.
package/docs/demo.gif CHANGED
Binary file
package/docs/demo.webm CHANGED
Binary file
Binary file
Binary file
@@ -9,7 +9,9 @@ import { HerdrViewer } from "../src/viewer.ts";
9
9
  import { BackgroundWidget, FINISHED_VISIBLE_MS, WIDGET_KEY, duration, visibleTasks } from "../src/widget.ts";
10
10
 
11
11
  const actions = ["start", "list", "output", "cancel"] as const;
12
- const startGuidance = "Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.";
12
+ const startNotice = "Completion is reported automatically. Continue other work or end the turn; do not repeatedly query just to wait for completion.";
13
+ // Bound model-visible status text when many completions accumulate.
14
+ const NOTIFICATION_MAX_BYTES = 16 * 1024;
13
15
  type Action = typeof actions[number];
14
16
  interface Params {
15
17
  action: Action;
@@ -20,12 +22,12 @@ interface Params {
20
22
  id?: string;
21
23
  }
22
24
  const Parameters = Type.Object({
23
- action: StringEnum(actions, { description: "start returns a task ID immediately; list checks tasks; output reads a bash-limited snapshot; 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. list and output also work while tasks are running." }),
24
26
  command: Type.Optional(Type.String({ description: "Shell command for start; may be multi-line. Runs locally, with stdin closed." })),
25
27
  description: Type.Optional(Type.String({ description: "Short display label for start" })),
26
28
  cwd: Type.Optional(Type.String({ description: "Working directory for start; defaults to the session directory. Relative paths resolve from it." })),
27
29
  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" })),
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." })),
30
+ id: Type.Optional(Type.String({ description: "Task ID for output or cancel; output returns a bounded snapshot (last 100 lines or 8 KiB) and the captured log path." })),
29
31
  }, { additionalProperties: false });
30
32
  const TaskSchema = Type.Object({
31
33
  id: Type.String(), status: StringEnum(["running", "succeeded", "failed", "cancelled", "timed_out", "output_limit"] as const),
@@ -37,7 +39,6 @@ const OutputSchema = Type.Object({
37
39
  action: Type.Optional(StringEnum(actions)), task: Type.Optional(TaskSchema), tasks: Type.Optional(Type.Array(TaskSchema)),
38
40
  running: Type.Optional(Type.Number()), total: Type.Optional(Type.Number()), omitted: Type.Optional(Type.Number()),
39
41
  output: Type.Optional(Type.String()), truncated: Type.Optional(Type.Boolean()), full_output_path: Type.Optional(Type.String()),
40
- guidance: Type.Optional(Type.String()),
41
42
  error: Type.Optional(Type.String()),
42
43
  });
43
44
 
@@ -53,6 +54,15 @@ function validate(params: Params): void {
53
54
  function formatTask(task: TaskSnapshot): string {
54
55
  return `${task.id} · ${task.status} · ${duration(task.elapsed_seconds)} / ${duration(task.timeout)}${task.exit_code === undefined ? "" : ` · exit ${task.exit_code}`} · ${JSON.stringify(task.description)}`;
55
56
  }
57
+
58
+ function completionText(task: TaskSnapshot): string {
59
+ const lines = [formatTask(task), `Ended at: ${new Date(task.ended_at!).toISOString()}`];
60
+ if (task.reason) lines.push(`Reason: ${task.reason}`);
61
+ lines.push(`Captured log: ${task.log_path}`);
62
+ if (!task.capture_complete) lines.push("Output capture is incomplete.");
63
+ return lines.join("\n");
64
+ }
65
+
56
66
  function parseCommand(input: string): Params | { action: "watch"; id: string } {
57
67
  const parts = input.trim().split(/\s+/).filter(Boolean);
58
68
  if (parts.length === 0 || (parts.length === 1 && parts[0] === "list")) return { action: "list" };
@@ -86,14 +96,25 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
86
96
  const takeNotification = () => {
87
97
  clearNotificationTimer();
88
98
  if (pending.size === 0) return;
99
+ if (!manager) throw new Error("Cannot deliver background results without their session manager");
89
100
  const tasks = [...pending.values()].sort((a, b) => a.ended_at! - b.ended_at!);
90
- pending.clear();
101
+ const selected: TaskSnapshot[] = [];
102
+ const parts = ["[Background task finished]"];
103
+ const guidance = "\n\nInspect logs progressively as needed: search for relevant terms or read bounded ranges; avoid loading the whole log by default.";
104
+ const more = "\n\nMore completed task results remain pending.";
105
+ for (const record of tasks) {
106
+ const task = manager.get(record.id);
107
+ const text = completionText(task);
108
+ if (Buffer.byteLength([...parts, text].join("\n\n") + guidance + more) > NOTIFICATION_MAX_BYTES) break;
109
+ parts.push(text);
110
+ selected.push(task);
111
+ }
112
+ if (!selected.length) throw new Error("A background completion exceeds the notification byte limit");
113
+ for (const task of selected) pending.delete(task.id);
91
114
  return {
92
115
  customType: "background-task-finished", display: true,
93
- details: { tasks, ...(tasks.length === 1 ? { task: tasks[0] } : {}) },
94
- content: `[Background task finished]\n${tasks.map((task) =>
95
- `${formatTask(task)}\nEnded at: ${new Date(task.ended_at!).toISOString()}${task.reason ? `\nReason: ${task.reason}` : ""}\nCaptured log: ${task.log_path}${task.capture_complete ? "" : "\nOutput capture is incomplete."}`
96
- ).join("\n\n")}`,
116
+ details: { tasks: selected, ...(selected.length === 1 ? { task: selected[0] } : {}) },
117
+ content: parts.join("\n\n") + guidance + (pending.size ? more : ""),
97
118
  };
98
119
  };
99
120
  const scheduleNotification = (delay = 0) => {
@@ -240,8 +261,8 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
240
261
  const task = manager.start({ command: params.command!, description: params.description, cwd: params.cwd, timeout: params.timeout }, cwd);
241
262
  void viewer?.show(task, params.command!);
242
263
  return {
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.`,
244
- data: { action: params.action, task, guidance: startGuidance }, details: { action: params.action, task }, isError: false,
264
+ text: `Started ${formatTask(task)}\n${startNotice}`,
265
+ data: { action: params.action, task }, details: { action: params.action, task }, isError: false,
245
266
  };
246
267
  }
247
268
  if (params.action === "list") {
@@ -268,7 +289,7 @@ export default function (pi: ExtensionAPI, dependencies: { operations?: BashOper
268
289
  pi.registerTool({
269
290
  name: "background_task", label: "Background task",
270
291
  exposure: "model-only",
271
- description: `Start shell commands as background tasks and return task IDs immediately. Supports status, output, and cancellation. After start: ${startGuidance}`,
292
+ description: "Run up to two concurrent background shell tasks with automatic completion notifications. Tasks stop and captured logs are deleted on session changes, reload, or exit.",
272
293
  parameters: Parameters, outputSchema: OutputSchema,
273
294
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
274
295
  async execute(_id, params, signal, _onUpdate, ctx) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maxiaochao/pi-background-tasks",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Session-scoped background shell tasks with completion notifications for Pi.",
5
5
  "type": "module",
6
6
  "keywords": [
package/src/output.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { closeSync, openSync, readSync, writeSync } from "node:fs";
2
- import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail, type TruncationResult } from "@earendil-works/pi-coding-agent";
2
+ import { formatSize, truncateTail, type TruncationResult } from "@earendil-works/pi-coding-agent";
3
3
 
4
- const PROGRAM_BYTES = 1024 * 1024;
4
+ const OUTPUT_MAX_BYTES = 8 * 1024;
5
+ const OUTPUT_MAX_LINES = 100;
5
6
  export type LogWrite = (fd: number, data: Buffer) => number;
6
7
 
7
8
  export interface OutputView {
@@ -23,6 +24,7 @@ export class TaskLog {
23
24
  private lines = 0;
24
25
  private openLine = false;
25
26
  private lastLineBytes = 0;
27
+ private lastCompletedLineBytes = 0;
26
28
 
27
29
  constructor(path: string, write: LogWrite = (fd, data) => writeSync(fd, data)) {
28
30
  this.path = path;
@@ -55,7 +57,7 @@ export class TaskLog {
55
57
  try {
56
58
  // Keep a bounded working window comparable to Bash's rolling tail. This
57
59
  // preserves an oversized last line that ends with a newline before trimming.
58
- const start = Math.max(0, this.bytes - DEFAULT_MAX_BYTES * 4 - 4);
60
+ const start = Math.max(0, this.bytes - OUTPUT_MAX_BYTES * 4 - 4);
59
61
  const tail = this.range(fd, start, this.bytes - start);
60
62
  let first = 0;
61
63
  while (first < tail.length && (tail[first] & 0xc0) === 0x80) first++;
@@ -64,14 +66,14 @@ export class TaskLog {
64
66
  const previous = this.range(fd, start - 1, 1)[0];
65
67
  if (first > 0 || previous !== 0x0a) {
66
68
  const newline = snapshot.indexOf("\n");
67
- if (newline !== -1) snapshot = snapshot.slice(newline + 1);
69
+ if (newline !== -1 && newline < snapshot.length - 1) snapshot = snapshot.slice(newline + 1);
68
70
  }
69
71
  }
70
- const truncation = truncateTail(snapshot);
72
+ const truncation = truncateTail(snapshot, { maxLines: OUTPUT_MAX_LINES, maxBytes: OUTPUT_MAX_BYTES });
71
73
  const totalLines = this.lines + (this.openLine ? 1 : 0);
72
- truncation.truncated = totalLines > DEFAULT_MAX_LINES || this.decodedBytes > DEFAULT_MAX_BYTES;
74
+ truncation.truncated = totalLines > OUTPUT_MAX_LINES || this.decodedBytes > OUTPUT_MAX_BYTES;
73
75
  truncation.truncatedBy = truncation.truncated
74
- ? (truncation.truncatedBy ?? (this.decodedBytes > DEFAULT_MAX_BYTES ? "bytes" : "lines")) : null;
76
+ ? (truncation.truncatedBy ?? (this.decodedBytes > OUTPUT_MAX_BYTES ? "bytes" : "lines")) : null;
75
77
  truncation.totalLines = totalLines;
76
78
  truncation.totalBytes = this.decodedBytes;
77
79
  let text = truncation.content || "(no output)";
@@ -79,29 +81,14 @@ export class TaskLog {
79
81
  const end = totalLines;
80
82
  const begin = end - truncation.outputLines + 1;
81
83
  const detail = truncation.lastLinePartial
82
- ? `last ${formatSize(truncation.outputBytes)} of line ${end} (line is ${formatSize(this.lastLineBytes)})`
83
- : `lines ${begin}-${end} of ${end}${truncation.truncatedBy === "bytes" ? ` (${formatSize(DEFAULT_MAX_BYTES)} limit)` : ""}`;
84
+ ? `last ${formatSize(truncation.outputBytes)} of line ${end} (line is ${formatSize(this.openLine ? this.lastLineBytes : this.lastCompletedLineBytes)})`
85
+ : `lines ${begin}-${end} of ${end}${truncation.truncatedBy === "bytes" ? ` (${formatSize(OUTPUT_MAX_BYTES)} limit)` : ""}`;
84
86
  text += `\n\n[Showing ${detail}. Full output: ${this.path}]`;
85
87
  }
86
- const program = this.readProgram(fd);
87
- return { text, output: program.content, truncated: program.truncated, truncation };
88
+ return { text, output: truncation.content, truncated: truncation.truncated, truncation };
88
89
  } finally { closeSync(fd); }
89
90
  }
90
91
 
91
- private readProgram(fd: number): { content: string; truncated: boolean } {
92
- if (this.bytes <= PROGRAM_BYTES) {
93
- return { content: new TextDecoder().decode(this.range(fd, 0, this.bytes), { stream: !this.closed }), truncated: false };
94
- }
95
- const half = PROGRAM_BYTES / 2;
96
- const head = this.range(fd, 0, half);
97
- const tail = this.range(fd, this.bytes - half, half);
98
- const headText = new TextDecoder().decode(head, { stream: true });
99
- let first = 0;
100
- while (first < tail.length && (tail[first] & 0xc0) === 0x80) first++;
101
- const tailText = new TextDecoder().decode(tail.subarray(first), { stream: !this.closed });
102
- return { content: `${headText}\n\n[... ${this.bytes - PROGRAM_BYTES} bytes omitted ...]\n\n${tailText}`, truncated: true };
103
- }
104
-
105
92
  private range(fd: number, position: number, length: number): Buffer {
106
93
  const data = Buffer.alloc(length);
107
94
  let offset = 0;
@@ -120,6 +107,8 @@ export class TaskLog {
120
107
  if (text.length) this.openLine = true;
121
108
  this.lastLineBytes += Buffer.byteLength(text);
122
109
  } else {
110
+ const previous = last === 0 ? -1 : text.lastIndexOf("\n", last - 1);
111
+ this.lastCompletedLineBytes = Buffer.byteLength(text.slice(previous + 1, last)) + (previous === -1 ? this.lastLineBytes : 0);
123
112
  for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", index + 1)) this.lines++;
124
113
  this.lastLineBytes = Buffer.byteLength(text.slice(last + 1));
125
114
  this.openLine = last < text.length - 1;
@@ -97,7 +97,9 @@ for (const outcome of ["success", "failure", "cancel"]) {
97
97
  });
98
98
  await session.bindExtensions({});
99
99
  await session.prompt("Earlier context to summarize: " + "background verification history ".repeat(200));
100
- await session.prompt("START_COMPACTION_JOB");
100
+ // Keep a complete earlier turn summarizable independently of the
101
+ // background tool's start-result length.
102
+ await session.prompt("START_COMPACTION_JOB " + "Recent context to keep. ".repeat(200));
101
103
  assert.equal(startedTask?.status, "running");
102
104
  assert.equal(session.isIdle, true);
103
105
  const notifications = () => session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === "background-task-finished");
@@ -134,6 +136,8 @@ for (const outcome of ["success", "failure", "cancel"]) {
134
136
  assert.equal(notifications().length, 1);
135
137
  assert.equal(conversationRequests().length, before + 1, "no user prompt is submitted after compact()");
136
138
  const notification = notifications()[0];
139
+ assert.doesNotMatch(notification.content, /finished during compaction/);
140
+ assert.ok(notification.content.includes(notification.details.tasks[0].log_path));
137
141
  const task = notification.details.tasks[0];
138
142
  assert.equal(task.id, startedTask.id);
139
143
  assert.equal(task.status, "failed");
@@ -15,7 +15,7 @@ function harness(mode = "tui", hasUI = true) {
15
15
  const placements = new Map();
16
16
  const statuses = new Map();
17
17
  const idleChecks = [];
18
- let tool, renders = 0, idle = true;
18
+ let tool, renders = 0, idle = true, failSend = false;
19
19
  const theme = { fg: (_color, text) => text, bold: (text) => text };
20
20
  const ctx = {
21
21
  cwd: f.root, mode, hasUI, isIdle: () => { idleChecks.push(f.clock.now()); return idle; },
@@ -33,12 +33,16 @@ function harness(mode = "tui", hasUI = true) {
33
33
  on(name, handler) { handlers.set(name, handler); },
34
34
  registerTool(value) { tool = value; },
35
35
  registerCommand(name, value) { commands.set(name, value); },
36
- sendMessage(message, options) { messages.push({ message, options }); },
36
+ sendMessage(message, options) {
37
+ if (failSend) { failSend = false; throw new Error("Fixture delivery rejected"); }
38
+ messages.push({ message, options });
39
+ },
37
40
  };
38
41
  register(pi, { operations: f.operations, clock: f.clock, logRoot: f.root, env: {} });
39
42
  return {
40
43
  ...f, handlers, commands, messages, notices, widgets, placements, statuses, idleChecks, ctx,
41
44
  setIdle(value) { idle = value; },
45
+ failNextSend() { failSend = true; },
42
46
  get tool() { return tool; }, get renders() { return renders; },
43
47
  async close() {
44
48
  const closing = handlers.get("session_shutdown")({}, ctx);
@@ -71,6 +75,139 @@ test("completions during a synchronous tool are merged before the next model req
71
75
  } finally { await h.close(); }
72
76
  });
73
77
 
78
+ test("completion sends only status and log location with progressive-inspection guidance", async () => {
79
+ const h = harness("print", false);
80
+ try {
81
+ await h.handlers.get("session_start")({}, h.ctx);
82
+ h.setIdle(false);
83
+ const task = (await h.tool.execute("start", { action: "start", command: "build" })).structuredContent.task;
84
+ h.calls[0].onData(Buffer.from("BUILD RESULT: done\n"));
85
+ h.calls[0].resolve();
86
+ await flush();
87
+ const message = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
88
+ assert.doesNotMatch(message.content, /BUILD RESULT: done|Untrusted shell output/);
89
+ assert.ok(message.content.includes(`Captured log: ${task.log_path}`));
90
+ assert.match(message.content, /Inspect logs progressively as needed/);
91
+ assert.match(message.content, /search for relevant terms or read bounded ranges/);
92
+ assert.doesNotMatch(message.content, /do not repeatedly|Do not sleep|Inspect:/);
93
+ const inspected = await h.tool.execute("inspect", { action: "output", id: task.id });
94
+ assert.equal(inspected.structuredContent.output, "BUILD RESULT: done\n");
95
+ assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx), undefined);
96
+ } finally { await h.close(); }
97
+ });
98
+
99
+ test("status-only completion batches stay bounded without reading or injecting large UTF-8 logs", async () => {
100
+ const h = harness("print", false);
101
+ try {
102
+ await h.handlers.get("session_start")({}, h.ctx);
103
+ h.setIdle(false);
104
+ const ids = [];
105
+ const data = Buffer.from("🙂".repeat(3000));
106
+ for (let i = 0; i < 10; i++) {
107
+ const task = (await h.tool.execute(`start-${i}`, { action: "start", command: `build-${i}`, description: "界".repeat(200) })).structuredContent.task;
108
+ ids.push(task.id);
109
+ h.calls[i].onData(data);
110
+ h.calls[i].reject(new Error("错".repeat(500)));
111
+ await flush();
112
+ }
113
+ const delivered = [];
114
+ let batches = 0;
115
+ for (;;) {
116
+ const boundary = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx);
117
+ if (!boundary) break;
118
+ assert.ok(++batches <= ids.length, "every batch must make progress");
119
+ const message = boundary.entries[0];
120
+ assert.ok(Buffer.byteLength(message.content) <= 16384);
121
+ assert.ok(!message.content.includes("\uFFFD"), "budget cuts must preserve UTF-8");
122
+ assert.ok(!message.content.includes("🙂"), "captured log bodies must not enter notifications");
123
+ assert.doesNotMatch(message.content, /Untrusted shell output|Output preview/);
124
+ delivered.push(...message.details.tasks.map((task) => task.id));
125
+ }
126
+ assert.ok(batches > 1, "long metadata must split the pending batch");
127
+ assert.deepEqual(delivered, ids);
128
+ assert.equal(h.messages.length, 0);
129
+ const inspected = await h.tool.execute("inspect", { action: "output", id: ids[0] });
130
+ assert.equal(inspected.structuredContent.task.bytes, data.length);
131
+ assert.equal(inspected.structuredContent.task.capture_complete, true);
132
+ } finally { await h.close(); }
133
+ });
134
+
135
+ test("notification does not open missing logs; later explicit inspections report errors independently", async () => {
136
+ const h = harness("print", false);
137
+ try {
138
+ await h.handlers.get("session_start")({}, h.ctx);
139
+ h.setIdle(false);
140
+ const broken = (await h.tool.execute("broken", { action: "start", command: "broken" })).structuredContent.task;
141
+ const healthy = (await h.tool.execute("healthy", { action: "start", command: "healthy" })).structuredContent.task;
142
+ h.calls[0].onData(Buffer.from("unavailable log\n"));
143
+ h.calls[1].onData(Buffer.from("healthy result\n"));
144
+ h.calls[0].resolve(7);
145
+ h.calls[1].resolve();
146
+ await flush();
147
+ unlinkSync(broken.log_path);
148
+ const message = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
149
+ assert.deepEqual(message.details.tasks.map((task) => task.id), [broken.id, healthy.id]);
150
+ assert.equal(message.details.tasks[0].status, "failed");
151
+ assert.equal(message.details.tasks[0].capture_complete, true, "notification must not inspect the file or mutate capture state");
152
+ assert.ok(message.content.includes(broken.log_path));
153
+ assert.ok(message.content.includes(healthy.log_path));
154
+ assert.doesNotMatch(message.content, /healthy result|unavailable log|Output unavailable/);
155
+ const missing = await h.tool.execute("read-broken", { action: "output", id: broken.id });
156
+ assert.equal(missing.isError, true);
157
+ assert.match(missing.structuredContent.error, /Cannot read task log/);
158
+ const present = await h.tool.execute("read-healthy", { action: "output", id: healthy.id });
159
+ assert.equal(present.structuredContent.output, "healthy result\n");
160
+ assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx), undefined);
161
+ } finally { await h.close(); }
162
+ });
163
+
164
+ test("a rejected idle delivery retains its result for the next safe boundary", async () => {
165
+ const h = harness("print", false);
166
+ try {
167
+ await h.handlers.get("session_start")({}, h.ctx);
168
+ const task = (await h.tool.execute("start", { action: "start", command: "build" })).structuredContent.task;
169
+ h.calls[0].onData(Buffer.from("retained result\n"));
170
+ h.calls[0].resolve();
171
+ await flush();
172
+ h.failNextSend();
173
+ h.clock.advance(0);
174
+ assert.equal(h.messages.length, 0);
175
+ const message = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
176
+ assert.equal(message.details.tasks[0].id, task.id);
177
+ assert.ok(message.content.includes(task.log_path));
178
+ assert.doesNotMatch(message.content, /retained result/);
179
+ assert.equal((await h.tool.execute("inspect", { action: "output", id: task.id })).structuredContent.output, "retained result\n");
180
+ assert.equal(h.handlers.get("agent_before_settle")({ entries: [], outcome: "completed" }, h.ctx), undefined);
181
+ } finally { await h.close(); }
182
+ });
183
+
184
+ test("timeout and empty-result notifications contain status and paths, not captured output", async () => {
185
+ const h = harness("print", false);
186
+ try {
187
+ await h.handlers.get("session_start")({}, h.ctx);
188
+ h.setIdle(false);
189
+ await h.tool.execute("slow", { action: "start", command: "slow", timeout: 1 });
190
+ h.calls[0].onData(Buffer.from("partial before deadline\n"));
191
+ h.clock.advance(1000);
192
+ h.calls[0].reject(new Error("aborted"));
193
+ await flush();
194
+ const timedOut = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
195
+ assert.equal(timedOut.details.tasks[0].status, "timed_out");
196
+ assert.match(timedOut.content, /Runtime limit of 1 seconds reached/);
197
+ assert.doesNotMatch(timedOut.content, /partial before deadline/);
198
+ assert.ok(timedOut.content.includes(timedOut.details.tasks[0].log_path));
199
+ assert.equal((await h.tool.execute("read-slow", { action: "output", id: timedOut.details.tasks[0].id })).structuredContent.output, "partial before deadline\n");
200
+ await h.tool.execute("empty", { action: "start", command: "empty" });
201
+ h.calls[1].resolve();
202
+ await flush();
203
+ const empty = h.handlers.get("turn_end")({ entries: [], outcome: "completed" }, h.ctx).entries[0];
204
+ assert.ok(empty.content.includes(empty.details.tasks[0].log_path));
205
+ assert.doesNotMatch(empty.content, /\(no output\)/);
206
+ assert.equal((await h.tool.execute("read-empty", { action: "output", id: empty.details.tasks[0].id })).structuredContent.output, "");
207
+ assert.doesNotMatch(empty.content, /For logs:|For more logs:/);
208
+ } finally { await h.close(); }
209
+ });
210
+
74
211
  test("a completion during manual compaction wakes after idle without another agent boundary", async () => {
75
212
  const h = harness("print", false);
76
213
  try {
@@ -326,7 +463,8 @@ test("registration is compact, does not inject prompt rules or start session res
326
463
  try {
327
464
  assert.equal(h.tool.name, "background_task");
328
465
  assert.equal(h.tool.exposure, "model-only");
329
- assert.match(h.tool.description, /return task IDs immediately/);
466
+ assert.match(h.tool.description, /up to two concurrent background shell tasks/);
467
+ assert.match(h.tool.parameters.properties.action.description, /start returns a task ID immediately/);
330
468
  assert.ok(h.tool.description.length < 500);
331
469
  assert.equal(h.tool.promptGuidelines, undefined);
332
470
  assert.ok(h.tool.outputSchema);
@@ -338,20 +476,28 @@ test("registration is compact, does not inject prompt rules or start session res
338
476
  } finally { await h.close(); }
339
477
  });
340
478
 
341
- test("start provides non-blocking next steps in both model text and structured results", async () => {
479
+ test("start keeps only task-specific guidance while the declaration describes lifecycle and running queries", async () => {
342
480
  const h = harness();
343
481
  try {
344
482
  await h.handlers.get("session_start")({}, h.ctx);
345
483
  const started = await h.tool.execute("start", { action: "start", command: "sleep 60" });
346
- const { task, guidance } = started.structuredContent;
484
+ const { task } = started.structuredContent;
485
+ const notice = "Completion is reported automatically. Continue other work or end the turn; do not repeatedly query just to wait for completion.";
347
486
  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);
487
+ assert.ok(started.content[0].text.includes(notice));
488
+ assert.ok(!started.content[0].text.includes(task.log_path));
489
+ assert.ok(!started.content[0].text.includes("session changes"));
490
+ assert.ok(!h.tool.description.includes(notice), "declaration must not duplicate the whole start reminder");
491
+ assert.match(h.tool.description, /automatic completion notifications/);
492
+ assert.match(h.tool.description, /session changes, reload, or exit/);
493
+ assert.match(h.tool.parameters.properties.action.description, /list and output also work while tasks are running/);
494
+ assert.equal(started.structuredContent.guidance, undefined);
495
+ assert.equal(h.tool.outputSchema.properties.guidance, undefined);
353
496
  const list = await h.tool.execute("list", { action: "list" });
354
497
  const output = await h.tool.execute("output", { action: "output", id: task.id });
498
+ assert.equal(list.structuredContent.tasks[0].status, "running", "status inspection does not require a completion notification");
499
+ assert.equal(output.structuredContent.task.status, "running", "log inspection is allowed before completion");
500
+ assert.equal(h.messages.length, 0, "running-task inspection does not wait for or create a notification");
355
501
  assert.equal(list.structuredContent.guidance, undefined);
356
502
  assert.equal(output.structuredContent.guidance, undefined);
357
503
  h.calls[0].resolve();
@@ -379,12 +525,12 @@ test("tools, commands, widget and idle notifications share the same session jobs
379
525
  for (const width of [1, 8, 40, 80]) assert.ok(widget.render(width).every((line) => visibleWidth(line) <= width));
380
526
  assert.ok(h.widgets.has("scheduler") && h.widgets.has("herdr-subagents"));
381
527
 
382
- h.calls[0].onData(Buffer.from("logs only on explicit read\n"));
528
+ h.calls[0].onData(Buffer.from("captured build output\n"));
383
529
  await h.commands.get("bg").handler(`output ${job.id}`, h.ctx);
384
- assert.match(h.messages.at(-1).message.content, /logs only on explicit read/);
530
+ assert.match(h.messages.at(-1).message.content, /captured build output/);
385
531
  assert.equal(h.messages.at(-1).options.triggerTurn, false);
386
532
  const output = await h.tool.execute("output", { action: "output", id: job.id });
387
- assert.equal(output.structuredContent.output, "logs only on explicit read\n");
533
+ assert.equal(output.structuredContent.output, "captured build output\n");
388
534
  assert.equal(output.details.output, undefined);
389
535
 
390
536
  h.calls[0].resolve(7);
@@ -394,7 +540,9 @@ test("tools, commands, widget and idle notifications share the same session jobs
394
540
  assert.equal(completed.length, 1);
395
541
  assert.deepEqual(completed[0].options, { triggerTurn: true, deliverAs: "steer" });
396
542
  assert.match(completed[0].message.content, /failed.*exit 7/);
397
- assert.ok(!completed[0].message.content.includes("logs only"));
543
+ assert.doesNotMatch(completed[0].message.content, /captured build output/);
544
+ assert.ok(!completed[0].message.content.includes(`background_task({action:"output",id:"${job.id}"})`), "complete small output needs no follow-up query");
545
+ assert.ok(completed[0].message.content.includes(job.log_path), "completion points at the log for progressive inspection");
398
546
  assert.match(h.widgets.get("background-tasks").render(140).join("\n"), /failed/);
399
547
  h.clock.advance(4999);
400
548
  assert.ok(h.widgets.has("background-tasks"));
@@ -60,7 +60,7 @@ export default function (pi: ExtensionAPI) {
60
60
  const wave = requests - 1;
61
61
  if (requests === 2) message.content.push({ type: "toolCall", id: "wait-first-wave", name: "synchronous_subagent_fixture", arguments: { wave: 0 } });
62
62
  for (let i = 0; i < 2; i++) message.content.push({ type: "toolCall", id: `start-${wave}-${i}`, name: "background_task", arguments: {
63
- action: "start", command: `while [ ! -f release-${wave} ]; do sleep 0.01; done; printf 'wave ${wave}\\n'; touch exited-${wave}-${i}; exit 7`, description: `wave ${wave} job ${i}`, timeout: 10,
63
+ action: "start", command: `while [ ! -f release-${wave} ]; do sleep 0.01; done; printf 'RESULT wave ${wave} job ${i}\\n'; touch exited-${wave}-${i}; exit 7`, description: `wave ${wave} job ${i}`, timeout: 10,
64
64
  } });
65
65
  if (requests === 2) {
66
66
  if (process.env.BG_NOTIFICATION_MODE === "codemode") message.content.push({ type: "toolCall", id: "wait-second-wave", name: "codemode", arguments: { code: "text(await tools.synchronous_subagent_fixture({ wave: 1 }));" } });
@@ -19,6 +19,7 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
19
19
  const release = join(directory, "release");
20
20
  const exited = join(directory, "exited");
21
21
  const requests = [], settlements = [], errors = [];
22
+ const warmupRequests = timing === "after active compaction" ? 1 : 0;
22
23
  let session, task, output, holding = false, summaries = 0;
23
24
  const waitFor = async (check, label) => {
24
25
  for (let i = 0; i < 1000; i++) {
@@ -43,11 +44,14 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
43
44
  if (compacting) {
44
45
  message.stopReason = "stop";
45
46
  message.content.push({ type: "text", text: "## Goal\nKeep the interrupted agent stopped. A shell job remains owned by this session." });
46
- } else if (requests.length === 1) message.content.push({ type: "toolCall", id: "start-job", name: "background_task", arguments: {
47
- action: "start", command: "while [ ! -f release ]; do sleep 0.01; done; printf 'late shell result\\n'; printf done > exited; exit 7", timeout: 10,
47
+ } else if (requests.length <= warmupRequests) {
48
+ message.stopReason = "stop";
49
+ message.content.push({ type: "text", text: "WARMUP_ACK" });
50
+ } else if (requests.length === warmupRequests + 1) message.content.push({ type: "toolCall", id: "start-job", name: "background_task", arguments: {
51
+ action: "start", command: "while [ ! -f release ]; do sleep 0.01; done; printf 'late shell result\\n'; printf done > exited; exit 7", description: "Interrupted shell fixture", timeout: 10,
48
52
  } });
49
- else if (requests.length === 2) message.content.push({ type: "toolCall", id: "hold-turn", name: "interrupt_fixture", arguments: {} });
50
- else if (requests.length === 3) message.content.push({ type: "toolCall", id: "read-result", name: "background_task", arguments: { action: "output", id: task.id } });
53
+ else if (requests.length === warmupRequests + 2) message.content.push({ type: "toolCall", id: "hold-turn", name: "interrupt_fixture", arguments: {} });
54
+ else if (requests.length === warmupRequests + 3) message.content.push({ type: "toolCall", id: "read-result", name: "background_task", arguments: { action: "output", id: task.id } });
51
55
  else {
52
56
  message.stopReason = "stop";
53
57
  message.content.push({ type: "text", text: "RESUMED_RESULT_ACK" });
@@ -87,6 +91,9 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
87
91
  else if (event.result.structuredContent.action === "output") output = event.result.structuredContent;
88
92
  });
89
93
  await session.bindExtensions({});
94
+ // Native compaction needs an earlier completed turn; do not depend
95
+ // on how verbose the background tool's start result happens to be.
96
+ if (warmupRequests) await session.prompt("Warmup history to summarize. ".repeat(200));
90
97
  const prompting = session.prompt("Start a job and hold the agent so the user can interrupt. " + "Prior history to compact. ".repeat(200));
91
98
  await waitFor(() => holding, "the real blocking tool");
92
99
  assert.equal(task.status, "running");
@@ -102,32 +109,34 @@ for (const timing of ["before interrupt", "after interrupt", "after active compa
102
109
  } else await session.abort();
103
110
  await prompting;
104
111
  const interruptedAt = Date.now();
105
- assert.deepEqual(settlements, [true], "native settlement must confirm the user interrupt");
112
+ assert.deepEqual(settlements, [...Array(warmupRequests).fill(false), true], "native settlement must confirm the user interrupt");
106
113
  assert.equal(session.isIdle, true);
107
114
  writeFileSync(release, "finish after user interruption");
108
115
  await waitFor(() => existsSync(exited), "the background shell surviving the interrupt");
109
116
  await delay(1250);
110
- assert.equal(requests.length, 2, "late completion must not start a model request");
117
+ assert.equal(requests.length, warmupRequests + 2, "late completion must not start a model request");
111
118
  assert.match(readFileSync(task.log_path, "utf8"), /late shell result/);
112
119
  assert.equal(session.isIdle, true);
113
120
  await session.prompt("Continue and inspect the completed job.");
114
- assert.equal(requests.length, 4);
115
- const resumedContext = JSON.stringify(requests[2]);
121
+ assert.equal(requests.length, warmupRequests + 4);
122
+ const resumedContext = JSON.stringify(requests[warmupRequests + 2]);
116
123
  assert.equal((resumedContext.match(/\[Background task finished\]/g) ?? []).length, 1, "retained completion enters context before the resumed model request");
117
124
  assert.ok(resumedContext.includes(task.id));
118
125
  assert.equal(output.task.exit_code, 7);
119
126
  assert.equal(output.output, "late shell result\n");
120
127
  await delay(50);
121
- assert.equal(requests.length, 4, "consumed completion must not trigger another turn");
128
+ assert.equal(requests.length, warmupRequests + 4, "consumed completion must not trigger another turn");
122
129
  const notifications = session.sessionManager.getBranch().filter((entry) => entry.type === "custom_message" && entry.customType === "background-task-finished");
123
130
  assert.equal(notifications.length, 1);
131
+ assert.doesNotMatch(notifications[0].content, /late shell result/);
132
+ assert.ok(notifications[0].content.includes(task.log_path));
124
133
  assert.equal(notifications[0].details.tasks[0].id, task.id);
125
134
  assert.equal(notifications[0].details.tasks[0].status, "failed");
126
135
  if (timing === "before interrupt") assert.ok(notifications[0].details.tasks[0].ended_at <= interruptRequestedAt);
127
136
  else assert.ok(notifications[0].details.tasks[0].ended_at >= interruptedAt);
128
137
  assert.equal(session.getLastAssistantText(), "RESUMED_RESULT_ACK");
129
138
  assert.deepEqual(errors, []);
130
- t.diagnostic(JSON.stringify({ timing, requestsBeforeResume: 2, requestsAfterResume: 4, pendingDeliveredOnce: true, lateResultRecovered: true }));
139
+ t.diagnostic(JSON.stringify({ timing, warmupRequests, requestsBeforeResume: warmupRequests + 2, requestsAfterResume: warmupRequests + 4, pendingDeliveredOnce: true, lateResultRecovered: true }));
131
140
  } finally {
132
141
  if (session) {
133
142
  await session.abort();
@@ -7,7 +7,7 @@ import { fileURLToPath } from "node:url";
7
7
  import { test } from "node:test";
8
8
  import { piBinary } from "./runtime.mjs";
9
9
 
10
- test("native model receives concise start guidance without Codemode instructions", () => {
10
+ test("native model receives distinct declaration and start guidance without Codemode instructions", () => {
11
11
  const directory = mkdtempSync(join(tmpdir(), "pi-bg-guidance-"));
12
12
  try {
13
13
  const events = join(directory, "events.jsonl");
@@ -22,13 +22,16 @@ test("native model receives concise start guidance without Codemode instructions
22
22
  const records = readFileSync(events, "utf8").trim().split("\n").map((line) => JSON.parse(line));
23
23
  const started = records.find((entry) => entry.event === "tool_end" && entry.name === "background_task");
24
24
  assert.equal(started.isError, false);
25
- const guidance = started.result.structuredContent.guidance;
26
- assert.equal(guidance, "Notifies automatically on completion. Do not sleep or poll; continue other work or end the turn.");
25
+ const notice = "Completion is reported automatically. Continue other work or end the turn; do not repeatedly query just to wait for completion.";
26
+ assert.equal(started.result.structuredContent.guidance, undefined);
27
27
  assert.equal(records.some((entry) => entry.event === "tool_end" && entry.name === "codemode"), false);
28
28
  const requests = records.filter((entry) => entry.event === "request");
29
- assert.ok(requests[0].backgroundDescription.includes(guidance));
29
+ assert.match(requests[0].backgroundDescription, /automatic completion notifications/);
30
+ assert.match(requests[0].backgroundDescription, /session changes, reload, or exit/);
31
+ assert.ok(!requests[0].backgroundDescription.includes(notice));
30
32
  assert.ok(!requests[0].backgroundDescription.includes("Codemode:"));
31
- assert.ok(requests[1].text.includes(guidance), "the next model request sees the startup guidance");
33
+ assert.ok(requests[1].text.includes(notice), "the next model request sees the task-specific reminder");
34
+ assert.ok(!started.result.content[0].text.includes(started.result.structuredContent.task.log_path));
32
35
  } finally { rmSync(directory, { recursive: true, force: true }); }
33
36
  });
34
37
 
@@ -89,6 +92,11 @@ for (const mode of ["codemode", "direct"]) {
89
92
  assert.equal(tasks.length, 4 - reads);
90
93
  assert.ok(tasks.every((task) => task.status === "failed" && task.exit_code === 7));
91
94
  assert.ok(tasks.every((task) => !returned.consumed.includes(task.id)));
95
+ for (const task of tasks) assert.ok(message.content.includes(task.log_path), "completion provides the captured output location");
96
+ assert.doesNotMatch(message.content, /RESULT wave/, "command output is not injected automatically");
97
+ assert.match(message.content, /Inspect logs progressively as needed/);
98
+ for (const task of returned.tasks.filter((task) => returned.consumed.includes(task.id))) assert.ok(!message.content.includes(`RESULT ${task.description}`), "consumed output is not delivered twice");
99
+ assert.ok(Buffer.byteLength(message.content) <= 16384);
92
100
  assert.deepEqual([...returned.consumed, ...tasks.map((task) => task.id)].sort(), returned.tasks.map((task) => task.id).sort());
93
101
  const toolEnd = transcript.findLastIndex((entry) => entry.type === "tool_execution_end" && ["synchronous_subagent_fixture", "codemode"].includes(entry.toolName));
94
102
  assert.ok(toolEnd >= 0 && transcript.indexOf(notifications[0]) > toolEnd, "the notification cannot interrupt the synchronous tool");
@@ -99,7 +107,10 @@ for (const mode of ["codemode", "direct"]) {
99
107
  assert.equal((nextContext.match(/\[Background task finished\]/g) ?? []).length, 1);
100
108
  assert.doesNotMatch(nextContext, /FINAL_REPORT/, "completion is delivered before, not after, the final report");
101
109
  const contextText = requests.at(-1).messages.flatMap((message) => typeof message.content === "string" ? [message.content] : (message.content ?? []).filter((block) => block.type === "text").map((block) => block.text)).join("\n");
102
- for (const task of returned.tasks.filter((task) => !returned.consumed.includes(task.id))) assert.ok(contextText.includes(task.id));
110
+ for (const task of returned.tasks.filter((task) => !returned.consumed.includes(task.id))) {
111
+ assert.ok(contextText.includes(task.id));
112
+ assert.ok(contextText.includes(task.log_path), "the next model request can locate output for on-demand inspection");
113
+ }
103
114
  } finally { rmSync(directory, { recursive: true, force: true }); }
104
115
  });
105
116
  }
package/tests/output.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
- import { writeFileSync } from "node:fs";
3
+ import { readFileSync, writeFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
- import { createBashTool } from "@earendil-works/pi-coding-agent";
5
+ import { createBashTool, truncateTail } from "@earendil-works/pi-coding-agent";
6
6
  import { fixture, flush } from "./helpers.mjs";
7
7
 
8
8
  const cases = [
@@ -17,8 +17,27 @@ const cases = [
17
17
  ["utf8-long-line", Buffer.from("中文🙂".repeat(130000))],
18
18
  ["invalid-utf8", Buffer.from([65, 0xf0, 0x9f])],
19
19
  ];
20
+
21
+ test("output exposes one bounded tail in both views while the full log remains on disk", async () => {
22
+ const f = fixture();
23
+ try {
24
+ const job = f.tasks.start({ command: "fixture" }, f.root);
25
+ const data = Array.from({ length: 110 }, (_, i) => `line-${i}`).join("\n");
26
+ f.calls[0].onData(Buffer.from(data));
27
+ f.calls[0].resolve();
28
+ await flush();
29
+ const result = f.tasks.output(job.id);
30
+ assert.equal(result.output, Array.from({ length: 100 }, (_, i) => `line-${i + 10}`).join("\n"));
31
+ assert.equal(result.output, result.truncation.content);
32
+ assert.ok(result.text.startsWith(result.output));
33
+ assert.equal(result.truncated, true);
34
+ assert.equal(result.truncation.totalLines, 110);
35
+ assert.equal(result.bytes, Buffer.byteLength(data));
36
+ } finally { await f.close(); }
37
+ });
38
+
20
39
  for (const [name, data] of cases) {
21
- test(`output matches native bash model/structured views: ${name}`, async () => {
40
+ test(`bounded output compared with native bash model/structured views: ${name}`, async () => {
22
41
  const f = fixture();
23
42
  try {
24
43
  const path = join(f.root, "fixture.log");
@@ -31,12 +50,17 @@ for (const [name, data] of cases) {
31
50
  await flush();
32
51
  const actual = f.tasks.output(job.id);
33
52
  const normalize = (text) => text.replace(/Full output: [^\]]+/g, "Full output: <log>");
34
- assert.equal(normalize(actual.text), normalize(native.content[0].text));
35
- assert.equal(actual.output, native.structuredContent.output);
36
- assert.equal(actual.truncated, native.structuredContent.truncated);
53
+ const expected = truncateTail(native.structuredContent.output, { maxLines: 100, maxBytes: 8192 });
54
+ assert.equal(actual.output, expected.content);
55
+ assert.equal(actual.output, actual.truncation.content);
56
+ assert.equal(actual.truncated, native.structuredContent.truncated || expected.truncated);
57
+ if (!actual.truncated) assert.equal(normalize(actual.text), normalize(native.content[0].text));
58
+ else assert.match(actual.text, /Showing .*Full output:/);
59
+ if (name === "long-line-with-newline") assert.match(actual.text, /line is 146\.5KB/);
60
+ assert.deepEqual(readFileSync(actual.log_path), data);
37
61
  assert.equal(actual.capture_complete, true);
38
- assert.ok(Buffer.byteLength(actual.truncation.content) <= 51200);
39
- assert.ok(Buffer.byteLength(actual.output) < 1024 * 1024 + 100);
62
+ assert.ok(Buffer.byteLength(actual.truncation.content) <= 8192);
63
+ assert.ok(Buffer.byteLength(actual.output) <= 8192);
40
64
  } finally { await f.close(); }
41
65
  });
42
66
  }
@@ -90,7 +90,7 @@ test("native large output truncates display, then stops at the 32 MiB disk budge
90
90
  assert.equal(result.bytes, 32 * 1024 * 1024);
91
91
  assert.equal(result.capture_complete, false);
92
92
  assert.equal(result.truncated, true);
93
- assert.ok(result.truncation.outputBytes <= 51200);
94
- assert.ok(Buffer.byteLength(result.output) < 1024 * 1024 + 100);
93
+ assert.ok(result.truncation.outputBytes <= 8192);
94
+ assert.ok(Buffer.byteLength(result.output) <= 8192);
95
95
  } finally { await tasks.shutdown(); }
96
96
  });