@ashx-j/lunr-dev 0.2.19-dev.10.1 → 0.2.25-dev.13.1

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 (690) hide show
  1. package/CHANGELOG.md +60 -2
  2. package/README.md +2 -2
  3. package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
  4. package/dist/builtin-extensions/ashxj-tui.js +2 -2
  5. package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
  6. package/dist/builtin-extensions/index.d.ts.map +1 -1
  7. package/dist/builtin-extensions/index.js +1 -2
  8. package/dist/builtin-extensions/index.js.map +1 -1
  9. package/dist/builtin-extensions/lunr-browser.d.ts +9 -0
  10. package/dist/builtin-extensions/lunr-browser.d.ts.map +1 -0
  11. package/dist/builtin-extensions/lunr-browser.js +169 -0
  12. package/dist/builtin-extensions/lunr-browser.js.map +1 -0
  13. package/dist/builtin-extensions/lunr-computer-use.d.ts.map +1 -1
  14. package/dist/builtin-extensions/lunr-computer-use.js +15 -14
  15. package/dist/builtin-extensions/lunr-computer-use.js.map +1 -1
  16. package/dist/builtin-extensions/lunr-plan-tools.d.ts +7 -7
  17. package/dist/builtin-extensions/lunr-plan-tools.d.ts.map +1 -1
  18. package/dist/builtin-extensions/lunr-plan-tools.js +12 -12
  19. package/dist/builtin-extensions/lunr-plan-tools.js.map +1 -1
  20. package/dist/builtin-extensions/lunr-todos.d.ts +6 -5
  21. package/dist/builtin-extensions/lunr-todos.d.ts.map +1 -1
  22. package/dist/builtin-extensions/lunr-todos.js +24 -7
  23. package/dist/builtin-extensions/lunr-todos.js.map +1 -1
  24. package/dist/builtin-extensions/pi-intercom/broker/spawn.d.ts +6 -4
  25. package/dist/builtin-extensions/pi-intercom/broker/spawn.d.ts.map +1 -1
  26. package/dist/builtin-extensions/pi-intercom/broker/spawn.js +114 -61
  27. package/dist/builtin-extensions/pi-intercom/broker/spawn.js.map +1 -1
  28. package/dist/builtin-extensions/pi-intercom/index.d.ts.map +1 -1
  29. package/dist/builtin-extensions/pi-intercom/index.js +365 -351
  30. package/dist/builtin-extensions/pi-intercom/index.js.map +1 -1
  31. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.d.ts.map +1 -1
  32. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js +1 -0
  33. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js.map +1 -1
  34. package/dist/builtin-extensions/pi-mcp-adapter/index.d.ts.map +1 -1
  35. package/dist/builtin-extensions/pi-mcp-adapter/index.js +1 -1
  36. package/dist/builtin-extensions/pi-mcp-adapter/index.js.map +1 -1
  37. package/dist/builtin-extensions/pi-subagents/src/extension/control-notices.d.ts +1 -1
  38. package/dist/builtin-extensions/pi-subagents/src/extension/control-notices.d.ts.map +1 -1
  39. package/dist/builtin-extensions/pi-subagents/src/extension/control-notices.js +5 -1
  40. package/dist/builtin-extensions/pi-subagents/src/extension/control-notices.js.map +1 -1
  41. package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.d.ts.map +1 -1
  42. package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.js +2 -2
  43. package/dist/builtin-extensions/pi-subagents/src/extension/fanout-child.js.map +1 -1
  44. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts +9 -7
  45. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
  46. package/dist/builtin-extensions/pi-subagents/src/extension/index.js +143 -59
  47. package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
  48. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts +18 -8
  49. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
  50. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +39 -14
  51. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
  52. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts +5 -3
  53. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts.map +1 -1
  54. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js +32 -17
  55. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
  56. package/dist/builtin-extensions/pi-subagents/src/intercom/communication.d.ts +17 -0
  57. package/dist/builtin-extensions/pi-subagents/src/intercom/communication.d.ts.map +1 -0
  58. package/dist/builtin-extensions/pi-subagents/src/intercom/communication.js +45 -0
  59. package/dist/builtin-extensions/pi-subagents/src/intercom/communication.js.map +1 -0
  60. package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.d.ts +2 -0
  61. package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.d.ts.map +1 -1
  62. package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.js +10 -14
  63. package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.js.map +1 -1
  64. package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.d.ts +12 -2
  65. package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.d.ts.map +1 -1
  66. package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js +401 -58
  67. package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js.map +1 -1
  68. package/dist/builtin-extensions/pi-subagents/src/intercom/result-intercom.d.ts +1 -0
  69. package/dist/builtin-extensions/pi-subagents/src/intercom/result-intercom.d.ts.map +1 -1
  70. package/dist/builtin-extensions/pi-subagents/src/intercom/result-intercom.js +1 -1
  71. package/dist/builtin-extensions/pi-subagents/src/intercom/result-intercom.js.map +1 -1
  72. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.d.ts +29 -0
  73. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.d.ts.map +1 -0
  74. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.js +184 -0
  75. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.js.map +1 -0
  76. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.d.ts +91 -0
  77. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.d.ts.map +1 -0
  78. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.js +542 -0
  79. package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.js.map +1 -0
  80. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts +13 -1
  81. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts.map +1 -1
  82. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js +42 -12
  83. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js.map +1 -1
  84. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.d.ts.map +1 -1
  85. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.js +3 -2
  86. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.js.map +1 -1
  87. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.d.ts +2 -1
  88. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.d.ts.map +1 -1
  89. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js +35 -8
  90. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js.map +1 -1
  91. package/dist/builtin-extensions/pi-subagents/src/runs/background/auto-drain.d.ts +1 -0
  92. package/dist/builtin-extensions/pi-subagents/src/runs/background/auto-drain.d.ts.map +1 -1
  93. package/dist/builtin-extensions/pi-subagents/src/runs/background/auto-drain.js +2 -1
  94. package/dist/builtin-extensions/pi-subagents/src/runs/background/auto-drain.js.map +1 -1
  95. package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.d.ts +7 -3
  96. package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.d.ts.map +1 -1
  97. package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.js +26 -4
  98. package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.js.map +1 -1
  99. package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.d.ts +1 -0
  100. package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.d.ts.map +1 -1
  101. package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.js +55 -38
  102. package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.js.map +1 -1
  103. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts +100 -0
  104. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts.map +1 -1
  105. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js +47 -32
  106. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js.map +1 -1
  107. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.d.ts +6 -6
  108. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.d.ts.map +1 -1
  109. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.js +75 -5
  110. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.js.map +1 -1
  111. package/dist/builtin-extensions/pi-subagents/src/runs/background/top-level-async.d.ts +15 -2
  112. package/dist/builtin-extensions/pi-subagents/src/runs/background/top-level-async.d.ts.map +1 -1
  113. package/dist/builtin-extensions/pi-subagents/src/runs/background/top-level-async.js +14 -4
  114. package/dist/builtin-extensions/pi-subagents/src/runs/background/top-level-async.js.map +1 -1
  115. package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.d.ts.map +1 -1
  116. package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js +43 -4
  117. package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js.map +1 -1
  118. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.d.ts +1 -0
  119. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.d.ts.map +1 -1
  120. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js +26 -9
  121. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js.map +1 -1
  122. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts.map +1 -1
  123. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js +4 -3
  124. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js.map +1 -1
  125. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts +0 -1
  126. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
  127. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +94 -25
  128. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
  129. package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.d.ts +2 -0
  130. package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.d.ts.map +1 -1
  131. package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.js +75 -18
  132. package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.js.map +1 -1
  133. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts +1 -1
  134. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts.map +1 -1
  135. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js +1 -1
  136. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js.map +1 -1
  137. package/dist/builtin-extensions/pi-subagents/src/runs/shared/completion-guard.d.ts +1 -1
  138. package/dist/builtin-extensions/pi-subagents/src/runs/shared/completion-guard.d.ts.map +1 -1
  139. package/dist/builtin-extensions/pi-subagents/src/runs/shared/completion-guard.js +1 -1
  140. package/dist/builtin-extensions/pi-subagents/src/runs/shared/completion-guard.js.map +1 -1
  141. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts +13 -1
  142. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts.map +1 -1
  143. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js +67 -11
  144. package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js.map +1 -1
  145. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts +1 -0
  146. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.d.ts.map +1 -1
  147. package/dist/builtin-extensions/pi-subagents/src/runs/shared/parallel-utils.js.map +1 -1
  148. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts +5 -0
  149. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts.map +1 -1
  150. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js +25 -15
  151. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js.map +1 -1
  152. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-control.d.ts +1 -0
  153. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-control.d.ts.map +1 -1
  154. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-control.js +3 -0
  155. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-control.js.map +1 -1
  156. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.d.ts.map +1 -1
  157. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.js +17 -5
  158. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.js.map +1 -1
  159. package/dist/builtin-extensions/pi-subagents/src/runs/shared/task-intent.d.ts +2 -2
  160. package/dist/builtin-extensions/pi-subagents/src/runs/shared/task-intent.d.ts.map +1 -1
  161. package/dist/builtin-extensions/pi-subagents/src/runs/shared/task-intent.js +5 -10
  162. package/dist/builtin-extensions/pi-subagents/src/runs/shared/task-intent.js.map +1 -1
  163. package/dist/builtin-extensions/pi-subagents/src/shared/async-guidance.d.ts +2 -0
  164. package/dist/builtin-extensions/pi-subagents/src/shared/async-guidance.d.ts.map +1 -0
  165. package/dist/builtin-extensions/pi-subagents/src/shared/async-guidance.js +3 -0
  166. package/dist/builtin-extensions/pi-subagents/src/shared/async-guidance.js.map +1 -0
  167. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.d.ts +3 -0
  168. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.d.ts.map +1 -1
  169. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js +70 -13
  170. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js.map +1 -1
  171. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.d.ts +12 -1
  172. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.d.ts.map +1 -1
  173. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.js +21 -2
  174. package/dist/builtin-extensions/pi-subagents/src/shared/formatters.js.map +1 -1
  175. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +23 -4
  176. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
  177. package/dist/builtin-extensions/pi-subagents/src/shared/types.js +1 -1
  178. package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
  179. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.d.ts.map +1 -1
  180. package/dist/builtin-extensions/pi-subagents/src/slash/delegation-adapters.js.map +1 -1
  181. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.d.ts +7 -0
  182. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.d.ts.map +1 -1
  183. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js +11 -7
  184. package/dist/builtin-extensions/pi-subagents/src/slash/prompt-workflows.js.map +1 -1
  185. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts +6 -0
  186. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts.map +1 -1
  187. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js +46 -29
  188. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js.map +1 -1
  189. package/dist/builtin-extensions/pi-subagents/src/tui/communication.d.ts +18 -0
  190. package/dist/builtin-extensions/pi-subagents/src/tui/communication.d.ts.map +1 -0
  191. package/dist/builtin-extensions/pi-subagents/src/tui/communication.js +48 -0
  192. package/dist/builtin-extensions/pi-subagents/src/tui/communication.js.map +1 -0
  193. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +46 -4
  194. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
  195. package/dist/builtin-extensions/pi-subagents/src/tui/render.js +407 -450
  196. package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
  197. package/dist/builtin-extensions/pi-subagents/src/watchdog/register-main.d.ts.map +1 -1
  198. package/dist/builtin-extensions/pi-subagents/src/watchdog/register-main.js +1 -1
  199. package/dist/builtin-extensions/pi-subagents/src/watchdog/register-main.js.map +1 -1
  200. package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.d.ts +2 -13
  201. package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.d.ts.map +1 -1
  202. package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.js +5 -91
  203. package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.js.map +1 -1
  204. package/dist/builtin-extensions/pi-web-access/index.d.ts.map +1 -1
  205. package/dist/builtin-extensions/pi-web-access/index.js +11 -7
  206. package/dist/builtin-extensions/pi-web-access/index.js.map +1 -1
  207. package/dist/cli/args.d.ts.map +1 -1
  208. package/dist/cli/args.js +2 -1
  209. package/dist/cli/args.js.map +1 -1
  210. package/dist/cli/install-cli.d.ts.map +1 -1
  211. package/dist/cli/install-cli.js +15 -45
  212. package/dist/cli/install-cli.js.map +1 -1
  213. package/dist/core/agent-session-runtime.d.ts +9 -0
  214. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  215. package/dist/core/agent-session-runtime.js +126 -29
  216. package/dist/core/agent-session-runtime.js.map +1 -1
  217. package/dist/core/agent-session.d.ts +23 -1
  218. package/dist/core/agent-session.d.ts.map +1 -1
  219. package/dist/core/agent-session.js +255 -109
  220. package/dist/core/agent-session.js.map +1 -1
  221. package/dist/core/browser/network.d.ts +9 -0
  222. package/dist/core/browser/network.d.ts.map +1 -0
  223. package/dist/core/browser/network.js +146 -0
  224. package/dist/core/browser/network.js.map +1 -0
  225. package/dist/core/browser/runtime.d.ts +24 -0
  226. package/dist/core/browser/runtime.d.ts.map +1 -0
  227. package/dist/core/browser/runtime.js +289 -0
  228. package/dist/core/browser/runtime.js.map +1 -0
  229. package/dist/core/browser/schema.d.ts +16 -0
  230. package/dist/core/browser/schema.d.ts.map +1 -0
  231. package/dist/core/browser/schema.js +36 -0
  232. package/dist/core/browser/schema.js.map +1 -0
  233. package/dist/core/browser/settings.d.ts +8 -0
  234. package/dist/core/browser/settings.d.ts.map +1 -0
  235. package/dist/core/browser/settings.js +30 -0
  236. package/dist/core/browser/settings.js.map +1 -0
  237. package/dist/core/browser/setup.d.ts +2 -0
  238. package/dist/core/browser/setup.d.ts.map +1 -0
  239. package/dist/core/browser/setup.js +16 -0
  240. package/dist/core/browser/setup.js.map +1 -0
  241. package/dist/core/catalog-cache-scope.d.ts.map +1 -1
  242. package/dist/core/catalog-cache-scope.js +3 -1
  243. package/dist/core/catalog-cache-scope.js.map +1 -1
  244. package/dist/core/computer-use/image.d.ts +27 -0
  245. package/dist/core/computer-use/image.d.ts.map +1 -0
  246. package/dist/core/computer-use/image.js +72 -0
  247. package/dist/core/computer-use/image.js.map +1 -0
  248. package/dist/core/computer-use/policy.d.ts.map +1 -1
  249. package/dist/core/computer-use/policy.js +2 -6
  250. package/dist/core/computer-use/policy.js.map +1 -1
  251. package/dist/core/computer-use/schemas.d.ts +14 -10
  252. package/dist/core/computer-use/schemas.d.ts.map +1 -1
  253. package/dist/core/computer-use/schemas.js +27 -35
  254. package/dist/core/computer-use/schemas.js.map +1 -1
  255. package/dist/core/computer-use/workflow.d.ts +16 -8
  256. package/dist/core/computer-use/workflow.d.ts.map +1 -1
  257. package/dist/core/computer-use/workflow.js +337 -260
  258. package/dist/core/computer-use/workflow.js.map +1 -1
  259. package/dist/core/customize.d.ts +2 -0
  260. package/dist/core/customize.d.ts.map +1 -1
  261. package/dist/core/customize.js +17 -13
  262. package/dist/core/customize.js.map +1 -1
  263. package/dist/core/export-html/index.d.ts.map +1 -1
  264. package/dist/core/export-html/index.js +1 -1
  265. package/dist/core/export-html/index.js.map +1 -1
  266. package/dist/core/extensions/loader.d.ts.map +1 -1
  267. package/dist/core/extensions/loader.js +4 -0
  268. package/dist/core/extensions/loader.js.map +1 -1
  269. package/dist/core/extensions/runner.d.ts +1 -0
  270. package/dist/core/extensions/runner.d.ts.map +1 -1
  271. package/dist/core/extensions/runner.js +1 -1
  272. package/dist/core/extensions/runner.js.map +1 -1
  273. package/dist/core/extensions/types.d.ts +1 -1
  274. package/dist/core/extensions/types.d.ts.map +1 -1
  275. package/dist/core/extensions/types.js.map +1 -1
  276. package/dist/core/install-features.d.ts.map +1 -1
  277. package/dist/core/install-features.js +10 -8
  278. package/dist/core/install-features.js.map +1 -1
  279. package/dist/core/memory-cap.d.ts.map +1 -1
  280. package/dist/core/memory-cap.js +5 -3
  281. package/dist/core/memory-cap.js.map +1 -1
  282. package/dist/core/model-runtime.d.ts.map +1 -1
  283. package/dist/core/model-runtime.js +3 -2
  284. package/dist/core/model-runtime.js.map +1 -1
  285. package/dist/core/model-tiers.d.ts.map +1 -1
  286. package/dist/core/model-tiers.js +9 -6
  287. package/dist/core/model-tiers.js.map +1 -1
  288. package/dist/core/permissions.d.ts +17 -23
  289. package/dist/core/permissions.d.ts.map +1 -1
  290. package/dist/core/permissions.js +79 -146
  291. package/dist/core/permissions.js.map +1 -1
  292. package/dist/core/plan-mode.d.ts +10 -12
  293. package/dist/core/plan-mode.d.ts.map +1 -1
  294. package/dist/core/plan-mode.js +20 -24
  295. package/dist/core/plan-mode.js.map +1 -1
  296. package/dist/core/process-registry.d.ts.map +1 -1
  297. package/dist/core/process-registry.js +6 -4
  298. package/dist/core/process-registry.js.map +1 -1
  299. package/dist/core/runtime-bridges.d.ts.map +1 -1
  300. package/dist/core/runtime-bridges.js +2 -2
  301. package/dist/core/runtime-bridges.js.map +1 -1
  302. package/dist/core/runtime-scope.d.ts +11 -0
  303. package/dist/core/runtime-scope.d.ts.map +1 -0
  304. package/dist/core/runtime-scope.js +3 -0
  305. package/dist/core/runtime-scope.js.map +1 -0
  306. package/dist/core/sdk.d.ts.map +1 -1
  307. package/dist/core/sdk.js +26 -6
  308. package/dist/core/sdk.js.map +1 -1
  309. package/dist/core/session-handoff.d.ts +35 -0
  310. package/dist/core/session-handoff.d.ts.map +1 -0
  311. package/dist/core/session-handoff.js +214 -0
  312. package/dist/core/session-handoff.js.map +1 -0
  313. package/dist/core/session-manager.d.ts +20 -0
  314. package/dist/core/session-manager.d.ts.map +1 -1
  315. package/dist/core/session-manager.js +191 -22
  316. package/dist/core/session-manager.js.map +1 -1
  317. package/dist/core/session-ownership.d.ts +28 -0
  318. package/dist/core/session-ownership.d.ts.map +1 -0
  319. package/dist/core/session-ownership.js +138 -0
  320. package/dist/core/session-ownership.js.map +1 -0
  321. package/dist/core/session-retention.d.ts.map +1 -1
  322. package/dist/core/session-retention.js +11 -2
  323. package/dist/core/session-retention.js.map +1 -1
  324. package/dist/core/settings-manager.d.ts +24 -1
  325. package/dist/core/settings-manager.d.ts.map +1 -1
  326. package/dist/core/settings-manager.js +78 -1
  327. package/dist/core/settings-manager.js.map +1 -1
  328. package/dist/core/slash-commands.d.ts.map +1 -1
  329. package/dist/core/slash-commands.js +6 -4
  330. package/dist/core/slash-commands.js.map +1 -1
  331. package/dist/core/subagent-cancellation.d.ts +21 -0
  332. package/dist/core/subagent-cancellation.d.ts.map +1 -0
  333. package/dist/core/subagent-cancellation.js +53 -0
  334. package/dist/core/subagent-cancellation.js.map +1 -0
  335. package/dist/core/subagent-permission-inherit.d.ts +6 -10
  336. package/dist/core/subagent-permission-inherit.d.ts.map +1 -1
  337. package/dist/core/subagent-permission-inherit.js +14 -14
  338. package/dist/core/subagent-permission-inherit.js.map +1 -1
  339. package/dist/core/subagent-spinner-setting.d.ts +6 -0
  340. package/dist/core/subagent-spinner-setting.d.ts.map +1 -0
  341. package/dist/core/subagent-spinner-setting.js +12 -0
  342. package/dist/core/subagent-spinner-setting.js.map +1 -0
  343. package/dist/core/subagent-spinner.d.ts +4 -0
  344. package/dist/core/subagent-spinner.d.ts.map +1 -0
  345. package/dist/core/subagent-spinner.js +6 -0
  346. package/dist/core/subagent-spinner.js.map +1 -0
  347. package/dist/core/subagent-wait-interruption.d.ts +11 -0
  348. package/dist/core/subagent-wait-interruption.d.ts.map +1 -0
  349. package/dist/core/subagent-wait-interruption.js +19 -0
  350. package/dist/core/subagent-wait-interruption.js.map +1 -0
  351. package/dist/core/system-prompt.d.ts +2 -0
  352. package/dist/core/system-prompt.d.ts.map +1 -1
  353. package/dist/core/system-prompt.js +14 -4
  354. package/dist/core/system-prompt.js.map +1 -1
  355. package/dist/core/todo-settings.d.ts +5 -0
  356. package/dist/core/todo-settings.d.ts.map +1 -0
  357. package/dist/core/todo-settings.js +7 -0
  358. package/dist/core/todo-settings.js.map +1 -0
  359. package/dist/core/tools/bash.d.ts.map +1 -1
  360. package/dist/core/tools/bash.js +4 -4
  361. package/dist/core/tools/bash.js.map +1 -1
  362. package/dist/core/tools/edit.d.ts.map +1 -1
  363. package/dist/core/tools/edit.js +5 -3
  364. package/dist/core/tools/edit.js.map +1 -1
  365. package/dist/core/tools/find.d.ts.map +1 -1
  366. package/dist/core/tools/find.js +4 -4
  367. package/dist/core/tools/find.js.map +1 -1
  368. package/dist/core/tools/grep.d.ts.map +1 -1
  369. package/dist/core/tools/grep.js +4 -4
  370. package/dist/core/tools/grep.js.map +1 -1
  371. package/dist/core/tools/ls.d.ts.map +1 -1
  372. package/dist/core/tools/ls.js +4 -4
  373. package/dist/core/tools/ls.js.map +1 -1
  374. package/dist/core/tools/read.d.ts.map +1 -1
  375. package/dist/core/tools/read.js +4 -4
  376. package/dist/core/tools/read.js.map +1 -1
  377. package/dist/core/tools/render-utils.d.ts +14 -5
  378. package/dist/core/tools/render-utils.d.ts.map +1 -1
  379. package/dist/core/tools/render-utils.js +34 -7
  380. package/dist/core/tools/render-utils.js.map +1 -1
  381. package/dist/core/tools/write.d.ts.map +1 -1
  382. package/dist/core/tools/write.js +4 -4
  383. package/dist/core/tools/write.js.map +1 -1
  384. package/dist/core/usage-service.d.ts.map +1 -1
  385. package/dist/core/usage-service.js +5 -3
  386. package/dist/core/usage-service.js.map +1 -1
  387. package/dist/gateway/adapters/discord.d.ts +12 -1
  388. package/dist/gateway/adapters/discord.d.ts.map +1 -1
  389. package/dist/gateway/adapters/discord.js +114 -24
  390. package/dist/gateway/adapters/discord.js.map +1 -1
  391. package/dist/gateway/adapters/telegram.d.ts +4 -2
  392. package/dist/gateway/adapters/telegram.d.ts.map +1 -1
  393. package/dist/gateway/adapters/telegram.js +41 -11
  394. package/dist/gateway/adapters/telegram.js.map +1 -1
  395. package/dist/gateway/agent-bridge.d.ts +18 -4
  396. package/dist/gateway/agent-bridge.d.ts.map +1 -1
  397. package/dist/gateway/agent-bridge.js +305 -73
  398. package/dist/gateway/agent-bridge.js.map +1 -1
  399. package/dist/gateway/approval.d.ts +3 -6
  400. package/dist/gateway/approval.d.ts.map +1 -1
  401. package/dist/gateway/approval.js +62 -24
  402. package/dist/gateway/approval.js.map +1 -1
  403. package/dist/gateway/authz.d.ts +2 -0
  404. package/dist/gateway/authz.d.ts.map +1 -1
  405. package/dist/gateway/authz.js +13 -0
  406. package/dist/gateway/authz.js.map +1 -1
  407. package/dist/gateway/buttons.d.ts +3 -1
  408. package/dist/gateway/buttons.d.ts.map +1 -1
  409. package/dist/gateway/buttons.js +45 -20
  410. package/dist/gateway/buttons.js.map +1 -1
  411. package/dist/gateway/command.d.ts.map +1 -1
  412. package/dist/gateway/command.js +49 -4
  413. package/dist/gateway/command.js.map +1 -1
  414. package/dist/gateway/commands.d.ts +2 -0
  415. package/dist/gateway/commands.d.ts.map +1 -1
  416. package/dist/gateway/commands.js +52 -16
  417. package/dist/gateway/commands.js.map +1 -1
  418. package/dist/gateway/config.d.ts +6 -0
  419. package/dist/gateway/config.d.ts.map +1 -1
  420. package/dist/gateway/config.js +7 -0
  421. package/dist/gateway/config.js.map +1 -1
  422. package/dist/gateway/conversations.d.ts +14 -0
  423. package/dist/gateway/conversations.d.ts.map +1 -0
  424. package/dist/gateway/conversations.js +30 -0
  425. package/dist/gateway/conversations.js.map +1 -0
  426. package/dist/gateway/cron.d.ts +1 -1
  427. package/dist/gateway/cron.d.ts.map +1 -1
  428. package/dist/gateway/cron.js +2 -2
  429. package/dist/gateway/cron.js.map +1 -1
  430. package/dist/gateway/download.d.ts +2 -0
  431. package/dist/gateway/download.d.ts.map +1 -0
  432. package/dist/gateway/download.js +36 -0
  433. package/dist/gateway/download.js.map +1 -0
  434. package/dist/gateway/index.d.ts.map +1 -1
  435. package/dist/gateway/index.js +106 -47
  436. package/dist/gateway/index.js.map +1 -1
  437. package/dist/gateway/mobile-commands.d.ts +24 -0
  438. package/dist/gateway/mobile-commands.d.ts.map +1 -0
  439. package/dist/gateway/mobile-commands.js +423 -0
  440. package/dist/gateway/mobile-commands.js.map +1 -0
  441. package/dist/gateway/presenter.d.ts +27 -0
  442. package/dist/gateway/presenter.d.ts.map +1 -0
  443. package/dist/gateway/presenter.js +308 -0
  444. package/dist/gateway/presenter.js.map +1 -0
  445. package/dist/gateway/router.d.ts +6 -5
  446. package/dist/gateway/router.d.ts.map +1 -1
  447. package/dist/gateway/router.js +126 -43
  448. package/dist/gateway/router.js.map +1 -1
  449. package/dist/gateway/service.d.ts +46 -0
  450. package/dist/gateway/service.d.ts.map +1 -0
  451. package/dist/gateway/service.js +404 -0
  452. package/dist/gateway/service.js.map +1 -0
  453. package/dist/gateway/setup.d.ts +9 -0
  454. package/dist/gateway/setup.d.ts.map +1 -0
  455. package/dist/gateway/setup.js +202 -0
  456. package/dist/gateway/setup.js.map +1 -0
  457. package/dist/gateway/stream.d.ts +6 -5
  458. package/dist/gateway/stream.d.ts.map +1 -1
  459. package/dist/gateway/stream.js +24 -11
  460. package/dist/gateway/stream.js.map +1 -1
  461. package/dist/gateway/types.d.ts +4 -2
  462. package/dist/gateway/types.d.ts.map +1 -1
  463. package/dist/gateway/types.js.map +1 -1
  464. package/dist/index.d.ts +2 -0
  465. package/dist/index.d.ts.map +1 -1
  466. package/dist/index.js +2 -0
  467. package/dist/index.js.map +1 -1
  468. package/dist/main.d.ts.map +1 -1
  469. package/dist/main.js +3 -3
  470. package/dist/main.js.map +1 -1
  471. package/dist/modes/interactive/components/assistant-message.d.ts +19 -2
  472. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  473. package/dist/modes/interactive/components/assistant-message.js +90 -35
  474. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  475. package/dist/modes/interactive/components/copyable-text.d.ts +27 -0
  476. package/dist/modes/interactive/components/copyable-text.d.ts.map +1 -0
  477. package/dist/modes/interactive/components/copyable-text.js +156 -0
  478. package/dist/modes/interactive/components/copyable-text.js.map +1 -0
  479. package/dist/modes/interactive/components/custom-entry.d.ts +1 -0
  480. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
  481. package/dist/modes/interactive/components/custom-entry.js +8 -0
  482. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  483. package/dist/modes/interactive/components/custom-message.d.ts +1 -0
  484. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  485. package/dist/modes/interactive/components/custom-message.js +8 -0
  486. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  487. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  488. package/dist/modes/interactive/components/session-selector.js +16 -0
  489. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  490. package/dist/modes/interactive/components/settings-selector.d.ts +16 -1
  491. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  492. package/dist/modes/interactive/components/settings-selector.js +147 -4
  493. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  494. package/dist/modes/interactive/components/thinking-tail.d.ts +9 -2
  495. package/dist/modes/interactive/components/thinking-tail.d.ts.map +1 -1
  496. package/dist/modes/interactive/components/thinking-tail.js +43 -1
  497. package/dist/modes/interactive/components/thinking-tail.js.map +1 -1
  498. package/dist/modes/interactive/components/tool-execution.d.ts +5 -3
  499. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  500. package/dist/modes/interactive/components/tool-execution.js +55 -44
  501. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  502. package/dist/modes/interactive/extension-widget-order.d.ts +8 -0
  503. package/dist/modes/interactive/extension-widget-order.d.ts.map +1 -0
  504. package/dist/modes/interactive/extension-widget-order.js +37 -0
  505. package/dist/modes/interactive/extension-widget-order.js.map +1 -0
  506. package/dist/modes/interactive/interactive-mode.d.ts +11 -2
  507. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  508. package/dist/modes/interactive/interactive-mode.js +386 -155
  509. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  510. package/dist/modes/interactive/theme/theme.d.ts +1 -0
  511. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  512. package/dist/modes/interactive/theme/theme.js +23 -0
  513. package/dist/modes/interactive/theme/theme.js.map +1 -1
  514. package/dist/node-runtime/agent-session-services-MQUPZSIN.js +51 -0
  515. package/dist/node-runtime/{builtin-extensions-7STLFW3A.js → builtin-extensions-4GNDR6U3.js} +8 -6
  516. package/dist/node-runtime/{chunk-LTXUQJI4.js → chunk-24C5IAJ4.js} +1 -6
  517. package/dist/node-runtime/chunk-2BLXLDJR.js +144 -0
  518. package/dist/node-runtime/{chunk-RQ5DNUNG.js → chunk-2CMV4L24.js} +21 -124
  519. package/dist/node-runtime/{chunk-OTT6JMPU.js → chunk-2MI5OPMN.js} +17 -370
  520. package/dist/node-runtime/{chunk-W3CVH5RX.js → chunk-2TKODGBZ.js} +11 -6
  521. package/dist/node-runtime/{chunk-K72NVGUB.js → chunk-33SIKK3Y.js} +38 -164
  522. package/dist/node-runtime/{chunk-GZQHMEWL.js → chunk-3DKIWPKN.js} +19 -4
  523. package/dist/node-runtime/{chunk-5OLJGVCB.js → chunk-3ONQTOMR.js} +2 -2
  524. package/dist/node-runtime/{chunk-3GHXVUAK.js → chunk-3VEY2IYY.js} +1 -1
  525. package/dist/node-runtime/chunk-4ER2ZV4Z.js +537 -0
  526. package/dist/node-runtime/chunk-4EULYYR4.js +62 -0
  527. package/dist/node-runtime/{chunk-BKAZ6BKX.js → chunk-4SBQAI4T.js} +31 -31
  528. package/dist/node-runtime/{chunk-W7S2REEG.js → chunk-53ARRUHA.js} +785 -285
  529. package/dist/node-runtime/{chunk-ZSEZY3II.js → chunk-5Q4A37RB.js} +10 -4
  530. package/dist/node-runtime/{chunk-SWSN6HAB.js → chunk-5UZOPGE3.js} +1 -1
  531. package/dist/node-runtime/{chunk-LCACDWHJ.js → chunk-5Z5PCXGY.js} +263 -222
  532. package/dist/node-runtime/chunk-5ZH3ZFIZ.js +308 -0
  533. package/dist/node-runtime/chunk-7JIYPIQU.js +356 -0
  534. package/dist/node-runtime/{chunk-ZRDIMBEQ.js → chunk-AJ6R5VTV.js} +66 -91
  535. package/dist/node-runtime/chunk-ATIF3RX5.js +352 -0
  536. package/dist/node-runtime/chunk-BBUVIEZB.js +51 -0
  537. package/dist/node-runtime/chunk-CCCN2UCX.js +14 -0
  538. package/dist/node-runtime/chunk-CJS4KQFI.js +3412 -0
  539. package/dist/node-runtime/chunk-DO6PALE2.js +205 -0
  540. package/dist/node-runtime/{chunk-MUMMMTW4.js → chunk-DRJI7ZSC.js} +572 -401
  541. package/dist/node-runtime/{chunk-6SPPH4FY.js → chunk-E75WFZ33.js} +4 -4
  542. package/dist/node-runtime/{chunk-MJQDX3BA.js → chunk-EBB4BJW4.js} +3 -3
  543. package/dist/node-runtime/{chunk-5NWQCSKR.js → chunk-EOEAQIJV.js} +70 -3
  544. package/dist/node-runtime/chunk-EOPL2HMM.js +117 -0
  545. package/dist/node-runtime/chunk-H4K3JDRB.js +47 -0
  546. package/dist/node-runtime/{chunk-HRS4HMDX.js → chunk-HT2XEJNP.js} +19 -3
  547. package/dist/node-runtime/chunk-IMLCWLPI.js +9 -0
  548. package/dist/node-runtime/{chunk-FLYMHKCS.js → chunk-JJWZB7S3.js} +60 -48
  549. package/dist/node-runtime/chunk-KFFOQR4G.js +672 -0
  550. package/dist/node-runtime/chunk-L5LZUGT7.js +40 -0
  551. package/dist/node-runtime/chunk-LV6CEFW2.js +97 -0
  552. package/dist/node-runtime/{chunk-EHMBW7FA.js → chunk-LWYIVUGV.js} +5 -4
  553. package/dist/node-runtime/{chunk-T5GM5BFH.js → chunk-MFV2LOOX.js} +186 -2194
  554. package/dist/node-runtime/{chunk-5SQDLSZJ.js → chunk-MNRO3UCV.js} +2 -2
  555. package/dist/node-runtime/{chunk-JHYKXIMM.js → chunk-MPKSOJBT.js} +1 -1
  556. package/dist/node-runtime/{chunk-C4O2RSQQ.js → chunk-N4TUWAGA.js} +1 -1
  557. package/dist/node-runtime/{chunk-4SJWFTUP.js → chunk-NAY6UUQZ.js} +1 -1
  558. package/dist/node-runtime/chunk-NKH2QBKF.js +773 -0
  559. package/dist/node-runtime/chunk-O2AT4MEU.js +124 -0
  560. package/dist/node-runtime/chunk-OAR4TYZE.js +146 -0
  561. package/dist/node-runtime/{chunk-DDGMHUOW.js → chunk-OGJN3OZV.js} +2 -1
  562. package/dist/node-runtime/{chunk-MX3GJNXJ.js → chunk-PLGA743X.js} +23 -0
  563. package/dist/node-runtime/chunk-Q3FEOEDA.js +1364 -0
  564. package/dist/node-runtime/chunk-QFADHUQV.js +74 -0
  565. package/dist/node-runtime/chunk-RBZQU6TJ.js +27 -0
  566. package/dist/node-runtime/{chunk-MGSB2C3M.js → chunk-RVOQBXTA.js} +10 -6
  567. package/dist/node-runtime/{chunk-ISQDQIZN.js → chunk-RW4PYFNE.js} +14 -94
  568. package/dist/node-runtime/chunk-TP7K7YWS.js +2830 -0
  569. package/dist/node-runtime/{chunk-TAP7QTUT.js → chunk-TVLBDVTR.js} +46 -436
  570. package/dist/node-runtime/chunk-UAEOTO52.js +119 -0
  571. package/dist/node-runtime/{chunk-MGWCVY6Y.js → chunk-UDKX3PFN.js} +3 -3
  572. package/dist/node-runtime/{chunk-AY6CAJSL.js → chunk-UJOCPOMX.js} +6 -3
  573. package/dist/node-runtime/{chunk-J7QGQD45.js → chunk-UQUCFAJ3.js} +1 -1
  574. package/dist/node-runtime/chunk-US544NN6.js +13 -0
  575. package/dist/node-runtime/{chunk-7AFOFSDY.js → chunk-V3HK3FE7.js} +1 -1
  576. package/dist/node-runtime/{chunk-6UB6NKA3.js → chunk-VIVYOI7C.js} +130 -27
  577. package/dist/node-runtime/{chunk-5Q45AVQG.js → chunk-XHIRAZ26.js} +1 -1
  578. package/dist/node-runtime/chunk-YPHAIRZT.js +10 -0
  579. package/dist/node-runtime/{chunk-3RCWXWAY.js → chunk-YRUY57IN.js} +1 -1
  580. package/dist/node-runtime/cli-runtime.js +2 -2
  581. package/dist/node-runtime/command-PYBNGLPP.js +45 -0
  582. package/dist/node-runtime/{commands-LGR5VT5X.js → commands-EMBQQVVT.js} +13 -13
  583. package/dist/node-runtime/commands-Y2OUC2T7.js +37 -0
  584. package/dist/node-runtime/config-7DYMNJUO.js +20 -0
  585. package/dist/node-runtime/{customize-XEXL2DGQ.js → customize-VFJV3U6A.js} +2 -1
  586. package/dist/node-runtime/{direct-tool-executor-TDJS7TBD.js → direct-tool-executor-4D7UXYU4.js} +10 -10
  587. package/dist/node-runtime/{export-html-E4DT6ZJQ.js → export-html-ETFOKW3M.js} +4 -3
  588. package/dist/node-runtime/{extension-input-RV5N6APL.js → extension-input-7QODTFAS.js} +4 -4
  589. package/dist/node-runtime/{extension-selector-CPD5LWDD.js → extension-selector-T65JEDJ5.js} +4 -4
  590. package/dist/node-runtime/{extract-IUCVZCWC.js → extract-EQJE7FZZ.js} +2 -2
  591. package/dist/node-runtime/gateway-QENRQA5X.js +1476 -0
  592. package/dist/node-runtime/{gemini-search-NCIDF7NE.js → gemini-search-35OCRFLN.js} +1 -1
  593. package/dist/node-runtime/{gemini-url-context-OKIN7AIP.js → gemini-url-context-UQY3PHHW.js} +2 -2
  594. package/dist/node-runtime/index.js +120 -77
  595. package/dist/node-runtime/{init-EKE277AG.js → init-P5AUV77I.js} +5 -5
  596. package/dist/node-runtime/{install-cli-TH7IJJQQ.js → install-cli-KHAXYBOO.js} +21 -82
  597. package/dist/node-runtime/interactive-mode-IN77GQGX.js +74 -0
  598. package/dist/node-runtime/{interactive-view-N6F4KUIT.js → interactive-view-OMWDFGUQ.js} +10 -10
  599. package/dist/node-runtime/lunr-browser-VVPRWC3F.js +174 -0
  600. package/dist/node-runtime/lunr-computer-use-IAUNXSXH.js +138 -0
  601. package/dist/node-runtime/{lunr-cron-KKBOGAEF.js → lunr-cron-P6ZJGVEF.js} +22 -8
  602. package/dist/node-runtime/main.js +50 -35
  603. package/dist/node-runtime/{mcp-auth-flow-YL6RWPYG.js → mcp-auth-flow-QVLFVLEO.js} +2 -2
  604. package/dist/node-runtime/{memory-cap-3S4XRLNP.js → memory-cap-EL3KL4JJ.js} +2 -1
  605. package/dist/node-runtime/mobile-commands-WKFSFACZ.js +33 -0
  606. package/dist/node-runtime/model-runtime-YXGJS5OJ.js +16 -0
  607. package/dist/node-runtime/{model-tiers-NJLHUEGK.js → model-tiers-OU3U5CZG.js} +2 -1
  608. package/dist/node-runtime/{package-manager-cli-C4EJOO5Q.js → package-manager-cli-J337RKTI.js} +28 -19
  609. package/dist/node-runtime/{pi-intercom-EEMBGQID.js → pi-intercom-QM53RLTS.js} +114 -88
  610. package/dist/node-runtime/{pi-mcp-adapter-DPTJGAAL.js → pi-mcp-adapter-3PHF4KZ4.js} +9 -8
  611. package/dist/node-runtime/{pi-subagents-VKCLYIBY.js → pi-subagents-RCHPB6UK.js} +1476 -646
  612. package/dist/node-runtime/{pi-web-access-BV6DSZOP.js → pi-web-access-PNG35XW7.js} +11 -11
  613. package/dist/node-runtime/process-registry-PVJ44F7H.js +31 -0
  614. package/dist/node-runtime/{proxy-modes-R64LU6WZ.js → proxy-modes-5FAPSZEZ.js} +14 -14
  615. package/dist/node-runtime/rpc-entry.js +50 -35
  616. package/dist/node-runtime/{rpc-mode-SJNSOA4G.js → rpc-mode-SH7VB4RH.js} +2 -2
  617. package/dist/node-runtime/runtime-4VA6JKNF.js +373 -0
  618. package/dist/node-runtime/runtime-bridges-3CQHWVVY.js +21 -0
  619. package/dist/node-runtime/service-HGGU3STY.js +36 -0
  620. package/dist/node-runtime/session-handoff-IAFIK7QP.js +33 -0
  621. package/dist/node-runtime/{session-manager-QEMZBMTM.js → session-manager-TCEFDKBL.js} +2 -1
  622. package/dist/node-runtime/{session-selector-URVJLOTK.js → session-selector-HG5J4BDZ.js} +5 -4
  623. package/dist/node-runtime/{settings-manager-K6IPIQTI.js → settings-manager-HIBIUNBK.js} +13 -5
  624. package/dist/node-runtime/setup-JBKOLJ6F.js +18 -0
  625. package/dist/node-runtime/setup-YU5LKRL3.js +215 -0
  626. package/dist/node-runtime/{subagent-executor-EFLTO32A.js → subagent-executor-2BH76MMS.js} +242 -314
  627. package/dist/node-runtime/theme-WTJWZSGD.js +68 -0
  628. package/dist/node-runtime/trust-manager-6ZQANSBX.js +17 -0
  629. package/dist/node-runtime/{update-cli-I6OVDRPL.js → update-cli-TVTPVUNM.js} +7 -3
  630. package/dist/node-runtime/usage-service-LFB2SWYV.js +37 -0
  631. package/dist/node-runtime/{video-extract-ETA5RA7U.js → video-extract-OOZHR7SU.js} +2 -2
  632. package/dist/node-runtime/workflow-TVJNKKQP.js +509 -0
  633. package/dist/node-runtime/{youtube-extract-SRVGNN26.js → youtube-extract-FNPAUNHU.js} +6 -6
  634. package/dist/startup/interactive-view.d.ts.map +1 -1
  635. package/dist/startup/interactive-view.js +5 -1
  636. package/dist/startup/interactive-view.js.map +1 -1
  637. package/dist/utils/image-resize-core.d.ts +2 -0
  638. package/dist/utils/image-resize-core.d.ts.map +1 -1
  639. package/dist/utils/image-resize-core.js +10 -0
  640. package/dist/utils/image-resize-core.js.map +1 -1
  641. package/docs/browser.md +86 -0
  642. package/docs/computer-use.md +319 -268
  643. package/docs/extensions.md +2 -0
  644. package/docs/features.md +129 -30
  645. package/docs/index.md +1 -1
  646. package/docs/interactive-startup.md +2 -1
  647. package/docs/keybindings.md +4 -2
  648. package/docs/providers.md +6 -2
  649. package/docs/quickstart.md +2 -2
  650. package/docs/sessions.md +10 -0
  651. package/docs/settings.md +6 -3
  652. package/docs/tui.md +2 -0
  653. package/docs/usage.md +20 -4
  654. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  655. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  656. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  657. package/examples/extensions/gondolin/package-lock.json +2 -2
  658. package/examples/extensions/gondolin/package.json +1 -1
  659. package/examples/extensions/plan-mode/README.md +1 -1
  660. package/examples/extensions/sandbox/package-lock.json +2 -2
  661. package/examples/extensions/sandbox/package.json +1 -1
  662. package/examples/extensions/with-deps/package-lock.json +2 -2
  663. package/examples/extensions/with-deps/package.json +1 -1
  664. package/install-lock/package-lock.json +39 -25
  665. package/install-lock/package.json +2 -2
  666. package/npm-shrinkwrap.json +36 -22
  667. package/package.json +10 -7
  668. package/scripts/install-browser.mjs +20 -0
  669. package/dist/builtin-extensions/lunr-settings-tools.d.ts +0 -4
  670. package/dist/builtin-extensions/lunr-settings-tools.d.ts.map +0 -1
  671. package/dist/builtin-extensions/lunr-settings-tools.js +0 -120
  672. package/dist/builtin-extensions/lunr-settings-tools.js.map +0 -1
  673. package/dist/core/settings-tools-bridge.d.ts +0 -35
  674. package/dist/core/settings-tools-bridge.d.ts.map +0 -1
  675. package/dist/core/settings-tools-bridge.js +0 -56
  676. package/dist/core/settings-tools-bridge.js.map +0 -1
  677. package/dist/node-runtime/agent-session-services-RSGP5GDN.js +0 -39
  678. package/dist/node-runtime/chunk-EH2LJQPM.js +0 -64
  679. package/dist/node-runtime/chunk-HQCKFM2O.js +0 -56
  680. package/dist/node-runtime/chunk-JT6YCS5B.js +0 -5648
  681. package/dist/node-runtime/command-6UXQ6XZN.js +0 -13
  682. package/dist/node-runtime/gateway-3OLC4GQN.js +0 -2139
  683. package/dist/node-runtime/image-resize-6ZPBFMWW.js +0 -11
  684. package/dist/node-runtime/interactive-mode-S5M26CQ7.js +0 -59
  685. package/dist/node-runtime/lunr-computer-use-4X3KUNF4.js +0 -206
  686. package/dist/node-runtime/runtime-bridges-UJ5WJJLN.js +0 -14
  687. package/dist/node-runtime/workflow-SA34S4VX.js +0 -325
  688. package/dist/node-runtime/{chunk-U6C7VTR5.js → chunk-7IQGBKBJ.js} +3 -3
  689. package/dist/node-runtime/{mcp-panel-IIGMXQGP.js → mcp-panel-KTTFXJZ4.js} +3 -3
  690. package/dist/node-runtime/{src-GPFAU3N6.js → src-IVPNZ2BX.js} +6 -6
