@draht/coding-agent 2026.10.4 → 2026.10.8-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +32 -6
  3. package/dist/bundle/chunks/{anthropic-messages-GAKYXF65.js → anthropic-messages-E2P6C3P7.js} +1 -1
  4. package/dist/bundle/chunks/anthropic.js +1 -1
  5. package/dist/bundle/chunks/{azure-openai-responses-ZIXMK6JO.js → azure-openai-responses-JZMSTDIM.js} +1 -1
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +20 -20
  7. package/dist/bundle/chunks/chunk-2JZLKNZ4.js +3 -0
  8. package/dist/bundle/chunks/chunk-5QJFWTKA.js +4 -0
  9. package/dist/bundle/chunks/{chunk-XKDTJ4YR.js → chunk-6QIFWMDF.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-5VZWYVZB.js → chunk-AHGUOQPH.js} +2 -2
  11. package/dist/bundle/chunks/{chunk-H6FT43VC.js → chunk-BOGY4QVF.js} +4 -4
  12. package/dist/bundle/chunks/{chunk-RZKPFWMH.js → chunk-D3HO453P.js} +2 -2
  13. package/dist/bundle/chunks/{chunk-KVH4HR57.js → chunk-FHX2S5IG.js} +1 -1
  14. package/dist/bundle/chunks/chunk-GBFVS2SF.js +12 -0
  15. package/dist/bundle/chunks/chunk-GD2WVXWT.js +65 -0
  16. package/dist/bundle/chunks/{chunk-Z2INEV2J.js → chunk-KJJJSTND.js} +307 -168
  17. package/dist/bundle/chunks/{chunk-BXSHCX3G.js → chunk-KY2BG6BC.js} +1 -1
  18. package/dist/bundle/chunks/chunk-LO6CVU2L.js +6 -0
  19. package/dist/bundle/chunks/chunk-PGJAHC3R.js +107 -0
  20. package/dist/bundle/chunks/chunk-QVFELZW2.js +312 -0
  21. package/dist/bundle/chunks/{chunk-COF5JT7R.js → chunk-QVTLBSTH.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-DPE4ALPU.js → chunk-U6LDZZGM.js} +10 -10
  23. package/dist/bundle/chunks/{chunk-D6TMD5Q2.js → chunk-UTRX2VHB.js} +8 -8
  24. package/dist/bundle/chunks/{chunk-LDAOC5RB.js → chunk-VQOV5VFH.js} +1 -1
  25. package/dist/bundle/chunks/chunk-VXUJMEMO.js +2 -0
  26. package/dist/bundle/chunks/{cli-SR5QBZH4.js → cli-O6OWCY7N.js} +1 -1
  27. package/dist/bundle/chunks/execute-4JU5WQXP.js +18 -0
  28. package/dist/bundle/chunks/google-antigravity.js +1 -1
  29. package/dist/bundle/chunks/google-gemini-cli.js +1 -1
  30. package/dist/bundle/chunks/{google-generative-ai-RPUPQ6PM.js → google-generative-ai-HPNDIAZD.js} +1 -1
  31. package/dist/bundle/chunks/{google-vertex-EZES5QVQ.js → google-vertex-KPAWJ4SP.js} +1 -1
  32. package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +13 -0
  33. package/dist/bundle/chunks/lib-ULKZYRGD.js +9 -0
  34. package/dist/bundle/chunks/{mistral-conversations-AOYGU43Y.js → mistral-conversations-FMSPWQ7A.js} +1 -1
  35. package/dist/bundle/chunks/{multipart-parser-AZP5BX2W.js → multipart-parser-HMCXZ4BD.js} +1 -1
  36. package/dist/bundle/chunks/{node-LQ52KV6B.js → node-4JNG6XQO.js} +1 -1
  37. package/dist/bundle/chunks/{node-C2JGH2OB.js → node-6IIDYB3K.js} +1 -1
  38. package/dist/bundle/chunks/openai-chatgpt.js +1 -1
  39. package/dist/bundle/chunks/{openai-codex-responses-M2Y77JEQ.js → openai-codex-responses-TU7NGPXE.js} +1 -1
  40. package/dist/bundle/chunks/openai-codex.js +1 -1
  41. package/dist/bundle/chunks/{openai-completions-A4OKYOYV.js → openai-completions-GANCQQO5.js} +1 -1
  42. package/dist/bundle/chunks/{openai-responses-6IXV53T3.js → openai-responses-ASDPAX3E.js} +1 -1
  43. package/dist/bundle/chunks/{openrouter-images-LYV4NKFM.js → openrouter-images-NROSQXMZ.js} +1 -1
  44. package/dist/bundle/chunks/openrouter.js +1 -1
  45. package/dist/bundle/chunks/{pi-messages-KKMEUT3Z.js → pi-messages-2QEJYOAO.js} +1 -1
  46. package/dist/bundle/chunks/radius.js +1 -1
  47. package/dist/bundle/chunks/{runtime-6YJPGSP7.js → runtime-FIGQHW75.js} +1 -1
  48. package/dist/bundle/chunks/runtime-TJ3EAMJK.js +3 -0
  49. package/dist/bundle/chunks/{settings-manager-D2EG7WDO.js → settings-manager-HC5RR36T.js} +1 -1
  50. package/dist/bundle/chunks/src-KDGO7EGF.js +4 -0
  51. package/dist/bundle/chunks/virtual-modules-UIGTRGHQ.js +2 -0
  52. package/dist/bundle/chunks/xai.js +1 -1
  53. package/dist/bundle/cli-runtime.js +1 -1
  54. package/dist/bundle/index.js +1 -1
  55. package/dist/bundle/rpc-entry.js +1 -1
  56. package/dist/cli/args.js +3 -3
  57. package/dist/cli/args.js.map +1 -1
  58. package/dist/core/builtins/duet.d.ts +5 -2
  59. package/dist/core/builtins/duet.d.ts.map +1 -1
  60. package/dist/core/builtins/duet.js +65 -27
  61. package/dist/core/builtins/duet.js.map +1 -1
  62. package/dist/core/builtins/index.d.ts.map +1 -1
  63. package/dist/core/builtins/index.js +2 -0
  64. package/dist/core/builtins/index.js.map +1 -1
  65. package/dist/core/builtins/polyphase.d.ts +15 -0
  66. package/dist/core/builtins/polyphase.d.ts.map +1 -0
  67. package/dist/core/builtins/polyphase.js +196 -0
  68. package/dist/core/builtins/polyphase.js.map +1 -0
  69. package/dist/core/builtins/subagent.d.ts +44 -34
  70. package/dist/core/builtins/subagent.d.ts.map +1 -1
  71. package/dist/core/builtins/subagent.js +827 -560
  72. package/dist/core/builtins/subagent.js.map +1 -1
  73. package/dist/core/extensions/types.d.ts +17 -2
  74. package/dist/core/extensions/types.d.ts.map +1 -1
  75. package/dist/core/extensions/types.js.map +1 -1
  76. package/dist/core/keybindings.d.ts +30 -0
  77. package/dist/core/keybindings.d.ts.map +1 -1
  78. package/dist/core/keybindings.js +24 -0
  79. package/dist/core/keybindings.js.map +1 -1
  80. package/dist/core/model-resolver.js +4 -4
  81. package/dist/core/model-resolver.js.map +1 -1
  82. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  83. package/dist/core/multi-agent/permission-gate.js +4 -1
  84. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  85. package/dist/core/polyphase/approval.d.ts +35 -0
  86. package/dist/core/polyphase/approval.d.ts.map +1 -0
  87. package/dist/core/polyphase/approval.js +184 -0
  88. package/dist/core/polyphase/approval.js.map +1 -0
  89. package/dist/core/polyphase/child-events.d.ts +107 -0
  90. package/dist/core/polyphase/child-events.d.ts.map +1 -0
  91. package/dist/core/polyphase/child-events.js +862 -0
  92. package/dist/core/polyphase/child-events.js.map +1 -0
  93. package/dist/core/polyphase/child-process.d.ts +65 -0
  94. package/dist/core/polyphase/child-process.d.ts.map +1 -0
  95. package/dist/core/polyphase/child-process.js +361 -0
  96. package/dist/core/polyphase/child-process.js.map +1 -0
  97. package/dist/core/polyphase/commands.d.ts +44 -0
  98. package/dist/core/polyphase/commands.d.ts.map +1 -0
  99. package/dist/core/polyphase/commands.js +244 -0
  100. package/dist/core/polyphase/commands.js.map +1 -0
  101. package/dist/core/polyphase/details.d.ts +40 -0
  102. package/dist/core/polyphase/details.d.ts.map +1 -0
  103. package/dist/core/polyphase/details.js +538 -0
  104. package/dist/core/polyphase/details.js.map +1 -0
  105. package/dist/core/polyphase/emitter.d.ts +20 -0
  106. package/dist/core/polyphase/emitter.d.ts.map +1 -0
  107. package/dist/core/polyphase/emitter.js +90 -0
  108. package/dist/core/polyphase/emitter.js.map +1 -0
  109. package/dist/core/polyphase/jsonl-reader.d.ts +31 -0
  110. package/dist/core/polyphase/jsonl-reader.d.ts.map +1 -0
  111. package/dist/core/polyphase/jsonl-reader.js +161 -0
  112. package/dist/core/polyphase/jsonl-reader.js.map +1 -0
  113. package/dist/core/polyphase/keyword.d.ts +27 -0
  114. package/dist/core/polyphase/keyword.d.ts.map +1 -0
  115. package/dist/core/polyphase/keyword.js +97 -0
  116. package/dist/core/polyphase/keyword.js.map +1 -0
  117. package/dist/core/polyphase/limiter.d.ts +38 -0
  118. package/dist/core/polyphase/limiter.d.ts.map +1 -0
  119. package/dist/core/polyphase/limiter.js +129 -0
  120. package/dist/core/polyphase/limiter.js.map +1 -0
  121. package/dist/core/polyphase/model-selection.d.ts +35 -0
  122. package/dist/core/polyphase/model-selection.d.ts.map +1 -0
  123. package/dist/core/polyphase/model-selection.js +72 -0
  124. package/dist/core/polyphase/model-selection.js.map +1 -0
  125. package/dist/core/polyphase/render/format.d.ts +52 -0
  126. package/dist/core/polyphase/render/format.d.ts.map +1 -0
  127. package/dist/core/polyphase/render/format.js +169 -0
  128. package/dist/core/polyphase/render/format.js.map +1 -0
  129. package/dist/core/polyphase/render/renderers.d.ts +63 -0
  130. package/dist/core/polyphase/render/renderers.d.ts.map +1 -0
  131. package/dist/core/polyphase/render/renderers.js +277 -0
  132. package/dist/core/polyphase/render/renderers.js.map +1 -0
  133. package/dist/core/polyphase/render/run-block.d.ts +45 -0
  134. package/dist/core/polyphase/render/run-block.d.ts.map +1 -0
  135. package/dist/core/polyphase/render/run-block.js +843 -0
  136. package/dist/core/polyphase/render/run-block.js.map +1 -0
  137. package/dist/core/polyphase/render/snapshot.d.ts +106 -0
  138. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -0
  139. package/dist/core/polyphase/render/snapshot.js +292 -0
  140. package/dist/core/polyphase/render/snapshot.js.map +1 -0
  141. package/dist/core/polyphase/result-text.d.ts +41 -0
  142. package/dist/core/polyphase/result-text.d.ts.map +1 -0
  143. package/dist/core/polyphase/result-text.js +326 -0
  144. package/dist/core/polyphase/result-text.js.map +1 -0
  145. package/dist/core/polyphase/session.d.ts +33 -0
  146. package/dist/core/polyphase/session.d.ts.map +1 -0
  147. package/dist/core/polyphase/session.js +106 -0
  148. package/dist/core/polyphase/session.js.map +1 -0
  149. package/dist/core/polyphase/settings.d.ts +18 -0
  150. package/dist/core/polyphase/settings.d.ts.map +1 -0
  151. package/dist/core/polyphase/settings.js +93 -0
  152. package/dist/core/polyphase/settings.js.map +1 -0
  153. package/dist/core/polyphase/store.d.ts +197 -0
  154. package/dist/core/polyphase/store.d.ts.map +1 -0
  155. package/dist/core/polyphase/store.js +558 -0
  156. package/dist/core/polyphase/store.js.map +1 -0
  157. package/dist/core/polyphase/types.d.ts +371 -0
  158. package/dist/core/polyphase/types.d.ts.map +1 -0
  159. package/dist/core/polyphase/types.js +36 -0
  160. package/dist/core/polyphase/types.js.map +1 -0
  161. package/dist/core/polyphase/ui/controller.d.ts +28 -0
  162. package/dist/core/polyphase/ui/controller.d.ts.map +1 -0
  163. package/dist/core/polyphase/ui/controller.js +150 -0
  164. package/dist/core/polyphase/ui/controller.js.map +1 -0
  165. package/dist/core/polyphase/ui/dock.d.ts +27 -0
  166. package/dist/core/polyphase/ui/dock.d.ts.map +1 -0
  167. package/dist/core/polyphase/ui/dock.js +121 -0
  168. package/dist/core/polyphase/ui/dock.js.map +1 -0
  169. package/dist/core/polyphase/ui/inspector.d.ts +117 -0
  170. package/dist/core/polyphase/ui/inspector.d.ts.map +1 -0
  171. package/dist/core/polyphase/ui/inspector.js +1016 -0
  172. package/dist/core/polyphase/ui/inspector.js.map +1 -0
  173. package/dist/core/polyphase/ui/transcript-layout.d.ts +55 -0
  174. package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -0
  175. package/dist/core/polyphase/ui/transcript-layout.js +210 -0
  176. package/dist/core/polyphase/ui/transcript-layout.js.map +1 -0
  177. package/dist/core/polyphase/update-pump.d.ts +18 -0
  178. package/dist/core/polyphase/update-pump.d.ts.map +1 -0
  179. package/dist/core/polyphase/update-pump.js +132 -0
  180. package/dist/core/polyphase/update-pump.js.map +1 -0
  181. package/dist/core/polyphase/workflow/agent-host.d.ts +26 -0
  182. package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -0
  183. package/dist/core/polyphase/workflow/agent-host.js +187 -0
  184. package/dist/core/polyphase/workflow/agent-host.js.map +1 -0
  185. package/dist/core/polyphase/workflow/guidance.d.ts +19 -0
  186. package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -0
  187. package/dist/core/polyphase/workflow/guidance.js +119 -0
  188. package/dist/core/polyphase/workflow/guidance.js.map +1 -0
  189. package/dist/core/polyphase/workflow/launch.d.ts +41 -0
  190. package/dist/core/polyphase/workflow/launch.d.ts.map +1 -0
  191. package/dist/core/polyphase/workflow/launch.js +173 -0
  192. package/dist/core/polyphase/workflow/launch.js.map +1 -0
  193. package/dist/core/polyphase/workflow/meta.d.ts +43 -0
  194. package/dist/core/polyphase/workflow/meta.d.ts.map +1 -0
  195. package/dist/core/polyphase/workflow/meta.js +529 -0
  196. package/dist/core/polyphase/workflow/meta.js.map +1 -0
  197. package/dist/core/polyphase/workflow/prelude.d.ts +24 -0
  198. package/dist/core/polyphase/workflow/prelude.d.ts.map +1 -0
  199. package/dist/core/polyphase/workflow/prelude.js +93 -0
  200. package/dist/core/polyphase/workflow/prelude.js.map +1 -0
  201. package/dist/core/polyphase/workflow/runtime.d.ts +79 -0
  202. package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -0
  203. package/dist/core/polyphase/workflow/runtime.js +217 -0
  204. package/dist/core/polyphase/workflow/runtime.js.map +1 -0
  205. package/dist/core/polyphase/workflow/runtime.lazy.d.ts +3 -0
  206. package/dist/core/polyphase/workflow/runtime.lazy.d.ts.map +1 -0
  207. package/dist/core/polyphase/workflow/runtime.lazy.js +3 -0
  208. package/dist/core/polyphase/workflow/runtime.lazy.js.map +1 -0
  209. package/dist/core/polyphase/workflow/saved.d.ts +55 -0
  210. package/dist/core/polyphase/workflow/saved.d.ts.map +1 -0
  211. package/dist/core/polyphase/workflow/saved.js +299 -0
  212. package/dist/core/polyphase/workflow/saved.js.map +1 -0
  213. package/dist/core/polyphase/workflow/structured-output.d.ts +22 -0
  214. package/dist/core/polyphase/workflow/structured-output.d.ts.map +1 -0
  215. package/dist/core/polyphase/workflow/structured-output.js +66 -0
  216. package/dist/core/polyphase/workflow/structured-output.js.map +1 -0
  217. package/dist/core/polyphase/workflow/tool.d.ts +24 -0
  218. package/dist/core/polyphase/workflow/tool.d.ts.map +1 -0
  219. package/dist/core/polyphase/workflow/tool.js +139 -0
  220. package/dist/core/polyphase/workflow/tool.js.map +1 -0
  221. package/dist/core/sdk.d.ts +1 -1
  222. package/dist/core/sdk.js +1 -1
  223. package/dist/core/sdk.js.map +1 -1
  224. package/dist/core/settings-manager.d.ts +27 -0
  225. package/dist/core/settings-manager.d.ts.map +1 -1
  226. package/dist/core/settings-manager.js.map +1 -1
  227. package/dist/core/socket-server/permission-relay.js +4 -0
  228. package/dist/core/socket-server/permission-relay.js.map +1 -1
  229. package/dist/core/trust-manager.d.ts +3 -2
  230. package/dist/core/trust-manager.d.ts.map +1 -1
  231. package/dist/core/trust-manager.js +5 -2
  232. package/dist/core/trust-manager.js.map +1 -1
  233. package/dist/experimental/micro/runtime.js +1 -1
  234. package/dist/experimental/micro/runtime.js.map +1 -1
  235. package/dist/modes/interactive/components/keybinding-hints.d.ts +7 -0
  236. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  237. package/dist/modes/interactive/components/keybinding-hints.js +18 -0
  238. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  239. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  240. package/dist/modes/interactive/interactive-mode.js +11 -2
  241. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  242. package/dist/modes/rpc/rpc-types.d.ts +9 -0
  243. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  244. package/dist/modes/rpc/rpc-types.js.map +1 -1
  245. package/dist/prompts/commands/orchestrate.md +1 -1
  246. package/dist/utils/shell.d.ts.map +1 -1
  247. package/dist/utils/shell.js +7 -1
  248. package/dist/utils/shell.js.map +1 -1
  249. package/docs/docs.json +4 -0
  250. package/docs/duet.md +3 -3
  251. package/docs/environment-variables.md +11 -0
  252. package/docs/json.md +7 -0
  253. package/docs/keybindings.md +20 -0
  254. package/docs/polyphase.md +391 -0
  255. package/docs/rpc-commands.md +9 -9
  256. package/docs/settings.md +12 -0
  257. package/docs/virtual-models.md +3 -3
  258. package/examples/extensions/preset.ts +3 -3
  259. package/examples/extensions/subagent/README.md +1 -1
  260. package/examples/extensions/subagent/agents/planner.md +1 -1
  261. package/examples/extensions/subagent/agents/reviewer.md +1 -1
  262. package/examples/extensions/subagent/agents/scout.md +1 -1
  263. package/examples/extensions/subagent/agents/worker.md +1 -1
  264. package/examples/extensions/summarize.ts +3 -3
  265. package/examples/sdk/02-custom-model.ts +1 -1
  266. package/examples/sdk/12-full-control.ts +1 -1
  267. package/examples/sdk/README.md +1 -1
  268. package/package.json +10 -10
  269. package/prompts/commands/orchestrate.md +1 -1
  270. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +0 -6
  271. package/dist/bundle/chunks/chunk-6ZJKIMU7.js +0 -2
  272. package/dist/bundle/chunks/chunk-736QBNUZ.js +0 -12
  273. package/dist/bundle/chunks/chunk-CEJJ5XF2.js +0 -170
  274. package/dist/bundle/chunks/chunk-IWTUBX6V.js +0 -4
  275. package/dist/bundle/chunks/chunk-TIA2T6EO.js +0 -3
  276. package/dist/bundle/chunks/execute-VCYDHEYA.js +0 -328
  277. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +0 -13
  278. package/dist/bundle/chunks/lib-XOG5PI3Y.js +0 -9
  279. package/dist/bundle/chunks/src-TIBHS42X.js +0 -4
  280. package/dist/bundle/chunks/virtual-modules-JTCGDL2Z.js +0 -2
  281. /package/dist/bundle/chunks/{chunk-ZZD35WKM.js → chunk-FBU742QF.js} +0 -0
  282. /package/dist/bundle/chunks/{chunk-SVNWI7EV.js → chunk-XHCO4PPH.js} +0 -0
