@ferris1225/pi-subagents 5.0.6 → 6.0.1

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +187 -97
  3. package/index.ts +1 -1
  4. package/package.json +4 -9
  5. package/src/configuration/role-migration.ts +2 -2
  6. package/src/configuration/setup.ts +4 -2
  7. package/src/configuration/ui.ts +144 -132
  8. package/src/delegation/agents.ts +15 -22
  9. package/src/delegation/dispatch.ts +17 -122
  10. package/src/delegation/prompt.ts +13 -12
  11. package/src/execution/cli-run.ts +112 -39
  12. package/src/execution/process-tree.ts +12 -8
  13. package/src/execution/run-control.ts +11 -3
  14. package/src/execution/spawn.ts +24 -7
  15. package/src/isolation/cleanup.ts +31 -12
  16. package/src/isolation/managed-paths.ts +6 -4
  17. package/src/isolation/manifest-mutation.ts +89 -0
  18. package/src/isolation/recovery.ts +33 -29
  19. package/src/isolation/temp-hygiene.ts +1 -1
  20. package/src/lifecycle/await-results.ts +114 -0
  21. package/src/lifecycle/dispatch-core.ts +7 -1
  22. package/src/lifecycle/durable.ts +83 -39
  23. package/src/lifecycle/runtime.ts +12 -4
  24. package/src/lifecycle/stop.ts +2 -2
  25. package/src/lifecycle/thread-lifecycle.ts +10 -5
  26. package/src/lifecycle/thread-restore.ts +26 -25
  27. package/src/lifecycle/thread-shared.ts +15 -3
  28. package/src/lifecycle/tools.ts +90 -33
  29. package/src/presentation/announcements.ts +8 -2
  30. package/src/presentation/monitor.ts +5 -3
  31. package/src/presentation/widget.ts +157 -113
  32. package/src/workflow/acceptance.ts +67 -0
  33. package/src/workflow/durable.ts +34 -14
  34. package/src/workflow/engine.ts +161 -51
  35. package/src/workflow/plan.ts +25 -4
  36. package/src/workflow/state.ts +6 -0
  37. package/src/workflow/templates.ts +156 -0
  38. package/src/workflow/tool.ts +65 -109
  39. package/skills/workflow/SKILL.md +0 -268
  40. package/src/workflow/files.ts +0 -236
  41. package/workflows/code-review.md +0 -38
  42. package/workflows/migration.md +0 -42
  43. package/workflows/research.md +0 -48
@@ -1,17 +1,19 @@
1
- /** Read-only run inspection and destructive cancellation of one-shot runs. */
1
+ /** Run inspection, steering, completed-run follow-ups, and destructive cancellation. */
2
2
 
3
3
  import { randomUUID } from "node:crypto";
