@xzzpig/pi-subagents 0.8.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 (218) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/README.md +2 -2
  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 +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +151 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +5 -4
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +370 -114
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +12 -2
  35. package/src/agents/agents.ts +919 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +31 -20
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +48 -18
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +57 -21
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +2 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +366 -128
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +45 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +189 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +676 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +468 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1172 -400
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +314 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +342 -0
  115. package/src/runs/shared/child-tool-plan.ts +540 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +142 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +38 -48
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +15 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/single-output.ts +89 -22
  149. package/src/runs/shared/structured-output.ts +49 -9
  150. package/src/runs/shared/subagent-control.ts +6 -2
  151. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  152. package/src/runs/shared/task-intent.ts +21 -7
  153. package/src/runs/shared/tool-availability.ts +18 -62
  154. package/src/runs/shared/tool-budget.ts +0 -14
  155. package/src/runs/shared/tool-timeout.ts +1 -1
  156. package/src/runs/shared/workflow-graph.ts +16 -0
  157. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  158. package/src/runs/shared/worktree.ts +571 -62
  159. package/src/shared/atomic-json.ts +3 -1
  160. package/src/shared/child-session-name.ts +46 -0
  161. package/src/shared/extension-context.ts +24 -0
  162. package/src/shared/fork-context.ts +21 -12
  163. package/src/shared/fork-session-cwd.ts +27 -0
  164. package/src/shared/formatters.ts +18 -3
  165. package/src/shared/jsonl-writer.ts +11 -0
  166. package/src/shared/launch-contract.ts +8 -1
  167. package/src/shared/pruned-fork.ts +450 -0
  168. package/src/shared/session-file-trust.ts +19 -0
  169. package/src/shared/session-tokens.ts +14 -3
  170. package/src/shared/settings.ts +19 -105
  171. package/src/shared/shortcuts.ts +17 -0
  172. package/src/shared/thinking-ceiling.ts +0 -6
  173. package/src/shared/types.ts +524 -70
  174. package/src/shared/utils.ts +60 -93
  175. package/src/shared/workflow-child-permit.ts +207 -0
  176. package/src/slash/delegation-adapters.ts +1 -9
  177. package/src/slash/delegation-request.ts +0 -4
  178. package/src/slash/prompt-template-bridge.ts +37 -1
  179. package/src/slash/slash-bridge.ts +1 -2
  180. package/src/slash/slash-commands.ts +383 -116
  181. package/src/slash/slash-live-state.ts +22 -11
  182. package/src/slash/subagents-admin.ts +29 -12
  183. package/src/tui/fleet-native-transcript.ts +4 -0
  184. package/src/tui/fleet-status.ts +217 -82
  185. package/src/tui/fleet-transcript.ts +11 -5
  186. package/src/tui/fleet.ts +54 -28
  187. package/src/tui/render-helpers.ts +31 -0
  188. package/src/tui/render.ts +1429 -163
  189. package/src/watchdog/change-signature.ts +40 -1
  190. package/src/watchdog/child-status.ts +54 -34
  191. package/src/watchdog/diff-tool.ts +77 -0
  192. package/src/watchdog/emission-guard.ts +5 -3
  193. package/src/watchdog/guidance.ts +20 -0
  194. package/src/watchdog/register-child.ts +28 -25
  195. package/src/watchdog/register-main.ts +10 -9
  196. package/src/watchdog/render.ts +4 -5
  197. package/src/watchdog/review.ts +15 -4
  198. package/src/watchdog/rules.ts +70 -0
  199. package/src/watchdog/runtime.ts +75 -92
  200. package/src/watchdog/scope.ts +0 -11
  201. package/src/watchdog/settings.ts +48 -104
  202. package/src/watchdog/turn-delta.ts +1 -1
  203. package/src/watchdog/types.ts +18 -32
  204. package/src/watchdog/warning-format.ts +0 -1
  205. package/src/workflows/chat-progress.ts +7 -3
  206. package/src/workflows/host-command.ts +235 -0
  207. package/src/workflows/scripted-workflow.ts +988 -59
  208. package/src/workflows/workflow-checklist.ts +439 -0
  209. package/src/workflows/workflow-child-summary.ts +121 -0
  210. package/src/workflows/workflow-preflight.ts +297 -0
  211. package/src/workflows/workflow-receipt.ts +232 -6
  212. package/src/workflows/workflow-resources.ts +150 -0
  213. package/src/workflows/workflow-settlement.ts +246 -0
  214. package/src/runs/shared/child-protocol.ts +0 -401
  215. package/src/runs/shared/pi-args.ts +0 -935
  216. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  217. package/src/runs/shared/turn-budget.ts +0 -98
  218. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -11,6 +11,7 @@ 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,