@@ -0,0 +1,843 @@
1
+ /**
2
+ * Layout for one polyphase run's tool-row content (§11.3-11.4): `layoutRun` turns a `RunSnapshot`
3
+ * into fitted lines, and `PolyphaseRunBlock` is the `Component` `render/renderers.ts` reuses across
4
+ * re-renders of the same tool call. Every line goes through `fitLine` as the last step (§0 width
5
+ * safety); no timers live here (§11.2.5) — the animated frame comes from `options.now`.
6
+ */
7
+ import { visibleWidth } from "@draht/tui";
8
+ import { keyHint, keyText } from "../../../modes/interactive/components/keybinding-hints.js";
9
+ import { stripAnsi } from "../../../utils/ansi.js";
10
+ import { sanitizeBinaryOutput } from "../../../utils/shell.js";
11
+ import { normalizeDisplayText, replaceTabs } from "../../tools/render-utils.js";
12
+ import { columns, fitLine, formatCost, formatDuration, formatModelLabel, formatTokens, oneLine, spinnerFrame, statusGlyph, } from "./format.js";
13
+ const COUNT_ORDER = ["running", "done", "failed", "cancelled", "queued", "pending", "skipped"];
14
+ const STATUS_WORDS = {
15
+ pending: "pending",
16
+ queued: "queued",
17
+ starting: "starting",
18
+ running: "running",
19
+ done: "done",
20
+ failed: "failed",
21
+ cancelled: "cancelled",
22
+ skipped: "skipped",
23
+ };
24
+ const FINISHED_STATUSES = ["done", "failed", "cancelled", "skipped"];
25
+ function isFinished(status) {
26
+ return FINISHED_STATUSES.includes(status);
27
+ }
28
+ function firstLine(text) {
29
+ const idx = text.indexOf("\n");
30
+ return idx === -1 ? text : text.slice(0, idx);
31
+ }
32
+ /** Whether this row/run may show animated or live-only content: elapsed, live tokens/cost, the
33
+ * now column and the transcript tail (§11.2.2). False only for a non-focused partial row, which
34
+ * must render static content that changes only on an agent's status transition. */
35
+ function isLive(options) {
36
+ return options.focus || !options.partial;
37
+ }
38
+ function staticHintText() {
39
+ return `live view on the newest run · ${keyText("app.polyphase.inspector")}`;
40
+ }
41
+ /** Packs `left` and `right` onto one line with at least a two-space gap; falls back to a plain
42
+ * concatenation (later clipped by `fitLine`) when both together would not fit. */
43
+ function joinLeftRight(left, right, width) {
44
+ if (!right)
45
+ return left;
46
+ const leftWidth = visibleWidth(left);
47
+ const rightWidth = visibleWidth(right);
48
+ const minGap = 2;
49
+ if (leftWidth + minGap + rightWidth >= width)
50
+ return `${left} ${right}`;
51
+ return left + " ".repeat(width - leftWidth - rightWidth) + right;
52
+ }
53
+ function slotsBusySuffix(limiter, queued) {
54
+ if (!limiter || queued <= 0 || limiter.active < limiter.capacity)
55
+ return "";
56
+ return ` (${limiter.active}/${limiter.capacity} slots busy)`;
57
+ }
58
+ function rightSummaryParts(snapshot) {
59
+ const parts = [formatDuration(snapshot.elapsedMs)];
60
+ if (snapshot.budget) {
61
+ parts.push(`${formatTokens(snapshot.budget.spentTokens)}/${formatTokens(snapshot.budget.totalTokens)} tok`);
62
+ }
63
+ else if (snapshot.tokens > 0) {
64
+ parts.push(`${formatTokens(snapshot.tokens)} tok`);
65
+ }
66
+ const cost = formatCost(snapshot.cost);
67
+ if (cost)
68
+ parts.push(cost);
69
+ return parts;
70
+ }
71
+ /** Joins `left` and as many of `rightParts` (in order) as fit at `width`, dropping whole parts from
72
+ * the end rather than cutting one mid-token (§11.3's "drop parts from the right when space runs
73
+ * out"). */
74
+ function joinLeftRightParts(left, rightParts, width) {
75
+ for (let count = rightParts.length; count > 0; count--) {
76
+ const candidate = joinLeftRight(left, rightParts.slice(0, count).join(" · "), width);
77
+ if (visibleWidth(candidate) <= width)
78
+ return candidate;
79
+ }
80
+ return left;
81
+ }
82
+ function liveCountsLeft(snapshot, theme, options) {
83
+ const merged = {
84
+ ...snapshot.counts,
85
+ running: snapshot.counts.running + snapshot.counts.starting,
86
+ };
87
+ const pieces = [];
88
+ for (const status of COUNT_ORDER) {
89
+ const n = merged[status];
90
+ if (n <= 0)
91
+ continue;
92
+ const animate = options.focus && options.partial && status === "running";
93
+ pieces.push(`${statusGlyph(status, theme, { now: options.now, animate })} ${n} ${STATUS_WORDS[status]}`);
94
+ }
95
+ const left = pieces.length > 0
96
+ ? pieces.join(" · ")
97
+ : `${statusGlyph("running", theme, { now: options.now, animate: options.focus && options.partial })} 0 running`;
98
+ // The limiter reflects every run's slots, not just this one's, so the suffix must stay off
99
+ // static rows (§11.2.2): it can otherwise change a row with no status transition of its own.
100
+ return isLive(options) ? left + slotsBusySuffix(snapshot.limiter, merged.queued) : left;
101
+ }
102
+ /** "cancelled by you" only when every cancelled agent was cancelled by the user; otherwise the
103
+ * generic word, since a budget/parent/shutdown cancel was not the user's doing. */
104
+ function cancelledByText(agents) {
105
+ const cancelled = agents.filter((a) => a.status === "cancelled");
106
+ const byUser = cancelled.length > 0 && cancelled.every((a) => a.cancelReason === "user" || a.cancelReason === undefined);
107
+ return byUser ? "cancelled by you" : "cancelled";
108
+ }
109
+ /** A single agent's cancel wording: `cancelled by you` for the user, else `cancelled by <reason>`
110
+ * (budget/run/parent/shutdown), matching §11.4's mockup wording for the user case. */
111
+ function cancelReasonText(reason) {
112
+ if (!reason)
113
+ return "cancelled";
114
+ return reason === "user" ? "cancelled by you" : `cancelled by ${reason}`;
115
+ }
116
+ /** Child-sourced text (output, error, status/now lines, task, tool summaries, labels, log lines,
117
+ * result previews) may carry ANSI/OSC sequences, raw tabs or a trailing CR. Stripped and normalized
118
+ * before any width math runs, so `visibleWidth`/`fitLine` see exactly what the terminal will draw
119
+ * (§0 width safety): a bare tab would otherwise jump to the terminal's own 8-column stop regardless
120
+ * of the 3-column width this file assumes, and a CR would move the cursor back to column 0. */
121
+ export function sanitizeChildText(text) {
122
+ return normalizeDisplayText(replaceTabs(sanitizeBinaryOutput(stripAnsi(text))));
123
+ }
124
+ function sanitizeRow(row) {
125
+ return {
126
+ ...row,
127
+ label: sanitizeChildText(row.label),
128
+ task: sanitizeChildText(row.task),
129
+ now: row.now !== undefined ? sanitizeChildText(row.now) : row.now,
130
+ statusLine: row.statusLine !== undefined ? sanitizeChildText(row.statusLine) : row.statusLine,
131
+ output: row.output !== undefined ? sanitizeChildText(row.output) : row.output,
132
+ error: row.error !== undefined ? sanitizeChildText(row.error) : row.error,
133
+ blockedSample: row.blockedSample !== undefined ? sanitizeChildText(row.blockedSample) : row.blockedSample,
134
+ // The child reports `provider`/`id` in its own `message_start` event, and `modelText` falls
135
+ // back to the raw requested pattern before confirmation: both reach `formatModelLabel`
136
+ // unsanitized otherwise (§security, formatModelLabel probe).
137
+ provider: row.provider !== undefined ? sanitizeChildText(row.provider) : row.provider,
138
+ modelId: row.modelId !== undefined ? sanitizeChildText(row.modelId) : row.modelId,
139
+ modelText: row.modelText !== undefined ? sanitizeChildText(row.modelText) : row.modelText,
140
+ };
141
+ }
142
+ /** Applied once at the top of `layoutRun` (§0), so every downstream layout function works on
143
+ * already-clean text instead of each sanitizing its own slice of it. */
144
+ function sanitizePhase(phase) {
145
+ return {
146
+ ...phase,
147
+ title: sanitizeChildText(phase.title),
148
+ detail: phase.detail !== undefined ? sanitizeChildText(phase.detail) : undefined,
149
+ };
150
+ }
151
+ /** A workflow script controls its own `name`/`description`/`args` (`workflow/meta.ts`), so these
152
+ * are script-supplied strings exactly like phase titles. */
153
+ function sanitizeWorkflow(workflow) {
154
+ if (!workflow)
155
+ return workflow;
156
+ return {
157
+ ...workflow,
158
+ name: sanitizeChildText(workflow.name),
159
+ description: sanitizeChildText(workflow.description),
160
+ args: workflow.args !== undefined ? sanitizeChildText(workflow.args) : undefined,
161
+ };
162
+ }
163
+ /** Every child- or script-supplied string a `RunSnapshot` carries, sanitized once so every renderer
164
+ * that consumes the snapshot (this file's `layoutRun`, `ui/inspector.ts`) works on already-clean
165
+ * text instead of each re-implementing the same stripping. */
166
+ export function sanitizeSnapshot(snapshot) {
167
+ return {
168
+ ...snapshot,
169
+ title: sanitizeChildText(snapshot.title),
170
+ log: snapshot.log.map(sanitizeChildText),
171
+ resultPreview: snapshot.resultPreview !== undefined ? sanitizeChildText(snapshot.resultPreview) : undefined,
172
+ agents: snapshot.agents.map(sanitizeRow),
173
+ phases: snapshot.phases.map(sanitizePhase),
174
+ workflow: sanitizeWorkflow(snapshot.workflow),
175
+ error: snapshot.error !== undefined ? sanitizeChildText(snapshot.error) : undefined,
176
+ };
177
+ }
178
+ /** The fixed §11.4 mockup wording: a blocked tool's real gate reason (child-events.ts keeps it in
179
+ * full, `NO_UI_APPROVAL_SUFFIX` included) is never shown on the tool row, only in the inspector's
180
+ * expanded detail, so a long or sensitive rule description can never widen or leak onto this line. */
181
+ const BLOCKED_TOOL_TEXT = "blocked: needs approval (subagents cannot ask)";
182
+ /** The run's true agent count, including any dropped before this snapshot was built (a degraded
183
+ * archived/final `details` with `agentsOmitted` set). `snapshot.counts` already covers every agent
184
+ * (it is copied from `details.totals.byStatus`), so only `agents.length` on its own undercounts. */
185
+ function agentTotal(snapshot) {
186
+ return snapshot.agents.length + (snapshot.agentsOmitted?.count ?? 0);
187
+ }
188
+ /** Appended to a final/archived summary so a degraded snapshot never silently claims to be the
189
+ * whole run. Empty for a live or non-degraded snapshot. */
190
+ function agentsOmittedNote(snapshot) {
191
+ const omitted = snapshot.agentsOmitted?.count ?? 0;
192
+ return omitted > 0 ? ` (${omitted} agent${omitted === 1 ? "" : "s"} omitted)` : "";
193
+ }
194
+ function finalSummaryLeft(snapshot, theme) {
195
+ const total = agentTotal(snapshot);
196
+ const { done, failed, cancelled } = snapshot.counts;
197
+ const note = agentsOmittedNote(snapshot);
198
+ if (snapshot.status === "cancelled" && failed === 0) {
199
+ return `${statusGlyph("cancelled", theme, { now: 0, animate: false })} ${cancelledByText(snapshot.agents)} after ${total} agent${total === 1 ? "" : "s"}${note}`;
200
+ }
201
+ if (done === total) {
202
+ return `${statusGlyph("done", theme, { now: 0, animate: false })} ${done}/${total} succeeded${note}`;
203
+ }
204
+ const parts = [`${done} of ${total} succeeded`];
205
+ if (failed > 0)
206
+ parts.push(`${failed} failed`);
207
+ if (cancelled > 0)
208
+ parts.push(`${cancelled} cancelled`);
209
+ const glyph = failed > 0
210
+ ? statusGlyph("failed", theme, { now: 0, animate: false })
211
+ : statusGlyph("cancelled", theme, { now: 0, animate: false });
212
+ return `${glyph} ${parts.join(" · ")}${note}`;
213
+ }
214
+ function buildMultiSummaryLine(snapshot, theme, options, width) {
215
+ const left = snapshot.status === "running" ? liveCountsLeft(snapshot, theme, options) : finalSummaryLeft(snapshot, theme);
216
+ if (!isLive(options))
217
+ return joinLeftRight(left, theme.fg("muted", staticHintText()), width);
218
+ return joinLeftRightParts(left, rightSummaryParts(snapshot), width);
219
+ }
220
+ /** §11.3's `nowLine`-driven flex cell: the status word for a static row, else the live activity,
221
+ * final status line/error, or chain-specific "waits for step N" / "not run". */
222
+ function flexText(row, options, waitsForStep) {
223
+ if (!isLive(options))
224
+ return STATUS_WORDS[row.status];
225
+ switch (row.status) {
226
+ case "done":
227
+ return row.statusLine || (row.output ? firstLine(row.output) : "") || "done";
228
+ case "failed":
229
+ return row.error ? row.error : "failed";
230
+ case "cancelled":
231
+ return cancelReasonText(row.cancelReason);
232
+ case "queued":
233
+ return "queued";
234
+ case "pending":
235
+ return waitsForStep !== undefined ? `waits for step ${waitsForStep}` : "pending";
236
+ case "skipped":
237
+ return "not run";
238
+ default:
239
+ return row.now || "running";
240
+ }
241
+ }
242
+ /** label width = `clamp(longest label, 6, 16)`, taken across every row in the group being laid out
243
+ * (§11.3), so the model/elapsed columns line up across rows instead of each row sizing itself. */
244
+ function computeLabelWidth(agents) {
245
+ const longest = agents.reduce((max, agent) => Math.max(max, visibleWidth(agent.label)), 0);
246
+ return Math.min(16, Math.max(6, longest));
247
+ }
248
+ /** `formatModelLabel`, but a static row never shows `thinking`: it is set only once the child's
249
+ * `message_end` confirms it (child-events.ts §6.3), which is not a status transition, so a static
250
+ * row must not change shape when it lands (§11.2.2). */
251
+ function modelLabelFor(row, options, formatOptions) {
252
+ if (isLive(options))
253
+ return formatModelLabel(row, formatOptions);
254
+ return formatModelLabel({ ...row, thinking: undefined }, formatOptions);
255
+ }
256
+ function agentCollapsedLine(row, theme, options, width, extra) {
257
+ const animate = options.focus && options.partial && (row.status === "running" || row.status === "starting");
258
+ const glyph = statusGlyph(row.status, theme, { now: options.now, animate });
259
+ const labelWidth = extra?.labelWidth ?? computeLabelWidth([row]);
260
+ const cells = [
261
+ extra?.stepLabel ? { text: `${glyph} ${extra.stepLabel}`, width: 4 } : { text: glyph, width: 2 },
262
+ { text: row.label, width: labelWidth },
263
+ ];
264
+ if (width >= 60)
265
+ cells.push({ text: modelLabelFor(row, options, { withProvider: false }), width: 22 });
266
+ if (width >= 40) {
267
+ const elapsedText = isLive(options) && row.elapsedMs !== undefined ? formatDuration(row.elapsedMs) : "";
268
+ cells.push({ text: elapsedText, width: 5, align: "right" });
269
+ }
270
+ cells.push({ text: flexText(row, options, extra?.waitsForStep), width: "flex" });
271
+ return columns(cells, width, 1);
272
+ }
273
+ function toolsSummary(tools) {
274
+ if (!tools)
275
+ return "";
276
+ return Object.entries(tools)
277
+ .map(([name, count]) => `${name} ×${count}`)
278
+ .join(" · ");
279
+ }
280
+ /** `tools read ×6 · grep ×3[ · ⚠ k blocked (<sample>)]` (§11.3). The blocked annotation is shown
281
+ * whenever `row.blocked > 0`, even if the agent has no tool-call counts yet. */
282
+ function toolsLineText(row) {
283
+ const parts = [];
284
+ const toolsText = toolsSummary(row.tools);
285
+ if (toolsText)
286
+ parts.push(toolsText);
287
+ if (row.blocked > 0)
288
+ parts.push(`⚠ ${row.blocked} blocked${row.blockedSample ? ` (${row.blockedSample})` : ""}`);
289
+ return parts.join(" · ");
290
+ }
291
+ /** Up to 10 lines with a `│ ` gutter; beyond that, the first 3, an omission marker, and the last 6
292
+ * (§11.3's final-output rule). */
293
+ function outputBlockLines(text) {
294
+ const lines = text.split("\n");
295
+ if (lines.length <= 10)
296
+ return lines.map((line) => ` │ ${line}`);
297
+ const first = lines.slice(0, 3).map((line) => ` │ ${line}`);
298
+ const last = lines.slice(-6).map((line) => ` │ ${line}`);
299
+ return [...first, ` … ${lines.length - 9} lines omitted …`, ...last];
300
+ }
301
+ function tailItemLines(items, width) {
302
+ const lines = [];
303
+ for (const item of items) {
304
+ if (item.kind === "thinking" || item.kind === "text") {
305
+ const label = item.kind === "thinking" ? "thinking" : "writing";
306
+ const cursor = item.done ? "" : "▌";
307
+ lines.push(` ▸ ${label} ${oneLine(sanitizeChildText(item.text))}${cursor}`);
308
+ }
309
+ else if (item.kind === "tool") {
310
+ const name = sanitizeChildText(item.name);
311
+ const summary = sanitizeChildText(item.summary);
312
+ if (item.status === "blocked") {
313
+ lines.push(` ⚠ ${name} ${summary} ${BLOCKED_TOOL_TEXT}`);
314
+ }
315
+ else {
316
+ const glyphChar = item.status === "ok" ? "✓" : item.status === "error" ? "✗" : "◐";
317
+ const duration = item.startedAt !== undefined && item.endedAt !== undefined
318
+ ? `${((item.endedAt - item.startedAt) / 1000).toFixed(1)}s`
319
+ : "";
320
+ lines.push(joinLeftRight(` ${glyphChar} ${name} ${summary}`.trimEnd(), duration, width));
321
+ }
322
+ }
323
+ else if (item.kind === "notice") {
324
+ lines.push(` ! ${sanitizeChildText(item.text)}`);
325
+ }
326
+ }
327
+ return lines;
328
+ }
329
+ function agentExpandedBlock(row, theme, options, width, extra) {
330
+ const lines = [];
331
+ const animate = options.focus && options.partial && (row.status === "running" || row.status === "starting");
332
+ const glyph = statusGlyph(row.status, theme, { now: options.now, animate });
333
+ const headerParts = [row.label, modelLabelFor(row, options, { withProvider: true, withSource: true })];
334
+ const live = isLive(options);
335
+ if (live && row.elapsedMs !== undefined)
336
+ headerParts.push(formatDuration(row.elapsedMs));
337
+ if (live && row.turns > 0)
338
+ headerParts.push(`${row.turns} turn${row.turns === 1 ? "" : "s"}`);
339
+ if (live) {
340
+ const costText = formatCost(row.cost);
341
+ if (costText)
342
+ headerParts.push(costText);
343
+ }
344
+ if (live && row.status === "queued")
345
+ headerParts.push(STATUS_WORDS.queued);
346
+ const prefix = extra?.stepLabel ? `${extra.stepLabel} ` : "";
347
+ lines.push(`${glyph} ${prefix}${headerParts.filter(Boolean).join(" · ")}`);
348
+ if (row.status === "pending") {
349
+ lines.push(` ${flexText(row, options, extra?.waitsForStep)}`);
350
+ return lines;
351
+ }
352
+ lines.push(` task ${oneLine(row.task)}`);
353
+ const toolsLine = toolsLineText(row);
354
+ if (live && toolsLine)
355
+ lines.push(` tools ${toolsLine}`);
356
+ if (isFinished(row.status)) {
357
+ if (row.output) {
358
+ // A finished agent inside a still-running row shows one line (§11.4's "Parallel, partial,
359
+ // expanded" mockup); the full `│`-gutter output block is reserved for final rows, so a
360
+ // long-output agent cannot crowd out every other agent's row within the live budget.
361
+ if (options.partial) {
362
+ const text = row.statusLine || firstLine(row.output);
363
+ if (text)
364
+ lines.push(` out ${oneLine(text)}`);
365
+ }
366
+ else {
367
+ lines.push(...outputBlockLines(row.output));
368
+ }
369
+ }
370
+ if (row.error)
371
+ lines.push(` error ${firstLine(row.error)}`);
372
+ }
373
+ else if (live && row.tail && row.tail.length > 0) {
374
+ lines.push(...tailItemLines(row.tail.slice(-4), width));
375
+ }
376
+ return lines;
377
+ }
378
+ function overflowLine(remaining, done, queued) {
379
+ const parts = [`${done} done`];
380
+ if (queued > 0)
381
+ parts.push(`${queued} queued`);
382
+ return `… +${remaining} more (${parts.join(", ")}) · ${keyText("app.polyphase.inspector")} inspect`;
383
+ }
384
+ /** Folds `agentsOmitted` (agents dropped before the row even reached this layout, e.g. a degraded
385
+ * archived snapshot) into the agents omitted by the line budget, so the overflow count and its
386
+ * done/queued breakdown always reflect every agent the run actually has. */
387
+ function overflowLineFor(omitted, agentsOmitted) {
388
+ const remaining = omitted.length + (agentsOmitted?.count ?? 0);
389
+ if (remaining <= 0)
390
+ return undefined;
391
+ const done = omitted.filter((a) => a.status === "done").length + (agentsOmitted?.byStatus.done ?? 0);
392
+ const queued = omitted.filter((a) => a.status === "queued").length + (agentsOmitted?.byStatus.queued ?? 0);
393
+ return overflowLine(remaining, done, queued);
394
+ }
395
+ function hintLine(options) {
396
+ if (!isLive(options))
397
+ return keyHint("app.polyphase.inspector", "inspect agents");
398
+ const inspectHint = keyHint("app.polyphase.inspector", "inspect agents");
399
+ const expandHint = keyHint("app.tools.expand", options.expanded ? "collapse" : "expand");
400
+ return options.partial ? `${inspectHint} · ${expandHint}` : `${expandHint} · ${inspectHint}`;
401
+ }
402
+ /** Adds agent blocks/lines to `lines` while `lines.length` stays within `maxLines`, reserving one
403
+ * line for an overflow marker unless the last agent fits without it (§11.2.3, §20.4: expanded blocks
404
+ * must not grow the row past the viewport-derived cap). A block that cannot fit in the remaining
405
+ * budget is clipped (header first) rather than dropped outright, so the row never shows zero agents
406
+ * when the very first one is too big; every later agent that does not fit is left fully omitted.
407
+ * Returns the agents that did not fit (in full). */
408
+ function layoutAgentsBounded(agents, maxLines, renderRow) {
409
+ const budget = Math.max(1, maxLines);
410
+ const lines = [];
411
+ let shown = 0;
412
+ for (const row of agents) {
413
+ const block = renderRow(row);
414
+ const isLastAgent = shown + 1 === agents.length;
415
+ const cap = isLastAgent ? budget : budget - 1;
416
+ const remaining = cap - lines.length;
417
+ if (remaining <= 0) {
418
+ // No room left, not even for the reserved overflow line: if nothing has shown yet, use
419
+ // whatever budget remains for a clipped first block rather than show nothing at all.
420
+ if (shown === 0 && budget - lines.length > 0) {
421
+ lines.push(...block.slice(0, budget - lines.length));
422
+ shown++;
423
+ }
424
+ break;
425
+ }
426
+ if (block.length <= remaining) {
427
+ lines.push(...block);
428
+ shown++;
429
+ continue;
430
+ }
431
+ if (shown === 0) {
432
+ lines.push(...block.slice(0, remaining));
433
+ shown++;
434
+ }
435
+ break;
436
+ }
437
+ return { lines, omitted: agents.slice(shown) };
438
+ }
439
+ function layoutParallel(snapshot, theme, options, width) {
440
+ const lines = [buildMultiSummaryLine(snapshot, theme, options, width)];
441
+ const labelWidth = computeLabelWidth(snapshot.agents);
442
+ const { lines: agentLines, omitted } = layoutAgentsBounded(snapshot.agents, options.maxLines, (row) => options.expanded
443
+ ? agentExpandedBlock(row, theme, options, width, { labelWidth })
444
+ : [agentCollapsedLine(row, theme, options, width, { labelWidth })]);
445
+ lines.push(...agentLines);
446
+ const overflow = overflowLineFor(omitted, snapshot.agentsOmitted);
447
+ if (overflow)
448
+ lines.push(overflow);
449
+ return lines;
450
+ }
451
+ /** The chain's current step: the first agent still doing something (running/starting/queued), else
452
+ * the first agent waiting to start (pending). A queued or momentarily-pending current step must
453
+ * still count as "the" step, not fall through to `step N of N` (§11.3). */
454
+ function findRunningStep(snapshot) {
455
+ const active = snapshot.agents.find((a) => a.status === "running" || a.status === "starting" || a.status === "queued");
456
+ if (active)
457
+ return active.step ?? active.i + 1;
458
+ const pending = snapshot.agents.find((a) => a.status === "pending");
459
+ return pending ? (pending.step ?? pending.i + 1) : undefined;
460
+ }
461
+ function chainSummaryLine(snapshot, theme, options, width) {
462
+ const total = agentTotal(snapshot);
463
+ const note = agentsOmittedNote(snapshot);
464
+ if (snapshot.status !== "running") {
465
+ const broken = snapshot.agents.find((a) => a.status === "failed" || a.status === "cancelled");
466
+ const left = broken
467
+ ? `${statusGlyph(broken.status, theme, { now: 0, animate: false })} ${broken.status === "cancelled" ? "cancelled" : "failed"} at step ${broken.step ?? broken.i + 1} of ${total} (${broken.label})${note}`
468
+ : `${statusGlyph("done", theme, { now: 0, animate: false })} done · ${total} steps${note}`;
469
+ return joinLeftRightParts(left, rightSummaryParts(snapshot), width);
470
+ }
471
+ const runningStep = findRunningStep(snapshot) ?? total;
472
+ const animate = options.focus && options.partial;
473
+ const pieces = [`${statusGlyph("running", theme, { now: options.now, animate })} step ${runningStep} of ${total}`];
474
+ for (const status of COUNT_ORDER) {
475
+ if (status === "running")
476
+ continue;
477
+ const n = snapshot.counts[status];
478
+ if (n <= 0)
479
+ continue;
480
+ pieces.push(`${statusGlyph(status, theme, { now: options.now, animate: false })} ${n} ${STATUS_WORDS[status]}`);
481
+ }
482
+ const left = pieces.join(" · ");
483
+ if (!isLive(options))
484
+ return joinLeftRight(left, theme.fg("muted", staticHintText()), width);
485
+ return joinLeftRightParts(left, rightSummaryParts(snapshot), width);
486
+ }
487
+ function layoutChain(snapshot, theme, options, width) {
488
+ const lines = [chainSummaryLine(snapshot, theme, options, width)];
489
+ const waitsForStep = findRunningStep(snapshot);
490
+ const labelWidth = computeLabelWidth(snapshot.agents);
491
+ const { lines: agentLines, omitted } = layoutAgentsBounded(snapshot.agents, options.maxLines, (row) => {
492
+ const extra = { stepLabel: String(row.step ?? row.i + 1), waitsForStep, labelWidth };
493
+ return options.expanded
494
+ ? agentExpandedBlock(row, theme, options, width, extra)
495
+ : [agentCollapsedLine(row, theme, options, width, extra)];
496
+ });
497
+ lines.push(...agentLines);
498
+ const overflow = overflowLineFor(omitted, snapshot.agentsOmitted);
499
+ if (overflow)
500
+ lines.push(overflow);
501
+ return lines;
502
+ }
503
+ function layoutSingle(snapshot, theme, options, width) {
504
+ const row = snapshot.agents[0];
505
+ if (!row)
506
+ return [snapshot.title];
507
+ const live = isLive(options);
508
+ const animate = options.focus && options.partial && (row.status === "running" || row.status === "starting");
509
+ const leftParts = [
510
+ STATUS_WORDS[row.status],
511
+ modelLabelFor(row, options, { withProvider: options.expanded, withSource: options.expanded }),
512
+ ];
513
+ if (live && (options.expanded || isFinished(row.status)) && row.turns > 0) {
514
+ leftParts.push(`${row.turns} turn${row.turns === 1 ? "" : "s"}`);
515
+ }
516
+ const left = `${statusGlyph(row.status, theme, { now: options.now, animate })} ${leftParts.filter(Boolean).join(" · ")}`;
517
+ const rightParts = [];
518
+ if (live) {
519
+ if (row.elapsedMs !== undefined)
520
+ rightParts.push(formatDuration(row.elapsedMs));
521
+ if (row.tokens > 0)
522
+ rightParts.push(`${formatTokens(row.tokens)} tok`);
523
+ const costText = formatCost(row.cost);
524
+ if (costText)
525
+ rightParts.push(costText);
526
+ }
527
+ const lines = [joinLeftRightParts(left, rightParts, width)];
528
+ if (options.expanded) {
529
+ lines.push(` task ${oneLine(row.task)}`);
530
+ const toolsLine = toolsLineText(row);
531
+ if (live && toolsLine)
532
+ lines.push(` tools ${toolsLine}`);
533
+ if (isFinished(row.status)) {
534
+ if (row.output)
535
+ lines.push(...outputBlockLines(row.output));
536
+ if (row.error)
537
+ lines.push(` error ${firstLine(row.error)}`);
538
+ }
539
+ else if (live && row.tail && row.tail.length > 0) {
540
+ // §11.2.3: single mode's row budget covers this header too, so the tail must shrink on a
541
+ // short terminal instead of growing the row past `options.maxLines` unconditionally.
542
+ const tailBudget = Math.max(0, Math.min(8, options.maxLines - lines.length - 1));
543
+ if (tailBudget > 0)
544
+ lines.push(...tailItemLines(row.tail.slice(-tailBudget), width));
545
+ }
546
+ }
547
+ else if (isFinished(row.status)) {
548
+ const text = row.statusLine ?? (row.output ? firstLine(row.output) : undefined);
549
+ if (text)
550
+ lines.push(` ${text}`);
551
+ if (row.error)
552
+ lines.push(` error ${firstLine(row.error)}`);
553
+ }
554
+ else {
555
+ lines.push(` task ${oneLine(row.task)}`);
556
+ if (live && row.now)
557
+ lines.push(` now ${row.now}`);
558
+ }
559
+ return lines;
560
+ }
561
+ function phaseAgentStatus(status) {
562
+ return status;
563
+ }
564
+ /** §11.4's alternative final-summary lines, chosen by `snapshot.status`/`snapshot.budget` rather
565
+ * than by agent counts alone, so a script-error `failed` run and a user `cancelled` run never show
566
+ * the `done` glyph. */
567
+ function workflowFinalSummaryLeft(snapshot, theme) {
568
+ const total = agentTotal(snapshot);
569
+ const { done, failed, cancelled } = snapshot.counts;
570
+ const note = agentsOmittedNote(snapshot);
571
+ if (snapshot.budget?.exhausted) {
572
+ return `${theme.fg("warning", "⚠")} budget of ${formatTokens(snapshot.budget.totalTokens)} tokens reached · ${cancelled} agent${cancelled === 1 ? "" : "s"} cancelled${note}`;
573
+ }
574
+ if (snapshot.status === "cancelled") {
575
+ return `${statusGlyph("cancelled", theme, { now: 0, animate: false })} ${cancelledByText(snapshot.agents)} after ${total} agent${total === 1 ? "" : "s"}${note}`;
576
+ }
577
+ if (snapshot.status === "failed") {
578
+ const detail = snapshot.error ? oneLine(snapshot.error) : `${done} of ${total} succeeded · ${failed} failed`;
579
+ return `${statusGlyph("failed", theme, { now: 0, animate: false })} ${detail}${note}`;
580
+ }
581
+ return `${statusGlyph("done", theme, { now: 0, animate: false })} done · ${total} agents · ${done} ok${cancelled > 0 ? ` · ${cancelled} cancelled` : ""}${note}`;
582
+ }
583
+ function workflowSummaryLine(snapshot, theme, options, width) {
584
+ if (snapshot.status !== "running") {
585
+ return joinLeftRightParts(workflowFinalSummaryLeft(snapshot, theme), rightSummaryParts(snapshot), width);
586
+ }
587
+ const currentPhase = snapshot.currentPhase !== undefined ? snapshot.phases[snapshot.currentPhase] : undefined;
588
+ const animate = options.focus && options.partial;
589
+ // §11.4's mockup is the phase's position among every phase (`(2/3)`), not its own agent tally
590
+ // (which the phase line below already shows as `done/total`).
591
+ const phaseText = currentPhase
592
+ ? `${currentPhase.title} (${currentPhase.index + 1}/${snapshot.phases.length})`
593
+ : snapshot.title;
594
+ const pieces = [`${statusGlyph("running", theme, { now: options.now, animate })} ${phaseText}`];
595
+ const running = snapshot.counts.running + snapshot.counts.starting;
596
+ if (running > 0)
597
+ pieces.push(`${statusGlyph("running", theme, { now: options.now, animate: false })} ${running}`);
598
+ for (const status of COUNT_ORDER) {
599
+ if (status === "running")
600
+ continue;
601
+ const n = snapshot.counts[status];
602
+ if (n <= 0)
603
+ continue;
604
+ pieces.push(`${statusGlyph(status, theme, { now: options.now, animate: false })} ${n}`);
605
+ }
606
+ const left = pieces.join(" · ");
607
+ if (!isLive(options))
608
+ return joinLeftRight(left, theme.fg("muted", staticHintText()), width);
609
+ return joinLeftRightParts(left, rightSummaryParts(snapshot), width);
610
+ }
611
+ /** Final phase tally: `done/total ok[ · c cancelled (<labels>[, by you])]` (§11.4). Running phases
612
+ * keep the plain `done/total` form from the live counts. */
613
+ function phaseTotalsText(snapshot, phase, phaseAgents) {
614
+ if (snapshot.status === "running")
615
+ return `${phase.done}/${phase.total}`;
616
+ // `phase.done`/`phase.total` are computed only from the agents a degraded archived snapshot
617
+ // kept (snapshot.ts), so a partial tally must not read as the phase's complete result.
618
+ if (phase.incomplete)
619
+ return `${phase.done}/${phase.total}+`;
620
+ const cancelled = phaseAgents.filter((agent) => agent.status === "cancelled");
621
+ if (cancelled.length === 0)
622
+ return `${phase.done}/${phase.total} ok`;
623
+ const labels = cancelled.map((agent) => agent.label).join(", ");
624
+ const byYou = cancelled.every((agent) => agent.cancelReason === "user");
625
+ return `${phase.done}/${phase.total} ok · ${cancelled.length} cancelled (${labels}${byYou ? ", by you" : ""})`;
626
+ }
627
+ const COLLAPSED_ACTIVE_PHASE_AGENT_CAP = 6;
628
+ function phaseAgentsOf(snapshot, phase) {
629
+ return snapshot.agents.filter((agent) => agent.phase === phase.index);
630
+ }
631
+ function isActivePhase(snapshot, phase) {
632
+ return phase.status === "running" && snapshot.currentPhase === phase.index;
633
+ }
634
+ function phaseHeaderLine(snapshot, theme, options, width, phase, phaseAgents) {
635
+ const glyph = statusGlyph(phaseAgentStatus(phase.status), theme, {
636
+ now: options.now,
637
+ animate: options.focus && options.partial && phase.status === "running",
638
+ });
639
+ const left = `${glyph} ${phase.index + 1} ${phase.title} ${phaseTotalsText(snapshot, phase, phaseAgents)}`;
640
+ const elapsed = isLive(options) && phase.elapsedMs !== undefined ? formatDuration(phase.elapsedMs) : "";
641
+ return joinLeftRight(left, elapsed, width);
642
+ }
643
+ /** One phase's full block within `budget` lines total (header included): its header line, plus its
644
+ * agents (up to 6 collapsed, §11.3) when `showAgents` is true, with an overflow marker for whatever
645
+ * does not fit. Agents left out get folded exactly like `layoutAgentsBounded` elsewhere, so a single
646
+ * phase can never consume more than its share of the tree's budget. */
647
+ function phaseBlock(snapshot, theme, options, width, phase, phaseAgents, showAgents, budget) {
648
+ if (budget <= 0)
649
+ return [];
650
+ const header = phaseHeaderLine(snapshot, theme, options, width, phase, phaseAgents);
651
+ if (!showAgents || phaseAgents.length === 0)
652
+ return [header];
653
+ const capped = options.expanded ? phaseAgents : phaseAgents.slice(0, COLLAPSED_ACTIVE_PHASE_AGENT_CAP);
654
+ const cappedOverflow = options.expanded ? [] : phaseAgents.slice(COLLAPSED_ACTIVE_PHASE_AGENT_CAP);
655
+ const labelWidth = computeLabelWidth(capped);
656
+ const reserve = cappedOverflow.length > 0 ? 1 : 0;
657
+ const agentBudget = budget - 1 - reserve;
658
+ if (agentBudget <= 0) {
659
+ // No room for an agent line within budget: a forced minimum line here would push the block
660
+ // past budget (the overrun this guards against). Prefer the overflow marker over a clipped
661
+ // agent line whenever there is room for it; otherwise the header alone.
662
+ if (budget - 1 > 0) {
663
+ const overflow = overflowLineFor(phaseAgents, undefined);
664
+ if (overflow)
665
+ return [header, ` ${overflow}`];
666
+ }
667
+ return [header];
668
+ }
669
+ const { lines: agentLines, omitted } = layoutAgentsBounded(capped, agentBudget, (row) => (options.expanded
670
+ ? agentExpandedBlock(row, theme, options, Math.max(1, width - 4), { labelWidth })
671
+ : [agentCollapsedLine(row, theme, options, Math.max(1, width - 4), { labelWidth })]).map((line) => ` ${line}`));
672
+ const lines = [header, ...agentLines];
673
+ const overflow = overflowLineFor([...omitted, ...cappedOverflow], undefined);
674
+ if (overflow && lines.length < budget)
675
+ lines.push(` ${overflow}`);
676
+ return lines;
677
+ }
678
+ /** The plain top-to-bottom layout: every phase in order, each a `phaseBlock`, until `budget` runs
679
+ * out. `shownIndexes` lets the caller tell whether this covered the run's active phase;
680
+ * `lineCountByIndex` lets the caller tell whether that phase's block was clipped by the room left
681
+ * over from earlier phases rather than laid out at its full share. */
682
+ function layoutPhasesSequential(snapshot, theme, options, width, budget) {
683
+ const lines = [];
684
+ const shownIndexes = new Set();
685
+ const lineCountByIndex = new Map();
686
+ for (const phase of snapshot.phases) {
687
+ if (lines.length >= budget)
688
+ break;
689
+ const phaseAgents = phaseAgentsOf(snapshot, phase);
690
+ const showAgents = options.expanded || isActivePhase(snapshot, phase);
691
+ const block = phaseBlock(snapshot, theme, options, width, phase, phaseAgents, showAgents, budget - lines.length);
692
+ lines.push(...block);
693
+ shownIndexes.add(phase.index);
694
+ lineCountByIndex.set(phase.index, block.length);
695
+ }
696
+ return { lines, shownIndexes, lineCountByIndex };
697
+ }
698
+ /** Fallback for when the plain sequential layout would run out of budget before reaching the
699
+ * active phase (e.g. many phases, a late current phase): the active phase and its running agents
700
+ * are laid out first, so they are never silently dropped, and every other phase is folded into a
701
+ * single `+N phases` header-only marker once there is no more room (§11.3). */
702
+ function layoutPhasesActiveFirst(snapshot, theme, options, width, budget, activeIndex) {
703
+ const phases = snapshot.phases;
704
+ const activePhase = phases[activeIndex];
705
+ const activeBlock = phaseBlock(snapshot, theme, options, width, activePhase, phaseAgentsOf(snapshot, activePhase), true, budget);
706
+ const lines = [...activeBlock];
707
+ const otherIndexes = phases.map((_, index) => index).filter((index) => index !== activeIndex);
708
+ const remaining = Math.max(0, budget - lines.length);
709
+ const showCount = otherIndexes.length <= remaining ? otherIndexes.length : Math.max(0, remaining - 1);
710
+ for (let k = 0; k < showCount; k++) {
711
+ const phase = phases[otherIndexes[k]];
712
+ lines.push(phaseHeaderLine(snapshot, theme, options, width, phase, phaseAgentsOf(snapshot, phase)));
713
+ }
714
+ const omitted = otherIndexes.length - showCount;
715
+ if (omitted > 0)
716
+ lines.push(`… +${omitted} phase${omitted === 1 ? "" : "s"}`);
717
+ return lines;
718
+ }
719
+ /** Collapsed: only the active phase, up to 6 agents (§11.3). Expanded: every phase's every agent,
720
+ * bounded by `budget` (§11.4's "every phase with every agent row"). Either way, agents left out by
721
+ * the 6-agent cap or by the line budget get an overflow marker (§11.3's "when agents exceed the line
722
+ * cap" rule), indented under their phase, so live agents never silently disappear from the tree.
723
+ * When the plain top-to-bottom layout would run out of room before the active phase, it switches to
724
+ * `layoutPhasesActiveFirst` instead of letting that phase vanish. */
725
+ function workflowPhaseLines(snapshot, theme, options, width, budget) {
726
+ if (budget <= 0 || snapshot.phases.length === 0)
727
+ return [];
728
+ const sequential = layoutPhasesSequential(snapshot, theme, options, width, budget);
729
+ const activeIndex = snapshot.phases.findIndex((phase) => isActivePhase(snapshot, phase));
730
+ if (activeIndex === -1)
731
+ return sequential.lines;
732
+ const activePhase = snapshot.phases[activeIndex];
733
+ if (!sequential.shownIndexes.has(activePhase.index)) {
734
+ return layoutPhasesActiveFirst(snapshot, theme, options, width, budget, activeIndex);
735
+ }
736
+ // The sequential pass reached the active phase, but may have handed it only whatever budget
737
+ // earlier phases left over, clipping its header/agents/overflow marker below what it would get
738
+ // at its full share. Compare against that full-share block (computed with the whole budget, as
739
+ // `layoutPhasesActiveFirst` would give it) to tell "reached" apart from "fit".
740
+ const fullActiveBlock = phaseBlock(snapshot, theme, options, width, activePhase, phaseAgentsOf(snapshot, activePhase), true, budget);
741
+ const renderedActiveLines = sequential.lineCountByIndex.get(activePhase.index) ?? 0;
742
+ if (renderedActiveLines < fullActiveBlock.length) {
743
+ return layoutPhasesActiveFirst(snapshot, theme, options, width, budget, activeIndex);
744
+ }
745
+ return sequential.lines;
746
+ }
747
+ /** Agents started before the script's first `phase()` call (`run.resolvePhase(undefined)` leaves
748
+ * `agent.phase` unset), or whose recorded phase index fell out of `snapshot.phases` (a degraded
749
+ * archived snapshot), belong to no phase row and would otherwise never be shown. */
750
+ function unphasedAgents(snapshot) {
751
+ const validIndexes = new Set(snapshot.phases.map((phase) => phase.index));
752
+ return snapshot.agents.filter((agent) => agent.phase === undefined || !validIndexes.has(agent.phase));
753
+ }
754
+ function layoutWorkflow(snapshot, theme, options, width) {
755
+ const budget = Math.max(1, options.maxLines);
756
+ const lines = [];
757
+ const unphased = unphasedAgents(snapshot);
758
+ if (unphased.length > 0) {
759
+ const capped = options.expanded ? unphased : unphased.slice(0, COLLAPSED_ACTIVE_PHASE_AGENT_CAP);
760
+ const cappedOverflow = options.expanded ? [] : unphased.slice(COLLAPSED_ACTIVE_PHASE_AGENT_CAP);
761
+ const labelWidth = computeLabelWidth(capped);
762
+ const reserve = cappedOverflow.length > 0 ? 1 : 0;
763
+ const { lines: unphasedLines, omitted } = layoutAgentsBounded(capped, Math.max(1, budget - reserve), (row) => options.expanded
764
+ ? agentExpandedBlock(row, theme, options, width, { labelWidth })
765
+ : [agentCollapsedLine(row, theme, options, width, { labelWidth })]);
766
+ lines.push(...unphasedLines);
767
+ const overflow = overflowLineFor([...omitted, ...cappedOverflow], undefined);
768
+ if (overflow && lines.length < budget)
769
+ lines.push(overflow);
770
+ }
771
+ lines.push(...workflowPhaseLines(snapshot, theme, options, width, Math.max(0, budget - lines.length)));
772
+ if (options.partial && isLive(options) && lines.length < budget) {
773
+ if (options.expanded) {
774
+ const logLines = snapshot.log.slice(-5);
775
+ if (logLines.length > 0) {
776
+ lines.push(theme.fg("muted", "log"));
777
+ for (const line of logLines) {
778
+ if (lines.length >= budget)
779
+ break;
780
+ lines.push(`${theme.fg("muted", "»")} ${oneLine(line)}`);
781
+ }
782
+ }
783
+ }
784
+ else {
785
+ const lastLog = snapshot.log[snapshot.log.length - 1];
786
+ if (lastLog)
787
+ lines.push(`${theme.fg("muted", "»")} ${oneLine(lastLog)}`);
788
+ }
789
+ }
790
+ else if (!options.partial && snapshot.resultPreview && lines.length < budget) {
791
+ lines.push(`${theme.fg("accent", "→")} ${oneLine(snapshot.resultPreview)}`);
792
+ }
793
+ return [workflowSummaryLine(snapshot, theme, options, width), ...lines];
794
+ }
795
+ /** Everything after `renderCall`'s title line (§11.4): the summary, the agent rows or workflow
796
+ * phase tree, and the hint line, each fitted to `width`. */
797
+ export function layoutRun(snapshot, width, theme, options) {
798
+ const sanitized = sanitizeSnapshot(snapshot);
799
+ const body = sanitized.kind === "workflow"
800
+ ? layoutWorkflow(sanitized, theme, options, width)
801
+ : sanitized.mode === "single"
802
+ ? layoutSingle(sanitized, theme, options, width)
803
+ : sanitized.mode === "chain"
804
+ ? layoutChain(sanitized, theme, options, width)
805
+ : layoutParallel(sanitized, theme, options, width);
806
+ const lines = options.hints ? [...body, hintLine(options)] : body;
807
+ return lines.map((line) => fitLine(line, width));
808
+ }
809
+ function layoutOptionsKey(options) {
810
+ return `${options.expanded}|${options.partial}|${options.focus}|${options.maxLines}|${options.hints}`;
811
+ }
812
+ /** Reused across re-renders of the same tool call (`context.lastComponent`). Caches its lines by
813
+ * `(snapshot.version, width, options, spinner frame when focus && partial)` (§11.2.6). */
814
+ export class PolyphaseRunBlock {
815
+ snapshot;
816
+ theme;
817
+ options;
818
+ cacheKey;
819
+ cachedLines = [];
820
+ update(snapshot, theme, options) {
821
+ this.snapshot = snapshot;
822
+ this.theme = theme;
823
+ this.options = options;
824
+ }
825
+ render(width) {
826
+ if (!this.snapshot || !this.theme || !this.options)
827
+ return [];
828
+ const snapshot = this.snapshot;
829
+ const theme = this.theme;
830
+ const options = this.options;
831
+ const spinner = options.focus && options.partial ? spinnerFrame(options.now) : "";
832
+ const key = `${snapshot.version}|${width}|${layoutOptionsKey(options)}|${spinner}`;
833
+ if (key !== this.cacheKey) {
834
+ this.cacheKey = key;
835
+ this.cachedLines = layoutRun(snapshot, width, theme, options);
836
+ }
837
+ return this.cachedLines;
838
+ }
839
+ invalidate() {
840
+ this.cacheKey = undefined;
841
+ }
842
+ }
843
+ //# sourceMappingURL=run-block.js.map