@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
@@ -1,7 +1,17 @@
1
+ import { normalizeWorktreeBaseRef } from "../runs/shared/worktree.ts";
2
+
1
3
  export interface PublicSubagentExecutionParams {
2
4
  action?: unknown;
5
+ capabilities?: unknown;
6
+ mode?: unknown;
7
+ repo?: unknown;
8
+ planId?: unknown;
3
9
  agent?: unknown;
4
10
  task?: unknown;
11
+ handoffPath?: unknown;
12
+ laneId?: unknown;
13
+ merge?: unknown;
14
+ supersession?: unknown;
5
15
  step?: unknown;
6
16
  tasks?: unknown;
7
17
  chain?: unknown;
@@ -10,13 +20,29 @@ export interface PublicSubagentExecutionParams {
10
20
  chainDir?: unknown;
11
21
  chainName?: unknown;
12
22
  config?: unknown;
23
+ workflow?: unknown;
24
+ args?: unknown;
13
25
  workflowScript?: unknown;
26
+ workflowScriptPath?: unknown;
27
+ sessionOnly?: unknown;
28
+ globalConcurrencyLimit?: unknown;
29
+ maxSubagentSpawnsPerRun?: unknown;
30
+ preflight?: unknown;
14
31
  isolation?: unknown;
15
32
  worktree?: unknown;
33
+ baseRef?: unknown;
34
+ lane?: unknown;
16
35
  async?: unknown;
17
36
  output?: unknown;
18
37
  resume?: unknown;
19
38
  clarify?: unknown;
39
+ workflowParentRunId?: unknown;
40
+ workflowKey?: unknown;
41
+ workflowChildAsyncId?: unknown;
42
+ workflowAwaitAsync?: unknown;
43
+ workflowAwaitDetached?: unknown;
44
+ workflowParentDeadlineAt?: unknown;
45
+ suppressRoutineResultIntercom?: unknown;
20
46
  runFanoutBudget?: unknown;
21
47
  runFanoutAdmitted?: unknown;
22
48
  }
@@ -27,30 +53,92 @@ export type PublicSubagentExecutionNormalization<T> =
27
53
  | { ok: true; params: T }
28
54
  | { ok: false; error: string; mode: PublicSubagentExecutionMode };
29
55
 
56
+ export function validateWorkflowCapacityOverrides(params: PublicSubagentExecutionParams): string | undefined {
57
+ for (const [name, value] of [
58
+ ["globalConcurrencyLimit", params.globalConcurrencyLimit],
59
+ ["maxSubagentSpawnsPerRun", params.maxSubagentSpawnsPerRun],
60
+ ] as const) {
61
+ if (value !== undefined && (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)) return `${name} must be a positive safe integer.`;
62
+ }
63
+ }
64
+
30
65
  /**
31
66
  * Enforce the public execution cutover before requests reach the executor.
32
67
  * Internal runs.run children and structured owned delegation bypass this boundary.
33
68
  */
34
- export function normalizePublicSubagentExecution<T extends PublicSubagentExecutionParams>(params: T, options: { asyncByDefault?: boolean } = {}): PublicSubagentExecutionNormalization<T> {
69
+ export function normalizePublicSubagentExecution<T extends PublicSubagentExecutionParams>(params: T): PublicSubagentExecutionNormalization<T> {
70
+ for (const field of ["resource", "resourceProvenance", "workflowResource", "workflowResourceProvenance", "workflowResourcePermit", "resourcePermit", "permit"] as const) {
71
+ if (Object.hasOwn(params, field) && (params as Record<string, unknown>)[field] !== undefined) {
72
+ return { ok: false, error: "Public execution does not accept workflow resource provenance or permit fields.", mode: params.action === undefined ? "workflow" : "management" };
73
+ }
74
+ }
75
+ if (params.baseRef !== undefined) {
76
+ if (typeof params.baseRef !== "string") return { ok: false, error: "baseRef must be a valid Git ref.", mode: params.action === undefined ? "workflow" : "management" };
77
+ try {
78
+ normalizeWorktreeBaseRef(params.baseRef);
79
+ } catch (error) {
80
+ return { ok: false, error: error instanceof Error ? error.message : String(error), mode: params.action === undefined ? "workflow" : "management" };
81
+ }
82
+ }
83
+ if (params.workflowScript !== undefined && params.workflowScriptPath !== undefined) {
84
+ return { ok: false, error: "workflowScript and workflowScriptPath are mutually exclusive.", mode: "workflow" };
85
+ }
86
+ const hasNamedWorkflow = params.workflow !== undefined;
87
+ if (hasNamedWorkflow && (typeof params.workflow !== "string" || !params.workflow.trim())) {
88
+ return { ok: false, error: "workflow must be a non-empty named workflow resource.", mode: "workflow" };
89
+ }
90
+ if (hasNamedWorkflow && (params.workflowScript !== undefined || params.workflowScriptPath !== undefined)) {
91
+ return { ok: false, error: "workflow is mutually exclusive with workflowScript and workflowScriptPath.", mode: "workflow" };
92
+ }
93
+ if (!hasNamedWorkflow && params.args !== undefined) {
94
+ return { ok: false, error: "args requires a named workflow resource.", mode: "workflow" };
95
+ }
96
+ const hasWorkflowInput = params.workflowScript !== undefined || params.workflowScriptPath !== undefined || hasNamedWorkflow;
97
+ const hasCapacityOverride = params.globalConcurrencyLimit !== undefined || params.maxSubagentSpawnsPerRun !== undefined;
98
+ if (hasCapacityOverride) {
99
+ const capacityOverrideError = validateWorkflowCapacityOverrides(params);
100
+ if (capacityOverrideError) return { ok: false, error: capacityOverrideError, mode: params.action === undefined ? "workflow" : "management" };
101
+ if (params.action !== undefined || hasNamedWorkflow || (params.workflowScript === undefined && params.workflowScriptPath === undefined)) {
102
+ return { ok: false, error: "Workflow capacity overrides are only supported on top-level workflowScript or workflowScriptPath calls.", mode: params.action === undefined ? "workflow" : "management" };
103
+ }
104
+ }
105
+ if (params.preflight !== undefined && !hasWorkflowInput) {
106
+ return { ok: false, error: "preflight requires workflowScript or workflowScriptPath.", mode: params.action === undefined ? "workflow" : "management" };
107
+ }
108
+ if (params.preflight !== undefined && hasNamedWorkflow && params.workflowScript === undefined && params.workflowScriptPath === undefined) {
109
+ return { ok: false, error: "preflight is not supported with named workflow resources.", mode: "workflow" };
110
+ }
111
+ const hasValidWorkflowInput = (typeof params.workflowScript === "string" && Boolean(params.workflowScript.trim()))
112
+ || (typeof params.workflowScriptPath === "string" && Boolean(params.workflowScriptPath.trim()))
113
+ || (typeof params.workflow === "string" && Boolean(params.workflow.trim()));
35
114
  if (params.isolation !== undefined) {
36
115
  if (params.isolation !== "none" && params.isolation !== "worktree") {
37
- return { ok: false, error: "isolation must be 'none' or 'worktree'.", mode: params.workflowScript !== undefined ? "workflow" : "management" };
116
+ return { ok: false, error: "isolation must be 'none' or 'worktree'.", mode: hasWorkflowInput ? "workflow" : "management" };
38
117
  }
39
118
  const isolationWorktree = params.isolation === "worktree";
40
119
  if (params.worktree !== undefined && params.worktree !== isolationWorktree) {
41
- return { ok: false, error: `isolation '${params.isolation}' conflicts with worktree: ${String(params.worktree)}.`, mode: params.workflowScript !== undefined ? "workflow" : "management" };
120
+ return { ok: false, error: `isolation '${params.isolation}' conflicts with worktree: ${String(params.worktree)}.`, mode: hasWorkflowInput ? "workflow" : "management" };
42
121
  }
43
122
  const { isolation: _isolation, ...normalizedParams } = params;
44
123
  params = { ...normalizedParams, worktree: isolationWorktree } as T;
45
124
  }
46
125
  if (params.runFanoutBudget !== undefined || params.runFanoutAdmitted !== undefined) {
47
- return { ok: false, error: "Public execution does not accept internal run fan-out fields.", mode: params.workflowScript !== undefined ? "workflow" : "management" };
126
+ return { ok: false, error: "Public execution does not accept internal run fan-out fields.", mode: hasWorkflowInput ? "workflow" : "management" };
127
+ }
128
+ if (params.workflowParentRunId !== undefined || params.workflowKey !== undefined || params.workflowChildAsyncId !== undefined || params.workflowAwaitAsync !== undefined || params.workflowAwaitDetached !== undefined || params.workflowParentDeadlineAt !== undefined || params.suppressRoutineResultIntercom !== undefined) {
129
+ return { ok: false, error: "Public execution does not accept internal workflow child fields.", mode: hasWorkflowInput ? "workflow" : "management" };
48
130
  }
49
131
  const action = params.action;
50
132
  if (action !== undefined && (typeof action !== "string" || !action.trim())) {
51
133
  return { ok: false, error: "action must be a non-empty management/control action, or omit action and use workflowScript.", mode: "management" };
52
134
  }
53
135
  const normalizedAction = typeof action === "string" ? action.trim() : undefined;
136
+ if (params.baseRef !== undefined && normalizedAction !== undefined && normalizedAction !== "resume" && normalizedAction !== "schedule.create") {
137
+ return { ok: false, error: "baseRef is only supported for child execution, resume, and schedule.create.", mode: "management" };
138
+ }
139
+ if (normalizedAction !== undefined && hasNamedWorkflow) {
140
+ return { ok: false, error: "Named workflow resource execution must omit action.", mode: "management" };
141
+ }
54
142
  if (params.clarify !== undefined) {
55
143
  return { ok: false, error: "Public workflowScript execution does not support clarify UI.", mode: "workflow" };
56
144
  }
@@ -81,17 +169,26 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
81
169
  if (legacyAction === "parallel" || legacyAction === "tasks" || legacyAction === "chain") {
82
170
  return { ok: false, error: "Legacy top-level chain and parallel inputs were removed; use workflowScript.", mode: "workflow" };
83
171
  }
172
+ if (normalizedAction === "validate") {
173
+ if (params.agent !== undefined || params.task !== undefined || params.step !== undefined) {
174
+ return { ok: false, error: "validate requires workflowScript or workflowScriptPath and does not accept direct agent, task, or step execution fields.", mode: "management" };
175
+ }
176
+ if (!hasValidWorkflowInput) {
177
+ return { ok: false, error: "validate requires a non-empty workflowScript or workflowScriptPath.", mode: "management" };
178
+ }
179
+ return { ok: true, params: { ...params, action: normalizedAction } };
180
+ }
84
181
  if (normalizedAction === "schedule.create") {
85
182
  if (params.agent !== undefined || params.task !== undefined || params.step !== undefined) {
86
- return { ok: false, error: "schedule.create requires workflowScript and does not accept direct agent, task, or step execution fields.", mode: "management" };
183
+ return { ok: false, error: "schedule.create requires workflowScript or workflowScriptPath and does not accept direct agent, task, or step execution fields.", mode: "management" };
87
184
  }
88
- if (typeof params.workflowScript !== "string" || !params.workflowScript.trim()) {
89
- return { ok: false, error: "schedule.create requires a non-empty workflowScript.", mode: "management" };
185
+ if (!hasValidWorkflowInput) {
186
+ return { ok: false, error: "schedule.create requires a non-empty workflowScript or workflowScriptPath.", mode: "management" };
90
187
  }
91
188
  return { ok: true, params: { ...params, action: normalizedAction } };
92
189
  }
93
- if (params.workflowScript !== undefined) {
94
- return { ok: false, error: "workflowScript execution must omit action; only schedule.create accepts action with workflowScript.", mode: "management" };
190
+ if (hasWorkflowInput) {
191
+ return { ok: false, error: "Workflow execution must omit action; only validate and schedule.create accept action with workflowScript or workflowScriptPath.", mode: "management" };
95
192
  }
96
193
  if (params.task !== undefined) {
97
194
  return { ok: false, error: "Structured single-child task cannot be combined with a management/control action.", mode: "management" };
@@ -101,8 +198,8 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
101
198
  if (params.step !== undefined) {
102
199
  return { ok: false, error: "step is not a public execution field; use workflowScript for orchestration.", mode: "workflow" };
103
200
  }
104
- if (params.workflowScript !== undefined && (params.agent !== undefined || params.task !== undefined)) {
105
- return { ok: false, error: "Structured single-child execution cannot be combined with workflowScript.", mode: "workflow" };
201
+ if (hasWorkflowInput && (params.agent !== undefined || params.task !== undefined)) {
202
+ return { ok: false, error: "Structured single-child execution cannot be combined with workflow, workflowScript, or workflowScriptPath.", mode: "workflow" };
106
203
  }
107
204
  if (params.agent !== undefined || params.task !== undefined) {
108
205
  if (typeof params.agent !== "string" || !params.agent.trim()) {
@@ -111,23 +208,17 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
111
208
  if (params.task !== undefined && typeof params.task !== "string") {
112
209
  return { ok: false, error: "Structured single-child task must be a string when provided.", mode: "workflow" };
113
210
  }
114
- const { agent: _agent, task: _task, output, ...workflowDefaults } = params;
115
- const child = {
116
- agent: params.agent.trim(),
117
- ...(params.task !== undefined ? { task: params.task } : {}),
118
- output: output === undefined ? true : output,
119
- };
120
211
  return {
121
212
  ok: true,
122
213
  params: {
123
- ...workflowDefaults,
124
- ...(params.async === undefined && options.asyncByDefault === false ? { async: false } : {}),
125
- workflowScript: `console.info("Converted structured single-child request to workflow runs.run('main', ...)."); return runs.run("main", ${JSON.stringify(child)})`,
214
+ ...params,
215
+ agent: params.agent.trim(),
216
+ output: params.output === undefined ? true : params.output,
126
217
  } as T,
127
218
  };
128
219
  }
129
- if (typeof params.workflowScript !== "string" || !params.workflowScript.trim()) {
130
- return { ok: false, error: "Execution requires either { agent, task? } for one child or a non-empty workflowScript for orchestration.", mode: "workflow" };
220
+ if (!hasValidWorkflowInput) {
221
+ return { ok: false, error: "Execution requires either { agent, task? } for one child, a named workflow resource, or a non-empty workflowScript or workflowScriptPath for orchestration.", mode: "workflow" };
131
222
  }
132
223
  return { ok: true, params };
133
224
  }
@@ -11,16 +11,20 @@ import {
11
11
  type AsyncJobStep,
12
12
  type Details,
13
13
  type SubagentState,
14
+ type TokenUsage,
14
15
  DIRS,
15
16
  SUBAGENT_ASYNC_COMPLETE_EVENT,
17
+ SUBAGENT_CHILD_STATUS_EVENT,
16
18
  SUBAGENT_PROCESS_TERMINAL_EVENT,
17
19
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
20
+ type SubagentChildStatusEvent,
18
21
  } from "../shared/types.ts";
19
22
  import { sanitizeDisplayText, truncateDisplayText } from "../shared/display-text.ts";
20
23
  import { readStatus } from "../shared/utils.ts";
21
24
  import { SubagentParams } from "./schemas.ts";
22
25
  import { normalizePublicSubagentExecution } from "./public-execution.ts";
23
26
  import { ASYNC_STATUS_SNAPSHOT_KIND, ASYNC_STATUS_SNAPSHOT_VERSION, buildAsyncStatusSnapshotForState } from "../runs/background/async-status-snapshot.ts";
27
+ import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren, type ResolvedAsyncStatusChild } from "../runs/shared/child-identity.ts";
24
28
 
25
29
  export const SUBAGENT_RPC_PROTOCOL_VERSION = 1;
26
30
  export const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
@@ -94,7 +98,7 @@ export interface SubagentRpcFleetEntry {
94
98
  model?: string;
95
99
  effort?: string;
96
100
  startedAt: number;
97
- tokens: { input: number; output: number; total: number };
101
+ tokens: TokenUsage;
98
102
  goal?: string;
99
103
  }
100
104
 
@@ -119,7 +123,7 @@ function displayText(value: unknown, maxLength: number): string | undefined {
119
123
  return normalized ? truncateDisplayText(normalized, maxLength) : undefined;
120
124
  }
121
125
 
122
- function publicTokens(value: unknown): { input: number; output: number; total: number } {
126
+ function publicTokens(value: unknown): TokenUsage {
123
127
  const record = isRecord(value) ? value : {};
124
128
  const count = (field: "input" | "output" | "total") => {
125
129
  const raw = record[field];
@@ -130,7 +134,21 @@ function publicTokens(value: unknown): { input: number; output: number; total: n
130
134
  const input = count("input");
131
135
  const output = count("output");
132
136
  const sum = Math.min(Number.MAX_SAFE_INTEGER, input + output);
133
- return { input, output, total: Math.max(sum, count("total")) };
137
+ const optionalCount = (field: "window" | "windowPeak") => {
138
+ const raw = record[field];
139
+ return typeof raw === "number" && Number.isFinite(raw) && raw >= 0
140
+ ? Math.min(Number.MAX_SAFE_INTEGER, Math.floor(raw))
141
+ : undefined;
142
+ };
143
+ const window = optionalCount("window");
144
+ const windowPeak = optionalCount("windowPeak");
145
+ return {
146
+ input,
147
+ output,
148
+ total: Math.max(sum, count("total")),
149
+ ...(window !== undefined ? { window } : {}),
150
+ ...(windowPeak !== undefined ? { windowPeak } : {}),
151
+ };
134
152
  }
135
153
 
136
154
  function activeState(value: unknown): boolean {
@@ -154,6 +172,8 @@ interface FleetCandidate {
154
172
  goal?: unknown;
155
173
  }
156
174
 
175
+ type StatusRpcParams = Pick<SubagentParamsLike, "id" | "runId" | "dir" | "index" | "view" | "lines">;
176
+
157
177
  function buildFleetStatus(
158
178
  state: SubagentState | undefined,
159
179
  keyState: FleetKeyState,
@@ -185,7 +205,7 @@ function buildFleetStatus(
185
205
  model: child.model,
186
206
  effort: child.thinking,
187
207
  startedAt: child.startedAt,
188
- tokens: { input: child.inputTokens ?? 0, output: child.outputTokens ?? 0, total: child.tokens ?? 0 },
208
+ tokens: { input: child.inputTokens ?? 0, output: child.outputTokens ?? 0, total: child.tokens ?? 0, ...(child.window !== undefined ? { window: child.window } : {}), ...(child.windowPeak !== undefined ? { windowPeak: child.windowPeak } : {}) },
189
209
  });
190
210
  } else {
191
211
  addCandidate({
@@ -194,7 +214,7 @@ function buildFleetStatus(
194
214
  model: control.model,
195
215
  effort: control.thinking,
196
216
  startedAt: control.startedAt,
197
- tokens: { input: control.inputTokens ?? 0, output: control.outputTokens ?? 0, total: control.tokens ?? 0 },
217
+ tokens: { input: control.inputTokens ?? 0, output: control.outputTokens ?? 0, total: control.tokens ?? 0, ...(control.window !== undefined ? { window: control.window } : {}), ...(control.windowPeak !== undefined ? { windowPeak: control.windowPeak } : {}) },
198
218
  });
199
219
  }
200
220
  }
@@ -362,8 +382,7 @@ function failIfToolError(result: ToolResultWithError): void {
362
382
  throw new SubagentRpcError("execution_failed", textFromToolResult(result) || "Subagent RPC execution failed.");
363
383
  }
364
384
 
365
- function normalizeTargetParams(params: unknown, method: SubagentRpcMethod): Pick<SubagentParamsLike, "id" | "runId" | "dir" | "index"> {
366
- const input = assertRecordParams(params, method);
385
+ function normalizeTargetParamsFromRecord(input: Record<string, unknown>): Pick<SubagentParamsLike, "id" | "runId" | "dir" | "index"> {
367
386
  const output: Pick<SubagentParamsLike, "id" | "runId" | "dir" | "index"> = {};
368
387
  if (input.id !== undefined) output.id = input.id as string;
369
388
  if (input.runId !== undefined) output.runId = input.runId as string;
@@ -372,6 +391,43 @@ function normalizeTargetParams(params: unknown, method: SubagentRpcMethod): Pick
372
391
  return output;
373
392
  }
374
393
 
394
+ function normalizeTargetParams(params: unknown, method: SubagentRpcMethod): Pick<SubagentParamsLike, "id" | "runId" | "dir" | "index"> {
395
+ return normalizeTargetParamsFromRecord(assertRecordParams(params, method));
396
+ }
397
+
398
+ function normalizeStatusParams(params: unknown): StatusRpcParams {
399
+ const input = assertRecordParams(params, "status");
400
+ const output: StatusRpcParams = normalizeTargetParamsFromRecord(input);
401
+ if (input.view !== undefined) output.view = input.view as StatusRpcParams["view"];
402
+ if (input.lines !== undefined) output.lines = input.lines as number;
403
+ return output;
404
+ }
405
+
406
+ function hasStatusTarget(params: StatusRpcParams): boolean {
407
+ return params.id !== undefined
408
+ || params.runId !== undefined
409
+ || params.dir !== undefined
410
+ || params.index !== undefined
411
+ || params.view !== undefined
412
+ || params.lines !== undefined;
413
+ }
414
+
415
+ function canUseInMemoryStatus(state: SubagentState | undefined, sessionId: string | undefined): state is SubagentState {
416
+ return Boolean(
417
+ state
418
+ && sessionId
419
+ && state.currentSessionId === sessionId
420
+ && state.statusProjectionSessionId === sessionId
421
+ && state.foregroundControls instanceof Map
422
+ && state.asyncJobs instanceof Map,
423
+ );
424
+ }
425
+
426
+ function inMemoryStatusSummary(fleet: SubagentRpcFleetStatus): string {
427
+ const noun = fleet.totalActive === 1 ? "child" : "children";
428
+ return `In-memory subagent status: ${fleet.totalActive} active ${noun}.`;
429
+ }
430
+
375
431
  function sessionData(ctx: ExtensionContext | null): { cwd?: string; sessionId?: string; sessionFile?: string | null } {
376
432
  if (!ctx) return {};
377
433
  return {
@@ -387,6 +443,7 @@ function pingData(ctx: ExtensionContext | null) {
387
443
  methods: [...SUBAGENT_RPC_METHODS],
388
444
  capabilities: {
389
445
  status: true,
446
+ statusProjection: { version: 1, untargeted: "in-memory-when-ready", targeted: "executor" },
390
447
  managementActions: [...SUBAGENT_RPC_MANAGEMENT_ACTIONS],
391
448
  fleetStatus: { version: 1 },
392
449
  asyncStatusSnapshot: { kind: ASYNC_STATUS_SNAPSHOT_KIND, version: ASYNC_STATUS_SNAPSHOT_VERSION },
@@ -405,6 +462,7 @@ function pingData(ctx: ExtensionContext | null) {
405
462
  request: SUBAGENT_RPC_REQUEST_EVENT,
406
463
  replyPrefix: SUBAGENT_RPC_REPLY_EVENT_PREFIX,
407
464
  asyncComplete: SUBAGENT_ASYNC_COMPLETE_EVENT,
465
+ childStatus: SUBAGENT_CHILD_STATUS_EVENT,
408
466
  processTerminal: SUBAGENT_PROCESS_TERMINAL_EVENT,
409
467
  },
410
468
  session: sessionData(ctx),
@@ -500,8 +558,14 @@ function stopAsyncRun(
500
558
  params: unknown,
501
559
  options: RegisterSubagentRpcBridgeOptions,
502
560
  ctx: ExtensionContext,
503
- ): { runId: string; asyncDir: string; previousState: string; state: "stopping"; message: string } {
504
- const target = normalizeTargetParams(params, "stop");
561
+ ): { runId: string; asyncDir: string; previousState: string; state: "stopping"; message: string; childId?: string } {
562
+ const input = assertRecordParams(params, "stop");
563
+ const rawChildId = input.childId;
564
+ if (rawChildId !== undefined && (typeof rawChildId !== "string" || !rawChildId.trim() || /[\r\n]/.test(rawChildId) || rawChildId.length > 256)) {
565
+ throw new SubagentRpcError("invalid_params", "RPC stop childId must be a non-empty string without newlines and at most 256 characters.");
566
+ }
567
+ const childId = typeof rawChildId === "string" ? rawChildId : undefined;
568
+ const target = normalizeTargetParams(input, "stop");
505
569
  assertSubagentParams({ action: "status", ...target }, "RPC stop target params");
506
570
  const asyncDirRoot = options.asyncDirRoot ?? DIRS.async;
507
571
  const resultsDir = options.resultsDir ?? DIRS.results;
@@ -523,8 +587,83 @@ function stopAsyncRun(
523
587
  throw new SubagentRpcError("not_found", `Async run '${initialRunId}' was not found in the active session.`);
524
588
  }
525
589
 
590
+ let child: ResolvedAsyncStatusChild | undefined;
591
+ const emitChildStopping = (runId: string, asyncDir: string, stoppedChild: ResolvedAsyncStatusChild, ts = options.now?.() ?? Date.now()): void => {
592
+ options.events.emit(SUBAGENT_CHILD_STATUS_EVENT, {
593
+ type: "subagent.child-status",
594
+ version: 1,
595
+ runId,
596
+ childId: stoppedChild.id,
597
+ status: "stopping",
598
+ ts,
599
+ reason: "rpc",
600
+ source: "rpc",
601
+ asyncDir,
602
+ stepIndex: stoppedChild.index,
603
+ agent: stoppedChild.step.agent,
604
+ ...(stoppedChild.step.runId ? { childRunId: stoppedChild.step.runId } : {}),
605
+ ...(stoppedChild.step.workflowKey ? { workflowKey: stoppedChild.step.workflowKey } : {}),
606
+ ...(stoppedChild.step.phase ? { phase: stoppedChild.step.phase } : {}),
607
+ ...(stoppedChild.step.label ? { label: stoppedChild.step.label } : {}),
608
+ } satisfies SubagentChildStatusEvent);
609
+ };
610
+ if (childId !== undefined) {
611
+ const resolution = resolveAsyncStatusChild(initialStatus, childId);
612
+ if (!resolution.ok) throw new SubagentRpcError(resolution.code === "not_found" ? "not_found" : "invalid_params", resolution.message);
613
+ child = resolution.child;
614
+ if (!isStoppableAsyncStatusStep(child.step)) {
615
+ throw new SubagentRpcError("invalid_state", `Child '${childId}' in async run '${initialRunId}' is ${child.step.status}; stop only supports pending or running children.`);
616
+ }
617
+ }
526
618
  if (initialStatus.mode === "workflow" && initialStatus.state === "running") {
527
- throw new SubagentRpcError("invalid_state", `Workflow ${initialRunId} is not controlled by this extension runtime; reload recovery cannot stop it safely.`);
619
+ const stopChild = options.state?.workflowChildStops?.get(initialRunId);
620
+ if (child) {
621
+ if (stopChild) {
622
+ if (!stopChild(child.id, `Workflow child '${child.id}' stopped by RPC.`)) throw new SubagentRpcError("invalid_state", `Child '${childId}' in workflow ${initialRunId} is not available to stop.`);
623
+ emitChildStopping(initialRunId, location.asyncDir, child);
624
+ return {
625
+ runId: initialRunId,
626
+ asyncDir: location.asyncDir,
627
+ previousState: initialStatus.state,
628
+ state: "stopping",
629
+ childId: child.id,
630
+ message: `Stop requested for child ${child.id} in async run ${initialRunId}.`,
631
+ };
632
+ }
633
+ }
634
+ const workflowController = options.state?.workflowControllers?.get(initialRunId);
635
+ if (workflowController && !child) {
636
+ stopStoppableAsyncStatusChildren(initialStatus, stopChild, "Workflow stopped by RPC.");
637
+ workflowController.abort(new Error("Workflow stopped by RPC."));
638
+ return {
639
+ runId: initialRunId,
640
+ asyncDir: location.asyncDir,
641
+ previousState: initialStatus.state,
642
+ state: "stopping",
643
+ message: `Stop requested for async run ${initialRunId}.`,
644
+ };
645
+ }
646
+ try {
647
+ deliverStopRequest({
648
+ asyncDir: location.asyncDir,
649
+ pid: initialStatus.pid,
650
+ kill: options.kill,
651
+ now: options.now,
652
+ source: "rpc-stop",
653
+ ...(child ? { targetIndex: child.index, childId: child.id } : {}),
654
+ });
655
+ } catch (error) {
656
+ throw new SubagentRpcError("execution_failed", error instanceof Error ? error.message : String(error));
657
+ }
658
+ if (child) emitChildStopping(initialRunId, location.asyncDir, child);
659
+ return {
660
+ runId: initialRunId,
661
+ asyncDir: location.asyncDir,
662
+ previousState: initialStatus.state,
663
+ state: "stopping",
664
+ ...(child ? { childId: child.id } : {}),
665
+ message: child ? `Stop requested for child ${child.id} in async run ${initialRunId}.` : `Stop requested for async run ${initialRunId}.`,
666
+ };
528
667
  }
529
668
 
530
669
  let status;
@@ -541,6 +680,14 @@ function stopAsyncRun(
541
680
  if (status.state !== "running") {
542
681
  throw new SubagentRpcError("invalid_state", `Async run ${runId} is ${status.state}; stop only supports running async runs.`);
543
682
  }
683
+ if (childId !== undefined) {
684
+ const resolution = resolveAsyncStatusChild(status, childId);
685
+ if (!resolution.ok) throw new SubagentRpcError(resolution.code === "not_found" ? "not_found" : "invalid_params", resolution.message);
686
+ child = resolution.child;
687
+ if (!isStoppableAsyncStatusStep(child.step)) {
688
+ throw new SubagentRpcError("invalid_state", `Child '${childId}' in async run '${runId}' is ${child.step.status}; stop only supports pending or running children.`);
689
+ }
690
+ }
544
691
 
545
692
  try {
546
693
  deliverStopRequest({
@@ -549,17 +696,20 @@ function stopAsyncRun(
549
696
  kill: options.kill,
550
697
  now: options.now,
551
698
  source: "rpc-stop",
699
+ ...(child ? { targetIndex: child.index, childId: child.id } : {}),
552
700
  });
553
701
  } catch (error) {
554
702
  throw new SubagentRpcError("execution_failed", error instanceof Error ? error.message : String(error));
555
703
  }
704
+ if (child) emitChildStopping(runId, location.asyncDir, child);
556
705
 
557
706
  return {
558
707
  runId,
559
708
  asyncDir: location.asyncDir,
560
709
  previousState: status.state,
561
710
  state: "stopping",
562
- message: `Stop requested for async run ${runId}.`,
711
+ ...(child ? { childId: child.id } : {}),
712
+ message: child ? `Stop requested for child ${child.id} in async run ${runId}.` : `Stop requested for async run ${runId}.`,
563
713
  };
564
714
  }
565
715
 
@@ -579,14 +729,33 @@ async function handleRequest(
579
729
  return executeChecked(options, ctx, request.requestId, request.method, spawnParams(request.params));
580
730
  }
581
731
  if (request.method === "status") {
732
+ const statusParams = normalizeStatusParams(request.params);
733
+ let sessionId: string | undefined;
734
+ if (!hasStatusTarget(statusParams)) {
735
+ try {
736
+ sessionId = resolveCurrentSessionId(ctx.sessionManager);
737
+ } catch {
738
+ // Let the executor produce the canonical error when session identity is unavailable.
739
+ }
740
+ if (canUseInMemoryStatus(options.state, sessionId)) {
741
+ const fleet = buildFleetStatus(options.state, fleetKeys, sessionId);
742
+ const asyncSnapshot = buildAsyncStatusSnapshotForState(options.state, sessionId);
743
+ return {
744
+ text: inMemoryStatusSummary(fleet),
745
+ details: { mode: "management", results: [] },
746
+ fleet,
747
+ asyncSnapshot,
748
+ };
749
+ }
750
+ }
582
751
  const status = await executeChecked(
583
752
  options,
584
753
  ctx,
585
754
  request.requestId,
586
755
  request.method,
587
- { action: "status", ...normalizeTargetParams(request.params, "status") },
756
+ { action: "status", ...statusParams },
588
757
  );
589
- const sessionId = resolveCurrentSessionId(ctx.sessionManager);
758
+ sessionId ??= resolveCurrentSessionId(ctx.sessionManager);
590
759
  return {
591
760
  ...status,
592
761
  fleet: buildFleetStatus(