@ashx-j/lunr 0.2.13 → 0.2.15

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 (335) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/README.md +10 -7
  3. package/dist/builtin-extensions/ashxj-tui.d.ts +16 -1
  4. package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
  5. package/dist/builtin-extensions/ashxj-tui.js +48 -24
  6. package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
  7. package/dist/builtin-extensions/index.d.ts.map +1 -1
  8. package/dist/builtin-extensions/index.js +2 -0
  9. package/dist/builtin-extensions/index.js.map +1 -1
  10. package/dist/builtin-extensions/lunr-settings-tools.d.ts +4 -0
  11. package/dist/builtin-extensions/lunr-settings-tools.d.ts.map +1 -0
  12. package/dist/builtin-extensions/lunr-settings-tools.js +120 -0
  13. package/dist/builtin-extensions/lunr-settings-tools.js.map +1 -0
  14. package/dist/builtin-extensions/pi-prompt-template-model/subagent-runtime.d.ts +2 -2
  15. package/dist/builtin-extensions/pi-prompt-template-model/subagent-runtime.d.ts.map +1 -1
  16. package/dist/builtin-extensions/pi-prompt-template-model/subagent-runtime.js.map +1 -1
  17. package/dist/builtin-extensions/pi-prompt-template-model/subagent-step.d.ts.map +1 -1
  18. package/dist/builtin-extensions/pi-prompt-template-model/subagent-step.js +3 -3
  19. package/dist/builtin-extensions/pi-prompt-template-model/subagent-step.js.map +1 -1
  20. package/dist/builtin-extensions/pi-subagents/src/api/delegation.d.ts +2 -2
  21. package/dist/builtin-extensions/pi-subagents/src/api/delegation.d.ts.map +1 -1
  22. package/dist/builtin-extensions/pi-subagents/src/api/delegation.js +1 -1
  23. package/dist/builtin-extensions/pi-subagents/src/api/delegation.js.map +1 -1
  24. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts +2 -0
  25. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
  26. package/dist/builtin-extensions/pi-subagents/src/extension/index.js +29 -23
  27. package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
  28. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts +5 -11
  29. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
  30. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +12 -15
  31. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
  32. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts +3 -3
  33. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts.map +1 -1
  34. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js +14 -27
  35. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
  36. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts.map +1 -1
  37. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js +9 -4
  38. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js.map +1 -1
  39. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.d.ts.map +1 -1
  40. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.js +2 -1
  41. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.js.map +1 -1
  42. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.d.ts.map +1 -1
  43. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js +16 -3
  44. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js.map +1 -1
  45. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-status.d.ts +1 -0
  46. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-status.d.ts.map +1 -1
  47. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-status.js +7 -4
  48. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-status.js.map +1 -1
  49. package/dist/builtin-extensions/pi-subagents/src/runs/background/chain-append.d.ts.map +1 -1
  50. package/dist/builtin-extensions/pi-subagents/src/runs/background/chain-append.js +1 -0
  51. package/dist/builtin-extensions/pi-subagents/src/runs/background/chain-append.js.map +1 -1
  52. package/dist/builtin-extensions/pi-subagents/src/runs/background/chain-root-attachment.d.ts.map +1 -1
  53. package/dist/builtin-extensions/pi-subagents/src/runs/background/chain-root-attachment.js +3 -0
  54. package/dist/builtin-extensions/pi-subagents/src/runs/background/chain-root-attachment.js.map +1 -1
  55. package/dist/builtin-extensions/pi-subagents/src/runs/background/fleet-view.d.ts.map +1 -1
  56. package/dist/builtin-extensions/pi-subagents/src/runs/background/fleet-view.js +3 -3
  57. package/dist/builtin-extensions/pi-subagents/src/runs/background/fleet-view.js.map +1 -1
  58. package/dist/builtin-extensions/pi-subagents/src/runs/background/run-status.d.ts.map +1 -1
  59. package/dist/builtin-extensions/pi-subagents/src/runs/background/run-status.js +2 -2
  60. package/dist/builtin-extensions/pi-subagents/src/runs/background/run-status.js.map +1 -1
  61. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts.map +1 -1
  62. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js +3 -0
  63. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js.map +1 -1
  64. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-clarify.d.ts.map +1 -1
  65. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-clarify.js +3 -35
  66. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-clarify.js.map +1 -1
  67. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.d.ts.map +1 -1
  68. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js +7 -8
  69. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js.map +1 -1
  70. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts.map +1 -1
  71. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js +2 -0
  72. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js.map +1 -1
  73. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts +1 -0
  74. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
  75. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +20 -21
  76. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
  77. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts +12 -1
  78. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts.map +1 -1
  79. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js +42 -17
  80. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js.map +1 -1
  81. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts +2 -0
  82. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts.map +1 -1
  83. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.js.map +1 -1
  84. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.d.ts +2 -1
  85. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.d.ts.map +1 -1
  86. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js +23 -1
  87. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js.map +1 -1
  88. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.d.ts +3 -1
  89. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.d.ts.map +1 -1
  90. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.js +15 -4
  91. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.js.map +1 -1
  92. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +14 -3
  93. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
  94. package/dist/builtin-extensions/pi-subagents/src/shared/types.js +1 -1
  95. package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
  96. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.d.ts +3 -3
  97. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.d.ts.map +1 -1
  98. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.js +7 -6
  99. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.js.map +1 -1
  100. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-request.d.ts.map +1 -1
  101. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-request.js +3 -3
  102. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-request.js.map +1 -1
  103. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.d.ts +1 -1
  104. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.d.ts.map +1 -1
  105. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js +6 -4
  106. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js.map +1 -1
  107. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts +1 -1
  108. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts.map +1 -1
  109. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js +15 -10
  110. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js.map +1 -1
  111. package/dist/builtin-extensions/pi-subagents/src/tui/fleet.d.ts.map +1 -1
  112. package/dist/builtin-extensions/pi-subagents/src/tui/fleet.js +5 -4
  113. package/dist/builtin-extensions/pi-subagents/src/tui/fleet.js.map +1 -1
  114. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +2 -2
  115. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
  116. package/dist/builtin-extensions/pi-subagents/src/tui/render.js +86 -52
  117. package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
  118. package/dist/catalog/models.json +1 -1
  119. package/dist/catalog/providers/amazon-bedrock.json +1 -1
  120. package/dist/catalog/providers/anthropic.json +1 -1
  121. package/dist/catalog/providers/azure-openai-responses.json +1 -1
  122. package/dist/catalog/providers/cloudflare-ai-gateway.json +1 -1
  123. package/dist/catalog/providers/fireworks.json +1 -1
  124. package/dist/catalog/providers/github-copilot.json +1 -1
  125. package/dist/catalog/providers/google-vertex.json +1 -1
  126. package/dist/catalog/providers/google.json +1 -1
  127. package/dist/catalog/providers/groq.json +1 -1
  128. package/dist/catalog/providers/huggingface.json +1 -1
  129. package/dist/catalog/providers/nvidia.json +1 -1
  130. package/dist/catalog/providers/openai-codex.json +1 -1
  131. package/dist/catalog/providers/openai.json +1 -1
  132. package/dist/catalog/providers/opencode-go.json +1 -1
  133. package/dist/catalog/providers/opencode.json +1 -1
  134. package/dist/catalog/providers/openrouter.json +1 -1
  135. package/dist/catalog/providers/vercel-ai-gateway.json +1 -1
  136. package/dist/catalog/publication.json +131 -3
  137. package/dist/cli/list-models.d.ts.map +1 -1
  138. package/dist/cli/list-models.js +1 -0
  139. package/dist/cli/list-models.js.map +1 -1
  140. package/dist/cli.d.ts.map +1 -1
  141. package/dist/cli.js +52 -27
  142. package/dist/cli.js.map +1 -1
  143. package/dist/core/agent-session-runtime.d.ts +5 -1
  144. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  145. package/dist/core/agent-session-runtime.js +7 -2
  146. package/dist/core/agent-session-runtime.js.map +1 -1
  147. package/dist/core/agent-session.d.ts +2 -0
  148. package/dist/core/agent-session.d.ts.map +1 -1
  149. package/dist/core/agent-session.js +18 -6
  150. package/dist/core/agent-session.js.map +1 -1
  151. package/dist/core/catalog-cache-scope.d.ts +3 -0
  152. package/dist/core/catalog-cache-scope.d.ts.map +1 -0
  153. package/dist/core/catalog-cache-scope.js +12 -0
  154. package/dist/core/catalog-cache-scope.js.map +1 -0
  155. package/dist/core/catalog-merge.d.ts +2 -0
  156. package/dist/core/catalog-merge.d.ts.map +1 -1
  157. package/dist/core/catalog-merge.js +29 -2
  158. package/dist/core/catalog-merge.js.map +1 -1
  159. package/dist/core/catalog-refresh-polling.d.ts +8 -0
  160. package/dist/core/catalog-refresh-polling.d.ts.map +1 -0
  161. package/dist/core/catalog-refresh-polling.js +30 -0
  162. package/dist/core/catalog-refresh-polling.js.map +1 -0
  163. package/dist/core/codex-catalog.d.ts +3 -0
  164. package/dist/core/codex-catalog.d.ts.map +1 -0
  165. package/dist/core/codex-catalog.js +15 -0
  166. package/dist/core/codex-catalog.js.map +1 -0
  167. package/dist/core/context-breakdown.d.ts +2 -0
  168. package/dist/core/context-breakdown.d.ts.map +1 -1
  169. package/dist/core/context-breakdown.js +6 -2
  170. package/dist/core/context-breakdown.js.map +1 -1
  171. package/dist/core/customize.d.ts +2 -4
  172. package/dist/core/customize.d.ts.map +1 -1
  173. package/dist/core/customize.js +2 -8
  174. package/dist/core/customize.js.map +1 -1
  175. package/dist/core/footer-data-provider.d.ts +3 -4
  176. package/dist/core/footer-data-provider.d.ts.map +1 -1
  177. package/dist/core/footer-data-provider.js +54 -82
  178. package/dist/core/footer-data-provider.js.map +1 -1
  179. package/dist/core/injected-prompt.d.ts +3 -3
  180. package/dist/core/injected-prompt.d.ts.map +1 -1
  181. package/dist/core/injected-prompt.js +2 -7
  182. package/dist/core/injected-prompt.js.map +1 -1
  183. package/dist/core/large-subagent-launch.d.ts +13 -0
  184. package/dist/core/large-subagent-launch.d.ts.map +1 -0
  185. package/dist/core/large-subagent-launch.js +54 -0
  186. package/dist/core/large-subagent-launch.js.map +1 -0
  187. package/dist/core/live-catalog.d.ts +5 -2
  188. package/dist/core/live-catalog.d.ts.map +1 -1
  189. package/dist/core/live-catalog.js +108 -27
  190. package/dist/core/live-catalog.js.map +1 -1
  191. package/dist/core/model-instructions.d.ts +24 -0
  192. package/dist/core/model-instructions.d.ts.map +1 -0
  193. package/dist/core/model-instructions.js +123 -0
  194. package/dist/core/model-instructions.js.map +1 -0
  195. package/dist/core/model-runtime.d.ts +8 -0
  196. package/dist/core/model-runtime.d.ts.map +1 -1
  197. package/dist/core/model-runtime.js +64 -12
  198. package/dist/core/model-runtime.js.map +1 -1
  199. package/dist/core/official-catalog.d.ts +4 -0
  200. package/dist/core/official-catalog.d.ts.map +1 -1
  201. package/dist/core/official-catalog.js +86 -21
  202. package/dist/core/official-catalog.js.map +1 -1
  203. package/dist/core/permissions.d.ts +10 -11
  204. package/dist/core/permissions.d.ts.map +1 -1
  205. package/dist/core/permissions.js +107 -40
  206. package/dist/core/permissions.js.map +1 -1
  207. package/dist/core/plan-mode.d.ts.map +1 -1
  208. package/dist/core/plan-mode.js +10 -1
  209. package/dist/core/plan-mode.js.map +1 -1
  210. package/dist/core/resource-loader.d.ts +3 -0
  211. package/dist/core/resource-loader.d.ts.map +1 -1
  212. package/dist/core/resource-loader.js +13 -4
  213. package/dist/core/resource-loader.js.map +1 -1
  214. package/dist/core/runtime-bridges.d.ts +4 -0
  215. package/dist/core/runtime-bridges.d.ts.map +1 -0
  216. package/dist/core/runtime-bridges.js +16 -0
  217. package/dist/core/runtime-bridges.js.map +1 -0
  218. package/dist/core/sdk.d.ts.map +1 -1
  219. package/dist/core/sdk.js +1 -0
  220. package/dist/core/sdk.js.map +1 -1
  221. package/dist/core/settings-manager.d.ts +13 -6
  222. package/dist/core/settings-manager.d.ts.map +1 -1
  223. package/dist/core/settings-manager.js +32 -17
  224. package/dist/core/settings-manager.js.map +1 -1
  225. package/dist/core/settings-tools-bridge.d.ts +35 -0
  226. package/dist/core/settings-tools-bridge.d.ts.map +1 -0
  227. package/dist/core/settings-tools-bridge.js +56 -0
  228. package/dist/core/settings-tools-bridge.js.map +1 -0
  229. package/dist/core/slash-commands.d.ts.map +1 -1
  230. package/dist/core/slash-commands.js +1 -1
  231. package/dist/core/slash-commands.js.map +1 -1
  232. package/dist/core/system-prompt.d.ts.map +1 -1
  233. package/dist/core/system-prompt.js +1 -1
  234. package/dist/core/system-prompt.js.map +1 -1
  235. package/dist/gateway/agent-bridge.d.ts.map +1 -1
  236. package/dist/gateway/agent-bridge.js +3 -2
  237. package/dist/gateway/agent-bridge.js.map +1 -1
  238. package/dist/gateway/approval.d.ts.map +1 -1
  239. package/dist/gateway/approval.js +4 -3
  240. package/dist/gateway/approval.js.map +1 -1
  241. package/dist/gateway/commands.d.ts +1 -1
  242. package/dist/gateway/commands.d.ts.map +1 -1
  243. package/dist/gateway/commands.js +1 -18
  244. package/dist/gateway/commands.js.map +1 -1
  245. package/dist/gateway/cron.d.ts.map +1 -1
  246. package/dist/gateway/cron.js +3 -2
  247. package/dist/gateway/cron.js.map +1 -1
  248. package/dist/gateway/router.d.ts +1 -1
  249. package/dist/gateway/router.d.ts.map +1 -1
  250. package/dist/gateway/router.js +1 -1
  251. package/dist/gateway/router.js.map +1 -1
  252. package/dist/main.d.ts +2 -0
  253. package/dist/main.d.ts.map +1 -1
  254. package/dist/main.js +108 -58
  255. package/dist/main.js.map +1 -1
  256. package/dist/migrations.d.ts +2 -0
  257. package/dist/migrations.d.ts.map +1 -1
  258. package/dist/migrations.js +18 -4
  259. package/dist/migrations.js.map +1 -1
  260. package/dist/modes/interactive/components/assistant-message.d.ts +1 -3
  261. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  262. package/dist/modes/interactive/components/assistant-message.js +4 -32
  263. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  264. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  265. package/dist/modes/interactive/components/custom-editor.js +2 -1
  266. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  267. package/dist/modes/interactive/components/injected-prompt-message.d.ts +1 -1
  268. package/dist/modes/interactive/components/injected-prompt-message.d.ts.map +1 -1
  269. package/dist/modes/interactive/components/injected-prompt-message.js +1 -1
  270. package/dist/modes/interactive/components/injected-prompt-message.js.map +1 -1
  271. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  272. package/dist/modes/interactive/components/model-selector.js +4 -1
  273. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  274. package/dist/modes/interactive/components/plan-message.d.ts +1 -3
  275. package/dist/modes/interactive/components/plan-message.d.ts.map +1 -1
  276. package/dist/modes/interactive/components/plan-message.js +1 -16
  277. package/dist/modes/interactive/components/plan-message.js.map +1 -1
  278. package/dist/modes/interactive/components/settings-selector.d.ts +8 -5
  279. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  280. package/dist/modes/interactive/components/settings-selector.js +71 -31
  281. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  282. package/dist/modes/interactive/components/user-message.d.ts +1 -3
  283. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  284. package/dist/modes/interactive/components/user-message.js +2 -19
  285. package/dist/modes/interactive/components/user-message.js.map +1 -1
  286. package/dist/modes/interactive/interactive-mode.d.ts +13 -4
  287. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  288. package/dist/modes/interactive/interactive-mode.js +163 -177
  289. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  290. package/dist/modes/interactive/theme/moon.json +0 -1
  291. package/dist/modes/interactive/theme/theme-schema.json +3 -3
  292. package/dist/modes/interactive/theme/theme.d.ts +1 -1
  293. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  294. package/dist/modes/interactive/theme/theme.js +95 -90
  295. package/dist/modes/interactive/theme/theme.js.map +1 -1
  296. package/dist/startup/interactive-view.d.ts +55 -0
  297. package/dist/startup/interactive-view.d.ts.map +1 -0
  298. package/dist/startup/interactive-view.js +332 -0
  299. package/dist/startup/interactive-view.js.map +1 -0
  300. package/dist/startup/launch-routing.d.ts +8 -0
  301. package/dist/startup/launch-routing.d.ts.map +1 -0
  302. package/dist/startup/launch-routing.js +29 -0
  303. package/dist/startup/launch-routing.js.map +1 -0
  304. package/dist/startup/startup-milestones.d.ts +4 -0
  305. package/dist/startup/startup-milestones.d.ts.map +1 -0
  306. package/dist/startup/startup-milestones.js +14 -0
  307. package/dist/startup/startup-milestones.js.map +1 -0
  308. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  309. package/dist/utils/syntax-highlight.js +10 -4
  310. package/dist/utils/syntax-highlight.js.map +1 -1
  311. package/docs/features.md +9 -9
  312. package/docs/interactive-startup.md +58 -0
  313. package/docs/keybindings.md +1 -1
  314. package/docs/model-catalog.md +29 -0
  315. package/docs/quickstart.md +3 -2
  316. package/docs/settings.md +4 -4
  317. package/docs/terminal-setup.md +2 -2
  318. package/docs/termux.md +1 -1
  319. package/docs/usage.md +4 -3
  320. package/docs/windows.md +1 -1
  321. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  322. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  323. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  324. package/examples/extensions/gondolin/package-lock.json +2 -2
  325. package/examples/extensions/gondolin/package.json +1 -1
  326. package/examples/extensions/sandbox/package-lock.json +2 -2
  327. package/examples/extensions/sandbox/package.json +1 -1
  328. package/examples/extensions/subagent/README.md +1 -1
  329. package/examples/extensions/with-deps/package-lock.json +2 -2
  330. package/examples/extensions/with-deps/package.json +1 -1
  331. package/package.json +16 -16
  332. package/dist/core/swarm.d.ts +0 -54
  333. package/dist/core/swarm.d.ts.map +0 -1
  334. package/dist/core/swarm.js +0 -119
  335. package/dist/core/swarm.js.map +0 -1
@@ -6,6 +6,7 @@ const CUSTOM_TOOL_DESCRIPTION_FILE = "subagent-tool-description.md";
6
6
  const CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;
7
7
  export const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
8
8
  • Prompt children directly. There is no agent roster. Every execution task needs task (the full child prompt) and description (a concise UI label).
9
+ • Every executable child also needs tier: "light", "standard", or "heavy". Direct model overrides and parent-model inheritance are not available. A missing, disabled, unconfigured, unavailable, or unauthenticated tier fails before launch.
9
10
  • permissions is "full" or "read-only". Omitted permissions means full. Plan-mode parents must pass permissions: "read-only"; full or omitted launches are rejected.
10
11
  • Keep execution and control separate: omit action for SINGLE/PARALLEL/CHAIN execution; use action only for status/interrupt/stop/resume/steer/append-step/doctor/watchdog.*/schedule*.
11
12
  • Async/background runs: launch with async:true only when work can proceed independently. Do not sleep or poll status just to wait. In an interactive session, normally return control and let lunR wake you; use subagent_wait when this request must run to completion in the current turn or skill. Headless sessions auto-drain current-session work.
@@ -15,12 +16,13 @@ export const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
15
16
  export const FULL_SUBAGENT_TOOL_DESCRIPTION = `Delegate work to generic children by prompting them directly. There are no named agent types.
16
17
 
17
18
  EXECUTION (use exactly ONE mode):
18
- • SINGLE: { task, description, permissions? } — one child. Multiple SINGLE calls in the same turn run concurrently; explicit concurrency/run limits still apply.
19
- • PARALLEL: { tasks: [{task, description, permissions?, count?, output?, reads?, progress?}, ...], concurrency?: number, worktree?: true } — one-call concurrent execution (default: all tasks at once; worktree: isolate each task in a git worktree)
20
- • CHAIN: { chain: [{task, description, permissions?}, {parallel:[{task, description, permissions?, count:3}]}] } — sequential pipeline with optional parallel fan-out. Use chain when a later child needs an earlier result.
19
+ • SINGLE: { task, description, tier, permissions? } — one child. Multiple SINGLE calls in the same turn run concurrently; explicit concurrency/run limits still apply.
20
+ • PARALLEL: { tasks: [{task, description, tier, permissions?, count?, output?, reads?, progress?}, ...], concurrency?: number, worktree?: true } — one-call concurrent execution (default: all tasks at once; worktree: isolate each task in a git worktree)
21
+ • CHAIN: { chain: [{task, description, tier, permissions?}, {parallel:[{task, description, tier, permissions?, count:3}]}] } — sequential pipeline with optional parallel fan-out. Use chain when a later child needs an earlier result.
21
22
  • description is required, single-line, max 80 characters. It is UI metadata only. task is the complete child prompt.
22
23
  • permissions: "full" (default) or "read-only". Full includes coding tools (read, search, shell, edit, write, web, LSP, MCP) and excludes parent-owned tools (cron, memory, behavior, goals, nested subagents). Plan-mode parents may launch only permissions: "read-only".
23
- Children always start with a fresh session (no inherited parent transcript). Model strings accept a thinking suffix (provider/model:off|minimal|low|medium|high|xhigh|max).
24
+ Every executable child requires tier: "light", "standard", or "heavy". Direct model overrides and parent-model inheritance are rejected. The configured tier model and credentials must be available.
25
+ • Children always start with a fresh session (no inherited parent transcript).
24
26
  • Optional timeout: { timeoutMs } or { maxRuntimeMs } sets a run-level max runtime for foreground and async/background runs
25
27
 
26
28
  CHAIN TEMPLATE VARIABLES (use in task and description strings):
@@ -29,9 +31,9 @@ CHAIN TEMPLATE VARIABLES (use in task and description strings):
29
31
  • {chain_dir} - Shared directory for chain files (e.g., <tmpdir>/pi-subagents-<scope>/chain-runs/abc123/)
30
32
 
31
33
  CHAIN EXAMPLES:
32
- • Sequential: { chain: [{task:"Analyze {task}", description:"Analyze request"}, {task:"Plan based on {previous}", description:"Draft plan"}] }
33
- • Parallel fan-out: { chain: [{parallel: [{task:"Check part of {task}", description:"Check one part", permissions:"read-only", count: 3}]}] }
34
- • Mixed: { chain: [{task:"Research {task}", description:"Research request", permissions:"read-only"}, {parallel: [{task:"Review {previous}", description:"Review findings", permissions:"read-only", count: 2}]}, {task:"Summarize {previous}", description:"Summarize reviews"}] }
34
+ • Sequential: { chain: [{task:"Analyze {task}", description:"Analyze request", tier:"standard"}, {task:"Plan based on {previous}", description:"Draft plan", tier:"heavy"}] }
35
+ • Parallel fan-out: { chain: [{parallel: [{task:"Check part of {task}", description:"Check one part", tier:"light", permissions:"read-only", count: 3}]}] }
36
+ • Mixed: { chain: [{task:"Research {task}", description:"Research request", tier:"standard", permissions:"read-only"}, {parallel: [{task:"Review {previous}", description:"Review findings", tier:"light", permissions:"read-only", count: 2}]}, {task:"Summarize {previous}", description:"Summarize reviews", tier:"standard"}] }
35
37
 
36
38
  CONTROL (use action field, omit task/chain/tasks):
37
39
  • { action: "watchdog.status" | "watchdog.check" | "watchdog.recommend-model" } - inspect the opt-in subagent watchdog and its strong complementary model recommendation
@@ -43,10 +45,10 @@ CONTROL (use action field, omit task/chain/tasks):
43
45
  • { action: "stop", id: "..." } - stop a current-session top-level async run; stopped runs finish with state "stopped"
44
46
  • { action: "resume", id: "...", message: "...", index?: 0 } - interrupt then follow up with a live async child, or revive a completed async/foreground child from its session
45
47
  • { action: "steer", id: "...", message: "...", index?: 0 } - await correlated child input acceptance for up to 3 seconds; returns delivered, scheduled, pending, partial, recovered, or failed with a request id. Only top-level single runs may recover after a further 15-second pause/revival bound; chain, parallel, and nested runs never auto-interrupt.
46
- • { action: "append-step", id: "...", chain: [{task:"Use {previous}", description:"Follow-up step"}] } - append one step to the tail of a running async chain
48
+ • { action: "append-step", id: "...", chain: [{task:"Use {previous}", description:"Follow-up step", tier:"standard"}] } - append one step to the tail of a running async chain
47
49
 
48
50
  SCHEDULE (opt-in; requires { "scheduledRuns": { "enabled": true } } in config.json):
49
- • { action: "schedule", task, description, permissions?, schedule: "+10m" | "2030-01-01T09:00:00Z", scheduleName? } - defer a child launch until a future time. Also accepts tasks[] or chain[]. Scheduled runs always launch async with fresh context; they become normal tracked async runs once they fire. Only schedule explicit delayed runs the user asked for.
51
+ • { action: "schedule", task, description, tier, permissions?, schedule: "+10m" | "2030-01-01T09:00:00Z", scheduleName? } - defer a child launch until a future time. Also accepts tasks[] or chain[]. Scheduled runs always launch async with fresh context; they become normal tracked async runs once they fire. Only schedule explicit delayed runs the user asked for.
50
52
  • { action: "schedule-list" } - list scheduled runs for this session
51
53
  • { action: "schedule-status", id: "..." } - inspect one scheduled run
52
54
  • { action: "schedule-cancel", id: "..." } - cancel a scheduled run before it fires
@@ -58,11 +60,11 @@ ${SUBAGENT_SAFETY_GUIDANCE}`;
58
60
  export const COMPACT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to generic children by prompting them. Use exactly one mode per call.
