@xzzpig/pi-subagents 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +4 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +343 -0
  5. package/docs/configuration.md +395 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +121 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +198 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +53 -23
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/preflight.ts +1 -1
  22. package/src/api/project-panes.ts +30 -0
  23. package/src/extension/config.ts +54 -1
  24. package/src/extension/doctor.ts +40 -0
  25. package/src/extension/fanout-child.ts +5 -4
  26. package/src/extension/index.ts +114 -38
  27. package/src/extension/public-execution.ts +35 -4
  28. package/src/extension/rpc.ts +10 -15
  29. package/src/extension/schemas.ts +33 -11
  30. package/src/extension/subagent-guide.ts +39 -0
  31. package/src/extension/tool-description.ts +38 -18
  32. package/src/inspectors/herdr/actions.ts +11 -2
  33. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  34. package/src/inspectors/herdr/project-panes.ts +459 -63
  35. package/src/intercom/intercom-bridge.ts +7 -2
  36. package/src/intercom/native-supervisor-channel.ts +102 -4
  37. package/src/missions/actions.ts +25 -2
  38. package/src/missions/lifecycle.ts +25 -9
  39. package/src/missions/store.ts +89 -7
  40. package/src/missions/types.ts +33 -0
  41. package/src/missions/workflow-state.ts +25 -15
  42. package/src/runs/background/active-async-capacity.ts +431 -0
  43. package/src/runs/background/active-run-index.ts +46 -0
  44. package/src/runs/background/async-execution.ts +158 -71
  45. package/src/runs/background/async-job-tracker.ts +297 -133
  46. package/src/runs/background/async-resume.ts +37 -5
  47. package/src/runs/background/async-status.ts +39 -5
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/completion-replay.ts +267 -0
  50. package/src/runs/background/control-channel.ts +95 -54
  51. package/src/runs/background/fleet-view.ts +18 -5
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-watcher.ts +113 -10
  55. package/src/runs/background/resume-guidance.ts +53 -0
  56. package/src/runs/background/retained-children.ts +14 -6
  57. package/src/runs/background/run-status.ts +119 -5
  58. package/src/runs/background/scheduled-runs.ts +25 -1
  59. package/src/runs/background/stale-run-reconciler.ts +12 -24
  60. package/src/runs/background/subagent-runner.ts +127 -41
  61. package/src/runs/background/subagent-wait.ts +5 -2
  62. package/src/runs/background/wait-completions.ts +39 -5
  63. package/src/runs/background/wait-subscriptions.ts +21 -5
  64. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  65. package/src/runs/foreground/async-steering-action.ts +7 -8
  66. package/src/runs/foreground/chain-execution.ts +40 -2
  67. package/src/runs/foreground/execution.ts +97 -19
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/foreground-history.ts +137 -0
  70. package/src/runs/foreground/prompt-audit.ts +172 -0
  71. package/src/runs/foreground/subagent-executor.ts +1274 -243
  72. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  73. package/src/runs/shared/acceptance.ts +13 -4
  74. package/src/runs/shared/completion-guard.ts +17 -1
  75. package/src/runs/shared/dynamic-fanout.ts +1 -1
  76. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  77. package/src/runs/shared/model-fallback.ts +8 -4
  78. package/src/runs/shared/model-scope.ts +12 -2
  79. package/src/runs/shared/parallel-utils.ts +3 -0
  80. package/src/runs/shared/pi-args.ts +44 -1
  81. package/src/runs/shared/run-fanout-budget.ts +280 -0
  82. package/src/runs/shared/single-output.ts +4 -2
  83. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  84. package/src/runs/shared/task-intent.ts +19 -3
  85. package/src/runs/shared/worktree.ts +20 -7
  86. package/src/shared/agent-stream-options.ts +5 -0
  87. package/src/shared/artifacts.ts +17 -21
  88. package/src/shared/display-text.ts +150 -0
  89. package/src/shared/file-coalescer.ts +9 -0
  90. package/src/shared/fork-context.ts +13 -0
  91. package/src/shared/formatters.ts +4 -6
  92. package/src/shared/node-executable.ts +21 -0
  93. package/src/shared/prompt-resources.ts +51 -0
  94. package/src/shared/settings.ts +15 -2
  95. package/src/shared/types.ts +158 -4
  96. package/src/shared/utf8.ts +11 -0
  97. package/src/shared/utils.ts +46 -34
  98. package/src/slash/prompt-workflows.ts +2 -15
  99. package/src/slash/slash-commands.ts +22 -2
  100. package/src/tui/fleet-status.ts +29 -17
  101. package/src/tui/fleet-transcript.ts +1 -48
  102. package/src/tui/fleet.ts +362 -37
  103. package/src/tui/render.ts +235 -71
  104. package/src/watchdog/change-signature.ts +4 -3
  105. package/src/watchdog/permission-arbiter.ts +2 -1
  106. package/src/watchdog/review.ts +4 -3
  107. package/src/workflows/chat-progress.ts +8 -2
  108. package/src/workflows/scripted-workflow.ts +273 -20
package/src/tui/fleet.ts CHANGED
@@ -2,10 +2,11 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
4
  import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
5
- import { Key, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component, type MarkdownTheme } from "@earendil-works/pi-tui";
5
+ import { matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component, type MarkdownTheme } from "@earendil-works/pi-tui";
6
6
  import { getArtifactPaths, getArtifactsDir } from "../shared/artifacts.ts";
7
7
  import { formatDuration, formatModelThinking, formatTokens, shortenPath } from "../shared/formatters.ts";
8
- import { DIRS, type AsyncJobState, type Details, type ForegroundChildControl, type ForegroundResumeChild, type ForegroundResumeRun, type ForegroundRunControl, type SubagentState } from "../shared/types.ts";
8
+ import { DIRS, type AsyncJobState, type Details, type FleetKeybindingAction, type FleetKeybindingsConfig, type ForegroundChildControl, type ForegroundResumeChild, type ForegroundResumeRun, type ForegroundRunControl, type SubagentState } from "../shared/types.ts";
9
+ import { decodeUtf8Tail } from "../shared/utf8.ts";
9
10
  import { readStatus } from "../shared/utils.ts";