@@ -6,7 +6,6 @@ import {
6
6
  ASYNC_DIR,
7
7
  DEFAULT_ARTIFACT_CONFIG,
8
8
  INTERCOM_DETACH_REQUEST_EVENT,
9
- MAX_WIDGET_JOBS,
10
9
  POLL_INTERVAL_MS,
11
10
  RESULTS_DIR,
12
11
  SLASH_RESULT_TYPE,
@@ -17,6 +16,7 @@ import {
17
16
  SLASH_SUBAGENT_UPDATE_EVENT,
18
17
  SLASH_TEXT_RESULT_TYPE,
19
18
  SUBAGENT_ASYNC_COMPLETE_EVENT,
19
+ SUBAGENT_ASYNC_GUIDANCE,
20
20
  SUBAGENT_ASYNC_STARTED_EVENT,
21
21
  SUBAGENT_CHILD_ENV,
22
22
  SUBAGENT_CONTROL_EVENT,
@@ -27,12 +27,14 @@ import {
27
27
  SUBAGENT_PARENT_SESSION_ENV,
28
28
  SUBAGENT_RESULT_INTERCOM_EVENT,
29
29
  SUBAGENT_STEERING_NOTICE_EVENT,
30
+ SUPERVISOR_PROGRESS_TYPE,
31
+ SUPERVISOR_REQUEST_TYPE,
30
32
  TEMP_ROOT_DIR,
31
33
  WIDGET_KEY,
32
- aggregateStepStatus,
33
34
  assertJsonSchemaObject,
34
35
  attachNestedChildrenToResultChildren,
35
36
  buildSubagentResultIntercomPayload,
37
+ childRowLabel,
36
38
  cleanupAllArtifactDirs,
37
39
  cleanupOldArtifacts,
38
40
  cleanupOldChainDirs,
@@ -40,16 +42,15 @@ import {
40
42
  compactNestedResultChildren,
41
43
  deliverStopRequest,
42
44
  deliverSubagentResultIntercomEvent,
43
- flatToLogicalStepIndex,
44
45
  formatActivityLabel,
45
46
  formatAgentRunningLabel,
46
47
  formatAsyncRunProgressLabel,
47
48
  formatAsyncRunTranscript,
48
- formatControlNoticeMessage,
49
+ formatCompactModelBadge,
49
50
  formatDuration,
50
51
  formatModelSelection,
51
52
  formatNestedAggregate,
52
- formatParallelOutcome,
53
+ formatNestedResultLines,
53
54
  formatTokens,
54
55
  formatToolCall,
55
56
  formatUsage,
@@ -60,57 +61,89 @@ import {
60
61
  getSingleResultOutput,
61
62
  handleSubagentControlNotice,
62
63
  hasLiveNestedDescendants,
64
+ isAsyncSubagentExecution,
65
+ legacySupervisorBody,
63
66
  listAsyncRuns,
67
+ normalizeAsyncLaunchConfig,
64
68
  normalizeParallelGroups,
65
69
  projectNestedRegistryForRoot,
70
+ readCommunication,
66
71
  readStatus,
72
+ readSteerCapability,
67
73
  reconcileAsyncRun,
68
74
  reconcileNestedAsyncDescendants,
69
75
  registerMainWatchdog,
76
+ requestAsyncSteer,
70
77
  resolveAsyncRunLocation,
78
+ resolveCommunicationPeer,
71
79
  resolveCurrentSessionId,
80
+ resolveSubagentRequestParams,
72
81
  resolveSubagentResultStatus,
82
+ resolveSubagentRunId,
73
83
  resolveTurnBudgetConfig,
74
84
  resolveWaitToolConfig,
75
85
  resolveWatchPath,
76
86
  sanitizeChildDescription,
77
87
  sanitizeSummary,
78
88
  shortenPath,
89
+ stopRequestPath,
90
+ subagentLaunchRunsAsync,
79
91
  summarizeAsyncStatus,
80
92
  updateAsyncJobNestedProjection,
81
93
  validateAcceptanceInput,
82
94
  validateExecutionAcceptance,
83
95
  validateToolBudgetConfig,
84
96
  writeAtomicJson
85
- } from "./chunk-MUMMMTW4.js";
86
- import "./chunk-MGSB2C3M.js";
87
- import "./chunk-K72NVGUB.js";
97
+ } from "./chunk-DRJI7ZSC.js";
98
+ import {
99
+ formatControlNoticeMessage
100
+ } from "./chunk-OAR4TYZE.js";
101
+ import {
102
+ getSubagentSpinnerDefinition
103
+ } from "./chunk-US544NN6.js";
104
+ import "./chunk-5ZH3ZFIZ.js";
105
+ import "./chunk-RVOQBXTA.js";
106
+ import "./chunk-33SIKK3Y.js";
88
107
  import "./chunk-53YJI7JU.js";
89
- import "./chunk-GZQHMEWL.js";
90
- import "./chunk-ZCHMJ34K.js";
91
- import "./chunk-5Q45AVQG.js";
92
- import "./chunk-ZRDIMBEQ.js";
108
+ import "./chunk-3DKIWPKN.js";
109
+ import "./chunk-XHIRAZ26.js";
110
+ import "./chunk-5Q4A37RB.js";
111
+ import {
112
+ subagentCommunicationEnabled
113
+ } from "./chunk-EOEAQIJV.js";
114
+ import "./chunk-L5LZUGT7.js";
115
+ import "./chunk-2CMV4L24.js";
116
+ import "./chunk-URD2SLIT.js";
117
+ import {
118
+ createSubagentCancellation,
119
+ registerSubagentCancellation
120
+ } from "./chunk-BBUVIEZB.js";
121
+ import "./chunk-AJ6R5VTV.js";
93
122
  import "./chunk-M3LZLQW2.js";
94
- import "./chunk-5OLJGVCB.js";
123
+ import "./chunk-3ONQTOMR.js";
124
+ import "./chunk-2BLXLDJR.js";
125
+ import "./chunk-ZCHMJ34K.js";
95
126
  import "./chunk-FVDOXRUD.js";
96
- import "./chunk-ZSEZY3II.js";
127
+ import "./chunk-UJOCPOMX.js";
128
+ import "./chunk-IMLCWLPI.js";
97
129
  import "./chunk-RQ2Q5IYR.js";
130
+ import "./chunk-O2AT4MEU.js";
98
131
  import {
99
132
  keyText
100
- } from "./chunk-C4O2RSQQ.js";
133
+ } from "./chunk-N4TUWAGA.js";
101
134
  import {
102
135
  getMarkdownTheme
103
- } from "./chunk-MX3GJNXJ.js";
136
+ } from "./chunk-PLGA743X.js";
104
137
  import "./chunk-PCIGF2XK.js";
105
138
  import "./chunk-Q4Q6D4IY.js";
106
139
  import "./chunk-BRJX2PRC.js";
107
140
 
108
141
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/extension/index.js
109
- import { randomUUID as randomUUID3 } from "node:crypto";
110
- import * as fs9 from "node:fs";
142
+ import { randomUUID as randomUUID4 } from "node:crypto";
143
+ import * as fs10 from "node:fs";
111
144
  import * as os from "node:os";
112
- import * as path11 from "node:path";
113
- import { Box, Container as Container2, Spacer as Spacer2, Text as Text2, truncateToWidth as truncateToWidth2, visibleWidth as visibleWidth3, wrapTextWithAnsi as wrapTextWithAnsi2 } from "@ashx-j/lunr-tui";
145
+ import * as path12 from "node:path";
146
+ import { Box as Box2, Container as Container3, Spacer as Spacer2, Text as Text3, truncateToWidth as truncateToWidth2, visibleWidth as visibleWidth3, wrapTextWithAnsi as wrapTextWithAnsi2 } from "@ashx-j/lunr-tui";
114
147
 
115
148
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/tui/render.js
116
149
  import { Container, Markdown, Spacer, Text, visibleWidth } from "@ashx-j/lunr-tui";
@@ -172,7 +205,11 @@ function wrapPlainText(text, maxWidth) {
172
205
  }
173
206
  return lines;
174
207
  }
