pi-task-dispatcher 2.0.0 → 3.0.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/README.md CHANGED
@@ -1,124 +1,192 @@
1
1
  # pi-task-dispatcher
2
2
 
3
- Delegate bounded tasks from a Pi session to dedicated mechanical and engineering worker models while the selected main model remains in control.
3
+ Supervised mechanical and engineering delegations for Pi.
4
4
 
5
- ## Features
6
-
7
- - **Two focused worker roles:** route precise execution work to a mechanic model and broader implementation work to an engineer model.
8
- - **Least-privilege delegation:** every call supplies an exact tool allowlist selected from tools active for the main agent. Workers cannot invoke the delegation tools recursively.
9
- - **Live progress:** streamed worker text, tool activity, and an elapsed-time heartbeat keep long-running tasks visible.
10
- - **Recoverable interruption:** approaching time and turn limits request a worker-authored checkpoint. A hard timeout returns a synthetic fallback checkpoint.
11
- - **Explicit continuation:** a checkpoint never starts another worker automatically. The main agent reviews current state and decides what happens next.
12
-
13
- ## Worker tools
14
-
15
- The package adds two model-only tools to Pi:
16
-
17
- | Tool | Intended use |
18
- | --- | --- |
19
- | `delegate_mechanical` | Bounded multi-step inspection, exact edits, repetitive transformations, commands, retrieval, or verification with precise acceptance conditions. |
20
- | `delegate_engineering` | Self-contained investigation, implementation, debugging, refactoring, testing, review, research, or analysis. |
5
+ Each delegation runs in an isolated, in-memory Pi RPC session. After every cohesive tool batch, a worker-side gate stops execution at a safe boundary and returns a bounded state report. The manager can then inspect the result and explicitly continue, revise, compact, checkpoint, cancel, or take over.
21
6
 
22
- The main model remains the **orchestrator**. It defines the delegated task, selects the smallest sufficient tool allowlist, evaluates the report, reviews material changes, performs required verification, and owns the final answer.
7
+ ## Features
23
8
 
24
- Workers operate in the current workspace and can modify files only when their selected tools permit it. Role routing to the configured `provider/model` is deterministic; worker output and correctness are not. Treat every worker report as input to review rather than proof of completion.
9
+ - **Two worker roles:** mechanical execution and broader engineering work.
10
+ - **Enforced supervision:** a private parent-child IPC gate calls `ctx.abort()` after persisted tool results; pausing does not depend on the worker following a prompt.
11
+ - **Explicit control:** continue, revise, recalculate, compact, checkpoint, cancel, or take over.
12
+ - **Resumable context:** continuation uses the same in-memory worker session and completed tool results.
13
+ - **Least privilege:** every start selects an exact Pi built-in worker-tool allowlist; delegation tools and unrelated discovered extensions are unavailable to the worker.
14
+ - **Model agnostic:** both roles inherit Pi's active model and thinking level unless an explicit role override is configured.
15
+ - **Formula-owned budgets:** the manager supplies semantic workload units, while the dispatcher calculates turn and time ceilings from workload, role, and delegated-model limits.
16
+ - **Context insight:** boundary reports include worker context usage, compactions, turns, elapsed time, action counts, and recommendations.
17
+ - **Recoverable reports:** the complete action ledger and worker text remain in structured tool details; bounded model-facing text retains recent actions plus both the beginning and ending of long reports.
18
+ - **Deterministic UI:** tool renderers display task, current activity, elapsed time, context pressure, and terminal success/failure colors. A compact paused-state line appears in Pi's footer.
25
19
 
26
20
  ## Requirements
27
21
 
28
- - Pi 1.0.2 or later
22
+ - Pi 1.0.3 or later
29
23
  - Node.js 22.19.0 or later
30
- - A configured and authenticated Pi model for each worker role you use
24
+ - One active, authenticated Pi model; optional role-specific models must also be available and authenticated
25
+
26
+ The supervision gate requires the parent Pi process and child Pi CLI to run under Node.js with an inherited IPC channel. The dispatcher fails closed when that boundary cannot be established; it does not fall back to prompt-only supervision. Worker processes disable ordinary extension discovery and load only the generated supervision gate.
31
27
 
32
28
  ## Installation
33
29
 
34
- Install the package for your Pi user configuration:
30
+ Install the published package for the current Pi user:
35
31
 
