@ferris1225/pi-subagents 7.0.5 → 7.0.7

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,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 7.0.7
4
+
5
+ - Show free dispatch slots in background launch receipts and the main prompt.
6
+ When the ownership list fills up, show runs occupying slots first.
7
+ - Tailor briefs to the role. A summary follow-up gives the child its current
8
+ objective and earlier evidence while keeping the same phase identity as a
9
+ retained-session follow-up. Switching context cannot start the same phase twice.
10
+ - Expand a terminal dispatch card to inspect each full brief, directory, and
11
+ isolation setting. The task widget counts worktree application separately
12
+ from running children.
13
+
14
+ ## 7.0.6
15
+
16
+ - Show Escape cancellation progress and per-run statistics in the terminal before
17
+ the next user message. Finished workers report pending integration and retain
18
+ normal result delivery.
19
+ - Gate staged commits, pull requests, and publishing on unused-code checks.
20
+ The main-agent prompt delegates a dead-code review before an authorized push.
21
+ Clean up confirmed unused code before committing.
22
+
3
23
  ## 7.0.5
4
24
 
5
25
  - Shorten the main and child prompts with clear routing, brief, and review steps.
package/README.md CHANGED
@@ -109,6 +109,10 @@ subagent nor main repeats or edits that scope. Questions and review-only request
109
109
  implementation. Explicit requests to work in main take precedence. Parallel workers require independent
110
110
  scope and disjoint write ownership; a fix and its regression tests share an owner.
111
111
 
112
+ For an authorized push of code changes, main proactively delegates a read-only
113
+ audit of the diff. It removes confirmed dead code within the task's scope and
114
+ runs the project's checks before committing and pushing.
115
+
112
116
  There are two roles, each using its own model/thinking settings:
113
117
 
114
118
  | Scope | Tool parameter | Access |
@@ -127,9 +131,10 @@ by the extension. No automatic review score certifies a worker's result.
127
131
 
128
132
  ## Briefs and calls
129
133
 
130
- A useful brief names the **outcome**, **acceptance criteria**, **relevant paths and
131
- evidence**, **write boundary**, **checks**, **return conditions**, and **expected
132
- result**. Pass established facts forward and assign only missing work.
134
+ Start the brief with the **outcome**. Give a researcher the question to answer,
135
+ where to look, and what evidence to return. Give a worker the paths it owns,
136
+ the acceptance criteria, the exact checks, and when to return for replanning.
137
+ Pass established facts forward so the child can start with the remaining work.
133
138
 
134
139
  ```ts
135
140
  subagent({
@@ -153,8 +158,11 @@ that directory. Top-level `isolation` is the default for tasks that omit their
153
158
  own. Duplicate normalized tasks in the same directory are rejected while an
154
159
  active or settled run owns them. Use its result or continue it with `subagent_message`.
155
160
 
156
- A batch receipt lists the accepted run IDs and any tasks that failed to start.
157
- Address the failed launches individually while the accepted runs proceed.
161
+ A background receipt lists the accepted run IDs, the number of dispatch slots
162
+ still free across the session, and any tasks that failed to start. Main also
163
+ sees the available count alongside its phase leases. Runs applying a worktree
164
+ or parked after interruption keep ownership of their task and release their slot.
165
+ Address failed launches individually while the accepted runs proceed.
158
166
 
159
167
  Leave `wait` omitted (`false` in TUI/RPC) by default so subagents run in the
160
168
  background while main immediately continues its own disjoint work in parallel.
@@ -165,9 +173,11 @@ until background results wake it automatically.
165
173
  Results are delivered once, after integration. Awaited failures are tool errors.
166
174
  Answers exceeding 40 lines or 8,000 characters link their full-result artifact.
167
175
  The terminal card shows live progress for awaited runs, including worktree
168
- integration, and gives each accepted run its own status row. Expand the tool
169
- output with Ctrl+O in Pi's default keybindings to read the result and recovery
170
- details.
176
+ integration, and gives each accepted run its own status row. Collapsed calls
177
+ keep each task preview on one line. Press Ctrl+O with
178
+ Pi's default keybindings to read the full brief, the resolved working directory
179
+ and requested isolation for each dispatch, and the result or recovery details.
180
+ Expanded steering and follow-up calls also show the full instruction.
171
181
 
172
182
  | Tool | Purpose |
173
183
  | --- | --- |
@@ -179,8 +189,10 @@ details.
179
189
 
180
190
  Follow-ups use `context: "auto"` by default: a private copy of the retained session,
181
191
  or an explicit summary fallback when it expired. `context: "session"` requires full
182
- history. Continuations retain the session ID/cache key and re-read files in their
183
- current workspace. Summary continuations cannot rely on omitted history.
192
+ history. A session continuation retains its session ID and cache key. A summary
193
+ continuation receives the new objective, the earlier result, and referenced files.
194
+ Both use the current workspace. Repeating the same instruction for the same
195
+ source run refers to the same phase across all three context choices.
184
196
 
185
197
  Steering waits for a matching RPC acknowledgement. Received/queued means Pi queued
186
198
  the instruction, not that the model acted on it. A rejected or missing
@@ -201,17 +213,20 @@ worktree. Integration applies only its delta, is serialized per repository,
201
213
  and preserves the caller's index, branch, and HEAD. Failures retain recovery
202
214
  artifacts. Worktrees isolate Git changes, not permissions.
203
215
 
204
- Escape cancels unfinished workers without waking main. Main receives a cancellation
205
- receipt on the next user turn. A worker whose child already finished and is only
206
- integrating its worktree is not cancelled: it settles normally, and its real
207
- result, like any result already queued for delivery, arrives on the next user
208
- turn. `subagent_stop({ all: true })` also leaves such runs alone. Tree navigation,
209
- new/resume/fork/reload, and shutdown stop old work; interrupted evidence remains
210
- available for recovery.
216
+ Escape stops unfinished workers when it cancels a parent turn. Pi's terminal
217
+ shows which runs are stopping, then saves their elapsed time, model usage, and
218
+ worktree status in the transcript as available. A finished worker that is still
219
+ applying its worktree continues integrating and reports progress.
220
+ `subagent_stop({ all: true })` also lets those integrations finish. Main receives
221
+ the cancellation receipt and any deferred results the next time you send a
222
+ message. Tree navigation,
223
+ new/resume/fork/reload, and shutdown stop old work and retain interrupted evidence
224
+ for recovery.
211
225
 
212
226
  The task widget shows status, elapsed time, model, thinking, tokens, and worktree
213
- state in at most ten lines. Independent workers can start together; only
214
- integration into the original checkout is serialized.
227
+ state in at most ten lines. The overview, task rows, and waiting tool card use
228
+ `applying` while a finished child's worktree is being integrated. Independent
229
+ workers can start together. Integration into the original checkout is serialized.
215
230
 
216
231
  ## Pi integration
217
232
 
@@ -274,12 +289,22 @@ npm ci
274
289
  npm run check
275
290
  ```
276
291
 
292
+ `npm run check:unused` runs TypeScript's unused declaration checks and Knip's
293
+ checks for unused files, exports, and dependencies. It runs before the tests in
294
+ `npm run check`. The release review also asks a read-only subagent to inspect
295
+ the diff and report dead code with evidence before main commits.
296
+
297
+ `npm ci` installs the repository's pre-commit hook in a checkout without custom
298
+ hooks. The hook runs the same check on the staged files, so unstaged edits stay
299
+ out of the check. If you already use a custom pre-commit hook, add
300
+ `npm run check:staged` to it to use the staged check.
301
+
277
302
  Runtime modules live in `src/`: configuration/UI, orchestration prompts,
278
303
  execution, lifecycle, isolation/recovery, and presentation. Native integration tests
279
304
  use a local fixture provider and do not consume paid model requests.
280
305
 
