@ferris1225/pi-subagents 7.0.6 → 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,16 @@
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
+
3
14
  ## 7.0.6
4
15
 
5
16
  - Show Escape cancellation progress and per-run statistics in the terminal before
package/README.md CHANGED
@@ -131,9 +131,10 @@ by the extension. No automatic review score certifies a worker's result.
131
131
 
132
132
  ## Briefs and calls
133
133
 
134
- A useful brief names the **outcome**, **acceptance criteria**, **relevant paths and
135
- evidence**, **write boundary**, **checks**, **return conditions**, and **expected
136
- 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.
137
138
 
138
139
  ```ts
139
140
  subagent({
@@ -157,8 +158,11 @@ that directory. Top-level `isolation` is the default for tasks that omit their
157
158
  own. Duplicate normalized tasks in the same directory are rejected while an
158
159
  active or settled run owns them. Use its result or continue it with `subagent_message`.
159
160
 
160
- A batch receipt lists the accepted run IDs and any tasks that failed to start.
161
- 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.
162
166
 
163
167
  Leave `wait` omitted (`false` in TUI/RPC) by default so subagents run in the
164
168
  background while main immediately continues its own disjoint work in parallel.
@@ -169,9 +173,11 @@ until background results wake it automatically.
169
173
  Results are delivered once, after integration. Awaited failures are tool errors.
170
174
  Answers exceeding 40 lines or 8,000 characters link their full-result artifact.
171
175
  The terminal card shows live progress for awaited runs, including worktree
172
- integration, and gives each accepted run its own status row. Expand the tool
173
- output with Ctrl+O in Pi's default keybindings to read the result and recovery
174
- 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.
175
181
 
176
182
  | Tool | Purpose |
177
183
  | --- | --- |
@@ -183,8 +189,10 @@ details.
183
189
 
184
190
  Follow-ups use `context: "auto"` by default: a private copy of the retained session,
185
191
  or an explicit summary fallback when it expired. `context: "session"` requires full
186
- history. Continuations retain the session ID/cache key and re-read files in their
187
- 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.
188
196
 
189
197
  Steering waits for a matching RPC acknowledgement. Received/queued means Pi queued
190
198
  the instruction, not that the model acted on it. A rejected or missing
@@ -216,8 +224,9 @@ new/resume/fork/reload, and shutdown stop old work and retain interrupted eviden
216
224
  for recovery.
217
225
 
218
226
  The task widget shows status, elapsed time, model, thinking, tokens, and worktree
219
- state in at most ten lines. Independent workers can start together; only
220
- 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.
221
230
 
222
231
  ## Pi integration
223
232
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ferris1225/pi-subagents",
3
- "version": "7.0.6",
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",
@@ -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,7 +231,7 @@ 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);
@@ -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,7 +170,7 @@ 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 = [
@@ -182,9 +201,12 @@ function buildStableDelegationSection(agents: AgentConfig[], includeEmptyCatalog
182
201
  /** Bounded ownership reminder; settled results remain reusable after compaction. */
183
202
  function buildActiveLeaseSection(sources: Iterable<PhaseLeaseSource>): string {
184
203
  const all = [...sources];
185
- const activeLeases = formatActivePhaseLeases(all);
204
+ const { activeIds, available } = dispatchCapacity(all);
205
+ const activeLeases = formatActivePhaseLeases(all, activeIds);
186
206
  const recent = all.filter(isSettledLease).slice(-MAX_RECENT_SETTLED_LEASES).map(leaseLine).join("\n");
207
+ if (!activeLeases && !recent) return "";
187
208
  return [
209
+ formatDispatchSlots(available),
188
210
  ...(activeLeases ? [`Active phase leases:\n${activeLeases}`] : []),
189
211
  ...(recent ? [`Recent settled phases — reuse results via subagent_status; continue only unfinished work:\n${recent}`] : []),
190
212
  ].join("\n");
@@ -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
@@ -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}`);
@@ -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,
@@ -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;
@@ -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
  }