@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
@@ -9,17 +9,25 @@
9
9
  * parallel — { tasks: [{ agent, task }] } (max 8, concurrency 4)
10
10
  * chain — { chain: [{ agent, task }] } (sequential, {previous} placeholder)
11
11
  */
12
- import { spawn } from "node:child_process";
13
12
  import { randomUUID } from "node:crypto";
14
13
  import * as fs from "node:fs";
15
- import * as os from "node:os";
16
14
  import * as path from "node:path";
17
- import { Text } from "@draht/tui";
18
15
  import { Type } from "@sinclair/typebox";
19
- import { CONFIG_DIR_NAME, getAgentDir, getPackageDir, isBunBinary } from "../../config.js";
16
+ import { CONFIG_DIR_NAME, getAgentDir, getPackageDir } from "../../config.js";
20
17
  import { comparablePath, realPathStrict } from "../../utils/canonical-path.js";
21
18
  import { parseFrontmatter } from "../../utils/frontmatter.js";
22
19
  import { AgentFSM, isPermissionMode, loadRules, MailboxSystem, PERMISSION_MODES, PermissionGate, parseRules, TaskBoard, WorktreeIsolator, } from "../multi-agent/index.js";
20
+ import { describeToolCallForApproval } from "../polyphase/approval.js";
21
+ import { createProcessAgentRunner } from "../polyphase/child-process.js";
22
+ import { buildDetails, sumRunUsage } from "../polyphase/details.js";
23
+ import { createPartialUpdateEmitter } from "../polyphase/emitter.js";
24
+ import { LimiterAbortedError } from "../polyphase/limiter.js";
25
+ import { resolveChildModel } from "../polyphase/model-selection.js";
26
+ import { createSubagentRenderers } from "../polyphase/render/renderers.js";
27
+ import { capHeadTail, formatSubagentResultText } from "../polyphase/result-text.js";
28
+ import { disposePolyphaseSession, getPolyphaseSession, peekPolyphaseSession } from "../polyphase/session.js";
29
+ import { resolvePolyphaseSettings } from "../polyphase/settings.js";
30
+ import { currentPolyphaseDepth, NO_UI_APPROVAL_SUFFIX, THINKING_LEVELS, WORKFLOW_TOOL_NAME, } from "../polyphase/types.js";
23
31
  import { boundedSafeText } from "../socket-server/safe-text.js";
24
32
  const MAX_PARALLEL = 8;
25
33
  const MAX_CONCURRENCY = 4;
@@ -47,11 +55,7 @@ export const multiAgentState = {
47
55
  board: taskBoard,
48
56
  worktree: worktreeIsolator,
49
57
  };
50
- // Build the command to spawn a subagent process.
51
- // Compiled Bun binary: process.execPath IS the CLI binary, args go directly.
52
- // Source/dev mode: process.execPath is the runtime (bun/node), process.argv[1] is the CLI script.
53
- const DRAHT_BIN = process.execPath;
54
- const DRAHT_ARGS_PREFIX = isBunBinary ? [] : [process.argv[1]];
58
+ // ─── Agent discovery ────────────────────────────────────────────────────────
55
59
  function loadAgentsFromDir(dir, source) {
56
60
  if (!fs.existsSync(dir))
57
61
  return [];
@@ -126,176 +130,9 @@ export function discoverAgents(cwd, scope, projectTrusted) {
126
130
  map.set(a.name, a);
127
131
  return Array.from(map.values());
128
132
  }
129
- function writeTemp(name, content) {
130
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "draht-subagent-"));
131
- const file = path.join(dir, `${name.replace(/[^\w.-]/g, "_")}.md`);
132
- fs.writeFileSync(file, content, { encoding: "utf-8", mode: 0o600 });
133
- return { file, dir };
134
- }
135
- function cleanTemp(file, dir) {
136
- try {
137
- fs.unlinkSync(file);
138
- }
139
- catch { }
140
- try {
141
- fs.rmdirSync(dir);
142
- }
143
- catch { }
144
- }
145
- function getFinalAssistant(messages) {
146
- for (let index = messages.length - 1; index >= 0; index--) {
147
- const message = messages[index];
148
- if (message.role === "assistant")
149
- return message;
150
- }
151
- return undefined;
152
- }
153
- function getFinalText(messages) {
154
- for (let i = messages.length - 1; i >= 0; i--) {
155
- const msg = messages[i];
156
- if (msg.role === "assistant") {
157
- for (const part of msg.content) {
158
- if (part.type === "text")
159
- return part.text;
160
- }
161
- }
162
- }
163
- return "";
164
- }
165
- function getCombinedUsage(messages) {
166
- const usages = messages
167
- .filter((message) => message.role === "assistant")
168
- .map((message) => message.usage)
169
- .filter((usage) => usage !== undefined);
170
- if (usages.length === 0)
171
- return undefined;
172
- return usages.reduce((total, usage) => ({
173
- input: total.input + usage.input,
174
- output: total.output + usage.output,
175
- cacheRead: total.cacheRead + usage.cacheRead,
176
- cacheWrite: total.cacheWrite + usage.cacheWrite,
177
- ...(total.cacheWrite1h !== undefined || usage.cacheWrite1h !== undefined
178
- ? { cacheWrite1h: (total.cacheWrite1h ?? 0) + (usage.cacheWrite1h ?? 0) }
179
- : {}),
180
- ...(total.reasoning !== undefined || usage.reasoning !== undefined
181
- ? { reasoning: (total.reasoning ?? 0) + (usage.reasoning ?? 0) }
182
- : {}),
183
- totalTokens: total.totalTokens + usage.totalTokens,
184
- cost: {
185
- input: total.cost.input + usage.cost.input,
186
- output: total.cost.output + usage.cost.output,
187
- cacheRead: total.cost.cacheRead + usage.cost.cacheRead,
188
- cacheWrite: total.cost.cacheWrite + usage.cost.cacheWrite,
189
- total: total.cost.total + usage.cost.total,
190
- },
191
- }));
192
- }
193
- async function runAgent(cwd, agent, task, signal, step, onProgress) {
194
- const args = ["--mode", "json", "-p", "--no-session"];
195
- if (agent.model)
196
- args.push("--model", agent.model);
197
- if (agent.tools?.length)
198
- args.push("--tools", agent.tools.join(","));
199
- if (agent.disableExtensions)
200
- args.push("--no-extensions");
201
- let tmpFile = null;
202
- let tmpDir = null;
203
- if (agent.systemPrompt.trim()) {
204
- const tmp = writeTemp(agent.name, agent.systemPrompt);
205
- tmpFile = tmp.file;
206
- tmpDir = tmp.dir;
207
- args.push("--append-system-prompt", tmpFile);
208
- }
209
- const messages = [];
210
- let stderr = "";
211
- try {
212
- const processExitCode = await new Promise((resolve) => {
213
- let closed = false;
214
- const proc = spawn(DRAHT_BIN, [...DRAHT_ARGS_PREFIX, ...args], {
215
- cwd,
216
- shell: false,
217
- stdio: ["pipe", "pipe", "pipe"],
218
- });
219
- proc.stdin.on("error", () => { });
220
- proc.stdin.end(`Task: ${task}`);
221
- let buf = "";
222
- const processLine = (line) => {
223
- if (!line.trim())
224
- return;
225
- try {
226
- const event = JSON.parse(line);
227
- if ((event.type === "message_end" || event.type === "tool_result_end") && event.message) {
228
- messages.push(event.message);
229
- }
230
- // Stream activity updates to the parent
231
- if (onProgress) {
232
- if (event.type === "tool_execution_start") {
233
- const toolArgs = event.args ?? {};
234
- const detail = toolArgs.command || toolArgs.path || toolArgs.file_path || toolArgs.pattern || "";
235
- const short = typeof detail === "string" && detail.length > 60 ? `${detail.slice(0, 60)}...` : detail;
236
- onProgress(short ? `${event.toolName} ${short}` : event.toolName);
237
- }
238
- else if (event.type === "text_delta") {
239
- // Show first line of streaming text as activity
240
- const text = event.text?.trim();
241
- if (text) {
242
- const firstLine = text.split("\n")[0];
243
- const short = firstLine.length > 80 ? `${firstLine.slice(0, 80)}...` : firstLine;
244
- onProgress(short);
245
- }
246
- }
247
- }
248
- }
249
- catch { }
250
- };
251
- proc.stdout.on("data", (d) => {
252
- buf += d.toString();
253
- const lines = buf.split("\n");
254
- buf = lines.pop() || "";
255
- for (const l of lines)
256
- processLine(l);
257
- });
258
- proc.stderr.on("data", (d) => {
259
- stderr += d.toString();
260
- });
261
- proc.on("close", (code) => {
262
- closed = true;
263
- if (buf.trim())
264
- processLine(buf);
265
- resolve(code ?? 1);
266
- });
267
- proc.on("error", () => resolve(1));
268
- if (signal) {
269
- const kill = () => {
270
- proc.kill("SIGTERM");
271
- setTimeout(() => {
272
- if (!closed)
273
- proc.kill("SIGKILL");
274
- }, 5000).unref();
275
- };
276
- if (signal.aborted)
277
- kill();
278
- else
279
- signal.addEventListener("abort", kill, { once: true });
280
- }
281
- });
282
- const finalAssistant = getFinalAssistant(messages);
283
- const failedResponse = finalAssistant?.stopReason === "error" || finalAssistant?.stopReason === "aborted";
284
- return {
285
- agent: agent.name,
286
- task,
287
- exitCode: processExitCode === 0 && !failedResponse ? 0 : 1,
288
- output: getFinalText(messages),
289
- stderr: stderr || (failedResponse ? (finalAssistant.errorMessage ?? finalAssistant.stopReason) : ""),
290
- usage: getCombinedUsage(messages),
291
- step,
292
- };
293
- }
294
- finally {
295
- if (tmpFile && tmpDir)
296
- cleanTemp(tmpFile, tmpDir);
297
- }
298
- }
133
+ // ─── Runner ─────────────────────────────────────────────────────────────────
134
+ const defaultRunner = createProcessAgentRunner();
135
+ /** Converts an item's own exception into a failed `RunResult` so one bad item never aborts the rest. */
299
136
  async function runParallel(items, concurrency, fn) {
300
137
  const results = new Array(items.length);
301
138
  let next = 0;
@@ -304,36 +141,131 @@ async function runParallel(items, concurrency, fn) {
304
141
  const i = next++;
305
142
  if (i >= items.length)
306
143
  return;
307
- results[i] = await fn(items[i], i);
144
+ try {
145
+ results[i] = await fn(items[i], i);
146
+ }
147
+ catch (error) {
148
+ results[i] = {
149
+ agent: items[i].agent.name,
150
+ task: items[i].task,
151
+ exitCode: 1,
152
+ output: "",
153
+ stderr: error instanceof Error ? error.message : String(error),
154
+ };
155
+ }
308
156
  }
309
157
  }));