281
- Pushes of an unpublished version to `main` run checks on Windows, macOS, and
282
- Linux, then [publish to npm and create a GitHub Release](./.github/workflows/publish.yml).
283
- Do not publish locally.
306
+ Pull requests and pushes to `main` run the checks on Windows, macOS, and Linux.
307
+ A passing push of an unpublished version to `main` publishes to npm and creates
308
+ a GitHub Release through the [publish workflow](./.github/workflows/publish.yml).
284
309
 
285
310
  [Changelog](./CHANGELOG.md) · [MIT license](./LICENSE)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ferris1225/pi-subagents",
3
- "version": "7.0.5",
3
+ "version": "7.0.7",
4
4
  "description": "Lead/worker orchestration for Pi: main plans and reviews, configurable workers execute with retained sessions and Git worktree isolation.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -36,8 +36,11 @@
36
36
  ]
37
37
  },
38
38
  "scripts": {
39
- "check": "tsc --noEmit && npm test",
39
+ "check": "npm run check:unused && npm test",
40
+ "check:unused": "tsc --noEmit && knip",
41
+ "check:staged": "node scripts/check-staged.mjs",
40
42
  "test": "node --test --test-concurrency=4 test/*.test.ts",
43
+ "prepare": "node scripts/install-git-hooks.mjs",
41
44
  "prepack": "npm run check"
42
45
  },
43
46
  "peerDependencies": {
@@ -51,6 +54,7 @@
51
54
  "@earendil-works/pi-coding-agent": "1.5.2",
52
55
  "@earendil-works/pi-tui": "1.5.2",
53
56
  "@types/node": "^22.10.0",
57
+ "knip": "6.48.0",
54
58
  "typebox": "^1.3.27",
55
59
  "typescript": "^5.9.0"
56
60
  },
@@ -9,19 +9,19 @@
9
9
  import { resolve } from "node:path";
10
10
  import { stripVTControlCharacters } from "node:util";
11
11
  import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
12
- import { Text } from "@earendil-works/pi-tui";
12
+ import { Container, Text, TruncatedText } from "@earendil-works/pi-tui";
13
13
  import { Type } from "typebox";
14
14
  import { loadBuiltinAgents } from "./agents.ts";
