@xzzpig/pi-subagents 0.22.0 → 0.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1138) hide show
  1. package/CHANGELOG.md +355 -0
  2. package/README.md +2 -2
  3. package/agents/evidence-auditor.md +1 -0
  4. package/agents/oracle.md +1 -0
  5. package/agents/reviewer.md +1 -0
  6. package/bundle/agent-management.js +16 -0
  7. package/bundle/agents.js +41 -0
  8. package/bundle/background-work.js +16 -0
  9. package/bundle/capability-ceiling.js +22 -0
  10. package/bundle/child-tool-plan.js +11 -0
  11. package/bundle/chunk-355ECEP2.js +1321 -0
  12. package/bundle/chunk-35GII5EF.js +637 -0
  13. package/bundle/chunk-3U633XDZ.js +749 -0
  14. package/bundle/chunk-4QFZZV3O.js +57 -0
  15. package/bundle/chunk-62OCY2S4.js +14 -0
  16. package/bundle/chunk-6BJUEES3.js +276 -0
  17. package/bundle/chunk-7J4ZXMY7.js +18 -0
  18. package/bundle/chunk-BGIYHF2W.js +138 -0
  19. package/bundle/chunk-CTPAE36Y.js +94 -0
  20. package/bundle/chunk-D4EHT5SJ.js +14 -0
  21. package/bundle/chunk-ED55MIC2.js +1681 -0
  22. package/bundle/chunk-EUPJB4S7.js +5503 -0
  23. package/bundle/chunk-FG6SQJAR.js +940 -0
  24. package/bundle/chunk-FJWI64H7.js +490 -0
  25. package/bundle/chunk-H36HBZB2.js +753 -0
  26. package/bundle/chunk-ICNYIALB.js +7347 -0
  27. package/bundle/chunk-JEA2ZKUA.js +1372 -0
  28. package/bundle/chunk-LCDJWBVM.js +57 -0
  29. package/bundle/chunk-LMGQAJ3O.js +9872 -0
  30. package/bundle/chunk-LVWU2HOO.js +1234 -0
  31. package/bundle/chunk-NIXWDZZV.js +9 -0
  32. package/bundle/chunk-QXASAHIA.js +173 -0
  33. package/bundle/chunk-RB4GELQA.js +458 -0
  34. package/bundle/chunk-RU522D5W.js +1768 -0
  35. package/bundle/chunk-SLNMBXLL.js +7336 -0
  36. package/bundle/chunk-SW2VMNIU.js +526 -0
  37. package/bundle/chunk-TGLFTQWJ.js +143 -0
  38. package/bundle/chunk-TMHVDPYW.js +4132 -0
  39. package/bundle/chunk-U4ODUYAG.js +235 -0
  40. package/bundle/chunk-UKG4V45O.js +228 -0
  41. package/bundle/chunk-UQDHXMUG.js +264 -0
  42. package/bundle/chunk-V2KFIGFH.js +8774 -0
  43. package/bundle/chunk-VO3G7HI3.js +85 -0
  44. package/bundle/chunk-WPW4V6HM.js +227 -0
  45. package/bundle/chunk-WW76JRIX.js +175 -0
  46. package/bundle/chunk-X6LOM3Z4.js +4175 -0
  47. package/bundle/chunk-XA3DY6UG.js +161 -0
  48. package/bundle/chunk-Y6H2G6KX.js +1310 -0
  49. package/bundle/chunk-YFCK7H2S.js +129 -0
  50. package/bundle/chunk-YYREO77V.js +137 -0
  51. package/bundle/chunk-Z6TFJ6BR.js +400 -0
  52. package/bundle/chunk-ZWXU5SPQ.js +16932 -0
  53. package/bundle/control-channel.js +11 -0
  54. package/bundle/delegation.js +14 -0
  55. package/bundle/external-job-provider.js +20 -0
  56. package/bundle/external-runs.js +21 -0
  57. package/bundle/index.js +30 -0
  58. package/bundle/inspectors.js +8 -0
  59. package/bundle/intercom-bridge.js +11 -0
  60. package/bundle/preflight.js +468 -0
  61. package/bundle/project-panes.js +28 -0
  62. package/bundle/required-child-extensions.js +6 -0
  63. package/bundle/shared-types.js +8 -0
  64. package/bundle/supervisor-routing.js +12 -0
  65. package/bundle/workflow-resources.js +7 -0
  66. package/docs/agents.md +42 -10
  67. package/docs/configuration.md +59 -14
  68. package/docs/extension-api.md +61 -9
  69. package/docs/goal-auto-continuation-gate.md +26 -0
  70. package/docs/missions.md +2 -0
  71. package/docs/observability.md +20 -5
  72. package/docs/standalone-background.md +8 -6
  73. package/docs/tool-reference.md +18 -5
  74. package/docs/workflows.md +25 -7
  75. package/index.d.ts +3 -0
  76. package/index.js +14 -0
  77. package/node_modules/@xzzpig/pi-components/package.json +1 -2
  78. package/package.json +107 -87
  79. package/skills/council-mode/SKILL.md +1 -4
  80. package/skills/pi-subagents/SKILL.md +130 -106
  81. package/skills/pi-subagents/references/orchestration.md +124 -0
  82. package/skills/pi-subagents/references/prompting-and-roles.md +96 -291
  83. package/src/agents/advertised-agent-prompt.d.ts +13 -0
  84. package/src/agents/advertised-agent-prompt.js +68 -0
  85. package/src/agents/agent-eject.d.ts +39 -0
  86. package/src/agents/agent-eject.js +263 -0
  87. package/src/agents/agent-management.d.ts +33 -0
  88. package/src/agents/agent-management.js +1541 -0
  89. package/src/agents/agent-memory.d.ts +48 -0
  90. package/src/agents/agent-memory.js +350 -0
  91. package/src/agents/agent-refinements.d.ts +99 -0
  92. package/src/agents/agent-refinements.js +568 -0
  93. package/src/agents/agent-scope.d.ts +3 -0
  94. package/src/agents/agent-scope.js +8 -0
  95. package/src/agents/agent-selection.d.ts +2 -0
  96. package/src/agents/agent-selection.js +22 -0
  97. package/src/agents/agent-serializer.d.ts +7 -0
  98. package/src/agents/agent-serializer.js +213 -0
  99. package/src/agents/agents.d.ts +352 -0
  100. package/src/agents/agents.js +2817 -0
  101. package/src/agents/builtin-names.d.ts +1 -0
  102. package/src/agents/builtin-names.js +16 -0
  103. package/src/agents/chain-serializer.d.ts +6 -0
  104. package/src/agents/chain-serializer.js +318 -0
  105. package/src/agents/frontmatter.d.ts +19 -0
  106. package/src/agents/frontmatter.js +166 -0
  107. package/src/agents/global-npm-root.d.ts +6 -0
  108. package/src/agents/global-npm-root.js +57 -0
  109. package/src/agents/identity.d.ts +7 -0
  110. package/src/agents/identity.js +29 -0
  111. package/src/agents/proactive-skills.d.ts +35 -0
  112. package/src/agents/proactive-skills.js +155 -0
  113. package/src/agents/runtime-agent-events.d.ts +26 -0
  114. package/src/agents/runtime-agent-events.js +52 -0
  115. package/src/agents/runtime-agent-registry.d.ts +66 -0
  116. package/src/agents/runtime-agent-registry.js +415 -0
  117. package/src/agents/runtime-discovery.d.ts +13 -0
  118. package/src/agents/runtime-discovery.js +27 -0
  119. package/src/agents/skills.d.ts +34 -0
  120. package/src/agents/skills.js +718 -0
  121. package/src/api/agent-management.d.ts +2 -0
  122. package/src/api/agent-management.js +2 -0
  123. package/src/api/agents.d.ts +6 -0
  124. package/src/api/agents.js +3 -0
  125. package/src/api/background-work.d.ts +41 -0
  126. package/src/api/background-work.js +171 -0
  127. package/src/api/capability-ceiling.d.ts +1 -0
  128. package/src/api/capability-ceiling.js +1 -0
  129. package/src/api/child-tool-plan.d.ts +1 -0
  130. package/src/api/child-tool-plan.js +1 -0
  131. package/src/api/control-channel.d.ts +1 -0
  132. package/src/api/control-channel.js +1 -0
  133. package/src/api/delegation.d.ts +132 -0
  134. package/src/api/delegation.js +8 -0
  135. package/src/api/external-job-provider.d.ts +57 -0
  136. package/src/api/external-job-provider.js +139 -0
  137. package/src/api/external-runs.d.ts +47 -0
  138. package/src/api/external-runs.js +245 -0
  139. package/src/api/inspectors.d.ts +20 -0
  140. package/src/api/inspectors.js +11 -0
  141. package/src/api/intercom-bridge.d.ts +1 -0
  142. package/src/api/intercom-bridge.js +1 -0
  143. package/src/api/preflight.d.ts +183 -0
  144. package/src/api/preflight.js +455 -0
  145. package/src/api/project-panes.d.ts +7 -0
  146. package/src/api/project-panes.js +7 -0
  147. package/src/api/required-child-extensions.d.ts +1 -0
  148. package/src/api/required-child-extensions.js +1 -0
  149. package/src/api/shared-types.d.ts +1 -0
  150. package/src/api/shared-types.js +1 -0
  151. package/src/api/supervisor-routing.d.ts +110 -0
  152. package/src/api/supervisor-routing.js +95 -0
  153. package/src/api/workflow-resources.d.ts +2 -0
  154. package/src/api/workflow-resources.js +1 -0
  155. package/src/extension/active-runs-prompt.d.ts +7 -0
  156. package/src/extension/active-runs-prompt.js +29 -0
  157. package/src/extension/config.d.ts +7 -0
  158. package/src/extension/config.js +290 -0
  159. package/src/extension/context-injection.d.ts +52 -0
  160. package/src/extension/context-injection.js +102 -0
  161. package/src/extension/control-notices.d.ts +18 -0
  162. package/src/extension/control-notices.js +29 -0
  163. package/src/extension/declaration-pinning.d.ts +18 -0
  164. package/src/extension/declaration-pinning.js +167 -0
  165. package/src/extension/doctor.d.ts +34 -0
  166. package/src/extension/doctor.js +236 -0
  167. package/src/extension/fanout-child.d.ts +6 -0
  168. package/src/extension/fanout-child.js +278 -0
  169. package/src/extension/herdr-pi-bridge.d.ts +16 -0
  170. package/src/extension/herdr-pi-bridge.js +261 -0
  171. package/src/extension/index.d.ts +18 -0
  172. package/src/extension/index.js +1300 -0
  173. package/src/extension/public-execution.d.ts +71 -0
  174. package/src/extension/public-execution.js +214 -0
  175. package/src/extension/reply-workflow-script.d.ts +11 -0
  176. package/src/extension/reply-workflow-script.js +71 -0
  177. package/src/extension/rpc.d.ts +84 -0
  178. package/src/extension/rpc.js +729 -0
  179. package/src/extension/schemas.d.ts +276 -0
  180. package/src/extension/schemas.js +311 -0
  181. package/src/extension/steering-notices.d.ts +14 -0
  182. package/src/extension/steering-notices.js +22 -0
  183. package/src/extension/subagent-guide.d.ts +4 -0
  184. package/src/extension/subagent-guide.js +114 -0
  185. package/src/extension/subagent-options.d.ts +7 -0
  186. package/src/extension/subagent-options.js +64 -0
  187. package/src/extension/tool-activation.d.ts +7 -0
  188. package/src/extension/tool-activation.js +185 -0
  189. package/src/extension/tool-description.d.ts +19 -0
  190. package/src/extension/tool-description.js +169 -0
  191. package/src/extension/tool-result.d.ts +9 -0
  192. package/src/extension/tool-result.js +16 -0
  193. package/src/extension/upgrade-notice.d.ts +6 -0
  194. package/src/extension/upgrade-notice.js +42 -0
  195. package/src/goal-auto-continue-gate.d.ts +17 -0
  196. package/src/goal-auto-continue-gate.js +61 -0
  197. package/src/goal-auto-continue-state.d.ts +22 -0
  198. package/src/goal-auto-continue-state.js +20 -0
  199. package/src/inspectors/actions.d.ts +24 -0
  200. package/src/inspectors/actions.js +182 -0
  201. package/src/inspectors/ghostty/actions.d.ts +11 -0
  202. package/src/inspectors/ghostty/actions.js +62 -0
  203. package/src/inspectors/ghostty/plugin.d.ts +7 -0
  204. package/src/inspectors/ghostty/plugin.js +23 -0
  205. package/src/inspectors/herdr/actions.d.ts +25 -0
  206. package/src/inspectors/herdr/actions.js +133 -0
  207. package/src/inspectors/herdr/client.d.ts +41 -0
  208. package/src/inspectors/herdr/client.js +129 -0
  209. package/src/inspectors/herdr/focus.d.ts +24 -0
  210. package/src/inspectors/herdr/focus.js +49 -0
  211. package/src/inspectors/herdr/plugin.d.ts +6 -0
  212. package/src/inspectors/herdr/plugin.js +14 -0
  213. package/src/inspectors/herdr/project-panes.d.ts +136 -0
  214. package/src/inspectors/herdr/project-panes.js +610 -0
  215. package/src/inspectors/inspector-runner.d.ts +23 -0
  216. package/src/inspectors/inspector-runner.js +161 -0
  217. package/src/inspectors/plugins.d.ts +8 -0
  218. package/src/inspectors/plugins.js +82 -0
  219. package/src/inspectors/session-roots-codec.d.ts +15 -0
  220. package/src/inspectors/session-roots-codec.js +32 -0
  221. package/src/inspectors/shell-command.d.ts +1 -0
  222. package/src/inspectors/shell-command.js +16 -0
  223. package/src/inspectors/tmux/actions.d.ts +25 -0
  224. package/src/inspectors/tmux/actions.js +181 -0
  225. package/src/inspectors/tmux/client.d.ts +27 -0
  226. package/src/inspectors/tmux/client.js +64 -0
  227. package/src/inspectors/tmux/plugin.d.ts +7 -0
  228. package/src/inspectors/tmux/plugin.js +14 -0
  229. package/src/inspectors/types.d.ts +48 -0
  230. package/src/inspectors/types.js +1 -0
  231. package/src/integrations/herdr-status.d.ts +47 -0
  232. package/src/integrations/herdr-status.js +350 -0
  233. package/src/integrations/pi-web-session-liveness.d.ts +19 -0
  234. package/src/integrations/pi-web-session-liveness.js +53 -0
  235. package/src/integrations/program-status.d.ts +30 -0
  236. package/src/integrations/program-status.js +188 -0
  237. package/src/intercom/fork-supervisor-routing.d.ts +90 -0
  238. package/src/intercom/fork-supervisor-routing.js +392 -0
  239. package/src/intercom/intercom-bridge.d.ts +58 -0
  240. package/src/intercom/intercom-bridge.js +193 -0
  241. package/src/intercom/native-supervisor-channel.d.ts +97 -0
  242. package/src/intercom/native-supervisor-channel.js +1184 -0
  243. package/src/intercom/result-intercom.d.ts +35 -0
  244. package/src/intercom/result-intercom.js +376 -0
  245. package/src/intercom/supervisor-ui.d.ts +29 -0
  246. package/src/intercom/supervisor-ui.js +49 -0
  247. package/src/missions/actions.d.ts +54 -0
  248. package/src/missions/actions.js +400 -0
  249. package/src/missions/goal-driver.d.ts +16 -0
  250. package/src/missions/goal-driver.js +171 -0
  251. package/src/missions/lifecycle.d.ts +50 -0
  252. package/src/missions/lifecycle.js +388 -0
  253. package/src/missions/store.d.ts +21 -0
  254. package/src/missions/store.js +605 -0
  255. package/src/missions/types.d.ts +169 -0
  256. package/src/missions/types.js +9 -0
  257. package/src/missions/workflow-state.d.ts +14 -0
  258. package/src/missions/workflow-state.js +273 -0
  259. package/src/policy/authority.d.ts +9 -0
  260. package/src/policy/authority.js +41 -0
  261. package/src/profiles/profiles.d.ts +134 -0
  262. package/src/profiles/profiles.js +526 -0
  263. package/src/runs/background/active-async-capacity.d.ts +115 -0
  264. package/src/runs/background/active-async-capacity.js +517 -0
  265. package/src/runs/background/active-run-index.d.ts +12 -0
  266. package/src/runs/background/active-run-index.js +157 -0
  267. package/src/runs/background/async-execution.d.ts +306 -0
  268. package/src/runs/background/async-execution.js +2210 -0
  269. package/src/runs/background/async-job-tracker.d.ts +37 -0
  270. package/src/runs/background/async-job-tracker.js +926 -0
  271. package/src/runs/background/async-resume.d.ts +60 -0
  272. package/src/runs/background/async-resume.js +707 -0
  273. package/src/runs/background/async-retention.d.ts +45 -0
  274. package/src/runs/background/async-retention.js +932 -0
  275. package/src/runs/background/async-status-snapshot.d.ts +9 -0
  276. package/src/runs/background/async-status-snapshot.js +26 -0
  277. package/src/runs/background/async-status.d.ts +179 -0
  278. package/src/runs/background/async-status.js +712 -0
  279. package/src/runs/background/auto-drain.d.ts +16 -0
  280. package/src/runs/background/auto-drain.js +71 -0
  281. package/src/runs/background/await-async-run.d.ts +26 -0
  282. package/src/runs/background/await-async-run.js +83 -0
  283. package/src/runs/background/binary-bootstrap.d.ts +8 -0
  284. package/src/runs/background/binary-bootstrap.js +69 -0
  285. package/src/runs/background/boot-id.d.ts +12 -0
  286. package/src/runs/background/boot-id.js +47 -0
  287. package/src/runs/background/calendar-schedule.d.ts +26 -0
  288. package/src/runs/background/calendar-schedule.js +93 -0
  289. package/src/runs/background/chain-append.d.ts +34 -0
  290. package/src/runs/background/chain-append.js +299 -0
  291. package/src/runs/background/chain-root-attachment.d.ts +51 -0
  292. package/src/runs/background/chain-root-attachment.js +186 -0
  293. package/src/runs/background/completion-batcher.d.ts +51 -0
  294. package/src/runs/background/completion-batcher.js +119 -0
  295. package/src/runs/background/completion-dedupe.d.ts +13 -0
  296. package/src/runs/background/completion-dedupe.js +48 -0
  297. package/src/runs/background/completion-replay.d.ts +47 -0
  298. package/src/runs/background/completion-replay.js +266 -0
  299. package/src/runs/background/control-channel.d.ts +170 -0
  300. package/src/runs/background/control-channel.js +610 -0
  301. package/src/runs/background/fleet-view.d.ts +63 -0
  302. package/src/runs/background/fleet-view.js +666 -0
  303. package/src/runs/background/index-segment.d.ts +16 -0
  304. package/src/runs/background/index-segment.js +58 -0
  305. package/src/runs/background/inspect-rpc.d.ts +64 -0
  306. package/src/runs/background/inspect-rpc.js +422 -0
  307. package/src/runs/background/interrupted-elsewhere.d.ts +22 -0
  308. package/src/runs/background/interrupted-elsewhere.js +68 -0
  309. package/src/runs/background/notify.d.ts +216 -0
  310. package/src/runs/background/notify.js +1006 -0
  311. package/src/runs/background/owned-process-tree.d.ts +10 -0
  312. package/src/runs/background/owned-process-tree.js +116 -0
  313. package/src/runs/background/parallel-groups.d.ts +3 -0
  314. package/src/runs/background/parallel-groups.js +46 -0
  315. package/src/runs/background/pid-namespace.d.ts +2 -0
  316. package/src/runs/background/pid-namespace.js +19 -0
  317. package/src/runs/background/process-terminal-candidate.d.ts +17 -0
  318. package/src/runs/background/process-terminal-candidate.js +96 -0
  319. package/src/runs/background/process-terminal.d.ts +21 -0
  320. package/src/runs/background/process-terminal.js +227 -0
  321. package/src/runs/background/result-delivery-ownership.d.ts +14 -0
  322. package/src/runs/background/result-delivery-ownership.js +38 -0
  323. package/src/runs/background/result-files.d.ts +63 -0
  324. package/src/runs/background/result-files.js +629 -0
  325. package/src/runs/background/result-watcher.d.ts +92 -0
  326. package/src/runs/background/result-watcher.js +819 -0
  327. package/src/runs/background/resume-guidance.d.ts +4 -0
  328. package/src/runs/background/resume-guidance.js +57 -0
  329. package/src/runs/background/retained-children.d.ts +24 -0
  330. package/src/runs/background/retained-children.js +128 -0
  331. package/src/runs/background/retained-nested-route-tracker.d.ts +12 -0
  332. package/src/runs/background/retained-nested-route-tracker.js +90 -0
  333. package/src/runs/background/run-child-session.d.ts +123 -0
  334. package/src/runs/background/run-child-session.js +670 -0
  335. package/src/runs/background/run-id-query.d.ts +3 -0
  336. package/src/runs/background/run-id-query.js +6 -0
  337. package/src/runs/background/run-id-resolver.d.ts +22 -0
  338. package/src/runs/background/run-id-resolver.js +172 -0
  339. package/src/runs/background/run-status.d.ts +25 -0
  340. package/src/runs/background/run-status.js +850 -0
  341. package/src/runs/background/runner-aliases.d.ts +17 -0
  342. package/src/runs/background/runner-aliases.js +191 -0
  343. package/src/runs/background/runner-child-launch.d.ts +24 -0
  344. package/src/runs/background/runner-child-launch.js +72 -0
  345. package/src/runs/background/runner-child-sessions.d.ts +6 -0
  346. package/src/runs/background/runner-child-sessions.js +34 -0
  347. package/src/runs/background/runner-http-dispatcher.d.ts +45 -0
  348. package/src/runs/background/runner-http-dispatcher.js +115 -0
  349. package/src/runs/background/runner-startup-failure.d.ts +13 -0
  350. package/src/runs/background/runner-startup-failure.js +46 -0
  351. package/src/runs/background/scheduled-runs.d.ts +127 -0
  352. package/src/runs/background/scheduled-runs.js +1265 -0
  353. package/src/runs/background/stale-run-reconciler.d.ts +62 -0
  354. package/src/runs/background/stale-run-reconciler.js +509 -0
  355. package/src/runs/background/steering.d.ts +51 -0
  356. package/src/runs/background/steering.js +246 -0
  357. package/src/runs/background/subagent-runner-bootstrap.d.ts +13 -0
  358. package/src/runs/background/subagent-runner-bootstrap.js +283 -0
  359. package/src/runs/background/subagent-runner.d.ts +210 -0
  360. package/src/runs/background/subagent-runner.js +4963 -0
  361. package/src/runs/background/subagent-wait.d.ts +124 -0
  362. package/src/runs/background/subagent-wait.js +756 -0
  363. package/src/runs/background/terminal-run-index.d.ts +10 -0
  364. package/src/runs/background/terminal-run-index.js +209 -0
  365. package/src/runs/background/top-level-async.d.ts +7 -0
  366. package/src/runs/background/top-level-async.js +5 -0
  367. package/src/runs/background/wait-completions.d.ts +28 -0
  368. package/src/runs/background/wait-completions.js +264 -0
  369. package/src/runs/background/wait-config.d.ts +8 -0
  370. package/src/runs/background/wait-config.js +46 -0
  371. package/src/runs/background/wait-subscriptions.d.ts +26 -0
  372. package/src/runs/background/wait-subscriptions.js +339 -0
  373. package/src/runs/background/wait-tool.d.ts +6 -0
  374. package/src/runs/background/wait-tool.js +48 -0
  375. package/src/runs/background/workflow-terminal-proof.d.ts +47 -0
  376. package/src/runs/background/workflow-terminal-proof.js +116 -0
  377. package/src/runs/foreground/async-dismiss-action.d.ts +6 -0
  378. package/src/runs/foreground/async-dismiss-action.js +82 -0
  379. package/src/runs/foreground/async-steering-action.d.ts +31 -0
  380. package/src/runs/foreground/async-steering-action.js +294 -0
  381. package/src/runs/foreground/async-stop-action.d.ts +13 -0
  382. package/src/runs/foreground/async-stop-action.js +213 -0
  383. package/src/runs/foreground/command-action.d.ts +12 -0
  384. package/src/runs/foreground/command-action.js +38 -0
  385. package/src/runs/foreground/execution.d.ts +10 -0
  386. package/src/runs/foreground/execution.js +2322 -0
  387. package/src/runs/foreground/foreground-control.d.ts +24 -0
  388. package/src/runs/foreground/foreground-control.js +138 -0
  389. package/src/runs/foreground/foreground-history.d.ts +25 -0
  390. package/src/runs/foreground/foreground-history.js +267 -0
  391. package/src/runs/foreground/prompt-audit.d.ts +32 -0
  392. package/src/runs/foreground/prompt-audit.js +138 -0
  393. package/src/runs/foreground/subagent-executor.d.ts +316 -0
  394. package/src/runs/foreground/subagent-executor.js +7990 -0
  395. package/src/runs/foreground/workflow-detach-reconcile.d.ts +15 -0
  396. package/src/runs/foreground/workflow-detach-reconcile.js +283 -0
  397. package/src/runs/foreground/workflow-foreground-steering.d.ts +43 -0
  398. package/src/runs/foreground/workflow-foreground-steering.js +148 -0
  399. package/src/runs/shared/abort-recovery.d.ts +26 -0
  400. package/src/runs/shared/abort-recovery.js +108 -0
  401. package/src/runs/shared/acceptance.d.ts +144 -0
  402. package/src/runs/shared/acceptance.js +1616 -0
  403. package/src/runs/shared/agent-contract.d.ts +5 -0
  404. package/src/runs/shared/agent-contract.js +35 -0
  405. package/src/runs/shared/async-status-projection.d.ts +100 -0
  406. package/src/runs/shared/async-status-projection.js +566 -0
  407. package/src/runs/shared/background-process-options.d.ts +4 -0
  408. package/src/runs/shared/background-process-options.js +6 -0
  409. package/src/runs/shared/capability-ceiling.d.ts +58 -0
  410. package/src/runs/shared/capability-ceiling.js +179 -0
  411. package/src/runs/shared/chain-outputs.d.ts +18 -0
  412. package/src/runs/shared/chain-outputs.js +104 -0
  413. package/src/runs/shared/child-commands.d.ts +29 -0
  414. package/src/runs/shared/child-commands.js +254 -0
  415. package/src/runs/shared/child-hooks.d.ts +31 -0
  416. package/src/runs/shared/child-hooks.js +173 -0
  417. package/src/runs/shared/child-identity.d.ts +23 -0
  418. package/src/runs/shared/child-identity.js +40 -0
  419. package/src/runs/shared/child-launch-plan.d.ts +70 -0
  420. package/src/runs/shared/child-launch-plan.js +88 -0
  421. package/src/runs/shared/child-launch.d.ts +128 -0
  422. package/src/runs/shared/child-launch.js +262 -0
  423. package/src/runs/shared/child-lifecycle.d.ts +13 -0
  424. package/src/runs/shared/child-lifecycle.js +22 -0
  425. package/src/runs/shared/child-runtime-config.d.ts +111 -0
  426. package/src/runs/shared/child-runtime-config.js +44 -0
  427. package/src/runs/shared/child-session.d.ts +178 -0
  428. package/src/runs/shared/child-session.js +726 -0
  429. package/src/runs/shared/child-tool-plan.d.ts +101 -0
  430. package/src/runs/shared/child-tool-plan.js +430 -0
  431. package/src/runs/shared/claude-code-adapter.d.ts +80 -0
  432. package/src/runs/shared/claude-code-adapter.js +255 -0
  433. package/src/runs/shared/codex-exec-adapter.d.ts +25 -0
  434. package/src/runs/shared/codex-exec-adapter.js +127 -0
  435. package/src/runs/shared/context-mode.d.ts +12 -0
  436. package/src/runs/shared/context-mode.js +38 -0
  437. package/src/runs/shared/cursor-agent-adapter.d.ts +26 -0
  438. package/src/runs/shared/cursor-agent-adapter.js +99 -0
  439. package/src/runs/shared/dynamic-fanout.d.ts +49 -0
  440. package/src/runs/shared/dynamic-fanout.js +273 -0
  441. package/src/runs/shared/effective-system-prompt.d.ts +17 -0
  442. package/src/runs/shared/effective-system-prompt.js +23 -0
  443. package/src/runs/shared/extension-bindings.d.ts +25 -0
  444. package/src/runs/shared/extension-bindings.js +96 -0
  445. package/src/runs/shared/external-cli-contract.d.ts +29 -0
  446. package/src/runs/shared/external-cli-contract.js +145 -0
  447. package/src/runs/shared/external-cli-preflight.d.ts +41 -0
  448. package/src/runs/shared/external-cli-preflight.js +159 -0
  449. package/src/runs/shared/external-cli-runner.d.ts +65 -0
  450. package/src/runs/shared/external-cli-runner.js +425 -0
  451. package/src/runs/shared/external-job-bridge.d.ts +24 -0
  452. package/src/runs/shared/external-job-bridge.js +486 -0
  453. package/src/runs/shared/external-job-runner.d.ts +44 -0
  454. package/src/runs/shared/external-job-runner.js +352 -0
  455. package/src/runs/shared/fast-mode-extension.d.ts +3 -0
  456. package/src/runs/shared/fast-mode-extension.js +8 -0
  457. package/src/runs/shared/fork-placed-env.d.ts +4 -0
  458. package/src/runs/shared/fork-placed-env.js +13 -0
  459. package/src/runs/shared/git-environment.d.ts +2 -0
  460. package/src/runs/shared/git-environment.js +27 -0
  461. package/src/runs/shared/herdr-connection.d.ts +79 -0
  462. package/src/runs/shared/herdr-connection.js +269 -0
  463. package/src/runs/shared/herdr-external-adapters.d.ts +148 -0
  464. package/src/runs/shared/herdr-external-adapters.js +404 -0
  465. package/src/runs/shared/herdr-machine.d.ts +59 -0
  466. package/src/runs/shared/herdr-machine.js +294 -0
  467. package/src/runs/shared/herdr-pane-host.d.ts +88 -0
  468. package/src/runs/shared/herdr-pane-host.js +155 -0
  469. package/src/runs/shared/herdr-pi-protocol.d.ts +21 -0
  470. package/src/runs/shared/herdr-pi-protocol.js +57 -0
  471. package/src/runs/shared/herdr-placed-run.d.ts +144 -0
  472. package/src/runs/shared/herdr-placed-run.js +380 -0
  473. package/src/runs/shared/host-step-status.d.ts +33 -0
  474. package/src/runs/shared/host-step-status.js +244 -0
  475. package/src/runs/shared/lane-metadata.d.ts +23 -0
  476. package/src/runs/shared/lane-metadata.js +126 -0
  477. package/src/runs/shared/launch-cwd.d.ts +1 -0
  478. package/src/runs/shared/launch-cwd.js +16 -0
  479. package/src/runs/shared/local-machine-access.d.ts +5 -0
  480. package/src/runs/shared/local-machine-access.js +28 -0
  481. package/src/runs/shared/long-running-guard.d.ts +34 -0
  482. package/src/runs/shared/long-running-guard.js +256 -0
  483. package/src/runs/shared/mcp-config-sources.d.ts +33 -0
  484. package/src/runs/shared/mcp-config-sources.js +418 -0
  485. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +86 -0
  486. package/src/runs/shared/mcp-direct-tool-allowlist.js +477 -0
  487. package/src/runs/shared/mcp-direct-tool-grant.d.ts +42 -0
  488. package/src/runs/shared/mcp-direct-tool-grant.js +159 -0
  489. package/src/runs/shared/model-resolution-diagnostic.d.ts +44 -0
  490. package/src/runs/shared/model-resolution-diagnostic.js +116 -0
  491. package/src/runs/shared/model-resolution.d.ts +109 -0
  492. package/src/runs/shared/model-resolution.js +411 -0
  493. package/src/runs/shared/model-scope.d.ts +68 -0
  494. package/src/runs/shared/model-scope.js +171 -0
  495. package/src/runs/shared/mutation-evidence.d.ts +18 -0
  496. package/src/runs/shared/mutation-evidence.js +198 -0
  497. package/src/runs/shared/nested-events.d.ts +135 -0
  498. package/src/runs/shared/nested-events.js +1090 -0
  499. package/src/runs/shared/nested-path.d.ts +8 -0
  500. package/src/runs/shared/nested-path.js +34 -0
  501. package/src/runs/shared/nested-render.d.ts +20 -0
  502. package/src/runs/shared/nested-render.js +115 -0
  503. package/src/runs/shared/orca-progress-tabs.d.ts +31 -0
  504. package/src/runs/shared/orca-progress-tabs.js +503 -0
  505. package/src/runs/shared/parallel-handoff.d.ts +78 -0
  506. package/src/runs/shared/parallel-handoff.js +783 -0
  507. package/src/runs/shared/parallel-utils.d.ts +177 -0
  508. package/src/runs/shared/parallel-utils.js +125 -0
  509. package/src/runs/shared/partial-output.d.ts +24 -0
  510. package/src/runs/shared/partial-output.js +35 -0
  511. package/src/runs/shared/permissions.d.ts +12 -0
  512. package/src/runs/shared/permissions.js +92 -0
  513. package/src/runs/shared/pi-spawn.d.ts +31 -0
  514. package/src/runs/shared/pi-spawn.js +211 -0
  515. package/src/runs/shared/placed-run-owner.d.ts +49 -0
  516. package/src/runs/shared/placed-run-owner.js +93 -0
  517. package/src/runs/shared/placement-host.d.ts +99 -0
  518. package/src/runs/shared/placement-host.js +157 -0
  519. package/src/runs/shared/process-signal.d.ts +15 -0
  520. package/src/runs/shared/process-signal.js +21 -0
  521. package/src/runs/shared/profile-extensions.d.ts +21 -0
  522. package/src/runs/shared/profile-extensions.js +122 -0
  523. package/src/runs/shared/profile-launch-env.d.ts +26 -0
  524. package/src/runs/shared/profile-launch-env.js +90 -0
  525. package/src/runs/shared/readonly-drain-observation.d.ts +25 -0
  526. package/src/runs/shared/readonly-drain-observation.js +50 -0
  527. package/src/runs/shared/rex-machine.d.ts +25 -0
  528. package/src/runs/shared/rex-machine.js +83 -0
  529. package/src/runs/shared/rex-pane-host.d.ts +62 -0
  530. package/src/runs/shared/rex-pane-host.js +327 -0
  531. package/src/runs/shared/run-fanout-budget.d.ts +14 -0
  532. package/src/runs/shared/run-fanout-budget.js +258 -0
  533. package/src/runs/shared/run-ownership.d.ts +3 -0
  534. package/src/runs/shared/run-ownership.js +8 -0
  535. package/src/runs/shared/runner-launcher.d.ts +11 -0
  536. package/src/runs/shared/runner-launcher.js +24 -0
  537. package/src/runs/shared/runtime-acknowledged-extensions.d.ts +7 -0
  538. package/src/runs/shared/runtime-acknowledged-extensions.js +44 -0
  539. package/src/runs/shared/sandbox-profile-guard.d.ts +23 -0
  540. package/src/runs/shared/sandbox-profile-guard.js +106 -0
  541. package/src/runs/shared/sandbox-startup-diagnostics.d.ts +21 -0
  542. package/src/runs/shared/sandbox-startup-diagnostics.js +51 -0
  543. package/src/runs/shared/session-lease.d.ts +69 -0
  544. package/src/runs/shared/session-lease.js +250 -0
  545. package/src/runs/shared/single-output.d.ts +90 -0
  546. package/src/runs/shared/single-output.js +349 -0
  547. package/src/runs/shared/spawn-budget.d.ts +20 -0
  548. package/src/runs/shared/spawn-budget.js +93 -0
  549. package/src/runs/shared/structured-output.d.ts +66 -0
  550. package/src/runs/shared/structured-output.js +483 -0
  551. package/src/runs/shared/subagent-control.d.ts +50 -0
  552. package/src/runs/shared/subagent-control.js +247 -0
  553. package/src/runs/shared/subagent-prompt-runtime.d.ts +90 -0
  554. package/src/runs/shared/subagent-prompt-runtime.js +776 -0
  555. package/src/runs/shared/tool-availability.d.ts +16 -0
  556. package/src/runs/shared/tool-availability.js +29 -0
  557. package/src/runs/shared/tool-budget.d.ts +21 -0
  558. package/src/runs/shared/tool-budget.js +78 -0
  559. package/src/runs/shared/tool-timeout.d.ts +31 -0
  560. package/src/runs/shared/tool-timeout.js +73 -0
  561. package/src/runs/shared/usage-budget.d.ts +7 -0
  562. package/src/runs/shared/usage-budget.js +74 -0
  563. package/src/runs/shared/usage-reconciliation.d.ts +8 -0
  564. package/src/runs/shared/usage-reconciliation.js +71 -0
  565. package/src/runs/shared/workflow-async-child-guidance.d.ts +3 -0
  566. package/src/runs/shared/workflow-async-child-guidance.js +17 -0
  567. package/src/runs/shared/workflow-graph.d.ts +31 -0
  568. package/src/runs/shared/workflow-graph.js +221 -0
  569. package/src/runs/shared/worktree-cleanup-apply.d.ts +36 -0
  570. package/src/runs/shared/worktree-cleanup-apply.js +178 -0
  571. package/src/runs/shared/worktree-cleanup-plan.d.ts +84 -0
  572. package/src/runs/shared/worktree-cleanup-plan.js +803 -0
  573. package/src/runs/shared/worktree-lock.d.ts +5 -0
  574. package/src/runs/shared/worktree-lock.js +40 -0
  575. package/src/runs/shared/worktree-setup-command.d.ts +38 -0
  576. package/src/runs/shared/worktree-setup-command.js +200 -0
  577. package/src/runs/shared/worktree.d.ts +181 -0
  578. package/src/runs/shared/worktree.js +1346 -0
  579. package/src/shared/accessible-dir.d.ts +11 -0
  580. package/src/shared/accessible-dir.js +39 -0
  581. package/src/shared/agent-stream-options.d.ts +5 -0
  582. package/src/shared/agent-stream-options.js +3 -0
  583. package/src/shared/artifacts.d.ts +22 -0
  584. package/src/shared/artifacts.js +272 -0
  585. package/src/shared/atomic-json.d.ts +19 -0
  586. package/src/shared/atomic-json.js +61 -0
  587. package/src/shared/capacity-resilient-json.d.ts +26 -0
  588. package/src/shared/capacity-resilient-json.js +86 -0
  589. package/src/shared/child-cache-retention.d.ts +29 -0
  590. package/src/shared/child-cache-retention.js +40 -0
  591. package/src/shared/child-session-name.d.ts +8 -0
  592. package/src/shared/child-session-name.js +40 -0
  593. package/src/shared/child-transcript.d.ts +37 -0
  594. package/src/shared/child-transcript.js +225 -0
  595. package/src/shared/completion-owner.d.ts +7 -0
  596. package/src/shared/completion-owner.js +13 -0
  597. package/src/shared/disabled-features.d.ts +93 -0
  598. package/src/shared/disabled-features.js +120 -0
  599. package/src/shared/display-text.d.ts +5 -0
  600. package/src/shared/display-text.js +154 -0
  601. package/src/shared/edit-distance.d.ts +4 -0
  602. package/src/shared/edit-distance.js +32 -0
  603. package/src/shared/extension-context.d.ts +21 -0
  604. package/src/shared/extension-context.js +39 -0
  605. package/src/shared/file-coalescer.d.ts +11 -0
  606. package/src/shared/file-coalescer.js +34 -0
  607. package/src/shared/file-lease.d.ts +10 -0
  608. package/src/shared/file-lease.js +106 -0
  609. package/src/shared/file-system-retry.d.ts +31 -0
  610. package/src/shared/file-system-retry.js +84 -0
  611. package/src/shared/fork-context.d.ts +64 -0
  612. package/src/shared/fork-context.js +185 -0
  613. package/src/shared/fork-session-cwd.d.ts +2 -0
  614. package/src/shared/fork-session-cwd.js +23 -0
  615. package/src/shared/formatters.d.ts +35 -0
  616. package/src/shared/formatters.js +137 -0
  617. package/src/shared/jsonl-writer.d.ts +20 -0
  618. package/src/shared/jsonl-writer.js +67 -0
  619. package/src/shared/launch-contract.d.ts +65 -0
  620. package/src/shared/launch-contract.js +145 -0
  621. package/src/shared/model-info.d.ts +55 -0
  622. package/src/shared/model-info.js +103 -0
  623. package/src/shared/model-response-aliases.d.ts +1 -0
  624. package/src/shared/model-response-aliases.js +15 -0
  625. package/src/shared/node-executable.d.ts +1 -0
  626. package/src/shared/node-executable.js +20 -0
  627. package/src/shared/opencode-session-headers.d.ts +12 -0
  628. package/src/shared/opencode-session-headers.js +26 -0
  629. package/src/shared/package-version.d.ts +2 -0
  630. package/src/shared/package-version.js +14 -0
  631. package/src/shared/parent-wake.d.ts +26 -0
  632. package/src/shared/parent-wake.js +68 -0
  633. package/src/shared/permission-profile.d.ts +26 -0
  634. package/src/shared/permission-profile.js +49 -0
  635. package/src/shared/prompt-resources.d.ts +5 -0
  636. package/src/shared/prompt-resources.js +10 -0
  637. package/src/shared/provider-diagnostics.d.ts +9 -0
  638. package/src/shared/provider-diagnostics.js +75 -0
  639. package/src/shared/pruned-fork.d.ts +34 -0
  640. package/src/shared/pruned-fork.js +434 -0
  641. package/src/shared/required-child-extensions.d.ts +34 -0
  642. package/src/shared/required-child-extensions.js +105 -0
  643. package/src/shared/runtime-module-path.d.ts +10 -0
  644. package/src/shared/runtime-module-path.js +16 -0
  645. package/src/shared/sandbox-profile.d.ts +12 -0
  646. package/src/shared/sandbox-profile.js +35 -0
  647. package/src/shared/session-file-trust.d.ts +1 -0
  648. package/src/shared/session-file-trust.js +20 -0
  649. package/src/shared/session-identity.d.ts +8 -0
  650. package/src/shared/session-identity.js +32 -0
  651. package/src/shared/session-succession.d.ts +4 -0
  652. package/src/shared/session-succession.js +24 -0
  653. package/src/shared/session-tokens.d.ts +2 -0
  654. package/src/shared/session-tokens.js +58 -0
  655. package/src/shared/settings-file-lease.d.ts +4 -0
  656. package/src/shared/settings-file-lease.js +38 -0
  657. package/src/shared/settings.d.ts +146 -0
  658. package/src/shared/settings.js +247 -0
  659. package/src/shared/shortcuts.d.ts +1 -0
  660. package/src/shared/shortcuts.js +17 -0
  661. package/src/shared/status-format.d.ts +9 -0
  662. package/src/shared/status-format.js +60 -0
  663. package/src/shared/thinking-ceiling.d.ts +13 -0
  664. package/src/shared/thinking-ceiling.js +37 -0
  665. package/src/shared/types.d.ts +2842 -0
  666. package/src/shared/types.js +276 -0
  667. package/src/shared/utf8.d.ts +5 -0
  668. package/src/shared/utf8.js +12 -0
  669. package/src/shared/utils.d.ts +83 -0
  670. package/src/shared/utils.js +612 -0
  671. package/src/shared/watch-strategy.d.ts +2 -0
  672. package/src/shared/watch-strategy.js +5 -0
  673. package/src/shared/workflow-child-permit.d.ts +58 -0
  674. package/src/shared/workflow-child-permit.js +159 -0
  675. package/src/slash/delegation-adapters.d.ts +154 -0
  676. package/src/slash/delegation-adapters.js +316 -0
  677. package/src/slash/delegation-json.d.ts +10 -0
  678. package/src/slash/delegation-json.js +117 -0
  679. package/src/slash/delegation-request.d.ts +12 -0
  680. package/src/slash/delegation-request.js +174 -0
  681. package/src/slash/prompt-template-bridge.d.ts +29 -0
  682. package/src/slash/prompt-template-bridge.js +399 -0
  683. package/src/slash/prompt-workflows.d.ts +21 -0
  684. package/src/slash/prompt-workflows.js +274 -0
  685. package/src/slash/selector.d.ts +47 -0
  686. package/src/slash/selector.js +117 -0
  687. package/src/slash/slash-bridge.d.ts +30 -0
  688. package/src/slash/slash-bridge.js +132 -0
  689. package/src/slash/slash-commands.d.ts +10 -0
  690. package/src/slash/slash-commands.js +1059 -0
  691. package/src/slash/slash-live-state.d.ts +21 -0
  692. package/src/slash/slash-live-state.js +263 -0
  693. package/src/slash/subagent-cost.d.ts +29 -0
  694. package/src/slash/subagent-cost.js +310 -0
  695. package/src/slash/subagents-admin.d.ts +3 -0
  696. package/src/slash/subagents-admin.js +481 -0
  697. package/src/tui/fleet-layout.d.ts +20 -0
  698. package/src/tui/fleet-layout.js +17 -0
  699. package/src/tui/fleet-native-transcript.d.ts +53 -0
  700. package/src/tui/fleet-native-transcript.js +339 -0
  701. package/src/tui/fleet-status.d.ts +92 -0
  702. package/src/tui/fleet-status.js +1132 -0
  703. package/src/tui/fleet-transcript.d.ts +64 -0
  704. package/src/tui/fleet-transcript.js +544 -0
  705. package/src/tui/fleet-viewport.d.ts +12 -0
  706. package/src/tui/fleet-viewport.js +35 -0
  707. package/src/tui/fleet.d.ts +196 -0
  708. package/src/tui/fleet.js +1588 -0
  709. package/src/tui/mouse-events.d.ts +21 -0
  710. package/src/tui/mouse-events.js +26 -0
  711. package/src/tui/render-helpers.d.ts +23 -0
  712. package/src/tui/render-helpers.js +100 -0
  713. package/src/tui/render.d.ts +66 -0
  714. package/src/tui/render.js +3707 -0
  715. package/src/tui/running-tone.d.ts +10 -0
  716. package/src/tui/running-tone.js +22 -0
  717. package/src/tui/subagent-messages.d.ts +22 -0
  718. package/src/tui/subagent-messages.js +270 -0
  719. package/src/ui-silent-marker.d.ts +20 -0
  720. package/src/ui-silent-marker.js +25 -0
  721. package/src/watchdog/change-signature.d.ts +7 -0
  722. package/src/watchdog/change-signature.js +243 -0
  723. package/src/watchdog/child-status.d.ts +53 -0
  724. package/src/watchdog/child-status.js +187 -0
  725. package/src/watchdog/diff-tool.d.ts +25 -0
  726. package/src/watchdog/diff-tool.js +104 -0
  727. package/src/watchdog/emission-guard.d.ts +36 -0
  728. package/src/watchdog/emission-guard.js +97 -0
  729. package/src/watchdog/guidance.d.ts +3 -0
  730. package/src/watchdog/guidance.js +19 -0
  731. package/src/watchdog/lsp-diagnostics.d.ts +17 -0
  732. package/src/watchdog/lsp-diagnostics.js +489 -0
  733. package/src/watchdog/model-selection.d.ts +24 -0
  734. package/src/watchdog/model-selection.js +167 -0
  735. package/src/watchdog/permission-arbiter.d.ts +20 -0
  736. package/src/watchdog/permission-arbiter.js +135 -0
  737. package/src/watchdog/register-child.d.ts +13 -0
  738. package/src/watchdog/register-child.js +128 -0
  739. package/src/watchdog/register-main.d.ts +11 -0
  740. package/src/watchdog/register-main.js +400 -0
  741. package/src/watchdog/render.d.ts +3 -0
  742. package/src/watchdog/render.js +33 -0
  743. package/src/watchdog/review.d.ts +36 -0
  744. package/src/watchdog/review.js +319 -0
  745. package/src/watchdog/rules.d.ts +21 -0
  746. package/src/watchdog/rules.js +58 -0
  747. package/src/watchdog/runtime.d.ts +195 -0
  748. package/src/watchdog/runtime.js +864 -0
  749. package/src/watchdog/scope.d.ts +14 -0
  750. package/src/watchdog/scope.js +44 -0
  751. package/src/watchdog/settings.d.ts +29 -0
  752. package/src/watchdog/settings.js +480 -0
  753. package/src/watchdog/tool-actions.d.ts +17 -0
  754. package/src/watchdog/tool-actions.js +150 -0
  755. package/src/watchdog/turn-delta.d.ts +15 -0
  756. package/src/watchdog/turn-delta.js +188 -0
  757. package/src/watchdog/types.d.ts +141 -0
  758. package/src/watchdog/types.js +27 -0
  759. package/src/watchdog/warning-format.d.ts +7 -0
  760. package/src/watchdog/warning-format.js +59 -0
  761. package/src/workflows/chat-progress.d.ts +37 -0
  762. package/src/workflows/chat-progress.js +129 -0
  763. package/src/workflows/host-command.d.ts +30 -0
  764. package/src/workflows/host-command.js +227 -0
  765. package/src/workflows/scripted-workflow.d.ts +204 -0
  766. package/src/workflows/scripted-workflow.js +1673 -0
  767. package/src/workflows/structured-workflow-scripts.d.ts +10 -0
  768. package/src/workflows/structured-workflow-scripts.js +179 -0
  769. package/src/workflows/workflow-auto-resume.d.ts +32 -0
  770. package/src/workflows/workflow-auto-resume.js +102 -0
  771. package/src/workflows/workflow-checklist.d.ts +127 -0
  772. package/src/workflows/workflow-checklist.js +314 -0
  773. package/src/workflows/workflow-child-summary.d.ts +24 -0
  774. package/src/workflows/workflow-child-summary.js +195 -0
  775. package/src/workflows/workflow-launch-record.d.ts +27 -0
  776. package/src/workflows/workflow-launch-record.js +48 -0
  777. package/src/workflows/workflow-preflight.d.ts +58 -0
  778. package/src/workflows/workflow-preflight.js +288 -0
  779. package/src/workflows/workflow-receipt.d.ts +34 -0
  780. package/src/workflows/workflow-receipt.js +454 -0
  781. package/src/workflows/workflow-resources.d.ts +55 -0
  782. package/src/workflows/workflow-resources.js +271 -0
  783. package/src/workflows/workflow-resume-claim.d.ts +82 -0
  784. package/src/workflows/workflow-resume-claim.js +210 -0
  785. package/src/workflows/workflow-resume.d.ts +56 -0
  786. package/src/workflows/workflow-resume.js +106 -0
  787. package/src/workflows/workflow-reuse.d.ts +61 -0
  788. package/src/workflows/workflow-reuse.js +186 -0
  789. package/src/workflows/workflow-revival.d.ts +33 -0
  790. package/src/workflows/workflow-revival.js +111 -0
  791. package/src/workflows/workflow-settlement.d.ts +84 -0
  792. package/src/workflows/workflow-settlement.js +203 -0
  793. package/src/workflows/workflow-stop-cause.d.ts +6 -0
  794. package/src/workflows/workflow-stop-cause.js +8 -0
  795. package/workflow-script-worker.cjs +1342 -0
  796. package/index.ts +0 -18
  797. package/node_modules/@xzzpig/pi-components/src/transcript.ts +0 -1878
  798. package/skills/pi-subagents/references/constraints-and-recipes.md +0 -74
  799. package/skills/pi-subagents/references/execution-controls.md +0 -561
  800. package/skills/pi-subagents/references/management-authoring-rpc.md +0 -165
  801. package/skills/pi-subagents/references/multi-lane-orchestration.md +0 -61
  802. package/skills/pi-subagents/references/review-and-validation.md +0 -73
  803. package/src/agents/advertised-agent-prompt.ts +0 -82
  804. package/src/agents/agent-eject.ts +0 -339
  805. package/src/agents/agent-management.ts +0 -1442
  806. package/src/agents/agent-memory.ts +0 -341
  807. package/src/agents/agent-refinements.ts +0 -624
  808. package/src/agents/agent-scope.ts +0 -10
  809. package/src/agents/agent-selection.ts +0 -25
  810. package/src/agents/agent-serializer.ts +0 -195
  811. package/src/agents/agents.ts +0 -3169
  812. package/src/agents/builtin-names.ts +0 -16
  813. package/src/agents/chain-serializer.ts +0 -285
  814. package/src/agents/frontmatter.ts +0 -153
  815. package/src/agents/global-npm-root.ts +0 -58
  816. package/src/agents/identity.ts +0 -30
  817. package/src/agents/proactive-skills.ts +0 -197
  818. package/src/agents/runtime-agent-events.ts +0 -70
  819. package/src/agents/runtime-agent-registry.ts +0 -457
  820. package/src/agents/runtime-discovery.ts +0 -39
  821. package/src/agents/skills.ts +0 -787
  822. package/src/api/agent-management.ts +0 -9
  823. package/src/api/agents.ts +0 -19
  824. package/src/api/background-work.ts +0 -206
  825. package/src/api/capability-ceiling.ts +0 -16
  826. package/src/api/child-tool-plan.ts +0 -5
  827. package/src/api/control-channel.ts +0 -4
  828. package/src/api/delegation.ts +0 -131
  829. package/src/api/external-job-provider.ts +0 -195
  830. package/src/api/external-runs.ts +0 -282
  831. package/src/api/inspectors.ts +0 -27
  832. package/src/api/intercom-bridge.ts +0 -3
  833. package/src/api/preflight.ts +0 -641
  834. package/src/api/project-panes.ts +0 -32
  835. package/src/api/required-child-extensions.ts +0 -6
  836. package/src/api/shared-types.ts +0 -29
  837. package/src/api/supervisor-routing.ts +0 -196
  838. package/src/api/workflow-resources.ts +0 -6
  839. package/src/extension/config.ts +0 -262
  840. package/src/extension/context-injection.ts +0 -123
  841. package/src/extension/control-notices.ts +0 -53
  842. package/src/extension/declaration-pinning.ts +0 -164
  843. package/src/extension/doctor.ts +0 -284
  844. package/src/extension/fanout-child.ts +0 -282
  845. package/src/extension/herdr-pi-bridge.ts +0 -166
  846. package/src/extension/index.ts +0 -1212
  847. package/src/extension/public-execution.ts +0 -262
  848. package/src/extension/reply-workflow-script.ts +0 -67
  849. package/src/extension/rpc.ts +0 -881
  850. package/src/extension/schemas.ts +0 -337
  851. package/src/extension/steering-notices.ts +0 -35
  852. package/src/extension/subagent-guide.ts +0 -127
  853. package/src/extension/subagent-options.ts +0 -47
  854. package/src/extension/tool-activation.ts +0 -147
  855. package/src/extension/tool-description.ts +0 -193
  856. package/src/extension/tool-result.ts +0 -19
  857. package/src/extension/upgrade-notice.ts +0 -40
  858. package/src/inspectors/actions.ts +0 -174
  859. package/src/inspectors/ghostty/actions.ts +0 -74
  860. package/src/inspectors/ghostty/plugin.ts +0 -29
  861. package/src/inspectors/herdr/actions.ts +0 -155
  862. package/src/inspectors/herdr/client.ts +0 -130
  863. package/src/inspectors/herdr/focus.ts +0 -55
  864. package/src/inspectors/herdr/plugin.ts +0 -20
  865. package/src/inspectors/herdr/project-panes.ts +0 -733
  866. package/src/inspectors/inspector-runner.ts +0 -153
  867. package/src/inspectors/plugins.ts +0 -76
  868. package/src/inspectors/session-roots-codec.ts +0 -31
  869. package/src/inspectors/shell-command.ts +0 -16
  870. package/src/inspectors/tmux/actions.ts +0 -204
  871. package/src/inspectors/tmux/client.ts +0 -85
  872. package/src/inspectors/tmux/plugin.ts +0 -21
  873. package/src/inspectors/types.ts +0 -51
  874. package/src/integrations/herdr-status.ts +0 -385
  875. package/src/integrations/pi-web-session-liveness.ts +0 -73
  876. package/src/integrations/program-status.ts +0 -215
  877. package/src/intercom/fork-supervisor-routing.ts +0 -533
  878. package/src/intercom/intercom-bridge.ts +0 -235
  879. package/src/intercom/native-supervisor-channel.ts +0 -1066
  880. package/src/intercom/result-intercom.ts +0 -433
  881. package/src/intercom/supervisor-ui.ts +0 -72
  882. package/src/missions/actions.ts +0 -433
  883. package/src/missions/goal-driver.ts +0 -177
  884. package/src/missions/lifecycle.ts +0 -367
  885. package/src/missions/store.ts +0 -613
  886. package/src/missions/types.ts +0 -190
  887. package/src/missions/workflow-state.ts +0 -281
  888. package/src/policy/authority.ts +0 -50
  889. package/src/profiles/profiles.ts +0 -674
  890. package/src/runs/background/active-async-capacity.ts +0 -548
  891. package/src/runs/background/active-run-index.ts +0 -155
  892. package/src/runs/background/async-execution.ts +0 -2479
  893. package/src/runs/background/async-job-tracker.ts +0 -869
  894. package/src/runs/background/async-resume.ts +0 -686
  895. package/src/runs/background/async-retention.ts +0 -953
  896. package/src/runs/background/async-status-snapshot.ts +0 -46
  897. package/src/runs/background/async-status.ts +0 -787
  898. package/src/runs/background/auto-drain.ts +0 -92
  899. package/src/runs/background/await-async-run.ts +0 -83
  900. package/src/runs/background/binary-bootstrap.ts +0 -67
  901. package/src/runs/background/calendar-schedule.ts +0 -90
  902. package/src/runs/background/chain-append.ts +0 -321
  903. package/src/runs/background/chain-root-attachment.ts +0 -263
  904. package/src/runs/background/completion-batcher.ts +0 -168
  905. package/src/runs/background/completion-dedupe.ts +0 -58
  906. package/src/runs/background/completion-replay.ts +0 -287
  907. package/src/runs/background/control-channel.ts +0 -659
  908. package/src/runs/background/fleet-view.ts +0 -692
  909. package/src/runs/background/index-segment.ts +0 -59
  910. package/src/runs/background/inspect-rpc.ts +0 -443
  911. package/src/runs/background/notify.ts +0 -1083
  912. package/src/runs/background/owned-process-tree.ts +0 -131
  913. package/src/runs/background/parallel-groups.ts +0 -45
  914. package/src/runs/background/pid-namespace.ts +0 -18
  915. package/src/runs/background/process-terminal-candidate.ts +0 -98
  916. package/src/runs/background/process-terminal.ts +0 -231
  917. package/src/runs/background/result-delivery-ownership.ts +0 -45
  918. package/src/runs/background/result-files.ts +0 -634
  919. package/src/runs/background/result-watcher.ts +0 -842
  920. package/src/runs/background/resume-guidance.ts +0 -56
  921. package/src/runs/background/retained-children.ts +0 -136
  922. package/src/runs/background/retained-nested-route-tracker.ts +0 -96
  923. package/src/runs/background/run-child-session.ts +0 -725
  924. package/src/runs/background/run-id-query.ts +0 -7
  925. package/src/runs/background/run-id-resolver.ts +0 -183
  926. package/src/runs/background/run-status.ts +0 -803
  927. package/src/runs/background/runner-aliases.ts +0 -183
  928. package/src/runs/background/runner-child-launch.ts +0 -96
  929. package/src/runs/background/runner-child-sessions.ts +0 -32
  930. package/src/runs/background/runner-http-dispatcher.ts +0 -122
  931. package/src/runs/background/runner-startup-failure.ts +0 -56
  932. package/src/runs/background/scheduled-runs.ts +0 -1222
  933. package/src/runs/background/stale-run-reconciler.ts +0 -463
  934. package/src/runs/background/steering.ts +0 -260
  935. package/src/runs/background/subagent-runner-bootstrap.ts +0 -279
  936. package/src/runs/background/subagent-runner.ts +0 -5251
  937. package/src/runs/background/subagent-wait.ts +0 -895
  938. package/src/runs/background/terminal-run-index.ts +0 -183
  939. package/src/runs/background/top-level-async.ts +0 -14
  940. package/src/runs/background/wait-completions.ts +0 -262
  941. package/src/runs/background/wait-config.ts +0 -50
  942. package/src/runs/background/wait-subscriptions.ts +0 -354
  943. package/src/runs/background/wait-tool.ts +0 -57
  944. package/src/runs/background/workflow-terminal-proof.ts +0 -85
  945. package/src/runs/foreground/async-dismiss-action.ts +0 -86
  946. package/src/runs/foreground/async-steering-action.ts +0 -276
  947. package/src/runs/foreground/async-stop-action.ts +0 -216
  948. package/src/runs/foreground/command-action.ts +0 -41
  949. package/src/runs/foreground/execution.ts +0 -2315
  950. package/src/runs/foreground/foreground-control.ts +0 -157
  951. package/src/runs/foreground/foreground-history.ts +0 -164
  952. package/src/runs/foreground/prompt-audit.ts +0 -172
  953. package/src/runs/foreground/subagent-executor.ts +0 -8252
  954. package/src/runs/foreground/workflow-detach-reconcile.ts +0 -304
  955. package/src/runs/foreground/workflow-foreground-steering.ts +0 -169
  956. package/src/runs/shared/abort-recovery.ts +0 -119
  957. package/src/runs/shared/acceptance.ts +0 -1664
  958. package/src/runs/shared/agent-contract.ts +0 -38
  959. package/src/runs/shared/async-status-projection.ts +0 -664
  960. package/src/runs/shared/background-process-options.ts +0 -9
  961. package/src/runs/shared/capability-ceiling.ts +0 -214
  962. package/src/runs/shared/chain-outputs.ts +0 -116
  963. package/src/runs/shared/child-commands.ts +0 -229
  964. package/src/runs/shared/child-hooks.ts +0 -175
  965. package/src/runs/shared/child-identity.ts +0 -62
  966. package/src/runs/shared/child-launch-plan.ts +0 -163
  967. package/src/runs/shared/child-launch.ts +0 -389
  968. package/src/runs/shared/child-lifecycle.ts +0 -28
  969. package/src/runs/shared/child-runtime-config.ts +0 -136
  970. package/src/runs/shared/child-session.ts +0 -699
  971. package/src/runs/shared/child-tool-plan.ts +0 -599
  972. package/src/runs/shared/claude-code-adapter.ts +0 -288
  973. package/src/runs/shared/codex-exec-adapter.ts +0 -129
  974. package/src/runs/shared/context-mode.ts +0 -44
  975. package/src/runs/shared/cursor-agent-adapter.ts +0 -114
  976. package/src/runs/shared/dynamic-fanout.ts +0 -297
  977. package/src/runs/shared/effective-system-prompt.ts +0 -33
  978. package/src/runs/shared/extension-bindings.ts +0 -103
  979. package/src/runs/shared/external-cli-contract.ts +0 -177
  980. package/src/runs/shared/external-cli-preflight.ts +0 -190
  981. package/src/runs/shared/external-cli-runner.ts +0 -437
  982. package/src/runs/shared/external-job-bridge.ts +0 -514
  983. package/src/runs/shared/external-job-runner.ts +0 -389
  984. package/src/runs/shared/fast-mode-extension.ts +0 -10
  985. package/src/runs/shared/fork-command-result.ts +0 -10
  986. package/src/runs/shared/git-environment.ts +0 -29
  987. package/src/runs/shared/herdr-connection.ts +0 -134
  988. package/src/runs/shared/herdr-external-adapters.ts +0 -169
  989. package/src/runs/shared/herdr-machine.ts +0 -279
  990. package/src/runs/shared/herdr-pi-protocol.ts +0 -59
  991. package/src/runs/shared/herdr-placed-run.ts +0 -264
  992. package/src/runs/shared/host-step-status.ts +0 -231
  993. package/src/runs/shared/lane-metadata.ts +0 -126
  994. package/src/runs/shared/launch-cwd.ts +0 -16
  995. package/src/runs/shared/long-running-guard.ts +0 -221
  996. package/src/runs/shared/mcp-config-sources.ts +0 -426
  997. package/src/runs/shared/mcp-direct-tool-allowlist.ts +0 -579
  998. package/src/runs/shared/mcp-direct-tool-grant.ts +0 -210
  999. package/src/runs/shared/model-resolution-diagnostic.ts +0 -101
  1000. package/src/runs/shared/model-resolution.ts +0 -503
  1001. package/src/runs/shared/model-scope.ts +0 -224
  1002. package/src/runs/shared/mutation-evidence.ts +0 -199
  1003. package/src/runs/shared/nested-events.ts +0 -1125
  1004. package/src/runs/shared/nested-path.ts +0 -38
  1005. package/src/runs/shared/nested-render.ts +0 -127
  1006. package/src/runs/shared/orca-progress-tabs.ts +0 -511
  1007. package/src/runs/shared/parallel-handoff.ts +0 -789
  1008. package/src/runs/shared/parallel-utils.ts +0 -292
  1009. package/src/runs/shared/partial-output.ts +0 -48
  1010. package/src/runs/shared/permissions.ts +0 -86
  1011. package/src/runs/shared/pi-spawn.ts +0 -205
  1012. package/src/runs/shared/process-signal.ts +0 -35
  1013. package/src/runs/shared/profile-extensions.ts +0 -134
  1014. package/src/runs/shared/profile-launch-env.ts +0 -121
  1015. package/src/runs/shared/readonly-drain-observation.ts +0 -42
  1016. package/src/runs/shared/run-fanout-budget.ts +0 -267
  1017. package/src/runs/shared/run-history.ts +0 -288
  1018. package/src/runs/shared/runner-launcher.ts +0 -25
  1019. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -44
  1020. package/src/runs/shared/sandbox-profile-guard.ts +0 -119
  1021. package/src/runs/shared/sandbox-startup-diagnostics.ts +0 -54
  1022. package/src/runs/shared/session-lease.ts +0 -293
  1023. package/src/runs/shared/single-output.ts +0 -366
  1024. package/src/runs/shared/spawn-budget.ts +0 -128
  1025. package/src/runs/shared/structured-output.ts +0 -463
  1026. package/src/runs/shared/subagent-control.ts +0 -295
  1027. package/src/runs/shared/subagent-prompt-runtime.ts +0 -598
  1028. package/src/runs/shared/tool-availability.ts +0 -37
  1029. package/src/runs/shared/tool-budget.ts +0 -87
  1030. package/src/runs/shared/tool-timeout.ts +0 -93
  1031. package/src/runs/shared/usage-budget.ts +0 -65
  1032. package/src/runs/shared/usage-reconciliation.ts +0 -73
  1033. package/src/runs/shared/workflow-async-child-guidance.ts +0 -18
  1034. package/src/runs/shared/workflow-graph.ts +0 -225
  1035. package/src/runs/shared/worktree-cleanup-apply.ts +0 -160
  1036. package/src/runs/shared/worktree-cleanup-plan.ts +0 -891
  1037. package/src/runs/shared/worktree-lock.ts +0 -29
  1038. package/src/runs/shared/worktree-setup-command.ts +0 -213
  1039. package/src/runs/shared/worktree.ts +0 -1554
  1040. package/src/shared/accessible-dir.ts +0 -47
  1041. package/src/shared/agent-stream-options.ts +0 -5
  1042. package/src/shared/artifacts.ts +0 -281
  1043. package/src/shared/atomic-json.ts +0 -85
  1044. package/src/shared/capacity-resilient-json.ts +0 -102
  1045. package/src/shared/child-cache-retention.ts +0 -43
  1046. package/src/shared/child-session-name.ts +0 -48
  1047. package/src/shared/child-transcript.ts +0 -264
  1048. package/src/shared/completion-owner.ts +0 -14
  1049. package/src/shared/disabled-features.ts +0 -123
  1050. package/src/shared/display-text.ts +0 -150
  1051. package/src/shared/edit-distance.ts +0 -33
  1052. package/src/shared/extension-context.ts +0 -37
  1053. package/src/shared/file-coalescer.ts +0 -49
  1054. package/src/shared/file-lease.ts +0 -74
  1055. package/src/shared/file-system-retry.ts +0 -95
  1056. package/src/shared/fork-context.ts +0 -243
  1057. package/src/shared/fork-session-cwd.ts +0 -27
  1058. package/src/shared/formatters.ts +0 -142
  1059. package/src/shared/jsonl-writer.ts +0 -92
  1060. package/src/shared/launch-contract.ts +0 -206
  1061. package/src/shared/model-info.ts +0 -132
  1062. package/src/shared/model-response-aliases.ts +0 -13
  1063. package/src/shared/node-executable.ts +0 -21
  1064. package/src/shared/opencode-session-headers.ts +0 -30
  1065. package/src/shared/package-version.ts +0 -17
  1066. package/src/shared/parent-wake.ts +0 -79
  1067. package/src/shared/permission-profile.ts +0 -56
  1068. package/src/shared/prompt-resources.ts +0 -11
  1069. package/src/shared/pruned-fork.ts +0 -469
  1070. package/src/shared/required-child-extensions.ts +0 -115
  1071. package/src/shared/runtime-module-path.ts +0 -19
  1072. package/src/shared/sandbox-profile.ts +0 -37
  1073. package/src/shared/session-file-trust.ts +0 -19
  1074. package/src/shared/session-identity.ts +0 -10
  1075. package/src/shared/session-tokens.ts +0 -55
  1076. package/src/shared/settings-file-lease.ts +0 -36
  1077. package/src/shared/settings.ts +0 -412
  1078. package/src/shared/shortcuts.ts +0 -13
  1079. package/src/shared/status-format.ts +0 -55
  1080. package/src/shared/thinking-ceiling.ts +0 -46
  1081. package/src/shared/types.ts +0 -3105
  1082. package/src/shared/utf8.ts +0 -11
  1083. package/src/shared/utils.ts +0 -610
  1084. package/src/shared/watch-strategy.ts +0 -12
  1085. package/src/shared/workflow-child-permit.ts +0 -212
  1086. package/src/slash/delegation-adapters.ts +0 -452
  1087. package/src/slash/delegation-json.ts +0 -108
  1088. package/src/slash/delegation-request.ts +0 -176
  1089. package/src/slash/prompt-template-bridge.ts +0 -435
  1090. package/src/slash/prompt-workflows.ts +0 -298
  1091. package/src/slash/selector.ts +0 -147
  1092. package/src/slash/slash-bridge.ts +0 -192
  1093. package/src/slash/slash-commands.ts +0 -1096
  1094. package/src/slash/slash-live-state.ts +0 -310
  1095. package/src/slash/subagent-cost.ts +0 -317
  1096. package/src/slash/subagents-admin.ts +0 -489
  1097. package/src/tui/fleet-native-transcript.ts +0 -424
  1098. package/src/tui/fleet-status.ts +0 -1139
  1099. package/src/tui/fleet-transcript.ts +0 -591
  1100. package/src/tui/fleet.ts +0 -1618
  1101. package/src/tui/mouse-events.ts +0 -42
  1102. package/src/tui/render-helpers.ts +0 -111
  1103. package/src/tui/render.ts +0 -3824
  1104. package/src/tui/running-tone.ts +0 -28
  1105. package/src/tui/subagent-messages.ts +0 -305
  1106. package/src/ui-silent-marker.ts +0 -32
  1107. package/src/watchdog/change-signature.ts +0 -260
  1108. package/src/watchdog/child-status.ts +0 -225
  1109. package/src/watchdog/diff-tool.ts +0 -112
  1110. package/src/watchdog/emission-guard.ts +0 -125
  1111. package/src/watchdog/guidance.ts +0 -20
  1112. package/src/watchdog/lsp-diagnostics.ts +0 -538
  1113. package/src/watchdog/model-selection.ts +0 -187
  1114. package/src/watchdog/permission-arbiter.ts +0 -154
  1115. package/src/watchdog/register-child.ts +0 -136
  1116. package/src/watchdog/register-main.ts +0 -425
  1117. package/src/watchdog/render.ts +0 -31
  1118. package/src/watchdog/review.ts +0 -362
  1119. package/src/watchdog/rules.ts +0 -70
  1120. package/src/watchdog/runtime.ts +0 -927
  1121. package/src/watchdog/scope.ts +0 -51
  1122. package/src/watchdog/settings.ts +0 -520
  1123. package/src/watchdog/tool-actions.ts +0 -156
  1124. package/src/watchdog/turn-delta.ts +0 -190
  1125. package/src/watchdog/types.ts +0 -186
  1126. package/src/watchdog/warning-format.ts +0 -72
  1127. package/src/workflows/chat-progress.ts +0 -152
  1128. package/src/workflows/host-command.ts +0 -235
  1129. package/src/workflows/scripted-workflow.ts +0 -2733
  1130. package/src/workflows/structured-workflow-scripts.ts +0 -177
  1131. package/src/workflows/workflow-checklist.ts +0 -442
  1132. package/src/workflows/workflow-child-summary.ts +0 -172
  1133. package/src/workflows/workflow-preflight.ts +0 -297
  1134. package/src/workflows/workflow-receipt.ts +0 -390
  1135. package/src/workflows/workflow-resources.ts +0 -275
  1136. package/src/workflows/workflow-reuse.ts +0 -120
  1137. package/src/workflows/workflow-revival.ts +0 -123
  1138. package/src/workflows/workflow-settlement.ts +0 -252