36
32
  ```sh
37
33
  pi install npm:pi-task-dispatcher
38
34
  ```
39
35
 
40
- To install it only for the current project, add `--local`:
36
+ ## Tools
41
37
 
42
- ```sh
43
- pi install npm:pi-task-dispatcher --local
44
- ```
38
+ | Tool | Responsibility |
39
+ | --- | --- |
40
+ | `delegate_mechanical` | Start a supervised mechanic delegation. |
41
+ | `delegate_engineering` | Start a supervised engineer delegation. |
42
+ | `delegate_control` | Apply one explicit manager decision to a paused delegation. |
43
+ | `delegate_status` | Recover the current or most recent state without changing it. |
44
+
45
+ Only one live delegation is currently permitted. A terminal delegation may be inspected until a new one replaces it.
45
46
 
46
- Project packages load only after the project is trusted. In an active Pi session, load the extension with:
47
+ ## Starting a delegation
47
48
 
48
- ```text
49
- /reload
49
+ Both role tools require:
50
+
51
+ - `task`: a self-contained objective, scope, constraints, and acceptance checks;
52
+ - `tools`: the smallest exact allowlist selected from Pi's built-in tools and active for the main agent;
53
+ - `workload`: semantic estimates used by the deterministic budget formula.
54
+
55
+ ```json
56
+ {
57
+ "task": "Inspect the parser cache, correct its invalidation, and run the focused tests.",
58
+ "tools": ["read", "edit", "bash"],
59
+ "workload": {
60
+ "investigationUnits": 3,
61
+ "changeUnits": 2,
62
+ "verificationUnits": 2,
63
+ "expectedLongRunningSeconds": 60
64
+ }
65
+ }
50
66
  ```
51
67
 
52
- ## Configuration
68
+ A workload unit is intentionally semantic:
69
+
70
+ - `investigationUnits`: cohesive components or evidence groups to inspect;
71
+ - `changeUnits`: related edit groups;
72
+ - `verificationUnits`: focused check or test groups;
73
+ - `expectedLongRunningSeconds`: additional expected command time.
74
+
75
+ At least one investigation, change, or verification unit is required.
76
+
77
+ Isolated workers accept `read`, `bash`, `powershell`, `edit`, `write`, `grep`, `find`, and `ls` when the selected tools are also active in the main Pi session. Extension tools are not supported because the child disables extension discovery.
78
+
79
+ The current formula derives planned work turns from those units, applies a role factor and a bounded scale based on the selected delegated model's own context window, reserves two additional turns for synthesis or recovery, then derives active execution time from calculated turns plus expected long-running time. Administrative ceilings always win. Formula inputs and results are returned in every state report so they can be reviewed and recalculated. Time spent paused for manager deliberation does not consume the active execution budget.
53
80
 
54
- The package works without a configuration file using these defaults:
81
+ ## Safe action boundaries
55
82
 
56
- | Role | Model | Thinking | Hard timeout | Checkpoint grace | Turn limit |
57
- | --- | --- | --- | ---: | ---: | ---: |
58
- | Mechanic | `openai-codex/gpt-5.6-luna` | `max` | 300 seconds | 30 seconds | 20 |
59
- | Engineer | `openai-codex/gpt-5.6-terra` | `max` | 900 seconds | 45 seconds | 30 |
83
+ A worker run proceeds as follows:
60
84
 
61
- To override them, create `~/.pi/agent/task-dispatcher.json`. If Pi uses a custom agent directory, create `task-dispatcher.json` in that directory instead. Missing roles and fields retain their defaults.
85
+ 1. Pi produces one assistant response.
86
+ 2. Its complete tool-call batch runs and tool results are persisted.
87
+ 3. The worker-only gate reports the boundary through private IPC.
88
+ 4. The gate aborts the automatic next worker turn.
89
+ 5. The RPC run settles while the child process and in-memory context remain alive.
90
+ 6. The delegation tool returns the new state to the manager.
91
+
92
+ An action batch can contain parallel tool calls from one worker response. Already-running tools are allowed to finish. The boundary prevents another productive model turn from starting without a manager decision.
93
+
94
+ ## Controlling a paused delegation
95
+
96
+ `delegate_control` accepts these actions:
97
+
98
+ | Action | Effect |
99
+ | --- | --- |
100
+ | `continue` | Resume from completed results. `actionBatches` may lease 1–10 batches before returning. |
101
+ | `revise` | Add controlling instructions, then resume. |
102
+ | `recalculate` | Supply remaining semantic workload and extend the current ceilings from observed turns and active execution time without running the worker. |
103
+ | `compact` | Compact the idle worker's own context and return refreshed state. |
104
+ | `take_over` | Stop the delegation externally and transfer remaining work to the manager. |
105
+ | `checkpoint` | Stop externally and preserve a synthetic checkpoint from observed state. |
106
+ | `cancel` | Stop externally and close the job. |
107
+
108
+ Example:
62
109
 
63
110
  ```json
