ceulen 0.5.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (367) hide show
  1. package/CHANGELOG.md +365 -12
  2. package/README.md +87 -91
  3. package/extensions/lib/advisor-marker.ts +33 -0
  4. package/extensions/lib/panel.ts +25 -2
  5. package/extensions/lib/rate.ts +24 -0
  6. package/extensions/lib/registry.test.ts +67 -0
  7. package/extensions/lib/registry.ts +104 -8
  8. package/extensions/lib/tools.ts +47 -0
  9. package/extensions/lib/usage-store.ts +33 -0
  10. package/extensions/modules/advisor/commands/advisor.ts +244 -0
  11. package/extensions/modules/advisor/configPanel.ts +194 -0
  12. package/extensions/modules/advisor/index.ts +235 -0
  13. package/extensions/modules/advisor/lib/config.ts +248 -0
  14. package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
  15. package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
  16. package/extensions/modules/advisor/lib/model-picker.ts +47 -0
  17. package/extensions/modules/advisor/lib/watcher.ts +288 -0
  18. package/extensions/modules/advisor/test/compliance.test.ts +125 -0
  19. package/extensions/modules/advisor/test/config.test.ts +202 -0
  20. package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
  21. package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
  22. package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
  23. package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
  24. package/extensions/modules/advisor/test/module.test.ts +649 -0
  25. package/extensions/modules/advisor/test/watcher.test.ts +478 -0
  26. package/extensions/modules/classifier/configPanel.ts +104 -0
  27. package/extensions/modules/classifier/index.ts +297 -0
  28. package/extensions/modules/classifier/lib/settings.ts +95 -0
  29. package/extensions/modules/classifier/test/classifier.test.ts +475 -0
  30. package/extensions/modules/composer/index.ts +152 -3
  31. package/extensions/modules/composer/lib/footer.ts +119 -0
  32. package/extensions/modules/composer/lib/shapes.ts +265 -26
  33. package/extensions/modules/composer/test/editor.test.ts +1 -1
  34. package/extensions/modules/composer/test/footer.test.ts +96 -0
  35. package/extensions/modules/composer/test/module.test.ts +113 -11
  36. package/extensions/modules/composer/test/screen.test.ts +29 -1
  37. package/extensions/modules/composer/test/shapes.test.ts +224 -8
  38. package/extensions/modules/config/defaultTools.ts +96 -0
  39. package/extensions/modules/config/index.ts +147 -7
  40. package/extensions/modules/config/piSettings.ts +254 -69
  41. package/extensions/modules/config/test/defaultTools.test.ts +122 -0
  42. package/extensions/modules/config/test/menu.test.ts +64 -0
  43. package/extensions/modules/config/test/panel.test.ts +38 -23
  44. package/extensions/modules/config/test/piSettings.test.ts +130 -3
  45. package/extensions/modules/config/test/renderTools.test.ts +71 -0
  46. package/extensions/modules/config/test/tools.test.ts +146 -0
  47. package/extensions/modules/fff/index.ts +2094 -0
  48. package/extensions/modules/fff/lib/query.ts +129 -0
  49. package/extensions/modules/fff/test/index.test.ts +607 -0
  50. package/extensions/modules/fff/test/query.test.ts +71 -0
  51. package/extensions/modules/munin/configPanel.ts +108 -0
  52. package/extensions/modules/munin/index.ts +641 -0
  53. package/extensions/modules/munin/lib/helpers.ts +471 -0
  54. package/extensions/modules/munin/lib/retry.ts +20 -0
  55. package/extensions/modules/munin/lib/sdk.ts +218 -0
  56. package/extensions/modules/munin/test/config.test.ts +168 -0
  57. package/extensions/modules/munin/test/configPanel.test.ts +186 -0
  58. package/extensions/modules/munin/test/extension.test.ts +224 -0
  59. package/extensions/modules/munin/test/helpers.test.ts +523 -0
  60. package/extensions/modules/munin/test/retry.test.ts +145 -0
  61. package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
  62. package/extensions/modules/plan/configPanel.ts +152 -0
  63. package/extensions/modules/plan/index.ts +917 -0
  64. package/extensions/modules/plan/lib/plan-tools.ts +72 -0
  65. package/extensions/modules/plan/lib/prompt.ts +65 -0
  66. package/extensions/modules/plan/lib/settings.ts +166 -0
  67. package/extensions/modules/plan/lib/shell-gate.ts +200 -0
  68. package/extensions/modules/plan/test/configPanel.test.ts +96 -0
  69. package/extensions/modules/plan/test/harness.ts +133 -0
  70. package/extensions/modules/plan/test/module.test.ts +305 -0
  71. package/extensions/modules/plan/test/settings.test.ts +114 -0
  72. package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
  73. package/extensions/modules/ponytail/index.ts +23 -73
  74. package/extensions/modules/ponytail/lib/config.ts +1 -6
  75. package/extensions/modules/ponytail/test/extension.test.ts +1 -85
  76. package/extensions/modules/repair/configPanel.ts +96 -0
  77. package/extensions/modules/repair/index.ts +414 -0
  78. package/extensions/modules/repair/lib/auto-bg.ts +333 -0
  79. package/extensions/modules/repair/lib/edit-repair.ts +155 -0
  80. package/extensions/modules/repair/lib/editor.ts +251 -0
  81. package/extensions/modules/repair/lib/guards.ts +34 -0
  82. package/extensions/modules/repair/lib/input-repair.ts +324 -0
  83. package/extensions/modules/repair/lib/patch.ts +481 -0
  84. package/extensions/modules/repair/lib/settings.ts +114 -0
  85. package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
  86. package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
  87. package/extensions/modules/repair/test/editor.test.ts +141 -0
  88. package/extensions/modules/repair/test/guards.test.ts +64 -0
  89. package/extensions/modules/repair/test/input-repair.test.ts +231 -0
  90. package/extensions/modules/repair/test/patch.test.ts +563 -0
  91. package/extensions/modules/repair/test/settings.test.ts +167 -0
  92. package/extensions/modules/repair/test/wrapper.test.ts +210 -0
  93. package/extensions/modules/router/commands/commands.ts +4 -0
  94. package/extensions/modules/router/configPanel.ts +24 -10
  95. package/extensions/modules/router/lib/client.ts +63 -0
  96. package/extensions/modules/router/lib/provider.ts +34 -13
  97. package/extensions/modules/router/lib/systemone.ts +152 -0
  98. package/extensions/modules/router/test/unit.test.ts +260 -0
  99. package/extensions/modules/rtk/findFallback.js +68 -0
  100. package/extensions/modules/rtk/index.ts +248 -0
  101. package/extensions/modules/rtk/safe-rewrite.js +74 -0
  102. package/extensions/modules/rtk/test/findFallback.test.js +66 -0
  103. package/extensions/modules/rtk/test/index.test.js +131 -0
  104. package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
  105. package/extensions/modules/rtk/version-gate.js +34 -0
  106. package/extensions/modules/rules/index.ts +120 -0
  107. package/extensions/modules/rules/lib/rules.ts +348 -0
  108. package/extensions/modules/rules/test/lib.test.ts +263 -0
  109. package/extensions/modules/rules/test/module.test.ts +222 -0
  110. package/extensions/modules/serena/index.ts +629 -0
  111. package/extensions/modules/serena/lib/detect.ts +73 -0
  112. package/extensions/modules/serena/lib/env.ts +76 -0
  113. package/extensions/modules/serena/lib/guidance.ts +26 -0
  114. package/extensions/modules/serena/lib/normalize.ts +27 -0
  115. package/extensions/modules/serena/lib/symbol-key.ts +20 -0
  116. package/extensions/modules/serena/lib/truncate.ts +20 -0
  117. package/extensions/modules/serena/test/env.test.ts +122 -0
  118. package/extensions/modules/serena/test/index.test.ts +347 -0
  119. package/extensions/modules/serena/test/worker.test.ts +562 -0
  120. package/extensions/modules/serena/worker.ts +858 -0
  121. package/extensions/modules/steering/configPanel.ts +122 -0
  122. package/extensions/modules/steering/index.ts +616 -0
  123. package/extensions/modules/steering/lib/anchor.ts +175 -0
  124. package/extensions/modules/steering/lib/errors.ts +253 -0
  125. package/extensions/modules/steering/lib/family.ts +33 -0
  126. package/extensions/modules/steering/lib/guidance.ts +172 -0
  127. package/extensions/modules/steering/lib/history.ts +170 -0
  128. package/extensions/modules/steering/lib/settings.ts +127 -0
  129. package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
  130. package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
  131. package/extensions/modules/steering/test/anchor.test.ts +160 -0
  132. package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
  133. package/extensions/modules/steering/test/errors.test.ts +309 -0
  134. package/extensions/modules/steering/test/family.test.ts +43 -0
  135. package/extensions/modules/steering/test/guidance.test.ts +357 -0
  136. package/extensions/modules/steering/test/harness.ts +93 -0
  137. package/extensions/modules/steering/test/history.test.ts +118 -0
  138. package/extensions/modules/steering/test/settings.test.ts +182 -0
  139. package/extensions/modules/steering/test/status.test.ts +71 -0
  140. package/extensions/modules/steering/test/toolCall.test.ts +99 -0
  141. package/extensions/modules/subagent/agents/planner.md +14 -0
  142. package/extensions/modules/subagent/agents/reviewer.md +42 -0
  143. package/extensions/modules/subagent/agents/scout.md +47 -0
  144. package/extensions/modules/subagent/agents/tester.md +12 -0
  145. package/extensions/modules/subagent/agents/worker.md +18 -0
  146. package/extensions/modules/subagent/configPanel.ts +219 -0
  147. package/extensions/modules/subagent/index.ts +2464 -0
  148. package/extensions/modules/subagent/lib/agents.ts +408 -0
  149. package/extensions/modules/subagent/lib/background.ts +383 -0
  150. package/extensions/modules/subagent/lib/herdr.ts +1019 -0
  151. package/extensions/modules/subagent/lib/history.ts +126 -0
  152. package/extensions/modules/subagent/lib/model.ts +156 -0
  153. package/extensions/modules/subagent/lib/render.ts +335 -0
  154. package/extensions/modules/subagent/lib/result.ts +110 -0
  155. package/extensions/modules/subagent/lib/roles.ts +296 -0
  156. package/extensions/modules/subagent/lib/routing.ts +228 -0
  157. package/extensions/modules/subagent/lib/runner.ts +559 -0
  158. package/extensions/modules/subagent/lib/schema.ts +21 -0
  159. package/extensions/modules/subagent/lib/security.ts +763 -0
  160. package/extensions/modules/subagent/lib/settings.ts +159 -0
  161. package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
  162. package/extensions/modules/subagent/lib/threads.ts +135 -0
  163. package/extensions/modules/subagent/lib/types.ts +18 -0
  164. package/extensions/modules/subagent/lib/widget.ts +475 -0
  165. package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
  166. package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
  167. package/extensions/modules/subagent/test/routing.test.ts +524 -0
  168. package/extensions/modules/subagent/test/widget.test.ts +208 -0
  169. package/extensions/modules/todo/index.ts +478 -0
  170. package/extensions/modules/todo/test/todo.test.ts +252 -0
  171. package/extensions/modules/usage/index.ts +70 -16
  172. package/extensions/modules/usage/test/genrate.test.ts +70 -0
  173. package/extensions/modules/usage/test/parsers.test.ts +13 -0
  174. package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
  175. package/extensions/modules/ux/UPSTREAM +24 -0
  176. package/extensions/modules/ux/index.ts +393 -0
  177. package/extensions/modules/ux/lib/audit.ts +562 -0
  178. package/extensions/modules/ux/lib/config.ts +136 -0
  179. package/extensions/modules/ux/lib/instructions.ts +77 -0
  180. package/extensions/modules/ux/test/audit.test.ts +756 -0
  181. package/extensions/modules/ux/test/extension.test.ts +394 -0
  182. package/extensions/modules/ux/test/instructions.test.ts +19 -0
  183. package/extensions/modules/web/configPanel.ts +218 -0
  184. package/extensions/modules/web/index.ts +978 -0
  185. package/extensions/modules/web/lib/agy.ts +209 -0
  186. package/extensions/modules/web/lib/brave.ts +42 -0
  187. package/extensions/modules/web/lib/cdp.ts +686 -0
  188. package/extensions/modules/web/lib/chatapi.ts +101 -0
  189. package/extensions/modules/web/lib/chatgpt.ts +796 -0
  190. package/extensions/modules/web/lib/chrome.ts +328 -0
  191. package/extensions/modules/web/lib/config.ts +136 -0
  192. package/extensions/modules/web/lib/content.ts +99 -0
  193. package/extensions/modules/web/lib/crawl4ai.ts +172 -0
  194. package/extensions/modules/web/lib/extract.ts +235 -0
  195. package/extensions/modules/web/lib/firecrawl.ts +56 -0
  196. package/extensions/modules/web/lib/format.ts +197 -0
  197. package/extensions/modules/web/lib/gemini-auth.ts +286 -0
  198. package/extensions/modules/web/lib/gemini-dr.ts +338 -0
  199. package/extensions/modules/web/lib/gemini.ts +551 -0
  200. package/extensions/modules/web/lib/imageapi.ts +559 -0
  201. package/extensions/modules/web/lib/retry.ts +71 -0
  202. package/extensions/modules/web/lib/search.ts +237 -0
  203. package/extensions/modules/web/lib/searxng.ts +69 -0
  204. package/extensions/modules/web/lib/settings.ts +157 -0
  205. package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
  206. package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
  207. package/extensions/modules/web/test/agy.test.ts +383 -0
  208. package/extensions/modules/web/test/cdp.test.ts +717 -0
  209. package/extensions/modules/web/test/chat.test.ts +171 -0
  210. package/extensions/modules/web/test/chatgpt.test.ts +633 -0
  211. package/extensions/modules/web/test/chrome.test.ts +282 -0
  212. package/extensions/modules/web/test/config.test.ts +218 -0
  213. package/extensions/modules/web/test/configPanel.test.ts +198 -0
  214. package/extensions/modules/web/test/crawl.test.ts +134 -0
  215. package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
  216. package/extensions/modules/web/test/extension.test.ts +118 -0
  217. package/extensions/modules/web/test/extract.test.ts +436 -0
  218. package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
  219. package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
  220. package/extensions/modules/web/test/fixtures/interaction.html +31 -0
  221. package/extensions/modules/web/test/format.test.ts +230 -0
  222. package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
  223. package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
  224. package/extensions/modules/web/test/gemini.test.ts +472 -0
  225. package/extensions/modules/web/test/hook.test.ts +101 -0
  226. package/extensions/modules/web/test/image.test.ts +1089 -0
  227. package/extensions/modules/web/test/retry.test.ts +119 -0
  228. package/extensions/modules/web/test/screenshot.test.ts +109 -0
  229. package/extensions/modules/web/test/search.test.ts +210 -0
  230. package/extensions/modules/web/test/settings.test.ts +165 -0
  231. package/extensions/modules/web/test/skill.test.ts +72 -0
  232. package/extensions/modules/web/types.d.ts +3 -0
  233. package/extensions/modules/web/vendor/package.json +1 -0
  234. package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
  235. package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
  236. package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
  237. package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
  238. package/extensions/modules/web/vendor/readability/index.js +9 -0
  239. package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
  240. package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
  241. package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
  242. package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
  243. package/extensions/modules/zai/configPanel.ts +154 -0
  244. package/extensions/modules/zai/index.ts +186 -0
  245. package/extensions/modules/zai/lib/anthropic.ts +159 -0
  246. package/extensions/modules/zai/lib/settings.ts +198 -0
  247. package/extensions/modules/zai/lib/signing.ts +721 -0
  248. package/extensions/modules/zai/lib/throttle.ts +198 -0
  249. package/extensions/modules/zai/test/anthropic.test.ts +132 -0
  250. package/extensions/modules/zai/test/configPanel.test.ts +230 -0
  251. package/extensions/modules/zai/test/extension.test.ts +249 -0
  252. package/extensions/modules/zai/test/settings.test.ts +183 -0
  253. package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
  254. package/extensions/modules/zai/test/signing.test.ts +364 -0
  255. package/extensions/modules/zai/test/throttle.test.ts +329 -0
  256. package/package.json +19 -4
  257. package/scripts/validate-themes.mjs +75 -0
  258. package/skills/munin/SKILL.md +117 -0
  259. package/skills/ux-capture/SKILL.md +202 -0
  260. package/skills/ux-design/SKILL.md +279 -0
  261. package/skills/ux-presets/SKILL.md +484 -0
  262. package/skills/ux-routing/SKILL.md +46 -0
  263. package/skills/web/SKILL.md +153 -0
  264. package/themes/alabaster.json +93 -0
  265. package/themes/amethyst.json +96 -0
  266. package/themes/anthracite.json +93 -0
  267. package/themes/basalt.json +91 -0
  268. package/themes/birch.json +95 -0
  269. package/themes/catppuccin-mocha.json +91 -0
  270. package/themes/dark-abyss.json +91 -0
  271. package/themes/dark-arctic.json +104 -0
  272. package/themes/dark-aurora.json +95 -0
  273. package/themes/dark-catppuccin.json +107 -0
  274. package/themes/dark-cavern.json +91 -0
  275. package/themes/dark-celestial.json +106 -0
  276. package/themes/dark-copper.json +95 -0
  277. package/themes/dark-cosmos.json +90 -0
  278. package/themes/dark-cyberpunk.json +102 -0
  279. package/themes/dark-dracula.json +98 -0
  280. package/themes/dark-eclipse.json +91 -0
  281. package/themes/dark-ember.json +95 -0
  282. package/themes/dark-equinox.json +90 -0
  283. package/themes/dark-forest.json +96 -0
  284. package/themes/dark-github.json +105 -0
  285. package/themes/dark-gruvbox.json +112 -0
  286. package/themes/dark-lavender.json +95 -0
  287. package/themes/dark-lunar.json +89 -0
  288. package/themes/dark-midnight.json +95 -0
  289. package/themes/dark-monochrome.json +94 -0
  290. package/themes/dark-monokai.json +98 -0
  291. package/themes/dark-nebula.json +90 -0
  292. package/themes/dark-neon-noir.json +100 -0
  293. package/themes/dark-nord.json +98 -0
  294. package/themes/dark-ocean.json +101 -0
  295. package/themes/dark-one.json +100 -0
  296. package/themes/dark-poimandres.json +115 -0
  297. package/themes/dark-rainforest.json +91 -0
  298. package/themes/dark-reef.json +91 -0
  299. package/themes/dark-retro.json +92 -0
  300. package/themes/dark-rose-pine.json +96 -0
  301. package/themes/dark-sakura.json +95 -0
  302. package/themes/dark-slate.json +95 -0
  303. package/themes/dark-solarized.json +97 -0
  304. package/themes/dark-solstice.json +90 -0
  305. package/themes/dark-starfall.json +91 -0
  306. package/themes/dark-sunset.json +99 -0
  307. package/themes/dark-swamp.json +90 -0
  308. package/themes/dark-synthwave.json +103 -0
  309. package/themes/dark-taiga.json +91 -0
  310. package/themes/dark-terminal.json +95 -0
  311. package/themes/dark-tokyo-night.json +101 -0
  312. package/themes/dark-tundra.json +91 -0
  313. package/themes/dark-twilight.json +91 -0
  314. package/themes/dark-volcanic.json +91 -0
  315. package/themes/dark.json +80 -0
  316. package/themes/graphite.json +92 -0
  317. package/themes/light-arctic.json +107 -0
  318. package/themes/light-aurora-day.json +91 -0
  319. package/themes/light-canyon.json +91 -0
  320. package/themes/light-catppuccin.json +106 -0
  321. package/themes/light-cirrus.json +90 -0
  322. package/themes/light-coral.json +95 -0
  323. package/themes/light-cyberpunk.json +96 -0
  324. package/themes/light-dawn.json +90 -0
  325. package/themes/light-dunes.json +91 -0
  326. package/themes/light-eucalyptus.json +95 -0
  327. package/themes/light-forest.json +100 -0
  328. package/themes/light-frost.json +95 -0
  329. package/themes/light-github.json +115 -0
  330. package/themes/light-glacier.json +91 -0
  331. package/themes/light-gruvbox.json +108 -0
  332. package/themes/light-haze.json +90 -0
  333. package/themes/light-honeycomb.json +95 -0
  334. package/themes/light-lagoon.json +91 -0
  335. package/themes/light-lavender.json +95 -0
  336. package/themes/light-meadow.json +91 -0
  337. package/themes/light-mint.json +95 -0
  338. package/themes/light-monochrome.json +101 -0
  339. package/themes/light-ocean.json +99 -0
  340. package/themes/light-one.json +99 -0
  341. package/themes/light-opal.json +91 -0
  342. package/themes/light-orchard.json +91 -0
  343. package/themes/light-paper.json +95 -0
  344. package/themes/light-poimandres.json +115 -0
  345. package/themes/light-prism.json +90 -0
  346. package/themes/light-retro.json +98 -0
  347. package/themes/light-sand.json +95 -0
  348. package/themes/light-savanna.json +91 -0
  349. package/themes/light-solarized.json +102 -0
  350. package/themes/light-soleil.json +90 -0
  351. package/themes/light-sunset.json +99 -0
  352. package/themes/light-synthwave.json +98 -0
  353. package/themes/light-tokyo-night.json +111 -0
  354. package/themes/light-wetland.json +91 -0
  355. package/themes/light-zenith.json +89 -0
  356. package/themes/light.json +80 -0
  357. package/themes/limestone.json +94 -0
  358. package/themes/mahogany.json +97 -0
  359. package/themes/marble.json +93 -0
  360. package/themes/mirage.json +79 -0
  361. package/themes/obsidian.json +91 -0
  362. package/themes/onyx.json +91 -0
  363. package/themes/pearl.json +93 -0
  364. package/themes/porcelain.json +91 -0
  365. package/themes/quartz.json +96 -0
  366. package/themes/sandstone.json +95 -0
  367. package/themes/titanium.json +90 -0
