@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,18 +1,11 @@
1
- /**
2
- * General utility functions for the subagent extension
3
- */
4
-
5
1
  import * as fs from "node:fs";
6
2
  import * as os from "node:os";
7
3
  import * as path from "node:path";
8
- import type { Message } from "@earendil-works/pi-ai";
4
+ import type { Message, Usage as PiUsage } from "@earendil-works/pi-ai";
9
5
  import { previewDisplayText, sanitizeDisplayText, truncateDisplayText } from "./display-text.ts";
10
6
  import { formatToolCall } from "./formatters.ts";
11
7
  import type { AgentProgress, AsyncStatus, Details, DisplayItem, ErrorInfo, NestedRunSummary, SingleResult, ToolCallSummary, Usage } from "./types.ts";
12
-
13
- // ============================================================================
14
- // File System Utilities
15
- // ============================================================================
8
+ import { validateAsyncStatusLaneMetadata } from "../runs/shared/lane-metadata.ts";
16
9
 
17
10
  const DEFAULT_CONFIG_DIR_NAME = ".pi";
18
11
  const PI_CODING_AGENT_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
@@ -96,9 +89,10 @@ export function getProjectConfigDir(projectRoot: string): string {
96
89
 
97
90
  export function getAgentDir(): string {
98
91
  const configured = process.env.PI_CODING_AGENT_DIR;
99
- if (configured === "~") return os.homedir();
100
- if (configured?.startsWith("~/")) return path.join(os.homedir(), configured.slice(2));
101
- return configured || path.join(os.homedir(), getConfigDirName(), "agent");
92
+ const home = process.env.HOME || process.env.USERPROFILE || os.homedir();
93
+ if (configured === "~") return home;
94
+ if (configured?.startsWith("~/") || configured?.startsWith("~\\")) return path.join(home, configured.slice(2));
95
+ return configured || path.join(home, getConfigDirName(), "agent");
102
96
  }
103
97
 
104
98
  const statusCache = new Map<string, { mtime: number; ctime: number; size: number; ino: number; status: AsyncStatus }>();
@@ -190,6 +184,13 @@ export function readStatus(asyncDir: string): AsyncStatus | null {
190
184
  cause: error instanceof Error ? error : undefined,
191
185
  });
192
186
  }
187
+ try {
188
+ validateAsyncStatusLaneMetadata(status, `Invalid async status '${statusPath}'`);
189
+ } catch (error) {
190
+ throw new Error(`Failed to validate async status file '${statusPath}': ${getErrorMessage(error)}`, {
191
+ cause: error instanceof Error ? error : undefined,
192
+ });
193
+ }
193
194
 