59
61
 
60
62
  EXECUTE:
61
- • SINGLE {task, description, permissions?} (same-turn singles overlap); PARALLEL {tasks:[{task,description,permissions?,count?,output?,reads?,progress?}], concurrency?, worktree?}; CHAIN {chain:[{task,description,permissions?},{parallel:[...]}]} for sequential work.
63
+ • SINGLE {task, description, tier, permissions?} (same-turn singles overlap); PARALLEL {tasks:[{task,description,tier,permissions?,count?,output?,reads?,progress?}], concurrency?, worktree?}; CHAIN {chain:[{task,description,tier,permissions?},{parallel:[...]}]} for sequential work.
62
64
  • description is required (single-line, max 80 chars, UI only). task is the full child prompt. permissions omitted = full. Plan-mode parents must pass permissions:"read-only".
63
- • Children always start with a fresh session. timeoutMs/maxRuntimeMs apply to foreground and async/background runs.
65
+ Every executable child requires tier:"light"|"standard"|"heavy". Direct model overrides and parent-model inheritance are rejected; tier resolution fails closed. Children always start with a fresh session. timeoutMs/maxRuntimeMs apply to foreground and async/background runs.
64
66
  • Chain templates may use {task}, {previous}, {chain_dir}, and named outputs. Parallel worktree isolation requires a clean git repo.
65
- • Chain example: { chain: [{task:"Analyze {task}", description:"Analyze request"}, {parallel: [{task:"Check {previous}", description:"Check prior result", permissions:"read-only", count: 3}]}] }
67
+ • Chain example: { chain: [{task:"Analyze {task}", description:"Analyze request", tier:"standard"}, {parallel: [{task:"Check {previous}", description:"Check prior result", tier:"light", permissions:"read-only", count: 3}]}] }
66
68
 
67
69
  CONTROL:
68
70
  • Use action without execution fields: doctor, watchdog.status, watchdog.check, watchdog.recommend-model, watchdog.configure, status, interrupt, stop, resume, steer, append-step.
@@ -189,21 +191,6 @@ export function buildSubagentToolDescription(config = {}, options) {
189
191
  else {
190
192
  description = FULL_SUBAGENT_TOOL_DESCRIPTION;
191
193
  }
192
- // lunr: append model-tier guidance only when lunR core's tier bridge is registered and enabled.
193
- if (isModelTierModeEnabled())
194
- return `${description}\n\n${MODEL_TIER_GUIDANCE}`;
195
194
  return description;
196
195
  }
197
- // lunr: model tier guidance appended to the subagent tool description when tier mode is on.
198
- const MODEL_TIER_GUIDANCE = `MODEL TIERS: Model tiers are enabled. For each subagent choose \`tier\`: 'light' for simple lookups/formatting, 'standard' for typical coding tasks, 'heavy' for deep reasoning/complex debugging. An explicit \`model\` overrides the tier. Omit both to inherit the parent model.`;
199
- // lunr: check lunR core's model-tier bridge (Symbol.for("@lunr/model-tiers")); absent bridge means tier mode is off.
200
- function isModelTierModeEnabled() {
201
- try {
202
- const bridge = globalThis[Symbol.for("@lunr/model-tiers")];
203
- return typeof bridge?.isTierModeEnabled === "function" && bridge.isTierModeEnabled() === true;
204
- }
205
- catch {
206
- return false;
207
- }
208
- }
209
196
  //# sourceMappingURL=tool-description.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool-description.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/extension/tool-description.ts"],"names":[],"mappings":"AAAA,cAAc;AACd,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAEtE,MAAM,4BAA4B,GAAG,8BAA8B,CAAC;AACpE,MAAM,iCAAiC,GAAG,EAAE,GAAG,IAAI,CAAC;AAEpD,MAAM,CAAC,MAAM,wBAAwB,GAAG;;;;;;;gQAOsN,CAAC;AAE/P,MAAM,CAAC,MAAM,8BAA8B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA0C5C,wBAAwB,EAAE,CAAC;AAE7B,MAAM,CAAC,MAAM,iCAAiC,GAAG;;;;;;;;;;;;;;;;;;;;sNAoBmK,CAAC;AAErN,SAAS,qBAAqB,CAAC,KAAc,EAAgC;IAC5E,OAAO,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,QAAQ,CAAC;AAAA,CACrE;AAED,SAAS,IAAI,CAAC,OAA2C,EAAE,OAAe,EAAQ;IACjF,CAAC,OAAO,EAAE,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,kBAAkB,OAAO,EAAE,CAAC,CAAC;AAAA,CAC7D;AAQD,MAAM,UAAU,0BAA0B,CAAC,MAAoD,EAAE,OAAgC,EAAuB;IACvJ,MAAM,IAAI,GAAG,MAAM,CAAC,mBAAm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,GAAG,0BAA0B,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACzD,IAAI,WAAmB,CAAC;IACxB,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACxB,WAAW,GAAG,iCAAiC,CAAC;IACjD,CAAC;SAAM,IAAI,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,MAAM,GAAG,yBAAyB,CAAC,OAAO,CAAC,CAAC;QAClD,IAAI,MAAM,EAAE,CAAC;YACZ,WAAW,GAAG,2BAA2B,CAAC,MAAM,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACP,IAAI,CAAC,OAAO,EAAE,GAAG,4BAA4B,mFAAmF,CAAC,CAAC;YAClI,WAAW,GAAG,8BAA8B,CAAC;QAC9C,CAAC;IACF,CAAC;SAAM,CAAC;QACP,WAAW,GAAG,8BAA8B,CAAC;IAC9C,CAAC;IACD,gGAAgG;IAChG,IAAI,sBAAsB,EAAE;QAAE,OAAO,GAAG,WAAW,OAAO,mBAAmB,EAAE,CAAC;IAChF,OAAO,WAAW,CAAC;AAAA,CACnB;AAED,4FAA4F;AAC5F,MAAM,mBAAmB,GAAG,qRAAqR,CAAC;AAElT,qHAAqH;AACrH,SAAS,sBAAsB,GAAY;IAC1C,IAAI,CAAC;QACJ,MAAM,MAAM,GAAI,UAAsC,CAAC,MAAM,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAE1E,CAAC;QACb,OAAO,OAAO,MAAM,EAAE,iBAAiB,KAAK,UAAU,IAAI,MAAM,CAAC,iBAAiB,EAAE,KAAK,IAAI,CAAC;IAC/F,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AAAA,CACD","sourcesContent":["// @ts-nocheck\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { ExtensionConfig, ToolDescriptionMode } from \"../shared/types.ts\";\nimport { getAgentDir, getProjectConfigDir } from \"../shared/utils.ts\";\n\nconst CUSTOM_TOOL_DESCRIPTION_FILE = \"subagent-tool-description.md\";\nconst CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;\n\nexport const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:\n• Prompt children directly. There is no agent roster. Every execution task needs task (the full child prompt) and description (a concise UI label).\n• permissions is \"full\" or \"read-only\". Omitted permissions means full. Plan-mode parents must pass permissions: \"read-only\"; full or omitted launches are rejected.\n• Keep execution and control separate: omit action for SINGLE/PARALLEL/CHAIN execution; use action only for status/interrupt/stop/resume/steer/append-step/doctor/watchdog.*/schedule*.\n• Async/background runs: launch with async:true only when work can proceed independently. Do not sleep or poll status just to wait. In an interactive session, normally return control and let lunR wake you; use subagent_wait when this request must run to completion in the current turn or skill. Headless sessions auto-drain current-session work.\n• Child-safety boundary: ordinary children are not orchestrators and must not run subagents. Only explicitly configured fanout children may use the child-safe subagent tool, still bounded by depth/session limits.\n• Writing/review safety: keep one full-access writer for the same cwd/worktree. Use fresh-context permissions: \"read-only\" children for independent review, then have the parent synthesize and apply fixes as the sole writer unless an isolated worktree was intentionally requested.\n• Artifacts/status essentials: chain outputs live under {chain_dir}; async runs expose asyncId/asyncDir with status.json, events.jsonl, output logs, and status via { action: \"status\", id }. Include output paths and residual risks when reporting results.`;\n\nexport const FULL_SUBAGENT_TOOL_DESCRIPTION = `Delegate work to generic children by prompting them directly. There are no named agent types.\n\nEXECUTION (use exactly ONE mode):\n• SINGLE: { task, description, permissions? } — one child. Multiple SINGLE calls in the same turn run concurrently; explicit concurrency/run limits still apply.\n• PARALLEL: { tasks: [{task, description, permissions?, count?, output?, reads?, progress?}, ...], concurrency?: number, worktree?: true } — one-call concurrent execution (default: all tasks at once; worktree: isolate each task in a git worktree)\n• CHAIN: { chain: [{task, description, permissions?}, {parallel:[{task, description, permissions?, count:3}]}] } — sequential pipeline with optional parallel fan-out. Use chain when a later child needs an earlier result.\n• description is required, single-line, max 80 characters. It is UI metadata only. task is the complete child prompt.\n• permissions: \"full\" (default) or \"read-only\". Full includes coding tools (read, search, shell, edit, write, web, LSP, MCP) and excludes parent-owned tools (cron, memory, behavior, goals, nested subagents). Plan-mode parents may launch only permissions: \"read-only\".\n• Children always start with a fresh session (no inherited parent transcript). Model strings accept a thinking suffix (provider/model:off|minimal|low|medium|high|xhigh|max).\n• Optional timeout: { timeoutMs } or { maxRuntimeMs } sets a run-level max runtime for foreground and async/background runs\n\nCHAIN TEMPLATE VARIABLES (use in task and description strings):\n• {task} - The original task/request from the user\n• {previous} - Text response from the previous step (empty for first step)\n• {chain_dir} - Shared directory for chain files (e.g., <tmpdir>/pi-subagents-<scope>/chain-runs/abc123/)\n\nCHAIN EXAMPLES:\n• Sequential: { chain: [{task:\"Analyze {task}\", description:\"Analyze request\"}, {task:\"Plan based on {previous}\", description:\"Draft plan\"}] }\n• Parallel fan-out: { chain: [{parallel: [{task:\"Check part of {task}\", description:\"Check one part\", permissions:\"read-only\", count: 3}]}] }\n• Mixed: { chain: [{task:\"Research {task}\", description:\"Research request\", permissions:\"read-only\"}, {parallel: [{task:\"Review {previous}\", description:\"Review findings\", permissions:\"read-only\", count: 2}]}, {task:\"Summarize {previous}\", description:\"Summarize reviews\"}] }\n\nCONTROL (use action field, omit task/chain/tasks):\n• { action: \"watchdog.status\" | \"watchdog.check\" | \"watchdog.recommend-model\" } - inspect the opt-in subagent watchdog and its strong complementary model recommendation\n• { action: \"watchdog.configure\", model: \"recommended\" | \"inherit\" | \"provider/model[:thinking]\", scope?: \"session\" | \"user\" | \"project\", target?: \"main\" | \"children\", thinking?: \"inherit\" | \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" } - configure watchdog model selection; default scope is session, use persistent scopes only when the user asks\n• { action: \"status\", id: \"...\" } - inspect an async/background run by id or prefix\n• { action: \"status\", view: \"fleet\" } - read-only active foreground/async fleet view with transcript commands\n• { action: \"status\", id: \"...\", view: \"transcript\", index?: 0, lines?: 80 } - tail a run or child output/session transcript\n• { action: \"interrupt\", id?: \"...\" } - soft-interrupt the current child turn and leave the run paused\n• { action: \"stop\", id: \"...\" } - stop a current-session top-level async run; stopped runs finish with state \"stopped\"\n• { action: \"resume\", id: \"...\", message: \"...\", index?: 0 } - interrupt then follow up with a live async child, or revive a completed async/foreground child from its session\n• { action: \"steer\", id: \"...\", message: \"...\", index?: 0 } - await correlated child input acceptance for up to 3 seconds; returns delivered, scheduled, pending, partial, recovered, or failed with a request id. Only top-level single runs may recover after a further 15-second pause/revival bound; chain, parallel, and nested runs never auto-interrupt.\n• { action: \"append-step\", id: \"...\", chain: [{task:\"Use {previous}\", description:\"Follow-up step\"}] } - append one step to the tail of a running async chain\n\nSCHEDULE (opt-in; requires { \"scheduledRuns\": { \"enabled\": true } } in config.json):\n• { action: \"schedule\", task, description, permissions?, schedule: \"+10m\" | \"2030-01-01T09:00:00Z\", scheduleName? } - defer a child launch until a future time. Also accepts tasks[] or chain[]. Scheduled runs always launch async with fresh context; they become normal tracked async runs once they fire. Only schedule explicit delayed runs the user asked for.\n• { action: \"schedule-list\" } - list scheduled runs for this session\n• { action: \"schedule-status\", id: \"...\" } - inspect one scheduled run\n• { action: \"schedule-cancel\", id: \"...\" } - cancel a scheduled run before it fires\n\nDIAGNOSTICS:\n• { action: \"doctor\" } - read-only report for runtime paths, sessions, and intercom\n\n${SUBAGENT_SAFETY_GUIDANCE}`;\n\nexport const COMPACT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to generic children by prompting them. Use exactly one mode per call.\n\nEXECUTE:\n• SINGLE {task, description, permissions?} (same-turn singles overlap); PARALLEL {tasks:[{task,description,permissions?,count?,output?,reads?,progress?}], concurrency?, worktree?}; CHAIN {chain:[{task,description,permissions?},{parallel:[...]}]} for sequential work.\n• description is required (single-line, max 80 chars, UI only). task is the full child prompt. permissions omitted = full. Plan-mode parents must pass permissions:\"read-only\".\n• Children always start with a fresh session. timeoutMs/maxRuntimeMs apply to foreground and async/background runs.\n• Chain templates may use {task}, {previous}, {chain_dir}, and named outputs. Parallel worktree isolation requires a clean git repo.\n• Chain example: { chain: [{task:\"Analyze {task}\", description:\"Analyze request\"}, {parallel: [{task:\"Check {previous}\", description:\"Check prior result\", permissions:\"read-only\", count: 3}]}] }\n\nCONTROL:\n• Use action without execution fields: doctor, watchdog.status, watchdog.check, watchdog.recommend-model, watchdog.configure, status, interrupt, stop, resume, steer, append-step.\n• Async control actions: status, interrupt, stop, resume, steer, append-step. Use stop with an id for current-session top-level async runs. Use status view:\"fleet\" for active-run overview, view:\"transcript\" to tail child output, and steer for acknowledged live guidance. Steering delivery means lunR accepted the correlated user input, not model compliance; use index for a specific child.\n• Opt-in schedule actions: schedule, schedule-list, schedule-status, schedule-cancel. Schedule only explicit delayed runs the user asked for.\n\nASYNC / WAIT:\n• async:true detaches background work. Do not sleep or poll just to wait. Interactive sessions normally yield for completion notifications; use subagent_wait for run-to-completion turns or skills. Headless sessions auto-drain current-session work.\n• Status and artifacts live under asyncId/asyncDir with status.json, events.jsonl, output logs, session files, and { action:\"status\", id:\"...\" }.\n\nSAFETY:\n• Ordinary children are not orchestrators and must not run subagents. Only explicit fanout children may use child-safe subagent, still bounded by depth/session limits.\n• Keep one full-access writer per cwd/worktree. Use fresh permissions:\"read-only\" review/validation fanout, then synthesize and apply fixes from the parent unless isolated worktrees were intentionally requested.`;\n\nfunction isToolDescriptionMode(value: unknown): value is ToolDescriptionMode {\n\treturn value === \"full\" || value === \"compact\" || value === \"custom\";\n}\n\nfunction warn(options: ToolDescriptionOptions | undefined, message: string): void {\n\t(options?.warn ?? console.warn)(`[pi-subagents] ${message}`);\n}\n\nexport interface ToolDescriptionOptions {\n\tcwd?: string;\n\tagentDir?: string;\n\twarn?: (message: string) => void;\n}\n\nexport function resolveToolDescriptionMode(config: Pick<ExtensionConfig, \"toolDescriptionMode\">, options?: ToolDescriptionOptions): ToolDescriptionMode {\n\tconst mode = config.toolDescriptionMode;\n\tif (mode === undefined) return \"full\";\n\tif (isToolDescriptionMode(mode)) return mode;\n\twarn(options, `Ignoring invalid toolDescriptionMode ${JSON.stringify(mode)}; expected \"full\", \"compact\", or \"custom\".`);\n\treturn \"full\";\n}\n\nfunction customDescriptionPaths(options?: ToolDescriptionOptions): string[] {\n\tconst cwd = options?.cwd ?? process.cwd();\n\tconst agentDir = options?.agentDir ?? getAgentDir();\n\treturn [\n\t\tpath.join(getProjectConfigDir(cwd), CUSTOM_TOOL_DESCRIPTION_FILE),\n\t\tpath.join(agentDir, CUSTOM_TOOL_DESCRIPTION_FILE),\n\t];\n}\n\nfunction renderCustomTemplate(template: string, options?: ToolDescriptionOptions): string {\n\tconst cwd = options?.cwd ?? process.cwd();\n\tconst agentDir = options?.agentDir ?? getAgentDir();\n\tconst projectConfigDir = getProjectConfigDir(cwd);\n\tconst variables: Record<string, () => string> = {\n\t\tfullDescription: () => FULL_SUBAGENT_TOOL_DESCRIPTION,\n\t\tfull: () => FULL_SUBAGENT_TOOL_DESCRIPTION,\n\t\tcompactDescription: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,\n\t\tcompact: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,\n\t\tsafetyGuidance: () => SUBAGENT_SAFETY_GUIDANCE,\n\t\tsafety: () => SUBAGENT_SAFETY_GUIDANCE,\n\t\tagentDir: () => agentDir,\n\t\tprojectConfigDir: () => projectConfigDir,\n\t};\n\treturn template.replace(/\\{\\{(\\w+)\\}\\}/g, (raw, name: string) => {\n\t\tconst replacement = variables[name];\n\t\tif (replacement) return replacement();\n\t\twarn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE}: unknown placeholder ${raw} left unchanged.`);\n\t\treturn raw;\n\t});\n}\n\nfunction loadCustomToolDescription(options?: ToolDescriptionOptions): string | undefined {\n\tfor (const filePath of customDescriptionPaths(options)) {\n\t\tlet stat: fs.Stats;\n\t\ttry {\n\t\t\tstat = fs.statSync(filePath);\n\t\t} catch (error) {\n\t\t\tif (typeof error === \"object\" && error !== null && \"code\" in error && (error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n\t\t\twarn(options, `Failed to inspect custom tool description '${filePath}': ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!stat.isFile()) {\n\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it is not a file.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (stat.size > CUSTOM_TOOL_DESCRIPTION_MAX_BYTES) {\n\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it is larger than ${CUSTOM_TOOL_DESCRIPTION_MAX_BYTES} bytes.`);\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst template = fs.readFileSync(filePath, \"utf-8\").trim();\n\t\t\tif (!template) {\n\t\t\t\twarn(options, `Ignoring empty custom tool description '${filePath}'.`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst rendered = renderCustomTemplate(template, options).trim();\n\t\t\tif (!rendered) {\n\t\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it rendered empty.`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn rendered;\n\t\t} catch (error) {\n\t\t\twarn(options, `Failed to read custom tool description '${filePath}': ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction withMandatorySafetyGuidance(description: string): string {\n\tconst customDescription = description\n\t\t.split(SUBAGENT_SAFETY_GUIDANCE)\n\t\t.map((part) => part.trim())\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\\n\");\n\treturn customDescription\n\t\t? `${customDescription}\\n\\n${SUBAGENT_SAFETY_GUIDANCE}`\n\t\t: SUBAGENT_SAFETY_GUIDANCE;\n}\n\nexport function buildSubagentToolDescription(config: Pick<ExtensionConfig, \"toolDescriptionMode\"> = {}, options?: ToolDescriptionOptions): string {\n\tconst mode = resolveToolDescriptionMode(config, options);\n\tlet description: string;\n\tif (mode === \"compact\") {\n\t\tdescription = COMPACT_SUBAGENT_TOOL_DESCRIPTION;\n\t} else if (mode === \"custom\") {\n\t\tconst custom = loadCustomToolDescription(options);\n\t\tif (custom) {\n\t\t\tdescription = withMandatorySafetyGuidance(custom);\n\t\t} else {\n\t\t\twarn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE} was not found or valid for toolDescriptionMode \"custom\"; using full description.`);\n\t\t\tdescription = FULL_SUBAGENT_TOOL_DESCRIPTION;\n\t\t}\n\t} else {\n\t\tdescription = FULL_SUBAGENT_TOOL_DESCRIPTION;\n\t}\n\t// lunr: append model-tier guidance only when lunR core's tier bridge is registered and enabled.\n\tif (isModelTierModeEnabled()) return `${description}\\n\\n${MODEL_TIER_GUIDANCE}`;\n\treturn description;\n}\n\n// lunr: model tier guidance appended to the subagent tool description when tier mode is on.\nconst MODEL_TIER_GUIDANCE = `MODEL TIERS: Model tiers are enabled. For each subagent choose \\`tier\\`: 'light' for simple lookups/formatting, 'standard' for typical coding tasks, 'heavy' for deep reasoning/complex debugging. An explicit \\`model\\` overrides the tier. Omit both to inherit the parent model.`;\n\n// lunr: check lunR core's model-tier bridge (Symbol.for(\"@lunr/model-tiers\")); absent bridge means tier mode is off.\nfunction isModelTierModeEnabled(): boolean {\n\ttry {\n\t\tconst bridge = (globalThis as Record<symbol, unknown>)[Symbol.for(\"@lunr/model-tiers\")] as\n\t\t\t| { isTierModeEnabled?: () => unknown }\n\t\t\t| undefined;\n\t\treturn typeof bridge?.isTierModeEnabled === \"function\" && bridge.isTierModeEnabled() === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n"]}