64
111
  {
65
- "mechanic": {
66
- "model": "openai-codex/gpt-5.6-luna",
67
- "thinking": "max",
68
- "timeoutSeconds": 300,
69
- "checkpointGraceSeconds": 30,
70
- "maxTurns": 20
71
- },
72
- "engineer": {
73
- "model": "openai-codex/gpt-5.6-terra",
74
- "thinking": "max",
75
- "timeoutSeconds": 900,
76
- "checkpointGraceSeconds": 45,
77
- "maxTurns": 30
78
- }
112
+ "jobId": "engineer-2",
113
+ "action": "continue",
114
+ "actionBatches": 2
79
115
  }
80
116
  ```
81
117
 
82
- | Field | Description |
83
- | --- | --- |
84
- | `mechanic`, `engineer` | Optional role objects. Each supplied field overrides that role's default. |
85
- | `model` | Exact `provider/model` identity. The dispatcher verifies model availability and authentication before starting a worker. |
86
- | `thinking` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`. |
87
- | `timeoutSeconds` | Positive integer hard wall-clock limit for the worker process. |
88
- | `checkpointGraceSeconds` | Positive integer period reserved before the hard timeout for a graceful checkpoint. It must be less than `timeoutSeconds`. |
89
- | `maxTurns` | Positive integer work-turn limit. The dispatcher allows a final checkpoint response after the limit is reached. |
118
+ The dispatcher enforces takeover, cancellation, budget exhaustion, no-progress policy, and process cleanup. These actions do not depend on worker cooperation.
90
119
 
91
- Configuration is read for every delegation, so configuration-only changes do not require `/reload`.
120
+ ## State reports and screen output
92
121
 
93
- Tool access is deliberately absent from role configuration. Every delegation selects its own exact allowlist from the main agent's currently active tools; `[]` gives the worker no tools. A continuation must select its tools again and does not inherit the previous allowlist.
122
+ A paused result contains:
94
123
 
95
- ## Usage
124
+ - a session-local sequential identity such as `engineer-2`, plus role, model, and status;
125
+ - the delegated task and live command or tool activity while execution is running;
126
+ - boundary sequence and current phase;
127
+ - completed, failed, and potentially mutating action counts;
128
+ - recent bounded activity labels;
129
+ - active elapsed time and turns against calculated budgets;
130
+ - context tokens, context window, percentage, and compaction counts;
131
+ - a recommended next decision;
132
+ - bounded worker text, if any.
96
133
 
97
- Give the main model a bounded objective and let it choose whether delegation is useful. For example:
134
+ The TUI renders the same structured state as a compact block. Expanding the tool result reveals bounded worker text. The complete action ledger and worker text remain in result details for state reconstruction rather than being discarded by display truncation.
98
135
 
99
- > Use the engineering worker to diagnose the failing parser test. Do not change public APIs. Run the focused test and report the cause, changed files, and test result.
136
+ When paused, one unindented footer status appears below Pi's primary report. It shows the identity, active elapsed time, last activity, and context as percentage/window—for example, `10.3%/32k context`. The percentage and window both come from that delegation's selected model and live worker-session statistics, not from the main model.
100
137
 
101
- For tighter control, name the role and allowed tools:
138
+ ## Worker compaction
102
139
 
103
- > Delegate this to the mechanic worker with only `read` and `bash`: inspect the generated manifest, run its validation command, and report exact mismatches. Do not modify files.
140
+ The dispatcher explicitly enables automatic compaction in every worker session. Pi's automatic compaction remains the overflow safety mechanism.
104
141
 
105
- A direct tool remains preferable for one trivial operation. Delegation is most useful when a self-contained episode would otherwise consume multiple agent turns or produce bulky intermediate output.
142
+ The dispatcher also:
106
143
 
