pi-background-tasks 0.7.0 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PUBLISHING.md +7 -7
- package/README.md +11 -7
- package/TESTING.md +4 -4
- package/TEST_PLAN.md +7 -7
- package/extensions/fusion-child.ts +1 -0
- package/package.json +1 -1
- package/src/core/common.ts +60 -0
- package/src/core/fusion/artifacts.ts +13 -3
- package/src/core/fusion/orchestrator.ts +4 -2
- package/src/core/fusion/pi-child.ts +285 -201
- package/src/core/fusion/types.ts +2 -1
- package/src/core/registry.ts +1 -0
- package/src/extension.ts +31 -14
- package/src/fusion-child-extension.ts +100 -0
- package/src/fusion-extension.ts +29 -13
package/PUBLISHING.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Publishing pi-background-tasks
|
|
2
2
|
|
|
3
|
-
Release checklist for npm publishing and standalone git publishing.
|
|
3
|
+
Release checklist for npm publishing and standalone git publishing. The current release candidate is 0.7.2; version 0.7.0 introduced the Fusion public surfaces (`/fusion`, `/fusion-models`, `fusion_brainstorm`) in addition to the background-task surfaces. Do not advertise the GitHub install target until the standalone repository has the exact release commit and tag.
|
|
4
4
|
|
|
5
5
|
## Preconditions
|
|
6
6
|
|
|
@@ -34,8 +34,8 @@ npm publish --access public
|
|
|
34
34
|
Pi install smoke after publish:
|
|
35
35
|
|
|
36
36
|
```bash
|
|
37
|
-
PI_CODING_AGENT_DIR=$(mktemp -d) pi -e npm:pi-background-tasks@0.7.
|
|
38
|
-
pi install npm:pi-background-tasks@0.7.
|
|
37
|
+
PI_CODING_AGENT_DIR=$(mktemp -d) pi -e npm:pi-background-tasks@0.7.2 --offline --no-tools --no-session -p "/jobs"
|
|
38
|
+
pi install npm:pi-background-tasks@0.7.2
|
|
39
39
|
```
|
|
40
40
|
|
|
41
41
|
## Publish to git
|
|
@@ -48,15 +48,15 @@ git status --short --branch
|
|
|
48
48
|
git log --oneline -3
|
|
49
49
|
git remote -v
|
|
50
50
|
git push origin main
|
|
51
|
-
git tag v0.7.
|
|
52
|
-
git push origin v0.7.
|
|
51
|
+
git tag v0.7.2
|
|
52
|
+
git push origin v0.7.2
|
|
53
53
|
```
|
|
54
54
|
|
|
55
55
|
Pi install smoke after git tag, using an isolated Pi agent directory so no local checkout or user `~/.pi` state is involved:
|
|
56
56
|
|
|
57
57
|
```bash
|
|
58
|
-
PI_CODING_AGENT_DIR=$(mktemp -d) pi -e git:github.com/ismailsaleekh/pi-background-tasks@v0.7.
|
|
59
|
-
pi install git:github.com/ismailsaleekh/pi-background-tasks@v0.7.
|
|
58
|
+
PI_CODING_AGENT_DIR=$(mktemp -d) pi -e git:github.com/ismailsaleekh/pi-background-tasks@v0.7.2 --offline --no-tools --no-session -p "/jobs"
|
|
59
|
+
pi install git:github.com/ismailsaleekh/pi-background-tasks@v0.7.2
|
|
60
60
|
```
|
|
61
61
|
|
|
62
62
|
## pi.dev/packages
|
package/README.md
CHANGED
|
@@ -9,19 +9,19 @@ This package adds named, tracked background shell jobs with durable output files
|
|
|
9
9
|
From npm after publish:
|
|
10
10
|
|
|
11
11
|
```bash
|
|
12
|
-
pi install npm:pi-background-tasks@0.7.
|
|
12
|
+
pi install npm:pi-background-tasks@0.7.2
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
From git after pushing this package to its standalone repository and tagging:
|
|
16
16
|
|
|
17
17
|
```bash
|
|
18
|
-
pi install git:github.com/ismailsaleekh/pi-background-tasks@v0.7.
|
|
18
|
+
pi install git:github.com/ismailsaleekh/pi-background-tasks@v0.7.2
|
|
19
19
|
```
|
|
20
20
|
|
|
21
21
|
For project-local install:
|
|
22
22
|
|
|
23
23
|
```bash
|
|
24
|
-
pi install -l npm:pi-background-tasks@0.7.
|
|
24
|
+
pi install -l npm:pi-background-tasks@0.7.2
|
|
25
25
|
```
|
|
26
26
|
|
|
27
27
|
## Commands
|
|
@@ -33,7 +33,7 @@ pi install -l npm:pi-background-tasks@0.7.0
|
|
|
33
33
|
- `/tasks` or `/bg-tasks` — fallback command to open the task manager UI.
|
|
34
34
|
- `/bg-clear` — clear finished background-task footer notices.
|
|
35
35
|
- `/bg-update` — print update instructions when a newer published version exists (instruct-only; never self-installs).
|
|
36
|
-
- `/fusion <prompt>` — run three candidate child Pi
|
|
36
|
+
- `/fusion <prompt>` — run three candidate child Pi final-text calls, one blind evaluator, and one merger, then append the merged answer directly as a visible `fusion-result` custom message without asking the parent model to rewrite it. Running `/fusion` without arguments opens a multiline editor in UI-capable modes; cancelling the editor does not spawn children.
|
|
37
37
|
- `/fusion-models` — TUI-only five-slot global model selector (`Candidate 1`, `Candidate 2`, `Candidate 3`, `Evaluator`, `Merger`). It supports duplicate selections, `$current` defaults, slash-containing model ids, atomic saves to `fusion-models.json`, and rejects non-TUI modes immediately.
|
|
38
38
|
|
|
39
39
|
## Footer dock UX
|
|
@@ -97,14 +97,18 @@ The lookup runs at most once per session on `session_start`, is time-boxed, and
|
|
|
97
97
|
- `bg_kill` — stop a running task.
|
|
98
98
|
- `fusion_brainstorm({prompt})` — always-active tool that runs the Fusion workflow and returns the exact merged text as the tool result for the parent agent to consume, with standard nested usage attached when the host Pi supports tool-result usage. Its closed public schema has exactly one required parameter, `prompt`; extra keys are rejected. It has no eligibility, quota, routine, or justification gate. Tool context capture excludes the current assistant tool-call leaf when Pi is executing that `fusion_brainstorm` call, so the nested children do not see the in-progress tool call or sibling calls.
|
|
99
99
|
|
|
100
|
-
`bg_run` requires a concise `name` for the footer dock, the shell `command`, and required `isAgent: boolean`. Set `isAgent: true` only when the background task launches an LLM/agent process (for example `pi -p ...` or `pi --mode json ...`); set `isAgent: false` for scripts, tests, dev servers, sleeps, and ordinary shell commands. It defaults
|
|
100
|
+
`bg_run` requires a concise `name` for the footer dock, the shell `command`, and required `isAgent: boolean`. Set `isAgent: true` only when the background task launches an LLM/agent process (for example `pi -p ...` or `pi --mode json ...`); set `isAgent: false` for scripts, tests, dev servers, sleeps, and ordinary shell commands. It defaults both `notifyOnCompletion` and `triggerOnCompletion` to `true`. With those defaults, `bg_run` returns immediately, the agent continues only independent useful work or ends its current turn instead of sleeping or polling, and a durable `background-task-notification` for completed, failed, or killed state automatically starts a follow-up turn. The launch receipt states the effective notification/wake behavior explicitly. `bg_status` and `bg_logs` remain available for user-requested inspection, deliberately disabled completion delivery, concrete hang diagnosis, or reading output after the terminal event; they are not waiting primitives, and the terminal notification does not need status reconfirmation. Setting `triggerOnCompletion: false` keeps the notification but prevents it from starting an agent turn. Setting `notifyOnCompletion: false` suppresses both notification and wake-up even if `triggerOnCompletion` is true.
|
|
101
|
+
|
|
102
|
+
Tasks marked with `isAgent: true` that launch print/json child Pi agents through the normal shell command name are telemetry-wrapped; set `PI_BG_DISABLE_PI_TELEMETRY=1` only when raw Pi stdout is required. The task snapshot and metadata expose `isAgent`, `contextUsage` (latest reported child assistant turn), cumulative `tokenUsage` (`input`, `output`, `cacheRead`, `cacheWrite`, `totalTokens`), cumulative `toolUsage` (`total`, `failed`, `byName`), and `model` (the LLM identifier reported by the child assistant turns, preferring the fully-qualified `provider/model` form) when reported by the child task. User-launched `/bg` jobs are display-only by default unless `--agent` is provided; UI reruns preserve the original task's `isAgent` value.
|
|
101
103
|
|
|
102
104
|
`bg_run_pi_attested` is separate from `bg_run` and never accepts a shell command. It takes structured `provider`, `model`, `prompt`, optional literal extra Pi argv, and a relative `reportPath`; launches exactly one direct `pi --mode json` child; records raw Pi JSON events, separate stderr, exact argv/cwd, prompt/report hashes, observed Pi session/provider/model, and `ModelRegistry.isUsingOAuth` credential class. It forbids direct API-key/auth-file launch arguments and emits no partial attestation: failures remain ordinary failed tasks with no sidecar.
|
|
103
105
|
|
|
104
106
|
|
|
105
107
|
## Fusion workflow
|
|
106
108
|
|
|
107
|
-
Fusion runs direct child `pi --mode
|
|
109
|
+
Fusion runs direct child `pi --mode text` processes only; it never calls `pi-ai` completion APIs. Each child is launched with `--no-session`, `--no-tools`, `--no-extensions`, `--no-skills`, `--no-prompt-templates`, `--no-themes`, and `--no-context-files`, plus the resolved provider/model/thinking level and the package-owned private `extensions/fusion-child.ts` metadata extension. The prompt travels over stdin, not a shell or positional argument.
|
|
110
|
+
|
|
111
|
+
Pi text mode writes the final full answer exactly once instead of serializing cumulative reasoning/partial-message events on every token delta. The private child extension emits one compact, reasoning-free metadata record per finalized assistant message for provider/model, stop reason, usage, and response byte/hash validation. Fusion persists those compact records in `*.events.jsonl`; the complete answer remains in the stage response artifact. The 32 MiB child stdout cap therefore applies to one final response, not amplified JSON telemetry. Failed attempts keep the authoritative response artifact empty and, when any stdout was captured, persist it separately as an explicitly incomplete `*.response.partial.*` artifact.
|
|
108
112
|
|
|
109
113
|
Model configuration is global under the Pi agent directory:
|
|
110
114
|
|
|
@@ -174,7 +178,7 @@ The attestation sidecar uses `schema_version: "phase2.pi_task_attestation.v1"` a
|
|
|
174
178
|
## Safety model
|
|
175
179
|
|
|
176
180
|
- Commands are spawned and tracked with `child_process.spawn`; the package does not rely on shell `&`.
|
|
177
|
-
- Fusion inference is isolated to direct child `pi --mode
|
|
181
|
+
- Fusion inference is isolated to direct child `pi --mode text` invocations with tools/skills/session/context files disabled and only the package-owned compact metadata extension explicitly loaded; no direct completion API, API-key argument, or model fallback is used.
|
|
178
182
|
- Attested Pi tasks are a local, unsigned, same-user-writable attestation path for downstream gates. They bind source bytes and observed Pi/ModelRegistry facts; they are not cryptographic proof against a malicious local user, compromised Pi binary, or compromised provider.
|
|
179
183
|
- stdout/stderr are captured to task output files.
|
|
180
184
|
- Model-visible logs are bounded and point to full output files.
|
package/TESTING.md
CHANGED
|
@@ -77,22 +77,22 @@ npm run test:rpc
|
|
|
77
77
|
npm run test:agent-loop
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
-
The Fusion SDK/RPC/scripted-provider tests install a deterministic fake child `pi` in a temp `PATH` from `tests/helpers/fusion-fake-pi.ts`. Parent Pi remains the real SDK/RPC runtime; only direct child `pi --mode
|
|
80
|
+
The Fusion SDK/RPC/scripted-provider tests install a deterministic fake child `pi` in a temp `PATH` from `tests/helpers/fusion-fake-pi.ts`. Parent Pi remains the real SDK/RPC runtime; only direct child `pi --mode text` calls with the package-owned private compact metadata extension are intercepted. `PI_CODING_AGENT_DIR` is pointed at the temp agent directory so `fusion-models.json` is never read from the user's real global Pi directory. Fusion context coverage is intentionally text-transcript coverage: tests verify long text is not summarization-truncated and image-containing session entries are represented by `[Image omitted from fusion text transcript: <mime-type>]` markers without forwarding raw image bytes/base64 to child Pi prompts. The release-only `npm run test:compat` packs the package, installs exact supported Pi versions, runs `/jobs`, runs `/fusion` through the installed package entrypoint with the fake child Pi, verifies five child invocations, and verifies `/fusion-models` rejects non-TUI mode.
|
|
81
81
|
|
|
82
82
|
## Coverage summary
|
|
83
83
|
|
|
84
84
|
Implemented coverage includes:
|
|
85
85
|
|
|
86
|
-
- tools: `bg_run`, `bg_run_pi_attested`, `bg_status`, `bg_logs`, `bg_kill`, `fusion_brainstorm`, including required `isAgent` schema/runtime validation, attested direct Pi spawn validation, Fusion exact merged tool result delivery/progress/details/context exclusion, text-transcript image omission markers with raw image data excluded from child prompts, unknown/ambiguous IDs, completed-kill failure, legacy no-name preparation, head/tail truncation, and notification on/off behavior
|
|
86
|
+
- tools: `bg_run`, `bg_run_pi_attested`, `bg_status`, `bg_logs`, `bg_kill`, `fusion_brainstorm`, including required `isAgent` schema/runtime validation, the event-driven no-sleep/no-poll system-prompt contract, truthful launch receipts for all four notification/wake combinations, non-terminating `bg_run` compatibility, point-in-time status/log guidance, durable terminal-notification authority, attested direct Pi spawn validation, Fusion exact merged tool result delivery/progress/details/context exclusion, text-transcript image omission markers with raw image data excluded from child prompts, unknown/ambiguous IDs, completed-kill failure, legacy no-name preparation, head/tail truncation, and notification on/off behavior
|
|
87
87
|
- commands: `/bg`, `/jobs`, `/logs`, `/kill`, `/tasks`, `/bg-tasks`, `/bg-clear`, `/bg-update`, `/fusion`, `/fusion-models` discovery, happy paths, `/fusion` direct custom-message delivery, `/fusion` editor/cancel flow, `/fusion-models` TUI save and non-TUI rejection, `/bg --agent` parsing, finished-notice clearing, malformed `/bg`, unknown/ambiguous IDs, completed-task `/kill`, byte-limit normalization, and RPC no-hang fallback behavior
|
|
88
88
|
- update-available notice: semver parse/compare/precedence, `formatUpdateSegment`, npm/`package.json` payload narrowing, and injected-fetch success/404/throw/timeout (unit); localhost-registry footer segment (idle + appended to an active footer), `/bg-update` non-installing instructions, and opt-out/offline/already-current/registry-failure no-segment-and-no-throw paths (SDK); `/bg-update` discovery and offline instructions (RPC). The check is one-shot on `session_start`, time-boxed, offline-safe, gated by `PI_OFFLINE`/`PI_BG_DISABLE_UPDATE_CHECK`, and `PI_BG_REGISTRY_URL` overrides the registry endpoint
|
|
89
89
|
- shortcut/UI: component coverage for focused dock list/detail/key handling, detail output-tail scrolling (arrow/page scroll, follow-pause-on-scroll, `lines X–Y of N` position indicator, resume-follow-at-bottom, and no-scroll when output fits), empty/history/unread states, paging, close aliases, stop/stop-all/rerun/path actions, missing output files; SDK coverage for explicit `/bg-clear` finished-notice clearing, `/bg-clear` footer hinting, optional `Ctrl+Alt+C` fallback shortcut registration, and mixed failed/stopped/done/focused footer status; RPC coverage that `/bg-clear` works as a terminal-independent clear path; and PTY coverage for `/tasks`, `/bg-tasks`, real `Shift+Down`, arrows, page keys, detail/back/history/stop/stop-all/rerun/path/close, failed unread badges, and running/completed/failed/killed rerun paths
|
|
90
|
-
- runtime files: output and metadata files under `.pi/tasks/`, Fusion private `.pi/fusion/<session-id>-<pid>/<run-id>/` artifacts plus global `fusion-models.json`, persisted `isAgent` classification, task-owned context-window telemetry snapshots, cumulative background Pi-agent token usage, tool-use counts, agent model identifier (preferring the fully-qualified `provider/model` form), explicit `isAgent:true` telemetry wrapping for background `pi` agents, `isAgent:false` non-wrapping for scripts, attested Pi flat siblings (`.pi-events.jsonl`, `.stderr`, `.pi-telemetry-wrapper.cjs`, `.attestation.json`), real child `pi --mode json` tool-event parsing, split/large telemetry ingestion, metadata after completion/failure, Fusion manifest aggregate usage equal to the sum of successful plus observed failed/cancelled child attempt usage, local tarball install contents
|
|
90
|
+
- runtime files: output and metadata files under `.pi/tasks/`, Fusion private `.pi/fusion/<session-id>-<pid>/<run-id>/` artifacts plus global `fusion-models.json`, persisted `isAgent` classification, task-owned context-window telemetry snapshots, cumulative background Pi-agent token usage, tool-use counts, agent model identifier (preferring the fully-qualified `provider/model` form), explicit `isAgent:true` telemetry wrapping for background `pi` agents, `isAgent:false` non-wrapping for scripts, attested Pi flat siblings (`.pi-events.jsonl`, `.stderr`, `.pi-telemetry-wrapper.cjs`, `.attestation.json`), real child `pi --mode json` tool-event parsing for background-agent telemetry, split/large telemetry ingestion, metadata after completion/failure, Fusion compact final-only child metadata and explicitly marked partial-response artifacts, Fusion manifest aggregate usage equal to the sum of successful plus observed failed/cancelled child attempt usage, local tarball install contents
|
|
91
91
|
- extension EventBus API: unit coverage for `pi-background-tasks:request:v1`/`response:v1` closed-frame validation, exact capability handshake, malformed payload rejection, unknown keys, unknown operations, duplicate request IDs, missing `session_start`, shutdown refusal, unsubscribe, strict terminal frame shape, and response-barrier ordering; registry coverage for exactly-one terminal publication after durable metadata plus loud/retriable terminal delivery failure; SDK coverage with a shared real `createEventBus()` loading the actual extension, starting `printf api-ok`, reading bounded logs, observing exactly one terminal event after the run response, and killing a real sleep task without model/provider calls
|
|
92
92
|
- attested Pi producer: unit/SDK coverage for 128-bit attested task ids, exact direct argv/cwd, ModelRegistry OAuth observation without secrets, raw Pi session/message events, separate stderr, prompt/report/source hashes, authority start/finish commit/tree/clean checks, atomic metadata serialization, completion visibility only after the sidecar is durable, malformed event rejection, and no attestation sidecar for ordinary tasks
|
|
93
93
|
- agent activity transcript: pure `parseAgentActivity`/`formatAgentActivityLine` coverage (assistant text, reasoning, tool start with arg summary, silent successful tool end, `✗ tool failed` errors, truncation, invalid/non-activity narrowing); registry-unit coverage that wrapped-agent stdout is reconstructed across split chunks into the human-readable transcript while telemetry/activity control JSON is stripped from the output file (telemetry fields still updated), stderr passes through, and the trailing partial line is flushed on finalize; SDK coverage that fake and real child `pi --mode json` runs surface `→ tool`/`✗ tool failed`/assistant text in `bg_logs` with no control JSON leaking into the visible output
|
|
94
94
|
- safety: kill, already-finished kill failure, timeout failure, spawn failure, low output-cap failure, multi-task shutdown cleanup, process-group kill fallback, Windows child-kill behavior, SIGKILL escalation, duplicate finalization/notification races, metadata/notification failure handling, and pruning
|
|
95
|
-
- agent loop: deterministic scripted-provider coverage for actual `bg_run`
|
|
95
|
+
- agent loop: deterministic scripted-provider coverage against `extensions/background-tasks.ts` for actual event-driven `bg_run` behavior. The provider observes the effective system prompt, public tool descriptions, and real launch receipt and deliberately emits the pre-fix `bg_status` poll if any contract layer is absent; the passing path proves one launch, no sleep/status/log polling, one durable terminal notification, and exactly one follow-up turn. It also covers notification-only `triggerOnCompletion:false`, `/bg` display-only behavior, `notifyOnCompletion:false`, failed-task notification error fields, and parent-model `fusion_brainstorm` tool use followed by normal parent response
|
|
96
96
|
- package: manifest, docs, `pi.extensions`, exported `src/core/extension-api.ts`, peer dependency/import parity, packed runtime files, tarball-install smoke, direct-completion import bans, test/helper/script/artifact exclusion, and isolated offline npm install environment for default package tests
|
|
97
97
|
|
|
98
98
|
## PTY notes
|
package/TEST_PLAN.md
CHANGED
|
@@ -45,18 +45,18 @@ This package follows:
|
|
|
45
45
|
| Show bounded logs | `/logs <id> [maxBytes]` | yes | | yes | | | | | Unit covers bounded reads; RPC verifies output/path. |
|
|
46
46
|
| Kill running task | `/kill <id>` | | yes | yes | | | | | SDK tool and RPC slash command. |
|
|
47
47
|
| Open task manager fallback | `/tasks`, `/bg-tasks` | | | discovery | yes | yes | | | Component covers dock; PTY covers `/tasks` and `/bg-tasks`. |
|
|
48
|
-
| Start background command from LLM tool | `bg_run` | yes | yes | | | | | yes | SDK
|
|
48
|
+
| Start background command from LLM tool | `bg_run` | yes | yes | | | | | yes | Unit derives all notification/wake modes from one typed helper. SDK exercises the registered tool's effective system prompt, descriptions, non-terminating behavior, and all four launch-receipt combinations. The scripted provider verifies a default launch yields without sleep/status/log polling before one terminal-event follow-up. |
|
|
49
49
|
| Attested direct Pi producer | `bg_run_pi_attested` | yes | yes | | | | type/schema | | Unit covers 128-bit ids, exact direct argv, raw events/stderr, provider/model/session capture from Pi JSON, OAuth observation via ModelRegistry, prompt/report/source hash laws, completion visibility only after durable sidecar creation, malformed-event rejection, and no sidecar for ordinary tasks. SDK runs a fake Pi CLI through the public tool and verifies one complete flat attestation. |
|
|
50
|
-
| Inspect task status | `bg_status` | | yes | | | | |
|
|
51
|
-
| Read task logs | `bg_logs` | yes | yes | | | | |
|
|
50
|
+
| Inspect task status | `bg_status` | | yes | | | | | yes | SDK uses exact IDs for deterministic lifecycle observations and verifies the model-facing contract calls status a point-in-time inspection rather than a wait primitive. Scripted-provider ordinary waiting makes zero status calls. |
|
|
51
|
+
| Read task logs | `bg_logs` | yes | yes | | | | | yes | SDK verifies bounded content and the model-facing no-wait-loop contract. Scripted-provider ordinary waiting makes zero log calls. |
|
|
52
52
|
| Stop task from LLM tool | `bg_kill` | | yes | | | | | | Covers running kill and already-finished loud failure. |
|
|
53
|
-
| Fusion command direct result | `/fusion`, `fusion-result` custom message | yes | yes | yes | | yes | yes | | Core unit covers deterministic full text-transcript context construction, explicit image omission markers without raw image data, direct child argv/stdin/
|
|
53
|
+
| Fusion command direct result | `/fusion`, `fusion-result` custom message | yes | yes | yes | | yes | yes | | Core unit covers deterministic full text-transcript context construction, explicit image omission markers without raw image data, direct final-text child argv/stdin/compact-metadata parsing, exact multi-block answer reconstruction, artifacts, pre-abort handling, and orchestration. SDK runs real `/fusion` against a fake child `pi`, verifies exactly five child text-mode invocations, hidden prompt persistence, visible exact merged custom message, no parent assistant rewrite, renderer output, progress/status behavior, no-argument editor flow, editor cancellation, and malformed config causing zero children. RPC verifies command discovery, `/fusion <prompt>` with U+2028/U+2029 content, custom-message result emission, no parent `agent_start`, no-argument editor protocol, malformed config/child failure visibility, and child isolation flags. PTY verifies `/fusion` renders the exact merged answer directly in a real TUI. Compatibility smoke runs `/fusion` through every supported Pi version with the installed package entrypoint. |
|
|
54
54
|
| Fusion tool result | `fusion_brainstorm({prompt})` | yes | yes | | | | yes | yes | Tool is registered at load and re-added on `session_start`; no eligibility/quota/routine/justification gates are implemented. Unit/SDK cover closed one-parameter schema, extra-key rejection, active tool-call leaf exclusion before asynchronous config/model work, sibling-call exclusion, exact merged text delivery, image-containing session context serialized as text omission markers with raw image bytes/base64 absent from child stdin, standard nested usage when supported, progress updates, final details with usage/artifact/model snapshot, and invalid config zero-child failure. Scripted-provider coverage proves a deterministic parent model calls `fusion_brainstorm`, receives the exact merged tool result, exercises one evaluator schema-repair child after invalid first evaluator JSON, then responds normally. |
|
|
55
55
|
| Fusion model selector | `/fusion-models`, `fusion-models.json`, `FusionModelSelector` | yes | yes | yes | yes | yes | yes | | Unit covers strict config parsing, duplicates, slash-containing model IDs, stale model failures, `$current`, atomic save, inter-process lock/revision compare-and-swap, and deterministic concurrent-save conflict. Component covers all five slots, duplicate selection, searchable model list, stale display, reset/save/cancel, persistence errors, and width safety. SDK drives the real command in a synthetic TUI context without `ctx.mode` to cover old Pi compatibility and verifies duplicate `$current`/explicit model persistence; SDK also verifies headless no-UI rejection. RPC verifies non-TUI notification without hanging, PTY verifies the real selector opens in a TUI, and compatibility smoke verifies print-mode rejection for every supported Pi version. |
|
|
56
|
-
| Fusion child isolation/lifecycle | child `pi --mode
|
|
56
|
+
| Fusion child isolation/lifecycle | child `pi --mode text`, private compact metadata extension, shutdown cleanup, `.pi/fusion` artifacts | yes | yes | yes | | | yes | | BUG-180 unit coverage proves reasoning and full response text are absent from compact metadata, text mode emits the complete final answer once, exact text-block byte/hash reconstruction preserves the unmodified answer, malformed metadata/model/stop/hash/newline states fail loudly, and the unchanged 32 MiB cap now bounds one semantic response. Unit coverage also covers argv, package-owned extension resolution, env cleanup, stdin failure, stdout/stderr caps, timeout/abort/process-group kill, abort-during-spawn race, cleanup failure surfacing, no-close-after-SIGKILL failure, manifest transitions, compact event artifacts, explicit incomplete partial-response artifacts, failed-run usage persistence, aggregate usage, transient spawn retry, sibling cancellation, concurrent workflows, and orchestrator cancellation. SDK/RPC verify actual public consumers launch direct child `pi` with all isolation flags. Session shutdown tracks initializing and live Fusion runs through the extension active-run set. |
|
|
57
57
|
| Extension request/response service | `pi-background-tasks:request:v1` → `pi-background-tasks:response:v1` | yes | yes | | | | yes | | Unit covers closed-frame validation, capability handshake, unknown keys, unknown operation, duplicate request IDs, missing `session_start`, shutdown refusal, strict `run.payload`, strict malformed frames, and unsubscribe. SDK loads the real extension with a shared `createEventBus()`, starts `printf api-ok`, reads bounded logs, lists status, starts and kills a real sleep task, and checks malformed/unknown/duplicate controls without model/provider calls. Package tests assert `src/core/extension-api.ts` ships. |
|
|
58
58
|
| Terminal EventBus publication | `pi-background-tasks:terminal:v1` | yes | yes | | | | yes | | Registry unit proves exactly-one terminal snapshot after durable metadata and loud/retriable EventBus delivery failure; extension API unit proves one strict terminal frame correlated by task id after the run response for immediate, normal, failed, timeout, and killed tasks; SDK observes one terminal event for a completed task and one for a killed task through the real extension service. |
|
|
59
|
-
| Completion notification | custom message `background-task-notification` | yes | yes | | renderer via typecheck | | | yes |
|
|
59
|
+
| Completion notification | custom message `background-task-notification` | yes | yes | | renderer via typecheck | | | yes | BUG-181 unit/SDK coverage pins the durable-terminal guidance and truthful effective delivery receipts. Scripted provider loads the shipped extension, conditionally attempts the old `bg_status` poll when the real system prompt/descriptions/receipt are incomplete, and proves the fixed contract instead yields with exactly one `bg_run`, one terminal notification, and one default follow-up. Notification-only, notification-disabled, failed-task, and display-only `/bg` paths remain covered. |
|
|
60
60
|
| Footer status | `ctx.ui.setStatus` | | load path + clear command/shortcut + mixed states/focused label | | render semantics | yes | | | SDK verifies `/bg-clear` hint, failed/stopped/done combinations, running combinations, and focused label; PTY verifies Shift+Down dock path after footer-visible task. |
|
|
61
61
|
| Explicit agent classification | required `bg_run.isAgent`, `/bg --agent`, task metadata | yes | yes | | | | | yes | `isAgent:true` is required only for LLM/agent tasks and enables Pi-agent telemetry wrapping when the command invokes plain `pi`; `isAgent:false` is required for scripts/non-agents and prevents wrapping even if the command text looks like `pi -p ...`. |
|
|
62
62
|
| Per-task context usage | task row/detail + `bg_status`/metadata/notification snapshots | yes | yes | | yes | | | | SDK verifies task-owned telemetry is captured, explicitly marked background `pi` invocations are wrapped to emit telemetry, and parent `ctx.getContextUsage()` is not used; component verifies list/detail rendering plus `ctx —` placeholder. |
|
|
@@ -93,7 +93,7 @@ Lane A residual hardening is now covered by automated tests. No remaining harden
|
|
|
93
93
|
| Process lifecycle/races | Unit tests cover duplicate error/close finalization, output-cap races, duplicate-notification prevention, waiter resolution via stop paths, metadata failure logging, and notification failure reset. |
|
|
94
94
|
| Process-tree kill safety | Unit tests cover POSIX process-group kill, child fallback, both-fail loud errors, SIGTERM idempotency, SIGKILL escalation, and Windows child-kill/shell invocation. |
|
|
95
95
|
| Pruning | Unit tests cover oldest-finished pruning while preserving running tasks. |
|
|
96
|
-
| Completion follow-up turns | `test:agent-loop` registers a deterministic scripted provider and verifies `bg_run`
|
|
96
|
+
| Completion follow-up turns | `test:agent-loop` registers a deterministic scripted provider against the shipped extension path and verifies event-driven `bg_run` yielding with no sleep/status/log polling, exactly one default wakeup, notification-only `triggerOnCompletion:false`, `/bg` display-only behavior, `notifyOnCompletion:false`, and failed notification error fields. |
|
|
97
97
|
| PTY secondary keys | `test:pty` covers arrows, page keys, `a`/`K`, `R`, `c`, `/bg-tasks`, failed/unread badges, multiple-task ordering, and rerun paths for running/completed/failed/killed tasks. |
|
|
98
98
|
| Footer/status combinations | SDK tests cover failed/stopped/done/running combinations, explicit clear, and focused label. |
|
|
99
99
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { default } from '../src/fusion-child-extension.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-background-tasks",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.2",
|
|
4
4
|
"description": "Pi extension package for background shell tasks plus five-model fusion brainstorming: bg_run tools, /bg commands, /fusion, fusion_brainstorm, model selector UI, bounded logs, kill/timeout safety, and completion wakeups.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "ISC",
|
package/src/core/common.ts
CHANGED
|
@@ -102,6 +102,66 @@ export interface BgTask extends Omit<BgTaskSnapshot, 'name'> {
|
|
|
102
102
|
waiters: Array<() => void>;
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
+
export type CompletionDeliveryMode =
|
|
106
|
+
| 'notification-and-wake'
|
|
107
|
+
| 'notification-only'
|
|
108
|
+
| 'manual-monitoring';
|
|
109
|
+
|
|
110
|
+
export interface CompletionDeliveryGuidance {
|
|
111
|
+
readonly mode: CompletionDeliveryMode;
|
|
112
|
+
readonly notificationEnabled: boolean;
|
|
113
|
+
readonly automaticWakeEnabled: boolean;
|
|
114
|
+
readonly text: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Describe the actual parent-agent completion path for one bg_run launch.
|
|
119
|
+
* A wake request cannot take effect without the notification that carries it.
|
|
120
|
+
*/
|
|
121
|
+
export function deriveCompletionDeliveryGuidance(
|
|
122
|
+
notifyOnCompletion: boolean,
|
|
123
|
+
triggerOnCompletion: boolean,
|
|
124
|
+
): CompletionDeliveryGuidance {
|
|
125
|
+
if (notifyOnCompletion && triggerOnCompletion) {
|
|
126
|
+
return {
|
|
127
|
+
mode: 'notification-and-wake',
|
|
128
|
+
notificationEnabled: true,
|
|
129
|
+
automaticWakeEnabled: true,
|
|
130
|
+
text: [
|
|
131
|
+
'Terminal notification: enabled.',
|
|
132
|
+
'Automatic follow-up turn: enabled.',
|
|
133
|
+
'Next action: do not poll or sleep merely to wait; continue only independent useful work, otherwise end this turn and wait for <background-task-notification>.',
|
|
134
|
+
].join('\n'),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (notifyOnCompletion) {
|
|
139
|
+
return {
|
|
140
|
+
mode: 'notification-only',
|
|
141
|
+
notificationEnabled: true,
|
|
142
|
+
automaticWakeEnabled: false,
|
|
143
|
+
text: [
|
|
144
|
+
'Terminal notification: enabled.',
|
|
145
|
+
'Automatic follow-up turn: disabled. The terminal notification will be delivered, but it will not start an agent turn.',
|
|
146
|
+
'Next action: automatic wake-up was explicitly disabled; use bg_status/bg_logs only when deliberate monitoring is required, without tight polling.',
|
|
147
|
+
].join('\n'),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return {
|
|
152
|
+
mode: 'manual-monitoring',
|
|
153
|
+
notificationEnabled: false,
|
|
154
|
+
automaticWakeEnabled: false,
|
|
155
|
+
text: [
|
|
156
|
+
'Terminal notification: disabled.',
|
|
157
|
+
triggerOnCompletion
|
|
158
|
+
? 'Automatic follow-up turn: disabled because terminal notifications are disabled. triggerOnCompletion has no effect while notifyOnCompletion is false.'
|
|
159
|
+
: 'Automatic follow-up turn: disabled.',
|
|
160
|
+
'Next action: completion delivery was explicitly disabled; use bg_status/bg_logs only for deliberate manual monitoring, without tight polling.',
|
|
161
|
+
].join('\n'),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
105
165
|
export interface BgRunDetails {
|
|
106
166
|
task: BgTaskSnapshot;
|
|
107
167
|
}
|
|
@@ -67,7 +67,8 @@ export interface RecordFusionFailedAttemptInput {
|
|
|
67
67
|
slot?: 1 | 2 | 3;
|
|
68
68
|
attempt: number;
|
|
69
69
|
prompt: string;
|
|
70
|
-
|
|
70
|
+
events: Buffer;
|
|
71
|
+
partialResponse: Buffer;
|
|
71
72
|
stderr: Buffer;
|
|
72
73
|
error: string;
|
|
73
74
|
status: 'failed' | 'cancelled';
|
|
@@ -353,7 +354,7 @@ export class FusionArtifactStore {
|
|
|
353
354
|
async recordChildAttempt(input: RecordFusionChildAttemptInput): Promise<void> {
|
|
354
355
|
const prefix = attemptPrefix(input.result.stage, input.result.slot, input.result.attempt);
|
|
355
356
|
const promptRef = await this.writeArtifact(`${prefix}.prompt.txt`, input.prompt);
|
|
356
|
-
const eventsRef = await this.writeArtifact(`${prefix}.events.jsonl`, input.result.
|
|
357
|
+
const eventsRef = await this.writeArtifact(`${prefix}.events.jsonl`, input.result.events);
|
|
357
358
|
const stderrRef = await this.writeArtifact(`${prefix}.stderr.txt`, input.result.stderr);
|
|
358
359
|
const responseRef = await this.writeArtifact(
|
|
359
360
|
responseName(prefix, input.responseKind),
|
|
@@ -381,9 +382,16 @@ export class FusionArtifactStore {
|
|
|
381
382
|
async recordFailedAttempt(input: RecordFusionFailedAttemptInput): Promise<void> {
|
|
382
383
|
const prefix = attemptPrefix(input.stage, input.slot, input.attempt);
|
|
383
384
|
const promptRef = await this.writeArtifact(`${prefix}.prompt.txt`, input.prompt);
|
|
384
|
-
const eventsRef = await this.writeArtifact(`${prefix}.events.jsonl`, input.
|
|
385
|
+
const eventsRef = await this.writeArtifact(`${prefix}.events.jsonl`, input.events);
|
|
385
386
|
const stderrRef = await this.writeArtifact(`${prefix}.stderr.txt`, input.stderr);
|
|
386
387
|
const responseRef = await this.writeArtifact(responseName(prefix, input.responseKind), '');
|
|
388
|
+
const partialResponseRef =
|
|
389
|
+
input.partialResponse.length === 0
|
|
390
|
+
? undefined
|
|
391
|
+
: await this.writeArtifact(
|
|
392
|
+
`${prefix}.response.partial.${input.responseKind}`,
|
|
393
|
+
input.partialResponse,
|
|
394
|
+
);
|
|
387
395
|
await this.updateManifest((manifest) => {
|
|
388
396
|
const record: FusionAttemptArtifactRecord = {
|
|
389
397
|
stage: input.stage,
|
|
@@ -395,6 +403,8 @@ export class FusionArtifactStore {
|
|
|
395
403
|
response_path: responseRef.path,
|
|
396
404
|
error: input.error,
|
|
397
405
|
};
|
|
406
|
+
if (partialResponseRef !== undefined)
|
|
407
|
+
record.partial_response_path = partialResponseRef.path;
|
|
398
408
|
if (input.provider !== undefined) record.provider = input.provider;
|
|
399
409
|
if (input.model !== undefined) record.model = input.model;
|
|
400
410
|
if (input.qualifiedId !== undefined) record.qualifiedId = input.qualifiedId;
|
|
@@ -143,7 +143,8 @@ function recordFailureInput(
|
|
|
143
143
|
stage,
|
|
144
144
|
attempt,
|
|
145
145
|
prompt,
|
|
146
|
-
|
|
146
|
+
events: error.events,
|
|
147
|
+
partialResponse: error.response,
|
|
147
148
|
stderr: error.stderr,
|
|
148
149
|
error: error.message,
|
|
149
150
|
status: error.code === 'child_cancelled' ? 'cancelled' : 'failed',
|
|
@@ -160,7 +161,8 @@ function recordFailureInput(
|
|
|
160
161
|
stage,
|
|
161
162
|
attempt,
|
|
162
163
|
prompt,
|
|
163
|
-
|
|
164
|
+
events: Buffer.alloc(0),
|
|
165
|
+
partialResponse: Buffer.alloc(0),
|
|
164
166
|
stderr: Buffer.alloc(0),
|
|
165
167
|
error: errorText(error),
|
|
166
168
|
status:
|