1
+ {"version":3,"file":"tool-description.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/extension/tool-description.ts"],"names":[],"mappings":"AAAA,cAAc;AACd,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAEtE,MAAM,4BAA4B,GAAG,8BAA8B,CAAC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,8BAA8B,CAAC;IAC9C,CAAC;IACD,OAAO,WAAW,CAAC;AAAA,CACnB","sourcesContent":["// @ts-nocheck\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { ExtensionConfig, ToolDescriptionMode } from \"../shared/types.ts\";\nimport { getAgentDir, getProjectConfigDir } from \"../shared/utils.ts\";\n\nconst CUSTOM_TOOL_DESCRIPTION_FILE = \"subagent-tool-description.md\";\nconst CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;\n\nexport const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:\n• Prompt children directly. There is no agent roster. Every execution task needs task (the full child prompt) and description (a concise UI label).\n• Every executable child also needs tier: \"light\", \"standard\", or \"heavy\". Direct model overrides and parent-model inheritance are not available. A missing, disabled, unconfigured, unavailable, or unauthenticated tier fails before launch.\n• permissions is \"full\" or \"read-only\". Omitted permissions means full. Plan-mode parents must pass permissions: \"read-only\"; full or omitted launches are rejected.\n• Keep execution and control separate: omit action for SINGLE/PARALLEL/CHAIN execution; use action only for status/interrupt/stop/resume/steer/append-step/doctor/watchdog.*/schedule*.\n• Async/background runs: launch with async:true only when work can proceed independently. Do not sleep or poll status just to wait. In an interactive session, normally return control and let lunR wake you; use subagent_wait when this request must run to completion in the current turn or skill. Headless sessions auto-drain current-session work.\n• Child-safety boundary: ordinary children are not orchestrators and must not run subagents. Only explicitly configured fanout children may use the child-safe subagent tool, still bounded by depth/session limits.\n• Writing/review safety: keep one full-access writer for the same cwd/worktree. Use fresh-context permissions: \"read-only\" children for independent review, then have the parent synthesize and apply fixes as the sole writer unless an isolated worktree was intentionally requested.\n• Artifacts/status essentials: chain outputs live under {chain_dir}; async runs expose asyncId/asyncDir with status.json, events.jsonl, output logs, and status via { action: \"status\", id }. Include output paths and residual risks when reporting results.`;\n\nexport const FULL_SUBAGENT_TOOL_DESCRIPTION = `Delegate work to generic children by prompting them directly. There are no named agent types.\n\nEXECUTION (use exactly ONE mode):\n• SINGLE: { task, description, tier, permissions? } — one child. Multiple SINGLE calls in the same turn run concurrently; explicit concurrency/run limits still apply.\n• PARALLEL: { tasks: [{task, description, tier, permissions?, count?, output?, reads?, progress?}, ...], concurrency?: number, worktree?: true } — one-call concurrent execution (default: all tasks at once; worktree: isolate each task in a git worktree)\n• CHAIN: { chain: [{task, description, tier, permissions?}, {parallel:[{task, description, tier, permissions?, count:3}]}] } — sequential pipeline with optional parallel fan-out. Use chain when a later child needs an earlier result.\n• description is required, single-line, max 80 characters. It is UI metadata only. task is the complete child prompt.\n• permissions: \"full\" (default) or \"read-only\". Full includes coding tools (read, search, shell, edit, write, web, LSP, MCP) and excludes parent-owned tools (cron, memory, behavior, goals, nested subagents). Plan-mode parents may launch only permissions: \"read-only\".\n• Every executable child requires tier: \"light\", \"standard\", or \"heavy\". Direct model overrides and parent-model inheritance are rejected. The configured tier model and credentials must be available.\n• Children always start with a fresh session (no inherited parent transcript).\n• Optional timeout: { timeoutMs } or { maxRuntimeMs } sets a run-level max runtime for foreground and async/background runs\n\nCHAIN TEMPLATE VARIABLES (use in task and description strings):\n• {task} - The original task/request from the user\n• {previous} - Text response from the previous step (empty for first step)\n• {chain_dir} - Shared directory for chain files (e.g., <tmpdir>/pi-subagents-<scope>/chain-runs/abc123/)\n\nCHAIN EXAMPLES:\n• Sequential: { chain: [{task:\"Analyze {task}\", description:\"Analyze request\", tier:\"standard\"}, {task:\"Plan based on {previous}\", description:\"Draft plan\", tier:\"heavy\"}] }\n• Parallel fan-out: { chain: [{parallel: [{task:\"Check part of {task}\", description:\"Check one part\", tier:\"light\", permissions:\"read-only\", count: 3}]}] }\n• Mixed: { chain: [{task:\"Research {task}\", description:\"Research request\", tier:\"standard\", permissions:\"read-only\"}, {parallel: [{task:\"Review {previous}\", description:\"Review findings\", tier:\"light\", permissions:\"read-only\", count: 2}]}, {task:\"Summarize {previous}\", description:\"Summarize reviews\", tier:\"standard\"}] }\n\nCONTROL (use action field, omit task/chain/tasks):\n• { action: \"watchdog.status\" | \"watchdog.check\" | \"watchdog.recommend-model\" } - inspect the opt-in subagent watchdog and its strong complementary model recommendation\n• { action: \"watchdog.configure\", model: \"recommended\" | \"inherit\" | \"provider/model[:thinking]\", scope?: \"session\" | \"user\" | \"project\", target?: \"main\" | \"children\", thinking?: \"inherit\" | \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\" } - configure watchdog model selection; default scope is session, use persistent scopes only when the user asks\n• { action: \"status\", id: \"...\" } - inspect an async/background run by id or prefix\n• { action: \"status\", view: \"fleet\" } - read-only active foreground/async fleet view with transcript commands\n• { action: \"status\", id: \"...\", view: \"transcript\", index?: 0, lines?: 80 } - tail a run or child output/session transcript\n• { action: \"interrupt\", id?: \"...\" } - soft-interrupt the current child turn and leave the run paused\n• { action: \"stop\", id: \"...\" } - stop a current-session top-level async run; stopped runs finish with state \"stopped\"\n• { action: \"resume\", id: \"...\", message: \"...\", index?: 0 } - interrupt then follow up with a live async child, or revive a completed async/foreground child from its session\n• { action: \"steer\", id: \"...\", message: \"...\", index?: 0 } - await correlated child input acceptance for up to 3 seconds; returns delivered, scheduled, pending, partial, recovered, or failed with a request id. Only top-level single runs may recover after a further 15-second pause/revival bound; chain, parallel, and nested runs never auto-interrupt.\n• { action: \"append-step\", id: \"...\", chain: [{task:\"Use {previous}\", description:\"Follow-up step\", tier:\"standard\"}] } - append one step to the tail of a running async chain\n\nSCHEDULE (opt-in; requires { \"scheduledRuns\": { \"enabled\": true } } in config.json):\n• { action: \"schedule\", task, description, tier, permissions?, schedule: \"+10m\" | \"2030-01-01T09:00:00Z\", scheduleName? } - defer a child launch until a future time. Also accepts tasks[] or chain[]. Scheduled runs always launch async with fresh context; they become normal tracked async runs once they fire. Only schedule explicit delayed runs the user asked for.\n• { action: \"schedule-list\" } - list scheduled runs for this session\n• { action: \"schedule-status\", id: \"...\" } - inspect one scheduled run\n• { action: \"schedule-cancel\", id: \"...\" } - cancel a scheduled run before it fires\n\nDIAGNOSTICS:\n• { action: \"doctor\" } - read-only report for runtime paths, sessions, and intercom\n\n${SUBAGENT_SAFETY_GUIDANCE}`;\n\nexport const COMPACT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to generic children by prompting them. Use exactly one mode per call.\n\nEXECUTE:\n• SINGLE {task, description, tier, permissions?} (same-turn singles overlap); PARALLEL {tasks:[{task,description,tier,permissions?,count?,output?,reads?,progress?}], concurrency?, worktree?}; CHAIN {chain:[{task,description,tier,permissions?},{parallel:[...]}]} for sequential work.\n• description is required (single-line, max 80 chars, UI only). task is the full child prompt. permissions omitted = full. Plan-mode parents must pass permissions:\"read-only\".\n• Every executable child requires tier:\"light\"|\"standard\"|\"heavy\". Direct model overrides and parent-model inheritance are rejected; tier resolution fails closed. Children always start with a fresh session. timeoutMs/maxRuntimeMs apply to foreground and async/background runs.\n• Chain templates may use {task}, {previous}, {chain_dir}, and named outputs. Parallel worktree isolation requires a clean git repo.\n• Chain example: { chain: [{task:\"Analyze {task}\", description:\"Analyze request\", tier:\"standard\"}, {parallel: [{task:\"Check {previous}\", description:\"Check prior result\", tier:\"light\", permissions:\"read-only\", count: 3}]}] }\n\nCONTROL:\n• Use action without execution fields: doctor, watchdog.status, watchdog.check, watchdog.recommend-model, watchdog.configure, status, interrupt, stop, resume, steer, append-step.\n• Async control actions: status, interrupt, stop, resume, steer, append-step. Use stop with an id for current-session top-level async runs. Use status view:\"fleet\" for active-run overview, view:\"transcript\" to tail child output, and steer for acknowledged live guidance. Steering delivery means lunR accepted the correlated user input, not model compliance; use index for a specific child.\n• Opt-in schedule actions: schedule, schedule-list, schedule-status, schedule-cancel. Schedule only explicit delayed runs the user asked for.\n\nASYNC / WAIT:\n• async:true detaches background work. Do not sleep or poll just to wait. Interactive sessions normally yield for completion notifications; use subagent_wait for run-to-completion turns or skills. Headless sessions auto-drain current-session work.\n• Status and artifacts live under asyncId/asyncDir with status.json, events.jsonl, output logs, session files, and { action:\"status\", id:\"...\" }.\n\nSAFETY:\n• Ordinary children are not orchestrators and must not run subagents. Only explicit fanout children may use child-safe subagent, still bounded by depth/session limits.\n• Keep one full-access writer per cwd/worktree. Use fresh permissions:\"read-only\" review/validation fanout, then synthesize and apply fixes from the parent unless isolated worktrees were intentionally requested.`;\n\nfunction isToolDescriptionMode(value: unknown): value is ToolDescriptionMode {\n\treturn value === \"full\" || value === \"compact\" || value === \"custom\";\n}\n\nfunction warn(options: ToolDescriptionOptions | undefined, message: string): void {\n\t(options?.warn ?? console.warn)(`[pi-subagents] ${message}`);\n}\n\nexport interface ToolDescriptionOptions {\n\tcwd?: string;\n\tagentDir?: string;\n\twarn?: (message: string) => void;\n}\n\nexport function resolveToolDescriptionMode(config: Pick<ExtensionConfig, \"toolDescriptionMode\">, options?: ToolDescriptionOptions): ToolDescriptionMode {\n\tconst mode = config.toolDescriptionMode;\n\tif (mode === undefined) return \"full\";\n\tif (isToolDescriptionMode(mode)) return mode;\n\twarn(options, `Ignoring invalid toolDescriptionMode ${JSON.stringify(mode)}; expected \"full\", \"compact\", or \"custom\".`);\n\treturn \"full\";\n}\n\nfunction customDescriptionPaths(options?: ToolDescriptionOptions): string[] {\n\tconst cwd = options?.cwd ?? process.cwd();\n\tconst agentDir = options?.agentDir ?? getAgentDir();\n\treturn [\n\t\tpath.join(getProjectConfigDir(cwd), CUSTOM_TOOL_DESCRIPTION_FILE),\n\t\tpath.join(agentDir, CUSTOM_TOOL_DESCRIPTION_FILE),\n\t];\n}\n\nfunction renderCustomTemplate(template: string, options?: ToolDescriptionOptions): string {\n\tconst cwd = options?.cwd ?? process.cwd();\n\tconst agentDir = options?.agentDir ?? getAgentDir();\n\tconst projectConfigDir = getProjectConfigDir(cwd);\n\tconst variables: Record<string, () => string> = {\n\t\tfullDescription: () => FULL_SUBAGENT_TOOL_DESCRIPTION,\n\t\tfull: () => FULL_SUBAGENT_TOOL_DESCRIPTION,\n\t\tcompactDescription: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,\n\t\tcompact: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,\n\t\tsafetyGuidance: () => SUBAGENT_SAFETY_GUIDANCE,\n\t\tsafety: () => SUBAGENT_SAFETY_GUIDANCE,\n\t\tagentDir: () => agentDir,\n\t\tprojectConfigDir: () => projectConfigDir,\n\t};\n\treturn template.replace(/\\{\\{(\\w+)\\}\\}/g, (raw, name: string) => {\n\t\tconst replacement = variables[name];\n\t\tif (replacement) return replacement();\n\t\twarn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE}: unknown placeholder ${raw} left unchanged.`);\n\t\treturn raw;\n\t});\n}\n\nfunction loadCustomToolDescription(options?: ToolDescriptionOptions): string | undefined {\n\tfor (const filePath of customDescriptionPaths(options)) {\n\t\tlet stat: fs.Stats;\n\t\ttry {\n\t\t\tstat = fs.statSync(filePath);\n\t\t} catch (error) {\n\t\t\tif (typeof error === \"object\" && error !== null && \"code\" in error && (error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n\t\t\twarn(options, `Failed to inspect custom tool description '${filePath}': ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!stat.isFile()) {\n\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it is not a file.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (stat.size > CUSTOM_TOOL_DESCRIPTION_MAX_BYTES) {\n\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it is larger than ${CUSTOM_TOOL_DESCRIPTION_MAX_BYTES} bytes.`);\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst template = fs.readFileSync(filePath, \"utf-8\").trim();\n\t\t\tif (!template) {\n\t\t\t\twarn(options, `Ignoring empty custom tool description '${filePath}'.`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst rendered = renderCustomTemplate(template, options).trim();\n\t\t\tif (!rendered) {\n\t\t\t\twarn(options, `Ignoring custom tool description '${filePath}' because it rendered empty.`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\treturn rendered;\n\t\t} catch (error) {\n\t\t\twarn(options, `Failed to read custom tool description '${filePath}': ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction withMandatorySafetyGuidance(description: string): string {\n\tconst customDescription = description\n\t\t.split(SUBAGENT_SAFETY_GUIDANCE)\n\t\t.map((part) => part.trim())\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\\n\");\n\treturn customDescription\n\t\t? `${customDescription}\\n\\n${SUBAGENT_SAFETY_GUIDANCE}`\n\t\t: SUBAGENT_SAFETY_GUIDANCE;\n}\n\nexport function buildSubagentToolDescription(config: Pick<ExtensionConfig, \"toolDescriptionMode\"> = {}, options?: ToolDescriptionOptions): string {\n\tconst mode = resolveToolDescriptionMode(config, options);\n\tlet description: string;\n\tif (mode === \"compact\") {\n\t\tdescription = COMPACT_SUBAGENT_TOOL_DESCRIPTION;\n\t} else if (mode === \"custom\") {\n\t\tconst custom = loadCustomToolDescription(options);\n\t\tif (custom) {\n\t\t\tdescription = withMandatorySafetyGuidance(custom);\n\t\t} else {\n\t\t\twarn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE} was not found or valid for toolDescriptionMode \"custom\"; using full description.`);\n\t\t\tdescription = FULL_SUBAGENT_TOOL_DESCRIPTION;\n\t\t}\n\t} else {\n\t\tdescription = FULL_SUBAGENT_TOOL_DESCRIPTION;\n\t}\n\treturn description;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"async-execution.d.ts","sourceRoot":"","sources":["../../../../../../src/builtin-extensions/pi-subagents/src/runs/background/async-execution.ts"],"names":[],"mappings":"AACA;;GAEG;AAQH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAMpE,OAAO,EAAiJ,KAAK,SAAS,EAAsE,MAAM,0BAA0B,CAAC;AAC7Q,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAI9D,OAAO,EAA4G,KAAK,kBAAkB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BAAkB,CAAC;IACtC,uFAAuF;IACvF,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,MAAM,0BAA0B,GACnC;IACD,KAAK,EAAE,UAAU,EAAE,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,UAAU,CAAC,OAAO,0BAA0B,CAAC,CAAC;IAC7D,UAAU,EAAE,SAAS,EAAE,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB,GACC;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAErB,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAQlE;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,OAAO,CAE1C;AAuBD,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,MAAM,GAAG;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAS9G;AAqND,wBAAgB,qBAAqB,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,0BAA0B,GAAG,0BAA0B,CAyRhH;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAChC,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,gBAAgB,GACtB,oBAAoB,CA+OtB;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CACjC,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,iBAAiB,GACvB,oBAAoB,CA+PtB","sourcesContent":["// @ts-nocheck\n/**\n * Async execution logic for subagent tool\n */\n\nimport { spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createRequire } from \"node:module\";\nimport type { ExtensionAPI } from \"@ashx-j/lunr\";\nimport { normalizeChildSpec } from \"../../shared/child-spec.ts\";\nimport { writePrivateAtomicJson } from \"../../shared/atomic-json.ts\";\nimport { applyThinkingSuffix } from \"../shared/pi-args.ts\";\nimport { snapshotParentPermissionMode } from \"../../../../../core/subagent-permission-inherit.ts\";\nimport { injectOutputPathSystemPrompt, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from \"../shared/single-output.ts\";\nimport { buildChainInstructions, isDynamicParallelStep, isParallelStep, resolveStepBehavior, suppressProgressForReadOnlyTask, writeInitialProgressFile, type ChainStep, type ResolvedStepBehavior, type SequentialStep, type StepOverrides } from \"../../shared/settings.ts\";\nimport type { RunnerStep } from \"../shared/parallel-utils.ts\";\nimport { resolvePiPackageRoot } from \"../shared/pi-spawn.ts\";\nimport { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from \"../../agents/skills.ts\";\nimport { PI_CODING_AGENT_PACKAGE_ROOT_ENV, resolveChildCwd } from \"../../shared/utils.ts\";\nimport { buildModelCandidates, resolveEffectiveSubagentModel, resolveModelCandidate, resolveSubagentModelOverride, type AvailableModelInfo, type ParentModel } from \"../shared/model-fallback.ts\";\nimport type { ModelScopeConfig } from \"../shared/model-scope.ts\";\nimport { resolveEffectiveThinking } from \"../../shared/model-info.ts\";\nimport { resolveExpectedWorktreeAgentCwd } from \"../shared/worktree.ts\";\nimport { buildWorkflowGraphSnapshot } from \"../shared/workflow-graph.ts\";\nimport { ChainOutputValidationError, validateChainOutputBindings } from \"../shared/chain-outputs.ts\";\nimport { createStructuredOutputRuntime } from \"../shared/structured-output.ts\";\nimport { resolveEffectiveAcceptance } from \"../shared/acceptance.ts\";\nimport {\n\ttype AcceptanceInput,\n\ttype ArtifactConfig,\n\ttype ChildSpec,\n\ttype Details,\n\ttype MaxOutputConfig,\n\ttype NestedRouteInfo,\n\ttype ResolvedControlConfig,\n\ttype ResolvedTurnBudget,\n\ttype ResolvedToolBudget,\n\ttype SubagentRunMode,\n\ttype SteeringRecoveryDescriptor,\n\tASYNC_DIR,\n\tRESULTS_DIR,\n\tSUBAGENT_ASYNC_STARTED_EVENT,\n\tSUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\tTEMP_ROOT_DIR,\n\tgetAsyncConfigPath,\n\tresolveChildMaxSubagentDepth,\n} from \"../../shared/types.ts\";\nimport { nestedResultsPath, resolveInheritedNestedRouteFromEnv, resolveNestedParentAddressFromEnv, writeNestedEvent } from \"../shared/nested-events.ts\";\nimport { initialTurnBudgetState } from \"../shared/turn-budget.ts\";\nimport { validateToolBudgetConfig } from \"../shared/tool-budget.ts\";\nimport type { ImportedAsyncRoot } from \"./chain-root-attachment.ts\";\nimport type { SessionLeaseRequest } from \"../shared/session-lease.ts\";\n\nconst require = createRequire(import.meta.url);\nconst piPackageRoot = resolvePiPackageRoot();\n\nfunction resolveJitiCliFromPackageJson(packageJsonPath: string): string | undefined {\n\tif (!fs.existsSync(packageJsonPath)) return undefined;\n\tconst packageRoot = path.dirname(packageJsonPath);\n\tconst pkg = JSON.parse(fs.readFileSync(packageJsonPath, \"utf-8\")) as {\n\t\tbin?: string | Record<string, string>;\n\t};\n\tconst binField = pkg.bin;\n\tconst binPath = typeof binField === \"string\"\n\t\t? binField\n\t\t: binField?.jiti ?? Object.values(binField ?? {})[0];\n\tconst candidates = [binPath, \"lib/jiti-cli.mjs\"].filter((candidate): candidate is string => Boolean(candidate));\n\tfor (const candidate of candidates) {\n\t\tconst cliPath = path.resolve(packageRoot, candidate);\n\t\tif (fs.existsSync(cliPath)) return cliPath;\n\t}\n\treturn undefined;\n}\n\nfunction resolveJitiCliPath(): string | undefined {\n\tconst candidates: Array<() => string | undefined> = [\n\t\t() => require.resolve(\"jiti/package.json\"),\n\t\t() => piPackageRoot\n\t\t\t? createRequire(path.join(piPackageRoot, \"package.json\")).resolve(\"jiti/package.json\")\n\t\t\t: undefined,\n\t\t() => {\n\t\t\tif (!process.argv[1]) return undefined;\n\t\t\tconst piEntry = fs.realpathSync(process.argv[1]);\n\t\t\treturn createRequire(piEntry).resolve(\"jiti/package.json\");\n\t\t},\n\t\t() => piPackageRoot ? path.join(piPackageRoot, \"node_modules\", \"jiti\", \"package.json\") : undefined,\n\t];\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst packageJsonPath = candidate();\n\t\t\tif (!packageJsonPath) continue;\n\t\t\tconst cliPath = resolveJitiCliFromPackageJson(packageJsonPath);\n\t\t\tif (cliPath) return cliPath;\n\t\t} catch {\n\t\t\t// Candidate not available in this install, continue probing.\n\t\t}\n\t}\n\treturn undefined;\n}\n\nconst jitiCliPath = resolveJitiCliPath();\n\ninterface AsyncExecutionContext {\n\tpi: ExtensionAPI;\n\tcwd: string;\n\tcurrentSessionId: string;\n\t/** Parent session id used by permission-system ask forwarding. */\n\tparentSessionId?: string;\n\tcurrentModelProvider?: string;\n\tcurrentModel?: ParentModel;\n\t/** Optional model-scope enforcement resolved from subagent settings. */\n\tmodelScope?: ModelScopeConfig;\n}\n\ninterface AsyncChainParams {\n\tchain: ChainStep[];\n\ttask?: string;\n\t/** Raw caller-facing goal used only by the started event. */\n\tgoal?: string;\n\tattachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };\n\tresultMode?: Exclude<SubagentRunMode, \"single\">;\n\tctx: AsyncExecutionContext;\n\tavailableModels?: AvailableModelInfo[];\n\tcwd?: string;\n\tmaxOutput?: MaxOutputConfig;\n\tartifactsDir?: string;\n\tartifactConfig: ArtifactConfig;\n\tshareEnabled: boolean;\n\tsessionRoot?: string;\n\tchainSkills?: string[];\n\tsessionFilesByFlatIndex?: (string | undefined)[];\n\tthinkingOverridesByFlatIndex?: (string | false | undefined)[];\n\tprogressDir?: string;\n\tdynamicFanoutMaxItems?: number;\n\tmaxSubagentDepth: number;\n\twaitToolEnabled?: boolean;\n\tworktreeSetupHook?: string;\n\tworktreeSetupHookTimeoutMs?: number;\n\tworktreeBaseDir?: string;\n\tcontrolConfig?: ResolvedControlConfig;\n\tcontrolIntercomTarget?: string;\n\tchildIntercomTarget?: (agent: string, index: number) => string | undefined;\n\tnestedRoute?: NestedRouteInfo;\n\tacceptance?: AcceptanceInput;\n\ttimeoutMs?: number;\n\tturnBudget?: ResolvedTurnBudget;\n\ttoolBudget?: ResolvedToolBudget;\n\tconfigToolBudget?: ResolvedToolBudget;\n\t/** Global cap on simultaneously-running subagent tasks within the async run. */\n\tglobalConcurrencyLimit?: number;\n}\n\ninterface AsyncSingleParams {\n\tspec: ChildSpec;\n\t/** Raw caller-facing goal used only by the started event. */\n\tgoal?: string;\n\tctx: AsyncExecutionContext;\n\tcwd?: string;\n\tmaxOutput?: MaxOutputConfig;\n\tartifactsDir?: string;\n\tartifactConfig: ArtifactConfig;\n\tshareEnabled: boolean;\n\tsessionRoot?: string;\n\tsessionDir?: string;\n\tsessionFile?: string;\n\trevivalLease?: SessionLeaseRequest;\n\tskills?: string[];\n\toutput?: string | boolean;\n\toutputMode?: \"inline\" | \"file-only\";\n\toutputBaseDir?: string;\n\tmodelOverride?: string;\n\tthinkingOverride?: string | false;\n\tavailableModels?: AvailableModelInfo[];\n\tmaxSubagentDepth: number;\n\twaitToolEnabled?: boolean;\n\tworktreeSetupHook?: string;\n\tworktreeSetupHookTimeoutMs?: number;\n\tworktreeBaseDir?: string;\n\tcontrolConfig?: ResolvedControlConfig;\n\tcontrolIntercomTarget?: string;\n\tchildIntercomTarget?: (agent: string, index: number) => string | undefined;\n\tnestedRoute?: NestedRouteInfo;\n\tacceptance?: AcceptanceInput;\n\ttimeoutMs?: number;\n\tabsoluteDeadlineAt?: number;\n\tturnBudget?: ResolvedTurnBudget;\n\ttoolBudget?: ResolvedToolBudget;\n\tconfigToolBudget?: ResolvedToolBudget;\n}\n\ninterface AsyncExecutionResult {\n\tcontent: Array<{ type: \"text\"; text: string }>;\n\tdetails: Details;\n\tisError?: boolean;\n}\n\nexport interface AsyncRunnerStepBuildParams {\n\tchain: ChainStep[];\n\ttask?: string;\n\tattachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };\n\tresultMode?: SubagentRunMode;\n\tctx: AsyncExecutionContext;\n\tavailableModels?: AvailableModelInfo[];\n\tcwd?: string;\n\tchainSkills?: string[];\n\tsessionFilesByFlatIndex?: (string | undefined)[];\n\tthinkingOverridesByFlatIndex?: (string | false | undefined)[];\n\tprogressDir?: string;\n\tdynamicFanoutMaxItems?: number;\n\tmaxSubagentDepth: number;\n\twaitToolEnabled?: boolean;\n\tworktreeBaseDir?: string;\n\tasyncDir: string;\n\toutputBaseDir?: string;\n\tvalidateOutputBindings?: boolean;\n\ttoolBudget?: ResolvedToolBudget;\n\tconfigToolBudget?: ResolvedToolBudget;\n\t/** Optional collision-free ChildSpec id namespace for steps appended to a live run. */\n\tchildIdRunId?: string;\n}\n\nexport type AsyncRunnerStepBuildResult =\n\t| {\n\t\tsteps: RunnerStep[];\n\t\trunnerCwd: string;\n\t\tworkflowGraph: ReturnType<typeof buildWorkflowGraphSnapshot>;\n\t\teventChain: ChainStep[];\n\t\toriginalTask?: string;\n\t}\n\t| { error: string };\n\nexport function formatAsyncStartedMessage(headline: string): string {\n\treturn [\n\t\theadline,\n\t\t\"\",\n\t\t\"The async run is detached. Do not run sleep timers or polling loops just to wait for it.\",\n\t\t\"If you have independent work, continue that work. When you have nothing left to do until the async result arrives, call subagent_wait() — it blocks until the run finishes and delivers the completion here. Only if you are certain you will get another turn (an interactive session where the user will prompt you again) can you instead stop and let Pi wake you; inside a skill that must run to completion, or in a non-interactive run, there is no next turn, so use subagent_wait().\",\n\t\t\"Use subagent({ action: \\\"status\\\", id: \\\"...\\\" }) when you need a one-shot status/result or to inspect a blocked/stale run. To block until completion, prefer subagent_wait(). Do not poll in a loop just to wait.\",\n\t].join(\"\\n\");\n}\n\n/**\n * Check if jiti is available for async execution\n */\nexport function isAsyncAvailable(): boolean {\n\treturn jitiCliPath !== undefined;\n}\n\nfunction isNodeExecutableName(execPath: string): boolean {\n\tconst basename = path.basename(execPath).toLowerCase();\n\treturn basename === \"node\" || basename === \"node.exe\" || basename === \"nodejs\" || basename === \"nodejs.exe\";\n}\n\nfunction canUseCurrentNodeExecutable(execPath: string): boolean {\n\ttry {\n\t\tfs.accessSync(execPath, process.platform === \"win32\" ? fs.constants.F_OK : fs.constants.X_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction resolveAsyncRunnerNodeCommand(): string {\n\tif (isNodeExecutableName(process.execPath) && canUseCurrentNodeExecutable(process.execPath)) {\n\t\treturn process.execPath;\n\t}\n\treturn process.platform === \"win32\" ? \"node.exe\" : \"node\";\n}\n\nexport function resolveAsyncRunnerLogPaths(cfg: object): { stdoutPath: string; stderrPath: string } | undefined {\n\tconst asyncDir = typeof (cfg as { asyncDir?: unknown }).asyncDir === \"string\"\n\t\t? (cfg as { asyncDir: string }).asyncDir\n\t\t: undefined;\n\tif (!asyncDir) return undefined;\n\treturn {\n\t\tstdoutPath: path.join(asyncDir, \"runner.stdout.log\"),\n\t\tstderrPath: path.join(asyncDir, \"runner.stderr.log\"),\n\t};\n}\n\nfunction closeFd(fd: number | undefined): void {\n\tif (fd === undefined) return;\n\ttry {\n\t\tfs.closeSync(fd);\n\t} catch {\n\t\t// Best-effort cleanup; child process already owns its duplicated stdio fd.\n\t}\n}\n\n/**\n * Spawn the async runner process\n */\nconst RUNNER_STARTUP_TIMEOUT_MS = 10_000;\nconst RUNNER_STARTUP_WAIT_BUFFER = typeof SharedArrayBuffer !== \"undefined\" ? new SharedArrayBuffer(4) : undefined;\nconst RUNNER_STARTUP_WAIT_VIEW = RUNNER_STARTUP_WAIT_BUFFER ? new Int32Array(RUNNER_STARTUP_WAIT_BUFFER) : undefined;\n\ntype RunnerStartupState = \"ready\" | \"acknowledged\";\n\ntype RunnerStartupWaitResult =\n\t| { ok: true; token: string }\n\t| { ok: false; error: string };\n\nfunction waitForStartupInterval(delayMs = 20): void {\n\tif (RUNNER_STARTUP_WAIT_VIEW) {\n\t\tAtomics.wait(RUNNER_STARTUP_WAIT_VIEW, 0, 0, delayMs);\n\t\treturn;\n\t}\n\tconst waitUntil = Date.now() + delayMs;\n\twhile (Date.now() < waitUntil) {\n\t\t// Startup handshakes are synchronous so resume rejects before reporting a run as started.\n\t}\n}\n\nfunction readRunnerStartup(startupPath: string, expectedState: RunnerStartupState, expectedToken?: string): RunnerStartupWaitResult | undefined {\n\tif (!fs.existsSync(startupPath)) return undefined;\n\ttry {\n\t\tconst payload = JSON.parse(fs.readFileSync(startupPath, \"utf-8\")) as { state?: unknown; token?: unknown; error?: unknown };\n\t\tif (payload.state === \"error\" && typeof payload.error === \"string\") return { ok: false, error: payload.error };\n\t\tif (payload.state !== expectedState) return undefined;\n\t\tif (typeof payload.token !== \"string\" || (expectedToken !== undefined && payload.token !== expectedToken)) {\n\t\t\treturn { ok: false, error: `Async runner wrote an invalid ${expectedState} startup handshake: ${startupPath}` };\n\t\t}\n\t\treturn { ok: true, token: payload.token };\n\t} catch (error) {\n\t\treturn { ok: false, error: `Failed to read async runner startup handshake '${startupPath}': ${error instanceof Error ? error.message : String(error)}` };\n\t}\n}\n\nfunction waitForRunnerStartup(startupPath: string, expectedState: RunnerStartupState, timeoutMs: number, expectedToken?: string): RunnerStartupWaitResult {\n\tconst deadline = Date.now() + timeoutMs;\n\tfor (;;) {\n\t\tconst result = readRunnerStartup(startupPath, expectedState, expectedToken);\n\t\tif (result) return result;\n\t\tif (Date.now() >= deadline) break;\n\t\twaitForStartupInterval(Math.min(20, Math.max(1, deadline - Date.now())));\n\t}\n\tconst finalResult = readRunnerStartup(startupPath, expectedState, expectedToken);\n\tif (finalResult) return finalResult;\n\treturn { ok: false, error: `Timed out after ${timeoutMs}ms waiting for the async runner startup state '${expectedState}'.` };\n}\n\nfunction writeRunnerStartupControl(filePath: string, payload: { action: \"ack\" | \"proceed\"; token: string }): void {\n\tconst tempPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;\n\ttry {\n\t\tfs.writeFileSync(tempPath, JSON.stringify(payload), { encoding: \"utf-8\", mode: 0o600 });\n\t\tfs.renameSync(tempPath, filePath);\n\t} catch (error) {\n\t\ttry {\n\t\t\tfs.rmSync(tempPath, { force: true });\n\t\t} catch {\n\t\t\t// Preserve the startup-control write error.\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction runnerIsAlive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t}\n}\n\nfunction terminateRunnerBeforeProceed(pid: number): void {\n\tfor (const signal of [\"SIGTERM\", \"SIGKILL\"] as const) {\n\t\tif (!runnerIsAlive(pid)) return;\n\t\ttry {\n\t\t\tprocess.kill(pid, signal);\n\t\t} catch {\n\t\t\tif (!runnerIsAlive(pid)) return;\n\t\t}\n\t\tconst deadline = Date.now() + 1000;\n\t\twhile (runnerIsAlive(pid) && Date.now() < deadline) waitForStartupInterval();\n\t}\n}\n\nfunction spawnRunner(cfg: object, suffix: string, cwd: string): { pid?: number; error?: string } {\n\tif (!jitiCliPath) {\n\t\treturn { error: \"upstream jiti for TypeScript execution could not be found; ensure package dependencies are installed\" };\n\t}\n\n\ttry {\n\t\tconst cwdStats = fs.statSync(cwd);\n\t\tif (!cwdStats.isDirectory()) {\n\t\t\treturn { error: `cwd is not a directory: ${cwd}` };\n\t\t}\n\t} catch {\n\t\treturn { error: `cwd does not exist: ${cwd}` };\n\t}\n\n\tfs.mkdirSync(TEMP_ROOT_DIR, { recursive: true });\n\tconst cfgPath = getAsyncConfigPath(suffix);\n\tfs.writeFileSync(cfgPath, JSON.stringify(cfg));\n\t// lunr: bake-in ships compiled .js only; use the .ts when present (upstream dev), else the .js sibling.\n\tconst runnerTsPath = path.join(path.dirname(fileURLToPath(import.meta.url)), \"subagent-runner.ts\");\n\tconst runner = fs.existsSync(runnerTsPath) ? runnerTsPath : runnerTsPath.replace(/\\.ts$/, \".js\");\n\tconst nodeCommand = resolveAsyncRunnerNodeCommand();\n\tconst startupPath = typeof (cfg as { revivalLease?: unknown; asyncDir?: unknown }).revivalLease === \"object\"\n\t\t&& typeof (cfg as { asyncDir?: unknown }).asyncDir === \"string\"\n\t\t? path.join((cfg as { asyncDir: string }).asyncDir, \"runner-startup.json\")\n\t\t: undefined;\n\tconst startupAckPath = startupPath ? path.join(path.dirname(startupPath), \"runner-startup-ack.json\") : undefined;\n\tconst startupProceedPath = startupPath ? path.join(path.dirname(startupPath), \"runner-startup-proceed.json\") : undefined;\n\tif (startupPath) fs.rmSync(startupPath, { force: true });\n\tif (startupAckPath) fs.rmSync(startupAckPath, { force: true });\n\tif (startupProceedPath) fs.rmSync(startupProceedPath, { force: true });\n\n\tconst logPaths = resolveAsyncRunnerLogPaths(cfg);\n\tlet stdoutFd: number | undefined;\n\tlet stderrFd: number | undefined;\n\ttry {\n\t\tif (logPaths) {\n\t\t\tfs.mkdirSync(path.dirname(logPaths.stdoutPath), { recursive: true });\n\t\t\tstdoutFd = fs.openSync(logPaths.stdoutPath, \"a\");\n\t\t\tstderrFd = fs.openSync(logPaths.stderrPath, \"a\");\n\t\t}\n\t\tconst proc = spawn(nodeCommand, [jitiCliPath, runner, cfgPath], {\n\t\t\tcwd,\n\t\t\tdetached: true,\n\t\t\tstdio: [\"ignore\", stdoutFd ?? \"ignore\", stderrFd ?? \"ignore\"],\n\t\t\twindowsHide: true,\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\t...(piPackageRoot ? { [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot } : {}),\n\t\t\t},\n\t\t});\n\t\tcloseFd(stdoutFd);\n\t\tcloseFd(stderrFd);\n\t\tproc.on(\"error\", (error) => {\n\t\t\tconsole.error(`[pi-subagents] async spawn failed: ${error.message}`);\n\t\t});\n\t\tif (typeof proc.pid !== \"number\") {\n\t\t\treturn { error: `async runner did not produce a pid for cwd: ${cwd}` };\n\t\t}\n\t\tproc.unref();\n\t\tif (startupPath && startupAckPath && startupProceedPath) {\n\t\t\tconst ready = waitForRunnerStartup(startupPath, \"ready\", RUNNER_STARTUP_TIMEOUT_MS);\n\t\t\tif (!ready.ok) {\n\t\t\t\tterminateRunnerBeforeProceed(proc.pid);\n\t\t\t\treturn { error: ready.error };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\twriteRunnerStartupControl(startupAckPath, { action: \"ack\", token: ready.token });\n\t\t\t} catch (error) {\n\t\t\t\tterminateRunnerBeforeProceed(proc.pid);\n\t\t\t\treturn { error: `Failed to acknowledge async runner startup: ${error instanceof Error ? error.message : String(error)}` };\n\t\t\t}\n\t\t\tconst acknowledged = waitForRunnerStartup(startupPath, \"acknowledged\", RUNNER_STARTUP_TIMEOUT_MS, ready.token);\n\t\t\tif (!acknowledged.ok) {\n\t\t\t\tterminateRunnerBeforeProceed(proc.pid);\n\t\t\t\treturn { error: acknowledged.error };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\twriteRunnerStartupControl(startupProceedPath, { action: \"proceed\", token: ready.token });\n\t\t\t} catch (error) {\n\t\t\t\tterminateRunnerBeforeProceed(proc.pid);\n\t\t\t\treturn { error: `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}` };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tfs.rmSync(startupPath, { force: true });\n\t\t\t} catch {\n\t\t\t\t// Proceed is the commit point; handshake cleanup cannot turn a running revival into a start error.\n\t\t\t}\n\t\t}\n\t\treturn { pid: proc.pid };\n\t} catch (error) {\n\t\tcloseFd(stdoutFd);\n\t\tcloseFd(stderrFd);\n\t\treturn { error: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\nfunction formatAsyncStartError(mode: SubagentRunMode, message: string): AsyncExecutionResult {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tisError: true,\n\t\tdetails: { mode, results: [] },\n\t};\n}\n\nconst UNAVAILABLE_SUBAGENT_SKILL_ERROR = \"Skills not found: pi-subagents\";\n\nclass UnavailableSubagentSkillError extends Error {}\nclass AsyncStartValidationError extends Error {}\n\nfunction childDescription(step: Pick<SequentialStep, \"description\" | \"label\" | \"agent\">): string {\n\treturn step.description || step.label || step.agent || \"child\";\n}\n\nexport function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildParams): AsyncRunnerStepBuildResult {\n\tconst {\n\t\tchain,\n\t\tctx,\n\t\tcwd,\n\t\tsessionFilesByFlatIndex,\n\t\tthinkingOverridesByFlatIndex,\n\t\tmaxSubagentDepth,\n\t\tworktreeBaseDir,\n\t\tasyncDir,\n\t} = params;\n\tconst outputBaseDir = params.outputBaseDir;\n\tconst resultMode = params.resultMode ?? \"chain\";\n\tconst chainSkills = params.chainSkills ?? [];\n\tconst availableModels = params.availableModels;\n\tconst runnerCwd = resolveChildCwd(ctx.cwd, cwd);\n\tconst progressDir = params.progressDir ?? runnerCwd;\n\tconst graphChain: ChainStep[] = params.attachRoot\n\t\t? [{\n\t\t\t\tagent: params.attachRoot.agent,\n\t\t\t\ttask: `Attach async root ${params.attachRoot.runId}`,\n\t\t\t\tlabel: params.attachRoot.label ?? `Attached root ${params.attachRoot.runId}`,\n\t\t\t\t...(params.attachRoot.outputName ? { as: params.attachRoot.outputName } : {}),\n\t\t\t}, ...chain]\n\t\t: chain;\n\tconst firstStep = chain[0];\n\tconst originalTask = params.task ?? (firstStep\n\t\t? (isParallelStep(firstStep)\n\t\t\t? firstStep.parallel[0]?.task\n\t\t\t: isDynamicParallelStep(firstStep)\n\t\t\t\t? firstStep.parallel.task\n\t\t\t\t: (firstStep as SequentialStep).task)\n\t\t: undefined);\n\ttry {\n\t\tif (params.validateOutputBindings !== false) {\n\t\t\tvalidateChainOutputBindings(chain, { maxItems: params.dynamicFanoutMaxItems });\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof ChainOutputValidationError) return { error: error.message };\n\t\tthrow error;\n\t}\n\tconst workflowGraph = buildWorkflowGraphSnapshot({ runId: id, mode: resultMode, steps: graphChain });\n\n\tlet progressInstructionCreated = false;\n\tconst buildStepOverrides = (s: SequentialStep): StepOverrides => {\n\t\tconst stepSkillInput = normalizeSkillInput(s.skill);\n\t\treturn {\n\t\t\t...(s.output !== undefined ? { output: s.output } : {}),\n\t\t\t...(s.outputMode !== undefined ? { outputMode: s.outputMode } : {}),\n\t\t\t...(s.reads !== undefined ? { reads: s.reads } : {}),\n\t\t\t...(s.progress !== undefined ? { progress: s.progress } : {}),\n\t\t\t...(stepSkillInput !== undefined ? { skills: stepSkillInput } : {}),\n\t\t\t...(s.model !== undefined ? { model: s.model } : {}),\n\t\t};\n\t};\n\tconst buildSeqStep = (s: SequentialStep, sessionFile?: string, behaviorCwd?: string, progressPrecreated = false, resolvedBehavior?: ResolvedStepBehavior, flatIndex?: number, parallelOutputNamespace?: { stepIndex: number; taskIndex?: number }) => {\n\t\tconst childIndex = flatIndex ?? parallelOutputNamespace?.stepIndex ?? 0;\n\t\tconst spec = normalizeChildSpec(s, {\n\t\t\tparentMode: snapshotParentPermissionMode(ctx.parentSessionId ?? ctx.currentSessionId),\n\t\t\trunId: params.childIdRunId ?? id,\n\t\t\tindex: childIndex,\n\t\t\tchildId: s.childId ?? (s.agent?.trim() ? s.agent : undefined),\n\t\t\tdefaultTask: \"{previous}\",\n\t\t\tfanoutAuthorized: false,\n\t\t});\n\t\tconst toolBudgetInput = spec.toolBudget ?? params.toolBudget ?? params.configToolBudget;\n\t\tconst resolvedToolBudget = validateToolBudgetConfig(toolBudgetInput, spec.toolBudget ? \"toolBudget\" : \"config.toolBudget\");\n\t\tif (resolvedToolBudget.error) throw new AsyncStartValidationError(resolvedToolBudget.error);\n\t\tconst stepCwd = resolveChildCwd(runnerCwd, s.cwd);\n\t\tconst instructionCwd = behaviorCwd ?? stepCwd;\n\t\tlet behavior = suppressProgressForReadOnlyTask(resolvedBehavior ?? resolveStepBehavior(buildStepOverrides(s), chainSkills), s.task, originalTask);\n\t\tconst inheritedRelativeParallelOutput = parallelOutputNamespace && s.output === undefined && typeof behavior.output === \"string\" && !path.isAbsolute(behavior.output);\n\t\tif (inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex !== undefined) {\n\t\t\tbehavior = {\n\t\t\t\t...behavior,\n\t\t\t\toutput: path.join(`parallel-${parallelOutputNamespace.stepIndex}`, String(parallelOutputNamespace.taskIndex), behavior.output),\n\t\t\t};\n\t\t}\n\t\tconst namespaceOutputPath = Boolean(inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex === undefined);\n\t\tconst skillNames = behavior.skills === false ? [] : behavior.skills;\n\t\tconst { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(\n\t\t\tskillNames,\n\t\t\tstepCwd,\n\t\t\tctx.cwd,\n\t\t\tundefined,\n\t\t\tstepCwd,\n\t\t);\n\t\tif (missingSkills.includes(\"pi-subagents\")) throw new UnavailableSubagentSkillError(UNAVAILABLE_SUBAGENT_SKILL_ERROR);\n\n\t\tlet systemPrompt = \"\";\n\t\tif (resolvedSkills.length > 0) {\n\t\t\tconst injection = buildSkillInjection(resolvedSkills);\n\t\t\tsystemPrompt = systemPrompt ? `${systemPrompt}\\n\\n${injection}` : injection;\n\t\t}\n\t\tconst readInstructions = buildChainInstructions({ ...behavior, output: false, progress: false }, instructionCwd, false);\n\t\tconst isFirstProgressAgent = behavior.progress && !progressPrecreated && !progressInstructionCreated;\n\t\tif (behavior.progress) progressInstructionCreated = true;\n\t\tconst progressInstructions = buildChainInstructions({ ...behavior, output: false, reads: false }, progressDir, isFirstProgressAgent);\n\t\tconst outputPath = resolveSingleOutputPath(behavior.output, ctx.cwd, instructionCwd, outputBaseDir);\n\t\tif (!namespaceOutputPath) systemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, {\n\t\t\ttools: spec.effectivePermissions === \"read-only\" ? [\"read\", \"grep\", \"find\", \"ls\", \"bash\"] : undefined,\n\t\t});\n\t\tconst validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Async step (${spec.description})`);\n\t\tif (validationError) throw new AsyncStartValidationError(validationError);\n\t\tlet taskTemplate = s.task ?? \"{previous}\";\n\t\ttaskTemplate = taskTemplate.replace(/\\{task\\}/g, originalTask ?? \"\");\n\t\ttaskTemplate = taskTemplate.replace(/\\{chain_dir\\}/g, runnerCwd);\n\t\tconst taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;\n\t\tconst task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, {\n\t\t\ttools: spec.effectivePermissions === \"read-only\" ? [\"read\", \"grep\", \"find\", \"ls\", \"bash\"] : undefined,\n\t\t});\n\n\t\tconst primaryModel = resolveEffectiveSubagentModel(\n\t\t\tspec.model,\n\t\t\tundefined,\n\t\t\tctx.currentModel,\n\t\t\tavailableModels,\n\t\t\tctx.currentModelProvider,\n\t\t\t{ scope: ctx.modelScope },\n\t\t);\n\t\tconst thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];\n\t\tconst effectiveThinking = thinkingOverride;\n\t\tconst model = applyThinkingSuffix(primaryModel, effectiveThinking, thinkingOverride !== undefined);\n\t\treturn {\n\t\t\tparentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,\n\t\t\tparentPermissionMode: snapshotParentPermissionMode(ctx.parentSessionId ?? ctx.currentSessionId),\n\t\t\tchildId: spec.childId,\n\t\t\tdescription: spec.description,\n\t\t\tpermissions: spec.effectivePermissions,\n\t\t\tagent: spec.description,\n\t\t\ttask,\n\t\t\tphase: s.phase,\n\t\t\tlabel: s.label,\n\t\t\toutputName: s.as,\n\t\t\tstructured: Boolean(s.outputSchema),\n\t\t\tcwd: stepCwd,\n\t\t\tmodel,\n\t\t\tthinking: resolveEffectiveThinking(model, effectiveThinking),\n\t\t\tmodelCandidates: buildModelCandidates(primaryModel, undefined, availableModels, ctx.currentModelProvider, { scope: ctx.modelScope }).map((candidate) =>\n\t\t\t\tapplyThinkingSuffix(candidate, effectiveThinking, thinkingOverride !== undefined),\n\t\t\t),\n\t\t\tsystemPrompt,\n\t\t\tsystemPromptMode: \"append\",\n\t\t\tinheritProjectContext: true,\n\t\t\tinheritSkills: false,\n\t\t\tskills: resolvedSkills.map((r) => r.name),\n\t\t\toutputPath,\n\t\t\t...(namespaceOutputPath ? { namespaceOutputPath: true } : {}),\n\t\t\toutputMode: behavior.outputMode,\n\t\t\tsessionFile,\n\t\t\tmaxSubagentDepth,\n\t\t\twaitToolEnabled: params.waitToolEnabled,\n\t\t\teffectiveAcceptance: resolveEffectiveAcceptance({\n\t\t\t\texplicit: s.acceptance,\n\t\t\t\tagentName: spec.description,\n\t\t\t\tpermissions: spec.effectivePermissions,\n\t\t\t\ttask,\n\t\t\t\tmode: resultMode,\n\t\t\t\tasync: true,\n\t\t\t\tdynamic: false,\n\t\t\t}),\n\t\t\tacceptanceInput: s.acceptance,\n\t\t\tacceptanceRole: spec.effectivePermissions === \"read-only\" ? \"read-only\" : \"writer\",\n\t\t\t...(s.outputSchema ? { structuredOutputSchema: s.outputSchema } : {}),\n\t\t\t...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, \"structured-output\")) } : {}),\n\t\t\t...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),\n\t\t};\n\t};\n\n\tlet flatStepIndex = 0;\n\tconst nextFlatStep = (): { index: number; sessionFile?: string; thinkingOverride?: string | false } => {\n\t\tconst index = flatStepIndex;\n\t\tconst sessionFile = sessionFilesByFlatIndex?.[flatStepIndex];\n\t\tconst thinkingOverride = thinkingOverridesByFlatIndex?.[flatStepIndex];\n\t\tflatStepIndex++;\n\t\treturn {\n\t\t\tindex,\n\t\t\t...(sessionFile ? { sessionFile } : {}),\n\t\t\t...(thinkingOverride ? { thinkingOverride } : {}),\n\t\t};\n\t};\n\n\ttry {\n\t\tconst builtSteps = chain.map((s, stepIndex) => {\n\t\t\tif (isParallelStep(s)) {\n\t\t\t\tconst parallelBehaviors = s.parallel.map((task) => {\n\t\t\t\t\treturn suppressProgressForReadOnlyTask(resolveStepBehavior(buildStepOverrides(task), chainSkills), task.task, originalTask);\n\t\t\t\t});\n\t\t\t\tconst progressPrecreated = parallelBehaviors.some((behavior) => behavior.progress);\n\t\t\t\tif (progressPrecreated) {\n\t\t\t\t\tif (!s.worktree || params.progressDir) writeInitialProgressFile(progressDir);\n\t\t\t\t\tprogressInstructionCreated = true;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tparallel: s.parallel.map((t, taskIndex) => {\n\t\t\t\t\t\tlet behaviorCwd: string | undefined;\n\t\t\t\t\t\tif (s.worktree) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tbehaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, taskIndex, worktreeBaseDir);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tbehaviorCwd = undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst staticStep = nextFlatStep();\n\t\t\t\t\t\treturn buildSeqStep(t, staticStep.sessionFile, behaviorCwd, progressPrecreated, parallelBehaviors[taskIndex], staticStep.index, { stepIndex, taskIndex });\n\t\t\t\t\t}),\n\t\t\t\t\tconcurrency: s.concurrency,\n\t\t\t\t\tfailFast: s.failFast,\n\t\t\t\t\tworktree: s.worktree,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (isDynamicParallelStep(s)) {\n\t\t\t\tconst behavior = suppressProgressForReadOnlyTask(resolveStepBehavior(buildStepOverrides(s.parallel), chainSkills), s.parallel.task, originalTask);\n\t\t\t\tconst progressPrecreated = behavior.progress;\n\t\t\t\tif (progressPrecreated) {\n\t\t\t\t\twriteInitialProgressFile(progressDir);\n\t\t\t\t\tprogressInstructionCreated = true;\n\t\t\t\t}\n\t\t\t\tconst maxItems = s.expand.maxItems ?? params.dynamicFanoutMaxItems ?? 0;\n\t\t\t\tconst dynamicFlatSteps = Array.from({ length: maxItems }, () => nextFlatStep());\n\t\t\t\tconst parallel = buildSeqStep(s.parallel as SequentialStep, undefined, undefined, progressPrecreated, behavior, undefined, { stepIndex });\n\t\t\t\treturn {\n\t\t\t\t\texpand: s.expand,\n\t\t\t\t\tparallel,\n\t\t\t\t\tcollect: s.collect,\n\t\t\t\t\tconcurrency: s.concurrency,\n\t\t\t\t\tfailFast: s.failFast,\n\t\t\t\t\tphase: s.phase,\n\t\t\t\t\tlabel: s.label,\n\t\t\t\t\tsessionFiles: dynamicFlatSteps.map((step) => step.sessionFile),\n\t\t\t\t\tthinkingOverrides: dynamicFlatSteps.map((step) => step.thinkingOverride),\n\t\t\t\t\teffectiveAcceptance: resolveEffectiveAcceptance({\n\t\t\t\t\t\texplicit: s.acceptance,\n\t\t\t\t\t\tagentName: s.parallel.description,\n\t\t\t\t\t\tpermissions: s.parallel.permissions === \"read-only\" ? \"read-only\" : \"full\",\n\t\t\t\t\t\ttask: parallel.task,\n\t\t\t\t\t\tmode: resultMode,\n\t\t\t\t\t\tasync: true,\n\t\t\t\t\t\tdynamicGroup: true,\n\t\t\t\t\t}),\n\t\t\t\t\tacceptanceInput: s.acceptance,\n\t\t\t\t\tacceptanceRole: s.parallel.permissions === \"read-only\" ? \"read-only\" : \"writer\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst staticStep = nextFlatStep();\n\t\t\treturn buildSeqStep(s as SequentialStep, staticStep.sessionFile, undefined, false, undefined, staticStep.index);\n\t\t});\n\t\tconst steps = params.attachRoot\n\t\t\t? [{\n\t\t\t\t\tagent: params.attachRoot.agent,\n\t\t\t\t\ttask: \"\",\n\t\t\t\t\tlabel: params.attachRoot.label ?? `Attached root ${params.attachRoot.runId}`,\n\t\t\t\t\toutputName: params.attachRoot.outputName,\n\t\t\t\t\timportAsyncRoot: {\n\t\t\t\t\t\trunId: params.attachRoot.runId,\n\t\t\t\t\t\tasyncDir: params.attachRoot.asyncDir,\n\t\t\t\t\t\tresultPath: params.attachRoot.resultPath,\n\t\t\t\t\t\tindex: params.attachRoot.index,\n\t\t\t\t\t},\n\t\t\t\t\tinheritProjectContext: false,\n\t\t\t\t\tinheritSkills: false,\n\t\t\t\t}, ...builtSteps]\n\t\t\t: builtSteps;\n\t\tfor (const step of steps) {\n\t\t\tif (!(\"parallel\" in step) || !Array.isArray(step.parallel)) continue;\n\t\t\tconst seen = new Map<string, { index: number; agent: string }>();\n\t\t\tfor (let index = 0; index < step.parallel.length; index++) {\n\t\t\t\tconst task = step.parallel[index]!;\n\t\t\t\tif (!task.outputPath) continue;\n\t\t\t\tconst previous = seen.get(task.outputPath);\n\t\t\t\tif (previous) {\n\t\t\t\t\tthrow new AsyncStartValidationError(`Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${task.agent}) resolve output to the same path: ${task.outputPath}. Use distinct output paths.`);\n\t\t\t\t}\n\t\t\t\tseen.set(task.outputPath, { index, agent: task.agent });\n\t\t\t}\n\t\t}\n\t\treturn { steps, runnerCwd, workflowGraph, eventChain: graphChain, ...(originalTask !== undefined ? { originalTask } : {}) };\n\t} catch (error) {\n\t\tif (error instanceof UnavailableSubagentSkillError || error instanceof AsyncStartValidationError) return { error: error.message };\n\t\tthrow error;\n\t}\n}\n\n/**\n * Execute a chain asynchronously\n */\nexport function executeAsyncChain(\n\tid: string,\n\tparams: AsyncChainParams,\n): AsyncExecutionResult {\n\tconst {\n\t\tchain,\n\t\tctx,\n\t\tcwd,\n\t\tmaxOutput,\n\t\tartifactsDir,\n\t\tartifactConfig,\n\t\tshareEnabled,\n\t\tsessionRoot,\n\t\tsessionFilesByFlatIndex,\n\t\tthinkingOverridesByFlatIndex,\n\t\tmaxSubagentDepth,\n\t\tworktreeSetupHook,\n\t\tworktreeSetupHookTimeoutMs,\n\t\tworktreeBaseDir,\n\t\tcontrolConfig,\n\t\tcontrolIntercomTarget,\n\t\tchildIntercomTarget,\n\t\tnestedRoute,\n\t} = params;\n\tconst resultMode = params.resultMode ?? \"chain\";\n\tconst inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();\n\tconst nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;\n\tconst asyncDir = inheritedNestedRoute\n\t\t? path.join(TEMP_ROOT_DIR, \"nested-subagent-runs\", inheritedNestedRoute.rootRunId, id)\n\t\t: path.join(ASYNC_DIR, id);\n\ttry {\n\t\tfs.mkdirSync(asyncDir, { recursive: true });\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Failed to create async run directory '${asyncDir}': ${message}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: resultMode, results: [] },\n\t\t};\n\t}\n\n\tconst built = buildAsyncRunnerSteps(id, {\n\t\tchain,\n\t\ttask: params.task,\n\t\tattachRoot: params.attachRoot,\n\t\tresultMode,\n\t\tctx,\n\t\tavailableModels: params.availableModels,\n\t\tcwd,\n\t\tchainSkills: params.chainSkills,\n\t\tsessionFilesByFlatIndex,\n\t\tthinkingOverridesByFlatIndex,\n\t\tprogressDir: params.progressDir ?? (artifactsDir ? path.join(artifactsDir, \"progress\", id) : resultMode === \"parallel\" ? path.join(asyncDir, \"progress\") : undefined),\n\t\toutputBaseDir: artifactsDir ? path.join(artifactsDir, \"outputs\", id) : undefined,\n\t\tdynamicFanoutMaxItems: params.dynamicFanoutMaxItems,\n\t\tmaxSubagentDepth,\n\t\twaitToolEnabled: params.waitToolEnabled,\n\t\tworktreeBaseDir,\n\t\tasyncDir,\n\t\ttoolBudget: params.toolBudget,\n\t\tconfigToolBudget: params.configToolBudget,\n\t});\n\tif (\"error\" in built) {\n\t\ttry {\n\t\t\tfs.rmSync(asyncDir, { recursive: true, force: true });\n\t\t} catch {\n\t\t\t// Best-effort cleanup for validation failures before the runner is spawned.\n\t\t}\n\t\treturn formatAsyncStartError(resultMode, built.error);\n\t}\n\tconst { steps, runnerCwd, workflowGraph, eventChain } = built;\n\tconst deadlineAt = params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined;\n\tconst initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;\n\tlet childTargetIndex = 0;\n\tconst childIntercomTargets = childIntercomTarget ? steps.flatMap((step) => {\n\t\tif (!(\"parallel\" in step) && step.importAsyncRoot) {\n\t\t\tchildTargetIndex++;\n\t\t\treturn [undefined];\n\t\t}\n\t\tif (\"parallel\" in step) {\n\t\t\tif (!Array.isArray(step.parallel)) {\n\t\t\t\tchildTargetIndex++;\n\t\t\t\treturn [undefined];\n\t\t\t}\n\t\t\treturn step.parallel.map((task) => childIntercomTarget(task.childId ?? task.agent, childTargetIndex++));\n\t\t}\n\t\treturn [childIntercomTarget(step.childId ?? step.agent, childTargetIndex++)];\n\t}) : undefined;\n\n\tlet spawnResult: { pid?: number; error?: string } = {};\n\ttry {\n\t\tspawnResult = spawnRunner(\n\t\t\t{\n\t\t\t\tid,\n\t\t\t\tsteps,\n\t\t\t\tresultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path.join(RESULTS_DIR, `${id}.json`),\n\t\t\t\tcwd: runnerCwd,\n\t\t\t\tplaceholder: \"{previous}\",\n\t\t\t\tmaxOutput,\n\t\t\t\tartifactsDir: artifactConfig.enabled ? artifactsDir : undefined,\n\t\t\t\tartifactConfig,\n\t\t\t\tshare: shareEnabled,\n\t\t\t\tsessionDir: sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined,\n\t\t\t\tasyncDir,\n\t\t\t\tsessionId: ctx.currentSessionId,\n\t\t\t\tpiPackageRoot,\n\t\t\t\tpiArgv1: process.argv[1],\n\t\t\t\tworktreeSetupHook,\n\t\t\t\tworktreeSetupHookTimeoutMs,\n\t\t\t\tworktreeBaseDir,\n\t\t\t\tcontrolConfig,\n\t\t\t\tturnBudget: params.turnBudget,\n\t\t\t\ttoolBudget: params.toolBudget,\n\t\t\t\tcontrolIntercomTarget,\n\t\t\t\tchildIntercomTargets,\n\t\t\t\tresultMode,\n\t\t\t\tdynamicFanoutMaxItems: params.dynamicFanoutMaxItems,\n\t\t\t\ttimeoutMs: params.timeoutMs,\n\t\t\t\tdeadlineAt,\n\t\t\t\tglobalConcurrencyLimit: params.globalConcurrencyLimit,\n\t\t\t\tworkflowGraph,\n\t\t\t\tnestedRoute: nestedRoute ?? inheritedNestedRoute,\n\t\t\t\tnestedSelf: inheritedNestedRoute && nestedAddress ? {\n\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\tdepth: nestedAddress.depth,\n\t\t\t\t\tpath: nestedAddress.path,\n\t\t\t\t} : undefined,\n\t\t\t},\n\t\t\tid,\n\t\t\trunnerCwd,\n\t\t);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${message}`);\n\t}\n\n\tif (spawnResult.error) {\n\t\treturn formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${spawnResult.error}`);\n\t}\n\n\tif (spawnResult.pid) {\n\t\tconst eventFirstStep = eventChain[0];\n\t\tconst firstAgents = isParallelStep(eventFirstStep)\n\t\t\t? eventFirstStep.parallel.map(childDescription)\n\t\t\t: isDynamicParallelStep(eventFirstStep)\n\t\t\t\t? [childDescription(eventFirstStep.parallel)]\n\t\t\t: [childDescription(eventFirstStep as SequentialStep)];\n\t\tconst firstTask = isParallelStep(eventFirstStep)\n\t\t\t? eventFirstStep.parallel[0]?.task\n\t\t\t: isDynamicParallelStep(eventFirstStep)\n\t\t\t\t? eventFirstStep.parallel.task\n\t\t\t\t: (eventFirstStep as SequentialStep).task;\n\t\tconst workflowGoal = params.goal ?? (params.task?.trim() || firstTask);\n\t\tconst parallelGroups: Array<{ start: number; count: number; stepIndex: number }> = [];\n\t\tconst flatAgents: string[] = [];\n\t\tlet flatStepStart = 0;\n\t\tfor (let stepIndex = 0; stepIndex < eventChain.length; stepIndex++) {\n\t\t\tconst step = eventChain[stepIndex]!;\n\t\t\tif (isParallelStep(step)) {\n\t\t\t\tparallelGroups.push({ start: flatStepStart, count: step.parallel.length, stepIndex });\n\t\t\t\tflatAgents.push(...step.parallel.map(childDescription));\n\t\t\t\tflatStepStart += step.parallel.length;\n\t\t\t} else if (isDynamicParallelStep(step)) {\n\t\t\t\tparallelGroups.push({ start: flatStepStart, count: 1, stepIndex });\n\t\t\t\tflatAgents.push(childDescription(step.parallel));\n\t\t\t\tflatStepStart++;\n\t\t\t} else {\n\t\t\t\tflatAgents.push(childDescription(step as SequentialStep));\n\t\t\t\tflatStepStart++;\n\t\t\t}\n\t\t}\n\t\tif (inheritedNestedRoute && nestedAddress) {\n\t\t\tconst now = Date.now();\n\t\t\ttry {\n\t\t\t\twriteNestedEvent(inheritedNestedRoute, {\n\t\t\t\t\ttype: \"subagent.nested.started\",\n\t\t\t\t\tts: now,\n\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\tchild: {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\t\tdepth: nestedAddress.depth,\n\t\t\t\t\t\tpath: nestedAddress.path,\n\t\t\t\t\t\tasyncDir,\n\t\t\t\t\t\tpid: spawnResult.pid,\n\t\t\t\t\t\townerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,\n\t\t\t\t\t\tleafIntercomTarget: childIntercomTargets?.[0],\n\t\t\t\t\t\tintercomTarget: childIntercomTargets?.[0],\n\t\t\t\t\t\townerState: \"live\",\n\t\t\t\t\t\tmode: resultMode,\n\t\t\t\t\t\tstate: \"running\",\n\t\t\t\t\t\tagent: firstAgents[0],\n\t\t\t\t\t\tagents: flatAgents,\n\t\t\t\t\t\tchainStepCount: eventChain.length,\n\t\t\t\t\t\tparallelGroups,\n\t\t\t\t\t\t...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),\n\t\t\t\t\t\t...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),\n\t\t\t\t\t\tstartedAt: now,\n\t\t\t\t\t\tlastUpdate: now,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Failed to emit nested async start event:\", error);\n\t\t\t}\n\t\t}\n\t\tctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {\n\t\t\tlifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\t\t\tid,\n\t\t\tpid: spawnResult.pid,\n\t\t\tsessionId: ctx.currentSessionId,\n\t\t\tmode: resultMode,\n\t\t\tagent: firstAgents[0],\n\t\t\tagents: flatAgents,\n\t\t\ttask: firstTask?.slice(0, 50),\n\t\t\tgoal: workflowGoal?.slice(0, 120),\n\t\t\tchain: eventChain.map((s) =>\n\t\t\t\tisParallelStep(s) ? `[${s.parallel.map(childDescription).join(\"+\")}]` : isDynamicParallelStep(s) ? `expand:${childDescription(s.parallel)}` : childDescription(s as SequentialStep),\n\t\t\t),\n\t\t\tchainStepCount: eventChain.length,\n\t\t\tparallelGroups,\n\t\t\tworkflowGraph,\n\t\t\tcwd: runnerCwd,\n\t\t\tasyncDir,\n\t\t\t...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),\n\t\t\t...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),\n\t\t\tnestedRoute,\n\t\t});\n\t}\n\n\tconst chainDesc = chain\n\t\t.map((s) =>\n\t\t\tisParallelStep(s) ? `[${s.parallel.map(childDescription).join(\"+\")}]` : isDynamicParallelStep(s) ? `expand:${childDescription(s.parallel)}` : childDescription(s as SequentialStep),\n\t\t)\n\t\t.join(\" -> \");\n\n\treturn {\n\t\tcontent: [{ type: \"text\", text: formatAsyncStartedMessage(`Async ${resultMode}: ${chainDesc} [${id}]`) }],\n\t\tdetails: { mode: resultMode, runId: id, results: [], asyncId: id, asyncDir, workflowGraph, ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}), ...(params.turnBudget ? { turnBudget: params.turnBudget } : {}), ...(params.toolBudget ? { toolBudget: params.toolBudget } : {}) },\n\t};\n}\n\n/**\n * Execute a single agent asynchronously\n */\nexport function executeAsyncSingle(\n\tid: string,\n\tparams: AsyncSingleParams,\n): AsyncExecutionResult {\n\tconst {\n\t\tspec,\n\t\tctx,\n\t\tcwd,\n\t\tmaxOutput,\n\t\tartifactsDir,\n\t\tartifactConfig,\n\t\tshareEnabled,\n\t\tsessionRoot,\n\t\tsessionFile,\n\t\tmaxSubagentDepth,\n\t\tworktreeSetupHook,\n\t\tworktreeSetupHookTimeoutMs,\n\t\tworktreeBaseDir,\n\t\tcontrolConfig,\n\t\tcontrolIntercomTarget,\n\t\tchildIntercomTarget,\n\t\tnestedRoute,\n\t} = params;\n\tconst agent = spec.description;\n\tconst task = spec.task;\n\tconst runnerCwd = resolveChildCwd(ctx.cwd, cwd);\n\tconst skillNames = params.skills ?? (spec.skill === false ? [] : normalizeSkillInput(spec.skill) ?? []);\n\tconst availableModels = params.availableModels;\n\tconst { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(\n\t\tskillNames,\n\t\trunnerCwd,\n\t\tctx.cwd,\n\t\tundefined,\n\t\trunnerCwd,\n\t);\n\tif (missingSkills.includes(\"pi-subagents\")) return formatAsyncStartError(\"single\", UNAVAILABLE_SUBAGENT_SKILL_ERROR);\n\tlet systemPrompt = \"\";\n\tif (resolvedSkills.length > 0) {\n\t\tconst injection = buildSkillInjection(resolvedSkills);\n\t\tsystemPrompt = systemPrompt ? `${systemPrompt}\\n\\n${injection}` : injection;\n\t}\n\tconst inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();\n\tconst nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;\n\tconst asyncDir = inheritedNestedRoute\n\t\t? path.join(TEMP_ROOT_DIR, \"nested-subagent-runs\", inheritedNestedRoute.rootRunId, id)\n\t\t: path.join(ASYNC_DIR, id);\n\ttry {\n\t\tfs.mkdirSync(asyncDir, { recursive: true });\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Failed to create async run directory '${asyncDir}': ${message}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"single\" as const, results: [] },\n\t\t};\n\t}\n\n\tconst effectiveOutput = normalizeSingleOutputOverride(params.output ?? spec.output, typeof spec.output === \"string\" ? spec.output : undefined);\n\tconst outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, runnerCwd, params.outputBaseDir ?? (artifactsDir ? path.join(artifactsDir, \"outputs\", id) : undefined));\n\tconst childToolShape = { tools: spec.effectivePermissions === \"read-only\" ? [\"read\", \"grep\", \"find\", \"ls\", \"bash\"] : undefined };\n\tsystemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, childToolShape);\n\tconst outputMode = params.outputMode ?? spec.outputMode ?? \"inline\";\n\tconst validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);\n\tif (validationError) return formatAsyncStartError(\"single\", validationError);\n\tconst taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, childToolShape);\n\tconst primaryModel = resolveSubagentModelOverride(\n\t\tparams.modelOverride ?? spec.model,\n\t\tctx.currentModel,\n\t\tavailableModels,\n\t\tctx.currentModelProvider,\n\t);\n\tconst effectiveThinking = params.thinkingOverride;\n\tconst model = applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);\n\tconst toolBudgetInput = params.toolBudget ?? spec.toolBudget ?? params.configToolBudget;\n\tconst resolvedToolBudget = validateToolBudgetConfig(toolBudgetInput, params.toolBudget || spec.toolBudget ? \"toolBudget\" : \"config.toolBudget\");\n\tif (resolvedToolBudget.error) return formatAsyncStartError(\"single\", resolvedToolBudget.error);\n\tconst deadlineAt = params.absoluteDeadlineAt ?? (params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined);\n\tconst timeoutMs = params.absoluteDeadlineAt !== undefined && deadlineAt !== undefined\n\t\t? deadlineAt - Date.now()\n\t\t: params.timeoutMs;\n\tif (timeoutMs !== undefined && timeoutMs <= 0) return formatAsyncStartError(\"single\", \"The source run's absolute deadline expired before recovery could launch.\");\n\tconst initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;\n\tconst resolvedSessionDir = params.sessionDir ?? (sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined);\n\tconst resolvedAcceptance = resolveEffectiveAcceptance({\n\t\texplicit: params.acceptance ?? spec.acceptance,\n\t\tagentName: agent,\n\t\tpermissions: spec.effectivePermissions,\n\t\ttask,\n\t\tmode: \"single\",\n\t\tasync: true,\n\t});\n\tconst recoveryDescriptor: SteeringRecoveryDescriptor = {\n\t\tversion: 3,\n\t\tlifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\t\tsourceRunId: id,\n\t\tchildId: spec.childId,\n\t\tdescription: spec.description,\n\t\tpermissions: spec.effectivePermissions,\n\t\tagent,\n\t\t...(sessionFile ? { sessionFile } : {}),\n\t\tcwd: runnerCwd,\n\t\t...(model ? { model } : {}),\n\t\t...(effectiveThinking ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),\n\t\t...(resolvedSkills.length ? { skills: resolvedSkills.map((skill) => skill.name) } : {}),\n\t\t...(outputPath ? { outputPath } : {}),\n\t\toutputMode,\n\t\t...(resolvedAcceptance ? { acceptance: resolvedAcceptance } : {}),\n\t\t...(controlConfig ? { controlConfig } : {}),\n\t\t...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),\n\t\t...(params.turnBudget ? { initialTurnBudget: params.turnBudget } : {}),\n\t\t...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),\n\t\tmaxSubagentDepth,\n\t\t...(maxOutput ? { maxOutput } : {}),\n\t\tshare: shareEnabled,\n\t\t...(resolvedSessionDir ? { sessionDir: resolvedSessionDir } : {}),\n\t\t...(artifactsDir ? { artifactsDir } : {}),\n\t\tartifactConfig,\n\t};\n\ttry {\n\t\twritePrivateAtomicJson(path.join(asyncDir, \"recovery-descriptor.json\"), recoveryDescriptor);\n\t} catch (error) {\n\t\treturn formatAsyncStartError(\"single\", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\tlet spawnResult: { pid?: number; error?: string } = {};\n\ttry {\n\t\tspawnResult = spawnRunner(\n\t\t\t{\n\t\t\t\tid,\n\t\t\t\tsteps: [\n\t\t\t\t\t{\n\t\t\t\t\t\tparentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,\n\t\t\t\t\t\tparentPermissionMode: snapshotParentPermissionMode(ctx.parentSessionId ?? ctx.currentSessionId),\n\t\t\t\t\t\tchildId: spec.childId,\n\t\t\t\t\t\tdescription: spec.description,\n\t\t\t\t\t\tpermissions: spec.effectivePermissions,\n\t\t\t\t\t\tagent,\n\t\t\t\t\t\ttask: taskWithOutputInstruction,\n\t\t\t\t\t\tcwd: runnerCwd,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinking: resolveEffectiveThinking(model, effectiveThinking),\n\t\t\t\t\t\tmodelCandidates: buildModelCandidates(primaryModel, undefined, availableModels, ctx.currentModelProvider, { scope: ctx.modelScope }).map((candidate) =>\n\t\t\t\t\t\t\tapplyThinkingSuffix(candidate, effectiveThinking, params.thinkingOverride !== undefined),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\tsystemPromptMode: \"append\",\n\t\t\t\t\t\tinheritProjectContext: true,\n\t\t\t\t\t\tinheritSkills: false,\n\t\t\t\t\t\tskills: resolvedSkills.map((r) => r.name),\n\t\t\t\t\t\toutputPath,\n\t\t\t\t\t\toutputMode,\n\t\t\t\t\t\tsessionFile,\n\t\t\t\t\t\tmaxSubagentDepth,\n\t\t\t\t\t\twaitToolEnabled: params.waitToolEnabled,\n\t\t\t\t\t\teffectiveAcceptance: resolvedAcceptance,\n\t\t\t\t\t\t...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tresultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path.join(RESULTS_DIR, `${id}.json`),\n\t\t\t\tcwd: runnerCwd,\n\t\t\t\tplaceholder: \"{previous}\",\n\t\t\t\tmaxOutput,\n\t\t\t\tartifactsDir: artifactConfig.enabled ? artifactsDir : undefined,\n\t\t\t\tartifactConfig,\n\t\t\t\tshare: shareEnabled,\n\t\t\t\tsessionDir: resolvedSessionDir,\n\t\t\t\tasyncDir,\n\t\t\t\tsessionId: ctx.currentSessionId,\n\t\t\t\tpiPackageRoot,\n\t\t\t\tpiArgv1: process.argv[1],\n\t\t\t\tworktreeSetupHook,\n\t\t\t\tworktreeSetupHookTimeoutMs,\n\t\t\t\tworktreeBaseDir,\n\t\t\t\tcontrolConfig,\n\t\t\t\ttimeoutMs,\n\t\t\t\tdeadlineAt,\n\t\t\t\tturnBudget: params.turnBudget,\n\t\t\t\ttoolBudget: params.toolBudget,\n\t\t\t\tcontrolIntercomTarget,\n\t\t\t\tchildIntercomTargets: childIntercomTarget ? [childIntercomTarget(spec.childId, 0)] : undefined,\n\t\t\t\tresultMode: \"single\",\n\t\t\t\t...(params.revivalLease ? { revivalLease: params.revivalLease } : {}),\n\t\t\t\tnestedRoute: nestedRoute ?? inheritedNestedRoute,\n\t\t\t\tnestedSelf: inheritedNestedRoute && nestedAddress ? {\n\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\tdepth: nestedAddress.depth,\n\t\t\t\t\tpath: nestedAddress.path,\n\t\t\t\t} : undefined,\n\t\t\t},\n\t\t\tid,\n\t\t\trunnerCwd,\n\t\t);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn formatAsyncStartError(\"single\", `Failed to start async run '${id}': ${message}`);\n\t}\n\n\tif (spawnResult.error) {\n\t\treturn formatAsyncStartError(\"single\", `Failed to start async run '${id}': ${spawnResult.error}`);\n\t}\n\n\tif (spawnResult.pid) {\n\t\tif (inheritedNestedRoute && nestedAddress) {\n\t\t\tconst now = Date.now();\n\t\t\ttry {\n\t\t\t\twriteNestedEvent(inheritedNestedRoute, {\n\t\t\t\t\ttype: \"subagent.nested.started\",\n\t\t\t\t\tts: now,\n\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\tchild: {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\t\tdepth: nestedAddress.depth,\n\t\t\t\t\t\tpath: nestedAddress.path,\n\t\t\t\t\t\tasyncDir,\n\t\t\t\t\t\tpid: spawnResult.pid,\n\t\t\t\t\t\townerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,\n\t\t\t\t\t\tleafIntercomTarget: childIntercomTarget?.(agent, 0),\n\t\t\t\t\t\tintercomTarget: childIntercomTarget?.(agent, 0),\n\t\t\t\t\t\townerState: \"live\",\n\t\t\t\t\t\tmode: \"single\",\n\t\t\t\t\t\tstate: \"running\",\n\t\t\t\t\t\tagent,\n\t\t\t\t\t\tagents: [agent],\n\t\t\t\t\t\tchainStepCount: 1,\n\t\t\t\t\t\t...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),\n\t\t\t\t\t\t...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),\n\t\t\t\t\t\tstartedAt: now,\n\t\t\t\t\t\tlastUpdate: now,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Failed to emit nested async start event:\", error);\n\t\t\t}\n\t\t}\n\t\tctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {\n\t\t\tlifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\t\t\tid,\n\t\t\tpid: spawnResult.pid,\n\t\t\tsessionId: ctx.currentSessionId,\n\t\t\tmode: \"single\",\n\t\t\tagent,\n\t\t\ttask: task?.slice(0, 50),\n\t\t\tgoal: (params.goal ?? task).slice(0, 120),\n\t\t\tcwd: runnerCwd,\n\t\t\tasyncDir,\n\t\t\t...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),\n\t\t\t...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),\n\t\t\tnestedRoute,\n\t\t});\n\t}\n\n\treturn {\n\t\tcontent: [{ type: \"text\", text: formatAsyncStartedMessage(`Async: ${agent} [${id}]`) }],\n\t\tdetails: { mode: \"single\", runId: id, results: [], asyncId: id, asyncDir, ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}), ...(params.turnBudget ? { turnBudget: params.turnBudget } : {}), ...(params.toolBudget ? { toolBudget: params.toolBudget } : {}) },\n\t};\n}\n"]}
1
+ {"version":3,"file":"async-execution.d.ts","sourceRoot":"","sources":["../../../../../../src/builtin-extensions/pi-subagents/src/runs/background/async-execution.ts"],"names":[],"mappings":"AACA;;GAEG;AAQH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAMpE,OAAO,EAAiJ,KAAK,SAAS,EAAsE,MAAM,0BAA0B,CAAC;AAC7Q,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAI9D,OAAO,EAAsI,KAAK,kBAAkB,EAAE,KAAK,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC5N,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAGjE,OAAO,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAC;AAIzE,OAAO,EACN,KAAK,eAAe,EACpB,KAA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AO,0BAA0B,CAAC,CAAC;IAC7D,UAAU,EAAE,SAAS,EAAE,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB,GACC;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAErB,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAQlE;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,OAAO,CAE1C;AAuBD,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,MAAM,GAAG;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAS9G;AAqND,wBAAgB,qBAAqB,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,0BAA0B,GAAG,0BAA0B,CAoRhH;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAChC,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,gBAAgB,GACtB,oBAAoB,CA+OtB;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CACjC,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,iBAAiB,GACvB,oBAAoB,CA6PtB","sourcesContent":["// @ts-nocheck\n/**\n * Async execution logic for subagent tool\n */\n\nimport { spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createRequire } from \"node:module\";\nimport type { ExtensionAPI } from \"@ashx-j/lunr\";\nimport { normalizeChildSpec } from \"../../shared/child-spec.ts\";\nimport { writePrivateAtomicJson } from \"../../shared/atomic-json.ts\";\nimport { applyThinkingSuffix } from \"../shared/pi-args.ts\";\nimport { snapshotParentPermissionMode } from \"../../../../../core/subagent-permission-inherit.ts\";\nimport { injectOutputPathSystemPrompt, injectSingleOutputInstruction, normalizeSingleOutputOverride, resolveSingleOutputPath, validateFileOnlyOutputMode } from \"../shared/single-output.ts\";\nimport { buildChainInstructions, isDynamicParallelStep, isParallelStep, resolveStepBehavior, suppressProgressForReadOnlyTask, writeInitialProgressFile, type ChainStep, type ResolvedStepBehavior, type SequentialStep, type StepOverrides } from \"../../shared/settings.ts\";\nimport type { RunnerStep } from \"../shared/parallel-utils.ts\";\nimport { resolvePiPackageRoot } from \"../shared/pi-spawn.ts\";\nimport { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from \"../../agents/skills.ts\";\nimport { PI_CODING_AGENT_PACKAGE_ROOT_ENV, resolveChildCwd } from \"../../shared/utils.ts\";\nimport { buildModelCandidates, resolveEffectiveSubagentModel, resolveModelCandidate, resolveRequiredTierModel, resolveSubagentModelOverride, type AvailableModelInfo, type ParentModel } from \"../shared/model-fallback.ts\";\nimport type { ModelScopeConfig } from \"../shared/model-scope.ts\";\nimport { resolveEffectiveThinking } from \"../../shared/model-info.ts\";\nimport { resolveExpectedWorktreeAgentCwd } from \"../shared/worktree.ts\";\nimport { buildWorkflowGraphSnapshot } from \"../shared/workflow-graph.ts\";\nimport { ChainOutputValidationError, validateChainOutputBindings } from \"../shared/chain-outputs.ts\";\nimport { createStructuredOutputRuntime } from \"../shared/structured-output.ts\";\nimport { resolveEffectiveAcceptance } from \"../shared/acceptance.ts\";\nimport {\n\ttype AcceptanceInput,\n\ttype ArtifactConfig,\n\ttype ChildSpec,\n\ttype Details,\n\ttype MaxOutputConfig,\n\ttype NestedRouteInfo,\n\ttype ResolvedControlConfig,\n\ttype ResolvedTurnBudget,\n\ttype ResolvedToolBudget,\n\ttype SubagentRunMode,\n\ttype SteeringRecoveryDescriptor,\n\tASYNC_DIR,\n\tRESULTS_DIR,\n\tSUBAGENT_ASYNC_STARTED_EVENT,\n\tSUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\tTEMP_ROOT_DIR,\n\tgetAsyncConfigPath,\n\tresolveChildMaxSubagentDepth,\n} from \"../../shared/types.ts\";\nimport { nestedResultsPath, resolveInheritedNestedRouteFromEnv, resolveNestedParentAddressFromEnv, writeNestedEvent } from \"../shared/nested-events.ts\";\nimport { initialTurnBudgetState } from \"../shared/turn-budget.ts\";\nimport { validateToolBudgetConfig } from \"../shared/tool-budget.ts\";\nimport type { ImportedAsyncRoot } from \"./chain-root-attachment.ts\";\nimport type { SessionLeaseRequest } from \"../shared/session-lease.ts\";\n\nconst require = createRequire(import.meta.url);\nconst piPackageRoot = resolvePiPackageRoot();\n\nfunction resolveJitiCliFromPackageJson(packageJsonPath: string): string | undefined {\n\tif (!fs.existsSync(packageJsonPath)) return undefined;\n\tconst packageRoot = path.dirname(packageJsonPath);\n\tconst pkg = JSON.parse(fs.readFileSync(packageJsonPath, \"utf-8\")) as {\n\t\tbin?: string | Record<string, string>;\n\t};\n\tconst binField = pkg.bin;\n\tconst binPath = typeof binField === \"string\"\n\t\t? binField\n\t\t: binField?.jiti ?? Object.values(binField ?? {})[0];\n\tconst candidates = [binPath, \"lib/jiti-cli.mjs\"].filter((candidate): candidate is string => Boolean(candidate));\n\tfor (const candidate of candidates) {\n\t\tconst cliPath = path.resolve(packageRoot, candidate);\n\t\tif (fs.existsSync(cliPath)) return cliPath;\n\t}\n\treturn undefined;\n}\n\nfunction resolveJitiCliPath(): string | undefined {\n\tconst candidates: Array<() => string | undefined> = [\n\t\t() => require.resolve(\"jiti/package.json\"),\n\t\t() => piPackageRoot\n\t\t\t? createRequire(path.join(piPackageRoot, \"package.json\")).resolve(\"jiti/package.json\")\n\t\t\t: undefined,\n\t\t() => {\n\t\t\tif (!process.argv[1]) return undefined;\n\t\t\tconst piEntry = fs.realpathSync(process.argv[1]);\n\t\t\treturn createRequire(piEntry).resolve(\"jiti/package.json\");\n\t\t},\n\t\t() => piPackageRoot ? path.join(piPackageRoot, \"node_modules\", \"jiti\", \"package.json\") : undefined,\n\t];\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst packageJsonPath = candidate();\n\t\t\tif (!packageJsonPath) continue;\n\t\t\tconst cliPath = resolveJitiCliFromPackageJson(packageJsonPath);\n\t\t\tif (cliPath) return cliPath;\n\t\t} catch {\n\t\t\t// Candidate not available in this install, continue probing.\n\t\t}\n\t}\n\treturn undefined;\n}\n\nconst jitiCliPath = resolveJitiCliPath();\n\ninterface AsyncExecutionContext {\n\tpi: ExtensionAPI;\n\tcwd: string;\n\tcurrentSessionId: string;\n\t/** Parent session id used by permission-system ask forwarding. */\n\tparentSessionId?: string;\n\tcurrentModelProvider?: string;\n\tcurrentModel?: ParentModel;\n\t/** Optional model-scope enforcement resolved from subagent settings. */\n\tmodelScope?: ModelScopeConfig;\n}\n\ninterface AsyncChainParams {\n\tchain: ChainStep[];\n\ttask?: string;\n\t/** Raw caller-facing goal used only by the started event. */\n\tgoal?: string;\n\tattachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };\n\tresultMode?: Exclude<SubagentRunMode, \"single\">;\n\tctx: AsyncExecutionContext;\n\tavailableModels?: AvailableModelInfo[];\n\tcwd?: string;\n\tmaxOutput?: MaxOutputConfig;\n\tartifactsDir?: string;\n\tartifactConfig: ArtifactConfig;\n\tshareEnabled: boolean;\n\tsessionRoot?: string;\n\tchainSkills?: string[];\n\tsessionFilesByFlatIndex?: (string | undefined)[];\n\tthinkingOverridesByFlatIndex?: (string | false | undefined)[];\n\tprogressDir?: string;\n\tdynamicFanoutMaxItems?: number;\n\tmaxSubagentDepth: number;\n\twaitToolEnabled?: boolean;\n\tworktreeSetupHook?: string;\n\tworktreeSetupHookTimeoutMs?: number;\n\tworktreeBaseDir?: string;\n\tcontrolConfig?: ResolvedControlConfig;\n\tcontrolIntercomTarget?: string;\n\tchildIntercomTarget?: (agent: string, index: number) => string | undefined;\n\tnestedRoute?: NestedRouteInfo;\n\tacceptance?: AcceptanceInput;\n\ttimeoutMs?: number;\n\tturnBudget?: ResolvedTurnBudget;\n\ttoolBudget?: ResolvedToolBudget;\n\tconfigToolBudget?: ResolvedToolBudget;\n\t/** Global cap on simultaneously-running subagent tasks within the async run. */\n\tglobalConcurrencyLimit?: number;\n}\n\ninterface AsyncSingleParams {\n\tspec: ChildSpec;\n\t/** Raw caller-facing goal used only by the started event. */\n\tgoal?: string;\n\tctx: AsyncExecutionContext;\n\tcwd?: string;\n\tmaxOutput?: MaxOutputConfig;\n\tartifactsDir?: string;\n\tartifactConfig: ArtifactConfig;\n\tshareEnabled: boolean;\n\tsessionRoot?: string;\n\tsessionDir?: string;\n\tsessionFile?: string;\n\trevivalLease?: SessionLeaseRequest;\n\tskills?: string[];\n\toutput?: string | boolean;\n\toutputMode?: \"inline\" | \"file-only\";\n\toutputBaseDir?: string;\n\tmodelOverride?: string;\n\tthinkingOverride?: string | false;\n\tavailableModels?: AvailableModelInfo[];\n\tmaxSubagentDepth: number;\n\twaitToolEnabled?: boolean;\n\tworktreeSetupHook?: string;\n\tworktreeSetupHookTimeoutMs?: number;\n\tworktreeBaseDir?: string;\n\tcontrolConfig?: ResolvedControlConfig;\n\tcontrolIntercomTarget?: string;\n\tchildIntercomTarget?: (agent: string, index: number) => string | undefined;\n\tnestedRoute?: NestedRouteInfo;\n\tacceptance?: AcceptanceInput;\n\ttimeoutMs?: number;\n\tabsoluteDeadlineAt?: number;\n\tturnBudget?: ResolvedTurnBudget;\n\ttoolBudget?: ResolvedToolBudget;\n\tconfigToolBudget?: ResolvedToolBudget;\n}\n\ninterface AsyncExecutionResult {\n\tcontent: Array<{ type: \"text\"; text: string }>;\n\tdetails: Details;\n\tisError?: boolean;\n}\n\nexport interface AsyncRunnerStepBuildParams {\n\tchain: ChainStep[];\n\ttask?: string;\n\tattachRoot?: ImportedAsyncRoot & { agent: string; outputName?: string; label?: string };\n\tresultMode?: SubagentRunMode;\n\tctx: AsyncExecutionContext;\n\tavailableModels?: AvailableModelInfo[];\n\tcwd?: string;\n\tchainSkills?: string[];\n\tsessionFilesByFlatIndex?: (string | undefined)[];\n\tthinkingOverridesByFlatIndex?: (string | false | undefined)[];\n\tprogressDir?: string;\n\tdynamicFanoutMaxItems?: number;\n\tmaxSubagentDepth: number;\n\twaitToolEnabled?: boolean;\n\tworktreeBaseDir?: string;\n\tasyncDir: string;\n\toutputBaseDir?: string;\n\tvalidateOutputBindings?: boolean;\n\ttoolBudget?: ResolvedToolBudget;\n\tconfigToolBudget?: ResolvedToolBudget;\n\t/** Optional collision-free ChildSpec id namespace for steps appended to a live run. */\n\tchildIdRunId?: string;\n}\n\nexport type AsyncRunnerStepBuildResult =\n\t| {\n\t\tsteps: RunnerStep[];\n\t\trunnerCwd: string;\n\t\tworkflowGraph: ReturnType<typeof buildWorkflowGraphSnapshot>;\n\t\teventChain: ChainStep[];\n\t\toriginalTask?: string;\n\t}\n\t| { error: string };\n\nexport function formatAsyncStartedMessage(headline: string): string {\n\treturn [\n\t\theadline,\n\t\t\"\",\n\t\t\"The async run is detached. Do not run sleep timers or polling loops just to wait for it.\",\n\t\t\"If you have independent work, continue that work. When you have nothing left to do until the async result arrives, call subagent_wait() — it blocks until the run finishes and delivers the completion here. Only if you are certain you will get another turn (an interactive session where the user will prompt you again) can you instead stop and let Pi wake you; inside a skill that must run to completion, or in a non-interactive run, there is no next turn, so use subagent_wait().\",\n\t\t\"Use subagent({ action: \\\"status\\\", id: \\\"...\\\" }) when you need a one-shot status/result or to inspect a blocked/stale run. To block until completion, prefer subagent_wait(). Do not poll in a loop just to wait.\",\n\t].join(\"\\n\");\n}\n\n/**\n * Check if jiti is available for async execution\n */\nexport function isAsyncAvailable(): boolean {\n\treturn jitiCliPath !== undefined;\n}\n\nfunction isNodeExecutableName(execPath: string): boolean {\n\tconst basename = path.basename(execPath).toLowerCase();\n\treturn basename === \"node\" || basename === \"node.exe\" || basename === \"nodejs\" || basename === \"nodejs.exe\";\n}\n\nfunction canUseCurrentNodeExecutable(execPath: string): boolean {\n\ttry {\n\t\tfs.accessSync(execPath, process.platform === \"win32\" ? fs.constants.F_OK : fs.constants.X_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction resolveAsyncRunnerNodeCommand(): string {\n\tif (isNodeExecutableName(process.execPath) && canUseCurrentNodeExecutable(process.execPath)) {\n\t\treturn process.execPath;\n\t}\n\treturn process.platform === \"win32\" ? \"node.exe\" : \"node\";\n}\n\nexport function resolveAsyncRunnerLogPaths(cfg: object): { stdoutPath: string; stderrPath: string } | undefined {\n\tconst asyncDir = typeof (cfg as { asyncDir?: unknown }).asyncDir === \"string\"\n\t\t? (cfg as { asyncDir: string }).asyncDir\n\t\t: undefined;\n\tif (!asyncDir) return undefined;\n\treturn {\n\t\tstdoutPath: path.join(asyncDir, \"runner.stdout.log\"),\n\t\tstderrPath: path.join(asyncDir, \"runner.stderr.log\"),\n\t};\n}\n\nfunction closeFd(fd: number | undefined): void {\n\tif (fd === undefined) return;\n\ttry {\n\t\tfs.closeSync(fd);\n\t} catch {\n\t\t// Best-effort cleanup; child process already owns its duplicated stdio fd.\n\t}\n}\n\n/**\n * Spawn the async runner process\n */\nconst RUNNER_STARTUP_TIMEOUT_MS = 10_000;\nconst RUNNER_STARTUP_WAIT_BUFFER = typeof SharedArrayBuffer !== \"undefined\" ? new SharedArrayBuffer(4) : undefined;\nconst RUNNER_STARTUP_WAIT_VIEW = RUNNER_STARTUP_WAIT_BUFFER ? new Int32Array(RUNNER_STARTUP_WAIT_BUFFER) : undefined;\n\ntype RunnerStartupState = \"ready\" | \"acknowledged\";\n\ntype RunnerStartupWaitResult =\n\t| { ok: true; token: string }\n\t| { ok: false; error: string };\n\nfunction waitForStartupInterval(delayMs = 20): void {\n\tif (RUNNER_STARTUP_WAIT_VIEW) {\n\t\tAtomics.wait(RUNNER_STARTUP_WAIT_VIEW, 0, 0, delayMs);\n\t\treturn;\n\t}\n\tconst waitUntil = Date.now() + delayMs;\n\twhile (Date.now() < waitUntil) {\n\t\t// Startup handshakes are synchronous so resume rejects before reporting a run as started.\n\t}\n}\n\nfunction readRunnerStartup(startupPath: string, expectedState: RunnerStartupState, expectedToken?: string): RunnerStartupWaitResult | undefined {\n\tif (!fs.existsSync(startupPath)) return undefined;\n\ttry {\n\t\tconst payload = JSON.parse(fs.readFileSync(startupPath, \"utf-8\")) as { state?: unknown; token?: unknown; error?: unknown };\n\t\tif (payload.state === \"error\" && typeof payload.error === \"string\") return { ok: false, error: payload.error };\n\t\tif (payload.state !== expectedState) return undefined;\n\t\tif (typeof payload.token !== \"string\" || (expectedToken !== undefined && payload.token !== expectedToken)) {\n\t\t\treturn { ok: false, error: `Async runner wrote an invalid ${expectedState} startup handshake: ${startupPath}` };\n\t\t}\n\t\treturn { ok: true, token: payload.token };\n\t} catch (error) {\n\t\treturn { ok: false, error: `Failed to read async runner startup handshake '${startupPath}': ${error instanceof Error ? error.message : String(error)}` };\n\t}\n}\n\nfunction waitForRunnerStartup(startupPath: string, expectedState: RunnerStartupState, timeoutMs: number, expectedToken?: string): RunnerStartupWaitResult {\n\tconst deadline = Date.now() + timeoutMs;\n\tfor (;;) {\n\t\tconst result = readRunnerStartup(startupPath, expectedState, expectedToken);\n\t\tif (result) return result;\n\t\tif (Date.now() >= deadline) break;\n\t\twaitForStartupInterval(Math.min(20, Math.max(1, deadline - Date.now())));\n\t}\n\tconst finalResult = readRunnerStartup(startupPath, expectedState, expectedToken);\n\tif (finalResult) return finalResult;\n\treturn { ok: false, error: `Timed out after ${timeoutMs}ms waiting for the async runner startup state '${expectedState}'.` };\n}\n\nfunction writeRunnerStartupControl(filePath: string, payload: { action: \"ack\" | \"proceed\"; token: string }): void {\n\tconst tempPath = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;\n\ttry {\n\t\tfs.writeFileSync(tempPath, JSON.stringify(payload), { encoding: \"utf-8\", mode: 0o600 });\n\t\tfs.renameSync(tempPath, filePath);\n\t} catch (error) {\n\t\ttry {\n\t\t\tfs.rmSync(tempPath, { force: true });\n\t\t} catch {\n\t\t\t// Preserve the startup-control write error.\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction runnerIsAlive(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t}\n}\n\nfunction terminateRunnerBeforeProceed(pid: number): void {\n\tfor (const signal of [\"SIGTERM\", \"SIGKILL\"] as const) {\n\t\tif (!runnerIsAlive(pid)) return;\n\t\ttry {\n\t\t\tprocess.kill(pid, signal);\n\t\t} catch {\n\t\t\tif (!runnerIsAlive(pid)) return;\n\t\t}\n\t\tconst deadline = Date.now() + 1000;\n\t\twhile (runnerIsAlive(pid) && Date.now() < deadline) waitForStartupInterval();\n\t}\n}\n\nfunction spawnRunner(cfg: object, suffix: string, cwd: string): { pid?: number; error?: string } {\n\tif (!jitiCliPath) {\n\t\treturn { error: \"upstream jiti for TypeScript execution could not be found; ensure package dependencies are installed\" };\n\t}\n\n\ttry {\n\t\tconst cwdStats = fs.statSync(cwd);\n\t\tif (!cwdStats.isDirectory()) {\n\t\t\treturn { error: `cwd is not a directory: ${cwd}` };\n\t\t}\n\t} catch {\n\t\treturn { error: `cwd does not exist: ${cwd}` };\n\t}\n\n\tfs.mkdirSync(TEMP_ROOT_DIR, { recursive: true });\n\tconst cfgPath = getAsyncConfigPath(suffix);\n\tfs.writeFileSync(cfgPath, JSON.stringify(cfg));\n\t// lunr: bake-in ships compiled .js only; use the .ts when present (upstream dev), else the .js sibling.\n\tconst runnerTsPath = path.join(path.dirname(fileURLToPath(import.meta.url)), \"subagent-runner.ts\");\n\tconst runner = fs.existsSync(runnerTsPath) ? runnerTsPath : runnerTsPath.replace(/\\.ts$/, \".js\");\n\tconst nodeCommand = resolveAsyncRunnerNodeCommand();\n\tconst startupPath = typeof (cfg as { revivalLease?: unknown; asyncDir?: unknown }).revivalLease === \"object\"\n\t\t&& typeof (cfg as { asyncDir?: unknown }).asyncDir === \"string\"\n\t\t? path.join((cfg as { asyncDir: string }).asyncDir, \"runner-startup.json\")\n\t\t: undefined;\n\tconst startupAckPath = startupPath ? path.join(path.dirname(startupPath), \"runner-startup-ack.json\") : undefined;\n\tconst startupProceedPath = startupPath ? path.join(path.dirname(startupPath), \"runner-startup-proceed.json\") : undefined;\n\tif (startupPath) fs.rmSync(startupPath, { force: true });\n\tif (startupAckPath) fs.rmSync(startupAckPath, { force: true });\n\tif (startupProceedPath) fs.rmSync(startupProceedPath, { force: true });\n\n\tconst logPaths = resolveAsyncRunnerLogPaths(cfg);\n\tlet stdoutFd: number | undefined;\n\tlet stderrFd: number | undefined;\n\ttry {\n\t\tif (logPaths) {\n\t\t\tfs.mkdirSync(path.dirname(logPaths.stdoutPath), { recursive: true });\n\t\t\tstdoutFd = fs.openSync(logPaths.stdoutPath, \"a\");\n\t\t\tstderrFd = fs.openSync(logPaths.stderrPath, \"a\");\n\t\t}\n\t\tconst proc = spawn(nodeCommand, [jitiCliPath, runner, cfgPath], {\n\t\t\tcwd,\n\t\t\tdetached: true,\n\t\t\tstdio: [\"ignore\", stdoutFd ?? \"ignore\", stderrFd ?? \"ignore\"],\n\t\t\twindowsHide: true,\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\t...(piPackageRoot ? { [PI_CODING_AGENT_PACKAGE_ROOT_ENV]: piPackageRoot } : {}),\n\t\t\t},\n\t\t});\n\t\tcloseFd(stdoutFd);\n\t\tcloseFd(stderrFd);\n\t\tproc.on(\"error\", (error) => {\n\t\t\tconsole.error(`[pi-subagents] async spawn failed: ${error.message}`);\n\t\t});\n\t\tif (typeof proc.pid !== \"number\") {\n\t\t\treturn { error: `async runner did not produce a pid for cwd: ${cwd}` };\n\t\t}\n\t\tproc.unref();\n\t\tif (startupPath && startupAckPath && startupProceedPath) {\n\t\t\tconst ready = waitForRunnerStartup(startupPath, \"ready\", RUNNER_STARTUP_TIMEOUT_MS);\n\t\t\tif (!ready.ok) {\n\t\t\t\tterminateRunnerBeforeProceed(proc.pid);\n\t\t\t\treturn { error: ready.error };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\twriteRunnerStartupControl(startupAckPath, { action: \"ack\", token: ready.token });\n\t\t\t} catch (error) {\n\t\t\t\tterminateRunnerBeforeProceed(proc.pid);\n\t\t\t\treturn { error: `Failed to acknowledge async runner startup: ${error instanceof Error ? error.message : String(error)}` };\n\t\t\t}\n\t\t\tconst acknowledged = waitForRunnerStartup(startupPath, \"acknowledged\", RUNNER_STARTUP_TIMEOUT_MS, ready.token);\n\t\t\tif (!acknowledged.ok) {\n\t\t\t\tterminateRunnerBeforeProceed(proc.pid);\n\t\t\t\treturn { error: acknowledged.error };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\twriteRunnerStartupControl(startupProceedPath, { action: \"proceed\", token: ready.token });\n\t\t\t} catch (error) {\n\t\t\t\tterminateRunnerBeforeProceed(proc.pid);\n\t\t\t\treturn { error: `Failed to authorize async runner startup: ${error instanceof Error ? error.message : String(error)}` };\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tfs.rmSync(startupPath, { force: true });\n\t\t\t} catch {\n\t\t\t\t// Proceed is the commit point; handshake cleanup cannot turn a running revival into a start error.\n\t\t\t}\n\t\t}\n\t\treturn { pid: proc.pid };\n\t} catch (error) {\n\t\tcloseFd(stdoutFd);\n\t\tcloseFd(stderrFd);\n\t\treturn { error: error instanceof Error ? error.message : String(error) };\n\t}\n}\n\nfunction formatAsyncStartError(mode: SubagentRunMode, message: string): AsyncExecutionResult {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tisError: true,\n\t\tdetails: { mode, results: [] },\n\t};\n}\n\nconst UNAVAILABLE_SUBAGENT_SKILL_ERROR = \"Skills not found: pi-subagents\";\n\nclass UnavailableSubagentSkillError extends Error {}\nclass AsyncStartValidationError extends Error {}\n\nfunction childDescription(step: Pick<SequentialStep, \"description\" | \"label\" | \"agent\">): string {\n\treturn step.description || step.label || step.agent || \"child\";\n}\n\nexport function buildAsyncRunnerSteps(id: string, params: AsyncRunnerStepBuildParams): AsyncRunnerStepBuildResult {\n\tconst {\n\t\tchain,\n\t\tctx,\n\t\tcwd,\n\t\tsessionFilesByFlatIndex,\n\t\tthinkingOverridesByFlatIndex,\n\t\tmaxSubagentDepth,\n\t\tworktreeBaseDir,\n\t\tasyncDir,\n\t} = params;\n\tconst outputBaseDir = params.outputBaseDir;\n\tconst resultMode = params.resultMode ?? \"chain\";\n\tconst chainSkills = params.chainSkills ?? [];\n\tconst availableModels = params.availableModels;\n\tconst runnerCwd = resolveChildCwd(ctx.cwd, cwd);\n\tconst progressDir = params.progressDir ?? runnerCwd;\n\tconst graphChain: ChainStep[] = params.attachRoot\n\t\t? [{\n\t\t\t\tagent: params.attachRoot.agent,\n\t\t\t\ttask: `Attach async root ${params.attachRoot.runId}`,\n\t\t\t\tlabel: params.attachRoot.label ?? `Attached root ${params.attachRoot.runId}`,\n\t\t\t\t...(params.attachRoot.outputName ? { as: params.attachRoot.outputName } : {}),\n\t\t\t}, ...chain]\n\t\t: chain;\n\tconst firstStep = chain[0];\n\tconst originalTask = params.task ?? (firstStep\n\t\t? (isParallelStep(firstStep)\n\t\t\t? firstStep.parallel[0]?.task\n\t\t\t: isDynamicParallelStep(firstStep)\n\t\t\t\t? firstStep.parallel.task\n\t\t\t\t: (firstStep as SequentialStep).task)\n\t\t: undefined);\n\ttry {\n\t\tif (params.validateOutputBindings !== false) {\n\t\t\tvalidateChainOutputBindings(chain, { maxItems: params.dynamicFanoutMaxItems });\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof ChainOutputValidationError) return { error: error.message };\n\t\tthrow error;\n\t}\n\tconst workflowGraph = buildWorkflowGraphSnapshot({ runId: id, mode: resultMode, steps: graphChain });\n\n\tlet progressInstructionCreated = false;\n\tconst buildStepOverrides = (s: SequentialStep): StepOverrides => {\n\t\tconst stepSkillInput = normalizeSkillInput(s.skill);\n\t\treturn {\n\t\t\t...(s.output !== undefined ? { output: s.output } : {}),\n\t\t\t...(s.outputMode !== undefined ? { outputMode: s.outputMode } : {}),\n\t\t\t...(s.reads !== undefined ? { reads: s.reads } : {}),\n\t\t\t...(s.progress !== undefined ? { progress: s.progress } : {}),\n\t\t\t...(stepSkillInput !== undefined ? { skills: stepSkillInput } : {}),\n\t\t\t...(s.model !== undefined ? { model: s.model } : {}),\n\t\t};\n\t};\n\tconst buildSeqStep = (s: SequentialStep, sessionFile?: string, behaviorCwd?: string, progressPrecreated = false, resolvedBehavior?: ResolvedStepBehavior, flatIndex?: number, parallelOutputNamespace?: { stepIndex: number; taskIndex?: number }) => {\n\t\tconst childIndex = flatIndex ?? parallelOutputNamespace?.stepIndex ?? 0;\n\t\tconst spec = normalizeChildSpec(s, {\n\t\t\tparentMode: snapshotParentPermissionMode(ctx.parentSessionId ?? ctx.currentSessionId),\n\t\t\trunId: params.childIdRunId ?? id,\n\t\t\tindex: childIndex,\n\t\t\tchildId: s.childId ?? (s.agent?.trim() ? s.agent : undefined),\n\t\t\tdefaultTask: \"{previous}\",\n\t\t\tfanoutAuthorized: false,\n\t\t});\n\t\tconst toolBudgetInput = spec.toolBudget ?? params.toolBudget ?? params.configToolBudget;\n\t\tconst resolvedToolBudget = validateToolBudgetConfig(toolBudgetInput, spec.toolBudget ? \"toolBudget\" : \"config.toolBudget\");\n\t\tif (resolvedToolBudget.error) throw new AsyncStartValidationError(resolvedToolBudget.error);\n\t\tconst stepCwd = resolveChildCwd(runnerCwd, s.cwd);\n\t\tconst instructionCwd = behaviorCwd ?? stepCwd;\n\t\tlet behavior = suppressProgressForReadOnlyTask(resolvedBehavior ?? resolveStepBehavior(buildStepOverrides(s), chainSkills), s.task, originalTask);\n\t\tconst inheritedRelativeParallelOutput = parallelOutputNamespace && s.output === undefined && typeof behavior.output === \"string\" && !path.isAbsolute(behavior.output);\n\t\tif (inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex !== undefined) {\n\t\t\tbehavior = {\n\t\t\t\t...behavior,\n\t\t\t\toutput: path.join(`parallel-${parallelOutputNamespace.stepIndex}`, String(parallelOutputNamespace.taskIndex), behavior.output),\n\t\t\t};\n\t\t}\n\t\tconst namespaceOutputPath = Boolean(inheritedRelativeParallelOutput && parallelOutputNamespace.taskIndex === undefined);\n\t\tconst skillNames = behavior.skills === false ? [] : behavior.skills;\n\t\tconst { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(\n\t\t\tskillNames,\n\t\t\tstepCwd,\n\t\t\tctx.cwd,\n\t\t\tundefined,\n\t\t\tstepCwd,\n\t\t);\n\t\tif (missingSkills.includes(\"pi-subagents\")) throw new UnavailableSubagentSkillError(UNAVAILABLE_SUBAGENT_SKILL_ERROR);\n\n\t\tlet systemPrompt = \"\";\n\t\tif (resolvedSkills.length > 0) {\n\t\t\tconst injection = buildSkillInjection(resolvedSkills);\n\t\t\tsystemPrompt = systemPrompt ? `${systemPrompt}\\n\\n${injection}` : injection;\n\t\t}\n\t\tconst readInstructions = buildChainInstructions({ ...behavior, output: false, progress: false }, instructionCwd, false);\n\t\tconst isFirstProgressAgent = behavior.progress && !progressPrecreated && !progressInstructionCreated;\n\t\tif (behavior.progress) progressInstructionCreated = true;\n\t\tconst progressInstructions = buildChainInstructions({ ...behavior, output: false, reads: false }, progressDir, isFirstProgressAgent);\n\t\tconst outputPath = resolveSingleOutputPath(behavior.output, ctx.cwd, instructionCwd, outputBaseDir);\n\t\tif (!namespaceOutputPath) systemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, {\n\t\t\ttools: spec.effectivePermissions === \"read-only\" ? [\"read\", \"grep\", \"find\", \"ls\", \"bash\"] : undefined,\n\t\t});\n\t\tconst validationError = validateFileOnlyOutputMode(behavior.outputMode, outputPath, `Async step (${spec.description})`);\n\t\tif (validationError) throw new AsyncStartValidationError(validationError);\n\t\tlet taskTemplate = s.task ?? \"{previous}\";\n\t\ttaskTemplate = taskTemplate.replace(/\\{task\\}/g, originalTask ?? \"\");\n\t\ttaskTemplate = taskTemplate.replace(/\\{chain_dir\\}/g, runnerCwd);\n\t\tconst taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;\n\t\tconst task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, {\n\t\t\ttools: spec.effectivePermissions === \"read-only\" ? [\"read\", \"grep\", \"find\", \"ls\", \"bash\"] : undefined,\n\t\t});\n\n\t\tconst primaryModel = resolveRequiredTierModel(spec.tier, availableModels, ctx.currentModelProvider);\n\t\tconst thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];\n\t\tconst effectiveThinking = thinkingOverride;\n\t\tconst model = applyThinkingSuffix(primaryModel, effectiveThinking, thinkingOverride !== undefined);\n\t\treturn {\n\t\t\tparentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,\n\t\t\tparentPermissionMode: snapshotParentPermissionMode(ctx.parentSessionId ?? ctx.currentSessionId),\n\t\t\tchildId: spec.childId,\n\t\t\tdescription: spec.description,\n\t\t\tpermissions: spec.effectivePermissions,\n\t\t\ttier: spec.tier,\n\t\t\tagent: spec.description,\n\t\t\ttask,\n\t\t\tphase: s.phase,\n\t\t\tlabel: s.label,\n\t\t\toutputName: s.as,\n\t\t\tstructured: Boolean(s.outputSchema),\n\t\t\tcwd: stepCwd,\n\t\t\tmodel,\n\t\t\tthinking: resolveEffectiveThinking(model, effectiveThinking),\n\t\t\t...(spec.modelSelection ? { modelSelection: spec.modelSelection } : {}),\n\t\t\tmodelCandidates: buildModelCandidates(primaryModel, undefined, availableModels, ctx.currentModelProvider, { scope: ctx.modelScope }).map((candidate) =>\n\t\t\t\tapplyThinkingSuffix(candidate, effectiveThinking, thinkingOverride !== undefined),\n\t\t\t),\n\t\t\tsystemPrompt,\n\t\t\tsystemPromptMode: \"append\",\n\t\t\tinheritProjectContext: true,\n\t\t\tinheritSkills: false,\n\t\t\tskills: resolvedSkills.map((r) => r.name),\n\t\t\toutputPath,\n\t\t\t...(namespaceOutputPath ? { namespaceOutputPath: true } : {}),\n\t\t\toutputMode: behavior.outputMode,\n\t\t\tsessionFile,\n\t\t\tmaxSubagentDepth,\n\t\t\twaitToolEnabled: params.waitToolEnabled,\n\t\t\teffectiveAcceptance: resolveEffectiveAcceptance({\n\t\t\t\texplicit: s.acceptance,\n\t\t\t\tagentName: spec.description,\n\t\t\t\tpermissions: spec.effectivePermissions,\n\t\t\t\ttask,\n\t\t\t\tmode: resultMode,\n\t\t\t\tasync: true,\n\t\t\t\tdynamic: false,\n\t\t\t}),\n\t\t\tacceptanceInput: s.acceptance,\n\t\t\tacceptanceRole: spec.effectivePermissions === \"read-only\" ? \"read-only\" : \"writer\",\n\t\t\t...(s.outputSchema ? { structuredOutputSchema: s.outputSchema } : {}),\n\t\t\t...(s.outputSchema ? { structuredOutput: createStructuredOutputRuntime(s.outputSchema, path.join(asyncDir, \"structured-output\")) } : {}),\n\t\t\t...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),\n\t\t};\n\t};\n\n\tlet flatStepIndex = 0;\n\tconst nextFlatStep = (): { index: number; sessionFile?: string; thinkingOverride?: string | false } => {\n\t\tconst index = flatStepIndex;\n\t\tconst sessionFile = sessionFilesByFlatIndex?.[flatStepIndex];\n\t\tconst thinkingOverride = thinkingOverridesByFlatIndex?.[flatStepIndex];\n\t\tflatStepIndex++;\n\t\treturn {\n\t\t\tindex,\n\t\t\t...(sessionFile ? { sessionFile } : {}),\n\t\t\t...(thinkingOverride ? { thinkingOverride } : {}),\n\t\t};\n\t};\n\n\ttry {\n\t\tconst builtSteps = chain.map((s, stepIndex) => {\n\t\t\tif (isParallelStep(s)) {\n\t\t\t\tconst parallelBehaviors = s.parallel.map((task) => {\n\t\t\t\t\treturn suppressProgressForReadOnlyTask(resolveStepBehavior(buildStepOverrides(task), chainSkills), task.task, originalTask);\n\t\t\t\t});\n\t\t\t\tconst progressPrecreated = parallelBehaviors.some((behavior) => behavior.progress);\n\t\t\t\tif (progressPrecreated) {\n\t\t\t\t\tif (!s.worktree || params.progressDir) writeInitialProgressFile(progressDir);\n\t\t\t\t\tprogressInstructionCreated = true;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tparallel: s.parallel.map((t, taskIndex) => {\n\t\t\t\t\t\tlet behaviorCwd: string | undefined;\n\t\t\t\t\t\tif (s.worktree) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tbehaviorCwd = resolveExpectedWorktreeAgentCwd(runnerCwd, `${id}-s${stepIndex}`, taskIndex, worktreeBaseDir);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\tbehaviorCwd = undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst staticStep = nextFlatStep();\n\t\t\t\t\t\treturn buildSeqStep(t, staticStep.sessionFile, behaviorCwd, progressPrecreated, parallelBehaviors[taskIndex], staticStep.index, { stepIndex, taskIndex });\n\t\t\t\t\t}),\n\t\t\t\t\tconcurrency: s.concurrency,\n\t\t\t\t\tfailFast: s.failFast,\n\t\t\t\t\tworktree: s.worktree,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (isDynamicParallelStep(s)) {\n\t\t\t\tconst behavior = suppressProgressForReadOnlyTask(resolveStepBehavior(buildStepOverrides(s.parallel), chainSkills), s.parallel.task, originalTask);\n\t\t\t\tconst progressPrecreated = behavior.progress;\n\t\t\t\tif (progressPrecreated) {\n\t\t\t\t\twriteInitialProgressFile(progressDir);\n\t\t\t\t\tprogressInstructionCreated = true;\n\t\t\t\t}\n\t\t\t\tconst maxItems = s.expand.maxItems ?? params.dynamicFanoutMaxItems ?? 0;\n\t\t\t\tconst dynamicFlatSteps = Array.from({ length: maxItems }, () => nextFlatStep());\n\t\t\t\tconst parallel = buildSeqStep(s.parallel as SequentialStep, undefined, undefined, progressPrecreated, behavior, undefined, { stepIndex });\n\t\t\t\treturn {\n\t\t\t\t\texpand: s.expand,\n\t\t\t\t\tparallel,\n\t\t\t\t\tcollect: s.collect,\n\t\t\t\t\tconcurrency: s.concurrency,\n\t\t\t\t\tfailFast: s.failFast,\n\t\t\t\t\tphase: s.phase,\n\t\t\t\t\tlabel: s.label,\n\t\t\t\t\tsessionFiles: dynamicFlatSteps.map((step) => step.sessionFile),\n\t\t\t\t\tthinkingOverrides: dynamicFlatSteps.map((step) => step.thinkingOverride),\n\t\t\t\t\teffectiveAcceptance: resolveEffectiveAcceptance({\n\t\t\t\t\t\texplicit: s.acceptance,\n\t\t\t\t\t\tagentName: s.parallel.description,\n\t\t\t\t\t\tpermissions: s.parallel.permissions === \"read-only\" ? \"read-only\" : \"full\",\n\t\t\t\t\t\ttask: parallel.task,\n\t\t\t\t\t\tmode: resultMode,\n\t\t\t\t\t\tasync: true,\n\t\t\t\t\t\tdynamicGroup: true,\n\t\t\t\t\t}),\n\t\t\t\t\tacceptanceInput: s.acceptance,\n\t\t\t\t\tacceptanceRole: s.parallel.permissions === \"read-only\" ? \"read-only\" : \"writer\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst staticStep = nextFlatStep();\n\t\t\treturn buildSeqStep(s as SequentialStep, staticStep.sessionFile, undefined, false, undefined, staticStep.index);\n\t\t});\n\t\tconst steps = params.attachRoot\n\t\t\t? [{\n\t\t\t\t\tagent: params.attachRoot.agent,\n\t\t\t\t\ttask: \"\",\n\t\t\t\t\tlabel: params.attachRoot.label ?? `Attached root ${params.attachRoot.runId}`,\n\t\t\t\t\toutputName: params.attachRoot.outputName,\n\t\t\t\t\timportAsyncRoot: {\n\t\t\t\t\t\trunId: params.attachRoot.runId,\n\t\t\t\t\t\tasyncDir: params.attachRoot.asyncDir,\n\t\t\t\t\t\tresultPath: params.attachRoot.resultPath,\n\t\t\t\t\t\tindex: params.attachRoot.index,\n\t\t\t\t\t},\n\t\t\t\t\tinheritProjectContext: false,\n\t\t\t\t\tinheritSkills: false,\n\t\t\t\t}, ...builtSteps]\n\t\t\t: builtSteps;\n\t\tfor (const step of steps) {\n\t\t\tif (!(\"parallel\" in step) || !Array.isArray(step.parallel)) continue;\n\t\t\tconst seen = new Map<string, { index: number; agent: string }>();\n\t\t\tfor (let index = 0; index < step.parallel.length; index++) {\n\t\t\t\tconst task = step.parallel[index]!;\n\t\t\t\tif (!task.outputPath) continue;\n\t\t\t\tconst previous = seen.get(task.outputPath);\n\t\t\t\tif (previous) {\n\t\t\t\t\tthrow new AsyncStartValidationError(`Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${task.agent}) resolve output to the same path: ${task.outputPath}. Use distinct output paths.`);\n\t\t\t\t}\n\t\t\t\tseen.set(task.outputPath, { index, agent: task.agent });\n\t\t\t}\n\t\t}\n\t\treturn { steps, runnerCwd, workflowGraph, eventChain: graphChain, ...(originalTask !== undefined ? { originalTask } : {}) };\n\t} catch (error) {\n\t\tif (error instanceof UnavailableSubagentSkillError || error instanceof AsyncStartValidationError) return { error: error.message };\n\t\tthrow error;\n\t}\n}\n\n/**\n * Execute a chain asynchronously\n */\nexport function executeAsyncChain(\n\tid: string,\n\tparams: AsyncChainParams,\n): AsyncExecutionResult {\n\tconst {\n\t\tchain,\n\t\tctx,\n\t\tcwd,\n\t\tmaxOutput,\n\t\tartifactsDir,\n\t\tartifactConfig,\n\t\tshareEnabled,\n\t\tsessionRoot,\n\t\tsessionFilesByFlatIndex,\n\t\tthinkingOverridesByFlatIndex,\n\t\tmaxSubagentDepth,\n\t\tworktreeSetupHook,\n\t\tworktreeSetupHookTimeoutMs,\n\t\tworktreeBaseDir,\n\t\tcontrolConfig,\n\t\tcontrolIntercomTarget,\n\t\tchildIntercomTarget,\n\t\tnestedRoute,\n\t} = params;\n\tconst resultMode = params.resultMode ?? \"chain\";\n\tconst inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();\n\tconst nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;\n\tconst asyncDir = inheritedNestedRoute\n\t\t? path.join(TEMP_ROOT_DIR, \"nested-subagent-runs\", inheritedNestedRoute.rootRunId, id)\n\t\t: path.join(ASYNC_DIR, id);\n\ttry {\n\t\tfs.mkdirSync(asyncDir, { recursive: true });\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Failed to create async run directory '${asyncDir}': ${message}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: resultMode, results: [] },\n\t\t};\n\t}\n\n\tconst built = buildAsyncRunnerSteps(id, {\n\t\tchain,\n\t\ttask: params.task,\n\t\tattachRoot: params.attachRoot,\n\t\tresultMode,\n\t\tctx,\n\t\tavailableModels: params.availableModels,\n\t\tcwd,\n\t\tchainSkills: params.chainSkills,\n\t\tsessionFilesByFlatIndex,\n\t\tthinkingOverridesByFlatIndex,\n\t\tprogressDir: params.progressDir ?? (artifactsDir ? path.join(artifactsDir, \"progress\", id) : resultMode === \"parallel\" ? path.join(asyncDir, \"progress\") : undefined),\n\t\toutputBaseDir: artifactsDir ? path.join(artifactsDir, \"outputs\", id) : undefined,\n\t\tdynamicFanoutMaxItems: params.dynamicFanoutMaxItems,\n\t\tmaxSubagentDepth,\n\t\twaitToolEnabled: params.waitToolEnabled,\n\t\tworktreeBaseDir,\n\t\tasyncDir,\n\t\ttoolBudget: params.toolBudget,\n\t\tconfigToolBudget: params.configToolBudget,\n\t});\n\tif (\"error\" in built) {\n\t\ttry {\n\t\t\tfs.rmSync(asyncDir, { recursive: true, force: true });\n\t\t} catch {\n\t\t\t// Best-effort cleanup for validation failures before the runner is spawned.\n\t\t}\n\t\treturn formatAsyncStartError(resultMode, built.error);\n\t}\n\tconst { steps, runnerCwd, workflowGraph, eventChain } = built;\n\tconst deadlineAt = params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined;\n\tconst initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;\n\tlet childTargetIndex = 0;\n\tconst childIntercomTargets = childIntercomTarget ? steps.flatMap((step) => {\n\t\tif (!(\"parallel\" in step) && step.importAsyncRoot) {\n\t\t\tchildTargetIndex++;\n\t\t\treturn [undefined];\n\t\t}\n\t\tif (\"parallel\" in step) {\n\t\t\tif (!Array.isArray(step.parallel)) {\n\t\t\t\tchildTargetIndex++;\n\t\t\t\treturn [undefined];\n\t\t\t}\n\t\t\treturn step.parallel.map((task) => childIntercomTarget(task.childId ?? task.agent, childTargetIndex++));\n\t\t}\n\t\treturn [childIntercomTarget(step.childId ?? step.agent, childTargetIndex++)];\n\t}) : undefined;\n\n\tlet spawnResult: { pid?: number; error?: string } = {};\n\ttry {\n\t\tspawnResult = spawnRunner(\n\t\t\t{\n\t\t\t\tid,\n\t\t\t\tsteps,\n\t\t\t\tresultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path.join(RESULTS_DIR, `${id}.json`),\n\t\t\t\tcwd: runnerCwd,\n\t\t\t\tplaceholder: \"{previous}\",\n\t\t\t\tmaxOutput,\n\t\t\t\tartifactsDir: artifactConfig.enabled ? artifactsDir : undefined,\n\t\t\t\tartifactConfig,\n\t\t\t\tshare: shareEnabled,\n\t\t\t\tsessionDir: sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined,\n\t\t\t\tasyncDir,\n\t\t\t\tsessionId: ctx.currentSessionId,\n\t\t\t\tpiPackageRoot,\n\t\t\t\tpiArgv1: process.argv[1],\n\t\t\t\tworktreeSetupHook,\n\t\t\t\tworktreeSetupHookTimeoutMs,\n\t\t\t\tworktreeBaseDir,\n\t\t\t\tcontrolConfig,\n\t\t\t\tturnBudget: params.turnBudget,\n\t\t\t\ttoolBudget: params.toolBudget,\n\t\t\t\tcontrolIntercomTarget,\n\t\t\t\tchildIntercomTargets,\n\t\t\t\tresultMode,\n\t\t\t\tdynamicFanoutMaxItems: params.dynamicFanoutMaxItems,\n\t\t\t\ttimeoutMs: params.timeoutMs,\n\t\t\t\tdeadlineAt,\n\t\t\t\tglobalConcurrencyLimit: params.globalConcurrencyLimit,\n\t\t\t\tworkflowGraph,\n\t\t\t\tnestedRoute: nestedRoute ?? inheritedNestedRoute,\n\t\t\t\tnestedSelf: inheritedNestedRoute && nestedAddress ? {\n\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\tdepth: nestedAddress.depth,\n\t\t\t\t\tpath: nestedAddress.path,\n\t\t\t\t} : undefined,\n\t\t\t},\n\t\t\tid,\n\t\t\trunnerCwd,\n\t\t);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${message}`);\n\t}\n\n\tif (spawnResult.error) {\n\t\treturn formatAsyncStartError(resultMode, `Failed to start async ${resultMode} '${id}': ${spawnResult.error}`);\n\t}\n\n\tif (spawnResult.pid) {\n\t\tconst eventFirstStep = eventChain[0];\n\t\tconst firstAgents = isParallelStep(eventFirstStep)\n\t\t\t? eventFirstStep.parallel.map(childDescription)\n\t\t\t: isDynamicParallelStep(eventFirstStep)\n\t\t\t\t? [childDescription(eventFirstStep.parallel)]\n\t\t\t: [childDescription(eventFirstStep as SequentialStep)];\n\t\tconst firstTask = isParallelStep(eventFirstStep)\n\t\t\t? eventFirstStep.parallel[0]?.task\n\t\t\t: isDynamicParallelStep(eventFirstStep)\n\t\t\t\t? eventFirstStep.parallel.task\n\t\t\t\t: (eventFirstStep as SequentialStep).task;\n\t\tconst workflowGoal = params.goal ?? (params.task?.trim() || firstTask);\n\t\tconst parallelGroups: Array<{ start: number; count: number; stepIndex: number }> = [];\n\t\tconst flatAgents: string[] = [];\n\t\tlet flatStepStart = 0;\n\t\tfor (let stepIndex = 0; stepIndex < eventChain.length; stepIndex++) {\n\t\t\tconst step = eventChain[stepIndex]!;\n\t\t\tif (isParallelStep(step)) {\n\t\t\t\tparallelGroups.push({ start: flatStepStart, count: step.parallel.length, stepIndex });\n\t\t\t\tflatAgents.push(...step.parallel.map(childDescription));\n\t\t\t\tflatStepStart += step.parallel.length;\n\t\t\t} else if (isDynamicParallelStep(step)) {\n\t\t\t\tparallelGroups.push({ start: flatStepStart, count: 1, stepIndex });\n\t\t\t\tflatAgents.push(childDescription(step.parallel));\n\t\t\t\tflatStepStart++;\n\t\t\t} else {\n\t\t\t\tflatAgents.push(childDescription(step as SequentialStep));\n\t\t\t\tflatStepStart++;\n\t\t\t}\n\t\t}\n\t\tif (inheritedNestedRoute && nestedAddress) {\n\t\t\tconst now = Date.now();\n\t\t\ttry {\n\t\t\t\twriteNestedEvent(inheritedNestedRoute, {\n\t\t\t\t\ttype: \"subagent.nested.started\",\n\t\t\t\t\tts: now,\n\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\tchild: {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\t\tdepth: nestedAddress.depth,\n\t\t\t\t\t\tpath: nestedAddress.path,\n\t\t\t\t\t\tasyncDir,\n\t\t\t\t\t\tpid: spawnResult.pid,\n\t\t\t\t\t\townerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,\n\t\t\t\t\t\tleafIntercomTarget: childIntercomTargets?.[0],\n\t\t\t\t\t\tintercomTarget: childIntercomTargets?.[0],\n\t\t\t\t\t\townerState: \"live\",\n\t\t\t\t\t\tmode: resultMode,\n\t\t\t\t\t\tstate: \"running\",\n\t\t\t\t\t\tagent: firstAgents[0],\n\t\t\t\t\t\tagents: flatAgents,\n\t\t\t\t\t\tchainStepCount: eventChain.length,\n\t\t\t\t\t\tparallelGroups,\n\t\t\t\t\t\t...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),\n\t\t\t\t\t\t...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),\n\t\t\t\t\t\tstartedAt: now,\n\t\t\t\t\t\tlastUpdate: now,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Failed to emit nested async start event:\", error);\n\t\t\t}\n\t\t}\n\t\tctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {\n\t\t\tlifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\t\t\tid,\n\t\t\tpid: spawnResult.pid,\n\t\t\tsessionId: ctx.currentSessionId,\n\t\t\tmode: resultMode,\n\t\t\tagent: firstAgents[0],\n\t\t\tagents: flatAgents,\n\t\t\ttask: firstTask?.slice(0, 50),\n\t\t\tgoal: workflowGoal?.slice(0, 120),\n\t\t\tchain: eventChain.map((s) =>\n\t\t\t\tisParallelStep(s) ? `[${s.parallel.map(childDescription).join(\"+\")}]` : isDynamicParallelStep(s) ? `expand:${childDescription(s.parallel)}` : childDescription(s as SequentialStep),\n\t\t\t),\n\t\t\tchainStepCount: eventChain.length,\n\t\t\tparallelGroups,\n\t\t\tworkflowGraph,\n\t\t\tcwd: runnerCwd,\n\t\t\tasyncDir,\n\t\t\t...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}),\n\t\t\t...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),\n\t\t\tnestedRoute,\n\t\t});\n\t}\n\n\tconst chainDesc = chain\n\t\t.map((s) =>\n\t\t\tisParallelStep(s) ? `[${s.parallel.map(childDescription).join(\"+\")}]` : isDynamicParallelStep(s) ? `expand:${childDescription(s.parallel)}` : childDescription(s as SequentialStep),\n\t\t)\n\t\t.join(\" -> \");\n\n\treturn {\n\t\tcontent: [{ type: \"text\", text: formatAsyncStartedMessage(`Async ${resultMode}: ${chainDesc} [${id}]`) }],\n\t\tdetails: { mode: resultMode, runId: id, results: [], asyncId: id, asyncDir, workflowGraph, ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs, deadlineAt } : {}), ...(params.turnBudget ? { turnBudget: params.turnBudget } : {}), ...(params.toolBudget ? { toolBudget: params.toolBudget } : {}) },\n\t};\n}\n\n/**\n * Execute a single agent asynchronously\n */\nexport function executeAsyncSingle(\n\tid: string,\n\tparams: AsyncSingleParams,\n): AsyncExecutionResult {\n\tconst {\n\t\tspec,\n\t\tctx,\n\t\tcwd,\n\t\tmaxOutput,\n\t\tartifactsDir,\n\t\tartifactConfig,\n\t\tshareEnabled,\n\t\tsessionRoot,\n\t\tsessionFile,\n\t\tmaxSubagentDepth,\n\t\tworktreeSetupHook,\n\t\tworktreeSetupHookTimeoutMs,\n\t\tworktreeBaseDir,\n\t\tcontrolConfig,\n\t\tcontrolIntercomTarget,\n\t\tchildIntercomTarget,\n\t\tnestedRoute,\n\t} = params;\n\tconst agent = spec.description;\n\tconst task = spec.task;\n\tconst runnerCwd = resolveChildCwd(ctx.cwd, cwd);\n\tconst skillNames = params.skills ?? (spec.skill === false ? [] : normalizeSkillInput(spec.skill) ?? []);\n\tconst availableModels = params.availableModels;\n\tconst { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(\n\t\tskillNames,\n\t\trunnerCwd,\n\t\tctx.cwd,\n\t\tundefined,\n\t\trunnerCwd,\n\t);\n\tif (missingSkills.includes(\"pi-subagents\")) return formatAsyncStartError(\"single\", UNAVAILABLE_SUBAGENT_SKILL_ERROR);\n\tlet systemPrompt = \"\";\n\tif (resolvedSkills.length > 0) {\n\t\tconst injection = buildSkillInjection(resolvedSkills);\n\t\tsystemPrompt = systemPrompt ? `${systemPrompt}\\n\\n${injection}` : injection;\n\t}\n\tconst inheritedNestedRoute = resolveInheritedNestedRouteFromEnv();\n\tconst nestedAddress = inheritedNestedRoute ? resolveNestedParentAddressFromEnv() : undefined;\n\tconst asyncDir = inheritedNestedRoute\n\t\t? path.join(TEMP_ROOT_DIR, \"nested-subagent-runs\", inheritedNestedRoute.rootRunId, id)\n\t\t: path.join(ASYNC_DIR, id);\n\ttry {\n\t\tfs.mkdirSync(asyncDir, { recursive: true });\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `Failed to create async run directory '${asyncDir}': ${message}` }],\n\t\t\tisError: true,\n\t\t\tdetails: { mode: \"single\" as const, results: [] },\n\t\t};\n\t}\n\n\tconst effectiveOutput = normalizeSingleOutputOverride(params.output ?? spec.output, typeof spec.output === \"string\" ? spec.output : undefined);\n\tconst outputPath = resolveSingleOutputPath(effectiveOutput, ctx.cwd, runnerCwd, params.outputBaseDir ?? (artifactsDir ? path.join(artifactsDir, \"outputs\", id) : undefined));\n\tconst childToolShape = { tools: spec.effectivePermissions === \"read-only\" ? [\"read\", \"grep\", \"find\", \"ls\", \"bash\"] : undefined };\n\tsystemPrompt = injectOutputPathSystemPrompt(systemPrompt, outputPath, childToolShape);\n\tconst outputMode = params.outputMode ?? spec.outputMode ?? \"inline\";\n\tconst validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);\n\tif (validationError) return formatAsyncStartError(\"single\", validationError);\n\tconst taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, childToolShape);\n\tconst primaryModel = resolveRequiredTierModel(spec.tier, availableModels, ctx.currentModelProvider);\n\tconst effectiveThinking = params.thinkingOverride;\n\tconst model = applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);\n\tconst toolBudgetInput = params.toolBudget ?? spec.toolBudget ?? params.configToolBudget;\n\tconst resolvedToolBudget = validateToolBudgetConfig(toolBudgetInput, params.toolBudget || spec.toolBudget ? \"toolBudget\" : \"config.toolBudget\");\n\tif (resolvedToolBudget.error) return formatAsyncStartError(\"single\", resolvedToolBudget.error);\n\tconst deadlineAt = params.absoluteDeadlineAt ?? (params.timeoutMs !== undefined ? Date.now() + params.timeoutMs : undefined);\n\tconst timeoutMs = params.absoluteDeadlineAt !== undefined && deadlineAt !== undefined\n\t\t? deadlineAt - Date.now()\n\t\t: params.timeoutMs;\n\tif (timeoutMs !== undefined && timeoutMs <= 0) return formatAsyncStartError(\"single\", \"The source run's absolute deadline expired before recovery could launch.\");\n\tconst initialTurnBudget = params.turnBudget ? initialTurnBudgetState(params.turnBudget) : undefined;\n\tconst resolvedSessionDir = params.sessionDir ?? (sessionRoot ? path.join(sessionRoot, `async-${id}`) : undefined);\n\tconst resolvedAcceptance = resolveEffectiveAcceptance({\n\t\texplicit: params.acceptance ?? spec.acceptance,\n\t\tagentName: agent,\n\t\tpermissions: spec.effectivePermissions,\n\t\ttask,\n\t\tmode: \"single\",\n\t\tasync: true,\n\t});\n\tconst recoveryDescriptor: SteeringRecoveryDescriptor = {\n\t\tversion: 4,\n\t\tlifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\t\tsourceRunId: id,\n\t\tchildId: spec.childId,\n\t\tdescription: spec.description,\n\t\tpermissions: spec.effectivePermissions,\n\t\tagent,\n\t\t...(sessionFile ? { sessionFile } : {}),\n\t\tcwd: runnerCwd,\n\t\t...(model ? { model } : {}),\n\t\ttier: spec.tier,\n\t\t...(effectiveThinking ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),\n\t\t...(spec.modelSelection ? { modelSelection: spec.modelSelection } : {}),\n\t\t...(resolvedSkills.length ? { skills: resolvedSkills.map((skill) => skill.name) } : {}),\n\t\t...(outputPath ? { outputPath } : {}),\n\t\toutputMode,\n\t\t...(resolvedAcceptance ? { acceptance: resolvedAcceptance } : {}),\n\t\t...(controlConfig ? { controlConfig } : {}),\n\t\t...(deadlineAt !== undefined ? { absoluteDeadlineAt: deadlineAt } : {}),\n\t\t...(params.turnBudget ? { initialTurnBudget: params.turnBudget } : {}),\n\t\t...(resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {}),\n\t\tmaxSubagentDepth,\n\t\t...(maxOutput ? { maxOutput } : {}),\n\t\tshare: shareEnabled,\n\t\t...(resolvedSessionDir ? { sessionDir: resolvedSessionDir } : {}),\n\t\t...(artifactsDir ? { artifactsDir } : {}),\n\t\tartifactConfig,\n\t};\n\ttry {\n\t\twritePrivateAtomicJson(path.join(asyncDir, \"recovery-descriptor.json\"), recoveryDescriptor);\n\t} catch (error) {\n\t\treturn formatAsyncStartError(\"single\", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\tlet spawnResult: { pid?: number; error?: string } = {};\n\ttry {\n\t\tspawnResult = spawnRunner(\n\t\t\t{\n\t\t\t\tid,\n\t\t\t\tsteps: [\n\t\t\t\t\t{\n\t\t\t\t\t\tparentSessionId: ctx.parentSessionId ?? ctx.currentSessionId,\n\t\t\t\t\t\tparentPermissionMode: snapshotParentPermissionMode(ctx.parentSessionId ?? ctx.currentSessionId),\n\t\t\t\t\t\tchildId: spec.childId,\n\t\t\t\t\t\tdescription: spec.description,\n\t\t\t\t\t\tpermissions: spec.effectivePermissions,\n\t\t\t\t\t\tagent,\n\t\t\t\t\t\ttask: taskWithOutputInstruction,\n\t\t\t\t\t\tcwd: runnerCwd,\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinking: resolveEffectiveThinking(model, effectiveThinking),\n\t\t\t\t\t\t...(spec.modelSelection ? { modelSelection: spec.modelSelection } : {}),\n\t\t\t\t\t\tmodelCandidates: buildModelCandidates(primaryModel, undefined, availableModels, ctx.currentModelProvider, { scope: ctx.modelScope }).map((candidate) =>\n\t\t\t\t\t\t\tapplyThinkingSuffix(candidate, effectiveThinking, params.thinkingOverride !== undefined),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\tsystemPromptMode: \"append\",\n\t\t\t\t\t\tinheritProjectContext: true,\n\t\t\t\t\t\tinheritSkills: false,\n\t\t\t\t\t\tskills: resolvedSkills.map((r) => r.name),\n\t\t\t\t\t\toutputPath,\n\t\t\t\t\t\toutputMode,\n\t\t\t\t\t\tsessionFile,\n\t\t\t\t\t\tmaxSubagentDepth,\n\t\t\t\t\t\twaitToolEnabled: params.waitToolEnabled,\n\t\t\t\t\t\teffectiveAcceptance: resolvedAcceptance,\n\t\t\t\t\t\t...(resolvedToolBudget.budget ? { toolBudget: resolvedToolBudget.budget } : {}),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tresultPath: inheritedNestedRoute ? nestedResultsPath(inheritedNestedRoute.rootRunId, id) : path.join(RESULTS_DIR, `${id}.json`),\n\t\t\t\tcwd: runnerCwd,\n\t\t\t\tplaceholder: \"{previous}\",\n\t\t\t\tmaxOutput,\n\t\t\t\tartifactsDir: artifactConfig.enabled ? artifactsDir : undefined,\n\t\t\t\tartifactConfig,\n\t\t\t\tshare: shareEnabled,\n\t\t\t\tsessionDir: resolvedSessionDir,\n\t\t\t\tasyncDir,\n\t\t\t\tsessionId: ctx.currentSessionId,\n\t\t\t\tpiPackageRoot,\n\t\t\t\tpiArgv1: process.argv[1],\n\t\t\t\tworktreeSetupHook,\n\t\t\t\tworktreeSetupHookTimeoutMs,\n\t\t\t\tworktreeBaseDir,\n\t\t\t\tcontrolConfig,\n\t\t\t\ttimeoutMs,\n\t\t\t\tdeadlineAt,\n\t\t\t\tturnBudget: params.turnBudget,\n\t\t\t\ttoolBudget: params.toolBudget,\n\t\t\t\tcontrolIntercomTarget,\n\t\t\t\tchildIntercomTargets: childIntercomTarget ? [childIntercomTarget(spec.childId, 0)] : undefined,\n\t\t\t\tresultMode: \"single\",\n\t\t\t\t...(params.revivalLease ? { revivalLease: params.revivalLease } : {}),\n\t\t\t\tnestedRoute: nestedRoute ?? inheritedNestedRoute,\n\t\t\t\tnestedSelf: inheritedNestedRoute && nestedAddress ? {\n\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\tdepth: nestedAddress.depth,\n\t\t\t\t\tpath: nestedAddress.path,\n\t\t\t\t} : undefined,\n\t\t\t},\n\t\t\tid,\n\t\t\trunnerCwd,\n\t\t);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn formatAsyncStartError(\"single\", `Failed to start async run '${id}': ${message}`);\n\t}\n\n\tif (spawnResult.error) {\n\t\treturn formatAsyncStartError(\"single\", `Failed to start async run '${id}': ${spawnResult.error}`);\n\t}\n\n\tif (spawnResult.pid) {\n\t\tif (inheritedNestedRoute && nestedAddress) {\n\t\t\tconst now = Date.now();\n\t\t\ttry {\n\t\t\t\twriteNestedEvent(inheritedNestedRoute, {\n\t\t\t\t\ttype: \"subagent.nested.started\",\n\t\t\t\t\tts: now,\n\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\tchild: {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tparentRunId: nestedAddress.parentRunId,\n\t\t\t\t\t\tparentStepIndex: nestedAddress.parentStepIndex,\n\t\t\t\t\t\tdepth: nestedAddress.depth,\n\t\t\t\t\t\tpath: nestedAddress.path,\n\t\t\t\t\t\tasyncDir,\n\t\t\t\t\t\tpid: spawnResult.pid,\n\t\t\t\t\t\townerIntercomTarget: process.env.PI_SUBAGENT_INTERCOM_SESSION_NAME,\n\t\t\t\t\t\tleafIntercomTarget: childIntercomTarget?.(agent, 0),\n\t\t\t\t\t\tintercomTarget: childIntercomTarget?.(agent, 0),\n\t\t\t\t\t\townerState: \"live\",\n\t\t\t\t\t\tmode: \"single\",\n\t\t\t\t\t\tstate: \"running\",\n\t\t\t\t\t\tagent,\n\t\t\t\t\t\tagents: [agent],\n\t\t\t\t\t\tchainStepCount: 1,\n\t\t\t\t\t\t...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),\n\t\t\t\t\t\t...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),\n\t\t\t\t\t\tstartedAt: now,\n\t\t\t\t\t\tlastUpdate: now,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Failed to emit nested async start event:\", error);\n\t\t\t}\n\t\t}\n\t\tctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {\n\t\t\tlifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,\n\t\t\tid,\n\t\t\tpid: spawnResult.pid,\n\t\t\tsessionId: ctx.currentSessionId,\n\t\t\tmode: \"single\",\n\t\t\tagent,\n\t\t\ttask: task?.slice(0, 50),\n\t\t\tgoal: (params.goal ?? task).slice(0, 120),\n\t\t\tcwd: runnerCwd,\n\t\t\tasyncDir,\n\t\t\t...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}),\n\t\t\t...(initialTurnBudget ? { turnBudget: initialTurnBudget } : {}),\n\t\t\tnestedRoute,\n\t\t});\n\t}\n\n\treturn {\n\t\tcontent: [{ type: \"text\", text: formatAsyncStartedMessage(`Async: ${agent} [${id}]`) }],\n\t\tdetails: { mode: \"single\", runId: id, results: [], asyncId: id, asyncDir, ...(timeoutMs !== undefined ? { timeoutMs, deadlineAt } : {}), ...(params.turnBudget ? { turnBudget: params.turnBudget } : {}), ...(params.toolBudget ? { toolBudget: params.toolBudget } : {}) },\n\t};\n}\n"]}
@@ -16,7 +16,7 @@ import { buildChainInstructions, isDynamicParallelStep, isParallelStep, resolveS
16
16
  import { resolvePiPackageRoot } from "../shared/pi-spawn.js";
17
17
  import { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from "../../agents/skills.js";
18
18
  import { PI_CODING_AGENT_PACKAGE_ROOT_ENV, resolveChildCwd } from "../../shared/utils.js";
19
- import { buildModelCandidates, resolveEffectiveSubagentModel, resolveSubagentModelOverride } from "../shared/model-fallback.js";
19
+ import { buildModelCandidates, resolveRequiredTierModel } from "../shared/model-fallback.js";
20
20
  import { resolveEffectiveThinking } from "../../shared/model-info.js";
21
21
  import { resolveExpectedWorktreeAgentCwd } from "../shared/worktree.js";
22
22
  import { buildWorkflowGraphSnapshot } from "../shared/workflow-graph.js";
@@ -437,7 +437,7 @@ export function buildAsyncRunnerSteps(id, params) {
437
437
  const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, {
438
438
  tools: spec.effectivePermissions === "read-only" ? ["read", "grep", "find", "ls", "bash"] : undefined,
439
439
  });
440
- const primaryModel = resolveEffectiveSubagentModel(spec.model, undefined, ctx.currentModel, availableModels, ctx.currentModelProvider, { scope: ctx.modelScope });
440
+ const primaryModel = resolveRequiredTierModel(spec.tier, availableModels, ctx.currentModelProvider);
441
441
  const thinkingOverride = flatIndex === undefined ? undefined : thinkingOverridesByFlatIndex?.[flatIndex];
442
442
  const effectiveThinking = thinkingOverride;
443
443
  const model = applyThinkingSuffix(primaryModel, effectiveThinking, thinkingOverride !== undefined);
@@ -447,6 +447,7 @@ export function buildAsyncRunnerSteps(id, params) {
447
447
  childId: spec.childId,
448
448
  description: spec.description,
449
449
  permissions: spec.effectivePermissions,
450
+ tier: spec.tier,
450
451
  agent: spec.description,
451
452
  task,
452
453
  phase: s.phase,
@@ -456,6 +457,7 @@ export function buildAsyncRunnerSteps(id, params) {
456
457
  cwd: stepCwd,
457
458
  model,
458
459
  thinking: resolveEffectiveThinking(model, effectiveThinking),
460
+ ...(spec.modelSelection ? { modelSelection: spec.modelSelection } : {}),
459
461
  modelCandidates: buildModelCandidates(primaryModel, undefined, availableModels, ctx.currentModelProvider, { scope: ctx.modelScope }).map((candidate) => applyThinkingSuffix(candidate, effectiveThinking, thinkingOverride !== undefined)),
460
462
  systemPrompt,
461
463
  systemPromptMode: "append",
@@ -861,7 +863,7 @@ export function executeAsyncSingle(id, params) {
861
863
  if (validationError)
862
864
  return formatAsyncStartError("single", validationError);
863
865
  const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, childToolShape);
864
- const primaryModel = resolveSubagentModelOverride(params.modelOverride ?? spec.model, ctx.currentModel, availableModels, ctx.currentModelProvider);
866
+ const primaryModel = resolveRequiredTierModel(spec.tier, availableModels, ctx.currentModelProvider);
865
867
  const effectiveThinking = params.thinkingOverride;
866
868
  const model = applyThinkingSuffix(primaryModel, effectiveThinking, params.thinkingOverride !== undefined);
867
869
  const toolBudgetInput = params.toolBudget ?? spec.toolBudget ?? params.configToolBudget;
@@ -885,7 +887,7 @@ export function executeAsyncSingle(id, params) {
885
887
  async: true,
886
888
  });
887
889
  const recoveryDescriptor = {
888
- version: 3,
890
+ version: 4,
889
891
  lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
890
892
  sourceRunId: id,
891
893
  childId: spec.childId,
@@ -895,7 +897,9 @@ export function executeAsyncSingle(id, params) {
895
897
  ...(sessionFile ? { sessionFile } : {}),
896
898
  cwd: runnerCwd,
897
899
  ...(model ? { model } : {}),
900
+ tier: spec.tier,
898
901
  ...(effectiveThinking ? { thinking: resolveEffectiveThinking(model, effectiveThinking) } : {}),
902
+ ...(spec.modelSelection ? { modelSelection: spec.modelSelection } : {}),
899
903
  ...(resolvedSkills.length ? { skills: resolvedSkills.map((skill) => skill.name) } : {}),
900
904
  ...(outputPath ? { outputPath } : {}),
901
905
  outputMode,
@@ -933,6 +937,7 @@ export function executeAsyncSingle(id, params) {
933
937
  cwd: runnerCwd,
934
938
  model,
935
939
  thinking: resolveEffectiveThinking(model, effectiveThinking),
940
+ ...(spec.modelSelection ? { modelSelection: spec.modelSelection } : {}),
936
941
  modelCandidates: buildModelCandidates(primaryModel, undefined, availableModels, ctx.currentModelProvider, { scope: ctx.modelScope }).map((candidate) => applyThinkingSuffix(candidate, effectiveThinking, params.thinkingOverride !== undefined)),
937
942
  systemPrompt,
938
943
  systemPromptMode: "append",