4
- import { copyFile, mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
5
- import { join } from "node:path";
4
+ import { copyFile, mkdir, mkdtemp, rm } from "node:fs/promises";
5
+ import { basename, join } from "node:path";
6
6
  import type { Message } from "@earendil-works/pi-ai";
7
7
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
8
  import { Text } from "@earendil-works/pi-tui";
9
9
  import { Type } from "typebox";
10
10
  import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
11
11
  import { loadBuiltinAgents } from "../delegation/agents.ts";
12
- import { getProjectRoot, getResultOutput, sessionExists } from "../execution/spawn.ts";
12
+ import { findSessionFile, getProjectRoot, getResultOutput, isFailedResult, sessionExists } from "../execution/spawn.ts";
13
13
  import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
14
14
  import type { DispatchCore } from "./dispatch-core.ts";
15
+ import { awaitRunResults, WaitSchema } from "./await-results.ts";
16
+ import { cancelActiveWork } from "./cancellation.ts";
15
17
  import { stopThreads } from "./stop.ts";
16
18
  import { formatCompletionBlock, matchRunIds } from "../presentation/format.ts";
17
19
  import { emptyUsage } from "../execution/run-control.ts";
@@ -124,6 +126,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
124
126
  waitReason: state === "queued" ? live?.waitReason : undefined,
125
127
  activity: live?.activity,
126
128
  recentActivity: live?.recentActivity ?? [],
129
+ lastSteering: thread.lastSteering,
127
130
  elapsedMs: monitor.getElapsedMs(thread.id) ?? thread.elapsedMs,
128
131
  model: live?.model ?? result?.model,
129
132
  thinking: live?.thinking ?? result?.thinking ?? thread.thinkingLevel,
@@ -133,6 +136,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
133
136
  errorMessage: result ? getResultError(result) : state === "failed" ? "No failure reason was recorded." : undefined,
134
137
  resultFile: result?.resultFile,
135
138
  sessionDir: thread.retired ? undefined : thread.sessionDir ?? result?.sessionDir,
139
+ followUpContext: state === "completed"
140
+ ? thread.sessionDir && thread.sessionId && sessionExists(thread.sessionDir, thread.sessionId) ? "session" : "summary"
141
+ : undefined,
136
142
  isolation: thread.isolation,
137
143
  isolationNote: result?.isolationNote,
138
144
  integrationStatus: live?.integrationStatus ?? result?.integrationStatus ?? thread.worktree?.state,
@@ -149,6 +155,8 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
149
155
  if (run.phaseId) lines.push(` phase: ${run.phaseId}`);
150
156
  if (run.scope) lines.push(` scope: ${JSON.stringify(run.scope)}`);
151
157
  if (run.isolationNote) lines.push(` isolation: ${run.isolationNote}`);
158
+ if (run.lastSteering) lines.push(` last steering: ${run.lastSteering.disposition} · acknowledged ${formatDuration(Math.max(0, Date.now() - run.lastSteering.acknowledgedAt))} ago${run.lastSteering.requestId ? ` · request ${run.lastSteering.requestId}` : ""} · ${run.lastSteering.message}`);
159
+ if (run.followUpContext) lines.push(` follow-up: ${run.followUpContext}${run.followUpContext === "summary" ? " (retained session unavailable)" : " available"}`);
152
160
  // The trail is the progress answer: what the run has been doing,
153
161
  // newest last. It replaces pointing the parent at child session
154
162
  // files, which it cannot usefully read mid-run.
@@ -216,65 +224,114 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
216
224
  pi.registerTool({
217
225
  name: "subagent_message",
218
226
  label: "Subagent Message",
219
- description: "Send a steering message to a running subagent, or continue a completed run. Use context \"session\" (default) to redo or revise the same work: it continues a private copy of the retained session, so earlier reasoning and the provider prompt-cache key survive. Use context \"summary\" for a new next step: it starts fresh with a bounded summary (objective, result, touched files) instead of loading the old transcript. Running messages are queued by Pi and acknowledged, not guaranteed to have been acted on yet.",
227
+ description: "Send a steering message to a running subagent, or continue a successfully completed run. Omit context or use \"auto\" to reuse its retained session when available and otherwise start from a bounded summary, reporting the fallback. Use \"session\" only when full history is required; missing history is an error. Use \"summary\" for a new next step with only the earlier objective, result, and touched files. Session copies preserve history and the provider cache key; summary runs have neither. Use wait:true to receive a completed-run follow-up in this call; one-shot print/JSON sessions wait by default. Steering waits for the child RPC acknowledgement and reports queued, handled by an input hook, or accepted with queue state unknown. Receipt is not proof of model execution; status retains the latest acknowledgement.",
220
228
  exposure: "model-only",
221
- executionMode: "sequential",
229
+ executionMode: "parallel",
222
230
  parameters: Type.Object({
223
231
  id: Type.Integer({ minimum: 1, description: "Exact run id in this parent session." }),
224
232
  message: Type.String({ minLength: 1, pattern: "\\S", description: "Additional instruction or follow-up question." }),
225
- context: Type.Optional(Type.String({ enum: ["session", "summary"], description: "session (default) continues the retained session, preserving its history and provider prompt-cache key. summary starts a fresh run briefed with a bounded summary of the earlier work: cheaper context, no cache reuse, and no access to details the summary omits." })),
233
+ context: Type.Optional(Type.String({ enum: ["auto", "session", "summary"], description: "auto (default) uses the retained session when available, otherwise a bounded summary and reports the fallback. session requires the full retained history and fails if unavailable. summary always starts fresh with the earlier objective, result, and touched files; no history or cache reuse." })),
234
+ wait: WaitSchema,
226
235
  }),
227
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
236
+ async execute(_toolCallId, params, _signal, onUpdate, ctx) {
228
237
  await runtime.durableRestore;
229
238
  const thread = runtime.threads.get(params.id);
230
239
  const fail = (message: string) => ({ content: [{ type: "text" as const, text: message }], details: {}, isError: true });
240
+ if (_signal?.aborted) return fail("Subagent message cancelled before delivery.");
231
241
  if (!thread || thread.retired) return fail(`No available run matches #${params.id} in this session.`);
232
242
  if (thread.state === "running" && !thread.lifecycleOperation) {
233
243
  try {
234
- await thread.control.steer(params.message);
235
- return { content: [{ type: "text" as const, text: `Steering queued for #${thread.id}; it has not necessarily been acted on yet.` }], details: { id: thread.id } };
236
- } catch (error) { return fail(`Could not send to #${thread.id}: ${error instanceof Error ? error.message : String(error)}`); }
244
+ const receipt = await thread.control.steer(params.message);
245
+ thread.lastSteering = { ...receipt, message: formatTaskSummary(params.message, 160, false) };
246
+ const status = receipt.disposition === "queued"
247
+ ? `Received by #${thread.id} · queued for the next steering boundary. Model execution is not yet confirmed.`
248
+ : receipt.disposition === "handled"
249
+ ? `Received by #${thread.id} · handled by an input hook. Delivery to the model is not confirmed.`
250
+ : `Accepted by #${thread.id} · queue state unconfirmed. Model execution is not yet confirmed.`;
251
+ monitor.setActivity(thread.id, `steering ${receipt.disposition}`);
252
+ return {
253
+ content: [{ type: "text" as const, text: `${status}${receipt.requestId ? `\nChild RPC acknowledgement: ${receipt.requestId}` : ""}` }],
254
+ details: { id: thread.id, steering: thread.lastSteering },
255
+ };
256
+ } catch (error) { return fail(`Steering to #${thread.id} was not confirmed: ${error instanceof Error ? error.message : String(error)}`); }
237
257
  }
238
258
  if (thread.state !== "completed" || thread.lifecycleOperation) {
239
- return fail(`Run #${thread.id} is ${thread.state}; wait for a running or successfully completed run.`);
259
+ const state = thread.state === "parked" ? "interrupted" : thread.state;
260
+ const terminal = !thread.lifecycleOperation && ["parked", "failed", "stopped"].includes(thread.state);
261
+ return fail(`Run #${thread.id} is ${state}; ${terminal
262
+ ? "inspect retained results with subagent_status and handle unfinished work in main. This run cannot be continued with subagent_message."
263
+ : "messages require a running or successfully completed run. Results arrive automatically."}`);
240
264
  }
241
265
  if (!dispatchCore) return fail("Follow-up dispatch is unavailable in this process.");
242
- const useSummary = params.context === "summary";
243
- if (!useSummary && (!thread.sessionDir || !thread.sessionId || !sessionExists(thread.sessionDir, thread.sessionId))) {
244
- return fail(`Run #${thread.id} has no available session to continue; retry with context: "summary".`);
266
+ const context = params.context ?? "auto";
267
+ const sourceFile = context !== "summary" && thread.sessionDir && thread.sessionId
268
+ ? findSessionFile(thread.sessionDir, thread.sessionId) : undefined;
269
+ if (context === "session" && !sourceFile) {
270
+ return fail(`Run #${thread.id} has no available session to continue; use context: "auto" or "summary" for a bounded summary without the earlier history.`);
245
271
  }
272
+ let fallbackReason = context === "auto" && !sourceFile ? "Retained session is unavailable." : undefined;
246
273
  let copyDir: string | undefined;
247
274
  try {
248
275
  dispatchCore.setEnvironment({ ctx, config: await loadConfig(runtime.configPath), agents: loadBuiltinAgents() });
249
- if (useSummary) {
250
- const task = buildSummaryFollowUp(thread, params.message);
251
- const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
252
- phaseId: `followup:${thread.id}:${randomUUID()}`, scope: thread.scope,
253
- });
254
- if (result.runId === undefined) throw new Error(result.errorMessage || "Follow-up dispatch failed.");
255
- return { content: [{ type: "text" as const, text: `Started follow-up #${result.runId} from #${thread.id} with a summary only; results arrive automatically.` }], details: { id: result.runId, sourceId: thread.id } };
276
+ if (sourceFile) {
277
+ const root = join(getProjectRoot(runtime.configPath, thread.cwd), "sessions");
278
+ await mkdir(root, { recursive: true });
279
+ copyDir = await mkdtemp(join(root, "pi-subagent-session-"));
280
+ writeTempOwnerMarker(copyDir);
281
+ try {
282
+ await copyFile(sourceFile, join(copyDir, basename(sourceFile)));
283
+ } catch (error) {
284
+ const code = (error as NodeJS.ErrnoException).code;
285
+ if (context !== "auto" || (code !== "ENOENT" && code !== "ENOTDIR")) throw error;
286
+ await rm(copyDir, { recursive: true, force: true });
287
+ copyDir = undefined;
288
+ fallbackReason = "Retained session became unavailable before it could be copied.";
289
+ }
256
290
  }
257
- const root = join(getProjectRoot(runtime.configPath, thread.cwd), "sessions");
258
- await mkdir(root, { recursive: true });
259
- copyDir = await mkdtemp(join(root, "pi-subagent-session-"));
260
- writeTempOwnerMarker(copyDir);
261
- const file = (await readdir(thread.sessionDir!)).find((name) => name.endsWith(`_${thread.sessionId}.jsonl`));
262
- if (!file) throw new Error("The retained session file is missing; retry with context: \"summary\".");
263
- await copyFile(join(thread.sessionDir!, file), join(copyDir, file));
264
- if (thread.retired || thread.lifecycleOperation || thread.state !== "completed") throw new Error("The source run changed while its session was copied.");
265
- const task = `Follow-up to run #${thread.id} (${randomUUID()}):\n${params.message}`;
291
+ if (_signal?.aborted) throw new Error("Follow-up cancelled before dispatch.");
292
+ if (thread.retired || thread.lifecycleOperation || thread.state !== "completed") throw new Error("The source run changed while the follow-up was prepared.");
293
+ const selectedContext = copyDir ? "session" : "summary";
294
+ const task = copyDir
295
+ ? `Follow-up to run #${thread.id} (${randomUUID()}):\n${params.message}`
296
+ : buildSummaryFollowUp(thread, params.message);
297
+ const wait = params.wait ?? (ctx.hasUI === false);
266
298
  const result = await dispatchCore.startBackground(thread.agentName, task, thread.cwd, thread.isolation, {
267
299
  phaseId: `followup:${thread.id}:${randomUUID()}`, scope: thread.scope,
268
- resumeSession: { sessionId: thread.sessionId!, sessionDir: copyDir },
300
+ deliveryRoute: wait ? "await" : "background",
301
+ ...(copyDir ? { resumeSession: { sessionId: thread.sessionId!, sessionDir: copyDir } } : {}),
269
302
  });
270
303
  if (result.runId === undefined) throw new Error(result.errorMessage || "Follow-up dispatch failed.");
271
304
  copyDir = undefined;
272
- return { content: [{ type: "text" as const, text: `Started follow-up #${result.runId} from #${thread.id} with its retained session; results arrive automatically.` }], details: { id: result.runId, sourceId: thread.id } };
305
+ const contextNote = selectedContext === "session" ? "its retained session" : "a summary only";
306
+ const receipt = `Follow-up #${result.runId} from #${thread.id} with ${contextNote}${fallbackReason ? ` (${fallbackReason})` : ""}`;
307
+ const details = { id: result.runId, sourceId: thread.id, context: selectedContext, ...(fallbackReason ? { fallbackReason } : {}) };
308
+ if (wait) {
309
+ const blocks = await awaitRunResults(runtime, [result.runId], _signal, DEFAULT_MAX_RESULT_LINES, thread.cwd, (text) => {
310
+ onUpdate?.({ content: [{ type: "text", text }], details });
311
+ });
312
+ if (_signal?.aborted) await cancelActiveWork(runtime, "Parent run was cancelled.");
313
+ else runtime.completeAwaitDelivery([result.runId]);
314
+ const settled = runtime.settledRuns.get(result.runId);
315
+ return {
316
+ content: [{ type: "text" as const, text: `${receipt}\n\n${blocks}` }], details,
317
+ ...(_signal?.aborted || !settled || isFailedResult(settled) ? { isError: true } : {}),
318
+ };
319
+ }
320
+ return {
321
+ content: [{ type: "text" as const, text: `${receipt} started; results arrive automatically. Continue independent work, then use the result to finish the task.` }], details,
322
+ };
273
323
  } catch (error) {
274
324
  if (copyDir) await rm(copyDir, { recursive: true, force: true }).catch(() => undefined);
275
325
  return fail(`Could not continue #${thread.id}: ${error instanceof Error ? error.message : String(error)}`);
276
326
  }
277
327
  },
328
+ renderCall(args, theme) {
329
+ 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);
330
+ },
331
+ renderResult(result, options, theme) {
332
+ if (options.expanded) return new Text(result.content.map((part) => part.type === "text" ? part.text : "").join("\n"), 0, 0);
333
+ return renderFirstLine(result, "subagent_message ", theme);
334
+ },
278
335
  });
