@xzzpig/pi-subagents 0.7.0 → 0.9.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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -15,7 +15,7 @@
15
15
 
16
16
  import { splitKnownThinkingSuffix } from "../../shared/model-info.ts";
17
17
 
18
- export interface ModelScopeConfig {
18
+ export interface ModelScopeRule {
19
19
  enforce?: boolean;
20
20
  /** Reject inherited and fallback models outside the allowlist instead of warning. */
21
21
  strict?: boolean;
@@ -23,6 +23,19 @@ export interface ModelScopeConfig {
23
23
  allow?: string[];
24
24
  }
25
25
 
26
+ export interface ModelScopeConfig extends ModelScopeRule {
27
+ /** Additional restrictions keyed by canonical agent name. */
28
+ agents?: Record<string, ModelScopeRule>;
29
+ }
30
+
31
+ export interface ModelScopeCheckRule extends ModelScopeRule {
32
+ origin?: string;
33
+ }
34
+
35
+ export interface ResolvedModelScope extends ModelScopeCheckRule {
36
+ origin: string;
37
+ }
38
+
26
39
  /** Where a resolved model originated, deciding enforcement severity. */
27
40
  export type ModelSource = "explicit" | "inherited";
28
41
 
@@ -32,6 +45,7 @@ export interface ModelScopeViolation {
32
45
  severity: "warn" | "error";
33
46
  message: string;
34
47
  allowedPatterns: string[];
48
+ origin: string;
35
49
  }
36
50
 
37
51
  function stripThinkingSuffix(model: string): string {
@@ -61,7 +75,7 @@ export function matchesScopePattern(model: string, pattern: string): boolean {
61
75
  */
62
76
  export function checkModelScope(
63
77
  model: string | undefined,
64
- scope: ModelScopeConfig | undefined,
78
+ scope: ModelScopeCheckRule | undefined,
65
79
  source: ModelSource,
66
80
  ): ModelScopeViolation | undefined {
67
81
  if (!model || !scope?.enforce) return undefined;
@@ -71,16 +85,89 @@ export function checkModelScope(
71
85
 
72
86
  const baseModel = stripThinkingSuffix(model);
73
87
  const severity: ModelScopeViolation["severity"] = source === "explicit" || scope.strict === true ? "error" : "warn";
88
+ const origin = scope.origin ?? "modelScope";
74
89
  return {
75
90
  model: baseModel,
76
91
  severity,
77
92
  allowedPatterns: allow,
93
+ origin,
78
94
  message:
79
- `Model '${baseModel}' is outside the configured subagent model scope. ` +
95
+ `Model '${baseModel}' is outside the configured subagent model scope (${origin}). ` +
80
96
  `Allowed patterns: ${allow.join(", ")}.`,
81
97
  };
82
98
  }
83
99
 
100
+ function expandInheritPattern(pattern: string, parentModel: { provider: string; id: string } | undefined): string {
101
+ return pattern === "inherit" && parentModel ? `${parentModel.provider}/${parentModel.id}` : pattern;
102
+ }
103
+
104
+ function assertRecord(value: unknown, field: string, meta: { filePath: string }, expected = "an object"): Record<string, unknown> {
105
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
106
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}'; expected ${expected}.`);
107
+ }
108
+ return value as Record<string, unknown>;
109
+ }
110
+
111
+ function parseAllowList(value: unknown, field: string, meta: { filePath: string }): string[] {
112
+ if (!Array.isArray(value)) {
113
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}'; expected an array of strings.`);
114
+ }
115
+ const allow: string[] = [];
116
+ for (const entry of value) {
117
+ if (typeof entry !== "string") {
118
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}'; expected an array of strings.`);
119
+ }
120
+ const trimmed = entry.trim();
121
+ if (trimmed) allow.push(trimmed);
122
+ }
123
+ if (allow.length === 0) {
124
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}'; expected a non-empty array of patterns.`);
125
+ }
126
+ return allow;
127
+ }
128
+
129
+ function parseScopeRule(input: Record<string, unknown>, field: string, meta: { filePath: string }): ModelScopeRule {
130
+ const rule: ModelScopeRule = {};
131
+ if ("enforce" in input) {
132
+ if (typeof input.enforce !== "boolean") throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}.enforce'; expected a boolean.`);
133
+ rule.enforce = input.enforce;
134
+ }
135
+ if ("strict" in input) {
136
+ if (typeof input.strict !== "boolean") throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}.strict'; expected a boolean.`);
137
+ rule.strict = input.strict;
138
+ }
139
+ if ("allow" in input) rule.allow = parseAllowList(input.allow, `${field}.allow`, meta);
140
+ return rule;
141
+ }
142
+
143
+ /** Resolve the global and matching agent policies into independent launch-time checks. */
144
+ export function resolveModelScopesForAgent(
145
+ config: ModelScopeConfig | undefined,
146
+ agentName: string,
147
+ parentModel: { provider: string; id: string } | undefined,
148
+ ): ResolvedModelScope[] {
149
+ if (!config) return [];
150
+ const scopes: ResolvedModelScope[] = [];
151
+ if (config.allow) {
152
+ scopes.push({
153
+ ...(config.enforce !== undefined ? { enforce: config.enforce } : {}),
154
+ ...(config.strict !== undefined ? { strict: config.strict } : {}),
155
+ allow: config.allow.map((pattern) => expandInheritPattern(pattern, parentModel)),
156
+ origin: "modelScope",
157
+ });
158
+ }
159
+ const agentScope = config.agents?.[agentName];
160
+ if (agentScope?.allow) {
161
+ scopes.push({
162
+ enforce: agentScope.enforce ?? config.enforce,
163
+ strict: agentScope.strict ?? config.strict,
164
+ allow: agentScope.allow.map((pattern) => expandInheritPattern(pattern, parentModel)),
165
+ origin: `modelScope.agents.${agentName}`,
166
+ });
167
+ }
168
+ return scopes;
169
+ }
170
+
84
171
  /**
85
172
  * Validate and normalize a raw `subagents.modelScope` value from settings.
86
173
  * Throws a descriptive error for malformed configs (matching the surrounding
@@ -91,46 +178,26 @@ export function parseModelScopeConfig(
91
178
  meta: { filePath: string },
92
179
  ): ModelScopeConfig | undefined {
93
180
  if (value === undefined) return undefined;
94
- if (!value || typeof value !== "object" || Array.isArray(value)) {
95
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope'; expected an object.`);
96
- }
97
-
98
- const input = value as Record<string, unknown>;
99
- const config: ModelScopeConfig = {};
100
-
101
- if ("enforce" in input) {
102
- if (typeof input.enforce !== "boolean") {
103
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.enforce'; expected a boolean.`);
104
- }
105
- config.enforce = input.enforce;
106
- }
107
-
108
- if ("strict" in input) {
109
- if (typeof input.strict !== "boolean") {
110
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.strict'; expected a boolean.`);
111
- }
112
- config.strict = input.strict;
113
- }
114
-
115
- if ("allow" in input) {
116
- if (!Array.isArray(input.allow)) {
117
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.allow'; expected an array of strings.`);
118
- }
119
- const allow: string[] = [];
120
- for (const entry of input.allow) {
121
- if (typeof entry !== "string") {
122
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.allow'; expected an array of strings.`);
181
+ const input = assertRecord(value, "modelScope", meta);
182
+ const config: ModelScopeConfig = parseScopeRule(input, "modelScope", meta);
183
+
184
+ if ("agents" in input) {
185
+ const agents: Record<string, ModelScopeRule> = {};
186
+ for (const [rawName, rawScope] of Object.entries(assertRecord(input.agents, "modelScope.agents", meta, "an object keyed by agent name"))) {
187
+ const name = rawName.trim();
188
+ const field = `modelScope.agents.${name}`;
189
+ if (!name) throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.agents' key; expected a non-empty agent name.`);
190
+ const agentInput = assertRecord(rawScope, field, meta);
191
+ if ("agents" in agentInput) {
192
+ throw new Error(`Subagent settings in '${meta.filePath}' have invalid '${field}.agents'; nested agent scopes are not supported.`);
123
193
  }
124
- const trimmed = entry.trim();
125
- if (trimmed) allow.push(trimmed);
126
- }
127
- if (allow.length === 0) {
128
- throw new Error(`Subagent settings in '${meta.filePath}' have invalid 'modelScope.allow'; expected a non-empty array of patterns.`);
194
+ agents[name] = parseScopeRule(agentInput, field, meta);
129
195
  }
130
- config.allow = allow;
196
+ config.agents = agents;
131
197
  }
132
198
 
133
- if (config.enforce === true && (!config.allow || config.allow.length === 0)) {
199
+ const hasAnyAllow = Boolean(config.allow?.length) || Object.values(config.agents ?? {}).some((scope) => Boolean(scope.allow?.length));
200
+ if (config.enforce === true && !hasAnyAllow) {
134
201
  throw new Error(`Subagent settings in '${meta.filePath}' set modelScope.enforce without a non-empty 'allow' list; supply allowed model patterns or disable enforcement.`);
135
202
  }
136
203
 
@@ -0,0 +1,199 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import * as fs from "node:fs";
4
+ import * as os from "node:os";
5
+ import * as path from "node:path";
6
+ import type { ArtifactPaths, TimeoutRecoveryProjection, TimeoutRecoverySummary, TrackedMutationEvidence, TrackedMutationFingerprint, TrackedMutationSnapshot } from "../../shared/types.ts";
7
+
8
+ const MAX_TRACKED_PATHS = 500;
9
+ const MAX_HASH_BYTES = 1024 * 1024;
10
+ const MAX_TIMEOUT_FILES = 20;
11
+
12
+ function gitArguments(args: string[]): string[] {
13
+ // Mutation evidence must not block child startup on a stale fsmonitor daemon.
14
+ return ["-c", "core.fsmonitor=false", ...args];
15
+ }
16
+
17
+ function gitOutput(cwd: string, args: string[], maxBuffer = MAX_HASH_BYTES): string {
18
+ return execFileSync("git", gitArguments(args), { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer, windowsHide: true });
19
+ }
20
+
21
+ function splitNul(output: string): string[] {
22
+ return output.split("\0").filter((part) => part.length > 0);
23
+ }
24
+
25
+ function hashLargeDiff(cwd: string, relativePath: string): string {
26
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagents-tracked-diff-"));
27
+ const diffPath = path.join(tempDir, "diff.patch");
28
+ try {
29
+ execFileSync("git", gitArguments(["diff", "--no-ext-diff", "--binary", `--output=${diffPath}`, "HEAD", "--", relativePath]), { cwd, stdio: "ignore", windowsHide: true });
30
+ const hash = createHash("sha256");
31
+ const buffer = Buffer.allocUnsafe(64 * 1024);
32
+ const fd = fs.openSync(diffPath, "r");
33
+ try {
34
+ for (;;) {
35
+ const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, null);
36
+ if (bytesRead === 0) break;
37
+ hash.update(buffer.subarray(0, bytesRead));
38
+ }
39
+ } finally {
40
+ fs.closeSync(fd);
41
+ }
42
+ return hash.digest("hex");
43
+ } finally {
44
+ fs.rmSync(tempDir, { recursive: true, force: true });
45
+ }
46
+ }
47
+
48
+ function listChangedTrackedFiles(cwd: string): { paths: string[]; truncated: boolean } {
49
+ const paths = splitNul(gitOutput(cwd, ["diff", "--no-ext-diff", "--name-only", "-z", "HEAD", "--"], MAX_HASH_BYTES));
50
+ return { paths: paths.slice(0, MAX_TRACKED_PATHS), truncated: paths.length > MAX_TRACKED_PATHS };
51
+ }
52
+
53
+ function fingerprintPath(cwd: string, relativePath: string): TrackedMutationFingerprint {
54
+ try {
55
+ const diff = gitOutput(cwd, ["diff", "--no-ext-diff", "--binary", "HEAD", "--", relativePath], MAX_HASH_BYTES);
56
+ return { kind: "diff", digest: createHash("sha256").update(diff).digest("hex") };
57
+ } catch {
58
+ return { kind: "diff", digest: hashLargeDiff(cwd, relativePath) };
59
+ }
60
+ }
61
+
62
+ function sameFingerprint(left: TrackedMutationFingerprint | undefined, right: TrackedMutationFingerprint): boolean {
63
+ if (!left || left.kind !== "diff" || right.kind !== "diff") return false;
64
+ return left.digest === right.digest;
65
+ }
66
+
67
+ export function snapshotTrackedMutations(cwd: string): TrackedMutationSnapshot {
68
+ try {
69
+ const changed = listChangedTrackedFiles(cwd);
70
+ const fingerprints: Record<string, TrackedMutationFingerprint> = {};
71
+ for (const file of changed.paths) fingerprints[file] = fingerprintPath(cwd, file);
72
+ return { source: "tracked-files", trackedOnly: true, cwd, dirtyFiles: changed.paths, fingerprints, truncated: changed.truncated };
73
+ } catch (error) {
74
+ return { source: "tracked-files", trackedOnly: true, cwd, dirtyFiles: [], fingerprints: {}, unavailable: error instanceof Error ? error.message : String(error) };
75
+ }
76
+ }
77
+
78
+ export function collectTrackedMutationEvidence(snapshot: TrackedMutationSnapshot, cwd = snapshot.cwd): TrackedMutationEvidence {
79
+ if (snapshot.unavailable) {
80
+ return { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: false, unavailable: snapshot.unavailable };
81
+ }
82
+ try {
83
+ const current = listChangedTrackedFiles(cwd);
84
+ const startDirty = new Set(snapshot.dirtyFiles);
85
+ const candidates = new Set([...snapshot.dirtyFiles, ...current.paths]);
86
+ const changedFiles: string[] = [];
87
+ for (const file of candidates) {
88
+ if (!startDirty.has(file)) {
89
+ if (!snapshot.truncated) changedFiles.push(file);
90
+ continue;
91
+ }
92
+ if (!sameFingerprint(snapshot.fingerprints[file], fingerprintPath(cwd, file))) changedFiles.push(file);
93
+ }
94
+ changedFiles.sort();
95
+ return {
96
+ source: "tracked-files",
97
+ trackedOnly: true,
98
+ changedFiles,
99
+ attemptedMutation: changedFiles.length > 0,
100
+ truncated: snapshot.truncated || current.truncated || undefined,
101
+ };
102
+ } catch (error) {
103
+ return { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: false, unavailable: error instanceof Error ? error.message : String(error) };
104
+ }
105
+ }
106
+
107
+ function formatPathList(paths: string[]): string {
108
+ if (paths.length === 0) return "none";
109
+ const shown = paths.slice(0, MAX_TIMEOUT_FILES).join(", ");
110
+ return paths.length > MAX_TIMEOUT_FILES ? `${shown}, ... (${paths.length - MAX_TIMEOUT_FILES} more)` : shown;
111
+ }
112
+
113
+ /** Keep status and completion details to bounded routing evidence, not raw output or effects. */
114
+ export function projectTimeoutRecovery(value: unknown): TimeoutRecoveryProjection | undefined {
115
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
116
+ const source = value as Record<string, unknown>;
117
+ const termination = source.termination === "timed-out" || source.termination === "stopped" ? source.termination : undefined;
118
+ if (!termination || !Array.isArray(source.changedFiles)) return undefined;
119
+ const allChangedFiles = source.changedFiles.filter((file): file is string => typeof file === "string");
120
+ const changedFiles = allChangedFiles.slice(0, MAX_TIMEOUT_FILES);
121
+ const reportStatus = source.reportStatus === "missing"
122
+ || source.reportStatus === "written"
123
+ || source.reportStatus === "not-requested"
124
+ || source.reportStatus === "unknown"
125
+ ? source.reportStatus
126
+ : undefined;
127
+ return {
128
+ termination,
129
+ changedFiles,
130
+ ...(source.truncated === true || allChangedFiles.length > changedFiles.length ? { truncated: true } : {}),
131
+ ...(source.recoveryNeeded === true ? { recoveryNeeded: true } : {}),
132
+ ...(source.reason === "timed-out-with-dirty-worktree" ? { reason: source.reason } : {}),
133
+ ...(reportStatus ? { reportStatus } : {}),
134
+ };
135
+ }
136
+
137
+ /** Render only the bounded recovery route needed by a parent/operator. */
138
+ export function formatTimeoutRecoveryLines(value: unknown, indent = ""): string[] {
139
+ const recovery = projectTimeoutRecovery(value);
140
+ if (!recovery?.recoveryNeeded) return [];
141
+ const changedFiles = recovery.changedFiles.length > 0
142
+ ? `${recovery.changedFiles.join(", ")}${recovery.truncated ? ", …" : ""}`
143
+ : "none";
144
+ const changedFileCount = recovery.changedFiles.length > 0 ? `${recovery.changedFiles.length}${recovery.truncated ? "+" : ""}` : "0";
145
+ return [
146
+ `${indent}Recovery needed: review the diff and artifacts before resuming or launching dependent stages.`,
147
+ `${indent}Recovery evidence: requested report: ${recovery.reportStatus ?? "unknown"}; changed tracked files: ${changedFiles} (${changedFileCount}); classification: ${recovery.reason ?? recovery.termination}`,
148
+ ];
149
+ }
150
+
151
+ export function buildTimeoutRecoverySummary(input: {
152
+ termination: "timed-out" | "stopped";
153
+ evidence: TrackedMutationEvidence;
154
+ requiredOutputMissing?: boolean;
155
+ currentTool?: string;
156
+ currentToolArgs?: string;
157
+ currentPath?: string;
158
+ sessionFile?: string;
159
+ transcriptPath?: string;
160
+ artifactPaths?: ArtifactPaths;
161
+ }): TimeoutRecoverySummary {
162
+ const warning = "Inspect partial changes before retrying or resuming the child.";
163
+ const changedFiles = input.evidence.changedFiles.slice(0, MAX_TIMEOUT_FILES);
164
+ let reportStatus: "missing" | "written" | "not-requested" = "not-requested";
165
+ if (input.requiredOutputMissing === true) reportStatus = "missing";
166
+ else if (input.requiredOutputMissing === false) reportStatus = "written";
167
+ const recoveryNeeded = input.termination === "timed-out"
168
+ && reportStatus === "missing"
169
+ && input.evidence.changedFiles.length > 0;
170
+ const lines = [
171
+ "Recovery summary:",
172
+ `- termination: ${input.termination}`,
173
+ `- changed tracked files: ${input.evidence.unavailable ? `unavailable (${input.evidence.unavailable})` : formatPathList(input.evidence.changedFiles)}`,
174
+ ];
175
+ if (input.requiredOutputMissing !== undefined) lines.push(`- requested report: ${reportStatus}`);
176
+ if (recoveryNeeded) lines.push("- Recovery needed: review the diff and artifacts before resuming or launching dependent stages.");
177
+ if (input.currentTool) lines.push(`- active tool: ${input.currentTool}${input.currentToolArgs ? ` — ${input.currentToolArgs}` : ""}`);
178
+ if (input.currentPath) lines.push(`- active path: ${input.currentPath}`);
179
+ if (input.sessionFile) lines.push(`- session file: ${input.sessionFile}`);
180
+ if (input.transcriptPath) lines.push(`- transcript: ${input.transcriptPath}`);
181
+ if (input.artifactPaths?.outputPath) lines.push(`- output artifact: ${input.artifactPaths.outputPath}`);
182
+ if (input.artifactPaths?.metadataPath) lines.push(`- metadata artifact: ${input.artifactPaths.metadataPath}`);
183
+ lines.push(`Warning: ${warning}`);
184
+ return {
185
+ termination: input.termination,
186
+ changedFiles,
187
+ truncated: input.evidence.changedFiles.length > changedFiles.length || input.evidence.truncated || undefined,
188
+ ...(recoveryNeeded ? { recoveryNeeded: true, reason: "timed-out-with-dirty-worktree" as const } : {}),
189
+ reportStatus,
190
+ currentTool: input.currentTool,
191
+ currentToolArgs: input.currentToolArgs,
192
+ currentPath: input.currentPath,
193
+ sessionFile: input.sessionFile,
194
+ transcriptPath: input.transcriptPath,
195
+ artifactPaths: input.artifactPaths,
196
+ warning,
197
+ message: lines.join("\n"),
198
+ };
199
+ }
@@ -16,17 +16,7 @@ import {
16
16
  type SubagentRunMode,
17
17
  type SubagentState,
18
18
  } from "../../shared/types.ts";