10
11
  import { formatAsyncRunTranscript } from "../runs/background/fleet-view.ts";
11
12
  import { listAsyncRuns, type AsyncRunSummary } from "../runs/background/async-status.ts";
@@ -16,11 +17,54 @@ import { contextModeBadge, contextModeLabel } from "../runs/shared/context-mode.
16
17
  import { FLEET_STATUS_WIDGET_KEY } from "./fleet-status.ts";
17
18
  import { readFleetTranscript, renderFleetTranscript, type FleetTranscript } from "./fleet-transcript.ts";
18
19
  import { handleHerdrInspectorAction } from "../inspectors/herdr/actions.ts";
20
+ import { getLivePromptAudit, type LivePromptAudit, type PromptAuditView } from "../runs/foreground/prompt-audit.ts";
19
21
 
20
22
  const REFRESH_MS = 750;
21
23
  const MAX_RECENT_ASYNC_RUNS = 20;
22
24
  const MAX_FLEET_HISTORY_CANDIDATES = 100;
23
25
  const TRANSCRIPT_LINES = 200;
26
+ const OUTPUT_TAIL_BYTES = 64 * 1024;
27
+ const PROMPT_AUDIT_SUMMARY_WIDTH = 160;
28
+
29
+ export const DEFAULT_FLEET_KEYBINDINGS: Record<FleetKeybindingAction, string[]> = {
30
+ close: ["escape", "ctrl+c", "q"],
31
+ scrollUp: ["K"],
32
+ scrollDown: ["J"],
33
+ selectUp: ["up", "k"],
34
+ selectDown: ["down", "j"],
35
+ selectFirst: ["home"],
36
+ selectLast: ["end"],
37
+ pageUp: ["pageUp"],
38
+ pageDown: ["pageDown"],
39
+ refresh: ["r", "R"],
40
+ steer: ["s"],
41
+ inspect: ["H"],
42
+ stop: ["D"],
43
+ toggleTools: ["x", "X", "ctrl+o"],
44
+ };
45
+
46
+ type ResolvedFleetKeybindings = Record<FleetKeybindingAction, string[]>;
47
+
48
+ export function resolveFleetKeybindings(config: FleetKeybindingsConfig | undefined): ResolvedFleetKeybindings {
49
+ return Object.fromEntries(
50
+ Object.entries(DEFAULT_FLEET_KEYBINDINGS).map(([action, defaults]) => [action, config?.[action as FleetKeybindingAction] ?? defaults]),
51
+ ) as ResolvedFleetKeybindings;
52
+ }
53
+
54
+ function matchesFleetBinding(data: string, binding: string): boolean {
55
+ const key = /^[A-Z]$/.test(binding) ? `shift+${binding.toLowerCase()}` : binding;
56
+ return matchesKey(data, key as Parameters<typeof matchesKey>[1]);
57
+ }
58
+
59
+ function matchesFleetAction(data: string, bindings: ResolvedFleetKeybindings, action: FleetKeybindingAction): boolean {
60
+ return bindings[action].some((binding) => matchesFleetBinding(data, binding));
61
+ }
62
+
63
+ function bindingLabel(bindings: ResolvedFleetKeybindings, action: FleetKeybindingAction): string {
64
+ return bindings[action]
65
+ .map((binding) => binding === "up" ? "↑" : binding === "down" ? "↓" : binding === "escape" ? "Esc" : binding === "return" ? "Enter" : binding)
66
+ .join("/");
67
+ }
24
68
 
25
69
  type Theme = ExtensionContext["ui"]["theme"];