16
17
  SUBAGENT_CHILD_STATUS_EVENT,
@@ -23,7 +24,7 @@ import { readStatus } from "../shared/utils.ts";
23
24
  import { SubagentParams } from "./schemas.ts";
24
25
  import { normalizePublicSubagentExecution } from "./public-execution.ts";
25
26
  import { ASYNC_STATUS_SNAPSHOT_KIND, ASYNC_STATUS_SNAPSHOT_VERSION, buildAsyncStatusSnapshotForState } from "../runs/background/async-status-snapshot.ts";
26
- import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, type ResolvedAsyncStatusChild } from "../runs/shared/child-identity.ts";
27
+ import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren, type ResolvedAsyncStatusChild } from "../runs/shared/child-identity.ts";
27
28
 
28
29
  export const SUBAGENT_RPC_PROTOCOL_VERSION = 1;
29
30
  export const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
@@ -97,7 +98,7 @@ export interface SubagentRpcFleetEntry {
97
98
  model?: string;
98
99
  effort?: string;
99
100
  startedAt: number;
100
- tokens: { input: number; output: number; total: number };
101
+ tokens: TokenUsage;
101
102
  goal?: string;
102
103
  }
103
104
 
@@ -122,7 +123,7 @@ function displayText(value: unknown, maxLength: number): string | undefined {
122
123
  return normalized ? truncateDisplayText(normalized, maxLength) : undefined;
123
124
  }
124
125
 
125
- function publicTokens(value: unknown): { input: number; output: number; total: number } {
126
+ function publicTokens(value: unknown): TokenUsage {
126
127
  const record = isRecord(value) ? value : {};
127
128
  const count = (field: "input" | "output" | "total") => {
128
129
  const raw = record[field];
@@ -133,7 +134,21 @@ function publicTokens(value: unknown): { input: number; output: number; total: n
133
134
  const input = count("input");
134
135
  const output = count("output");
135
136
  const sum = Math.min(Number.MAX_SAFE_INTEGER, input + output);
136
- 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
+ };
137
152
  }
138
153
 
139
154
  function activeState(value: unknown): boolean {
@@ -157,6 +172,8 @@ interface FleetCandidate {
157
172
  goal?: unknown;
158
173
  }
159
174
 
175
+ type StatusRpcParams = Pick<SubagentParamsLike, "id" | "runId" | "dir" | "index" | "view" | "lines">;
176
+
160
177
  function buildFleetStatus(
161
178
  state: SubagentState | undefined,
162
179
  keyState: FleetKeyState,
@@ -188,7 +205,7 @@ function buildFleetStatus(
188
205
  model: child.model,
189
206
  effort: child.thinking,
190
207
  startedAt: child.startedAt,
191
- 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 } : {}) },
192
209
  });
193
210
  } else {
194
211
  addCandidate({
@@ -197,7 +214,7 @@ function buildFleetStatus(
197
214
  model: control.model,
198
215
  effort: control.thinking,
199
216
  startedAt: control.startedAt,
200
- 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 } : {}) },
201
218
  });
202
219
  }
203
220
  }
@@ -365,8 +382,7 @@ function failIfToolError(result: ToolResultWithError): void {
365
382
  throw new SubagentRpcError("execution_failed", textFromToolResult(result) || "Subagent RPC execution failed.");
366
383
  }
367
384
 