19
- import { isSafeNestedPathId, parseNestedPathEnv, sanitizeNestedPath, type NestedPathEntry } from "./nested-path.ts";
20
- import {
21
- SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV,
22
- SUBAGENT_PARENT_CHILD_INDEX_ENV,
23
- SUBAGENT_PARENT_CONTROL_INBOX_ENV,
24
- SUBAGENT_PARENT_DEPTH_ENV,
25
- SUBAGENT_PARENT_EVENT_SINK_ENV,
26
- SUBAGENT_PARENT_PATH_ENV,
27
- SUBAGENT_PARENT_ROOT_RUN_ID_ENV,
28
- SUBAGENT_PARENT_RUN_ID_ENV,
29
- } from "./pi-args.ts";
19
+ import { isSafeNestedPathId, sanitizeNestedPath, type NestedPathEntry } from "./nested-path.ts";
30
20
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
31
21
  import { sanitizeProcessTerminal } from "../background/process-terminal.ts";
32
22
  import { THINKING_LEVELS } from "../../shared/model-info.ts";
@@ -141,13 +131,9 @@ export function createNestedRoute(rootRunId: string): NestedRoute {
141
131
  return { rootRunId, eventSink, controlInbox, capabilityToken };
142
132
  }
143
133
 
144
- export function resolveNestedRouteFromEnv(env: NodeJS.ProcessEnv = process.env): NestedRoute | undefined {
145
- const rootRunId = env[SUBAGENT_PARENT_ROOT_RUN_ID_ENV];
146
- const eventSink = env[SUBAGENT_PARENT_EVENT_SINK_ENV];
147
- const controlInbox = env[SUBAGENT_PARENT_CONTROL_INBOX_ENV];
148
- const capabilityToken = env[SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV];
149
- if (!rootRunId || !eventSink || !controlInbox || !capabilityToken) return undefined;
150
- const route = { rootRunId, eventSink, controlInbox, capabilityToken };
134
+ /** Validate a route handed to an in-process child against its on-disk metadata. */
135
+ export function resolveNestedRoute(route: NestedRoute): NestedRoute {
136
+ const { rootRunId, capabilityToken } = route;
151
137
  validateRouteShape(route);
152
138
  const routeFile = path.join(commonRouteRoot(route), ROUTE_FILE);
153
139
  const metadata = JSON.parse(fs.readFileSync(routeFile, "utf-8")) as { rootRunId?: unknown; capabilityToken?: unknown };
@@ -157,24 +143,38 @@ export function resolveNestedRouteFromEnv(env: NodeJS.ProcessEnv = process.env):
157
143
  return route;
158
144
  }
159
145
 
160
- export function resolveInheritedNestedRouteFromEnv(env: NodeJS.ProcessEnv = process.env): NestedRoute | undefined {
146
+ export function resolveInheritedNestedRoute(route: NestedRoute): NestedRoute | undefined {
161
147
  try {
162
- return resolveNestedRouteFromEnv(env);
148
+ return resolveNestedRoute(route);
163
149
  } catch (error) {
164
150
  console.error("Ignoring invalid nested subagent event route:", error);
165
151
  return undefined;
166
152
  }
167
153
  }
168
154
 
169
- export function resolveNestedParentAddressFromEnv(env: NodeJS.ProcessEnv = process.env): { parentRunId: string; parentStepIndex?: number; depth: number; path: NestedPathEntry[] } | undefined {
170
- const parentRunId = env[SUBAGENT_PARENT_RUN_ID_ENV];
171
- if (!isSafeNestedId(parentRunId)) return undefined;
172
- const rawIndex = env[SUBAGENT_PARENT_CHILD_INDEX_ENV];
173
- const parentStepIndex = rawIndex && /^\d+$/.test(rawIndex) ? Number(rawIndex) : undefined;
174
- const depth = Math.min(Math.max(1, clampNumber(Number(env[SUBAGENT_PARENT_DEPTH_ENV])) ?? 1), MAX_DEPTH);
175
- const parsedPath = parseNestedPathEnv(env[SUBAGENT_PARENT_PATH_ENV]);
176
- const nestedPath = parsedPath.length ? parsedPath : [{ runId: parentRunId, ...(parentStepIndex !== undefined ? { stepIndex: parentStepIndex } : {}) }];
177
- return { parentRunId, ...(parentStepIndex !== undefined ? { parentStepIndex } : {}), depth, path: nestedPath };
155
+ export interface NestedParentAddress {
156
+ parentRunId: string;
157
+ parentStepIndex?: number;
158
+ depth: number;
159
+ path: NestedPathEntry[];
160
+ }
161
+
162
+ /** The nested route an executor inherited from its own child runtime, validated against disk. */
163
+ export function inheritedNestedRouteOf(runtime: { nestedRoute?: NestedRoute } | undefined): NestedRoute | undefined {
164
+ return runtime?.nestedRoute ? resolveInheritedNestedRoute(runtime.nestedRoute) : undefined;
165
+ }
166
+
167
+ /** The executor's own position in the nested run tree, from its child runtime. */
168
+ export function inheritedNestedParentAddressOf(runtime: { nestedParent?: { parentRunId: string; parentChildIndex?: number; depth: number; path: NestedPathEntry[] } } | undefined): NestedParentAddress | undefined {
169
+ const parent = runtime?.nestedParent;
170
+ if (!parent || !isSafeNestedId(parent.parentRunId)) return undefined;
171
+ const depth = Math.min(Math.max(1, clampNumber(parent.depth) ?? 1), MAX_DEPTH);
172
+ return {
173
+ parentRunId: parent.parentRunId,
174
+ ...(parent.parentChildIndex !== undefined ? { parentStepIndex: parent.parentChildIndex } : {}),
175
+ depth,
176
+ path: parent.path.length ? parent.path : [{ runId: parent.parentRunId, ...(parent.parentChildIndex !== undefined ? { stepIndex: parent.parentChildIndex } : {}) }],
177
+ };
178
178
  }
179
179
 
180
180
  export function resolveNestedAsyncDir(rootRunId: string, run: NestedRunSummary): string | undefined {
@@ -199,8 +199,10 @@ function sanitizeTokenUsage(value: unknown): NestedRunSummary["totalTokens"] | u
199
199
  const input = clampNumber(raw.input);
200
200
  const output = clampNumber(raw.output);
201
201
  const total = clampNumber(raw.total);
202
+ const window = clampNumber(raw.window);
203
+ const windowPeak = clampNumber(raw.windowPeak);
202
204
  return input !== undefined && output !== undefined && total !== undefined
203
- ? { input, output, total }
205
+ ? { input, output, total, ...(window !== undefined ? { window } : {}), ...(windowPeak !== undefined ? { windowPeak } : {}) }
204
206
  : undefined;
205
207
  }
206
208
 
@@ -284,7 +286,7 @@ function sanitizeTurnBudget(value: unknown): TurnBudgetState | undefined {
284
286
  }
285
287
 
286
288
  function sanitizeState(value: unknown, fallback: NestedRunState): NestedRunState {
287
- return value === "queued" || value === "running" || value === "complete" || value === "failed" || value === "paused" || value === "stopped"
289
+ return value === "queued" || value === "running" || value === "complete" || value === "failed" || value === "partial" || value === "paused" || value === "stopped"
288
290
  ? value
289
291
  : fallback;
290
292
  }
@@ -304,6 +306,7 @@ function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefi
304
306
  status,
305
307
  ...(model ? { model } : {}),
306
308
  ...(thinking ? { thinking } : {}),
309
+ ...(stringValue(raw.sessionName, 256) ? { sessionName: stringValue(raw.sessionName, 256) } : {}),
307
310
  ...(stringValue(raw.sessionFile, 2048) ? { sessionFile: stringValue(raw.sessionFile, 2048) } : {}),
308
311
  ...(raw.activityState === "active_long_running" || raw.activityState === "needs_attention" ? { activityState: raw.activityState } : {}),
309
312
  ...(clampNumber(raw.lastActivityAt) !== undefined ? { lastActivityAt: clampNumber(raw.lastActivityAt) } : {}),
@@ -344,6 +347,7 @@ export function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | u
344
347
  depth: Math.min(Math.max(0, clampNumber(raw.depth) ?? 0), MAX_DEPTH),
345
348
  path: pathParts,
346
349
  state: sanitizeState(raw.state, "running"),
350
+ ...(stringValue(raw.sessionName, 256) ? { sessionName: stringValue(raw.sessionName, 256) } : {}),
347
351
  ...(stringValue(raw.model) ? { model: stringValue(raw.model) } : {}),
348
352
  ...(THINKING_LEVELS.find((level) => level === raw.thinking) ? { thinking: THINKING_LEVELS.find((level) => level === raw.thinking) } : {}),
349
353
  ...(stringValue(raw.asyncDir, 2048) ? { asyncDir: stringValue(raw.asyncDir, 2048) } : {}),
@@ -434,7 +438,7 @@ export function parseNestedEventRecords(content: string, route: NestedRoute): Ne
434
438
  }
435
439
 
436
440
  function terminal(state: NestedRunState): boolean {
437
- return state === "complete" || state === "failed" || state === "paused" || state === "stopped";
441
+ return state === "complete" || state === "failed" || state === "partial" || state === "paused" || state === "stopped";
438
442
  }
439
443
 
440
444
  function mergeBoundedChildren(existing: NestedRunSummary[] | undefined, incoming: NestedRunSummary[] | undefined): NestedRunSummary[] | undefined {
@@ -943,15 +947,6 @@ export function readNestedControlResults(route: NestedRoute): NestedControlResul
943
947
  .flatMap((entry) => readControlResultsFromFile(route, path.join(route.eventSink, entry)));
944
948
  }
945
949
 
946
- export function nestedRouteEnv(route: NestedRoute): Record<string, string> {
947
- return {
948
- [SUBAGENT_PARENT_EVENT_SINK_ENV]: route.eventSink,
949
- [SUBAGENT_PARENT_CONTROL_INBOX_ENV]: route.controlInbox,
950
- [SUBAGENT_PARENT_ROOT_RUN_ID_ENV]: route.rootRunId,
951
- [SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV]: route.capabilityToken,
952
- };
953
- }
954
-
955
950
  export function attachRootChildrenToSteps<T extends { children?: NestedRunSummary[]; index?: number }>(rootRunId: string, steps: T[] | undefined, children: NestedRunSummary[] | undefined): void {
956
951
  if (!steps?.length) return;
957
952
  for (const step of steps) {
@@ -1003,6 +998,7 @@ export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: stri
1003
998
  mode: status.mode ?? fallback.mode,
1004
999
  ...(status.steps?.length === 1 && status.steps[0]?.model ? { model: status.steps[0].model } : {}),
1005
1000
  ...(status.steps?.length === 1 && status.steps[0]?.thinking ? { thinking: status.steps[0].thinking } : {}),
1001
+ ...(status.steps?.length === 1 && status.steps[0]?.sessionName ? { sessionName: status.steps[0].sessionName } : {}),
1006
1002
  ...(status.processTerminal ? { processTerminal: sanitizeProcessTerminal(status.processTerminal, { runId: status.runId || fallback.id, runnerProcessInstanceId: status.processTerminal.runnerProcessInstanceId }, `${asyncDir}/status.json`) } : {}),
1007
1003
  ...(status.launchResolvedExtensions ? { launchResolvedExtensions: status.launchResolvedExtensions } : {}),
1008
1004
  ...runtimeAcknowledgedEntry(status.runtimeAcknowledgedExtensions),
@@ -1033,6 +1029,7 @@ export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: stri
1033
1029
  ...(status.sessionFile ? { sessionFile: status.sessionFile } : {}),
1034
1030
  ...(status.steps?.length ? { steps: status.steps.map((step, index) => ({
1035
1031
  agent: step.agent,
1032
+ ...(step.sessionName ? { sessionName: step.sessionName } : {}),
1036
1033
  status: step.status,
1037
1034
  ...(step.model ? { model: step.model } : {}),
1038
1035
  ...(step.thinking ? { thinking: step.thinking } : {}),
@@ -1061,13 +1058,6 @@ export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: stri
1061
1058
  };
1062
1059
  }
1063
1060
 
1064
- export function nestedArtifactEnv(rootRunId: string, parentRunId: string): Record<string, string> {
1065
- return {
1066
- PI_SUBAGENT_NESTED_ROOT_RUN_ID: rootRunId,
1067
- PI_SUBAGENT_NESTED_PARENT_RUN_ID: parentRunId,
1068
- };
1069
- }
1070
-
1071
1061
  export function isTopLevelAsyncDir(asyncDir: string): boolean {
1072
1062
  const resolved = path.resolve(asyncDir);
1073
1063
  return containedPath(DIRS.async, resolved) && !containedPath(path.join(TEMP_ROOT_DIR, "nested-subagent-runs"), resolved);
@@ -36,17 +36,3 @@ export function sanitizeNestedPath(value: unknown): NestedPathEntry[] {
36
36
  };
37
37
  }).filter((part): part is NestedPathEntry => Boolean(part)).slice(0, MAX_NESTED_PATH_ENTRIES);
38
38
  }
39
-
40
- export function parseNestedPathEnv(value: string | undefined): NestedPathEntry[] {
41
- if (!value) return [];
42
- try {
43
- return sanitizeNestedPath(JSON.parse(value) as unknown);
44
- } catch {
45
- return [];
46
- }
47
- }
48
-
49
- export function encodeNestedPathEnv(value: NestedPathEntry[]): string {
50
- const sanitized = sanitizeNestedPath(value);
51
- return sanitized.length ? JSON.stringify(sanitized) : "";
52
- }
@@ -1,6 +1,6 @@
1
- import { formatDuration, formatModelThinking, formatTokens, shortenPath } from "../../shared/formatters.ts";
1
+ import { formatDuration, formatModelThinking, formatTokenUsage, shortenPath } from "../../shared/formatters.ts";
2
2
  import { formatActivityLabel } from "../../shared/status-format.ts";
3
- import type { ActivityState, NestedRunSummary, NestedStepSummary } from "../../shared/types.ts";
3
+ import type { ActivityState, NestedRunSummary } from "../../shared/types.ts";
4
4
 
5
5
  export interface NestedRunCounts {
6
6
  total: number;
@@ -8,13 +8,14 @@ export interface NestedRunCounts {
8
8
  paused: number;
9
9
  complete: number;
10
10
  failed: number;
11
+ partial: number;
11
12
  rejected: number;
12
13
  stopped: number;
13
14
  queued: number;
14
15
  }
15
16
 
16
17
  export function countNestedRuns(children: NestedRunSummary[] | undefined): NestedRunCounts {
17
- const counts: NestedRunCounts = { total: 0, running: 0, paused: 0, complete: 0, failed: 0, rejected: 0, stopped: 0, queued: 0 };
18
+ const counts: NestedRunCounts = { total: 0, running: 0, paused: 0, complete: 0, failed: 0, partial: 0, rejected: 0, stopped: 0, queued: 0 };
18
19
  for (const child of children ?? []) {
19
20
  counts.total++;
20
21
  counts[child.state]++;
@@ -24,6 +25,7 @@ export function countNestedRuns(children: NestedRunSummary[] | undefined): Neste
24
25
  counts.paused += nested.paused;
25
26
  counts.complete += nested.complete;
26
27
  counts.failed += nested.failed;
28
+ counts.partial += nested.partial;
27
29
  counts.rejected += nested.rejected;
28
30
  counts.stopped += nested.stopped;
29
31
  counts.queued += nested.queued;
@@ -38,6 +40,7 @@ export function formatNestedAggregate(children: NestedRunSummary[] | undefined):
38
40
  counts.running > 0 ? `${counts.running} running` : "",
39
41
  counts.paused > 0 ? `${counts.paused} paused` : "",
40
42
  counts.failed > 0 ? `${counts.failed} failed` : "",
43
+ counts.partial > 0 ? `${counts.partial} partial` : "",
41
44
  counts.rejected > 0 ? `${counts.rejected} rejected` : "",
42
45
  counts.stopped > 0 ? `${counts.stopped} stopped` : "",
43
46
  counts.complete > 0 ? `${counts.complete} complete` : "",
@@ -47,6 +50,7 @@ export function formatNestedAggregate(children: NestedRunSummary[] | undefined):
47
50
  }
48
51
 
49
52
  function nestedRunLabel(run: NestedRunSummary): string {
53
+ if (run.sessionName?.trim()) return run.sessionName.trim();
50
54
  if (run.agent) return run.agent;
51
55
  if (run.agents?.length) return run.agents.length === 1 ? run.agents[0]! : `${run.agents.slice(0, 2).join(", ")}${run.agents.length > 2 ? ` +${run.agents.length - 2}` : ""}`;
52
56
  return run.id;
@@ -68,7 +72,7 @@ function formatNestedActivity(input: {
68
72
  if (input.currentPath) facts.push(shortenPath(input.currentPath));
69
73
  if (input.turnCount !== undefined) facts.push(`${input.turnCount} turns`);
70
74
  if (input.toolCount !== undefined) facts.push(`${input.toolCount} tools`);
71
- if (input.totalTokens) facts.push(`${formatTokens(input.totalTokens.total)} tok`);
75
+ if (input.totalTokens) facts.push(formatTokenUsage(input.totalTokens));
72
76
  const activity = formatActivityLabel(input.lastActivityAt, input.activityState as ActivityState | undefined);
73
77
  return activity || facts.length ? [activity, ...facts].filter(Boolean).join(" | ") : undefined;
74
78
  }
@@ -103,7 +107,7 @@ function formatNestedRunLines(children: NestedRunSummary[] | undefined, options:
103
107
  if (lines.length >= options.maxLines) return;
104
108
  const stepActivity = step.status === "running" ? formatNestedActivity(step) : undefined;
105
109
  const stepModelThinking = formatModelThinking(step.model, step.thinking);
106
- lines.push(`${indent} ${stepIndex + 1}. ${step.agent} ${step.status}${stepModelThinking ? ` | ${stepModelThinking}` : ""}${stepActivity ? ` | ${stepActivity}` : ""}${step.error ? ` | error: ${step.error}` : ""}`);
110
+ lines.push(`${indent} ${stepIndex + 1}. ${step.sessionName?.trim() || step.agent} ${step.status}${stepModelThinking ? ` | ${stepModelThinking}` : ""}${stepActivity ? ` | ${stepActivity}` : ""}${step.error ? ` | error: ${step.error}` : ""}`);
107
111
  append(step.children, depth + 1, `${indent} `);
108
112
  }
109
113
  append(child.children, depth + 1, `${indent} `);