279
336
 
280
337
  // Cancel one or more active runs: aborts the queue controller, which
@@ -35,8 +35,14 @@ async function removeUnavailableAgentModels(
35
35
  export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime): void {
36
36
  pi.on("session_start", async (_event, ctx) => {
37
37
  await ensureDefaultConfig(ctx, runtime.configPath);
38
- await relocateRecoveryManifest(runtime.configPath);
39
- await announceRecoveryRecords(runtime.configPath, ctx);
38
+ try {
39
+ await relocateRecoveryManifest(runtime.configPath);
40
+ await announceRecoveryRecords(runtime.configPath, ctx);
41
+ } catch (error) {
42
+ // Recovery readers must fail closed for cleanup, but a failed notice
43
+ // must not prevent the rest of the session UI from being installed.
44
+ ctx.ui.notify(`pi-subagents: recovery inspection failed; continuing startup: ${error instanceof Error ? error.message : String(error)}`, "warning");
45
+ }
40
46
  await removeUnavailableAgentModels(ctx, runtime);
41
47
  // Bootstrap also runs on session_start; wait so this notice sees restored
42
48
  // threads instead of racing an empty list.
@@ -193,8 +193,9 @@ function tailGraphemes(segments: string[], maxWidth: number): string {
193
193
  * Grapheme-safe — CJK, ZWJ emoji and combining sequences are never split.
194
194
  */
195
195
  export function formatTaskSummary(task: string, maxWidth: number = TASK_SUMMARY_MAX, keysOnly = true): string {
196
+ if (maxWidth <= 0) return "";
196
197
  const oneLine = stripVTControlCharacters(task).replace(/\s+/g, " ").trim();
197
- if (maxWidth <= 0 || visibleWidth(oneLine) <= maxWidth) return oneLine;
198
+ if (visibleWidth(oneLine) <= maxWidth) return oneLine;
198
199
 
199
200
  const segments = [...graphemeSegmenter.segment(oneLine)].map((s) => s.segment);
200
201
  const ellipsisWidth = visibleWidth(TASK_SUMMARY_ELLIPSIS);
@@ -248,9 +249,10 @@ const RUN_LABEL_MAX = 32;
248
249
  * head slice of its prose. Grapheme-safe.
249
250
  */
250
251
  export function runLabel(task: string): string {
251
- const fragments = extractKeyFragments(task);
252
+ const oneLine = stripVTControlCharacters(task).replace(/\s+/g, " ").trim();
253
+ const fragments = extractKeyFragments(oneLine);
252
254
  const fragment = fragments.find((candidate) => /[\\/]|\.[A-Za-z0-9]{1,5}$/.test(candidate)) ?? fragments[0];
253
- const src = fragment ?? stripVTControlCharacters(task).replace(/\s+/g, " ").trim();
255
+ const src = fragment ?? oneLine;
254
256
  if (visibleWidth(src) <= RUN_LABEL_MAX) return src;
255
257
  const chars = [...graphemeSegmenter.segment(src)].map((s) => s.segment);
256
258
  // A path/symbol fragment keeps its tail (filename/symbol is recognisable);
@@ -1,4 +1,4 @@
1
- /** A compact task board: overview, workflow groups, then actionable run rows. */
1
+ /** A bounded operations ledger: failures, live work, then dependency waits. */
2
2
 
3
3
  import type { WorkflowRun, WorkflowNodeRun } from "../workflow/state.ts";
4
4
  import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
@@ -12,6 +12,10 @@ const SUBAGENTS_WIDGET_ID = "pi-subagents";
12
12
  const MAX_WIDGET_LINES = 10;
13
13
  const SEPARATOR = " · ";
14
14
 
15
+ function isAcceptance(node: WorkflowNodeRun): boolean {
16
+ return "kind" in node && node.kind === "acceptance";
17
+ }
18
+
15
19
  function waitWord(run: Pick<RunView, "waitReason">): string {
16
20
  return run.waitReason === "starting" ? "starting" : "queued";
17
21
  }
@@ -24,11 +28,10 @@ function worktreeBadge(run: RunView): string | undefined {
24
28
  return "worktree:" + (run.worktreeId ?? "?") + (suffix ? " " + suffix : "");
25
29
  }
26
30
 
27
- /** Reserve the right edge for progress/time before truncating the task name. */
31
+ /** Identity owns at least half the row. Drop telemetry before losing it. */
28
32
  function splitLine(left: string, right: string, theme: Theme, width: number): string {
29
- if (!right) return truncateToWidth(left, width, "…");
30
33
  const budget = width - visibleWidth(right) - 2;
31
- if (budget < 1) return truncateToWidth(theme.fg("dim", right), width, "…");
34
+ if (!right || budget < Math.min(28, Math.ceil(width / 2))) return truncateToWidth(left, width, "…");
32
35
  const clipped = truncateToWidth(left, budget, "…");
33
36
  return clipped + " ".repeat(width - visibleWidth(clipped) - visibleWidth(right)) + theme.fg("dim", right);
34
37
  }
@@ -36,13 +39,15 @@ function splitLine(left: string, right: string, theme: Theme, width: number): st
36
39
  interface TaskRow {
37
40
  primary: string;
38
41
  detail?: string;
39
- /** Errors first, then active work, queue/dependency waits, then settled. */
42
+ /** A failure or an acceptance wait must carry its explanation. */
43
+ requiredDetail?: boolean;
40
44
  priority: number;
41
45
  state: string;
42
46
  }
43
47
  interface TaskGroup {
44
48
  header?: string;
45
49
  rows: TaskRow[];
50
+ acceptance?: TaskRow;
46
51
  priority: number;
47
52
  }
48
53
 
@@ -51,64 +56,78 @@ function metadata(run: RunView): string[] {
51
56
  formatUsageCompact(run.usage), worktreeBadge(run)].filter((part): part is string => Boolean(part));
52
57
  }
53
58
 
59
+ function detailLine(activity: string | undefined, run: RunView | undefined, theme: Theme, width: number): string | undefined {
60
+ const parts = activity ? ["↳ " + formatTaskSummary(activity, Math.max(1, width - 6), false)] : [];
61
+ for (const part of run ? metadata(run) : []) {
62
+ if (visibleWidth([...parts, part].join(SEPARATOR)) > width - 4) break;
63
+ parts.push(part);
64
+ }
65
+ return parts.length ? theme.fg("dim", " " + parts.join(SEPARATOR)) : undefined;
66
+ }
67
+
54
68
  function runRow(run: RunView, theme: Theme, width: number, now: number): TaskRow {
55
69
  const state = run.status === "queued" ? waitWord(run) : run.integrationStatus === "finalizing" ? "applying" : run.status;
56
- const label = run.label ?? formatTaskSummary(run.task, 48);
57
- const identity = statusIcon(run.status, theme) + " " + theme.fg("dim", "#" + run.id) + " " + theme.fg("accent", run.agent);
58
- const primary = splitLine(identity + " " + label, [state, formatElapsed(run, now)].filter(Boolean).join(SEPARATOR), theme, width);
59
- const activity = run.activity ? truncateToWidth("↳ " + formatTaskSummary(run.activity, Math.max(8, width - 6)), Math.max(0, width - 4), "…") : "";
60
- const parts = metadata(run);
61
- // Keep current activity readable; reveal model, reasoning, usage and isolation
62
- // as space allows, rather than shrinking the task to make telemetry fit.
63
- const budget = width - 4 - visibleWidth(activity) - (activity ? visibleWidth(SEPARATOR) : 0);
64
- while (parts.length && visibleWidth(parts.join(SEPARATOR)) > budget) parts.pop();
65
- const detail = activity || parts.length ? " " + [activity, ...parts].filter(Boolean).join(SEPARATOR) : undefined;
66
- return { primary, detail: detail ? theme.fg("dim", truncateToWidth(detail, width, "…")) : undefined,
67
- priority: run.status === "failed" ? 0 : run.status === "interrupting" ? 1 : run.status === "running" ? 2 : 3, state: run.status };
68
- }
69
-
70
- /** Budget task identities before optional detail lines, so a busy run cannot
71
- * hide a sibling. Error groups and error rows win when the board overflows. */
70
+ const label = run.label ?? formatTaskSummary(run.task, Math.max(1, width - 18));
71
+ const narrowState = width < 60 && run.status === "queued" ? " · " + state : "";
72
+ const identity = statusIcon(run.status, theme) + " " + theme.fg("dim", "#" + run.id) + " " + run.agent + narrowState + " · " + label;
73
+ const elapsed = formatElapsed(run, now);
74
+ const primary = splitLine(identity, width >= 60 ? [state, elapsed].filter(Boolean).join(SEPARATOR) : elapsed, theme, width);
75
+ return {
76
+ primary, detail: detailLine(run.activity, run, theme, width),
77
+ requiredDetail: run.status === "failed" && Boolean(run.activity),
78
+ priority: run.status === "failed" ? 0 : run.status === "interrupting" ? 1 : run.status === "running" ? 2 : 3,
79
+ state: run.status,
80
+ };
81
+ }
82
+
83
+ function rowCost(row: TaskRow): number { return 1 + Number(Boolean(row.requiredDetail && row.detail)); }
84
+
85
+ /** Select identities before optional details, including the cost of each graph's
86
+ * heading and required acceptance status. Overflow describes only hidden work. */
72
87
  function renderBoard(groups: TaskGroup[], theme: Theme, width: number, overview?: string): string[] {
73
88
  if (width <= 0 || !groups.length) return [];
74
89
  const sorted = [...groups].sort((a, b) => a.priority - b.priority);
75
- const lines: string[] = overview ? [overview] : [];
76
- const allRows = sorted.flatMap((group) => group.rows);
77
- const headers = sorted.filter((group) => group.header).length;
78
- const needsOverflow = lines.length + headers + allRows.length > MAX_WIDGET_LINES;
79
- const capacity = MAX_WIDGET_LINES - lines.length - (needsOverflow ? 1 : 0);
80
- // Select across groups before rendering, reserving one header per visible graph.
90
+ const totalCost = sorted.reduce((sum, group) => sum + Number(Boolean(group.header))
91
+ + (group.acceptance ? rowCost(group.acceptance) : 0) + group.rows.reduce((cost, row) => cost + rowCost(row), 0), 0);
92
+ const lines = overview ? [overview] : [];
93
+ const capacity = MAX_WIDGET_LINES - lines.length - Number(totalCost + lines.length > MAX_WIDGET_LINES);
81
94
  const selected = new Set<TaskRow>();
82
95
  const included = new Set<TaskGroup>();
83
96
  let used = 0;
84
- const candidates = sorted.flatMap((group) => [...group.rows].sort((a, b) => a.priority - b.priority)
85
- .map((row, index) => ({ group, row, index })));
86
- candidates.sort((a, b) => a.row.priority - b.row.priority || a.index - b.index);
97
+ const candidates: { group: TaskGroup; row?: TaskRow; index: number; priority: number }[] = sorted.flatMap((group) => [
98
+ ...group.rows.map((row, index) => ({ group, row, index, priority: row.priority })),
99
+ ...(group.acceptance || !group.rows.length ? [{ group, index: 0, priority: group.acceptance?.priority ?? group.priority }] : []),
100
+ ]);
101
+ candidates.sort((a, b) => a.priority - b.priority || a.index - b.index);
87
102
  for (const { group, row } of candidates) {
88
- const cost = 1 + (!included.has(group) && group.header ? 1 : 0);
103
+ const overhead = included.has(group) ? 0 : Number(Boolean(group.header)) + (group.acceptance ? rowCost(group.acceptance) : 0);
104
+ const cost = overhead + (row ? rowCost(row) : 0);
89
105
  if (used + cost > capacity) continue;
90
106
  included.add(group);
91
- selected.add(row);
107
+ if (row) selected.add(row);
92
108
  used += cost;
93
109
  }
94
- // Keep graph status visible even when no actionable node rows remain.
95
- for (const group of sorted) {
96
- if (!group.rows.length && group.header && used < capacity) { included.add(group); used++; }
97
- }
98
110
  let detailBudget = capacity - used;
99
111
  for (const group of sorted) {
100
112
  if (!included.has(group)) continue;
101
113
  if (group.header) lines.push(group.header);
102
- for (const row of [...group.rows].sort((a, b) => a.priority - b.priority)) {
103
- if (!selected.has(row)) continue;
114
+ const rows = [...group.rows.filter((row) => selected.has(row)), ...(group.acceptance ? [group.acceptance] : [])]
115
+ .sort((a, b) => a.priority - b.priority);
116
+ for (const row of rows) {
104
117
  lines.push(row.primary);
105
- if (row.detail && detailBudget > 0) { lines.push(row.detail); detailBudget--; }
118
+ if (row.detail && (row.requiredDetail || detailBudget > 0)) {
119
+ lines.push(row.detail);
120
+ if (!row.requiredDetail) detailBudget--;
121
+ }
106
122
  }
107
123
  }
108
- const hiddenTasks = allRows.length - selected.size;
109
- const hiddenGroups = sorted.filter((group) => !included.has(group)).length;
110
- if (hiddenTasks || hiddenGroups) lines.push(theme.fg("dim", "… +" + hiddenTasks + " tasks" + (hiddenGroups ? " · " + hiddenGroups + " groups hidden" : "")));
111
- return lines.slice(0, MAX_WIDGET_LINES).map((line) => truncateToWidth(line, width, "…"));
124
+ const hiddenTasks = sorted.reduce((sum, group) => sum + group.rows.length, 0) - selected.size;
125
+ const hiddenGraphs = sorted.filter((group) => group.header && !included.has(group)).length;
126
+ if (hiddenTasks || hiddenGraphs) {
127
+ const parts = [hiddenTasks ? "+" + hiddenTasks + " tasks" : "", hiddenGraphs ? hiddenGraphs + " workflows hidden" : ""].filter(Boolean);
128
+ lines.push(theme.fg("dim", "… " + parts.join(SEPARATOR)));
129
+ }
130
+ return lines.map((line) => truncateToWidth(line, width, "…"));
112
131
  }
113
132
 
114
133
  export function formatActiveRunLines(runs: readonly RunView[], theme: Theme, width: number, now = Date.now()): string[] {
@@ -116,33 +135,59 @@ export function formatActiveRunLines(runs: readonly RunView[], theme: Theme, wid
116
135
  return rows.length ? renderBoard([{ rows, priority: 2 }], theme, width) : [];
117
136
  }
118
137
 
119
- function workflowGroup(graph: WorkflowRun, runs: readonly RunView[], theme: Theme, width: number, now: number): TaskGroup {
120
- const count = (state: WorkflowNodeRun["state"]) => graph.nodes.filter((node) => node.state === state).length;
121
- const completed = count("completed");
122
- const progress = completed + "/" + graph.nodes.length + " completed";
123
- const color = graph.state === "failed" ? "error" : "accent";
124
- const name = theme.fg(color, theme.bold("Workflow #" + graph.id + " · " + graph.name));
125
- const parts = [progress, ...(["failed", "blocked", "pending"] as const).filter((state) => count(state))
126
- .map((state) => count(state) + " " + (state === "pending" ? "waiting" : state))];
127
- const tail = width >= 100 ? parts.join(SEPARATOR) : progress + SEPARATOR + graph.state;
128
- const rows = graph.nodes.filter((node) => node.state !== "completed" && node.state !== "stopped").map((node): TaskRow => {
129
- const live = runs.find((run) => run.id === node.runId);
130
- const waitingOn = node.dependsOn.filter((id) => graph.nodes.find((dependency) => dependency.id === id)?.state !== "completed");
138
+ function workflowGroup(graph: WorkflowRun, runs: ReadonlyMap<number, RunView>, theme: Theme, width: number, now: number): TaskGroup {
139
+ const work = graph.nodes.filter((node) => !isAcceptance(node));
140
+ const nodes = new Map(graph.nodes.map((node) => [node.id, node]));
141
+ const completed = work.filter((node) => node.state === "completed").length;
142
+ const unsettled = work.filter((node) => node.state === "running" || node.state === "pending").length;
143
+ const heading = theme.bold((width < 60 ? "#" : "Workflow #") + graph.id + " · " + formatTaskSummary(graph.name, width, false));
144
+ const header = splitLine(heading, completed + "/" + work.length + (width < 60 ? " work done" : " work passed"), theme, width);
145
+ const rows: TaskRow[] = [];
146
+ let acceptance: TaskRow | undefined;
147
+ for (const node of graph.nodes) {
148
+ const required = isAcceptance(node);
149
+ if (!required && (node.state === "completed" || node.state === "stopped")) continue;
150
+ const live = node.runId === undefined ? undefined : runs.get(node.runId);
131
151
  const state = node.state === "pending" ? "waiting" : node.state === "running" && live?.status === "queued" ? "queued" : node.state;
132
- const detail = node.state === "pending" ? waitingOn.length ? "waits for " + waitingOn.join(", ") : "ready"
133
- : node.error ? node.state + ": " + formatTaskSummary(node.error, 100, false)
134
- : live?.status === "queued" ? waitWord(live)
135
- : live?.integrationStatus === "finalizing" ? "integrating worktree"
136
- : live?.activity ?? node.state;
137
- const iconState = node.state === "pending" ? "queued" : node.state === "failed" || node.state === "blocked" ? "failed" : live?.status ?? "running";
138
- const identity = " " + statusIcon(iconState, theme) + " " + theme.fg("accent", node.id) + theme.fg("dim", " · " + node.agent + (node.runId === undefined ? "" : " #" + node.runId));
139
- const elapsed = node.startedAt === undefined ? "" : formatDuration((node.endedAt ?? now) - node.startedAt);
140
- const primary = splitLine(identity + " · " + theme.fg(node.error ? "error" : "dim", detail), elapsed, theme, width);
141
- const meta = live ? metadata(live).join(SEPARATOR) : "";
142
- return { primary, detail: meta ? theme.fg("dim", " " + meta) : undefined,
143
- priority: node.state === "failed" ? 0 : node.state === "blocked" ? 1 : node.state === "running" ? 2 : 3, state };
144
- });
145
- return { header: splitLine(name, tail, theme, width), rows, priority: rows.length ? Math.min(...rows.map((row) => row.priority)) : 4 };
152
+ const iconState = node.state === "completed" ? "done" : node.state === "pending" ? "queued"
153
+ : node.state === "failed" ? "failed" : node.state === "blocked" ? "interrupting" : live?.status ?? "running";
154
+ const elapsed = live ? formatElapsed(live, now) : node.startedAt !== undefined && (node.state === "running" || node.endedAt !== undefined)
155
+ ? formatDuration((node.endedAt ?? now) - node.startedAt) : "";
156
+ let row: TaskRow;
157
+ if (required) {
158
+ const verdict = node.state === "completed" ? "PASS" : node.state === "failed" ? "FAIL"
159
+ : node.state === "pending" ? "pending" : live?.status === "queued" ? waitWord(live) : node.state;
160
+ const reason = node.error ?? (node.state === "pending"
161
+ ? unsettled ? "after " + unsettled + " work " + (unsettled === 1 ? "node settles" : "nodes settle") : "ready · all work settled"
162
+ : [node.agent + (node.runId === undefined ? "" : " #" + node.runId), live?.activity].filter(Boolean).join(SEPARATOR));
163
+ row = {
164
+ primary: splitLine(" " + statusIcon(iconState, theme) + " " + theme.bold("Acceptance required") + " · " + verdict, elapsed, theme, width),
165
+ detail: theme.fg("dim", " " + formatTaskSummary(reason, Math.max(1, width - 4), false)),
166
+ requiredDetail: node.state === "pending" || Boolean(node.error),
167
+ priority: node.state === "failed" ? 0 : node.state === "running" ? 2 : node.state === "pending" ? 3 : 4,
168
+ state: verdict,
169
+ };
170
+ acceptance = row;
171
+ continue;
172
+ }
173
+ const waitingOn = node.state === "pending" ? node.dependsOn.filter((id) => nodes.get(id)?.state !== "completed") : [];
174
+ const reason = node.error ?? (node.state === "pending" ? waitingOn.length ? "waits for " + waitingOn.join(", ") : "ready"
175
+ : live?.status === "queued" ? waitWord(live) : live?.integrationStatus === "finalizing" ? "integrating worktree" : live?.activity ?? node.task);
176
+ const role = width < 60 && node.state === "pending" ? "" : " · " + node.agent + (node.runId === undefined ? "" : " #" + node.runId);
177
+ const identity = " " + statusIcon(iconState, theme) + " " + node.id + theme.fg("dim", role);
178
+ // A waiting row carries its dependency inline. Failures own a separate
179
+ // cause line so even a 40-column terminal can explain the blocker.
180
+ const inline = node.state === "pending" ? " · " + reason : "";
181
+ row = {
182
+ primary: splitLine(identity + inline, [state === "queued" && live ? waitWord(live) : state, elapsed].filter(Boolean).join(SEPARATOR), theme, width),
183
+ detail: node.state === "pending" ? undefined : detailLine(reason, live, theme, width),
184
+ requiredDetail: node.state === "failed" || node.state === "blocked",
185
+ priority: node.state === "failed" ? 0 : node.state === "blocked" ? 1 : node.state === "running" ? 2 : 3,
186
+ state,
187
+ };
188
+ rows.push(row);
189
+ }
190
+ return { header, rows, acceptance, priority: Math.min(4, ...rows.map((row) => row.priority), acceptance?.priority ?? 4) };
146
191
  }
147
192
 
148
193
  export function formatSubagentWidgetLines(
@@ -151,67 +196,66 @@ export function formatSubagentWidgetLines(
151
196
  if (width <= 0) return [];
152
197
  const graphIds = new Set(workflows.map((graph) => graph.id));
153
198
  const visibleWorkflows = workflows.filter((graph) => graph.state !== "stopped" && graph.state !== "completed");
199
+ const runMap = new Map(runs.map((run) => [run.id, run]));
154
200
  const standalone = runs.filter((run) => (!run.workflow || !graphIds.has(run.workflow.workflowId)) && (isRunActiveStatus(run.status) || run.status === "failed"));
155
- const groups = visibleWorkflows.map((graph) => workflowGroup(graph, runs, theme, width, now));
201
+ const groups = visibleWorkflows.map((graph) => workflowGroup(graph, runMap, theme, width, now));
156
202
  if (standalone.length) {
157
203
  const rows = standalone.map((run) => runRow(run, theme, width, now));
158
204
  groups.push({ rows, priority: Math.min(...rows.map((row) => row.priority)) });
159
205
  }
160
206
  if (!groups.length) return [];
161
- const states = groups.flatMap((group) => group.rows.map((row) => row.state));
207
+ const states = new Map<string, number>();
208
+ for (const group of groups) for (const row of group.rows) states.set(row.state, (states.get(row.state) ?? 0) + 1);
162
209
  const counts = ["failed", "blocked", "interrupting", "running", "queued", "waiting"]
163
- .map((state) => ({ state, count: states.filter((value) => value === state).length }))
164
- .filter(({ count }) => count > 0).map(({ state, count }) => count + " " + state);
210
+ .filter((state) => states.has(state)).map((state) => states.get(state) + " " + state);
165
211
  if (visibleWorkflows.length) counts.push(visibleWorkflows.length + " workflow" + (visibleWorkflows.length === 1 ? "" : "s"));
166
- const overview = theme.fg("accent", theme.bold("Subagents")) + theme.fg("dim", " " + counts.join(SEPARATOR));
212
+ const overview = theme.bold("Subagents") + theme.fg("dim", " " + counts.join(SEPARATOR));
167
213
  return renderBoard(groups, theme, width, overview);
168
214
  }
169
215
 
170
- function hasActiveRun(): boolean {
171
- return monitor.getRuns().some((run) => isRunActiveStatus(run.status) && run.activeSince !== undefined);
216
+ /** Tick only while a rendered elapsed value can change; pending graphs and
217
+ * queued processes have no running clock. Monitor events render transitions. */
218
+ function hasTickingContent(): boolean {
219
+ const graphs = monitor.getWorkflows();
220
+ const hiddenGraphs = new Set(graphs.filter((graph) => graph.state === "completed" || graph.state === "stopped").map((graph) => graph.id));
221
+ const runs = monitor.getRuns().filter((run) => !run.workflow || !hiddenGraphs.has(run.workflow.workflowId));
222
+ if (runs.some((run) => isRunActiveStatus(run.status) && run.status !== "queued"
223
+ && (run.activeSince !== undefined || (run.startedAt !== undefined && run.endedAt === undefined)))) return true;
224
+ const byId = new Map(runs.map((run) => [run.id, run]));
225
+ return graphs.some((graph) => graph.state === "running" && graph.nodes.some((node) =>
226
+ node.state === "running" && node.startedAt !== undefined && node.endedAt === undefined
227
+ && (node.runId === undefined || !byId.has(node.runId))));
172
228
  }
173
229
 
174
- /** Install the widget for one TUI session. Its timer exists only while at
175
- * least one active run is executing, and is disposed with the widget. */
176
230
  export function installActiveRunsWidget(ctx: Pick<ExtensionContext, "mode" | "ui">): void {
177
231
  if (ctx.mode !== "tui") return;
178
- ctx.ui.setWidget(
179
- SUBAGENTS_WIDGET_ID,
180
- (tui, theme) => {
181
- let timer: ReturnType<typeof setInterval> | undefined;
182
- let disposed = false;
183
-
184
- const syncTimer = (): void => {
185
- if (disposed) return;
186
- if (hasActiveRun() || monitor.getWorkflows().some((graph) => graph.state === "running")) {
187
- if (timer) return;
188
- timer = setInterval(() => tui.requestRender(), 1_000);
189
- timer.unref?.();
190
- return;
191
- }
232
+ ctx.ui.setWidget(SUBAGENTS_WIDGET_ID, (tui, theme) => {
233
+ let timer: ReturnType<typeof setInterval> | undefined;
234
+ let disposed = false;
235
+ const syncTimer = (): void => {
236
+ if (disposed) return;
237
+ if (hasTickingContent()) {
238
+ if (timer) return;
239
+ timer = setInterval(() => tui.requestRender(), 1_000);
240
+ timer.unref?.();
241
+ } else {
192
242
  if (timer) clearInterval(timer);
193
243
  timer = undefined;
194
- };
195
-
196
- const unsubscribe = monitor.subscribe(() => {
197
- syncTimer();
198
- tui.requestRender();
199
- });
200
- syncTimer();
201
-
202
- return {
203
- render: (width: number) => formatSubagentWidgetLines(monitor.getRuns(), monitor.getWorkflows(), theme, width, Date.now()),
204
- invalidate() {},
205
- dispose() {
206
- disposed = true;
207
- unsubscribe();
208
- if (timer) clearInterval(timer);
209
- timer = undefined;
210
- },
211
- };
212
- },
213
- { placement: "aboveEditor" },
214
- );
244
+ }
245
+ };
246
+ const unsubscribe = monitor.subscribe(() => { syncTimer(); tui.requestRender(); });
247
+ syncTimer();
248
+ return {
249
+ render: (width: number) => formatSubagentWidgetLines(monitor.getRuns(), monitor.getWorkflows(), theme, width),
250
+ invalidate() {},
251
+ dispose() {
252
+ disposed = true;
253
+ unsubscribe();
254
+ if (timer) clearInterval(timer);
255
+ timer = undefined;
256
+ },
257
+ };
258
+ }, { placement: "aboveEditor" });
215
259
  }
216
260
 
217
261
  export function clearActiveRunsWidget(ctx: Pick<ExtensionContext, "mode" | "ui">): void {