26
70
  type FleetTui = {
@@ -49,6 +93,7 @@ export interface FleetActionHandlers {
49
93
  steer(input: { runId: string; asyncDir: string; index?: number; message: string; mode: SteerDeliveryMode }): Promise<FleetActionResult>;
50
94
  stop(input: { runId: string; asyncDir: string; index?: number }): Promise<FleetActionResult> | FleetActionResult;
51
95
  inspect?(input: { runId: string; asyncDir: string; index?: number }): Promise<FleetActionResult>;
96
+ redoPrompt?(input: { runId: string; index: number; guidance: string; control?: ForegroundRunControl }): Promise<FleetActionResult>;
52
97
  }
53
98
 
54
99
  export interface FleetViewOptions {
@@ -57,7 +102,9 @@ export interface FleetViewOptions {
57
102
  refreshMs?: number;
58
103
  initialKey?: string;
59
104
  markdownTheme?: MarkdownTheme;
105
+ fleetKeybindings?: FleetKeybindingsConfig;
60
106
  actions?: FleetActionHandlers;
107
+ copyText?: (text: string) => Promise<void> | void;
61
108
  }
62
109
 
63
110
  function belongsToCurrentSession(sessionId: string | undefined, currentSessionId: string | null): boolean {
@@ -237,22 +284,62 @@ function statusGlyph(item: FleetItem, theme: Theme): string {
237
284
  return theme.fg("error", "✗");
238
285
  }
239
286
 
240
- function foregroundActiveDetail(item: Extract<FleetItem, { kind: "foreground-active" }>): string[] {
287
+ function foregroundPromptAuditCount(item: Extract<FleetItem, { kind: "foreground-active" }>, state: SubagentState): number {
288
+ if (!state.currentSessionId || item.control.sessionId !== state.currentSessionId) return 0;
289
+ if (!item.control.activeChildren) return getLivePromptAudit(item.control, item.index ?? 0) ? 1 : 0;
290
+ return [...item.control.activeChildren.keys()].filter((index) => getLivePromptAudit(item.control, index)).length;
291
+ }
292
+
293
+ function authoredPromptSummary(text: string): string | undefined {
294
+ const summary = text.replace(/\s+/g, " ").trim();
295
+ return summary ? truncateToWidth(summary, PROMPT_AUDIT_SUMMARY_WIDTH, "…") : undefined;
296
+ }
297
+
298
+ function foregroundAuthoredPromptSummary(item: Extract<FleetItem, { kind: "foreground-active" }>, state: SubagentState): string | undefined {
299
+ if (!state.currentSessionId || item.control.sessionId !== state.currentSessionId) return undefined;
300
+ const prompt = getLivePromptAudit(item.control, item.index ?? 0);
301
+ return prompt ? authoredPromptSummary(prompt.authoredTask) : undefined;
302
+ }
303
+
304
+ function promptAuditText(prompt: LivePromptAudit, view: PromptAuditView): string {
305
+ switch (view) {
306
+ case "authored": return prompt.authoredTask;
307
+ case "runtime": return prompt.runtimeAdditions;
308
+ case "effective": return prompt.finalEffectivePrompt;
309
+ }
310
+ }
311
+
312
+ function promptAuditViewLabel(view: PromptAuditView): string {
313
+ switch (view) {
314
+ case "authored": return "[1] Authored task";
315
+ case "runtime": return "[2] Runtime additions";
316
+ case "effective": return "[3] Final effective prompt";
317
+ }
318
+ }
319
+
320
+ function foregroundActiveDetail(item: Extract<FleetItem, { kind: "foreground-active" }>, state: SubagentState): string[] {
241
321
  const { control } = item;
242
322
  const live = item.activeChild ?? control;
243
323
  const modelThinking = formatModelThinking(live.model, live.thinking);
324
+ const promptAuditCount = foregroundPromptAuditCount(item, state);
325
+ const promptSummary = foregroundAuthoredPromptSummary(item, state);
244
326
  const lines = [
245
327
  `Run: ${item.runId}`,
246
328
  "Source: foreground",
247
329
  `State: running`,
248
330
  `Mode: ${control.mode}`,
331
+ control.parentWorkflowRunId ? `Workflow child of: ${control.parentWorkflowRunId}${control.workflowKey ? ` (${control.workflowKey})` : ""}` : undefined,
332
+ control.sourceRunId ? `Redo source: ${control.sourceRunId}` : undefined,
333
+ control.supersededByRunId ? `Superseded by: ${control.supersededByRunId}` : undefined,
249
334
  item.index !== undefined ? `Child: ${item.index} (${item.agent})` : `Agent: ${item.agent}`,
250
335
  modelThinking ? `Model: ${modelThinking}` : undefined,
336
+ promptSummary ? `Task: ${promptSummary}` : undefined,
251
337
  `Started: ${new Date(live.startedAt).toISOString()}`,
252
338
  live.currentTool ? `Current tool: ${live.currentTool}${live.currentPath ? ` · ${shortenPath(live.currentPath)}` : ""}` : undefined,
253
339
  live.turnCount !== undefined ? `Turns: ${live.turnCount}` : undefined,
254
340
  live.toolCount !== undefined ? `Tools: ${live.toolCount}` : undefined,
255
341
  live.tokens !== undefined ? `Tokens: ${formatTokens(live.tokens)}` : undefined,
342
+ promptAuditCount > 0 ? `Prompt audit: ${promptAuditCount} live · 3 views · p opens` : undefined,
256
343
  "",
257
344
  "Transcript",
258
345
  "Live foreground output remains in the expanded subagent tool result. Persisted output and session paths appear here after the child settles.",
@@ -260,7 +347,59 @@ function foregroundActiveDetail(item: Extract<FleetItem, { kind: "foreground-act
260
347
  return lines.filter((line): line is string => line !== undefined);
261
348
  }
262
349
 
263
- function foregroundRecentDetail(item: Extract<FleetItem, { kind: "foreground-recent" }>): string[] {
350
+ function pathWithin(base: string, candidate: string): boolean {
351
+ const resolvedBase = path.resolve(base);
352
+ const resolvedCandidate = path.resolve(candidate);
353
+ return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path.sep}`);
354
+ }
355
+
356
+ function trustedFileTail(filePath: string, trustedRoots: string[]): { text?: string; warning?: string; unavailable?: string } {
357
+ const resolvedPath = path.resolve(filePath);
358
+ if (trustedRoots.length === 0 || !trustedRoots.some((root) => pathWithin(root, resolvedPath))) return { warning: `output artifact is outside trusted roots: ${filePath}` };
359
+ let stat: fs.Stats;
360
+ try {
361
+ stat = fs.lstatSync(resolvedPath);
362
+ } catch (error) {
363
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return { unavailable: `output artifact unavailable: ${filePath}` };
364
+ return { warning: `output artifact could not be inspected: ${error instanceof Error ? error.message : String(error)}` };
365
+ }
366
+ if (stat.isSymbolicLink()) return { warning: `output artifact refused a symlink: ${filePath}` };
367
+ if (!stat.isFile()) return { warning: `output artifact is not a file: ${filePath}` };
368
+ try {
369
+ const realPath = fs.realpathSync(resolvedPath);
370
+ const realRoots = trustedRoots.filter((root) => fs.existsSync(root)).map((root) => fs.realpathSync(root));
371
+ if (!realRoots.some((root) => pathWithin(root, realPath))) return { warning: `output artifact resolves outside trusted roots: ${filePath}` };
372
+ const fd = fs.openSync(realPath, "r");
373
+ try {
374
+ const bytes = Math.min(stat.size, OUTPUT_TAIL_BYTES);
375
+ const buffer = Buffer.alloc(bytes);
376
+ fs.readSync(fd, buffer, 0, bytes, stat.size - bytes);
377
+ return { text: decodeUtf8Tail(buffer) };
378
+ } finally {
379
+ fs.closeSync(fd);
380
+ }
381
+ } catch (error) {
382
+ return { warning: `output artifact could not be read: ${error instanceof Error ? error.message : String(error)}` };
383
+ }
384
+ }
385
+
386
+ function foregroundRecentOutputLines(item: Extract<FleetItem, { kind: "foreground-recent" }>, state: SubagentState): string[] {
387
+ const outputPath = item.child.artifactPaths?.outputPath ?? item.child.savedOutputPath;
388
+ const output = item.child.finalOutput
389
+ ? { text: item.child.finalOutput }
390
+ : outputPath
391
+ ? trustedFileTail(path.isAbsolute(outputPath) ? outputPath : path.resolve(item.run.cwd, outputPath), uniquePaths([
392
+ fleetArtifactsRoot(state, item.run.cwd),
393
+ fleetArtifactsRoot(state, state.baseCwd),
394
+ ]))
395
+ : undefined;
396
+ if (output?.warning) return [`(${output.warning})`];
397
+ if (output?.unavailable) return [`(${output.unavailable})`];
398
+ const outputLines = (output?.text ?? "").split(/\r?\n/).filter((line) => line.trim()).slice(-TRANSCRIPT_LINES);
399
+ return outputLines.length ? outputLines : ["(no recovered output available)"];
400
+ }
401
+
402
+ function foregroundRecentDetail(item: Extract<FleetItem, { kind: "foreground-recent" }>, state: SubagentState): string[] {
264
403
  const { child, run } = item;
265
404
  const outputPath = child.artifactPaths?.outputPath ?? child.savedOutputPath;
266
405
  const modelThinking = formatModelThinking(child.model, child.thinking);
@@ -281,8 +420,7 @@ function foregroundRecentDetail(item: Extract<FleetItem, { kind: "foreground-rec
281
420
  "",
282
421
  "Result transcript tail",
283
422
  ];
284
- const outputLines = (child.finalOutput ?? "").split(/\r?\n/).filter((line) => line.trim()).slice(-TRANSCRIPT_LINES);
285
- lines.push(...(outputLines.length ? outputLines : ["(no recovered output available)"]));
423
+ lines.push(...foregroundRecentOutputLines(item, state));
286
424
  return lines.filter((line): line is string => line !== undefined);
287
425
  }
288
426
 
@@ -306,12 +444,12 @@ function asyncDetail(item: Extract<FleetItem, { kind: "async" }>): string[] {
306
444
  ].filter((line): line is string => line !== undefined);
307
445
  }
308
446
 
309
- function detailLines(item: FleetItem | undefined, error: string | undefined): string[] {
447
+ function detailLines(item: FleetItem | undefined, error: string | undefined, state: SubagentState): string[] {
310
448
  if (!item) return [error ? `Fleet scan failed: ${error}` : "No current-session foreground or recent async children.", "", "New runs appear here automatically while this inspector remains open."];
311
449
  const lines = item.kind === "foreground-active"
312
- ? foregroundActiveDetail(item)
450
+ ? foregroundActiveDetail(item, state)
313
451
  : item.kind === "foreground-recent"
314
- ? foregroundRecentDetail(item)
452
+ ? foregroundRecentDetail(item, state)
315
453
  : asyncDetail(item);
316
454
  if (error) lines.unshift(`Fleet scan warning: ${error}`, "");
317
455
  return lines;
@@ -335,7 +473,7 @@ function fleetArtifactsRoot(state: SubagentState, cwd: string): string {
335
473
  return getArtifactsDir(
336
474
  state.parentSessionFile ?? null,
337
475
  cwd,
338
- state.artifactDirPreference ?? "project",
476
+ state.artifactDirPreference,
339
477
  );
340
478
  }
341
479
 
@@ -372,6 +510,7 @@ function transcriptTarget(item: FleetItem, state: SubagentState): { path: string
372
510
  item.run.asyncDir,
373
511
  fleetArtifactsRoot(state, state.baseCwd),
374
512
  trackedJob?.cwd ? fleetArtifactsRoot(state, trackedJob.cwd) : undefined,
513
+ item.run.sessionFile ? getArtifactsDir(item.run.sessionFile, item.run.cwd ?? state.baseCwd, state.artifactDirPreference) : undefined,
375
514
  ]),
376
515
  };
377
516
  }
@@ -422,7 +561,7 @@ function itemStats(item: FleetItem): string[] {
422
561
  ].filter((value): value is string => Boolean(value));
423
562
  }
424
563
 
425
- function structuredHeader(item: FleetItem, width: number, theme: Theme, conversationState: string): string[] {
564
+ function structuredHeader(item: FleetItem, width: number, theme: Theme, conversationState: string, promptSummary?: string): string[] {
426
565
  const lines: string[] = [];
427
566
  lines.push(rightAligned(` ${statusGlyph(item, theme)} ${theme.bold(item.agent)}`, theme.fg("dim", item.state), width));
428
567
  const child = item.index !== undefined ? ` · child ${item.index + 1}` : "";
@@ -431,10 +570,7 @@ function structuredHeader(item: FleetItem, width: number, theme: Theme, conversa
431
570
  lines.push(` ${theme.fg("dim", identity)}`);
432
571
  const stats = itemStats(item);
433
572
  if (stats.length) lines.push(` ${theme.fg("muted", stats.join(" · "))}`);
434
- if (item.description) {
435
- const task = item.description.replace(/\s+/g, " ").trim();
436
- lines.push(` ${theme.fg("dim", "Task")} ${task}`);
437
- }
573
+ if (promptSummary) lines.push(` ${theme.fg("muted", `Task: ${promptSummary}`)}`);
438
574
  lines.push(`${theme.fg("accent", "Conversation")} ${theme.fg("dim", `· ${conversationState}`)}`);
439
575
  return lines.map((line) => truncateToWidth(line, width));
440
576
  }
@@ -483,8 +619,11 @@ export class SubagentFleetComponent implements Component {
483
619
  private detailViewportHeight = 8;
484
620
  private bodyHeight = 8;
485
621
  private expandedTools = false;
622
+ private promptAuditOpen = false;
623
+ private promptAuditView: PromptAuditView = "authored";
486
624
  private actionNotice: FleetActionResult | undefined;
487
625
  private steerDraft: string | undefined;
626
+ private redoGuidanceDraft: string | undefined;
488
627
  private steerMode: SteerDeliveryMode = "steer";
489
628
  private stopConfirming = false;
490
629
  private actionBusy = false;
@@ -497,6 +636,7 @@ export class SubagentFleetComponent implements Component {
497
636
  private readonly state: SubagentState;
498
637
  private readonly done: (result: undefined) => void;
499
638
  private readonly options: FleetViewOptions;
639
+ private readonly keybindings: ResolvedFleetKeybindings;
500
640
 
501
641
  constructor(
502
642
  tui: FleetTui,
@@ -511,6 +651,7 @@ export class SubagentFleetComponent implements Component {
511
651
  this.state = state;
512
652
  this.done = done;
513
653
  this.options = options;
654
+ this.keybindings = resolveFleetKeybindings(options.fleetKeybindings);
514
655
  this.selectedKey = options.initialKey;
515
656
  this.refresh();
516
657
  this.timer = setInterval(() => {
@@ -538,8 +679,45 @@ export class SubagentFleetComponent implements Component {
538
679
  this.tui.requestRender();
539
680
  }
540
681
 
682
+ private selectedPromptAudit(): LivePromptAudit | undefined {
683
+ const item = this.snapshot.items[this.selected];
684
+ if (item?.kind !== "foreground-active") return undefined;
685
+ if (!this.state.currentSessionId || item.control.sessionId !== this.state.currentSessionId) return undefined;
686
+ return getLivePromptAudit(item.control, item.index ?? 0);
687
+ }
688
+
689
+ private promptAuditItems(): Array<{ item: Extract<FleetItem, { kind: "foreground-active" }>; prompt: LivePromptAudit }> {
690
+ const selected = this.snapshot.items[this.selected];
691
+ if (selected?.kind !== "foreground-active" || !this.state.currentSessionId || selected.control.sessionId !== this.state.currentSessionId) return [];
692
+ return this.snapshot.items.flatMap((item) => {
693
+ if (item.kind !== "foreground-active" || item.control !== selected.control) return [];
694
+ const prompt = getLivePromptAudit(item.control, item.index ?? 0);
695
+ return prompt ? [{ item, prompt }] : [];
696
+ });
697
+ }
698
+
699
+ private selectedPromptText(): string | undefined {
700
+ const prompt = this.selectedPromptAudit();
701
+ return prompt ? promptAuditText(prompt, this.promptAuditView) : undefined;
702
+ }
703
+
704
+ private movePromptSelection(delta: number): void {
705
+ const items = this.promptAuditItems();
706
+ if (items.length === 0) return;
707
+ const currentKey = this.snapshot.items[this.selected]?.key;
708
+ const current = Math.max(0, items.findIndex(({ item }) => item.key === currentKey));
709
+ const target = items[Math.max(0, Math.min(items.length - 1, current + delta))]?.item;
710
+ if (!target) return;
711
+ this.selected = this.snapshot.items.findIndex((item) => item.key === target.key);
712
+ this.selectedKey = target.key;
713
+ this.detailScroll = 0;
714
+ this.detailAutoFollow = false;
715
+ this.tui.requestRender();
716
+ }
717
+
541
718
  private resetActionInput(): void {
542
719
  this.steerDraft = undefined;
720
+ this.redoGuidanceDraft = undefined;
543
721
  this.steerMode = "steer";
544
722
  this.stopConfirming = false;
545
723
  }
@@ -552,12 +730,28 @@ export class SubagentFleetComponent implements Component {
552
730
  return { item };
553
731
  }
554
732
 
733
+ private selectedHerdrInspectAction(): { runId: string; asyncDir: string; index?: number } | { reason: string } {
734
+ const item = this.snapshot.items[this.selected];
735
+ if (!item) return { reason: "No child is selected." };
736
+ if (item.kind === "async") {
737
+ if (!isActionableAsyncState(item.run.state) || !isActionableAsyncState(item.state)) return { reason: `Selected child is ${item.state}; controls require a running or queued async child.` };
738
+ return { runId: item.runId, asyncDir: item.run.asyncDir, ...(item.index !== undefined ? { index: item.index } : {}) };
739
+ }
740
+ if (item.kind !== "foreground-active" || !item.control.parentWorkflowRunId) return { reason: "Fleet controls are available for current-session top-level async runs only." };
741
+ const parent = this.state.asyncJobs.get(item.control.parentWorkflowRunId) ?? this.state.fleetJobs?.get(item.control.parentWorkflowRunId);
742
+ if (!parent || !isActionableAsyncState(parent.status)) return { reason: "The parent workflow is no longer available for Herdr inspection." };
743
+ return { runId: parent.asyncId, asyncDir: parent.asyncDir };
744
+ }
745
+
555
746
  private actionLines(): string[] {
556
747
  const lines: string[] = [];
557
748
  if (this.actionBusy) lines.push(this.theme.fg("accent", "Action pending..."));
558
749
  if (this.steerDraft !== undefined) {
559
750
  lines.push(this.theme.fg("accent", `Steer message (${this.steerMode}): ${this.steerDraft}${this.theme.fg("dim", "▌")}`));
560
751
  lines.push(this.theme.fg("dim", "Enter sends · Tab changes mode · Esc cancels · Backspace edits"));
752
+ } else if (this.redoGuidanceDraft !== undefined) {
753
+ lines.push(this.theme.fg("accent", `Redo guidance: ${this.redoGuidanceDraft}${this.theme.fg("dim", "▌")}`));
754
+ lines.push(this.theme.fg("dim", "Enter rewrites and reruns · Esc cancels · Backspace edits"));
561
755
  } else if (this.stopConfirming) {
562
756
  const selected = this.snapshot.items[this.selected];
563
757
  lines.push(this.theme.fg("warning", `Confirm stop for async run ${selected?.runId ?? "selected run"}?`));
@@ -604,6 +798,82 @@ export class SubagentFleetComponent implements Component {
604
798
  }
605
799
 
606
800
  handleInput(data: string): void {
801
+ if (this.promptAuditOpen && this.redoGuidanceDraft !== undefined) {
802
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
803
+ this.resetActionInput();
804
+ this.tui.requestRender();
805
+ return;
806
+ }
807
+ if (matchesKey(data, "return") || data === "\r" || data === "\n") {
808
+ const guidance = this.redoGuidanceDraft.trim();
809
+ if (!guidance) {
810
+ this.setActionNotice({ text: "Redo guidance cannot be empty.", isError: true });
811
+ return;
812
+ }
813
+ const selected = this.snapshot.items[this.selected];
814
+ if (selected?.kind !== "foreground-active" || !this.options.actions?.redoPrompt) {
815
+ this.setActionNotice({ text: "Redo is unavailable for this prompt.", isError: true });
816
+ return;
817
+ }
818
+ this.runAction(() => this.options.actions!.redoPrompt!({ runId: selected.runId, index: selected.index ?? 0, guidance, control: selected.control }));
819
+ return;
820
+ }
821
+ if (matchesKey(data, "backspace") || data === "\x7f") {
822
+ this.redoGuidanceDraft = this.redoGuidanceDraft.slice(0, -1);
823
+ this.tui.requestRender();
824
+ return;
825
+ }
826
+ if (data.length === 1 && data >= " " && data !== "\x7f") {
827
+ this.redoGuidanceDraft += data;
828
+ this.tui.requestRender();
829
+ }
830
+ return;
831
+ }
832
+ if (this.promptAuditOpen) {
833
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
834
+ this.promptAuditOpen = false;
835
+ this.detailAutoFollow = true;
836
+ this.tui.requestRender();
837
+ return;
838
+ }
839
+ if (data === "j") return this.movePromptSelection(1);
840
+ if (data === "k") return this.movePromptSelection(-1);
841
+ if (data === "1" || data === "2" || data === "3") {
842
+ this.promptAuditView = data === "1" ? "authored" : data === "2" ? "runtime" : "effective";
843
+ this.detailScroll = 0;
844
+ this.tui.requestRender();
845
+ return;
846
+ }
847
+ if (data === "g") {
848
+ const prompt = this.selectedPromptAudit();
849
+ if (!prompt) this.setActionNotice({ text: "Prompt Audit is available only for a live child owned by this session.", isError: true });
850
+ else if (!prompt.rerun) this.setActionNotice({ text: "Redo is not safe for this prompt in this slice.", isError: true });
851
+ else if (!this.options.actions?.redoPrompt) this.setActionNotice({ text: "Redo controls are unavailable in this context.", isError: true });
852
+ else {
853
+ this.actionNotice = undefined;
854
+ this.redoGuidanceDraft = "";
855
+ this.detailAutoFollow = false;
856
+ this.detailScroll = 0;
857
+ this.tui.requestRender();
858
+ }
859
+ return;
860
+ }
861
+ if (data === "c") {
862
+ const text = this.selectedPromptText();
863
+ if (!text) this.setActionNotice({ text: "No prompt view is available to copy.", isError: true });
864
+ else if (!this.options.copyText) this.setActionNotice({ text: "Clipboard is unavailable in this context.", isError: true });
865
+ else this.runAction(async () => {
866
+ await this.options.copyText!(text);
867
+ return { text: "Copied visible prompt view." };
868
+ });
869
+ return;
870
+ }
871
+ if (matchesFleetAction(data, this.keybindings, "scrollUp")) return this.scrollDetail(-1);
872
+ if (matchesFleetAction(data, this.keybindings, "scrollDown")) return this.scrollDetail(1);
873
+ if (matchesFleetAction(data, this.keybindings, "pageUp")) return this.scrollDetail(-this.detailViewportHeight);
874
+ if (matchesFleetAction(data, this.keybindings, "pageDown")) return this.scrollDetail(this.detailViewportHeight);
875
+ return;
876
+ }
607
877
  if (this.steerDraft !== undefined) {
608
878
  if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
609
879
  this.resetActionInput();
@@ -657,25 +927,37 @@ export class SubagentFleetComponent implements Component {
657
927
  }
658
928
  return;
659
929
  }
660
- if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c") || matchesKey(data, "q")) {
930
+ if (matchesFleetAction(data, this.keybindings, "close")) {
661
931
  this.done(undefined);
662
932
  return;
663
933
  }
664
- if (matchesKey(data, Key.shift("k"))) return this.scrollDetail(-1);
665
- if (matchesKey(data, Key.shift("j"))) return this.scrollDetail(1);
666
- if (matchesKey(data, "up") || matchesKey(data, "k")) return this.moveSelection(-1);
667
- if (matchesKey(data, "down") || matchesKey(data, "j")) return this.moveSelection(1);
668
- if (matchesKey(data, "home")) return this.moveSelection(-this.snapshot.items.length);
669
- if (matchesKey(data, "end")) return this.moveSelection(this.snapshot.items.length);
670
- if (matchesKey(data, "pageUp")) return this.scrollDetail(-this.detailViewportHeight);
671
- if (matchesKey(data, "pageDown")) return this.scrollDetail(this.detailViewportHeight);
672
- if (data.toLowerCase() === "r") {
934
+ if (matchesFleetAction(data, this.keybindings, "scrollUp")) return this.scrollDetail(-1);
935
+ if (matchesFleetAction(data, this.keybindings, "scrollDown")) return this.scrollDetail(1);
936
+ if (matchesFleetAction(data, this.keybindings, "selectUp")) return this.moveSelection(-1);
937
+ if (matchesFleetAction(data, this.keybindings, "selectDown")) return this.moveSelection(1);
938
+ if (matchesFleetAction(data, this.keybindings, "selectFirst")) return this.moveSelection(-this.snapshot.items.length);
939
+ if (matchesFleetAction(data, this.keybindings, "selectLast")) return this.moveSelection(this.snapshot.items.length);
940
+ if (matchesFleetAction(data, this.keybindings, "pageUp")) return this.scrollDetail(-this.detailViewportHeight);
941
+ if (matchesFleetAction(data, this.keybindings, "pageDown")) return this.scrollDetail(this.detailViewportHeight);
942
+ if (matchesFleetAction(data, this.keybindings, "refresh")) {
673
943
  this.transcriptCache = undefined;
674
944
  this.refresh();
675
945
  this.tui.requestRender();
676
946
  return;
677
947
  }
678
- if (data === "s") {
948
+ if (data === "p") {
949
+ if (!this.selectedPromptAudit()) this.setActionNotice({ text: "Prompt Audit is available only for a live child owned by this session.", isError: true });
950
+ else {
951
+ this.promptAuditOpen = true;
952
+ this.promptAuditView = "authored";
953
+ this.detailScroll = 0;
954
+ this.detailAutoFollow = false;
955
+ this.actionNotice = undefined;
956
+ this.tui.requestRender();
957
+ }
958
+ return;
959
+ }
960
+ if (matchesFleetAction(data, this.keybindings, "steer")) {
679
961
  const target = this.selectedAsyncAction();
680
962
  if ("reason" in target || !this.options.actions) this.setActionNotice({ text: "reason" in target ? target.reason : "Fleet controls are unavailable in this context.", isError: true });
681
963
  else {
@@ -687,13 +969,13 @@ export class SubagentFleetComponent implements Component {
687
969
  }
688
970
  return;
689
971
  }
690
- if (data === "H") {
691
- const target = this.selectedAsyncAction();
972
+ if (matchesFleetAction(data, this.keybindings, "inspect")) {
973
+ const target = this.selectedHerdrInspectAction();
692
974
  if ("reason" in target || !this.options.actions?.inspect) this.setActionNotice({ text: "reason" in target ? target.reason : "Herdr inspector controls are unavailable in this context.", isError: true });
693
- else this.runAction(() => this.options.actions!.inspect!({ runId: target.item.runId, asyncDir: target.item.run.asyncDir, ...(target.item.index !== undefined ? { index: target.item.index } : {}) }));
975
+ else this.runAction(() => this.options.actions!.inspect!(target));
694
976
  return;
695
977
  }
696
- if (data === "D") {
978
+ if (matchesFleetAction(data, this.keybindings, "stop")) {
697
979
  const target = this.selectedAsyncAction();
698
980
  if ("reason" in target || !this.options.actions) this.setActionNotice({ text: "reason" in target ? target.reason : "Fleet controls are unavailable in this context.", isError: true });
699
981
  else {
@@ -705,7 +987,7 @@ export class SubagentFleetComponent implements Component {
705
987
  }
706
988
  return;
707
989
  }
708
- if (data.toLowerCase() === "x" || matchesKey(data, "ctrl+o")) {
990
+ if (matchesFleetAction(data, this.keybindings, "toggleTools")) {
709
991
  this.expandedTools = !this.expandedTools;
710
992
  this.transcriptCache = undefined;
711
993
  this.tui.requestRender();
@@ -720,7 +1002,7 @@ export class SubagentFleetComponent implements Component {
720
1002
  const marker = index === this.selected ? this.theme.fg("accent", "›") : " ";
721
1003
  const context = item.kind === "async" ? contextModeBadge(this.theme, item.step?.context ?? item.run.context) : item.kind === "foreground-recent" ? contextModeBadge(this.theme, item.child.context) : "";
722
1004
  const agent = index === this.selected ? this.theme.bold(item.agent) : item.agent;
723
- const identity = item.description?.replace(/\s+/g, " ").trim() || item.runId.slice(0, 8);
1005
+ const identity = item.runId.slice(0, 8);
724
1006
  const left = `${marker} ${statusGlyph(item, this.theme)} ${agent}${context} ${this.theme.fg("dim", `· ${identity}`)}`;
725
1007
  return rightAligned(left, this.theme.fg("dim", item.state), width);
726
1008
  });
@@ -743,7 +1025,35 @@ export class SubagentFleetComponent implements Component {
743
1025
  return { transcript, body: [...body] };
744
1026
  }
745
1027
 
1028
+ private promptAuditDetail(width: number): FleetDetailSections {
1029
+ const selected = this.snapshot.items[this.selected];
1030
+ const prompt = this.selectedPromptAudit();
1031
+ const items = this.promptAuditItems();
1032
+ const selectedPosition = selected ? items.findIndex(({ item }) => item.key === selected.key) : -1;
1033
+ const live = selected?.kind === "foreground-active" ? selected.activeChild ?? selected.control : undefined;
1034
+ const viewLabel = promptAuditViewLabel(this.promptAuditView);
1035
+ const promptText = this.selectedPromptText()
1036
+ ?? this.theme.fg("muted", "Selected prompt unavailable.");
1037
+ const raw = [
1038
+ this.theme.bold("Prompt Audit"),
1039
+ this.theme.fg("dim", "Retention: live memory only · no storage"),
1040
+ selected?.kind === "foreground-active" ? `Run: ${selected.runId}${selected.index !== undefined ? ` · Child: ${selected.index}` : ""} · Agent: ${selected.agent}` : "Selected prompt unavailable",
1041
+ live ? `Started: ${new Date(live.startedAt).toISOString()}` : undefined,
1042
+ live ? `Model: ${formatModelThinking(live.model, live.thinking) || "default"}` : undefined,
1043
+ prompt?.cwd ? `Cwd: ${prompt.cwd}` : undefined,
1044
+ prompt?.outputPath ? `Output: ${prompt.outputPath}` : undefined,
1045
+ this.theme.fg("dim", `Live children: ${items.map(({ item }) => item.agent).join(", ") || "none"}`),
1046
+ this.theme.fg("dim", selectedPosition >= 0 ? `Selected: ${selectedPosition + 1}/${items.length}` : "Selected prompt unavailable"),
1047
+ "",
1048
+ this.theme.fg("accent", viewLabel),
1049
+ promptText,
1050
+ ];
1051
+ const body = raw.filter((line): line is string => line !== undefined).flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width)));
1052
+ return { header: [], body: this.withActionLines(body) };
1053
+ }
1054
+
746
1055
  private wrappedDetail(width: number): FleetDetailSections {
1056
+ if (this.promptAuditOpen) return this.promptAuditDetail(width);
747
1057
  const selected = this.snapshot.items[this.selected];
748
1058
  let transcriptWarning: string | undefined;
749
1059
  if (selected) {
@@ -761,16 +1071,17 @@ export class SubagentFleetComponent implements Component {
761
1071
  : latest?.kind === "tool"
762
1072
  ? `${latest.name} · ${latest.status}`
763
1073
  : "activity";
764
- return { header: structuredHeader(selected, width, this.theme, conversationState), body: this.withActionLines(body) };
1074
+ const promptSummary = selected.kind === "foreground-active" ? foregroundAuthoredPromptSummary(selected, this.state) : undefined;
1075
+ return { header: structuredHeader(selected, width, this.theme, conversationState, promptSummary), body: this.withActionLines(body) };
765
1076
  }
766
1077
  }
767
1078
  }
768
1079
 
769
- const raw = detailLines(selected, this.snapshot.error);
1080
+ const raw = detailLines(selected, this.snapshot.error, this.state);
770
1081
  if (transcriptWarning) raw.unshift(`Transcript preview warning: ${transcriptWarning}`, "");
771
1082
  const lines: string[] = [];
772
1083
  for (const line of raw) {
773
- const styled = /^(Run|State|Mode|Source|Child|Agent|Model):/.test(line)
1084
+ const styled = /^(Run|State|Mode|Source|Child|Agent|Model|Task):/.test(line)
774
1085
  ? this.theme.bold(line)
775
1086
  : /^(Transcript|Result transcript tail)/.test(line)
776
1087
  ? this.theme.fg("accent", line)
@@ -823,7 +1134,9 @@ export class SubagentFleetComponent implements Component {
823
1134
  }
824
1135
  lines.push(this.theme.fg("border", `├${"─".repeat(rosterWidth)}┴${"─".repeat(detailWidth)}┤`));
825
1136
  const position = this.snapshot.items.length ? `${this.selected + 1}/${this.snapshot.items.length}` : "0/0";
826
- const footer = ` ↑↓/jk agent · H Herdr · s steer · D stop · x/Ctrl+O tools · r refresh · Esc close · ${position}`;
1137
+ const footer = this.promptAuditOpen
1138
+ ? ` j/k child · 1/2/3 view · g redo with guidance · c copy · Esc close Prompt Audit · ${position}`
1139
+ : ` ${bindingLabel(this.keybindings, "selectUp")}/${bindingLabel(this.keybindings, "selectDown")} agent · p Prompt Audit · ${bindingLabel(this.keybindings, "inspect")} Herdr · ${bindingLabel(this.keybindings, "steer")} steer · ${bindingLabel(this.keybindings, "stop")} stop · ${bindingLabel(this.keybindings, "toggleTools")} tools · ${bindingLabel(this.keybindings, "refresh")} refresh · ${bindingLabel(this.keybindings, "close")} close · ${position}`;
827
1140
  lines.push(this.theme.fg("border", "│") + fit(this.theme.fg("dim", footer), innerWidth) + this.theme.fg("border", "│"));
828
1141
  lines.push(this.theme.fg("border", `╰${"─".repeat(innerWidth)}╯`));
829
1142
  return lines.map((line) => truncateToWidth(line, width));
@@ -844,6 +1157,12 @@ export async function openSubagentFleet(ctx: ExtensionContext, state: SubagentSt
844
1157
  const wasOpen = state.fleetInspectorOpen === true;
845
1158
  state.fleetInspectorOpen = true;
846
1159
  if (typeof ctx.ui.setWidget === "function") ctx.ui.setWidget(FLEET_STATUS_WIDGET_KEY, undefined);
1160
+ const copyText = options.copyText ?? (async (text: string) => {
1161
+ const module = await import("@earendil-works/pi-coding-agent");
1162
+ const copyToClipboard = (module as { copyToClipboard?: (value: string) => Promise<void> | void }).copyToClipboard;
1163
+ if (!copyToClipboard) throw new Error("Clipboard is unavailable in this Pi version.");
1164
+ await copyToClipboard(text);
1165
+ });
847
1166
  const actions = options.actions ?? {
848
1167
  steer: async (input: { runId: string; asyncDir: string; index?: number; message: string; mode: SteerDeliveryMode }) => firstToolResultText(await steerAsyncRun({
849
1168
  state,
@@ -860,14 +1179,20 @@ export async function openSubagentFleet(ctx: ExtensionContext, state: SubagentSt
860
1179
  ...(input.index !== undefined ? { index: input.index } : {}),
861
1180
  }, {
862
1181
  state,
1182
+ sessionRoots: state.trustedSessionRoots,
863
1183
  cwd: state.baseCwd,
864
1184
  ...(state.authorityPolicy ? { authorityPolicy: state.authorityPolicy } : {}),
865
1185
  ...(state.missionStoreConfig ? { missions: state.missionStoreConfig } : {}),
866
1186
  }), `Failed to open Herdr inspector for async run ${input.runId}.`),
1187
+ redoPrompt: async (input: { runId: string; index: number; guidance: string; control?: ForegroundRunControl }) => {
1188
+ const control = input.control ?? state.foregroundControls.get(input.runId);
1189
+ if (!control?.promptAuditRedo) return { text: "Redo is not available for this live child.", isError: true };
1190
+ return control.promptAuditRedo(input.index, input.guidance);
1191
+ },
867
1192
  } satisfies FleetActionHandlers;
868
1193
  try {
869
1194
  await ctx.ui.custom<undefined>(
870
- (tui, theme, _keybindings, done) => new SubagentFleetComponent(tui, theme, state, done, { ...options, actions }),
1195
+ (tui, theme, _keybindings, done) => new SubagentFleetComponent(tui, theme, state, done, { ...options, actions, copyText }),
871
1196
  {
872
1197
  overlay: true,
873
1198
  overlayOptions: { anchor: "center", width: "95%", minWidth: 60, maxHeight: "85%", margin: 1 },