310
158
  return results;
311
159
  }
160
+ // ─── Multi-agent orchestration ─────────────────────────────────────────────
161
+ //
162
+ // Wraps the process runner (`defaultRunner`, or a pluggable `AgentRunner` for tests) with the
163
+ // multi-agent coordination primitives: an AgentFSM tracks each run's
164
+ // IDLE→REQUEST→WORKING→RESPOND→IDLE lifecycle, a mailbox delivers the run's
165
+ // TaskResult (or Abort on failure) to an interested recipient, and worktree
166
+ // isolation is applied opt-in per run. Parallel mode additionally posts each
167
+ // task to the shared TaskBoard so agents "self-assign" work; chain mode
168
+ // relays `{previous}` between steps via a per-chain mailbox instead of a bare
169
+ // local variable.
170
+ /** `{agent, task, exitCode: 1, output: "", stderr: "cancelled", cancelled: true, step}` (§10.1). */
171
+ function cancelledResult(agentName, task, step) {
172
+ return { agent: agentName, task, exitCode: 1, output: "", stderr: "cancelled", cancelled: true, step };
173
+ }
312
174
  /**
313
- * Runs one agent task through the full multi-agent lifecycle: FSM
314
- * transitions around the run, opt-in worktree isolation, and a mailbox
315
- * message on completion. This is the single point every orchestration mode
316
- * (single/parallel/chain) below funnels through.
175
+ * Runs one agent task through the full multi-agent lifecycle: a pre-abort check, an optional
176
+ * limiter lease, FSM transitions around the run, opt-in worktree isolation, and a mailbox message
177
+ * on completion. This is the single point every orchestration mode (single/parallel/chain) below
178
+ * funnels through.
179
+ *
180
+ * A signal already aborted before (or while queued for) a limiter slot short-circuits to a
181
+ * cancelled result without running the FSM or spawning — but `run.onFinish` still fires, since
182
+ * `LiveAgent.createRunContext()` depends on it to leave "queued"/"pending" and settle.
317
183
  */