@@ -0,0 +1,2464 @@
1
+ // ponytail: ported from @bacnh85/pi-subagent 0.23.2 (extensions/index.ts).
2
+ // ceulen deltas: ceulen- customTypes, no auto-review/service/roles-panel (dropped),
3
+ // classifier routing hook + wait op + settings-driven timeouts (lib/routing.ts, lib/settings.ts).
4
+ /**
5
+ * pi-subagent — Minimal-overhead sub-agent extension for pi.
6
+ *
7
+ * Provides a `subagent` tool that delegates tasks to specialized agents
8
+ * running in isolated in-process SDK sessions. Supports three modes:
9
+ *
10
+ * - Single: { agent: "scout", task: "find auth code" }
11
+ * - Parallel: { tasks: [{ agent: "scout", task: "..." }, ...] }
12
+ * - Chain: { chain: [{ agent: "scout", task: "..." }, ...] }
13
+ *
14
+ * Compared to process-spawning, this saves ~4-11K tokens per sub-agent
15
+ * by using the pi SDK directly with a minimal system prompt, no AGENTS.md,
16
+ * no extensions, no skills, no thinking, and no compaction.
17
+ */
18
+
19
+ import * as path from "node:path";
20
+ import * as fsPromises from "node:fs/promises";
21
+ import { Container, Markdown, SelectList, Spacer, Text } from "@earendil-works/pi-tui";
22
+ import { Type } from "typebox";
23
+ import {
24
+ CONFIG_DIR_NAME,
25
+ DynamicBorder,
26
+ type AgentToolUpdateCallback,
27
+ type ExtensionAPI,
28
+ type ExtensionContext,
29
+ getAgentDir,
30
+ getMarkdownTheme,
31
+ type ThemeColor,
32
+ } from "@earendil-works/pi-coding-agent";
33
+ import { StringEnum } from "./lib/schema.ts";
34
+
35
+ import { type AgentColor, type AgentConfig, type AgentScope, discoverAgents, formatAgentList, getModelCandidates, invalidateAgentCache } from "./lib/agents.ts";
36
+ import {
37
+ type SubAgentProgress,
38
+ type SubAgentResult,
39
+ formatPatchBlock,
40
+ getFinalOutput,
41
+ getResultOutput,
42
+ isFailedResult,
43
+ mapWithConcurrencyLimit,
44
+ runSubAgent,
45
+ startHeartbeat,
46
+ } from "./lib/runner.ts";
47
+ import {
48
+ flushWarnings,
49
+ isRetryableModelResult,
50
+ resolveChildTimeouts,
51
+ resolveSafeCwd,
52
+ validateAgentTools,
53
+ needsExtensions,
54
+ truncateParallelOutput,
55
+ validateExecutionRequest,
56
+ READ_ONLY_TOOLS,
57
+ MAX_CONCURRENCY,
58
+ MAX_PARALLEL_TASKS,
59
+ MAX_CHAIN_LENGTH,
60
+ MAX_INSTRUCTIONS_LENGTH,
61
+ } from "./lib/security.ts";
62
+ import {
63
+ aggregateUsage,
64
+ formatUsageStats,
65
+ renderSingleResult,
66
+ } from "./lib/render.ts";
67
+ import { type SubagentThread, threadStore } from "./lib/threads.ts";
68
+ import { resolveModel, runWithModelFallback, type ResolvedModel } from "./lib/model.ts";
69
+ import { DEFAULT_ROLES, describeAgentModels, effectiveAgentThinking, expandModelCandidates, readSubagentRoles, readSubagentRolesGlobal, resolveAgentModelChain, THINKING_LEVELS, type ExpandedCandidates, type RolesConfig, type SubagentThinkingLevel } from "./lib/roles.ts";
70
+ import { classifyTask, type RoutingVerdict } from "./lib/routing.ts";
71
+ import { readSubagentSettings } from "./lib/settings.ts";
72
+ import { setSubagentBridge } from "./configPanel.ts";
73
+ import { ThreadViewer, type ThreadViewerCallbacks } from "./lib/thread-viewer.ts";
74
+ import { createTaskWidgetController, renderLiveThreadLine, renderWaitTree, type TaskWidgetController } from "./lib/widget.ts";
75
+ import { startBackgroundTask,
76
+ backgroundHerdrHint,
77
+ cancelBackgroundTask,
78
+ getBackgroundTask,
79
+ getAllBackgroundTasks,
80
+ snapshotTask,
81
+ clearBackgroundTasks,
82
+ } from "./lib/background.ts";
83
+ import { parseStructuredResult } from "./lib/result.ts";
84
+ import { appendHistory, readHistory, markInterruptedOnRestart, trimHistory, getHistoryPath } from "./lib/history.ts";
85
+ import { herdrCli } from './lib/herdr.ts';
86
+ /** Keep-alive cadence for herdr delegations (test seam: shorten to assert). */
87
+ export const herdrHeartbeat = { intervalMs: 30_000 };
88
+ import {
89
+ cancelAgent,
90
+ canCloseHerdrTab,
91
+ collectResult,
92
+ executeHerdrTask,
93
+ forgetHerdrAgent,
94
+ forgetHerdrTab,
95
+ getAgentInfo,
96
+ herdrDisabled,
97
+ getHerdrRegistry,
98
+ herdrEnvDetected,
99
+ herdrTabCloseBlockers,
100
+ isDelegatedHerdrAgent,
101
+ listHerdrAgents,
102
+ HERDR_TASK_BUDGET,
103
+ MAX_HERDR_TASK_BYTES,
104
+ MAX_REPORT_BYTES,
105
+ prepareHerdrTask,
106
+ promptAndWait,
107
+ resolveEffectiveRunner,
108
+ truncateHerdrTask,
109
+ wrapTaskPrompt,
110
+ wouldHerdrDelegate,
111
+ type HerdrHandle,
112
+ type PromptOutcome,
113
+ } from "./lib/herdr.ts";
114
+
115
+ // ---------------------------------------------------------------------------
116
+ // Constants
117
+ // ---------------------------------------------------------------------------
118
+
119
+ // ---------------------------------------------------------------------------
120
+ // Helpers
121
+ // ---------------------------------------------------------------------------
122
+
123
+ /** Namespace for trusted configuration loaded from pi settings, never from tool params. */
124
+ function getTrustedConfig(ctx: ExtensionContext): { allowUnconfirmedProjectAgents: boolean; allowExternalCwd: boolean } {
125
+ // Use pi's settings infrastructure if available; fall back to env vars for testing.
126
+ // The model cannot influence these values.
127
+ const settings = (ctx as any).settings ?? {};
128
+ return {
129
+ allowUnconfirmedProjectAgents:
130
+ (settings as Record<string, unknown>).allowUnconfirmedProjectAgents === true ||
131
+ process.env.PI_SUBAGENT_ALLOW_UNCONFIRMED_PROJECT_AGENTS === "true",
132
+ allowExternalCwd:
133
+ (settings as Record<string, unknown>).allowExternalCwd === true ||
134
+ process.env.PI_SUBAGENT_ALLOW_EXTERNAL_CWD === "true",
135
+ };
136
+ }
137
+
138
+ /** Session-scoped approvals for project-local agents ("Trust for this session"). */
139
+ const trustedProjectAgentDirs = new Set<string>();
140
+
141
+
142
+ // ---------------------------------------------------------------------------
143
+ // Tool parameter schema
144
+ // ---------------------------------------------------------------------------
145
+
146
+ const TaskItem = Type.Object({
147
+ agent: Type.String({ description: "Name of the agent to invoke" }),
148
+ task: Type.String({ description: "Task to delegate to the agent" }),
149
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent" })),
150
+ solutionSpace: Type.Optional(Type.String({ description: "How open-ended this task's problem is — feeds model-tier/thinking routing." })),
151
+ timeout: Type.Optional(Type.Number({ description: "Inactivity timeout in ms; aborts on no activity within timeout. Default: 3 min (PI_SUBAGENT_INACTIVITY_TIMEOUT_MINS). The agent always has a lifetime cap: default 20 min or (PI_SUBAGENT_HARD_TIMEOUT_MINS)." })),
152
+ merge: Type.Optional(StringEnum(["3way"] as const, { description: "With a worktree-sandboxed agent, apply its diff to the parent checkout via git apply --3way after it completes. Conflicts are reported, not resolved. Default: patch returned only." })),
153
+ });
154
+
155
+ const ChainItem = Type.Object({
156
+ agent: Type.String({ description: "Name of the agent to invoke" }),
157
+ task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }),
158
+ cwd: Type.Optional(Type.String({ description: "Working directory for the agent" })),
159
+ timeout: Type.Optional(Type.Number({ description: "Inactivity timeout in ms; aborts on no activity within timeout. Default: 3 min (PI_SUBAGENT_INACTIVITY_TIMEOUT_MINS). The agent always has a lifetime cap: default 20 min or (PI_SUBAGENT_HARD_TIMEOUT_MINS)." })),
160
+ merge: Type.Optional(StringEnum(["3way"] as const, { description: "With a worktree-sandboxed agent, apply its diff to the parent checkout via git apply --3way after the step completes. Conflicts are reported, not resolved." })),
161
+ });
162
+
163
+ const AgentScopeSchema = StringEnum(["user", "project", "both"] as const, {
164
+ description:
165
+ 'Which agent directories to use. Default: "user". Use "both" to include project-local agents.',
166
+ default: "user",
167
+ });
168
+
169
+ const SubagentParams = Type.Object({
170
+ operation: Type.Optional(
171
+ Type.Union([Type.Literal("status"), Type.Literal("cancel"), Type.Literal("wait")], {
172
+ description: 'Task control: inspect ("status"), cancel ("cancel"), or block on ("wait") an existing task by taskId, without starting a new agent. wait resolves early when the task settles; otherwise it returns a liveness snapshot after timeoutMs. Omit for normal start/resume.',
173
+ }),
174
+ ),
175
+ taskId: Type.Optional(
176
+ Type.String({ description: "Existing background task id, for operation: status/cancel/wait" }),
177
+ ),
178
+ waitTimeoutMs: Type.Optional(
179
+ Type.Number({ description: 'operation "wait": max ms to block (default 60000, max 600000). Returns early when the task settles.' }),
180
+ ),
181
+ background: Type.Optional(
182
+ Type.Boolean({
183
+ description: "Run async (single mode only). You will be notified on completion — DO NOT poll or sleep. Default: false.",
184
+ default: false,
185
+ }),
186
+ ),
187
+ agent: Type.Optional(Type.String({ description: "Name of the agent to invoke (single mode)" })),
188
+ task: Type.Optional(Type.String({ description: "Task to delegate (single mode)" })),
189
+ tasks: Type.Optional(
190
+ Type.Array(TaskItem, { description: "Array of {agent, task} for parallel execution" }),
191
+ ),
192
+ chain: Type.Optional(
193
+ Type.Array(ChainItem, {
194
+ description: "Array of {agent, task} for sequential execution with {previous}",
195
+ }),
196
+ ),
197
+ agentScope: Type.Optional(AgentScopeSchema),
198
+ // Security: confirmProjectAgents is NOT exposed as a model-controllable parameter.
199
+ // Project-agent confirmation is enforced via trusted configuration.
200
+ // See Security model section in README.
201
+ cwd: Type.Optional(Type.String({ description: "Working directory (single mode, must be inside workspace)" })),
202
+ timeout: Type.Optional(Type.Number({ description: "Inactivity timeout for the whole run, in ms; resets on activity, aborts on silence. Default 3 min (PI_SUBAGENT_INACTIVITY_TIMEOUT_MINS). Lifetime cap: 20 min or (PI_SUBAGENT_HARD_TIMEOUT_MINS)." })),
203
+ merge: Type.Optional(StringEnum(["3way"] as const, { description: "Single mode: with a worktree-sandboxed agent, apply its diff to the parent checkout via git apply --3way after it completes. Conflicts are reported, not resolved. Default: patch returned only." })),
204
+ instructions: Type.Optional(Type.String({ description: "Bounded repository/task instructions passed to each child (max 16 KB)" })),
205
+ solutionSpace: Type.Optional(Type.String({ description: "Single/parallel mode: how open-ended the child's problem is (design given vs choices open). Feeds model-tier/thinking routing; never mention siblings. e.g. 'one fix: rename, names given' vs 'several retry API shapes; error classes to choose'." })),
206
+ runner: Type.Optional(StringEnum(["sdk", "herdr"] as const, {
207
+ description: 'Execution backend: "sdk" (in-process, lean) or "herdr" (visible interactive pi panes in a herdr session; one tab per agent type, one pane per instance). Default: herdr when pi runs inside herdr, otherwise sdk.',
208
+ })),
209
+ abortOnFailure: Type.Optional(Type.Boolean({ description: "In parallel mode, cancel remaining tasks when one fails. Default: false.", default: false })),
210
+ });
211
+
212
+ // ---------------------------------------------------------------------------
213
+ // Details type
214
+ // ---------------------------------------------------------------------------
215
+
216
+ interface SubagentDetails {
217
+ mode: "single" | "parallel" | "chain";
218
+ agentScope: AgentScope;
219
+ projectAgentsDir: string | null;
220
+ results: SubAgentResult[];
221
+ /** Set when a background task was started (single mode + background:true). */
222
+ backgroundTaskId?: string;
223
+ /** Set when the run was delegated to herdr panes. */
224
+ runner?: "herdr";
225
+ }
226
+
227
+ // ---------------------------------------------------------------------------
228
+ // Cold-start catalog retry
229
+ // ---------------------------------------------------------------------------
230
+
231
+ /**
232
+ * Cooldown for the forced catalog refresh. MODULE scope, NOT the execute()
233
+ * closure: a burst of parallel (background) dispatches each get their own
234
+ * closure, so per-call state would let every one fire a forced network
235
+ * refresh — exactly the burst we rate-limit against. Classifier-module
236
+ * precedent (`lastForcedRefresh`).
237
+ */
238
+ let lastCatalogRefresh = 0;
239
+
240
+ /** Test hook: clear the cooldown (module state outlives a test). */
241
+ export function resetCatalogRefreshCooldown(): void {
242
+ lastCatalogRefresh = 0;
243
+ }
244
+
245
+ /**
246
+ * The router catalog's network pull races session start, so the FIRST dispatch
247
+ * of a session can miss every candidate ("Model not found"). On a resolve miss,
248
+ * one forced refresh + retry — rate-limited by {@link lastCatalogRefresh}.
249
+ * Exported for tests.
250
+ */
251
+ export async function resolveModelWithColdStartRetry(
252
+ ctx: ExtensionContext,
253
+ candidates: readonly string[],
254
+ ): Promise<ResolvedModel> {
255
+ let resolved = await resolveModel(candidates, ctx.model, ctx.modelRegistry);
256
+ if (resolved.model) return resolved;
257
+ if (Date.now() - lastCatalogRefresh > 60_000) {
258
+ lastCatalogRefresh = Date.now();
259
+ try {
260
+ await ctx.modelRegistry.refresh({ force: true });
261
+ } catch {
262
+ /* offline/endpoint down — the caller's error path still fires */
263
+ }
264
+ resolved = await resolveModel(candidates, ctx.model, ctx.modelRegistry);
265
+ }
266
+ return resolved;
267
+ }
268
+
269
+ // ---------------------------------------------------------------------------
270
+ // Extension entry point
271
+ // ---------------------------------------------------------------------------
272
+
273
+ export default function (pi: ExtensionAPI) {
274
+ let currentCtx: ExtensionContext | undefined;
275
+
276
+ // Live progress widget — fed by threadStore subscriptions (per SDK event).
277
+ const widget: TaskWidgetController = createTaskWidgetController(
278
+ () => threadStore.getAllThreads(),
279
+ (listener) => threadStore.subscribe(listener),
280
+ );
281
+
282
+ // Resolve bundled agents directory relative to this module file
283
+ // (upstream: extensions/index.ts → ../agents; ceulen module: ./agents)
284
+ const bundledAgentsDir = path.resolve(__dirname, "agents");
285
+
286
+ // Invalidate agent cache + clear thread store on session replacement.
287
+ pi.on("session_start", (event, ctx) => {
288
+ currentCtx = ctx;
289
+ if (event.reason === "reload") invalidateAgentCache();
290
+ threadStore.clear();
291
+ trustedProjectAgentDirs.clear();
292
+ // /config bridge: live registry + discovered agent names (advisor pattern).
293
+ setSubagentBridge({
294
+ registry: ctx?.modelRegistry,
295
+ agentNames: () => discoverAgents(ctx?.cwd ?? process.cwd(), "both", bundledAgentsDir).agents.map((a) => a.name),
296
+ });
297
+ // Clear any widget from a prior session.
298
+ if (ctx.mode === "tui") widget.clearWidgetIfIdle(ctx);
299
+ // Mark prior-session running tasks as interrupted (we can't resume them),
300
+ // but keep entries for background tasks still live in this process — only
301
+ // shutdown aborts them, so a session reload must not mislabel them.
302
+ // ponytail: honest about the in-process ceiling — no live-session resume.
303
+ try {
304
+ const liveBgIds = new Set(getAllBackgroundTasks().map((t) => t.id));
305
+ markInterruptedOnRestart(path.join(ctx.cwd, CONFIG_DIR_NAME), liveBgIds);
306
+ } catch { /* history file not writable — non-fatal */ }
307
+ });
308
+
309
+ // Clear the widget + abort background tasks on shutdown.
310
+ pi.on("session_shutdown", () => {
311
+ widget.dispose();
312
+ clearBackgroundTasks();
313
+ });
314
+
315
+ // Inject available agent catalog into system prompt for semantic auto-delegation
316
+ pi.on("before_agent_start", async (event) => {
317
+ const ctx = currentCtx;
318
+ const discovery = discoverAgents(ctx?.cwd ?? process.cwd(), "both", bundledAgentsDir);
319
+ const projectTrusted = ctx?.isProjectTrusted?.() ?? false;
320
+ // Security: project agents are repo-controlled (untrusted until the user
321
+ // approves them). Never let their description text reach the parent's
322
+ // system prompt unless the project is trusted — same gate as AGENTS.md.
323
+ const catalogAgents = discovery.agents.filter(
324
+ (agent) => projectTrusted || agent.source !== "project",
325
+ );
326
+ const rolesCfg = readSubagentRoles(ctx);
327
+ const catalog = catalogAgents
328
+ .map((agent) => {
329
+ const modelInfo = ` (models: ${describeAgentModels(agent, rolesCfg)})`;
330
+ const thinkingInfo = effectiveAgentThinking(agent, rolesCfg) ? `, thinking: ${effectiveAgentThinking(agent, rolesCfg)}` : "";
331
+ const sandboxInfo = agent.sandbox ? `, sandbox: ${agent.sandbox}` : "";
332
+ // ponytail: one-line inheritance hint; the model picks agents by description, this just sets expectations.
333
+ const toolsInfo = agent.tools ? `, tools: ${agent.tools.join(", ")}` : ", tools: inherits all parent tools";
334
+ return `- **${agent.name}**: ${agent.description}${modelInfo}${thinkingInfo}${sandboxInfo}${toolsInfo}`;
335
+ })
336
+ .join("\n");
337
+ return {
338
+ systemPrompt:
339
+ event.systemPrompt +
340
+ `\n\n## Available Subagents\n${catalog}\n\n` +
341
+ "The subagent tool can delegate tasks to these specialized agents with isolated context. " +
342
+ "Use for read-heavy exploration, parallel analysis, or work that would flood the main context.\n" +
343
+ "Agents marked `inherits all parent tools` can use web, Serena, Munin, and other extensions the main agent has; " +
344
+ "agents with an explicit tool list are leaner and restricted to those tools.\n" +
345
+ "Prefer **scout** and **tester** for cheap routine work. " +
346
+ "Prefer **worker** for normal coding. " +
347
+ "Prefer **planner** and **reviewer** for consequential reasoning. " +
348
+ "Delegation gates: never outsource the top-level plan or slice design; fan only genuine slices " +
349
+ "(never delegate ONE slice — do it yourself); never babysit — spawn, keep working, read the delivered result; " +
350
+ "do NOT delegate single-file small edits or quick greps. " +
351
+ "Modes: single, parallel (max 8 tasks, 4 concurrent), chain.",
352
+ };
353
+ });
354
+
355
+ // Register renderer for background-task completion (follow-up turn).
356
+ pi.registerMessageRenderer?.("ceulen-subagent-complete", (message, _opts, theme) => {
357
+ const d = (message.details ?? {}) as {
358
+ agent?: string; status?: string; summary?: string; full_output?: string;
359
+ elapsed_ms?: number; model?: string; thinking?: string; usage?: { turns?: number; cost?: number };
360
+ };
361
+ const fg = theme.fg.bind(theme);
362
+ const isErr = d.status && d.status !== "completed";
363
+ const icon = isErr ? fg("error", "✗") : fg("success", "✓");
364
+ const container = new Container();
365
+ const agentColor = "accent";
366
+ container.addChild(new Text(
367
+ `${icon} ${fg(agentColor, theme.bold(d.agent ?? "subagent"))} ${fg("muted", `[background · ${d.status ?? "done"}]`)}`,
368
+ 0, 0,
369
+ ));
370
+ if (d.full_output) {
371
+ const md = new Markdown(d.full_output.trim(), 0, 0, getMarkdownTheme());
372
+ for (const line of md.render(100)) {
373
+ container.addChild(new Text(line, 0, 0));
374
+ }
375
+ }
376
+ const usageParts: string[] = [];
377
+ if (d.usage?.turns) usageParts.push(`${d.usage.turns} turn${d.usage.turns > 1 ? "s" : ""}`);
378
+ if (d.usage?.cost) usageParts.push(`$${d.usage.cost.toFixed(4)}`);
379
+ if (d.elapsed_ms) {
380
+ const secs = Math.round(d.elapsed_ms / 1000);
381
+ usageParts.push(`${secs}s`);
382
+ }
383
+ if (d.model) usageParts.push(d.model);
384
+ if (d.thinking) usageParts.push(`think:${d.thinking}`);
385
+ if (usageParts.length > 0) {
386
+ container.addChild(new Text(fg("dim", usageParts.join(" · ")), 0, 0));
387
+ }
388
+ return container;
389
+ });
390
+ pi.registerCommand("subagent", {
391
+ description: "Configure model roles (/subagent), list agents (/subagent list), agent details (/subagent <name>), role detail (/subagent @role), reload definitions (/subagent reload), history (/subagent history)",
392
+ getArgumentCompletions: (prefix) => {
393
+ const ctx = currentCtx;
394
+ const keywords = ["list", "all", "agents", "roles", "reload", "refresh", "history"];
395
+ const vocab = [...keywords];
396
+ if (ctx) {
397
+ const discovery = discoverAgents(ctx.cwd, "both", bundledAgentsDir);
398
+ vocab.push(...discovery.agents.map((a) => a.name));
399
+ try { vocab.push(...Object.keys(readSubagentRoles(ctx).roles).map((r) => `@${r}`)); } catch { /* roles optional */ }
400
+ }
401
+ const q = prefix.trim().toLowerCase();
402
+ const items = vocab.filter((v) => v.toLowerCase().startsWith(q))
403
+ .map((v) => ({ value: v, label: v, description: keywords.includes(v) ? "subagent command" : "agent / role" }));
404
+ return items.length > 0 ? items : null;
405
+ },
406
+ handler: async (args, ctx) => {
407
+ const cmd = args.trim().toLowerCase();
408
+ const discovery = discoverAgents(ctx.cwd, "both", bundledAgentsDir);
409
+
410
+ // /subagent history — list recent task delegations (durable metadata).
411
+ if (cmd === "history" || cmd === "hist") {
412
+ const piDir = path.join(ctx.cwd, CONFIG_DIR_NAME);
413
+ const entries = readHistory(piDir)
414
+ .sort((a, b) => (b.completedAt ?? b.startedAt) - (a.completedAt ?? a.startedAt))
415
+ .slice(0, 20);
416
+ if (entries.length === 0) {
417
+ pi.sendMessage({
418
+ customType: "ceulen-subagent",
419
+ content: "No task history yet. History is recorded when subagent tasks complete.",
420
+ display: true,
421
+ });
422
+ return;
423
+ }
424
+ const lines = entries.map((e) => {
425
+ const time = new Date(e.startedAt).toLocaleString();
426
+ const statusIcon = e.status === "completed" ? "✓" : e.status === "interrupted" ? "⚠" : "✗";
427
+ const bg = e.background ? " [bg]" : "";
428
+ const summary = e.summary ? ` — ${e.summary.slice(0, 60)}` : "";
429
+ const routed = e.model ? ` · ${e.model}${e.thinking ? ` (${e.thinking})` : ""}` : "";
430
+ const advisor = e.advisorRounds ? ` · advisor:${e.advisorRounds} revision${e.advisorRounds > 1 ? "s" : ""}` : "";
431
+ return ` ${statusIcon} ${e.agent}${bg} · ${time}${routed}${advisor}${summary}`;
432
+ });
433
+ pi.sendMessage({
434
+ customType: "ceulen-subagent",
435
+ content: `Recent task history (${entries.length}${entries.length === 20 ? "+" : ""}):\n${lines.join("\n")}\n\nFile: ${getHistoryPath(piDir)}`,
436
+ display: true,
437
+ });
438
+ return;
439
+ }
440
+
441
+ const openRolesSummary = async (): Promise<void> => {
442
+ // Roles editor lives in the central /config (Tasks tab → Subagents);
443
+ // headless/bare /subagent prints the effective mapping instead.
444
+ const rolesCfg = readSubagentRoles(ctx);
445
+ const lines = discovery.agents.map((a) => ` ${a.name.padEnd(16)} ${describeAgentModels(a, rolesCfg)}`);
446
+ pi.sendMessage({
447
+ customType: "ceulen-subagent",
448
+ content: [
449
+ "Model roles (edit via /config → Tasks → Subagents, or ~/.pi/agent/settings.json → subagent.roles):",
450
+ ...Object.entries(rolesCfg.roles).map(([name, chain]) =>
451
+ ` @${name} = ${Array.isArray(chain) ? chain.join(", ") : chain}`),
452
+ "",
453
+ "Effective models per agent:",
454
+ ...lines,
455
+ ].join("\n"),
456
+ display: true,
457
+ });
458
+ return;
459
+ };
460
+
461
+ if (cmd === "roles") {
462
+ await openRolesSummary();
463
+ return;
464
+ }
465
+
466
+ if (cmd === "reload" || cmd === "refresh") {
467
+ invalidateAgentCache();
468
+ const fresh = discoverAgents(ctx.cwd, "both", bundledAgentsDir);
469
+ const list = formatAgentList(fresh.agents, 20);
470
+ const extra = list.remaining > 0 ? `\n ... +${list.remaining} more` : "";
471
+ const dirs = fresh.projectAgentsDir ? `project: ${fresh.projectAgentsDir}` : "no project agents dir";
472
+ const diagText = fresh.diagnostics.length > 0
473
+ ? "\n\nWarnings:\n" + fresh.diagnostics.map(d => ` - [${d.severity}] ${d.filePath}: ${d.issue}`).join("\n")
474
+ : "";
475
+ pi.sendMessage({
476
+ customType: "ceulen-subagent",
477
+ content: `Agent definitions reloaded.\n\nAvailable agents (${fresh.agents.length}):\n ${list.text}${extra}${diagText}\n\nDirectories searched:\n user: ${path.join(getAgentDir(), "agents")}\n ${dirs}\n bundled: ${bundledAgentsDir}`,
478
+ display: true,
479
+ });
480
+ ctx.ui.notify("Agent definitions reloaded", "info");
481
+ return;
482
+ }
483
+
484
+ // Handle listing keywords before agent lookup
485
+ if (cmd === "all" || cmd === "list" || cmd === "agents") {
486
+ const list = formatAgentList(discovery.agents, 20);
487
+ const extra = list.remaining > 0 ? `\n ... +${list.remaining} more` : "";
488
+ const dirs = discovery.projectAgentsDir ? `\n project: ${discovery.projectAgentsDir}` : "";
489
+ const diagText = discovery.diagnostics.length > 0
490
+ ? "\n\nWarnings:\n" + discovery.diagnostics.map(d => ` - [${d.severity}] ${d.filePath}: ${d.issue}`).join("\n")
491
+ : "";
492
+ pi.sendMessage({
493
+ customType: "ceulen-subagent",
494
+ content: `Available agents (${discovery.agents.length}):\n ${list.text}${extra}${diagText}\n\nScopes searched:\n user: ${path.join(getAgentDir(), "agents")}${dirs}\n bundled: ${bundledAgentsDir}\n\nUse /subagent <name> for agent details, /subagent @role for role detail, /subagent reload to refresh.`,
495
+ display: true,
496
+ });
497
+ return;
498
+ }
499
+
500
+ if (cmd) {
501
+ // Show details for a specific agent; fall back to a role detail view
502
+ // when the name matches a model role (e.g. "/subagent coder").
503
+ const agent = discovery.agents.find(
504
+ (a) => a.name.toLowerCase() === cmd,
505
+ );
506
+ if (!agent) {
507
+ const rolesCfg = readSubagentRoles(ctx);
508
+ const arg = args.trim().toLowerCase();
509
+ const roleName = arg.startsWith("@") ? arg.slice(1) : arg;
510
+ // Resolve the role key case-insensitively (role names are free-form).
511
+ const roleKey = Object.keys(rolesCfg.roles).find((k) => k.toLowerCase() === roleName);
512
+ const roleChain = roleKey !== undefined ? rolesCfg.roles[roleKey] : undefined;
513
+ const role = roleKey !== undefined && roleChain !== undefined
514
+ ? { key: roleKey, chain: roleChain }
515
+ : undefined;
516
+ if (role) {
517
+ const { key, chain } = role;
518
+ const chainText = Array.isArray(chain) ? chain.join(" → ") : String(chain);
519
+ const users = discovery.agents.filter((a) => getModelCandidates(a).some((c) => c.toLowerCase().split(":")[0] === `@${key.toLowerCase()}`));
520
+ const overrides = Object.entries(rolesCfg.agentModels).filter(([, v]) => v.toLowerCase().split(":")[0] === `@${key.toLowerCase()}`);
521
+ const defaultText = DEFAULT_ROLES[key] !== undefined
522
+ ? (Array.isArray(DEFAULT_ROLES[key]) ? (DEFAULT_ROLES[key] as string[]).join(" → ") : String(DEFAULT_ROLES[key]))
523
+ : "(custom role)";
524
+ pi.sendMessage({
525
+ customType: "ceulen-subagent",
526
+ content: [
527
+ `Role: @${key}`,
528
+ `Chain: ${chainText} → parent fallback`,
529
+ `Default: ${defaultText}`,
530
+ users.length > 0 ? `Agents using @${key}: ${users.map((a) => a.name).join(", ")}` : `No agent references @${key} yet`,
531
+ overrides.length > 0 ? `Overrides via @${key}: ${overrides.map(([n]) => n).join(", ")}` : "",
532
+ "",
533
+ `Edit with /subagent (roles editor) or ~/.pi/agent/settings.json → subagent.roles.`,
534
+ ].filter(Boolean).join("\n"),
535
+ display: true,
536
+ });
537
+ return;
538
+ }
539
+ ctx.ui.notify(`Unknown agent: "${args.trim()}". Use /subagent list to list all.`, "error");
540
+ return;
541
+ }
542
+ const rolesCfg = readSubagentRoles(ctx);
543
+ pi.sendMessage({
544
+ customType: "ceulen-subagent",
545
+ content: [
546
+ `Agent: ${agent.name} (${agent.source})`,
547
+ `Description: ${agent.description}`,
548
+ `Models: ${describeAgentModels(agent, rolesCfg)}`,
549
+ `Thinking: ${effectiveAgentThinking(agent, rolesCfg) || "off"}${rolesCfg.agentThinking[agent.name] ? " (settings override)" : ""}`,
550
+ `Tools: ${agent.tools?.join(", ") || "all default"}`,
551
+ `Source file: ${agent.filePath}`,
552
+ "",
553
+ "--- System Prompt ---",
554
+ agent.systemPrompt,
555
+ ].join("\n"),
556
+ display: true,
557
+ });
558
+ return;
559
+ }
560
+
561
+ // Bare /subagent — print the effective role mapping (editor lives in /config).
562
+ await openRolesSummary();
563
+ },
564
+ });
565
+
566
+ /** Map AgentColor (from agent frontmatter) to ThemeColor (for pi TUI). */
567
+ const AGENT_TO_THEME_COLOR: Record<AgentColor, ThemeColor> = {
568
+ red: "error",
569
+ blue: "accent",
570
+ green: "success",
571
+ yellow: "warning",
572
+ purple: "syntaxType",
573
+ orange: "syntaxString",
574
+ pink: "customMessageLabel",
575
+ cyan: "syntaxVariable",
576
+ };
577
+
578
+ /** Resolve agent-defined color to a valid ThemeColor for thread creation. */
579
+ const agentToThemeColor = (agentName: string): ThemeColor | undefined => {
580
+ const ctx = currentCtx;
581
+ if (!ctx) return undefined;
582
+ const agent = discoverAgents(ctx.cwd, "both", bundledAgentsDir).agents.find(a => a.name === agentName);
583
+ return agent?.color ? AGENT_TO_THEME_COLOR[agent.color] : undefined;
584
+ };
585
+
586
+ /** Look up agent color by name for TUI rendering. */
587
+ const resolveAgentColor = (name: string): ThemeColor => {
588
+ const ctx = currentCtx;
589
+ if (!ctx) return "accent";
590
+ const found = discoverAgents(ctx.cwd, "both", bundledAgentsDir).agents.find(a => a.name === name);
591
+ return found?.color ? AGENT_TO_THEME_COLOR[found.color] : "accent";
592
+ };
593
+
594
+ pi.registerTool({
595
+ name: "subagent",
596
+ label: "Subagent",
597
+ description: [
598
+ "Delegate tasks to specialized subagents with isolated context (SDK-based, minimal overhead).",
599
+ "Modes: single (agent + task), parallel (tasks array, max 8, 4 concurrent), chain (sequential with {previous}).",
600
+ "Task control: operation \"status\" or \"cancel\" with taskId inspects/cancels an existing background task without starting an agent.",
601
+ "Background: single mode accepts background:true to run detached; completion arrives as a follow-up turn.",
602
+ `Default agent scope is "user" (from ${path.join(getAgentDir(), "agents")}).`,
603
+ `To enable project-local agents in ${CONFIG_DIR_NAME}/agents, set agentScope: "both" or "project".`,
604
+ ].join(" "),
605
+ parameters: SubagentParams,
606
+ promptSnippet: "Delegate tasks to specialized sub-agents with automatic role-based model routing",
607
+ promptGuidelines: [
608
+ "Use subagent to delegate work that would flood the main context with search results or file contents.",
609
+ "Modes: single {agent, task}, parallel {tasks: [...]} (max 8, 4 concurrent), chain {chain: [...]} (sequential with {previous}).",
610
+ "Bundled agents: scout (fast recon), tester (verification), worker (implementation), planner (planning), reviewer (review). Model tier + thinking are auto-routed per task via the classifier; roles pin the pools (/config → Tasks → Subagents).",
611
+ "For background single tasks use background:true — you will be notified on completion; DO NOT poll or sleep.",
612
+ 'Task control by taskId: operation "status" (snapshot + liveness age), "wait" (block until settled or waitTimeoutMs, then snapshot), "cancel" (abort). A task producing output is NEVER hard-killed; only total silence (idle timeout) aborts it. "STALLED" in a snapshot means no child activity — cancel it or keep waiting.',
613
+ "Set solutionSpace when a task's openness isn't obvious from its text — it feeds tier/thinking routing.",
614
+ "Inside herdr, a single dispatch that names neither runner nor background may be sent to background by the task classifier (long/self-contained work) — pass runner or background explicitly to force one.",
615
+ "Worktree-sandboxed agents return their diff as a patch block in the result; pass merge: \"3way\" to auto-apply it to the parent checkout (git apply --3way; conflicts reported, never silently resolved).",
616
+ `Runner: "sdk" runs agents in-process (lean, default outside herdr); "herdr" delegates to visible interactive pi panes in a herdr session (one tab per agent type, one pane per instance) — default when pi runs inside herdr. herdr children share the working tree and skip worktree isolation; background:true always uses the sdk runner.`,
617
+ "Use /subagent list to list all available agents, /subagent <name> for agent details, /subagent @role for role detail.",
618
+ ],
619
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
620
+ // Surface env-var timeout warnings collected at module load. The
621
+ // interactive TUI swallows module-load stderr, so notify on launch.
622
+ for (const msg of flushWarnings()) {
623
+ ctx.ui?.notify?.(msg, "warning");
624
+ }
625
+ const agentScope: AgentScope = params.agentScope ?? "user";
626
+ const discovery = discoverAgents(ctx.cwd, agentScope, bundledAgentsDir);
627
+ const agents = discovery.agents;
628
+
629
+ // Trusted configuration — never from tool params.
630
+ const trusted = getTrustedConfig(ctx);
631
+ const confirmProjectAgents = !trusted.allowUnconfirmedProjectAgents;
632
+ const allowExternalCwd = trusted.allowExternalCwd;
633
+
634
+ // Resolve workspace root for cwd validation.
635
+ const workspaceRoot = ctx.cwd;
636
+
637
+ const hasChain = (params.chain?.length ?? 0) > 0;
638
+ const hasTasks = (params.tasks?.length ?? 0) > 0;
639
+ const hasSingle = Boolean(params.agent && params.task);
640
+ const modeCount = Number(hasChain) + Number(hasTasks) + Number(hasSingle);
641
+
642
+ // Runner resolution: explicit param wins; default auto-detects herdr
643
+ // (HERDR_ENV=1 + herdr binary answering, unless subagent.herdr:"off"
644
+ // or the PI_SUBAGENT_HERDR=off child recursion guard). Task-control
645
+ // operations and background runs never dispatch via herdr — skip the
646
+ // binary probe entirely.
647
+ const skipRunnerResolution = params.runner === undefined &&
648
+ (params.operation !== undefined || params.background === true);
649
+ const runnerResolved = skipRunnerResolution
650
+ ? { runner: "sdk" as const }
651
+ : await resolveEffectiveRunner(
652
+ params.runner,
653
+ (ctx as any).settings?.subagent ?? {},
654
+ herdrCli.exec,
655
+ );
656
+ if (runnerResolved.error) {
657
+ return {
658
+ content: [{ type: "text", text: runnerResolved.error }],
659
+ details: { mode: "single" as const, agentScope, projectAgentsDir: discovery.projectAgentsDir, results: [] },
660
+ isError: true,
661
+ };
662
+ }
663
+ // background:true always runs the in-process SDK runner (herdr tasks are
664
+ // foreground) — keep the details stamp honest.
665
+ const herdrActive = runnerResolved.runner === "herdr" && !params.background;
666
+
667
+ // Worktree isolation / merge:"3way" is an SDK-runner feature — herdr
668
+ // children share the parent's working tree, so a silent drop would turn
669
+ // an explicit isolation request into unmerged edits in the shared tree.
670
+ // Covers explicit merge params AND agent-level sandbox:"worktree".
671
+ const requestedMerge = params.merge || params.tasks?.some((t) => t.merge) || params.chain?.some((c) => c.merge);
672
+ const worktreeAgentRequested = [params.agent, ...(params.tasks ?? []).map((t) => t.agent), ...(params.chain ?? []).map((c) => c.agent)]
673
+ .some((n) => agents.find((a) => a.name === n)?.sandbox === "worktree");
674
+ if (herdrActive && (requestedMerge || worktreeAgentRequested)) {
675
+ return {
676
+ content: [{ type: "text", text: `Worktree isolation${requestedMerge ? " / merge:\"3way\"" : ""} requires runner:"sdk" — herdr children share the parent's working tree. Re-run with runner:"sdk"${requestedMerge ? " or drop merge" : ""}.` }],
677
+ details: { mode: "single" as const, agentScope, projectAgentsDir: discovery.projectAgentsDir, results: [] },
678
+ isError: true,
679
+ };
680
+ }
681
+
682
+ const makeDetails =
683
+ (mode: "single" | "parallel" | "chain") =>
684
+ (results: SubAgentResult[]): SubagentDetails => ({
685
+ mode,
686
+ agentScope,
687
+ projectAgentsDir: discovery.projectAgentsDir,
688
+ results,
689
+ runner: herdrActive ? "herdr" : undefined,
690
+ });
691
+
692
+ // Task-control results (operation status/cancel) describe an existing
693
+ // background task — they ran nothing themselves, so they must not
694
+ // inherit the ambient herdr stamp (a status lookup of an SDK task would
695
+ // otherwise be labeled runner:"herdr").
696
+ const opDetails = (): SubagentDetails => {
697
+ const details = makeDetails("single")([]);
698
+ details.runner = undefined;
699
+ return details;
700
+ };
701
+
702
+ // Validate execution request before any processing.
703
+ const validationErrors = validateExecutionRequest({
704
+ agentName: params.agent,
705
+ task: params.task,
706
+ tasks: params.tasks,
707
+ chain: params.chain,
708
+ timeout: params.timeout,
709
+ });
710
+ if (validationErrors.length > 0) {
711
+ const errorMessages = validationErrors.map((e) => ` • ${e.field}: ${e.message}`).join("\n");
712
+ return {
713
+ content: [{ type: "text", text: `Invalid parameters:\n${errorMessages}` }],
714
+ details: opDetails(),
715
+ isError: true,
716
+ };
717
+ }
718
+
719
+ // Control requests (status/cancel) legitimately have no mode — handle
720
+ // them before the mode-count validation rejects them.
721
+ if (params.operation === "status" || params.operation === "cancel" || params.operation === "wait") {
722
+ const taskId = params.taskId;
723
+ if (!taskId) {
724
+ return {
725
+ content: [{ type: "text" as const, text: `Missing taskId for operation "${params.operation}". Provide the taskId returned when the task was started.` }],
726
+ details: opDetails(),
727
+ isError: true,
728
+ };
729
+ }
730
+ const bgTask = getBackgroundTask(taskId);
731
+ if (params.operation === "status" || params.operation === "wait") {
732
+ // wait: block until the task settles or the wait window ends, then
733
+ // return the same snapshot status returns — early-exit on settle.
734
+ if (params.operation === "wait" && bgTask?.status === "running") {
735
+ const waitMs = Math.min(Math.max(params.waitTimeoutMs ?? 60_000, 1000), 600_000);
736
+ const deadline = Date.now() + waitMs;
737
+ while (bgTask.status === "running" && Date.now() < deadline) {
738
+ await new Promise((r) => setTimeout(r, 500));
739
+ if (signal?.aborted) break;
740
+ }
741
+ }
742
+ if (!bgTask) {
743
+ // Evicted after the 60s post-completion retention — fall back to
744
+ // the durable history so a finished task doesn't read as "never existed".
745
+ // Background entries only: foreground fg-* ids write a running
746
+ // entry at start, so a completed fg task is upserted WITHOUT the
747
+ // background flag and never matches this filter.
748
+ const hist = readHistory(path.join(ctx.cwd, CONFIG_DIR_NAME)).find((e) => e.id === taskId && e.background);
749
+ if (hist) {
750
+ const terminal = hist.status === "completed" || hist.status === "failed" || hist.status === "aborted" || hist.status === "timeout";
751
+ const paren = terminal
752
+ ? "finished — no longer retained in memory"
753
+ : `history shows ${hist.status} — not live in this session`;
754
+ const lines = [
755
+ `Task ${hist.id} (${hist.agent}): ${hist.status} (${paren})`,
756
+ `Task: ${hist.task}`,
757
+ ];
758
+ if (hist.summary) lines.push(`Summary: ${hist.summary}`);
759
+ return { content: [{ type: "text" as const, text: lines.join("\n") }], details: opDetails() };
760
+ }
761
+ return { content: [{ type: "text" as const, text: `No background task with id "${taskId}".` }], details: opDetails() };
762
+ }
763
+ const snap = snapshotTask(bgTask);
764
+ const lines = [
765
+ `Task ${snap.id} (${snap.agent}): ${snap.status}`,
766
+ `Elapsed: ${Math.round(snap.elapsedMs / 1000)}s`,
767
+ `Task: ${snap.task}`,
768
+ ];
769
+ if (snap.result) {
770
+ lines.push(`Output: ${String(snap.result.output).slice(0, 2000)}`);
771
+ if (snap.result.patchLines) lines.push(`Patch: ${snap.result.patchLines} diff lines (worktree)`);
772
+ } else {
773
+ // Liveness from the thread store's last SDK-event timestamp: a low
774
+ // age means the child has a pulse; a high age means it is stalled
775
+ // (the idle timer will abort it at subagent.idleTimeoutMins).
776
+ const thread = threadStore.getThread(bgTask.threadId);
777
+ const lastEventAt = thread?.lastActivityAt ?? thread?.createdAt;
778
+ const idleForS = lastEventAt ? Math.round((Date.now() - lastEventAt) / 1000) : null;
779
+ const liveness = idleForS === null
780
+ ? "(still running)"
781
+ : idleForS <= 30
782
+ ? `(still running — last activity ${idleForS}s ago)`
783
+ : `(still running — STALLED: no child activity for ${idleForS}s; it will be aborted by the idle timeout) — call again with operation "cancel" to stop it now, or keep waiting`;
784
+ lines.push(liveness);
785
+ }
786
+ return { content: [{ type: "text" as const, text: lines.join("\n") }], details: opDetails() };
787
+ }
788
+
789
+ // cancel
790
+ const result = cancelBackgroundTask(taskId);
791
+ if (result.outcome === "not_found") {
792
+ return { content: [{ type: "text" as const, text: `No background task with id "${taskId}".` }], details: opDetails(), isError: true };
793
+ }
794
+ if (result.outcome === "already_done") {
795
+ return { content: [{ type: "text" as const, text: `Task ${taskId} already finished (${result.task?.status}).` }], details: opDetails() };
796
+ }
797
+ return { content: [{ type: "text" as const, text: `Cancelled background task ${taskId}.` }], details: opDetails() };
798
+ }
799
+
800
+ // Validate: exactly one mode
801
+ if (modeCount !== 1) {
802
+ const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
803
+ return {
804
+ content: [
805
+ {
806
+ type: "text",
807
+ text: [
808
+ "Invalid parameters. Provide exactly one mode:",
809
+ " single: { agent, task }",
810
+ " parallel: { tasks: [...] }",
811
+ " chain: { chain: [...] }",
812
+ `Available agents: ${available}`,
813
+ ].join("\n"),
814
+ },
815
+ ],
816
+ details: makeDetails("single")([]),
817
+ isError: true,
818
+ };
819
+ }
820
+
821
+ // Handle project-local agent confirmation
822
+ // Security: confirmation policy comes from trusted config, never from tool params.
823
+ if (agentScope === "project" || agentScope === "both") {
824
+ const requestedAgentNames = new Set<string>();
825
+ if (params.chain) for (const s of params.chain) requestedAgentNames.add(s.agent);
826
+ if (params.tasks) for (const t of params.tasks) requestedAgentNames.add(t.agent);
827
+ if (params.agent) requestedAgentNames.add(params.agent);
828
+
829
+ const projectAgentsRequested = Array.from(requestedAgentNames)
830
+ .map((name) => agents.find((a) => a.name === name))
831
+ .filter((a): a is AgentConfig => a?.source === "project");
832
+
833
+ if (projectAgentsRequested.length > 0) {
834
+ if (confirmProjectAgents) {
835
+ const dir = discovery.projectAgentsDir ?? "(unknown)";
836
+ if (trustedProjectAgentDirs.has(dir)) {
837
+ // Previously approved "Trust for this session" for this agents dir.
838
+ } else if (ctx.hasUI) {
839
+ const names = projectAgentsRequested.map((a) => a.name).join(", ");
840
+ const choice = await ctx.ui.select(
841
+ `Run project-local agents?\n\nAgents: ${names}\nSource: ${dir}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`,
842
+ ["Allow once", "Trust for this session", "Deny"],
843
+ );
844
+ if (choice !== "Allow once" && choice !== "Trust for this session") {
845
+ return {
846
+ content: [{ type: "text", text: "Canceled: project-local agents not approved." }],
847
+ details: makeDetails(hasChain ? "chain" : hasTasks ? "parallel" : "single")([]),
848
+ };
849
+ }
850
+ if (choice === "Trust for this session") trustedProjectAgentDirs.add(dir);
851
+ } else {
852
+ // Fail closed in headless sessions.
853
+ return {
854
+ content: [{
855
+ type: "text",
856
+ text: "Project agents require explicit user approval. "
857
+ + "Enable the trusted project-agent setting to use them in headless mode.",
858
+ }],
859
+ details: makeDetails(hasChain ? "chain" : hasTasks ? "parallel" : "single")([]),
860
+ };
861
+ }
862
+ }
863
+ // else: allowUnconfirmedProjectAgents is true — skip confirmation.
864
+ }
865
+ }
866
+
867
+ const modelRegistry = ctx.modelRegistry;
868
+ const modelRuntime = (modelRegistry as any).runtime;
869
+ const authStorage = (modelRegistry as any).authStorage;
870
+
871
+ // Roles + routing + timeouts are read once per execute() call so every
872
+ // child in this run sees a consistent mapping (settings-driven — a
873
+ // /config save applies live, no /reload).
874
+ const rolesCfg: RolesConfig = readSubagentRoles(ctx);
875
+ const subSettings = readSubagentSettings(ctx);
876
+
877
+ // Parent session's registered tool names. Agents that omit `tools` inherit
878
+ // the full set (minus the denylist); agents with an explicit `tools` line
879
+ // are validated against built-ins ∪ this set.
880
+ const parentToolNames = pi.getAllTools().map((t) => t.name);
881
+ const projectTrusted = ctx.isProjectTrusted();
882
+
883
+ // Helper: resolve a safe child working directory.
884
+ function resolveChildCwd(childCwd: string | undefined): string {
885
+ const safe = resolveSafeCwd({ workspaceRoot, childCwd, allowExternalCwd });
886
+ if (safe.error) {
887
+ throw new Error(safe.error);
888
+ }
889
+ return safe.path;
890
+ }
891
+
892
+ // Helper: stable history id for a foreground run (shared between the
893
+ // running entry written at start and the completion entry).
894
+ function makeForegroundHistoryId(startedAt: number): string {
895
+ return `fg-${startedAt.toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
896
+ }
897
+
898
+ // Helper: record a running foreground task so a crash mid-run shows as
899
+ // "interrupted" after restart (completion upserts by id and replaces it).
900
+ function recordForegroundStart(entryId: string, agentName: string, taskText: string, startedAt: number): void {
901
+ try {
902
+ appendHistory(path.join(ctx.cwd, CONFIG_DIR_NAME), {
903
+ id: entryId,
904
+ agent: agentName,
905
+ task: taskText,
906
+ status: "running",
907
+ startedAt,
908
+ });
909
+ } catch { /* history file not writable — non-fatal */ }
910
+ }
911
+
912
+ // Helper: record a completed foreground task to the history registry.
913
+ // ponytail: best-effort — history is non-fatal metadata for /subagent history.
914
+ function recordForegroundHistory(
915
+ entryId: string,
916
+ agentName: string,
917
+ taskText: string,
918
+ result: SubAgentResult,
919
+ startedAt: number,
920
+ background = false,
921
+ ): void {
922
+ try {
923
+ const output = getFinalOutput(result.messages) || getResultOutput(result) || "";
924
+ const structured = parseStructuredResult(output);
925
+ const status = isFailedResult(result)
926
+ ? result.stopReason === "timeout"
927
+ ? "timeout"
928
+ : result.stopReason === "aborted"
929
+ ? "aborted"
930
+ : "failed"
931
+ : "completed";
932
+ appendHistory(path.join(ctx.cwd, CONFIG_DIR_NAME), {
933
+ id: entryId,
934
+ agent: agentName,
935
+ task: taskText,
936
+ status,
937
+ startedAt,
938
+ completedAt: Date.now(),
939
+ summary: structured.summary,
940
+ background,
941
+ model: result.model,
942
+ thinking: result.thinking,
943
+ advisorRounds: result.advisorRounds,
944
+ });
945
+ } catch { /* history file not writable — non-fatal */ }
946
+ }
947
+
948
+ // Helper: validate and normalise tools for an agent. Returns the effective
949
+ // tool list and whether extensions must be loaded (any non-built-in tool).
950
+ function resolveChildTools(agentTools: string[] | undefined, sandbox?: string, readOnly?: boolean): { tools: string[]; loadExtensions: boolean } {
951
+ // Omitted tools => inherit all parent tools (Claude Code model).
952
+ let rawTools = agentTools ?? parentToolNames;
953
+ // sandbox overrides tools: silently strip mutation tools, not an error
954
+ if (sandbox === "read-only") {
955
+ rawTools = rawTools.filter(t => READ_ONLY_TOOLS.includes(t));
956
+ if (rawTools.length === 0) rawTools = [...READ_ONLY_TOOLS];
957
+ }
958
+ const effectiveReadOnly = readOnly || sandbox === "read-only";
959
+ const result = validateAgentTools({ tools: rawTools, readOnly: effectiveReadOnly, availableTools: parentToolNames });
960
+ if (result.errors.length > 0) {
961
+ throw new Error(`Tool validation errors: ${result.errors.join("; ")}`);
962
+ }
963
+ return { tools: result.tools, loadExtensions: needsExtensions(result.tools) };
964
+ }
965
+
966
+ // Helper: uniform error SubAgentResult — single source for every
967
+ // hand-rolled failure literal (unknown agent, model exhaustion,
968
+ // validation, herdr delegation, sibling cancellation).
969
+ function makeErrorResult(agentName: string, task: string, message: string, stopReason = "error"): SubAgentResult {
970
+ return {
971
+ agent: agentName, task, exitCode: 1, status: "error", stopReason,
972
+ messages: [], stderr: message,
973
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
974
+ errorMessage: message,
975
+ };
976
+ }
977
+
978
+ // Helper: widget progress snapshot from a herdr lifecycle state.
979
+ function herdrProgress(agentName: string, task: string, state: string, startedAt: number, timeoutMs: number): SubAgentProgress {
980
+ const now = Date.now();
981
+ return {
982
+ label: `herdr: ${state}`,
983
+ at: now,
984
+ elapsedMs: now - startedAt,
985
+ inactivityDeadline: now + timeoutMs,
986
+ hardDeadline: startedAt + timeoutMs,
987
+ result: {
988
+ agent: agentName, task, exitCode: -1, messages: [], stderr: "",
989
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
990
+ },
991
+ };
992
+ }
993
+
994
+ // Classifier routing (mode: classify): one Jev round-trip asks tier +
995
+ // effort. Precedence — pins beat dynamic, dynamic beats defaults:
996
+ // agentModels pin skips the call; agentThinking pin skips effort only;
997
+ // the verdict otherwise amends the frontmatter-derived defaults. Shared
998
+ // by the SDK (runOne) and herdr (prepareHerdrOne) runners so the chosen
999
+ // model/thinking never depends on how the child is dispatched.
1000
+ async function routedChain(
1001
+ agent: AgentConfig,
1002
+ task: string,
1003
+ solutionSpace?: string,
1004
+ precomputed?: RoutingVerdict,
1005
+ ): Promise<{ chain: ExpandedCandidates; defaultThinking: SubagentThinkingLevel | undefined; error?: string }> {
1006
+ let tierOverride: string[] | undefined;
1007
+ let classifierThinking: SubagentThinkingLevel | undefined;
1008
+ // A precomputed verdict already carries tier/effort (single-mode
1009
+ // dispatch decision) — never ask Jev twice for the same dispatch.
1010
+ const verdict = precomputed ?? await classifyTask(ctx, subSettings.routing, agent, task, solutionSpace ?? params.solutionSpace, rolesCfg);
1011
+ if (verdict?.applied && verdict.tier) {
1012
+ const tierChain = rolesCfg.roles[verdict.tier];
1013
+ if (tierChain !== undefined) tierOverride = Array.isArray(tierChain) ? tierChain : [tierChain];
1014
+ }
1015
+ if (verdict?.applied && verdict.effort) {
1016
+ const level = (THINKING_LEVELS as readonly string[]).includes(verdict.effort) ? verdict.effort as SubagentThinkingLevel : undefined;
1017
+ if (level) classifierThinking = level;
1018
+ }
1019
+ const chain = tierOverride
1020
+ ? expandModelCandidates(tierOverride, rolesCfg.roles)
1021
+ : resolveAgentModelChain(agent, rolesCfg);
1022
+ return {
1023
+ chain,
1024
+ defaultThinking: classifierThinking ?? effectiveAgentThinking(agent, rolesCfg),
1025
+ // A typo'd `@alias` must FAIL LOUD: an empty candidate list would
1026
+ // otherwise read as "use the parent model" (resolveModel's fallback)
1027
+ // and silently dispatch the child on the parent model. Only when
1028
+ // NOTHING resolves — one bad entry beside a resolvable chain is a
1029
+ // diagnostic, not a dispatch failure. Both runners share this path.
1030
+ error: chain.unresolved.length > 0 && chain.candidates.length === 0
1031
+ ? `Unresolved model role(s): ${chain.unresolved.join(", ")} — fix the agent frontmatter or subagent.roles.`
1032
+ : undefined,
1033
+ };
1034
+ }
1035
+
1036
+ // Helper (herdr runner): validate + create topology + start the child pi,
1037
+ // without prompting — so parallel dispatch can materialise every pane
1038
+ // up front before any work starts.
1039
+ async function prepareHerdrOne(
1040
+ agentName: string,
1041
+ task: string,
1042
+ cwd: string | undefined,
1043
+ timeoutMs: number | undefined,
1044
+ solutionSpace?: string,
1045
+ verdict?: RoutingVerdict,
1046
+ ): Promise<{ handle: HerdrHandle; timeoutMs: number; startedAt: number } | { error: string }> {
1047
+ const agent = agents.find((a) => a.name === agentName);
1048
+ if (!agent) return { error: `Unknown agent: "${agentName}".` };
1049
+ const { chain: agentChain, defaultThinking, error: chainError } = await routedChain(agent, task, solutionSpace, verdict);
1050
+ if (chainError) return { error: chainError };
1051
+ const resolved = await resolveModelWithColdStartRetry(ctx, agentChain.candidates);
1052
+ if (!resolved.model) {
1053
+ return { error: `No model resolved for agent "${agentName}" (tried: ${resolved.attempted.join(", ") || "none"}).` };
1054
+ }
1055
+ // herdr children run full pi — they need SOME lifetime cap so an
1056
+ // unattended pane can't run forever; fall back to the idle window.
1057
+ const timeouts = resolveChildTimeouts({ requested: timeoutMs, agentTimeoutMins: agent.timeout, idleTimeoutMins: subSettings.idleTimeoutMins, hardTimeoutMins: subSettings.hardTimeoutMins });
1058
+ if (timeouts.error) return { error: timeouts.error };
1059
+ const hardTimeoutMs = timeouts.hardTimeoutMs ?? timeouts.timeoutMs ?? 0;
1060
+ if (!hardTimeoutMs) return { error: "Invalid herdr timeout configuration." };
1061
+ const safe = resolveSafeCwd({ workspaceRoot, childCwd: cwd, allowExternalCwd });
1062
+ if (safe.error) return { error: safe.error };
1063
+ const startedAt = Date.now();
1064
+ const systemPrompt = params.instructions
1065
+ ? `${agent.systemPrompt}\n\n## Task Contract\n${params.instructions.slice(0, MAX_INSTRUCTIONS_LENGTH)}`
1066
+ : agent.systemPrompt;
1067
+ try {
1068
+ const handle = await prepareHerdrTask({
1069
+ agentType: agent.name,
1070
+ systemPrompt,
1071
+ task,
1072
+ cwd: safe.path,
1073
+ model: `${resolved.model.provider}/${resolved.model.id}`,
1074
+ thinking: agentChain.thinkingByCandidate.get(resolved.matchedCandidate ?? "") ?? defaultThinking,
1075
+ tools: agent.tools,
1076
+ readOnly: agent.sandbox === "read-only",
1077
+ timeoutMs: hardTimeoutMs,
1078
+ });
1079
+ return { handle, timeoutMs: hardTimeoutMs, startedAt };
1080
+ } catch (err) {
1081
+ return { error: err instanceof Error ? err.message : String(err) };
1082
+ }
1083
+ }
1084
+
1085
+ // Helper (herdr runner): full delegation (prepare + prompt + collect).
1086
+ async function startHerdrOne(
1087
+ agentName: string,
1088
+ task: string,
1089
+ cwd: string | undefined,
1090
+ parentSignal: AbortSignal | undefined,
1091
+ timeoutMs: number | undefined,
1092
+ onActivity?: (progress: SubAgentProgress) => void,
1093
+ onUpdate?: AgentToolUpdateCallback<SubagentDetails>,
1094
+ heartbeatDetails?: () => SubagentDetails,
1095
+ onHeartbeat?: () => void,
1096
+ solutionSpace?: string,
1097
+ verdict?: RoutingVerdict,
1098
+ ): Promise<SubAgentResult> {
1099
+ const prepared = await prepareHerdrOne(agentName, task, cwd, timeoutMs, solutionSpace, verdict);
1100
+ if ("error" in prepared) return makeErrorResult(agentName, task, prepared.error);
1101
+ const { handle, startedAt } = prepared;
1102
+ // Keep-alive parity with the SDK path: a long pane run must emit
1103
+ // onUpdate traffic or the host may idle-abort the tool call.
1104
+ const stopHeartbeat = onUpdate ? startHeartbeat(() => {
1105
+ onHeartbeat?.();
1106
+ onUpdate({ content: [{ type: "text", text: "" }], details: heartbeatDetails?.() ?? makeDetails("single")([]) });
1107
+ widget.requestRender();
1108
+ }, herdrHeartbeat.intervalMs) : undefined;
1109
+ let onCancel: (() => void) | undefined;
1110
+ if (parentSignal) {
1111
+ onCancel = () => { void cancelAgent(handle.name, herdrCli.exec); };
1112
+ // An already-aborted signal never fires its listeners — cancel now.
1113
+ if (parentSignal.aborted) onCancel();
1114
+ else parentSignal.addEventListener("abort", onCancel, { once: true });
1115
+ }
1116
+ try {
1117
+ return await executeHerdrTask(handle, {
1118
+ onState: onActivity
1119
+ ? (state) => onActivity(herdrProgress(handle.agentType, task, state, startedAt, prepared.timeoutMs))
1120
+ : undefined,
1121
+ // The child's own advisor reviews the settled turn and may steer a
1122
+ // correction into it — wait for that verdict before collecting, so
1123
+ // the parent never consumes a draft the child is about to fix.
1124
+ advisorWaitMs: subSettings.advisorWaitSecs * 1000,
1125
+ onAdvisorPhase: onActivity
1126
+ ? (phase) => onActivity(herdrProgress(handle.agentType, task, phase, startedAt, prepared.timeoutMs))
1127
+ : undefined,
1128
+ signal: parentSignal,
1129
+ });
1130
+ } catch (err) {
1131
+ return makeErrorResult(agentName, task, `herdr delegation failed: ${err instanceof Error ? err.message : String(err)}`);
1132
+ } finally {
1133
+ // Settled: stop the keep-alive and detach the abort listener so a
1134
+ // later abort never keystrokes a completed step's pane.
1135
+ stopHeartbeat?.();
1136
+ if (parentSignal && onCancel) parentSignal.removeEventListener("abort", onCancel);
1137
+ }
1138
+ }
1139
+
1140
+ // Helper: run a single agent via SDK with security validation
1141
+ async function runOne(
1142
+ agentName: string,
1143
+ task: string,
1144
+ cwd: string | undefined,
1145
+ parentSignal?: AbortSignal,
1146
+ timeoutMs?: number,
1147
+ onProgress?: (partial: SubAgentResult) => void,
1148
+ onActivity?: (progress: SubAgentProgress) => void,
1149
+ heartbeatDetails?: () => SubagentDetails,
1150
+ onHeartbeat?: () => void,
1151
+ isReadOnly?: boolean,
1152
+ merge?: "3way",
1153
+ solutionSpace?: string,
1154
+ ): Promise<SubAgentResult> {
1155
+ const agent = agents.find((a) => a.name === agentName);
1156
+
1157
+ if (!agent) {
1158
+ const available = agents.map((a) => `"${a.name}"`).join(", ") || "none";
1159
+ return makeErrorResult(agentName, task, `Unknown agent: "${agentName}". Available: ${available}.`);
1160
+ }
1161
+
1162
+ const { chain: agentChain, defaultThinking, error: chainError } = await routedChain(agent, task, solutionSpace);
1163
+ if (chainError) return makeErrorResult(agentName, task, chainError);
1164
+ const resolved = await resolveModelWithColdStartRetry(ctx, agentChain.candidates);
1165
+ if (!resolved.model) {
1166
+ const tried = resolved.attempted.join(", ") || "none";
1167
+ const parentInfo = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "none";
1168
+ return makeErrorResult(
1169
+ agentName, task,
1170
+ `Model not found for agent "${agentName}". Tried: ${tried}. Parent model: ${parentInfo}. Check agent definition and pi model configuration.`,
1171
+ );
1172
+ }
1173
+
1174
+ // Security: validate tools, timeout, and cwd (wrapped in try/catch).
1175
+ let tools: string[];
1176
+ let loadExtensions: boolean;
1177
+ let effectiveTimeoutMs: number | undefined;
1178
+ let effectiveHardMs: number | undefined;
1179
+ let safeCwd: string;
1180
+ try {
1181
+ const resolved = resolveChildTools(agent.tools, agent.sandbox, isReadOnly);
1182
+ tools = resolved.tools;
1183
+ loadExtensions = resolved.loadExtensions;
1184
+ // Precedence: per-call timeout > agent frontmatter default > global
1185
+ // default; hard cap from settings (0 = OFF — a child producing events
1186
+ // is never hard-killed; the idle window is the hang detector).
1187
+ const timeouts = resolveChildTimeouts({ requested: timeoutMs, agentTimeoutMins: agent.timeout, globalTimeout: params.timeout, idleTimeoutMins: subSettings.idleTimeoutMins, hardTimeoutMins: subSettings.hardTimeoutMins });
1188
+ if (timeouts.error) throw new Error(timeouts.error);
1189
+ effectiveTimeoutMs = timeouts.timeoutMs;
1190
+ effectiveHardMs = timeouts.hardTimeoutMs;
1191
+ safeCwd = resolveChildCwd(cwd);
1192
+ } catch (err: unknown) {
1193
+ const errorMsg = err instanceof Error ? err.message : String(err);
1194
+ return makeErrorResult(agentName, task, `Validation error: ${errorMsg}`);
1195
+ }
1196
+
1197
+ // Retry loop: rate-limit model fallback (candidates already role-expanded).
1198
+ // Shared with the service path — single source of truth for triedModels
1199
+ // bookkeeping and per-candidate `:thinking` resolution.
1200
+ const candidates = agentChain.candidates;
1201
+
1202
+ // Transport keep-alive only: resets parent idle timeout so a long child
1203
+ // run isn't killed. The visible progress now lives in the live widget;
1204
+ // we no longer push the plain "still running…" text.
1205
+ const stopHeartbeat = onUpdate ? startHeartbeat(() => {
1206
+ onHeartbeat?.();
1207
+ onUpdate({ content: [{ type: "text", text: "" }], details: heartbeatDetails?.() ?? makeDetails("single")([]) });
1208
+ widget.requestRender();
1209
+ }) : undefined;
1210
+ try {
1211
+ return await runWithModelFallback<SubAgentResult>({
1212
+ candidates,
1213
+ parentModel: ctx.model,
1214
+ modelRegistry: ctx.modelRegistry,
1215
+ thinkingByCandidate: agentChain.thinkingByCandidate,
1216
+ defaultThinking,
1217
+ runAttempt: (model, thinkingLevel) =>
1218
+ runSubAgent({
1219
+ cwd: safeCwd,
1220
+ sandbox: agent.sandbox === "worktree" ? "worktree" : undefined,
1221
+ merge: agent.sandbox === "worktree" ? merge : undefined,
1222
+ systemPrompt: params.instructions
1223
+ ? `${agent.systemPrompt}\n\n## Task Contract\n${params.instructions.slice(0, MAX_INSTRUCTIONS_LENGTH)}`
1224
+ : agent.systemPrompt,
1225
+ task,
1226
+ tools,
1227
+ model,
1228
+ modelRuntime,
1229
+ authStorage,
1230
+ modelRegistry,
1231
+ signal: parentSignal,
1232
+ timeoutMs: effectiveTimeoutMs,
1233
+ hardTimeoutMs: effectiveHardMs,
1234
+ agentName,
1235
+ thinkingLevel,
1236
+ onMessage: onProgress,
1237
+ onProgress: onActivity,
1238
+ loadExtensions,
1239
+ projectTrusted,
1240
+ }),
1241
+ isRateLimited: (result) => isRetryableModelResult(result),
1242
+ onExhausted: (reason, triedModels, remaining) => {
1243
+ const exhaustedStderr = reason === "no-model"
1244
+ ? [
1245
+ `All models rate-limited or unavailable.`,
1246
+ `Tried: ${triedModels.join(" → ") || "(none)"}.`,
1247
+ `Remaining candidates: ${remaining.join(", ") || "none"}.`,
1248
+ `Parent: ${ctx.model?.provider}/${ctx.model?.id}.`,
1249
+ ].join(" ")
1250
+ : [
1251
+ `All available models exhausted.`,
1252
+ `Tried: ${triedModels.join(" → ")}.`,
1253
+ ].join(" ");
1254
+ return makeErrorResult(
1255
+ agentName, task, exhaustedStderr,
1256
+ // ponytail: exhaustive-models case; set a distinct stopReason if callers ever need to tell them apart.
1257
+ );
1258
+ },
1259
+ });
1260
+ } finally {
1261
+ stopHeartbeat?.();
1262
+ }
1263
+ }
1264
+
1265
+ // --- Chain mode ---
1266
+ if (params.chain && params.chain.length > 0) {
1267
+ const results: SubAgentResult[] = [];
1268
+ let previousOutput = "";
1269
+
1270
+ for (let i = 0; i < params.chain.length; i++) {
1271
+ const step = params.chain[i];
1272
+ const taskWithContext = step.task.replace(/\{previous\}/g, () => previousOutput);
1273
+ // A large step report can blow the herdr argv ceiling — truncate the
1274
+ // substituted text (SDK tasks have no ceiling and stay untouched).
1275
+ const dispatchTask = herdrActive ? truncateHerdrTask(taskWithContext) : taskWithContext;
1276
+
1277
+ const thread = threadStore.createThread({
1278
+ agentName: step.agent,
1279
+ task: dispatchTask,
1280
+ mode: "chain-step",
1281
+ toolCallId: _toolCallId,
1282
+ color: agentToThemeColor(step.agent),
1283
+ });
1284
+ if (ctx.mode === "tui") widget.ensureWidget(ctx);
1285
+ const historyId = makeForegroundHistoryId(thread.createdAt);
1286
+ recordForegroundStart(historyId, step.agent, dispatchTask, thread.createdAt);
1287
+ const result = herdrActive
1288
+ ? await startHerdrOne(
1289
+ step.agent, dispatchTask, step.cwd,
1290
+ signal, step.timeout ?? params.timeout,
1291
+ (progress) => threadStore.updateProgress(thread.id, progress),
1292
+ onUpdate,
1293
+ () => makeDetails("chain")(results),
1294
+ () => threadStore.refreshHeartbeat(thread.id),
1295
+ params.solutionSpace,
1296
+ )
1297
+ : await runOne(
1298
+ step.agent, taskWithContext, step.cwd,
1299
+ signal, step.timeout ?? params.timeout,
1300
+ (partial) => threadStore.updateThread(thread.id, { result: partial }),
1301
+ (progress) => threadStore.updateProgress(thread.id, progress),
1302
+ () => makeDetails("chain")(results),
1303
+ () => threadStore.refreshHeartbeat(thread.id),
1304
+ undefined,
1305
+ step.merge,
1306
+ params.solutionSpace,
1307
+ );
1308
+ threadStore.updateThread(thread.id, {
1309
+ status: isFailedResult(result) ? (result.stopReason === "aborted" ? "aborted" : "failed") : "completed",
1310
+ result,
1311
+ });
1312
+ recordForegroundHistory(historyId, step.agent, dispatchTask, result, thread.createdAt);
1313
+ results.push(result);
1314
+
1315
+ // Herdr: a blocked pane needs human input — pause the chain instead
1316
+ // of feeding degraded output to the next step.
1317
+ if (result.stopReason === "blocked") {
1318
+ return {
1319
+ content: [{
1320
+ type: "text",
1321
+ text: `Chain paused at step ${i + 1}/${params.chain.length} (${step.agent}): the agent is blocked awaiting input. Answer it in its herdr pane (or via the herdr tool), then re-run the remaining steps.`,
1322
+ }],
1323
+ details: makeDetails("chain")(results),
1324
+ };
1325
+ }
1326
+
1327
+ const isError = isFailedResult(result);
1328
+ if (isError) {
1329
+ const errorMsg = getResultOutput(result);
1330
+ if (onUpdate) {
1331
+ onUpdate({
1332
+ content: [{ type: "text", text: errorMsg }],
1333
+ details: makeDetails("chain")(results),
1334
+ });
1335
+ }
1336
+ // Include successful previous step outputs in the error content
1337
+ const prevCount = i;
1338
+ let contentText = `Chain stopped at step ${i + 1} (${step.agent}): ${errorMsg}`;
1339
+ const failedPatch = formatPatchBlock(result);
1340
+ if (failedPatch) contentText += `\n\n${failedPatch}`;
1341
+ if (prevCount > 0) {
1342
+ const prevSummaries = results
1343
+ .slice(0, prevCount)
1344
+ .map((r, j) => {
1345
+ const out = getResultOutput(r).slice(0, 500);
1346
+ return `Step ${j + 1} (${r.agent}): ${out}`;
1347
+ })
1348
+ .join("\n");
1349
+ contentText = `Chain stopped at step ${i + 1}/${params.chain.length}. ${prevCount} previous step(s) succeeded:\n\n${prevSummaries}\n\nError at step ${i + 1} (${step.agent}): ${errorMsg}`;
1350
+ }
1351
+ return {
1352
+ content: [{ type: "text", text: contentText }],
1353
+ details: makeDetails("chain")(results),
1354
+ isError: true,
1355
+ };
1356
+ }
1357
+
1358
+ previousOutput = getFinalOutput(result.messages);
1359
+
1360
+ if (onUpdate) {
1361
+ onUpdate({
1362
+ content: [{ type: "text", text: [getFinalOutput(result.messages) || "(no output)", formatPatchBlock(result)].filter(Boolean).join("\n\n") }],
1363
+ details: makeDetails("chain")(results),
1364
+ });
1365
+ }
1366
+ }
1367
+
1368
+ const last = results[results.length - 1];
1369
+ // Chain deliverable: final output plus every step's worktree patch,
1370
+ // labeled so the parent can merge them in order.
1371
+ const chainPatches = results
1372
+ .map((r, i) => (formatPatchBlock(r) ? `Step ${i + 1} (${r.agent}): ${formatPatchBlock(r)}` : ""))
1373
+ .filter(Boolean)
1374
+ .join("\n\n");
1375
+ return {
1376
+ content: [
1377
+ { type: "text", text: [getFinalOutput(last.messages) || "(no output)", chainPatches].filter(Boolean).join("\n\n") },
1378
+ ],
1379
+ details: makeDetails("chain")(results),
1380
+ };
1381
+ }
1382
+
1383
+ // --- Parallel mode ---
1384
+ if (params.tasks && params.tasks.length > 0) {
1385
+ const abortOnFailure = params.abortOnFailure ?? false;
1386
+ const parallelController = new AbortController();
1387
+ let abortCause: "parent" | "sibling" | "timeout" | undefined;
1388
+ let cleanupParentSignal: (() => void) | undefined;
1389
+
1390
+ // Link parent abort into parallelController so queued tasks see aborted state
1391
+ if (signal) {
1392
+ if (signal.aborted) {
1393
+ abortCause = "parent";
1394
+ parallelController.abort();
1395
+ } else {
1396
+ const onParentAbort = () => {
1397
+ if (!abortCause) abortCause = "parent";
1398
+ parallelController.abort();
1399
+ };
1400
+ signal.addEventListener("abort", onParentAbort, { once: true });
1401
+ cleanupParentSignal = () => signal.removeEventListener("abort", onParentAbort);
1402
+ }
1403
+ }
1404
+
1405
+ // Wrap all remaining setup + execution so cleanupParentSignal always runs.
1406
+ let stopParallelHeartbeat: ReturnType<typeof startHeartbeat> | undefined;
1407
+ try {
1408
+ // Pre-create threads for all parallel tasks
1409
+ const parallelThreads = params.tasks.map((t) =>
1410
+ threadStore.createThread({
1411
+ agentName: t.agent,
1412
+ task: t.task,
1413
+ mode: "parallel-task",
1414
+ toolCallId: _toolCallId,
1415
+ color: agentToThemeColor(t.agent),
1416
+ }),
1417
+ );
1418
+ if (ctx.mode === "tui") widget.ensureWidget(ctx);
1419
+
1420
+ const allResults: SubAgentResult[] = new Array(params.tasks.length);
1421
+ // Initialize placeholder results for streaming
1422
+ for (let i = 0; i < params.tasks.length; i++) {
1423
+ allResults[i] = {
1424
+ agent: params.tasks[i].agent,
1425
+ task: params.tasks[i].task,
1426
+ exitCode: -1,
1427
+ messages: [],
1428
+ stderr: "",
1429
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 },
1430
+ };
1431
+ }
1432
+
1433
+ // Herdr: materialise every pane up front so all delegated agents are
1434
+ // visible in herdr before any work starts, then submit prompts under
1435
+ // the concurrency limit below.
1436
+ const herdrPrepared = herdrActive
1437
+ ? await Promise.all(params.tasks.map(async (t) => {
1438
+ const startedAt = Date.now();
1439
+ const prepared = await prepareHerdrOne(t.agent, t.task, t.cwd, t.timeout ?? params.timeout, t.solutionSpace);
1440
+ if ("error" in prepared) return { ok: false as const, error: prepared.error, startedAt };
1441
+ return { ok: true as const, handle: prepared.handle, timeoutMs: prepared.timeoutMs, startedAt: prepared.startedAt };
1442
+ }))
1443
+ : undefined;
1444
+ if (herdrPrepared) {
1445
+ const cancelAll = () => {
1446
+ for (const p of herdrPrepared) if (p.ok) void cancelAgent(p.handle.name, herdrCli.exec);
1447
+ };
1448
+ if (signal) {
1449
+ if (signal.aborted) cancelAll();
1450
+ else signal.addEventListener("abort", cancelAll, { once: true });
1451
+ }
1452
+ // abortOnFailure / parent abort go through parallelController —
1453
+ // in-flight herdr agents must be cancelled too, not just queued ones.
1454
+ parallelController.signal.addEventListener("abort", cancelAll, { once: true });
1455
+ const previousCleanup = cleanupParentSignal;
1456
+ cleanupParentSignal = () => {
1457
+ previousCleanup?.();
1458
+ signal?.removeEventListener("abort", cancelAll);
1459
+ parallelController.signal.removeEventListener("abort", cancelAll);
1460
+ };
1461
+ }
1462
+
1463
+ // One keep-alive for the whole herdr parallel block (per tool call,
1464
+ // not per slot) — parity with the SDK path's heartbeat.
1465
+ stopParallelHeartbeat = herdrActive && onUpdate
1466
+ ? startHeartbeat(() => {
1467
+ onUpdate({ content: [{ type: "text", text: "" }], details: makeDetails("parallel")([...allResults]) });
1468
+ widget.requestRender();
1469
+ })
1470
+ : undefined;
1471
+
1472
+ const emitParallelUpdate = () => {
1473
+ if (onUpdate) {
1474
+ const running = allResults.filter((r) => r.exitCode === -1).length;
1475
+ const done = allResults.filter((r) => r.exitCode !== -1).length;
1476
+ onUpdate({
1477
+ content: [
1478
+ {
1479
+ type: "text",
1480
+ text: `Parallel: ${done}/${allResults.length} done, ${running} running...`,
1481
+ },
1482
+ ],
1483
+ details: makeDetails("parallel")([...allResults]),
1484
+ });
1485
+ }
1486
+ };
1487
+
1488
+ const results = await mapWithConcurrencyLimit(
1489
+ params.tasks,
1490
+ MAX_CONCURRENCY,
1491
+ async (t, index) => {
1492
+ // Skip if already aborted by sibling failure or parent abort
1493
+ if (parallelController.signal.aborted) {
1494
+ const preparedSkip = herdrPrepared?.[index];
1495
+ if (preparedSkip?.ok) void cancelAgent(preparedSkip.handle.name, herdrCli.exec);
1496
+ // Sibling/parent cancellation surfaces as "aborted", not "error" —
1497
+ // render and /subagent history key off the stopReason.
1498
+ const skipReason =
1499
+ abortCause === "sibling" ? "Cancelled: sibling task failed"
1500
+ : abortCause === "timeout" ? "Cancelled: sibling task timed out"
1501
+ : "Cancelled: parent operation aborted";
1502
+ const skippedResult = makeErrorResult(t.agent, t.task, skipReason, "aborted");
1503
+ threadStore.updateThread(parallelThreads[index].id, {
1504
+ status: "aborted",
1505
+ result: skippedResult,
1506
+ });
1507
+ emitParallelUpdate();
1508
+ return skippedResult;
1509
+ }
1510
+ const historyId = makeForegroundHistoryId(parallelThreads[index].createdAt);
1511
+ recordForegroundStart(historyId, t.agent, t.task, parallelThreads[index].createdAt);
1512
+ const prepared = herdrPrepared?.[index];
1513
+ const result = prepared
1514
+ ? prepared.ok
1515
+ ? await executeHerdrTask(prepared.handle, {
1516
+ onState: (state) => threadStore.updateProgress(
1517
+ parallelThreads[index].id,
1518
+ herdrProgress(t.agent, t.task, state, prepared.startedAt, prepared.timeoutMs),
1519
+ ),
1520
+ // Covers abortOnFailure AND parent abort (parent abort
1521
+ // feeds parallelController via onParentAbort).
1522
+ signal: parallelController.signal,
1523
+ })
1524
+ : makeErrorResult(t.agent, t.task, prepared.error)
1525
+ : await runOne(
1526
+ t.agent, t.task, t.cwd,
1527
+ parallelController.signal, t.timeout ?? params.timeout,
1528
+ (partial) => threadStore.updateThread(parallelThreads[index].id, { result: partial }),
1529
+ (progress) => threadStore.updateProgress(parallelThreads[index].id, progress),
1530
+ () => makeDetails("parallel")([...allResults]),
1531
+ () => threadStore.refreshHeartbeat(parallelThreads[index].id),
1532
+ undefined,
1533
+ t.merge,
1534
+ t.solutionSpace,
1535
+ );
1536
+ allResults[index] = result;
1537
+ threadStore.updateThread(parallelThreads[index].id, {
1538
+ status: isFailedResult(result) ? (result.stopReason === "aborted" ? "aborted" : "failed") : "completed",
1539
+ result,
1540
+ });
1541
+ recordForegroundHistory(historyId, t.agent, t.task, result, parallelThreads[index].createdAt);
1542
+ // Early-abort: if this task failed and abortOnFailure is set
1543
+ if (abortOnFailure && isFailedResult(result) && !abortCause) {
1544
+ abortCause = result.stopReason === "timeout" ? "timeout" : "sibling";
1545
+ parallelController.abort();
1546
+ }
1547
+ emitParallelUpdate();
1548
+ return result;
1549
+ },
1550
+ );
1551
+
1552
+ // Blocked herdr panes (status "partial") are neither succeeded nor
1553
+ // failed — they await human input and get their own count.
1554
+ const blockedCount = results.filter((r) => r.stopReason === "blocked").length;
1555
+ const successCount = results.filter((r) => !isFailedResult(r) && r.stopReason !== "blocked").length;
1556
+ const cancelCount = results.filter((r) => r.stopReason === "aborted" && r.errorMessage?.includes("Cancelled")).length;
1557
+ const summaries = results.map((r) => {
1558
+ const output = truncateParallelOutput(getResultOutput(r));
1559
+ const status = isFailedResult(r)
1560
+ ? `failed${r.stopReason ? ` (${r.stopReason})` : ""}`
1561
+ : r.stopReason === "blocked"
1562
+ ? "blocked — awaiting input in its pane"
1563
+ : "completed";
1564
+ const patch = formatPatchBlock(r);
1565
+ return `### [${r.agent}] ${status}\n\n${output}${patch ? `\n\n${patch}` : ""}`;
1566
+ });
1567
+
1568
+ let headerText = `Parallel: ${successCount}/${results.length} succeeded`;
1569
+ if (blockedCount > 0) headerText += ` (${blockedCount} blocked awaiting input)`;
1570
+ if (cancelCount > 0) headerText += ` (${cancelCount} cancelled)`;
1571
+ return {
1572
+ content: [
1573
+ {
1574
+ type: "text",
1575
+ text: `${headerText}\n\n${summaries.join("\n\n---\n\n")}`,
1576
+ },
1577
+ ],
1578
+ details: makeDetails("parallel")(results),
1579
+ };
1580
+ } finally {
1581
+ stopParallelHeartbeat?.();
1582
+ cleanupParentSignal?.();
1583
+ }
1584
+ }
1585
+
1586
+ // --- Single mode ---
1587
+ if (params.agent && params.task) {
1588
+ // Classifier-chosen dispatch (single mode, inside herdr): with neither
1589
+ // runner nor background named, Jev may answer "background" so long,
1590
+ // self-contained work detaches instead of occupying a pane and blocking
1591
+ // this turn. Explicit params always win; fail-open keeps the pane.
1592
+ let autoBackground = false;
1593
+ let dispatchVerdict: RoutingVerdict | undefined;
1594
+ if (herdrActive && params.runner === undefined && subSettings.routing.dispatch === "classify") {
1595
+ const routedAgent = agents.find((a) => a.name === params.agent);
1596
+ if (routedAgent) {
1597
+ dispatchVerdict = await classifyTask(ctx, subSettings.routing, routedAgent, params.task, params.solutionSpace, rolesCfg, { askDispatch: true });
1598
+ autoBackground = dispatchVerdict?.applied === true && dispatchVerdict.dispatch === "background";
1599
+ }
1600
+ }
1601
+ // Background: run detached, return receipt immediately, notify on completion.
1602
+ if (params.background || autoBackground) {
1603
+ const { taskId, receipt } = startBackgroundTask({
1604
+ agent: params.agent,
1605
+ task: params.task,
1606
+ cwd: params.cwd,
1607
+ timeout: params.timeout,
1608
+ merge: params.merge,
1609
+ agentColor: agentToThemeColor(params.agent),
1610
+ toolCallId: _toolCallId,
1611
+ deps: { pi, ctx, runOne, threadStore },
1612
+ });
1613
+ if (ctx.mode === "tui") widget.ensureWidget(ctx);
1614
+ // A foreground rerun of a pinned-sdk / disabled / unprobed call would
1615
+ // also run in-process — only advise when it would really delegate.
1616
+ const hint = backgroundHerdrHint(await wouldHerdrDelegate(params.runner, (ctx as any).settings?.subagent, herdrCli.exec));
1617
+ const autoNote = autoBackground
1618
+ ? "Dispatch: the task classifier chose background (long/self-contained) — pass runner or background explicitly to override."
1619
+ : "";
1620
+ const receiptText = [receipt, hint, autoNote].filter(Boolean).join("\n");
1621
+ return {
1622
+ content: [{ type: "text", text: receiptText }],
1623
+ details: { ...makeDetails("single")([]), backgroundTaskId: taskId },
1624
+ };
1625
+ }
1626
+ const thread = threadStore.createThread({
1627
+ agentName: params.agent,
1628
+ task: params.task,
1629
+ mode: "single",
1630
+ toolCallId: _toolCallId,
1631
+ color: agentToThemeColor(params.agent),
1632
+ });
1633
+ if (ctx.mode === "tui") widget.ensureWidget(ctx);
1634
+ const historyId = makeForegroundHistoryId(thread.createdAt);
1635
+ recordForegroundStart(historyId, params.agent, params.task, thread.createdAt);
1636
+ const result = herdrActive
1637
+ ? await startHerdrOne(
1638
+ params.agent, params.task, params.cwd,
1639
+ signal, params.timeout,
1640
+ (progress) => threadStore.updateProgress(thread.id, progress),
1641
+ onUpdate,
1642
+ () => makeDetails("single")([]),
1643
+ () => threadStore.refreshHeartbeat(thread.id),
1644
+ params.solutionSpace,
1645
+ dispatchVerdict,
1646
+ )
1647
+ : await runOne(
1648
+ params.agent, params.task, params.cwd,
1649
+ signal, params.timeout,
1650
+ (partial) => threadStore.updateThread(thread.id, { result: partial }),
1651
+ (progress) => threadStore.updateProgress(thread.id, progress),
1652
+ () => makeDetails("single")([]),
1653
+ () => threadStore.refreshHeartbeat(thread.id),
1654
+ undefined,
1655
+ params.merge,
1656
+ params.solutionSpace,
1657
+ );
1658
+ threadStore.updateThread(thread.id, {
1659
+ status: isFailedResult(result) ? (result.stopReason === "aborted" ? "aborted" : "failed") : "completed",
1660
+ result,
1661
+ });
1662
+ recordForegroundHistory(historyId, params.agent, params.task, result, thread.createdAt);
1663
+ const isError = isFailedResult(result);
1664
+
1665
+ if (onUpdate) {
1666
+ onUpdate({
1667
+ content: [
1668
+ { type: "text", text: getFinalOutput(result.messages) || "(running...)" },
1669
+ ],
1670
+ details: makeDetails("single")([result]),
1671
+ });
1672
+ }
1673
+
1674
+ if (isError) {
1675
+ const errorMsg = getResultOutput(result);
1676
+ const patch = formatPatchBlock(result);
1677
+ return {
1678
+ content: [
1679
+ {
1680
+ type: "text",
1681
+ text: `Agent ${result.stopReason || "failed"}: ${errorMsg}${patch ? `\n\n${patch}` : ""}`,
1682
+ },
1683
+ ],
1684
+ details: makeDetails("single")([result]),
1685
+ isError: true,
1686
+ };
1687
+ }
1688
+
1689
+ // Herdr panes blocked on a permission/question dialog are not
1690
+ // successes with no output — tell the model exactly what happened.
1691
+ if (result.stopReason === "blocked") {
1692
+ return {
1693
+ content: [{
1694
+ type: "text",
1695
+ text: `${params.agent} is blocked awaiting input in its herdr pane — answer it there (or via the herdr tool), then prompt again. ${result.errorMessage ?? ""}`,
1696
+ }],
1697
+ details: makeDetails("single")([result]),
1698
+ };
1699
+ }
1700
+
1701
+ return {
1702
+ content: [
1703
+ { type: "text", text: [getFinalOutput(result.messages) || "(no output)", formatPatchBlock(result)].filter(Boolean).join("\n\n") },
1704
+ ],
1705
+ details: makeDetails("single")([result]),
1706
+ };
1707
+ }
1708
+
1709
+ // Exhaustiveness check: the modeCount === 1 validation above ensures
1710
+ // at least one of the three branches is taken, but TS cannot prove it.
1711
+ throw new Error("unreachable");
1712
+ },
1713
+
1714
+ // ------------------------------------------------------------------
1715
+ // TUI rendering
1716
+ // ------------------------------------------------------------------
1717
+
1718
+ renderCall(args, theme, context) {
1719
+ const scope: AgentScope = args.agentScope ?? "user";
1720
+ const fg = theme.fg.bind(theme);
1721
+ const now = Date.now();
1722
+
1723
+ // Live-render driver: while the tool executes, re-render every second
1724
+ // (bash.js pattern) so elapsed + tool-call count stay fresh in the TUI.
1725
+ // The interval lives in shared renderer state, cleared by renderResult.
1726
+ const state = context.state as { interval?: ReturnType<typeof setInterval> };
1727
+ if (context.executionStarted && !state.interval) {
1728
+ state.interval = setInterval(() => context.invalidate(), 1000);
1729
+ }
1730
+
1731
+ // Look up threads for this tool call (stable toolCallId).
1732
+ const threads = threadStore
1733
+ .getAllThreads()
1734
+ .filter((t) => t.toolCallId === context.toolCallId);
1735
+ const runningThread = threads.find((t) => t.status === "running");
1736
+
1737
+ // Task control (status/cancel) — no agent/task; show the operation.
1738
+ // status/wait render the OMP-style live job tree over the SESSION fleet
1739
+ // (wait ops have their own toolCallId, so the per-call thread filter is
1740
+ // always empty here — the whole store is the job set).
1741
+ if (args.operation) {
1742
+ if (args.operation === "status" || args.operation === "wait") {
1743
+ // A waited background task resolves to its thread via the bg registry.
1744
+ let focusThreadId: string | undefined;
1745
+ if (args.taskId) {
1746
+ const bg = getBackgroundTask(args.taskId);
1747
+ if (bg) focusThreadId = bg.threadId;
1748
+ }
1749
+ const fleet = threadStore.getAllThreads();
1750
+ const tree = renderWaitTree({ taskId: args.taskId, focusThreadId, threads: fleet, width: 120, theme }).join("\n");
1751
+ const container = new Container();
1752
+ container.addChild(new Text(tree, 0, 0));
1753
+ return container;
1754
+ }
1755
+ return new Text(
1756
+ fg("accent", String(args.operation)) +
1757
+ fg("muted", args.taskId ? ` [${args.taskId}]` : ""),
1758
+ 0, 0,
1759
+ );
1760
+ }
1761
+
1762
+ // Chain
1763
+ if (args.chain && args.chain.length > 0) {
1764
+ let text =
1765
+ fg("accent", `chain (${args.chain.length} steps)`) +
1766
+ fg("muted", ` [${scope}]`);
1767
+ const cap = context.expanded ? args.chain.length : 3;
1768
+ for (let i = 0; i < Math.min(args.chain.length, cap); i++) {
1769
+ const step = args.chain[i];
1770
+ const cleanTask = step.task.replace(/\{previous\}/g, "").trim();
1771
+ const preview = cleanTask.length > 40 ? `${cleanTask.slice(0, 40)}...` : cleanTask;
1772
+ const stepThread = threads[i];
1773
+ const live = stepThread && stepThread.status === "running"
1774
+ ? "\n " + renderLiveThreadLine(stepThread, theme, now, resolveAgentColor(step.agent))
1775
+ : "";
1776
+ text +=
1777
+ "\n " +
1778
+ fg("muted", `${i + 1}.`) +
1779
+ " " +
1780
+ fg(resolveAgentColor(step.agent), step.agent) +
1781
+ fg("dim", ` ${preview}`) +
1782
+ live;
1783
+ }
1784
+ if (args.chain.length > cap)
1785
+ text += `\n ${fg("muted", `... +${args.chain.length - cap} more${context.expanded ? "" : " (Ctrl+O to expand)"}`)}`;
1786
+ return new Text(text, 0, 0);
1787
+ }
1788
+
1789
+ // Parallel — live line per task with a running thread.
1790
+ if (args.tasks && args.tasks.length > 0) {
1791
+ let text =
1792
+ fg("accent", `parallel (${args.tasks.length} tasks)`) +
1793
+ fg("muted", ` [${scope}]`);
1794
+ const cap = context.expanded ? args.tasks.length : 3;
1795
+ for (const t of args.tasks.slice(0, cap)) {
1796
+ const preview = t.task.length > 40 ? `${t.task.slice(0, 40)}...` : t.task;
1797
+ const taskThread = threads.find((th) => th.agentName === t.agent && th.task === t.task);
1798
+ const live = taskThread && taskThread.status === "running"
1799
+ ? "\n " + renderLiveThreadLine(taskThread, theme, now, resolveAgentColor(t.agent))
1800
+ : "";
1801
+ text += `\n ${fg(resolveAgentColor(t.agent), t.agent)}${fg("dim", ` ${preview}`)}${live}`;
1802
+ }
1803
+ if (args.tasks.length > cap)
1804
+ text += `\n ${fg("muted", `... +${args.tasks.length - cap} more${context.expanded ? "" : " (Ctrl+O to expand)"}`)}`;
1805
+ return new Text(text, 0, 0);
1806
+ }
1807
+
1808
+ // Single — live header while running, static summary otherwise.
1809
+ const agentName = args.agent || "...";
1810
+ const preview = args.task
1811
+ ? args.task.length > 60
1812
+ ? `${args.task.slice(0, 60)}...`
1813
+ : args.task
1814
+ : "...";
1815
+ let text =
1816
+ fg(resolveAgentColor(agentName), agentName) +
1817
+ fg("muted", ` [${scope}]`) +
1818
+ (args.background ? fg("dim", " bg") : "");
1819
+ if (runningThread) {
1820
+ text += "\n" + renderLiveThreadLine(runningThread, theme, now, resolveAgentColor(agentName));
1821
+ } else {
1822
+ text += `\n ${fg("dim", preview)}`;
1823
+ }
1824
+ return new Text(text, 0, 0);
1825
+ },
1826
+
1827
+ renderResult(result, { expanded }, theme, _context) {
1828
+ // Stop the live-render interval started by renderCall (shared state).
1829
+ const state = _context.state as { interval?: ReturnType<typeof setInterval> };
1830
+ if (state?.interval) {
1831
+ clearInterval(state.interval);
1832
+ state.interval = undefined;
1833
+ }
1834
+
1835
+ const details = result.details as SubagentDetails | undefined;
1836
+ if (!details || details.results.length === 0) {
1837
+ const text = result.content[0];
1838
+ return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0);
1839
+ }
1840
+
1841
+ const fg = theme.fg.bind(theme);
1842
+ const mdTheme = getMarkdownTheme();
1843
+
1844
+ // --- Single ---
1845
+ if (details.mode === "single" && details.results.length === 1) {
1846
+ const r = details.results[0];
1847
+ return renderSingleResult(r, expanded, theme, resolveAgentColor(r.agent));
1848
+ }
1849
+
1850
+ // --- Chain ---
1851
+ if (details.mode === "chain") {
1852
+ const successCount = details.results.filter((r) => !isFailedResult(r)).length;
1853
+ const icon =
1854
+ successCount === details.results.length
1855
+ ? fg("success", "✓")
1856
+ : fg("error", "✗");
1857
+
1858
+ if (expanded) {
1859
+ const container = new Container();
1860
+ container.addChild(
1861
+ new Text(
1862
+ icon +
1863
+ " " +
1864
+ fg("toolTitle", theme.bold("chain ")) +
1865
+ fg("accent", `${successCount}/${details.results.length} steps`),
1866
+ 0,
1867
+ 0,
1868
+ ),
1869
+ );
1870
+ for (const r of details.results) {
1871
+ container.addChild(new Spacer(1));
1872
+ const stepIcon = isFailedResult(r) ? fg("error", "✗") : fg("success", "✓");
1873
+ container.addChild(
1874
+ new Text(
1875
+ fg("muted", `─── Step ${r.exitCode !== -1 ? "" : "?"}: `) +
1876
+ fg(resolveAgentColor(r.agent), r.agent) +
1877
+ ` ${stepIcon}`,
1878
+ 0,
1879
+ 0,
1880
+ ),
1881
+ );
1882
+ if (r.errorMessage) {
1883
+ container.addChild(
1884
+ new Text(fg("error", `Error: ${r.errorMessage}`), 0, 0),
1885
+ );
1886
+ }
1887
+ const finalOutput = getResultOutput(r);
1888
+ if (finalOutput) {
1889
+ container.addChild(new Spacer(1));
1890
+ container.addChild(new Markdown(finalOutput.trim(), 0, 0, mdTheme));
1891
+ }
1892
+ const usageStr = formatUsageStats(r.usage, r.model);
1893
+ if (usageStr)
1894
+ container.addChild(new Text(fg("dim", usageStr), 0, 0));
1895
+ }
1896
+ const totalUsage = formatUsageStats(aggregateUsage(details.results));
1897
+ if (totalUsage) {
1898
+ container.addChild(new Spacer(1));
1899
+ container.addChild(new Text(fg("dim", `Total: ${totalUsage}`), 0, 0));
1900
+ }
1901
+ return container;
1902
+ }
1903
+
1904
+ let text =
1905
+ icon +
1906
+ " " +
1907
+ fg("toolTitle", theme.bold("chain ")) +
1908
+ fg("accent", `${successCount}/${details.results.length} steps`);
1909
+ for (const r of details.results) {
1910
+ const stepIcon = isFailedResult(r) ? fg("error", "✗") : fg("success", "✓");
1911
+ const color = resolveAgentColor(r.agent);
1912
+ text += `\n ${stepIcon} ${fg(color, r.agent)}`;
1913
+ }
1914
+ const totalUsage = formatUsageStats(aggregateUsage(details.results));
1915
+ if (totalUsage) text += `\n${fg("dim", totalUsage)}`;
1916
+ text += `\n${fg("muted", "(Ctrl+O to expand)")}`;
1917
+ return new Text(text, 0, 0);
1918
+ }
1919
+
1920
+ // --- Parallel ---
1921
+ if (details.mode === "parallel") {
1922
+ const running = details.results.filter((r) => r.exitCode === -1).length;
1923
+ const successCount = details.results.filter(
1924
+ (r) => r.exitCode !== -1 && !isFailedResult(r),
1925
+ ).length;
1926
+ const failCount = details.results.filter(
1927
+ (r) => r.exitCode !== -1 && isFailedResult(r),
1928
+ ).length;
1929
+ const isRunning = running > 0;
1930
+ const icon = isRunning
1931
+ ? fg("warning", "⏳")
1932
+ : failCount > 0
1933
+ ? fg("warning", "◐")
1934
+ : fg("success", "✓");
1935
+ const status = isRunning
1936
+ ? `${successCount + failCount}/${details.results.length} done, ${running} running`
1937
+ : `${successCount}/${details.results.length} tasks`;
1938
+
1939
+ if (expanded && !isRunning) {
1940
+ const container = new Container();
1941
+ container.addChild(
1942
+ new Text(
1943
+ `${icon} ${fg("toolTitle", theme.bold("parallel "))}${fg("accent", status)}`,
1944
+ 0,
1945
+ 0,
1946
+ ),
1947
+ );
1948
+ for (const r of details.results) {
1949
+ container.addChild(new Spacer(1));
1950
+ const taskIcon = isFailedResult(r)
1951
+ ? fg("error", "✗")
1952
+ : fg("success", "✓");
1953
+ container.addChild(
1954
+ new Text(
1955
+ fg("muted", "─── ") + fg(resolveAgentColor(r.agent), r.agent) + ` ${taskIcon}`,
1956
+ 0,
1957
+ 0,
1958
+ ),
1959
+ );
1960
+ container.addChild(
1961
+ new Text(fg("muted", "Task: ") + fg("dim", r.task), 0, 0),
1962
+ );
1963
+ if (r.errorMessage) {
1964
+ container.addChild(
1965
+ new Text(fg("error", `Error: ${r.errorMessage}`), 0, 0),
1966
+ );
1967
+ }
1968
+ const finalOutput = getResultOutput(r);
1969
+ if (finalOutput) {
1970
+ container.addChild(new Spacer(1));
1971
+ container.addChild(
1972
+ new Markdown(finalOutput.trim(), 0, 0, mdTheme),
1973
+ );
1974
+ }
1975
+ const taskUsage = formatUsageStats(r.usage, r.model);
1976
+ if (taskUsage)
1977
+ container.addChild(new Text(fg("dim", taskUsage), 0, 0));
1978
+ }
1979
+ const totalUsage = formatUsageStats(aggregateUsage(details.results));
1980
+ if (totalUsage) {
1981
+ container.addChild(new Spacer(1));
1982
+ container.addChild(new Text(fg("dim", `Total: ${totalUsage}`), 0, 0));
1983
+ }
1984
+ return container;
1985
+ }
1986
+
1987
+ let text = `${icon} ${fg("toolTitle", theme.bold("parallel "))}${fg("accent", status)}`;
1988
+ for (const r of details.results) {
1989
+ const taskIcon =
1990
+ r.exitCode === -1
1991
+ ? fg("warning", "⏳")
1992
+ : isFailedResult(r)
1993
+ ? fg("error", "✗")
1994
+ : fg("success", "✓");
1995
+ text += `\n ${taskIcon} ${fg(resolveAgentColor(r.agent), r.agent)}`;
1996
+ }
1997
+ if (!isRunning) {
1998
+ const totalUsage = formatUsageStats(aggregateUsage(details.results));
1999
+ if (totalUsage) text += `\n${fg("dim", totalUsage)}`;
2000
+ }
2001
+ if (!expanded) text += `\n${fg("muted", "(Ctrl+O to expand)")}`;
2002
+ return new Text(text, 0, 0);
2003
+ }
2004
+
2005
+ const fallback = result.content[0];
2006
+ return new Text(fallback?.type === "text" ? fallback.text : "(no output)", 0, 0);
2007
+ },
2008
+ });
2009
+
2010
+ // ---------------------------------------------------------------------------
2011
+ // herdr control tool — main-session oversight of delegated pane agents
2012
+ // ---------------------------------------------------------------------------
2013
+
2014
+ const HerdrControlParams = Type.Object({
2015
+ action: StringEnum(["list", "status", "read", "prompt", "cancel", "focus", "close-tab", "forget"] as const, {
2016
+ description:
2017
+ "list: delegated agents with live states; status: one agent's lifecycle state; " +
2018
+ "read: recent pane output (best-effort — TUI agents render on the alternate screen); " +
2019
+ "prompt: send a follow-up to the agent's session; cancel: interrupt (esc, then ctrl+c); " +
2020
+ "focus: raise the agent's tab; close-tab: close the tab of an agent this session delegated; " +
2021
+ "forget: drop a stale registry entry (e.g. after its tab was closed outside this session).",
2022
+ }),
2023
+ name: Type.Optional(Type.String({ description: "Herdr agent name (e.g. scout-1, from action \"list\"). Required for every action except list." })),
2024
+ text: Type.Optional(Type.String({ description: "Follow-up prompt text (action: prompt)." })),
2025
+ lines: Type.Optional(Type.Number({ description: "action: read — lines of recent output (default 120)." })),
2026
+ wait: Type.Optional(Type.Boolean({ description: "action: prompt — wait for a settled state and collect the report (default: submit and return immediately)." })),
2027
+ timeout: Type.Optional(Type.Number({ description: "action: prompt with wait:true — timeout in ms (default 120000)." })),
2028
+ });
2029
+
2030
+ pi.registerTool({
2031
+ name: "herdr",
2032
+ label: "Herdr",
2033
+ description: [
2034
+ "Control agents this session delegated to herdr panes (subagent runner:\"herdr\", automatic inside herdr).",
2035
+ "Actions: list, status, read, prompt, cancel, focus, close-tab, forget.",
2036
+ ].join(" "),
2037
+ parameters: HerdrControlParams,
2038
+ promptSnippet: "Control delegated herdr pane agents (list/status/read/prompt/cancel/focus/close-tab/forget)",
2039
+ promptGuidelines: [
2040
+ "Use for oversight of herdr-delegated subagents: status/read to inspect, prompt to continue an agent's session, cancel to interrupt, focus to raise its tab, forget to drop a stale registry entry.",
2041
+ "A blocked agent waits for human input — answer it in the pane directly, or cancel and re-delegate.",
2042
+ "prompt/cancel/forget only accept agents this session delegated and close-tab only tabs it created; status/read/focus can inspect any live herdr agent.",
2043
+ "read is best-effort: pi renders on the terminal's alternate screen, so finished reports may not be scrollback-visible (delegated tasks deliver via report files instead).",
2044
+ ],
2045
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
2046
+ const toolResult = (text: string, isError = false) => ({
2047
+ content: [{ type: "text" as const, text }],
2048
+ isError,
2049
+ details: {},
2050
+ });
2051
+ if (!herdrEnvDetected()) {
2052
+ return toolResult("Not running inside herdr (HERDR_ENV!=1). Start pi inside a herdr pane to delegate agents to herdr tabs.", true);
2053
+ }
2054
+ if (herdrDisabled(undefined)) {
2055
+ // Delegated child session (PI_SUBAGENT_HERDR=off): no herdr control.
2056
+ return toolResult("herdr control is disabled in this session (PI_SUBAGENT_HERDR=off child guard).", true);
2057
+ }
2058
+ if (params.action !== "list" && !params.name) {
2059
+ return toolResult(`Missing name for action "${params.action}". Use a herdr agent name from action "list" (e.g. scout-1).`, true);
2060
+ }
2061
+ const name = params.name!;
2062
+ // Mutating actions are scoped to agents this session delegated —
2063
+ // the model must not drive (or kill) panes it never spawned.
2064
+ if ((params.action === "prompt" || params.action === "cancel") && !isDelegatedHerdrAgent(name)) {
2065
+ return toolResult(`"${name}" was not delegated by this session — refusing to ${params.action} an agent this session did not start. If this pane predates a /reload-runtime, interrupt or close it manually (herdr tab close <tabId>; tab id via herdr status).`, true);
2066
+ }
2067
+ switch (params.action) {
2068
+ case "list": {
2069
+ const entries = getHerdrRegistry();
2070
+ if (entries.length === 0) {
2071
+ return toolResult("No herdr-delegated agents this session. Delegation goes to herdr panes automatically while pi runs inside herdr (or with subagent runner:\"herdr\").");
2072
+ }
2073
+ const live = await listHerdrAgents(herdrCli.exec);
2074
+ const stateByPane = new Map(live.filter((a) => a.paneId).map((a) => [a.paneId!, a.status ?? "unknown"]));
2075
+ const lines = entries.map((e) =>
2076
+ `- ${e.name} · ${e.agentType} · ${stateByPane.get(e.paneId) ?? "unknown"} · tab ${e.tabId} / pane ${e.paneId} — ${e.task.slice(0, 60)}${e.task.length > 60 ? "…" : ""}`,
2077
+ );
2078
+ return toolResult(`Delegated herdr agents (${entries.length}):\n${lines.join("\n")}`);
2079
+ }
2080
+ case "status": {
2081
+ const info = await getAgentInfo(name, herdrCli.exec);
2082
+ if (!info) {
2083
+ return toolResult(`No herdr agent named "${name}".`, true);
2084
+ }
2085
+ return toolResult(`${name}: ${info.status ?? "unknown"} (tab ${info.tabId ?? "?"} / pane ${info.paneId ?? "?"}${info.cwd ? `, cwd ${info.cwd}` : ""})`);
2086
+ }
2087
+ case "read": {
2088
+ // Clamp scrollback size and cap the returned bytes (consistent with
2089
+ // report-file caps) — lines comes straight from the model.
2090
+ const lines = Math.min(Math.max(Math.trunc(params.lines ?? 120), 1), 1000);
2091
+ const res = await herdrCli.exec(
2092
+ "herdr",
2093
+ ["agent", "read", name, "--source", "recent-unwrapped", "--lines", String(lines)],
2094
+ { timeout: 10_000 },
2095
+ );
2096
+ const roEntry = getHerdrRegistry().find((e) => e.name === name);
2097
+ const text = res.code === 0
2098
+ ? res.stdout.trim().slice(0, MAX_REPORT_BYTES) || (roEntry?.readOnly
2099
+ ? "(no readable output — the agent may be rendering on the alternate screen; prompt it and it will reply inline — it has read-only tools and cannot write files)"
2100
+ : "(no readable output — the agent may be rendering on the alternate screen; prompt it to write its report to a file)")
2101
+ : `herdr agent read failed: ${(res.stderr || res.stdout).trim().split("\n")[0]}`;
2102
+ return toolResult(text, res.code !== 0);
2103
+ }
2104
+ case "prompt": {
2105
+ if (!params.text) {
2106
+ return toolResult('Missing text for action "prompt".', true);
2107
+ }
2108
+ if (Buffer.byteLength(params.text, "utf8") > HERDR_TASK_BUDGET) {
2109
+ return toolResult(`Prompt exceeds the ${HERDR_TASK_BUDGET}-byte budget (argv ceiling incl. delivery wrapper) — shorten it.`, true);
2110
+ }
2111
+ const entry = getHerdrRegistry().find((e) => e.name === name);
2112
+ // Delegated agents keep the delivery contract on follow-ups too
2113
+ // (report file — or inline reply for read-only children).
2114
+ const text = entry ? wrapTaskPrompt(params.text, entry.resultFile, entry.readOnly) : params.text;
2115
+ if (params.wait) {
2116
+ const timeoutMs = params.timeout ?? 120_000;
2117
+ const fileStampBefore = entry
2118
+ ? await fsPromises.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "")
2119
+ : "";
2120
+ // Abortable: an aborted tool call interrupts the wait (esc to the
2121
+ // child) instead of blocking until the CLI timeout.
2122
+ const outcome = await new Promise<PromptOutcome>((resolve) => {
2123
+ let settled = false;
2124
+ const onAbort = () => {
2125
+ if (settled) return;
2126
+ settled = true;
2127
+ _signal?.removeEventListener("abort", onAbort);
2128
+ void cancelAgent(name, herdrCli.exec);
2129
+ resolve({ state: "unknown", delivered: false, error: "aborted: tool call cancelled" });
2130
+ };
2131
+ _signal?.addEventListener("abort", onAbort, { once: true });
2132
+ promptAndWait({ name, text, timeoutMs, exec: herdrCli.exec }).then((o) => {
2133
+ if (settled) return;
2134
+ settled = true;
2135
+ _signal?.removeEventListener("abort", onAbort);
2136
+ resolve(o);
2137
+ }, () => {
2138
+ if (settled) return;
2139
+ settled = true;
2140
+ _signal?.removeEventListener("abort", onAbort);
2141
+ resolve({ state: "unknown", delivered: false, error: "herdr agent prompt failed" });
2142
+ });
2143
+ });
2144
+ if (outcome.error) {
2145
+ return toolResult(`${name}: ${outcome.error} (state: ${outcome.state})`, true);
2146
+ }
2147
+ let output = "";
2148
+ if (entry) {
2149
+ const collected = await collectResult({ handle: entry, exec: herdrCli.exec });
2150
+ // Follow-ups reuse the same report file: only return its content
2151
+ // if THIS prompt changed it — otherwise the previous run's report
2152
+ // would come back as the answer.
2153
+ if (collected.source === "file") {
2154
+ const stampAfter = await fsPromises.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
2155
+ if (stampAfter === fileStampBefore) {
2156
+ // Unchanged file = the previous run's report — don't return
2157
+ // it as the answer to this prompt.
2158
+ return toolResult(`${name}: ${outcome.state} (no new report file content for this follow-up)`);
2159
+ }
2160
+ output = collected.output;
2161
+ } else {
2162
+ output = collected.output;
2163
+ }
2164
+ }
2165
+ return toolResult(`${name}: ${outcome.state}${output ? `\n\n${output}` : ""}`);
2166
+ }
2167
+ const res = await herdrCli.exec("herdr", ["agent", "prompt", name, text], { timeout: 15_000 });
2168
+ return toolResult(
2169
+ res.code === 0 ? `Prompt submitted to ${name}.` : `herdr agent prompt failed: ${(res.stderr || res.stdout).trim().split("\n")[0]}`,
2170
+ res.code !== 0,
2171
+ );
2172
+ }
2173
+ case "cancel": {
2174
+ await cancelAgent(name, herdrCli.exec);
2175
+ return toolResult(`Sent esc to ${name} (plus ctrl+c if it was still working).`);
2176
+ }
2177
+ case "focus": {
2178
+ const tabId = getHerdrRegistry().find((e) => e.name === name)?.tabId
2179
+ ?? (await getAgentInfo(name, herdrCli.exec))?.tabId;
2180
+ if (!tabId) {
2181
+ return toolResult(`No herdr agent named "${name}".`, true);
2182
+ }
2183
+ const res = await herdrCli.exec("herdr", ["tab", "focus", tabId], { timeout: 10_000 });
2184
+ return toolResult(
2185
+ res.code === 0 ? `Focused tab ${tabId}.` : `herdr tab focus failed: ${(res.stderr || res.stdout).trim().split("\n")[0]}`,
2186
+ res.code !== 0,
2187
+ );
2188
+ }
2189
+ case "close-tab": {
2190
+ const entry = getHerdrRegistry().find((e) => e.name === name);
2191
+ if (!entry) {
2192
+ return toolResult(`"${name}" was not delegated by this session — refusing to close tabs this session did not create. If this pane predates a /reload-runtime, close it manually (herdr tab close <tabId>; tab id via herdr status).`, true);
2193
+ }
2194
+ if (!canCloseHerdrTab(name)) {
2195
+ return toolResult(`"${name}" runs in a tab that existed before this session dispatched to it (label match) — reusing it for dispatch, but refusing to close it.`, true);
2196
+ }
2197
+ // Same-type agents share one tab: closing it kills every pane in it,
2198
+ // so refuse while the named agent or a sibling is still doing work.
2199
+ const live = await listHerdrAgents(herdrCli.exec);
2200
+ const stateByPane = new Map(live.filter((a) => a.paneId).map((a) => [a.paneId!, a.status]));
2201
+ const { siblings: busy, self: selfBusy } = herdrTabCloseBlockers(name, stateByPane);
2202
+ if (busy.length > 0) {
2203
+ return toolResult(`Refusing to close tab ${entry.tabId}: sibling agent(s) still busy or unverifiable: ${busy.join(", ")}. Cancel them first (herdr action "cancel") or wait until they settle.`, true);
2204
+ }
2205
+ if (selfBusy) {
2206
+ return toolResult(`"${name}" is still ${selfBusy} — cancel it first (herdr action "cancel") or wait for it to settle before closing its tab.`, true);
2207
+ }
2208
+ const res = await herdrCli.exec("herdr", ["tab", "close", entry.tabId], { timeout: 10_000 });
2209
+ if (res.code !== 0) {
2210
+ return toolResult(`herdr tab close failed: ${(res.stderr || res.stdout).trim().split("\n")[0]}`, true);
2211
+ }
2212
+ forgetHerdrTab(entry.tabId);
2213
+ return toolResult(`Closed tab ${entry.tabId} (all ${entry.agentType} panes in it).`);
2214
+ }
2215
+ case "forget": {
2216
+ // Registry hygiene: drops a stale entry (e.g. its tab was closed
2217
+ // outside this session). Never touches herdr state.
2218
+ if (!isDelegatedHerdrAgent(name)) {
2219
+ return toolResult(`"${name}" was not delegated by this session — nothing to forget.`, true);
2220
+ }
2221
+ forgetHerdrAgent(name);
2222
+ return toolResult(`Forgot ${name} (registry entry only — herdr panes/tabs untouched).`);
2223
+ }
2224
+ }
2225
+ },
2226
+ });
2227
+ // /agent command — switch between subagent threads.
2228
+ // When a thread is selected, the viewer replaces the main TUI (not overlay).
2229
+ pi.registerCommand("agent", {
2230
+ description: "Switch to a subagent thread to view its work in isolation",
2231
+ handler: async (_args, ctx) => {
2232
+ // Show picker overlay
2233
+ const selectedId = await showAgentPicker(ctx, buildPickerItems(threadStore.getAllThreads()));
2234
+ if (!selectedId) return; // Cancelled — stay in current view
2235
+
2236
+ // Main selected — close viewer if active, return to conversation
2237
+ if (selectedId === "__main__") {
2238
+ if (activeViewerDone) {
2239
+ activeViewerDone();
2240
+ activeViewerDone = null;
2241
+ }
2242
+ return;
2243
+ }
2244
+
2245
+ // Close existing viewer (if any) before opening new one
2246
+ if (activeViewerDone) {
2247
+ activeViewerDone();
2248
+ activeViewerDone = null;
2249
+ }
2250
+
2251
+ // Show thread viewer (re-resolve against current store)
2252
+ const freshThreads = threadStore.getAllThreads();
2253
+ const idx = freshThreads.findIndex((t) => t.id === selectedId);
2254
+ if (idx === -1) {
2255
+ ctx.ui.notify("Selected subagent thread no longer exists.", "warning");
2256
+ return;
2257
+ }
2258
+
2259
+ await showThreadViewer(ctx, freshThreads, idx);
2260
+ },
2261
+ });
2262
+
2263
+ // ---------------------------------------------------------------------------
2264
+ // Module-level viewer state (so /agent can close an active viewer)
2265
+ // ---------------------------------------------------------------------------
2266
+ let activeViewerDone: (() => void) | null = null;
2267
+
2268
+ // ---------------------------------------------------------------------------
2269
+ // Picker helpers (shared between /agent handler and Ctrl+P in viewer)
2270
+ // ---------------------------------------------------------------------------
2271
+
2272
+ interface PickerItem { value: string; label: string; description: string }
2273
+
2274
+ function buildPickerItems(threads: SubagentThread[]): PickerItem[] {
2275
+ const items: PickerItem[] = [
2276
+ { value: "__main__", label: "Main [default]", description: "(current)" },
2277
+ ];
2278
+ for (const t of threads) {
2279
+ let statusIcon: string;
2280
+ switch (t.status) {
2281
+ case "running": statusIcon = "⏳"; break;
2282
+ case "completed": statusIcon = "✓"; break;
2283
+ case "failed": statusIcon = "✗"; break;
2284
+ case "aborted": statusIcon = "✗"; break;
2285
+ }
2286
+ let modeTag = "";
2287
+ if (t.mode === "parallel-task") modeTag = " [parallel]";
2288
+ else if (t.mode === "chain-step") modeTag = " [chain]";
2289
+ const label = `${statusIcon} ${t.agentName}${modeTag}`;
2290
+ const desc = t.task.length > 60 ? `${t.task.slice(0, 57)}...` : t.task;
2291
+ items.push({ value: t.id, label, description: desc });
2292
+ }
2293
+ return items;
2294
+ }
2295
+
2296
+ async function showAgentPicker(
2297
+ ctx: { ui: { custom: <T>(factory: any, opts?: any) => Promise<T> } },
2298
+ items: PickerItem[],
2299
+ ): Promise<string | null> {
2300
+ return ctx.ui.custom<string | null>((tui: any, theme: any, _kb: any, done: (value: string | null) => void) => {
2301
+ const container = new Container();
2302
+ container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
2303
+ container.addChild(new Text(theme.fg("accent", theme.bold("Subagents")), 1, 0));
2304
+ container.addChild(new Text(theme.fg("dim", "⌥ + ← previous, ⌥ + → next."), 1, 0));
2305
+
2306
+ const selectList = new SelectList(
2307
+ items.map((it) => ({ value: it.value, label: it.label, description: it.description })),
2308
+ Math.min(items.length + 2, 15),
2309
+ {
2310
+ selectedPrefix: (t: string) => theme.fg("accent", t),
2311
+ selectedText: (t: string) => theme.fg("accent", t),
2312
+ description: (t: string) => theme.fg("muted", t),
2313
+ scrollInfo: (t: string) => theme.fg("dim", t),
2314
+ noMatch: (t: string) => theme.fg("warning", t),
2315
+ },
2316
+ );
2317
+ selectList.onSelect = (item) => done(item.value);
2318
+ selectList.onCancel = () => done(null);
2319
+ container.addChild(selectList);
2320
+
2321
+ container.addChild(new Text(
2322
+ `${theme.fg("dim", "↑↓ navigate · enter select · esc back")}`,
2323
+ 1, 0,
2324
+ ));
2325
+
2326
+ container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
2327
+
2328
+ return {
2329
+ render: (w: number) => container.render(w),
2330
+ invalidate: () => container.invalidate(),
2331
+ handleInput: (data: string) => { selectList.handleInput(data); tui.requestRender(); },
2332
+ };
2333
+ }, { overlay: true });
2334
+ }
2335
+
2336
+ // Helper: show thread viewer as overlay so editor remains visible.
2337
+ // Uses dynamic thread list + store subscriptions for live progress.
2338
+ // Ctrl+P opens picker overlay to jump to any thread.
2339
+ async function showThreadViewer(
2340
+ ctx: { ui: { custom: <T>(factory: any, opts?: any) => Promise<T> } },
2341
+ _threads: SubagentThread[],
2342
+ startIndex: number,
2343
+ ): Promise<void> {
2344
+ let currentIndex = startIndex;
2345
+
2346
+ // Resolve thread list dynamically
2347
+ const getThreads = () => threadStore.getAllThreads();
2348
+
2349
+ // Overlay mode: viewer appears above editor, Esc dismisses
2350
+ await ctx.ui.custom<void>((tui: any, theme: any, _kb: any, done: () => void) => {
2351
+ let unsubscribe: (() => void) | undefined;
2352
+ let closed = false;
2353
+
2354
+ const cleanup = () => {
2355
+ if (unsubscribe) {
2356
+ unsubscribe();
2357
+ unsubscribe = undefined;
2358
+ }
2359
+ };
2360
+
2361
+ const close = () => {
2362
+ if (closed) return;
2363
+ closed = true;
2364
+ cleanup();
2365
+ activeViewerDone = null;
2366
+ done();
2367
+ };
2368
+
2369
+ // Track this viewer so /agent can close it before opening a new one
2370
+ activeViewerDone = close;
2371
+
2372
+ function makeCallbacks(): ThreadViewerCallbacks {
2373
+ const list = getThreads();
2374
+ return {
2375
+ onClose: close,
2376
+ onPrev: () => {
2377
+ const current = getThreads();
2378
+ if (currentIndex > 0) {
2379
+ currentIndex--;
2380
+ viewer.setThread(current[currentIndex], makeCallbacks());
2381
+ tui.requestRender();
2382
+ }
2383
+ },
2384
+ onNext: () => {
2385
+ const current = getThreads();
2386
+ if (currentIndex < current.length - 1) {
2387
+ currentIndex++;
2388
+ viewer.setThread(current[currentIndex], makeCallbacks());
2389
+ tui.requestRender();
2390
+ }
2391
+ },
2392
+ hasPrev: currentIndex > 0,
2393
+ hasNext: currentIndex < list.length - 1,
2394
+ };
2395
+ }
2396
+
2397
+ const list = getThreads();
2398
+ if (list.length === 0 || currentIndex < 0 || currentIndex >= list.length) {
2399
+ close();
2400
+ return {
2401
+ render: (_w: number) => [],
2402
+ invalidate: () => {},
2403
+ handleInput: (_data: string) => {},
2404
+ dispose: () => {
2405
+ cleanup();
2406
+ if (activeViewerDone === close) activeViewerDone = null;
2407
+ closed = true;
2408
+ },
2409
+ };
2410
+ }
2411
+
2412
+ const viewer = new ThreadViewer(list[currentIndex], makeCallbacks(), theme);
2413
+ let pickerOpen = false;
2414
+
2415
+ // Subscribe to thread store for live updates (after viewer is created)
2416
+ unsubscribe = threadStore.subscribe(() => {
2417
+ const current = getThreads();
2418
+ if (current.length === 0) {
2419
+ close();
2420
+ return;
2421
+ }
2422
+ currentIndex = Math.min(currentIndex, current.length - 1);
2423
+ viewer.setThread(current[currentIndex], makeCallbacks());
2424
+ tui.requestRender();
2425
+ });
2426
+
2427
+ return {
2428
+ render: (w: number) => viewer.render(w),
2429
+ invalidate: () => viewer.invalidate(),
2430
+ handleInput: (data: string) => {
2431
+ // Ctrl+P opens the picker to jump between threads
2432
+ if (data === "\x10") {
2433
+ if (!pickerOpen) {
2434
+ pickerOpen = true;
2435
+ openThreadPicker().finally(() => { pickerOpen = false; });
2436
+ }
2437
+ return;
2438
+ }
2439
+ viewer.handleInput(data);
2440
+ tui.requestRender();
2441
+ },
2442
+ dispose: () => {
2443
+ cleanup();
2444
+ if (activeViewerDone === close) activeViewerDone = null;
2445
+ closed = true;
2446
+ },
2447
+ };
2448
+
2449
+ // Opens picker overlay on top of viewer to jump to any thread
2450
+ async function openThreadPicker() {
2451
+ const items = buildPickerItems(getThreads());
2452
+ const selectedId = await showAgentPicker(ctx, items);
2453
+ if (!selectedId) return;
2454
+ if (selectedId === "__main__") { close(); return; }
2455
+ const idx = getThreads().findIndex((t) => t.id === selectedId);
2456
+ if (idx >= 0) {
2457
+ currentIndex = idx;
2458
+ viewer.setThread(getThreads()[currentIndex], makeCallbacks());
2459
+ tui.requestRender();
2460
+ }
2461
+ }
2462
+ }, { overlay: true, overlayOptions: { maxHeight: "70%" } }); // Overlay: editor stays visible below
2463
+ }
2464
+ }