pi-subagents 0.49.0 → 0.50.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 (75) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/agents/oracle.md +7 -5
  3. package/agents/researcher.md +1 -1
  4. package/agents/reviewer.md +2 -2
  5. package/agents/scout.md +1 -1
  6. package/agents/worker.md +1 -1
  7. package/docs/agents.md +2 -0
  8. package/docs/configuration.md +47 -3
  9. package/docs/extension-api.md +36 -0
  10. package/docs/missions.md +1 -1
  11. package/docs/observability.md +16 -0
  12. package/docs/tool-reference.md +19 -2
  13. package/docs/workflows.md +2 -2
  14. package/package.json +1 -1
  15. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  16. package/skills/pi-subagents/references/execution-controls.md +5 -4
  17. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  18. package/skills/pi-subagents/references/prompting-and-roles.md +31 -15
  19. package/src/agents/agent-serializer.ts +2 -0
  20. package/src/agents/agents.ts +10 -0
  21. package/src/api/external-runs.ts +174 -84
  22. package/src/api/preflight.ts +12 -6
  23. package/src/extension/config.ts +33 -0
  24. package/src/extension/index.ts +48 -5
  25. package/src/extension/public-execution.ts +3 -1
  26. package/src/extension/rpc.ts +5 -1
  27. package/src/extension/schemas.ts +2 -1
  28. package/src/extension/tool-description.ts +4 -2
  29. package/src/inspectors/herdr/actions.ts +3 -7
  30. package/src/inspectors/herdr/project-panes.ts +2 -6
  31. package/src/inspectors/herdr/shell-command.ts +16 -0
  32. package/src/intercom/intercom-bridge.ts +2 -3
  33. package/src/intercom/native-supervisor-channel.ts +19 -42
  34. package/src/missions/goal-driver.ts +3 -1
  35. package/src/runs/background/active-run-index.ts +71 -1
  36. package/src/runs/background/async-execution.ts +49 -7
  37. package/src/runs/background/async-job-tracker.ts +1 -0
  38. package/src/runs/background/async-resume.ts +3 -5
  39. package/src/runs/background/async-status-snapshot.ts +277 -0
  40. package/src/runs/background/async-status.ts +8 -3
  41. package/src/runs/background/chain-root-attachment.ts +2 -2
  42. package/src/runs/background/completion-replay.ts +11 -1
  43. package/src/runs/background/fleet-view.ts +3 -1
  44. package/src/runs/background/result-files.ts +437 -0
  45. package/src/runs/background/result-watcher.ts +188 -41
  46. package/src/runs/background/retained-children.ts +69 -20
  47. package/src/runs/background/run-id-resolver.ts +30 -24
  48. package/src/runs/background/run-status.ts +7 -2
  49. package/src/runs/background/scheduled-runs.ts +54 -28
  50. package/src/runs/background/stale-run-reconciler.ts +27 -13
  51. package/src/runs/background/subagent-runner.ts +294 -32
  52. package/src/runs/background/subagent-wait.ts +2 -0
  53. package/src/runs/background/wait-completions.ts +5 -2
  54. package/src/runs/foreground/async-dismiss-action.ts +2 -1
  55. package/src/runs/foreground/chain-execution.ts +16 -0
  56. package/src/runs/foreground/execution.ts +219 -15
  57. package/src/runs/foreground/subagent-executor.ts +114 -28
  58. package/src/runs/shared/completion-guard.ts +96 -6
  59. package/src/runs/shared/external-cli-runner.ts +4 -0
  60. package/src/runs/shared/model-fallback.ts +16 -2
  61. package/src/runs/shared/nested-events.ts +66 -62
  62. package/src/runs/shared/orca-progress-tabs.ts +375 -0
  63. package/src/runs/shared/parallel-utils.ts +2 -0
  64. package/src/runs/shared/subagent-control.ts +15 -0
  65. package/src/runs/shared/subagent-prompt-runtime.ts +1 -9
  66. package/src/runs/shared/subagent-startup-retry.ts +12 -0
  67. package/src/runs/shared/tool-timeout.ts +93 -0
  68. package/src/shared/types.ts +29 -2
  69. package/src/slash/slash-commands.ts +34 -25
  70. package/src/slash/slash-live-state.ts +3 -0
  71. package/src/tui/fleet-status.ts +160 -45
  72. package/src/tui/fleet.ts +125 -15
  73. package/src/tui/render.ts +41 -10
  74. package/src/workflows/chat-progress.ts +6 -4
  75. package/src/workflows/scripted-workflow.ts +227 -70