368
- function normalizeTargetParams(params: unknown, method: SubagentRpcMethod): Pick<SubagentParamsLike, "id" | "runId" | "dir" | "index"> {
369
- const input = assertRecordParams(params, method);
385
+ function normalizeTargetParamsFromRecord(input: Record<string, unknown>): Pick<SubagentParamsLike, "id" | "runId" | "dir" | "index"> {
370
386
  const output: Pick<SubagentParamsLike, "id" | "runId" | "dir" | "index"> = {};
371
387
  if (input.id !== undefined) output.id = input.id as string;
372
388
  if (input.runId !== undefined) output.runId = input.runId as string;
@@ -375,6 +391,43 @@ function normalizeTargetParams(params: unknown, method: SubagentRpcMethod): Pick
375
391
  return output;
376
392
  }
377
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
+
378
431
  function sessionData(ctx: ExtensionContext | null): { cwd?: string; sessionId?: string; sessionFile?: string | null } {
379
432
  if (!ctx) return {};
380
433
  return {
@@ -390,6 +443,7 @@ function pingData(ctx: ExtensionContext | null) {
390
443
  methods: [...SUBAGENT_RPC_METHODS],
391
444
  capabilities: {
392
445
  status: true,
446
+ statusProjection: { version: 1, untargeted: "in-memory-when-ready", targeted: "executor" },
393
447
  managementActions: [...SUBAGENT_RPC_MANAGEMENT_ACTIONS],
394
448
  fleetStatus: { version: 1 },
395
449
  asyncStatusSnapshot: { kind: ASYNC_STATUS_SNAPSHOT_KIND, version: ASYNC_STATUS_SNAPSHOT_VERSION },
@@ -542,7 +596,7 @@ function stopAsyncRun(
542
596
  childId: stoppedChild.id,
543
597
  status: "stopping",
544
598
  ts,
545
- reason: "user",
599
+ reason: "rpc",
546
600
  source: "rpc",
547
601
  asyncDir,
548
602
  stepIndex: stoppedChild.index,
@@ -562,22 +616,24 @@ function stopAsyncRun(
562
616
  }
563
617
  }
564
618
  if (initialStatus.mode === "workflow" && initialStatus.state === "running") {
619
+ const stopChild = options.state?.workflowChildStops?.get(initialRunId);
565
620
  if (child) {
566
- const stopChild = options.state?.workflowChildStops?.get(initialRunId);
567
- if (!stopChild) throw new SubagentRpcError("invalid_state", `Workflow ${initialRunId} is not controlled by this extension runtime; child stop is unavailable.`);
568
- 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.`);
569
- emitChildStopping(initialRunId, location.asyncDir, child);
570
- return {
571
- runId: initialRunId,
572
- asyncDir: location.asyncDir,
573
- previousState: initialStatus.state,
574
- state: "stopping",
575
- childId: child.id,
576
- message: `Stop requested for child ${child.id} in async run ${initialRunId}.`,
577
- };
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
+ }
578
633
  }
579
634
  const workflowController = options.state?.workflowControllers?.get(initialRunId);
580
- if (workflowController) {
635
+ if (workflowController && !child) {
636
+ stopStoppableAsyncStatusChildren(initialStatus, stopChild, "Workflow stopped by RPC.");
581
637
  workflowController.abort(new Error("Workflow stopped by RPC."));
582
638
  return {
583
639
  runId: initialRunId,
@@ -587,7 +643,27 @@ function stopAsyncRun(
587
643
  message: `Stop requested for async run ${initialRunId}.`,
588
644
  };
589
645
  }
590
- throw new SubagentRpcError("invalid_state", `Workflow ${initialRunId} is not controlled by this extension runtime; reload recovery cannot stop it safely.`);
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
+ };
591
667
  }
592
668
 
593
669
  let status;
@@ -653,14 +729,33 @@ async function handleRequest(
653
729
  return executeChecked(options, ctx, request.requestId, request.method, spawnParams(request.params));
654
730
  }
655
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
+ }
656
751
  const status = await executeChecked(
657
752
  options,
658
753
  ctx,
659
754
  request.requestId,
660
755
  request.method,
661
- { action: "status", ...normalizeTargetParams(request.params, "status") },
756
+ { action: "status", ...statusParams },
662
757
  );
663
- const sessionId = resolveCurrentSessionId(ctx.sessionManager);
758
+ sessionId ??= resolveCurrentSessionId(ctx.sessionManager);
664
759
  return {
665
760
  ...status,
666
761
  fleet: buildFleetStatus(
@@ -86,10 +86,13 @@ const AcceptanceOverride = Type.Unsafe({
86
86
  deprecated: true,
87
87
  description: "Invalid as an explicit policy. Recognized only so preflight can explain that reviewed is an achieved status.",
88
88
  },
89
+ {
90
+ type: "string",
91
+ },
89
92
  { type: "boolean", enum: [false] },
90
93
  { type: "object", additionalProperties: true },
91
94
  ],
92
- description: `Optional acceptance policy. For reviewer/read-only calls, omit acceptance. Example: { level: "checked", evidence: ["commands-run", "changed-files"] }. Supported evidence kinds: ${AcceptanceEvidenceKinds.join(", ")}. Evidence levels end at verified; use acceptance.review.required for review. Omitted means auto-inferred unless agentContract compatibility behavior is enabled.`,
95
+ description: `Optional acceptance policy. Prefer an inline JSON object. JSON-encoded object strings are tolerated only during input normalization; invalid strings fail closed. Reviewer/read-only calls, omit acceptance. { level: "checked", evidence: ["commands-run", "changed-files"] }. Supported evidence kinds: ${AcceptanceEvidenceKinds.join(",")}. acceptance.review.required.`,
93
96
  });
94
97
 
95
98
  const AgentContractOverride = Type.Object({
@@ -101,10 +104,14 @@ const ChainGateOverride = Type.String({
101
104
  description: "For chain steps with agentContract, choose whether the chain advances on execution success or acceptance success. Defaults to execution.",
102
105
  });
103
106
 
104
- const TurnBudgetOverride = Type.Object({
105
- maxTurns: Type.Integer({ minimum: 1 }),
106
- graceTurns: Type.Optional(Type.Integer({ minimum: 0 })),
107
- }, { additionalProperties: false, description: "Optional assistant-turn budget. At maxTurns the child is asked to wrap up; after graceTurns additional assistant turns it is aborted and partial output is returned." });
107
+ const WorkflowLaneMetadata = Type.Object({
108
+ version: Type.Integer({ minimum: 1, maximum: 1 }),
109
+ key: Type.String({ minLength: 1, maxLength: 128, pattern: "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" }),
110
+ mode: Type.Optional(Type.String({ enum: ["mutation", "review", "scout", "gate"] })),
111
+ sourceRef: Type.Optional(Type.String({ minLength: 1, maxLength: 128 })),
112
+ claims: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 160 }), { maxItems: 20 })),
113
+ outputPaths: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 256 }), { maxItems: 10 })),
114
+ }, { additionalProperties: false, description: "Optional bounded child lane metadata. Display/triage only; sourceRef is opaque and never resolved during status rendering." });
108
115
 
109
116
  const ToolBudgetBlock = Type.Unsafe({
110
117
  anyOf: [
@@ -129,6 +136,21 @@ const UsageBudgetOverride = Type.Object({
129
136
  costUsd: Type.Optional(UsageBudgetLimitOverride),
130
137
  }, { additionalProperties: false, description: "Optional root-only reported-usage budget. Hard limits prevent future child launches; running children are not stopped." });
131
138
 
139
+ const WorkflowPreflightLane = Type.Object({
140
+ key: Type.String({ minLength: 1, maxLength: 128 }),
141
+ mode: Type.Optional(Type.String({ enum: ["mutation", "review", "scout", "gate"] })),
142
+ decision: Type.Optional(Type.String({ maxLength: 256 })),
143
+ claims: Type.Optional(Type.Array(Type.String({ maxLength: 256 }), { maxItems: 16 })),
144
+ expectedOutput: Type.Optional(Type.String({ maxLength: 256 })),
145
+ independence: Type.Optional(Type.String({ maxLength: 256 })),
146
+ }, { additionalProperties: false });
147
+
148
+ const WorkflowPreflightOverride = Type.Object({
149
+ version: Type.Integer({ minimum: 1, maximum: 1 }),
150
+ coverage: Type.Optional(Type.String({ enum: ["complete", "partial"] })),
151
+ lanes: Type.Array(WorkflowPreflightLane, { maxItems: 64 }),
152
+ }, { additionalProperties: false, description: "Bounded display-only lane hints for workflow launch/status. V1 coverage mismatches warn but never change launch authority or execution." });
153
+
132
154
  // Parallel task item (within a parallel step)
133
155
  export const ParallelTaskSchema = Type.Object({
134
156
  agent: Type.String(),
@@ -257,12 +279,13 @@ const ControlOverrides = Type.Object({
257
279
 
258
280
  const SubagentParamProperties = {
259
281
  agent: Type.Optional(Type.String({ description: "Agent for one-child execution, or target for agent management actions." })),
260
- task: Type.Optional(Type.String({ description: "Optional one-child task. Requires agent; cannot combine with action or workflowScript." })),
282
+ task: Type.Optional(Type.String({ description: "Optional one-child task. Requires agent; cannot combine with action, workflowScript, or workflowScriptPath." })),
261
283
  extensionBindings: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Namespaced, bounded plain-JSON metadata delivered only to the child runtime. Namespace keys use package.name/1 syntax." })),
262
284
  // Management action (when present, tool operates in management mode)
263
285
  action: Type.Optional(Type.String({ minLength: 1,
264
- description: "Optional management/control action. Omit this field for structured single-child or workflowScript execution; use it only for management/control actions."
286
+ description: "Optional management/control action. Use action='validate' with workflowScript or workflowScriptPath for offline checks. Omit this field for structured single-child or workflow execution; otherwise, use it only for management/control actions."
265
287
  })),
288
+ capabilities: Type.Optional(Type.Boolean({ description: "For action='list', return compact capability rows and structured details without system prompts." })),
266
289
  name: Type.Optional(Type.String({ description: "Human-readable name for action='schedule.create'." })),
267
290
  id: Type.Optional(Type.String({
268
291
  description: "Run id/prefix for status/debug.run, interrupt, steer, or mission.attach-run."
@@ -273,7 +296,12 @@ const SubagentParamProperties = {
273
296
  dir: Type.Optional(Type.String({
274
297
  description: "Async run directory for status/debug.run, stop, resume, or steer."
275
298
  })),
276
- handoffPath: Type.Optional(Type.String({ description: "worktree.discard manifest." })),
299
+ handoffPath: Type.Optional(Type.String({ description: "Existing parallel handoff manifest for worktree.discard, worktree.cleanup metadata, or lane evidence actions." })),
300
+ repo: Type.Optional(Type.String({ description: "Repository path for action='worktree.cleanup'; defaults to cwd." })),
301
+ planId: Type.Optional(Type.String({ description: "Cleanup plan id reserved for a future worktree.cleanup apply action." })),
302
+ laneId: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Exact manifest run id for lane.status, lane.recordMerge, or lane.recordSupersession." })),
303
+ merge: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "Attested merge evidence for lane.recordMerge: prNumber, reviewedHead, mergeCommit, treeEquivalent, postMergeChecks, attestedBy, and attestedAt." })),
304
+ supersession: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "Attested replacement-lane evidence for lane.recordSupersession: supersededBy, attestedBy, and attestedAt." })),
277
305
  index: Type.Optional(Type.Integer({ minimum: 0, description: "Zero-based child index for actions that target a specific child or transcript." })),
278
306
  childId: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "Stable child identity for child-scoped stop requests." })),
279
307
  view: Type.Optional(Type.String({
@@ -283,17 +311,18 @@ const SubagentParamProperties = {
283
311
  lines: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "Maximum transcript lines for action='status', view='transcript'. Defaults to 80." })),
284
312
  topic: Type.Optional(Type.String()),
285
313
  message: Type.Optional(Type.String({ description: "Follow-up message for resume, live guidance for steer, or optional startup prompt for project.open." })),
286
- mode: Type.Optional(Type.String({ enum: ["steer", "follow_up", "auto"], description: "Delivery mode for action='steer'. steer interrupts at the next safe point (default), follow_up waits for the next turn boundary, and auto follows up mid-turn but delivers immediately between turns." })),
314
+ mode: Type.Optional(Type.String({ enum: ["steer", "follow_up", "auto", "plan", "apply"], description: "Delivery mode for action='steer', or plan/apply mode for worktree.cleanup. worktree.cleanup currently supports plan only; apply/removal is not available yet." })),
287
315
  steeringRecovery: Type.Optional(Type.Boolean({ description: "For action='steer', allow pause-and-revive recovery after a missed acknowledgment. Defaults true for direct tool calls in steer mode; extension RPC steering forces false so callers retain exact child ownership." })),
288
316
  additional: Type.Optional(Type.Integer({ minimum: 1, description: "Positive launches to add with action='grant-spawn-budget'. Root interactive parent with native user confirmation only; total grants cannot exceed the original configured cap." })),
289
317
  scope: Type.Optional(Type.String({ enum: ["session", "user", "project"], description: "Scope for action='watchdog.configure'. Defaults to session to avoid persistent settings writes unless user/project is explicit." })),
290
318
  target: Type.Optional(Type.String({ enum: ["main", "children", "child"], description: "Target for watchdog actions." })),
291
319
  focus: Type.Optional(Type.Boolean({ description: "Focus the new Herdr pane for inspector.open or project.open." })),
292
- thinking: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "boolean", enum: [false] }], description: "Thinking level for action='watchdog.configure' (off/minimal/low/medium/high/xhigh/max, inherit, or false for off)." })),
320
+ thinking: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "boolean", enum: [false] }], description: "Thinking level for action='watchdog.configure' only (off/minimal/low/medium/high/xhigh/max, inherit, or false for off). Ignored on dispatch; set per-run child thinking with a suffix on the model string, e.g. model: 'provider/id:high'." })),
293
321
  at: Type.Optional(Type.String({ description: "One-shot trigger for action='schedule.create': a relative delay such as '+10m' or an ISO timestamp with timezone." })),
294
322
  every: Type.Optional(Type.String({ description: "Fixed recurring interval for action='schedule.create', such as '30m', '6h', '2d', or '2w'." })),
323
+ sessionOnly: Type.Optional(Type.Boolean()),
295
324
  on: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "integer" }], description: "Calendar selector reserved for a later schedule slice." })),
296
- timezone: Type.Optional(Type.String({ description: "IANA timezone reserved for a later calendar schedule slice." })),
325
+ timezone: Type.Optional(Type.String()),
297
326
  overlap: Type.Optional(Type.String({ enum: ["skip"], description: "Overlap policy. This slice supports skip only." })),
298
327
  catchUp: Type.Optional(Type.String({ enum: ["none", "latest"], description: "Missed occurrence policy for recurring schedules. Defaults to latest." })),
299
328
  missionId: Type.Optional(Type.String({ description: "Mission id." })),
@@ -312,19 +341,26 @@ const SubagentParamProperties = {
312
341
  ],
313
342
  description: "Agent config for create/update. Object or JSON string."
314
343
  })),
315
- workflowScript: Type.Optional(Type.String({ minLength: 1, description: "Trusted inline JavaScript statement body. Normally async unless asyncByDefault:false; set async:true when async matters. Use async:false only when the parent must block until completion, never for reviews or gates. Use explicit return for output. Use top-level await, plain helper functions, or explicit Promise chains; nested async function, arrow, and method helpers are rejected. Use await runs.run(key, {agent, task, worktree?, gate?}) or runs.run(key, {resume, task}), where resume is a retained run id or {workflowRunId,key,latest:true} from a durable async workflow receipt. Use runs.all([...]), await runs.steer(key, message, {mode?, index?, ackTimeoutMs?}), runs.status(id), runs.ref(s), emit(value), console, and return. For ordinary parallel fanout, use await runs.all([{key, agent, task}, ...]); it resolves to an ordered array, not a key map, so use results[0], destructuring, or results.map(...), not results.<key>. Do not read .output from unawaited runs.run launches. Stored runs.run promises are only for advanced rolling fanout, and each must later be observed with direct await, Promise.race, or Promise.all. runs.steer targets a prior stable child key, never a raw run id, and must be awaited or returned. Mission workflows also have async state.get(key) and state.set(key, JSONValue). Compose sequential and parallel phases dynamically. Set worktree:true at workflow or child level for a separate managed worktree; child fields override workflow defaults. gate is one host-run command and cannot be combined with acceptance. runs.run accepts one child only. No filesystem, shell, Pi tools, or host globals." })),
344
+ workflow: Type.Optional(Type.String({ minLength: 1, description: "Extension-owned workflow resource; resolves its script and authority internally." })),
345
+ args: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Bounded plain-JSON args for workflow; resource validation applies." })),
346
+ workflowScript: Type.Optional(Type.String({ minLength: 1, description: "Inline JavaScript statement body with unknown resource provenance. Normally async unless asyncByDefault:false; set async:true for async workflows and async:false only when the parent must block. Use explicit return, top-level await, plain helper functions, or explicit Promise chains. Nested async function, arrow, and method helpers are rejected. Globals: runs, emit, console, and mission state when enabled. No filesystem, shell, Pi tools, or host globals except through runs.host." })),
347
+ workflowScriptPath: Type.Optional(Type.String({ minLength: 1, description: "Path to a JavaScript workflow file with unknown resource provenance. Mutually exclusive with workflowScript and workflow. Relative paths resolve against the request cwd. The host reads the file before the filesystem-free workflow sandbox starts." })),
348
+ globalConcurrencyLimit: Type.Optional(Type.Integer({ minimum: 1 })),
349
+ maxSubagentSpawnsPerRun: Type.Optional(Type.Integer({ minimum: 1 })),
350
+ preflight: Type.Optional(WorkflowPreflightOverride),
316
351
  chatProgress: Type.Optional(Type.String({ enum: ["auto", "off", "live-card"], description: "WorkflowScript chat progress projection. auto shows a live in-chat card only for watched foreground workflows in the same Git repository; it is off otherwise. Explicit live-card requires same-repository async:false; async workflows should omit chatProgress or use auto/off." })),
317
352
  isolation: Type.Optional(Type.String({ enum: ["none", "worktree"], description: "Workflow child isolation. none runs in the shared cwd; worktree requires managed git worktree isolation." })),
318
353
  worktree: Type.Optional(Type.Boolean({ description: "Managed child isolation. true gives each workflow child a separate git worktree; an individual runs.run/runs.all item can override a workflow default with worktree:false." })),
354
+ baseRef: Type.Optional(Type.String()),
355
+ lane: Type.Optional(WorkflowLaneMetadata),
319
356
  context: Type.Optional(Type.String({
320
357
  enum: ["fresh", "fork", "profile"],
321
- description: "'fresh' or 'fork' to branch from parent session, or 'profile' to require the selected agent's declared defaultContext. Explicit fresh/fork overrides every child; profile ignores config defaultSubagentContext and fails when an agent has no defaultContext. If omitted, config defaultSubagentContext wins over each agent defaultContext; implicit fork needs a persisted parent session and leaf, else fresh.",
358
+ description: "'fresh' or 'fork' to branch from parent session, or 'profile' to require the selected agent's declared defaultContext. Explicit fresh/fork overrides every child; profile ignores config defaultSubagentContext and fails when an agent has no defaultContext. If omitted, config defaultSubagentContext wins over each agent defaultContext; implicit fork needs a persisted parent session and leaf, else fresh. Config forkContext may prune resolved forks before spawn without adding another context value.",
322
359
  })),
323
360
  async: Type.Optional(Type.Boolean({ description: "Run in background unless asyncByDefault:false. Set false only when the parent must block until completion." })),
324
361
  timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Timeout. Foreground and single async runs use config timeoutMs, else 30m; async composites have no default parent deadline. Alias maxRuntimeMs." })),
325
362
  maxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: "Alias timeoutMs. Foreground and single async runs use config timeoutMs, else 30m; async composites have no default parent deadline." })),
326
363
  toolTimeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Optional hard per-tool-call timeout in milliseconds; known-fast built-in tools have a five-minute default." })),
327
- turnBudget: Type.Optional(TurnBudgetOverride),
328
364
  toolBudget: Type.Optional(ToolBudgetOverride),
329
365
  usageBudget: Type.Optional(UsageBudgetOverride),
330
366
  agentScope: Type.Optional(Type.String({ description: "Agent discovery scope: 'user', 'project', or 'both' (default: 'both'; project wins on name collisions)" })),
@@ -342,11 +378,11 @@ const SubagentParamProperties = {
342
378
  { type: "string" },
343
379
  { type: "boolean" },
344
380
  ],
345
- description: "Default child output file (string), or false to disable. Relative paths resolve against cwd.",
381
+ description: "Default child output file (string), or false to disable. Relative workflow child paths use managed artifact routing. Task filename prose is not an output declaration; for durable workflow handoff, return the child's outputReference, outputPathMapping, or artifactPaths.",
346
382
  })),
347
383
  outputMode: Type.Optional(OutputModeOverride),
348
384
  skill: Type.Optional(SkillOverride),
349
- model: Type.Optional(Type.String({ description: "Default child model override. Full provider/id values are accepted; bare ids resolve from the active registry." })),
385
+ model: Type.Optional(Type.String({ description: "Default child model override. Full provider/id values are accepted; bare ids resolve from the active registry. Append a thinking suffix (off/minimal/low/medium/high/xhigh/max, e.g. 'provider/id:low') to set the child's thinking level for the run; the suffix wins over the agent's thinking default." })),
350
386
  fast: Type.Optional(Type.Boolean({ description: "Opt into priority service tier for supported native OpenAI-Codex child models. Default false. This can increase quota or cost." })),
351
387
  outputSchema: Type.Optional(JsonSchemaObject),
352
388
  agentContract: Type.Optional(AgentContractOverride),
@@ -364,20 +400,20 @@ export function createSubagentParamsSchema(): typeof SubagentParams {
364
400
 
365
401
  const SubagentWaitParamsSchema = Type.Object({
366
402
  id: Type.Optional(Type.String({
367
- description: "Async run or remembered detached foreground run id/prefix to wait for one specific run. Omit to wait across every active async run started in this session.",
403
+ description: "Async run or remembered detached foreground run id/prefix to wait for one specific run. Ordinary async subagent runs already notify this session natively; use bg_wait for provider, detached, or other background work without native notification, or when same-turn blocking results are truly needed. Omit to wait across every active async run started in this session only when a same-turn wait is truly needed.",
368
404
  })),
369
405
  nonBlocking: Type.Optional(Type.Boolean({
370
- description: "When true, resolve id to one exact run, persist a wake subscription, and return immediately. The originating session is woken on completion, failure, attention, reconciliation failure, or timeout. Requires id and cannot be combined with all.",
406
+ description: "When true, resolve id to one exact run, persist a wake subscription, and return immediately. Use this only for provider, detached, or other background work without a native completion notification; ordinary async subagent runs already notify this session natively and do not need a subscription. The originating session is woken on completion, failure, attention, reconciliation failure, or timeout. Requires id and cannot be combined with all.",
371
407
  })),
372
408
  all: Type.Optional(Type.Boolean({
373
- description: "Wait for ALL active runs to finish. Default false: return as soon as the first run finishes, so a fleet manager can spawn a replacement and wait again. Ignored when id targets a single run.",
409
+ description: "Wait for ALL active runs to finish. Ordinary async subagent runs already notify this session natively; use all only when a same-turn result from tracked background work is truly needed. Default false: return when the first tracked run or provider item finishes or needs attention. Ignored when id targets a single run.",
374
410
  })),
375
411
  timeoutMs: Type.Optional(Type.Integer({
376
412
  minimum: 1,
377
- description: "Give up waiting after this many milliseconds (the runs keep going regardless). Defaults to 1800000 (30 minutes).",
413
+ description: "Give up waiting after this many milliseconds (the runs keep going regardless). Ordinary async subagent runs already notify this session natively; use a wait timeout only when same-turn results are truly needed for provider, detached, or other background work without native notification. Defaults to config waitTool.defaultTimeoutMs, then 1800000 (30 minutes). Window expiry is a non-error active-work result.",
378
414
  })),
379
415
  stopOnAttention: Type.Optional(Type.Boolean({
380
- description: "Blocking waits stop when a run needs attention by default. Set false to keep waiting through idle or long-thinking attention; supervisor/contact requests still stop the wait.",
416
+ description: "For a blocking wait that is truly needed, stop when a run needs attention by default. Set false to keep waiting through idle or long-thinking attention; supervisor/contact requests still stop the wait.",
381
417
  })),
382
418
  });
383
419