@xzzpig/pi-subagents 0.22.0 → 0.24.0

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