@@ -0,0 +1,93 @@
1
+ export const TOOL_TIMEOUT_ENV = "PI_SUBAGENT_TOOL_TIMEOUT_MS";
2
+
3
+ /** Maximum delay a Node.js timer accepts without overflow. */
4
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
5
+
6
+ export const DEFAULT_FAST_TOOL_TIMEOUT_MS = 300_000;
7
+
8
+ export const DEFAULT_FAST_TOOL_TIMEOUT_TOOLS = new Set([
9
+ "read",
10
+ "grep",
11
+ "find",
12
+ "ls",
13
+ "edit",
14
+ "write",
15
+ "structured_output",
16
+ ]);
17
+
18
+ /** Tools whose normal job can be to wait for a person or another run. */
19
+ export const TOOL_TIMEOUT_EXEMPT_TOOLS = new Set(["contact_supervisor", "intercom", "subagent_wait"]);
20
+
21
+ // Backward-compatible export name for existing callers/tests.
22
+ export const TOOL_TIMEOUT_ALLOWLIST = TOOL_TIMEOUT_EXEMPT_TOOLS;
23
+
24
+ export function isToolTimeoutExempt(toolName: string | undefined): boolean {
25
+ return toolName !== undefined && TOOL_TIMEOUT_EXEMPT_TOOLS.has(toolName);
26
+ }
27
+
28
+ export function defaultToolTimeoutMs(toolName: string | undefined): number | undefined {
29
+ return toolName !== undefined && DEFAULT_FAST_TOOL_TIMEOUT_TOOLS.has(toolName)
30
+ ? DEFAULT_FAST_TOOL_TIMEOUT_MS
31
+ : undefined;
32
+ }
33
+
34
+ export function effectiveToolTimeoutMs(toolName: string | undefined, configuredToolTimeoutMs: number | undefined): number | undefined {
35
+ if (isToolTimeoutExempt(toolName)) return undefined;
36
+ return configuredToolTimeoutMs ?? defaultToolTimeoutMs(toolName);
37
+ }
38
+
39
+ export function formatToolTimeoutMessage(toolName: string, timeoutMs: number): string {
40
+ return `Tool '${toolName}' exceeded its timeout of ${timeoutMs}ms.`;
41
+ }
42
+
43
+ export function toolTimeoutCallKey(event: { toolCallId?: unknown; toolName?: unknown }, fallbackId: number): string {
44
+ return typeof event.toolCallId === "string" && event.toolCallId.length > 0
45
+ ? `id:${event.toolCallId}`
46
+ : `anon:${String(event.toolName ?? "tool")}:${fallbackId}`;
47
+ }
48
+
49
+ export interface ToolTimeoutResolutionInput {
50
+ /** Per-call value from the subagent tool params (highest precedence). */
51
+ callValue?: unknown;
52
+ /** Agent frontmatter default (second precedence). */
53
+ agentValue?: number;
54
+ /** Global extension config.toolTimeoutMs (third precedence). */
55
+ configValue?: unknown;
56
+ /** PI_SUBAGENT_TOOL_TIMEOUT_MS environment override (lowest precedence). */
57
+ envValue?: string | undefined;
58
+ }
59
+
60
+ /** Resolve the configured hard timeout. Default fast-tool timeouts apply later per tool name. */
61
+ export function resolveToolTimeoutMs(input: ToolTimeoutResolutionInput): { toolTimeoutMs?: number; error?: string } {
62
+ const candidates: Array<{ label: string; value: unknown }> = [
63
+ { label: "toolTimeoutMs", value: input.callValue },
64
+ { label: "agent.toolTimeoutMs", value: input.agentValue },
65
+ { label: "config.toolTimeoutMs", value: input.configValue },
66
+ ];
67
+ let winner: { label: string; value: unknown } | undefined;
68
+ for (const candidate of candidates) {
69
+ if (candidate.value === undefined) continue;
70
+ winner = candidate;
71
+ break;
72
+ }
73
+ if (winner === undefined && input.envValue !== undefined && input.envValue.trim() !== "") {
74
+ winner = { label: TOOL_TIMEOUT_ENV, value: input.envValue };
75
+ }
76
+ if (winner === undefined) return {};
77
+
78
+ let raw: unknown = winner.value;
79
+ let parsed: number;
80
+ if (winner.label === TOOL_TIMEOUT_ENV && typeof raw === "string") {
81
+ parsed = Number(raw);
82
+ if (raw.trim() !== "" && !Number.isNaN(parsed)) raw = parsed;
83
+ }
84
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw <= 0 || raw > MAX_TIMER_DELAY_MS) {
85
+ return { error: `${winner.label} must be a positive integer no larger than ${MAX_TIMER_DELAY_MS}.` };
86
+ }
87
+ return { toolTimeoutMs: raw };
88
+ }
89
+
90
+ /** Read the environment override without requiring callers to know the name. */
91
+ export function toolTimeoutFromEnv(env: NodeJS.ProcessEnv = process.env): string | undefined {
92
+ return env[TOOL_TIMEOUT_ENV];
93
+ }
@@ -215,7 +215,7 @@ export interface ControlEvent {
215
215
  nestedRunId?: string;
216
216
  nestingPath?: NestedRunAddress["path"];
217
217
  message: string;
218
- reason?: "idle" | "completion_guard" | "active_long_running" | "tool_failures" | "supervisor_request" | "time_threshold" | "turn_threshold" | "token_threshold";
218
+ reason?: "idle" | "completion_guard" | "active_long_running" | "tool_failures" | "supervisor_request" | "time_threshold" | "turn_threshold" | "token_threshold" | "tool_open_threshold";
219
219
  turns?: number;
220
220
  tokens?: number;
221
221
  toolCount?: number;
@@ -1031,6 +1031,7 @@ export interface Details {
1031
1031
  controlEvents?: ControlEvent[];
1032
1032
  steering?: SteerActionResult;
1033
1033
  asyncId?: string;
1034
+ background?: boolean;
1034
1035
  asyncDir?: string;
1035
1036
  timeoutMs?: number;
1036
1037
  deadlineAt?: number;
@@ -1088,7 +1089,7 @@ export interface Details {
1088
1089
  trace: Array<{
1089
1090
  operation: "run" | "status";
1090
1091
  key: string;
1091
- state: "started" | "completed" | "failed" | "stopped" | "reused";
1092
+ state: "started" | "completed" | "failed" | "detached" | "stopped" | "reused";
1092
1093
  agent?: string;
1093
1094
  runId?: string;
1094
1095
  phase?: string;
@@ -1464,6 +1465,8 @@ export type AsyncJobStep = NonNullable<AsyncStatus["steps"]>[number] & {
1464
1465
  export interface AsyncJobState {
1465
1466
  asyncId: string;
1466
1467
  asyncDir: string;
1468
+ /** Host tool-call id retained when it differs from the internal run id. */
1469
+ toolCallId?: string;
1467
1470
  /** Parent-resolved launch directory retained for trusted live artifact lookup. */
1468
1471
  cwd?: string;
1469
1472
  /** Parent-resolved child session root retained for trusted live transcript lookup. */
@@ -1767,6 +1770,10 @@ export interface RunSyncOptions {
1767
1770
  interruptSignal?: AbortSignal;
1768
1771
  timeoutMs?: number;
1769
1772
  deadlineAt?: number;
1773
+ /** Per-call per-tool timeout (ms), resolved with the agent/config/environment ladder at execution. */
1774
+ toolTimeoutMs?: number;
1775
+ /** Raw global config.toolTimeoutMs, used by the per-child resolver. */
1776
+ configToolTimeoutMs?: number;
1770
1777
  turnBudget?: ResolvedTurnBudget;
1771
1778
  usageBudget?: UsageBudgetConfig;
1772
1779
  /** Enforce maxTurns + graceTurns as a hard model-turn boundary. */
@@ -1831,6 +1838,8 @@ export interface RunSyncOptions {
1831
1838
  };
1832
1839
  /** Private live callback for the exact child prompt after runtime acceptance injection. */
1833
1840
  onEffectivePrompt?: (prompt: string) => void;
1841
+ /** Internal lifecycle hook for the observer shared across retries of one logical child. */
1842
+ onOrcaProgressTabCreated?: (tab: import("../runs/shared/orca-progress-tabs.ts").OrcaProgressTab) => void;
1834
1843
  }
1835
1844
 
1836
1845
  export type IntercomBridgeMode = "off" | "fork-only" | "always";
@@ -1892,6 +1901,11 @@ export const FLEET_KEYBINDING_ACTIONS = [
1892
1901
  export type FleetKeybindingAction = typeof FLEET_KEYBINDING_ACTIONS[number];
1893
1902
  export type FleetKeybindingsConfig = Partial<Record<FleetKeybindingAction, string[]>>;
1894
1903
 
1904
+ export interface OrcaProgressTabsConfig {
1905
+ /** Create one Orca terminal tab per running subagent. Experimental and opt-in. */
1906
+ enabled?: boolean;
1907
+ }
1908
+
1895
1909
  export interface MainWindowRendererConfig {
1896
1910
  /** Unit of horizontal space in main chat subagent call/result rows. Omit to preserve current spacing. Set 0 for no extra padding. */
1897
1911
  horizontalSpacing?: number;
@@ -1901,6 +1915,8 @@ export interface MainWindowRendererConfig {
1901
1915
 
1902
1916
  export interface ExtensionConfig {
1903
1917
  asyncByDefault?: boolean;
1918
+ /** Optional shortcut that detaches the active foreground single-subagent run. */
1919
+ foregroundDetachShortcut?: string;
1904
1920
  /** Show the Claude Code-style navigable fleet. Defaults to true. */
1905
1921
  fleetView?: boolean;
1906
1922
  /** Place the persistent FleetView above or below the editor. Defaults to belowEditor. */
@@ -1917,6 +1933,8 @@ export interface ExtensionConfig {
1917
1933
  inlineToolDisplay?: InlineToolDisplay;
1918
1934
  /** Density controls for the main chat subagent call/result renderer. */
1919
1935
  mainWindowRenderer?: MainWindowRendererConfig;
1936
+ /** Experimental observer: mirror each native subagent's progress into a new Orca tab. */
1937
+ orcaProgressTabs?: OrcaProgressTabsConfig;
1920
1938
  forceTopLevelAsync?: boolean;
1921
1939
  waitTool?: WaitToolConfig;
1922
1940
  defaultSessionDir?: string;
@@ -1940,6 +1958,15 @@ export interface ExtensionConfig {
1940
1958
  * Must be a positive integer; invalid values are ignored.
1941
1959
  */
1942
1960
  timeoutMs?: number;
1961
+ /**
1962
+ * Optional hard per-tool-call timeout in milliseconds. Bounds a single
1963
+ * subagent tool call inside the child; the run-level timeout remains
1964
+ * authoritative. Known-fast built-in tools have a five-minute default when
1965
+ * this is undefined. Precedence: call param > agent frontmatter > this config >
1966
+ * PI_SUBAGENT_TOOL_TIMEOUT_MS. Must be a positive integer; invalid values
1967
+ * are rejected with an error.
1968
+ */
1969
+ toolTimeoutMs?: number;
1943
1970
  control?: ControlConfig;
1944
1971
  completionBatch?: CompletionBatchConfig;
1945
1972
  turnBudget?: TurnBudgetConfig;
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { keyText, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
5
- import { Key, matchesKey, truncateToWidth, type Component, type TUI } from "@earendil-works/pi-tui";
5
+ import { Key, matchesKey, truncateToWidth, type Component, type KeyId, type TUI } from "@earendil-works/pi-tui";
6
6
  import { BUILTIN_AGENT_NAMES, discoverAgents } from "../agents/agents.ts";
7
7
  import { resolveExistingReadPaths } from "../shared/settings.ts";
8
8
  import {
@@ -631,7 +631,7 @@ function slashRunWorkflowScript(key: string, child: Record<string, unknown>): st
631
631
  export function registerSlashCommands(
632
632
  pi: ExtensionAPI,
633
633
  state: SubagentState,
634
- options: { fleetKeybindings?: FleetKeybindingsConfig } = {},
634
+ options: { fleetKeybindings?: FleetKeybindingsConfig; foregroundDetachShortcut?: string } = {},
635
635
  ): void {
636
636
  let fleetOpen = false;
637
637
  const showFleet = async (ctx: ExtensionContext) => {
@@ -741,33 +741,42 @@ export function registerSlashCommands(
741
741
  handler: async (ctx) => showFleet(ctx),
742
742
  });
743
743
 
744
+ const detachForegroundRun = (args: string, ctx: ExtensionContext): void => {
745
+ const id = args.trim();
746
+ let control: ReturnType<typeof selectForegroundDetachControl>;
747
+ try {
748
+ control = selectForegroundDetachControl(state, id);
749
+ } catch (error) {
750
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
751
+ return;
752
+ }
753
+ if (!control) {
754
+ ctx.ui.notify(id ? `No active foreground run found for '${id}'.` : "No active foreground single-subagent run to detach.", "info");
755
+ return;
756
+ }
757
+ if (control.mode !== "single") {
758
+ ctx.ui.notify("/subagents-detach currently supports single-subagent runs only.", "error");
759
+ return;
760
+ }
761
+ if (!control.detach?.()) {
762
+ ctx.ui.notify(`Foreground run ${control.runId} is not currently detachable.`, "info");
763
+ return;
764
+ }
765
+ sendSlashText(pi, `Detached foreground run ${control.runId} without terminating its child. Use subagent({ action: "status", id: ${JSON.stringify(control.runId)} }) or subagent_wait({ id: ${JSON.stringify(control.runId)} }) to recover the eventual result. This does not daemonize the process or guarantee survival across Pi reload/restart.`);
766
+ };
767
+
744
768
  pi.registerCommand("subagents-detach", {
745
769
  description: "Detach the active foreground single-subagent run without terminating it",
746
- handler: async (args, ctx) => {
747
- const id = args.trim();
748
- let control: ReturnType<typeof selectForegroundDetachControl>;
749
- try {
750
- control = selectForegroundDetachControl(state, id);
751
- } catch (error) {
752
- ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
753
- return;
754
- }
755
- if (!control) {
756
- ctx.ui.notify(id ? `No active foreground run found for '${id}'.` : "No active foreground single-subagent run to detach.", "info");
757
- return;
758
- }
759
- if (control.mode !== "single") {
760
- ctx.ui.notify("/subagents-detach currently supports single-subagent runs only.", "error");
761
- return;
762
- }
763
- if (!control.detach?.()) {
764
- ctx.ui.notify(`Foreground run ${control.runId} is not currently detachable.`, "info");
765
- return;
766
- }
767
- sendSlashText(pi, `Detached foreground run ${control.runId} without terminating its child. Use subagent({ action: "status", id: ${JSON.stringify(control.runId)} }) or subagent_wait({ id: ${JSON.stringify(control.runId)} }) to recover the eventual result. This does not daemonize the process or guarantee survival across Pi reload/restart.`);
768
- },
770
+ handler: async (args, ctx) => detachForegroundRun(args, ctx),
769
771
  });
770
772
 
773
+ if (options.foregroundDetachShortcut) {
774
+ pi.registerShortcut(options.foregroundDetachShortcut as KeyId, {
775
+ description: "Detach the active foreground subagent and keep it running in the background",
776
+ handler: async (ctx) => detachForegroundRun("", ctx),
777
+ });
778
+ }
779
+
771
780
  pi.registerCommand("subagents-stop", {
772
781
  description: "Stop a current-session async subagent run",
773
782
  handler: async (args, ctx) => {
@@ -81,6 +81,7 @@ function buildParallelInitialResult(params: SubagentParamsLike): AgentToolResult
81
81
  content: [{ type: "text", text: tasks.map((task) => `${task.agent}: ${task.task}`).join("\n\n") }],
82
82
  details: {
83
83
  mode: "parallel",
84
+ ...(params.async ? { background: true } : {}),
84
85
  ...(params.context ? { context: params.context } : {}),
85
86
  results: tasks.map((task, index) => createPlaceholderResult(task.agent, task.task, "running", index)),
86
87
  progress: tasks.map((task, index) => ({
@@ -136,6 +137,7 @@ function buildChainInitialResult(params: SubagentParamsLike): AgentToolResult<De
136
137
  }],
137
138
  details: {
138
139
  mode: "chain",
140
+ ...(params.async ? { background: true } : {}),
139
141
  ...(params.context ? { context: params.context } : {}),
140
142
  results,
141
143
  progress: results.map((result, index) => ({
@@ -164,6 +166,7 @@ function buildSingleInitialResult(params: SubagentParamsLike): AgentToolResult<D
164
166
  content: [{ type: "text", text: task }],
165
167
  details: {
166
168
  mode: "single",
169
+ ...(params.async ? { background: true } : {}),
167
170
  ...(params.context ? { context: params.context } : {}),
168
171
  results: [createPlaceholderResult(agent, task, "running", 0)],
169
172
  progress: [{
@@ -1,12 +1,13 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { type EditorComponent, isKeyRelease, Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+ import { snapshotExternalRuns } from "../api/external-runs.ts";
3
4
  import { formatModelThinking } from "../shared/formatters.ts";
4
5
  import type { AsyncJobStep, FleetViewPlacement, NestedRunSummary, NestedStepSummary, SubagentState } from "../shared/types.ts";
5
6
  import { formatWorkflowJsonPreview } from "../workflows/scripted-workflow.ts";
6
7
 
7
8
  export const FLEET_STATUS_WIDGET_KEY = "subagent-fleet-status";
8
9
 
9
- // Six rows fit the accepted collapsed hierarchy: one owner, four direct leaves, and overflow.
10
+ // Six rows fit the accepted collapsed hierarchy: one owner, four visible descendants, and overflow.
10
11
  const MAX_AGENT_ROWS = 6;
11
12
  const REFRESH_MS = 500;
12
13
 
@@ -16,12 +17,15 @@ type FleetStatusTui = {
16
17
  };
17
18
  type FleetStatusEntry = {
18
19
  key: string;
20
+ parentKey?: string;
21
+ workflowWrapper?: boolean;
19
22
  agent: string;
20
23
  modelThinking?: string;
21
24
  description?: string;
22
25
  startedAt: number;
23
26
  tokens: number;
24
27
  state: string;
28
+ external?: true;
25
29
  nestedChildren?: NestedRunSummary[];
26
30
  };
27
31
 
@@ -31,11 +35,13 @@ type FleetNestedRow = {
31
35
  modelThinking?: string;
32
36
  activity?: string;
33
37
  startedAt?: number;
38
+ depth: number;
34
39
  overflow?: number;
35
40
  };
36
41
 
37
42
  type FleetTreeRow =
38
43
  | { kind: "owner"; entry: FleetStatusEntry }
44
+ | { kind: "child"; entry: FleetStatusEntry; last: boolean }
39
45
  | { kind: "nested"; ownerKey: string; row: FleetNestedRow; last: boolean };
40
46
 
41
47
  export interface FleetStatusOptions {
@@ -94,44 +100,112 @@ function nestedStatusGlyph(state: FleetNestedRow["state"], theme: Theme): string
94
100
  return theme.fg("warning", "■");
95
101
  }
96
102
 
97
- function nestedFleetRows(children: NestedRunSummary[] | undefined): FleetNestedRow[] {
98
- const rows: FleetNestedRow[] = [];
99
- for (const child of children ?? []) {
103
+ function nestedStepDisplayCount(steps: NestedStepSummary[] | undefined, start = 0): number {
104
+ let count = 0;
105
+ for (let index = start; index < (steps?.length ?? 0); index++) {
106
+ count += 1 + nestedDisplayCount(steps![index]!.children);
107
+ }
108
+ return count;
109
+ }
110
+
111
+ function nestedDisplayCount(children: NestedRunSummary[] | undefined, start = 0): number {
112
+ let count = 0;
113
+ for (let index = start; index < (children?.length ?? 0); index++) {
114
+ const child = children![index]!;
100
115
  const steps = (child.mode === "parallel" || child.mode === "chain") ? child.steps ?? [] : [];
101
- if (steps.length > 0) {
102
- for (const step of steps) {
103
- const modelThinking = formatModelThinking(step.model, step.thinking) || undefined;
104
- const activity = nestedActivity(step);
116
+ count += steps.length > 0 ? nestedStepDisplayCount(steps) : 1;
117
+ count += nestedDisplayCount(child.children);
118
+ }
119
+ return count;
120
+ }
121
+
122
+ function nestedFleetRows(children: NestedRunSummary[] | undefined, visibleLimit: number): FleetNestedRow[] {
123
+ const rows: FleetNestedRow[] = [];
124
+ let omitted = 0;
125
+ const appendRuns = (runs: NestedRunSummary[] | undefined, depth: number): boolean => {
126
+ for (let runIndex = 0; runIndex < (runs?.length ?? 0); runIndex++) {
127
+ const child = runs![runIndex]!;
128
+ const steps = (child.mode === "parallel" || child.mode === "chain") ? child.steps ?? [] : [];
129
+ if (steps.length > 0) {
130
+ for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
131
+ if (rows.length >= visibleLimit) {
132
+ omitted += nestedStepDisplayCount(steps, stepIndex);
133
+ omitted += nestedDisplayCount(child.children);
134
+ omitted += nestedDisplayCount(runs, runIndex + 1);
135
+ return false;
136
+ }
137
+ const step = steps[stepIndex]!;
138
+ const modelThinking = formatModelThinking(step.model, step.thinking) || undefined;
139
+ const activity = nestedActivity(step);
140
+ rows.push({
141
+ name: step.agent,
142
+ state: step.status,
143
+ depth,
144
+ ...(modelThinking ? { modelThinking } : {}),
145
+ ...(activity ? { activity } : {}),
146
+ ...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
147
+ });
148
+ if (!appendRuns(step.children, depth + 1)) {
149
+ omitted += nestedStepDisplayCount(steps, stepIndex + 1);
150
+ omitted += nestedDisplayCount(child.children);
151
+ omitted += nestedDisplayCount(runs, runIndex + 1);
152
+ return false;
153
+ }
154
+ }
155
+ } else {
156
+ if (rows.length >= visibleLimit) {
157
+ omitted += nestedDisplayCount(runs, runIndex);
158
+ return false;
159
+ }
160
+ const modelThinking = formatModelThinking(child.model, child.thinking) || undefined;
161
+ const activity = nestedActivity(child);
105
162
  rows.push({
106
- name: step.agent,
107
- state: step.status,
163
+ name: nestedRunLabel(child),
164
+ state: child.state,
165
+ depth,
108
166
  ...(modelThinking ? { modelThinking } : {}),
109
167
  ...(activity ? { activity } : {}),
110
- ...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
168
+ ...(child.startedAt !== undefined ? { startedAt: child.startedAt } : {}),
111
169
  });
112
170
  }
113
- continue;
171
+ if (!appendRuns(child.children, depth + 1)) {
172
+ omitted += nestedDisplayCount(runs, runIndex + 1);
173
+ return false;
174
+ }
114
175
  }
115
- const modelThinking = formatModelThinking(child.model, child.thinking) || undefined;
116
- const activity = nestedActivity(child);
117
- rows.push({
118
- name: nestedRunLabel(child),
119
- state: child.state,
120
- ...(modelThinking ? { modelThinking } : {}),
121
- ...(activity ? { activity } : {}),
122
- ...(child.startedAt !== undefined ? { startedAt: child.startedAt } : {}),
123
- });
124
- }
125
- const visible = rows.slice(0, 4);
126
- if (rows.length > visible.length) visible.push({ name: `… +${rows.length - visible.length} more nested leaves`, state: "complete", overflow: rows.length - visible.length });
127
- return visible;
176
+ return true;
177
+ };
178
+ appendRuns(children, 0);
179
+ if (omitted > 0) rows.push({ name: `… +${omitted} more nested leaves`, state: "complete", depth: 0, overflow: omitted });
180
+ return rows;
128
181
  }
129
182
 
130
183
  function fleetTreeRows(entries: FleetStatusEntry[]): FleetTreeRow[] {
131
184
  const rows: FleetTreeRow[] = [];
185
+ const entryKeys = new Set(entries.map((entry) => entry.key));
186
+ const childrenByParent = new Map<string, FleetStatusEntry[]>();
187
+ for (const entry of entries) {
188
+ if (!entry.parentKey || !entryKeys.has(entry.parentKey)) continue;
189
+ const children = childrenByParent.get(entry.parentKey) ?? [];
190
+ children.push(entry);
191
+ childrenByParent.set(entry.parentKey, children);
192
+ }
132
193
  for (const entry of entries) {
194
+ if (entry.parentKey && entryKeys.has(entry.parentKey)) continue;
133
195
  rows.push({ kind: "owner", entry });
134
- const nested = nestedFleetRows(entry.nestedChildren);
196
+ const attached = childrenByParent.get(entry.key) ?? [];
197
+ for (const [index, child] of attached.entries()) {
198
+ const nested = nestedFleetRows(child.nestedChildren, 3);
199
+ const laterRows = index < attached.length - 1 || Boolean(entry.nestedChildren?.length);
200
+ rows.push({ kind: "child", entry: child, last: !laterRows && nested.length === 0 });
201
+ for (const [nestedIndex, row] of nested.entries()) rows.push({
202
+ kind: "nested",
203
+ ownerKey: child.key,
204
+ row: { ...row, depth: row.depth + 1 },
205
+ last: nestedIndex === nested.length - 1 && !laterRows,
206
+ });
207
+ }
208
+ const nested = nestedFleetRows(entry.nestedChildren, attached.length > 0 ? 3 : 4);
135
209
  for (const [index, row] of nested.entries()) rows.push({ kind: "nested", ownerKey: entry.key, row, last: index === nested.length - 1 });
136
210
  }
137
211
  return rows;
@@ -150,14 +224,24 @@ function foregroundDescription(control: { parentWorkflowRunId?: string; workflow
150
224
  return description ? `${workflow} · ${description}` : workflow;
151
225
  }
152
226
 
227
+ function activeLeafAgentCount(entries: FleetStatusEntry[]): number {
228
+ return entries.filter((entry) => !entry.workflowWrapper).length;
229
+ }
230
+
153
231
  export function collectFleetStatusEntries(state: SubagentState): FleetStatusEntry[] {
154
232
  const entries: FleetStatusEntry[] = [];
233
+ const activeWorkflowKeys = new Set([...state.asyncJobs.values()]
234
+ .filter((job) => job.mode === "workflow" && isActiveState(job.status))
235
+ .map((job) => `async:${job.asyncId}`));
155
236
  for (const control of state.foregroundControls.values()) {
237
+ const parentKey = control.parentWorkflowRunId ? `async:${control.parentWorkflowRunId}` : undefined;
238
+ const linkedParentKey = parentKey && activeWorkflowKeys.has(parentKey) ? parentKey : undefined;
156
239
  if (control.activeChildren) {
157
240
  for (const child of [...control.activeChildren.values()].sort((left, right) => left.index - right.index)) {
158
241
  const modelThinking = formatModelThinking(child.model, child.thinking) || undefined;
159
242
  entries.push({
160
243
  key: `foreground-active:${control.runId}:${child.index}`,
244
+ ...(linkedParentKey ? { parentKey: linkedParentKey } : {}),
161
245
  agent: child.agent,
162
246
  ...(modelThinking ? { modelThinking } : {}),
163
247
  description: foregroundDescription(control, child.description),
@@ -174,6 +258,7 @@ export function collectFleetStatusEntries(state: SubagentState): FleetStatusEntr
174
258
  const modelThinking = formatModelThinking(control.model, control.thinking) || undefined;
175
259
  entries.push({
176
260
  key: `foreground-active:${control.runId}:${control.currentIndex ?? 0}`,
261
+ ...(linkedParentKey ? { parentKey: linkedParentKey } : {}),
177
262
  agent: control.currentAgent ?? control.mode,
178
263
  ...(modelThinking ? { modelThinking } : {}),
179
264
  description: foregroundDescription(control, control.description),
@@ -191,6 +276,7 @@ export function collectFleetStatusEntries(state: SubagentState): FleetStatusEntr
191
276
  const latestEmit = job.workflow?.emits?.length ? formatWorkflowJsonPreview(job.workflow.emits.at(-1), 120) : undefined;
192
277
  entries.push({
193
278
  key: `async:${job.asyncId}`,
279
+ workflowWrapper: true,
194
280
  agent: "workflow",
195
281
  description: latestEmit !== undefined ? `latest emit: ${latestEmit}` : job.description,
196
282
  startedAt,
@@ -241,6 +327,25 @@ export function collectFleetStatusEntries(state: SubagentState): FleetStatusEntr
241
327
  }
242
328
  }
243
329
 
330
+ if (state.currentSessionId) {
331
+ try {
332
+ for (const run of snapshotExternalRuns(state.currentSessionId, { ignoreMalformed: true, onMalformedRecord: (message) => console.warn(`[pi-subagents] Removed ${message}`) })) {
333
+ if (!isActiveState(run.state)) continue;
334
+ entries.push({
335
+ key: `external:${run.id}`,
336
+ agent: `external · ${run.label}`,
337
+ description: run.currentAction ?? `source: ${run.source}`,
338
+ startedAt: run.startedAt,
339
+ tokens: 0,
340
+ state: run.state,
341
+ external: true,
342
+ });
343
+ }
344
+ } catch (cause) {
345
+ console.warn(`[pi-subagents] Failed to inspect external jobs: ${cause instanceof Error ? cause.message : String(cause)}`);
346
+ }
347
+ }
348
+
244
349
  return entries.sort((left, right) => left.startedAt - right.startedAt || left.key.localeCompare(right.key));
245
350
  }
246
351
 
@@ -417,10 +522,15 @@ export class SubagentFleetStatus {
417
522
  if (!this.active) {
418
523
  const tokens = this.entries.reduce((total, entry) => total + entry.tokens, 0);
419
524
  const capacity = this.state.activeAsyncCapacity;
420
- const asyncRuns = capacity ? `Async runs ${capacity.used}/${capacity.limit || "∞"}` : "";
421
- const agents = this.entries.length > 0 ? `${this.entries.length} active ${this.entries.length === 1 ? "agent" : "agents"}` : "";
525
+ const hasNativeRows = this.entries.some((entry) => !entry.external);
526
+ const showNativeSummary = hasNativeRows || Boolean(capacity?.used);
527
+ const asyncRuns = capacity && showNativeSummary ? `Async runs ${capacity.used}/${capacity.limit || "∞"}` : "";
528
+ const activeEntries = activeLeafAgentCount(this.entries);
529
+ const noun = this.entries.some((entry) => entry.external) ? "job" : "agent";
530
+ const agents = activeEntries > 0 ? `${activeEntries} active ${noun}${activeEntries === 1 ? "" : "s"}` : "";
422
531
  const label = [agents, asyncRuns].filter(Boolean).join(" · ");
423
- return [truncateToWidth(` ${theme.fg("muted", label)} · ${theme.fg("dim", `${formatFleetTokens(tokens)} · ↓/← to inspect`)}`, width)];
532
+ const detail = [showNativeSummary ? formatFleetTokens(tokens) : undefined, "↓/← to inspect"].filter(Boolean).join(" · ");
533
+ return [truncateToWidth(` ${theme.fg("muted", label)} · ${theme.fg("dim", detail)}`, width)];
424
534
  }
425
535
  const roster = this.rosterKeys();
426
536
  const selectedIndex = Math.max(0, roster.indexOf(this.selectedKey));
@@ -428,16 +538,16 @@ export class SubagentFleetStatus {
428
538
  lines.push(truncateToWidth(` ${this.bullet(0, selectedIndex, theme)} main`, width));
429
539
 
430
540
  const tree = fleetTreeRows(this.entries);
431
- const selectedTreeIndex = Math.max(0, tree.findIndex((row) => row.kind === "owner" && row.entry.key === this.selectedKey));
541
+ const selectedTreeIndex = Math.max(0, tree.findIndex((row) => (row.kind === "owner" || row.kind === "child") && row.entry.key === this.selectedKey));
432
542
  const visibleCount = Math.min(this.maxAgentRows, tree.length);
433
543
  const start = selectedTreeIndex < visibleCount ? 0 : selectedTreeIndex - visibleCount + 1;
434
544
  const hiddenBelow = tree.length - (start + visibleCount);
435
545
  if (start > 0) lines.push(rightAlign("", theme.fg("dim", `↑ ${start} more`), width));
436
546
  for (let index = start; index < start + visibleCount; index++) {
437
547
  const row = tree[index]!;
438
- if (row.kind === "owner") {
548
+ if (row.kind === "owner" || row.kind === "child") {
439
549
  const ownerIndex = this.entries.findIndex((entry) => entry.key === row.entry.key);
440
- lines.push(this.renderEntry(ownerIndex + 1, selectedIndex, row.entry, width, theme));
550
+ lines.push(this.renderEntry(ownerIndex + 1, selectedIndex, row.entry, width, theme, row.kind === "child" ? (row.last ? "└─" : "├─") : undefined));
441
551
  } else {
442
552
  lines.push(this.renderNestedRow(row.row, row.last, width, theme));
443
553
  }
@@ -446,20 +556,22 @@ export class SubagentFleetStatus {
446
556
  return lines;
447
557
  }
448
558
 
449
- private renderEntry(rosterIndex: number, selectedIndex: number, entry: FleetStatusEntry, width: number, theme: Theme): string {
559
+ private renderEntry(rosterIndex: number, selectedIndex: number, entry: FleetStatusEntry, width: number, theme: Theme, branch?: string): string {
450
560
  const agent = entry.modelThinking ? `${entry.agent} (${entry.modelThinking})` : entry.agent;
451
- const left = ` ${this.bullet(rosterIndex, selectedIndex, theme)} ${theme.fg("muted", agent)} · ${entry.state}`;
561
+ const prefix = branch ? ` ${branch}` : " ";
562
+ const left = `${prefix} ${this.bullet(rosterIndex, selectedIndex, theme)} ${theme.fg("muted", agent)} · ${entry.state}`;
452
563
  const elapsed = Date.now() - entry.startedAt;
453
- const right = theme.fg("dim", `${formatFleetElapsed(elapsed)} · ${formatFleetTokens(entry.tokens)}`);
564
+ const right = theme.fg("dim", entry.external ? formatFleetElapsed(elapsed) : `${formatFleetElapsed(elapsed)} · ${formatFleetTokens(entry.tokens)}`);
454
565
  return rightAlign(left, right, width);
455
566
  }
456
567
 
457
568
  private renderNestedRow(row: FleetNestedRow, last: boolean, width: number, theme: Theme): string {
458
569
  const marker = last ? "└─" : "├─";
459
- if (row.overflow !== undefined) return truncateToWidth(` ${marker} ${theme.fg("dim", `+${row.overflow} nested leaves`)}`, width);
570
+ const indent = " ".repeat(row.depth + 1);
571
+ if (row.overflow !== undefined) return truncateToWidth(`${indent}${marker} ${theme.fg("dim", `+${row.overflow} nested leaves`)}`, width);
460
572
  const modelThinking = row.modelThinking ? ` (${row.modelThinking})` : "";
461
573
  const activity = row.activity ? ` · ${row.activity}` : "";
462
- const left = ` ${marker} ${nestedStatusGlyph(row.state, theme)} ${theme.fg("muted", `${row.name}${modelThinking}`)} · ${row.state}${activity}`;
574
+ const left = `${indent}${marker} ${nestedStatusGlyph(row.state, theme)} ${theme.fg("muted", `${row.name}${modelThinking}`)} · ${row.state}${activity}`;
463
575
  const elapsed = row.startedAt !== undefined ? ` · ${formatFleetElapsed(Date.now() - row.startedAt)}` : "";
464
576
  return truncateToWidth(`${left}${theme.fg("dim", elapsed)}`, width);
465
577
  }
@@ -504,22 +616,25 @@ export class SubagentFleetStatus {
504
616
  entries: this.entries.map((entry) => this.active
505
617
  ? [
506
618
  entry.key,
619
+ entry.parentKey,
507
620
  entry.agent,
508
621
  entry.state,
509
622
  entry.modelThinking,
510
623
  entry.description,
624
+ entry.external,
511
625
  Math.round((now - entry.startedAt) / 1000),
512
626
  entry.tokens,
513
- entry.nestedChildren?.map((child) => [
514
- child.id,
515
- child.state,
516
- child.model,
517
- child.thinking,
518
- child.lastUpdate,
519
- child.steps?.map((step) => [step.agent, step.status, step.model, step.thinking, step.lastActivityAt]),
627
+ nestedFleetRows(entry.nestedChildren, entry.parentKey ? 3 : 4).map((row) => [
628
+ row.name,
629
+ row.state,
630
+ row.modelThinking,
631
+ row.activity,
632
+ row.startedAt,
633
+ row.depth,
634
+ row.overflow,
520
635
  ]),
521
636
  ]
522
- : [entry.key, entry.state, entry.tokens]),
637
+ : [entry.key, entry.state, entry.external, entry.tokens]),
523
638
  });
524
639
  }
525
640