@@ -0,0 +1,3707 @@
1
+ /**
2
+ * Rendering functions for subagent results
3
+ */
4
+ import * as path from "node:path";
5
+ import { createHash } from "node:crypto";
6
+ import { getMarkdownTheme, keyText } from "@earendil-works/pi-coding-agent";
7
+ import { Container, Markdown, Spacer, Text, visibleWidth } from "@earendil-works/pi-tui";
8
+ import { unresolvedChildWatchdogBlockers } from "../watchdog/child-status.js";
9
+ import { MAX_WIDGET_JOBS, WIDGET_ANIMATION_INTERVAL_MS, WIDGET_KEY, } from "../shared/types.js";
10
+ import { previewDisplayText, sanitizeDisplayText, truncateDisplayText } from "../shared/display-text.js";
11
+ import { formatShortcutLabel } from "../shared/shortcuts.js";
12
+ import { formatContextUsage, formatTokens, formatUsage, formatDuration, formatModelThinking, formatToolCall, formatTokenUsage, shortenPath } from "../shared/formatters.js";
13
+ import { getDisplayItems, getSingleResultOutput, PROMPT_REDACTED } from "../shared/utils.js";
14
+ import { flatToLogicalStepIndex } from "../runs/background/parallel-groups.js";
15
+ import { formatNestedAggregate } from "../runs/shared/nested-render.js";
16
+ import { aggregateStepStatus, formatActivityLabel, formatAgentRunningLabel, formatParallelOutcome } from "../shared/status-format.js";
17
+ import { contextModeBadge, contextModePrefix } from "../runs/shared/context-mode.js";
18
+ import { shouldSuppressSingleStep, stripRepeatedAgentPrefix, withDuplicateLabelDiscriminators } from "./render-helpers.js";
19
+ import { runningTone } from "./running-tone.js";
20
+ import { childThinkingLevel } from "../shared/model-info.js";
21
+ import { buildWorkflowChatProgressRows } from "../workflows/chat-progress.js";
22
+ import { formatWorkflowPreflight, formatWorkflowPreflightPlanSummary, formatWorkflowPreflightWarningSummary, formatWorkflowPreflightWarnings } from "../workflows/workflow-preflight.js";
23
+ import { encodeAsyncStatusSnapshotWidget } from "../runs/background/async-status-snapshot.js";
24
+ import { projectAsyncWorkflowRows } from "../runs/shared/async-status-projection.js";
25
+ import { hostStepReportName, hostStepVerdictLabel } from "../runs/shared/host-step-status.js";
26
+ import { workflowGraphStageNodes } from "../runs/shared/workflow-graph.js";
27
+ import { formatWorkflowChecklistBottleneck, formatWorkflowChecklistPhase, formatWorkflowChecklistSummary, projectWorkflowChecklist } from "../workflows/workflow-checklist.js";
28
+ function resolveMainWindowRenderLayout(config) {
29
+ return {
30
+ horizontalSpacing: config?.horizontalSpacing ?? 2,
31
+ ...(config?.compactResultMaxLines !== undefined ? { compactResultMaxLines: config.compactResultMaxLines } : {}),
32
+ };
33
+ }
34
+ function mainWindowIndent(layout, level) {
35
+ return " ".repeat(Math.max(0, layout.horizontalSpacing * level));
36
+ }
37
+ function capCompactMainWindowResult(component, layout, theme, enabled) {
38
+ const maxLines = layout.compactResultMaxLines;
39
+ if (!enabled || maxLines === undefined)
40
+ return component;
41
+ const capped = new Container();
42
+ capped.render = (width) => {
43
+ const lines = component.render(width);
44
+ if (lines.length <= maxLines)
45
+ return lines;
46
+ const visibleRows = maxLines === 1 ? 1 : maxLines - 1;
47
+ const hiddenCount = lines.length - visibleRows;
48
+ const hint = theme.fg("accent", `… ${hiddenCount} rows hidden · ${expandKeyHint("to expand")}`);
49
+ if (maxLines === 1)
50
+ return [truncLine(`${lines[0] ?? ""} ${hint}`, width)];
51
+ return [...lines.slice(0, visibleRows), truncLine(hint, width)];
52
+ };
53
+ return capped;
54
+ }
55
+ function expandKeyHint(action) {
56
+ // keyText is empty wherever Pi's app keybindings are not loaded (RPC, print mode), even when the key is bound.
57
+ return `Press ${keyText("app.tools.expand") || "the expand key"} ${action}`;
58
+ }
59
+ export function liveDetailHintText() {
60
+ return expandKeyHint("for live detail");
61
+ }
62
+ function workflowDetailHintText() {
63
+ return expandKeyHint("for details");
64
+ }
65
+ function foregroundSingleHintText(shortcut) {
66
+ if (!shortcut)
67
+ return liveDetailHintText();
68
+ const label = formatShortcutLabel(shortcut);
69
+ return `${liveDetailHintText()} · ${label} to run in background`;
70
+ }
71
+ function getTermWidth() {
72
+ return process.stdout.columns || 120;
73
+ }
74
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
75
+ const ansiStylePattern = /\x1b\[[0-9;]*m/y;
76
+ /**
77
+ * Truncate a line to maxWidth, preserving ANSI styling through the ellipsis.
78
+ *
79
+ * pi-tui's truncateToWidth adds \x1b[0m before ellipsis which resets all styling,
80
+ * causing background color bleed in the TUI. This implementation tracks active
81
+ * ANSI styles and re-applies them before the ellipsis.
82
+ *
83
+ * Uses Intl.Segmenter for proper Unicode/emoji handling (not char-by-char).
84
+ */
85
+ export function truncLine(text, maxWidth) {
86
+ if (maxWidth <= 0)
87
+ return "";
88
+ if (visibleWidth(text) <= maxWidth)
89
+ return text;
90
+ const targetWidth = maxWidth - 1;
91
+ let result = "";
92
+ let currentWidth = 0;
93
+ let activeStyles = [];
94
+ let i = 0;
95
+ while (i < text.length) {
96
+ ansiStylePattern.lastIndex = i;
97
+ const ansiMatch = ansiStylePattern.exec(text);
98
+ if (ansiMatch) {
99
+ const code = ansiMatch[0];
100
+ result += code;
101
+ if (code === "\x1b[0m" || code === "\x1b[m") {
102
+ activeStyles = [];
103
+ }
104
+ else {
105
+ activeStyles.push(code);
106
+ }
107
+ i += code.length;
108
+ continue;
109
+ }
110
+ let end = text.indexOf("\x1b[", i);
111
+ if (end === i)
112
+ end = text.indexOf("\x1b[", i + 2);
113
+ if (end === -1)
114
+ end = text.length;
115
+ const textPortion = text.slice(i, end);
116
+ for (const seg of segmenter.segment(textPortion)) {
117
+ const grapheme = seg.segment;
118
+ const graphemeWidth = grapheme === "\x1b" ? 0 : visibleWidth(grapheme);
119
+ if (currentWidth + graphemeWidth > targetWidth) {
120
+ return result + activeStyles.join("") + "…";
121
+ }
122
+ result += grapheme;
123
+ currentWidth += graphemeWidth;
124
+ }
125
+ i = end;
126
+ }
127
+ return result + activeStyles.join("") + "…";
128
+ }
129
+ function wrapPlainText(text, maxWidth) {
130
+ if (maxWidth <= 0)
131
+ return [""];
132
+ const lines = [];
133
+ for (const rawLine of text.split("\n")) {
134
+ if (rawLine.length === 0) {
135
+ lines.push("");
136
+ continue;
137
+ }
138
+ let current = "";
139
+ let currentWidth = 0;
140
+ for (const seg of segmenter.segment(rawLine)) {
141
+ const grapheme = seg.segment;
142
+ const graphemeWidth = visibleWidth(grapheme);
143
+ if (graphemeWidth > maxWidth)
144
+ continue;
145
+ if (currentWidth > 0 && currentWidth + graphemeWidth > maxWidth) {
146
+ lines.push(current);
147
+ current = grapheme;
148
+ currentWidth = graphemeWidth;
149
+ continue;
150
+ }
151
+ current += grapheme;
152
+ currentWidth += graphemeWidth;
153
+ }
154
+ lines.push(current);
155
+ }
156
+ return lines;
157
+ }
158
+ const RUNNING_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
159
+ const STATIC_RUNNING_GLYPH = "●";
160
+ function runningSeed(...values) {
161
+ let seed;
162
+ for (const value of values) {
163
+ if (value === undefined || !Number.isFinite(value))
164
+ continue;
165
+ seed = (seed ?? 0) + Math.trunc(value);
166
+ }
167
+ return seed;
168
+ }
169
+ function runningGlyph(seed) {
170
+ if (seed === undefined)
171
+ return STATIC_RUNNING_GLYPH;
172
+ return RUNNING_FRAMES[Math.abs(seed) % RUNNING_FRAMES.length];
173
+ }
174
+ function animatedSeed(seed, frame) {
175
+ if (frame === undefined)
176
+ return seed;
177
+ return (seed ?? 0) + frame;
178
+ }
179
+ function progressRunningSeed(progress) {
180
+ if (!progress)
181
+ return undefined;
182
+ return runningSeed(progress.index, progress.toolCount, progress.tokens, progress.durationMs, progress.lastActivityAt, progress.currentToolStartedAt, progress.turnCount);
183
+ }
184
+ export function clearLegacyResultAnimationTimer(context) {
185
+ const timer = context.state.subagentResultAnimationTimer;
186
+ if (!timer)
187
+ return;
188
+ clearInterval(timer);
189
+ context.state.subagentResultAnimationTimer = undefined;
190
+ }
191
+ function extractOutputTarget(task) {
192
+ const writeToMatch = task.match(/\[Write to:\s*([^\]\n]+)\]/i);
193
+ if (writeToMatch?.[1]?.trim())
194
+ return writeToMatch[1].trim();
195
+ const findingsMatch = task.match(/Write your findings to(?: exactly this path)?:\s*([^\r\n]+)/i);
196
+ if (findingsMatch?.[1]?.trim())
197
+ return findingsMatch[1].trim();
198
+ const outputMatch = task.match(/[Oo]utput(?:\s+to)?\s*:\s*(\S+)/i);
199
+ if (outputMatch?.[1]?.trim())
200
+ return outputMatch[1].trim();
201
+ return undefined;
202
+ }
203
+ function hasEmptyTextOutputWithoutOutputTarget(task, output) {
204
+ if (output.trim())
205
+ return false;
206
+ return !extractOutputTarget(task);
207
+ }
208
+ function getToolCallLines(result, expanded) {
209
+ if (result.messages) {
210
+ return getDisplayItems(result.messages)
211
+ .filter((item) => item.type === "tool")
212
+ .map((item) => formatToolCall(item.name, item.args, expanded));
213
+ }
214
+ return result.toolCalls?.map((toolCall) => expanded ? toolCall.expandedText : toolCall.text) ?? [];
215
+ }
216
+ const ansiEscapePattern = /\x1b\[[0-9;]*m/g;
217
+ const noisyStatusPatterns = [
218
+ /^(?:i|we)\s+(?:will|need|can|should|am|are)\b/i,
219
+ /^i(?:'m|’m| am)\b/i,
220
+ /\bso i (?:will|need|can)\b/i,
221
+ /^(?:checking|fetching|reading|inspecting|verifying|collecting|confirming|polling)\b/i,
222
+ /^(?:async\s+subagent\s+)?[\w.-]+\s*·\s*(?:step|agent)\s+\d+\/\d+\s*·/i,
223
+ /^(?:Step|Agent)\s+\d+\/\d+:\s+[\w.-]+\s*·\s*(?:running|queued|pending|complete|completed)\b/i,
224
+ /^(?:async\s+subagent\s+)?[\w.-]+(?:\s+\[(?:fresh|fork|mixed)\])?\s*·\s*(?:running|queued|pending|complete|completed|done)\b/i,
225
+ /^Press\s+\S+\s+for\s+live\s+detail$/i,
226
+ /^output:\s+.+\/async-subagent-runs\//i,
227
+ ];
228
+ const liveOutputWordSignalPattern = /\b(?:access denied|denied|error|exception|fail(?:ed|ure)?|fatal|panic|rejected|timeout|timed out|unable|warning)\b/i;
229
+ const liveOutputCodeSignalPattern = /\bE[A-Z0-9_]{2,}\b/;
230
+ function oneLine(text) {
231
+ return text.replace(ansiEscapePattern, "").replace(/\s+/g, " ").trim();
232
+ }
233
+ const COMPACT_TASK_MAX_CHARS = 96;
234
+ /** Display label for a child run: the derived session name (agent + task
235
+ * excerpt) when the launcher provided one, else the bare agent name. */
236
+ function childDisplayName(result, fallback = "subagent") {
237
+ return result?.sessionName?.trim() || result?.agent || fallback;
238
+ }
239
+ export function compactTaskText(task, label) {
240
+ const taskText = task?.trim();
241
+ const labelText = label?.trim();
242
+ const normalizedTask = taskText && taskText !== PROMPT_REDACTED ? oneLine(taskText) : "";
243
+ const normalizedLabel = labelText && labelText !== PROMPT_REDACTED ? oneLine(labelText) : "";
244
+ const normalized = normalizedLabel && normalizedTask && normalizedLabel !== normalizedTask
245
+ ? `${normalizedLabel} — ${normalizedTask}`
246
+ : normalizedLabel || normalizedTask;
247
+ if (!normalized)
248
+ return undefined;
249
+ return previewDisplayText(normalized, COMPACT_TASK_MAX_CHARS);
250
+ }
251
+ const LANE_VALUE_MAX_CHARS = 48;
252
+ function boundedLaneValue(value, maxChars = LANE_VALUE_MAX_CHARS) {
253
+ if (!value?.trim() || value.trim() === PROMPT_REDACTED)
254
+ return undefined;
255
+ return previewDisplayText(oneLine(value), maxChars);
256
+ }
257
+ function workflowNodeStepStatus(status) {
258
+ switch (status) {
259
+ case "completed":
260
+ return "completed";
261
+ case "detached":
262
+ return "paused";
263
+ default:
264
+ return status;
265
+ }
266
+ }
267
+ function workflowNodeStatusLabel(status) {
268
+ switch (status) {
269
+ case "completed":
270
+ return "complete";
271
+ case "detached":
272
+ return "paused";
273
+ default:
274
+ return status;
275
+ }
276
+ }
277
+ function workflowStepPriority(step, currentNodeId) {
278
+ const isCurrent = step.workflowKey === currentNodeId;
279
+ if (step.status === "running" || (isCurrent && step.status !== "complete" && step.status !== "completed"))
280
+ return 0;
281
+ const gate = laneGate(step);
282
+ if (step.status === "failed"
283
+ || step.status === "partial"
284
+ || step.status === "paused"
285
+ || step.status === "stopped"
286
+ || step.status === "rejected"
287
+ || step.toolBudgetBlocked === true
288
+ || step.turnBudgetExceeded === true
289
+ || step.activityState === "needs_attention"
290
+ || step.watchdog?.phase === "stale"
291
+ || unresolvedChildWatchdogBlockers(step.watchdog).length > 0
292
+ || gate !== undefined)
293
+ return 1;
294
+ if (step.status === "pending")
295
+ return 2;
296
+ return 3;
297
+ }
298
+ /** Merge materialized child rows with the planned workflow stages for rendering. */
299
+ function workflowWidgetSteps(job, planned = job.mode === "workflow" ? workflowGraphStageNodes(job.workflowGraph) : []) {
300
+ const loaded = job.steps ?? [];
301
+ if (planned.length === 0)
302
+ return loaded;
303
+ const loadedIndexesByKey = new Map();
304
+ for (const [index, step] of loaded.entries()) {
305
+ if (!step.workflowKey)
306
+ continue;
307
+ const indexes = loadedIndexesByKey.get(step.workflowKey) ?? [];
308
+ indexes.push(index);
309
+ loadedIndexesByKey.set(step.workflowKey, indexes);
310
+ }
311
+ const consumed = new Set();
312
+ const entries = [];
313
+ for (const [order, node] of planned.entries()) {
314
+ const loadedIndex = loadedIndexesByKey.get(node.id)?.find((index) => !consumed.has(index));
315
+ if (loadedIndex !== undefined) {
316
+ consumed.add(loadedIndex);
317
+ const loadedStep = loaded[loadedIndex];
318
+ entries.push({
319
+ step: {
320
+ ...loadedStep,
321
+ index: node.flatIndex ?? loadedStep.index ?? order,
322
+ agent: loadedStep.agent || node.agent || job.agents?.[0] || "workflow",
323
+ phase: loadedStep.phase ?? node.phase,
324
+ label: loadedStep.label ?? node.label,
325
+ workflowKey: loadedStep.workflowKey ?? node.id,
326
+ ...(loadedStep.outputName === undefined && node.outputName !== undefined ? { outputName: node.outputName } : {}),
327
+ ...(loadedStep.structured === undefined && node.structured !== undefined ? { structured: node.structured } : {}),
328
+ ...(loadedStep.error === undefined && node.error !== undefined ? { error: node.error } : {}),
329
+ },
330
+ order,
331
+ });
332
+ continue;
333
+ }
334
+ entries.push({
335
+ step: {
336
+ index: node.flatIndex ?? order,
337
+ agent: node.agent ?? job.agents?.[0] ?? "workflow",
338
+ status: workflowNodeStepStatus(node.status),
339
+ workflowKey: node.id,
340
+ label: node.label,
341
+ ...(node.phase ? { phase: node.phase } : {}),
342
+ ...(node.outputName ? { outputName: node.outputName } : {}),
343
+ ...(node.structured !== undefined ? { structured: node.structured } : {}),
344
+ ...(node.error ? { error: node.error } : {}),
345
+ },
346
+ order,
347
+ });
348
+ }
349
+ for (const [index, step] of loaded.entries()) {
350
+ if (!consumed.has(index))
351
+ entries.push({ step, order: planned.length + index });
352
+ }
353
+ entries.sort((left, right) => workflowStepPriority(left.step, job.workflowGraph?.currentNodeId) - workflowStepPriority(right.step, job.workflowGraph?.currentNodeId) || left.order - right.order);
354
+ return entries.map(({ step }) => step);
355
+ }
356
+ function workflowStageProgress(job, stages = job.mode === "workflow" ? workflowGraphStageNodes(job.workflowGraph) : []) {
357
+ if (job.mode !== "workflow")
358
+ return undefined;
359
+ if (stages.length === 0)
360
+ return undefined;
361
+ const currentId = job.workflowGraph?.currentNodeId;
362
+ const currentIndex = currentId ? stages.findIndex((stage) => stage.id === currentId) : -1;
363
+ if (currentIndex >= 0 && stages[currentIndex]?.status !== "completed")
364
+ return { total: stages.length, current: currentIndex };
365
+ const runningIndex = stages.findIndex((stage) => stage.status === "running");
366
+ if (runningIndex >= 0)
367
+ return { total: stages.length, current: runningIndex };
368
+ const indexedStage = job.currentStep !== undefined && job.currentStep >= 0 ? stages[job.currentStep] : undefined;
369
+ if (indexedStage && indexedStage.status !== "completed")
370
+ return { total: stages.length, current: job.currentStep };
371
+ if (stages.every((stage) => stage.status === "completed"))
372
+ return { total: stages.length, current: stages.length - 1 };
373
+ return { total: stages.length };
374
+ }
375
+ function buildWorkflowWidgetProjection(job, now = Date.now()) {
376
+ const stages = job.mode === "workflow" ? workflowGraphStageNodes(job.workflowGraph) : [];
377
+ const stageProgress = workflowStageProgress(job, stages);
378
+ const clock = job.status === "running" ? now : job.updatedAt;
379
+ const loadedSteps = workflowWidgetSteps(job, stages);
380
+ const steps = job.mode === "workflow" ? loadedSteps.map((step) => step.status === "running" && step.startedAt !== undefined && clock !== undefined
381
+ ? { ...step, durationMs: Math.max(0, clock - step.startedAt) } : step) : loadedSteps;
382
+ const projection = { stages, steps, now };
383
+ if (stageProgress)
384
+ projection.stageProgress = stageProgress;
385
+ if (stages.length)
386
+ projection.plannedKeys = new Set(stages.map((node) => node.id));
387
+ if (job.mode === "workflow") {
388
+ const checklist = projectWorkflowChecklist({
389
+ graph: job.workflowGraph,
390
+ steps: job.steps,
391
+ hostSteps: job.hostSteps,
392
+ preflight: job.preflight,
393
+ trace: job.workflow?.trace,
394
+ now: clock,
395
+ });
396
+ if (checklist.total > 0)
397
+ projection.checklist = checklist;
398
+ }
399
+ return projection;
400
+ }
401
+ function workflowWidgetProjectionLookup(now = Date.now(), childrenByParent = new Map()) {
402
+ const projections = new WeakMap();
403
+ return (job) => {
404
+ const cached = projections.get(job);
405
+ if (cached)
406
+ return cached;
407
+ const projection = buildWorkflowWidgetProjection(job, now);
408
+ const children = childrenByParent.get(job.asyncId);
409
+ if (children?.length) {
410
+ projection.children = children;
411
+ projection.materializedKeys = new Set(children.flatMap((child) => [child.asyncId, ...(child.workflowKey ? [child.workflowKey] : [])]));
412
+ for (const step of projection.steps) {
413
+ if (step.runId && projection.materializedKeys.has(step.runId) && step.workflowKey)
414
+ projection.materializedKeys.add(step.workflowKey);
415
+ }
416
+ }
417
+ projections.set(job, projection);
418
+ return projection;
419
+ };
420
+ }
421
+ function laneStepForJob(job, steps = workflowWidgetSteps(job)) {
422
+ if (steps.length === 0)
423
+ return undefined;
424
+ const graphCurrent = job.workflowGraph?.currentNodeId;
425
+ if (graphCurrent) {
426
+ const current = steps.find((step) => step.workflowKey === graphCurrent);
427
+ if (current)
428
+ return current;
429
+ }
430
+ if (job.currentStep !== undefined) {
431
+ const current = steps[job.currentStep];
432
+ if (current && (current.index === undefined || current.index === job.currentStep))
433
+ return current;
434
+ // Active parallel groups retain flat indices while exposing only the group slice.
435
+ const indexedCurrent = steps.find((step) => step.index === job.currentStep);
436
+ if (indexedCurrent)
437
+ return indexedCurrent;
438
+ return steps[0];
439
+ }
440
+ return steps.find((step) => step.status === "running")
441
+ ?? steps.find((step) => step.status === "pending")
442
+ ?? steps.at(-1);
443
+ }
444
+ function laneTraceForJob(job) {
445
+ return Array.isArray(job.workflow?.trace) ? job.workflow.trace.at(-1) : undefined;
446
+ }
447
+ function laneGate(step) {
448
+ const review = step?.review?.status ?? step?.acceptance?.reviewResult?.status;
449
+ if (review === "blockers")
450
+ return "review blockers";
451
+ if (review === "review-required")
452
+ return "review required";
453
+ if (review === "reviewed")
454
+ return "reviewed";
455
+ const acceptance = step?.acceptance?.status;
456
+ if (acceptance === "review-required")
457
+ return "acceptance review";
458
+ if (acceptance === "checked" || acceptance === "verified" || acceptance === "accepted")
459
+ return "acceptance";
460
+ return undefined;
461
+ }
462
+ function laneNextAction(state, step, output, gate) {
463
+ if (unresolvedChildWatchdogBlockers(step?.watchdog).length > 0)
464
+ return "resolve watchdog blockers";
465
+ if (step?.watchdog?.phase === "stale")
466
+ return "inspect stale state";
467
+ if (step?.toolBudgetBlocked === true || step?.turnBudgetExceeded === true)
468
+ return "inspect blocked state";
469
+ if (gate === "review blockers")
470
+ return "resolve review blockers";
471
+ if (gate === "review required" || gate === "acceptance review")
472
+ return "review output";
473
+ if (step?.activityState === "needs_attention")
474
+ return "inspect attention";
475
+ if (state === "queued" || state === "pending")
476
+ return "await launch";
477
+ if (state === "failed" || state === "rejected")
478
+ return "inspect failure";
479
+ if (state === "partial")
480
+ return "inspect partial state";
481
+ if (state === "paused")
482
+ return "inspect paused state";
483
+ if (state === "stopped")
484
+ return "inspect stopped state";
485
+ if ((state === "complete" || state === "completed") && gate === "reviewed")
486
+ return "ready";
487
+ if ((state === "complete" || state === "completed") && output)
488
+ return "inspect output";
489
+ return undefined;
490
+ }
491
+ function isTerminalLaneState(state) {
492
+ return state !== "queued" && state !== "running";
493
+ }
494
+ /** Project already-loaded async status facts into one bounded, render-only lane row. */
495
+ export function projectAsyncLane(job, ...args) {
496
+ const selectedStep = args.length === 0 ? laneStepForJob(job) : args[0];
497
+ const trace = laneTraceForJob(job);
498
+ const workspace = job.cwd ? boundedLaneValue(shortenPath(job.cwd)) : undefined;
499
+ const label = compactTaskText(selectedStep?.description, selectedStep?.label)
500
+ ?? boundedLaneValue(trace?.label)
501
+ ?? (workspace ? undefined : boundedLaneValue(selectedStep?.workflowKey ?? job.workflowKey));
502
+ const role = boundedLaneValue(selectedStep?.agent ?? trace?.agent ?? job.agents?.[0] ?? widgetJobName(job), 32) ?? "subagent";
503
+ const phase = boundedLaneValue(selectedStep?.phase ?? trace?.phase);
504
+ const gate = laneGate(selectedStep);
505
+ const output = boundedLaneValue(selectedStep?.outputName);
506
+ const ref = boundedLaneValue(selectedStep?.workflowKey ?? job.workflowKey ?? job.asyncId.slice(0, 8), 24) ?? job.asyncId.slice(0, 8);
507
+ const chips = [
508
+ selectedStep?.context,
509
+ selectedStep?.structured ? "structured" : undefined,
510
+ selectedStep?.activityState === "active_long_running" ? "long-running" : undefined,
511
+ selectedStep?.activityState === "needs_attention" ? "attention" : undefined,
512
+ selectedStep?.watchdog?.phase === "stale" ? "stale" : undefined,
513
+ unresolvedChildWatchdogBlockers(selectedStep?.watchdog).length > 0 ? `wd:${unresolvedChildWatchdogBlockers(selectedStep?.watchdog).length}` : undefined,
514
+ selectedStep?.toolBudgetBlocked === true || selectedStep?.turnBudgetExceeded === true ? "blocked" : undefined,
515
+ ].filter((chip) => Boolean(chip));
516
+ const state = isTerminalLaneState(job.status) ? job.status : selectedStep?.status ?? job.status;
517
+ const next = laneNextAction(state, selectedStep, output, gate);
518
+ if (!label && !phase && !gate && !output && !selectedStep?.workflowKey && !job.workflowKey && !trace?.label && !trace?.phase)
519
+ return undefined;
520
+ return { ...(label ? { label } : {}), role, ...(phase ? { phase } : {}), state, ...(gate ? { gate } : {}), ...(next ? { next } : {}), ...(output ? { output } : {}), ...(workspace ? { workspace } : {}), ref, chips };
521
+ }
522
+ function laneStateLabel(state, theme) {
523
+ if (state === "running")
524
+ return theme.fg("accent", "running");
525
+ if (state === "queued" || state === "pending")
526
+ return theme.fg("muted", state);
527
+ if (state === "complete" || state === "completed")
528
+ return theme.fg("success", "complete");
529
+ if (state === "failed" || state === "rejected")
530
+ return theme.fg("error", state === "rejected" ? "rejected" : "failed");
531
+ return theme.fg("warning", state);
532
+ }
533
+ function formatLaneProjection(lane, theme) {
534
+ const label = boundedLaneValue(lane.label, 56);
535
+ const identity = [label, lane.role ? `role:${lane.role}` : undefined].filter(Boolean).join(" · ");
536
+ return `${identity ? theme.bold(identity) : theme.bold(lane.role)} · ${laneStateLabel(lane.state, theme)}`;
537
+ }
538
+ function formatLaneChip(chip, theme) {
539
+ const text = `[${chip}]`;
540
+ if (chip === "blocked")
541
+ return theme.fg("error", text);
542
+ if (chip === "stale")
543
+ return theme.fg("warning", text);
544
+ return text;
545
+ }
546
+ function formatLaneProjectionDetails(lane, theme) {
547
+ const details = [
548
+ lane.phase ? `phase:${lane.phase}` : undefined,
549
+ lane.gate ? `gate:${lane.gate}` : undefined,
550
+ lane.next ? `next:${lane.next}` : undefined,
551
+ lane.output ? `out:${lane.output}` : undefined,
552
+ lane.workspace ? `workspace:${lane.workspace}` : lane.ref ? `ref:${lane.ref}` : undefined,
553
+ ].filter(Boolean);
554
+ const chips = lane.chips.map((chip) => formatLaneChip(chip, theme));
555
+ return [...(details.length ? [theme.fg("dim", details.join(" · "))] : []), ...chips].join(" · ") || undefined;
556
+ }
557
+ function formatLaneProjectionLines(lane, theme, indent) {
558
+ const details = formatLaneProjectionDetails(lane, theme);
559
+ return [
560
+ `${indent}${formatLaneProjection(lane, theme)}`,
561
+ ...(details ? [`${indent} ${details}`] : []),
562
+ ];
563
+ }
564
+ function laneRenderKey(job, projection) {
565
+ const selectedStep = projection ? laneStepForJob(job, projection.steps) : laneStepForJob(job);
566
+ const lane = projectAsyncLane(job, selectedStep);
567
+ return lane ? [lane.label, lane.role, lane.phase, lane.state, lane.gate, lane.next, lane.output, lane.workspace, lane.ref, lane.chips] : undefined;
568
+ }
569
+ function widgetLaneDetailLines(job, theme, projection) {
570
+ if (job.steps?.length && (job.mode === "parallel" || job.mode === "chain"))
571
+ return [];
572
+ const selectedStep = projection ? laneStepForJob(job, projection.steps) : laneStepForJob(job);
573
+ const lane = projectAsyncLane(job, selectedStep);
574
+ return lane ? formatLaneProjectionLines(lane, theme, " ") : [];
575
+ }
576
+ function workflowPreflightLines(job) {
577
+ if (job.mode !== "workflow" || !job.preflight)
578
+ return [];
579
+ return [
580
+ ...formatWorkflowPreflight(job.preflight, { indent: " " }).split("\n"),
581
+ ...(job.workflow?.preflightWarnings ? formatWorkflowPreflightWarnings(job.workflow.preflightWarnings, { indent: " " }).split("\n") : []),
582
+ ];
583
+ }
584
+ function workflowLabelForResult(details, resultIndex) {
585
+ const flatIndex = foregroundResultIndex(details, resultIndex);
586
+ const visit = (nodes) => {
587
+ for (const node of nodes) {
588
+ if (node.flatIndex === flatIndex && node.label.trim())
589
+ return node.label;
590
+ const nested = node.children ? visit(node.children) : undefined;
591
+ if (nested)
592
+ return nested;
593
+ }
594
+ return undefined;
595
+ };
596
+ return details.workflowGraph ? visit(details.workflowGraph.nodes) : undefined;
597
+ }
598
+ function foregroundProgressForResult(details, resultIndex) {
599
+ const result = details.results[resultIndex];
600
+ if (result?.progress)
601
+ return result.progress;
602
+ const index = result?.index ?? resultIndex;
603
+ const indexed = details.progress?.find((progress) => progress.index === index);
604
+ if (indexed)
605
+ return indexed;
606
+ return result?.agent
607
+ ? details.progress?.find((progress) => progress.agent === result.agent && progress.status === "running")
608
+ : undefined;
609
+ }
610
+ function foregroundResultIndex(details, resultIndex) {
611
+ const result = details.results[resultIndex];
612
+ if (typeof result?.index === "number")
613
+ return result.index;
614
+ return foregroundProgressForResult(details, resultIndex)?.index ?? resultIndex;
615
+ }
616
+ function foregroundResultDisplayName(details, resultIndex, result, fallback) {
617
+ const progress = foregroundProgressForResult(details, resultIndex);
618
+ const agent = normalizedParallelDisplayText(result?.agent) ?? normalizedParallelDisplayText(progress?.agent);
619
+ const workflowLabel = normalizedParallelDisplayText(workflowLabelForResult(details, resultIndex));
620
+ if (workflowLabel)
621
+ return compactTaskText(undefined, workflowLabel) ?? workflowLabel;
622
+ const sessionName = normalizedParallelDisplayText(result?.sessionName) ?? normalizedParallelDisplayText(progress?.sessionName);
623
+ if (sessionName) {
624
+ const sessionTask = stripRepeatedAgentPrefix(sessionName, agent);
625
+ if (sessionTask && sessionTask !== PROMPT_REDACTED && sessionTask.toLowerCase() !== agent?.toLowerCase()) {
626
+ return compactTaskText(sessionTask) ?? sessionTask;
627
+ }
628
+ }
629
+ return compactTaskText(result?.task) ?? compactTaskText(progress?.task) ?? agent ?? fallback;
630
+ }
631
+ function foregroundSingleDisplayName(result) {
632
+ return normalizedParallelDisplayText(result?.agent)
633
+ ?? normalizedParallelDisplayText(result?.sessionName)
634
+ ?? compactTaskText(result?.task)
635
+ ?? "subagent";
636
+ }
637
+ function hasLiveOutputSignal(line) {
638
+ const clean = oneLine(line);
639
+ return liveOutputWordSignalPattern.test(clean) || liveOutputCodeSignalPattern.test(clean);
640
+ }
641
+ function isNoisyStatusLine(line) {
642
+ const clean = oneLine(line);
643
+ return clean.length > 0
644
+ && clean.length <= 240
645
+ && !hasLiveOutputSignal(clean)
646
+ && noisyStatusPatterns.some((pattern) => pattern.test(clean));
647
+ }
648
+ function latestActivityText(line) {
649
+ return oneLine(line)
650
+ .replace(/^i (?:will|can|need to|am going to)\s+/i, "")
651
+ .replace(/^i(?:'m|’m| am)\s+/i, "");
652
+ }
653
+ function progressUpdateSummary(lines) {
654
+ const counts = new Map();
655
+ for (const line of lines)
656
+ counts.set(line.toLowerCase(), (counts.get(line.toLowerCase()) ?? 0) + 1);
657
+ const exactRepeatCount = Math.max(...counts.values());
658
+ const latest = latestActivityText(lines[lines.length - 1]);
659
+ const repeat = exactRepeatCount > 1 ? ` · repeated ${exactRepeatCount}×` : "";
660
+ return `↻ ${lines.length} progress updates${repeat} · latest: ${latest}`;
661
+ }
662
+ function compactRecentOutputLines(recentOutput) {
663
+ const lines = [];
664
+ const noisyLines = [];
665
+ const otherLines = [];
666
+ for (const rawLine of recentOutput ?? []) {
667
+ const line = oneLine(rawLine);
668
+ if (!line || line === "(running...)")
669
+ continue;
670
+ lines.push(line);
671
+ (isNoisyStatusLine(line) ? noisyLines : otherLines).push(line);
672
+ }
673
+ if (noisyLines.length >= 4 && !otherLines.some(hasLiveOutputSignal)) {
674
+ if (otherLines.length === 0) {
675
+ return [
676
+ progressUpdateSummary(noisyLines),
677
+ "pattern: repeated short status lines",
678
+ ];
679
+ }
680
+ const visibleTail = otherLines.slice(-3);
681
+ const hiddenSignals = otherLines.slice(0, -3).filter(hasLiveOutputSignal);
682
+ return [
683
+ progressUpdateSummary(noisyLines),
684
+ ...(hiddenSignals.length > 0 ? [`… ${hiddenSignals.length} older signal ${hiddenSignals.length === 1 ? "line" : "lines"}: ${hiddenSignals.at(-1)}`] : []),
685
+ ...visibleTail,
686
+ ].slice(0, 5);
687
+ }
688
+ if (lines.length <= 5)
689
+ return lines;
690
+ const tail = lines.slice(-5);
691
+ const hiddenSignals = lines.slice(0, -5).filter(hasLiveOutputSignal);
692
+ if (hiddenSignals.length === 0)
693
+ return tail;
694
+ return [
695
+ `… ${hiddenSignals.length} older signal ${hiddenSignals.length === 1 ? "line" : "lines"}: ${hiddenSignals.at(-1)}`,
696
+ ...lines.slice(-4),
697
+ ];
698
+ }
699
+ function compactWorkflowError(error) {
700
+ const outputMatch = error.match(/(?:^|\n)Output:\s*([\s\S]+)/);
701
+ if (!outputMatch)
702
+ return oneLine(error);
703
+ const prefix = oneLine(error.slice(0, outputMatch.index)).replace(/:$/, "") || "Failed";
704
+ const outputLines = outputMatch[1].split(/\r?\n/).map(oneLine).filter(Boolean);
705
+ const allOutputLinesAreNoisy = outputLines.length > 0 && outputLines.every(isNoisyStatusLine);
706
+ const latest = outputLines.at(-1);
707
+ return allOutputLinesAreNoisy && latest
708
+ ? `${prefix} · latest: ${latestActivityText(latest)}`
709
+ : `${prefix} · ${oneLine(outputMatch[1] ?? "")}`;
710
+ }
711
+ const WORKFLOW_LIVE_ROW_LIMIT = 8;
712
+ function visibleWorkflowRows(rows) {
713
+ if (rows.length <= WORKFLOW_LIVE_ROW_LIMIT)
714
+ return { rows, hiddenRows: 0 };
715
+ const selected = new Set();
716
+ const add = (row) => {
717
+ if (selected.size >= WORKFLOW_LIVE_ROW_LIMIT || selected.has(row.key))
718
+ return;
719
+ selected.add(row.key);
720
+ };
721
+ for (const row of [...rows].reverse()) {
722
+ if (row.state === "failed" || row.state === "detached")
723
+ add(row);
724
+ }
725
+ for (const row of [...rows].reverse())
726
+ add(row);
727
+ return {
728
+ rows: rows.filter((row) => selected.has(row.key)),
729
+ hiddenRows: rows.length - selected.size,
730
+ };
731
+ }
732
+ function snapshotNowForProgress(progress) {
733
+ if (progress.currentToolStartedAt !== undefined && progress.durationMs !== undefined)
734
+ return progress.currentToolStartedAt + progress.durationMs;
735
+ return progress.lastActivityAt;
736
+ }
737
+ function renderToolArgsPreview(value, maxLength, expanded) {
738
+ const normalized = sanitizeDisplayText(value);
739
+ if (expanded || normalized.length <= maxLength)
740
+ return normalized;
741
+ return `${truncateDisplayText(normalized, maxLength)}...`;
742
+ }
743
+ function formatCurrentToolLine(progress, availableWidth, expanded, snapshotNow) {
744
+ if (!progress.currentTool)
745
+ return undefined;
746
+ const maxToolArgsLen = Math.max(50, availableWidth - 20);
747
+ const toolArgsPreview = progress.currentToolArgs
748
+ ? renderToolArgsPreview(progress.currentToolArgs, maxToolArgsLen, expanded)
749
+ : "";
750
+ const durationSuffix = progress.currentToolStartedAt !== undefined && snapshotNow !== undefined
751
+ ? ` | ${formatDuration(Math.max(0, snapshotNow - progress.currentToolStartedAt))}`
752
+ : "";
753
+ return toolArgsPreview
754
+ ? `${progress.currentTool}: ${toolArgsPreview}${durationSuffix}`
755
+ : `${progress.currentTool}${durationSuffix}`;
756
+ }
757
+ function buildLiveStatusLine(progress, snapshotNow) {
758
+ if (progress.lastActivityAt !== undefined && snapshotNow !== undefined)
759
+ return formatActivityLabel(progress.lastActivityAt, progress.activityState, snapshotNow);
760
+ if (progress.activityState === "needs_attention")
761
+ return "needs attention";
762
+ if (progress.activityState === "active_long_running")
763
+ return "active but long-running";
764
+ if (progress.lastActivityAt !== undefined)
765
+ return "active";
766
+ return undefined;
767
+ }
768
+ function themeBold(theme, text) {
769
+ return (theme.bold?.(text)) ?? text;
770
+ }
771
+ function statJoin(theme, parts) {
772
+ return parts.filter(Boolean).map((part) => theme.fg("dim", part)).join(` ${theme.fg("dim", "·")} `);
773
+ }
774
+ function formatTokenStat(tokens) {
775
+ return `${formatTokens(tokens)} token`;
776
+ }
777
+ function formatToolUseStat(count) {
778
+ return `${count} tool use${count === 1 ? "" : "s"}`;
779
+ }
780
+ function formatTotalCostStat(totalCost) {
781
+ if (!totalCost || (totalCost.inputTokens === 0 && totalCost.outputTokens === 0 && totalCost.costUsd === 0))
782
+ return "";
783
+ const parts = [];
784
+ if (totalCost.inputTokens)
785
+ parts.push(`in:${formatTokens(totalCost.inputTokens)}`);
786
+ if (totalCost.outputTokens)
787
+ parts.push(`out:${formatTokens(totalCost.outputTokens)}`);
788
+ if (totalCost.costUsd)
789
+ parts.push(`$${totalCost.costUsd.toFixed(4)}`);
790
+ return parts.join(" ");
791
+ }
792
+ function formatProgressStats(theme, progress, includeDuration = true) {
793
+ if (!progress)
794
+ return "";
795
+ const parts = [];
796
+ if (progress.toolCount > 0)
797
+ parts.push(formatToolUseStat(progress.toolCount));
798
+ if (progress.tokens > 0)
799
+ parts.push(formatTokenStat(progress.tokens));
800
+ if (includeDuration && progress.durationMs > 0)
801
+ parts.push(formatDuration(progress.durationMs));
802
+ return statJoin(theme, parts);
803
+ }
804
+ function firstOutputLine(text) {
805
+ return text.split("\n").find((line) => line.trim())?.trim() ?? "";
806
+ }
807
+ function resultStatusLine(result, output) {
808
+ if (result.detached)
809
+ return result.detachedReason ? `Detached: ${result.detachedReason}` : "Detached";
810
+ if (result.stopped)
811
+ return "Stopped";
812
+ if (result.interrupted)
813
+ return "Paused";
814
+ if (result.exitCode !== 0)
815
+ return `Error: ${result.error ?? (firstOutputLine(output) || `exit ${result.exitCode}`)}`;
816
+ if (result.acceptance?.status && result.acceptance.status !== "not-required")
817
+ return `Done · acceptance: ${result.acceptance.status}`;
818
+ if (hasEmptyTextOutputWithoutOutputTarget(result.task, output))
819
+ return "Done (no text output)";
820
+ return "Done";
821
+ }
822
+ function semanticResultPresentation(input) {
823
+ if (input.running) {
824
+ const glyph = input.frame !== undefined ? runningGlyph((input.seed ?? 0) + input.frame) : runningGlyph(input.seed);
825
+ return { glyph, label: "running", tone: "accent", ...(input.thinking ? { thinking: input.thinking } : {}) };
826
+ }
827
+ if (input.detached)
828
+ return { glyph: "■", label: "detached", tone: "warning" };
829
+ if (input.stopped)
830
+ return { glyph: "■", label: "stopped", tone: "warning" };
831
+ if (input.interrupted)
832
+ return { glyph: "■", label: "paused", tone: "warning" };
833
+ if (input.failed)
834
+ return { glyph: "✗", label: "failed", tone: "error" };
835
+ if (input.partial)
836
+ return { glyph: "■", label: "partial", tone: "warning" };
837
+ return { glyph: "✓", label: "completed", tone: input.completedWithoutOutput ? "warning" : "success" };
838
+ }
839
+ function hasTerminalResultFlag(result) {
840
+ return Boolean(result.detached || result.stopped || result.interrupted);
841
+ }
842
+ function hasTerminalResult(result) {
843
+ if (hasTerminalResultFlag(result))
844
+ return true;
845
+ const status = result.progress?.status;
846
+ if (status === "running" || status === "pending")
847
+ return false;
848
+ return result.exitCode !== undefined;
849
+ }
850
+ function isResultRunning(result, status = result.progress?.status) {
851
+ return status === "running" && !hasTerminalResultFlag(result);
852
+ }
853
+ function detailsHaveRunningResult(details) {
854
+ return details.progress?.some((progress) => {
855
+ if (progress.status !== "running")
856
+ return false;
857
+ const result = details.results.find((entry) => entry.progress?.index === progress.index) ?? details.results[progress.index];
858
+ return !result || !hasTerminalResultFlag(result);
859
+ })
860
+ || details.results.some((result) => isResultRunning(result))
861
+ || workflowGraphHasStatus(details, ["running"]);
862
+ }
863
+ function resultPresentation(result, output, running = isResultRunning(result), seed = progressRunningSeed(result.progress ?? result.progressSummary), frame) {
864
+ return semanticResultPresentation({
865
+ running,
866
+ detached: result.detached,
867
+ stopped: result.stopped,
868
+ interrupted: result.interrupted,
869
+ failed: result.exitCode !== 0,
870
+ completedWithoutOutput: hasEmptyTextOutputWithoutOutputTarget(result.task, output),
871
+ seed,
872
+ frame,
873
+ thinking: childThinkingLevel(result, result.progress),
874
+ });
875
+ }
876
+ function presentationTone(presentation, theme) {
877
+ return presentation.label === "running" ? runningTone(theme, presentation.thinking) : (text) => theme.fg(presentation.tone, text);
878
+ }
879
+ function resultGlyph(result, output, theme, running = isResultRunning(result), seed = progressRunningSeed(result.progress ?? result.progressSummary), frame) {
880
+ const presentation = resultPresentation(result, output, running, seed, frame);
881
+ return presentationTone(presentation, theme)(presentation.glyph);
882
+ }
883
+ function styledResultPresentation(presentation, theme) {
884
+ const tone = presentationTone(presentation, theme);
885
+ return {
886
+ glyph: tone(presentation.glyph),
887
+ label: tone(presentation.label),
888
+ };
889
+ }
890
+ function compactCurrentActivity(progress) {
891
+ const snapshotNow = snapshotNowForProgress(progress);
892
+ return formatCurrentToolLine(progress, getTermWidth() - 4, false, snapshotNow) ?? buildLiveStatusLine(progress, snapshotNow) ?? "thinking…";
893
+ }
894
+ function textDigest(text) {
895
+ return createHash("sha256").update(text).digest("hex").slice(0, 16);
896
+ }
897
+ function displayTextRenderKey(text) {
898
+ const normalized = sanitizeDisplayText(text);
899
+ return [normalized.length, textDigest(normalized)];
900
+ }
901
+ function expandedStepActivityRenderKey(step) {
902
+ return [
903
+ step.recentTools?.slice(-3).map((tool) => [tool.tool, displayTextRenderKey(tool.args), tool.endMs]),
904
+ compactRecentOutputLines(step.recentOutput).map(displayTextRenderKey),
905
+ ];
906
+ }
907
+ function widgetStepRenderKey(step, index, expanded = false) {
908
+ return [
909
+ step.index ?? index,
910
+ step.agent,
911
+ step.sessionName,
912
+ step.workflowKey,
913
+ step.phase,
914
+ step.label,
915
+ step.status,
916
+ step.activityState,
917
+ step.lastActivityAt,
918
+ step.currentTool,
919
+ step.currentToolArgs,
920
+ step.currentToolStartedAt,
921
+ step.currentPath,
922
+ step.turnCount,
923
+ step.toolCount,
924
+ step.startedAt,
925
+ step.endedAt,
926
+ step.durationMs,
927
+ step.tokens?.total,
928
+ step.model,
929
+ step.thinking,
930
+ step.context,
931
+ step.description,
932
+ step.outputName,
933
+ step.structured,
934
+ step.acceptance?.status,
935
+ step.acceptance?.reviewResult?.status,
936
+ step.review?.status,
937
+ step.toolBudgetBlocked,
938
+ step.turnBudgetExceeded,
939
+ step.timedOut,
940
+ step.stopped,
941
+ step.execution?.status,
942
+ step.execution?.error,
943
+ step.execution?.timedOut,
944
+ step.execution?.interrupted,
945
+ step.execution?.stopped,
946
+ step.execution?.detached,
947
+ step.watchdog?.phase,
948
+ unresolvedChildWatchdogBlockers(step.watchdog).length,
949
+ step.error,
950
+ expanded ? expandedStepActivityRenderKey(step) : undefined,
951
+ nestedRenderKey(step.children, expanded),
952
+ ];
953
+ }
954
+ function nestedRenderKey(children, expanded = false) {
955
+ return (children ?? []).map((child) => [
956
+ child.id,
957
+ child.state,
958
+ child.agent,
959
+ child.sessionName,
960
+ child.model,
961
+ child.thinking,
962
+ child.activityState,
963
+ child.lastActivityAt,
964
+ child.currentTool,
965
+ child.currentToolStartedAt,
966
+ child.currentPath,
967
+ child.turnCount,
968
+ child.toolCount,
969
+ child.startedAt,
970
+ child.endedAt,
971
+ child.lastUpdate,
972
+ child.error,
973
+ child.totalTokens?.total,
974
+ child.steps?.map((step, index) => widgetStepRenderKey({ ...step, agent: step.agent, status: step.status }, index, expanded)),
975
+ nestedRenderKey(child.children, expanded),
976
+ ]);
977
+ }
978
+ function hostStepRenderKey(row) {
979
+ return [
980
+ row.kind,
981
+ row.name,
982
+ row.state,
983
+ row.provider,
984
+ row.role,
985
+ row.verdict,
986
+ row.reasonCode,
987
+ row.detail,
988
+ row.target,
989
+ row.freshness,
990
+ row.reportPath,
991
+ ];
992
+ }
993
+ export function widgetRenderKey(job, expanded = false) {
994
+ const projection = buildWorkflowWidgetProjection(job, job.updatedAt ?? 0);
995
+ return JSON.stringify({
996
+ asyncDir: job.asyncDir,
997
+ parentWorkflowRunId: job.parentWorkflowRunId,
998
+ workflowKey: job.workflowKey,
999
+ status: job.status,
1000
+ description: job.mode === "workflow" ? job.description : undefined,
1001
+ activityState: job.activityState,
1002
+ lastActivityAt: job.lastActivityAt,
1003
+ currentTool: job.currentTool,
1004
+ currentToolStartedAt: job.currentToolStartedAt,
1005
+ currentPath: job.currentPath,
1006
+ turnCount: job.turnCount,
1007
+ toolCount: job.toolCount,
1008
+ mode: job.mode,
1009
+ agents: job.agents,
1010
+ currentStep: job.currentStep,
1011
+ chainStepCount: job.chainStepCount,
1012
+ parallelGroups: job.parallelGroups,
1013
+ workflowHostSteps: projectAsyncWorkflowRows([], job.hostSteps).map(hostStepRenderKey),
1014
+ workflowGraph: job.mode === "workflow" && job.workflowGraph ? {
1015
+ currentNodeId: job.workflowGraph.currentNodeId,
1016
+ stages: projection.stages.map((node) => [node.id, node.status, node.agent, node.phase, node.label, node.flatIndex, node.outputName, node.structured, node.error]),
1017
+ } : undefined,
1018
+ preflight: expanded ? job.preflight : job.preflight?.lanes.map((lane) => [lane.key, lane.mode, lane.decision, lane.claims, lane.expectedOutput]),
1019
+ preflightWarnings: expanded ? job.workflow?.preflightWarnings : undefined,
1020
+ checklist: projection.checklist ? {
1021
+ total: projection.checklist.total,
1022
+ done: projection.checklist.done,
1023
+ running: projection.checklist.running,
1024
+ queued: projection.checklist.queued,
1025
+ blocked: projection.checklist.blocked,
1026
+ failed: projection.checklist.failed,
1027
+ phases: projection.checklist.phases.map((phase) => [phase.key, phase.state, phase.done, phase.total, phase.running, phase.queued, phase.blocked, phase.failed, phase.paused, phase.stopped, phase.items.map((item) => [item.key, item.label, item.agent, item.state, item.preflight?.key, item.preflight?.mode, item.preflight?.decision, item.preflight?.claims, item.preflight?.expectedOutput, item.currentTool, item.currentPath, item.durationMs, item.toolCount, item.error])]),
1028
+ } : undefined,
1029
+ steps: job.steps?.map((step, index) => widgetStepRenderKey(step, index, expanded)),
1030
+ nestedChildren: nestedRenderKey(job.nestedChildren, expanded),
1031
+ lane: laneRenderKey(job, projection),
1032
+ stepsTotal: job.stepsTotal,
1033
+ runningSteps: job.runningSteps,
1034
+ completedSteps: job.completedSteps,
1035
+ activeParallelGroup: job.activeParallelGroup,
1036
+ startedAt: job.startedAt,
1037
+ updatedAt: job.updatedAt,
1038
+ timedOut: job.timedOut,
1039
+ stopped: job.stopped,
1040
+ totalTokens: job.totalTokens,
1041
+ });
1042
+ }
1043
+ function formatWidgetAgents(agents) {
1044
+ const distinct = [...new Set(agents)];
1045
+ if (distinct.length === 1 && agents.length > 1)
1046
+ return `${distinct[0]} ×${agents.length}`;
1047
+ if (agents.length > 3)
1048
+ return `${agents.slice(0, 2).join(", ")} +${agents.length - 2} more`;
1049
+ return agents.join(", ");
1050
+ }
1051
+ function widgetJobName(job) {
1052
+ if (job.mode === "parallel")
1053
+ return "parallel";
1054
+ if (job.mode === "chain")
1055
+ return "chain";
1056
+ if (job.mode === "single" && job.agents?.length === 1)
1057
+ return job.agents[0];
1058
+ if (job.agents?.length)
1059
+ return formatWidgetAgents(job.agents);
1060
+ return job.mode ?? "subagent";
1061
+ }
1062
+ function isSingleChildAsyncJob(job) {
1063
+ return job.mode === "single"
1064
+ && job.steps?.length === 1
1065
+ && shouldSuppressSingleStep(job.chainStepCount, job.stepsTotal);
1066
+ }
1067
+ function isCompletedWidgetStepStatus(status) {
1068
+ return status === "complete" || status === "completed";
1069
+ }
1070
+ function singleChildAgentName(job, step) {
1071
+ return job.agents?.length === 1 ? job.agents[0] : step.agent || widgetJobName(job);
1072
+ }
1073
+ function hasSingleChildDetailEvidence(job, step) {
1074
+ return Boolean(step.error?.trim()
1075
+ || step.execution?.error?.trim()
1076
+ || step.phase?.trim()
1077
+ || step.label?.trim()
1078
+ || step.workflowKey?.trim()
1079
+ || step.outputName?.trim()
1080
+ || step.lane
1081
+ || job.workflowKey?.trim()
1082
+ || job.lane
1083
+ || laneTraceForJob(job)?.phase?.trim()
1084
+ || laneTraceForJob(job)?.label?.trim()
1085
+ || step.timedOut
1086
+ || step.stopped
1087
+ || step.execution?.timedOut
1088
+ || step.execution?.interrupted
1089
+ || step.execution?.stopped
1090
+ || step.execution?.detached
1091
+ || job.timedOut
1092
+ || job.stopped
1093
+ || ["failed", "partial", "paused", "stopped", "detached"].includes(step.execution?.status ?? "")
1094
+ || step.acceptance?.status === "rejected"
1095
+ || step.acceptance?.reviewResult?.status === "blockers"
1096
+ || step.review?.status === "blockers");
1097
+ }
1098
+ function shouldCollapseSingleChildDetails(job, step) {
1099
+ if (!isSingleChildAsyncJob(job) || hasSingleChildDetailEvidence(job, step))
1100
+ return false;
1101
+ if (job.status === "running")
1102
+ return step.status === "running";
1103
+ if (job.status === "complete")
1104
+ return isCompletedWidgetStepStatus(step.status);
1105
+ return false;
1106
+ }
1107
+ /** A child's task in one line: its label and task, else its session name without the repeated agent name. */
1108
+ export function stepTaskSummary(step, agentName) {
1109
+ const task = compactTaskText(step.description, step.label);
1110
+ if (task)
1111
+ return task;
1112
+ const sessionName = step.sessionName?.trim();
1113
+ if (!sessionName)
1114
+ return undefined;
1115
+ const sessionTask = stripRepeatedAgentPrefix(sessionName, agentName);
1116
+ return sessionTask === agentName ? undefined : compactTaskText(sessionTask);
1117
+ }
1118
+ function widgetActivity(job) {
1119
+ const facts = [];
1120
+ if (job.currentTool && job.currentToolStartedAt !== undefined && job.updatedAt !== undefined)
1121
+ facts.push(`${job.currentTool} ${formatDuration(Math.max(0, job.updatedAt - job.currentToolStartedAt))}`);
1122
+ else if (job.currentTool)
1123
+ facts.push(job.currentTool);
1124
+ if (job.currentPath)
1125
+ facts.push(shortenPath(job.currentPath));
1126
+ if (job.turnCount !== undefined)
1127
+ facts.push(`${job.turnCount} turns`);
1128
+ if (job.toolCount !== undefined)
1129
+ facts.push(`${job.toolCount} tools`);
1130
+ const activity = buildLiveStatusLine(job, job.updatedAt);
1131
+ if (activity && facts.length)
1132
+ return `${activity} · ${facts.join(" · ")}`;
1133
+ if (activity)
1134
+ return activity;
1135
+ if (facts.length)
1136
+ return facts.join(" · ");
1137
+ if (job.status === "running")
1138
+ return "thinking…";
1139
+ if (job.status === "queued")
1140
+ return "queued…";
1141
+ if (job.status === "paused")
1142
+ return "Paused";
1143
+ if (job.status === "stopped")
1144
+ return "Stopped";
1145
+ if (job.status === "partial")
1146
+ return "Partial";
1147
+ if (job.status === "failed")
1148
+ return "Failed";
1149
+ return "Done";
1150
+ }
1151
+ function widgetStepRunningSeed(step, fallbackIndex) {
1152
+ return runningSeed(fallbackIndex, step.index, step.toolCount, step.turnCount, step.tokens?.total, step.lastActivityAt, step.currentToolStartedAt, step.durationMs);
1153
+ }
1154
+ function widgetStepsRunningSeed(steps) {
1155
+ let seed;
1156
+ for (const [index, step] of (steps ?? []).entries())
1157
+ seed = runningSeed(seed, widgetStepRunningSeed(step, index));
1158
+ return seed;
1159
+ }
1160
+ function widgetJobRunningSeed(job) {
1161
+ return runningSeed(job.updatedAt, job.lastActivityAt, job.toolCount, job.turnCount, job.totalTokens?.total, job.currentStep, job.runningSteps, job.completedSteps, widgetStepsRunningSeed(job.steps));
1162
+ }
1163
+ function widgetJobsRunningSeed(jobs) {
1164
+ let seed;
1165
+ for (const job of jobs)
1166
+ seed = runningSeed(seed, widgetJobRunningSeed(job));
1167
+ return seed;
1168
+ }
1169
+ function activeHeaderTone(theme, hasActive) {
1170
+ return hasActive ? runningTone(theme) : (text) => theme.fg("dim", text);
1171
+ }
1172
+ function widgetStatusGlyph(job, theme, frame) {
1173
+ if (job.status === "running")
1174
+ return runningTone(theme, job.mode === "single" ? childThinkingLevel(job.steps?.[0]) : undefined)(runningGlyph(animatedSeed(widgetJobRunningSeed(job), frame)));
1175
+ if (job.status === "queued")
1176
+ return theme.fg("muted", "◦");
1177
+ if (job.status === "complete")
1178
+ return theme.fg("success", "✓");
1179
+ if (job.status === "paused")
1180
+ return theme.fg("warning", "■");
1181
+ if (job.status === "stopped")
1182
+ return theme.fg("warning", "■");
1183
+ return theme.fg("error", "✗");
1184
+ }
1185
+ function widgetStepGlyph(status, theme, seed, frame, thinking) {
1186
+ if (status === "running")
1187
+ return runningTone(theme, thinking)(runningGlyph(animatedSeed(seed, frame)));
1188
+ if (status === "complete" || status === "completed")
1189
+ return theme.fg("success", "✓");
1190
+ if (status === "failed")
1191
+ return theme.fg("error", "✗");
1192
+ if (status === "paused")
1193
+ return theme.fg("warning", "■");
1194
+ if (status === "stopped")
1195
+ return theme.fg("warning", "■");
1196
+ return theme.fg("muted", "◦");
1197
+ }
1198
+ function widgetStepStatus(status, theme, thinking) {
1199
+ if (status === "running")
1200
+ return runningTone(theme, thinking)("running");
1201
+ if (status === "complete" || status === "completed")
1202
+ return theme.fg("success", "complete");
1203
+ if (status === "failed")
1204
+ return theme.fg("error", "failed");
1205
+ if (status === "paused")
1206
+ return theme.fg("warning", "paused");
1207
+ if (status === "stopped")
1208
+ return theme.fg("warning", "stopped");
1209
+ return theme.fg("dim", status);
1210
+ }
1211
+ function workflowChecklistStateLabel(state) {
1212
+ if (state === "running")
1213
+ return "running";
1214
+ if (state === "complete")
1215
+ return "complete";
1216
+ return state;
1217
+ }
1218
+ function workflowChecklistGlyph(item, theme, frame) {
1219
+ if (item.state === "running")
1220
+ return runningTone(theme, item.thinking)(runningGlyph(animatedSeed(runningSeed(item.startedAt, item.durationMs, item.toolCount, item.currentToolStartedAt), frame)));
1221
+ if (item.state === "complete")
1222
+ return theme.fg("success", "✓");
1223
+ if (item.state === "blocked")
1224
+ return theme.fg("error", "!");
1225
+ if (item.state === "failed")
1226
+ return theme.fg("error", "✗");
1227
+ if (item.state === "paused" || item.state === "stopped")
1228
+ return theme.fg("warning", "■");
1229
+ return theme.fg("muted", "◦");
1230
+ }
1231
+ function workflowChecklistItemPriority(state) {
1232
+ if (state === "blocked")
1233
+ return 0;
1234
+ if (state === "failed")
1235
+ return 1;
1236
+ if (state === "running")
1237
+ return 2;
1238
+ if (state === "paused")
1239
+ return 3;
1240
+ if (state === "stopped")
1241
+ return 4;
1242
+ if (state === "queued")
1243
+ return 5;
1244
+ return 6;
1245
+ }
1246
+ function workflowChecklistItemLine(item, theme, indent, frame, includeError) {
1247
+ const identity = [item.label, item.agent && item.agent !== item.label ? item.agent : undefined].filter(Boolean).join(" · ");
1248
+ const context = contextModeBadge(theme, item.context);
1249
+ const state = item.state === "complete" ? "" : ` ${theme.fg("dim", `· ${workflowChecklistStateLabel(item.state)}`)}`;
1250
+ const details = [
1251
+ item.currentTool ? `${item.currentTool}${item.durationMs !== undefined ? ` ${formatDuration(item.durationMs)}` : ""}` : undefined,
1252
+ !item.currentTool && item.currentPath ? shortenPath(item.currentPath) : undefined,
1253
+ !item.currentTool && item.durationMs !== undefined ? formatDuration(item.durationMs) : undefined,
1254
+ item.toolCount !== undefined ? `${item.toolCount} tools` : undefined,
1255
+ item.outputName ? `out:${item.outputName}` : undefined,
1256
+ includeError && item.error ? `error:${oneLine(item.error)}` : undefined,
1257
+ ].filter(Boolean).join(" · ");
1258
+ return `${indent}${workflowChecklistGlyph(item, theme, frame)} ${theme.bold(identity || item.key)}${context}${state}${details ? ` ${theme.fg("dim", `· ${details}`)}` : ""}`;
1259
+ }
1260
+ const COLLAPSED_WORKFLOW_PHASE_LIMIT = 4;
1261
+ function workflowChecklistWidgetLines(checklist, theme, indent, expanded, frame, options = {}) {
1262
+ if (!checklist?.total)
1263
+ return [];
1264
+ const includeSummary = options.includeSummary ?? true;
1265
+ const limitPhases = options.limitPhases ?? !expanded;
1266
+ const includeBottleneckOutput = options.includeBottleneckOutput ?? expanded;
1267
+ const includeItemErrors = options.includeItemErrors ?? true;
1268
+ const lines = includeSummary ? [`${indent}${theme.fg("dim", `Checklist ${formatWorkflowChecklistSummary(checklist)}`)}`] : [];
1269
+ const phases = !limitPhases || checklist.phases.length <= COLLAPSED_WORKFLOW_PHASE_LIMIT
1270
+ ? checklist.phases
1271
+ : checklist.phases
1272
+ .map((phase, index) => ({ phase, index }))
1273
+ .sort((left, right) => Number(left.phase.state !== "running") - Number(right.phase.state !== "running")
1274
+ || Number(left.phase.state === "complete") - Number(right.phase.state === "complete")
1275
+ || left.index - right.index)
1276
+ .slice(0, COLLAPSED_WORKFLOW_PHASE_LIMIT)
1277
+ .sort((left, right) => left.index - right.index)
1278
+ .map(({ phase }) => phase);
1279
+ for (const phase of phases) {
1280
+ const phaseItem = phase.items.find((item) => item.state === "running") ?? phase.items[0];
1281
+ const glyph = workflowChecklistGlyph({
1282
+ state: phase.state,
1283
+ startedAt: phaseItem?.startedAt,
1284
+ durationMs: phaseItem?.durationMs,
1285
+ toolCount: phaseItem?.toolCount,
1286
+ currentToolStartedAt: phaseItem?.currentToolStartedAt,
1287
+ }, theme, frame);
1288
+ lines.push(`${indent}${glyph} ${theme.bold(formatWorkflowChecklistPhase(phase))}`);
1289
+ if (expanded) {
1290
+ for (const item of [...phase.items].sort((left, right) => workflowChecklistItemPriority(left.state) - workflowChecklistItemPriority(right.state))) {
1291
+ lines.push(workflowChecklistItemLine(item, theme, `${indent} `, frame, includeItemErrors || item.kind === "host"));
1292
+ }
1293
+ }
1294
+ }
1295
+ const bottleneck = formatWorkflowChecklistBottleneck(checklist.bottleneck, { includeOutput: includeBottleneckOutput, includeError: !expanded });
1296
+ if (bottleneck) {
1297
+ const tone = checklist.bottleneck?.state === "blocked" || checklist.bottleneck?.state === "failed" ? "error" : checklist.bottleneck?.state === "running" ? "accent" : "warning";
1298
+ lines.push(`${indent}${theme.fg(tone, `bottleneck · ${bottleneck}`)}`);
1299
+ }
1300
+ return lines;
1301
+ }
1302
+ function compactWorkflowLaneState(items) {
1303
+ let state;
1304
+ for (const item of items) {
1305
+ if (state === undefined || workflowChecklistItemPriority(item.state) < workflowChecklistItemPriority(state))
1306
+ state = item.state;
1307
+ }
1308
+ return state ?? "queued";
1309
+ }
1310
+ function compactWorkflowLaneOwner(items) {
1311
+ const owners = [...new Set(items.map((item) => item.agent ?? item.role).filter((value) => Boolean(value?.trim())))];
1312
+ if (owners.length === 0)
1313
+ return undefined;
1314
+ return boundedLaneValue(owners.length > 2 ? `${owners.slice(0, 2).join(", ")} +${owners.length - 2}` : owners.join(", "), 32);
1315
+ }
1316
+ function compactWorkflowLaneLabel(items, key) {
1317
+ const labels = [...new Set(items.map((item) => item.label).filter((value) => Boolean(value?.trim() && value.trim() !== key)))];
1318
+ if (labels.length === 0)
1319
+ return undefined;
1320
+ return boundedLaneValue(labels.length > 1 ? `${labels[0]} +${labels.length - 1}` : labels[0], 48);
1321
+ }
1322
+ function compactWorkflowLaneRow(key, items, lane = items.find((item) => item.preflight)?.preflight, fallbackState = "queued") {
1323
+ const state = items.length ? compactWorkflowLaneState(items) : fallbackState;
1324
+ const toolCounts = items.map((item) => item.toolCount).filter((value) => value !== undefined);
1325
+ const durations = items.map((item) => item.durationMs).filter((value) => value !== undefined);
1326
+ const label = compactWorkflowLaneLabel(items, key);
1327
+ return {
1328
+ key: boundedLaneValue(key, 40) ?? key,
1329
+ state,
1330
+ agent: compactWorkflowLaneOwner(items),
1331
+ ...(items.length === 1 && items[0]?.thinking ? { thinking: items[0].thinking } : {}),
1332
+ ...(lane?.mode ? { mode: lane.mode } : {}),
1333
+ ...(lane?.decision ? { decision: boundedLaneValue(lane.decision, 56) } : {}),
1334
+ ...(lane?.claims?.length ? { claims: boundedLaneValue(lane.claims.join(", "), 56) } : {}),
1335
+ ...(lane?.expectedOutput ? { expectedOutput: boundedLaneValue(lane.expectedOutput, 56) } : {}),
1336
+ ...(label ? { label } : {}),
1337
+ ...(toolCounts.length ? { toolUses: toolCounts.reduce((sum, value) => sum + value, 0) } : {}),
1338
+ ...(durations.length ? { durationMs: Math.max(...durations) } : {}),
1339
+ };
1340
+ }
1341
+ function compactWorkflowFallbackState(job) {
1342
+ if (job.activityState === "needs_attention" || job.timedOut || job.toolBudgetBlocked || job.turnBudgetExceeded)
1343
+ return "blocked";
1344
+ switch (job.status) {
1345
+ case "complete": return "complete";
1346
+ case "failed": return "failed";
1347
+ case "paused": return "paused";
1348
+ case "stopped": return "stopped";
1349
+ case "partial":
1350
+ case "rejected": return "blocked";
1351
+ default: return "queued";
1352
+ }
1353
+ }
1354
+ /** Flatten the loaded checklist into one compact row per declared lane. */
1355
+ function compactWorkflowLaneRows(job, checklist) {
1356
+ const groups = new Map();
1357
+ for (const item of checklist?.phases.flatMap((phase) => phase.items) ?? []) {
1358
+ const key = item.preflight?.key ?? item.key;
1359
+ const group = groups.get(key);
1360
+ if (group)
1361
+ group.push(item);
1362
+ else
1363
+ groups.set(key, [item]);
1364
+ }
1365
+ const rows = [];
1366
+ const preflightKeys = new Set(job.preflight?.lanes.map((lane) => lane.key) ?? []);
1367
+ if (job.preflight?.lanes.length) {
1368
+ for (const lane of job.preflight.lanes) {
1369
+ rows.push(compactWorkflowLaneRow(lane.key, groups.get(lane.key) ?? [], lane, compactWorkflowFallbackState(job)));
1370
+ }
1371
+ }
1372
+ for (const [key, items] of groups) {
1373
+ if (preflightKeys.has(key))
1374
+ continue;
1375
+ rows.push(compactWorkflowLaneRow(key, items));
1376
+ }
1377
+ return rows;
1378
+ }
1379
+ function compactWorkflowLaneCounts(rows) {
1380
+ const counts = { total: rows.length, done: 0, active: 0, queued: 0, blocked: 0, failed: 0, paused: 0, stopped: 0 };
1381
+ for (const row of rows) {
1382
+ switch (row.state) {
1383
+ case "complete":
1384
+ counts.done++;
1385
+ break;
1386
+ case "running":
1387
+ counts.active++;
1388
+ break;
1389
+ case "queued":
1390
+ counts.queued++;
1391
+ break;
1392
+ case "blocked":
1393
+ counts.blocked++;
1394
+ break;
1395
+ case "failed":
1396
+ counts.failed++;
1397
+ break;
1398
+ case "paused":
1399
+ counts.paused++;
1400
+ break;
1401
+ case "stopped":
1402
+ counts.stopped++;
1403
+ break;
1404
+ }
1405
+ }
1406
+ return counts;
1407
+ }
1408
+ function compactWorkflowLaneLine(row, theme, indent, frame) {
1409
+ const owner = row.agent && row.mode ? `${row.agent}/${row.mode}` : row.agent ?? row.mode;
1410
+ const state = row.state === "complete" ? undefined : row.state === "running" ? "active" : row.state;
1411
+ const intent = [
1412
+ row.decision,
1413
+ row.claims,
1414
+ row.expectedOutput,
1415
+ !row.mode && row.label ? row.label : undefined,
1416
+ ].filter((value) => Boolean(value));
1417
+ return `${indent}${workflowChecklistGlyph({ state: row.state, durationMs: row.durationMs, toolCount: row.toolUses, thinking: row.thinking }, theme, frame)} ${theme.bold(row.key)}${owner ? ` ${theme.fg("dim", `· ${owner}`)}` : ""}${state ? ` ${theme.fg("dim", `· ${state}`)}` : ""}${intent.length ? ` ${theme.fg("dim", `· ${intent.join(" · ")}`)}` : ""}`;
1418
+ }
1419
+ function compactWorkflowShortId(job) {
1420
+ return job.asyncId.slice(0, 8);
1421
+ }
1422
+ function compactWorkflowDisplayLabel(job) {
1423
+ return boundedLaneValue(job.description, 64) ?? compactWorkflowShortId(job);
1424
+ }
1425
+ function compactWorkflowStats(job, rows, theme, projection) {
1426
+ const counts = compactWorkflowLaneCounts(rows);
1427
+ const total = counts.total || projection.stageProgress?.total || job.stepsTotal || job.agents?.length || 0;
1428
+ const progress = [
1429
+ total > 0 ? `${counts.done}/${total} done` : undefined,
1430
+ counts.active ? `${counts.active} active` : undefined,
1431
+ counts.queued ? `${counts.queued} queued` : undefined,
1432
+ counts.blocked ? `${counts.blocked} blocked` : undefined,
1433
+ counts.failed ? `${counts.failed} failed` : undefined,
1434
+ counts.paused ? `${counts.paused} paused` : undefined,
1435
+ counts.stopped ? `${counts.stopped} stopped` : undefined,
1436
+ ].filter((value) => Boolean(value));
1437
+ const rowToolUses = rows.map((row) => row.toolUses).filter((value) => value !== undefined);
1438
+ const toolUses = job.toolCount ?? (rowToolUses.length ? rowToolUses.reduce((sum, value) => sum + value, 0) : undefined);
1439
+ const rowDuration = rows.map((row) => row.durationMs).filter((value) => value !== undefined);
1440
+ const end = job.status === "running" ? projection.now : job.updatedAt;
1441
+ const durationMs = job.status !== "queued" && job.startedAt !== undefined && end !== undefined
1442
+ ? Math.max(0, end - job.startedAt)
1443
+ : job.status !== "queued" && rowDuration.length ? Math.max(...rowDuration) : undefined;
1444
+ return statJoin(theme, [
1445
+ `id: ${compactWorkflowShortId(job)}`,
1446
+ ...progress,
1447
+ toolUses !== undefined ? formatToolUseStat(toolUses) : undefined,
1448
+ durationMs !== undefined ? formatDuration(durationMs) : undefined,
1449
+ ].filter((value) => Boolean(value)));
1450
+ }
1451
+ function compactWorkflowBottleneck(rows, job) {
1452
+ let row;
1453
+ for (const candidate of rows) {
1454
+ if (candidate.state !== "blocked" && candidate.state !== "failed" && candidate.state !== "paused" && candidate.state !== "stopped")
1455
+ continue;
1456
+ if (!row || workflowChecklistItemPriority(candidate.state) < workflowChecklistItemPriority(row.state))
1457
+ row = candidate;
1458
+ }
1459
+ if (row)
1460
+ return { text: `${row.key} · ${row.state}`, tone: row.state === "blocked" || row.state === "failed" ? "error" : "warning" };
1461
+ if (job.activityState === "needs_attention" || job.timedOut || job.toolBudgetBlocked || job.turnBudgetExceeded)
1462
+ return { text: `workflow · ${job.activityState === "needs_attention" ? "needs attention" : "blocked"}`, tone: job.activityState === "needs_attention" ? "warning" : "error" };
1463
+ if (job.status === "failed" || job.status === "partial" || job.status === "rejected")
1464
+ return { text: `workflow · ${job.status}`, tone: "error" };
1465
+ if (job.status === "paused" || job.status === "stopped")
1466
+ return { text: `workflow · ${job.status}`, tone: "warning" };
1467
+ return undefined;
1468
+ }
1469
+ function compactWorkflowHeaderLine(job, theme, width) {
1470
+ const label = compactWorkflowDisplayLabel(job);
1471
+ const full = `${theme.fg("toolTitle", themeBold(theme, `async workflow: ${label}`))} ${theme.fg("dim", "─ background")}`;
1472
+ if (width === undefined || visibleWidth(full) <= width)
1473
+ return full;
1474
+ return `${theme.fg("toolTitle", themeBold(theme, `async workflow ${label}`))} ${theme.fg("dim", "· background")}`;
1475
+ }
1476
+ function compactWorkflowWidgetBodyLines(job, theme, frame, projection) {
1477
+ const rows = compactWorkflowLaneRows(job, projection.checklist);
1478
+ const lines = [` ${compactWorkflowStats(job, rows, theme, projection)}`];
1479
+ if (projection.inlineFleetCovered)
1480
+ return [...lines, ` ${theme.fg("dim", "Workflow children shown in Fleet roster")}`];
1481
+ if (rows.length) {
1482
+ for (const row of rows) {
1483
+ if (!projection.materializedKeys?.has(row.key))
1484
+ lines.push(compactWorkflowLaneLine(row, theme, " ", frame));
1485
+ }
1486
+ }
1487
+ else {
1488
+ lines.push(` ${theme.fg("dim", "◦ waiting for workflow lanes")}`);
1489
+ }
1490
+ const bottleneck = compactWorkflowBottleneck(rows, job);
1491
+ if (bottleneck)
1492
+ lines.push(` ${theme.fg(bottleneck.tone, `bottleneck · ${bottleneck.text}`)}`);
1493
+ if (job.status === "running" || rows.some((row) => row.state === "running"))
1494
+ lines.push(` ${theme.fg("accent", workflowDetailHintText())}`);
1495
+ return lines;
1496
+ }
1497
+ function widgetStepActivity(step, snapshotNow) {
1498
+ const facts = [];
1499
+ if (step.currentTool && step.currentToolStartedAt !== undefined && snapshotNow !== undefined)
1500
+ facts.push(`${step.currentTool} ${formatDuration(Math.max(0, snapshotNow - step.currentToolStartedAt))}`);
1501
+ else if (step.currentTool)
1502
+ facts.push(step.currentTool);
1503
+ if (step.currentPath)
1504
+ facts.push(shortenPath(step.currentPath));
1505
+ if (step.turnCount !== undefined)
1506
+ facts.push(`${step.turnCount} turns`);
1507
+ if (step.toolCount !== undefined)
1508
+ facts.push(`${step.toolCount} tools`);
1509
+ if (step.tokens?.total)
1510
+ facts.push(formatTokenUsage(step.tokens, "token"));
1511
+ const activity = buildLiveStatusLine(step, snapshotNow);
1512
+ if (activity && facts.length)
1513
+ return `${activity} · ${facts.join(" · ")}`;
1514
+ if (activity)
1515
+ return activity;
1516
+ return facts.join(" · ");
1517
+ }
1518
+ function widgetChainDetails(job, theme, expanded = false, width = getTermWidth(), frame) {
1519
+ if (!job.steps?.length)
1520
+ return [];
1521
+ const total = job.chainStepCount ?? job.steps.length;
1522
+ const lines = [];
1523
+ for (const span of buildAsyncChainStepSpans(total, job.steps.length, job.parallelGroups)) {
1524
+ const steps = job.steps.slice(span.start, span.start + span.count);
1525
+ if (span.isParallel) {
1526
+ lines.push(...parallelWidgetGroupDetails(job, theme, { steps, total: span.count, stepIndex: span.stepIndex, chainTotal: total }, expanded, width, frame, false));
1527
+ continue;
1528
+ }
1529
+ const step = steps[0];
1530
+ if (!step) {
1531
+ lines.push(` ${theme.fg("dim", `◦ Step ${span.stepIndex + 1}/${total}: pending`)}`);
1532
+ continue;
1533
+ }
1534
+ lines.push(...foregroundStyleWidgetStepLines(job, theme, step, "Step", span.stepIndex + 1, total, expanded, width, frame));
1535
+ }
1536
+ return lines;
1537
+ }
1538
+ function widgetParallelAgentDetails(job, theme, expanded = false, width = getTermWidth(), frame) {
1539
+ if (!job.steps?.length)
1540
+ return [];
1541
+ if (job.mode !== "parallel" && job.mode !== "chain")
1542
+ return [];
1543
+ if (job.mode === "chain" && !job.activeParallelGroup && job.parallelGroups?.length)
1544
+ return widgetChainDetails(job, theme, expanded, width, frame);
1545
+ const group = activeParallelWidgetGroup(job);
1546
+ if (group)
1547
+ return parallelWidgetGroupDetails(job, theme, group, expanded, width, frame, Boolean(job.activeParallelGroup));
1548
+ const total = job.stepsTotal ?? job.steps.length;
1549
+ const lines = [];
1550
+ for (const [index, step] of job.steps.entries()) {
1551
+ const marker = index === job.steps.length - 1 ? "└" : "├";
1552
+ const activity = widgetStepActivity(step, job.updatedAt);
1553
+ const itemTitle = job.mode === "parallel" || job.activeParallelGroup ? "Agent" : "Step";
1554
+ const modelDisplay = modelThinkingBadge(theme, step.model, step.thinking);
1555
+ const label = compactTaskText(step.description, step.label);
1556
+ const display = step.sessionName?.trim() || (label ? `${label} (${step.agent})` : step.agent);
1557
+ const thinking = childThinkingLevel(step);
1558
+ lines.push(` ${theme.fg("dim", `${marker} ${widgetStepGlyph(step.status, theme, widgetStepRunningSeed(step, index), frame, thinking)} ${itemTitle} ${index + 1}/${total}: ${display} · ${widgetStepStatus(step.status, theme, thinking)}${modelDisplay}${activity ? ` · ${activity}` : ""}`)}`);
1559
+ const lane = projectAsyncLane(job, step);
1560
+ if (lane)
1561
+ lines.push(...formatLaneProjectionLines(lane, theme, " "));
1562
+ for (const nestedLine of formatNestedWidgetLines(step.children, theme, width, expanded, job.updatedAt, expanded ? 8 : 6))
1563
+ lines.push(` ${nestedLine}`);
1564
+ }
1565
+ return lines;
1566
+ }
1567
+ function parseParallelGroupAgentCount(label) {
1568
+ if (!label || !label.startsWith("[") || !label.endsWith("]"))
1569
+ return undefined;
1570
+ const inner = label.slice(1, -1).trim();
1571
+ if (!inner)
1572
+ return 0;
1573
+ return inner.split("+").map((part) => part.trim()).filter(Boolean).length;
1574
+ }
1575
+ function buildChainStepSpans(details) {
1576
+ if (details.workflowGraph?.nodes?.length) {
1577
+ const spans = [];
1578
+ let flatCursor = 0;
1579
+ for (const node of details.workflowGraph.nodes) {
1580
+ if (node.stepIndex === undefined)
1581
+ continue;
1582
+ if (node.kind === "parallel-group" || node.kind === "dynamic-parallel-group") {
1583
+ const childFlatIndexes = (node.children ?? [])
1584
+ .map((child) => child.flatIndex)
1585
+ .filter((value) => typeof value === "number");
1586
+ const start = childFlatIndexes.length ? Math.min(...childFlatIndexes) : flatCursor;
1587
+ const count = node.children?.length ?? 0;
1588
+ spans.push({ stepIndex: node.stepIndex, start, count, isParallel: true, status: node.status, label: node.label, error: node.error });
1589
+ flatCursor = Math.max(flatCursor, start + count);
1590
+ continue;
1591
+ }
1592
+ const start = node.flatIndex ?? flatCursor;
1593
+ spans.push({ stepIndex: node.stepIndex, start, count: 1, isParallel: false, status: node.status, label: node.label, error: node.error });
1594
+ flatCursor = Math.max(flatCursor, start + 1);
1595
+ }
1596
+ if (spans.length)
1597
+ return spans.sort((left, right) => left.stepIndex - right.stepIndex);
1598
+ }
1599
+ if (!details.chainAgents?.length)
1600
+ return [];
1601
+ const spans = [];
1602
+ let start = 0;
1603
+ for (let stepIndex = 0; stepIndex < details.chainAgents.length; stepIndex++) {
1604
+ const label = details.chainAgents[stepIndex];
1605
+ const parsedCount = parseParallelGroupAgentCount(label);
1606
+ const count = parsedCount ?? 1;
1607
+ spans.push({ stepIndex, start, count, isParallel: parsedCount !== undefined });
1608
+ start += count;
1609
+ }
1610
+ return spans;
1611
+ }
1612
+ function buildAsyncChainStepSpans(total, stepCount, parallelGroups = []) {
1613
+ const groupsByStep = new Map();
1614
+ for (const group of parallelGroups) {
1615
+ if (!groupsByStep.has(group.stepIndex))
1616
+ groupsByStep.set(group.stepIndex, group);
1617
+ }
1618
+ const spans = [];
1619
+ let flatIndex = 0;
1620
+ for (let stepIndex = 0; stepIndex < total; stepIndex++) {
1621
+ const group = groupsByStep.get(stepIndex);
1622
+ if (group) {
1623
+ spans.push({ stepIndex, start: group.start, count: group.count, isParallel: true });
1624
+ flatIndex = Math.max(flatIndex, group.start + group.count);
1625
+ continue;
1626
+ }
1627
+ spans.push({ stepIndex, start: flatIndex, count: flatIndex < stepCount ? 1 : 0, isParallel: false });
1628
+ flatIndex++;
1629
+ }
1630
+ return spans;
1631
+ }
1632
+ function normalizedParallelDisplayText(value) {
1633
+ if (!value?.trim())
1634
+ return undefined;
1635
+ const normalized = oneLine(value);
1636
+ return normalized && normalized !== PROMPT_REDACTED ? normalized : undefined;
1637
+ }
1638
+ function parallelWidgetStepDisplayName(step) {
1639
+ const agent = normalizedParallelDisplayText(step.agent);
1640
+ const explicitLabel = normalizedParallelDisplayText(step.label);
1641
+ if (explicitLabel) {
1642
+ const label = compactTaskText(step.description, explicitLabel) ?? explicitLabel;
1643
+ return agent ? `${label} (${agent})` : label;
1644
+ }
1645
+ const sessionName = normalizedParallelDisplayText(step.sessionName);
1646
+ if (sessionName) {
1647
+ const sessionTask = stripRepeatedAgentPrefix(sessionName, agent);
1648
+ if (sessionTask && sessionTask !== PROMPT_REDACTED && sessionTask.toLowerCase() !== agent?.toLowerCase())
1649
+ return sessionTask;
1650
+ }
1651
+ return compactTaskText(step.description) ?? agent ?? "subagent";
1652
+ }
1653
+ function parallelWidgetStepPriority(step) {
1654
+ if (step.status === "running" || step.activityState === "needs_attention")
1655
+ return 0;
1656
+ switch (step.status) {
1657
+ case "failed":
1658
+ case "rejected":
1659
+ case "partial":
1660
+ case "stopped":
1661
+ case "paused":
1662
+ return 1;
1663
+ case "complete":
1664
+ case "completed":
1665
+ return 2;
1666
+ default:
1667
+ return 3;
1668
+ }
1669
+ }
1670
+ function parallelWidgetStepRows(steps, total, prioritizeActive) {
1671
+ const indexed = steps.map((step, index) => ({ step, index, displayName: parallelWidgetStepDisplayName(step) }));
1672
+ if (prioritizeActive)
1673
+ indexed.sort((left, right) => parallelWidgetStepPriority(left.step) - parallelWidgetStepPriority(right.step) || left.index - right.index);
1674
+ return withDuplicateLabelDiscriminators(indexed, total).map(({ displayName, ...row }) => row);
1675
+ }
1676
+ function activeParallelWidgetGroup(job) {
1677
+ const steps = job.steps ?? [];
1678
+ if (!steps.length)
1679
+ return undefined;
1680
+ if (job.mode === "parallel")
1681
+ return { steps, total: job.stepsTotal ?? steps.length };
1682
+ if (job.mode !== "chain" || !job.activeParallelGroup)
1683
+ return undefined;
1684
+ const chainTotal = job.chainStepCount ?? job.stepsTotal ?? steps.length;
1685
+ const spans = buildAsyncChainStepSpans(chainTotal, steps.length, job.parallelGroups);
1686
+ const currentStep = job.currentStep;
1687
+ const activeSpan = currentStep === undefined
1688
+ ? spans.find((span) => span.isParallel)
1689
+ : spans.find((span) => span.isParallel
1690
+ && currentStep >= span.start
1691
+ && currentStep < span.start + span.count);
1692
+ return {
1693
+ steps,
1694
+ total: activeSpan?.count ?? job.stepsTotal ?? steps.length,
1695
+ stepIndex: activeSpan?.stepIndex,
1696
+ chainTotal,
1697
+ };
1698
+ }
1699
+ function parallelWidgetGroupHeader(group, theme, frame) {
1700
+ const status = aggregateStepStatus(group.steps);
1701
+ const label = group.stepIndex !== undefined && group.chainTotal !== undefined
1702
+ ? `Step ${group.stepIndex + 1}/${group.chainTotal}: parallel group`
1703
+ : "parallel group";
1704
+ return ` ${widgetStepGlyph(status, theme, widgetStepsRunningSeed(group.steps), frame)} ${themeBold(theme, label)} ${theme.fg("dim", "·")} ${theme.fg("dim", formatParallelOutcome(group.steps, group.total))}`;
1705
+ }
1706
+ function parallelWidgetGroupDetails(job, theme, group, expanded, width, frame, prioritizeActive) {
1707
+ const lines = [parallelWidgetGroupHeader(group, theme, frame)];
1708
+ const rows = parallelWidgetStepRows(group.steps, group.total, prioritizeActive);
1709
+ for (const [rowIndex, row] of rows.entries()) {
1710
+ const marker = rowIndex === rows.length - 1 && rows.length >= group.total ? "└─" : "├─";
1711
+ lines.push(...foregroundStyleWidgetStepLines(job, theme, row.step, "Agent", row.index + 1, group.total, expanded, width, frame, {
1712
+ rowLabel: row.rowLabel,
1713
+ rowIndent: " ",
1714
+ detailIndent: " ",
1715
+ rowMarker: marker,
1716
+ includeCurrentPath: true,
1717
+ }));
1718
+ }
1719
+ for (let index = rows.length; index < group.total; index++) {
1720
+ const marker = index === group.total - 1 ? "└─" : "├─";
1721
+ lines.push(` ${marker} ${theme.fg("muted", "◦")} ${theme.fg("dim", "pending")}`);
1722
+ }
1723
+ return lines;
1724
+ }
1725
+ function isDoneResult(result) {
1726
+ const status = result.progress?.status;
1727
+ if (status === "completed")
1728
+ return true;
1729
+ if (status === "running" || status === "pending")
1730
+ return false;
1731
+ if (result.interrupted || result.detached)
1732
+ return false;
1733
+ return result.exitCode === 0;
1734
+ }
1735
+ function workflowGraphHasStatus(details, statuses) {
1736
+ return details.workflowGraph?.nodes.some((node) => statuses.includes(node.status)) ?? false;
1737
+ }
1738
+ function chainSpanStatus(details, span) {
1739
+ if (span.status)
1740
+ return span.status;
1741
+ const results = details.results.slice(span.start, span.start + span.count);
1742
+ if (results.some((result) => isResultRunning(result)))
1743
+ return "running";
1744
+ if (results.some((result) => !hasTerminalResultFlag(result) && (result.progress?.status === "failed" || result.exitCode !== 0) && !isResultRunning(result)))
1745
+ return "failed";
1746
+ if (results.some((result) => result.stopped))
1747
+ return "stopped";
1748
+ if (results.some((result) => result.interrupted))
1749
+ return "paused";
1750
+ if (results.some((result) => result.detached || result.progress?.status === "detached"))
1751
+ return "detached";
1752
+ if (results.length < span.count)
1753
+ return "pending";
1754
+ if (results.length > 0 && results.every(isDoneResult))
1755
+ return "completed";
1756
+ return "pending";
1757
+ }
1758
+ function withDuplicateForegroundLabels(entries, total) {
1759
+ return withDuplicateLabelDiscriminators(entries.map((entry) => ({ ...entry, index: entry.displayIndex, displayName: entry.agentName })), total).map(({ displayName, rowLabel, ...entry }) => ({
1760
+ ...entry,
1761
+ rowLabel: rowLabel === displayName ? undefined : rowLabel.slice(0, -(displayName.length + 2)),
1762
+ }));
1763
+ }
1764
+ function buildChainRenderEntries(details, label) {
1765
+ if (details.mode !== "chain" || !label.hasParallelInChain || label.showActiveGroupOnly)
1766
+ return undefined;
1767
+ const entries = [];
1768
+ for (const span of buildChainStepSpans(details)) {
1769
+ if (span.isParallel) {
1770
+ entries.push({
1771
+ kind: "group",
1772
+ stepLabel: `Step ${span.stepIndex + 1}/${label.logicalStepCount}: parallel group`,
1773
+ groupLabel: span.label?.trim() || undefined,
1774
+ status: chainSpanStatus(details, span),
1775
+ error: span.error,
1776
+ });
1777
+ const groupEntries = [];
1778
+ for (let index = span.start; index < span.start + span.count; index++) {
1779
+ const result = details.results[index];
1780
+ const localIndex = foregroundResultIndex(details, index);
1781
+ const displayIndex = localIndex >= span.start && localIndex < span.start + span.count
1782
+ ? localIndex - span.start
1783
+ : index - span.start;
1784
+ groupEntries.push({
1785
+ kind: "result",
1786
+ resultIndex: index,
1787
+ rowNumber: index - span.start + 1,
1788
+ agentName: foregroundResultDisplayName(details, index, result, `agent-${displayIndex + 1}`),
1789
+ displayIndex,
1790
+ isParallel: true,
1791
+ });
1792
+ }
1793
+ entries.push(...withDuplicateForegroundLabels(groupEntries, span.count));
1794
+ continue;
1795
+ }
1796
+ for (let index = span.start; index < span.start + span.count; index++) {
1797
+ const result = details.results[index];
1798
+ entries.push({
1799
+ kind: "result",
1800
+ resultIndex: index,
1801
+ rowNumber: span.stepIndex + 1,
1802
+ rowLabel: resultRowLabel(label, span.stepIndex + 1),
1803
+ agentName: foregroundResultDisplayName(details, index, result, details.chainAgents?.[span.stepIndex] ?? `step-${span.stepIndex + 1}`),
1804
+ displayIndex: foregroundResultIndex(details, index),
1805
+ });
1806
+ }
1807
+ }
1808
+ return entries;
1809
+ }
1810
+ function buildMultiProgressLabel(details, hasRunning) {
1811
+ const stepSpans = buildChainStepSpans(details);
1812
+ const hasParallelInChain = details.mode === "chain" && stepSpans.some((span) => span.isParallel);
1813
+ const activeParallelGroup = details.mode === "chain"
1814
+ && details.currentStepIndex !== undefined
1815
+ && stepSpans.some((span) => span.stepIndex === details.currentStepIndex && span.isParallel);
1816
+ const itemTitle = details.mode === "parallel" || activeParallelGroup ? "Agent" : "Step";
1817
+ if (details.mode === "parallel") {
1818
+ const totalCount = details.totalSteps ?? details.results.length;
1819
+ const statuses = new Array(totalCount).fill("pending");
1820
+ for (const progress of details.progress ?? []) {
1821
+ if (progress.index >= 0 && progress.index < totalCount)
1822
+ statuses[progress.index] = progress.status;
1823
+ }
1824
+ for (let i = 0; i < details.results.length; i++) {
1825
+ const result = details.results[i];
1826
+ const progressFromArray = details.progress?.find((progress) => progress.index === i)
1827
+ || details.progress?.find((progress) => progress.agent === result.agent && progress.status === "running");
1828
+ const index = result.progress?.index ?? progressFromArray?.index ?? i;
1829
+ if (index < 0 || index >= totalCount)
1830
+ continue;
1831
+ const status = result.stopped
1832
+ ? "stopped"
1833
+ : result.interrupted || result.detached
1834
+ ? "detached"
1835
+ : result.progress?.status
1836
+ ?? (result.exitCode === 0 ? "completed" : "failed");
1837
+ statuses[index] = status;
1838
+ }
1839
+ const running = statuses.filter((status) => status === "running").length;
1840
+ const done = statuses.filter((status) => status === "completed").length;
1841
+ const headerLabel = hasRunning
1842
+ ? `${formatAgentRunningLabel(running)} · ${done}/${totalCount} done`
1843
+ : `${done}/${totalCount} done`;
1844
+ return { headerLabel, itemTitle, totalCount, hasParallelInChain, activeParallelGroup, groupStartIndex: 0, groupEndIndex: totalCount, showActiveGroupOnly: false, logicalStepCount: totalCount };
1845
+ }
1846
+ if (activeParallelGroup) {
1847
+ const currentStepIndex = details.currentStepIndex;
1848
+ const span = stepSpans[currentStepIndex];
1849
+ const groupSize = span?.count ?? 1;
1850
+ const groupStart = span?.start ?? 0;
1851
+ const groupEnd = groupStart + groupSize;
1852
+ let running = 0;
1853
+ let done = 0;
1854
+ for (let index = groupStart; index < groupEnd; index++) {
1855
+ const progressEntry = details.progress?.find((progress) => progress.index === index);
1856
+ const resultEntry = details.results.find((result) => result.progress?.index === index) ?? details.results[index];
1857
+ if (progressEntry?.status === "running" && (!resultEntry || !hasTerminalResultFlag(resultEntry))) {
1858
+ running++;
1859
+ continue;
1860
+ }
1861
+ if (progressEntry?.status === "completed") {
1862
+ done++;
1863
+ continue;
1864
+ }
1865
+ if (resultEntry && isDoneResult(resultEntry))
1866
+ done++;
1867
+ }
1868
+ const totalSteps = details.totalSteps ?? details.chainAgents?.length ?? 1;
1869
+ const headerLabel = hasRunning
1870
+ ? `step ${currentStepIndex + 1}/${totalSteps} · parallel group: ${formatAgentRunningLabel(running)} · ${done}/${groupSize} done`
1871
+ : `step ${currentStepIndex + 1}/${totalSteps} · parallel group: ${done}/${groupSize} done`;
1872
+ return { headerLabel, itemTitle, totalCount: groupSize, hasParallelInChain, activeParallelGroup, groupStartIndex: groupStart, groupEndIndex: groupEnd, showActiveGroupOnly: true, logicalStepCount: totalSteps };
1873
+ }
1874
+ if (details.mode === "chain" && details.chainAgents?.length) {
1875
+ const totalCount = details.totalSteps ?? details.chainAgents.length;
1876
+ const doneLogical = stepSpans.filter((span) => {
1877
+ if (span.status && span.status !== "completed")
1878
+ return false;
1879
+ if (span.count === 0)
1880
+ return span.status === "completed";
1881
+ for (let index = span.start; index < span.start + span.count; index++) {
1882
+ const progressEntry = details.progress?.find((progress) => progress.index === index);
1883
+ const resultEntry = details.results.find((result) => result.progress?.index === index) ?? details.results[index];
1884
+ if (progressEntry?.status === "running" || progressEntry?.status === "pending" || progressEntry?.status === "failed")
1885
+ return false;
1886
+ if (!resultEntry || !isDoneResult(resultEntry))
1887
+ return false;
1888
+ }
1889
+ return true;
1890
+ }).length;
1891
+ const currentStep = details.currentStepIndex !== undefined ? details.currentStepIndex + 1 : Math.min(totalCount, doneLogical + (hasRunning ? 1 : 0));
1892
+ const headerLabel = hasRunning ? `step ${currentStep}/${totalCount}` : `step ${doneLogical}/${totalCount}`;
1893
+ return { headerLabel, itemTitle, totalCount, hasParallelInChain, activeParallelGroup, groupStartIndex: 0, groupEndIndex: details.results.length, showActiveGroupOnly: false, logicalStepCount: totalCount };
1894
+ }
1895
+ const totalCount = details.totalSteps ?? details.results.length;
1896
+ const currentStep = details.currentStepIndex !== undefined ? details.currentStepIndex + 1 : Math.min(totalCount, details.results.filter(isDoneResult).length + (hasRunning ? 1 : 0));
1897
+ const done = details.results.filter(isDoneResult).length;
1898
+ const headerLabel = hasRunning ? `step ${currentStep}/${totalCount}` : `step ${done}/${totalCount}`;
1899
+ return { headerLabel, itemTitle, totalCount, hasParallelInChain, activeParallelGroup, groupStartIndex: 0, groupEndIndex: details.results.length, showActiveGroupOnly: false, logicalStepCount: totalCount };
1900
+ }
1901
+ function resultRowLabel(label, stepNumber) {
1902
+ if (label.itemTitle === "Agent")
1903
+ return undefined;
1904
+ if (shouldSuppressSingleStep(label.logicalStepCount))
1905
+ return undefined;
1906
+ return `Step ${stepNumber}/${label.logicalStepCount}`;
1907
+ }
1908
+ function buildForegroundResultEntries(details, label, displayStart, displayEnd, useResultsDirectly) {
1909
+ const fallbackLabel = label.itemTitle.toLowerCase();
1910
+ const entries = Array.from({ length: displayEnd - displayStart }, (_, offset) => {
1911
+ const index = displayStart + offset;
1912
+ const result = details.results[index];
1913
+ const stableIndex = foregroundResultIndex(details, index);
1914
+ const rowNumber = label.showActiveGroupOnly ? index - label.groupStartIndex + 1 : stableIndex + 1;
1915
+ const fallbackAgent = useResultsDirectly
1916
+ ? (result?.agent || `${fallbackLabel}-${rowNumber}`)
1917
+ : (details.chainAgents[index] || result?.agent || `${fallbackLabel}-${rowNumber}`);
1918
+ const displayIndex = label.activeParallelGroup && stableIndex >= label.groupStartIndex && stableIndex < label.groupEndIndex
1919
+ ? stableIndex - label.groupStartIndex
1920
+ : label.activeParallelGroup ? index - label.groupStartIndex : stableIndex;
1921
+ return {
1922
+ kind: "result",
1923
+ resultIndex: index,
1924
+ rowNumber,
1925
+ rowLabel: resultRowLabel(label, rowNumber),
1926
+ agentName: foregroundResultDisplayName(details, index, result, fallbackAgent),
1927
+ displayIndex,
1928
+ };
1929
+ });
1930
+ return label.itemTitle === "Agent" ? withDuplicateForegroundLabels(entries, label.totalCount) : entries;
1931
+ }
1932
+ function widgetStats(job, theme, projection = buildWorkflowWidgetProjection(job), collapsed = false) {
1933
+ const parts = [];
1934
+ const { stageProgress } = projection;
1935
+ const stepsTotal = stageProgress?.total ?? job.stepsTotal ?? (job.agents?.length ?? 1);
1936
+ const isSingleChild = isSingleChildAsyncJob(job);
1937
+ const checklistPrimary = collapsed && job.mode === "workflow" && projection.checklist !== undefined;
1938
+ if (checklistPrimary) {
1939
+ parts.push(formatWorkflowChecklistSummary(projection.checklist));
1940
+ }
1941
+ else if (stageProgress) {
1942
+ const currentStage = stageProgress.current !== undefined ? projection.stages[stageProgress.current] : undefined;
1943
+ const focus = currentStage
1944
+ ? [compactTaskText(undefined, currentStage.label) ?? boundedLaneValue(currentStage.id), currentStage.agent ? boundedLaneValue(currentStage.agent) : "", workflowNodeStatusLabel(currentStage.status)].filter(Boolean)
1945
+ : [];
1946
+ parts.push(["staged lane", stageProgress.current !== undefined ? `stage ${stageProgress.current + 1}/${stageProgress.total}` : `${stageProgress.total} stages`, ...focus].join(" · "));
1947
+ }
1948
+ else if (job.activeParallelGroup) {
1949
+ const running = job.runningSteps ?? (job.status === "running" ? 1 : 0);
1950
+ const done = job.completedSteps ?? (job.status === "complete" ? stepsTotal : 0);
1951
+ if (job.mode === "parallel") {
1952
+ if (job.status === "running" && running > 0)
1953
+ parts.push(formatAgentRunningLabel(running));
1954
+ if (stepsTotal > 0)
1955
+ parts.push(`${done}/${stepsTotal} done`);
1956
+ }
1957
+ else {
1958
+ const activeGroup = job.currentStep !== undefined
1959
+ ? job.parallelGroups?.find((group) => job.currentStep >= group.start && job.currentStep < group.start + group.count)
1960
+ : job.parallelGroups?.find((group) => group.start === 0);
1961
+ const logicalStep = activeGroup?.stepIndex ?? job.currentStep ?? 0;
1962
+ const total = job.chainStepCount ?? stepsTotal;
1963
+ const groupParts = [`${done}/${stepsTotal} done`];
1964
+ if (job.status === "running" && running > 0)
1965
+ groupParts.unshift(formatAgentRunningLabel(running));
1966
+ parts.push(`step ${logicalStep + 1}/${total} · parallel group: ${groupParts.join(" · ")}`);
1967
+ }
1968
+ }
1969
+ else if (job.currentStep !== undefined) {
1970
+ if (job.mode === "chain") {
1971
+ const total = job.chainStepCount ?? stepsTotal;
1972
+ parts.push(`step ${flatToLogicalStepIndex(job.currentStep, total, job.parallelGroups ?? []) + 1}/${total}`);
1973
+ }
1974
+ else if (!isSingleChild) {
1975
+ parts.push(`step ${job.currentStep + 1}/${stepsTotal}`);
1976
+ }
1977
+ }
1978
+ else if (stepsTotal > 1) {
1979
+ parts.push(`steps ${stepsTotal}`);
1980
+ }
1981
+ if (projection.checklist && !checklistPrimary)
1982
+ parts.push(formatWorkflowChecklistSummary(projection.checklist));
1983
+ if (job.toolCount !== undefined)
1984
+ parts.push(formatToolUseStat(job.toolCount));
1985
+ if (job.totalTokens?.total)
1986
+ parts.push(formatTokenUsage(job.totalTokens, "token"));
1987
+ const end = job.status === "running" && (job.mode === "workflow" || job.parentWorkflowRunId) ? projection.now : job.updatedAt;
1988
+ if (job.status !== "queued" && job.startedAt !== undefined && end !== undefined)
1989
+ parts.push(formatDuration(Math.max(0, end - job.startedAt)));
1990
+ return statJoin(theme, parts);
1991
+ }
1992
+ function widgetStepStats(theme, step, snapshotNow = Date.now()) {
1993
+ const externalElapsed = step.runner?.type === "external-cli" && step.externalProcess
1994
+ ? step.externalProcess.durationMs ?? Math.max(0, (step.externalProcess.endedAt ?? snapshotNow) - step.externalProcess.startedAt)
1995
+ : undefined;
1996
+ return statJoin(theme, [
1997
+ step.runner?.type === "external-cli" ? "external-cli" : "",
1998
+ step.turnCount !== undefined ? `${step.turnCount} turns` : "",
1999
+ step.toolCount !== undefined ? formatToolUseStat(step.toolCount) : "",
2000
+ step.tokens
2001
+ ? step.contextLimit !== undefined
2002
+ ? formatContextUsage(step.tokens, step.contextLimit) ?? formatTokenUsage(step.tokens, "token")
2003
+ : step.tokens.total ? formatTokenUsage(step.tokens, "token") : ""
2004
+ : "",
2005
+ externalElapsed !== undefined ? formatDuration(externalElapsed) : step.durationMs !== undefined ? formatDuration(step.durationMs) : "",
2006
+ ]);
2007
+ }
2008
+ function modelThinkingBadge(theme, model, thinking) {
2009
+ const label = formatModelThinking(model, thinking);
2010
+ return label ? theme.fg("dim", ` (${label})`) : "";
2011
+ }
2012
+ function widgetStepActivityLine(step, width, expanded, snapshotNow) {
2013
+ const toolLine = formatCurrentToolLine(step, width, expanded, snapshotNow);
2014
+ if (toolLine)
2015
+ return toolLine;
2016
+ const activity = buildLiveStatusLine(step, snapshotNow);
2017
+ if (activity)
2018
+ return activity;
2019
+ if (step.status === "running")
2020
+ return "thinking…";
2021
+ return "";
2022
+ }
2023
+ function widgetOutputPath(job, step) {
2024
+ if (typeof step.index !== "number")
2025
+ return undefined;
2026
+ return path.join(job.asyncDir, `output-${step.index}.log`);
2027
+ }
2028
+ function nestedRunName(run) {
2029
+ if (run.sessionName?.trim())
2030
+ return run.sessionName.trim();
2031
+ if (run.agent)
2032
+ return run.agent;
2033
+ if (run.agents?.length)
2034
+ return formatWidgetAgents(run.agents);
2035
+ return run.id;
2036
+ }
2037
+ function nestedStatusGlyph(state, theme, seed, thinking) {
2038
+ if (state === "running")
2039
+ return runningTone(theme, thinking)(runningGlyph(seed));
2040
+ if (state === "complete" || state === "completed")
2041
+ return theme.fg("success", "✓");
2042
+ if (state === "failed")
2043
+ return theme.fg("error", "✗");
2044
+ if (state === "partial")
2045
+ return theme.fg("warning", "■");
2046
+ if (state === "paused")
2047
+ return theme.fg("warning", "■");
2048
+ if (state === "stopped")
2049
+ return theme.fg("warning", "■");
2050
+ return theme.fg("muted", "◦");
2051
+ }
2052
+ function nestedRunSeed(run) {
2053
+ return runningSeed(run.lastUpdate, run.lastActivityAt, run.currentStep, run.toolCount, run.turnCount, run.totalTokens?.total, run.currentToolStartedAt);
2054
+ }
2055
+ function formatClockTime(ms) {
2056
+ if (ms === undefined || !Number.isFinite(ms))
2057
+ return undefined;
2058
+ const date = new Date(ms);
2059
+ const pad = (value) => value.toString().padStart(2, "0");
2060
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
2061
+ }
2062
+ function nestedRunEventTime(run) {
2063
+ return run.state === "running"
2064
+ ? (run.lastActivityAt ?? run.currentToolStartedAt ?? run.lastUpdate ?? run.startedAt)
2065
+ : (run.endedAt ?? run.lastUpdate ?? run.lastActivityAt ?? run.startedAt);
2066
+ }
2067
+ function nestedStepTimestamp(step, fallback) {
2068
+ return formatClockTime(step.status === "running"
2069
+ ? (step.lastActivityAt ?? step.currentToolStartedAt ?? fallback ?? step.startedAt)
2070
+ : (step.endedAt ?? step.lastActivityAt ?? fallback ?? step.startedAt));
2071
+ }
2072
+ function nestedTimestampPrefix(timestamp) {
2073
+ return timestamp ? `[${timestamp}] ` : "";
2074
+ }
2075
+ function nestedActivity(input, state, snapshotNow) {
2076
+ const facts = [];
2077
+ if (input.currentTool && input.currentToolStartedAt !== undefined && snapshotNow !== undefined)
2078
+ facts.push(`${input.currentTool} ${formatDuration(Math.max(0, snapshotNow - input.currentToolStartedAt))}`);
2079
+ else if (input.currentTool)
2080
+ facts.push(input.currentTool);
2081
+ if (input.currentPath)
2082
+ facts.push(shortenPath(input.currentPath));
2083
+ if (input.turnCount !== undefined)
2084
+ facts.push(`${input.turnCount} turns`);
2085
+ if (input.toolCount !== undefined)
2086
+ facts.push(`${input.toolCount} tools`);
2087
+ const activity = buildLiveStatusLine(input, snapshotNow);
2088
+ if (activity && facts.length)
2089
+ return `${activity} · ${facts.join(" · ")}`;
2090
+ if (activity)
2091
+ return activity;
2092
+ if (facts.length)
2093
+ return facts.join(" · ");
2094
+ if (state === "running")
2095
+ return "thinking…";
2096
+ if (state === "queued" || state === "pending")
2097
+ return "queued…";
2098
+ if (state === "paused")
2099
+ return "Paused";
2100
+ if (state === "stopped")
2101
+ return "Stopped";
2102
+ if (state === "partial")
2103
+ return "Partial";
2104
+ if (state === "failed")
2105
+ return "Failed";
2106
+ return "Done";
2107
+ }
2108
+ function formatNestedWidgetLines(children, theme, width, expanded, snapshotNow, lineBudget = expanded ? 12 : 1) {
2109
+ if (!children?.length || lineBudget <= 0)
2110
+ return [];
2111
+ if (!expanded) {
2112
+ const rows = [];
2113
+ const maxLeaves = 4;
2114
+ const maxLines = Math.min(6, lineBudget);
2115
+ let leaves = 0;
2116
+ let overflow = 0;
2117
+ const appendLeaf = (step, prefix, fallback) => {
2118
+ if (leaves >= maxLeaves) {
2119
+ overflow++;
2120
+ return;
2121
+ }
2122
+ leaves++;
2123
+ const state = "status" in step ? step.status : step.state;
2124
+ const modelThinking = formatModelThinking(step.model, step.thinking);
2125
+ const activity = nestedActivity(step, state, snapshotNow ?? fallback);
2126
+ const timestamp = "status" in step ? nestedStepTimestamp(step, fallback) : formatClockTime(nestedRunEventTime(step));
2127
+ const error = step.error ? ` · ${step.error}` : "";
2128
+ const name = "status" in step ? childDisplayName(step) : nestedRunName(step);
2129
+ rows.push({
2130
+ prefix,
2131
+ text: `${nestedTimestampPrefix(timestamp)}${nestedStatusGlyph(state, theme, undefined, childThinkingLevel(step))} ${name} · ${state}${modelThinking ? ` · ${modelThinking}` : ""}${activity ? ` · ${activity}` : ""}${error}`,
2132
+ });
2133
+ };
2134
+ for (const child of children) {
2135
+ const steps = (child.mode === "parallel" || child.mode === "chain") ? child.steps ?? [] : [];
2136
+ if (steps.length > 0) {
2137
+ const ownerModelThinking = formatModelThinking(child.model, child.thinking);
2138
+ const ownerActivity = nestedActivity(child, child.state, snapshotNow ?? child.lastUpdate);
2139
+ const ownerError = child.error ? ` · ${child.error}` : "";
2140
+ rows.push({
2141
+ prefix: "↳ ",
2142
+ text: `OWNER ${nestedStatusGlyph(child.state, theme, nestedRunSeed(child), childThinkingLevel(child))} ${nestedRunName(child)} · ${child.state}${ownerModelThinking ? ` · ${ownerModelThinking}` : ""}${ownerActivity ? ` · ${ownerActivity}` : ""}${ownerError}`,
2143
+ });
2144
+ for (const step of steps)
2145
+ appendLeaf(step, "↳ │ ", child.lastUpdate);
2146
+ }
2147
+ else {
2148
+ appendLeaf(child, "↳ ", child.lastUpdate);
2149
+ }
2150
+ }
2151
+ if (overflow > 0)
2152
+ rows.push({ prefix: "↳ ", text: `… +${overflow} more nested leaves` });
2153
+ const visibleRows = rows.length <= maxLines
2154
+ ? rows
2155
+ : overflow > 0
2156
+ ? [...rows.slice(0, Math.max(0, maxLines - 1)), rows.at(-1)]
2157
+ : rows.slice(0, maxLines);
2158
+ return visibleRows.map((row, index) => {
2159
+ const marker = index === visibleRows.length - 1 ? "└─" : "├─";
2160
+ const prefix = row.prefix;
2161
+ const text = row.text.startsWith("OWNER ") ? row.text.slice("OWNER ".length) : row.text;
2162
+ return truncLine(theme.fg("dim", `${prefix}${marker} ${text}`), width);
2163
+ });
2164
+ }
2165
+ const lines = [];
2166
+ const maxDepth = 2;
2167
+ const append = (items, depth, prefix) => {
2168
+ if (!items?.length || lines.length >= lineBudget)
2169
+ return;
2170
+ if (depth > maxDepth) {
2171
+ const aggregate = formatNestedAggregate(items);
2172
+ if (aggregate && lines.length < lineBudget)
2173
+ lines.push(theme.fg("dim", `${prefix}↳ ${aggregate}`));
2174
+ return;
2175
+ }
2176
+ for (let index = 0; index < items.length; index++) {
2177
+ const child = items[index];
2178
+ if (lines.length >= lineBudget) {
2179
+ const aggregate = formatNestedAggregate(items.slice(index));
2180
+ if (aggregate)
2181
+ lines[lines.length - 1] = theme.fg("dim", `${prefix}↳ ${aggregate}`);
2182
+ return;
2183
+ }
2184
+ const activity = nestedActivity(child, child.state, snapshotNow ?? child.lastUpdate);
2185
+ const error = child.error ? ` · ${child.error}` : "";
2186
+ const modelThinking = formatModelThinking(child.model, child.thinking);
2187
+ lines.push(theme.fg("dim", `${prefix}↳ ${nestedTimestampPrefix(formatClockTime(nestedRunEventTime(child)))}${nestedStatusGlyph(child.state, theme, nestedRunSeed(child), childThinkingLevel(child))} ${nestedRunName(child)} · ${child.state}${modelThinking ? ` · ${modelThinking}` : ""} · ${activity}${error}`));
2188
+ if (depth === maxDepth) {
2189
+ const aggregate = formatNestedAggregate([...(child.steps?.flatMap((step) => step.children ?? []) ?? []), ...(child.children ?? [])]);
2190
+ if (aggregate && lines.length < lineBudget)
2191
+ lines.push(theme.fg("dim", `${prefix} ↳ ${aggregate}`));
2192
+ continue;
2193
+ }
2194
+ for (const step of child.steps ?? []) {
2195
+ if (lines.length >= lineBudget)
2196
+ return;
2197
+ const modelThinking = formatModelThinking(step.model, step.thinking);
2198
+ lines.push(theme.fg("dim", `${prefix} ↳ ${nestedTimestampPrefix(nestedStepTimestamp(step, child.lastUpdate))}${nestedStatusGlyph(step.status, theme, undefined, childThinkingLevel(step))} ${childDisplayName(step)} · ${step.status}${modelThinking ? ` · ${modelThinking}` : ""} · ${nestedActivity(step, step.status, snapshotNow ?? child.lastUpdate)}`));
2199
+ append(step.children, depth + 1, `${prefix} `);
2200
+ }
2201
+ append(child.children, depth + 1, `${prefix} `);
2202
+ }
2203
+ };
2204
+ append(children, 0, "");
2205
+ return lines.map((line) => truncLine(line, width));
2206
+ }
2207
+ function foregroundStyleWidgetStepLines(job, theme, step, itemTitle, index, total, expanded, width, frame, options) {
2208
+ const rowIndent = options?.rowIndent ?? " ";
2209
+ const detailIndent = options?.detailIndent ?? " ";
2210
+ const thinking = childThinkingLevel(step);
2211
+ const status = widgetStepStatus(step.status, theme, thinking);
2212
+ const stats = widgetStepStats(theme, step, job.updatedAt);
2213
+ const modelDisplay = modelThinkingBadge(theme, step.model, step.thinking);
2214
+ const collapseDetails = shouldCollapseSingleChildDetails(job, step);
2215
+ const displayName = collapseDetails ? singleChildAgentName(job, step) : childDisplayName(step);
2216
+ const stageName = itemTitle === "Stage"
2217
+ ? compactTaskText(undefined, step.label) ?? boundedLaneValue(step.workflowKey) ?? displayName
2218
+ : undefined;
2219
+ const stageIdentity = stageName && stageName !== displayName ? `${stageName} (${displayName})` : stageName ?? displayName;
2220
+ const rowLabel = collapseDetails ? displayName : (options?.rowLabel ?? `${itemTitle} ${index}/${total}: ${itemTitle === "Stage" ? stageIdentity : displayName}`);
2221
+ const rowMarker = options?.rowMarker ? `${options.rowMarker} ` : "";
2222
+ const lines = [`${rowIndent}${rowMarker}${widgetStepGlyph(step.status, theme, widgetStepRunningSeed(step, index - 1), frame, thinking)} ${themeBold(theme, rowLabel)}${contextModeBadge(theme, step.context)} ${theme.fg("dim", "·")} ${status}${modelDisplay}${stats ? ` ${theme.fg("dim", "·")} ${stats}` : ""}`];
2223
+ const lane = projectAsyncLane(job, step);
2224
+ if (lane)
2225
+ lines.push(...formatLaneProjectionLines(lane, theme, detailIndent));
2226
+ const task = collapseDetails ? stepTaskSummary(step, displayName) : compactTaskText(step.description, step.label);
2227
+ if (task)
2228
+ lines.push(`${detailIndent}${theme.fg("dim", `task: ${task}`)}`);
2229
+ const activity = widgetStepActivityLine(step, width, expanded, job.updatedAt);
2230
+ const currentPath = options?.includeCurrentPath && step.currentPath ? shortenPath(step.currentPath) : undefined;
2231
+ const activityWithPath = currentPath && activity && !activity.includes(currentPath)
2232
+ ? `${activity} · ${currentPath}`
2233
+ : activity ?? currentPath;
2234
+ if (activityWithPath)
2235
+ lines.push(`${detailIndent}${theme.fg("dim", `⎿ ${activityWithPath}`)}`);
2236
+ for (const nestedLine of formatNestedWidgetLines(step.children, theme, width, expanded, job.updatedAt, expanded ? 12 : 6)) {
2237
+ lines.push(`${detailIndent}${nestedLine}`);
2238
+ }
2239
+ const error = step.error?.trim() || step.execution?.error?.trim();
2240
+ if (error)
2241
+ lines.push(`${detailIndent}${theme.fg("error", `error: ${oneLine(error)}`)}`);
2242
+ if (step.status === "running") {
2243
+ if (!expanded)
2244
+ lines.push(`${detailIndent}${theme.fg("accent", liveDetailHintText())}`);
2245
+ const output = widgetOutputPath(job, step);
2246
+ if (output)
2247
+ lines.push(`${detailIndent}${theme.fg("dim", `output: ${shortenPath(output)}`)}`);
2248
+ if (expanded) {
2249
+ const liveStatus = buildLiveStatusLine(step, job.updatedAt);
2250
+ if (liveStatus && liveStatus !== activity)
2251
+ lines.push(`${detailIndent}${theme.fg("accent", liveStatus)}`);
2252
+ for (const tool of step.recentTools?.slice(-3) ?? []) {
2253
+ const maxArgsLen = Math.max(40, width - 30);
2254
+ const argsPreview = renderToolArgsPreview(tool.args, maxArgsLen, expanded);
2255
+ lines.push(`${detailIndent} ${theme.fg("dim", `${tool.tool}${argsPreview ? `: ${argsPreview}` : ""}`)}`);
2256
+ }
2257
+ for (const line of compactRecentOutputLines(step.recentOutput)) {
2258
+ lines.push(`${detailIndent} ${theme.fg("dim", line)}`);
2259
+ }
2260
+ }
2261
+ }
2262
+ return lines;
2263
+ }
2264
+ function hostStepWidgetLines(job, theme, indent) {
2265
+ const rows = projectAsyncWorkflowRows([], job.hostSteps).filter((row) => row.kind);
2266
+ const visible = rows.slice(0, 8);
2267
+ const lines = visible.map((row) => {
2268
+ const state = hostStepVerdictLabel(row.state, row.verdict);
2269
+ const glyph = state === "running" ? theme.fg("accent", "●")
2270
+ : state === "pending" ? theme.fg("muted", "◦")
2271
+ : state === "pass" ? theme.fg("success", "✓")
2272
+ : state === "fail" || state === "error" ? theme.fg("error", "✗")
2273
+ : theme.fg("warning", "■");
2274
+ const details = [
2275
+ row.provider ? `provider:${row.provider}` : undefined,
2276
+ row.role ? `role:${row.role}` : undefined,
2277
+ row.target,
2278
+ row.detail,
2279
+ row.reasonCode ? `reason:${row.reasonCode}` : undefined,
2280
+ row.freshness?.stale ? "stale" : row.freshness?.observedRef ? `ref:${row.freshness.observedRef}` : undefined,
2281
+ row.reportPath ? `out:${hostStepReportName(row.reportPath)}` : undefined,
2282
+ ].filter(Boolean).join(" · ");
2283
+ return `${indent}${glyph} ${row.kind}: ${row.name} · ${state}${details ? ` · ${details}` : ""}`;
2284
+ });
2285
+ if (rows.length > visible.length)
2286
+ lines.push(`${indent}${theme.fg("dim", `… +${rows.length - visible.length} host steps hidden`)}`);
2287
+ return lines;
2288
+ }
2289
+ function foregroundStyleWidgetDetails(job, theme, expanded, width, frame, projection = buildWorkflowWidgetProjection(job)) {
2290
+ const steps = projection.steps.filter((step) => !projection.materializedKeys?.has(step.workflowKey ?? "") && !projection.materializedKeys?.has(step.runId ?? ""));
2291
+ const checklist = widgetChecklistWithoutMaterializedChildren(projection);
2292
+ if (!expanded && job.mode === "workflow") {
2293
+ return compactWorkflowWidgetBodyLines(job, theme, frame, projection);
2294
+ }
2295
+ if (!steps.length) {
2296
+ const lane = projectAsyncLane(job, laneStepForJob(job, steps));
2297
+ return [
2298
+ ...(expanded ? workflowPreflightLines(job) : []),
2299
+ ...workflowChecklistWidgetLines(checklist, theme, " ", expanded, frame),
2300
+ ...(lane ? formatLaneProjectionLines(lane, theme, " ") : []),
2301
+ ...hostStepWidgetLines(job, theme, " "),
2302
+ ` ${theme.fg("dim", `⎿ ${widgetActivity(job)}`)}`,
2303
+ ...formatNestedWidgetLines(job.nestedChildren, theme, width, expanded, job.updatedAt, expanded ? 12 : 6).map((line) => ` ${line}`),
2304
+ ];
2305
+ }
2306
+ if (job.mode === "chain" && !job.activeParallelGroup && job.parallelGroups?.length)
2307
+ return widgetChainDetails(job, theme, expanded, width, frame);
2308
+ const lines = [
2309
+ ...(expanded ? workflowPreflightLines(job) : []),
2310
+ ...workflowChecklistWidgetLines(checklist, theme, " ", expanded, frame, { includeItemErrors: !expanded }),
2311
+ ];
2312
+ const group = activeParallelWidgetGroup(job);
2313
+ if (group) {
2314
+ lines.push(...parallelWidgetGroupDetails(job, theme, group, expanded, width, frame, Boolean(job.activeParallelGroup)));
2315
+ }
2316
+ else {
2317
+ const { stageProgress, plannedKeys } = projection;
2318
+ const total = job.mode === "chain"
2319
+ ? job.chainStepCount ?? job.stepsTotal ?? steps.length
2320
+ : stageProgress?.total ?? job.stepsTotal ?? steps.length;
2321
+ const stageTotal = stageProgress?.total ?? total;
2322
+ const extraStepCount = plannedKeys
2323
+ ? steps.filter((step) => step.workflowKey === undefined || !plannedKeys.has(step.workflowKey)).length
2324
+ : total;
2325
+ let extraStepIndex = 0;
2326
+ for (const [index, step] of steps.entries()) {
2327
+ const isPlannedStage = plannedKeys !== undefined && step.workflowKey !== undefined && plannedKeys.has(step.workflowKey);
2328
+ const itemTitle = isPlannedStage ? "Stage" : "Step";
2329
+ const displayIndex = isPlannedStage ? (step.index ?? index) + 1 : plannedKeys ? ++extraStepIndex : index + 1;
2330
+ const displayTotal = isPlannedStage ? stageTotal : extraStepCount;
2331
+ lines.push(...foregroundStyleWidgetStepLines(job, theme, step, itemTitle, displayIndex, displayTotal, expanded, width, frame));
2332
+ }
2333
+ }
2334
+ lines.push(...hostStepWidgetLines(job, theme, " "));
2335
+ const attached = new Set(steps.flatMap((step) => step.children?.map((child) => child.id) ?? []));
2336
+ const unattached = job.nestedChildren?.filter((child) => !attached.has(child.id)) ?? [];
2337
+ for (const nestedLine of formatNestedWidgetLines(unattached, theme, width, expanded, job.updatedAt, expanded ? 12 : 6)) {
2338
+ lines.push(` ${nestedLine}`);
2339
+ }
2340
+ return lines;
2341
+ }
2342
+ function buildSingleWidgetLines(job, theme, width, expanded, frame, projection = buildWorkflowWidgetProjection(job)) {
2343
+ if ((!expanded || projection.inlineFleetCovered) && job.mode === "workflow")
2344
+ return [compactWorkflowHeaderLine(job, theme, width), ...compactWorkflowWidgetBodyLines(job, theme, frame, projection)].map((line) => truncLine(line, width));
2345
+ const stats = widgetStats(job, theme, projection, !expanded);
2346
+ const count = job.mode === "workflow"
2347
+ ? projection.checklist?.total ?? projection.stageProgress?.total ?? job.stepsTotal ?? job.agents?.length ?? job.steps?.length
2348
+ : job.mode === "chain" ? job.chainStepCount : projection.stageProgress?.total ?? job.stepsTotal ?? job.agents?.length ?? job.steps?.length;
2349
+ const mode = widgetJobName(job);
2350
+ const title = isSingleChildAsyncJob(job)
2351
+ ? "async subagent"
2352
+ : `async subagent ${mode}${count && count > 1 ? ` (${count})` : ""}`;
2353
+ const checklistPrimary = !expanded && job.mode === "workflow" && projection.checklist !== undefined;
2354
+ const collapseDetails = !checklistPrimary && job.steps?.length === 1 && shouldCollapseSingleChildDetails(job, job.steps[0]);
2355
+ const summary = `${widgetStatusGlyph(job, theme, frame)} ${themeBold(theme, mode)}${contextModeBadge(theme, job.context)}${stats ? ` ${theme.fg("dim", "·")} ${stats}` : ""}`;
2356
+ return [
2357
+ `${theme.fg("toolTitle", themeBold(theme, title))} ${theme.fg("dim", "· background")}`,
2358
+ ...(collapseDetails ? [] : [summary]),
2359
+ ...foregroundStyleWidgetDetails(job, theme, expanded, width, frame, projection),
2360
+ ].map((line) => truncLine(line, width));
2361
+ }
2362
+ function compactSingleWidgetLines(job, theme, width, frame, projection = buildWorkflowWidgetProjection(job)) {
2363
+ const fullLines = buildSingleWidgetLines(job, theme, width, false, frame, projection);
2364
+ if (fullLines.length <= 10 || !job.steps?.length || (job.mode !== "parallel" && !job.activeParallelGroup))
2365
+ return fullLines;
2366
+ const group = activeParallelWidgetGroup(job);
2367
+ if (!group)
2368
+ return fullLines;
2369
+ const rows = parallelWidgetStepRows(group.steps, group.total, Boolean(job.activeParallelGroup));
2370
+ const lines = fullLines.slice(0, 2);
2371
+ lines.push(parallelWidgetGroupHeader(group, theme, frame));
2372
+ for (const [rowIndex, row] of rows.entries()) {
2373
+ const step = row.step;
2374
+ const thinking = childThinkingLevel(step);
2375
+ const status = widgetStepStatus(step.status, theme, thinking);
2376
+ const activity = widgetStepActivityLine(step, width, false, job.updatedAt);
2377
+ const stepStats = widgetStepStats(theme, step, job.updatedAt);
2378
+ const activitySuffix = activity ? ` ${theme.fg("dim", "·")} ${theme.fg("dim", activity)}` : "";
2379
+ const modelDisplay = modelThinkingBadge(theme, step.model, step.thinking);
2380
+ const task = compactTaskText(step.description, step.label);
2381
+ const taskSuffix = task ? ` ${theme.fg("dim", "·")} ${theme.fg("dim", `task: ${task}`)}` : "";
2382
+ const marker = rowIndex === rows.length - 1 && rowIndex >= group.total - 1 ? "└─" : "├─";
2383
+ lines.push(` ${marker} ${widgetStepGlyph(step.status, theme, widgetStepRunningSeed(step, row.index), frame, thinking)} ${themeBold(theme, row.rowLabel)}${contextModeBadge(theme, step.context)} ${theme.fg("dim", "·")} ${status}${modelDisplay}${taskSuffix}${activitySuffix}${stepStats ? ` ${theme.fg("dim", "·")} ${stepStats}` : ""}`);
2384
+ const lane = projectAsyncLane(job, step);
2385
+ if (lane)
2386
+ lines.push(...formatLaneProjectionLines(lane, theme, " "));
2387
+ for (const nestedLine of formatNestedWidgetLines(step.children, theme, width, false, job.updatedAt, 6))
2388
+ lines.push(` ${nestedLine}`);
2389
+ }
2390
+ lines.push(...hostStepWidgetLines(job, theme, " "));
2391
+ if (job.steps.some((step) => step.status === "running"))
2392
+ lines.push(theme.fg("accent", ` ${liveDetailHintText()}`));
2393
+ return lines.map((line) => truncLine(line, width));
2394
+ }
2395
+ const RESERVED_NON_WIDGET_ROWS = 19;
2396
+ let widgetLayoutSession;
2397
+ function resetWidgetLayoutSession() {
2398
+ widgetLayoutSession = undefined;
2399
+ }
2400
+ function estimateAvailableWidgetRows() {
2401
+ const rows = process.stdout.rows || 30;
2402
+ return Math.max(1, rows - RESERVED_NON_WIDGET_ROWS);
2403
+ }
2404
+ function currentTerminalRows() {
2405
+ return process.stdout.rows || 30;
2406
+ }
2407
+ function currentTerminalColumns() {
2408
+ return process.stdout.columns || 120;
2409
+ }
2410
+ function widgetSessionMatches(expanded) {
2411
+ return widgetLayoutSession?.expanded === expanded
2412
+ && widgetLayoutSession.rows === currentTerminalRows()
2413
+ && widgetLayoutSession.columns === currentTerminalColumns();
2414
+ }
2415
+ function widgetHeaderCounts(jobs) {
2416
+ return {
2417
+ running: jobs.filter((job) => job.status === "running"),
2418
+ queued: jobs.filter((job) => job.status === "queued"),
2419
+ complete: jobs.filter((job) => job.status === "complete"),
2420
+ failed: jobs.filter((job) => job.status === "failed"),
2421
+ paused: jobs.filter((job) => job.status === "paused"),
2422
+ stopped: jobs.filter((job) => job.status === "stopped"),
2423
+ };
2424
+ }
2425
+ const roundStateByUi = new WeakMap();
2426
+ function trackSubagentsRound(ui, jobs, now) {
2427
+ const running = jobs.filter((job) => job.status === "running");
2428
+ if (running.length > 0) {
2429
+ // Seed from the oldest running job so a round restored after a session resume matches the job rows.
2430
+ if (!roundStateByUi.has(ui))
2431
+ roundStateByUi.set(ui, { startedAt: Math.min(now, ...running.map((job) => job.startedAt ?? now)) });
2432
+ return;
2433
+ }
2434
+ roundStateByUi.delete(ui);
2435
+ }
2436
+ function roundElapsedSuffix(ui, now) {
2437
+ const state = roundStateByUi.get(ui);
2438
+ return state ? ` ${formatRoundElapsed(now - state.startedAt)}` : "";
2439
+ }
2440
+ function formatRoundElapsed(ms) {
2441
+ const total = Math.max(0, Math.floor(ms / 1000));
2442
+ const hours = Math.floor(total / 3600);
2443
+ const minutes = Math.floor((total % 3600) / 60);
2444
+ const seconds = total % 60;
2445
+ if (hours > 0)
2446
+ return `${hours}h${minutes}m${seconds}s`;
2447
+ if (minutes > 0)
2448
+ return `${minutes}m${seconds}s`;
2449
+ return `${seconds}s`;
2450
+ }
2451
+ function buildSingleLineWidgetLines(jobs, theme, width, frame, elapsedSuffix = "") {
2452
+ const counts = widgetHeaderCounts(jobs);
2453
+ const hasActive = counts.running.length > 0 || counts.queued.length > 0;
2454
+ const glyph = counts.running.length > 0 ? runningGlyph(animatedSeed(widgetJobsRunningSeed(counts.running), frame)) : hasActive ? "●" : "○";
2455
+ const parts = [];
2456
+ if (counts.running.length > 0)
2457
+ parts.push(`${counts.running.length}/${jobs.length} running${elapsedSuffix}`);
2458
+ if (counts.queued.length > 0)
2459
+ parts.push(`${counts.queued.length} queued`);
2460
+ if (counts.failed.length > 0)
2461
+ parts.push(`${counts.failed.length} failed`);
2462
+ if (counts.stopped.length > 0)
2463
+ parts.push(`${counts.stopped.length} stopped`);
2464
+ if (counts.paused.length > 0)
2465
+ parts.push(`${counts.paused.length} paused`);
2466
+ for (const status of ["partial", "rejected"]) {
2467
+ const count = jobs.filter((job) => job.status === status).length;
2468
+ if (count > 0)
2469
+ parts.push(`${count} ${status}`);
2470
+ }
2471
+ if (!hasActive && counts.complete.length > 0)
2472
+ parts.push(`${counts.complete.length}/${jobs.length} done`);
2473
+ const tone = activeHeaderTone(theme, hasActive);
2474
+ return [truncLine(`${tone(glyph)} ${tone("subagents")} (${parts.join(", ") || `${jobs.length} total`})`, width)];
2475
+ }
2476
+ function orderedWidgetJobs(jobs) {
2477
+ return [
2478
+ ...jobs.filter((job) => job.status === "running"),
2479
+ ...jobs.filter((job) => job.status === "queued"),
2480
+ ...jobs.filter((job) => job.status !== "running" && job.status !== "queued"),
2481
+ ];
2482
+ }
2483
+ function progressiveJobKey(job) {
2484
+ return job.asyncId;
2485
+ }
2486
+ function isProgressiveActiveJob(job) {
2487
+ return job?.status === "running" || job?.status === "queued";
2488
+ }
2489
+ function selectProgressiveJobKeys(jobs, previousKeys, bodyRows) {
2490
+ if (bodyRows <= 0)
2491
+ return [];
2492
+ const jobsByKey = new Map(jobs.map((job) => [progressiveJobKey(job), job]));
2493
+ const selected = [];
2494
+ const append = (key) => {
2495
+ if (selected.includes(key) || !jobsByKey.has(key))
2496
+ return;
2497
+ selected.push(key);
2498
+ };
2499
+ for (const key of previousKeys) {
2500
+ if (!isProgressiveActiveJob(jobsByKey.get(key)))
2501
+ continue;
2502
+ append(key);
2503
+ if (selected.length >= bodyRows)
2504
+ return selected;
2505
+ }
2506
+ for (const job of orderedWidgetJobs(jobs)) {
2507
+ if (!isProgressiveActiveJob(job))
2508
+ continue;
2509
+ const key = progressiveJobKey(job);
2510
+ append(key);
2511
+ if (selected.length >= bodyRows)
2512
+ break;
2513
+ }
2514
+ if (selected.length >= bodyRows)
2515
+ return selected;
2516
+ for (const key of previousKeys) {
2517
+ if (isProgressiveActiveJob(jobsByKey.get(key)))
2518
+ continue;
2519
+ append(key);
2520
+ if (selected.length >= bodyRows)
2521
+ return selected;
2522
+ }
2523
+ for (const job of orderedWidgetJobs(jobs)) {
2524
+ const key = progressiveJobKey(job);
2525
+ append(key);
2526
+ if (selected.length >= bodyRows)
2527
+ break;
2528
+ }
2529
+ return selected;
2530
+ }
2531
+ // Counts the leaf entries collectFleetStatusEntries (fleet-status.ts) makes for a running async job,
2532
+ // so this matches FleetView's "N active agents": a workflow counts only its loaded child runs;
2533
+ // another job counts its active steps, synthesized from `agents` when it has no steps.
2534
+ function runningLeafAgentCount(job, projectionFor) {
2535
+ if (job.mode === "workflow")
2536
+ return (projectionFor(job).children ?? []).reduce((total, child) => total + runningLeafAgentCount(child, projectionFor), 0);
2537
+ if (job.status !== "running")
2538
+ return 0;
2539
+ const sequential = job.mode === "chain" && !job.activeParallelGroup;
2540
+ const current = job.currentStep ?? 0;
2541
+ const steps = job.steps?.length
2542
+ ? job.steps
2543
+ : job.agents?.map((_, index) => ({ index, status: sequential && index !== current ? "pending" : "running" }));
2544
+ if (!steps?.length)
2545
+ return 1;
2546
+ return steps.filter((step, offset) => ["running", "queued", "pending"].includes(step.status)
2547
+ && !(step.status === "pending" && sequential && (step.index ?? offset) !== current)).length;
2548
+ }
2549
+ function progressiveHeaderLine(jobs, theme, width, frame, projectionFor) {
2550
+ const counts = widgetHeaderCounts(jobs);
2551
+ const hasActive = counts.running.length > 0 || counts.queued.length > 0;
2552
+ const glyph = counts.running.length > 0 ? runningGlyph(animatedSeed(widgetJobsRunningSeed(counts.running), frame)) : hasActive ? "●" : "○";
2553
+ const parts = [];
2554
+ const runningAgents = jobs.reduce((total, job) => total + runningLeafAgentCount(job, projectionFor), 0);
2555
+ if (runningAgents > 0)
2556
+ parts.push(formatAgentRunningLabel(runningAgents));
2557
+ if (counts.queued.length > 0)
2558
+ parts.push(`${counts.queued.length} queued`);
2559
+ if (!hasActive) {
2560
+ if (counts.failed.length > 0)
2561
+ parts.push(`${counts.failed.length} failed`);
2562
+ if (counts.stopped.length > 0)
2563
+ parts.push(`${counts.stopped.length} stopped`);
2564
+ if (counts.paused.length > 0)
2565
+ parts.push(`${counts.paused.length} paused`);
2566
+ if (counts.complete.length > 0)
2567
+ parts.push(`${counts.complete.length}/${jobs.length} done`);
2568
+ }
2569
+ const tone = activeHeaderTone(theme, hasActive);
2570
+ return truncLine(`${tone(glyph)} ${tone("Async agents")} ${theme.fg("dim", "·")} ${theme.fg("dim", parts.join(", ") || `${jobs.length} total`)}`, width);
2571
+ }
2572
+ function progressiveJobLine(job, theme, width, frame, projection = buildWorkflowWidgetProjection(job), compactRows = job.mode === "workflow" ? compactWorkflowLaneRows(job, projection.checklist) : undefined) {
2573
+ const compactWorkflow = job.mode === "workflow";
2574
+ const stats = compactWorkflow ? compactWorkflowStats(job, compactRows ?? [], theme, projection) : widgetStats(job, theme, projection, true);
2575
+ if (compactWorkflow) {
2576
+ const bottleneck = compactWorkflowBottleneck(compactRows ?? [], job);
2577
+ const suffix = [stats, bottleneck ? theme.fg(bottleneck.tone, `bottleneck · ${bottleneck.text}`) : undefined].filter((value) => Boolean(value)).join(` ${theme.fg("dim", "·")} `);
2578
+ return truncLine(` ${widgetStatusGlyph(job, theme, frame)} ${compactWorkflowHeaderLine(job, theme, Math.max(0, width - 4))}${suffix ? ` ${theme.fg("dim", "·")} ${suffix}` : ""}`, width);
2579
+ }
2580
+ const activity = widgetActivity(job);
2581
+ const status = job.status === "complete" ? "done" : job.status;
2582
+ const lane = projectAsyncLane(job, laneStepForJob(job, projection.steps));
2583
+ const laneSummary = lane
2584
+ ? [lane.label ?? lane.role, lane.phase ? `phase:${lane.phase}` : undefined, lane.output ? `out:${lane.output}` : undefined, lane.workspace ? `workspace:${lane.workspace}` : `ref:${lane.ref}`].filter(Boolean).join(" · ")
2585
+ : "";
2586
+ const laneSignals = lane
2587
+ ? [lane.next ? `next:${lane.next}` : undefined, ...lane.chips.map((chip) => formatLaneChip(chip, theme))].filter(Boolean).join(" · ")
2588
+ : "";
2589
+ const parts = [
2590
+ `${themeBold(theme, widgetJobName(job))}${contextModeBadge(theme, job.context)}`,
2591
+ theme.fg("dim", status),
2592
+ laneSignals ? laneSignals : "",
2593
+ laneSummary ? theme.fg("dim", laneSummary) : "",
2594
+ stats,
2595
+ activity && activity.toLowerCase() !== status ? theme.fg("dim", activity) : "",
2596
+ ].filter(Boolean);
2597
+ return truncLine(` ${widgetStatusGlyph(job, theme, frame)} ${parts.join(` ${theme.fg("dim", "·")} `)}`, width);
2598
+ }
2599
+ function progressiveHiddenLine(hiddenJobs, theme, width) {
2600
+ const counts = widgetHeaderCounts(hiddenJobs);
2601
+ const parts = [];
2602
+ if (counts.running.length > 0)
2603
+ parts.push(`${counts.running.length} running`);
2604
+ if (counts.queued.length > 0)
2605
+ parts.push(`${counts.queued.length} queued`);
2606
+ const finished = counts.complete.length + counts.failed.length + counts.paused.length + counts.stopped.length;
2607
+ if (finished > 0)
2608
+ parts.push(`${finished} finished`);
2609
+ return truncLine(theme.fg("dim", ` +${hiddenJobs.length} more${parts.length ? ` (${parts.join(", ")})` : ""}`), width);
2610
+ }
2611
+ function buildProgressiveWidgetLines(jobs, theme, width, lockedRows, previousKeys, frame, projectionFor = workflowWidgetProjectionLookup(), elapsedSuffix = "") {
2612
+ const rowCount = Math.max(1, lockedRows);
2613
+ if (rowCount === 1)
2614
+ return { lines: buildSingleLineWidgetLines(jobs, theme, width, frame, elapsedSuffix), visibleJobKeys: [], contentRows: 1 };
2615
+ const bodyRows = rowCount - 1;
2616
+ let visibleJobKeys = selectProgressiveJobKeys(jobs, previousKeys, bodyRows);
2617
+ const jobsByKey = new Map(jobs.map((job) => [progressiveJobKey(job), job]));
2618
+ let visibleJobs = visibleJobKeys.map((key) => jobsByKey.get(key)).filter((job) => Boolean(job));
2619
+ let hiddenJobs = jobs.filter((job) => !visibleJobKeys.includes(progressiveJobKey(job)));
2620
+ const needsHiddenLine = hiddenJobs.length > 0;
2621
+ if (needsHiddenLine && visibleJobs.length >= bodyRows && bodyRows > 0) {
2622
+ visibleJobs = visibleJobs.slice(0, bodyRows - 1);
2623
+ visibleJobKeys = visibleJobs.map(progressiveJobKey);
2624
+ hiddenJobs = jobs.filter((job) => !visibleJobKeys.includes(progressiveJobKey(job)));
2625
+ }
2626
+ // Rows left after every visible job line show the visible workflows' lanes.
2627
+ let spareRows = rowCount - 1 - visibleJobs.length - (hiddenJobs.length > 0 ? 1 : 0);
2628
+ const lines = [progressiveHeaderLine(jobs, theme, width, frame, projectionFor)];
2629
+ for (const job of visibleJobs) {
2630
+ const projection = projectionFor(job);
2631
+ const laneRows = job.mode === "workflow" ? compactWorkflowLaneRows(job, projection.checklist) : undefined;
2632
+ lines.push(progressiveJobLine(job, theme, width, frame, projection, laneRows));
2633
+ if (!laneRows || projection.inlineFleetCovered)
2634
+ continue;
2635
+ const shownLanes = laneRows.slice(0, Math.max(0, spareRows));
2636
+ for (const row of shownLanes)
2637
+ lines.push(truncLine(compactWorkflowLaneLine(row, theme, " ", frame), width));
2638
+ spareRows -= shownLanes.length;
2639
+ }
2640
+ if (hiddenJobs.length > 0 && lines.length < rowCount)
2641
+ lines.push(progressiveHiddenLine(hiddenJobs, theme, width));
2642
+ const contentRows = Math.min(lines.length, rowCount);
2643
+ while (lines.length < rowCount)
2644
+ lines.push(" ");
2645
+ return { lines: lines.slice(0, rowCount), visibleJobKeys, contentRows };
2646
+ }
2647
+ function collapsedWidgetLineBudget(rows) {
2648
+ return Math.max(10, Math.min(14, Math.floor(rows * 0.35)));
2649
+ }
2650
+ function paddedWidgetLine(line, width) {
2651
+ if (width <= 2)
2652
+ return " ".repeat(Math.max(0, width));
2653
+ const text = ` ${truncLine(line, width - 2)} `;
2654
+ return `${text}${" ".repeat(Math.max(0, width - visibleWidth(text)))}`;
2655
+ }
2656
+ function fitWidgetLineBudget(lines, theme, width, expanded) {
2657
+ const rows = process.stdout.rows || 30;
2658
+ const budget = expanded
2659
+ ? Math.max(12, Math.min(24, Math.floor(rows * 0.55)))
2660
+ : collapsedWidgetLineBudget(rows);
2661
+ if (lines.length <= budget)
2662
+ return lines;
2663
+ const visibleLines = Math.max(1, budget - 1);
2664
+ const hiddenCount = lines.length - visibleLines;
2665
+ const hint = expanded
2666
+ ? `… ${hiddenCount} live-detail lines hidden`
2667
+ : `… ${hiddenCount} lines hidden · ${expandKeyHint("to expand")}`;
2668
+ return [...lines.slice(0, visibleLines), truncLine(theme.fg("dim", hint), width)];
2669
+ }
2670
+ function fitAdaptiveWidgetLines(jobs, buildLines, theme, width, expanded, frame, projectionFor, layout = "adaptive", elapsedSuffix = "") {
2671
+ if (expanded) {
2672
+ resetWidgetLayoutSession();
2673
+ return fitWidgetLineBudget(buildLines(), theme, width, true);
2674
+ }
2675
+ const hasMatchingSession = widgetSessionMatches(expanded);
2676
+ const rows = currentTerminalRows();
2677
+ const columns = currentTerminalColumns();
2678
+ const availableRows = estimateAvailableWidgetRows();
2679
+ if (hasMatchingSession && widgetLayoutSession?.tier === "single-line") {
2680
+ return buildSingleLineWidgetLines(jobs, theme, width, frame, elapsedSuffix);
2681
+ }
2682
+ if (hasMatchingSession && widgetLayoutSession?.tier === "progressive" && widgetLayoutSession.lockedRows !== undefined) {
2683
+ const session = widgetLayoutSession;
2684
+ const lockedRows = widgetLayoutSession.lockedRows;
2685
+ let rendered = buildProgressiveWidgetLines(jobs, theme, width, lockedRows, session.visibleJobKeys, frame, projectionFor, elapsedSuffix);
2686
+ // The height stays fixed across content-only updates (#186). It grows when a new job would be hidden while the cap
2687
+ // has room, and shrinks to content only when root jobs leave, so finished jobs leave no blank rows.
2688
+ const capRows = Math.min(availableRows, collapsedWidgetLineBudget(rows));
2689
+ if (rendered.visibleJobKeys.length < jobs.length && lockedRows < capRows) {
2690
+ rendered = buildProgressiveWidgetLines(jobs, theme, width, capRows, session.visibleJobKeys, frame, projectionFor, elapsedSuffix);
2691
+ session.lockedRows = Math.max(lockedRows, rendered.contentRows);
2692
+ }
2693
+ else if (jobs.length < (session.rootJobCount ?? 0)) {
2694
+ session.lockedRows = rendered.contentRows;
2695
+ }
2696
+ session.rootJobCount = jobs.length;
2697
+ session.visibleJobKeys = rendered.visibleJobKeys;
2698
+ return rendered.lines.slice(0, session.lockedRows);
2699
+ }
2700
+ if (layout === "adaptive") {
2701
+ const lines = buildLines();
2702
+ if (lines.length <= availableRows) {
2703
+ widgetLayoutSession = { expanded, rows, columns, tier: "full", visibleJobKeys: [] };
2704
+ return fitWidgetLineBudget(lines, theme, width, false);
2705
+ }
2706
+ if (availableRows > 2 && jobs.length === 1 && projectionFor?.(jobs[0]).stageProgress) {
2707
+ widgetLayoutSession = { expanded, rows, columns, tier: "full", visibleJobKeys: [] };
2708
+ return fitWidgetLineBudget(lines, theme, width, false);
2709
+ }
2710
+ }
2711
+ if (availableRows <= 2) {
2712
+ widgetLayoutSession = { expanded, rows, columns, tier: "single-line", visibleJobKeys: [] };
2713
+ return buildSingleLineWidgetLines(jobs, theme, width, frame, elapsedSuffix);
2714
+ }
2715
+ // Lock to the rows the content fills so the fixed-height card has no blank padding.
2716
+ const rendered = buildProgressiveWidgetLines(jobs, theme, width, Math.min(availableRows, collapsedWidgetLineBudget(rows)), [], frame, projectionFor, elapsedSuffix);
2717
+ const lockedRows = rendered.contentRows;
2718
+ widgetLayoutSession = { expanded, rows, columns, tier: "progressive", lockedRows, rootJobCount: jobs.length, visibleJobKeys: rendered.visibleJobKeys };
2719
+ return rendered.lines.slice(0, lockedRows);
2720
+ }
2721
+ const asyncWidgetUpdates = new WeakMap();
2722
+ const inlineWorkflowCoverage = new WeakMap();
2723
+ const asyncWidgetInvalidations = new WeakMap();
2724
+ function inlineWorkflowDescendantShape(children) {
2725
+ return children?.map((child) => [child.id, child.agent, inlineWorkflowDescendantShape(child.children)]);
2726
+ }
2727
+ function inlineWorkflowRowShape(job) {
2728
+ return [
2729
+ job.asyncId,
2730
+ job.parentWorkflowRunId,
2731
+ job.workflowKey,
2732
+ job.mode,
2733
+ job.currentStep,
2734
+ job.activeParallelGroup,
2735
+ job.status,
2736
+ job.context,
2737
+ job.agents,
2738
+ job.steps?.map((step, index) => [
2739
+ step.index ?? index,
2740
+ step.workflowKey,
2741
+ step.agent,
2742
+ step.status,
2743
+ Boolean(step.runner),
2744
+ inlineWorkflowDescendantShape(step.children),
2745
+ ]),
2746
+ inlineWorkflowDescendantShape(job.nestedChildren),
2747
+ job.hostSteps?.map((row) => [row.id, row.monitorKind, row.label]),
2748
+ Boolean(job.workflowGraph),
2749
+ ];
2750
+ }
2751
+ /** Structural identity of the workflow rows that Fleet can cover. */
2752
+ export function inlineWorkflowRenderKey(job, children) {
2753
+ return JSON.stringify([inlineWorkflowRowShape(job), children.map(inlineWorkflowRowShape)]);
2754
+ }
2755
+ /** Presentation-only coverage from the mounted inline Fleet roster, never configuration. */
2756
+ export function setInlineWorkflowCoverage(ui, coverage) {
2757
+ const previous = inlineWorkflowCoverage.get(ui);
2758
+ if ((previous?.size ?? 0) === coverage.size && [...coverage].every(([id, key]) => previous?.get(id) === key))
2759
+ return;
2760
+ if (coverage.size)
2761
+ inlineWorkflowCoverage.set(ui, coverage);
2762
+ else
2763
+ inlineWorkflowCoverage.delete(ui);
2764
+ asyncWidgetInvalidations.get(ui)?.();
2765
+ }
2766
+ /** Attach only to loaded workflow parents; orphan jobs remain top-level. */
2767
+ function widgetJobTree(jobs, now) {
2768
+ const parents = new Map(jobs.filter((job) => job.mode === "workflow").map((job) => [job.asyncId, job]));
2769
+ const childrenByParent = new Map();
2770
+ const roots = [];
2771
+ for (const job of jobs) {
2772
+ const parent = job.parentWorkflowRunId ? parents.get(job.parentWorkflowRunId) : undefined;
2773
+ // Root-only adaptive summaries cannot advertise live work under a non-running parent.
2774
+ const keepLiveRoot = isProgressiveActiveJob(job) && parent?.status !== "running";
2775
+ if (parent && parent.asyncId !== job.asyncId && !keepLiveRoot) {
2776
+ const children = childrenByParent.get(parent.asyncId) ?? [];
2777
+ children.push(job);
2778
+ childrenByParent.set(parent.asyncId, children);
2779
+ }
2780
+ else
2781
+ roots.push(job);
2782
+ }
2783
+ return { roots, projectionFor: workflowWidgetProjectionLookup(now, childrenByParent) };
2784
+ }
2785
+ function widgetChecklistWithoutMaterializedChildren(projection) {
2786
+ const { checklist, materializedKeys } = projection;
2787
+ if (!checklist || !materializedKeys)
2788
+ return checklist;
2789
+ return { ...checklist, phases: checklist.phases.map((phase) => ({ ...phase, items: phase.items.filter((item) => !materializedKeys.has(item.key)) })) };
2790
+ }
2791
+ function materializedWidgetChildLines(job, theme, width, expanded, frame, projectionFor) {
2792
+ const { children, inlineFleetCovered } = projectionFor(job);
2793
+ if (inlineFleetCovered || !children?.length)
2794
+ return [];
2795
+ const lines = [];
2796
+ const shown = orderedWidgetJobs(children).slice(0, MAX_WIDGET_JOBS);
2797
+ for (const [index, child] of shown.entries()) {
2798
+ const projection = projectionFor(child);
2799
+ const last = index === children.length - 1;
2800
+ const identity = child.workflowKey ?? child.asyncId;
2801
+ const stats = widgetStats(child, theme, projection, !expanded);
2802
+ lines.push(` ${last ? "└─" : "├─"} ${theme.bold(identity)} ${widgetStatusGlyph(child, theme, frame)} ${themeBold(theme, widgetJobName(child))}${contextModeBadge(theme, child.context)}${stats ? ` ${theme.fg("dim", "·")} ${stats}` : ""}`);
2803
+ for (const detail of foregroundStyleWidgetDetails(child, theme, expanded, Math.max(0, width - 6), frame, projection))
2804
+ lines.push(` ${last ? " " : "│ "}${detail}`);
2805
+ for (const detail of materializedWidgetChildLines(child, theme, Math.max(0, width - 4), expanded, frame, projectionFor))
2806
+ lines.push(` ${detail}`);
2807
+ }
2808
+ if (shown.length < children.length)
2809
+ lines.push(` +${children.length - shown.length} more workflow children`);
2810
+ return lines;
2811
+ }
2812
+ function buildWidgetComponent(jobs, ui, initiallyCollapsed = false, layout) {
2813
+ return (tui, theme) => {
2814
+ const container = new Container();
2815
+ let cachedRenderWidth;
2816
+ let cachedFrame;
2817
+ let cachedExpanded;
2818
+ let cachedLines;
2819
+ let cachedCoverage = "[]";
2820
+ let collapsed = initiallyCollapsed;
2821
+ const invalidate = () => {
2822
+ cachedLines = undefined;
2823
+ resetWidgetLayoutSession();
2824
+ tui.requestRender();
2825
+ };
2826
+ const invalidateCoverage = () => {
2827
+ cachedLines = undefined;
2828
+ tui.requestRender();
2829
+ };
2830
+ asyncWidgetInvalidations.set(ui, invalidateCoverage);
2831
+ const update = (nextJobs) => {
2832
+ jobs = nextJobs;
2833
+ cachedLines = undefined;
2834
+ tui.requestRender();
2835
+ };
2836
+ asyncWidgetUpdates.set(ui, update);
2837
+ const component = Object.assign(container, {
2838
+ // Only the mouse fields used here, without requiring newer Pi type exports.
2839
+ handleMouse(event) {
2840
+ if (event.type !== "click" || event.button !== "left" || event.y !== 0)
2841
+ return undefined;
2842
+ if (event.shift || event.alt || event.ctrl)
2843
+ return undefined;
2844
+ collapsed = !collapsed;
2845
+ invalidate();
2846
+ return { handled: true };
2847
+ },
2848
+ dispose() {
2849
+ if (asyncWidgetUpdates.get(ui) === update)
2850
+ asyncWidgetUpdates.delete(ui);
2851
+ if (asyncWidgetInvalidations.get(ui) === invalidateCoverage)
2852
+ asyncWidgetInvalidations.delete(ui);
2853
+ },
2854
+ });
2855
+ container.render = (renderWidth) => {
2856
+ const now = Date.now();
2857
+ const frame = Math.floor(now / WIDGET_ANIMATION_INTERVAL_MS);
2858
+ trackSubagentsRound(ui, jobs, now);
2859
+ const expanded = ui.getToolsExpanded?.() ?? false;
2860
+ const coverage = inlineWorkflowCoverage.get(ui);
2861
+ const covered = new Set();
2862
+ if (coverage?.size) {
2863
+ const childrenByParent = new Map();
2864
+ for (const child of jobs) {
2865
+ if (!child.parentWorkflowRunId)
2866
+ continue;
2867
+ const children = childrenByParent.get(child.parentWorkflowRunId) ?? [];
2868
+ children.push(child);
2869
+ childrenByParent.set(child.parentWorkflowRunId, children);
2870
+ }
2871
+ for (const job of jobs) {
2872
+ const snapshot = coverage.get(job.asyncId);
2873
+ if (snapshot === undefined)
2874
+ continue;
2875
+ const children = childrenByParent.get(job.asyncId) ?? [];
2876
+ if (!children.some((child) => childrenByParent.has(child.asyncId))
2877
+ && snapshot === inlineWorkflowRenderKey(job, children))
2878
+ covered.add(job.asyncId);
2879
+ }
2880
+ }
2881
+ const coverageKey = JSON.stringify([...covered]);
2882
+ if (cachedLines && cachedRenderWidth === renderWidth && cachedFrame === frame && cachedExpanded === expanded && cachedCoverage === coverageKey)
2883
+ return cachedLines;
2884
+ if (cachedCoverage !== coverageKey)
2885
+ resetWidgetLayoutSession();
2886
+ cachedCoverage = coverageKey;
2887
+ const width = Math.max(0, renderWidth - 2);
2888
+ const { roots, projectionFor } = widgetJobTree(jobs, now);
2889
+ for (const job of roots)
2890
+ projectionFor(job).inlineFleetCovered = covered.has(job.asyncId);
2891
+ const buildLines = () => expanded
2892
+ ? buildWidgetLinesWithProjection(roots, theme, width, true, frame, projectionFor)
2893
+ : roots.length === 1 && !projectionFor(roots[0]).children?.length
2894
+ ? compactSingleWidgetLines(roots[0], theme, width, frame, projectionFor(roots[0]))
2895
+ : buildWidgetLinesWithProjection(roots, theme, width, false, frame, projectionFor);
2896
+ cachedRenderWidth = renderWidth;
2897
+ cachedFrame = frame;
2898
+ cachedExpanded = expanded;
2899
+ const elapsedSuffix = roundElapsedSuffix(ui, now);
2900
+ cachedLines = (collapsed
2901
+ ? buildSingleLineWidgetLines(jobs, theme, width, frame, elapsedSuffix)
2902
+ : fitAdaptiveWidgetLines(roots, buildLines, theme, width, expanded, frame, projectionFor, layout, elapsedSuffix)).map((line) => paddedWidgetLine(line, renderWidth));
2903
+ return cachedLines;
2904
+ };
2905
+ return component;
2906
+ };
2907
+ }
2908
+ function buildWidgetLinesWithProjection(jobs, theme, width = getTermWidth(), expanded = false, frame, projectionFor = workflowWidgetProjectionLookup()) {
2909
+ if (jobs.length === 0)
2910
+ return [];
2911
+ if (jobs.length === 1)
2912
+ return [
2913
+ ...buildSingleWidgetLines(jobs[0], theme, width, expanded, frame, projectionFor(jobs[0])),
2914
+ ...materializedWidgetChildLines(jobs[0], theme, width, expanded, frame, projectionFor).map((line) => truncLine(line, width)),
2915
+ ];
2916
+ const running = jobs.filter((job) => job.status === "running");
2917
+ const queued = jobs.filter((job) => job.status === "queued");
2918
+ const finished = jobs.filter((job) => job.status !== "running" && job.status !== "queued");
2919
+ const lines = [];
2920
+ const hasActive = running.length > 0 || queued.length > 0;
2921
+ const headerGlyph = running.length > 0 ? runningGlyph(animatedSeed(widgetJobsRunningSeed(running), frame)) : hasActive ? "●" : "○";
2922
+ const tone = activeHeaderTone(theme, hasActive);
2923
+ lines.push(truncLine(`${tone(headerGlyph)} ${tone("Async agents")} ${theme.fg("dim", "· background")}`, width));
2924
+ const items = [];
2925
+ let hiddenRunning = 0;
2926
+ let hiddenFinished = 0;
2927
+ let queuedSummaryShown = false;
2928
+ let slots = MAX_WIDGET_JOBS;
2929
+ const appendJob = (job) => {
2930
+ const projection = projectionFor(job);
2931
+ const compactWorkflow = (!expanded || projection.inlineFleetCovered) && job.mode === "workflow";
2932
+ const stats = compactWorkflow ? "" : widgetStats(job, theme, projection, !expanded);
2933
+ const details = compactWorkflow
2934
+ ? [
2935
+ ...compactWorkflowWidgetBodyLines(job, theme, frame, projection),
2936
+ ]
2937
+ : [
2938
+ ` ${theme.fg("dim", `⎿ ${widgetActivity(job)}`)}`,
2939
+ ...widgetLaneDetailLines(job, theme, projection),
2940
+ ...workflowChecklistWidgetLines(widgetChecklistWithoutMaterializedChildren(projection), theme, " ", expanded, frame, { includeItemErrors: !expanded || !job.steps?.length }),
2941
+ ...widgetParallelAgentDetails(job, theme, expanded, width, frame),
2942
+ ];
2943
+ items.push([
2944
+ compactWorkflow
2945
+ ? compactWorkflowHeaderLine(job, theme, width)
2946
+ : `${widgetStatusGlyph(job, theme, frame)} ${themeBold(theme, widgetJobName(job))}${contextModeBadge(theme, job.context)}${stats ? ` ${theme.fg("dim", "·")} ${stats}` : ""}`,
2947
+ ...details,
2948
+ ...materializedWidgetChildLines(job, theme, width, expanded, frame, projectionFor),
2949
+ ]);
2950
+ };
2951
+ for (const job of running) {
2952
+ if (slots <= 0) {
2953
+ hiddenRunning++;
2954
+ continue;
2955
+ }
2956
+ appendJob(job);
2957
+ slots--;
2958
+ }
2959
+ if (queued.length > 0 && slots > 0) {
2960
+ items.push([`${theme.fg("muted", "◦")} ${theme.fg("dim", `${queued.length} queued`)}`]);
2961
+ queuedSummaryShown = true;
2962
+ slots--;
2963
+ }
2964
+ for (const job of finished) {
2965
+ if (slots <= 0) {
2966
+ hiddenFinished++;
2967
+ continue;
2968
+ }
2969
+ appendJob(job);
2970
+ slots--;
2971
+ }
2972
+ const hiddenQueued = queued.length > 0 && !queuedSummaryShown ? queued.length : 0;
2973
+ const hiddenTotal = hiddenRunning + hiddenFinished + hiddenQueued;
2974
+ if (hiddenTotal > 0) {
2975
+ const parts = [];
2976
+ if (hiddenRunning > 0)
2977
+ parts.push(`${hiddenRunning} running`);
2978
+ if (hiddenQueued > 0)
2979
+ parts.push(`${hiddenQueued} queued`);
2980
+ if (hiddenFinished > 0)
2981
+ parts.push(`${hiddenFinished} finished`);
2982
+ items.push([theme.fg("dim", `+${hiddenTotal} more (${parts.join(", ")})`)]);
2983
+ }
2984
+ for (let i = 0; i < items.length; i++) {
2985
+ const item = items[i];
2986
+ const last = i === items.length - 1;
2987
+ const branch = last ? "└─" : "├─";
2988
+ const continuation = last ? " " : "│ ";
2989
+ lines.push(truncLine(`${theme.fg("dim", branch)} ${item[0]}`, width));
2990
+ for (const detail of item.slice(1)) {
2991
+ lines.push(truncLine(`${theme.fg("dim", continuation)} ${detail}`, width));
2992
+ }
2993
+ }
2994
+ return lines;
2995
+ }
2996
+ export function buildWidgetLines(jobs, theme, width = getTermWidth(), expanded = false, frame) {
2997
+ const { roots, projectionFor } = widgetJobTree(jobs, Date.now());
2998
+ return buildWidgetLinesWithProjection(roots, theme, width, expanded, frame, projectionFor);
2999
+ }
3000
+ /**
3001
+ * Render the async jobs widget
3002
+ */
3003
+ export function renderWidget(ctx, jobs, initiallyCollapsed = false, layout = "adaptive") {
3004
+ // Advance round tracking on every widget update, including the empty-jobs
3005
+ // cleanup path below, which never reaches container.render.
3006
+ trackSubagentsRound(ctx.ui, jobs, Date.now());
3007
+ if (jobs.length === 0) {
3008
+ resetWidgetLayoutSession();
3009
+ asyncWidgetUpdates.delete(ctx.ui);
3010
+ if (ctx.hasUI)
3011
+ ctx.ui.setWidget(WIDGET_KEY, undefined);
3012
+ return;
3013
+ }
3014
+ if (!ctx.hasUI)
3015
+ return;
3016
+ if (ctx.mode === "rpc") {
3017
+ ctx.ui.setWidget(WIDGET_KEY, encodeAsyncStatusSnapshotWidget(jobs));
3018
+ return;
3019
+ }
3020
+ // Pi replaces a widget by deleting and reinserting its key. Update the mounted
3021
+ // component instead so progress cannot move it past other extensions' widgets.
3022
+ const update = asyncWidgetUpdates.get(ctx.ui);
3023
+ if (update)
3024
+ update(jobs);
3025
+ else
3026
+ ctx.ui.setWidget(WIDGET_KEY, buildWidgetComponent(jobs, ctx.ui, initiallyCollapsed, layout));
3027
+ }
3028
+ function renderSingleCompact(d, r, theme, layout, frame, foregroundDetachShortcut) {
3029
+ const output = r.truncation?.text || getSingleResultOutput(r);
3030
+ const progress = r.progress || r.progressSummary;
3031
+ const isRunning = isResultRunning(r);
3032
+ const contextBadge = contextModeBadge(theme, r.context ?? d.context);
3033
+ const stats = statJoin(theme, [
3034
+ r.usage?.turns ? `⟳ ${r.usage.turns}` : "",
3035
+ formatProgressStats(theme, progress),
3036
+ ]);
3037
+ const c = new Container();
3038
+ const width = getTermWidth() - 4;
3039
+ const detailIndent = mainWindowIndent(layout, 1);
3040
+ const continuationIndent = mainWindowIndent(layout, 2) + (layout.horizontalSpacing > 0 ? " " : "");
3041
+ const modelDisplay = modelThinkingBadge(theme, r.progress?.model ?? r.model, r.thinking ?? r.progress?.thinking);
3042
+ c.addChild(new Text(truncLine(`${resultGlyph(r, output, theme, isRunning, undefined, frame)} ${theme.fg("toolTitle", theme.bold(foregroundSingleDisplayName(r)))}${modelDisplay}${contextBadge}${stats ? ` ${theme.fg("dim", "·")} ${stats}` : ""}`, width), 0, 0));
3043
+ if (isRunning && r.progress) {
3044
+ const task = compactTaskText(r.task);
3045
+ if (task)
3046
+ c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}task: ${task}`), width), 0, 0));
3047
+ const progressSnapshotNow = snapshotNowForProgress(r.progress);
3048
+ const activity = compactCurrentActivity(r.progress);
3049
+ c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}⎿ ${activity}`), width), 0, 0));
3050
+ const liveStatus = buildLiveStatusLine(r.progress, progressSnapshotNow);
3051
+ if (liveStatus && liveStatus !== activity)
3052
+ c.addChild(new Text(truncLine(theme.fg("dim", `${continuationIndent}${liveStatus}`), width), 0, 0));
3053
+ for (const nestedLine of formatNestedWidgetLines(r.children, theme, width, false, progressSnapshotNow)) {
3054
+ c.addChild(new Text(truncLine(`${detailIndent}${nestedLine}`, width), 0, 0));
3055
+ }
3056
+ c.addChild(new Text(truncLine(theme.fg("accent", `${detailIndent}${foregroundSingleHintText(foregroundDetachShortcut)}`), width), 0, 0));
3057
+ if (r.artifactPaths)
3058
+ c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}output: ${shortenPath(r.artifactPaths.outputPath)}`), width), 0, 0));
3059
+ return c;
3060
+ }
3061
+ for (const nestedLine of formatNestedWidgetLines(r.children, theme, width, false, r.progress?.lastActivityAt)) {
3062
+ c.addChild(new Text(truncLine(`${detailIndent}${nestedLine}`, width), 0, 0));
3063
+ }
3064
+ c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}⎿ ${resultStatusLine(r, output)}`), width), 0, 0));
3065
+ const preview = firstOutputLine(output);
3066
+ if (preview && r.exitCode === 0 && !hasEmptyTextOutputWithoutOutputTarget(r.task, output)) {
3067
+ c.addChild(new Text(truncLine(theme.fg("dim", `${continuationIndent}${preview}`), width), 0, 0));
3068
+ }
3069
+ if (r.sessionFile)
3070
+ c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}session: ${shortenPath(r.sessionFile)}`), width), 0, 0));
3071
+ if (r.artifactPaths)
3072
+ c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}output: ${shortenPath(r.artifactPaths.outputPath)}`), width), 0, 0));
3073
+ if (r.truncation?.artifactPath)
3074
+ c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}full output: ${shortenPath(r.truncation.artifactPath)}`), width), 0, 0));
3075
+ return c;
3076
+ }
3077
+ function workflowRowGlyph(row, theme, frame, thinking) {
3078
+ if (row.state === "planned")
3079
+ return theme.fg("muted", "◦");
3080
+ if (row.state === "running")
3081
+ return runningTone(theme, thinking)(runningGlyph(frame));
3082
+ if (row.state === "complete")
3083
+ return theme.fg("success", "✓");
3084
+ if (row.state === "detached" || row.state === "stopped")
3085
+ return theme.fg("warning", "■");
3086
+ return theme.fg("error", "✗");
3087
+ }
3088
+ function workflowRowStateLabel(row, theme, thinking) {
3089
+ const label = (row.state === "complete" ? "complete" : row.state).padEnd(8);
3090
+ if (row.state === "planned")
3091
+ return theme.fg("dim", label);
3092
+ if (row.state === "running")
3093
+ return runningTone(theme, thinking)(label);
3094
+ if (row.state === "complete")
3095
+ return theme.fg("success", label);
3096
+ if (row.state === "detached" || row.state === "stopped")
3097
+ return theme.fg("warning", label);
3098
+ return theme.fg("error", label);
3099
+ }
3100
+ function workflowOverallState(rows, hasTerminalValue, isError) {
3101
+ if (rows.some((row) => row.state === "failed"))
3102
+ return "failed";
3103
+ if (rows.some((row) => row.state === "detached"))
3104
+ return "paused";
3105
+ if (isError)
3106
+ return "failed";
3107
+ if ((rows.length > 0 && rows.every((row) => row.state === "complete")) || hasTerminalValue)
3108
+ return "complete";
3109
+ return "running";
3110
+ }
3111
+ function foregroundWorkflowChecklist(details) {
3112
+ if (details.mode !== "workflow")
3113
+ return undefined;
3114
+ const stageNodes = details.workflowGraph ? workflowGraphStageNodes(details.workflowGraph) : [];
3115
+ const steps = details.results.flatMap((result, resultIndex) => {
3116
+ const stableIndex = foregroundResultIndex(details, resultIndex);
3117
+ const workflowKey = result.workflowKey;
3118
+ if (details.workflowGraph && typeof workflowKey !== "string")
3119
+ return [];
3120
+ const node = typeof workflowKey === "string"
3121
+ ? stageNodes.find((candidate) => candidate.id === workflowKey)
3122
+ : undefined;
3123
+ const progress = foregroundProgressForResult(details, resultIndex);
3124
+ const status = isResultRunning(result) || progress?.status === "running"
3125
+ ? "running"
3126
+ : result.detached
3127
+ ? "paused"
3128
+ : result.stopped
3129
+ ? "stopped"
3130
+ : result.exitCode === 0
3131
+ ? "complete"
3132
+ : "failed";
3133
+ return [{
3134
+ key: node?.id ?? (typeof workflowKey === "string" ? workflowKey : `result-${resultIndex + 1}`),
3135
+ label: node?.label ?? workflowLabelForResult(details, resultIndex) ?? result.task ?? result.agent,
3136
+ phase: node?.phase,
3137
+ agent: result.agent,
3138
+ thinking: result.thinking ?? progress?.thinking,
3139
+ status,
3140
+ context: result.context,
3141
+ activityState: progress?.activityState,
3142
+ startedAt: progress?.lastActivityAt !== undefined && progress.durationMs !== undefined ? progress.lastActivityAt - progress.durationMs : undefined,
3143
+ durationMs: progress?.durationMs,
3144
+ currentTool: progress?.currentTool,
3145
+ currentToolStartedAt: progress?.currentToolStartedAt,
3146
+ currentPath: progress?.currentPath,
3147
+ turnCount: progress?.turnCount,
3148
+ toolCount: progress?.toolCount ?? result.progressSummary?.toolCount,
3149
+ error: result.error,
3150
+ toolBudgetBlocked: result.toolBudgetBlocked,
3151
+ turnBudgetExceeded: result.turnBudgetExceeded,
3152
+ timedOut: result.timedOut,
3153
+ stopped: result.stopped,
3154
+ acceptance: result.acceptance ? { status: result.acceptance.status, reviewResult: result.acceptance.reviewResult ? { status: result.acceptance.reviewResult.status } : undefined } : undefined,
3155
+ review: result.review ? { status: result.review.status } : undefined,
3156
+ watchdog: result.watchdog,
3157
+ }];
3158
+ });
3159
+ const checklist = projectWorkflowChecklist({
3160
+ graph: details.workflowGraph,
3161
+ steps,
3162
+ hostSteps: details.workflow?.receipt?.hostSteps,
3163
+ preflight: details.preflight,
3164
+ trace: details.workflow?.trace,
3165
+ now: Date.now(),
3166
+ });
3167
+ return checklist.total > 0 ? checklist : undefined;
3168
+ }
3169
+ function renderWorkflowChatProgress(d, result, theme, layout, frame, expanded = false) {
3170
+ const workflow = d.workflow;
3171
+ const rows = workflow ? buildWorkflowChatProgressRows(workflow.trace, d.preflight) : d.preflight ? buildWorkflowChatProgressRows([], d.preflight) : [];
3172
+ const state = workflowOverallState(rows, workflow?.value !== undefined, result.isError);
3173
+ const glyph = state === "running" ? runningTone(theme)(runningGlyph(frame)) : state === "complete" ? theme.fg("success", "✓") : state === "paused" ? theme.fg("warning", "■") : theme.fg("error", "✗");
3174
+ const width = getTermWidth() - 4;
3175
+ const runId = d.runId ? d.runId.slice(0, 12) : "workflow";
3176
+ const repoLabel = d.chatProgress?.repoLabel ?? (d.chatProgress?.repoRelation === "same" ? "same repo" : "other repo");
3177
+ const phase = rows.find((row) => row.state === "running" && row.phase)?.phase ?? [...rows].reverse().find((row) => row.phase)?.phase;
3178
+ const c = new Container();
3179
+ const rowIndent = mainWindowIndent(layout, 1);
3180
+ c.addChild(new Text(truncLine(`${glyph} ${theme.fg("toolTitle", theme.bold("workflow"))} ${runId} ${theme.fg("dim", "·")} ${d.chatProgress?.repoRelation === "same" ? "same repo" : "other repo"} ${theme.fg("dim", "·")} ${state}`, width), 0, 0));
3181
+ c.addChild(new Text(truncLine(theme.fg("dim", `${rowIndent}Repo ${repoLabel}`), width), 0, 0));
3182
+ if (d.preflight)
3183
+ c.addChild(new Text(truncLine(theme.fg("dim", formatWorkflowPreflightPlanSummary(d.preflight, { indent: rowIndent })), width), 0, 0));
3184
+ if (phase)
3185
+ c.addChild(new Text(truncLine(theme.fg("dim", `${rowIndent}Phase ${phase}`), width), 0, 0));
3186
+ const checklist = projectWorkflowChecklist({ hostSteps: workflow?.receipt?.hostSteps, preflight: d.preflight, trace: workflow?.trace, now: Date.now() });
3187
+ for (const line of workflowChecklistWidgetLines(checklist, theme, rowIndent, false, frame, { limitPhases: !expanded, includeBottleneckOutput: expanded })) {
3188
+ c.addChild(new Text(truncLine(line, width), 0, 0));
3189
+ }
3190
+ if (rows.length === 0) {
3191
+ c.addChild(new Text(truncLine(theme.fg("dim", `${rowIndent}◦ waiting for workflow child launches`), width), 0, 0));
3192
+ return c;
3193
+ }
3194
+ const visible = visibleWorkflowRows(rows);
3195
+ if (visible.hiddenRows > 0)
3196
+ c.addChild(new Text(truncLine(theme.fg("dim", `${rowIndent}… ${visible.hiddenRows} older workflow rows hidden`), width), 0, 0));
3197
+ const childLevels = new Map((d.workflowChildren?.children ?? []).map((child) => [child.childId, childThinkingLevel(child)]));
3198
+ for (const row of visible.rows) {
3199
+ const thinking = childLevels.get(row.key);
3200
+ const status = workflowRowStateLabel(row, theme, thinking);
3201
+ const label = row.label && row.label !== row.key ? ` ${oneLine(row.label)}` : "";
3202
+ const duration = row.durationMs !== undefined ? ` ${theme.fg("dim", `· ${formatDuration(row.durationMs)}`)}` : "";
3203
+ const run = row.runId ? ` ${theme.fg("dim", `[${row.runId.slice(0, 8)}]`)}` : "";
3204
+ const error = row.error ? ` ${theme.fg(row.state === "detached" ? "warning" : "error", `· ${compactWorkflowError(row.error)}`)}` : "";
3205
+ const hints = expanded && row.preflight ? [
3206
+ row.preflight.mode ? `mode:${row.preflight.mode}` : undefined,
3207
+ row.preflight.decision ? `decision:${row.preflight.decision}` : undefined,
3208
+ row.preflight.claims?.length ? `claims:${row.preflight.claims.join(",")}` : undefined,
3209
+ row.preflight.expectedOutput ? `expected:${row.preflight.expectedOutput}` : undefined,
3210
+ row.preflight.independence ? `independence:${row.preflight.independence}` : undefined,
3211
+ ].filter((value) => Boolean(value)).join(" · ") : "";
3212
+ c.addChild(new Text(truncLine(`${rowIndent}${workflowRowGlyph(row, theme, frame, thinking)} ${status} ${theme.bold(row.key)}${label}${run}${duration}${error}${hints ? ` ${theme.fg("dim", `· ${hints}`)}` : ""}`, width), 0, 0));
3213
+ }
3214
+ if (workflow?.preflightWarnings?.length) {
3215
+ const warningLines = expanded
3216
+ ? formatWorkflowPreflightWarnings(workflow.preflightWarnings, { indent: rowIndent }).split("\n")
3217
+ : [formatWorkflowPreflightWarningSummary(workflow.preflightWarnings, { indent: rowIndent, hint: "expand for debug" })];
3218
+ for (const warningLine of warningLines)
3219
+ c.addChild(new Text(truncLine(theme.fg("warning", warningLine), width), 0, 0));
3220
+ }
3221
+ if (workflow?.emits.length)
3222
+ c.addChild(new Text(truncLine(theme.fg("dim", `${rowIndent}Emits ${workflow.emits.length}`), width), 0, 0));
3223
+ return c;
3224
+ }
3225
+ function renderMultiCompact(d, theme, layout, frame) {
3226
+ const hasRunning = detailsHaveRunningResult(d);
3227
+ const detached = d.results.some((r) => r.detached)
3228
+ || workflowGraphHasStatus(d, ["detached"]);
3229
+ const stopped = d.results.some((r) => r.stopped)
3230
+ || workflowGraphHasStatus(d, ["stopped"]);
3231
+ const failed = d.results.some((r) => !hasTerminalResultFlag(r) && r.exitCode !== 0 && !isResultRunning(r))
3232
+ || workflowGraphHasStatus(d, ["failed"]);
3233
+ const paused = d.results.some((r) => r.interrupted)
3234
+ || workflowGraphHasStatus(d, ["paused"]);
3235
+ const partial = workflowGraphHasStatus(d, ["partial"]);
3236
+ let totalSummary = d.progressSummary;
3237
+ if (!totalSummary) {
3238
+ let sawProgress = false;
3239
+ const summary = { toolCount: 0, tokens: 0, durationMs: 0 };
3240
+ for (const r of d.results) {
3241
+ const prog = r.progress || r.progressSummary;
3242
+ if (!prog)
3243
+ continue;
3244
+ sawProgress = true;
3245
+ summary.toolCount += prog.toolCount;
3246
+ summary.tokens += prog.tokens;
3247
+ summary.durationMs = d.mode === "chain" ? summary.durationMs + prog.durationMs : Math.max(summary.durationMs, prog.durationMs);
3248
+ }
3249
+ if (sawProgress)
3250
+ totalSummary = summary;
3251
+ }
3252
+ const multiLabel = buildMultiProgressLabel(d, hasRunning);
3253
+ const itemTitle = multiLabel.itemTitle;
3254
+ const workflowChecklist = foregroundWorkflowChecklist(d);
3255
+ const checklistPrimary = d.mode === "workflow" && workflowChecklist !== undefined;
3256
+ const stats = statJoin(theme, [checklistPrimary ? formatWorkflowChecklistSummary(workflowChecklist) : multiLabel.headerLabel, formatProgressStats(theme, totalSummary), formatTotalCostStat(d.totalCost)]);
3257
+ const aggregatePresentation = semanticResultPresentation({
3258
+ running: hasRunning,
3259
+ detached,
3260
+ stopped,
3261
+ interrupted: paused,
3262
+ failed,
3263
+ partial,
3264
+ seed: runningSeed(progressRunningSeed(totalSummary), d.currentStepIndex),
3265
+ frame,
3266
+ });
3267
+ const glyph = presentationTone(aggregatePresentation, theme)(aggregatePresentation.glyph);
3268
+ const contextBadge = contextModeBadge(theme, d.context);
3269
+ const c = new Container();
3270
+ const width = getTermWidth() - 4;
3271
+ const rowIndent = mainWindowIndent(layout, 1);
3272
+ const detailIndent = mainWindowIndent(layout, 2);
3273
+ c.addChild(new Text(truncLine(`${glyph} ${theme.fg("toolTitle", theme.bold(d.mode))}${contextBadge}${stats ? ` ${theme.fg("dim", "·")} ${stats}` : ""}`, width), 0, 0));
3274
+ if (checklistPrimary) {
3275
+ for (const line of workflowChecklistWidgetLines(workflowChecklist, theme, rowIndent, false, frame, { includeSummary: false })) {
3276
+ c.addChild(new Text(truncLine(line, width), 0, 0));
3277
+ }
3278
+ if (hasRunning || workflowChecklist.running > 0)
3279
+ c.addChild(new Text(truncLine(theme.fg("accent", `${rowIndent}${liveDetailHintText()}`), width), 0, 0));
3280
+ return c;
3281
+ }
3282
+ for (const line of workflowChecklistWidgetLines(workflowChecklist, theme, rowIndent, false, frame)) {
3283
+ c.addChild(new Text(truncLine(line, width), 0, 0));
3284
+ }
3285
+ const useResultsDirectly = multiLabel.hasParallelInChain || !d.chainAgents?.length;
3286
+ const displayStart = multiLabel.showActiveGroupOnly ? multiLabel.groupStartIndex : 0;
3287
+ const displayEnd = multiLabel.showActiveGroupOnly ? multiLabel.groupEndIndex : (useResultsDirectly ? d.results.length : d.chainAgents.length);
3288
+ const chainEntries = buildChainRenderEntries(d, multiLabel);
3289
+ const renderEntries = chainEntries ?? buildForegroundResultEntries(d, multiLabel, displayStart, displayEnd, useResultsDirectly);
3290
+ for (const entry of renderEntries) {
3291
+ if (entry.kind === "group") {
3292
+ const glyph = widgetStepGlyph(entry.status, theme);
3293
+ const statusLabel = widgetStepStatus(entry.status, theme);
3294
+ const groupLabel = entry.groupLabel ? ` (${compactTaskText(undefined, entry.groupLabel) ?? entry.groupLabel})` : "";
3295
+ c.addChild(new Text(truncLine(`${rowIndent}${glyph} ${entry.stepLabel}${groupLabel} ${theme.fg("dim", "·")} ${statusLabel}`, width), 0, 0));
3296
+ if (entry.error)
3297
+ c.addChild(new Text(truncLine(theme.fg("error", `${detailIndent}⎿ Error: ${entry.error}`), width), 0, 0));
3298
+ continue;
3299
+ }
3300
+ const i = entry.resultIndex;
3301
+ const r = d.results[i];
3302
+ const rowNumber = entry.rowNumber;
3303
+ const agentName = entry.agentName;
3304
+ if (!r) {
3305
+ const pendingLabel = entry.rowLabel ?? (entry.isParallel ? "" : `${itemTitle} ${rowNumber}`);
3306
+ const labelPrefix = pendingLabel ? `${pendingLabel}: ` : "";
3307
+ c.addChild(new Text(truncLine(theme.fg("dim", `${rowIndent}◦ ${labelPrefix}${agentName} · pending`), width), 0, 0));
3308
+ continue;
3309
+ }
3310
+ const output = getSingleResultOutput(r);
3311
+ const progressFromArray = foregroundProgressForResult(d, i);
3312
+ const rProg = r.progress || progressFromArray || r.progressSummary;
3313
+ const rRunning = rProg && "status" in rProg && isResultRunning(r, rProg.status);
3314
+ const rPending = rProg && "status" in rProg && rProg.status === "pending";
3315
+ const stepStats = formatProgressStats(theme, rProg);
3316
+ const glyph = rPending ? theme.fg("dim", "◦") : resultGlyph(r, output, theme, rRunning, progressRunningSeed(rProg), frame);
3317
+ const pendingLabel = rPending ? ` ${theme.fg("dim", "· pending")}` : "";
3318
+ const stepLabel = entry.rowLabel;
3319
+ const rowProgressModel = rProg && "status" in rProg ? rProg : undefined;
3320
+ const rowModelDisplay = modelThinkingBadge(theme, rowProgressModel?.model ?? r.model, r.thinking ?? rowProgressModel?.thinking);
3321
+ const labelPrefix = stepLabel ? `${stepLabel}: ` : "";
3322
+ const line = `${glyph} ${labelPrefix}${themeBold(theme, agentName)}${contextModeBadge(theme, r.context)}${rowModelDisplay}${stepStats ? ` ${theme.fg("dim", "·")} ${stepStats}` : ""}${pendingLabel}`;
3323
+ c.addChild(new Text(truncLine(`${rowIndent}${line}`, width), 0, 0));
3324
+ if (rRunning || rPending) {
3325
+ const task = compactTaskText(r.task, workflowLabelForResult(d, i));
3326
+ if (task)
3327
+ c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}task: ${task}`), width), 0, 0));
3328
+ }
3329
+ if (rRunning && rProg && "status" in rProg) {
3330
+ const liveProgress = rProg;
3331
+ const activity = compactCurrentActivity(liveProgress);
3332
+ c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}⎿ ${activity}`), width), 0, 0));
3333
+ for (const nestedLine of formatNestedWidgetLines(r.children, theme, width, false, snapshotNowForProgress(liveProgress))) {
3334
+ c.addChild(new Text(truncLine(`${detailIndent}${nestedLine}`, width), 0, 0));
3335
+ }
3336
+ c.addChild(new Text(truncLine(theme.fg("accent", `${detailIndent}${liveDetailHintText()}`), width), 0, 0));
3337
+ }
3338
+ else if (!rPending && (r.exitCode !== 0 || r.interrupted || r.detached || hasEmptyTextOutputWithoutOutputTarget(r.task, output))) {
3339
+ c.addChild(new Text(truncLine(theme.fg(r.exitCode !== 0 ? "error" : "dim", `${detailIndent}⎿ ${resultStatusLine(r, output)}`), width), 0, 0));
3340
+ }
3341
+ if (!rRunning && !rPending) {
3342
+ for (const nestedLine of formatNestedWidgetLines(r.children, theme, width, false, r.progress?.lastActivityAt)) {
3343
+ c.addChild(new Text(truncLine(`${detailIndent}${nestedLine}`, width), 0, 0));
3344
+ }
3345
+ }
3346
+ const outputTarget = extractOutputTarget(r.task);
3347
+ if (outputTarget)
3348
+ c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}output: ${outputTarget}`), width), 0, 0));
3349
+ if (r.artifactPaths)
3350
+ c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}output: ${shortenPath(r.artifactPaths.outputPath)}`), width), 0, 0));
3351
+ }
3352
+ if (d.artifacts)
3353
+ c.addChild(new Text(truncLine(theme.fg("dim", `${rowIndent}artifacts: ${shortenPath(d.artifacts.dir)}`), width), 0, 0));
3354
+ return c;
3355
+ }
3356
+ export function renderSubagentSummary(result, options, theme) {
3357
+ const details = result.details;
3358
+ const results = details?.results ?? [];
3359
+ const hasSingleTerminalResult = results.length === 1 && hasTerminalResult(results[0]);
3360
+ const hasOnlyTerminalResults = results.length > 0 && results.every(hasTerminalResult);
3361
+ const running = !hasSingleTerminalResult && !hasOnlyTerminalResults && (options.isPartial === true
3362
+ || Boolean(details?.asyncId && details.mode !== "management")
3363
+ || Boolean(details && detailsHaveRunningResult(details)));
3364
+ const stopped = results.some((entry) => entry.stopped)
3365
+ || Boolean(details && workflowGraphHasStatus(details, ["stopped"]));
3366
+ const paused = results.some((entry) => entry.interrupted || entry.detached)
3367
+ || Boolean(details && workflowGraphHasStatus(details, ["paused", "detached"]));
3368
+ const failed = result.isError === true
3369
+ || results.some((entry) => !hasTerminalResultFlag(entry) && entry.exitCode !== 0 && !isResultRunning(entry))
3370
+ || Boolean(details && workflowGraphHasStatus(details, ["failed"]));
3371
+ const partial = Boolean(details && workflowGraphHasStatus(details, ["partial"]));
3372
+ const state = running ? "running" : failed ? "failed" : stopped ? "stopped" : paused ? "paused" : partial ? "partial" : "completed";
3373
+ const glyph = state === "running"
3374
+ ? runningTone(theme, details?.mode === "single" && results.length === 1 ? childThinkingLevel(results[0], results[0]?.progress) : undefined)(STATIC_RUNNING_GLYPH)
3375
+ : state === "completed"
3376
+ ? theme.fg("success", "✓")
3377
+ : state === "failed"
3378
+ ? theme.fg("error", "✗")
3379
+ : theme.fg("warning", "■");
3380
+ const label = details?.mode === "single" && results.length === 1
3381
+ ? foregroundSingleDisplayName(results[0])
3382
+ : details?.mode || "subagent";
3383
+ return new Text(truncLine(`${glyph} ${theme.fg("toolTitle", theme.bold(label))} ${theme.fg("dim", "·")} ${theme.fg(state === "failed" ? "error" : state === "completed" ? "success" : state === "running" ? "accent" : "warning", state)}`, getTermWidth() - 4), 0, 0);
3384
+ }
3385
+ /**
3386
+ * Render a subagent result
3387
+ */
3388
+ export function renderSubagentResult(result, options, theme, frame, rendererConfig, foregroundDetachShortcut) {
3389
+ const layout = resolveMainWindowRenderLayout(rendererConfig);
3390
+ const compact = (component) => capCompactMainWindowResult(component, layout, theme, !options.expanded);
3391
+ const d = result.details;
3392
+ if (d?.mode === "workflow" && d.chatProgress?.mode === "live-card" && d.workflow?.value === undefined && (!result.isError || (d.workflow?.trace.length ?? 0) > 0)) {
3393
+ return compact(renderWorkflowChatProgress(d, result, theme, options.expanded ? resolveMainWindowRenderLayout() : layout, frame, options.expanded));
3394
+ }
3395
+ if (!d || !d.results.length) {
3396
+ const t = result.content[0];
3397
+ const text = t?.type === "text" ? t.text : "(no output)";
3398
+ const contextPrefix = contextModePrefix(theme, d?.context);
3399
+ const width = getTermWidth() - 4;
3400
+ if (!text.includes("\n"))
3401
+ return compact(new Text(truncLine(`${contextPrefix}${text}`, width), 0, 0));
3402
+ if (d && !options.expanded && !result.isError) {
3403
+ const lines = text.split(/\r?\n/);
3404
+ const firstNonEmptyLine = lines.find((line) => line.trim())?.trim() || "(no output)";
3405
+ const compactLine = d.mode === "workflow" && d.preflight
3406
+ ? formatWorkflowPreflightPlanSummary(d.preflight)
3407
+ : firstNonEmptyLine;
3408
+ const c = new Container();
3409
+ const detailIndent = mainWindowIndent(layout, 1);
3410
+ c.addChild(new Text(truncLine(`${contextPrefix}${compactLine} · ${lines.length} lines`, width), 0, 0));
3411
+ c.addChild(new Text(truncLine(theme.fg("accent", `${detailIndent}${expandKeyHint("for full output")}`), width), 0, 0));
3412
+ return compact(c);
3413
+ }
3414
+ const c = new Container();
3415
+ const wrapped = wrapPlainText(`${contextPrefix}${text}`, width);
3416
+ for (const line of wrapped)
3417
+ c.addChild(new Text(line, 0, 0));
3418
+ return c;
3419
+ }
3420
+ const expanded = options.expanded;
3421
+ const mdTheme = getMarkdownTheme();
3422
+ if (d.mode === "single" && d.results.length === 1) {
3423
+ const r = d.results[0];
3424
+ const detachableShortcut = d.asyncId || d.background ? undefined : foregroundDetachShortcut;
3425
+ if (!r)
3426
+ return compact(renderMultiCompact(d, theme, layout, frame));
3427
+ if (!expanded)
3428
+ return compact(renderSingleCompact(d, r, theme, layout, frame, detachableShortcut));
3429
+ const isRunning = isResultRunning(r);
3430
+ const contextBadge = contextModeBadge(theme, r.context ?? d.context);
3431
+ const output = r.truncation?.text || getSingleResultOutput(r);
3432
+ const presentation = styledResultPresentation(resultPresentation(r, output, isRunning, undefined, frame), theme);
3433
+ const progressInfo = isRunning && r.progress
3434
+ ? ` | ${r.progress.toolCount} tools, ${formatTokens(r.progress.tokens)} tok, ${formatDuration(r.progress.durationMs)}`
3435
+ : r.progressSummary
3436
+ ? ` | ${r.progressSummary.toolCount} tools, ${formatTokens(r.progressSummary.tokens)} tok, ${formatDuration(r.progressSummary.durationMs)}`
3437
+ : "";
3438
+ const w = getTermWidth() - 4;
3439
+ const fit = (text) => expanded ? text : truncLine(text, w);
3440
+ const toolCallLines = getToolCallLines(r, expanded);
3441
+ const c = new Container();
3442
+ c.addChild(new Text(fit(`${presentation.glyph} ${theme.fg("toolTitle", theme.bold(foregroundSingleDisplayName(r)))}${contextBadge}${progressInfo} ${theme.fg("dim", "·")} ${presentation.label}`), 0, 0));
3443
+ c.addChild(new Spacer(1));
3444
+ const taskMaxLen = Math.max(20, w - 8);
3445
+ const taskPreview = expanded || r.task.length <= taskMaxLen
3446
+ ? r.task
3447
+ : `${r.task.slice(0, taskMaxLen)}...`;
3448
+ c.addChild(new Text(fit(theme.fg("dim", `Task: ${taskPreview}`)), 0, 0));
3449
+ c.addChild(new Spacer(1));
3450
+ if (!isRunning && (r.exitCode !== 0 || r.interrupted || r.detached || r.stopped)) {
3451
+ c.addChild(new Text(fit(theme.fg(r.exitCode !== 0 ? "error" : "dim", ` ⎿ ${resultStatusLine(r, output)}`)), 0, 0));
3452
+ }
3453
+ if (isRunning && r.progress) {
3454
+ const progressSnapshotNow = snapshotNowForProgress(r.progress);
3455
+ for (const nestedLine of formatNestedWidgetLines(r.children, theme, w, true, progressSnapshotNow, 12)) {
3456
+ c.addChild(new Text(fit(` ${nestedLine}`), 0, 0));
3457
+ }
3458
+ const toolLine = formatCurrentToolLine(r.progress, w, expanded, progressSnapshotNow);
3459
+ if (toolLine) {
3460
+ c.addChild(new Text(fit(theme.fg("warning", `> ${toolLine}`)), 0, 0));
3461
+ }
3462
+ const liveStatusLine = buildLiveStatusLine(r.progress, progressSnapshotNow);
3463
+ if (liveStatusLine) {
3464
+ c.addChild(new Text(fit(theme.fg("accent", liveStatusLine)), 0, 0));
3465
+ }
3466
+ c.addChild(new Text(fit(theme.fg("accent", foregroundSingleHintText(detachableShortcut))), 0, 0));
3467
+ if (r.artifactPaths) {
3468
+ c.addChild(new Text(fit(theme.fg("dim", `Artifacts: ${shortenPath(r.artifactPaths.outputPath)}`)), 0, 0));
3469
+ }
3470
+ if (r.progress.recentTools?.length) {
3471
+ for (const t of r.progress.recentTools.slice(-3)) {
3472
+ const maxArgsLen = Math.max(40, w - 24);
3473
+ const argsPreview = renderToolArgsPreview(t.args, maxArgsLen, expanded);
3474
+ c.addChild(new Text(fit(theme.fg("dim", `${t.tool}: ${argsPreview}`)), 0, 0));
3475
+ }
3476
+ }
3477
+ for (const line of compactRecentOutputLines(r.progress.recentOutput)) {
3478
+ c.addChild(new Text(fit(theme.fg("dim", ` ${line}`)), 0, 0));
3479
+ }
3480
+ if (toolLine || liveStatusLine || r.progress.recentTools?.length || r.progress.recentOutput?.length || r.artifactPaths) {
3481
+ c.addChild(new Spacer(1));
3482
+ }
3483
+ }
3484
+ else {
3485
+ for (const nestedLine of formatNestedWidgetLines(r.children, theme, w, true, r.progress?.lastActivityAt, 8)) {
3486
+ c.addChild(new Text(fit(` ${nestedLine}`), 0, 0));
3487
+ }
3488
+ }
3489
+ if (expanded) {
3490
+ for (const line of toolCallLines) {
3491
+ c.addChild(new Text(fit(theme.fg("muted", line)), 0, 0));
3492
+ }
3493
+ if (toolCallLines.length)
3494
+ c.addChild(new Spacer(1));
3495
+ }
3496
+ if (output)
3497
+ c.addChild(new Markdown(output, 0, 0, mdTheme));
3498
+ c.addChild(new Spacer(1));
3499
+ if (r.skills?.length) {
3500
+ c.addChild(new Text(fit(theme.fg("dim", `Skills: ${r.skills.join(", ")}`)), 0, 0));
3501
+ }
3502
+ if (r.skillsWarning) {
3503
+ c.addChild(new Text(fit(theme.fg("warning", `Warning: ${r.skillsWarning}`)), 0, 0));
3504
+ }
3505
+ c.addChild(new Text(fit(theme.fg("dim", formatUsage(r.usage, r.progress?.model ?? r.model))), 0, 0));
3506
+ if (r.sessionFile) {
3507
+ c.addChild(new Text(fit(theme.fg("dim", `Session: ${shortenPath(r.sessionFile)}`)), 0, 0));
3508
+ }
3509
+ if (!isRunning && r.artifactPaths) {
3510
+ c.addChild(new Spacer(1));
3511
+ c.addChild(new Text(fit(theme.fg("dim", `Artifacts: ${shortenPath(r.artifactPaths.outputPath)}`)), 0, 0));
3512
+ }
3513
+ return c;
3514
+ }
3515
+ if (!expanded)
3516
+ return compact(renderMultiCompact(d, theme, layout, frame));
3517
+ const hasRunning = detailsHaveRunningResult(d);
3518
+ const detached = d.results.some((r) => r.detached)
3519
+ || workflowGraphHasStatus(d, ["detached"]);
3520
+ const stopped = d.results.some((r) => r.stopped)
3521
+ || workflowGraphHasStatus(d, ["stopped"]);
3522
+ const failed = d.results.some((r) => !hasTerminalResultFlag(r) && r.exitCode !== 0 && !isResultRunning(r))
3523
+ || workflowGraphHasStatus(d, ["failed"]);
3524
+ const paused = d.results.some((r) => r.interrupted)
3525
+ || workflowGraphHasStatus(d, ["paused"]);
3526
+ const partial = workflowGraphHasStatus(d, ["partial"]);
3527
+ const completedWithoutOutput = d.results.some((r) => !hasTerminalResultFlag(r)
3528
+ && r.exitCode === 0
3529
+ && !isResultRunning(r)
3530
+ && hasEmptyTextOutputWithoutOutputTarget(r.task, getSingleResultOutput(r)));
3531
+ const presentation = styledResultPresentation(semanticResultPresentation({
3532
+ running: hasRunning,
3533
+ detached,
3534
+ stopped,
3535
+ interrupted: paused,
3536
+ failed,
3537
+ partial,
3538
+ completedWithoutOutput,
3539
+ frame,
3540
+ }), theme);
3541
+ const totalSummary = d.progressSummary ||
3542
+ d.results.reduce((acc, r) => {
3543
+ const prog = r.progress || r.progressSummary;
3544
+ if (prog) {
3545
+ acc.toolCount += prog.toolCount;
3546
+ acc.tokens += prog.tokens;
3547
+ acc.durationMs =
3548
+ d.mode === "chain"
3549
+ ? acc.durationMs + prog.durationMs
3550
+ : Math.max(acc.durationMs, prog.durationMs);
3551
+ }
3552
+ return acc;
3553
+ }, { toolCount: 0, tokens: 0, durationMs: 0 });
3554
+ const summaryParts = [
3555
+ totalSummary.toolCount || totalSummary.tokens
3556
+ ? `${totalSummary.toolCount} tools, ${formatTokens(totalSummary.tokens)} tok, ${formatDuration(totalSummary.durationMs)}`
3557
+ : "",
3558
+ formatTotalCostStat(d.totalCost),
3559
+ ].filter(Boolean);
3560
+ const summaryStr = summaryParts.length ? ` | ${summaryParts.join(", ")}` : "";
3561
+ const modeLabel = d.mode;
3562
+ const contextBadge = contextModeBadge(theme, d.context);
3563
+ const multiLabel = buildMultiProgressLabel(d, hasRunning);
3564
+ const itemTitle = multiLabel.itemTitle;
3565
+ const chainVis = d.chainAgents?.length && !multiLabel.hasParallelInChain
3566
+ ? d.chainAgents
3567
+ .map((agent, i) => {
3568
+ const result = d.results[i];
3569
+ const displayName = foregroundResultDisplayName(d, i, result, agent);
3570
+ const isCurrent = i === (d.currentStepIndex ?? d.results.length);
3571
+ const stepPresentation = result
3572
+ ? styledResultPresentation(resultPresentation(result, getSingleResultOutput(result), isCurrent && hasRunning && !hasTerminalResultFlag(result)), theme)
3573
+ : undefined;
3574
+ const stepStatus = stepPresentation
3575
+ ? `${stepPresentation.glyph} ${stepPresentation.label}`
3576
+ : theme.fg("dim", "◦ pending");
3577
+ return `${stepStatus} ${displayName}${contextModeBadge(theme, result?.context)}`;
3578
+ })
3579
+ .join(theme.fg("dim", " → "))
3580
+ : null;
3581
+ const w = getTermWidth() - 4;
3582
+ const fit = (text) => expanded ? text : truncLine(text, w);
3583
+ const c = new Container();
3584
+ c.addChild(new Text(fit(`${presentation.glyph} ${theme.fg("toolTitle", theme.bold(modeLabel))}${contextBadge} · ${multiLabel.headerLabel}${summaryStr} ${theme.fg("dim", "·")} ${presentation.label}`), 0, 0));
3585
+ if (chainVis) {
3586
+ c.addChild(new Text(fit(` ${chainVis}`), 0, 0));
3587
+ }
3588
+ const workflowChecklist = foregroundWorkflowChecklist(d);
3589
+ for (const line of workflowChecklistWidgetLines(workflowChecklist, theme, " ", true, frame, { includeItemErrors: false })) {
3590
+ c.addChild(new Text(fit(line), 0, 0));
3591
+ }
3592
+ const useResultsDirectly = multiLabel.hasParallelInChain || !d.chainAgents?.length;
3593
+ const displayStart = multiLabel.showActiveGroupOnly ? multiLabel.groupStartIndex : 0;
3594
+ const displayEnd = multiLabel.showActiveGroupOnly ? multiLabel.groupEndIndex : (useResultsDirectly ? d.results.length : d.chainAgents.length);
3595
+ const chainEntries = buildChainRenderEntries(d, multiLabel);
3596
+ const renderEntries = chainEntries ?? buildForegroundResultEntries(d, multiLabel, displayStart, displayEnd, useResultsDirectly);
3597
+ c.addChild(new Spacer(1));
3598
+ for (const entry of renderEntries) {
3599
+ if (entry.kind === "group") {
3600
+ const statusLabel = widgetStepStatus(entry.status, theme);
3601
+ const groupLabel = entry.groupLabel ? ` (${compactTaskText(undefined, entry.groupLabel) ?? entry.groupLabel})` : "";
3602
+ c.addChild(new Text(fit(` ${statusLabel} ${entry.stepLabel}${groupLabel}`), 0, 0));
3603
+ c.addChild(new Text(theme.fg(entry.status === "failed" ? "error" : "dim", ` status: ${entry.status}`), 0, 0));
3604
+ if (entry.error)
3605
+ c.addChild(new Text(theme.fg("error", ` error: ${entry.error}`), 0, 0));
3606
+ c.addChild(new Spacer(1));
3607
+ continue;
3608
+ }
3609
+ const i = entry.resultIndex;
3610
+ const r = d.results[i];
3611
+ const rowNumber = entry.rowNumber;
3612
+ const agentName = entry.agentName;
3613
+ if (!r) {
3614
+ const pendingLabel = entry.rowLabel ?? (entry.isParallel ? "" : `${itemTitle} ${rowNumber}`);
3615
+ const labelPrefix = pendingLabel ? `${pendingLabel}: ` : "";
3616
+ c.addChild(new Text(fit(theme.fg("dim", ` ${labelPrefix}${agentName}`)), 0, 0));
3617
+ c.addChild(new Text(theme.fg("dim", ` status: pending`), 0, 0));
3618
+ c.addChild(new Spacer(1));
3619
+ continue;
3620
+ }
3621
+ const progressFromArray = foregroundProgressForResult(d, i);
3622
+ const rProg = r.progress || progressFromArray || r.progressSummary;
3623
+ const rRunning = isResultRunning(r, rProg?.status);
3624
+ const resultOutput = getSingleResultOutput(r);
3625
+ const rowPresentation = styledResultPresentation(resultPresentation(r, resultOutput, rRunning, progressRunningSeed(rProg), frame), theme);
3626
+ const stats = rProg ? ` | ${rProg.toolCount} tools, ${formatDuration(rProg.durationMs)}` : "";
3627
+ const modelDisplay = modelThinkingBadge(theme, rProg?.model ?? r.model, r.thinking ?? rProg?.thinking);
3628
+ const stepLabel = entry.rowLabel;
3629
+ const contextBadge = contextModeBadge(theme, r.context);
3630
+ const labelPrefix = stepLabel ? `${stepLabel}: ` : "";
3631
+ const stepHeader = rRunning
3632
+ ? `${rowPresentation.glyph} ${labelPrefix}${theme.bold(theme.fg("warning", agentName))}${contextBadge}${modelDisplay}${stats} ${theme.fg("dim", "·")} ${rowPresentation.label}`
3633
+ : `${rowPresentation.glyph} ${labelPrefix}${theme.bold(agentName)}${contextBadge}${modelDisplay}${stats} ${theme.fg("dim", "·")} ${rowPresentation.label}`;
3634
+ const toolCallLines = getToolCallLines(r, expanded);
3635
+ c.addChild(new Text(fit(stepHeader), 0, 0));
3636
+ const taskMaxLen = Math.max(20, w - 12);
3637
+ const taskPreview = expanded || r.task.length <= taskMaxLen
3638
+ ? r.task
3639
+ : `${r.task.slice(0, taskMaxLen)}...`;
3640
+ c.addChild(new Text(fit(theme.fg("dim", ` task: ${taskPreview}`)), 0, 0));
3641
+ const outputTarget = extractOutputTarget(r.task);
3642
+ if (outputTarget) {
3643
+ c.addChild(new Text(fit(theme.fg("dim", ` output: ${outputTarget}`)), 0, 0));
3644
+ }
3645
+ if (!rRunning && (r.exitCode !== 0 || r.interrupted || r.detached || r.stopped)) {
3646
+ c.addChild(new Text(fit(theme.fg(r.exitCode !== 0 ? "error" : "dim", ` ⎿ ${resultStatusLine(r, resultOutput)}`)), 0, 0));
3647
+ }
3648
+ if (r.skills?.length) {
3649
+ c.addChild(new Text(fit(theme.fg("dim", ` skills: ${r.skills.join(", ")}`)), 0, 0));
3650
+ }
3651
+ if (r.skillsWarning) {
3652
+ c.addChild(new Text(fit(theme.fg("warning", ` Warning: ${r.skillsWarning}`)), 0, 0));
3653
+ }
3654
+ if (rRunning && rProg) {
3655
+ if (rProg.skills?.length) {
3656
+ c.addChild(new Text(fit(theme.fg("accent", ` skills: ${rProg.skills.join(", ")}`)), 0, 0));
3657
+ }
3658
+ const progressSnapshotNow = snapshotNowForProgress(rProg);
3659
+ const toolLine = formatCurrentToolLine(rProg, w, expanded, progressSnapshotNow);
3660
+ if (toolLine) {
3661
+ c.addChild(new Text(fit(theme.fg("warning", ` > ${toolLine}`)), 0, 0));
3662
+ }
3663
+ const liveStatusLine = buildLiveStatusLine(rProg, progressSnapshotNow);
3664
+ if (liveStatusLine) {
3665
+ c.addChild(new Text(fit(theme.fg("accent", ` ${liveStatusLine}`)), 0, 0));
3666
+ }
3667
+ for (const nestedLine of formatNestedWidgetLines(r.children, theme, w, true, progressSnapshotNow, 8)) {
3668
+ c.addChild(new Text(fit(` ${nestedLine}`), 0, 0));
3669
+ }
3670
+ c.addChild(new Text(fit(theme.fg("accent", ` ${liveDetailHintText()}`)), 0, 0));
3671
+ if (r.artifactPaths) {
3672
+ c.addChild(new Text(fit(theme.fg("dim", ` artifacts: ${shortenPath(r.artifactPaths.outputPath)}`)), 0, 0));
3673
+ }
3674
+ if (rProg.recentTools?.length) {
3675
+ for (const t of rProg.recentTools.slice(-3)) {
3676
+ const maxArgsLen = Math.max(40, w - 30);
3677
+ const argsPreview = renderToolArgsPreview(t.args, maxArgsLen, expanded);
3678
+ c.addChild(new Text(fit(theme.fg("dim", ` ${t.tool}: ${argsPreview}`)), 0, 0));
3679
+ }
3680
+ }
3681
+ for (const line of compactRecentOutputLines(rProg.recentOutput)) {
3682
+ c.addChild(new Text(fit(theme.fg("dim", ` ${line}`)), 0, 0));
3683
+ }
3684
+ }
3685
+ if (!rRunning) {
3686
+ for (const nestedLine of formatNestedWidgetLines(r.children, theme, w, true, r.progress?.lastActivityAt, 8)) {
3687
+ c.addChild(new Text(fit(` ${nestedLine}`), 0, 0));
3688
+ }
3689
+ }
3690
+ if (!rRunning && r.artifactPaths) {
3691
+ c.addChild(new Text(fit(theme.fg("dim", ` artifacts: ${shortenPath(r.artifactPaths.outputPath)}`)), 0, 0));
3692
+ }
3693
+ if (expanded && !rRunning) {
3694
+ for (const line of toolCallLines) {
3695
+ c.addChild(new Text(fit(theme.fg("muted", ` ${line}`)), 0, 0));
3696
+ }
3697
+ if (toolCallLines.length)
3698
+ c.addChild(new Spacer(1));
3699
+ }
3700
+ c.addChild(new Spacer(1));
3701
+ }
3702
+ if (d.artifacts) {
3703
+ c.addChild(new Spacer(1));
3704
+ c.addChild(new Text(fit(theme.fg("dim", `Artifacts dir: ${shortenPath(d.artifacts.dir)}`)), 0, 0));
3705
+ }
3706
+ return c;
3707
+ }