15
15
  import { BUILTIN_AGENT_NAMES, DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
16
16
  import { stringEnum } from "../configuration/schema.ts";
17
- import { formatUsage } from "../presentation/format.ts";
17
+ import { formatExpandedBrief, formatUsage } from "../presentation/format.ts";
18
18
  import {
19
19
  formatTaskSummary,
20
20
  monitor,
21
21
  statusIcon,
22
22
  } from "../presentation/monitor.ts";
23
23
  import { duplicateDispatchRemedy, findDuplicateDispatch, formatPhaseLeaseReceipt } from "./prompt.ts";
24
- import type { SubagentRuntime, SubagentThread } from "../lifecycle/runtime.ts";
24
+ import type { SubagentRuntime } from "../lifecycle/runtime.ts";
25
25
  import { cancelActiveWork } from "../lifecycle/cancellation.ts";
26
26
  import { awaitRunResults, WaitSchema } from "../lifecycle/await-results.ts";
27
27
  import { createDispatchCore, type DispatchCore } from "../lifecycle/dispatch-core.ts";
@@ -46,7 +46,7 @@ const IsolationSchema = Type.Optional(
46
46
  );
47
47
 
48
48
  const TASK_BRIEF_DESCRIPTION =
49
- "Self-contained brief with the outcome, acceptance criteria, relevant paths, known evidence, write boundaries, checks, and when to return for replanning. The child has no parent conversation.";
49
+ "Lead with the outcome. For research, specify the question, sources and evidence. For implementation, include owned paths, acceptance criteria and exact checks. Supply the facts the child needs from this conversation.";
50
50
 
51
51
  const agentSchema = (description: string) => stringEnum(BUILTIN_AGENT_NAMES, { description });
52
52
 
@@ -163,13 +163,6 @@ export function registerSubagentTool(
163
163
  ): void {
164
164
  const { startBackground, makeDetails } = core;
165
165
 
166
- const phaseLeaseReceipt = (runIds: number[]): string =>
167
- formatPhaseLeaseReceipt(
168
- runIds
169
- .map((runId) => runtime.threads.get(runId))
170
- .filter((thread): thread is SubagentThread => thread !== undefined),
171
- );
172
-
173
166
  pi.registerTool({
174
167
  name: "subagent",
175
168
  label: "Subagent",
@@ -238,11 +231,11 @@ export function registerSubagentTool(
238
231
  }
239
232
  const failureNotes = failures.length ? `\n\nLaunch failures:\n${failures.join("\n")}` : "";
240
233
  const details = makeDetails(mode)(results);
241
- if (!wait) return { content: [{ type: "text", text: phaseLeaseReceipt(ids) + failureNotes }], details };
234
+ if (!wait) return { content: [{ type: "text", text: formatPhaseLeaseReceipt(ids, runtime.threads) + failureNotes }], details };
242
235
 
243
236
  const blocks = await awaitRunResults(runtime, ids, signal, DEFAULT_MAX_RESULT_LINES, ctx.cwd, onUpdate
244
237
  ? (text) => onUpdate({ content: [{ type: "text", text }], details }) : undefined);
245
- if (signal?.aborted) await cancelActiveWork(runtime, "Parent run was cancelled.");
238
+ if (signal?.aborted) await cancelActiveWork(runtime, "Parent run was cancelled.", { context: ctx });
246
239
  else runtime.completeAwaitDelivery(ids);
247
240
  const settled = results.map((result) => result.runId === undefined ? result : runtime.settledRuns.get(result.runId) ?? result);
248
241
  return {
@@ -252,25 +245,34 @@ export function registerSubagentTool(
252
245
  };
253
246
  },
254
247
 
255
- renderCall(args, theme) {
256
- if (args.tasks && args.tasks.length > 0) {
257
- let text = `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", `parallel (${args.tasks.length})`)}`;
258
- for (const t of args.tasks.slice(0, MAX_CONCURRENT_SUBAGENTS)) {
259
- const preview = formatTaskSummary(t.task, 48);
260
- const isolation = defaultIsolationMode(t.agent, t.isolation ?? args.isolation) === "worktree" ? " [worktree]" : "";
261
- text += `\n ${theme.fg("accent", t.agent)}${theme.fg("dim", isolation)} ${theme.fg("dim", preview)}`;
248
+ renderCall(args, theme, { expanded, cwd }) {
249
+ const title = theme.fg("toolTitle", theme.bold("subagent "));
250
+ const batch = Array.isArray(args.tasks) ? args.tasks : undefined;
251
+ const lines = batch ? [title + theme.fg("accent", `parallel (${batch.length})`)] : [];
252
+ const baseCwd = expanded ? resolve(cwd, typeof args.cwd === "string" ? args.cwd : ".") : "";
253
+ // Pi renders streamed arguments before schema validation, including incomplete batch entries.
254
+ for (const item of (batch ?? [args]).slice(0, MAX_CONCURRENT_SUBAGENTS)) {
255
+ const role = typeof item?.agent === "string" ? stripVTControlCharacters(item.agent) : "…";
256
+ const task = typeof item?.task === "string" ? item.task : "";
257
+ const isolation = item?.isolation ?? args.isolation;
258
+ const mode = defaultIsolationMode(role, isolation);
259
+ const badge = mode === "worktree" ? (isolation ? "worktree" : "auto worktree")
260
+ : (isolation === "shared" || (expanded && role === "researcher")) ? "shared" : "";
261
+ const heading = (batch ? " " : title) + theme.fg("accent", role) + (badge ? theme.fg("dim", ` [${badge}]`) : "");
262
+ if (expanded) {
263
+ const directory = batch && typeof item?.cwd === "string" ? resolve(baseCwd, item.cwd) : baseCwd;
264
+ lines.push(heading + theme.fg("dim", ` · ${stripVTControlCharacters(directory)}`));
265
+ if (task) lines.push(formatExpandedBrief(task));
266
+ } else {
267
+ const preview = formatTaskSummary(task, batch ? 48 : 60);
268
+ lines.push(heading + (preview ? " " + theme.fg("dim", preview) : ""));
262
269
  }
263
- if (args.tasks.length > MAX_CONCURRENT_SUBAGENTS) text += `\n ${theme.fg("dim", `… +${args.tasks.length - MAX_CONCURRENT_SUBAGENTS} more`)}`;
264
- return new Text(text, 0, 0);
265
270
  }
266
- const task: string = args.task ?? "";
267
- const preview = formatTaskSummary(task, 60);
268
- const isolation = defaultIsolationMode(args.agent ?? "", args.isolation) === "worktree" ? " [worktree]" : "";
269
- return new Text(
270
- `${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", args.agent ?? "?")}${theme.fg("dim", `${isolation}`)} ${theme.fg("dim", preview)}`,
271
- 0,
272
- 0,
273
- );
271
+ if (batch && batch.length > MAX_CONCURRENT_SUBAGENTS) lines.push(theme.fg("dim", ` … +${batch.length - MAX_CONCURRENT_SUBAGENTS} more`));
272
+ if (expanded) return new Text(lines.join("\n"), 0, 0);
273
+ const card = new Container();
274
+ for (const line of lines) card.addChild(new TruncatedText(line));
275
+ return card;
274
276
  },
275
277
 
276
278
  renderResult(result, options, theme) {
@@ -17,6 +17,7 @@ import type { AgentConfig } from "./agents.ts";
17
17
  import { formatCatalogEntry } from "./agents.ts";
18
18
  import { ORCHESTRATION_SECTION } from "./orchestration.ts";
19
19
  import { MAX_CONCURRENT_SUBAGENTS } from "../execution/background.ts";
20
+ import { dispatchCapacity } from "../lifecycle/thread-shared.ts";
20
21
 
21
22
  export interface PhaseLeaseSource {
22
23
  id: number;
@@ -104,6 +105,15 @@ export function duplicateDispatchRemedy(owner: PhaseLeaseSource): string {
104
105
  }
105
106
  }
106
107
 
108
+ /** A follow-up can check ownership before copying history. Fresh admission
109
+ * checks it again when synchronously reserving the new run. */
110
+ export function duplicatePhaseConflict(sources: Iterable<PhaseLeaseSource>, task: string, cwd: string): string | undefined {
111
+ const duplicate = findDuplicateDispatch(sources, task, cwd);
112
+ if (!duplicate) return undefined;
113
+ const owner = duplicate.source;
114
+ return `Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${duplicateDispatchRemedy(owner)}`;
115
+ }
116
+
107
117
  function summarizeLeaseTask(task: string): string {
108
118
  const oneLine = normalizedTask(task);
109
119
  const characters = [...oneLine];
@@ -121,9 +131,10 @@ function leaseLine(source: PhaseLeaseSource): string {
121
131
 
122
132
  /** Prompt-section view of active leases, bounded so a wide batch cannot grow
123
133
  * every later prompt. */
124
- function formatActivePhaseLeases(sources: Iterable<PhaseLeaseSource>): string {
134
+ function formatActivePhaseLeases(sources: Iterable<PhaseLeaseSource>, slotOwners: ReadonlySet<number>): string {
135
+ const priority = (source: PhaseLeaseSource) => slotOwners.has(source.id) ? 0 : source.state === "parked" ? 2 : 1;
125
136
  const active = [...sources].filter(isActivePhaseLease)
126
- .sort((left, right) => Number(left.state === "parked") - Number(right.state === "parked"));
137
+ .sort((left, right) => priority(left) - priority(right));
127
138
  if (active.length === 0) return "";
128
139
  const lines = active.slice(0, MAX_ACTIVE_LEASES).map(leaseLine);
129
140
  if (active.length > MAX_ACTIVE_LEASES) {
@@ -134,11 +145,19 @@ function formatActivePhaseLeases(sources: Iterable<PhaseLeaseSource>): string {
134
145
 
135
146
  /** Launch receipt listing every run the call started, so each id stays
136
147
  * addressable for steering, status, and stop. */
137
- export function formatPhaseLeaseReceipt(sources: Iterable<PhaseLeaseSource>): string {
138
- const accepted = [...sources];
148
+ export function formatPhaseLeaseReceipt(runIds: readonly number[], threads: ReadonlyMap<number, PhaseLeaseSource>): string {
149
+ const accepted = runIds.map((id) => threads.get(id)).filter((source) => source !== undefined);
139
150
  if (accepted.length === 0) return "";
140
151
  const count = accepted.length;
141
- return `Accepted ${count} subagent ${count === 1 ? "run" : "runs"}\n${accepted.map(leaseLine).join("\n")}\nContinue only disjoint work. Results return automatically after settlement.`;
152
+ const { available } = dispatchCapacity(threads.values());
153
+ return [
154
+ `Accepted ${count} subagent ${count === 1 ? "run" : "runs"}`, ...accepted.map(leaseLine),
155
+ formatDispatchSlots(available), "Continue only disjoint work. Results return automatically after settlement.",
156
+ ].join("\n");
157
+ }
158
+
159
+ export function formatDispatchSlots(available: number): string {
160
+ return `Dispatch slots: ${available}/${MAX_CONCURRENT_SUBAGENTS} free.`;
142
161
  }
143
162
 
144
163
  function delegationBody(agents: AgentConfig[]): string {
@@ -151,12 +170,13 @@ function delegationBody(agents: AgentConfig[]): string {
151
170
  ];
152
171
  const dispatch = [
153
172
  `Use \`subagent({ agent, task })\` for one phase. Batch independent phases in one \`subagent({ tasks })\` call within the free slots (${MAX_CONCURRENT_SUBAGENTS} maximum). Sequence dependent phases. Give each writer a disjoint scope and keep a change with its tests. Leave an owned phase to its current run.`,
154
- "Write a self-contained brief. Give the outcome and acceptance criteria, paths or symbols, known evidence, write boundaries, exact checks, and when to return for replanning. Children have no parent conversation. Assign only the remaining work.",
173
+ "Start each brief with the outcome. For research, name the question, sources, and evidence needed. For implementation, name the owned paths, acceptance criteria, exact checks, and when to return for replanning. Include only the context the child needs.",
155
174
  "Omit `wait` for background work in TUI/RPC. Continue disjoint work, or end the turn and let results wake you after integration. Use `wait: true` when the next step depends on this result and no disjoint work can proceed. Avoid polling. Print/JSON waits by default.",
156
175
  ];
157
176
  const review = [
158
177
  "Treat child output as evidence. Review the actual diff, affected callers, and check evidence against the acceptance criteria. Reuse checks that still cover the code and read the result file when output was truncated.",
159
178
  "Use `subagent_message` to steer a running child or give a completed run a focused correction. Inspect failed or interrupted results with `subagent_status`, then correct the brief or finish in main. In a partial batch, leave accepted runs alone and address only the failed launches.",
179
+ "For an authorized push of code changes, first delegate a read-only audit of the diff for dead code and unused files, exports, or dependencies. If unavailable, audit in main. Remove confirmed dead code within scope. Delegate bounded fixes when practical. Run project checks before committing and pushing.",
160
180
  ];
161
181
 
162
182
  return `## Subagent orchestration
@@ -181,9 +201,12 @@ function buildStableDelegationSection(agents: AgentConfig[], includeEmptyCatalog
181
201
  /** Bounded ownership reminder; settled results remain reusable after compaction. */
182
202
  function buildActiveLeaseSection(sources: Iterable<PhaseLeaseSource>): string {
183
203
  const all = [...sources];
184
- const activeLeases = formatActivePhaseLeases(all);
204
+ const { activeIds, available } = dispatchCapacity(all);
205
+ const activeLeases = formatActivePhaseLeases(all, activeIds);
185
206
  const recent = all.filter(isSettledLease).slice(-MAX_RECENT_SETTLED_LEASES).map(leaseLine).join("\n");
207
+ if (!activeLeases && !recent) return "";
186
208
  return [
209
+ formatDispatchSlots(available),
187
210
  ...(activeLeases ? [`Active phase leases:\n${activeLeases}`] : []),
188
211
  ...(recent ? [`Recent settled phases — reuse results via subagent_status; continue only unfinished work:\n${recent}`] : []),
189
212
  ].join("\n");
@@ -101,16 +101,13 @@ export class RunControl {
101
101
  private stopRequested = false;
102
102
  private stopMessage = "Subagent was aborted";
103
103
  private childPids = new Set<number>();
104
- readonly generation: number;
105
104
  private readonly onPhase?: (phase: RunControlPhase) => void;
106
105
 
107
106
  constructor(
108
107
  objective: string,
109
- generation: number,
110
108
  onPhase?: (phase: RunControlPhase) => void,
111
109
  ) {
112
110
  this.objective = objective;
113
- this.generation = generation;
114
111
  this.onPhase = onPhase;
115
112
  }
116
113
 
@@ -46,8 +46,6 @@ function directoryBytes(path: string): number {
46
46
  }
47
47
 
48
48
  interface CleanupUsage {
49
- /** Absolute path of the extension's durable root. */
50
- root: string;
51
49
  /** Per-project usage, largest first. */
52
50
  projects: Array<{ path: string; bytes: number; sessions: number; worktrees: number }>;
53
51
  totalBytes: number;
@@ -70,7 +68,7 @@ export function measureDurableUsage(root: string): CleanupUsage {
70
68
  try {
71
69
  projects = readdirSync(root, { withFileTypes: true });
72
70
  } catch {
73
- return { root, projects: [], totalBytes: 0 };
71
+ return { projects: [], totalBytes: 0 };
74
72
  }
75
73
  const measured = projects
76
74
  .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && !entry.name.endsWith(".lock"))
@@ -85,7 +83,6 @@ export function measureDurableUsage(root: string): CleanupUsage {
85
83
  })
86
84
  .sort((left, right) => right.bytes - left.bytes);
87
85
  return {
88
- root,
89
86
  projects: measured,
90
87
  totalBytes: measured.reduce((sum, project) => sum + project.bytes, 0),
91
88
  };
@@ -115,8 +115,6 @@ export interface WorktreeFinalization {
115
115
  /** True once the patch was successfully applied to the original worktree. */
116
116
  integrated: boolean;
117
117
  hadChanges: boolean;
118
- /** Repository a recovery path can prune stale worktree metadata against. */
119
- originalRoot?: string;
120
118
  worktreePath?: string;
121
119
  patchPath?: string;
122
120
  error?: string;
@@ -546,7 +544,6 @@ class GitWorktreeIsolation implements WorktreeIsolation {
546
544
  status: "retained",
547
545
  integrated,
548
546
  hadChanges,
549
- originalRoot: this.originalRoot,
550
547
  ...(existsSync(this.worktreePath) ? { worktreePath: this.worktreePath } : {}),
551
548
  ...(patchWritten && existsSync(this.patchPath) ? { patchPath: this.patchPath } : {}),
552
549
  error,
@@ -90,8 +90,7 @@ export async function awaitRunResults(
90
90
  if (settled) return `#${id} ${isFailedResult(settled) ? "failed" : "done"}`;
91
91
  const live = monitor.findRun(id);
92
92
  if (!live) return `#${id} …`;
93
- const state = live.integrationStatus === "finalizing" ? "integrating" : live.status === "failed" ? "failed" : statusLabel(live.status);
94
- return `#${id} ${state}`;
93
+ return `#${id} ${statusLabel(live)}`;
95
94
  });
96
95
  const text = `Waiting in-turn on ${runIds.length} run${runIds.length === 1 ? "" : "s"} · ${parts.join(", ")}`;
97
96
  // The monitor notifies on every usage and activity change; this line
@@ -6,34 +6,70 @@
6
6
  * user turn without waking the parent. Branch navigation abandons the
7
7
  * conversation, so it stops everything and discards results. */
8
8
 
9
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
- import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
9
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+ import { Text } from "@earendil-works/pi-tui";
11
+ import { formatDuration, formatTaskSummary } from "../presentation/monitor.ts";
12
+ import { formatUsage } from "../presentation/format.ts";
13
+ import { CANCELLATION_STATS_ENTRY, type SubagentRuntime, type SubagentThread } from "./runtime.ts";
11
14
  import { stopThreads } from "./stop.ts";
12
15
 
13
16
  const cancellations = new WeakMap<SubagentRuntime, Promise<void>>();
14
17
 
18
+ interface CancellationOptions {
19
+ context?: Pick<ExtensionContext, "mode" | "ui">;
20
+ notifyParent?: boolean;
21
+ }
22
+
23
+ function showTuiNotice(context: CancellationOptions["context"], text: string): void {
24
+ if (context?.mode !== "tui") return;
25
+ try {
26
+ context.ui.notify(text, "info");
27
+ } catch {
28
+ /* The terminal may have closed during cancellation. */
29
+ }
30
+ }
31
+
32
+ function formatStoppedRun(runtime: SubagentRuntime, thread: SubagentThread): string {
33
+ const result = runtime.settledRuns.get(thread.id);
34
+ return [
35
+ `#${thread.id} ${thread.agentName}`,
36
+ formatDuration(thread.elapsedMs),
37
+ result?.model ? formatTaskSummary(result.model, 60, false) : undefined,
38
+ result && formatUsage(result.usage),
39
+ result?.integrationStatus && `worktree ${result.integrationStatus.replaceAll("_", " ")}`,
40
+ ].filter(Boolean).join(" · ");
41
+ }
42
+
15
43
  /** The child has settled and only Git integration and delivery remain. */
16
44
  export function isSettlingThread(thread: SubagentThread): boolean {
17
45
  return !thread.retired && thread.lifecycleOperation === "settle";
18
46
  }
19
47
 
20
- export function cancelActiveWork(runtime: SubagentRuntime, reason: string, notifyParent = true): Promise<void> {
48
+ export function cancelActiveWork(
49
+ runtime: SubagentRuntime,
50
+ reason: string,
51
+ { context, notifyParent = true }: CancellationOptions = {},
52
+ ): Promise<void> {
21
53
  const existing = cancellations.get(runtime);
22
54
  if (existing) return existing;
23
55
  runtime.suppressCompletions = true;
24
- if (notifyParent) runtime.deferPendingCompletions();
56
+ const deferredCount = notifyParent ? runtime.deferPendingCompletions() : 0;
25
57
  runtime.discardCompletions();
26
58
  const threads = [...runtime.threads.values()];
27
59
  // Only a parent cancellation keeps finished work; an abandoned branch stops it.
28
- const keepSettling = notifyParent;
29
- if (keepSettling) for (const thread of threads.filter(isSettlingThread)) runtime.deferRunDelivery(thread.id);
60
+ const settlingThreads = notifyParent ? threads.filter(isSettlingThread) : [];
61
+ for (const thread of settlingThreads) runtime.deferRunDelivery(thread.id);
30
62
  const activeThreads = threads
31
- .filter((thread) => !thread.retired && !(keepSettling && isSettlingThread(thread))
63
+ .filter((thread) => !thread.retired && !(notifyParent && isSettlingThread(thread))
32
64
  && (thread.lifecycleOperation !== undefined || ["queued", "running", "interrupting"].includes(thread.state)));
33
65
  const threadIds = activeThreads.map((thread) => thread.id);
66
+ const runCount = `${threadIds.length} subagent run${threadIds.length === 1 ? "" : "s"}`;
34
67
  const done = stopThreads(runtime, threadIds, reason).then(() => {
35
68
  if (notifyParent && runtime.sessionActive && threadIds.length > 0) {
36
- runtime.recordCancellation(threadIds);
69
+ const stats = context?.mode === "tui"
70
+ ? [`Stopped ${runCount}`, ...activeThreads.map((thread) => formatStoppedRun(runtime, thread))]
71
+ : undefined;
72
+ runtime.recordCancellation(threadIds, stats);
37
73
  }
38
74
  }).finally(() => {
39
75
  runtime.discardCompletions();
@@ -41,12 +77,27 @@ export function cancelActiveWork(runtime: SubagentRuntime, reason: string, notif
41
77
  cancellations.delete(runtime);
42
78
  });
43
79
  cancellations.set(runtime, done);
80
+ if (notifyParent && runtime.sessionActive) {
81
+ const notices: string[] = [];
82
+ if (threadIds.length) notices.push(`Stopping ${runCount} · ${threadIds.map((id) => `#${id}`).join(", ")}`);
83
+ for (const thread of settlingThreads) {
84
+ const progress = thread.isolation === "worktree" ? "applying worktree changes" : "finalizing its result";
85
+ notices.push(`#${thread.id} ${thread.agentName} finished and is ${progress}.`);
86
+ }
87
+ if (deferredCount) notices.push(`${deferredCount} completed subagent result${deferredCount === 1 ? "" : "s"} ready for your next message.`);
88
+ if (notices.length) showTuiNotice(context, notices.join("\n"));
89
+ }
44
90
  return done;
45
91
  }
46
92
 
47
93
  export function registerCancellationHooks(pi: ExtensionAPI, runtime: SubagentRuntime): void {
48
- pi.on("agent_settled", (event) => event.aborted ? cancelActiveWork(runtime, "Parent run was cancelled.") : undefined);
49
- pi.on("session_before_tree", () => cancelActiveWork(runtime, "Parent navigated to another conversation branch.", false));
94
+ pi.registerEntryRenderer<string[]>(CANCELLATION_STATS_ENTRY, (entry, _options, theme) => {
95
+ if (!Array.isArray(entry.data) || !entry.data.length) return undefined;
96
+ const [title, ...runs] = entry.data;
97
+ return new Text([theme.bold(title!), ...runs].join("\n"), 0, 0);
98
+ });
99
+ pi.on("agent_settled", (event, context) => event.aborted ? cancelActiveWork(runtime, "Parent run was cancelled.", { context }) : undefined);
100
+ pi.on("session_before_tree", () => cancelActiveWork(runtime, "Parent navigated to another conversation branch.", { notifyParent: false }));
50
101
  // Pi emits session_shutdown for new/resume/fork/reload. The runtime's
51
102
  // shutdown path stops children, retains recovery evidence, and disables delivery.
52
103
  }
@@ -22,7 +22,6 @@ export interface DispatchCore {
22
22
  startBackground: StartBackgroundInternal;
23
23
  /** Stamp a terminal monitor state and toast the result once. */
24
24
  finishRun: (runId: number, status: "done" | "failed", opts?: { silent?: boolean }) => void;
25
- makeLiveHandler: (runId: number, generation?: number) => (event: SubagentLiveEvent) => void;
26
25
  makeDetails: (mode: "single" | "parallel") => (results: SingleResult[]) => SubagentDetails;
27
26
  }
28
27
 
@@ -145,7 +144,6 @@ export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
145
144
  },
146
145
  startBackground,
147
146
  finishRun,
148
- makeLiveHandler,
149
147
  makeDetails,
150
148
  };
151
149
  }
@@ -25,6 +25,8 @@ import type { RunControl, SteeringReceipt } from "../execution/run-control.ts";
25
25
  import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
26
26
  import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "../isolation/worktree.ts";
27
27
 
28
+ export const CANCELLATION_STATS_ENTRY = "subagent-cancellation-stats";
29
+
28
30
  export type ThreadState = "queued" | "running" | "interrupting" | "parked" | "completed" | "failed" | "stopped";
29
31
 
30
32
  type ThreadLifecycleOperation = "stop" | "settle";
@@ -86,13 +88,13 @@ export interface SubagentRuntime {
86
88
  /** Cancelling a parent must not wake it again with old child results. */
87
89
  suppressCompletions: boolean;
88
90
  discardCompletions: () => void;
89
- /** Hand held completions to the next user turn without waking the parent. */
90
- deferPendingCompletions: () => void;
91
+ /** Hand held completions to the next user turn and return the number queued. */
92
+ deferPendingCompletions: () => number;
91
93
  /** Route a run that already finished its child to the next user turn, even
92
94
  * while completions are suppressed: its result is real and must not be lost. */
93
95
  deferRunDelivery: (runId: number) => void;
94
- /** Record cancellation for the next user turn without waking the parent. */
95
- recordCancellation: (runIds: number[]) => void;
96
+ /** Show optional terminal stats and queue the cancellation receipt for the next user turn. */
97
+ recordCancellation: (runIds: number[], stats?: string[]) => void;
96
98
  /** Resolves when the load-time durable restore pass has finished. Everything
97
99
  * that answers "which threads exist" awaits it — the lookup tools, a fresh
98
100
  * dispatch before it allocates a run id, and the restored-thread notice — so
@@ -160,13 +162,23 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
160
162
  getToolInfos: () => pi.getAllTools(),
161
163
  sessionActive: true,
162
164
  suppressCompletions: false,
163
- recordCancellation: (runIds) => {
165
+ recordCancellation: (runIds, stats) => {
164
166
  if (!runIds.length) return;
167
+ let display = true;
168
+ if (stats) {
169
+ try {
170
+ // Custom entries render immediately and stay out of model context.
171
+ pi.appendEntry(CANCELLATION_STATS_ENTRY, stats);
172
+ display = false;
173
+ } catch {
174
+ /* Keep the next-turn receipt visible if the entry could not be saved. */
175
+ }
176
+ }
165
177
  const targets = "runs " + runIds.map((id) => `#${id}`).join(", ");
166
178
  pi.sendMessage({
167
179
  customType: "subagent-cancelled",
168
180
  content: `Parent cancellation stopped ${targets}. These runs are already cancelled; no further subagent_stop is needed. Do not restart cancelled work unless the user requests it. Partial edits and retained integration artifacts may remain; inspect them only if continuing the task.`,
169
- display: true,
181
+ display,
170
182
  details: { runIds },
171
183
  }, { deliverAs: "nextTurn", triggerTurn: false });
172
184
  },
@@ -179,6 +191,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
179
191
  const pending = [...runtime.completionBatcher.dispose(), ...heldCompletions];
180
192
  heldCompletions = [];
181
193
  sendNextTurn(pending);
194
+ return pending.length;
182
195
  },
183
196
  deferRunDelivery: (runId) => {
184
197
  deferredRuns.add(runId);
@@ -63,10 +63,15 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
63
63
  // An isolated stop may need the repository lane for final integration;
64
64
  // cancelling all holders first prevents stop-all from waiting behind a
65
65
  // later run that this same operation has not interrupted yet.
66
- const interruptionPromises = claimed.map(({ thread, stopMessage, controller }) => {
66
+ const interruptions = claimed.map(({ runId, thread, stopMessage, controller }) => {
67
67
  const stopping = thread.control.stop(stopMessage).catch(() => undefined);
68
68
  runtime.backgroundQueue.cancel(controller);
69
- return stopping;
69
+ // Capture each duration as its child stops. A sibling may spend much
70
+ // longer integrating its worktree before we can remove this monitor row.
71
+ const captureElapsed = quiesced(stopping).then(() => {
72
+ thread.elapsedMs = monitor.getElapsedMs(runId) ?? thread.elapsedMs;
73
+ });
74
+ return { stopping, captureElapsed };
70
75
  });
71
76
 
72
77
  const stopped: string[] = [];
@@ -93,7 +98,8 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
93
98
  // unkillable child can stall even process termination. Stop owns the
94
99
  // lifecycle synchronously, so a stuck tail settles silently after we
95
100
  // proceed; none of its late paths can publish a second result.
96
- await quiesced(interruptionPromises[claimIndex]);
101
+ const interruption = interruptions[claimIndex]!;
102
+ await interruption.captureElapsed;
97
103
  if (!(await quiesced(completion))) runtime.backgroundQueue.cancel(controller);
98
104
  if (runtime.runControllers.get(runId) === controller) runtime.runControllers.delete(runId);
99
105
  if (thread.queueController === controller) thread.queueController = undefined;
@@ -127,7 +133,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
127
133
  exitCode: 1,
128
134
  messages: [],
129
135
  stderr: stopMessage,
130
- usage: emptyUsage(),
136
+ usage: run?.usage ?? emptyUsage(),
131
137
  model: run?.model,
132
138
  thinking: run?.thinking,
133
139
  projectCwd: thread.cwd,
@@ -186,7 +192,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
186
192
  if (thread.durableId) await removeThreadRecord(runtime.configPath, thread.durableId, thread.cwd).catch(() => undefined);
187
193
  // Returning from a bounded stop retires context, but cannot release a
188
194
  // writer or phase lease while a child or Git tail can still change files.
189
- void Promise.allSettled([interruptionPromises[claimIndex]!, completion, finalizationCompletion]).then(() => {
195
+ void Promise.allSettled([interruption.stopping, completion, finalizationCompletion]).then(() => {
190
196
  if (thread.lifecycleVersion === stopVersion && thread.lifecycleOperation === "stop") {
191
197
  thread.lifecycleOperation = undefined;
192
198
  }
@@ -14,7 +14,7 @@ import type { CompletionMessageItem } from "./completion.ts";
14
14
  import { DEFAULT_IDLE_TIMEOUT_SEC, DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
15
15
  import { dispatchFailedResult, failedStartResult, formatCompletionBlock, queuedResult } from "../presentation/format.ts";
16
16
  import { formatTaskSummary, monitor } from "../presentation/monitor.ts";
17
- import { duplicateDispatchRemedy, findDuplicateDispatch } from "../delegation/prompt.ts";
17
+ import { duplicatePhaseConflict } from "../delegation/prompt.ts";
18
18
  import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isolation/recovery.ts";
19
19
  import { type SubagentRuntime, type SubagentThread, type ThreadState } from "./runtime.ts";
20
20
  import {
@@ -104,16 +104,8 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
104
104
  isolation,
105
105
  };
106
106
  }
107
- const duplicate = findDuplicateDispatch(runtime.threads.values(), task, originalCwd);
108
- if (duplicate) {
109
- // A phase stays owned across reloads: an interrupted run keeps its claim
110
- // until it is retired, so "let it finish" is wrong advice for a parked
111
- // owner and leaves the caller with no way forward. A retired owner is
112
- // still releasing its child or worktree after subagent_stop.
113
- const owner = duplicate.source;
114
- return failedStartResult(agentName, task,
115
- `Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${duplicateDispatchRemedy(owner)}`);
116
- }
107
+ const duplicate = duplicatePhaseConflict(runtime.threads.values(), task, originalCwd);
108
+ if (duplicate) return failedStartResult(agentName, task, duplicate);
117
109
  const capacityConflict = concurrencyAdmissionConflict(runtime, 1);
118
110
  if (capacityConflict) {
119
111
  return failedStartResult(agentName, task, `Subagent dispatch rejected: ${capacityConflict}`);
@@ -140,7 +132,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
140
132
  };
141
133
 
142
134
  let thread!: SubagentThread;
143
- const control = new RunControl(task, generation, (phase) => {
135
+ const control = new RunControl(task, (phase) => {
144
136
  if (runtime.threads.get(runId)?.generation !== generation || phase === "settled") return;
145
137
  const state: ThreadState =
146
138
  phase === "queued" || phase === "starting"
@@ -237,6 +229,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
237
229
  resolveAgentBeforeLaunch: resolveLiveAgentTools,
238
230
  agentName,
239
231
  task,
232
+ stdinText: startOptions.stdinText,
240
233
  cwd: executionCwd,
241
234
  thinkingLevel: activeRoute.thinkingLevel,
242
235
  signal: backgroundSignal,
@@ -58,7 +58,7 @@ function createRestoredThread(
58
58
  isolation: record.isolation,
59
59
  worktree,
60
60
  state,
61
- control: new RunControl(record.task, record.generation),
61
+ control: new RunControl(record.task),
62
62
  generationCompletion: Promise.resolve(),
63
63
  lifecycleVersion: 0,
64
64
  elapsedMs: record.elapsedMs,
@@ -29,8 +29,12 @@ function isConcurrencyActiveThread(
29
29
  return thread.state === "queued" || thread.state === "running" || thread.state === "interrupting";
30
30
  }
31
31
 
32
- function activeConcurrencyThreads(runtime: Pick<SubagentRuntime, "threads">): SubagentThread[] {
33
- return [...runtime.threads.values()].filter(isConcurrencyActiveThread);
32
+ export function dispatchCapacity(threads: Iterable<Pick<SubagentThread, "id" | "state" | "retired" | "lifecycleOperation">>) {
33
+ const activeIds = new Set<number>();
34
+ for (const thread of threads) {
35
+ if (isConcurrencyActiveThread(thread)) activeIds.add(thread.id);
36
+ }
37
+ return { activeIds, available: Math.max(0, MAX_CONCURRENT_SUBAGENTS - activeIds.size) };
34
38
  }
35
39
 
36
40
  export function concurrencyAdmissionConflict(
@@ -40,14 +44,13 @@ export function concurrencyAdmissionConflict(
40
44
  if (requestedCount > MAX_CONCURRENT_SUBAGENTS) {
41
45
  return `requested ${requestedCount} tasks, exceeding the maximum concurrency of ${MAX_CONCURRENT_SUBAGENTS}. Batch at most ${MAX_CONCURRENT_SUBAGENTS} independent, disjoint tasks at once; continue disjoint work in main and dispatch remaining phases after active runs finish.`;
42
46
  }
43
- const active = activeConcurrencyThreads(runtime);
44
- const available = Math.max(0, MAX_CONCURRENT_SUBAGENTS - active.length);
47
+ const { activeIds, available } = dispatchCapacity(runtime.threads.values());
45
48
  if (requestedCount <= available) return undefined;
46
- const activeIds = active.map((thread) => `#${thread.id}`).join(", ");
49
+ const owners = [...activeIds].map((id) => `#${id}`).join(", ");
47
50
  if (available === 0) {
48
- return `concurrency limit of ${MAX_CONCURRENT_SUBAGENTS} active subagents is full (${activeIds} active). Do not duplicate their work; continue disjoint work in main until an active run finishes.`;
51
+ return `concurrency limit of ${MAX_CONCURRENT_SUBAGENTS} active subagents is full (${owners} active). Do not duplicate their work; continue disjoint work in main until an active run finishes.`;
49
52
  }
50
- return `${active.length}/${MAX_CONCURRENT_SUBAGENTS} subagents are already active (${activeIds}), leaving ${available} free slot${available === 1 ? "" : "s"} for ${requestedCount} requested tasks. Dispatch at most ${available} independent task${available === 1 ? "" : "s"} now, or continue disjoint work in main until active runs finish.`;
53
+ return `${activeIds.size}/${MAX_CONCURRENT_SUBAGENTS} subagents are already active (${owners}), leaving ${available} free slot${available === 1 ? "" : "s"} for ${requestedCount} requested tasks. Dispatch at most ${available} independent task${available === 1 ? "" : "s"} now, or continue disjoint work in main until active runs finish.`;
51
54
  }
52
55
 
53
56
  /** Control operations must never wait forever on a settling generation: the
@@ -112,6 +115,9 @@ export interface DispatchEnvironment {
112
115
  export interface StartBackgroundOptions {
113
116
  /** A private copy of a settled session used for a follow-up run. */
114
117
  resumeSession?: { sessionId: string; sessionDir: string };
118
+ /** Historical evidence and the new instruction for a summary continuation.
119
+ * The logical task stays the same whichever history the parent chooses. */
120
+ stdinText?: string;
115
121
  /** Omitted public isolation may fall back only when no Git baseline exists. */
116
122
  automaticIsolation?: boolean;
117
123
  /** Chosen by the tool call before the queue can start a fast child. */
@@ -4,21 +4,22 @@ import { copyFile, mkdir, mkdtemp, rm } from "node:fs/promises";
4
4
  import { basename, join } from "node:path";
5
5
  import type { Message } from "@earendil-works/pi-ai";
6
6
  import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
7
- import { Text } from "@earendil-works/pi-tui";
7
+ import { Text, TruncatedText } from "@earendil-works/pi-tui";
8
8
  import { Type } from "typebox";
9
9
  import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
10
10
  import { loadBuiltinAgents } from "../delegation/agents.ts";
11
+ import { duplicatePhaseConflict, formatDispatchSlots } from "../delegation/prompt.ts";
11
12
  import { findSessionFile, getProjectRoot, getResultOutput, isFailedResult, sessionExists } from "../execution/spawn.ts";
12
13
  import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
13
14
  import type { DispatchCore } from "./dispatch-core.ts";
14
15
  import { awaitRunResults, WaitSchema } from "./await-results.ts";
15
16
  import { cancelActiveWork, isSettlingThread } from "./cancellation.ts";
16
17
  import { stopThreads } from "./stop.ts";
17
- import { formatCompletionBlock } from "../presentation/format.ts";
18
+ import { formatCompletionBlock, formatExpandedBrief } from "../presentation/format.ts";
18
19
  import { emptyUsage } from "../execution/run-control.ts";
19
20
  import { formatDuration, formatTaskSummary, monitor } from "../presentation/monitor.ts";
20
21
  import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
21
- import { concurrencyAdmissionConflict, projectResultsRoot } from "./thread-shared.ts";
22
+ import { concurrencyAdmissionConflict, dispatchCapacity, projectResultsRoot } from "./thread-shared.ts";
22
23
  import { getResultError } from "../execution/spawn.ts";
23
24
 
24
25
  function renderFirstLine(result: { content?: unknown }, label: string, theme: Theme): Text {
@@ -63,17 +64,18 @@ function buildSummaryFollowUp(thread: SubagentThread, message: string): string {
63
64
  const bounded = prior.length > 4_000 ? prior.slice(0, 4_000) + "\n…(truncated; read the files for detail)" : prior;
64
65
  const files = touchedPaths(thread.lastResult?.messages);
65
66
  return [
66
- `Earlier run #${thread.id} (${thread.agentName}) was briefed with:`,
67
- formatTaskSummary(thread.task, 1_200, false),
67
+ `Current objective for this follow-up to run #${thread.id}:`,
68
+ message,
68
69
  "",
69
- "It finished with:",
70
- bounded,
71
- ...(files.length ? ["", "Files it touched:", files.map((path) => `- ${path}`).join("\n")] : []),
70
+ "Use the earlier findings as evidence. Verify relevant files in the current workspace before editing.",
72
71
  "",
73
- "Continue with this instruction:",
74
- message,
72
+ "Earlier objective:",
73
+ formatTaskSummary(thread.task, 1_200, false),
75
74
  "",
76
- "You did not witness the earlier session. Verify the files before relying on them, and state any assumption this summary does not support.",
75
+ "Earlier result:",
76
+ bounded,
77
+ ...(thread.lastResult?.resultFile ? [`Full result: ${thread.lastResult.resultFile}`] : []),
78
+ ...(files.length ? ["", "Files referenced in earlier tool calls:", ...files.map((path) => `- ${path}`)] : []),
77
79
  ].join("\n");
78
80
  }
79
81
 
@@ -189,7 +191,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
189
191
  pi.registerTool({
190
192
  name: "subagent_message",
191
193
  label: "Subagent Message",
192
- description: "Steer a running subagent, or continue a successfully completed run with a new bounded step in the same role and workspace (within the 5-active-subagent limit). Steering waits for the child's RPC acknowledgement and reports queued or handled by an input hook; receipt is not proof of model execution, and status retains the latest acknowledgement. A continuation chooses its history with the context parameter. Omit wait so main continues disjoint work in parallel without duplicating leased scopes; use wait:true only when no disjoint main work remains (one-shot print/JSON sessions wait by default).",
194
+ description: "Steer a running child or give a completed run its next bounded objective in the same role and workspace. Steering reports the child's acknowledgement. A continuation uses one dispatch slot. Choose its history with context and use the returned run ID for further work.",
193
195
  exposure: "model-only",
194
196
  executionMode: "parallel",
195
197
  parameters: Type.Object({
@@ -226,6 +228,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
226
228
  : "messages require a running or successfully completed run. Results arrive automatically."}`);
227
229
  }
228
230
  if (!dispatchCore) return fail("Follow-up dispatch is unavailable in this process.");
231
+ const task = `Follow-up to run #${thread.id}:\n${params.message}`;
232
+ const duplicate = duplicatePhaseConflict(runtime.threads.values(), task, thread.cwd);
233
+ if (duplicate) return fail(duplicate);
229
234
  const capacityConflict = concurrencyAdmissionConflict(runtime, 1);
230
235
  if (capacityConflict) return fail(`Could not continue #${thread.id}: ${capacityConflict}`);
231
236
  const context = params.context ?? "auto";
@@ -261,13 +266,12 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
261
266
  throw new Error("The source run changed while the follow-up was prepared.");
262
267
  }
263
268
  const selectedContext = copyDir ? "session" : "summary";
264
- const task = copyDir
265
- ? `Follow-up to run #${thread.id}:\n${params.message}`
266
- : buildSummaryFollowUp(thread, params.message);
267
269
  const wait = params.wait ?? (ctx.hasUI === false);
268
270
  const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
269
271
  deliveryRoute: wait ? "await" : "background",
270
- ...(copyDir ? { resumeSession: { sessionId: thread.sessionId!, sessionDir: copyDir } } : {}),
272
+ ...(copyDir
273
+ ? { resumeSession: { sessionId: thread.sessionId!, sessionDir: copyDir } }
274
+ : { stdinText: buildSummaryFollowUp(thread, params.message) }),
271
275
  });
272
276
  if (result.runId === undefined) throw new Error(result.errorMessage || "Follow-up dispatch failed.");
273
277
  copyDir = undefined;
@@ -278,7 +282,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
278
282
  const blocks = await awaitRunResults(runtime, [result.runId], _signal, DEFAULT_MAX_RESULT_LINES, thread.cwd, (text) => {
279
283
  onUpdate?.({ content: [{ type: "text", text }], details });
280
284
  });
281
- if (_signal?.aborted) await cancelActiveWork(runtime, "Parent run was cancelled.");
285
+ if (_signal?.aborted) await cancelActiveWork(runtime, "Parent run was cancelled.", { context: ctx });
282
286
  else runtime.completeAwaitDelivery([result.runId]);
283
287
  const settled = runtime.settledRuns.get(result.runId);
284
288
  return {
@@ -286,16 +290,20 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
286
290
  ...(_signal?.aborted || !settled || isFailedResult(settled) ? { isError: true } : {}),
287
291
  };
288
292
  }
293
+ const { available } = dispatchCapacity(runtime.threads.values());
289
294
  return {
290
- content: [{ type: "text" as const, text: `${receipt} started; results arrive automatically. Do not duplicate its scope; continue disjoint work in main, then use the result to finish the task.` }], details,
295
+ content: [{ type: "text" as const, text: `${receipt} started.\n${formatDispatchSlots(available)} Continue disjoint work until its result arrives.` }], details,
291
296
  };
292
297
  } catch (error) {
293
298
  if (copyDir) await rm(copyDir, { recursive: true, force: true }).catch(() => undefined);
294
299
  return fail(`Could not continue #${thread.id}: ${error instanceof Error ? error.message : String(error)}`);
295
300
  }
296
301
  },
297
- renderCall(args, theme) {
298
- return new Text(`${theme.fg("toolTitle", theme.bold("subagent_message "))}${theme.fg("accent", `#${args.id ?? "?"}`)} ${theme.fg("dim", formatTaskSummary(args.message ?? "", 80, false))}`, 0, 0);
302
+ renderCall(args, theme, { expanded }) {
303
+ const heading = theme.fg("toolTitle", theme.bold("subagent_message ")) + theme.fg("accent", `#${args.id ?? "?"}`);
304
+ const message = typeof args.message === "string" ? args.message : "";
305
+ if (expanded) return new Text(message ? heading + "\n" + formatExpandedBrief(message) : heading, 0, 0);
306
+ return new TruncatedText(heading + " " + theme.fg("dim", formatTaskSummary(message, 80, false)));
299
307
  },
300
308
  renderResult(result, options, theme) {
301
309
  if (options.expanded) return new Text(result.content.map((part) => part.type === "text" ? part.text : "").join("\n"), 0, 0);
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import { readFileSync } from "node:fs";
7
+ import { stripVTControlCharacters } from "node:util";
7
8
  import type { AgentConfig } from "../delegation/agents.ts";
8
9
  import { formatUsageCompact, runLabel, shrinkRunLabel } from "./monitor.ts";
9
10
  import { emptyUsage } from "../execution/run-control.ts";
@@ -62,6 +63,12 @@ export function formatUsage(usage: UsageStats): string {
62
63
  return [turns, formatUsageCompact(usage)].filter(Boolean).join(" ");
63
64
  }
64
65
 
66
+ /** Preserve the brief's paragraphs and indentation when a Pi tool card expands. */
67
+ export function formatExpandedBrief(task: string): string {
68
+ return stripVTControlCharacters(task).replace(/\r\n?/gu, "\n").split("\n")
69
+ .map((line) => line && " " + line).join("\n");
70
+ }
71
+
65
72
  interface CompletionFormatOptions {
66
73
  /** Project-scoped directory the full result is written to when the output
67
74
  * is truncated: <projectRoot>/results. */
@@ -673,20 +673,10 @@ export function statusIcon(status: RunStatus, theme: Theme): string {
673
673
  }
674
674
  }
675
675
 
676
- /** User-facing lifecycle label used by tool/status rendering. */
677
- export function statusLabel(status: RunStatus): string {
678
- switch (status) {
679
- case "queued":
680
- return "starting";
681
- case "running":
682
- return "running";
683
- case "interrupting":
684
- return "interrupting";
685
- case "parked":
686
- return "interrupted";
687
- case "done":
688
- return "done";
689
- case "failed":
690
- return "stopped";
691
- }
676
+ /** The widget and the waiting tool card show the same lifecycle transition. */
677
+ export function statusLabel(run: RunView): string {
678
+ if (run.integrationStatus === "finalizing" && (run.status === "running" || run.status === "queued")) return "applying";
679
+ if (run.status === "queued") return "starting";
680
+ if (run.status === "parked") return "interrupted";
681
+ return run.status;
692
682
  }
@@ -4,7 +4,7 @@ import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
4
4
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
5
5
  import {
6
6
  formatElapsed, formatTaskSummary, formatUsageCompact,
7
- isRunActiveStatus, monitor, statusIcon, type RunView,
7
+ isRunActiveStatus, monitor, statusIcon, statusLabel, type RunView,
8
8
  } from "./monitor.ts";
9
9
 
10
10
  const SUBAGENTS_WIDGET_ID = "pi-subagents";
@@ -20,9 +20,9 @@ function worktreeBadge(run: RunView): string | undefined {
20
20
  }
21
21
 
22
22
  /** Identity owns at least half the row. Drop telemetry before losing it. */
23
- function splitLine(left: string, right: string, theme: Theme, width: number, preserveLeft = false): string {
23
+ function splitLine(left: string, right: string, theme: Theme, width: number): string {
24
24
  const budget = width - visibleWidth(right) - 2;
25
- if (!right || budget < Math.min(28, Math.ceil(width / 2)) || (preserveLeft && visibleWidth(left) > budget)) return truncateToWidth(left, width, "…");
25
+ if (!right || budget < Math.min(28, Math.ceil(width / 2))) return truncateToWidth(left, width, "…");
26
26
  const clipped = truncateToWidth(left, budget, "…");
27
27
  return clipped + " ".repeat(width - visibleWidth(clipped) - visibleWidth(right)) + theme.fg("dim", right);
28
28
  }
@@ -41,9 +41,9 @@ function metadata(run: RunView): string[] {
41
41
  formatUsageCompact(run.usage), worktreeBadge(run)].filter((part): part is string => Boolean(part));
42
42
  }
43
43
 
44
- function detailLine(activity: string | undefined, run: RunView | undefined, theme: Theme, width: number): string | undefined {
45
- const parts = activity ? ["↳ " + formatTaskSummary(activity, Math.max(1, width - 6), false)] : [];
46
- for (const part of run ? metadata(run) : []) {
44
+ function detailLine(run: RunView, theme: Theme, width: number): string | undefined {
45
+ const parts = run.activity ? ["↳ " + formatTaskSummary(run.activity, Math.max(1, width - 6), false)] : [];
46
+ for (const part of metadata(run)) {
47
47
  if (visibleWidth([...parts, part].join(SEPARATOR)) > width - 4) break;
48
48
  parts.push(part);
49
49
  }
@@ -51,17 +51,17 @@ function detailLine(activity: string | undefined, run: RunView | undefined, them
51
51
  }
52
52
 
53
53
  function runRow(run: RunView, theme: Theme, width: number, now: number): TaskRow {
54
- const state = run.status === "queued" ? "starting" : run.integrationStatus === "finalizing" ? "applying" : run.status;
54
+ const state = statusLabel(run);
55
55
  const label = run.label ?? formatTaskSummary(run.task, Math.max(1, width - 18));
56
- const narrowState = width < 60 && (run.status === "queued" || run.integrationStatus === "finalizing") ? " · " + state : "";
57
- const identity = statusIcon(run.status, theme) + " " + theme.fg("dim", "#" + run.id) + " " + run.agent + narrowState + " · " + label;
56
+ const narrowState = width < 60 && state !== "running" ? " · " + state : "";
57
+ const identity = statusIcon(state === "applying" ? "running" : run.status, theme) + " " + theme.fg("dim", "#" + run.id) + " " + run.agent + narrowState + " · " + label;
58
58
  const elapsed = formatElapsed(run, now);
59
59
  const primary = splitLine(identity, width >= 60 ? [state, elapsed].filter(Boolean).join(SEPARATOR) : elapsed, theme, width);
60
60
  return {
61
- primary, detail: detailLine(run.activity, run, theme, width),
61
+ primary, detail: detailLine(run, theme, width),
62
62
  requiredDetail: run.status === "failed" && Boolean(run.activity),
63
63
  priority: run.status === "failed" ? 0 : run.status === "interrupting" ? 1 : run.status === "running" ? 2 : 3,
64
- state: run.status,
64
+ state,
65
65
  };
66
66
  }
67
67
 
@@ -106,8 +106,8 @@ export function formatSubagentWidgetLines(
106
106
  const rows = visible.map((run) => runRow(run, theme, width, now));
107
107
  const states = new Map<string, number>();
108
108
  for (const row of rows) states.set(row.state, (states.get(row.state) ?? 0) + 1);
109
- const counts = ["failed", "interrupting", "running", "queued"]
110
- .filter((state) => states.has(state)).map((state) => states.get(state) + " " + (state === "queued" ? "starting" : state));
109
+ const counts = ["failed", "interrupting", "running", "applying", "starting"]
110
+ .filter((state) => states.has(state)).map((state) => states.get(state) + " " + state);
111
111
  const overview = theme.bold("Subagents") + theme.fg("dim", " " + counts.join(SEPARATOR));
112
112
  return renderBoard(rows, theme, width, overview);
113
113
  }