107
- ## Limits and checkpoints
144
+ - observes compaction lifecycle events;
145
+ - accounts for reported compaction usage;
146
+ - queries `get_session_stats` at safe boundaries;
147
+ - recommends proactive compaction when context usage reaches the current policy threshold;
148
+ - permits explicit worker compaction only while paused.
108
149
 
109
- Each delegation runs in a separate Pi RPC child process with an in-memory, no-session conversation. The worker receives its role prompt, selected model, thinking level, and only the allowlist chosen for that call.
150
+ Worker compaction is independent from compaction of the main Pi conversation.
110
151
 
111
- The dispatcher propagates parent cancellation and reports live text and tool activity. Before the hard timeout, it steers the worker to stop at the next safe turn boundary and produce a checkpoint. Reaching the turn limit uses the same checkpoint flow. If the worker cannot settle before the hard deadline, the dispatcher terminates it and reports observed completed and interrupted activity in a fallback checkpoint.
152
+ ## Configuration
112
153
 
113
- Non-completed results include the stopping reason, available partial worker text, observed activity, and a warning when filesystem effects may remain. The main agent then chooses whether to:
154
+ The optional configuration file is `task-dispatcher.json` in Pi's agent directory.
114
155
 
115
- - inspect and continue directly;
116
- - delegate a bounded continuation with a newly selected allowlist;
117
- - request user input; or
118
- - stop and report a limitation.
156
+ ```json
157
+ {
158
+ "policy": {
159
+ "absoluteMaxTurns": 96,
160
+ "absoluteMaxSeconds": 7200,
161
+ "pausedLeaseSeconds": 1800,
162
+ "noProgressSeconds": 600
163
+ }
164
+ }
165
+ ```
166
+
167
+ Configuration is read for every new delegation. By default, both roles inherit the manager's active model and thinking level, so installation assumes no particular provider or model access. A role may optionally override `model` with `"provider/model"`, `thinking`, or both. Policy values are administrative failsafes, not ordinary task budgets.
168
+
169
+ Version 3 intentionally ignores the version 2 fields `maxTurns`, `timeoutSeconds`, and `checkpointGraceSeconds`. Remove them from local configuration after migration.
170
+
171
+ ## Lifecycle and cleanup
172
+
173
+ - A parent-operation abort stops the active worker stage.
174
+ - A paused lease eventually closes an abandoned worker.
175
+ - Session shutdown or extension reload disposes the child and runtime-controlled temporary files.
176
+ - Worker process failures reject pending RPC operations and produce a failed state.
177
+ - Worker role instructions and the supervision gate exist only in a runtime-controlled temporary directory.
178
+ - The worker uses `--no-session`; no worker session file is persisted.
179
+
180
+ Process separation is not a security sandbox. Worker tools execute with the Pi host's operating-system permissions. Tool availability does not establish task scope or authorization.
181
+
182
+ ## Development checks
183
+
184
+ ```sh
185
+ npm run check
186
+ npm run test:gate
187
+ ```
119
188
 
120
- Continuation is never automatic.
189
+ `check` runs static release invariants and deterministic fake-RPC lifecycle and renderer scenarios. The fake child verifies pause/resume, usage deltas, full action-ledger retention, intercepted prompts, missing-boundary failure, fail-closed timeouts, pre-aborted operations, partial argument rendering, stable repeated rendering, and manager-state transitions without a model request.
121
190
 
122
- ## Security
191
+ `test:gate` performs a small live model integration check with the active parent model exported by Pi through `PI_PROVIDER`, `PI_MODEL`, and `PI_REASONING_LEVEL`, falling back to Pi's configured default when those values are unavailable; it contains no provider or model assumption. Optional `PI_TASK_DISPATCHER_GATE_MODEL` and `PI_TASK_DISPATCHER_GATE_THINKING` overrides are available for explicit test matrices. The probe verifies that the private gate pauses after a read batch and that the same in-memory child can subsequently complete. It requires configured credentials and therefore is not a hermetic unit test.
123
192
 
124
- Worker process separation is **not** a security sandbox. A worker uses its selected tools with the Pi host's permissions in the current environment. Tool availability does not establish task scope, authorization, or safety. Use the smallest practical allowlist and delegate only work you are prepared to authorize and review.