194
195
  statusCache.set(statusPath, {
195
196
  mtime: stat.mtimeMs,
@@ -206,57 +207,7 @@ export function readStatus(asyncDir: string): AsyncStatus | null {
206
207
  return status;
207
208
  }
208
209
 
209
- const outputTailCache = new Map<string, { mtime: number; size: number; lines: string[] }>();
210
-
211
- /**
212
- * Get the last N lines from an output file (with mtime/size-based caching)
213
- */
214
- function getOutputTail(outputFile: string | undefined, maxLines: number = 3): string[] {
215
- if (!outputFile) return [];
216
- let fd: number | null = null;
217
- try {
218
- const stat = fs.statSync(outputFile);
219
- if (stat.size === 0) return [];
220
-
221
- const cached = outputTailCache.get(outputFile);
222
- if (cached && cached.mtime === stat.mtimeMs && cached.size === stat.size) {
223
- return cached.lines;
224
- }
225
-
226
- const tailBytes = 4096;
227
- const start = Math.max(0, stat.size - tailBytes);
228
- fd = fs.openSync(outputFile, "r");
229
- const buffer = Buffer.alloc(Math.min(tailBytes, stat.size));
230
- fs.readSync(fd, buffer, 0, buffer.length, start);
231
- const content = buffer.toString("utf-8");
232
- const allLines = content.split("\n").filter((l) => l.trim());
233
- const lines = allLines.slice(-maxLines).map((l) => l.slice(0, 120) + (l.length > 120 ? "..." : ""));
234
-
235
- outputTailCache.set(outputFile, { mtime: stat.mtimeMs, size: stat.size, lines });
236
- if (outputTailCache.size > 20) {
237
- const firstKey = outputTailCache.keys().next().value;
238
- if (firstKey) outputTailCache.delete(firstKey);
239
- }
240
-
241
- return lines;
242
- } catch {
243
- // Output tails are UI-only hints; unreadable or missing files should render as no tail.
244
- return [];
245
- } finally {
246
- if (fd !== null) {
247
- try {
248
- fs.closeSync(fd);
249
- } catch {
250
- // Closing the best-effort tail file handle should not surface over the main status view.
251
- }
252
- }
253
- }
254
- }
255
-
256
- /**
257
- * Get human-readable last activity time for a file
258
- */
259
- export function getLastActivity(outputFile: string | undefined): string {
210
+ export function getLastActivity(outputFile: string | undefined): string {
260
211
  if (!outputFile) return "";
261
212
  try {
262
213
  const stat = fs.statSync(outputFile);
@@ -265,14 +216,11 @@ function getOutputTail(outputFile: string | undefined, maxLines: number = 3): st
265
216
  if (ago < 60000) return `active ${Math.floor(ago / 1000)}s ago`;
266
217
  return `active ${Math.floor(ago / 60000)}m ago`;
267
218
  } catch {
268
- // Last-activity text is best effort; missing files should simply omit the hint.
219
+ // Last-activity text is best effort; missing files should omit the hint.
269
220
  return "";
270
221
  }
271
222
  }
272
223
 
273
- /**
274
- * Find the latest session file in a directory
275
- */
276
224
  export function findLatestSessionFile(sessionDir: string): string | null {
277
225
  if (!fs.existsSync(sessionDir)) return null;
278
226
  const files = fs.readdirSync(sessionDir)
@@ -289,23 +237,12 @@ export function findLatestSessionFile(sessionDir: string): string | null {
289
237
  return latest ? latest.path : null;
290
238
  }
291
239
 
292
- /**
293
- * Write a prompt to a temporary file
294
- */
295
- function writePrompt(agent: string, prompt: string): { dir: string; path: string } {
296
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
297
- const p = path.join(dir, `${agent.replace(/[^\w.-]/g, "_")}.md`);
298
- fs.writeFileSync(p, prompt, { mode: 0o600 });
299
- return { dir, path: p };
300
- }
240
+ const PI_TURN_TIMING_FOOTER = /(?:\r?\n)*\x1b\[38;2;136;136;136m✻ Turn took [^()\r\n]+ \(Total time [^·\r\n]+ · \d+ turns?\)\x1b\[0m[ \t]*$/u;
301
241
 
302
- // ============================================================================
303
- // Message Parsing Utilities
304
- // ============================================================================
242
+ function stripPiTurnTimingFooter(text: string): string {
243
+ return text.replace(PI_TURN_TIMING_FOOTER, "");
244
+ }
305
245
 
306
- /**
307
- * Get the final text output from a list of messages
308
- */
309
246
  export function getFinalOutput(messages: Message[]): string {
310
247
  const validTextParts: string[] = [];
311
248
  for (let i = messages.length - 1; i >= 0; i--) {
@@ -315,21 +252,26 @@ export function getFinalOutput(messages: Message[]): string {
315
252
  || ("stopReason" in msg && msg.stopReason === "error");
316
253
  if (hasAssistantError) continue;
317
254
  const messageText = msg.content
318
- .filter((part) => part.type === "text" && part.text.trim().length > 0)
319
- .map((part) => part.type === "text" ? part.text : "")
255
+ .flatMap((part) => {
256
+ if (part.type !== "text") return [];
257
+ const text = stripPiTurnTimingFooter(part.text);
258
+ return text.trim().length > 0 ? [text] : [];
259
+ })
320
260
  .join("\n");
321
261
  for (let j = msg.content.length - 1; j >= 0; j--) {
322
262
  const part = msg.content[j];
323
- if (!part || part.type !== "text" || part.text.trim().length === 0) continue;
324
- validTextParts.push(part.text);
325
- if (/```acceptance[-_]report\s*\n[\s\S]*?```/i.test(part.text)) return messageText;
326
- for (const match of part.text.matchAll(/```(?:json|jsonc|json5)\s*\n([\s\S]*?)```/gi)) {
263
+ if (!part || part.type !== "text") continue;
264
+ const text = stripPiTurnTimingFooter(part.text);
265
+ if (text.trim().length === 0) continue;
266
+ validTextParts.push(text);
267
+ if (/```acceptance[-_]report\s*\n[\s\S]*?```/i.test(text)) return messageText;
268
+ for (const match of text.matchAll(/```(?:json|jsonc|json5)\s*\n([\s\S]*?)```/gi)) {
327
269
  const body = match[1] ?? "";
328
270
  if (/"(?:criteriaSatisfied|criteria_satisfied)"/.test(body) && /"(?:changedFiles|changed_files|testsAddedOrUpdated|tests_added_or_updated|commandsRun|commands_run|validationOutput|validation_output|residualRisks|residual_risks|noStagedFiles|no_staged_files|diffSummary|diff_summary|reviewFindings|review_findings|manualNotes|manual_notes)"/.test(body)) {
329
271
  return messageText;
330
272
  }
331
273
  }
332
- if (/ACCEPTANCE_REPORT\s*:/i.test(part.text)) return messageText;
274
+ if (/ACCEPTANCE_REPORT\s*:/i.test(text)) return messageText;
333
275
  }
334
276
  }
335
277
  return validTextParts[0] ?? "";
@@ -361,6 +303,7 @@ function compactCompletedProgress(progress: AgentProgress): AgentProgress {
361
303
  return {
362
304
  index: progress.index,
363
305
  agent: progress.agent,
306
+ ...(progress.sessionName ? { sessionName: progress.sessionName } : {}),
364
307
  status: progress.status,
365
308
  activityState: progress.activityState,
366
309
  task: "[prompt redacted]",
@@ -407,6 +350,17 @@ export function sumResultsUsage(results: SingleResult[]): Usage {
407
350
  return usage;
408
351
  }
409
352
 
353
+ export function toAgentToolUsage(usage: Usage): PiUsage {
354
+ return {
355
+ input: usage.input,
356
+ output: usage.output,
357
+ cacheRead: usage.cacheRead,
358
+ cacheWrite: usage.cacheWrite,
359
+ totalTokens: usage.input + usage.output + usage.cacheRead + usage.cacheWrite,
360
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: usage.cost },
361
+ };
362
+ }
363
+
410
364
  function addNestedCost(total: NonNullable<Details["totalCost"]>, children: NestedRunSummary[] | undefined): void {
411
365
  for (const child of children ?? []) {
412
366
  if (child.totalCost) {
@@ -459,10 +413,9 @@ export function compactForegroundDetails(details: Details): Details {
459
413
  *
460
414
  * The completed-compaction helpers above bail out while a child is still
461
415
  * `running`, so a long or deeply nested fan-out streams full, unbounded progress on
462
- * every tick. Pi serializes each streamed `tool_execution_update` as a single
463
- * child-stdout line, which the parent reads under `MAX_CHILD_PENDING_LINE_BYTES`;
464
- * an unbounded running snapshot can cross that cap and kill the child with
465
- * `protocol_output_limit`.
416
+ * every tick. The parent records every streamed `tool_execution_update` in its
417
+ * transcript and `events.jsonl`, so an unbounded running snapshot grows those
418
+ * artifacts and the live display state without bound.
466
419
  *
467
420
  * These bound the STREAMED snapshot only. The final returned result keeps the full
468
421
  * live progress and message transcript, and every live-display consumer already
@@ -505,6 +458,20 @@ export function hasEmptyTerminalAssistantResponse(messages: Message[]): boolean
505
458
  && lastAssistant.usage.output === 0;
506
459
  }
507
460
 
461
+ export function formatEmptyTerminalAssistantResponseError(messages: Message[]): string {
462
+ const lastAssistant = messages.findLast((message) => message.role === "assistant");
463
+ const errorMessage = lastAssistant && "errorMessage" in lastAssistant && typeof lastAssistant.errorMessage === "string" && lastAssistant.errorMessage.trim()
464
+ ? lastAssistant.errorMessage.trim()
465
+ : undefined;
466
+ if (errorMessage) return errorMessage;
467
+ const stopReason = lastAssistant && "stopReason" in lastAssistant && typeof lastAssistant.stopReason === "string" && lastAssistant.stopReason.trim()
468
+ ? lastAssistant.stopReason.trim()
469
+ : undefined;
470
+ return stopReason && stopReason !== "stop"
471
+ ? `Subagent produced no output after terminal assistant stopReason "${stopReason}".`
472
+ : "Subagent produced no output (possible model cold-start or empty response).";
473
+ }
474
+
508
475
  /**
509
476
  * Detect errors in subagent execution from messages (only errors with no subsequent success)
510
477
  */
@@ -0,0 +1,207 @@
1
+ import { stableJsonDigest } from "./launch-contract.ts";
2
+ import type { WorkflowResourceProvenanceV1 } from "./types.ts";
3
+
4
+ export interface WorkflowChildPermitInput {
5
+ issuerPackage: string;
6
+ workflowRunId: string;
7
+ childKey: string;
8
+ agent: string;
9
+ launchContractDigest: string;
10
+ context: "fresh" | "fork";
11
+ }
12
+
13
+ export interface WorkflowChildPermitLaunch {
14
+ workflowRunId: string;
15
+ childKey: string;
16
+ agent: string;
17
+ launchContractDigest: string;
18
+ context: "fresh" | "fork";
19
+ runner: "pi";
20
+ }
21
+
22
+ export interface WorkflowChildPermitContext {
23
+ permit: WorkflowChildPermit;
24
+ workflowRunId: string;
25
+ childKey: string;
26
+ }
27
+
28
+ export interface WorkflowChildPermit {
29
+ readonly __workflowChildPermit: unique symbol;
30
+ }
31
+
32
+ interface WorkflowChildPermitRecord {
33
+ issuerPackage: string;
34
+ workflowRunId: string;
35
+ childKey: string;
36
+ agent: string;
37
+ expectedProjectionDigest: string;
38
+ state: "available" | "claimed" | "consumed";
39
+ }
40
+
41
+ const records = new WeakMap<object, WorkflowChildPermitRecord>();
42
+
43
+ function projectionDigest(input: Omit<WorkflowChildPermitLaunch, "workflowRunId">): string {
44
+ return stableJsonDigest({
45
+ version: 1,
46
+ childKey: input.childKey,
47
+ agent: input.agent,
48
+ launchContractDigest: input.launchContractDigest,
49
+ context: input.context,
50
+ runner: input.runner,
51
+ });
52
+ }
53
+
54
+ function required(value: string, label: string): string {
55
+ if (!value.trim() || value !== value.trim()) throw new Error(`${label} must be a non-empty trimmed string.`);
56
+ return value;
57
+ }
58
+
59
+ /** Package-internal first-slice permit. It is opaque, in-memory, and not serializable. */
60
+ export function createWorkflowChildPermit(input: WorkflowChildPermitInput): WorkflowChildPermit {
61
+ const permit = Object.freeze(Object.create(null)) as WorkflowChildPermit;
62
+ const record: WorkflowChildPermitRecord = {
63
+ issuerPackage: required(input.issuerPackage, "issuerPackage"),
64
+ workflowRunId: required(input.workflowRunId, "workflowRunId"),
65
+ childKey: required(input.childKey, "childKey"),
66
+ agent: required(input.agent, "agent"),
67
+ expectedProjectionDigest: projectionDigest({
68
+ childKey: input.childKey,
69
+ agent: input.agent,
70
+ launchContractDigest: required(input.launchContractDigest, "launchContractDigest"),
71
+ context: input.context,
72
+ runner: "pi",
73
+ }),
74
+ state: "available",
75
+ };
76
+ records.set(permit as object, record);
77
+ return permit;
78
+ }
79
+
80
+ export function validateWorkflowChildPermitRoot(permit: WorkflowChildPermit, workflowRunId: string): string | undefined {
81
+ const record = records.get(permit as object);
82
+ if (!record) return "Workflow child permit is invalid.";
83
+ if (record.state !== "available") return "Workflow child permit is already consumed.";
84
+ if (record.workflowRunId !== workflowRunId) return "Workflow child permit does not match this workflow root.";
85
+ return undefined;
86
+ }
87
+
88
+ /** Claim the first distinct launch attempt before validating its model-authored shape. */
89
+ export function claimWorkflowChildPermit(permit: WorkflowChildPermit, workflowRunId: string, childKey: string): string | undefined {
90
+ const record = records.get(permit as object);
91
+ if (!record) return "Workflow child permit is invalid.";
92
+ if (record.state !== "available") return "Workflow child permit is already consumed.";
93
+ if (record.workflowRunId !== workflowRunId) return "Workflow child permit does not match this workflow root.";
94
+ record.state = record.childKey === childKey ? "claimed" : "consumed";
95
+ if (record.childKey !== childKey) return "Workflow child permit child key mismatch.";
96
+ return undefined;
97
+ }
98
+
99
+ /** Verify and permanently consume the permit before the one native process spawn. */
100
+ export function consumeWorkflowChildPermit(permit: WorkflowChildPermit, launch: WorkflowChildPermitLaunch): string | undefined {
101
+ const record = records.get(permit as object);
102
+ if (!record) return "Workflow child permit is invalid.";
103
+ if (record.state === "available") return "Workflow child permit launch was not claimed.";
104
+ if (record.state === "consumed") return "Workflow child permit is already consumed.";
105
+ if (record.workflowRunId !== launch.workflowRunId) return "Workflow child permit does not match this workflow root.";
106
+ record.state = "consumed";
107
+ if (record.childKey !== launch.childKey) return "Workflow child permit child key mismatch.";
108
+ if (record.agent !== launch.agent) return "Workflow child permit agent mismatch.";
109
+ if (launch.runner !== "pi") return "Workflow child permit supports native Pi children only.";
110
+ if (record.expectedProjectionDigest !== projectionDigest(launch)) return "Workflow child permit does not match the final launch projection.";
111
+ return undefined;
112
+ }
113
+
114
+ export function workflowChildPermitConsumed(permit: WorkflowChildPermit): boolean {
115
+ const state = records.get(permit as object)?.state;
116
+ return state === "claimed" || state === "consumed";
117
+ }
118
+
119
+ export interface WorkflowResourceHostAuthority {
120
+ keys: readonly string[];
121
+ commands: readonly string[];
122
+ }
123
+
124
+ export interface WorkflowResourceAuthority {
125
+ host?: WorkflowResourceHostAuthority;
126
+ }
127
+
128
+ export interface WorkflowResourcePermitInput {
129
+ resourceName: string;
130
+ resourceVersion: number;
131
+ resourceId: string;
132
+ scriptDigest: string;
133
+ authority: WorkflowResourceAuthority;
134
+ }
135
+
136
+ export interface WorkflowResourcePermit {
137
+ readonly __workflowResourcePermit: unique symbol;
138
+ }
139
+
140
+ interface WorkflowResourcePermitRecord {
141
+ resourceName: string;
142
+ resourceVersion: number;
143
+ resourceId: string;
144
+ scriptDigest: string;
145
+ authority: WorkflowResourceAuthority;
146
+ provenance: WorkflowResourceProvenanceV1;
147
+ state: "available" | "consumed";
148
+ }
149
+
150
+ const resourceRecords = new WeakMap<object, WorkflowResourcePermitRecord>();
151
+
152
+ function cloneWorkflowResourceAuthority(authority: WorkflowResourceAuthority): WorkflowResourceAuthority {
153
+ if (!authority || typeof authority !== "object" || Array.isArray(authority)) throw new Error("Workflow resource authority must be an object.");
154
+ if (authority.host === undefined) return Object.freeze({});
155
+ if (!authority.host || typeof authority.host !== "object" || Array.isArray(authority.host)) throw new Error("Workflow resource host authority must be an object.");
156
+ const { keys, commands } = authority.host;
157
+ if (!Array.isArray(keys) || keys.some((key) => typeof key !== "string" || !key.trim())) throw new Error("Workflow resource host authority keys must be non-empty strings.");
158
+ if (!Array.isArray(commands) || commands.some((command) => typeof command !== "string" || !command.trim())) throw new Error("Workflow resource host authority commands must be non-empty strings.");
159
+ return Object.freeze({ host: Object.freeze({ keys: Object.freeze([...keys]), commands: Object.freeze([...commands]) }) });
160
+ }
161
+
162
+ /** Package-internal permit for a workflow resource resolved by the extension. */
163
+ export function createWorkflowResourcePermit(input: WorkflowResourcePermitInput): WorkflowResourcePermit {
164
+ const resourceName = required(input.resourceName, "resourceName");
165
+ const resourceId = required(input.resourceId, "resourceId");
166
+ const scriptDigest = required(input.scriptDigest, "scriptDigest");
167
+ if (!Number.isInteger(input.resourceVersion) || input.resourceVersion < 1) throw new Error("resourceVersion must be a positive integer.");
168
+ const authority = cloneWorkflowResourceAuthority(input.authority);
169
+ const permit = Object.freeze(Object.create(null)) as WorkflowResourcePermit;
170
+ resourceRecords.set(permit as object, {
171
+ resourceName,
172
+ resourceVersion: input.resourceVersion,
173
+ resourceId,
174
+ scriptDigest,
175
+ authority,
176
+ provenance: Object.freeze({
177
+ kind: "workflow",
178
+ name: resourceName,
179
+ version: input.resourceVersion,
180
+ invocation: "named",
181
+ expansion: "resolved",
182
+ id: resourceId,
183
+ }),
184
+ state: "available",
185
+ });
186
+ return permit;
187
+ }
188
+
189
+ export function consumeWorkflowResourcePermit(permit: WorkflowResourcePermit, script: string): { provenance: WorkflowResourceProvenanceV1; authority: WorkflowResourceAuthority } | string {
190
+ const record = resourceRecords.get(permit as object);
191
+ if (!record) return "Workflow resource permit is invalid.";
192
+ if (record.state !== "available") return "Workflow resource permit is already consumed.";
193
+ if (stableJsonDigest(script) !== record.scriptDigest) return "Workflow resource permit does not match the resolved workflow script.";
194
+ record.state = "consumed";
195
+ return { provenance: record.provenance, authority: record.authority };
196
+ }
197
+
198
+ /** Validate a host call against the authority attached to a consumed resource. */
199
+ export function authorizeWorkflowResourceHost(permit: WorkflowResourcePermit, key: string, command: string): string | undefined {
200
+ const record = resourceRecords.get(permit as object);
201
+ if (!record || record.state !== "consumed") return "Workflow resource authority is unavailable.";
202
+ const host = record.authority.host;
203
+ if (!host) return "runs.host is not allowed for this workflow resource.";
204
+ if (!host.keys.includes(key)) return `runs.host('${key}') is not allowed for workflow resource '${record.resourceName}'.`;
205
+ if (!host.commands.includes(command.trim())) return `The command for runs.host('${key}') is not allowed for workflow resource '${record.resourceName}'.`;
206
+ return undefined;
207
+ }
@@ -6,7 +6,7 @@ import {
6
6
  type SubagentDelegationUpdate,
7
7
  type SubagentDelegationValue,
8
8
  } from "../api/delegation.ts";
9
- import type { AcceptanceInput, AgentContract, EffectsProjection, ExecutionProjection, JsonSchemaObject, ReviewProjection, ToolBudgetConfig, TurnBudgetConfig, Usage } from "../shared/types.ts";
9
+ import type { AcceptanceInput, AgentContract, EffectsProjection, ExecutionProjection, JsonSchemaObject, ReviewProjection, ToolBudgetConfig, Usage } from "../shared/types.ts";
10
10
  import { cloneJsonWithinByteLimit } from "./delegation-json.ts";
11
11
 
12
12
  export interface PromptTemplateDelegationRequest {
@@ -82,7 +82,6 @@ export interface PromptTemplateBridgeResult {
82
82
  interrupted?: boolean;
83
83
  timedOut?: boolean;
84
84
  stopped?: boolean;
85
- turnBudgetExceeded?: boolean;
86
85
  toolBudgetBlocked?: boolean;
87
86
  structuredOutputFailed?: boolean;
88
87
  savedOutputPath?: string;
@@ -120,9 +119,6 @@ export interface DelegatedSubagentExecutionParams {
120
119
  model?: string;
121
120
  cwd: string;
122
121
  timeoutMs?: number;
123
- turnBudget?: TurnBudgetConfig;
124
- /** Internal-only strict turn-boundary enforcement for structured foreground delegation. */
125
- enforceHardTurnLimit?: boolean;
126
122
  toolBudget?: ToolBudgetConfig;
127
123
  skill?: string | string[] | boolean;
128
124
  output?: string | boolean;
@@ -294,11 +290,8 @@ export function toSubagentDelegationExecutionParams(request: SubagentDelegationR
294
290
  cwd: request.cwd,
295
291
  model: request.model,
296
292
  timeoutMs: request.timeoutMs,
297
- turnBudget: request.turnBudget,
298
- enforceHardTurnLimit: true,
299
293
  toolBudget: request.toolBudget,
300
294
  skill: request.skill,
301
- output: false,
302
295
  ...(request.result.kind === "structured" ? { outputSchema: request.result.schema } : {}),
303
296
  acceptance: false,
304
297
  artifacts: request.artifacts,
@@ -342,7 +335,6 @@ function resolveSubagentDelegationStatus(
342
335
  if (!child) return "failed";
343
336
  if (result.details?.timedOut || child.timedOut) return "timed_out";
344
337
  if (child?.structuredOutputFailed) return "structured_output_failed";
345
- if (child?.turnBudgetExceeded) return "turn_budget_exhausted";
346
338
  if (child?.toolBudgetBlocked) return "tool_budget_exhausted";
347
339
  if (child?.acceptance?.status === "rejected" && child.acceptance.explicit) return "acceptance_failed";
348
340
  if (result.details?.stopped || child?.stopped || child?.interrupted) return "interrupted";
@@ -2,7 +2,6 @@ import {
2
2
  type SubagentDelegationRequest,
3
3
  } from "../api/delegation.ts";
4
4
  import { validateToolBudgetConfig } from "../runs/shared/tool-budget.ts";
5
- import { resolveTurnBudgetConfig } from "../runs/shared/turn-budget.ts";
6
5
  import { cloneJsonWithinByteLimit } from "./delegation-json.ts";
7
6
 
8
7
  export type SubagentDelegationParseResult =
@@ -20,7 +19,6 @@ const supportedFields = new Set([
20
19
  "model",
21
20
  "thinking",
22
21
  "timeoutMs",
23
- "turnBudget",
24
22
  "toolBudget",
25
23
  "skill",
26
24
  "artifacts",
@@ -80,8 +78,6 @@ export function parseSubagentDelegationRequest(data: unknown): SubagentDelegatio
80
78
  if (timeoutMs !== undefined && timeoutMs > 2_147_483_647) {
81
79
  return { ok: false, ...identity, error: "timeoutMs must be <= 2147483647." };
82
80
  }
83
- const turnBudget = resolveTurnBudgetConfig(value.turnBudget);
84
- if (turnBudget.error) return { ok: false, ...identity, error: turnBudget.error };
85
81
  if (value.toolBudget && typeof value.toolBudget === "object" && !Array.isArray(value.toolBudget)) {
86
82
  const unsupportedToolBudgetField = Object.keys(value.toolBudget).find((key) => key !== "soft" && key !== "hard" && key !== "block");
87
83
  if (unsupportedToolBudgetField) {
@@ -7,6 +7,7 @@ import {
7
7
  type SubagentDelegationInvalidResponse,
8
8
  type SubagentDelegationRequest,
9
9
  type SubagentDelegationResponse,
10
+ type SubagentDelegationUpdate,
10
11
  } from "../api/delegation.ts";
11
12
  import { parseSubagentDelegationRequest } from "./delegation-request.ts";
12
13
  import {
@@ -66,6 +67,37 @@ function validId(value: unknown): value is string {
66
67
  return typeof value === "string" && value.trim().length > 0 && value.length <= 256 && !/[\r\n]/.test(value);
67
68
  }
68
69
 
70
+ function sameStringArray(left: string[] | undefined, right: string[] | undefined): boolean {
71
+ if (left === right) return true;
72
+ if (!left || !right || left.length !== right.length) return false;
73
+ return left.every((value, index) => value === right[index]);
74
+ }
75
+
76
+ function sameRecentTools(
77
+ left: Array<{ tool: string; args: string }> | undefined,
78
+ right: Array<{ tool: string; args: string }> | undefined,
79
+ ): boolean {
80
+ if (left === right) return true;
81
+ if (!left || !right || left.length !== right.length) return false;
82
+ return left.every((tool, index) => tool.tool === right[index]?.tool && tool.args === right[index]?.args);
83
+ }
84
+
85
+ /** Duration is a heartbeat clock, not delegation-visible progress; terminal usage remains authoritative. */
86
+ function sameStructuredDelegationUpdateProgress(left: SubagentDelegationUpdate, right: SubagentDelegationUpdate): boolean {
87
+ return left.requestId === right.requestId
88
+ && left.ownerRunId === right.ownerRunId
89
+ && left.nodeId === right.nodeId
90
+ && left.runId === right.runId
91
+ && left.currentTool === right.currentTool
92
+ && left.currentToolArgs === right.currentToolArgs
93
+ && left.recentOutput === right.recentOutput
94
+ && sameStringArray(left.recentOutputLines, right.recentOutputLines)
95
+ && sameRecentTools(left.recentTools, right.recentTools)
96
+ && left.model === right.model
97
+ && left.toolCount === right.toolCount
98
+ && left.tokens === right.tokens;
99
+ }
100
+
69
101
  export function registerPromptTemplateDelegationBridge<Ctx extends { cwd?: string }>(
70
102
  options: PromptTemplateBridgeOptions<Ctx>,
71
103
  ): {
@@ -298,6 +330,7 @@ export function registerPromptTemplateDelegationBridge<Ctx extends { cwd?: strin
298
330
  const executeRequest = structuredRequest && options.executeStructured
299
331
  ? options.executeStructured
300
332
  : options.execute;
333
+ let lastStructuredUpdate: SubagentDelegationUpdate | undefined;
301
334
  const result = await executeRequest(
302
335
  requestId,
303
336
  params,
@@ -307,7 +340,10 @@ export function registerPromptTemplateDelegationBridge<Ctx extends { cwd?: strin
307
340
  if (key ? !ownsAttempt(key, controller) : !ownsLegacyRequest(requestId, controller)) return;
308
341
  if (structuredRequest) {
309
342
  const payload = toSubagentDelegationUpdate(structuredRequest, update);
310
- if (payload) options.events.emit(SUBAGENT_DELEGATION_UPDATE_EVENT, payload);
343
+ if (payload && (!lastStructuredUpdate || !sameStructuredDelegationUpdateProgress(lastStructuredUpdate, payload))) {
344
+ lastStructuredUpdate = payload;
345
+ options.events.emit(SUBAGENT_DELEGATION_UPDATE_EVENT, payload);
346
+ }
311
347
  return;
312
348
  }
313
349
  const payload = toDelegationUpdate(requestId, update);
@@ -39,7 +39,6 @@ interface EventBus {
39
39
 
40
40
  interface SlashBridgeOptions {
41
41
  events: EventBus;
42
- asyncByDefault: boolean;
43
42
  getContext: () => ExtensionContext | null;
44
43
  execute: (
45
44
  id: string,
@@ -80,7 +79,7 @@ export function registerSlashSubagentBridge(options: SlashBridgeOptions): {
80
79
  const request = data as Partial<SlashSubagentRequest>;
81
80
  if (typeof request.requestId !== "string" || !request.params) return;
82
81
  const { requestId } = request as SlashSubagentRequest;
83
- const normalized = normalizePublicSubagentExecution((request as SlashSubagentRequest).params, { asyncByDefault: options.asyncByDefault });
82
+ const normalized = normalizePublicSubagentExecution((request as SlashSubagentRequest).params);
84
83
  if (!normalized.ok) {
85
84
  options.events.emit(SLASH_SUBAGENT_RESPONSE_EVENT, {
86
85
  requestId,