175
- var RUNNING_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"], STATIC_RUNNING_GLYPH = "\u25CF";
208
+ var STATIC_RUNNING_GLYPH = "\u25CF", SUBAGENT_PAINT_INTERVAL_MS = 80;
209
+ function selectedSubagentSpinner() {
210
+ let bridge = globalThis[/* @__PURE__ */ Symbol.for("@lunr/customize")];
211
+ return getSubagentSpinnerDefinition(bridge?.getSubagentSpinner?.() ?? "braille");
212
+ }
176
213
  function runningSeed(...values) {
177
214
  let seed;
178
215
  for (let value of values)
@@ -180,7 +217,14 @@ function runningSeed(...values) {
180
217
  return seed;
181
218
  }
182
219
  function runningGlyph(seed) {
183
- return seed === void 0 ? STATIC_RUNNING_GLYPH : RUNNING_FRAMES[Math.abs(seed) % RUNNING_FRAMES.length];
220
+ if (seed === void 0)
221
+ return STATIC_RUNNING_GLYPH;
222
+ let frames = selectedSubagentSpinner().frames;
223
+ return frames[Math.abs(seed) % frames.length];
224
+ }
225
+ function foregroundSpinnerFrame(timerFrame) {
226
+ let { interval } = selectedSubagentSpinner();
227
+ return Math.floor(Math.max(0, timerFrame) * SUBAGENT_PAINT_INTERVAL_MS / interval);
184
228
  }
185
229
  function progressRunningSeed(progress) {
186
230
  if (progress)
@@ -240,6 +284,16 @@ function statJoin(theme, parts) {
240
284
  function formatTokenStat(tokens) {
241
285
  return `${formatTokens(tokens)} token`;
242
286
  }
287
+ function usageTokenTotal(usage) {
288
+ return usage ? (usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0) : 0;
289
+ }
290
+ function compactResultTokens(result2) {
291
+ let progress = result2.progress || result2.progressSummary;
292
+ if (progress && progress.tokens > 0)
293
+ return progress.tokens;
294
+ let fromUsage = usageTokenTotal(result2.usage);
295
+ return fromUsage > 0 ? fromUsage : progress?.tokens ?? 0;
296
+ }
243
297
  function formatToolUseStat(count) {
244
298
  return `${count} tool use${count === 1 ? "" : "s"}`;
245
299
  }
@@ -250,7 +304,10 @@ function formatTotalCostStat(totalCost) {
250
304
  return totalCost.inputTokens && parts.push(`in:${formatTokens(totalCost.inputTokens)}`), totalCost.outputTokens && parts.push(`out:${formatTokens(totalCost.outputTokens)}`), totalCost.costUsd && parts.push(`$${totalCost.costUsd.toFixed(4)}`), parts.join(" ");
251
305
  }
252
306
  function liveDurationMs(progress, running, now) {
253
- return progress ? !running || progress.lastActivityAt === void 0 ? progress.durationMs : progress.durationMs + Math.max(0, now - progress.lastActivityAt) : 0;
307
+ if (!progress)
308
+ return 0;
309
+ let durationMs = progress.durationMs ?? 0;
310
+ return !running || progress.lastActivityAt === void 0 ? durationMs : durationMs + Math.max(0, now - progress.lastActivityAt);
254
311
  }
255
312
  function formatProgressStats(theme, progress, includeDuration = !0, options = {}) {
256
313
  if (!progress)
@@ -290,13 +347,17 @@ function resultStatusLine(result2, output) {
290
347
  function resultGlyph(result2, output, theme, running = result2.progress?.status === "running", seed = progressRunningSeed(result2.progress ?? result2.progressSummary), frame) {
291
348
  return running ? frame !== void 0 ? theme.fg("accent", runningGlyph((seed ?? 0) + frame)) : theme.fg("accent", runningGlyph(seed)) : result2.detached || result2.stopped || result2.interrupted ? theme.fg("warning", "\u25A0") : result2.exitCode !== 0 ? theme.fg("error", "\u2717") : hasEmptyTextOutputWithoutOutputTarget(result2.task, output) ? theme.fg("warning", "\u2713") : theme.fg("success", "\u2713");
292
349
  }
293
- function formatCompactStatsHangLine(progress, width, paint = (s) => s, prefix = " \u23BF ", now = Date.now(), running = !1) {
294
- let toolCount = progress?.toolCount ?? 0, tokens = progress?.tokens ?? 0, durationMs = liveDurationMs(progress, running, now), body = [
295
- formatToolUseStat(toolCount),
296
- formatTokenStat(tokens),
297
- durationMs > 0 ? formatDuration(durationMs) : "0ms"
298
- ].join(" \xB7 ");
299
- return truncLine(paint(`${prefix}${body}`), width);
350
+ function formatCompactRowStats(tokens, durationMs) {
351
+ return `${formatTokenStat(tokens)} \xB7 ${durationMs > 0 ? formatDuration(durationMs) : "0ms"}`;
352
+ }
353
+ function formatCompactSubagentRow(theme, width, parts) {
354
+ let stats = formatCompactRowStats(parts.tokens, parts.durationMs), body = [
355
+ `${parts.prefix ?? ""}${parts.glyph} ${themeBold(theme, parts.description)}`,
356
+ parts.modelBadge ? theme.fg("dim", parts.modelBadge) : "",
357
+ theme.fg("dim", stats),
358
+ parts.terminalStatus ? theme.fg("dim", parts.terminalStatus) : ""
359
+ ].filter(Boolean).join(` ${theme.fg("dim", "\xB7")} `);
360
+ return truncLine(body, width);
300
361
  }
301
362
  function widgetRenderKey(job) {
302
363
  return JSON.stringify({
@@ -350,14 +411,9 @@ function widgetStepsRunningSeed(steps) {
350
411
  function widgetJobRunningSeed(job) {
351
412
  return runningSeed(job.currentStep, job.runningSteps, widgetStepsRunningSeed(job.steps));
352
413
  }
353
- function widgetJobsRunningSeed(jobs) {
354
- let seed;
355
- for (let job of jobs)
356
- seed = runningSeed(seed, widgetJobRunningSeed(job));
357
- return seed;
358
- }
359
414
  function widgetAnimFrame(now = Date.now()) {
360
- return Math.floor(now / 80) % RUNNING_FRAMES.length;
415
+ let definition = selectedSubagentSpinner();
416
+ return Math.floor(now / definition.interval) % definition.frames.length;
361
417
  }
362
418
  function widgetStatusGlyph(job, theme, now = Date.now()) {
363
419
  return job.status === "running" ? theme.fg("accent", runningGlyph((widgetJobRunningSeed(job) ?? 0) + widgetAnimFrame(now))) : job.status === "queued" ? theme.fg("muted", "\u25E6") : job.status === "complete" ? theme.fg("success", "\u2713") : job.status === "paused" || job.status === "stopped" ? theme.fg("warning", "\u25A0") : theme.fg("error", "\u2717");
@@ -368,48 +424,6 @@ function widgetStepGlyph(status, theme, seed) {
368
424
  function widgetStepStatus(status, theme) {
369
425
  return status === "running" ? theme.fg("accent", "running") : status === "complete" || status === "completed" ? theme.fg("success", "complete") : status === "failed" ? theme.fg("error", "failed") : status === "paused" ? theme.fg("warning", "paused") : status === "stopped" ? theme.fg("warning", "stopped") : theme.fg("dim", status);
370
426
  }
371
- function widgetStepActivity(step, snapshotNow) {
372
- let facts = [];
373
- step.currentTool && step.currentToolStartedAt !== void 0 && snapshotNow !== void 0 ? facts.push(`${step.currentTool} ${formatDuration(Math.max(0, snapshotNow - step.currentToolStartedAt))}`) : step.currentTool && facts.push(step.currentTool), step.currentPath && facts.push(shortenPath(step.currentPath)), step.turnCount !== void 0 && facts.push(`${step.turnCount} turns`), step.toolCount !== void 0 && facts.push(`${step.toolCount} tools`), step.tokens?.total && facts.push(formatTokenStat(step.tokens.total));
374
- let activity = buildLiveStatusLine(step, snapshotNow);
375
- return activity && facts.length ? `${activity} \xB7 ${facts.join(" \xB7 ")}` : activity || facts.join(" \xB7 ");
376
- }
377
- function widgetChainDetails(job, theme, expanded = !1, width = getTermWidth()) {
378
- if (!job.steps?.length)
379
- return [];
380
- let total = job.chainStepCount ?? job.steps.length, lines = [];
381
- for (let span of buildAsyncChainStepSpans(total, job.steps.length, job.parallelGroups)) {
382
- let steps = job.steps.slice(span.start, span.start + span.count);
383
- if (span.isParallel) {
384
- let status = aggregateStepStatus(steps);
385
- lines.push(` ${widgetStepGlyph(status, theme, widgetStepsRunningSeed(steps))} Step ${span.stepIndex + 1}/${total}: ${themeBold(theme, "parallel group")} ${theme.fg("dim", "\xB7")} ${theme.fg("dim", formatParallelOutcome(steps, span.count))}`);
386
- continue;
387
- }
388
- let step = steps[0];
389
- if (!step) {
390
- lines.push(` ${theme.fg("dim", `\u25E6 Step ${span.stepIndex + 1}/${total}: pending`)}`);
391
- continue;
392
- }
393
- lines.push(...foregroundStyleWidgetStepLines(job, theme, step, "Step", span.stepIndex + 1, total, expanded, width));
394
- }
395
- return lines;
396
- }
397
- function widgetParallelAgentDetails(job, theme, expanded = !1, width = getTermWidth()) {
398
- if (!job.steps?.length)
399
- return [];
400
- if (job.mode !== "parallel" && job.mode !== "chain")
401
- return [];
402
- if (job.mode === "chain" && !job.activeParallelGroup && job.parallelGroups?.length)
403
- return widgetChainDetails(job, theme, expanded, width);
404
- let total = job.stepsTotal ?? job.steps.length, lines = [];
405
- for (let [index, step] of job.steps.entries()) {
406
- let marker = index === job.steps.length - 1 ? "\u2514" : "\u251C", activity = widgetStepActivity(step, job.updatedAt), itemTitle = job.mode === "parallel" || job.activeParallelGroup ? "Agent" : "Step", modelDisplay = modelThinkingBadge(theme, step.model, step.thinking, step.modelSelection);
407
- lines.push(` ${theme.fg("dim", `${marker} ${widgetStepGlyph(step.status, theme, widgetStepRunningSeed(step, index))} ${itemTitle} ${index + 1}/${total}: ${step.agent} \xB7 ${widgetStepStatus(step.status, theme)}${modelDisplay}${activity ? ` \xB7 ${activity}` : ""}`)}`);
408
- for (let nestedLine of formatNestedWidgetLines(step.children, theme, width, expanded, job.updatedAt, expanded ? 8 : 1))
409
- lines.push(` ${nestedLine}`);
410
- }
411
- return lines;
412
- }
413
427
  function parseParallelGroupAgentCount(label) {
414
428
  if (!label || !label.startsWith("[") || !label.endsWith("]"))
415
429
  return;
@@ -445,24 +459,16 @@ function buildChainStepSpans(details) {
445
459
  function isChainParallelGroupActive(details) {
446
460
  return details.mode !== "chain" || details.currentStepIndex === void 0 ? !1 : buildChainStepSpans(details).some((span) => span.stepIndex === details.currentStepIndex && span.isParallel);
447
461
  }
448
- function buildAsyncChainStepSpans(total, stepCount, parallelGroups = []) {
449
- let spans = [], flatIndex = 0;
450
- for (let stepIndex = 0; stepIndex < total; stepIndex++) {
451
- let group = parallelGroups.find((candidate) => candidate.stepIndex === stepIndex);
452
- if (group) {
453
- spans.push({ stepIndex, start: group.start, count: group.count, isParallel: !0 }), flatIndex = Math.max(flatIndex, group.start + group.count);
454
- continue;
455
- }
456
- spans.push({ stepIndex, start: flatIndex, count: flatIndex < stepCount ? 1 : 0, isParallel: !1 }), flatIndex++;
457
- }
458
- return spans;
459
- }
460
462
  function isDoneResult(result2) {
461
463
  let status = result2.progress?.status;
462
464
  return status === "completed" ? !0 : status === "running" || status === "pending" || result2.interrupted || result2.detached ? !1 : result2.exitCode === 0;
463
465
  }
464
466
  function workflowGraphHasStatus(details, statuses) {
465
- return details.workflowGraph?.nodes.some((node) => statuses.includes(node.status)) ?? !1;
467
+ let matches = (nodes) => nodes.some((node) => statuses.includes(node.status) || matches(node.children ?? []));
468
+ return matches(details.workflowGraph?.nodes ?? []);
469
+ }
470
+ function resultAtFlatIndex(details, flatIndex) {
471
+ return details.results.find((result2, arrayIndex) => (result2.progress?.index ?? result2.progressSummary?.index ?? arrayIndex) === flatIndex);
466
472
  }
467
473
  function buildChainRenderEntries(details, label) {
468
474
  if (details.mode !== "chain" || !label.hasParallelInChain || label.showActiveGroupOnly)
@@ -480,13 +486,17 @@ function buildChainRenderEntries(details, label) {
480
486
  });
481
487
  continue;
482
488
  }
483
- for (let index = span.start; index < span.start + span.count; index++)
489
+ for (let index = span.start; index < span.start + span.count; index++) {
490
+ let workflowStep = details.workflowGraph?.nodes.find((node) => node.stepIndex === span.stepIndex), workflowNode = workflowStep?.children?.find((node) => node.flatIndex === index) ?? (workflowStep?.flatIndex === index ? workflowStep : void 0), result2 = resultAtFlatIndex(details, index);
484
491
  entries.push({
485
492
  kind: "result",
486
493
  resultIndex: index,
487
494
  rowNumber: index + 1,
488
- agentName: details.results[index]?.agent ?? details.chainAgents?.[span.stepIndex] ?? `step-${span.stepIndex + 1}`
495
+ agentName: result2?.agent ?? workflowNode?.label ?? details.chainAgents?.[span.stepIndex] ?? `step-${span.stepIndex + 1}`,
496
+ status: workflowNode?.status ?? span.status,
497
+ error: workflowNode?.error ?? span.error
489
498
  });
499
+ }
490
500
  }
491
501
  return entries;
492
502
  }
@@ -551,38 +561,6 @@ function resultRowLabel(details, label, resultIndex, stepNumber) {
551
561
  }
552
562
  return label.itemTitle === "Agent" ? `Agent ${label.activeParallelGroup ? Math.max(1, stepNumber - label.groupStartIndex) : stepNumber}/${label.totalCount}` : `Step ${stepNumber}`;
553
563
  }
554
- function widgetStats(job, theme, now = Date.now()) {
555
- let parts = [], stepsTotal = job.stepsTotal ?? job.agents?.length ?? 1;
556
- if (job.activeParallelGroup) {
557
- let running = job.runningSteps ?? (job.status === "running" ? 1 : 0), done = job.completedSteps ?? (job.status === "complete" ? stepsTotal : 0);
558
- if (job.mode === "parallel")
559
- job.status === "running" && running > 0 && parts.push(formatAgentRunningLabel(running)), stepsTotal > 0 && parts.push(`${done}/${stepsTotal} done`);
560
- else {
561
- let logicalStep = (job.currentStep !== void 0 ? job.parallelGroups?.find((group) => job.currentStep >= group.start && job.currentStep < group.start + group.count) : job.parallelGroups?.find((group) => group.start === 0))?.stepIndex ?? job.currentStep ?? 0, total = job.chainStepCount ?? stepsTotal, groupParts = [`${done}/${stepsTotal} done`];
562
- job.status === "running" && running > 0 && groupParts.unshift(formatAgentRunningLabel(running)), parts.push(`step ${logicalStep + 1}/${total} \xB7 parallel group: ${groupParts.join(" \xB7 ")}`);
563
- }
564
- } else if (job.currentStep !== void 0)
565
- if (job.mode === "chain" && job.parallelGroups?.length) {
566
- let total = job.chainStepCount ?? stepsTotal;
567
- parts.push(`step ${flatToLogicalStepIndex(job.currentStep, total, job.parallelGroups) + 1}/${total}`);
568
- } else
569
- parts.push(`step ${job.currentStep + 1}/${stepsTotal}`);
570
- else stepsTotal > 1 && parts.push(`steps ${stepsTotal}`);
571
- if (job.toolCount !== void 0 && parts.push(formatToolUseStat(job.toolCount)), job.totalTokens?.total && parts.push(formatTokenStat(job.totalTokens.total)), job.startedAt !== void 0) {
572
- let end = job.status === "running" ? now : job.updatedAt;
573
- end !== void 0 && parts.push(`${job.status === "running" ? "" : "ran for "}${formatDuration(Math.max(0, end - job.startedAt))}`);
574
- }
575
- return statJoin(theme, parts);
576
- }
577
- function widgetStepStats(theme, step, now = Date.now()) {
578
- let running = step.status === "running", durationMs = step.durationMs !== void 0 ? step.durationMs + (running && step.lastActivityAt !== void 0 ? Math.max(0, now - step.lastActivityAt) : 0) : step.startedAt !== void 0 ? Math.max(0, (running ? now : step.endedAt ?? step.lastActivityAt ?? now) - step.startedAt) : void 0;
579
- return statJoin(theme, [
580
- step.turnCount !== void 0 ? `${step.turnCount} turns` : "",
581
- step.toolCount !== void 0 ? formatToolUseStat(step.toolCount) : "",
582
- step.tokens?.total ? formatTokenStat(step.tokens.total) : "",
583
- durationMs !== void 0 ? `${running ? "" : "ran for "}${formatDuration(durationMs)}` : ""
584
- ]);
585
- }
586
564
  function modelThinkingBadge(theme, model, thinking, selection) {
587
565
  let label = formatModelSelection(selection, model, thinking);
588
566
  return label ? theme.fg("dim", ` (${label})`) : "";
@@ -647,30 +625,28 @@ function formatNestedWidgetLines(children, theme, width, expanded, snapshotNow,
647
625
  };
648
626
  return append(children, 0, ""), lines.map((line) => truncLine(line, width));
649
627
  }
650
- function foregroundStyleWidgetStepLines(job, theme, step, itemTitle, index, total, expanded, width) {
651
- let status = widgetStepStatus(step.status, theme), stats = widgetStepStats(theme, step), modelDisplay = modelThinkingBadge(theme, step.model, step.thinking, step.modelSelection), lines = [` ${widgetStepGlyph(step.status, theme, widgetStepRunningSeed(step, index - 1))} ${itemTitle} ${index}/${total}: ${themeBold(theme, step.agent)} ${theme.fg("dim", "\xB7")} ${status}${modelDisplay}${stats ? ` ${theme.fg("dim", "\xB7")} ${stats}` : ""}`], activity = widgetStepActivityLine(step, width, expanded, job.updatedAt);
652
- activity && lines.push(` ${theme.fg("dim", `\u23BF ${activity}`)}`);
653
- for (let nestedLine of formatNestedWidgetLines(step.children, theme, width, expanded, job.updatedAt))
654
- lines.push(` ${nestedLine}`);
655
- if (step.status === "running" && (expanded || lines.push(` ${theme.fg("accent", liveDetailHintText())}`), expanded)) {
656
- let liveStatus = buildLiveStatusLine(step, job.updatedAt);
657
- liveStatus && liveStatus !== activity && lines.push(` ${theme.fg("accent", liveStatus)}`);
658
- for (let tool of step.recentTools?.slice(-3) ?? []) {
659
- let maxArgsLen = Math.max(40, width - 30), argsPreview = tool.args.length <= maxArgsLen ? tool.args : `${tool.args.slice(0, maxArgsLen)}...`;
660
- lines.push(` ${theme.fg("dim", `${tool.tool}${argsPreview ? `: ${argsPreview}` : ""}`)}`);
661
- }
662
- for (let line of step.recentOutput?.slice(-5) ?? [])
663
- lines.push(` ${theme.fg("dim", line)}`);
664
- }
665
- return lines;
628
+ function compactTerminalStatus(status) {
629
+ if (status === "failed")
630
+ return "failed";
631
+ if (status === "paused")
632
+ return "paused";
633
+ if (status === "stopped")
634
+ return "stopped";
635
+ if (status === "detached")
636
+ return "detached";
666
637
  }
667
638
  function compactJobProgress(job, step, now = Date.now()) {
668
- let running = (step?.status ?? job.status) === "running", startedAt = step?.startedAt ?? job.startedAt, endedAt = running ? now : step?.endedAt ?? step?.lastActivityAt ?? job.updatedAt ?? now, durationMs = step?.durationMs !== void 0 ? step.durationMs : startedAt !== void 0 ? Math.max(0, endedAt - startedAt) : 0;
669
- return {
670
- toolCount: step?.toolCount ?? job.toolCount ?? 0,
671
- tokens: step?.tokens?.total ?? job.totalTokens?.total ?? 0,
672
- durationMs
673
- };
639
+ let running = (step?.status ?? job.status) === "running", tokens = step?.tokens?.total ?? job.totalTokens?.total ?? 0;
640
+ if (step?.durationMs !== void 0)
641
+ return {
642
+ tokens,
643
+ durationMs: liveDurationMs({ durationMs: step.durationMs, lastActivityAt: step.lastActivityAt }, running, now)
644
+ };
645
+ let startedAt = step?.startedAt ?? job.startedAt;
646
+ if (startedAt === void 0)
647
+ return { tokens, durationMs: 0 };
648
+ let endedAt = running ? now : step?.endedAt ?? step?.lastActivityAt ?? job.updatedAt ?? now;
649
+ return { tokens, durationMs: Math.max(0, endedAt - startedAt) };
674
650
  }
675
651
  function compactJobLead(job, step) {
676
652
  return compactRowLead({
@@ -679,18 +655,15 @@ function compactJobLead(job, step) {
679
655
  }) || widgetJobName(job);
680
656
  }
681
657
  function compactJobLines(job, step, theme, width, now = Date.now()) {
682
- let running = (step?.status ?? job.status) === "running", lead = compactJobLead(job, step), modelBadge = formatModelSelection(step?.modelSelection, step?.model, step?.thinking), permissionBadge = step?.permissions ? theme.fg("dim", step.permissions) : "", glyph = step ? widgetStepGlyph(step.status, theme, running ? (widgetStepRunningSeed(step, step.index) ?? 0) + widgetAnimFrame(now) : widgetStepRunningSeed(step, step.index)) : widgetStatusGlyph(job, theme, now), hang = formatCompactStatsHangLine(compactJobProgress(job, step, now), width, (s) => theme.fg("dim", s), " \u23BF ", now, running);
683
- return [
684
- truncLine(`${glyph} ${themeBold(theme, lead)}${modelBadge ? ` ${theme.fg("dim", "\xB7")} ${theme.fg("dim", modelBadge)}` : ""}${permissionBadge ? ` ${theme.fg("dim", "\xB7")} ${permissionBadge}` : ""}`, width),
685
- hang
686
- ];
687
- }
688
- function buildSingleWidgetLines(job, theme, width, _expanded) {
689
- let now = Date.now(), steps = job.steps ?? [];
690
- return steps.length <= 1 ? compactJobLines(job, steps[0], theme, width, now) : steps.flatMap((step) => compactJobLines(job, step, theme, width, now));
691
- }
692
- function compactSingleWidgetLines(job, theme, width) {
693
- return buildSingleWidgetLines(job, theme, width, !1);
658
+ let running = (step?.status ?? job.status) === "running", lead = compactJobLead(job, step), modelBadge = formatCompactModelBadge(step?.modelSelection, step?.model), glyph = step ? widgetStepGlyph(step.status, theme, running ? (widgetStepRunningSeed(step, step.index) ?? 0) + widgetAnimFrame(now) : widgetStepRunningSeed(step, step.index)) : widgetStatusGlyph(job, theme, now), progress = compactJobProgress(job, step, now);
659
+ return [formatCompactSubagentRow(theme, width, {
660
+ glyph,
661
+ description: lead,
662
+ modelBadge,
663
+ tokens: progress.tokens,
664
+ durationMs: progress.durationMs,
665
+ terminalStatus: compactTerminalStatus(step?.status ?? job.status)
666
+ })];
694
667
  }
695
668
  var RESERVED_NON_WIDGET_ROWS = 19, widgetLayoutSession;
696
669
  function resetWidgetLayoutSession() {
@@ -709,20 +682,6 @@ function currentTerminalColumns() {
709
682
  function widgetSessionMatches(expanded) {
710
683
  return widgetLayoutSession?.expanded === expanded && widgetLayoutSession.rows === currentTerminalRows() && widgetLayoutSession.columns === currentTerminalColumns();
711
684
  }
712
- function widgetHeaderCounts(jobs) {
713
- return {
714
- running: jobs.filter((job) => job.status === "running"),
715
- queued: jobs.filter((job) => job.status === "queued"),
716
- complete: jobs.filter((job) => job.status === "complete"),
717
- failed: jobs.filter((job) => job.status === "failed"),
718
- paused: jobs.filter((job) => job.status === "paused"),
719
- stopped: jobs.filter((job) => job.status === "stopped")
720
- };
721
- }
722
- function buildSingleLineWidgetLines(jobs, theme, width) {
723
- let counts = widgetHeaderCounts(jobs), hasActive = counts.running.length > 0 || counts.queued.length > 0, glyph = counts.running.length > 0 ? runningGlyph(widgetJobsRunningSeed(counts.running)) : hasActive ? "\u25CF" : "\u25CB", parts = [];
724
- return counts.running.length > 0 && parts.push(`${counts.running.length}/${jobs.length} running`), counts.queued.length > 0 && parts.push(`${counts.queued.length} queued`), counts.failed.length > 0 && parts.push(`${counts.failed.length} failed`), counts.stopped.length > 0 && parts.push(`${counts.stopped.length} stopped`), counts.paused.length > 0 && parts.push(`${counts.paused.length} paused`), !hasActive && counts.complete.length > 0 && parts.push(`${counts.complete.length}/${jobs.length} done`), [truncLine(`${theme.fg(hasActive ? "accent" : "dim", glyph)} ${theme.fg(hasActive ? "accent" : "dim", "subagents")} (${parts.join(", ") || `${jobs.length} total`})`, width)];
725
- }
726
685
  function orderedWidgetJobs(jobs) {
727
686
  return [
728
687
  ...jobs.filter((job) => job.status === "running"),
@@ -730,73 +689,6 @@ function orderedWidgetJobs(jobs) {
730
689
  ...jobs.filter((job) => job.status !== "running" && job.status !== "queued")
731
690
  ];
732
691
  }
733
- function progressiveJobKey(job) {
734
- return job.asyncId;
735
- }
736
- function isProgressiveActiveJob(job) {
737
- return job?.status === "running" || job?.status === "queued";
738
- }
739
- function selectProgressiveJobKeys(jobs, previousKeys, bodyRows) {
740
- if (bodyRows <= 0)
741
- return [];
742
- let jobsByKey = new Map(jobs.map((job) => [progressiveJobKey(job), job])), selected = [], append = (key) => {
743
- selected.includes(key) || !jobsByKey.has(key) || selected.push(key);
744
- };
745
- for (let key of previousKeys)
746
- if (isProgressiveActiveJob(jobsByKey.get(key)) && (append(key), selected.length >= bodyRows))
747
- return selected;
748
- for (let job of orderedWidgetJobs(jobs)) {
749
- if (!isProgressiveActiveJob(job))
750
- continue;
751
- let key = progressiveJobKey(job);
752
- if (append(key), selected.length >= bodyRows)
753
- break;
754
- }
755
- if (selected.length >= bodyRows)
756
- return selected;
757
- for (let key of previousKeys)
758
- if (!isProgressiveActiveJob(jobsByKey.get(key)) && (append(key), selected.length >= bodyRows))
759
- return selected;
760
- for (let job of orderedWidgetJobs(jobs)) {
761
- let key = progressiveJobKey(job);
762
- if (append(key), selected.length >= bodyRows)
763
- break;
764
- }
765
- return selected;
766
- }
767
- function progressiveHeaderLine(jobs, theme, width) {
768
- let counts = widgetHeaderCounts(jobs), hasActive = counts.running.length > 0 || counts.queued.length > 0, glyph = counts.running.length > 0 ? runningGlyph(widgetJobsRunningSeed(counts.running)) : hasActive ? "\u25CF" : "\u25CB", parts = [];
769
- return counts.running.length > 0 && parts.push(formatAgentRunningLabel(counts.running.length)), counts.queued.length > 0 && parts.push(`${counts.queued.length} queued`), hasActive || (counts.failed.length > 0 && parts.push(`${counts.failed.length} failed`), counts.stopped.length > 0 && parts.push(`${counts.stopped.length} stopped`), counts.paused.length > 0 && parts.push(`${counts.paused.length} paused`), counts.complete.length > 0 && parts.push(`${counts.complete.length}/${jobs.length} done`)), truncLine(`${theme.fg(hasActive ? "accent" : "dim", glyph)} ${theme.fg(hasActive ? "accent" : "dim", "Async agents")} ${theme.fg("dim", "\xB7")} ${theme.fg("dim", parts.join(", ") || `${jobs.length} total`)}`, width);
770
- }
771
- function progressiveJobLine(job, theme, width) {
772
- let stats = widgetStats(job, theme), activity = widgetActivity(job), status = job.status === "complete" ? "done" : job.status, parts = [
773
- themeBold(theme, widgetJobName(job)),
774
- theme.fg("dim", status),
775
- stats,
776
- activity && activity.toLowerCase() !== status ? theme.fg("dim", activity) : ""
777
- ].filter(Boolean);
778
- return truncLine(` ${widgetStatusGlyph(job, theme)} ${parts.join(` ${theme.fg("dim", "\xB7")} `)}`, width);
779
- }
780
- function progressiveHiddenLine(hiddenJobs, theme, width) {
781
- let counts = widgetHeaderCounts(hiddenJobs), parts = [];
782
- counts.running.length > 0 && parts.push(`${counts.running.length} running`), counts.queued.length > 0 && parts.push(`${counts.queued.length} queued`);
783
- let finished = counts.complete.length + counts.failed.length + counts.paused.length + counts.stopped.length;
784
- return finished > 0 && parts.push(`${finished} finished`), truncLine(theme.fg("dim", ` +${hiddenJobs.length} more${parts.length ? ` (${parts.join(", ")})` : ""}`), width);
785
- }
786
- function buildProgressiveWidgetLines(jobs, theme, width, lockedRows, previousKeys) {
787
- let rowCount = Math.max(1, lockedRows);
788
- if (rowCount === 1)
789
- return { lines: buildSingleLineWidgetLines(jobs, theme, width), visibleJobKeys: [] };
790
- let bodyRows = rowCount - 1, visibleJobKeys = selectProgressiveJobKeys(jobs, previousKeys, bodyRows), jobsByKey = new Map(jobs.map((job) => [progressiveJobKey(job), job])), visibleJobs = visibleJobKeys.map((key) => jobsByKey.get(key)).filter((job) => !!job), hiddenJobs = jobs.filter((job) => !visibleJobKeys.includes(progressiveJobKey(job)));
791
- hiddenJobs.length > 0 && visibleJobs.length >= bodyRows && bodyRows > 0 && (visibleJobs = visibleJobs.slice(0, bodyRows - 1), visibleJobKeys = visibleJobs.map(progressiveJobKey), hiddenJobs = jobs.filter((job) => !visibleJobKeys.includes(progressiveJobKey(job))));
792
- let lines = [
793
- progressiveHeaderLine(jobs, theme, width),
794
- ...visibleJobs.map((job) => progressiveJobLine(job, theme, width))
795
- ];
796
- for (hiddenJobs.length > 0 && lines.length < rowCount && lines.push(progressiveHiddenLine(hiddenJobs, theme, width)); lines.length < rowCount; )
797
- lines.push(" ");
798
- return { lines: lines.slice(0, rowCount), visibleJobKeys };
799
- }
800
692
  function collapsedWidgetLineBudget(rows) {
801
693
  return Math.max(10, Math.min(14, Math.floor(rows * 0.35)));
802
694
  }
@@ -807,150 +699,185 @@ function fitWidgetLineBudget(lines, theme, width, expanded) {
807
699
  let visibleLines = Math.max(1, budget - 1), hiddenCount = lines.length - visibleLines, hint = expanded ? `\u2026 ${hiddenCount} live-detail lines hidden` : `\u2026 ${hiddenCount} lines hidden \xB7 ${liveDetailKeyText()} expands`;
808
700
  return [...lines.slice(0, visibleLines), truncLine(theme.fg("dim", hint), width)];
809
701
  }
810
- function fitAdaptiveWidgetLines(jobs, lines, theme, width, expanded) {
702
+ function fitAdaptiveWidgetLines(_jobs, lines, theme, width, expanded) {
811
703
  if (expanded)
812
704
  return resetWidgetLayoutSession(), fitWidgetLineBudget(lines, theme, width, !0);
813
- let hasMatchingSession = widgetSessionMatches(expanded), rows = currentTerminalRows(), columns = currentTerminalColumns(), availableRows = estimateAvailableWidgetRows();
814
- if (hasMatchingSession && widgetLayoutSession?.tier === "single-line")
815
- return buildSingleLineWidgetLines(jobs, theme, width);
816
- if (hasMatchingSession && widgetLayoutSession?.tier === "progressive" && widgetLayoutSession.lockedRows !== void 0) {
817
- let rendered2 = buildProgressiveWidgetLines(jobs, theme, width, widgetLayoutSession.lockedRows, widgetLayoutSession.visibleJobKeys);
818
- return widgetLayoutSession.visibleJobKeys = rendered2.visibleJobKeys, rendered2.lines;
819
- }
705
+ let rows = currentTerminalRows(), columns = currentTerminalColumns(), availableRows = estimateAvailableWidgetRows();
820
706
  if (lines.length <= availableRows)
821
- return widgetLayoutSession = { expanded, rows, columns, tier: "full", visibleJobKeys: [] }, fitWidgetLineBudget(lines, theme, width, !1);
822
- if (availableRows <= 2)
823
- return widgetLayoutSession = { expanded, rows, columns, tier: "single-line", visibleJobKeys: [] }, buildSingleLineWidgetLines(jobs, theme, width);
824
- let lockedRows = Math.min(availableRows, collapsedWidgetLineBudget(rows)), rendered = buildProgressiveWidgetLines(jobs, theme, width, lockedRows, []);
825
- return widgetLayoutSession = { expanded, rows, columns, tier: "progressive", lockedRows, visibleJobKeys: rendered.visibleJobKeys }, rendered.lines;
826
- }
827
- function buildWidgetComponent(jobs, expanded) {
828
- return (_tui, theme) => {
829
- let width = getTermWidth(), lines = expanded ? buildWidgetLines(jobs, theme, width, !0) : jobs.length === 1 ? compactSingleWidgetLines(jobs[0], theme, width) : buildWidgetLines(jobs, theme, width, !1), container = new Container();
830
- for (let line of fitAdaptiveWidgetLines(jobs, lines, theme, width, expanded))
831
- container.addChild(new Text(line, 1, 0));
832
- return container;
833
- };
707
+ return widgetLayoutSession = { expanded, rows, columns, tier: "full" }, fitWidgetLineBudget(lines, theme, width, !1);
708
+ let lockedRows = widgetSessionMatches(expanded) && widgetLayoutSession?.tier === "progressive" ? widgetLayoutSession.lockedRows ?? 1 : Math.max(1, Math.min(availableRows, collapsedWidgetLineBudget(rows)));
709
+ if (widgetLayoutSession = { expanded, rows, columns, tier: "progressive", lockedRows }, lockedRows === 1)
710
+ return lines.slice(0, 1);
711
+ let visibleCount = Math.max(1, lockedRows - 1), visible = lines.slice(0, visibleCount), hidden = lines.length - visible.length;
712
+ for (hidden > 0 && visible.push(truncLine(theme.fg("dim", `+${hidden} more`), width)); visible.length < lockedRows; )
713
+ visible.push(" ");
714
+ return visible.slice(0, lockedRows);
715
+ }
716
+ function widgetExpandedDiagnostics(job, step, index, theme, width, now) {
717
+ let lines = [], status = step?.status ?? job.status, runLabel = step ? `${job.asyncId}:${step.index ?? index}` : job.asyncId;
718
+ lines.push(truncLine(theme.fg("dim", ` \u23BF run ${runLabel} \xB7 ${status}`), width));
719
+ let error = step?.error;
720
+ error && lines.push(truncLine(theme.fg("error", ` ${error}`), width));
721
+ let snapshotNow = status === "running" ? now : step?.endedAt ?? job.updatedAt, activity = step ? widgetStepActivityLine(step, Math.max(1, width - 4), !0, snapshotNow) : widgetActivity(job, now);
722
+ activity && lines.push(truncLine(theme.fg("dim", ` ${activity}`), width));
723
+ for (let tool of step?.recentTools?.slice(-3) ?? [])
724
+ lines.push(truncLine(theme.fg("dim", ` ${tool.tool}${tool.args ? `: ${tool.args}` : ""}`), width));
725
+ for (let output of step?.recentOutput?.slice(-5) ?? [])
726
+ lines.push(truncLine(theme.fg("dim", ` ${output}`), width));
727
+ for (let nestedLine of formatNestedWidgetLines(step?.children ?? job.nestedChildren, theme, width, !0, snapshotNow))
728
+ lines.push(truncLine(` ${nestedLine}`, width));
729
+ return lines;
834
730
  }
835
- function buildWidgetLines(jobs, theme, width = getTermWidth(), expanded = !1) {
836
- if (jobs.length === 0)
837
- return [];
838
- if (jobs.length === 1)
839
- return buildSingleWidgetLines(jobs[0], theme, width, expanded);
840
- let running = jobs.filter((job) => job.status === "running"), queued = jobs.filter((job) => job.status === "queued"), finished = jobs.filter((job) => job.status !== "running" && job.status !== "queued"), lines = [], hasActive = running.length > 0 || queued.length > 0, headerGlyph = running.length > 0 ? runningGlyph(widgetJobsRunningSeed(running)) : hasActive ? "\u25CF" : "\u25CB";
841
- lines.push(truncLine(`${theme.fg(hasActive ? "accent" : "dim", headerGlyph)} ${theme.fg(hasActive ? "accent" : "dim", "Async agents")} ${theme.fg("dim", "\xB7 background")}`, width));
842
- let items = [], hiddenRunning = 0, hiddenFinished = 0, queuedSummaryShown = !1, slots = MAX_WIDGET_JOBS;
843
- for (let job of running) {
844
- if (slots <= 0) {
845
- hiddenRunning++;
846
- continue;
847
- }
848
- let stats = widgetStats(job, theme);
849
- items.push([
850
- `${widgetStatusGlyph(job, theme)} ${themeBold(theme, widgetJobName(job))}${stats ? ` ${theme.fg("dim", "\xB7")} ${stats}` : ""}`,
851
- ` ${theme.fg("dim", `\u23BF ${widgetActivity(job)}`)}`,
852
- ...widgetParallelAgentDetails(job, theme, expanded, width)
853
- ]), slots--;
854
- }
855
- queued.length > 0 && slots > 0 && (items.push([`${theme.fg("muted", "\u25E6")} ${theme.fg("dim", `${queued.length} queued`)}`]), queuedSummaryShown = !0, slots--);
856
- for (let job of finished) {
857
- if (slots <= 0) {
858
- hiddenFinished++;
859
- continue;
860
- }
861
- let stats = widgetStats(job, theme);
862
- items.push([
863
- `${widgetStatusGlyph(job, theme)} ${themeBold(theme, widgetJobName(job))}${stats ? ` ${theme.fg("dim", "\xB7")} ${stats}` : ""}`,
864
- ` ${theme.fg("dim", `\u23BF ${widgetActivity(job)}`)}`,
865
- ...widgetParallelAgentDetails(job, theme, expanded, width)
866
- ]), slots--;
867
- }
868
- let hiddenQueued = queued.length > 0 && !queuedSummaryShown ? queued.length : 0, hiddenTotal = hiddenRunning + hiddenFinished + hiddenQueued;
869
- if (hiddenTotal > 0) {
870
- let parts = [];
871
- hiddenRunning > 0 && parts.push(`${hiddenRunning} running`), hiddenQueued > 0 && parts.push(`${hiddenQueued} queued`), hiddenFinished > 0 && parts.push(`${hiddenFinished} finished`), items.push([theme.fg("dim", `+${hiddenTotal} more (${parts.join(", ")})`)]);
872
- }
873
- for (let i = 0; i < items.length; i++) {
874
- let item = items[i], last = i === items.length - 1, branch = last ? "\u2514\u2500" : "\u251C\u2500", continuation = last ? " " : "\u2502 ";
875
- lines.push(truncLine(`${theme.fg("dim", branch)} ${item[0]}`, width));
876
- for (let detail of item.slice(1))
877
- lines.push(truncLine(`${theme.fg("dim", continuation)} ${detail}`, width));
731
+ function buildWidgetLines(jobs, theme, width = getTermWidth(), expanded = !1, now = Date.now()) {
732
+ let lines = [];
733
+ for (let job of orderedWidgetJobs(jobs)) {
734
+ let steps = job.steps?.length ? job.steps : job.agents?.length ? job.agents.map((agent, index) => ({ agent, description: agent, status: job.status, index })) : [void 0];
735
+ for (let [index, step] of steps.entries())
736
+ lines.push(...compactJobLines(job, step, theme, width, now)), expanded && lines.push(...widgetExpandedDiagnostics(job, step, index, theme, width, now));
878
737
  }
879
738
  return lines;
880
739
  }
881
- var widgetPaintTimer, widgetPaintCtx;
882
- function clearWidgetPaintTimer() {
883
- widgetPaintTimer && (clearInterval(widgetPaintTimer), widgetPaintTimer = void 0), widgetPaintCtx = void 0;
884
- }
885
- function ensureWidgetPaintTimer(ctx, running) {
886
- if (widgetPaintCtx = ctx, !running || !ctx.hasUI) {
887
- clearWidgetPaintTimer();
888
- return;
740
+ var activeWidget, SubagentAsyncWidget = class {
741
+ jobs;
742
+ expanded;
743
+ theme;
744
+ requestRender;
745
+ nowFn;
746
+ timer;
747
+ disposed = !1;
748
+ cachedWidth;
749
+ cachedLines;
750
+ constructor(jobs, theme, options) {
751
+ this.jobs = jobs, this.theme = theme, this.expanded = options?.expanded ?? !1, this.requestRender = options?.requestRender, this.nowFn = options?.now ?? Date.now, this.syncTimer();
752
+ }
753
+ setTheme(theme) {
754
+ this.theme = theme, this.invalidate();
755
+ }
756
+ setJobs(jobs) {
757
+ this.jobs = jobs, this.invalidate(), this.syncTimer();
758
+ }
759
+ setExpanded(expanded) {
760
+ this.expanded !== expanded && (this.expanded = expanded, this.invalidate());
761
+ }
762
+ setRequestRender(requestRender) {
763
+ this.requestRender = requestRender;
764
+ }
765
+ hasRunning() {
766
+ return this.jobs.some((job) => job.status === "running");
889
767
  }
890
- widgetPaintTimer || (widgetPaintTimer = setInterval(() => {
891
- widgetPaintCtx?.ui.requestRender?.();
892
- }, 80), widgetPaintTimer.unref?.());
768
+ syncTimer() {
769
+ this.disposed || (this.hasRunning() ? this.startTimer() : this.stopTimer());
770
+ }
771
+ startTimer() {
772
+ this.timer || (this.timer = setInterval(() => {
773
+ this.disposed || (this.invalidate(), this.requestRender?.());
774
+ }, SUBAGENT_PAINT_INTERVAL_MS), this.timer.unref?.());
775
+ }
776
+ stopTimer() {
777
+ this.timer && (clearInterval(this.timer), this.timer = void 0);
778
+ }
779
+ invalidate() {
780
+ this.cachedWidth = void 0, this.cachedLines = void 0;
781
+ }
782
+ dispose() {
783
+ this.disposed = !0, this.stopTimer(), activeWidget === this && (activeWidget = void 0);
784
+ }
785
+ render(width) {
786
+ let theme = this.theme;
787
+ if (!theme)
788
+ return [];
789
+ if (this.cachedLines && this.cachedWidth === width && !this.hasRunning())
790
+ return this.cachedLines;
791
+ let now = this.nowFn(), innerWidth = Math.max(1, width - 2), lines = buildWidgetLines(this.jobs, theme, innerWidth, this.expanded, now), padded = fitAdaptiveWidgetLines(this.jobs, lines, theme, innerWidth, this.expanded).map((line) => {
792
+ let withPad = ` ${line}`, vis = visibleWidth(withPad);
793
+ return withPad + " ".repeat(Math.max(0, width - vis));
794
+ });
795
+ return this.cachedWidth = width, this.cachedLines = padded, padded;
796
+ }
797
+ };
798
+ function disposeSubagentWidget() {
799
+ activeWidget?.dispose(), activeWidget = void 0;
893
800
  }
894
801
  function renderWidget(ctx, jobs) {
895
802
  if (jobs.length === 0) {
896
- resetWidgetLayoutSession(), clearWidgetPaintTimer(), ctx.hasUI && ctx.ui.setWidget(WIDGET_KEY, void 0);
803
+ resetWidgetLayoutSession(), disposeSubagentWidget(), ctx.hasUI && ctx.ui.setWidget(WIDGET_KEY, void 0);
897
804
  return;
898
805
  }
899
- ctx.hasUI && (ensureWidgetPaintTimer(ctx, jobs.some((job) => job.status === "running")), ctx.ui.setWidget(WIDGET_KEY, buildWidgetComponent(jobs, ctx.ui.getToolsExpanded?.() ?? !1)));
806
+ if (!ctx.hasUI)
807
+ return;
808
+ let expanded = ctx.ui.getToolsExpanded?.() ?? !1, requestRender = () => ctx.ui.requestRender?.();
809
+ if (activeWidget) {
810
+ activeWidget.setJobs(jobs), activeWidget.setExpanded(expanded), activeWidget.setRequestRender(requestRender), ctx.ui.requestRender?.();
811
+ return;
812
+ }
813
+ let widget = new SubagentAsyncWidget(jobs, void 0, { expanded, requestRender });
814
+ activeWidget = widget, ctx.ui.setWidget(WIDGET_KEY, (_tui, theme) => (widget.setTheme(theme), widget));
815
+ }
816
+ function compactResultTerminalStatus(result2) {
817
+ if (result2.stopped)
818
+ return "stopped";
819
+ if (result2.detached)
820
+ return "detached";
821
+ if (result2.interrupted)
822
+ return "paused";
823
+ if (result2.exitCode !== 0)
824
+ return "failed";
900
825
  }
901
826
  function renderSingleCompact(d, r, theme, frame) {
902
- let output = r.truncation?.text || getSingleResultOutput(r), progress = r.progress || r.progressSummary, isRunning = r.progress?.status === "running", contextBadge = d.context === "fork" ? theme.fg("warning", " [fork]") : "", c = new Container(), width = getTermWidth() - 4, lead = compactRowLead({ description: r.description ?? r.agent, task: r.task }), modelBadge = formatModelSelection(r.modelSelection ?? progress?.modelSelection, r.model ?? progress?.model, r.thinking ?? progress?.thinking), permissionBadge = r.permissions ? theme.fg("dim", r.permissions) : "";
903
- if (c.addChild(animatedLine((f, now) => {
904
- let stats = formatProgressStats(theme, progress, !0, { running: isRunning, terminal: !isRunning, now });
905
- return truncLine(`${resultGlyph(r, output, theme, isRunning, void 0, f)} ${themeBold(theme, lead)}${modelBadge ? ` ${theme.fg("dim", "\xB7")} ${theme.fg("dim", modelBadge)}` : ""}${permissionBadge ? ` ${theme.fg("dim", "\xB7")} ${permissionBadge}` : ""}${contextBadge}${stats ? ` ${theme.fg("dim", "\xB7")} ${stats}` : ""}`, width);
906
- }, frame, isRunning)), isRunning && r.progress)
907
- return c.addChild(animatedLine((_f, now) => formatCompactStatsHangLine(r.progress, width, (s) => theme.fg("dim", s), " \u23BF ", now, !0), frame, !0)), c;
908
- c.addChild(new Text(truncLine(theme.fg("dim", ` \u23BF ${resultStatusLine(r, output)}`), width), 0, 0));
909
- let preview = firstOutputLine(output);
910
- return preview && r.exitCode === 0 && !hasEmptyTextOutputWithoutOutputTarget(r.task, output) && c.addChild(new Text(truncLine(theme.fg("dim", ` ${preview}`), width), 0, 0)), r.sessionFile && c.addChild(new Text(truncLine(theme.fg("dim", ` session: ${shortenPath(r.sessionFile)}`), width), 0, 0)), c;
827
+ let output = r.truncation?.text || getSingleResultOutput(r), progress = r.progress || r.progressSummary, isRunning = r.progress?.status === "running", width = getTermWidth() - 4, lead = compactRowLead({ description: r.description ?? r.agent, task: r.task }), modelBadge = formatCompactModelBadge(r.modelSelection ?? progress?.modelSelection, r.model ?? progress?.model);
828
+ return animatedLine((animationTick, now) => formatCompactSubagentRow(theme, width, {
829
+ glyph: resultGlyph(r, output, theme, isRunning, void 0, foregroundSpinnerFrame(animationTick)),
830
+ description: lead,
831
+ modelBadge,
832
+ tokens: compactResultTokens(r),
833
+ durationMs: liveDurationMs(progress, isRunning, now),
834
+ terminalStatus: compactResultTerminalStatus(r)
835
+ }), frame, isRunning);
836
+ }
837
+ function progressStatusGlyph(progress, theme, frame) {
838
+ return !progress || progress.status === "pending" ? theme.fg("muted", "\u25E6") : progress.status === "running" ? theme.fg("accent", runningGlyph((progressRunningSeed(progress) ?? 0) + (frame ?? 0))) : progress.status === "completed" ? theme.fg("success", "\u2713") : progress.status === "failed" ? theme.fg("error", "\u2717") : theme.fg("warning", "\u25A0");
839
+ }
840
+ function flattenCompactWorkflowNodes(nodes) {
841
+ let rows = [];
842
+ for (let node of nodes)
843
+ node.children?.length ? rows.push(...flattenCompactWorkflowNodes(node.children)) : rows.push(node);
844
+ return rows;
845
+ }
846
+ function compactForegroundEntries(d) {
847
+ let workflowNodes = flattenCompactWorkflowNodes(d.workflowGraph?.nodes ?? []);
848
+ if (workflowNodes.length === 0) {
849
+ let progressCount2 = d.progress?.reduce((count2, entry) => Math.max(count2, entry.index + 1), 0) ?? 0, chainCount = d.mode === "chain" ? buildChainStepSpans(d).reduce((count2, span) => Math.max(count2, span.start + span.count), 0) : 0, count = Math.max(d.results.length, progressCount2, d.chainChildren?.length ?? 0, d.chainAgents?.length ?? 0, chainCount);
850
+ return Array.from({ length: count }, (_, flatIndex) => ({ flatIndex }));
851
+ }
852
+ let entries = workflowNodes.map((node) => ({ flatIndex: node.flatIndex, node })), seen = new Set(entries.flatMap((entry) => entry.flatIndex === void 0 ? [] : [entry.flatIndex])), progressCount = d.progress?.reduce((count, entry) => Math.max(count, entry.index + 1), 0) ?? 0, dataCount = Math.max(d.results.length, progressCount, d.chainChildren?.length ?? 0);
853
+ for (let flatIndex = 0; flatIndex < dataCount; flatIndex++)
854
+ seen.has(flatIndex) || entries.push({ flatIndex });
855
+ return entries;
911
856
  }
912
857
  function renderMultiCompact(d, theme, frame) {
913
- let hasRunning = d.progress?.some((p) => p.status === "running") || d.results.some((r) => r.progress?.status === "running") || workflowGraphHasStatus(d, ["running"]), stopped = d.results.some((r) => r.stopped && r.progress?.status !== "running") || workflowGraphHasStatus(d, ["stopped"]), failed = d.results.some((r) => !r.stopped && r.exitCode !== 0 && r.progress?.status !== "running") || workflowGraphHasStatus(d, ["failed"]), paused = d.results.some((r) => (r.interrupted || r.detached) && r.progress?.status !== "running") || workflowGraphHasStatus(d, ["paused", "detached"]), totalSummary = d.progressSummary;
914
- if (!totalSummary) {
915
- let sawProgress = !1, summary = { toolCount: 0, tokens: 0, durationMs: 0, lastActivityAt: void 0 };
916
- for (let r of d.results) {
917
- let prog = r.progress || r.progressSummary;
918
- prog && (sawProgress = !0, summary.toolCount += prog.toolCount, summary.tokens += prog.tokens, summary.durationMs = d.mode === "chain" ? summary.durationMs + prog.durationMs : Math.max(summary.durationMs, prog.durationMs), prog.status === "running" && prog.lastActivityAt !== void 0 && (summary.lastActivityAt = Math.max(summary.lastActivityAt ?? 0, prog.lastActivityAt)));
919
- }
920
- sawProgress && (totalSummary = summary);
921
- }
922
- let multiLabel = buildMultiProgressLabel(d, hasRunning), itemTitle = multiLabel.itemTitle, glyph = (f) => hasRunning ? theme.fg("accent", runningGlyph(f !== void 0 ? (runningSeed(progressRunningSeed(totalSummary), d.currentStepIndex) ?? 0) + f : runningSeed(progressRunningSeed(totalSummary), d.currentStepIndex))) : stopped ? theme.fg("warning", "\u25A0") : failed ? theme.fg("error", "\u2717") : paused ? theme.fg("warning", "\u25A0") : theme.fg("success", "\u2713"), contextBadge = d.context === "fork" ? theme.fg("warning", " [fork]") : "", c = new Container(), width = getTermWidth() - 4;
923
- c.addChild(animatedLine((f, now) => {
924
- let stats = statJoin(theme, [multiLabel.headerLabel, formatProgressStats(theme, totalSummary, !0, { running: hasRunning, terminal: !hasRunning, now }), formatTotalCostStat(d.totalCost)]);
925
- return truncLine(`${glyph(f)} ${theme.fg("toolTitle", theme.bold(d.mode))}${contextBadge}${stats ? ` ${theme.fg("dim", "\xB7")} ${stats}` : ""}`, width);
926
- }, frame, hasRunning));
927
- let useResultsDirectly = multiLabel.hasParallelInChain || !d.chainAgents?.length, displayStart = multiLabel.showActiveGroupOnly ? multiLabel.groupStartIndex : 0, displayEnd = multiLabel.showActiveGroupOnly ? multiLabel.groupEndIndex : useResultsDirectly ? d.results.length : d.chainAgents.length, chainEntries = buildChainRenderEntries(d, multiLabel), renderEntries = chainEntries ?? Array.from({ length: displayEnd - displayStart }, (_, offset) => {
928
- let i = displayStart + offset, r = d.results[i], fallbackLabel = itemTitle.toLowerCase(), rowNumber = multiLabel.showActiveGroupOnly ? i - multiLabel.groupStartIndex + 1 : i + 1;
929
- return { kind: "result", resultIndex: i, rowNumber, agentName: useResultsDirectly ? r?.agent || `${fallbackLabel}-${rowNumber}` : d.chainAgents[i] || r?.agent || `${fallbackLabel}-${rowNumber}` };
930
- });
931
- for (let entry of renderEntries) {
932
- if (entry.kind === "placeholder") {
933
- let glyph2 = widgetStepGlyph(entry.status, theme), statusLabel = widgetStepStatus(entry.status, theme);
934
- c.addChild(new Text(truncLine(` ${glyph2} ${entry.stepLabel}: ${themeBold(theme, entry.agentName)} ${theme.fg("dim", "\xB7")} ${statusLabel}`, width), 0, 0)), entry.error && c.addChild(new Text(truncLine(theme.fg("error", ` \u23BF Error: ${entry.error}`), width), 0, 0));
935
- continue;
936
- }
937
- let i = entry.resultIndex, r = d.results[i], rowNumber = entry.rowNumber, agentName = entry.agentName;
938
- if (!r) {
939
- let pendingLabel2 = chainEntries ? resultRowLabel(d, multiLabel, i, rowNumber) : `${itemTitle} ${rowNumber}`;
940
- c.addChild(new Text(truncLine(theme.fg("dim", ` \u25E6 ${pendingLabel2}: ${agentName} \xB7 pending`), width), 0, 0));
941
- continue;
942
- }
943
- let output = getSingleResultOutput(r), progressFromArray = d.progress?.find((p) => p.index === i) || d.progress?.find((p) => p.agent === r.agent && p.status === "running"), rProg = r.progress || progressFromArray || r.progressSummary, rRunning = rProg && "status" in rProg && rProg.status === "running", rPending = rProg && "status" in rProg && rProg.status === "pending", pendingLabel = rPending ? ` ${theme.fg("dim", "\xB7 pending")}` : "", lead = compactRowLead({ description: r.description ?? agentName, task: r.task }), permissionBadge = r.permissions ? theme.fg("dim", r.permissions) : "", modelBadge = formatModelSelection(r.modelSelection ?? (rProg && "modelSelection" in rProg ? rProg.modelSelection : void 0), r.model ?? (rProg && "model" in rProg ? rProg.model : void 0), r.thinking ?? (rProg && "thinking" in rProg ? rProg.thinking : void 0));
944
- c.addChild(animatedLine((f, now) => {
945
- let glyph2 = rPending ? theme.fg("dim", "\u25E6") : resultGlyph(r, output, theme, rRunning, progressRunningSeed(rProg), f), stepStats = formatProgressStats(theme, rProg, !0, { running: !!rRunning, terminal: !rRunning && !rPending, now });
946
- return truncLine(` ${glyph2} ${themeBold(theme, lead)}${modelBadge ? ` ${theme.fg("dim", "\xB7")} ${theme.fg("dim", modelBadge)}` : ""}${permissionBadge ? ` ${theme.fg("dim", "\xB7")} ${permissionBadge}` : ""}${stepStats ? ` ${theme.fg("dim", "\xB7")} ${stepStats}` : ""}${pendingLabel}`, width);
947
- }, frame, !!rRunning)), rRunning && rProg && "status" in rProg ? c.addChild(animatedLine((_f, now) => formatCompactStatsHangLine(rProg, width, (s) => theme.fg("dim", s), " \u23BF ", now, !0), frame, !0)) : !rPending && (r.exitCode !== 0 || r.interrupted || r.detached || hasEmptyTextOutputWithoutOutputTarget(r.task, output)) && c.addChild(new Text(truncLine(theme.fg(r.exitCode !== 0 ? "error" : "dim", ` \u23BF ${resultStatusLine(r, output)}`), width), 0, 0));
858
+ let c = new Container(), width = getTermWidth() - 4, entries = compactForegroundEntries(d);
859
+ for (let [rowIndex, entry] of entries.entries()) {
860
+ let flatIndex = entry.flatIndex, result2 = flatIndex === void 0 ? void 0 : resultAtFlatIndex(d, flatIndex), progress = result2?.progress ?? (flatIndex === void 0 ? void 0 : d.progress?.find((candidate) => candidate.index === flatIndex)) ?? result2?.progressSummary, status = progress?.status ?? entry.node?.status ?? "pending", description = compactRowLead({
861
+ description: result2?.description ?? progress?.description ?? entry.node?.label ?? (flatIndex === void 0 ? void 0 : d.chainChildren?.[flatIndex]?.description) ?? (flatIndex === void 0 ? void 0 : d.chainAgents?.[flatIndex]) ?? result2?.agent ?? progress?.agent,
862
+ task: result2?.task ?? progress?.task
863
+ }) || `child ${rowIndex + 1}`, running = status === "running", output = result2 ? getSingleResultOutput(result2) : "", modelBadge = formatCompactModelBadge(result2?.modelSelection ?? progress?.modelSelection, result2?.model ?? progress?.model);
864
+ c.addChild(animatedLine((animationTick, now) => {
865
+ let animationFrame = foregroundSpinnerFrame(animationTick);
866
+ return formatCompactSubagentRow(theme, width, {
867
+ glyph: result2 ? resultGlyph(result2, output, theme, running, progressRunningSeed(progress), animationFrame) : progressStatusGlyph({ ...progress, status, index: flatIndex }, theme, animationFrame),
868
+ description,
869
+ modelBadge,
870
+ tokens: result2 ? compactResultTokens(result2) : progress?.tokens ?? 0,
871
+ durationMs: liveDurationMs(progress, running, now),
872
+ terminalStatus: result2 ? compactResultTerminalStatus(result2) : compactTerminalStatus(status)
873
+ });
874
+ }, frame, running));
948
875
  }
949
876
  return c;
950
877
  }
951
878
  function renderSubagentResult(result2, options, theme, frame) {
952
- let d = result2.details;
953
- if (!d || !d.results.length) {
879
+ let d = result2.details, hasWorkflowRows = d?.mode !== "management" && !!(d?.workflowGraph?.nodes.length || d?.progress?.length || d?.chainChildren?.length);
880
+ if (!d || !d.results.length && !hasWorkflowRows) {
954
881
  let t = result2.content[0], text = t?.type === "text" ? t.text : "(no output)", contextPrefix = d?.context === "fork" ? `${theme.fg("warning", "[fork]")} ` : "", width = getTermWidth() - 4;
955
882
  if (!text.includes(`
956
883
  `))
@@ -971,7 +898,7 @@ function renderSubagentResult(result2, options, theme, frame) {
971
898
  return fit3(`${icon2} ${theme.fg("toolTitle", theme.bold(r.agent))}${modelDisplay}${contextBadge2}${stats ? ` | ${stats}` : ""}`);
972
899
  }, frame, isRunning)), c2.addChild(new Spacer(1));
973
900
  let taskMaxLen = Math.max(20, w2 - 8), taskPreview = expanded || r.task.length <= taskMaxLen ? r.task : `${r.task.slice(0, taskMaxLen)}...`;
974
- if (c2.addChild(new Text(fit3(theme.fg("dim", `Task: ${taskPreview}`)), 0, 0)), c2.addChild(new Spacer(1)), isRunning && r.progress) {
901
+ if (c2.addChild(new Text(fit3(theme.fg("dim", `Task: ${taskPreview}`)), 0, 0)), !isRunning && compactResultTerminalStatus(r) && c2.addChild(new Text(fit3(theme.fg(r.exitCode !== 0 ? "error" : "warning", resultStatusLine(r, output))), 0, 0)), c2.addChild(new Spacer(1)), isRunning && r.progress) {
975
902
  let progressSnapshotNow = snapshotNowForProgress(r.progress), toolLine = formatCurrentToolLine(r.progress, w2, expanded, progressSnapshotNow);
976
903
  toolLine && c2.addChild(new Text(fit3(theme.fg("warning", `> ${toolLine}`)), 0, 0));
977
904
  let liveStatusLine = buildLiveStatusLine(r.progress, progressSnapshotNow);
@@ -993,7 +920,7 @@ function renderSubagentResult(result2, options, theme, frame) {
993
920
  }
994
921
  if (!expanded)
995
922
  return renderMultiCompact(d, theme, frame);
996
- let hasRunning = d.progress?.some((p) => p.status === "running") || d.results.some((r) => r.progress?.status === "running") || workflowGraphHasStatus(d, ["running"]), ok = d.results.filter((r) => r.progress?.status === "completed" || r.exitCode === 0 && r.progress?.status !== "running").length, hasEmptyWithoutTarget = d.results.some((r) => r.exitCode === 0 && r.progress?.status !== "running" && hasEmptyTextOutputWithoutOutputTarget(r.task, getSingleResultOutput(r))), hasWorkflowFailure = workflowGraphHasStatus(d, ["failed"]), hasWorkflowStop = d.results.some((r) => r.stopped && r.progress?.status !== "running") || workflowGraphHasStatus(d, ["stopped"]), hasWorkflowPause = workflowGraphHasStatus(d, ["paused", "detached"]), icon = hasRunning ? theme.fg("warning", "running") : hasEmptyWithoutTarget ? theme.fg("warning", "warning") : hasWorkflowFailure ? theme.fg("error", "failed") : hasWorkflowStop ? theme.fg("warning", "stopped") : hasWorkflowPause ? theme.fg("warning", "paused") : ok === d.results.length ? theme.fg("success", "ok") : theme.fg("error", "failed"), totalSummary = d.progressSummary || d.results.reduce((acc, r) => {
923
+ let hasRunning = d.progress?.some((p) => p.status === "running") || d.results.some((r) => r.progress?.status === "running") || workflowGraphHasStatus(d, ["running"]), ok = d.results.filter((r) => r.progress?.status === "completed" || r.exitCode === 0 && r.progress?.status !== "running").length, hasEmptyWithoutTarget = d.results.some((r) => r.exitCode === 0 && r.progress?.status !== "running" && hasEmptyTextOutputWithoutOutputTarget(r.task, getSingleResultOutput(r))), hasWorkflowFailure = workflowGraphHasStatus(d, ["failed"]), hasWorkflowStop = d.results.some((r) => r.stopped && r.progress?.status !== "running") || workflowGraphHasStatus(d, ["stopped"]), hasWorkflowPause = workflowGraphHasStatus(d, ["paused", "detached"]), hasWorkflowPending = workflowGraphHasStatus(d, ["pending"]), icon = hasRunning ? theme.fg("warning", "running") : hasEmptyWithoutTarget ? theme.fg("warning", "warning") : hasWorkflowFailure ? theme.fg("error", "failed") : hasWorkflowStop ? theme.fg("warning", "stopped") : hasWorkflowPause ? theme.fg("warning", "paused") : hasWorkflowPending ? theme.fg("dim", "pending") : ok === d.results.length ? theme.fg("success", "ok") : theme.fg("error", "failed"), totalSummary = d.progressSummary || d.results.reduce((acc, r) => {
997
924
  let prog = r.progress || r.progressSummary;
998
925
  return prog && (acc.toolCount += prog.toolCount, acc.tokens += prog.tokens, acc.durationMs = d.mode === "chain" ? acc.durationMs + prog.durationMs : Math.max(acc.durationMs, prog.durationMs)), acc;
999
926
  }, { toolCount: 0, tokens: 0, durationMs: 0 }), modeLabel = d.mode, contextBadge = d.context === "fork" ? theme.fg("warning", " [fork]") : "", multiLabel = buildMultiProgressLabel(d, hasRunning), itemTitle = multiLabel.itemTitle, chainVis = d.chainAgents?.length && !multiLabel.hasParallelInChain ? d.chainAgents.map((agent, i) => {
@@ -1007,10 +934,26 @@ function renderSubagentResult(result2, options, theme, frame) {
1007
934
  ].filter(Boolean), summaryStr = summaryParts.length ? ` | ${summaryParts.join(", ")}` : "";
1008
935
  return fit2(`${icon} ${theme.fg("toolTitle", theme.bold(modeLabel))}${contextBadge} \xB7 ${multiLabel.headerLabel}${summaryStr}`);
1009
936
  }, frame, hasRunning)), chainVis && c.addChild(new Text(fit2(` ${chainVis}`), 0, 0));
1010
- let useResultsDirectly = multiLabel.hasParallelInChain || !d.chainAgents?.length, displayStart = multiLabel.showActiveGroupOnly ? multiLabel.groupStartIndex : 0, displayEnd = multiLabel.showActiveGroupOnly ? multiLabel.groupEndIndex : useResultsDirectly ? d.results.length : d.chainAgents.length, chainEntries = buildChainRenderEntries(d, multiLabel), renderEntries = chainEntries ?? Array.from({ length: displayEnd - displayStart }, (_, offset) => {
1011
- let i = displayStart + offset, r = d.results[i], rowNumber = multiLabel.showActiveGroupOnly ? i - multiLabel.groupStartIndex + 1 : i + 1;
1012
- return { kind: "result", resultIndex: i, rowNumber, agentName: useResultsDirectly ? r?.agent || `step-${rowNumber}` : d.chainAgents[i] || r?.agent || `step-${rowNumber}` };
1013
- });
937
+ let chainEntries = buildChainRenderEntries(d, multiLabel), fallbackEntries = compactForegroundEntries(d).filter((entry) => !multiLabel.showActiveGroupOnly || entry.flatIndex === void 0 || entry.flatIndex >= multiLabel.groupStartIndex && entry.flatIndex < multiLabel.groupEndIndex).map((entry, rowIndex) => {
938
+ if (entry.flatIndex === void 0)
939
+ return {
940
+ kind: "placeholder",
941
+ rowNumber: entry.node?.stepIndex !== void 0 ? entry.node.stepIndex + 1 : rowIndex + 1,
942
+ stepLabel: `Step ${entry.node?.stepIndex !== void 0 ? entry.node.stepIndex + 1 : rowIndex + 1}`,
943
+ agentName: entry.node?.label ?? `step-${rowIndex + 1}`,
944
+ status: entry.node?.status ?? "pending",
945
+ error: entry.node?.error
946
+ };
947
+ let result3 = resultAtFlatIndex(d, entry.flatIndex), rowNumber = multiLabel.showActiveGroupOnly ? entry.flatIndex - multiLabel.groupStartIndex + 1 : entry.flatIndex + 1;
948
+ return {
949
+ kind: "result",
950
+ resultIndex: entry.flatIndex,
951
+ rowNumber,
952
+ agentName: result3?.agent ?? entry.node?.label ?? d.chainChildren?.[entry.flatIndex]?.description ?? d.chainAgents?.[entry.flatIndex] ?? `step-${rowNumber}`,
953
+ status: entry.node?.status,
954
+ error: entry.node?.error
955
+ };
956
+ }), renderEntries = chainEntries ?? fallbackEntries;
1014
957
  c.addChild(new Spacer(1));
1015
958
  for (let entry of renderEntries) {
1016
959
  if (entry.kind === "placeholder") {
@@ -1018,10 +961,10 @@ function renderSubagentResult(result2, options, theme, frame) {
1018
961
  c.addChild(new Text(fit2(` ${statusLabel} ${entry.stepLabel}: ${theme.bold(entry.agentName)}`), 0, 0)), c.addChild(new Text(theme.fg(entry.status === "failed" ? "error" : "dim", ` status: ${entry.status}`), 0, 0)), entry.error && c.addChild(new Text(theme.fg("error", ` error: ${entry.error}`), 0, 0)), c.addChild(new Spacer(1));
1019
962
  continue;
1020
963
  }
1021
- let i = entry.resultIndex, r = d.results[i], rowNumber = entry.rowNumber, agentName = entry.agentName;
964
+ let i = entry.resultIndex, r = resultAtFlatIndex(d, i), rowNumber = entry.rowNumber, agentName = entry.agentName;
1022
965
  if (!r) {
1023
- let pendingLabel = chainEntries ? resultRowLabel(d, multiLabel, i, rowNumber) : `${itemTitle} ${rowNumber}`;
1024
- c.addChild(new Text(fit2(theme.fg("dim", ` ${pendingLabel}: ${agentName}`)), 0, 0)), c.addChild(new Text(theme.fg("dim", " status: pending"), 0, 0)), c.addChild(new Spacer(1));
966
+ let rowLabel = chainEntries ? resultRowLabel(d, multiLabel, i, rowNumber) : `${itemTitle} ${rowNumber}`, status = entry.status ?? "pending";
967
+ c.addChild(new Text(fit2(theme.fg(status === "failed" ? "error" : "dim", ` ${rowLabel}: ${agentName}`)), 0, 0)), c.addChild(new Text(theme.fg(status === "failed" ? "error" : "dim", ` status: ${status}`), 0, 0)), entry.error && c.addChild(new Text(theme.fg("error", ` error: ${entry.error}`), 0, 0)), c.addChild(new Spacer(1));
1025
968
  continue;
1026
969
  }
1027
970
  let progressFromArray = d.progress?.find((p) => p.index === i) || d.progress?.find((p) => p.agent === r.agent && p.status === "running"), rProg = r.progress || progressFromArray || r.progressSummary, rRunning = rProg?.status === "running", stepNumber = typeof rProg?.index == "number" ? rProg.index + 1 : i + 1, resultOutput = getSingleResultOutput(r), statusIcon = rRunning ? theme.fg("warning", "running") : r.exitCode !== 0 ? theme.fg("error", "failed") : hasEmptyTextOutputWithoutOutputTarget(r.task, resultOutput) ? theme.fg("warning", "warning") : theme.fg("success", "done"), modelDisplay = modelThinkingBadge(theme, r.model, r.thinking ?? (rProg && "thinking" in rProg ? rProg.thinking : void 0), r.modelSelection ?? (rProg && "modelSelection" in rProg ? rProg.modelSelection : void 0)), stepLabel = resultRowLabel(d, multiLabel, i, stepNumber), toolCallLines = getToolCallLines(r, expanded);
@@ -1030,7 +973,7 @@ function renderSubagentResult(result2, options, theme, frame) {
1030
973
  return fit2(rRunning ? `${statusIcon} ${stepLabel}: ${theme.bold(theme.fg("warning", r.agent))}${modelDisplay}${stats ? ` | ${stats}` : ""}` : `${statusIcon} ${stepLabel}: ${theme.bold(r.agent)}${modelDisplay}${stats ? ` | ${stats}` : ""}`);
1031
974
  }, frame, rRunning));
1032
975
  let taskMaxLen = Math.max(20, w - 12), taskPreview = expanded || r.task.length <= taskMaxLen ? r.task : `${r.task.slice(0, taskMaxLen)}...`;
1033
- if (c.addChild(new Text(fit2(theme.fg("dim", ` task: ${taskPreview}`)), 0, 0)), r.skills?.length && c.addChild(new Text(fit2(theme.fg("dim", ` skills: ${r.skills.join(", ")}`)), 0, 0)), r.skillsWarning && c.addChild(new Text(fit2(theme.fg("warning", ` Warning: ${r.skillsWarning}`)), 0, 0)), r.attemptedModels && r.attemptedModels.length > 1 && c.addChild(new Text(fit2(theme.fg("dim", ` fallbacks: ${r.attemptedModels.join(" \u2192 ")}`)), 0, 0)), rRunning && rProg) {
976
+ if (c.addChild(new Text(fit2(theme.fg("dim", ` task: ${taskPreview}`)), 0, 0)), !rRunning && compactResultTerminalStatus(r) && c.addChild(new Text(fit2(theme.fg(r.exitCode !== 0 ? "error" : "warning", ` ${resultStatusLine(r, resultOutput)}`)), 0, 0)), r.skills?.length && c.addChild(new Text(fit2(theme.fg("dim", ` skills: ${r.skills.join(", ")}`)), 0, 0)), r.skillsWarning && c.addChild(new Text(fit2(theme.fg("warning", ` Warning: ${r.skillsWarning}`)), 0, 0)), r.attemptedModels && r.attemptedModels.length > 1 && c.addChild(new Text(fit2(theme.fg("dim", ` fallbacks: ${r.attemptedModels.join(" \u2192 ")}`)), 0, 0)), rRunning && rProg) {
1034
977
  rProg.skills?.length && c.addChild(new Text(fit2(theme.fg("accent", ` skills: ${rProg.skills.join(", ")}`)), 0, 0));
1035
978
  let progressSnapshotNow = snapshotNowForProgress(rProg), toolLine = formatCurrentToolLine(rProg, w, expanded, progressSnapshotNow);
1036
979
  toolLine && c.addChild(new Text(fit2(theme.fg("warning", ` > ${toolLine}`)), 0, 0));
@@ -1059,15 +1002,15 @@ import { Type } from "typebox";
1059
1002
  function keepTopLevelParameterDescriptions(schema) {
1060
1003
  return pruneNestedDescriptions(schema, []);
1061
1004
  }
1062
- function pruneNestedDescriptions(value, path12) {
1005
+ function pruneNestedDescriptions(value, path13) {
1063
1006
  if (!value || typeof value != "object")
1064
1007
  return value;
1065
1008
  let result2 = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
1066
1009
  for (let key of Reflect.ownKeys(value)) {
1067
1010
  let descriptor = Object.getOwnPropertyDescriptor(value, key);
1068
- if (descriptor && !(key === "description" && !isPropertiesMap(path12) && !isTopLevelParameterHelpText(path12))) {
1011
+ if (descriptor && !(key === "description" && !isPropertiesMap(path13) && !isTopLevelParameterHelpText(path13))) {
1069
1012
  if ("value" in descriptor) {
1070
- let nextPath = typeof key == "string" ? [...path12, key] : path12;
1013
+ let nextPath = typeof key == "string" ? [...path13, key] : path13;
1071
1014
  descriptor.value = pruneNestedDescriptions(descriptor.value, nextPath);
1072
1015
  }
1073
1016
  Object.defineProperty(result2, key, descriptor);
@@ -1075,11 +1018,11 @@ function pruneNestedDescriptions(value, path12) {
1075
1018
  }
1076
1019
  return result2;
1077
1020
  }
1078
- function isPropertiesMap(path12) {
1079
- return path12[path12.length - 1] === "properties";
1021
+ function isPropertiesMap(path13) {
1022
+ return path13[path13.length - 1] === "properties";
1080
1023
  }
1081
- function isTopLevelParameterHelpText(path12) {
1082
- return path12.length === 2 && path12[0] === "properties";
1024
+ function isTopLevelParameterHelpText(path13) {
1025
+ return path13.length === 2 && path13[0] === "properties";
1083
1026
  }
1084
1027
  var SkillOverride = Type.Unsafe({
1085
1028
  anyOf: [
@@ -1097,10 +1040,16 @@ var SkillOverride = Type.Unsafe({
1097
1040
  }), OutputModeOverride = Type.String({
1098
1041
  enum: ["inline", "file-only"],
1099
1042
  description: "Return saved output inline (default) or only a concise file reference. file-only requires output to be a path."
1100
- }), TierOverride = Type.String({
1043
+ }), TIER_SELECTION_DESCRIPTION = "Choose the lowest model tier that can reliably complete the task: 'light' for quick checks, fact gathering, and small code inspections; 'standard' for everyday coding, clearly described bugs, and focused reviews; 'heavy' for complex implementation, difficult debugging, architectural decisions, and large or high-risk reviews.", TierOverride = Type.Optional(Type.String({
1101
1044
  enum: ["light", "standard", "heavy"],
1102
- description: "Required model tier: 'light' for simple/fast work, 'standard' for typical coding, or 'heavy' for complex reasoning. The configured tier model must be available and authenticated."
1103
- }), ReadsOverride = Type.Unsafe({
1045
+ description: `Required by default. ${TIER_SELECTION_DESCRIPTION} Do not combine with model. The configured tier model must be available and authenticated.`
1046
+ })), ModelOverride = Type.Optional(Type.String({
1047
+ minLength: 1,
1048
+ description: "Explicit provider/model id only when the user names a model. Do not combine with tier. Optional thinking belongs in the thinking field or as a known :level suffix."
1049
+ })), ThinkingOverride = Type.Optional(Type.String({
1050
+ enum: ["off", "minimal", "low", "medium", "high", "xhigh", "max"],
1051
+ description: "Thinking level for an explicit model launch. Omit for tier launches (they use configured tier thinking)."
1052
+ })), ReadsOverride = Type.Unsafe({
1104
1053
  anyOf: [
1105
1054
  { type: "array", items: { type: "string" } },
1106
1055
  { type: "boolean", enum: [!1] }
@@ -1135,7 +1084,7 @@ var SkillOverride = Type.Unsafe({
1135
1084
  description: "Required concise single-line UI label (max 80 characters). Presentation metadata only; not used as an identifier."
1136
1085
  }), PermissionsField = Type.Optional(Type.String({
1137
1086
  enum: ["full", "read-only"],
1138
- description: "Child permission level. Omit or 'full' for coding tools (read/search/shell/edit/write/web/LSP/MCP). 'read-only' inspects without edit/write. Plan-mode parents must pass 'read-only'."
1087
+ description: "Child permission level. Omit or 'full' for coding tools (read/search/shell/edit/write/web/LSP/MCP). 'read-only' inspects without edit/write. Read-only parents must pass 'read-only'."
1139
1088
  })), TaskItem = Type.Object({
1140
1089
  task: Type.String({ description: "Complete model-authored prompt sent to the child." }),
1141
1090
  description: DescriptionField,
@@ -1147,6 +1096,8 @@ var SkillOverride = Type.Unsafe({
1147
1096
  reads: Type.Optional(ReadsOverride),
1148
1097
  progress: Type.Optional(Type.Boolean({ description: "Enable progress.md tracking for this task" })),
1149
1098
  tier: TierOverride,
1099
+ model: ModelOverride,
1100
+ thinking: ThinkingOverride,
1150
1101
  skill: Type.Optional(SkillOverride),
1151
1102
  toolBudget: Type.Optional(ToolBudgetOverride),
1152
1103
  acceptance: Type.Optional(AcceptanceOverride)
@@ -1166,6 +1117,8 @@ var SkillOverride = Type.Unsafe({
1166
1117
  progress: Type.Optional(Type.Boolean({ description: "Enable progress.md tracking in {chain_dir}" })),
1167
1118
  skill: Type.Optional(SkillOverride),
1168
1119
  tier: TierOverride,
1120
+ model: ModelOverride,
1121
+ thinking: ThinkingOverride,
1169
1122
  toolBudget: Type.Optional(ToolBudgetOverride),
1170
1123
  acceptance: Type.Optional(AcceptanceOverride)
1171
1124
  }), DynamicExpandSchema = Type.Object({
@@ -1195,6 +1148,8 @@ var SkillOverride = Type.Unsafe({
1195
1148
  progress: Type.Optional(Type.Boolean({ description: "Enable progress.md tracking in {chain_dir}" })),
1196
1149
  skill: Type.Optional(SkillOverride),
1197
1150
  tier: TierOverride,
1151
+ model: ModelOverride,
1152
+ thinking: ThinkingOverride,
1198
1153
  toolBudget: Type.Optional(ToolBudgetOverride),
1199
1154
  acceptance: Type.Optional(AcceptanceOverride)
1200
1155
  }, { additionalProperties: !1 }), DynamicCollectSchema = Type.Object({
@@ -1217,6 +1172,8 @@ var SkillOverride = Type.Unsafe({
1217
1172
  progress: Type.Optional(Type.Boolean({ description: "Enable progress.md tracking in {chain_dir}" })),
1218
1173
  skill: Type.Optional(SkillOverride),
1219
1174
  tier: TierOverride,
1175
+ model: ModelOverride,
1176
+ thinking: ThinkingOverride,
1220
1177
  toolBudget: Type.Optional(ToolBudgetOverride),
1221
1178
  acceptance: Type.Optional(AcceptanceOverride),
1222
1179
  parallel: Type.Optional(Type.Unsafe({
@@ -1234,7 +1191,7 @@ var SkillOverride = Type.Unsafe({
1234
1191
  description: "Create isolated git worktrees for each parallel task."
1235
1192
  }))
1236
1193
  }, {
1237
- description: "Chain step: use {task, description, tier, permissions?} for sequential, {parallel: [...]} for static concurrent execution, or {expand, parallel: {...}, collect} for dynamic fanout. Every executable child requires tier.",
1194
+ description: "Chain step: use {task, description, tier|model, permissions?} for sequential, {parallel: [...]} for static concurrent execution, or {expand, parallel: {...}, collect} for dynamic fanout. Every executable child needs exactly one of tier or model.",
1238
1195
  additionalProperties: !1
1239
1196
  }), ControlOverrides = Type.Object({
1240
1197
  enabled: Type.Optional(Type.Boolean({ description: "Enable/disable subagent control attention tracking for this run" })),
@@ -1273,12 +1230,9 @@ var SkillOverride = Type.Unsafe({
1273
1230
  })),
1274
1231
  lines: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "Maximum transcript lines for action='status', view='transcript'. Defaults to 80." })),
1275
1232
  message: Type.Optional(Type.String({ description: "Follow-up message for action='resume' or non-terminal guidance for action='steer'. Use index to choose a child from multi-child runs." })),
1276
- scope: Type.Optional(Type.String({ enum: ["session", "user", "project"], description: "Scope for action='watchdog.configure'. Defaults to session to avoid persistent settings writes unless user/project is explicit." })),
1277
- target: Type.Optional(Type.String({ enum: ["main", "children"], description: "Target for action='watchdog.configure'. Defaults to main." })),
1278
- thinking: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "boolean", enum: [!1] }], description: "Thinking level for action='watchdog.configure' (off/minimal/low/medium/high/xhigh/max, inherit, or false for off)." })),
1279
1233
  schedule: Type.Optional(Type.String({ description: "Explicit one-shot schedule for action='schedule'. Only honored when scheduledRuns.enabled is true. Use '+10m' or a future ISO timestamp with timezone; scheduled runs always launch async with fresh context." })),
1280
1234
  scheduleName: Type.Optional(Type.String({ description: "Optional display name for action='schedule'." })),
1281
- tasks: Type.Optional(Type.Array(TaskItem, { description: "PARALLEL mode: [{task, description, tier, permissions?, count?, output?, outputMode?, reads?, progress?}, ...]" })),
1235
+ tasks: Type.Optional(Type.Array(TaskItem, { description: "PARALLEL mode: [{task, description, tier|model, thinking?, permissions?, count?, output?, outputMode?, reads?, progress?}, ...]" })),
1282
1236
  concurrency: Type.Optional(Type.Integer({ minimum: 1, description: "Top-level PARALLEL mode only: max concurrent tasks. Defaults to config.parallel.concurrency or unlimited." })),
1283
1237
  worktree: Type.Optional(Type.Boolean({
1284
1238
  description: "Create isolated git worktrees for parallel tasks; requires clean git state."
@@ -1289,7 +1243,7 @@ var SkillOverride = Type.Unsafe({
1289
1243
  description: "Children always start with a fresh session. Fork context is not available."
1290
1244
  })),
1291
1245
  chainDir: Type.Optional(Type.String({ description: "Persistent chain artifact directory; defaults to user-scoped temp storage." })),
1292
- async: Type.Optional(Type.Boolean({ description: "Run in background (default: false, or per config)" })),
1246
+ async: Type.Optional(Type.Boolean({ description: "Run async in the background. Defaults to true when omitted; set false for immediate foreground results." })),
1293
1247
  timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Optional run-level timeout in ms for foreground and async/background runs. Alias of maxRuntimeMs." })),
1294
1248
  maxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: "Alias of timeoutMs for optional run-level timeout in foreground and async/background runs." })),
1295
1249
  turnBudget: Type.Optional(TurnBudgetOverride),
@@ -1300,7 +1254,7 @@ var SkillOverride = Type.Unsafe({
1300
1254
  share: Type.Optional(Type.Boolean({ description: "Upload session to GitHub Gist for sharing (default: false)" })),
1301
1255
  sessionDir: Type.Optional(Type.String({ description: "Directory to store session logs (default: temp; enables sessions even if share=false)" })),
1302
1256
  // Clarification TUI
1303
- clarify: Type.Optional(Type.Boolean({ description: "Show TUI to preview/edit before execution. Explicit clarify: true keeps the run foreground for the clarify UI; omitted clarify can still run in the background when async: true is set." })),
1257
+ clarify: Type.Optional(Type.Boolean({ description: "Show the interactive TUI preview/editor before execution. clarify:true keeps the run foreground even when async is omitted or true." })),
1304
1258
  control: Type.Optional(ControlOverrides),
1305
1259
  output: Type.Optional(Type.Unsafe({
1306
1260
  anyOf: [
@@ -1313,15 +1267,26 @@ var SkillOverride = Type.Unsafe({
1313
1267
  skill: Type.Optional(SkillOverride),
1314
1268
  tier: Type.Optional(Type.String({
1315
1269
  enum: ["light", "standard", "heavy"],
1316
- description: "Required for SINGLE execution. Omit for control actions; PARALLEL and CHAIN children carry their own required tier."
1270
+ description: `Preferred for SINGLE execution. Required by default. Omit for control actions. Do not combine with model; PARALLEL and CHAIN children carry their own tier or model. ${TIER_SELECTION_DESCRIPTION}`
1271
+ })),
1272
+ model: Type.Optional(Type.String({
1273
+ minLength: 1,
1274
+ description: "Explicit provider/model for SINGLE execution only when the user names a model. Do not combine with tier."
1275
+ })),
1276
+ thinking: Type.Optional(Type.String({
1277
+ enum: ["off", "minimal", "low", "medium", "high", "xhigh", "max"],
1278
+ description: "Thinking level for an explicit model launch. Tier launches use configured tier thinking instead."
1317
1279
  })),
1318
1280
  acceptance: Type.Optional(AcceptanceOverride)
1319
1281
  }), SubagentParams = keepTopLevelParameterDescriptions(SubagentParamsSchema), SubagentWaitParamsSchema = Type.Object({
1320
1282
  id: Type.Optional(Type.String({
1321
1283
  description: "Async run or remembered detached foreground run id/prefix to wait for one specific run. Omit to wait across every active async run started in this session."
1322
1284
  })),
1285
+ questionId: Type.Optional(Type.String({
1286
+ description: "Wait for one supervisor question id from subagent_supervisor action='ask'. Returns when that question is answered, expired, or cancelled. Separate from final async run results."
1287
+ })),
1323
1288
  all: Type.Optional(Type.Boolean({
1324
- description: "Wait for ALL active runs to finish. Default false: return as soon as the first run finishes, so a fleet manager can spawn a replacement and wait again. Ignored when id targets a single run."
1289
+ description: "Wait for ALL active runs to finish. Default false: return as soon as the first run finishes, so a fleet manager can spawn a replacement and wait again. Ignored when id or questionId targets one item."
1325
1290
  })),
1326
1291
  timeoutMs: Type.Optional(Type.Integer({
1327
1292
  minimum: 1,
@@ -1346,28 +1311,28 @@ function typeName(value) {
1346
1311
  function quoteList(keys) {
1347
1312
  return keys.map((key) => `"${key}"`).join(", ");
1348
1313
  }
1349
- function disallowedMessage(path12, keys, allowed, example) {
1314
+ function disallowedMessage(path13, keys, allowed, example) {
1350
1315
  let subject = keys.length === 1 ? `property "${keys[0]}" is not allowed` : `properties ${quoteList(keys)} are not allowed`, examplePart = example ? `
1351
1316
 
1352
1317
  Example: ${example}` : "";
1353
- return `subagent ${path12}: ${subject}.
1318
+ return `subagent ${path13}: ${subject}.
1354
1319
  Allowed properties: ${allowed.join(", ")}.${examplePart}`;
1355
1320
  }
1356
- function expectObject(value, path12, allowed, example) {
1321
+ function expectObject(value, path13, allowed, example) {
1357
1322
  if (!isPlainObject(value)) {
1358
1323
  let examplePart = example ? `
1359
1324
 
1360
1325
  Example: ${example}` : "";
1361
- throw new Error(`subagent ${path12}: expected an object, received ${typeName(value)}.
1326
+ throw new Error(`subagent ${path13}: expected an object, received ${typeName(value)}.
1362
1327
  Allowed properties: ${allowed.join(", ")}.${examplePart}`);
1363
1328
  }
1364
1329
  }
1365
- function checkNoExtraKeys(value, path12, schema, allowed, example) {
1330
+ function checkNoExtraKeys(value, path13, schema, allowed, example) {
1366
1331
  if (schema.additionalProperties !== !1)
1367
1332
  return;
1368
1333
  let extra = disallowedKeys(value, allowed);
1369
1334
  if (extra.length > 0)
1370
- throw new Error(disallowedMessage(path12, extra, allowed, example));
1335
+ throw new Error(disallowedMessage(path13, extra, allowed, example));
1371
1336
  }
1372
1337
  function validateChainInput(args) {
1373
1338
  if (!isPlainObject(args))
@@ -1525,7 +1490,7 @@ function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
1525
1490
  if (parsed.type !== "subagent.control")
1526
1491
  return;
1527
1492
  let record = parsed;
1528
- if (!record.event || !Array.isArray(record.channels))
1493
+ if (!record.event || !Array.isArray(record.channels) || record.event.reason === "completion_guard")
1529
1494
  return;
1530
1495
  let payload = {
1531
1496
  event: record.event,
@@ -1620,8 +1585,7 @@ function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
1620
1585
  }
1621
1586
  widgetRenderKey(job) !== widgetStateBefore && (widgetChanged = !0);
1622
1587
  }
1623
- let timerNeedsPaint = [...state.asyncJobs.values()].some((job) => job.status === "running");
1624
- (widgetChanged || timerNeedsPaint) && state.lastUiContext?.hasUI && rerenderWidget(state.lastUiContext);
1588
+ widgetChanged && state.lastUiContext?.hasUI && rerenderWidget(state.lastUiContext);
1625
1589
  }, pollIntervalMs), state.poller.unref?.());
1626
1590
  };
1627
1591
  return { ensurePoller, refreshWidget, handleStarted: (data) => {
@@ -1761,15 +1725,15 @@ function createFileCoalescer(handler, defaultDelayMs, timerApi = defaultTimerApi
1761
1725
 
1762
1726
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.js
1763
1727
  var WATCHER_RESTART_DELAY_MS = 3e3, POLL_INTERVAL_MS2 = 3e3;
1764
- function sanitizeNestedResultChildren(value, resultPath, label) {
1728
+ function sanitizeNestedResultChildren(value, resultPath, label, report) {
1765
1729
  if (value === void 0)
1766
1730
  return;
1767
1731
  if (!Array.isArray(value)) {
1768
- console.error(`Ignoring invalid nested children in subagent result file '${resultPath}' at ${label}: expected an array.`);
1732
+ report(`Ignoring invalid nested children in subagent result file '${resultPath}' at ${label}: expected an array.`);
1769
1733
  return;
1770
1734
  }
1771
1735
  let children = value.map((child) => sanitizeSummary(child)).filter((child) => !!child);
1772
- return children.length !== value.length && console.error(`Ignoring ${value.length - children.length} invalid nested child record(s) in subagent result file '${resultPath}' at ${label}.`), children.length ? children : void 0;
1736
+ return children.length !== value.length && report(`Ignoring ${value.length - children.length} invalid nested child record(s) in subagent result file '${resultPath}' at ${label}.`), children.length ? children : void 0;
1773
1737
  }
1774
1738
  function getErrorCode(error) {
1775
1739
  return typeof error == "object" && error !== null && "code" in error ? error.code : void 0;
@@ -1782,27 +1746,27 @@ function shouldFallBackToPolling(error) {
1782
1746
  return code === "EMFILE" || code === "ENOSPC";
1783
1747
  }
1784
1748
  function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {}) {
1785
- let fsApi = deps.fs ?? fs2, timers = deps.timers ?? { setTimeout, clearTimeout, setInterval, clearInterval }, handleResult = async (file) => {
1786
- let resultPath = path2.join(resultsDir, file);
1787
- if (fsApi.existsSync(resultPath))
1749
+ let fsApi = deps.fs ?? fs2, timers = deps.timers ?? { setTimeout, clearTimeout, setInterval, clearInterval }, generation = 0, inFlight = /* @__PURE__ */ new Set(), attempts = /* @__PURE__ */ new Map(), report = (message, error) => {
1750
+ pi.appendEntry?.("subagent_result_delivery", { message, error: error instanceof Error ? error.message : error });
1751
+ }, handleResult = async (file) => {
1752
+ if (inFlight.has(file) || (attempts.get(file) ?? 0) >= 3)
1753
+ return;
1754
+ let currentGeneration = generation, sessionId = state.currentSessionId, isCurrent = () => generation === currentGeneration && state.currentSessionId === sessionId, resultPath = path2.join(resultsDir, file);
1755
+ if (fsApi.existsSync(resultPath)) {
1756
+ inFlight.add(file);
1788
1757
  try {
1789
1758
  let data = JSON.parse(fsApi.readFileSync(resultPath, "utf-8"));
1790
1759
  if (typeof data.sessionId != "string" || data.sessionId !== state.currentSessionId)
1791
1760
  return;
1792
- let runId = data.runId ?? data.id ?? file.replace(/\.json$/i, ""), hasExplicitNestedChildren = data.nestedChildren !== void 0, nestedChildren = compactNestedResultChildren(sanitizeNestedResultChildren(data.nestedChildren, resultPath, "nestedChildren"));
1761
+ let runId = data.runId ?? data.id ?? file.replace(/\.json$/i, ""), hasExplicitNestedChildren = data.nestedChildren !== void 0, nestedChildren = compactNestedResultChildren(sanitizeNestedResultChildren(data.nestedChildren, resultPath, "nestedChildren", report));
1793
1762
  if (!nestedChildren?.length && !hasExplicitNestedChildren)
1794
1763
  try {
1795
1764
  nestedChildren = compactNestedResultChildren(projectNestedRegistryForRoot(runId)?.children);
1796
1765
  } catch (error) {
1797
- console.error(`Failed to enrich subagent result file '${resultPath}' with nested registry children; will retry later:`, error);
1766
+ report(`Failed to enrich subagent result file '${resultPath}' with nested registry children; will retry later:`, error);
1798
1767
  return;
1799
1768
  }
1800
- let now = Date.now(), completionKey = buildCompletionKey(data, `result:${file}`);
1801
- if (markSeenWithTtl(state.completionSeen, completionKey, now, completionTtlMs)) {
1802
- fsApi.unlinkSync(resultPath);
1803
- return;
1804
- }
1805
- let hasResultChildren = Array.isArray(data.results) && data.results.length > 0, resultChildren = hasResultChildren ? data.results : [{
1769
+ let now = Date.now(), completionKey = buildCompletionKey(data, `result:${file}`), hasResultChildren = Array.isArray(data.results) && data.results.length > 0, resultChildren = hasResultChildren ? data.results : [{
1806
1770
  agent: data.agent,
1807
1771
  output: data.summary,
1808
1772
  success: data.success
@@ -1810,7 +1774,7 @@ function createResultWatcher(pi, state, resultsDir, completionTtlMs, deps = {})
1810
1774
  let baseOutput = result2.output ?? data.summary, hasRealOutput = typeof baseOutput == "string" && baseOutput.trim().length > 0, output = hasRealOutput ? baseOutput : "(no output)", summary = result2.success === !1 && result2.error ? `${result2.error}${hasRealOutput ? `
1811
1775
 
1812
1776
  Output:
1813
- ${baseOutput}` : ""}` : output, sessionPath = result2.sessionFile ?? (resultChildren.length === 1 ? data.sessionFile : void 0), childNestedChildren = sanitizeNestedResultChildren(result2.children, resultPath, `results[${index}].children`), childState = result2.state === "paused" || result2.state === "stopped" ? result2.state : result2.stopped === !0 ? "stopped" : data.state === "paused" || !hasResultChildren && (data.state === "stopped" || typeof result2.success != "boolean") ? data.state : void 0;
1777
+ ${baseOutput}` : ""}` : output, sessionPath = result2.sessionFile ?? (resultChildren.length === 1 ? data.sessionFile : void 0), childNestedChildren = sanitizeNestedResultChildren(result2.children, resultPath, `results[${index}].children`, report), childState = result2.state === "paused" || result2.state === "stopped" ? result2.state : result2.stopped === !0 ? "stopped" : data.state === "paused" || !hasResultChildren && (data.state === "stopped" || typeof result2.success != "boolean") ? data.state : void 0;
1814
1778
  return {
1815
1779
  agent: result2.agent ?? data.agent ?? `step-${index + 1}`,
1816
1780
  status: resolveSubagentResultStatus({
@@ -1824,7 +1788,24 @@ ${baseOutput}` : ""}` : output, sessionPath = result2.sessionFile ?? (resultChil
1824
1788
  ...result2.intercomTarget ? { intercomTarget: result2.intercomTarget } : {},
1825
1789
  ...childNestedChildren ? { children: childNestedChildren } : {}
1826
1790
  };
1827
- }), nestedChildren), intercomTarget = data.intercomTarget?.trim();
1791
+ }), nestedChildren);
1792
+ if (markSeenWithTtl(state.completionSeen, completionKey, now, completionTtlMs) || pi.events.emit(SUBAGENT_ASYNC_COMPLETE_EVENT, {
1793
+ ...data,
1794
+ runId,
1795
+ ...nestedChildren?.length ? { nestedChildren } : {},
1796
+ ...Array.isArray(data.results) ? { results: hasResultChildren ? normalizedChildren.map((child, index) => ({
1797
+ ...data.results[index],
1798
+ agent: child.agent,
1799
+ status: child.status,
1800
+ summary: child.summary,
1801
+ index: child.index,
1802
+ artifactPath: child.artifactPath,
1803
+ sessionPath: child.sessionPath,
1804
+ children: child.children
1805
+ })) : [] } : {}
1806
+ }), !isCurrent())
1807
+ return;
1808
+ let intercomTarget = data.state === "stopped" ? void 0 : data.intercomTarget?.trim();
1828
1809
  if (intercomTarget) {
1829
1810
  let mode = data.mode === "single" || data.mode === "parallel" || data.mode === "chain" ? data.mode : resultChildren.length > 1 ? "chain" : "single", payload = buildSubagentResultIntercomPayload({
1830
1811
  to: intercomTarget,
@@ -1835,30 +1816,24 @@ ${baseOutput}` : ""}` : output, sessionPath = result2.sessionFile ?? (resultChil
1835
1816
  asyncId: data.id,
1836
1817
  asyncDir: data.asyncDir
1837
1818
  });
1838
- await deliverSubagentResultIntercomEvent(pi.events, payload) || console.error(`Subagent async grouped result intercom delivery was not acknowledged for '${resultPath}'.`);
1819
+ payload.requestId = `async-result:${sessionId}:${completionKey}`, payload.ownerNotificationSessionId = sessionId, attempts.set(file, (attempts.get(file) ?? 0) + 1);
1820
+ let delivered = await deliverSubagentResultIntercomEvent(pi.events, payload);
1821
+ if (!isCurrent())
1822
+ return;
1823
+ if (!delivered) {
1824
+ report(`Async result delivery pending for '${runId}'; output retained.`, resultPath), attempts.get(file) < 3 && state.resultFileCoalescer.schedule(file, 1e3);
1825
+ return;
1826
+ }
1839
1827
  }
1840
- pi.events.emit(SUBAGENT_ASYNC_COMPLETE_EVENT, {
1841
- ...data,
1842
- runId,
1843
- ...nestedChildren?.length ? { nestedChildren } : {},
1844
- ...Array.isArray(data.results) ? {
1845
- results: hasResultChildren ? normalizedChildren.map((child, index) => ({
1846
- ...data.results[index],
1847
- agent: child.agent,
1848
- status: child.status,
1849
- summary: child.summary,
1850
- index: child.index,
1851
- artifactPath: child.artifactPath,
1852
- sessionPath: child.sessionPath,
1853
- children: child.children
1854
- })) : []
1855
- } : {}
1856
- }), fsApi.unlinkSync(resultPath);
1828
+ isCurrent() && fsApi.unlinkSync(resultPath);
1857
1829
  } catch (error) {
1858
1830
  if (isNotFoundError(error))
1859
1831
  return;
1860
- console.error(`Failed to process subagent result file '${resultPath}':`, error);
1832
+ report(`Failed to process subagent result file '${resultPath}'.`, error);
1833
+ } finally {
1834
+ inFlight.delete(file);
1861
1835
  }
1836
+ }
1862
1837
  };
1863
1838
  state.resultFileCoalescer = createFileCoalescer((file) => {
1864
1839
  handleResult(file);
@@ -1869,10 +1844,10 @@ ${baseOutput}` : ""}` : output, sessionPath = result2.sessionFile ?? (resultChil
1869
1844
  } catch (error) {
1870
1845
  if (isNotFoundError(error))
1871
1846
  return;
1872
- console.error(`Failed to scan subagent result directory '${resultsDir}':`, error);
1847
+ report(`Failed to scan subagent result directory '${resultsDir}':`, error);
1873
1848
  }
1874
1849
  }, startPollingFallback = (reason) => {
1875
- state.watcher?.close(), state.watcher = null, !state.watcherRestartTimer && (console.error(`Subagent result watcher for '${resultsDir}' fell back to polling because native fs.watch is unavailable (${getErrorCode(reason) ?? "unknown error"}).`), primeExistingResults(), state.watcherRestartTimer = timers.setInterval(primeExistingResults, POLL_INTERVAL_MS2), state.watcherRestartTimer.unref?.());
1850
+ state.watcher?.close(), state.watcher = null, !state.watcherRestartTimer && (report(`Subagent result watcher for '${resultsDir}' fell back to polling because native fs.watch is unavailable (${getErrorCode(reason) ?? "unknown error"}).`), primeExistingResults(), state.watcherRestartTimer = timers.setInterval(primeExistingResults, POLL_INTERVAL_MS2), state.watcherRestartTimer.unref?.());
1876
1851
  }, scheduleRestart = () => {
1877
1852
  state.watcherRestartTimer || (state.watcherRestartTimer = timers.setTimeout(() => {
1878
1853
  state.watcherRestartTimer = null;
@@ -1883,7 +1858,7 @@ ${baseOutput}` : ""}` : output, sessionPath = result2.sessionFile ?? (resultChil
1883
1858
  startPollingFallback(error);
1884
1859
  return;
1885
1860
  }
1886
- console.error(`Failed to restart subagent result watcher for '${resultsDir}':`, error), scheduleRestart();
1861
+ report(`Failed to restart subagent result watcher for '${resultsDir}':`, error), scheduleRestart();
1887
1862
  }
1888
1863
  }, WATCHER_RESTART_DELAY_MS), state.watcherRestartTimer.unref?.());
1889
1864
  }, startResultWatcher = () => {
@@ -1901,19 +1876,19 @@ ${baseOutput}` : ""}` : output, sessionPath = result2.sessionFile ?? (resultChil
1901
1876
  startPollingFallback(error);
1902
1877
  return;
1903
1878
  }
1904
- console.error(`Subagent result watcher failed for '${resultsDir}':`, error), state.watcher?.close(), state.watcher = null, scheduleRestart();
1879
+ report(`Subagent result watcher failed for '${resultsDir}':`, error), state.watcher?.close(), state.watcher = null, scheduleRestart();
1905
1880
  }), state.watcher.unref?.();
1906
1881
  } catch (error) {
1907
1882
  if (shouldFallBackToPolling(error)) {
1908
1883
  startPollingFallback(error);
1909
1884
  return;
1910
1885
  }
1911
- console.error(`Failed to start subagent result watcher for '${resultsDir}':`, error), state.watcher = null, scheduleRestart();
1886
+ report(`Failed to start subagent result watcher for '${resultsDir}':`, error), state.watcher = null, scheduleRestart();
1912
1887
  }
1913
1888
  }
1914
1889
  };
1915
1890
  return { startResultWatcher, primeExistingResults, stopResultWatcher: () => {
1916
- state.watcher?.close(), state.watcher = null, state.watcherRestartTimer && (timers.clearTimeout(state.watcherRestartTimer), timers.clearInterval(state.watcherRestartTimer)), state.watcherRestartTimer = null, state.resultFileCoalescer.clear();
1891
+ generation++, attempts.clear(), state.watcher?.close(), state.watcher = null, state.watcherRestartTimer && (timers.clearTimeout(state.watcherRestartTimer), timers.clearInterval(state.watcherRestartTimer)), state.watcherRestartTimer = null, state.resultFileCoalescer.clear();
1917
1892
  } };
1918
1893
  }
1919
1894
 
@@ -2446,7 +2421,7 @@ function substituteArgs(template, args) {
2446
2421
  return template.replace(/\$ARGUMENTS/g, all).replace(/\$@/g, all).replace(/\$\{(\d+):-([^}]*)\}/g, (_match, index, fallback) => args[Number(index) - 1] || fallback).replace(/\$(\d+)/g, (_match, index) => args[Number(index) - 1] ?? "");
2447
2422
  }
2448
2423
  function parseRuntimeOptions(words) {
2449
- let args = [], descriptionOverride, permissions, worktree = !1, bg = !1;
2424
+ let args = [], descriptionOverride, permissions, worktree = !1, async;
2450
2425
  for (let i = 0; i < words.length; i++) {
2451
2426
  let word = words[i];
2452
2427
  if (word === "--read-only") {
@@ -2462,7 +2437,11 @@ function parseRuntimeOptions(words) {
2462
2437
  continue;
2463
2438
  }
2464
2439
  if (word === "--bg" || word === "--async") {
2465
- bg = !0;
2440
+ async = !0;
2441
+ continue;
2442
+ }
2443
+ if (word === "--fg" || word === "--foreground") {
2444
+ async = !1;
2466
2445
  continue;
2467
2446
  }
2468
2447
  if (word === "--description") {
@@ -2476,7 +2455,7 @@ function parseRuntimeOptions(words) {
2476
2455
  }
2477
2456
  args.push(word);
2478
2457
  }
2479
- return { args, descriptionOverride, permissions, worktree, bg };
2458
+ return { args, descriptionOverride, permissions, worktree, async };
2480
2459
  }
2481
2460
  function splitChainDeclaration(input) {
2482
2461
  let delimiter = input.indexOf(" -- ");
@@ -2495,7 +2474,7 @@ function workflowParams(workflow, args, runtime) {
2495
2474
  ...workflow.skill !== void 0 ? { skill: workflow.skill } : {},
2496
2475
  ...workflow.cwd ? { cwd: workflow.cwd } : {},
2497
2476
  ...runtime.worktree || workflow.worktree ? { worktree: !0 } : {},
2498
- ...runtime.bg ? { async: !0 } : {}
2477
+ ...runtime.async !== void 0 ? { async: runtime.async } : {}
2499
2478
  };
2500
2479
  }
2501
2480
  function workflowChainStep(workflow, args, runtime) {
@@ -2543,7 +2522,7 @@ function registerPromptWorkflowCommands(input) {
2543
2522
  throw new Error(`Unknown prompt workflow in chain '${workflow.name}': ${stepName}`);
2544
2523
  return workflowChainStep(step, runtime.args, runtime);
2545
2524
  });
2546
- await run({ chain, task: runtime.args.join(" "), clarify: !1, ...runtime.bg ? { async: !0 } : {} }, ctx);
2525
+ await run({ chain, task: runtime.args.join(" "), clarify: !1, ...runtime.async !== void 0 ? { async: runtime.async } : {} }, ctx);
2547
2526
  return;
2548
2527
  }
2549
2528
  await run(workflowParams(workflow, runtime.args, runtime), ctx);
@@ -2571,7 +2550,7 @@ function registerPromptWorkflowCommands(input) {
2571
2550
  throw new Error(`Unknown prompt workflow: ${name}`);
2572
2551
  return workflowChainStep(workflow, runtime.args, runtime);
2573
2552
  });
2574
- await run({ chain, task: runtime.args.join(" "), clarify: !1, ...runtime.bg ? { async: !0 } : {} }, ctx);
2553
+ await run({ chain, task: runtime.args.join(" "), clarify: !1, ...runtime.async !== void 0 ? { async: runtime.async } : {} }, ctx);
2575
2554
  } catch (error) {
2576
2555
  ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
2577
2556
  }
@@ -3102,6 +3081,12 @@ var parseInlineConfig = (raw) => {
3102
3081
  case "tier":
3103
3082
  (val === "light" || val === "standard" || val === "heavy") && (config.tier = val);
3104
3083
  break;
3084
+ case "model":
3085
+ val && (config.model = val);
3086
+ break;
3087
+ case "thinking":
3088
+ ["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(val) && (config.thinking = val);
3089
+ break;
3105
3090
  case "permissions":
3106
3091
  (val === "full" || val === "read-only") && (config.permissions = val);
3107
3092
  break;
@@ -3145,15 +3130,14 @@ var parseInlineConfig = (raw) => {
3145
3130
  let end = token.lastIndexOf("]");
3146
3131
  return { name: token.slice(0, bracket), config: parseInlineConfig(token.slice(bracket + 1, end !== -1 ? end : void 0)) };
3147
3132
  }, extractExecutionFlags = (rawArgs) => {
3148
- let args = rawArgs.trim(), bg = !1;
3133
+ let args = rawArgs.trim(), async;
3149
3134
  for (; ; ) {
3150
- if (args.endsWith(" --bg") || args === "--bg") {
3151
- bg = !0, args = args === "--bg" ? "" : args.slice(0, -5).trim();
3152
- continue;
3153
- }
3154
- break;
3135
+ let match = args.match(/(?:^|\s)(--bg|--async|--fg|--foreground)$/);
3136
+ if (!match)
3137
+ break;
3138
+ async ??= match[1] === "--bg" || match[1] === "--async", args = args.slice(0, match.index).trim();
3155
3139
  }
3156
- return { args, bg };
3140
+ return { args, async };
3157
3141
  };
3158
3142
  function sendSlashText(pi, text) {
3159
3143
  pi.sendMessage({ customType: SLASH_TEXT_RESULT_TYPE, content: text, display: !0 });
@@ -3651,12 +3635,16 @@ function loadInlineOutputSchema(baseCwd, agent, value) {
3651
3635
  }
3652
3636
  var mapParsedTaskToStepObject = (step, fallbackTask, isFirst, opts) => {
3653
3637
  let { name, config, task: stepTask } = step;
3654
- if (!config.tier)
3655
- throw new SlashParseError(`Step '${name}' requires tier=light, tier=standard, or tier=heavy.`);
3638
+ if (!config.tier && !config.model)
3639
+ throw new SlashParseError(`Step '${name}' requires tier=light|standard|heavy or model=provider/id.`);
3640
+ if (config.tier && config.model)
3641
+ throw new SlashParseError(`Step '${name}' must choose exactly one of tier or model.`);
3656
3642
  return config.acceptance !== void 0 && validateInlineAcceptanceInput(config.acceptance, name), {
3657
3643
  description: name,
3658
3644
  permissions: config.permissions ?? "full",
3659
- tier: config.tier,
3645
+ ...config.tier ? { tier: config.tier } : {},
3646
+ ...config.model ? { model: config.model } : {},
3647
+ ...config.thinking ? { thinking: config.thinking } : {},
3660
3648
  ...stepTask ? { task: stepTask } : isFirst && fallbackTask ? { task: fallbackTask } : {},
3661
3649
  ...config.output !== void 0 ? { output: config.output } : {},
3662
3650
  ...config.outputMode !== void 0 ? { outputMode: config.outputMode } : {},
@@ -3730,16 +3718,16 @@ function registerSlashCommands(pi, state) {
3730
3718
  }
3731
3719
  };
3732
3720
  pi.registerCommand("run", {
3733
- description: "Run a prompt-defined child: /run description[tier=standard] task [--bg]",
3721
+ description: "Run an async prompt-defined child; add --foreground to wait inline",
3734
3722
  handler: async (args, ctx) => {
3735
- let { args: cleanedArgs, bg } = extractExecutionFlags(args), input = cleanedArgs.trim(), firstSpace = input.indexOf(" ");
3723
+ let { args: cleanedArgs, async } = extractExecutionFlags(args), input = cleanedArgs.trim(), firstSpace = input.indexOf(" ");
3736
3724
  if (!input) {
3737
- ctx.ui.notify("Usage: /run <description> <task> [--bg]", "error");
3725
+ ctx.ui.notify("Usage: /run <description> <task> [--foreground]", "error");
3738
3726
  return;
3739
3727
  }
3740
3728
  let { name: description, config: inline } = parseAgentToken(firstSpace === -1 ? input : input.slice(0, firstSpace)), task = firstSpace === -1 ? "" : input.slice(firstSpace + 1).trim();
3741
3729
  if (!description || !task || !inline.tier) {
3742
- ctx.ui.notify("Usage: /run <description>[tier=light|standard|heavy] <task> [--bg]", "error");
3730
+ ctx.ui.notify("Usage: /run <description>[tier=light|standard|heavy] <task> [--foreground]", "error");
3743
3731
  return;
3744
3732
  }
3745
3733
  let finalTask = task;
@@ -3747,27 +3735,29 @@ function registerSlashCommands(pi, state) {
3747
3735
 
3748
3736
  ${finalTask}`);
3749
3737
  let params = { description, permissions: inline.permissions ?? "full", tier: inline.tier, task: finalTask, clarify: !1 };
3750
- inline.output !== void 0 && (params.output = inline.output), inline.outputMode !== void 0 && (params.outputMode = inline.outputMode), inline.skill !== void 0 && (params.skill = inline.skill), bg && (params.async = !0), await runSlashSubagent(pi, ctx, params);
3738
+ inline.output !== void 0 && (params.output = inline.output), inline.outputMode !== void 0 && (params.outputMode = inline.outputMode), inline.skill !== void 0 && (params.skill = inline.skill), async !== void 0 && (params.async = async), await runSlashSubagent(pi, ctx, params);
3751
3739
  }
3752
3740
  }), pi.registerCommand("chain", {
3753
- description: 'Run prompt-defined children in sequence: /chain inspect "task" -> implement [--bg]',
3741
+ description: "Run prompt-defined children as an async sequence; add --foreground to wait inline",
3754
3742
  handler: async (args, ctx) => {
3755
- let { args: cleanedArgs, bg } = extractExecutionFlags(args), built = buildChainExpressionSteps(state, cleanedArgs, ctx);
3743
+ let { args: cleanedArgs, async } = extractExecutionFlags(args), built = buildChainExpressionSteps(state, cleanedArgs, ctx);
3756
3744
  if (!built)
3757
3745
  return;
3758
3746
  let params = { chain: built.chain, task: built.task, clarify: !1 };
3759
- bg && (params.async = !0), await runSlashSubagent(pi, ctx, params);
3747
+ async !== void 0 && (params.async = async), await runSlashSubagent(pi, ctx, params);
3760
3748
  }
3761
3749
  }), pi.registerCommand("parallel", {
3762
- description: 'Run prompt-defined children in parallel: /parallel inspect "task1" -> review "task2" [--bg]',
3750
+ description: "Run prompt-defined children async in parallel; add --foreground to wait inline",
3763
3751
  handler: async (args, ctx) => {
3764
- let { args: cleanedArgs, bg } = extractExecutionFlags(args), parsed = parseAgentArgs(state, cleanedArgs, "parallel", ctx);
3752
+ let { args: cleanedArgs, async } = extractExecutionFlags(args), parsed = parseAgentArgs(state, cleanedArgs, "parallel", ctx);
3765
3753
  if (!parsed)
3766
3754
  return;
3767
3755
  let tasks = parsed.steps.map(({ name, config, task: stepTask }) => ({
3768
3756
  description: name,
3769
3757
  permissions: config.permissions ?? "full",
3770
- tier: config.tier,
3758
+ ...config.tier ? { tier: config.tier } : {},
3759
+ ...config.model ? { model: config.model } : {},
3760
+ ...config.thinking ? { thinking: config.thinking } : {},
3771
3761
  task: stepTask ?? parsed.task,
3772
3762
  ...config.output !== void 0 ? { output: config.output } : {},
3773
3763
  ...config.outputMode !== void 0 ? { outputMode: config.outputMode } : {},
@@ -3775,12 +3765,16 @@ ${finalTask}`);
3775
3765
  ...config.skill !== void 0 ? { skill: config.skill } : {},
3776
3766
  ...config.progress !== void 0 ? { progress: config.progress } : {}
3777
3767
  }));
3778
- if (tasks.some((task) => !task.tier)) {
3779
- ctx.ui.notify("Every parallel child requires [tier=light|standard|heavy].", "error");
3768
+ if (tasks.some((task) => !task.tier && !task.model)) {
3769
+ ctx.ui.notify("Every parallel child requires [tier=light|standard|heavy] or [model=provider/id].", "error");
3770
+ return;
3771
+ }
3772
+ if (tasks.some((task) => task.tier && task.model)) {
3773
+ ctx.ui.notify("Each parallel child must choose exactly one of tier or model.", "error");
3780
3774
  return;
3781
3775
  }
3782
3776
  let params = { tasks, clarify: !1 };
3783
- bg && (params.async = !0), await runSlashSubagent(pi, ctx, params);
3777
+ async !== void 0 && (params.async = async), await runSlashSubagent(pi, ctx, params);
3784
3778
  }
3785
3779
  }), pi.registerCommand("subagent-cost", {
3786
3780
  description: "Show parent and subagent child usage cost for this session",
@@ -4404,28 +4398,582 @@ function registerSlashSubagentBridge(options) {
4404
4398
  }
4405
4399
 
4406
4400
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js
4401
+ import * as fs7 from "node:fs";
4402
+ import * as path8 from "node:path";
4403
+ import { Type as Type2 } from "typebox";
4404
+
4405
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.js
4406
+ import { randomUUID as randomUUID3 } from "node:crypto";
4407
4407
  import * as fs6 from "node:fs";
4408
4408
  import * as path7 from "node:path";
4409
- import { Type as Type2 } from "typebox";
4410
- var SUPERVISOR_CHANNEL_ROOT = path7.join(TEMP_ROOT_DIR, "supervisor-channels"), REQUESTS_DIR = "requests", REPLIES_DIR = "replies", NATIVE_SUPERVISOR_TOOL_NAME = "subagent_supervisor", MAX_MESSAGE_BYTES = 64 * 1024, DEFAULT_ASK_TIMEOUT_MS = 600 * 1e3, CHANNEL_POLL_MS = Math.min(POLL_INTERVAL_MS, 500), STALE_EMPTY_CHANNEL_AGE_MS = 60 * 1e3, STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS = 60 * 1e3, ContactSupervisorParamsSchema = Type2.Object({
4411
- reason: Type2.String({ enum: ["need_decision", "interview_request", "progress_update"] }),
4409
+ var QUESTIONS_DIR = "questions", SUPERVISOR_CHANNEL_ROOT = path7.join(TEMP_ROOT_DIR, "supervisor-channels"), SUBAGENT_SUPERVISOR_ANSWER_TYPE = "subagent_supervisor_answer", SUBAGENT_QUESTION_EVENT = "subagent:supervisor-question", MAX_MESSAGE_BYTES = 64 * 1024, DEFAULT_ASK_TIMEOUT_MS = 600 * 1e3, activeQuestionWaits = /* @__PURE__ */ new Set();
4410
+ function askTimeoutMs() {
4411
+ let parsed = Number(process.env.PI_INTERCOM_ASK_TIMEOUT_MS);
4412
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_ASK_TIMEOUT_MS;
4413
+ }
4414
+ function safeSegment(value) {
4415
+ return value.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "unknown";
4416
+ }
4417
+ function resolveSupervisorChannelDir(runId, agent, childIndex) {
4418
+ return path7.join(SUPERVISOR_CHANNEL_ROOT, `${safeSegment(runId)}-${safeSegment(agent)}-${childIndex}`);
4419
+ }
4420
+ function questionsDir(channelDir) {
4421
+ return path7.join(channelDir, QUESTIONS_DIR);
4422
+ }
4423
+ function questionFile(channelDir, questionId) {
4424
+ return path7.join(questionsDir(channelDir), `${safeSegment(questionId)}.json`);
4425
+ }
4426
+ function deliveredFile(channelDir, questionId) {
4427
+ return path7.join(questionsDir(channelDir), `${safeSegment(questionId)}.delivered.json`);
4428
+ }
4429
+ function terminalFile(channelDir, questionId) {
4430
+ return path7.join(questionsDir(channelDir), `${safeSegment(questionId)}.terminal.json`);
4431
+ }
4432
+ function notifiedFile(channelDir, questionId) {
4433
+ return path7.join(questionsDir(channelDir), `${safeSegment(questionId)}.notified.json`);
4434
+ }
4435
+ function lateFile(channelDir, questionId) {
4436
+ return path7.join(questionsDir(channelDir), `${safeSegment(questionId)}.late.json`);
4437
+ }
4438
+ function writeExclusiveJson(filePath, payload) {
4439
+ fs6.mkdirSync(path7.dirname(filePath), { recursive: !0, mode: 448 });
4440
+ let temporary = `${filePath}.${randomUUID3()}.tmp`;
4441
+ try {
4442
+ return fs6.writeFileSync(temporary, JSON.stringify(payload), { encoding: "utf-8", flag: "wx", mode: 384 }), fs6.linkSync(temporary, filePath), !0;
4443
+ } catch (error) {
4444
+ if (error.code === "EEXIST")
4445
+ return !1;
4446
+ throw error;
4447
+ } finally {
4448
+ fs6.rmSync(temporary, { force: !0 });
4449
+ }
4450
+ }
4451
+ function readJsonFile(filePath) {
4452
+ return JSON.parse(fs6.readFileSync(filePath, "utf-8"));
4453
+ }
4454
+ function tryReadJson(filePath) {
4455
+ try {
4456
+ return readJsonFile(filePath);
4457
+ } catch (error) {
4458
+ return error.code === "ENOENT", void 0;
4459
+ }
4460
+ }
4461
+ function parseIncarnation(raw) {
4462
+ if (!raw || typeof raw != "object" || Array.isArray(raw))
4463
+ return;
4464
+ let input = raw, pid = input.pid, readyAt = input.readyAt;
4465
+ if (!(!Number.isInteger(pid) || pid === void 0 || pid <= 0) && !(typeof readyAt != "number" || !Number.isFinite(readyAt) || readyAt <= 0))
4466
+ return { pid, readyAt };
4467
+ }
4468
+ function parseQuestionRecord(raw) {
4469
+ if (!raw || typeof raw != "object" || Array.isArray(raw))
4470
+ return;
4471
+ let input = raw;
4472
+ if (input.type !== "subagent.supervisor.question" || typeof input.id != "string" || !input.id.trim() || typeof input.createdAt != "number" || !Number.isFinite(input.createdAt) || typeof input.expiresAt != "number" || !Number.isFinite(input.expiresAt) || typeof input.reason != "string" || !input.reason.trim() || typeof input.message != "string" || !input.message.trim() || typeof input.runId != "string" || !input.runId.trim())
4473
+ return;
4474
+ let childIndex = input.childIndex;
4475
+ if (!Number.isInteger(childIndex) || childIndex === void 0 || childIndex < 0 || typeof input.childId != "string" || !input.childId.trim() || typeof input.parentSessionId != "string" || !input.parentSessionId.trim())
4476
+ return;
4477
+ let parentGeneration = input.parentGeneration;
4478
+ if (!Number.isInteger(parentGeneration) || parentGeneration === void 0 || parentGeneration < 0)
4479
+ return;
4480
+ let incarnation = parseIncarnation(input.childIncarnation);
4481
+ return {
4482
+ type: "subagent.supervisor.question",
4483
+ id: input.id.trim(),
4484
+ createdAt: input.createdAt,
4485
+ expiresAt: input.expiresAt,
4486
+ reason: input.reason.trim(),
4487
+ message: input.message.trim(),
4488
+ runId: input.runId.trim(),
4489
+ childIndex,
4490
+ childId: input.childId.trim(),
4491
+ ...typeof input.childDescription == "string" && input.childDescription.trim() ? { childDescription: input.childDescription.trim() } : {},
4492
+ parentSessionId: input.parentSessionId.trim(),
4493
+ parentGeneration,
4494
+ ...incarnation ? { childIncarnation: incarnation } : {}
4495
+ };
4496
+ }
4497
+ function parseDeliveredRecord(raw) {
4498
+ if (!raw || typeof raw != "object" || Array.isArray(raw))
4499
+ return;
4500
+ let input = raw;
4501
+ if (input.type !== "subagent.supervisor.delivered" || typeof input.id != "string" || !input.id.trim() || typeof input.at != "number" || !Number.isFinite(input.at))
4502
+ return;
4503
+ let incarnation = parseIncarnation(input);
4504
+ if (incarnation)
4505
+ return { type: "subagent.supervisor.delivered", id: input.id.trim(), at: input.at, pid: incarnation.pid, readyAt: incarnation.readyAt };
4506
+ }
4507
+ function parseTerminalRecord(raw) {
4508
+ if (!raw || typeof raw != "object" || Array.isArray(raw))
4509
+ return;
4510
+ let input = raw;
4511
+ if (!(input.type !== "subagent.supervisor.terminal" || typeof input.id != "string" || !input.id.trim()) && !(typeof input.at != "number" || !Number.isFinite(input.at))) {
4512
+ if (input.state === "answered")
4513
+ return typeof input.message != "string" || !input.message.trim() ? void 0 : { type: "subagent.supervisor.terminal", id: input.id.trim(), state: "answered", at: input.at, message: input.message };
4514
+ if (input.state === "expired")
4515
+ return { type: "subagent.supervisor.terminal", id: input.id.trim(), state: "expired", at: input.at };
4516
+ if (input.state === "cancelled")
4517
+ return typeof input.reason != "string" || !input.reason.trim() ? void 0 : { type: "subagent.supervisor.terminal", id: input.id.trim(), state: "cancelled", at: input.at, reason: input.reason.trim() };
4518
+ }
4519
+ }
4520
+ function parseNotifiedRecord(raw) {
4521
+ if (!raw || typeof raw != "object" || Array.isArray(raw))
4522
+ return;
4523
+ let input = raw;
4524
+ if (!(input.type !== "subagent.supervisor.notified" || typeof input.id != "string" || !input.id.trim()) && !(typeof input.at != "number" || !Number.isFinite(input.at)))
4525
+ return { type: "subagent.supervisor.notified", id: input.id.trim(), at: input.at };
4526
+ }
4527
+ function parseLateRecord(raw) {
4528
+ if (!raw || typeof raw != "object" || Array.isArray(raw))
4529
+ return;
4530
+ let input = raw;
4531
+ if (!(input.type !== "subagent.supervisor.late-answer" || typeof input.id != "string" || !input.id.trim()) && !(typeof input.at != "number" || !Number.isFinite(input.at) || typeof input.message != "string"))
4532
+ return { type: "subagent.supervisor.late-answer", id: input.id.trim(), at: input.at, message: input.message };
4533
+ }
4534
+ function composeQuestion(record, channelDir) {
4535
+ let delivered = parseDeliveredRecord(tryReadJson(deliveredFile(channelDir, record.id))), terminal = parseTerminalRecord(tryReadJson(terminalFile(channelDir, record.id))), notified = parseNotifiedRecord(tryReadJson(notifiedFile(channelDir, record.id))), late = parseLateRecord(tryReadJson(lateFile(channelDir, record.id)));
4536
+ return {
4537
+ ...record,
4538
+ ...delivered ? { deliveredAt: delivered.at, childIncarnation: record.childIncarnation ?? { pid: delivered.pid, readyAt: delivered.readyAt } } : {},
4539
+ ...terminal?.state === "answered" ? { answeredAt: terminal.at, answer: terminal.message } : {},
4540
+ ...terminal?.state === "expired" ? { expiredAt: terminal.at } : {},
4541
+ ...terminal?.state === "cancelled" ? { cancelledAt: terminal.at, cancelReason: terminal.reason } : {},
4542
+ ...notified ? { notifiedAt: notified.at } : {},
4543
+ ...late ? { lateAnswerAt: late.at, ...terminal?.state === "answered" ? {} : { answer: late.message } } : {}
4544
+ };
4545
+ }
4546
+ function assertMessageSize(value, label) {
4547
+ if (Buffer.byteLength(value, "utf-8") > MAX_MESSAGE_BYTES)
4548
+ throw new Error(`${label} is too large.`);
4549
+ }
4550
+ function ensureQuestionsDir(channelDir) {
4551
+ fs6.mkdirSync(questionsDir(channelDir), { recursive: !0, mode: 448 });
4552
+ }
4553
+ function supervisorQuestionPublicState(question) {
4554
+ return question.answeredAt ? "answered" : question.expiredAt ? "expired" : question.cancelledAt ? "cancelled" : "pending";
4555
+ }
4556
+ function supervisorQuestionIsTerminal(question) {
4557
+ return supervisorQuestionPublicState(question) !== "pending";
4558
+ }
4559
+ function readSupervisorQuestion(channelDir, questionId) {
4560
+ let record = parseQuestionRecord(tryReadJson(questionFile(channelDir, questionId)));
4561
+ if (!(!record || record.id !== questionId))
4562
+ return composeQuestion(record, channelDir);
4563
+ }
4564
+ function listSupervisorQuestions(channelDir) {
4565
+ let dir = questionsDir(channelDir), entries;
4566
+ try {
4567
+ entries = fs6.readdirSync(dir).filter((name) => name.endsWith(".json") && !name.endsWith(".delivered.json") && !name.endsWith(".terminal.json") && !name.endsWith(".notified.json") && !name.endsWith(".late.json"));
4568
+ } catch (error) {
4569
+ if (error.code === "ENOENT")
4570
+ return [];
4571
+ throw error;
4572
+ }
4573
+ let questions = [];
4574
+ for (let entry of entries.sort()) {
4575
+ let record = parseQuestionRecord(tryReadJson(path7.join(dir, entry)));
4576
+ record && questions.push(composeQuestion(record, channelDir));
4577
+ }
4578
+ return questions;
4579
+ }
4580
+ function writeTerminal(channelDir, record) {
4581
+ return writeExclusiveJson(terminalFile(channelDir, record.id), record);
4582
+ }
4583
+ function createSupervisorQuestion(input) {
4584
+ let reason = input.reason.trim(), message = input.message.trim();
4585
+ if (!reason)
4586
+ throw new Error("reason is required and must name the concrete decision the child's answer will change.");
4587
+ if (!message)
4588
+ throw new Error("message is required for supervisor questions.");
4589
+ assertMessageSize(reason, "reason"), assertMessageSize(message, "message");
4590
+ let createdAt = input.now ?? Date.now(), timeoutMs = input.timeoutMs && input.timeoutMs > 0 ? input.timeoutMs : askTimeoutMs(), record = {
4591
+ type: "subagent.supervisor.question",
4592
+ id: input.id ?? randomUUID3(),
4593
+ createdAt,
4594
+ expiresAt: createdAt + timeoutMs,
4595
+ reason,
4596
+ message,
4597
+ runId: input.runId,
4598
+ childIndex: input.childIndex,
4599
+ childId: input.childId,
4600
+ ...input.childDescription ? { childDescription: input.childDescription } : {},
4601
+ parentSessionId: input.parentSessionId,
4602
+ parentGeneration: input.parentGeneration,
4603
+ ...input.childIncarnation ? { childIncarnation: input.childIncarnation } : {}
4604
+ };
4605
+ if (assertMessageSize(JSON.stringify(record), "Supervisor question"), ensureQuestionsDir(input.channelDir), !writeExclusiveJson(questionFile(input.channelDir, record.id), record))
4606
+ throw new Error(`Supervisor question '${record.id}' already exists.`);
4607
+ return composeQuestion(record, input.channelDir);
4608
+ }
4609
+ function outstandingQuestionsForChild(channelDir, childIndex, childId) {
4610
+ return refreshSupervisorQuestionLifecycle(channelDir), listSupervisorQuestions(channelDir).filter((question) => !(supervisorQuestionIsTerminal(question) || question.childIndex !== childIndex || childId && question.childId !== childId));
4611
+ }
4612
+ function hasBlockingSupervisorRequest(channelDir, runId, childIndex) {
4613
+ let directory = path7.join(channelDir, "requests");
4614
+ if (!fs6.existsSync(directory))
4615
+ return !1;
4616
+ for (let name of fs6.readdirSync(directory)) {
4617
+ if (!name.endsWith(".json"))
4618
+ continue;
4619
+ let raw = tryReadJson(path7.join(directory, name));
4620
+ if (!raw || typeof raw != "object")
4621
+ continue;
4622
+ let request = raw;
4623
+ if (!(request.type !== "subagent.supervisor.request" || request.expectsReply !== !0) && !(request.runId !== runId || request.childIndex !== childIndex || typeof request.id != "string") && !(typeof request.expiresAt == "number" && request.expiresAt <= Date.now()) && !fs6.existsSync(path7.join(channelDir, "replies", `${safeSegment(request.id)}.json`)))
4624
+ return !0;
4625
+ }
4626
+ return !1;
4627
+ }
4628
+ function hasOutstandingQuestionForChild(channelDir, childIndex, childId) {
4629
+ return outstandingQuestionsForChild(channelDir, childIndex, childId).length > 0;
4630
+ }
4631
+ function incarnationMatches(expected, actual) {
4632
+ return expected ? expected.pid === actual.pid && expected.readyAt === actual.readyAt : !0;
4633
+ }
4634
+ function expireSupervisorQuestion(channelDir, questionId, now = Date.now()) {
4635
+ let current = readSupervisorQuestion(channelDir, questionId);
4636
+ return !current || supervisorQuestionIsTerminal(current) || now <= current.expiresAt ? current && supervisorQuestionIsTerminal(current) ? current : void 0 : (writeTerminal(channelDir, { type: "subagent.supervisor.terminal", id: questionId, state: "expired", at: now }), readSupervisorQuestion(channelDir, questionId));
4637
+ }
4638
+ function cancelSupervisorQuestion(channelDir, questionId, reason, now = Date.now()) {
4639
+ let current = readSupervisorQuestion(channelDir, questionId);
4640
+ return !current || supervisorQuestionIsTerminal(current) ? current : (writeTerminal(channelDir, { type: "subagent.supervisor.terminal", id: questionId, state: "cancelled", at: now, reason: reason.trim() || "cancelled" }), readSupervisorQuestion(channelDir, questionId));
4641
+ }
4642
+ function refreshSupervisorQuestionLifecycle(channelDir, now = Date.now()) {
4643
+ let changed = [];
4644
+ for (let question of listSupervisorQuestions(channelDir))
4645
+ if (!supervisorQuestionIsTerminal(question) && now > question.expiresAt) {
4646
+ let expired = expireSupervisorQuestion(channelDir, question.id, now);
4647
+ expired && expired.expiredAt && changed.push(expired);
4648
+ }
4649
+ return changed;
4650
+ }
4651
+ function formatParentQuestionForChild(question) {
4652
+ return [
4653
+ `Parent question (${question.id})`,
4654
+ `Decision needed: ${question.reason}`,
4655
+ "",
4656
+ question.message,
4657
+ "",
4658
+ `Reply with: contact_supervisor({ action: "reply", replyTo: "${question.id}", message: "..." })`,
4659
+ "Answer from current findings and uncertainty. Do not silently start extra investigation. Continue the assigned task after replying."
4660
+ ].join(`
4661
+ `);
4662
+ }
4663
+ function formatSupervisorQuestionAnswer(question) {
4664
+ let state = supervisorQuestionPublicState(question), lines = [
4665
+ state === "answered" ? `Subagent answer (${question.id})` : `Subagent question ${state} (${question.id})`,
4666
+ `From: ${question.childDescription ?? `Subagent ${question.childIndex + 1}`}`,
4667
+ `Decision: ${question.reason}`
4668
+ ];
4669
+ return state === "answered" && question.answer?.trim() ? lines.push("", question.answer.trim()) : question.cancelReason && lines.push("", question.cancelReason), lines.join(`
4670
+ `);
4671
+ }
4672
+ function registerQuestionWait(questionIds) {
4673
+ let ids = [...questionIds];
4674
+ for (let id of ids)
4675
+ activeQuestionWaits.add(id);
4676
+ return () => {
4677
+ for (let id of ids)
4678
+ activeQuestionWaits.delete(id);
4679
+ };
4680
+ }
4681
+ function isQuestionWaitActive(questionId) {
4682
+ return activeQuestionWaits.has(questionId);
4683
+ }
4684
+ function claimQuestionNotification(channelDir, questionId, now = Date.now()) {
4685
+ return writeExclusiveJson(notifiedFile(channelDir, questionId), {
4686
+ type: "subagent.supervisor.notified",
4687
+ id: questionId,
4688
+ at: now
4689
+ });
4690
+ }
4691
+ function listSupervisorChannelDirs() {
4692
+ let entries;
4693
+ try {
4694
+ entries = fs6.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: !0 });
4695
+ } catch (error) {
4696
+ if (error.code === "ENOENT")
4697
+ return [];
4698
+ throw error;
4699
+ }
4700
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => path7.join(SUPERVISOR_CHANNEL_ROOT, entry.name));
4701
+ }
4702
+ function findSupervisorQuestion(questionId) {
4703
+ let id = questionId.trim();
4704
+ if (id)
4705
+ for (let channelDir of listSupervisorChannelDirs()) {
4706
+ let question = readSupervisorQuestion(channelDir, id);
4707
+ if (question)
4708
+ return { channelDir, question };
4709
+ }
4710
+ }
4711
+ function cancelPendingSupervisorQuestionsForOwner(input) {
4712
+ if (!input.parentSessionId?.trim())
4713
+ return [];
4714
+ let now = input.now ?? Date.now(), cancelled = [];
4715
+ for (let channelDir of listSupervisorChannelDirs())
4716
+ for (let question of listSupervisorQuestions(channelDir)) {
4717
+ if (supervisorQuestionIsTerminal(question) || question.parentSessionId !== input.parentSessionId || input.parentGeneration !== void 0 && question.parentGeneration !== input.parentGeneration || input.runId && question.runId !== input.runId)
4718
+ continue;
4719
+ let next = cancelSupervisorQuestion(channelDir, question.id, input.reason, now);
4720
+ next?.cancelledAt && cancelled.push(next);
4721
+ }
4722
+ return cancelled;
4723
+ }
4724
+
4725
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.js
4726
+ function runningSteps(status) {
4727
+ return (status.steps ?? []).map((step, index) => ({
4728
+ index,
4729
+ childId: step.childId ?? step.agent,
4730
+ agent: step.agent,
4731
+ status: step.status
4732
+ })).filter((step) => step.status === "running").map((step) => ({ index: step.index, childId: step.childId, agent: step.agent }));
4733
+ }
4734
+ function resolveAskChild(status, params) {
4735
+ if (params.index !== void 0 && (!Number.isInteger(params.index) || params.index < 0))
4736
+ throw new Error("index must be a non-negative integer.");
4737
+ let running = runningSteps(status);
4738
+ if (params.childId?.trim()) {
4739
+ let childId = params.childId.trim(), matches = (status.steps ?? []).map((step, index) => ({ index, childId: step.childId ?? step.agent, agent: step.agent, status: step.status })).filter((step) => step.childId === childId);
4740
+ if (matches.length === 0)
4741
+ throw new Error(`Async run '${status.runId}' has no child '${childId}'.`);
4742
+ if (matches.length > 1)
4743
+ throw new Error(`Async run '${status.runId}' has multiple children named '${childId}'. Pass index.`);
4744
+ let match = matches[0];
4745
+ if (params.index !== void 0 && params.index !== match.index)
4746
+ throw new Error(`Child '${childId}' is index ${match.index}, not ${params.index}.`);
4747
+ if (match.status !== "running")
4748
+ throw new Error(`Async run '${status.runId}' child ${match.index} is ${match.status} and cannot be asked.`);
4749
+ return { index: match.index, childId: match.childId, agent: match.agent };
4750
+ }
4751
+ if (params.index !== void 0) {
4752
+ let steps = status.steps ?? [];
4753
+ if (params.index >= steps.length)
4754
+ throw new Error(`Async run '${status.runId}' has ${steps.length} children. Index ${params.index} is out of range.`);
4755
+ let step = steps[params.index];
4756
+ if (step.status !== "running")
4757
+ throw new Error(`Async run '${status.runId}' child ${params.index} is ${step.status} and cannot be asked.`);
4758
+ return { index: params.index, childId: step.childId ?? step.agent, agent: step.agent };
4759
+ }
4760
+ if (running.length === 1)
4761
+ return running[0];
4762
+ throw running.length === 0 ? new Error(`Async run '${status.runId}' has no running child to ask.`) : new Error(`Async run '${status.runId}' has ${running.length} running children. Pass index or childId; broadcast asks are not supported.`);
4763
+ }
4764
+ function requestMatchesChild(request, runId, child) {
4765
+ if (!request.expectsReply || typeof request.runId != "string" || request.runId !== runId)
4766
+ return !1;
4767
+ let indexMatches = Number.isInteger(request.childIndex) && request.childIndex === child.index, idMatches = request.agent === child.childId || request.agent === child.agent || request.childTarget === child.childId;
4768
+ return indexMatches && idMatches;
4769
+ }
4770
+ function reconcileAsyncQuestion(channelDir, question, state) {
4771
+ expireSupervisorQuestion(channelDir, question.id);
4772
+ let current = readSupervisorQuestion(channelDir, question.id) ?? question;
4773
+ if (supervisorQuestionIsTerminal(current))
4774
+ return current;
4775
+ let resolved = resolveSubagentRunId(current.runId, { state });
4776
+ if (resolved?.kind !== "async" || !resolved.location.asyncDir)
4777
+ return current;
4778
+ let status = readStatus(resolved.location.asyncDir);
4779
+ if (!status)
4780
+ return current;
4781
+ let step = status.steps?.[current.childIndex], capability = readSteerCapability(resolved.location.asyncDir, current.childIndex), reason;
4782
+ status.sessionId !== current.parentSessionId ? reason = "async run ownership changed" : status.state !== "running" || !step || step.status !== "running" ? reason = "target child is no longer running" : (step.childId ?? step.agent) !== current.childId ? reason = "target child identity changed" : capability && !incarnationMatches(current.childIncarnation, capability) ? reason = "target child process changed" : capability && !capability.supported && (reason = "target child no longer accepts questions");
4783
+ let delivery = status.steering?.recent.find((request) => request.id === current.id)?.targets.find((target) => target.index === current.childIndex);
4784
+ return (delivery?.state === "failed" || delivery?.state === "late") && (reason = delivery.reason ?? "question delivery failed"), reason ? cancelSupervisorQuestion(channelDir, current.id, reason) ?? current : current;
4785
+ }
4786
+ function askRunningAsyncChild(input) {
4787
+ let runId = input.params.id?.trim();
4788
+ if (!runId)
4789
+ throw new Error("action='ask' requires id for the async run.");
4790
+ let reason = input.params.reason?.trim(), message = input.params.message?.trim();
4791
+ if (!reason)
4792
+ throw new Error("action='ask' requires reason naming the concrete decision the child's answer will change.");
4793
+ if (!message)
4794
+ throw new Error("action='ask' requires message.");
4795
+ let sessionId = input.state.currentSessionId;
4796
+ if (!sessionId)
4797
+ throw new Error("action='ask' requires an active session identity.");
4798
+ let resolved = resolveSubagentRunId(runId, { state: input.state });
4799
+ if (!resolved)
4800
+ throw new Error(`No async run matched '${runId}'.`);
4801
+ if (resolved.kind !== "async")
4802
+ throw new Error("action='ask' targets a running async child only. It does not revive, reassign, or broadcast.");
4803
+ if (!resolved.location.asyncDir)
4804
+ throw new Error(`Async run '${resolved.id}' has no live run directory.`);
4805
+ let status = readStatus(resolved.location.asyncDir);
4806
+ if (!status)
4807
+ throw new Error(`Async run '${resolved.id}' has no status.`);
4808
+ if (!status.sessionId || status.sessionId !== sessionId)
4809
+ throw new Error(`Async run '${resolved.id}' was not found in the active session.`);
4810
+ if (status.state !== "running")
4811
+ throw new Error(`Async run '${resolved.id}' is ${status.state} and cannot be asked.`);
4812
+ let child = resolveAskChild(status, input.params), channelDir = resolveSupervisorChannelDir(status.runId, child.childId, child.index);
4813
+ if (hasOutstandingQuestionForChild(channelDir, child.index, child.childId))
4814
+ throw new Error(`A question is already outstanding for async run '${status.runId}' child ${child.index}. Wait for that answer or expiry before asking again.`);
4815
+ for (let request of input.childRequests ?? [])
4816
+ if (requestMatchesChild(request, status.runId, child))
4817
+ throw new Error(`Child ${child.index} is waiting for a supervisor reply. Asking now would deadlock. Reply to the child request first.`);
4818
+ if (hasBlockingSupervisorRequest(channelDir, status.runId, child.index))
4819
+ throw new Error("Child is waiting for a supervisor reply. Reply to its request before asking a question.");
4820
+ let capability = readSteerCapability(resolved.location.asyncDir, child.index);
4821
+ if (!capability?.supported)
4822
+ throw new Error("This child is not ready to receive questions. Continue other work until it is ready; no question was queued.");
4823
+ let incarnation = { pid: capability.pid, readyAt: capability.readyAt }, step = status.steps?.[child.index], childDescription = resolveCommunicationPeer(input.state, status.runId, child.index, child.childId, step?.description ?? child.agent), question = createSupervisorQuestion({
4824
+ channelDir,
4825
+ childDescription,
4826
+ reason,
4827
+ message,
4828
+ runId: status.runId,
4829
+ childIndex: child.index,
4830
+ childId: child.childId,
4831
+ parentSessionId: sessionId,
4832
+ parentGeneration: input.state.sessionGeneration ?? 0,
4833
+ childIncarnation: incarnation
4834
+ });
4835
+ try {
4836
+ if (hasBlockingSupervisorRequest(channelDir, status.runId, child.index))
4837
+ throw new Error("Child is waiting for a supervisor reply. Reply to its request before asking a question.");
4838
+ requestAsyncSteer(resolved.location.asyncDir, {
4839
+ message: formatParentQuestionForChild(question),
4840
+ targetIndex: child.index,
4841
+ source: "supervisor-question",
4842
+ id: question.id
4843
+ });
4844
+ } catch (error) {
4845
+ throw cancelSupervisorQuestion(channelDir, question.id, "failed to queue delivery to child"), error instanceof Error ? error : new Error(String(error));
4846
+ }
4847
+ return {
4848
+ content: [{ type: "text", text: `Question ${question.id} queued for async run ${status.runId} child ${child.index}. The child's answer is delivered separately from the run result.` }],
4849
+ details: {
4850
+ questionId: question.id,
4851
+ state: "pending",
4852
+ runId: status.runId,
4853
+ childIndex: child.index,
4854
+ childId: child.childId,
4855
+ communication: { direction: "to", peer: childDescription, message, kind: "question" },
4856
+ delivered: !1,
4857
+ answered: !1
4858
+ }
4859
+ };
4860
+ }
4861
+
4862
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/tui/communication.js
4863
+ import { Box, Container as Container2, Text as Text2 } from "@ashx-j/lunr-tui";
4864
+ function renderCommunicationBody(communication, theme) {
4865
+ let direction = communication.direction === "from" ? "From" : "To";
4866
+ return new Text2(`${theme.fg("muted", `${direction}: ${communication.peer}`)}
4867
+
4868
+ ${communication.message}`, 0, 0);
4869
+ }
4870
+ function renderCommunicationCard(communication, expanded, theme) {
4871
+ let box = new Box(1, 1, (text) => theme.bg("toolSuccessBg", text));
4872
+ return box.addChild(new Text2(theme.fg("toolTitle", theme.bold(`\u25CF subagent ${communication.kind}`)), 0, 0)), expanded && box.addChild(renderCommunicationBody(communication, theme)), box;
4873
+ }
4874
+ function renderCommunicationCall(name, args, theme, context, communication, displayTitle) {
4875
+ let container = new Container2(), details = context?.result?.details, saved = readCommunication(details?.communication) ?? communication, action = args.action ?? (args.reason === "need_decision" ? "request" : args.reason === "interview_request" ? "interview" : args.reason === "progress_update" ? "progress" : args.reason), title = theme.fg("toolTitle", theme.bold(`${name}${action ? ` ${action}` : ""}`));
4876
+ return container.addChild(new Text2(displayTitle ? `${title} ${theme.fg("accent", displayTitle)}` : title, 0, 0)), context?.expanded && saved && container.addChild(renderCommunicationBody(saved, theme)), container;
4877
+ }
4878
+ function renderCommunicationResult(content, details, expanded, isError, theme) {
4879
+ let container = new Container2();
4880
+ if (!expanded)
4881
+ return container;
4882
+ if (isError)
4883
+ container.addChild(new Text2(theme.fg("error", content.filter((part) => part.type === "text").map((part) => part.text ?? "").join(`
4884
+ `)), 0, 0));
4885
+ else {
4886
+ let saved = details;
4887
+ saved?.response ? container.addChild(new Text2(`
4888
+ ${theme.fg("muted", "From: Supervisor")}
4889
+
4890
+ ${saved.response}`, 0, 0)) : saved?.steering?.state ? container.addChild(new Text2(`
4891
+ Delivery: ${saved.steering.state === "recovered" ? "recovered; replacement launched" : saved.steering.state}`, 0, 0)) : saved?.asyncId && saved.communication ? container.addChild(new Text2(`
4892
+ Continuation launched.`, 0, 0)) : saved?.state && saved.communication ? container.addChild(new Text2(`
4893
+ ${saved.state === "pending" ? "Question queued; awaiting an answer." : saved.state}`, 0, 0)) : saved?.communication || container.addChild(new Text2(content.filter((part) => part.type === "text").map((part) => part.text ?? "").join(`
4894
+ `), 0, 0));
4895
+ }
4896
+ return container;
4897
+ }
4898
+
4899
+ // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js
4900
+ var REQUESTS_DIR = "requests", REPLIES_DIR = "replies", NATIVE_SUPERVISOR_TOOL_NAME = "subagent_supervisor";
4901
+ var MAX_MESSAGE_BYTES2 = 64 * 1024, DEFAULT_ASK_TIMEOUT_MS2 = 600 * 1e3, CHANNEL_POLL_MS = Math.min(POLL_INTERVAL_MS, 500), STALE_EMPTY_CHANNEL_AGE_MS = 60 * 1e3, STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS = 60 * 1e3, PARENT_ASK_DESCRIPTION = [
4902
+ "Ask a specific running async child, or reply to a child supervisor request. Asking is unavailable when Subagent communication is off in /settings; final results still arrive normally.",
4903
+ "Ask only when the child owns missing context, the answer changes a concrete next decision, and waiting risks a block or rework.",
4904
+ "Use available results first, batch related questions, and keep working while awaiting the answer. Do not use ask for status checks, polling, duplicate queries, or step-by-step supervision. Follow up only when the answer leaves the original decision unresolved.",
4905
+ "Returns a question id immediately. The child's explicit answer is delivered separately from the final run result.",
4906
+ 'Ask: { action: "ask", id: "<runId>", index?: 0, childId?: "...", reason: "<concrete decision>", message: "..." }',
4907
+ "Use pending or list to find child requests awaiting your reply; status reports channel availability. Free-form send is unsupported. Asking never revives a child or changes its assignment.",
4908
+ 'Reply: { action: "reply", replyTo: "<requestId>", message: "..." }'
4909
+ ].join(" "), CHILD_CONTACT_DESCRIPTION = [
4910
+ "Contact the supervisor for decisions outside your assigned authority, safety concerns, or blockers. Make reversible implementation choices within your scope yourself.",
4911
+ "need_decision/interview_request wait for a reply: state the blocked decision, evidence, and recommended choice. Consolidate related questions; continue independent work before opening a blocking request.",
4912
+ "Return one self-contained final report with outcomes, verification, blockers, and artifact paths; the runtime delivers it. Routine work already appears in activity indicators.",
4913
+ "For parent questions use action='reply' with replyTo set to the question id. Answer from current findings and uncertainty; do not start extra investigation just to reply. Continue the assigned task after replying.",
4914
+ "Do not open a blocking need_decision while a parent question is already outstanding for this child."
4915
+ ].join(" "), ContactSupervisorParamsSchema = Type2.Object({
4916
+ reason: Type2.Optional(Type2.String({ enum: ["need_decision", "interview_request", "progress_update", "handoff"] })),
4412
4917
  message: Type2.Optional(Type2.String()),
4413
- interview: Type2.Optional(Type2.Unsafe({ type: "object", additionalProperties: !0 }))
4918
+ interview: Type2.Optional(Type2.Unsafe({ type: "object", additionalProperties: !0 })),
4919
+ action: Type2.Optional(Type2.String({ enum: ["reply"] })),
4920
+ replyTo: Type2.Optional(Type2.String())
4414
4921
  }, { additionalProperties: !1 }), IntercomParamsSchema = Type2.Object({
4415
4922
  action: Type2.String({ enum: ["list", "send", "ask", "reply", "pending", "status"] }),
4416
4923
  to: Type2.Optional(Type2.String()),
4417
4924
  message: Type2.Optional(Type2.String()),
4418
- replyTo: Type2.Optional(Type2.String())
4925
+ replyTo: Type2.Optional(Type2.String()),
4926
+ id: Type2.Optional(Type2.String({ description: "Async run id for action='ask'." })),
4927
+ index: Type2.Optional(Type2.Integer({ minimum: 0, description: "Zero-based child index for action='ask'. Select index or childId when more than one child is running." })),
4928
+ childId: Type2.Optional(Type2.String({ description: "Private child identity for action='ask'." })),
4929
+ reason: Type2.Optional(Type2.String({ description: "Concrete decision the child's answer will change. Required for action='ask'." }))
4930
+ }, { additionalProperties: !1 }), ParentSupervisorParamsSchema = Type2.Object({
4931
+ ...IntercomParamsSchema.properties,
4932
+ action: Type2.String({ enum: ["list", "ask", "reply", "pending", "status"] })
4419
4933
  }, { additionalProperties: !1 });
4420
- function safeSegment(value) {
4934
+ function safeSegment2(value) {
4421
4935
  return value.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "unknown";
4422
4936
  }
4423
4937
  function replyPath(channelDir, requestId) {
4424
- return path7.join(channelDir, REPLIES_DIR, `${safeSegment(requestId)}.json`);
4938
+ return path8.join(channelDir, REPLIES_DIR, `${safeSegment2(requestId)}.json`);
4425
4939
  }
4426
- function askTimeoutMs() {
4940
+ function communicationKind(reason) {
4941
+ return reason === "progress_update" ? "progress" : reason === "handoff" ? "handoff" : reason === "interview_request" ? "interview" : "request";
4942
+ }
4943
+ function communicationBody(message, interview, protocolVersion) {
4944
+ let body = protocolVersion === 2 ? message : legacySupervisorBody(message);
4945
+ return interview !== void 0 && protocolVersion === 2 ? `${body}
4946
+
4947
+ ${JSON.stringify(interview, null, 2)}` : body;
4948
+ }
4949
+ function requestCommunication(request, state) {
4950
+ return {
4951
+ direction: "from",
4952
+ peer: resolveCommunicationPeer(state, request.runId, request.childIndex, request.agent, request.description),
4953
+ message: communicationBody(request.message, request.interview, request.protocolVersion),
4954
+ kind: communicationKind(request.reason)
4955
+ };
4956
+ }
4957
+ function registerSupervisorRenderers(pi, state) {
4958
+ for (let customType of [SUPERVISOR_REQUEST_TYPE, SUBAGENT_SUPERVISOR_ANSWER_TYPE])
4959
+ pi.registerMessageRenderer(customType, (message, options, theme) => {
4960
+ let details = message.details, communication = readCommunication(details?.communication) ?? {
4961
+ direction: "from",
4962
+ peer: details?.runId ? resolveCommunicationPeer(state, details.runId, details.childIndex ?? 0, details.childId ?? details.agent) : "Subagent",
4963
+ message: legacySupervisorBody(typeof message.content == "string" ? message.content : message.content.filter((part) => part.type === "text").map((part) => part.text).join(`
4964
+ `)),
4965
+ kind: customType === SUBAGENT_SUPERVISOR_ANSWER_TYPE ? "answer" : communicationKind(details?.reason)
4966
+ };
4967
+ return renderCommunicationCard(communication, options.expanded, theme);
4968
+ });
4969
+ pi.registerEntryRenderer(SUPERVISOR_PROGRESS_TYPE, (entry, options, theme) => {
4970
+ let communication = readCommunication(entry.data?.communication);
4971
+ return communication ? renderCommunicationCard(communication, options.expanded, theme) : void 0;
4972
+ });
4973
+ }
4974
+ function askTimeoutMs2() {
4427
4975
  let parsed = Number(process.env.PI_INTERCOM_ASK_TIMEOUT_MS);
4428
- return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_ASK_TIMEOUT_MS;
4976
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_ASK_TIMEOUT_MS2;
4429
4977
  }
4430
4978
  function hasTool(pi, name) {
4431
4979
  try {
@@ -4436,16 +4984,26 @@ function hasTool(pi, name) {
4436
4984
  }
4437
4985
  function parseRequestFile(file, channelDir) {
4438
4986
  try {
4439
- let parsed = JSON.parse(fs6.readFileSync(file, "utf-8"));
4440
- return parsed.type !== "subagent.supervisor.request" || typeof parsed.id != "string" || !parsed.id || parsed.reason !== "need_decision" && parsed.reason !== "interview_request" && parsed.reason !== "progress_update" || typeof parsed.message != "string" || !parsed.message || typeof parsed.runId != "string" || typeof parsed.agent != "string" || typeof parsed.childIndex != "number" ? void 0 : { ...parsed, channelDir, requestFile: file };
4987
+ let parsed = JSON.parse(fs7.readFileSync(file, "utf-8"));
4988
+ return parsed.type !== "subagent.supervisor.request" || parsed.supervisorSessionId !== void 0 && (typeof parsed.supervisorSessionId != "string" || !parsed.supervisorSessionId.trim()) || typeof parsed.id != "string" || !parsed.id || parsed.reason !== "need_decision" && parsed.reason !== "interview_request" && parsed.reason !== "progress_update" && parsed.reason !== "handoff" || parsed.protocolVersion !== void 0 && parsed.protocolVersion !== 2 || parsed.protocolVersion === 2 && parsed.expectsReply !== (parsed.reason === "need_decision" || parsed.reason === "interview_request") || parsed.reason === "handoff" && parsed.protocolVersion !== 2 || parsed.description !== void 0 && typeof parsed.description != "string" || typeof parsed.message != "string" || !parsed.message || typeof parsed.runId != "string" || typeof parsed.agent != "string" || typeof parsed.childIndex != "number" ? void 0 : { ...parsed, channelDir, requestFile: file };
4441
4989
  } catch {
4442
4990
  return;
4443
4991
  }
4444
4992
  }
4993
+ function hasPendingBlockingSupervisorRequest(runId, sessionId, now = Date.now()) {
4994
+ if (!runId)
4995
+ return !1;
4996
+ for (let { channelDir, file } of listRequestFiles()) {
4997
+ let request = parseRequestFile(file, channelDir);
4998
+ if (request?.expectsReply && request.runId === runId && !(sessionId && (request.supervisorSessionId ?? request.orchestratorSessionId) !== sessionId) && !fs7.existsSync(replyPath(request.channelDir, request.id)) && !(now > requestExpiresAt(request, now)))
4999
+ return !0;
5000
+ }
5001
+ return !1;
5002
+ }
4445
5003
  function listRequestFiles() {
4446
5004
  let channelEntries;
4447
5005
  try {
4448
- channelEntries = fs6.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: !0 });
5006
+ channelEntries = fs7.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: !0 });
4449
5007
  } catch (error) {
4450
5008
  if (error.code === "ENOENT")
4451
5009
  return [];
@@ -4455,34 +5013,34 @@ function listRequestFiles() {
4455
5013
  for (let entry of channelEntries) {
4456
5014
  if (!entry.isDirectory())
4457
5015
  continue;
4458
- let channelDir = path7.join(SUPERVISOR_CHANNEL_ROOT, entry.name), requestsDir = path7.join(channelDir, REQUESTS_DIR), requestEntries;
5016
+ let channelDir = path8.join(SUPERVISOR_CHANNEL_ROOT, entry.name), requestsDir = path8.join(channelDir, REQUESTS_DIR), requestEntries;
4459
5017
  try {
4460
- requestEntries = fs6.readdirSync(requestsDir, { withFileTypes: !0 });
5018
+ requestEntries = fs7.readdirSync(requestsDir, { withFileTypes: !0 });
4461
5019
  } catch {
4462
5020
  continue;
4463
5021
  }
4464
5022
  for (let requestEntry of requestEntries)
4465
- requestEntry.isFile() && requestEntry.name.endsWith(".json") && files.push({ channelDir, file: path7.join(requestsDir, requestEntry.name) });
5023
+ requestEntry.isFile() && requestEntry.name.endsWith(".json") && files.push({ channelDir, file: path8.join(requestsDir, requestEntry.name) });
4466
5024
  }
4467
5025
  return files;
4468
5026
  }
4469
5027
  function readDirectoryEntries(dir) {
4470
5028
  try {
4471
- return fs6.readdirSync(dir, { withFileTypes: !0 });
5029
+ return fs7.readdirSync(dir, { withFileTypes: !0 });
4472
5030
  } catch (error) {
4473
5031
  return error.code === "ENOENT" ? [] : void 0;
4474
5032
  }
4475
5033
  }
4476
5034
  function directoryMtimeMs(dir) {
4477
5035
  try {
4478
- return fs6.statSync(dir).mtimeMs;
5036
+ return fs7.statSync(dir).mtimeMs;
4479
5037
  } catch {
4480
5038
  return 0;
4481
5039
  }
4482
5040
  }
4483
5041
  function removeEmptyDirectory(dir) {
4484
5042
  try {
4485
- return fs6.rmdirSync(dir), !0;
5043
+ return fs7.rmdirSync(dir), !0;
4486
5044
  } catch (error) {
4487
5045
  let code = error.code;
4488
5046
  if (code === "ENOENT")
@@ -4493,19 +5051,22 @@ function removeEmptyDirectory(dir) {
4493
5051
  }
4494
5052
  }
4495
5053
  function removeStaleEmptySupervisorChannel(channelDir, nowMs) {
4496
- let requestsDir = path7.join(channelDir, REQUESTS_DIR), repliesDir = path7.join(channelDir, REPLIES_DIR), newestKnownMtimeMs = Math.max(directoryMtimeMs(channelDir), directoryMtimeMs(requestsDir), directoryMtimeMs(repliesDir));
5054
+ let requestsDir = path8.join(channelDir, REQUESTS_DIR), repliesDir = path8.join(channelDir, REPLIES_DIR), questionsPath = path8.join(channelDir, QUESTIONS_DIR), newestKnownMtimeMs = Math.max(directoryMtimeMs(channelDir), directoryMtimeMs(requestsDir), directoryMtimeMs(repliesDir), directoryMtimeMs(questionsPath));
4497
5055
  if (nowMs - newestKnownMtimeMs < STALE_EMPTY_CHANNEL_AGE_MS)
4498
5056
  return !1;
4499
5057
  let requestEntries = readDirectoryEntries(requestsDir);
4500
5058
  if (!requestEntries || requestEntries.length > 0)
4501
5059
  return !1;
4502
5060
  let replyEntries = readDirectoryEntries(repliesDir);
4503
- return !(!replyEntries || replyEntries.length > 0 || !removeEmptyDirectory(requestsDir) || !removeEmptyDirectory(repliesDir) || !removeEmptyDirectory(channelDir));
5061
+ if (!replyEntries || replyEntries.length > 0)
5062
+ return !1;
5063
+ let questionEntries = readDirectoryEntries(questionsPath);
5064
+ return !(!questionEntries || questionEntries.length > 0 || !removeEmptyDirectory(requestsDir) || !removeEmptyDirectory(repliesDir) || !removeEmptyDirectory(questionsPath) || !removeEmptyDirectory(channelDir));
4504
5065
  }
4505
5066
  function cleanupStaleEmptySupervisorChannels(nowMs = Date.now()) {
4506
5067
  let channelEntries;
4507
5068
  try {
4508
- channelEntries = fs6.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: !0 });
5069
+ channelEntries = fs7.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: !0 });
4509
5070
  } catch (error) {
4510
5071
  if (error.code === "ENOENT")
4511
5072
  return 0;
@@ -4515,7 +5076,7 @@ function cleanupStaleEmptySupervisorChannels(nowMs = Date.now()) {
4515
5076
  for (let entry of channelEntries)
4516
5077
  if (entry.isDirectory())
4517
5078
  try {
4518
- removeStaleEmptySupervisorChannel(path7.join(SUPERVISOR_CHANNEL_ROOT, entry.name), nowMs) && removed++;
5079
+ removeStaleEmptySupervisorChannel(path8.join(SUPERVISOR_CHANNEL_ROOT, entry.name), nowMs) && removed++;
4519
5080
  } catch {
4520
5081
  }
4521
5082
  return removed;
@@ -4529,36 +5090,47 @@ function currentContextSessionId(state, ctx) {
4529
5090
  }
4530
5091
  return state.currentSessionId ?? void 0;
4531
5092
  }
5093
+ function currentSupervisorSessionId(state, ctx) {
5094
+ try {
5095
+ return ctx.sessionManager.getSessionFile?.() ?? currentContextSessionId(state, ctx);
5096
+ } catch {
5097
+ return state.currentSessionId ?? void 0;
5098
+ }
5099
+ }
4532
5100
  function requestMatchesContext(request, state, ctx) {
4533
- let currentSessionId = currentContextSessionId(state, ctx);
4534
- return !!(currentSessionId && request.orchestratorSessionId === currentSessionId);
5101
+ let currentSessionId = request.supervisorSessionId !== void 0 ? currentSupervisorSessionId(state, ctx) : currentContextSessionId(state, ctx);
5102
+ return !!(currentSessionId && (request.supervisorSessionId ?? request.orchestratorSessionId) === currentSessionId);
4535
5103
  }
4536
5104
  function removeRequestFile(file) {
4537
5105
  try {
4538
- fs6.rmSync(file, { force: !0 });
5106
+ fs7.rmSync(file, { force: !0 });
4539
5107
  } catch {
4540
5108
  }
4541
5109
  }
4542
5110
  function requestExpiresAt(request, now) {
4543
5111
  let expiresAt = request.expiresAt;
4544
- return typeof expiresAt == "number" && Number.isFinite(expiresAt) ? expiresAt : Number.isFinite(request.createdAt) ? request.createdAt + askTimeoutMs() : now;
5112
+ return typeof expiresAt == "number" && Number.isFinite(expiresAt) ? expiresAt : Number.isFinite(request.createdAt) ? request.createdAt + askTimeoutMs2() : now;
4545
5113
  }
4546
- function requestRunInactive(request, state) {
5114
+ function requestRunState(request, state) {
4547
5115
  if (state.foregroundControls.has(request.runId))
4548
- return !1;
5116
+ return "active";
4549
5117
  let foregroundRun = state.foregroundRuns?.get(request.runId), foregroundChild = foregroundRun?.children.find((child) => child.index === request.childIndex && child.agent === request.agent) ?? foregroundRun?.children[request.childIndex];
4550
5118
  if (foregroundChild)
4551
- return foregroundChild.status !== "detached";
4552
- let asyncJob = state.asyncJobs.get(request.runId);
4553
- if (!asyncJob)
4554
- return !1;
4555
- if (asyncJob.status === "complete" || asyncJob.status === "failed" || asyncJob.status === "paused")
4556
- return !0;
4557
- let stepStatus = asyncJob.steps?.[request.childIndex]?.status;
4558
- return stepStatus === "complete" || stepStatus === "completed" || stepStatus === "failed" || stepStatus === "paused";
5119
+ return foregroundChild.status === "stopped" ? "stopped" : foregroundChild.status === "detached" ? "active" : "inactive";
5120
+ let job = state.asyncJobs.get(request.runId) ?? state.fleetJobs?.get(request.runId), asyncDir = job?.asyncDir ?? path8.join(ASYNC_DIR, safeSegment2(request.runId)), status = readStatus(asyncDir), runStatus = status?.state ?? job?.status, stepStatus = (status?.steps ?? job?.steps)?.[request.childIndex]?.status;
5121
+ return fs7.existsSync(stopRequestPath(asyncDir)) || runStatus === "stopped" || job?.status === "stopped" || status?.stopped || stepStatus === "stopped" ? "stopped" : ["complete", "failed", "paused"].includes(runStatus ?? "") || ["complete", "completed", "failed", "paused"].includes(stepStatus ?? "") ? "inactive" : "active";
4559
5122
  }
4560
5123
  function requestLifecycle(request, state, ctx, now) {
4561
- return ctx && !requestMatchesContext(request, state, ctx) ? "wrong-session" : fs6.existsSync(request.requestFile) ? request.expectsReply && fs6.existsSync(replyPath(request.channelDir, request.id)) ? "resolved" : request.expectsReply && now > requestExpiresAt(request, now) ? "expired" : request.expectsReply && requestRunInactive(request, state) ? "inactive" : "pending" : "missing";
5124
+ if (ctx && !requestMatchesContext(request, state, ctx))
5125
+ return "wrong-session";
5126
+ if (!fs7.existsSync(request.requestFile))
5127
+ return "missing";
5128
+ if (request.expectsReply && fs7.existsSync(replyPath(request.channelDir, request.id)))
5129
+ return "resolved";
5130
+ if (request.expectsReply && now > requestExpiresAt(request, now))
5131
+ return "expired";
5132
+ let runState = requestRunState(request, state);
5133
+ return runState === "stopped" || request.expectsReply && runState === "inactive" ? "inactive" : "pending";
4562
5134
  }
4563
5135
  function cleanupRequestLifecycle(request, lifecycle) {
4564
5136
  (lifecycle === "resolved" || lifecycle === "expired" || lifecycle === "inactive") && removeRequestFile(request.requestFile);
@@ -4574,9 +5146,9 @@ function formatPendingLine(request) {
4574
5146
  let replyHint = request.expectsReply ? ` Reply: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: "reply", replyTo: "${request.id}", message: "..." })` : "";
4575
5147
  return `- ${request.id}: ${request.agent} [${request.runId}#${request.childIndex}] ${request.reason}.${replyHint}`;
4576
5148
  }
4577
- function requestVisibleText(request) {
4578
- let lines = [request.message];
4579
- return request.expectsReply && lines.push("", `Reply with: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: "reply", replyTo: "${request.id}", message: "..." })`), lines.join(`
5149
+ function requestVisibleText(request, communication) {
5150
+ let lines = [`From: ${communication.peer}`, "", communication.message];
5151
+ return request.reason === "interview_request" && lines.push("", "Reply with JSON matching the requested interview shape."), request.expectsReply && lines.push("", `Reply with: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: "reply", replyTo: "${request.id}", message: "..." })`), lines.join(`
4580
5152
  `);
4581
5153
  }
4582
5154
  function writeReply(request, message) {
@@ -4623,8 +5195,15 @@ function buildParentIntercomTool(pending, state, name = "intercom") {
4623
5195
  return {
4624
5196
  name,
4625
5197
  label: name === "intercom" ? "Intercom" : "Subagent Supervisor",
4626
- description: name === "intercom" ? "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests." : "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding pi-intercom.",
4627
- parameters: IntercomParamsSchema,
5198
+ description: PARENT_ASK_DESCRIPTION,
5199
+ parameters: ParentSupervisorParamsSchema,
5200
+ renderCall(args, theme, context) {
5201
+ let request = args.action === "reply" ? pending.get(args.replyTo) : void 0, peer = request ? requestCommunication(request, state).peer : args.id ? resolveCommunicationPeer(state, args.id, args.index ?? 0, args.childId) : "Subagent";
5202
+ return renderCommunicationCall(name, args, theme, context, args.message ? { direction: "to", peer, message: args.message, kind: args.action === "ask" ? "question" : "reply" } : void 0);
5203
+ },
5204
+ renderResult(result2, options, theme, context) {
5205
+ return renderCommunicationResult(result2.content, result2.details, options.expanded, context.isError, theme);
5206
+ },
4628
5207
  async execute(_id, params) {
4629
5208
  refreshPendingRequests(pending, state, state.lastUiContext ?? void 0);
4630
5209
  let input = params;
@@ -4637,14 +5216,64 @@ function buildParentIntercomTool(pending, state, name = "intercom") {
4637
5216
  }
4638
5217
  if (input.action === "reply") {
4639
5218
  let request = resolvePendingRequest(pending, input);
4640
- return writeReply(request, input.message ?? ""), pending.delete(request.id), { content: [{ type: "text", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };
5219
+ return writeReply(request, input.message ?? ""), pending.delete(request.id), { content: [{ type: "text", text: `Replied to ${requestCommunication(request, state).peer}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent, communication: { ...requestCommunication(request, state), direction: "to", kind: "reply", message: input.message } } };
4641
5220
  }
4642
- throw input.action === "send" || input.action === "ask" ? new Error("Native pi-subagents intercom currently handles supervisor replies. Child agents initiate asks with contact_supervisor.") : new Error(`Unsupported intercom action: ${input.action}`);
5221
+ if (input.action === "ask")
5222
+ return subagentCommunicationEnabled(process.cwd(), getAgentDir()) ? askRunningAsyncChild({
5223
+ params: {
5224
+ id: input.id,
5225
+ index: input.index,
5226
+ childId: input.childId,
5227
+ reason: input.reason,
5228
+ message: input.message
5229
+ },
5230
+ state,
5231
+ childRequests: pending.values()
5232
+ }) : { content: [{ type: "text", text: "Subagent communication is off in /settings. Wait for the child to complete instead of asking it." }], isError: !0, details: { disabled: !0 } };
5233
+ throw input.action === "send" ? new Error("Native pi-subagents intercom does not support free-form send. Use action='ask' for a running async child or action='reply' for a pending child request.") : new Error(`Unsupported intercom action: ${input.action}`);
4643
5234
  }
4644
5235
  };
4645
5236
  }
5237
+ function questionMatchesParentContext(question, state, ctx) {
5238
+ let sessionId = currentSupervisorSessionId(state, ctx);
5239
+ return !(!sessionId || question.parentSessionId !== sessionId || (state.sessionGeneration ?? 0) !== question.parentGeneration);
5240
+ }
5241
+ function notifyQuestionTerminal(pi, question, channelDir, state) {
5242
+ if (!supervisorQuestionIsTerminal(question) || question.notifiedAt || (pi.events?.emit(SUBAGENT_QUESTION_EVENT, {
5243
+ questionId: question.id,
5244
+ state: supervisorQuestionPublicState(question),
5245
+ runId: question.runId
5246
+ }), isQuestionWaitActive(question.id)) || !claimQuestionNotification(channelDir, question.id))
5247
+ return;
5248
+ let outcome = supervisorQuestionPublicState(question), communication = { direction: "from", peer: question.childDescription ?? resolveCommunicationPeer(state, question.runId, question.childIndex, question.childId), message: question.answer ?? question.cancelReason ?? outcome, kind: "answer" };
5249
+ pi.sendMessage({
5250
+ customType: SUBAGENT_SUPERVISOR_ANSWER_TYPE,
5251
+ content: formatSupervisorQuestionAnswer(question),
5252
+ display: outcome === "answered",
5253
+ details: {
5254
+ questionId: question.id,
5255
+ state: outcome,
5256
+ communication,
5257
+ runId: question.runId,
5258
+ childIndex: question.childIndex,
5259
+ childId: question.childId,
5260
+ reason: question.reason,
5261
+ answered: outcome === "answered",
5262
+ delivered: !!question.deliveredAt
5263
+ }
5264
+ }, { triggerTurn: outcome === "answered" });
5265
+ }
5266
+ function pollSupervisorQuestions(pi, state, ctx) {
5267
+ for (let channelDir of listSupervisorChannelDirs())
5268
+ for (let question of listSupervisorQuestions(channelDir)) {
5269
+ if (!questionMatchesParentContext(question, state, ctx))
5270
+ continue;
5271
+ let current = reconcileAsyncQuestion(channelDir, question, state);
5272
+ notifyQuestionTerminal(pi, current, channelDir, state);
5273
+ }
5274
+ }
4646
5275
  function createNativeSupervisorChannel(pi, state) {
4647
- let pending = /* @__PURE__ */ new Map(), seenFiles = /* @__PURE__ */ new Set(), poller, lastStaleCleanupAt = 0, registerParentTools = () => {
5276
+ let pending = /* @__PURE__ */ new Map(), seenFiles = /* @__PURE__ */ new Set(), deliveredRequests = /* @__PURE__ */ new Set(), poller, lastStaleCleanupAt = 0, registerParentTools = () => {
4648
5277
  hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME) || pi.registerTool(buildParentIntercomTool(pending, state, NATIVE_SUPERVISOR_TOOL_NAME)), hasTool(pi, "intercom") || pi.registerTool(buildParentIntercomTool(pending, state));
4649
5278
  }, cleanupStaleChannelsIfDue = () => {
4650
5279
  let nowMs = Date.now();
@@ -4655,12 +5284,24 @@ function createNativeSupervisorChannel(pi, state) {
4655
5284
  } catch {
4656
5285
  }
4657
5286
  }
5287
+ }, cancelOwnedQuestions = (reason) => {
5288
+ state.currentSessionId && cancelPendingSupervisorQuestionsForOwner({
5289
+ parentSessionId: state.currentSessionId,
5290
+ parentGeneration: state.sessionGeneration ?? 0,
5291
+ reason
5292
+ });
5293
+ }, settleRunQuestions = (runId, reason) => {
5294
+ state.currentSessionId && cancelPendingSupervisorQuestionsForOwner({
5295
+ parentSessionId: state.currentSessionId,
5296
+ runId,
5297
+ reason
5298
+ });
4658
5299
  }, poll = () => {
4659
5300
  cleanupStaleChannelsIfDue();
4660
5301
  let ctx = state.lastUiContext;
4661
5302
  if (!ctx)
4662
5303
  return;
4663
- refreshPendingRequests(pending, state, ctx);
5304
+ refreshPendingRequests(pending, state, ctx), pollSupervisorQuestions(pi, state, ctx);
4664
5305
  let now = Date.now();
4665
5306
  for (let { channelDir, file } of listRequestFiles()) {
4666
5307
  if (seenFiles.has(file))
@@ -4673,39 +5314,65 @@ function createNativeSupervisorChannel(pi, state) {
4673
5314
  seenFiles.add(file), cleanupRequestLifecycle(request, lifecycle);
4674
5315
  continue;
4675
5316
  }
4676
- seenFiles.add(file), request.expectsReply ? pending.set(request.id, request) : removeRequestFile(request.requestFile), pi.sendMessage({
4677
- customType: "subagent_supervisor_request",
4678
- content: requestVisibleText(request),
5317
+ if (request.expectsReply && pending.set(request.id, request), deliveredRequests.has(request.id)) {
5318
+ seenFiles.add(file);
5319
+ continue;
5320
+ }
5321
+ let communication = requestCommunication(request, state), details = {
5322
+ id: request.id,
5323
+ reason: request.reason,
5324
+ expectsReply: request.expectsReply,
5325
+ runId: request.runId,
5326
+ agent: request.agent,
5327
+ childIndex: request.childIndex,
5328
+ communication
5329
+ };
5330
+ if (request.reason === "progress_update" && request.protocolVersion === 2 ? pi.appendEntry(SUPERVISOR_PROGRESS_TYPE, details) : pi.sendMessage({
5331
+ customType: SUPERVISOR_REQUEST_TYPE,
5332
+ content: requestVisibleText(request, communication),
4679
5333
  display: !0,
4680
- details: {
4681
- id: request.id,
4682
- reason: request.reason,
4683
- expectsReply: request.expectsReply,
5334
+ details
5335
+ }, { triggerTurn: request.expectsReply || request.reason === "handoff" }), deliveredRequests.add(request.id), seenFiles.add(file), request.expectsReply || removeRequestFile(request.requestFile), request.expectsReply) {
5336
+ let job = state.asyncJobs.get(request.runId);
5337
+ job && (job.activityState = "needs_attention");
5338
+ let events = pi.events;
5339
+ events?.emit(INTERCOM_DETACH_REQUEST_EVENT, {
5340
+ requestId: request.id,
4684
5341
  runId: request.runId,
4685
5342
  agent: request.agent,
4686
5343
  childIndex: request.childIndex
4687
- }
4688
- }), request.expectsReply && pi.events?.emit(INTERCOM_DETACH_REQUEST_EVENT, {
4689
- requestId: request.id,
4690
- runId: request.runId,
4691
- agent: request.agent,
4692
- childIndex: request.childIndex
4693
- });
5344
+ }), events?.emit(SUBAGENT_CONTROL_EVENT, {
5345
+ type: "needs_attention",
5346
+ to: "needs_attention",
5347
+ runId: request.runId,
5348
+ agent: request.agent,
5349
+ index: request.childIndex
5350
+ });
5351
+ }
4694
5352
  }
4695
5353
  };
4696
5354
  return {
4697
5355
  start: () => {
4698
- poller || (registerParentTools(), poll(), poller = setInterval(poll, CHANNEL_POLL_MS), poller.unref?.());
5356
+ if (!poller) {
5357
+ registerParentTools();
5358
+ for (let entry of state.lastUiContext?.sessionManager.getBranch?.() ?? []) {
5359
+ let data = entry.type === "custom_message" && entry.customType === SUPERVISOR_REQUEST_TYPE ? entry.details : entry.type === "custom" && entry.customType === SUPERVISOR_PROGRESS_TYPE ? entry.data : void 0;
5360
+ data && typeof data == "object" && "id" in data && typeof data.id == "string" && deliveredRequests.add(data.id);
5361
+ }
5362
+ poll(), poller = setInterval(poll, CHANNEL_POLL_MS), poller.unref?.();
5363
+ }
4699
5364
  },
4700
5365
  dispose: () => {
4701
- poller && clearInterval(poller), poller = void 0, pending.clear(), seenFiles.clear();
5366
+ cancelOwnedQuestions("parent supervisor channel disposed"), poller && clearInterval(poller), poller = void 0, pending.clear(), seenFiles.clear(), deliveredRequests.clear();
4702
5367
  },
4703
- pending
5368
+ pending,
5369
+ cancelOwnedQuestions,
5370
+ settleRunQuestions
4704
5371
  };
4705
5372
  }
4706
5373
 
4707
5374
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/extension/rpc.js
4708
- import * as path8 from "node:path";
5375
+ import * as path9 from "node:path";
4709
5376
  import { Compile } from "typebox/compile";
4710
5377
  var SUBAGENT_RPC_PROTOCOL_VERSION = 1, SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request", SUBAGENT_RPC_READY_EVENT = "subagents:rpc:v1:ready", SUBAGENT_RPC_REPLY_EVENT_PREFIX = "subagents:rpc:v1:reply:", SUBAGENT_RPC_METHODS = ["ping", "status", "spawn", "interrupt", "stop"], SubagentRpcError = class extends Error {
4711
5378
  code;
@@ -4812,7 +5479,7 @@ function stopAsyncRun(params, options, ctx) {
4812
5479
  }
4813
5480
  if (!location.asyncDir)
4814
5481
  throw new SubagentRpcError("not_found", "Async run not found or already completed; stop requires a live async run directory.");
4815
- let currentSessionId = ctx.sessionManager.getSessionId(), initialStatus = readStatus(location.asyncDir), initialRunId = initialStatus?.runId ?? location.resolvedId ?? path8.basename(location.asyncDir);
5482
+ let currentSessionId = ctx.sessionManager.getSessionId(), initialStatus = readStatus(location.asyncDir), initialRunId = initialStatus?.runId ?? location.resolvedId ?? path9.basename(location.asyncDir);
4816
5483
  if (!initialStatus)
4817
5484
  throw new SubagentRpcError("not_found", `Status file not found for async run '${initialRunId}'.`);
4818
5485
  if (!currentSessionId || initialStatus.sessionId !== currentSessionId)
@@ -5044,7 +5711,9 @@ var ACTIVE_STATES = ["queued", "running"], DEFAULT_TIMEOUT_MS = 1800 * 1e3, MIN_
5044
5711
  SUBAGENT_FOREGROUND_COMPLETE_EVENT,
5045
5712
  SUBAGENT_CONTROL_EVENT,
5046
5713
  SUBAGENT_CONTROL_INTERCOM_EVENT,
5047
- SUBAGENT_RESULT_INTERCOM_EVENT
5714
+ SUBAGENT_RESULT_INTERCOM_EVENT,
5715
+ INTERCOM_DETACH_REQUEST_EVENT,
5716
+ SUBAGENT_QUESTION_EVENT
5048
5717
  ];
5049
5718
  function defaultSleep(ms, signal) {
5050
5719
  return new Promise((resolve3) => {
@@ -5113,8 +5782,8 @@ function summarizeForegroundChildren(run, indices) {
5113
5782
  !indices.has(child.index) || child.status === "detached" || counts.set(child.status, (counts.get(child.status) ?? 0) + 1);
5114
5783
  return [...counts.entries()].map(([status, count]) => `${count} ${status}`).join(", ");
5115
5784
  }
5116
- function needsAttention(run) {
5117
- return run.activityState === "needs_attention";
5785
+ function needsAttention(run, sessionId) {
5786
+ return run.activityState === "needs_attention" || hasPendingBlockingSupervisorRequest(run.id, sessionId);
5118
5787
  }
5119
5788
  function backgroundWorkIdentity(item) {
5120
5789
  return `${item.provider}\0${item.sessionId}\0${item.id}`;
@@ -5136,7 +5805,7 @@ function activeRunsForSession(params, deps) {
5136
5805
  return params.id ? runs.filter((run) => matchesId(run, params.id)) : runs;
5137
5806
  }
5138
5807
  function attentionRunsForSession(params, deps, initialIds) {
5139
- return activeRunsForSession(params, deps).filter((run) => needsAttention(run) && initialIds.has(run.id));
5808
+ return activeRunsForSession(params, deps).filter((run) => needsAttention(run, deps.state.currentSessionId) && initialIds.has(run.id));
5140
5809
  }
5141
5810
  function allRunsForSession(params, deps) {
5142
5811
  let asyncDirRoot = deps.asyncDirRoot ?? ASYNC_DIR, resultsDir = deps.resultsDir ?? RESULTS_DIR, runs = listAsyncRuns(asyncDirRoot, {
@@ -5175,6 +5844,8 @@ async function waitForDetachedForegroundRun(run, signal, deps, startedAt, now, p
5175
5844
  let outcome = summarizeForegroundChildren(current, initialDetachedIndices);
5176
5845
  return result(`Waited ${formatDuration(now() - startedAt)} for remembered detached foreground run "${run.runId}"; done. Outcome: ${outcome || "no recovered child status"}. Completion event observed; inspect with subagent({ action: "status", id: "${run.runId}" }) for recovered output.`);
5177
5846
  }
5847
+ if (deps.wasInterrupted?.())
5848
+ return result("Wait interrupted by user input; background work remains active.");
5178
5849
  if (signal?.aborted)
5179
5850
  return result(`Wait aborted after ${formatDuration(now() - startedAt)}. Remembered foreground run "${run.runId}" remains detached.`, !0);
5180
5851
  if (now() - startedAt >= timeoutMs)
@@ -5182,12 +5853,59 @@ async function waitForDetachedForegroundRun(run, signal, deps, startedAt, now, p
5182
5853
  await waitForWake(pollIntervalMs, signal, deps);
5183
5854
  }
5184
5855
  }
5856
+ async function waitForSupervisorQuestion(questionId, signal, deps, startedAt, now, pollIntervalMs, timeoutMs) {
5857
+ let sessionId = deps.state.currentSessionId;
5858
+ if (!sessionId)
5859
+ return result("subagent_wait requires an active session identity to scope background work safely.", !0);
5860
+ let releaseWait = registerQuestionWait([questionId]);
5861
+ try {
5862
+ for (; ; ) {
5863
+ let found = findSupervisorQuestion(questionId);
5864
+ if (!found)
5865
+ return result(`No supervisor question matched "${questionId}".`, !0);
5866
+ let { channelDir } = found, { question } = found;
5867
+ if (question.parentSessionId !== sessionId || deps.state.currentSessionId !== sessionId)
5868
+ return result(`Supervisor question "${questionId}" belongs to another session.`, !0);
5869
+ if ((deps.state.sessionGeneration ?? 0) !== question.parentGeneration)
5870
+ return result(`Supervisor question "${questionId}" was cancelled by a session replacement.`, !0);
5871
+ if (question = reconcileAsyncQuestion(channelDir, question, deps.state), supervisorQuestionIsTerminal(question)) {
5872
+ claimQuestionNotification(channelDir, question.id);
5873
+ let state = supervisorQuestionPublicState(question);
5874
+ return {
5875
+ content: [{ type: "text", text: formatSupervisorQuestionAnswer(question) }],
5876
+ ...state === "answered" ? {} : { isError: !0 },
5877
+ details: {
5878
+ mode: "management",
5879
+ results: [],
5880
+ questionId: question.id,
5881
+ state,
5882
+ runId: question.runId,
5883
+ answered: state === "answered",
5884
+ delivered: !!question.deliveredAt
5885
+ }
5886
+ };
5887
+ }
5888
+ if (deps.wasInterrupted?.())
5889
+ return result("Wait interrupted by user input; background work remains active.");
5890
+ if (signal?.aborted)
5891
+ return result(`Wait aborted after ${formatDuration(now() - startedAt)} for supervisor question "${questionId}".`, !0);
5892
+ if (now() - startedAt >= timeoutMs)
5893
+ return result(`Wait timed out after ${formatDuration(timeoutMs)} for supervisor question "${questionId}". The question remains pending until answered, expired, or cancelled.`, !0);
5894
+ await waitForWake(pollIntervalMs, signal, deps);
5895
+ }
5896
+ } finally {
5897
+ releaseWait();
5898
+ }
5899
+ }
5185
5900
  async function waitForSubagents(params, signal, deps) {
5186
5901
  if (deps.enabled === !1)
5187
5902
  return result('subagent_wait is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED; returning immediately without blocking background work. Active work keeps going, and you can inspect subagents with subagent({ action: "status" }) or rely on completion notifications.');
5188
5903
  if (!deps.state.currentSessionId)
5189
5904
  return result("subagent_wait requires an active session identity to scope background work safely.", !0);
5190
- let now = deps.now ?? Date.now, pollIntervalMs = Math.max(MIN_POLL_INTERVAL_MS, deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS), timeoutMs = params.timeoutMs !== void 0 && params.timeoutMs > 0 ? params.timeoutMs : DEFAULT_TIMEOUT_MS, startedAt = now(), waitForAll = params.id ? !0 : params.all === !0, active, foreground, providerSnapshot;
5905
+ let now = deps.now ?? Date.now, pollIntervalMs = Math.max(MIN_POLL_INTERVAL_MS, deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS), timeoutMs = params.timeoutMs !== void 0 && params.timeoutMs > 0 ? params.timeoutMs : DEFAULT_TIMEOUT_MS, startedAt = now();
5906
+ if (params.questionId?.trim())
5907
+ return waitForSupervisorQuestion(params.questionId.trim(), signal, deps, startedAt, now, pollIntervalMs, timeoutMs);
5908
+ let waitForAll = params.id ? !0 : params.all === !0, active, foreground, providerSnapshot;
5191
5909
  try {
5192
5910
  active = activeRunsForSession(params, deps), foreground = activeDetachedForegroundRuns(params, deps), providerSnapshot = params.id ? { providers: [], items: [] } : backgroundWorkForSession(deps, startedAt);
5193
5911
  } catch (error) {
@@ -5208,7 +5926,7 @@ async function waitForSubagents(params, signal, deps) {
5208
5926
  let providerActive = providerSnapshot.items;
5209
5927
  if (active.length === 0 && providerActive.length === 0)
5210
5928
  return result(params.id ? `No active run matched "${params.id}". Nothing to wait for.` : "No active async runs or registered provider work in this session. Nothing to wait for.");
5211
- let waitParams = params.id ? { ...params, id: active[0].id } : params, initialAsyncIds = new Set(active.map((run) => run.id)), initialProviderIds = new Set(providerActive.map(backgroundWorkIdentity)), initialProviderNames = new Set(providerActive.map((item) => item.provider)), initialCount = initialAsyncIds.size + initialProviderIds.size, stopOnAttention = deps.stopOnAttention !== !1, attention = active.filter((run) => needsAttention(run)), isDone = () => {
5929
+ let waitParams = params.id ? { ...params, id: active[0].id } : params, initialAsyncIds = new Set(active.map((run) => run.id)), initialProviderIds = new Set(providerActive.map(backgroundWorkIdentity)), initialProviderNames = new Set(providerActive.map((item) => item.provider)), initialCount = initialAsyncIds.size + initialProviderIds.size, stopOnAttention = deps.stopOnAttention !== !1, attention = active.filter((run) => needsAttention(run, deps.state.currentSessionId)), isDone = () => {
5212
5930
  if (stopOnAttention && attention.some((run) => initialAsyncIds.has(run.id)))
5213
5931
  return !0;
5214
5932
  let activeAsyncIds = new Set(active.map((run) => run.id)), activeProviderIds2 = new Set(providerActive.map(backgroundWorkIdentity));
@@ -5219,8 +5937,12 @@ async function waitForSubagents(params, signal, deps) {
5219
5937
  ...activeInitialRuns.map((run) => `${run.id} (${run.state})`),
5220
5938
  ...activeInitialProviderItems.map((item) => `${item.provider}/${item.id}`)
5221
5939
  ].join(", ");
5940
+ if (deps.wasInterrupted?.())
5941
+ return result("Wait interrupted by user input; background work remains active.");
5222
5942
  if (signal?.aborted)
5223
5943
  return result(`Wait aborted after ${formatDuration(now() - startedAt)}. Still active: ${stillActive}.`, !0);
5944
+ if (deps.shouldYield?.())
5945
+ return result("Wait yielded for pending session messages; background work remains active.");
5224
5946
  if (now() - startedAt >= timeoutMs)
5225
5947
  return result(`Wait timed out after ${formatDuration(timeoutMs)} with ${activeInitialRuns.length} async run(s) and ${activeInitialProviderItems.length} provider item(s) still active: ${stillActive}. The work keeps going; call subagent_wait again or inspect subagent status.`, !0);
5226
5948
  try {
@@ -5250,17 +5972,28 @@ async function waitForSubagents(params, signal, deps) {
5250
5972
  }
5251
5973
 
5252
5974
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js
5975
+ var WAIT_INTERRUPTION_SYMBOL = /* @__PURE__ */ Symbol.for("@lunr/subagent-wait-interruption");
5976
+ function registerWaitInterruption(sessionId) {
5977
+ return sessionId ? globalThis[WAIT_INTERRUPTION_SYMBOL]?.owners?.get(sessionId)?.register() : void 0;
5978
+ }
5979
+ function interruptedResult() {
5980
+ return {
5981
+ content: [{ type: "text", text: "Wait interrupted by user input; background work remains active." }],
5982
+ details: { mode: "management", results: [] }
5983
+ };
5984
+ }
5253
5985
  function registerWaitTool(pi, state, enabled = resolveWaitToolConfig().enabled, waitForPendingLaunches) {
5254
5986
  let tool = {
5255
5987
  name: "subagent_wait",
5256
5988
  label: "Subagent Wait",
5257
5989
  description: `Block until background work owned by this session changes, then return.
5258
5990
 
5259
- In an interactive chat, do not call this merely to wait: return control to the user and let Pi wake the session on completion. Call it when the current request must run to completion in this turn, when a skill cannot return before its work finishes, or in a non-interactive run where there is no next turn.
5991
+ Call this when the current turn or skill must finish after its children. For normal interactive completion, yield and let lunR wake the session. Headless sessions auto-drain current-session work after the agent turn.
5260
5992
 
5261
5993
  \u2022 { } \u2014 return when the first initially active async run or registered provider item finishes, or when a subagent needs attention.
5262
5994
  \u2022 { all: true } \u2014 wait for every async run and provider item that was active when the call began.
5263
5995
  \u2022 { id: "..." } \u2014 wait for one async or remembered detached foreground subagent run (id or prefix).
5996
+ \u2022 { questionId: "..." } \u2014 wait for one supervisor question from subagent_supervisor action='ask' (answered/expired/cancelled). Separate from final run results.
5264
5997
  \u2022 { timeoutMs: 600000 } \u2014 stop waiting after N ms; active work keeps running.
5265
5998
 
5266
5999
  Provider jobs are session-scoped and identified exactly, so replacing one job with another cannot hide a completion. Provider extensions must be explicitly loaded in this process. In a child agent, keep \`subagent_wait\` in the child tool allowlist and load each provider through the agent's extensions or subagentOnlyExtensions; this tool never loads providers or grants tools itself.${enabled ? "" : `
@@ -5268,7 +6001,25 @@ Provider jobs are session-scoped and identified exactly, so replacing one job wi
5268
6001
  Configured behavior: subagent_wait is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED and returns immediately without blocking.`}`,
5269
6002
  parameters: SubagentWaitParams,
5270
6003
  async execute(_id, params, signal) {
5271
- return await Promise.resolve(), await waitForPendingLaunches?.(signal), signal?.throwIfAborted(), waitForSubagents(params, signal, { state, events: pi.events, enabled });
6004
+ await Promise.resolve();
6005
+ let interruption = registerWaitInterruption(state.currentSessionId), waitSignal = interruption ? signal ? AbortSignal.any([signal, interruption.signal]) : interruption.signal : signal;
6006
+ try {
6007
+ try {
6008
+ await waitForPendingLaunches?.(waitSignal);
6009
+ } catch (error) {
6010
+ if (interruption?.wasInterrupted())
6011
+ return interruptedResult();
6012
+ throw error;
6013
+ }
6014
+ return interruption?.wasInterrupted() ? interruptedResult() : (signal?.throwIfAborted(), waitForSubagents(params, waitSignal, {
6015
+ state,
6016
+ events: pi.events,
6017
+ enabled,
6018
+ wasInterrupted: interruption?.wasInterrupted
6019
+ }));
6020
+ } finally {
6021
+ interruption?.unregister();
6022
+ }
5272
6023
  }
5273
6024
  };
5274
6025
  pi.registerTool(tool);
@@ -5295,7 +6046,7 @@ async function drainOutstandingWork(deps) {
5295
6046
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
5296
6047
  throw new Error("Auto-drain timeoutMs must be a positive finite number.");
5297
6048
  let deadlineAt = now() + timeoutMs, hasWork = deps.hasWork ?? hasOutstandingWork, wait = deps.wait ?? waitForSubagents;
5298
- for (; hasWork(sessionId, now()); ) {
6049
+ for (; !deps.hasPendingMessages?.() && hasWork(sessionId, now()); ) {
5299
6050
  let remainingMs = deadlineAt - now();
5300
6051
  if (remainingMs <= 0)
5301
6052
  throw new Error(`Auto-drain timed out after ${timeoutMs}ms with background work still active in session '${sessionId}'.`);
@@ -5304,6 +6055,7 @@ async function drainOutstandingWork(deps) {
5304
6055
  events: deps.events,
5305
6056
  now,
5306
6057
  stopOnAttention: !1,
6058
+ shouldYield: deps.hasPendingMessages,
5307
6059
  failOnFailedRuns: !0
5308
6060
  });
5309
6061
  if (waitResult.isError)
@@ -5395,7 +6147,7 @@ function formatSingleCompletion(details) {
5395
6147
  }
5396
6148
  function parseSubagentNotifyContent(content) {
5397
6149
  let lines = content.split(`
5398
- `), match = (lines[0] ?? "").match(/^(Background task|Detached foreground task) (completed|failed|paused): \*\*(.+?)\*\*(?:\s+(\([^)]*\)))?$/);
6150
+ `), match = (lines[0] ?? "").match(/^(Background task|Detached foreground task) (completed|failed|paused|stopped): \*\*(.+?)\*\*(?:\s+(\([^)]*\)))?$/);
5399
6151
  if (!match)
5400
6152
  return;
5401
6153
  let body = lines.slice(2), sessionIndex = -1;
@@ -5439,7 +6191,7 @@ function sendCompletion(pi, details) {
5439
6191
  customType: "subagent-notify",
5440
6192
  content,
5441
6193
  display: !0
5442
- }, { triggerTurn: !0 });
6194
+ }, { triggerTurn: details.some((detail) => detail.status !== "stopped") });
5443
6195
  }
5444
6196
  function completionBatchKey(result2) {
5445
6197
  let sessionId = typeof result2.sessionId == "string" ? result2.sessionId.trim() : "";
@@ -5449,13 +6201,38 @@ function completionBatchKey(result2) {
5449
6201
  return cwd ? `cwd:${cwd}` : "unknown";
5450
6202
  }
5451
6203
  function buildCompletionDetails(result2) {
5452
- let agent = result2.agent ?? "unknown", summary = typeof result2.summary == "string" ? result2.summary : "", status = !result2.success && (result2.exitCode === 0 || result2.state === "paused" || summary.startsWith("Paused after interrupt.")) ? "paused" : result2.success ? "completed" : "failed", taskInfo = result2.taskIndex !== void 0 && result2.totalTasks !== void 0 ? ` (${result2.taskIndex + 1}/${result2.totalTasks})` : void 0, session = result2.shareUrl ? { label: "Session", value: result2.shareUrl } : result2.shareError ? { label: "Session share error", value: result2.shareError } : result2.sessionFile ? { label: "Session file", value: result2.sessionFile } : void 0;
6204
+ let agent = result2.agent ?? "unknown", summary = typeof result2.summary == "string" ? result2.summary : "", paused = !result2.success && (result2.exitCode === 0 || result2.state === "paused" || summary.startsWith("Paused after interrupt.")), status = result2.state === "stopped" ? "stopped" : paused ? "paused" : result2.success ? "completed" : "failed", taskInfo = result2.taskIndex !== void 0 && result2.totalTasks !== void 0 ? ` (${result2.taskIndex + 1}/${result2.totalTasks})` : void 0, session = result2.shareUrl ? { label: "Session", value: result2.shareUrl } : result2.shareError ? { label: "Session share error", value: result2.shareError } : result2.sessionFile ? { label: "Session file", value: result2.sessionFile } : void 0;
5453
6205
  return {
5454
6206
  agent,
5455
6207
  status,
5456
6208
  ...result2.source ? { source: result2.source } : {},
5457
6209
  ...taskInfo ? { taskInfo } : {},
5458
- resultPreview: summary,
6210
+ resultPreview: [
6211
+ result2.id ? `Run: ${result2.id}` : void 0,
6212
+ result2.asyncDir ? `Async dir: ${result2.asyncDir}` : void 0,
6213
+ result2.results?.length ? result2.results.map((child, index) => {
6214
+ let output = child.summary ?? (child.error ? `${child.error}
6215
+
6216
+ Output:
6217
+ ${child.output}` : child.output), report = child.acceptance?.childReport, childIndex = child.index ?? index;
6218
+ return [
6219
+ `${childIndex + 1}. ${child.agent} [${child.status ?? resolveSubagentResultStatus({ success: child.success, state: result2.state })}]`,
6220
+ child.artifactPath ? `Output artifact: ${child.artifactPath}` : void 0,
6221
+ child.sessionPath ? `Session: ${child.sessionPath}` : void 0,
6222
+ child.sessionPath && result2.id && result2.source !== "foreground" ? `Revive: subagent({ action: "resume", id: ${JSON.stringify(result2.id)}, index: ${childIndex}, message: "..." })` : void 0,
6223
+ ...formatNestedResultLines(child.children),
6224
+ output,
6225
+ report ? `\`\`\`acceptance-report
6226
+ ${JSON.stringify(report, null, 2)}
6227
+ \`\`\`` : void 0
6228
+ ].filter((line) => line !== void 0).join(`
6229
+ `);
6230
+ }).join(`
6231
+
6232
+ `) : summary
6233
+ ].filter((line) => line !== void 0).join(`
6234
+
6235
+ `),
5459
6236
  ...typeof result2.durationMs == "number" ? { durationMs: result2.durationMs } : {},
5460
6237
  ...session ? { sessionLabel: session.label, sessionValue: session.value } : {}
5461
6238
  };
@@ -5538,15 +6315,15 @@ function handleSubagentSteeringNotice(input) {
5538
6315
  }
5539
6316
 
5540
6317
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/extension/config.js
5541
- import * as fs7 from "node:fs";
5542
- import * as path9 from "node:path";
6318
+ import * as fs8 from "node:fs";
6319
+ import * as path10 from "node:path";
5543
6320
  function getConfigPath() {
5544
- return path9.join(getAgentDir(), "extensions", "subagent", "config.json");
6321
+ return path10.join(getAgentDir(), "extensions", "subagent", "config.json");
5545
6322
  }
5546
6323
  function readConfigForUpdate(configPath = getConfigPath()) {
5547
- if (!fs7.existsSync(configPath))
6324
+ if (!fs8.existsSync(configPath))
5548
6325
  return {};
5549
- let parsed = JSON.parse(fs7.readFileSync(configPath, "utf-8"));
6326
+ let parsed = JSON.parse(fs8.readFileSync(configPath, "utf-8"));
5550
6327
  if (!parsed || typeof parsed != "object" || Array.isArray(parsed))
5551
6328
  throw new Error(`Subagent config at '${configPath}' must be a JSON object`);
5552
6329
  return parsed;
@@ -5562,25 +6339,33 @@ function loadConfig() {
5562
6339
  }
5563
6340
 
5564
6341
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js
5565
- import * as fs8 from "node:fs";
5566
- import * as path10 from "node:path";
5567
- var CUSTOM_TOOL_DESCRIPTION_FILE = "subagent-tool-description.md", CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024, SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
6342
+ import * as fs9 from "node:fs";
6343
+ import * as path11 from "node:path";
6344
+ var CUSTOM_TOOL_DESCRIPTION_FILE = "subagent-tool-description.md", CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024, SUBAGENT_TIER_GUIDANCE = `TIER SELECTION:
6345
+ \u2022 Choose the lowest tier that can reliably complete the task.
6346
+ \u2022 light: Use for simple, straightforward tasks that require little reasoning. Good for quick checks, finding information, collecting facts for research, inspecting a small amount of code, or verifying a specific fact.
6347
+ \u2022 standard: Use for moderately difficult work and everyday coding tasks. Good for writing simple code, fixing a clearly described bug, reviewing a focused change, or completing work with clear requirements. Use heavy when the task requires deep architectural understanding or complex reasoning.
6348
+ \u2022 heavy: Use for complex or ambiguous tasks that require deep reasoning and strong code understanding. Good for implementing complex plans, debugging difficult or poorly understood problems, reviewing large or high-risk changes, and making architectural decisions.`, SUBAGENT_COORDINATION_GUIDANCE = "Define file ownership, local decision authority, and required outputs at launch. Establish shared contracts before dependent parallel work; use chains and artifacts to pass results. When enabled, native child intercom reaches the supervisor only, not siblings. Reserve parent relays for actionable exceptions, not routine progress or implementation approvals.", SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
5568
6349
  \u2022 Prompt children directly. There is no agent roster. Every execution task needs task (the full child prompt) and description (a concise UI label).
5569
- \u2022 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.
5570
- \u2022 permissions is "full" or "read-only". Omitted permissions means full. Plan-mode parents must pass permissions: "read-only"; full or omitted launches are rejected.
5571
- \u2022 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*.
5572
- \u2022 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.
6350
+ \u2022 Every executable child chooses exactly one of tier: "light"|"standard"|"heavy" (default) or model: "provider/id" when the user names a model. Do not pass both, and do not use inherit. Missing, disabled, unconfigured, unavailable, or unauthenticated selections fail before launch.
6351
+ \u2022 Optional thinking (off/minimal/low/medium/high/xhigh/max) is only valid with an explicit model. Tier launches use the configured tier thinking level.
6352
+ ${SUBAGENT_TIER_GUIDANCE}
6353
+ \u2022 permissions is "full" or "read-only". Omitted permissions means full. Read-only parents must pass permissions: "read-only"; full or omitted launches are rejected.
6354
+ \u2022 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.status|check|recommend-model/schedule*.
6355
+ \u2022 ${SUBAGENT_ASYNC_GUIDANCE}
5573
6356
  \u2022 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.
5574
6357
  \u2022 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.
6358
+ \u2022 ${SUBAGENT_COORDINATION_GUIDANCE}
6359
+ \u2022 When Subagent communication is off in /settings, child contact and parent questions/steering are unavailable; final results and subagent_wait still work.
5575
6360
  \u2022 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.`, FULL_SUBAGENT_TOOL_DESCRIPTION = `Delegate work to generic children by prompting them directly. There are no named agent types.
5576
6361
 
5577
6362
  EXECUTION (use exactly ONE mode):
5578
- \u2022 SINGLE: { task, description, tier, permissions? } \u2014 one child. Multiple SINGLE calls in the same turn run concurrently; explicit concurrency/run limits still apply.
5579
- \u2022 PARALLEL: { tasks: [{task, description, tier, permissions?, count?, output?, reads?, progress?}, ...], concurrency?: number, worktree?: true } \u2014 one-call concurrent execution (default: all tasks at once; worktree: isolate each task in a git worktree)
5580
- \u2022 CHAIN: { chain: [{task, description, tier, permissions?}, {parallel:[{task, description, tier, permissions?, count:3}]}] } \u2014 sequential pipeline with optional parallel fan-out. Use chain when a later child needs an earlier result.
6363
+ \u2022 SINGLE: { task, description, tier|model, thinking?, permissions? } \u2014 one child. Multiple SINGLE calls in the same turn run concurrently; explicit concurrency/run limits still apply.
6364
+ \u2022 PARALLEL: { tasks: [{task, description, tier|model, thinking?, permissions?, count?, output?, reads?, progress?}, ...], concurrency?: number, worktree?: true } \u2014 one-call concurrent execution (default: all tasks at once; worktree: isolate each task in a git worktree)
6365
+ \u2022 CHAIN: { chain: [{task, description, tier|model, thinking?, permissions?}, {parallel:[{task, description, tier|model, thinking?, permissions?, count:3}]}] } \u2014 sequential pipeline with optional parallel fan-out. Use chain when a later child needs an earlier result.
5581
6366
  \u2022 description is required, single-line, max 80 characters. It is UI metadata only. task is the complete child prompt.
5582
- \u2022 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".
5583
- \u2022 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.
6367
+ \u2022 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). Read-only parents may launch only permissions: "read-only".
6368
+ \u2022 Model selection: pass tier by default ("light"|"standard"|"heavy"). Pass model: "provider/id" only when the user specifies a model. Exactly one of tier or model. Optional thinking only with model; tier uses configured thinking. Direct model launches do not require tier mode to be enabled. No inherit and no silent fallback for an explicit model.
5584
6369
  \u2022 Children always start with a fresh session (no inherited parent transcript).
5585
6370
  \u2022 Optional timeout: { timeoutMs } or { maxRuntimeMs } sets a run-level max runtime for foreground and async/background runs
5586
6371
 
@@ -5595,8 +6380,7 @@ CHAIN EXAMPLES:
5595
6380
  \u2022 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"}] }
5596
6381
 
5597
6382
  CONTROL (use action field, omit task/chain/tasks):
5598
- \u2022 { action: "watchdog.status" | "watchdog.check" | "watchdog.recommend-model" } - inspect the opt-in subagent watchdog and its strong complementary model recommendation
5599
- \u2022 { 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
6383
+ \u2022 { action: "watchdog.status" | "watchdog.check" | "watchdog.recommend-model" } - inspect the opt-in subagent watchdog and its strong complementary model recommendation (read-only; there is no configure action)
5600
6384
  \u2022 { action: "status", id: "..." } - inspect an async/background run by id or prefix
5601
6385
  \u2022 { action: "status", view: "fleet" } - read-only active foreground/async fleet view with transcript commands
5602
6386
  \u2022 { action: "status", id: "...", view: "transcript", index?: 0, lines?: 80 } - tail a run or child output/session transcript
@@ -5604,10 +6388,12 @@ CONTROL (use action field, omit task/chain/tasks):
5604
6388
  \u2022 { action: "stop", id: "..." } - stop a current-session top-level async run; stopped runs finish with state "stopped"
5605
6389
  \u2022 { 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
5606
6390
  \u2022 { 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.
6391
+ \u2022 subagent_supervisor({ action: "ask", id, reason, message, index?, childId? }) - ask one running async child; returns question id immediately. Ask only when the child owns missing context, the answer changes a concrete next decision, and waiting risks block/rework. No broadcast, revive, task replacement, status polling, or micromanagement.
6392
+ \u2022 subagent_wait({ questionId }) - wait for that supervisor question answer/expiry/cancel. Answers stay separate from final run results.
5607
6393
  \u2022 { 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
5608
6394
 
5609
6395
  SCHEDULE (opt-in; requires { "scheduledRuns": { "enabled": true } } in config.json):
5610
- \u2022 { 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.
6396
+ \u2022 { action: "schedule", task, description, tier|model, thinking?, 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.
5611
6397
  \u2022 { action: "schedule-list" } - list scheduled runs for this session
5612
6398
  \u2022 { action: "schedule-status", id: "..." } - inspect one scheduled run
5613
6399
  \u2022 { action: "schedule-cancel", id: "..." } - cancel a scheduled run before it fires
@@ -5618,19 +6404,22 @@ DIAGNOSTICS:
5618
6404
  ${SUBAGENT_SAFETY_GUIDANCE}`, COMPACT_SUBAGENT_TOOL_DESCRIPTION = `Delegate to generic children by prompting them. Use exactly one mode per call.
5619
6405
 
5620
6406
  EXECUTE:
5621
- \u2022 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.
5622
- \u2022 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".
5623
- \u2022 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.
6407
+ \u2022 SINGLE {task, description, tier|model, thinking?, permissions?} (same-turn singles overlap); PARALLEL {tasks:[{task,description,tier|model,thinking?,permissions?,count?,output?,reads?,progress?}], concurrency?, worktree?}; CHAIN {chain:[{task,description,tier|model,thinking?,permissions?},{parallel:[...]}]} for sequential work.
6408
+ \u2022 description is required (single-line, max 80 chars, UI only). task is the full child prompt. permissions omitted = full. Read-only parents must pass permissions:"read-only".
6409
+ \u2022 Exactly one of tier:"light"|"standard"|"heavy" (default) or model:"provider/id" when the user names a model. thinking only with model. No inherit; fail closed on unavailable selections. Children always start fresh. timeoutMs/maxRuntimeMs apply to foreground and async/background runs.
6410
+ ${SUBAGENT_TIER_GUIDANCE}
6411
+ \u2022 ${SUBAGENT_COORDINATION_GUIDANCE}
6412
+ \u2022 When Subagent communication is off in /settings, child contact and parent questions/steering are unavailable; final results and subagent_wait still work.
5624
6413
  \u2022 Chain templates may use {task}, {previous}, {chain_dir}, and named outputs. Parallel worktree isolation requires a clean git repo.
5625
6414
  \u2022 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}]}] }
5626
6415
 
5627
6416
  CONTROL:
5628
- \u2022 Use action without execution fields: doctor, watchdog.status, watchdog.check, watchdog.recommend-model, watchdog.configure, status, interrupt, stop, resume, steer, append-step.
6417
+ \u2022 Use action without execution fields: doctor, watchdog.status, watchdog.check, watchdog.recommend-model, status, interrupt, stop, resume, steer, append-step.
5629
6418
  \u2022 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.
5630
6419
  \u2022 Opt-in schedule actions: schedule, schedule-list, schedule-status, schedule-cancel. Schedule only explicit delayed runs the user asked for.
5631
6420
 
5632
6421
  ASYNC / WAIT:
5633
- \u2022 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.
6422
+ \u2022 ${SUBAGENT_ASYNC_GUIDANCE}
5634
6423
  \u2022 Status and artifacts live under asyncId/asyncDir with status.json, events.jsonl, output logs, session files, and { action:"status", id:"..." }.
5635
6424
 
5636
6425
  SAFETY:
@@ -5649,8 +6438,8 @@ function resolveToolDescriptionMode(config, options) {
5649
6438
  function customDescriptionPaths(options) {
5650
6439
  let cwd = options?.cwd ?? process.cwd(), agentDir = options?.agentDir ?? getAgentDir();
5651
6440
  return [
5652
- path10.join(getProjectConfigDir(cwd), CUSTOM_TOOL_DESCRIPTION_FILE),
5653
- path10.join(agentDir, CUSTOM_TOOL_DESCRIPTION_FILE)
6441
+ path11.join(getProjectConfigDir(cwd), CUSTOM_TOOL_DESCRIPTION_FILE),
6442
+ path11.join(agentDir, CUSTOM_TOOL_DESCRIPTION_FILE)
5654
6443
  ];
5655
6444
  }
5656
6445
  function renderCustomTemplate(template, options) {
@@ -5673,7 +6462,7 @@ function loadCustomToolDescription(options) {
5673
6462
  for (let filePath of customDescriptionPaths(options)) {
5674
6463
  let stat;
5675
6464
  try {
5676
- stat = fs8.statSync(filePath);
6465
+ stat = fs9.statSync(filePath);
5677
6466
  } catch (error) {
5678
6467
  if (typeof error == "object" && error !== null && "code" in error && error.code === "ENOENT")
5679
6468
  continue;
@@ -5689,7 +6478,7 @@ function loadCustomToolDescription(options) {
5689
6478
  continue;
5690
6479
  }
5691
6480
  try {
5692
- let template = fs8.readFileSync(filePath, "utf-8").trim();
6481
+ let template = fs9.readFileSync(filePath, "utf-8").trim();
5693
6482
  if (!template) {
5694
6483
  warn(options, `Ignoring empty custom tool description '${filePath}'.`);
5695
6484
  continue;
@@ -5728,24 +6517,24 @@ function buildSubagentToolDescription(config = {}, options) {
5728
6517
  // packages/coding-agent/dist/builtin-extensions/pi-subagents/src/extension/index.js
5729
6518
  function getSubagentSessionRoot(parentSessionFile) {
5730
6519
  if (parentSessionFile) {
5731
- let baseName = path11.basename(parentSessionFile, ".jsonl"), sessionsDir = path11.dirname(parentSessionFile);
5732
- return path11.join(sessionsDir, baseName);
6520
+ let baseName = path12.basename(parentSessionFile, ".jsonl"), sessionsDir = path12.dirname(parentSessionFile);
6521
+ return path12.join(sessionsDir, baseName);
5733
6522
  }
5734
- return fs9.mkdtempSync(path11.join(os.tmpdir(), "pi-subagent-session-"));
6523
+ return fs10.mkdtempSync(path12.join(os.tmpdir(), "pi-subagent-session-"));
5735
6524
  }
5736
6525
  function expandTilde(p) {
5737
- return p.startsWith("~/") ? path11.join(os.homedir(), p.slice(2)) : p;
6526
+ return p.startsWith("~/") ? path12.join(os.homedir(), p.slice(2)) : p;
5738
6527
  }
5739
6528
  function ensureAccessibleDir(dirPath) {
5740
- fs9.mkdirSync(dirPath, { recursive: !0 });
6529
+ fs10.mkdirSync(dirPath, { recursive: !0 });
5741
6530
  try {
5742
- fs9.accessSync(dirPath, fs9.constants.R_OK | fs9.constants.W_OK);
6531
+ fs10.accessSync(dirPath, fs10.constants.R_OK | fs10.constants.W_OK);
5743
6532
  } catch {
5744
6533
  try {
5745
- fs9.rmSync(dirPath, { recursive: !0, force: !0 });
6534
+ fs10.rmSync(dirPath, { recursive: !0, force: !0 });
5746
6535
  } catch {
5747
6536
  }
5748
- fs9.mkdirSync(dirPath, { recursive: !0 }), fs9.accessSync(dirPath, fs9.constants.R_OK | fs9.constants.W_OK);
6537
+ fs10.mkdirSync(dirPath, { recursive: !0 }), fs10.accessSync(dirPath, fs10.constants.R_OK | fs10.constants.W_OK);
5749
6538
  }
5750
6539
  }
5751
6540
  function isSlashResultRunning(result2) {
@@ -5760,23 +6549,58 @@ function effectiveParallelTaskCount(tasks) {
5760
6549
  return total + count;
5761
6550
  }, 0);
5762
6551
  }
5763
- function renderSubagentCall(args, theme, context) {
6552
+ function matchingActionJobs(state, requestedId) {
6553
+ let jobs = /* @__PURE__ */ new Map();
6554
+ for (let job of state.asyncJobs.values())
6555
+ jobs.set(job.asyncId, job);
6556
+ for (let job of state.fleetJobs?.values() ?? [])
6557
+ jobs.set(job.asyncId, job);
6558
+ let exact = jobs.get(requestedId);
6559
+ return exact ? [exact] : [...jobs.values()].filter((job) => job.asyncId.startsWith(requestedId));
6560
+ }
6561
+ function resolveSubagentActionDisplayTitle(args, state) {
6562
+ let requestedId = (args.id || args.runId || "").trim();
6563
+ if (!requestedId)
6564
+ return;
6565
+ let matches = matchingActionJobs(state, requestedId);
6566
+ if (matches.length !== 1)
6567
+ return;
6568
+ let job = matches[0], steps = job.steps ?? [];
6569
+ if (Number.isInteger(args.index)) {
6570
+ let step = steps.find((candidate) => candidate.index === args.index) ?? steps[args.index];
6571
+ return step ? childRowLabel(step) : void 0;
6572
+ }
6573
+ if (steps.length === 1)
6574
+ return childRowLabel(steps[0]);
6575
+ if (steps.length > 1)
6576
+ return `${job.mode ?? "subagent"} run`;
6577
+ if (job.agents?.length === 1)
6578
+ return job.agents[0];
6579
+ if (job.agents?.length)
6580
+ return `${job.mode ?? "subagent"} run`;
6581
+ }
6582
+ function renderSubagentCall(rawArgs, theme, context, options) {
6583
+ let args = resolveSubagentRequestParams(rawArgs);
5764
6584
  if (args.action) {
5765
- let target = args.id || args.runId || "";
5766
- return new Text2(`${theme.fg("toolTitle", theme.bold("subagent "))}${args.action}${target ? ` ${theme.fg("accent", target)}` : ""}`, 0, 0);
6585
+ let resolvedTitle = context?.result?.details?.displayTitle || options?.resolveActionTitle?.(args), target = resolvedTitle || args.id || args.runId || "";
6586
+ return (args.action === "steer" || args.action === "resume") && args.message ? renderCommunicationCall("subagent", args, theme, context, { direction: "to", peer: resolvedTitle || "Subagent", kind: "steer", message: args.message }, resolvedTitle) : new Text3(`${theme.fg("toolTitle", theme.bold("subagent "))}${args.action}${target ? ` ${theme.fg("accent", target)}` : ""}`, 0, 0);
5767
6587
  }
5768
- let isParallel = (args.tasks?.length ?? 0) > 0, parallelCount = effectiveParallelTaskCount(args.tasks), asyncLabel = args.async === !0 && args.clarify !== !0 ? theme.fg("warning", " [async]") : "";
6588
+ let isParallel = (args.tasks?.length ?? 0) > 0, parallelCount = effectiveParallelTaskCount(args.tasks), asyncMark = subagentLaunchRunsAsync(args) ? `${theme.fg("warning", "async")} ` : "";
5769
6589
  if (args.chain?.length)
5770
- return new Text2(`${theme.fg("toolTitle", theme.bold("subagent "))}chain (${args.chain.length})${asyncLabel}`, 0, 0);
6590
+ return new Text3(`${theme.fg("toolTitle", theme.bold("subagent "))}${asyncMark}chain (${args.chain.length})`, 0, 0);
5771
6591
  if (isParallel)
5772
- return new Text2(`${theme.fg("toolTitle", theme.bold("subagent "))}parallel (${parallelCount})${asyncLabel}`, 0, 0);
5773
- let description = !context?.isPartial && !context?.expanded && !context?.isError ? theme.fg("accent", args.description || args.task || "?") : "";
5774
- return new Text2(`${theme.fg("toolTitle", theme.bold(description ? "subagent " : "subagent"))}${description}${asyncLabel}`, 0, 0);
6592
+ return new Text3(`${theme.fg("toolTitle", theme.bold("subagent "))}${asyncMark}parallel (${parallelCount})`, 0, 0);
6593
+ let description = !context?.result && !context?.isPartial && !context?.expanded && !context?.isError ? theme.fg("accent", args.description || args.task || "?") : "", title = theme.fg("toolTitle", theme.bold("subagent")), rest = [asyncMark.trim() ? theme.fg("warning", "async") : "", description].filter(Boolean).join(" ");
6594
+ return new Text3(rest ? `${title} ${rest}` : title, 0, 0);
6595
+ }
6596
+ function renderSubagentNotify(details, theme) {
6597
+ let status = typeof details?.status == "string" ? details.status : "", icon = status === "completed" ? theme.fg("success", "\u2713") : status === "failed" ? theme.fg("error", "\u2717") : theme.fg("warning", "\u25A0"), title = details?.agent || "child";
6598
+ return new Text3(`${icon} ${theme.bold(title)} ${theme.fg("dim", status)}`, 0, 0);
5775
6599
  }
5776
6600
  function ensureSubagentResultAnimation(context) {
5777
6601
  let state = context.state;
5778
6602
  state.subagentResultAnimationTimer || typeof context.invalidate == "function" && (state.frame === void 0 && (state.frame = 0), state.subagentResultAnimationTimer = setInterval(() => {
5779
- state.frame = ((state.frame ?? 0) + 1) % 10;
6603
+ state.frame = (state.frame ?? 0) + 1;
5780
6604
  try {
5781
6605
  let entries = state.animEntries;
5782
6606
  if (entries?.length && typeof context.requestRender == "function") {
@@ -5788,7 +6612,7 @@ function ensureSubagentResultAnimation(context) {
5788
6612
  context.invalidate();
5789
6613
  } catch {
5790
6614
  }
5791
- }, 80));
6615
+ }, SUBAGENT_PAINT_INTERVAL_MS));
5792
6616
  }
5793
6617
  function isSlashResultError(result2) {
5794
6618
  return result2.details?.results.some((entry) => entry.exitCode !== 0 && entry.progress?.status !== "running") || !1;
@@ -5798,14 +6622,14 @@ function isStaleExtensionContextError(error) {
5798
6622
  }
5799
6623
  function rebuildSlashResultContainer(container, result2, options, theme) {
5800
6624
  container.clear(), container.addChild(new Spacer2(1));
5801
- let boxTheme = isSlashResultRunning(result2) ? "toolPendingBg" : isSlashResultError(result2) ? "toolErrorBg" : "toolSuccessBg", box = new Box(1, 1, (text) => theme.bg(boxTheme, text));
6625
+ let boxTheme = isSlashResultRunning(result2) ? "toolPendingBg" : isSlashResultError(result2) ? "toolErrorBg" : "toolSuccessBg", box = new Box2(1, 1, (text) => theme.bg(boxTheme, text));
5802
6626
  box.addChild(renderSubagentResult(result2, options, theme)), container.addChild(box);
5803
6627
  }
5804
6628
  function createSlashResultComponent(details, options, theme) {
5805
- let container = new Container2(), lastVersion = -1;
6629
+ let container = new Container3(), lastVersion = -1;
5806
6630
  return container.render = (width) => {
5807
6631
  let snapshot = getSlashRenderableSnapshot(details);
5808
- return (snapshot.version !== lastVersion || isSlashResultRunning(snapshot.result)) && (lastVersion = snapshot.version, rebuildSlashResultContainer(container, snapshot.result, options, theme)), Container2.prototype.render.call(container, width);
6632
+ return (snapshot.version !== lastVersion || isSlashResultRunning(snapshot.result)) && (lastVersion = snapshot.version, rebuildSlashResultContainer(container, snapshot.result, options, theme)), Container3.prototype.render.call(container, width);
5809
6633
  }, container;
5810
6634
  }
5811
6635
  function registerSubagentExtension(pi) {
@@ -5818,11 +6642,12 @@ function registerSubagentExtension(pi) {
5818
6642
  } catch {
5819
6643
  }
5820
6644
  ensureAccessibleDir(RESULTS_DIR), ensureAccessibleDir(ASYNC_DIR), cleanupOldChainDirs();
5821
- let config = loadConfig(), waitToolConfig = resolveWaitToolConfig(config.waitTool), asyncByDefault = config.asyncByDefault === !0, tempArtifactsDir = getArtifactsDir(null);
6645
+ let config = normalizeAsyncLaunchConfig(loadConfig()), waitToolConfig = resolveWaitToolConfig(config.waitTool), tempArtifactsDir = getArtifactsDir(null);
5822
6646
  cleanupAllArtifactDirs(DEFAULT_ARTIFACT_CONFIG.cleanupDays);
5823
6647
  let state = {
5824
6648
  baseCwd: "",
5825
6649
  currentSessionId: null,
6650
+ sessionGeneration: 0,
5826
6651
  foregroundSubagentInFlight: 0,
5827
6652
  subagentSpawns: { sessionId: null, count: 0 },
5828
6653
  asyncJobs: /* @__PURE__ */ new Map(),
@@ -5844,15 +6669,19 @@ function registerSubagentExtension(pi) {
5844
6669
  }
5845
6670
  }, supervisorChannel = createNativeSupervisorChannel(pi, state), mainWatchdog = registerMainWatchdog(pi), { startResultWatcher, primeExistingResults, stopResultWatcher } = createResultWatcher(pi, state, RESULTS_DIR, 600 * 1e3);
5846
6671
  startResultWatcher(), primeExistingResults();
5847
- let generation = 0, executorPromise, pendingLaunches = /* @__PURE__ */ new Set(), runtimeCleanup = () => {
5848
- generation++, executorPromise = void 0, pendingLaunches.clear(), mainWatchdog.dispose(), stopResultWatcher(), scheduledRunManager.stop(), supervisorChannel.dispose(), clearPendingForegroundControlNotices(state), state.poller && (clearInterval(state.poller), state.poller = null);
6672
+ let generation = 0, executorPromise, pendingLaunches = /* @__PURE__ */ new Set(), pendingAsyncLaunches = /* @__PURE__ */ new Set(), unregisterCancellation, runtimeCleanup = () => {
6673
+ generation++, supervisorChannel.cancelOwnedQuestions("parent runtime replaced"), state.sessionGeneration = (state.sessionGeneration ?? 0) + 1, executorPromise = void 0, pendingLaunches.clear(), pendingAsyncLaunches.clear(), unregisterCancellation?.(), mainWatchdog.dispose(), stopResultWatcher(), scheduledRunManager.stop(), supervisorChannel.dispose(), clearPendingForegroundControlNotices(state), disposeSubagentWidget(), state.poller && (clearInterval(state.poller), state.poller = null);
5849
6674
  };
5850
6675
  globalStore[runtimeCleanupStoreKey] = runtimeCleanup;
5851
- let { ensurePoller, refreshWidget, handleStarted, handleComplete, resetJobs, restoreActiveJobs } = createAsyncJobTracker(pi, state, ASYNC_DIR, {
6676
+ let { ensurePoller, refreshWidget, handleStarted, handleComplete: trackComplete, resetJobs, restoreActiveJobs } = createAsyncJobTracker(pi, state, ASYNC_DIR, {
5852
6677
  widgetEnabled: config.asyncWidget !== !1
5853
- }), executorExecute, scheduledRunManager = createScheduledRunManager({
6678
+ }), handleComplete = (data) => {
6679
+ trackComplete(data);
6680
+ let result2 = data;
6681
+ typeof state.currentSessionId == "string" && result2.sessionId !== state.currentSessionId || typeof result2.id == "string" && result2.id.trim() && supervisorChannel.settleRunQuestions(result2.id, "async run settled");
6682
+ }, executorExecute, scheduledRunManager = createScheduledRunManager({
5854
6683
  config,
5855
- launch: (params, ctx, signal) => executorExecute ? executorExecute(randomUUID3(), params, signal, void 0, ctx) : Promise.resolve({
6684
+ launch: (params, ctx, signal) => executorExecute ? executorExecute(randomUUID4(), params, signal, void 0, ctx) : Promise.resolve({
5856
6685
  content: [{ type: "text", text: "Scheduled subagent launch is unavailable (executor not ready)." }],
5857
6686
  isError: !0,
5858
6687
  details: { mode: "management", results: [] }
@@ -5862,20 +6691,19 @@ function registerSubagentExtension(pi) {
5862
6691
  let resolveLaunchReady, launchReady = !1, launchReadyPromise = new Promise((resolve3) => {
5863
6692
  resolveLaunchReady = resolve3;
5864
6693
  }), markLaunchReady = () => {
5865
- launchReady || (launchReady = !0, pendingLaunches.delete(launchReadyPromise), resolveLaunchReady());
6694
+ launchReady || (launchReady = !0, pendingLaunches.delete(launchReadyPromise), pendingAsyncLaunches.delete(launchReadyPromise), resolveLaunchReady());
5866
6695
  };
5867
- pendingLaunches.add(launchReadyPromise);
6696
+ pendingLaunches.add(launchReadyPromise), isAsyncSubagentExecution(resolveSubagentRequestParams(params)) && pendingAsyncLaunches.add(launchReadyPromise);
5868
6697
  try {
5869
6698
  let currentGeneration = generation;
5870
6699
  if (signal?.throwIfAborted(), !executorPromise) {
5871
- let pending = import("./subagent-executor-EFLTO32A.js").then(({ createSubagentExecutor }) => {
6700
+ let pending = import("./subagent-executor-2BH76MMS.js").then(({ createSubagentExecutor }) => {
5872
6701
  if (generation !== currentGeneration)
5873
6702
  throw new Error("Subagent session changed before initialization");
5874
6703
  return createSubagentExecutor({
5875
6704
  pi,
5876
6705
  state,
5877
6706
  config,
5878
- asyncByDefault,
5879
6707
  waitToolEnabled: waitToolConfig.enabled,
5880
6708
  handleScheduledRunAction: (params2, ctx2) => scheduledRunManager.handleToolCall(params2, ctx2),
5881
6709
  watchdog: mainWatchdog,
@@ -5898,43 +6726,32 @@ function registerSubagentExtension(pi) {
5898
6726
  }
5899
6727
  }
5900
6728
  };
5901
- executorExecute = executor.execute, pi.registerMessageRenderer(SLASH_RESULT_TYPE, (message, options, theme) => {
6729
+ executorExecute = executor.execute, registerSupervisorRenderers(pi, state), pi.registerMessageRenderer(SLASH_RESULT_TYPE, (message, options, theme) => {
5902
6730
  let details = resolveSlashMessageDetails(message.details);
5903
6731
  if (details)
5904
6732
  return createSlashResultComponent(details, options, theme);
5905
6733
  }), pi.registerMessageRenderer(SLASH_TEXT_RESULT_TYPE, (message, _options, _theme) => {
5906
6734
  let content = typeof message.content == "string" ? message.content : message.content.filter((entry) => entry.type === "text").map((entry) => entry.text).join(`
5907
6735
  `);
5908
- return new Text2(content, 0, 0);
5909
- }), pi.registerMessageRenderer("subagent-notify", (message, options, theme) => {
6736
+ return new Text3(content, 0, 0);
6737
+ }), pi.registerMessageRenderer("subagent-notify", (message, _options, theme) => {
5910
6738
  let content = typeof message.content == "string" ? message.content : "", details = message.details ?? parseSubagentNotifyContent(content);
5911
- if (!details)
5912
- return new Text2(content, 0, 0);
5913
- let icon = details.status === "completed" ? theme.fg("success", "\u2713") : details.status === "paused" ? theme.fg("warning", "\u25A0") : theme.fg("error", "\u2717"), parts = [];
5914
- details.taskInfo && parts.push(details.taskInfo), details.durationMs !== void 0 && parts.push(formatDuration(details.durationMs));
5915
- let notifyLabel = details.taskInfo || details.agent || "child", text = `${icon} ${theme.bold(notifyLabel)} ${theme.fg("dim", details.status)}`;
5916
- parts.length > 0 && (text += ` ${theme.fg("dim", "\xB7")} ${parts.map((part) => theme.fg("dim", part)).join(` ${theme.fg("dim", "\xB7")} `)}`);
5917
- let trimmedPreview = details.resultPreview.trim(), previewLines = options.expanded ? trimmedPreview.split(`
5918
- `).filter((line) => line.trim()) : [trimmedPreview.split(`
5919
- `, 1)[0] ?? ""].filter((line) => line.trim());
5920
- for (let line of previewLines.length > 0 ? previewLines : ["(no output)"])
5921
- text += `
5922
- ${theme.fg("dim", `\u23BF ${line}`)}`;
5923
- if (!options.expanded && trimmedPreview.includes(`
5924
- `)) {
5925
- let expandKey = keyText("app.tools.expand");
5926
- text += `
5927
- ${theme.fg("dim", `${expandKey} full notification`)}`;
5928
- }
5929
- return details.sessionLabel && details.sessionValue && (text += `
5930
- ${theme.fg("muted", `${details.sessionLabel}: ${shortenPath(details.sessionValue)}`)}`), new Text2(text, 0, 0);
6739
+ return details ? renderSubagentNotify(details, theme) : new Text3(content, 0, 0);
5931
6740
  }), pi.registerMessageRenderer(SUBAGENT_STEERING_MESSAGE_TYPE, (message, _options, theme) => {
5932
6741
  let details = message.details;
5933
6742
  if (details)
5934
- return new Text2(theme.fg(details.state === "recovered" ? "warning" : "error", formatSteeringNotice(details)), 0, 0);
6743
+ return new Text3(theme.fg(details.state === "recovered" ? "warning" : "error", formatSteeringNotice(details)), 0, 0);
5935
6744
  }), pi.registerMessageRenderer(SUBAGENT_CONTROL_MESSAGE_TYPE, () => {
5936
6745
  });
5937
- let executeSubagentCollapsed = (id, params, signal, onUpdate, ctx) => (ctx.hasUI && ctx.ui.setToolsExpanded(!1), executor.execute(id, params, signal, onUpdate, ctx)), slashBridge = registerSlashSubagentBridge({
6746
+ let executeSubagentCollapsed = async (id, params, signal, onUpdate, ctx) => {
6747
+ ctx.hasUI && ctx.ui.setToolsExpanded(!1);
6748
+ let isCommunication = (params.action === "steer" || params.action === "resume") && typeof params.message == "string", displayTitle = isCommunication ? resolveSubagentActionDisplayTitle(params, state) : void 0, jobs = isCommunication ? matchingActionJobs(state, (params.id || params.runId || "").trim()) : [], targetNames = new Map(jobs.length === 1 ? jobs[0].steps?.map((step, index) => [step.index ?? index, childRowLabel(step)]) : []), result2 = await executor.execute(id, params, signal, onUpdate, ctx);
6749
+ if (displayTitle && result2.details && (result2.details.displayTitle = displayTitle), isCommunication && result2.details) {
6750
+ let targets = result2.details.steering?.targets.map((target) => targetNames.get(target.index) ?? `Subagent ${target.index + 1}`), peer = targets?.length ? targets.join(", ") : displayTitle || "Subagent";
6751
+ result2.details.communication = { direction: "to", peer, kind: "steer", message: params.message };
6752
+ }
6753
+ return result2;
6754
+ }, slashBridge = registerSlashSubagentBridge({
5938
6755
  events: pi.events,
5939
6756
  getContext: () => state.lastUiContext,
5940
6757
  execute: (id, params, signal, onUpdate, ctx) => executeSubagentCollapsed(id, params, signal, onUpdate, ctx)
@@ -5959,8 +6776,12 @@ function registerSubagentExtension(pi) {
5959
6776
  execute(id, params, signal, onUpdate, ctx) {
5960
6777
  return executeSubagentCollapsed(id, params, signal, onUpdate, ctx);
5961
6778
  },
5962
- renderCall: renderSubagentCall,
6779
+ renderCall: (args, theme, context) => renderSubagentCall(args, theme, context, {
6780
+ resolveActionTitle: (params) => resolveSubagentActionDisplayTitle(params, state)
6781
+ }),
5963
6782
  renderResult(result2, options, theme, context) {
6783
+ if (result2.details?.communication)
6784
+ return renderCommunicationResult(result2.content, result2.details, options.expanded, context.isError, theme);
5964
6785
  subagentResultIsRunning(result2) ? ensureSubagentResultAnimation(context) : clearLegacyResultAnimationTimer(context);
5965
6786
  let state2 = context.state, entries = [];
5966
6787
  state2.animEntries = entries, subagentAnimSink.current = entries;
@@ -5978,7 +6799,7 @@ function registerSubagentExtension(pi) {
5978
6799
  launches.length !== 0 && await awaitWithAbort(Promise.all(launches).then(() => {
5979
6800
  }), signal);
5980
6801
  }), pi.on("agent_end", async (_event, ctx) => {
5981
- ctx.hasUI || await drainOutstandingWork({ state, events: pi.events });
6802
+ ctx.hasUI || await drainOutstandingWork({ state, events: pi.events, hasPendingMessages: () => ctx.hasPendingMessages() });
5982
6803
  }), registerSlashCommands(pi, state);
5983
6804
  let eventUnsubscribeStoreKey = "__piSubagentEventUnsubscribes", controlNoticeSeenStoreKey = "__piSubagentVisibleControlNotices", previousEventUnsubscribes = globalStore[eventUnsubscribeStoreKey];
5984
6805
  if (Array.isArray(previousEventUnsubscribes)) {
@@ -6018,16 +6839,25 @@ function registerSubagentExtension(pi) {
6018
6839
  } catch {
6019
6840
  }
6020
6841
  }, resetSessionState = (ctx) => {
6021
- if (generation++, executorPromise = void 0, pendingLaunches.clear(), state.baseCwd = ctx.cwd, state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager), state.subagentSpawns = { sessionId: state.currentSessionId, count: 0 }, !process.env[SUBAGENT_CHILD_ENV]) {
6022
- let sessionId = ctx.sessionManager.getSessionId();
6023
- sessionId && (process.env[SUBAGENT_PARENT_SESSION_ENV] = sessionId);
6024
- }
6025
- state.lastUiContext = ctx, cleanupSessionArtifacts(ctx), clearPendingForegroundControlNotices(state), resetJobs(ctx), restoreActiveJobs(ctx), scheduledRunManager.bindSession(ctx), restoreSlashFinalSnapshots(ctx.sessionManager.getEntries()), primeExistingResults();
6842
+ if (generation++, supervisorChannel.cancelOwnedQuestions("parent session replaced"), state.sessionGeneration = (state.sessionGeneration ?? 0) + 1, executorPromise = void 0, pendingLaunches.clear(), pendingAsyncLaunches.clear(), unregisterCancellation?.(), state.baseCwd = ctx.cwd, state.currentSessionId = resolveCurrentSessionId(ctx.sessionManager), state.subagentSpawns = { sessionId: state.currentSessionId, count: 0 }, !process.env[SUBAGENT_CHILD_ENV]) {
6843
+ let sessionId2 = ctx.sessionManager.getSessionId();
6844
+ sessionId2 && (process.env[SUBAGENT_PARENT_SESSION_ENV] = sessionId2);
6845
+ }
6846
+ state.lastUiContext = ctx, cleanupSessionArtifacts(ctx), clearPendingForegroundControlNotices(state), resetJobs(ctx), restoreActiveJobs(ctx);
6847
+ let sessionId = state.currentSessionId, sessionGeneration = generation;
6848
+ sessionId && (unregisterCancellation = registerSubagentCancellation(sessionId, createSubagentCancellation({
6849
+ pendingLaunches: pendingAsyncLaunches,
6850
+ isCurrent: () => generation === sessionGeneration && state.currentSessionId === sessionId,
6851
+ getActiveRunIds: () => [...state.asyncJobs.values()].filter((job) => job.sessionId === sessionId && (job.status === "queued" || job.status === "running")).map((job) => job.asyncId),
6852
+ async stopRun(id) {
6853
+ return !(await executor.execute(randomUUID4(), { action: "stop", id }, new AbortController().signal, void 0, ctx)).isError;
6854
+ }
6855
+ }))), scheduledRunManager.bindSession(ctx), restoreSlashFinalSnapshots(ctx.sessionManager.getEntries()), primeExistingResults();
6026
6856
  };
6027
6857
  pi.on("session_start", (_event, ctx) => {
6028
6858
  resetSessionState(ctx), rpcBridge.emitReady(ctx), supervisorChannel.start();
6029
6859
  }), pi.on("session_shutdown", () => {
6030
- generation++, executorPromise = void 0, pendingLaunches.clear(), delete process.env[SUBAGENT_PARENT_SESSION_ENV];
6860
+ generation++, supervisorChannel.cancelOwnedQuestions("parent session shutdown"), state.sessionGeneration = (state.sessionGeneration ?? 0) + 1, executorPromise = void 0, pendingLaunches.clear(), pendingAsyncLaunches.clear(), unregisterCancellation?.(), delete process.env[SUBAGENT_PARENT_SESSION_ENV];
6031
6861
  for (let unsubscribe of eventUnsubscribes)
6032
6862
  try {
6033
6863
  unsubscribe();
@@ -6036,7 +6866,7 @@ function registerSubagentExtension(pi) {
6036
6866
  globalStore[eventUnsubscribeStoreKey] === eventUnsubscribes && delete globalStore[eventUnsubscribeStoreKey], stopResultWatcher(), scheduledRunManager.stop(), state.poller && clearInterval(state.poller), state.poller = null, clearPendingForegroundControlNotices(state);
6037
6867
  for (let timer of state.cleanupTimers.values())
6038
6868
  clearTimeout(timer);
6039
- state.cleanupTimers.clear(), state.asyncJobs.clear(), clearSlashSnapshots(), slashBridge.cancelAll(), slashBridge.dispose(), promptTemplateBridge.cancelAll(), promptTemplateBridge.dispose(), supervisorChannel.dispose(), globalStore[runtimeCleanupStoreKey] === runtimeCleanup && delete globalStore[runtimeCleanupStoreKey];
6869
+ state.cleanupTimers.clear(), state.asyncJobs.clear(), clearSlashSnapshots(), slashBridge.cancelAll(), slashBridge.dispose(), promptTemplateBridge.cancelAll(), promptTemplateBridge.dispose(), supervisorChannel.dispose(), globalStore[runtimeCleanupStoreKey] === runtimeCleanup && delete globalStore[runtimeCleanupStoreKey], disposeSubagentWidget();
6040
6870
  try {
6041
6871
  state.lastUiContext?.hasUI && state.lastUiContext.ui.setWidget(WIDGET_KEY, void 0);
6042
6872
  } catch (error) {