318
184
  async function runAgentWithLifecycle(cwd, agent, task, opts) {
319
- const { agentId, resultMailbox = SUBAGENT_RESULT_MAILBOX, worktree, taskId = agentId, runner = runAgent } = opts;
185
+ const { agentId, resultMailbox = SUBAGENT_RESULT_MAILBOX, worktree, taskId = agentId, runner = defaultRunner, limiter, run, } = opts;
186
+ if (opts.signal?.aborted) {
187
+ const result = cancelledResult(agent.name, task, opts.step);
188
+ run?.onFinish?.(result);
189
+ return result;
190
+ }
191
+ let lease;
192
+ if (limiter) {
193
+ try {
194
+ lease = await limiter.acquire({ signal: opts.signal, onQueued: run?.onQueued });
195
+ }
196
+ catch (error) {
197
+ // Any acquire rejection — aborted-while-queued or e.g. `limiter.rejectAll()` on session
198
+ // teardown — must resolve to a RunResult and fire `onFinish` exactly once rather than
199
+ // escape as a rejection, since callers (and `LiveAgent`) depend on both.
200
+ const result = error instanceof LimiterAbortedError
201
+ ? cancelledResult(agent.name, task, opts.step)
202
+ : {
203
+ agent: agent.name,
204
+ task,
205
+ exitCode: 1,
206
+ output: "",
207
+ stderr: error instanceof Error ? error.message : String(error),
208
+ step: opts.step,
209
+ };
210
+ run?.onFinish?.(result);
211
+ return result;
212
+ }
213
+ }
320
214
  const fsm = new AgentFSM(agentId);
321
215
  const forward = (event) => {
322
- for (const listener of fsmTransitionListeners)
323
- listener(event);
216
+ for (const listener of fsmTransitionListeners) {
217
+ try {
218
+ listener(event);
219
+ }
220
+ catch {
221
+ // A throwing observer must not skip the lease release or mailbox cleanup below.
222
+ }
223
+ }
324
224
  };
325
225
  fsm.onTransition(forward);
326
226
  mailboxSystem.register(agentId);
327
227
  fsm.transition("REQUEST");
328
228
  fsm.transition("WORKING");
329
- const effectiveCwd = worktree ? worktreeIsolator.create(cwd, taskId) : cwd;
330
- const result = await runner(effectiveCwd, agent, task, opts.signal, opts.step, opts.onProgress);
331
- // effectiveCwd === cwd means create() fell back to cwd outside a git repo,
332
- // where merge(taskId) would fabricate a failure for the unknown taskId.
333
- if (worktree && effectiveCwd !== cwd) {
334
- if (result.exitCode === 0)
335
- result.merge = worktreeIsolator.merge(taskId);
336
- worktreeIsolator.cleanup(taskId);
229
+ let effectiveCwd = cwd;
230
+ let usedWorktree = false;
231
+ let result;
232
+ try {
233
+ if (opts.signal?.aborted) {
234
+ result = cancelledResult(agent.name, task, opts.step);
235
+ }
236
+ else {
237
+ if (worktree) {
238
+ effectiveCwd = worktreeIsolator.create(cwd, taskId);
239
+ // effectiveCwd === cwd means create() fell back to cwd outside a git repo, where
240
+ // merge(taskId)/cleanup(taskId) would fabricate a failure for the unknown taskId.
241
+ usedWorktree = effectiveCwd !== cwd;
242
+ }
243
+ result = await runner(effectiveCwd, agent, task, opts.signal, opts.step, opts.onProgress, run);
244
+ if (usedWorktree && result.exitCode === 0) {
245
+ result.merge = worktreeIsolator.merge(taskId);
246
+ }
247
+ }
248
+ }
249
+ catch (error) {
250
+ result = {
251
+ agent: agent.name,
252
+ task,
253
+ exitCode: 1,
254
+ output: "",
255
+ stderr: error instanceof Error ? error.message : String(error),
256
+ step: opts.step,
257
+ };
258
+ }
259
+ finally {
260
+ if (usedWorktree) {
261
+ try {
262
+ worktreeIsolator.cleanup(taskId);
263
+ }
264
+ catch {
265
+ // Best-effort teardown; a failed cleanup must not mask the run's real result.
266
+ }
267
+ }
268
+ lease?.release();
337
269
  }
338
270
  fsm.transition("RESPOND");
339
271
  mailboxSystem.send(agentId, resultMailbox, {
@@ -344,6 +276,7 @@ async function runAgentWithLifecycle(cwd, agent, task, opts) {
344
276
  if (agentId !== resultMailbox) {
345
277
  mailboxSystem.deregister(agentId);
346
278
  }
279
+ run?.onFinish?.(result);
347
280
  return result;
348
281
  }
349
282
  /** Single-mode orchestration: one agent, one task, one FSM/mailbox lifecycle. */
@@ -355,6 +288,8 @@ export async function runSingleTask(cwd, agent, task, opts = {}) {
355
288
  worktree: opts.worktree,
356
289
  runner: opts.runner,
357
290
  resultMailbox: opts.resultMailbox,
291
+ limiter: opts.limiter,
292
+ run: opts.run,
358
293
  agentId,
359
294
  taskId: agentId,
360
295
  });
@@ -364,29 +299,45 @@ export async function runSingleTask(cwd, agent, task, opts = {}) {
364
299
  * up front (with `{ agentType: agent.name }` requirements), then atomically
365
300
  * assigned to its corresponding worker. Direct assignment keeps concurrent
366
301
  * orchestration calls from claiming one another's same-role tasks.
302
+ *
303
+ * The pool is `items.length` when `limiter` is given — the limiter itself is what bounds real
304
+ * concurrency — else `MAX_CONCURRENCY`.
367
305
  */
368
306
  export async function runParallelTasks(cwd, items, opts = {}) {
369
307
  const postedIds = items.map((item) => taskBoard.post({ requirements: { agentType: item.agent.name }, description: item.task }));
370
- return runParallel(items, MAX_CONCURRENCY, async (item, i) => {
308
+ const concurrency = opts.limiter ? items.length : MAX_CONCURRENCY;
309
+ return runParallel(items, concurrency, async (item, i) => {
371
310
  const workerId = `parallel-${i}-${randomUUID()}`;
372
311
  const taskId = postedIds[i];
373
312
  const assignment = taskBoard.assign(taskId, workerId);
374
313
  if (!assignment.ok)
375
314
  throw new Error(assignment.error);
376
- const result = await runAgentWithLifecycle(cwd, item.agent, item.task, {
377
- signal: opts.signal,
378
- onProgress: opts.makeOnProgress?.(item.agent.name),
379
- worktree: opts.worktree,
380
- runner: opts.runner,
381
- resultMailbox: opts.resultMailbox,
382
- agentId: workerId,
383
- taskId,
384
- });
385
- if (result.exitCode === 0)
386
- taskBoard.complete(taskId, result.output);
387
- else
388
- taskBoard.fail(taskId, result.stderr || result.output || "subagent task failed");
389
- return result;
315
+ // A throw anywhere below — `perItem(i)` or `runAgentWithLifecycle` itself — must still fail
316
+ // the posted task; otherwise it stays `assigned` forever (`runParallel`'s own catch turns the
317
+ // throw into a failed RunResult, but never touches the board).
318
+ try {
319
+ const perItem = opts.perItem?.(i);
320
+ const result = await runAgentWithLifecycle(cwd, item.agent, item.task, {
321
+ signal: perItem?.signal ?? opts.signal,
322
+ onProgress: opts.makeOnProgress?.(item.agent.name),
323
+ worktree: opts.worktree,
324
+ runner: opts.runner,
325
+ resultMailbox: opts.resultMailbox,
326
+ limiter: opts.limiter,
327
+ run: perItem?.run,
328
+ agentId: workerId,
329
+ taskId,
330
+ });
331
+ if (result.exitCode === 0)
332
+ taskBoard.complete(taskId, capHeadTail(result.output, 4096).text);
333
+ else
334
+ taskBoard.fail(taskId, capHeadTail(result.stderr || result.output || "subagent task failed", 4096).text);
335
+ return result;
336
+ }
337
+ catch (error) {
338
+ taskBoard.fail(taskId, capHeadTail(error instanceof Error ? error.message : String(error), 4096).text);
339
+ throw error;
340
+ }
390
341
  });
391
342
  }
392
343
  /**
@@ -395,7 +346,8 @@ export async function runParallelTasks(cwd, items, opts = {}) {
395
346
  * TaskResult is delivered to — not a bare local variable — so downstream
396
347
  * steps consume the prior step's output the same way any other mailbox
397
348
  * message-passing consumer would. Stops (without throwing) at the first
398
- * failed step; the failed result is still included as the last entry.
349
+ * step that did not exit 0 (failed or cancelled); that result is still
350
+ * included as the last entry.
399
351
  */
400
352
  export async function runChainTasks(cwd, steps, opts = {}) {
401
353
  const chainMailbox = `chain-relay-${randomUUID()}`;
@@ -407,14 +359,19 @@ export async function runChainTasks(cwd, steps, opts = {}) {
407
359
  const step = steps[i];
408
360
  opts.onBeforeStep?.(i, steps.length, step.agent.name);
409
361
  const stepAgentId = `chain-${i}-${randomUUID()}`;
410
- const task = step.task.replace(/\{previous\}/g, previous);
362
+ // A function replacer: `previous` may itself contain `$&`/`$1`-shaped text, which a
363
+ // string replacement would reinterpret as a back-reference instead of inserting literally.
364
+ const task = step.task.replace(/\{previous\}/g, () => previous);
365
+ const perItem = opts.perItem?.(i);
411
366
  const result = await runAgentWithLifecycle(cwd, step.agent, task, {
412
- signal: opts.signal,
367
+ signal: perItem?.signal ?? opts.signal,
413
368
  step: i + 1,
414
369
  onProgress: opts.makeOnProgress?.(step.agent.name),
415
370
  worktree: opts.worktree,
416
371
  runner: opts.runner,
417
372
  resultMailbox: chainMailbox,
373
+ limiter: opts.limiter,
374
+ run: perItem?.run,
418
375
  agentId: stepAgentId,
419
376
  taskId: stepAgentId,
420
377
  });
@@ -431,6 +388,22 @@ export async function runChainTasks(cwd, steps, opts = {}) {
431
388
  }
432
389
  return results;
433
390
  }
391
+ /** Registers `${prefix}-${randomUUID()}`; `dispose` drains and deregisters it (idempotent). */
392
+ export function createRunMailbox(prefix) {
393
+ const name = `${prefix}-${randomUUID()}`;
394
+ mailboxSystem.register(name);
395
+ let disposed = false;
396
+ return {
397
+ name,
398
+ dispose() {
399
+ if (disposed)
400
+ return;
401
+ disposed = true;
402
+ mailboxSystem.drain(name);
403
+ mailboxSystem.deregister(name);
404
+ },
405
+ };
406
+ }
434
407
  /** Grapheme budget for every attacker-influenced string that travels in a permission ask. */
435
408
  const PERMISSION_DETAIL_MAX_GRAPHEMES = 512;
436
409
  /**
@@ -440,12 +413,15 @@ const PERMISSION_DETAIL_MAX_GRAPHEMES = 512;
440
413
  * schema, then refused by the attach bridge, which closed the renderer's socket with 1008.
441
414
  *
442
415
  * 512 × 4 bytes: four is the widest a single code point is in UTF-8, so every ordinary cluster
443
- * survives untouched. A `tool_permission` detail carries FIVE such fields — `toolCallId`,
444
- * `toolName`, `cwd`, `reason`, and exactly one of `command` / `path` / `operation` — so at maximum
445
- * it is 5 × 2048 = 10,240 bytes of free text plus a fixed option pair and a handful of keys: ~10 KiB
446
- * against the 64 KiB `maxFrameBytes` a permission frame must fit into, which is never split.
416
+ * survives untouched. A `tool_permission` detail carries FIVE such scalar fields — `toolCallId`,
417
+ * `toolName`, `cwd`, `reason`, and exactly one of `command` / `path` / `operation` — plus up to
418
+ * `MAX_SUMMARY_LINES` lines of `summary`, so at maximum it is (5 + MAX_SUMMARY_LINES) × 2048 bytes
419
+ * of free text plus a fixed option pair and a handful of keys, comfortably under the 64 KiB
420
+ * `maxFrameBytes` a permission frame must fit into, which is never split.
447
421
  */
448
422
  const PERMISSION_DETAIL_MAX_BYTES = 512 * 4;
423
+ /** Caps the lines an {@link ApprovalDescription} can add to a permission ask's `summary`. */
424
+ const MAX_SUMMARY_LINES = 8;
449
425
  /**
450
426
  * The vocabulary this phase offers for a tool permission ask.
451
427
  *
@@ -481,8 +457,18 @@ function safeField(raw, verdict) {
481
457
  * Neutralization happens HERE, at construction, not at any protocol layer: three renderers
482
458
  * (TUI, `draht --attach`, RPC) inherit this object, and the attach client is a bare `JSON.parse`
483
459
  * cast that never passes through a schema. Constructing it safe is what makes all three safe.
460
+ *
461
+ * `description`, when given, carries the workflow approval's own title/message/operation. Its
462
+ * `operation` replaces the command/path/operation inference below outright: a workflow call's
463
+ * free-text `script`/`args` fields are not themselves what a human needs to approve, the parsed
464
+ * phase summary is. Its `message` becomes `detail.summary` — rows ahead of `toolName`/`cwd`/
465
+ * `reason` — so the description is never dropped on a renderer that only knows `detail` (§15).
466
+ * `summary` itself reaches the TUI and an RPC client (the three renderers above inherit this same
467
+ * object), but not `draht --attach` or geist: `socket-server/permission-relay.ts`'s
468
+ * `buildRequestFrame` hand-builds that wire frame and has no field for it (see
469
+ * `PermissionAskDetail.summary`'s doc).
484
470
  */
485
- function buildPermissionAskDetail(event, ctx, reason) {
471
+ function buildPermissionAskDetail(event, ctx, reason, description) {
486
472
  const input = (event.input ?? {});
487
473
  const verdict = { truncated: false };
488
474
  const detail = {
@@ -496,23 +482,34 @@ function buildPermissionAskDetail(event, ctx, reason) {
496
482
  options: TOOL_PERMISSION_OPTIONS,
497
483
  truncated: false,
498
484
  };
499
- const command = typeof input.command === "string" ? input.command : undefined;
500
- const filePath = typeof input.file_path === "string" ? input.file_path : undefined;
501
- const plainPath = typeof input.path === "string" ? input.path : undefined;
502
- if (command !== undefined) {
503
- detail.command = safeField(command, verdict);
485
+ if (description !== undefined) {
486
+ detail.summary = description.message
487
+ .split("\n")
488
+ .slice(0, MAX_SUMMARY_LINES)
489
+ .map((line) => safeField(line, verdict));
504
490
  }
505
- else if (filePath !== undefined || plainPath !== undefined) {
506
- detail.path = safeField((filePath ?? plainPath), verdict);
491
+ if (description?.operation !== undefined) {
492
+ detail.operation = safeField(description.operation, verdict);
507
493
  }
508
494
  else {
509
- // Every extension tool takes `Record<string, unknown>`, so there is always SOMETHING to
510
- // show. Serializing the whole argument object beats an empty ask that asks the human to
511
- // approve an unknown action.
512
- detail.operation = safeField(serializeToolInput(input), verdict);
495
+ const command = typeof input.command === "string" ? input.command : undefined;
496
+ const filePath = typeof input.file_path === "string" ? input.file_path : undefined;
497
+ const plainPath = typeof input.path === "string" ? input.path : undefined;
498
+ if (command !== undefined) {
499
+ detail.command = safeField(command, verdict);
500
+ }
501
+ else if (filePath !== undefined || plainPath !== undefined) {
502
+ detail.path = safeField((filePath ?? plainPath), verdict);
503
+ }
504
+ else {
505
+ // Every extension tool takes `Record<string, unknown>`, so there is always SOMETHING to
506
+ // show. Serializing the whole argument object beats an empty ask that asks the human to
507
+ // approve an unknown action.
508
+ detail.operation = safeField(serializeToolInput(input), verdict);
509
+ }
513
510
  }
514
- // Set LAST: the command/path/operation branch above is the field most likely to be elided, and
515
- // it is assigned after the literal. Reading `verdict` any earlier reports on a partial detail.
511
+ // Set LAST: the branches above are the fields most likely to be elided, and the override is
512
+ // assigned after the literal. Reading `verdict` any earlier reports on a partial detail.
516
513
  detail.truncated = verdict.truncated;
517
514
  return detail;
518
515
  }
@@ -543,7 +540,7 @@ export function loadPermissionRules(projectDir, projectTrusted, globalDir) {
543
540
  * `pi.on("tool_call", ...)` — this prepares the wiring point without forcing
544
541
  * every tool call in the process through it by default.
545
542
  */
546
- export function createPermissionGateToolCallHandler(gate) {
543
+ export function createPermissionGateToolCallHandler(gate, options) {
547
544
  return async (event, ctx) => {
548
545
  const decision = gate.evaluate(event.toolName, event.input);
549
546
  if (decision.action === "deny") {
@@ -553,9 +550,17 @@ export function createPermissionGateToolCallHandler(gate) {
553
550
  // No answering surface at all: keep today's loud, operator-facing block verbatim rather
554
551
  // than letting a no-op UI resolve `false` and be recorded as a user's denial.
555
552
  if (!ctx.hasUI) {
556
- return { block: true, reason: `${decision.reason} (no UI available to request approval)` };
553
+ return { block: true, reason: `${decision.reason} ${NO_UI_APPROVAL_SUFFIX}` };
557
554
  }
558
- const detail = buildPermissionAskDetail(event, ctx, decision.reason);
555
+ const description = options?.describe?.(event, ctx);
556
+ // Called right before the prompt, so an open inspector closes and the parent dialog
557
+ // stays reachable.
558
+ options?.beforePrompt?.(ctx);
559
+ const detail = buildPermissionAskDetail(event, ctx, decision.reason, description);
560
+ const title = description?.title ?? "Approve tool call?";
561
+ const message = description
562
+ ? `${description.message}\n\n${decision.reason}`
563
+ : `${event.toolName}: ${decision.reason}`;
559
564
  // Both positional strings are unchanged so every existing renderer keeps working; the
560
565
  // canonical facts ride alongside them for surfaces that can render structure.
561
566
  //
@@ -567,10 +572,7 @@ export function createPermissionGateToolCallHandler(gate) {
567
572
  // clock. Aborting the turn now takes the dialog down on every surface, and — because
568
573
  // nobody answered — it is recorded as `cancelled` by the system rather than as this
569
574
  // human's refusal.
570
- const approved = await ctx.ui.confirm("Approve tool call?", `${event.toolName}: ${decision.reason}`, {
571
- detail,
572
- signal: ctx.signal,
573
- });
575
+ const approved = await ctx.ui.confirm(title, message, { detail, signal: ctx.signal });
574
576
  if (!approved) {
575
577
  // The turn being aborted is NOT a refusal, and saying so in the transcript would put the
576
578
  // same fabrication in front of the model that the durable record was just cleared of:
@@ -588,23 +590,75 @@ export function createPermissionGateToolCallHandler(gate) {
588
590
  };
589
591
  }
590
592
  // ─── Extension ──────────────────────────────────────────────────────────────
593
+ const ThinkingParam = Type.Union(THINKING_LEVELS.map((level) => Type.Literal(level)), {
594
+ description: "Thinking level for this agent",
595
+ });
591
596
  const TaskItem = Type.Object({
592
597
  agent: Type.String({ description: "Agent name" }),
593
598
  task: Type.String({ description: "Task description" }),
599
+ label: Type.Optional(Type.String({ description: "Short display label (default: agent name, #n for duplicates)" })),
600
+ model: Type.Optional(Type.String({
601
+ description: "provider/id[:thinking]; default: agent frontmatter model, else the current session model",
602
+ })),
603
+ thinking: Type.Optional(ThinkingParam),
594
604
  });
595
605
  const ChainItem = Type.Object({
596
606
  agent: Type.String({ description: "Agent name" }),
597
607
  task: Type.String({ description: "Task, optionally using {previous} placeholder" }),
608
+ label: Type.Optional(Type.String({ description: "Short display label (default: agent name, #n for duplicates)" })),
609
+ model: Type.Optional(Type.String({
610
+ description: "provider/id[:thinking]; default: agent frontmatter model, else the current session model",
611
+ })),
612
+ thinking: Type.Optional(ThinkingParam),
598
613
  });
599
614
  const Params = Type.Object({
600
615
  agent: Type.Optional(Type.String()),
601
616
  task: Type.Optional(Type.String()),
617
+ label: Type.Optional(Type.String({ description: "Short display label (single mode)" })),
618
+ model: Type.Optional(Type.String({
619
+ description: "provider/id[:thinking] (single mode); default: agent frontmatter model, else current",
620
+ })),
621
+ thinking: Type.Optional(ThinkingParam),
602
622
  tasks: Type.Optional(Type.Array(TaskItem, { description: "Parallel tasks" })),
603
623
  chain: Type.Optional(Type.Array(ChainItem, { description: "Chained tasks" })),
604
624
  agentScope: Type.Optional(Type.Union([Type.Literal("user"), Type.Literal("project"), Type.Literal("both")], { default: "both" })),
605
625
  worktree: Type.Optional(Type.Boolean({ description: "Opt-in: run each task in an isolated git worktree, merged back on success" })),
606
626
  });
607
- // ─── Rendering helpers ──────────────────────────────────────────────────────
627
+ /** A blank or whitespace-only label is treated as absent, not as the literal empty string. */
628
+ function labelKey(item) {
629
+ const trimmed = item.label?.trim();
630
+ return trimmed ? trimmed : item.agent.name;
631
+ }
632
+ /**
633
+ * Default label is the agent name; duplicates (whether default or user-provided) become
634
+ * `<key>#1`, `<key>#2`, in order. Every emitted label is tracked across the whole call, so a
635
+ * user-provided label that collides with a number this function would otherwise generate (e.g.
636
+ * `["reviewer#1", default, default]` for three `reviewer` tasks) still comes out unique.
637
+ */
638
+ function assignLabels(items) {
639
+ const totals = new Map();
640
+ for (const item of items) {
641
+ const key = labelKey(item);
642
+ totals.set(key, (totals.get(key) ?? 0) + 1);
643
+ }
644
+ const seen = new Map();
645
+ const emitted = new Set();
646
+ return items.map((item) => {
647
+ const key = labelKey(item);
648
+ let label = (totals.get(key) ?? 0) <= 1 ? key : undefined;
649
+ if (label === undefined || emitted.has(label)) {
650
+ let n = (seen.get(key) ?? 0) + 1;
651
+ label = `${key}#${n}`;
652
+ while (emitted.has(label)) {
653
+ n++;
654
+ label = `${key}#${n}`;
655
+ }
656
+ seen.set(key, n);
657
+ }
658
+ emitted.add(label);
659
+ return label;
660
+ });
661
+ }
608
662
  /**
609
663
  * Human-readable recovery notice for a failed worktree merge-back, or
610
664
  * `undefined` when no merge was attempted or it succeeded. The branch name,
@@ -620,351 +674,564 @@ export function describeMergeFailure(result) {
620
674
  `and is NOT in the working tree.${conflicts} To integrate it, run \`git merge ${branch}\`, ` +
621
675
  `then invoke the resolve-conflicts skill (/resolve-conflicts) to resolve the conflicts and finish the merge.`);
622
676
  }
623
- function truncateTask(task, maxLen = 120) {
624
- const oneLine = task.replace(/\n/g, " ").trim();
625
- return oneLine.length > maxLen ? `${oneLine.slice(0, maxLen)}...` : oneLine;
626
- }
627
- export default function (pi) {
628
- // Autocomplete gets no ctx, so the last trust answer a ctx gave for this cwd stands in; unseen cwds count as untrusted.
629
- let lastProjectTrust;
630
- const noteProjectTrust = (ctx) => {
631
- lastProjectTrust = { cwd: ctx.cwd, trusted: ctx.isProjectTrusted() };
632
- };
633
- const rememberedProjectTrust = (cwd) => lastProjectTrust?.cwd === cwd ? lastProjectTrust.trusted : false;
634
- pi.registerTool({
635
- name: "subagent",
636
- label: "Subagent",
637
- description: "Delegate to specialized agents. single: {agent,task} | parallel: {tasks:[]} | chain: {chain:[]} with {previous} placeholder. agentScope: 'both' (default) uses project .draht/agents/ + global.",
638
- parameters: Params,
639
- renderCall(args, theme) {
640
- const lines = [];
641
- if (args.chain?.length) {
642
- const agents = args.chain.map((s) => s.agent).join(" -> ");
643
- lines.push(`${theme.fg("toolTitle", theme.bold(`subagent chain`))} ${theme.fg("accent", agents)}`);
644
- for (let i = 0; i < args.chain.length; i++) {
645
- const step = args.chain[i];
646
- const prefix = theme.fg("muted", ` ${i + 1}.`);
647
- lines.push(`${prefix} ${theme.fg("accent", step.agent)} ${theme.fg("toolOutput", truncateTask(step.task))}`);
648
- }
649
- }
650
- else if (args.tasks?.length) {
651
- lines.push(theme.fg("toolTitle", theme.bold(`subagent parallel`)) +
652
- theme.fg("muted", ` (${args.tasks.length} tasks)`));
653
- for (const t of args.tasks) {
654
- lines.push(` ${theme.fg("accent", t.agent)} ${theme.fg("toolOutput", truncateTask(t.task))}`);
655
- }
656
- }
657
- else if (args.agent) {
658
- lines.push(theme.fg("toolTitle", theme.bold("subagent")) +
659
- " " +
660
- theme.fg("accent", args.agent) +
661
- (args.task ? ` ${theme.fg("toolOutput", truncateTask(args.task))}` : ""));
662
- }
663
- else {
664
- lines.push(theme.fg("toolTitle", theme.bold("subagent")));
665
- }
666
- return new Text(lines.join("\n"), 0, 0);
667
- },
668
- renderResult(result, options, theme) {
669
- const status = result.details?.status;
670
- const output = result.content
671
- ?.filter((c) => c.type === "text")
672
- .map((c) => ("text" in c ? c.text : ""))
673
- .join("\n") || "";
674
- const lines = [];
675
- if (status) {
676
- lines.push(theme.fg("muted", status));
677
- }
678
- if (output.trim()) {
679
- const trimmed = output.trim();
680
- if (options.expanded || options.isPartial) {
681
- // When expanded or during execution, show full activity log
682
- for (const line of trimmed.split("\n")) {
683
- lines.push(theme.fg("toolOutput", line));
684
- }
685
- }
686
- else {
687
- // Collapsed final result — show preview
688
- const allLines = trimmed.split("\n");
689
- const previewLines = allLines.slice(0, 8);
690
- lines.push(theme.fg("toolOutput", previewLines.join("\n")));
691
- if (allLines.length > 8) {
692
- lines.push(theme.fg("muted", `... (${allLines.length - 8} more lines)`));
693
- }
694
- }
695
- }
696
- if (lines.length === 0)
697
- return new Text("", 0, 0);
698
- return new Text(lines.join("\n"), 0, 0);
699
- },
700
- async execute(_id, params, signal, onUpdate, ctx) {
701
- const scope = params.agentScope ?? "both";
702
- noteProjectTrust(ctx);
703
- const agents = discoverAgents(ctx.cwd, scope, ctx.isProjectTrusted());
704
- const available = agents.map((a) => a.name).join(", ") || "none";
705
- const find = (name) => agents.find((a) => a.name === name);
706
- const notFound = (name) => ({
707
- content: [{ type: "text", text: `Unknown agent "${name}". Available: ${available}` }],
708
- isError: true,
709
- details: {},
710
- });
711
- // Stream live activity from the subagent process
712
- const activityLines = [];
713
- const emitProgress = (agentName, activity) => {
714
- const status = activity ? `${agentName}: ${activity}` : `${agentName} working...`;
715
- onUpdate?.({
716
- content: [{ type: "text", text: activityLines.join("\n") }],
717
- details: { status },
677
+ /** `createSubagentExtension(options?)`; the default export is `createSubagentExtension()` (§10.5). */
678
+ export function createSubagentExtension(options = {}) {
679
+ const runnerOverride = options.runner;
680
+ return (pi) => {
681
+ // Autocomplete gets no ctx, so the last trust answer a ctx gave for this cwd stands in; unseen cwds count as untrusted.
682
+ let lastProjectTrust;
683
+ const noteProjectTrust = (ctx) => {
684
+ lastProjectTrust = { cwd: ctx.cwd, trusted: ctx.isProjectTrusted() };
685
+ };
686
+ const rememberedProjectTrust = (cwd) => lastProjectTrust?.cwd === cwd ? lastProjectTrust.trusted : false;
687
+ let currentSession;
688
+ const renderDeps = {
689
+ getStore: () => currentSession?.store,
690
+ viewportRows: () => process.stdout.rows || 24,
691
+ };
692
+ const { renderCall, renderResult } = createSubagentRenderers(renderDeps);
693
+ pi.registerTool({
694
+ name: "subagent",
695
+ label: "Subagent",
696
+ description: "Delegate to specialized agents. single: {agent,task} | parallel: {tasks:[]} | chain: {chain:[]} with {previous} placeholder. agentScope: 'both' (default) uses project .draht/agents/ + global. " +
697
+ "Agents without a model inherit the current model and thinking level. Optional per-task label/model/thinking.",
698
+ parameters: Params,
699
+ renderCall,
700
+ renderResult,
701
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
702
+ const scope = params.agentScope ?? "both";
703
+ noteProjectTrust(ctx);
704
+ const agents = discoverAgents(ctx.cwd, scope, ctx.isProjectTrusted());
705
+ const available = agents.map((a) => a.name).join(", ") || "none";
706
+ const find = (name) => agents.find((a) => a.name === name);
707
+ const notFound = (name) => ({
708
+ content: [{ type: "text", text: `Unknown agent "${name}". Available: ${available}` }],
709
+ isError: true,
710
+ details: {},
718
711
  });
719
- };
720
- const makeProgressFn = (agentName) => (activity) => {
721
- // Keep a rolling log of recent activities
722
- activityLines.push(`${agentName}: ${activity}`);
723
- if (activityLines.length > 50)
724
- activityLines.splice(0, activityLines.length - 50);
725
- emitProgress(agentName, activity);
726
- };
727
- const worktree = Boolean(params.worktree);
728
- // ── Chain mode ──
729
- if (params.chain?.length) {
730
- const steps = [];
731
- for (const step of params.chain) {
732
- const agent = find(step.agent);
733
- if (!agent)
734
- return notFound(step.agent);
735
- steps.push({ agent, task: step.task });
712
+ const worktree = Boolean(params.worktree);
713
+ // `getPolyphaseSession` keys a `WeakMap` on this value, which throws a `TypeError` for
714
+ // anything that is not an object. Not reachable through a real session (`sessionManager`
715
+ // is always set there), but the fake `pi`/`ctx` used by the trust test suite omits it.
716
+ if (typeof ctx.sessionManager !== "object" || ctx.sessionManager === null) {
717
+ return {
718
+ content: [{ type: "text", text: "No session available for subagent delegation." }],
719
+ isError: true,
720
+ details: {},
721
+ };
736
722
  }
737
- const results = await runChainTasks(ctx.cwd, steps, {
738
- signal,
739
- worktree,
740
- makeOnProgress: (agentName) => makeProgressFn(agentName),
741
- onBeforeStep: (i, total, agentName) => {
742
- activityLines.length = 0;
743
- emitProgress(agentName, `step ${i + 1}/${total}`);
744
- },
745
- });
746
- const mergeNotices = results
747
- .map(describeMergeFailure)
748
- .filter((notice) => notice !== undefined);
749
- const noticeBlock = mergeNotices.length > 0 ? `\n\n${mergeNotices.join("\n\n")}` : "";
750
- const last = results[results.length - 1];
751
- if (last.exitCode !== 0) {
752
- const failedIndex = results.length - 1;
723
+ const session = getPolyphaseSession(ctx.sessionManager, pi.getSettings().polyphase);
724
+ currentSession = session;
725
+ const settings = session.settings();
726
+ const depth = currentPolyphaseDepth();
727
+ if (depth >= settings.maxDepth) {
753
728
  return {
754
729
  content: [
755
730
  {
756
731
  type: "text",
757
- text: `Chain failed at step ${failedIndex + 1} (${params.chain[failedIndex].agent}):\n${last.output || last.stderr}${noticeBlock}`,
732
+ text: `Delegation depth limit reached (depth ${depth}, polyphase.maxDepth ${settings.maxDepth}).`,
758
733
  },
759
734
  ],
760
735
  isError: true,
761
736
  details: {},
762
737
  };
763
738
  }
764
- return {
765
- content: [{ type: "text", text: `${last.output || "(no output)"}${noticeBlock}` }],
766
- // A merge-back failure means a step's work did not land in the
767
- // caller's tree, even though every step's agent succeeded.
768
- ...(mergeNotices.length > 0 ? { isError: true } : {}),
769
- details: {},
770
- };
771
- }
772
- // ── Parallel mode ──
773
- if (params.tasks?.length) {
774
- if (params.tasks.length > MAX_PARALLEL) {
775
- return {
776
- content: [{ type: "text", text: `Too many tasks (max ${MAX_PARALLEL})` }],
777
- isError: true,
778
- details: {},
779
- };
739
+ const available_ = ctx.modelRegistry.getAvailable();
740
+ const exclude = depth + 1 >= settings.maxDepth ? ["subagent"] : [];
741
+ // ── Chain mode ──
742
+ if (params.chain?.length) {
743
+ const steps = [];
744
+ for (const step of params.chain) {
745
+ const agent = find(step.agent);
746
+ if (!agent)
747
+ return notFound(step.agent);
748
+ steps.push({ agent, task: step.task, model: step.model, thinking: step.thinking });
749
+ }
750
+ const labels = assignLabels(params.chain.map((s, i) => ({ agent: steps[i].agent, label: s.label })));
751
+ const choices = [];
752
+ for (let i = 0; i < steps.length; i++) {
753
+ const step = steps[i];
754
+ try {
755
+ choices.push(resolveChildModel({
756
+ override: step.model,
757
+ effort: step.thinking,
758
+ agentModel: step.agent.model,
759
+ parentModel: ctx.model,
760
+ parentThinking: ctx.thinkingLevel,
761
+ available: available_,
762
+ }));
763
+ }
764
+ catch (error) {
765
+ return {
766
+ content: [
767
+ {
768
+ type: "text",
769
+ text: `Invalid model for chain step ${i + 1} (${step.agent.name}): ${error instanceof Error ? error.message : String(error)}`,
770
+ },
771
+ ],
772
+ isError: true,
773
+ details: {},
774
+ };
775
+ }
776
+ }
777
+ const title = `subagent chain · ${steps.map((s) => s.agent.name).join(" → ")}`;
778
+ const run = session.store.createRun({
779
+ id: toolCallId,
780
+ kind: "subagent",
781
+ origin: "tool",
782
+ mode: "chain",
783
+ title,
784
+ budgetTokens: null,
785
+ parentSignal: signal,
786
+ });
787
+ // Chain steps relay `{previous}` through their own per-chain mailbox (runChainTasks /
788
+ // `chainMailbox` above), not through a run mailbox like parallel/single mode: there is no
789
+ // `resultMailbox` field on `RunChainTasksOptions`, so one is never created here.
790
+ let emitter;
791
+ try {
792
+ const live = steps.map((step, i) => run.addAgent({
793
+ label: labels[i],
794
+ agentType: step.agent.name,
795
+ task: step.task,
796
+ step: i + 1,
797
+ model: choices[i].info,
798
+ }));
799
+ emitter = createPartialUpdateEmitter(run, onUpdate, {
800
+ mode: ctx.mode,
801
+ liveUpdateMs: settings.liveUpdateMs,
802
+ });
803
+ const perItem = (i) => ({
804
+ signal: live[i].signal,
805
+ run: live[i].createRunContext({
806
+ model: choices[i].modelArg,
807
+ thinking: choices[i].thinking,
808
+ modelInfo: choices[i].info,
809
+ fallbackToChildDefaultModel: choices[i].info.source === "inherited",
810
+ excludeTools: exclude,
811
+ }),
812
+ });
813
+ const results = await runChainTasks(ctx.cwd, steps.map((s) => ({ agent: s.agent, task: s.task })), { signal, worktree, runner: runnerOverride, limiter: session.limiter, perItem });
814
+ const last = results[results.length - 1];
815
+ const mergeNotices = results
816
+ .map(describeMergeFailure)
817
+ .filter((notice) => notice !== undefined);
818
+ const isError = last.exitCode !== 0 || mergeNotices.length > 0;
819
+ const status = last.exitCode !== 0 ? (last.cancelled ? "cancelled" : "failed") : isError ? "failed" : "done";
820
+ run.finish(status);
821
+ const content = formatSubagentResultText(run, {
822
+ mode: "chain",
823
+ resultChars: settings.resultChars,
824
+ notices: mergeNotices,
825
+ });
826
+ return {
827
+ content: [{ type: "text", text: content }],
828
+ ...(isError ? { isError: true } : {}),
829
+ details: buildDetails(run, { final: true }),
830
+ usage: sumRunUsage(run),
831
+ };
832
+ }
833
+ catch (error) {
834
+ if (run.status === "running")
835
+ run.finish("failed", error instanceof Error ? error.message : String(error));
836
+ return {
837
+ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
838
+ isError: true,
839
+ details: buildDetails(run, { final: true }),
840
+ usage: sumRunUsage(run),
841
+ };
842
+ }
843
+ finally {
844
+ emitter?.dispose();
845
+ }
846
+ }
847
+ // ── Parallel mode ──
848
+ if (params.tasks?.length) {
849
+ if (params.tasks.length > MAX_PARALLEL) {
850
+ return {
851
+ content: [{ type: "text", text: `Too many tasks (max ${MAX_PARALLEL})` }],
852
+ isError: true,
853
+ details: {},
854
+ };
855
+ }
856
+ const items = [];
857
+ for (const t of params.tasks) {
858
+ const agent = find(t.agent);
859
+ if (!agent)
860
+ return notFound(t.agent);
861
+ items.push({ agent, task: t.task, model: t.model, thinking: t.thinking });
862
+ }
863
+ const labels = assignLabels(params.tasks.map((t, i) => ({ agent: items[i].agent, label: t.label })));
864
+ const choices = [];
865
+ for (let i = 0; i < items.length; i++) {
866
+ const item = items[i];
867
+ try {
868
+ choices.push(resolveChildModel({
869
+ override: item.model,
870
+ effort: item.thinking,
871
+ agentModel: item.agent.model,
872
+ parentModel: ctx.model,
873
+ parentThinking: ctx.thinkingLevel,
874
+ available: available_,
875
+ }));
876
+ }
877
+ catch (error) {
878
+ return {
879
+ content: [
880
+ {
881
+ type: "text",
882
+ text: `Invalid model for task ${i + 1} (${item.agent.name}): ${error instanceof Error ? error.message : String(error)}`,
883
+ },
884
+ ],
885
+ isError: true,
886
+ details: {},
887
+ };
888
+ }
889
+ }
890
+ const title = `subagent parallel · ${items.length} agents`;
891
+ const run = session.store.createRun({
892
+ id: toolCallId,
893
+ kind: "subagent",
894
+ origin: "tool",
895
+ mode: "parallel",
896
+ title,
897
+ budgetTokens: null,
898
+ parentSignal: signal,
899
+ });
900
+ let mailbox;
901
+ let emitter;
902
+ try {
903
+ const live = items.map((item, i) => run.addAgent({
904
+ label: labels[i],
905
+ agentType: item.agent.name,
906
+ task: item.task,
907
+ model: choices[i].info,
908
+ }));
909
+ mailbox = createRunMailbox("subagent-run");
910
+ emitter = createPartialUpdateEmitter(run, onUpdate, {
911
+ mode: ctx.mode,
912
+ liveUpdateMs: settings.liveUpdateMs,
913
+ });
914
+ const perItem = (i) => ({
915
+ signal: live[i].signal,
916
+ run: live[i].createRunContext({
917
+ model: choices[i].modelArg,
918
+ thinking: choices[i].thinking,
919
+ modelInfo: choices[i].info,
920
+ fallbackToChildDefaultModel: choices[i].info.source === "inherited",
921
+ excludeTools: exclude,
922
+ }),
923
+ });
924
+ const results = await runParallelTasks(ctx.cwd, items.map((item) => ({ agent: item.agent, task: item.task })), {
925
+ signal,
926
+ worktree,
927
+ runner: runnerOverride,
928
+ limiter: session.limiter,
929
+ resultMailbox: mailbox.name,
930
+ perItem,
931
+ });
932
+ const succeeded = results.some((r) => r.exitCode === 0 && describeMergeFailure(r) === undefined);
933
+ const allCancelled = results.every((r) => r.cancelled);
934
+ const status = succeeded ? "done" : allCancelled ? "cancelled" : "failed";
935
+ run.finish(status);
936
+ const mergeNotices = results
937
+ .map(describeMergeFailure)
938
+ .filter((notice) => notice !== undefined);
939
+ const content = formatSubagentResultText(run, {
940
+ mode: "parallel",
941
+ resultChars: settings.resultChars,
942
+ notices: mergeNotices,
943
+ });
944
+ return {
945
+ content: [{ type: "text", text: content }],
946
+ ...(succeeded ? {} : { isError: true }),
947
+ details: buildDetails(run, { final: true }),
948
+ usage: sumRunUsage(run),
949
+ };
950
+ }
951
+ catch (error) {
952
+ if (run.status === "running")
953
+ run.finish("failed", error instanceof Error ? error.message : String(error));
954
+ return {
955
+ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
956
+ isError: true,
957
+ details: buildDetails(run, { final: true }),
958
+ usage: sumRunUsage(run),
959
+ };
960
+ }
961
+ finally {
962
+ emitter?.dispose();
963
+ mailbox?.dispose();
964
+ }
780
965
  }
781
- const items = [];
782
- for (const t of params.tasks) {
783
- const agent = find(t.agent);
966
+ // ── Single mode ──
967
+ if (params.agent && params.task) {
968
+ const agent = find(params.agent);
784
969
  if (!agent)
785
- return notFound(t.agent);
786
- items.push({ agent, task: t.task });
970
+ return notFound(params.agent);
971
+ let choice;
972
+ try {
973
+ choice = resolveChildModel({
974
+ override: params.model,
975
+ effort: params.thinking,
976
+ agentModel: agent.model,
977
+ parentModel: ctx.model,
978
+ parentThinking: ctx.thinkingLevel,
979
+ available: available_,
980
+ });
981
+ }
982
+ catch (error) {
983
+ return {
984
+ content: [
985
+ {
986
+ type: "text",
987
+ text: `Invalid model for ${params.agent}: ${error instanceof Error ? error.message : String(error)}`,
988
+ },
989
+ ],
990
+ isError: true,
991
+ details: {},
992
+ };
993
+ }
994
+ const title = `subagent ${agent.name}`;
995
+ const run = session.store.createRun({
996
+ id: toolCallId,
997
+ kind: "subagent",
998
+ origin: "tool",
999
+ mode: "single",
1000
+ title,
1001
+ budgetTokens: null,
1002
+ parentSignal: signal,
1003
+ });
1004
+ let mailbox;
1005
+ let emitter;
1006
+ try {
1007
+ const label = labelKey({ agent, label: params.label });
1008
+ const live = run.addAgent({ label, agentType: agent.name, task: params.task, model: choice.info });
1009
+ mailbox = createRunMailbox("subagent-run");
1010
+ emitter = createPartialUpdateEmitter(run, onUpdate, {
1011
+ mode: ctx.mode,
1012
+ liveUpdateMs: settings.liveUpdateMs,
1013
+ });
1014
+ const runContext = live.createRunContext({
1015
+ model: choice.modelArg,
1016
+ thinking: choice.thinking,
1017
+ modelInfo: choice.info,
1018
+ fallbackToChildDefaultModel: choice.info.source === "inherited",
1019
+ excludeTools: exclude,
1020
+ });
1021
+ const result = await runSingleTask(ctx.cwd, agent, params.task, {
1022
+ signal: live.signal,
1023
+ worktree,
1024
+ runner: runnerOverride,
1025
+ resultMailbox: mailbox.name,
1026
+ limiter: session.limiter,
1027
+ run: runContext,
1028
+ });
1029
+ const mergeNotice = describeMergeFailure(result);
1030
+ // Matches chain/parallel: a worktree merge-back failure fails the run even when the
1031
+ // child itself exited 0, instead of reporting "done" with `isError` as the only signal.
1032
+ const status = result.exitCode !== 0
1033
+ ? result.cancelled
1034
+ ? "cancelled"
1035
+ : "failed"
1036
+ : mergeNotice !== undefined
1037
+ ? "failed"
1038
+ : "done";
1039
+ run.finish(status);
1040
+ const content = formatSubagentResultText(run, {
1041
+ mode: "single",
1042
+ resultChars: settings.resultChars,
1043
+ notices: mergeNotice !== undefined ? [mergeNotice] : [],
1044
+ });
1045
+ const isError = result.exitCode !== 0 || mergeNotice !== undefined;
1046
+ return {
1047
+ content: [{ type: "text", text: content }],
1048
+ ...(isError ? { isError: true } : {}),
1049
+ details: buildDetails(run, { final: true }),
1050
+ usage: sumRunUsage(run),
1051
+ };
1052
+ }
1053
+ catch (error) {
1054
+ if (run.status === "running")
1055
+ run.finish("failed", error instanceof Error ? error.message : String(error));
1056
+ return {
1057
+ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
1058
+ isError: true,
1059
+ details: buildDetails(run, { final: true }),
1060
+ usage: sumRunUsage(run),
1061
+ };
1062
+ }
1063
+ finally {
1064
+ emitter?.dispose();
1065
+ mailbox?.dispose();
1066
+ }
787
1067
  }
788
- const agentNames = params.tasks.map((t) => t.agent).join(", ");
789
- emitProgress(agentNames);
790
- const results = await runParallelTasks(ctx.cwd, items, {
791
- signal,
792
- worktree,
793
- makeOnProgress: (agentName) => makeProgressFn(agentName),
794
- });
795
- const ok = results.filter((r) => r.exitCode === 0 && describeMergeFailure(r) === undefined).length;
796
- const summary = results
797
- .map((r) => `[${r.agent}] ${r.exitCode !== 0 ? "fail" : describeMergeFailure(r) ? "merge-failed" : "ok"} ${r.output.slice(0, 200)}`)
798
- .join("\n\n");
799
- const notices = results
800
- .map(describeMergeFailure)
801
- .filter((notice) => notice !== undefined);
802
- const noticeBlock = notices.length > 0 ? `\n\n${notices.join("\n\n")}` : "";
803
1068
  return {
804
- content: [
805
- {
806
- type: "text",
807
- text: `Parallel: ${ok}/${results.length} succeeded\n\n${summary}${noticeBlock}`,
808
- },
809
- ],
1069
+ content: [{ type: "text", text: `Provide exactly one mode. Available agents: ${available}` }],
1070
+ isError: true,
810
1071
  details: {},
811
1072
  };
812
- }
813
- // ── Single mode ──
814
- if (params.agent && params.task) {
815
- const agent = find(params.agent);
816
- if (!agent)
817
- return notFound(params.agent);
818
- emitProgress(params.agent);
819
- const result = await runSingleTask(ctx.cwd, agent, params.task, {
820
- signal,
821
- worktree,
822
- onProgress: makeProgressFn(params.agent),
823
- });
824
- const mergeNotice = describeMergeFailure(result);
825
- // A merge-back failure means the delegated change did NOT land in
826
- // the caller's tree — a plain success would mislead the orchestrator.
827
- const isError = result.exitCode !== 0 || mergeNotice !== undefined;
828
- const baseText = result.output || result.stderr || "(no output)";
829
- return {
830
- content: [{ type: "text", text: mergeNotice ? `${baseText}\n\n${mergeNotice}` : baseText }],
831
- ...(isError ? { isError: true } : {}),
832
- details: {},
833
- };
834
- }
835
- return {
836
- content: [{ type: "text", text: `Provide exactly one mode. Available agents: ${available}` }],
837
- isError: true,
838
- details: {},
839
- };
840
- },
841
- });
842
- // ── Permission gate hook point ────────────────────────────────────────────
843
- // Prepares the wiring point for the multi-agent permission gate: every tool
844
- // call in this process is offered to the gate before it runs. Rules are
845
- // (re)loaded per call so project-local `.draht/permissions.yml` edits — read
846
- // only for a trusted project — and per-session cwd changes take effect
847
- // without an extension reload.
848
- //
849
- // The session permission mode (default/auto/yolo) is session-scoped state,
850
- // settable via /permissions and /yolo below and seeded from
851
- // DRAHT_PERMISSION_MODE. It relaxes prompting, never `deny` rules.
852
- let permissionMode = isPermissionMode(process.env.DRAHT_PERMISSION_MODE)
853
- ? process.env.DRAHT_PERMISSION_MODE
854
- : "default";
855
- function updatePermissionStatus(ctx) {
856
- ctx.ui.setStatus("permissions", permissionMode === "default" ? undefined : `perms: ${permissionMode}`);
857
- }
858
- const MODE_DESCRIPTIONS = {
859
- default: "rules as authored; unmatched bash commands require approval",
860
- auto: "auto-approve bash unless the command looks dangerous (deny rules still block)",
861
- yolo: "no approval prompts this session (deny rules still block)",
862
- };
863
- pi.on("tool_call", (event, ctx) => {
864
- noteProjectTrust(ctx);
865
- return createPermissionGateToolCallHandler(new PermissionGate(loadPermissionRules(ctx.cwd, ctx.isProjectTrusted()), {
866
- cwd: ctx.cwd,
867
- mode: permissionMode,
868
- }))(event, ctx);
869
- });
870
- // /permissions command — show or set the session permission mode
871
- pi.registerCommand("permissions", {
872
- description: `Show or set the session permission mode. Usage: /permissions [${PERMISSION_MODES.join("|")}]`,
873
- handler: async (args, ctx) => {
874
- const requested = args.trim();
875
- if (!requested) {
876
- ctx.ui.notify(`Permission mode: ${permissionMode} — ${MODE_DESCRIPTIONS[permissionMode]}`, "info");
877
- return;
878
- }
879
- if (!isPermissionMode(requested)) {
880
- ctx.ui.notify(`Unknown mode "${requested}". Available: ${PERMISSION_MODES.join(", ")}`, "warning");
881
- return;
882
- }
883
- permissionMode = requested;
884
- updatePermissionStatus(ctx);
885
- ctx.ui.notify(`Permission mode: ${permissionMode} — ${MODE_DESCRIPTIONS[permissionMode]}`, "info");
886
- },
887
- });
888
- // /yolo command — toggle yolo mode for this session
889
- pi.registerCommand("yolo", {
890
- description: "Toggle yolo permission mode for this session (skip approval prompts; deny rules still block)",
891
- handler: async (_args, ctx) => {
892
- permissionMode = permissionMode === "yolo" ? "default" : "yolo";
893
- updatePermissionStatus(ctx);
894
- ctx.ui.notify(permissionMode === "yolo"
895
- ? "yolo mode ON — no approval prompts this session (deny rules still block)"
896
- : "yolo mode OFF — back to default permissions", "info");
897
- },
898
- });
899
- // ── Agent selection for user prompts ─────────────────────────────────────
900
- let selectedAgent;
901
- function updateAgentStatus(ctx) {
902
- ctx.ui.setStatus("agent", selectedAgent ? `agent: ${selectedAgent}` : undefined);
903
- }
904
- // /agent command — select an agent or clear selection
905
- pi.registerCommand("agent", {
906
- description: "Select an agent to handle your next prompts, or clear selection. Usage: /agent [name]",
907
- handler: async (args, ctx) => {
1073
+ },
1074
+ });
1075
+ // ── Permission gate hook point ────────────────────────────────────────────
1076
+ // Prepares the wiring point for the multi-agent permission gate: every tool
1077
+ // call in this process is offered to the gate before it runs. Rules are
1078
+ // (re)loaded per call so project-local `.draht/permissions.yml` edits — read
1079
+ // only for a trusted project — and per-session cwd changes take effect
1080
+ // without an extension reload.
1081
+ //
1082
+ // The session permission mode (default/auto/yolo) is session-scoped state,
1083
+ // settable via /permissions and /yolo below and seeded from
1084
+ // DRAHT_PERMISSION_MODE. It relaxes prompting, never `deny` rules.
1085
+ let permissionMode = isPermissionMode(process.env.DRAHT_PERMISSION_MODE)
1086
+ ? process.env.DRAHT_PERMISSION_MODE
1087
+ : "default";
1088
+ function updatePermissionStatus(ctx) {
1089
+ ctx.ui.setStatus("permissions", permissionMode === "default" ? undefined : `perms: ${permissionMode}`);
1090
+ }
1091
+ const MODE_DESCRIPTIONS = {
1092
+ default: "rules as authored; unmatched bash commands require approval",
1093
+ auto: "auto-approve bash unless the command looks dangerous (deny rules still block)",
1094
+ yolo: "no approval prompts this session (deny rules still block)",
1095
+ };
1096
+ pi.on("tool_call", (event, ctx) => {
908
1097
  noteProjectTrust(ctx);
909
- const agents = discoverAgents(ctx.cwd, "both", ctx.isProjectTrusted());
910
- if (args.trim()) {
911
- // Direct selection: /agent architect
912
- const name = args.trim();
913
- if (name === "none" || name === "off" || name === "clear") {
914
- selectedAgent = undefined;
1098
+ return createPermissionGateToolCallHandler(new PermissionGate(loadPermissionRules(ctx.cwd, ctx.isProjectTrusted()), {
1099
+ cwd: ctx.cwd,
1100
+ mode: permissionMode,
1101
+ }), {
1102
+ describe: (e, c) => {
1103
+ if (e.toolName !== WORKFLOW_TOOL_NAME)
1104
+ return undefined;
1105
+ try {
1106
+ const limits = resolvePolyphaseSettings(pi.getSettings().polyphase);
1107
+ return describeToolCallForApproval(e.toolName, (e.input ?? {}), {
1108
+ cwd: c.cwd,
1109
+ projectTrusted: c.isProjectTrusted(),
1110
+ agentDir: getAgentDir(),
1111
+ limits: {
1112
+ concurrency: limits.maxConcurrency,
1113
+ maxAgents: limits.maxAgentsPerRun,
1114
+ budgetTokens: limits.defaultBudgetTokens,
1115
+ },
1116
+ });
1117
+ }
1118
+ catch {
1119
+ return undefined;
1120
+ }
1121
+ },
1122
+ beforePrompt: (c) => peekPolyphaseSession(c.sessionManager)?.notifyParentPrompt(),
1123
+ })(event, ctx);
1124
+ });
1125
+ // /permissions command — show or set the session permission mode
1126
+ pi.registerCommand("permissions", {
1127
+ description: `Show or set the session permission mode. Usage: /permissions [${PERMISSION_MODES.join("|")}]`,
1128
+ handler: async (args, ctx) => {
1129
+ const requested = args.trim();
1130
+ if (!requested) {
1131
+ ctx.ui.notify(`Permission mode: ${permissionMode} — ${MODE_DESCRIPTIONS[permissionMode]}`, "info");
1132
+ return;
1133
+ }
1134
+ if (!isPermissionMode(requested)) {
1135
+ ctx.ui.notify(`Unknown mode "${requested}". Available: ${PERMISSION_MODES.join(", ")}`, "warning");
1136
+ return;
1137
+ }
1138
+ permissionMode = requested;
1139
+ updatePermissionStatus(ctx);
1140
+ ctx.ui.notify(`Permission mode: ${permissionMode} — ${MODE_DESCRIPTIONS[permissionMode]}`, "info");
1141
+ },
1142
+ });
1143
+ // /yolo command — toggle yolo mode for this session
1144
+ pi.registerCommand("yolo", {
1145
+ description: "Toggle yolo permission mode for this session (skip approval prompts; deny rules still block)",
1146
+ handler: async (_args, ctx) => {
1147
+ permissionMode = permissionMode === "yolo" ? "default" : "yolo";
1148
+ updatePermissionStatus(ctx);
1149
+ ctx.ui.notify(permissionMode === "yolo"
1150
+ ? "yolo mode ON — no approval prompts this session (deny rules still block)"
1151
+ : "yolo mode OFF — back to default permissions", "info");
1152
+ },
1153
+ });
1154
+ // ── Agent selection for user prompts ─────────────────────────────────────
1155
+ let selectedAgent;
1156
+ function updateAgentStatus(ctx) {
1157
+ ctx.ui.setStatus("agent", selectedAgent ? `agent: ${selectedAgent}` : undefined);
1158
+ }
1159
+ // /agent command — select an agent or clear selection
1160
+ pi.registerCommand("agent", {
1161
+ description: "Select an agent to handle your next prompts, or clear selection. Usage: /agent [name]",
1162
+ handler: async (args, ctx) => {
1163
+ noteProjectTrust(ctx);
1164
+ const agents = discoverAgents(ctx.cwd, "both", ctx.isProjectTrusted());
1165
+ if (args.trim()) {
1166
+ // Direct selection: /agent architect
1167
+ const name = args.trim();
1168
+ if (name === "none" || name === "off" || name === "clear") {
1169
+ selectedAgent = undefined;
1170
+ updateAgentStatus(ctx);
1171
+ ctx.ui.notify("Agent cleared — prompts go to default model", "info");
1172
+ return;
1173
+ }
1174
+ const agent = agents.find((a) => a.name === name);
1175
+ if (!agent) {
1176
+ const available = agents.map((a) => a.name).join(", ") || "none";
1177
+ ctx.ui.notify(`Unknown agent "${name}". Available: ${available}`, "warning");
1178
+ return;
1179
+ }
1180
+ selectedAgent = name;
915
1181
  updateAgentStatus(ctx);
916
- ctx.ui.notify("Agent cleared — prompts go to default model", "info");
1182
+ ctx.ui.notify(`Agent set to "${name}" — your prompts will be handled by this agent`, "info");
917
1183
  return;
918
1184
  }
919
- const agent = agents.find((a) => a.name === name);
920
- if (!agent) {
921
- const available = agents.map((a) => a.name).join(", ") || "none";
922
- ctx.ui.notify(`Unknown agent "${name}". Available: ${available}`, "warning");
1185
+ // Interactive selection
1186
+ if (!ctx.hasUI) {
1187
+ ctx.ui.notify("Usage: /agent <name> or /agent none", "warning");
923
1188
  return;
924
1189
  }
925
- selectedAgent = name;
926
- updateAgentStatus(ctx);
927
- ctx.ui.notify(`Agent set to "${name}" — your prompts will be handled by this agent`, "info");
928
- return;
929
- }
930
- // Interactive selection
931
- if (!ctx.hasUI) {
932
- ctx.ui.notify("Usage: /agent <name> or /agent none", "warning");
1190
+ const optionsList = ["(none — default model)", ...agents.map((a) => `${a.name} — ${a.description}`)];
1191
+ const choice = await ctx.ui.select("Select agent for your prompts", optionsList);
1192
+ if (choice === undefined)
1193
+ return; // cancelled
1194
+ if (choice === optionsList[0]) {
1195
+ selectedAgent = undefined;
1196
+ updateAgentStatus(ctx);
1197
+ ctx.ui.notify("Agent cleared", "info");
1198
+ }
1199
+ else {
1200
+ const name = choice.split(" — ")[0];
1201
+ selectedAgent = name;
1202
+ updateAgentStatus(ctx);
1203
+ ctx.ui.notify(`Agent set to "${name}"`, "info");
1204
+ }
1205
+ },
1206
+ getArgumentCompletions: (partial) => {
1207
+ const cwd = process.cwd();
1208
+ const agents = discoverAgents(cwd, "both", rememberedProjectTrust(cwd));
1209
+ const names = ["none", ...agents.map((a) => a.name)];
1210
+ return names.filter((n) => n.startsWith(partial)).map((n) => ({ value: n, label: n }));
1211
+ },
1212
+ });
1213
+ // Intercept user input when an agent is selected
1214
+ pi.on("input", (event, ctx) => {
1215
+ noteProjectTrust(ctx);
1216
+ if (!selectedAgent)
1217
+ return { action: "continue" };
1218
+ // Don't intercept slash commands
1219
+ if (event.text.startsWith("/") || event.text.startsWith("!"))
1220
+ return { action: "continue" };
1221
+ const wrapped = `Use the subagent tool to delegate to the "${selectedAgent}" agent with this task:\n\n"${event.text}"\n\nSet agentScope to "both".`;
1222
+ return { action: "transform", text: wrapped, images: event.images };
1223
+ });
1224
+ pi.on("session_start", (_event, ctx) => {
1225
+ if (!ctx.sessionManager)
933
1226
  return;
934
- }
935
- const options = ["(none — default model)", ...agents.map((a) => `${a.name} — ${a.description}`)];
936
- const choice = await ctx.ui.select("Select agent for your prompts", options);
937
- if (choice === undefined)
938
- return; // cancelled
939
- if (choice === options[0]) {
940
- selectedAgent = undefined;
941
- updateAgentStatus(ctx);
942
- ctx.ui.notify("Agent cleared", "info");
943
- }
944
- else {
945
- const name = choice.split(" — ")[0];
946
- selectedAgent = name;
947
- updateAgentStatus(ctx);
948
- ctx.ui.notify(`Agent set to "${name}"`, "info");
949
- }
950
- },
951
- getArgumentCompletions: (partial) => {
952
- const cwd = process.cwd();
953
- const agents = discoverAgents(cwd, "both", rememberedProjectTrust(cwd));
954
- const names = ["none", ...agents.map((a) => a.name)];
955
- return names.filter((n) => n.startsWith(partial)).map((n) => ({ value: n, label: n }));
956
- },
957
- });
958
- // Intercept user input when an agent is selected
959
- pi.on("input", (event, ctx) => {
960
- noteProjectTrust(ctx);
961
- if (!selectedAgent)
962
- return { action: "continue" };
963
- // Don't intercept slash commands
964
- if (event.text.startsWith("/") || event.text.startsWith("!"))
965
- return { action: "continue" };
966
- const wrapped = `Use the subagent tool to delegate to the "${selectedAgent}" agent with this task:\n\n"${event.text}"\n\nSet agentScope to "both".`;
967
- return { action: "transform", text: wrapped, images: event.images };
968
- });
1227
+ currentSession = getPolyphaseSession(ctx.sessionManager, pi.getSettings().polyphase);
1228
+ currentSession.setPermissionModeProvider(() => permissionMode);
1229
+ });
1230
+ pi.on("session_shutdown", (_event, ctx) => {
1231
+ disposePolyphaseSession(ctx.sessionManager, "shutdown");
1232
+ currentSession = undefined;
1233
+ });
1234
+ };
969
1235
  }
1236
+ export default createSubagentExtension();
970
1237
  //# sourceMappingURL=subagent.js.map