@draht/coding-agent 2026.10.31-1 → 2026.11.5-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 (492) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/dist/bundle/chunks/anthropic-messages-UJZ4SGHU.js +6 -0
  3. package/dist/bundle/chunks/azure-openai-responses-NCMJPZVJ.js +2 -0
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +8 -5
  5. package/dist/bundle/chunks/{chunk-IGO52ZOY.js → chunk-3BJ462DN.js} +2 -2
  6. package/dist/bundle/chunks/chunk-5OXIAQP5.js +2 -0
  7. package/dist/bundle/chunks/chunk-6M3D4XVD.js +2 -0
  8. package/dist/bundle/chunks/chunk-AOCWORXE.js +2 -0
  9. package/dist/bundle/chunks/chunk-BK5LXGIH.js +2 -0
  10. package/dist/bundle/chunks/chunk-CA23BDNK.js +2 -0
  11. package/dist/bundle/chunks/chunk-DWOGGNWY.js +18 -0
  12. package/dist/bundle/chunks/{chunk-7ATV4EYW.js → chunk-EOXOMUKR.js} +1 -1
  13. package/dist/bundle/chunks/chunk-F5TDVH26.js +159 -0
  14. package/dist/bundle/chunks/chunk-HJ3PS7QP.js +4 -0
  15. package/dist/bundle/chunks/chunk-ITKDPD4D.js +12 -0
  16. package/dist/bundle/chunks/chunk-KFREX3FS.js +10 -0
  17. package/dist/bundle/chunks/{chunk-E4VZJRJ2.js → chunk-P7O36UDU.js} +2 -2
  18. package/dist/bundle/chunks/chunk-PMINB7UH.js +1401 -0
  19. package/dist/bundle/chunks/chunk-PZKD35UB.js +2 -0
  20. package/dist/bundle/chunks/{chunk-CPFKZX4B.js → chunk-Q2QKCYPU.js} +1 -1
  21. package/dist/bundle/chunks/chunk-QBUTRTYN.js +2 -0
  22. package/dist/bundle/chunks/chunk-SUVMF4W5.js +2 -0
  23. package/dist/bundle/chunks/chunk-UFACUBF2.js +16 -0
  24. package/dist/bundle/chunks/chunk-VXO6B72D.js +9 -0
  25. package/dist/bundle/chunks/{chunk-PMDUR6B5.js → chunk-WXASQQBZ.js} +2 -2
  26. package/dist/bundle/chunks/chunk-Y3NLUJYO.js +2 -0
  27. package/dist/bundle/chunks/chunk-Y7QE2R34.js +2 -0
  28. package/dist/bundle/chunks/chunk-YD5VPPI4.js +30 -0
  29. package/dist/bundle/chunks/chunk-YWRWN7ZB.js +82 -0
  30. package/dist/bundle/chunks/{cli-HTUB6WOG.js → cli-4SUT6MJ6.js} +10 -10
  31. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-BJVMNETD.js +2 -0
  32. package/dist/bundle/chunks/{execute-UUPNZJJG.js → execute-ZI7T2SUH.js} +1 -1
  33. package/dist/bundle/chunks/github-copilot.js +1 -1
  34. package/dist/bundle/chunks/{google-generative-ai-A2277FHU.js → google-generative-ai-N5IPPKQY.js} +1 -1
  35. package/dist/bundle/chunks/{google-vertex-2KSVQZQN.js → google-vertex-A4BKUE4H.js} +1 -1
  36. package/dist/bundle/chunks/image-resize-worker.js +1 -1
  37. package/dist/bundle/chunks/kimi-coding.js +1 -1
  38. package/dist/bundle/chunks/{llama-cpp-classify-Y3DUSEM2.js → llama-cpp-classify-L4URPZ4F.js} +1 -1
  39. package/dist/bundle/chunks/meta.js +1 -1
  40. package/dist/bundle/chunks/mistral-conversations-CK2BS74V.js +5 -0
  41. package/dist/bundle/chunks/openai-codex-responses-XGVNKP4D.js +10 -0
  42. package/dist/bundle/chunks/openai-completions-72XZO4Q3.js +7 -0
  43. package/dist/bundle/chunks/{openai-decisions-JRN6M2KB.js → openai-decisions-P5OCXLLD.js} +1 -1
  44. package/dist/bundle/chunks/openai-responses-RGLZ4E3Q.js +4 -0
  45. package/dist/bundle/chunks/{openrouter-images-2XTVCXIC.js → openrouter-images-LSBWMZDK.js} +1 -1
  46. package/dist/bundle/chunks/pi-messages-CL4MEVNS.js +8 -0
  47. package/dist/bundle/chunks/radius.js +1 -1
  48. package/dist/bundle/chunks/{runtime-IB3XQ7E3.js → runtime-F4362CZF.js} +1 -1
  49. package/dist/bundle/chunks/{runtime-LB35PK4J.js → runtime-FJYRBK3O.js} +1 -1
  50. package/dist/bundle/chunks/settings-manager-T6G6KKY3.js +2 -0
  51. package/dist/bundle/chunks/typesafe-system-one-BFYS6AEA.js +2 -0
  52. package/dist/bundle/chunks/virtual-modules-BPZIVXNK.js +2 -0
  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.d.ts.map +1 -1
  57. package/dist/cli/args.js +8 -7
  58. package/dist/cli/args.js.map +1 -1
  59. package/dist/cli/config-selector.d.ts.map +1 -1
  60. package/dist/cli/config-selector.js +3 -1
  61. package/dist/cli/config-selector.js.map +1 -1
  62. package/dist/config.d.ts +10 -0
  63. package/dist/config.d.ts.map +1 -1
  64. package/dist/config.js +24 -5
  65. package/dist/config.js.map +1 -1
  66. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  67. package/dist/core/agent-session-runtime.js +4 -3
  68. package/dist/core/agent-session-runtime.js.map +1 -1
  69. package/dist/core/agent-session.d.ts +16 -1
  70. package/dist/core/agent-session.d.ts.map +1 -1
  71. package/dist/core/agent-session.js +104 -30
  72. package/dist/core/agent-session.js.map +1 -1
  73. package/dist/core/ai-schemas.d.ts +166 -0
  74. package/dist/core/ai-schemas.d.ts.map +1 -0
  75. package/dist/core/ai-schemas.js +21 -0
  76. package/dist/core/ai-schemas.js.map +1 -0
  77. package/dist/core/auth-storage.d.ts.map +1 -1
  78. package/dist/core/auth-storage.js +3 -2
  79. package/dist/core/auth-storage.js.map +1 -1
  80. package/dist/core/bash-executor.d.ts.map +1 -1
  81. package/dist/core/bash-executor.js +3 -1
  82. package/dist/core/bash-executor.js.map +1 -1
  83. package/dist/core/bug-report.d.ts +4 -4
  84. package/dist/core/cache-warmer.d.ts.map +1 -1
  85. package/dist/core/cache-warmer.js +2 -0
  86. package/dist/core/cache-warmer.js.map +1 -1
  87. package/dist/core/compaction/branch-summarization.d.ts +4 -2
  88. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  89. package/dist/core/compaction/branch-summarization.js +16 -4
  90. package/dist/core/compaction/branch-summarization.js.map +1 -1
  91. package/dist/core/exec.d.ts +9 -1
  92. package/dist/core/exec.d.ts.map +1 -1
  93. package/dist/core/exec.js +104 -60
  94. package/dist/core/exec.js.map +1 -1
  95. package/dist/core/export-html/template.css +9 -0
  96. package/dist/core/export-html/template.js +165 -45
  97. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  98. package/dist/core/export-html/tool-renderer.js +3 -0
  99. package/dist/core/export-html/tool-renderer.js.map +1 -1
  100. package/dist/core/extensions/ai-extension-view.d.ts +19 -0
  101. package/dist/core/extensions/ai-extension-view.d.ts.map +1 -0
  102. package/dist/core/extensions/ai-extension-view.js +22 -0
  103. package/dist/core/extensions/ai-extension-view.js.map +1 -0
  104. package/dist/core/extensions/index.d.ts +1 -1
  105. package/dist/core/extensions/index.d.ts.map +1 -1
  106. package/dist/core/extensions/index.js.map +1 -1
  107. package/dist/core/extensions/loader.d.ts.map +1 -1
  108. package/dist/core/extensions/loader.js +15 -9
  109. package/dist/core/extensions/loader.js.map +1 -1
  110. package/dist/core/extensions/runner.d.ts +1 -0
  111. package/dist/core/extensions/runner.d.ts.map +1 -1
  112. package/dist/core/extensions/runner.js +9 -1
  113. package/dist/core/extensions/runner.js.map +1 -1
  114. package/dist/core/extensions/types.d.ts +55 -11
  115. package/dist/core/extensions/types.d.ts.map +1 -1
  116. package/dist/core/extensions/types.js.map +1 -1
  117. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  118. package/dist/core/extensions/virtual-modules.js +6 -5
  119. package/dist/core/extensions/virtual-modules.js.map +1 -1
  120. package/dist/core/keybindings.d.ts +2 -2
  121. package/dist/core/keybindings.js +1 -1
  122. package/dist/core/keybindings.js.map +1 -1
  123. package/dist/core/mcp-servers.d.ts +21 -38
  124. package/dist/core/mcp-servers.d.ts.map +1 -1
  125. package/dist/core/mcp-servers.js +58 -134
  126. package/dist/core/mcp-servers.js.map +1 -1
  127. package/dist/core/model-config.d.ts +1717 -1990
  128. package/dist/core/model-config.d.ts.map +1 -1
  129. package/dist/core/model-config.js +2 -3
  130. package/dist/core/model-config.js.map +1 -1
  131. package/dist/core/model-resolver.d.ts.map +1 -1
  132. package/dist/core/model-resolver.js +16 -9
  133. package/dist/core/model-resolver.js.map +1 -1
  134. package/dist/core/model-runtime.d.ts.map +1 -1
  135. package/dist/core/model-runtime.js +4 -4
  136. package/dist/core/model-runtime.js.map +1 -1
  137. package/dist/core/package-manager.d.ts +24 -1
  138. package/dist/core/package-manager.d.ts.map +1 -1
  139. package/dist/core/package-manager.js +215 -52
  140. package/dist/core/package-manager.js.map +1 -1
  141. package/dist/core/pi-manifest.d.ts +1 -0
  142. package/dist/core/pi-manifest.d.ts.map +1 -1
  143. package/dist/core/pi-manifest.js +3 -0
  144. package/dist/core/pi-manifest.js.map +1 -1
  145. package/dist/core/project-trust.js +1 -1
  146. package/dist/core/project-trust.js.map +1 -1
  147. package/dist/core/provider-composer.d.ts +2 -1
  148. package/dist/core/provider-composer.d.ts.map +1 -1
  149. package/dist/core/provider-composer.js +8 -4
  150. package/dist/core/provider-composer.js.map +1 -1
  151. package/dist/core/resource-loader.d.ts +4 -1
  152. package/dist/core/resource-loader.d.ts.map +1 -1
  153. package/dist/core/resource-loader.js +38 -23
  154. package/dist/core/resource-loader.js.map +1 -1
  155. package/dist/core/sdk.d.ts.map +1 -1
  156. package/dist/core/sdk.js +3 -1
  157. package/dist/core/sdk.js.map +1 -1
  158. package/dist/core/session-manager.d.ts +7 -0
  159. package/dist/core/session-manager.d.ts.map +1 -1
  160. package/dist/core/session-manager.js +32 -13
  161. package/dist/core/session-manager.js.map +1 -1
  162. package/dist/core/settings-manager.d.ts +2 -0
  163. package/dist/core/settings-manager.d.ts.map +1 -1
  164. package/dist/core/settings-manager.js +11 -0
  165. package/dist/core/settings-manager.js.map +1 -1
  166. package/dist/core/settings-schema.d.ts +4 -2
  167. package/dist/core/settings-schema.d.ts.map +1 -1
  168. package/dist/core/settings-schema.js +8 -1
  169. package/dist/core/settings-schema.js.map +1 -1
  170. package/dist/core/skills.d.ts.map +1 -1
  171. package/dist/core/skills.js +6 -15
  172. package/dist/core/skills.js.map +1 -1
  173. package/dist/core/slash-commands.js +2 -2
  174. package/dist/core/slash-commands.js.map +1 -1
  175. package/dist/core/source-info.d.ts +9 -0
  176. package/dist/core/source-info.d.ts.map +1 -1
  177. package/dist/core/source-info.js +14 -0
  178. package/dist/core/source-info.js.map +1 -1
  179. package/dist/core/system-prompt.d.ts.map +1 -1
  180. package/dist/core/system-prompt.js +5 -6
  181. package/dist/core/system-prompt.js.map +1 -1
  182. package/dist/core/tools/bash.d.ts +2 -2
  183. package/dist/core/tools/bash.d.ts.map +1 -1
  184. package/dist/core/tools/bash.js.map +1 -1
  185. package/dist/core/tools/edit.d.ts +3 -3
  186. package/dist/core/tools/edit.d.ts.map +1 -1
  187. package/dist/core/tools/edit.js +2 -4
  188. package/dist/core/tools/edit.js.map +1 -1
  189. package/dist/core/tools/find.d.ts +2 -2
  190. package/dist/core/tools/find.d.ts.map +1 -1
  191. package/dist/core/tools/find.js +41 -25
  192. package/dist/core/tools/find.js.map +1 -1
  193. package/dist/core/tools/grep.d.ts +4 -5
  194. package/dist/core/tools/grep.d.ts.map +1 -1
  195. package/dist/core/tools/grep.js +73 -70
  196. package/dist/core/tools/grep.js.map +1 -1
  197. package/dist/core/tools/ls.d.ts +2 -2
  198. package/dist/core/tools/ls.d.ts.map +1 -1
  199. package/dist/core/tools/ls.js +2 -1
  200. package/dist/core/tools/ls.js.map +1 -1
  201. package/dist/core/tools/read.d.ts +2 -2
  202. package/dist/core/tools/read.d.ts.map +1 -1
  203. package/dist/core/tools/read.js.map +1 -1
  204. package/dist/core/tools/render-utils.d.ts.map +1 -1
  205. package/dist/core/tools/render-utils.js +2 -7
  206. package/dist/core/tools/render-utils.js.map +1 -1
  207. package/dist/core/tools/renderers/write.d.ts.map +1 -1
  208. package/dist/core/tools/renderers/write.js +19 -19
  209. package/dist/core/tools/renderers/write.js.map +1 -1
  210. package/dist/core/tools/tool-definition-wrapper.d.ts +11 -1
  211. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  212. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  213. package/dist/core/tools/truncate.d.ts +0 -14
  214. package/dist/core/tools/truncate.d.ts.map +1 -1
  215. package/dist/core/tools/truncate.js +0 -29
  216. package/dist/core/tools/truncate.js.map +1 -1
  217. package/dist/core/tools/write.d.ts +2 -2
  218. package/dist/core/tools/write.d.ts.map +1 -1
  219. package/dist/core/tools/write.js.map +1 -1
  220. package/dist/core/trust-manager.d.ts.map +1 -1
  221. package/dist/core/trust-manager.js +15 -8
  222. package/dist/core/trust-manager.js.map +1 -1
  223. package/dist/core/usage-totals.d.ts.map +1 -1
  224. package/dist/core/usage-totals.js +2 -0
  225. package/dist/core/usage-totals.js.map +1 -1
  226. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  227. package/dist/extensions/codemode/renderer.js +6 -2
  228. package/dist/extensions/codemode/renderer.js.map +1 -1
  229. package/dist/extensions/codemode/tool.d.ts +2 -1
  230. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  231. package/dist/extensions/codemode/tool.js +33 -8
  232. package/dist/extensions/codemode/tool.js.map +1 -1
  233. package/dist/extensions/llama/client.d.ts +2 -0
  234. package/dist/extensions/llama/client.d.ts.map +1 -1
  235. package/dist/extensions/llama/client.js +23 -2
  236. package/dist/extensions/llama/client.js.map +1 -1
  237. package/dist/extensions/llama/ui.d.ts.map +1 -1
  238. package/dist/extensions/llama/ui.js +16 -4
  239. package/dist/extensions/llama/ui.js.map +1 -1
  240. package/dist/extensions/mcp/cli.d.ts +2 -0
  241. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  242. package/dist/extensions/mcp/cli.js +72 -15
  243. package/dist/extensions/mcp/cli.js.map +1 -1
  244. package/dist/extensions/mcp/config.d.ts.map +1 -1
  245. package/dist/extensions/mcp/config.js +4 -7
  246. package/dist/extensions/mcp/config.js.map +1 -1
  247. package/dist/extensions/mcp/index.d.ts.map +1 -1
  248. package/dist/extensions/mcp/index.js +2 -2
  249. package/dist/extensions/mcp/index.js.map +1 -1
  250. package/dist/extensions/mcp/oauth.d.ts +13 -50
  251. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  252. package/dist/extensions/mcp/oauth.js +53 -319
  253. package/dist/extensions/mcp/oauth.js.map +1 -1
  254. package/dist/extensions/mcp/resources.d.ts +1 -1
  255. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  256. package/dist/extensions/mcp/resources.js +4 -3
  257. package/dist/extensions/mcp/resources.js.map +1 -1
  258. package/dist/extensions/mcp/runtime.d.ts +4 -3
  259. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  260. package/dist/extensions/mcp/runtime.js +4 -3
  261. package/dist/extensions/mcp/runtime.js.map +1 -1
  262. package/dist/extensions/mcp/tools.d.ts +2 -23
  263. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  264. package/dist/extensions/mcp/tools.js +6 -58
  265. package/dist/extensions/mcp/tools.js.map +1 -1
  266. package/dist/extensions/mcp/ui.d.ts +1 -0
  267. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  268. package/dist/extensions/mcp/ui.js +33 -24
  269. package/dist/extensions/mcp/ui.js.map +1 -1
  270. package/dist/extensions/tool-search/tool.d.ts +21 -6
  271. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  272. package/dist/extensions/tool-search/tool.js +104 -36
  273. package/dist/extensions/tool-search/tool.js.map +1 -1
  274. package/dist/index.d.ts +2 -2
  275. package/dist/index.d.ts.map +1 -1
  276. package/dist/index.js.map +1 -1
  277. package/dist/main.d.ts.map +1 -1
  278. package/dist/main.js +16 -8
  279. package/dist/main.js.map +1 -1
  280. package/dist/modes/interactive/components/assistant-message.d.ts +4 -1
  281. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  282. package/dist/modes/interactive/components/assistant-message.js +44 -20
  283. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  284. package/dist/modes/interactive/components/branch-summary-message.d.ts +5 -1
  285. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  286. package/dist/modes/interactive/components/branch-summary-message.js +12 -4
  287. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  288. package/dist/modes/interactive/components/compaction-summary-message.d.ts +5 -1
  289. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  290. package/dist/modes/interactive/components/compaction-summary-message.js +12 -4
  291. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  292. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  293. package/dist/modes/interactive/components/config-selector.js +4 -18
  294. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  295. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  296. package/dist/modes/interactive/components/custom-editor.js +7 -0
  297. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  298. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
  299. package/dist/modes/interactive/components/custom-entry.js +2 -1
  300. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  301. package/dist/modes/interactive/components/custom-message.d.ts +5 -2
  302. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  303. package/dist/modes/interactive/components/custom-message.js +12 -4
  304. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  305. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  306. package/dist/modes/interactive/components/diff.js +11 -5
  307. package/dist/modes/interactive/components/diff.js.map +1 -1
  308. package/dist/modes/interactive/components/extension-editor.d.ts +2 -0
  309. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  310. package/dist/modes/interactive/components/extension-editor.js +4 -0
  311. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  312. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  313. package/dist/modes/interactive/components/extension-selector.js +9 -1
  314. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  315. package/dist/modes/interactive/components/login-dialog.d.ts +5 -0
  316. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  317. package/dist/modes/interactive/components/login-dialog.js +104 -10
  318. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  319. package/dist/modes/interactive/components/markdown-transform.d.ts +2 -1
  320. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -1
  321. package/dist/modes/interactive/components/markdown-transform.js +3 -2
  322. package/dist/modes/interactive/components/markdown-transform.js.map +1 -1
  323. package/dist/modes/interactive/components/mermaid.d.ts +2 -1
  324. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  325. package/dist/modes/interactive/components/mermaid.js +25 -20
  326. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  327. package/dist/modes/interactive/components/model-selector.d.ts +1 -0
  328. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  329. package/dist/modes/interactive/components/model-selector.js +17 -6
  330. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  331. package/dist/modes/interactive/components/oauth-selector.d.ts +1 -0
  332. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  333. package/dist/modes/interactive/components/oauth-selector.js +13 -4
  334. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  335. package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -0
  336. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  337. package/dist/modes/interactive/components/scoped-models-selector.js +14 -3
  338. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  339. package/dist/modes/interactive/components/session-selector-search.d.ts +4 -0
  340. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  341. package/dist/modes/interactive/components/session-selector-search.js +86 -22
  342. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  343. package/dist/modes/interactive/components/session-selector.d.ts +2 -1
  344. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  345. package/dist/modes/interactive/components/session-selector.js +20 -27
  346. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  347. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  348. package/dist/modes/interactive/components/settings-submenu.js +2 -0
  349. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  350. package/dist/modes/interactive/components/skill-invocation-message.d.ts +5 -1
  351. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  352. package/dist/modes/interactive/components/skill-invocation-message.js +12 -4
  353. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  354. package/dist/modes/interactive/components/tool-execution.d.ts +6 -0
  355. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  356. package/dist/modes/interactive/components/tool-execution.js +14 -2
  357. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  358. package/dist/modes/interactive/components/tree-selector.d.ts +2 -0
  359. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  360. package/dist/modes/interactive/components/tree-selector.js +24 -16
  361. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  362. package/dist/modes/interactive/components/user-message-selector.d.ts +1 -0
  363. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  364. package/dist/modes/interactive/components/user-message-selector.js +9 -1
  365. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  366. package/dist/modes/interactive/components/user-message.d.ts +3 -1
  367. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  368. package/dist/modes/interactive/components/user-message.js +6 -2
  369. package/dist/modes/interactive/components/user-message.js.map +1 -1
  370. package/dist/modes/interactive/external-editor.d.ts +1 -0
  371. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  372. package/dist/modes/interactive/external-editor.js +16 -4
  373. package/dist/modes/interactive/external-editor.js.map +1 -1
  374. package/dist/modes/interactive/interactive-mode.d.ts +7 -0
  375. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  376. package/dist/modes/interactive/interactive-mode.js +179 -53
  377. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  378. package/dist/modes/interactive/model-search.d.ts +10 -0
  379. package/dist/modes/interactive/model-search.d.ts.map +1 -1
  380. package/dist/modes/interactive/model-search.js +21 -0
  381. package/dist/modes/interactive/model-search.js.map +1 -1
  382. package/dist/modes/interactive/theme/theme.d.ts +10 -0
  383. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  384. package/dist/modes/interactive/theme/theme.js +35 -23
  385. package/dist/modes/interactive/theme/theme.js.map +1 -1
  386. package/dist/modes/print-mode.d.ts.map +1 -1
  387. package/dist/modes/print-mode.js +19 -10
  388. package/dist/modes/print-mode.js.map +1 -1
  389. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  390. package/dist/modes/rpc/rpc-mode.js +53 -23
  391. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  392. package/dist/package-manager-cli.d.ts.map +1 -1
  393. package/dist/package-manager-cli.js +78 -9
  394. package/dist/package-manager-cli.js.map +1 -1
  395. package/dist/utils/ansi.d.ts.map +1 -1
  396. package/dist/utils/ansi.js +5 -2
  397. package/dist/utils/ansi.js.map +1 -1
  398. package/dist/utils/changelog.d.ts +2 -2
  399. package/dist/utils/changelog.d.ts.map +1 -1
  400. package/dist/utils/changelog.js +15 -2
  401. package/dist/utils/changelog.js.map +1 -1
  402. package/dist/utils/clipboard-command.d.ts.map +1 -1
  403. package/dist/utils/clipboard-command.js +4 -0
  404. package/dist/utils/clipboard-command.js.map +1 -1
  405. package/dist/utils/git.d.ts +1 -1
  406. package/dist/utils/git.d.ts.map +1 -1
  407. package/dist/utils/git.js.map +1 -1
  408. package/dist/utils/image-resize-core.d.ts.map +1 -1
  409. package/dist/utils/image-resize-core.js +5 -3
  410. package/dist/utils/image-resize-core.js.map +1 -1
  411. package/dist/utils/open-browser.d.ts.map +1 -1
  412. package/dist/utils/open-browser.js +4 -1
  413. package/dist/utils/open-browser.js.map +1 -1
  414. package/dist/utils/paths.d.ts +17 -0
  415. package/dist/utils/paths.d.ts.map +1 -1
  416. package/dist/utils/paths.js +42 -1
  417. package/dist/utils/paths.js.map +1 -1
  418. package/dist/utils/shell.d.ts.map +1 -1
  419. package/dist/utils/shell.js +14 -0
  420. package/dist/utils/shell.js.map +1 -1
  421. package/dist/utils/syntax-highlight.d.ts +5 -0
  422. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  423. package/dist/utils/syntax-highlight.js +7 -0
  424. package/dist/utils/syntax-highlight.js.map +1 -1
  425. package/dist/utils/tools-manager.d.ts.map +1 -1
  426. package/dist/utils/tools-manager.js +30 -35
  427. package/dist/utils/tools-manager.js.map +1 -1
  428. package/docs/cli.md +22 -10
  429. package/docs/custom-provider.md +2 -0
  430. package/docs/environment-variables.md +2 -0
  431. package/docs/extensions.md +3201 -233
  432. package/docs/keybindings.md +2 -2
  433. package/docs/llama-cpp.md +23 -15
  434. package/docs/message-types.md +1 -1
  435. package/docs/models-configuration.md +17 -4
  436. package/docs/models.md +9 -4
  437. package/docs/packages.md +24 -0
  438. package/docs/providers.md +1 -1
  439. package/docs/rpc.md +3 -1
  440. package/docs/sessions.md +11 -3
  441. package/docs/settings.md +5 -4
  442. package/docs/slash-commands.md +3 -2
  443. package/docs/terminal-setup.md +3 -1
  444. package/docs/tmux.md +6 -0
  445. package/docs/tui.md +2 -0
  446. package/docs/windows.md +27 -0
  447. package/eval/drahtbank/isolated-tools.ts +0 -1
  448. package/examples/extensions/antigravity-image-gen.ts +1 -1
  449. package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  450. package/examples/extensions/debug-provider.ts +2 -2
  451. package/examples/extensions/gondolin/package.json +1 -1
  452. package/examples/extensions/plan-mode/index.ts +23 -13
  453. package/examples/extensions/plan-mode/utils.ts +42 -16
  454. package/examples/extensions/preset.ts +2 -0
  455. package/examples/extensions/reload-runtime.ts +17 -5
  456. package/examples/extensions/sandbox/package-lock.json +15 -41
  457. package/examples/extensions/sandbox/package.json +1 -1
  458. package/examples/extensions/subagent/index.ts +388 -171
  459. package/examples/extensions/todo.ts +7 -0
  460. package/examples/extensions/tools.ts +2 -0
  461. package/examples/tsconfig.json +188 -0
  462. package/package.json +15 -16
  463. package/schemas/models.schema.json +85 -39
  464. package/schemas/settings.schema.json +17 -0
  465. package/dist/bundle/chunks/anthropic-messages-CZYDBUW7.js +0 -6
  466. package/dist/bundle/chunks/azure-openai-responses-UKM4K3L6.js +0 -2
  467. package/dist/bundle/chunks/chunk-2TZWVGCR.js +0 -2
  468. package/dist/bundle/chunks/chunk-76YNMQ57.js +0 -2
  469. package/dist/bundle/chunks/chunk-AS6DCLAM.js +0 -1428
  470. package/dist/bundle/chunks/chunk-BL72B6LV.js +0 -82
  471. package/dist/bundle/chunks/chunk-C2XCXA6V.js +0 -2
  472. package/dist/bundle/chunks/chunk-CLKG6K6Z.js +0 -7
  473. package/dist/bundle/chunks/chunk-FOYIPAAD.js +0 -6
  474. package/dist/bundle/chunks/chunk-FXCTQRNN.js +0 -2
  475. package/dist/bundle/chunks/chunk-H5BLLINF.js +0 -11
  476. package/dist/bundle/chunks/chunk-IT4RIOZD.js +0 -2
  477. package/dist/bundle/chunks/chunk-N3FZGIII.js +0 -16
  478. package/dist/bundle/chunks/chunk-OCUU7HYF.js +0 -2
  479. package/dist/bundle/chunks/chunk-QMN7OD6G.js +0 -2
  480. package/dist/bundle/chunks/chunk-UCJ7FLSO.js +0 -166
  481. package/dist/bundle/chunks/chunk-WFHH5SX6.js +0 -4
  482. package/dist/bundle/chunks/chunk-WYWBXNDO.js +0 -6
  483. package/dist/bundle/chunks/chunk-XOGEYN4Q.js +0 -2
  484. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-V37VPUK4.js +0 -2
  485. package/dist/bundle/chunks/mistral-conversations-R2NJADHS.js +0 -5
  486. package/dist/bundle/chunks/openai-codex-responses-KJZDJELP.js +0 -10
  487. package/dist/bundle/chunks/openai-completions-RTWADJBP.js +0 -7
  488. package/dist/bundle/chunks/openai-responses-B7ASLN2Z.js +0 -4
  489. package/dist/bundle/chunks/pi-messages-7TX4RC24.js +0 -8
  490. package/dist/bundle/chunks/settings-manager-YNY5F4RU.js +0 -2
  491. package/dist/bundle/chunks/typesafe-system-one-7BNMQFXE.js +0 -2
  492. package/dist/bundle/chunks/virtual-modules-OFCQ5AEG.js +0 -2
@@ -1,65 +1,325 @@
1
+ > draht can create extensions. Ask it to build one for your use case.
2
+
1
3
  # Extensions
2
4
 
3
- Extensions are TypeScript modules that add executable behavior to draht. Use one when a workflow needs tools, commands, event handlers, model providers, session state, or terminal UI rather than instructions alone.
5
+ Extensions are TypeScript modules that extend draht's behavior. They can subscribe to lifecycle events, register custom tools callable by the LLM, add commands, and more.
4
6
 
5
7
  An extension runs inside the draht process with the same operating-system permissions. It can inspect prompts, tool calls, files, credentials, and session history, so load extensions only from sources you trust.
6
8
 
7
- Typical extensions add an agent tool, protect paths, confirm dangerous commands, react to session events, modify context, expose a command, or display persistent status.
9
+ > **Placement for /reload:** Put extensions in `~/.draht/agent/extensions/` (global) or `.draht/extensions/` (project-local) for auto-discovery. Use `draht -e ./path.ts` only for quick tests. Extensions in auto-discovered locations can be hot-reloaded with `/reload`.
10
+
11
+ **Key capabilities:**
12
+ - **Custom tools** - Register tools the LLM can call via `pi.registerTool()`
13
+ - **Event interception** - Block or modify tool calls, inject context, customize compaction
14
+ - **User interaction** - Prompt users via `ctx.ui` (select, confirm, input, notify)
15
+ - **Custom UI components** - Full TUI components with keyboard input via `ctx.ui.custom()` for complex interactions
16
+ - **Custom commands** - Register commands like `/mycommand` via `pi.registerCommand()`
17
+ - **Session persistence** - Store state that survives restarts via `pi.appendEntry()`
18
+ - **Custom rendering** - Control how tool calls/results and messages appear in TUI
19
+ - **Providers and MCP servers** - Register model providers, virtual models, and MCP servers
20
+
21
+ **Example use cases:**
22
+ - Permission gates (confirm before `rm -rf`, `sudo`, etc.)
23
+ - Git checkpointing (stash at each turn, restore on branch)
24
+ - Path protection (block writes to `.env`, `node_modules/`)
25
+ - Custom compaction (summarize conversation your way)
26
+ - Conversation summaries (see `summarize.ts` example)
27
+ - Interactive tools (questions, wizards, custom dialogs)
28
+ - Stateful tools (todo lists, connection pools)
29
+ - External integrations (file watchers, webhooks, CI triggers)
30
+ - Games while you wait (see `snake.ts` example)
31
+
32
+ See [examples/extensions/](../examples/extensions/) for working implementations.
33
+
34
+ ## Table of Contents
35
+
36
+ - [Quick Start](#quick-start)
37
+ - [Extension Locations](#extension-locations)
38
+ - [Available Imports](#available-imports)
39
+ - [Writing an Extension](#writing-an-extension)
40
+ - [Extension Styles](#extension-styles)
41
+ - [Events](#events)
42
+ - [Lifecycle Overview](#lifecycle-overview)
43
+ - [Handler Composition](#handler-composition)
44
+ - [Startup Events](#startup-events)
45
+ - [Resource Events](#resource-events)
46
+ - [Session Events](#session-events)
47
+ - [Agent Events](#agent-events)
48
+ - [Model Events](#model-events)
49
+ - [Tool Events](#tool-events)
50
+ - [User Bash Events](#user-bash-events)
51
+ - [Input Events](#input-events)
52
+ - [ExtensionContext](#extensioncontext)
53
+ - [ExtensionCommandContext](#extensioncommandcontext)
54
+ - [ExtensionAPI Methods](#extensionapi-methods)
55
+ - [State Management](#state-management)
56
+ - [Custom Tools](#custom-tools)
57
+ - [Tool Exposure](#tool-exposure)
58
+ - [Calling Other Tools](#calling-other-tools)
59
+ - [Dynamic Tool Loading](#dynamic-tool-loading)
60
+ - [MCP Servers](#mcp-servers)
61
+ - [Custom UI](#custom-ui)
62
+ - [Error Handling](#error-handling)
63
+ - [Mode Behavior](#mode-behavior)
64
+ - [Examples Reference](#examples-reference)
8
65
 
9
- <a id="quick-start"></a>
10
- <a id="writing-an-extension"></a>
11
66
  <a id="create-an-extension"></a>
12
67
 
13
- ## Create and load an extension
14
-
15
- An extension exports a default factory that receives `ExtensionAPI`. The factory registers capabilities for the current extension runtime.
68
+ ## Quick Start
16
69
 
17
- Create `~/.draht/agent/extensions/hello.ts`:
70
+ Create `~/.draht/agent/extensions/my-extension.ts`:
18
71
 
19
72
  ```typescript
20
- import type { ExtensionAPI } from "@draht/coding-agent";
73
+ import { type ExtensionAPI, isToolCallEventType } from "@draht/coding-agent";
74
+ import { Type } from "typebox";
21
75
 
22
76
  export default function (pi: ExtensionAPI) {
77
+ // React to events
78
+ pi.on("session_start", async (_event, ctx) => {
79
+ ctx.ui.notify("Extension loaded!", "info");
80
+ });
81
+
82
+ pi.on("tool_call", async (event, ctx) => {
83
+ if (isToolCallEventType("bash", event) && event.input.command.includes("rm -rf")) {
84
+ const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?");
85
+ if (!ok) return { block: true, reason: "Blocked by user" };
86
+ }
87
+ });
88
+
89
+ // Register a custom tool
90
+ pi.registerTool({
91
+ name: "greet",
92
+ label: "Greet",
93
+ description: "Greet someone by name",
94
+ parameters: Type.Object({
95
+ name: Type.String({ description: "Name to greet" }),
96
+ }),
97
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
98
+ return {
99
+ content: [{ type: "text", text: `Hello, ${params.name}!` }],
100
+ details: {},
101
+ };
102
+ },
103
+ });
104
+
105
+ // Register a command
23
106
  pi.registerCommand("hello", {
24
- description: "Show a greeting",
25
- handler: async (name, ctx) => {
26
- ctx.ui.notify(`Hello, ${name || "world"}!`, "info");
107
+ description: "Say hello",
108
+ handler: async (args, ctx) => {
109
+ ctx.ui.notify(`Hello ${args || "world"}!`, "info");
27
110
  },
28
111
  });
29
112
  }
30
113
  ```
31
114
 
32
- Start draht and run `/hello`. During development, load a file directly:
115
+ Test with `--extension` (or `-e`) flag:
33
116
 
34
117
  ```bash
35
- draht --extension ./hello.ts
118
+ draht -e ./my-extension.ts
36
119
  ```
37
120
 
38
- draht uses `jiti`, so local TypeScript extensions do not need a separate compilation step. Use [draht packages](packages.md) for distributed extensions and dependencies.
39
-
40
- <a id="extension-locations"></a>
41
- <a id="available-imports"></a>
42
121
  <a id="choose-where-it-loads"></a>
43
122
 
44
- ## Add it to draht
123
+ ## Extension Locations
124
+
125
+ > **Security:** Extensions run with your full system permissions and can execute arbitrary code. Only install from sources you trust.
126
+
127
+ Extensions are auto-discovered from trusted locations. Project-local `.draht/extensions` entries load only after the project is trusted.
128
+
129
+ | Location | Scope |
130
+ |----------|-------|
131
+ | `~/.draht/agent/extensions/*.ts` or `*.js` | Global (all projects) |
132
+ | `~/.draht/agent/extensions/*/index.ts` or `index.js` | Global (subdirectory) |
133
+ | `~/.draht/agent/extensions/*/package.json` with a `draht.extensions` field | Global (subdirectory with manifest) |
134
+ | `.draht/extensions/...` | Project-local, same layouts |
135
+
136
+ Discovery goes one level deep. Larger packages declare their entry points in a `package.json` manifest.
137
+
138
+ Additional paths via `settings.json`:
139
+
140
+ ```json
141
+ {
142
+ "packages": [
143
+ "npm:@foo/bar@1.0.0",
144
+ "git:github.com/user/repo@v1"
145
+ ],
146
+ "extensions": [
147
+ "/path/to/local/extension.ts",
148
+ "/path/to/local/extension/dir"
149
+ ]
150
+ }
151
+ ```
152
+
153
+ Settings also accept built-in extensions as `builtin:<name>` entries; see [Settings](settings.md#resources). To share extensions via npm or git as draht packages, see [packages.md](packages.md).
154
+
155
+ ## Available Imports
156
+
157
+ | Package | Purpose |
158
+ |---------|---------|
159
+ | `@draht/coding-agent` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) and helpers |
160
+ | `@draht/agent-core` | Agent message and tool types |
161
+ | `typebox`, `typebox/compile`, `typebox/value` | Schema definitions for tool parameters |
162
+ | `@draht/ai` | AI utilities (`StringEnum` for string enums, transcript helpers, model types). Inside draht it also exports TypeBox's `Type`, `Static` and `TSchema`, which the published package no longer re-exports; import them from `typebox` in new code |
163
+ | `@draht/ai/compat`, `/models`, `/oauth`, `/providers/all` | Provider construction, built-in APIs, and OAuth helpers |
164
+ | `@draht/tui` | TUI components for custom rendering |
165
+
166
+ draht maps these imports to its own copies, so extensions share draht's classes and registries. The legacy `@sinclair/typebox` name maps to the same module.
167
+
168
+ npm dependencies work too. Add a `package.json` next to your extension (or in a parent directory), run `npm install`, and imports from `node_modules/` are resolved automatically.
169
+
170
+ For distributed draht packages installed with `draht install` (npm or git), runtime deps must be in `dependencies`; `devDependencies` are not installed. Do not list the host-provided packages above in `dependencies`. See [Declare dependencies](packages.md#declare-dependencies).
171
+
172
+ ### Tool parameter schemas and TypeBox
173
+
174
+ draht validates tool arguments as JSON Schema with `@draht/schema`, whatever built the schema; TypeBox schemas are JSON Schema and work unchanged. Before validation, loosely typed arguments are coerced: numeric strings to numbers, `"true"` to `true`, a single value to a one-item array, `null` in an optional property dropped. TypeBox features outside JSON Schema do not apply to tool arguments:
175
+
176
+ - `Type.Refine()` refinements are not run. Check such constraints in `execute()`.
177
+ - `Type.BigInt()`, `Type.Undefined()` and `Type.Void()` reject every argument, since JSON has no such values. Codecs (`Type.Codec()`) do not decode: `execute()` receives the JSON value.
178
+ - Formats registered with TypeBox's `Format.Set()` are not checked. The standard formats are, plus `url` and `json-pointer-uri-fragment`.
179
+ - Property names are matched as names, not as regular expressions, and `additionalProperties` applies only to properties the object does not declare.
180
+ - A `$ref` that names nothing rejects only arguments at its place.
181
+
182
+ Validation errors the model sees use `@draht/schema`'s messages, such as `- path: missing` or `- limit: expected number, got string`.
183
+
184
+ Node.js built-ins (`node:fs`, `node:path`, etc.) are also available.
185
+
186
+ ## Writing an Extension
187
+
188
+ An extension exports a default factory function that receives `ExtensionAPI`. The factory can be synchronous or asynchronous:
189
+
190
+ ```typescript
191
+ import type { ExtensionAPI } from "@draht/coding-agent";
192
+
193
+ export default function (pi: ExtensionAPI) {
194
+ // Subscribe to events
195
+ pi.on("event_name", async (event, ctx) => {
196
+ // ctx.ui for user interaction
197
+ const ok = await ctx.ui.confirm("Title", "Are you sure?");
198
+ ctx.ui.notify("Done!", "info");
199
+ ctx.ui.setStatus("my-ext", "Processing..."); // Footer status
200
+ ctx.ui.setWidget("my-ext", ["Line 1", "Line 2"]); // Widget above editor (default)
201
+ });
202
+
203
+ // Register tools, commands, shortcuts, flags
204
+ pi.registerTool({ ... });
205
+ pi.registerCommand("name", { ... });
206
+ pi.registerShortcut("ctrl+x", { ... });
207
+ pi.registerFlag("my-flag", { ... });
208
+ }
209
+ ```
210
+
211
+ Extensions are loaded via [jiti](https://github.com/unjs/jiti), so TypeScript works without compilation.
212
+
213
+ If the factory returns a `Promise`, draht awaits it before continuing startup. That means async initialization completes before `session_start`, before `resources_discover`, and before provider registrations queued via `pi.registerProvider()` are flushed.
214
+
215
+ ### Async factory functions
216
+
217
+ Use an async factory for one-time startup work such as fetching remote configuration or dynamically discovering available models.
218
+
219
+ ```typescript
220
+ import type { ExtensionAPI } from "@draht/coding-agent";
221
+
222
+ export default async function (pi: ExtensionAPI) {
223
+ const response = await fetch("http://localhost:1234/v1/models");
224
+ const payload = (await response.json()) as {
225
+ data: Array<{
226
+ id: string;
227
+ name?: string;
228
+ context_window?: number;
229
+ max_tokens?: number;
230
+ }>;
231
+ };
232
+
233
+ pi.registerProvider("local-openai", {
234
+ baseUrl: "http://localhost:1234/v1",
235
+ apiKey: "$LOCAL_OPENAI_API_KEY",
236
+ api: "openai-completions",
237
+ models: payload.data.map((model) => ({
238
+ id: model.id,
239
+ name: model.name ?? model.id,
240
+ reasoning: false,
241
+ input: ["text"],
242
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
243
+ contextWindow: model.context_window ?? 128000,
244
+ maxTokens: model.max_tokens ?? 4096,
245
+ })),
246
+ });
247
+ }
248
+ ```
249
+
250
+ This pattern makes the fetched models available during normal startup and to `draht --list-models`. For model lists that change while draht runs, implement `refreshModels` instead; see [pi.registerProvider()](#piregisterprovidername-config).
251
+
252
+ ### Long-lived resources and shutdown
253
+
254
+ Extension factories may run in invocations that never start a session. Do not start background resources such as processes, sockets, file watchers, or timers from the factory.
255
+
256
+ Defer background resource startup until `session_start` or the command/tool/event that needs the resource. Register an idempotent `session_shutdown` handler to close any session-scoped resources you start.
257
+
258
+ ### Extension Styles
259
+
260
+ **Single file** - simplest, for small extensions:
261
+
262
+ ```
263
+ ~/.draht/agent/extensions/
264
+ └── my-extension.ts
265
+ ```
266
+
267
+ **Directory with index.ts** - for multi-file extensions:
268
+
269
+ ```
270
+ ~/.draht/agent/extensions/
271
+ └── my-extension/
272
+ ├── index.ts # Entry point (exports default function)
273
+ ├── tools.ts # Helper module
274
+ └── utils.ts # Helper module
275
+ ```
276
+
277
+ **Package with dependencies** - for extensions that need npm packages:
278
+
279
+ ```
280
+ ~/.draht/agent/extensions/
281
+ └── my-extension/
282
+ ├── package.json # Declares dependencies and entry points
283
+ ├── package-lock.json
284
+ ├── node_modules/ # After npm install
285
+ └── src/
286
+ └── index.ts
287
+ ```
288
+
289
+ ```json
290
+ // package.json
291
+ {
292
+ "name": "my-extension",
293
+ "dependencies": {
294
+ "zod": "^3.0.0",
295
+ "chalk": "^5.0.0"
296
+ },
297
+ "draht": {
298
+ "extensions": ["./src/index.ts"]
299
+ }
300
+ }
301
+ ```
302
+
303
+ draht falls back to the `pi` key when `package.json` has no `draht` key, so extension packages written for pi work unchanged.
45
304
 
46
- Place the extension in your user or project extensions directory. draht loads direct TypeScript or JavaScript files and subdirectories containing an `index.ts` or `index.js` entry point.
305
+ Run `npm install` in the extension directory, then imports from `node_modules/` work automatically.
47
306
 
48
- Use a single file for a small extension and a directory for a multi-file implementation. Put npm dependencies in a nearby `package.json`. A package declares its extensions under the `draht` key in `package.json`; draht falls back to the `pi` key, so extension packages written for pi work unchanged. See [Configuration](configuration.md) for conventional locations and [Settings](settings.md#resources) for additional paths.
307
+ <a id="extension-events"></a>
49
308
 
50
- Reload replaces the extension runtime, so code after `await ctx.reload()` must not reuse state from the old runtime. Only personal and explicit command-line extensions can participate in the `project_trust` event that runs before project extensions load.
309
+ ## Events
51
310
 
52
311
  <a id="understand-the-lifecycle"></a>
53
312
 
54
- ## Understand the runtime lifecycle
313
+ ### Lifecycle Overview
55
314
 
56
- The factory can be synchronous or asynchronous. draht waits for an asynchronous factory before startup continues, allowing it to fetch configuration or register providers needed during startup.
315
+ A prompt starts a run. Input handling comes first:
57
316
 
58
- Do not start processes, sockets, watchers, or timers in the factory because some invocations load extensions without starting a session.
59
- Start long-lived resources from `session_start` or from the command or tool that needs them.
60
- Close session-scoped resources from an idempotent `session_shutdown` handler.
317
+ 1. Extension commands (`/name`) run their handler. The `input` event does not fire. Typed and RPC prompts always check for commands; `pi.sendUserMessage()` checks only with `expandPromptTemplates: true`.
318
+ 2. `input` handlers can intercept, transform, or handle the text.
319
+ 3. Skill commands (`/skill:name`) and prompt templates (`/template`) expand.
320
+ 4. `before_agent_start` runs, then the agent loop starts.
61
321
 
62
- A normal prompt starts a run. The run repeats turns, then checks whether more work starts another low-level agent run:
322
+ The run repeats turns, then checks whether more work starts another low-level agent run:
63
323
 
64
324
  ```mermaid
65
325
  flowchart TD
@@ -75,7 +335,7 @@ flowchart TD
75
335
  Continue -->|no| Settled["agent_settled"]
76
336
  ```
77
337
 
78
- More work means a retry, recovery, compaction retry, or queued work.
338
+ More work means a retry, final-attempt recovery, a compaction retry, or queued messages. `agent_end` is therefore not a final-idle signal; use `agent_settled` for that. An aborted run skips `agent_before_settle` and goes from `agent_end` to `agent_settled`. draht counts as busy while a run starts, including the compaction check and `before_agent_start`, so messages sent meanwhile go into the starting run.
79
339
 
80
340
  Each turn sends one model request and executes the tool calls in the assistant response:
81
341
 
@@ -93,36 +353,24 @@ flowchart TD
93
353
 
94
354
  The model request runs these hooks in order:
95
355
 
96
- 1. `context`
97
- 2. `context_with_system`
98
- 3. `before_provider_headers`
99
- 4. `before_provider_request`
100
- 5. `after_provider_response`
101
- 6. `provider_stream_event` and assistant message events
356
+ 1. `context` (can modify conversation messages)
357
+ 2. `context_with_system` (can modify the full transcript)
358
+ 3. `before_provider_headers` (can mutate headers)
359
+ 4. `before_provider_request` (can inspect or replace the payload)
360
+ 5. `after_provider_response` (status and headers, before the stream is consumed)
361
+ 6. `provider_stream_event` (raw parsed stream events) and `message_start` / `message_update` / `message_end` for the assistant message
102
362
 
103
- Tool execution runs these hooks in order for each tool call:
363
+ A tool call that executes runs these hooks in order:
104
364
 
105
365
  1. `tool_execution_start`
106
- 2. `tool_call`
366
+ 2. `tool_call` (can block or mutate input)
107
367
  3. `tool_execution_update` while the tool executes
108
- 4. `tool_result`
368
+ 4. `tool_result` (can modify the result)
109
369
  5. `tool_execution_end`
110
370
 
111
- The lifecycle involves these event groups:
112
-
113
- | Area | Events |
114
- |---|---|
115
- | Input preparation | `input`, `before_agent_start` |
116
- | Agent run | `agent_start`, `agent_end` |
117
- | Model turn | `turn_start`, `context`, `context_with_system`, `turn_end` |
118
- | Provider call | `before_provider_headers`, `before_provider_request`, `after_provider_response`, `provider_stream_event` |
119
- | Message lifecycle | `message_start`, `message_update`, `message_end` |
120
- | Tool execution | `tool_execution_start`, `tool_call`, `tool_execution_update`, `tool_result`, `tool_execution_end` |
121
- | Settlement | `agent_before_settle`, `agent_settled` |
122
-
123
- Draht counts as busy while a run starts, including the compaction check and `before_agent_start`, so messages sent meanwhile go into the starting run. Message lifecycle events also cover user and tool-result messages; the model request list places only the assistant stream where it occurs in each turn.
371
+ Calls that do not execute end early. An unknown tool or invalid arguments skip `tool_call`; a blocked or aborted call skips execution and `tool_result`. Each of these still gets `tool_execution_end` with an error result, so use `tool_execution_end` to observe every finalized call.
124
372
 
125
- Tool hooks run for each tool call, and one assistant response can start another turn by returning tool calls. Provider hooks run only when that transport exposes the corresponding stage. See the exported declarations in [`extensions/types.ts`](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/extensions/types.ts) for exact event payloads and result types.
373
+ `turn_end` can append entries and request a continuation. Threshold compaction runs before a naturally required next turn. Message events also fire for other messages, such as user, tool-result, and custom messages. Provider hooks run only when the transport exposes the corresponding stage.
126
374
 
127
375
  Session startup and replacement follow a separate lifecycle:
128
376
 
@@ -134,77 +382,38 @@ flowchart TD
134
382
  Fork["/fork or /clone"] --> BeforeFork["session_before_fork"]
135
383
  BeforeSwitch --> Shutdown["session_shutdown"]
136
384
  BeforeFork --> Shutdown
137
- Reload["reload"] --> Shutdown
385
+ Reload["/reload"] --> Shutdown
386
+ Exit["exit"] --> Shutdown
138
387
  Shutdown --> Replacing{"Replacing the runtime?"}
139
- Replacing -->|yes| Replacement["load replacement extension runtime"]
388
+ Replacing -->|yes| ReplacementTrust["project_trust when the working directory is new"]
389
+ ReplacementTrust --> Replacement["load replacement extension runtime"]
140
390
  Replacement --> SessionStart
141
391
  Replacing -->|no| Stop["process exits"]
142
392
  SessionStart --> Discover["resources_discover"]
143
393
  ```
144
394
 
145
- `project_trust` runs before trusted project resources load and can run again when session replacement enters a new working directory. Retries, recovery, compaction, and queued messages can start another agent run after `agent_end`, so `agent_end` is not a final-idle signal. Reload and session replacement invalidate the old runtime. Code after `await ctx.reload()` still belongs to the old runtime and must not reuse its session-bound state.
146
-
147
- ### Choose an event by intent
148
-
149
- | Goal | Event |
150
- |---|---|
151
- | Inspect, transform, or consume raw user input | `input` |
152
- | Change prompt sections, active tools, or add context before a run | `before_agent_start` |
153
- | Observe one low-level agent run | `agent_start`, `agent_end` |
154
- | Act after one model response and its tool calls | `turn_end` |
155
- | Filter conversation messages for one provider request | `context` |
156
- | Transform the complete transcript, including system messages | `context_with_system` |
157
- | Change request headers or the serialized provider payload | `before_provider_headers`, `before_provider_request` |
158
- | Observe provider response metadata or parsed stream events | `after_provider_response`, `provider_stream_event` |
159
- | Authorize or modify a tool call | `tool_call` |
160
- | Redact, annotate, or replace a tool result | `tool_result` |
161
- | Append final entries or request one last continuation | `agent_before_settle` |
162
- | Run notification work after automatic processing has stopped | `agent_settled` |
163
- | Initialize or release session-scoped resources | `session_start`, `session_shutdown` |
164
-
165
- <a id="agent_start--agent_end--agent_before_settle--agent_settled"></a>
166
-
167
- Use `agent_before_settle` when an extension must append entries or request one final continuation. Use `agent_settled` for notification-only work that should run after draht has no automatic continuation remaining.
395
+ `session_start` carries `reason: "startup" | "reload" | "new" | "resume" | "fork"`, and `session_shutdown` carries `reason: "quit" | "reload" | "new" | "resume" | "fork"`. `resources_discover` uses `reason: "reload"` after a reload and `"startup"` otherwise. Exit covers Ctrl+C, Ctrl+D, SIGHUP, and SIGTERM. `project_trust` runs before trusted project resources load and can run again when session replacement enters a new working directory.
168
396
 
169
- <a id="extensionapi-methods"></a>
397
+ Other operations change the current session without replacing the runtime:
170
398
 
171
- ## Choose an integration point
172
-
173
- | Capability | Main API |
399
+ | Operation | Events |
174
400
  |---|---|
175
- | Observe or modify lifecycle behavior | `pi.on()` |
176
- | Add a model-callable operation | `pi.registerTool()` |
177
- | Add a `/` command | `pi.registerCommand()` |
178
- | Add a shortcut or CLI flag | `pi.registerShortcut()` or `pi.registerFlag()` |
179
- | Send user or custom messages | `pi.sendUserMessage()` or `pi.sendMessage()` |
180
- | Persist non-context session data | `pi.appendEntry()` |
181
- | Record model-attributed usage outside a tool result | `pi.appendUsage()` |
182
- | Change active tools, model, or thinking level | Session control methods on `pi` |
183
- | Read or restore working-tree checkpoints | `pi.checkpoints` |
184
- | Add a model provider | `pi.registerProvider()` |
185
- | Add an MCP server | `pi.registerMcpServer()` |
186
- | Route each request to a model | [`pi.registerVirtualModel()`](virtual-models.md) |
187
- | Add terminal rendering | Renderer registration and `ctx.ui` |
188
- | Communicate with another extension | `pi.events` |
189
-
190
- `pi.setModel()` and `pi.setThinkingLevel()` change only the current session by default; pass `{ persist: true }` to also update the user's global default.
191
-
192
- Use the exported declarations in [`extensions/types.ts`](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/extensions/types.ts) for exact event, context, tool, and result types.
193
-
194
- ## Follow the extension contracts
195
-
196
- <a id="events"></a>
401
+ | `/compact` or automatic compaction | `session_before_compact` (can cancel or customize), then `session_compact` or `session_compact_failed` |
402
+ | `/tree` navigation | `session_before_tree` (can cancel or customize), then `session_tree` |
403
+ | `/name` or `pi.setSessionName()` | `session_info_changed` |
404
+ | `/model` or model cycling (`Ctrl+P`) | `thinking_level_select` if the level changes or is clamped, then `model_select` |
405
+ | Thinking-level change (settings, keybinding, `pi.setThinkingLevel()`) | `thinking_level_select` |
406
+ | `!` or `!!` command | `user_bash` (can intercept) |
407
+ | Extension dialog or custom screen waits for the user | `ui_prompt_start`, `ui_prompt_end` |
408
+ | Idle prompt-cache refresh | `cache_warming_decision` |
409
+ | Extension registers or removes an MCP server after startup | `mcp_servers_change` |
410
+
411
+ <a id="events-and-concurrency"></a>
197
412
  <a id="work-with-events"></a>
198
413
 
199
- ### Events and concurrency
200
-
201
- Handlers run in extension load and registration order. `pi.on()` returns a function that unsubscribes that registration; changes do not affect a dispatch already in progress.
202
- Some events notify; others transform data, replace results, or cancel an operation.
203
- Use each event’s declared result type rather than assuming every return value has an effect.
414
+ ### Handler Composition
204
415
 
205
- Events cover resource discovery, sessions, agent and message lifecycle, providers, tools, and raw input.
206
-
207
- #### Understand handler composition
416
+ Handlers run in extension load order, then registration order. Some events notify; others transform data, replace results, or cancel an operation:
208
417
 
209
418
  | Pattern | Behavior |
210
419
  |---|---|
@@ -217,196 +426,2955 @@ Events cover resource discovery, sessions, agent and message lifecycle, provider
217
426
 
218
427
  Notification handlers should not perform slow work on a streaming event. Transform handlers should preserve fields they do not intentionally own, and gate handlers should fail closed when their safety decision cannot be made.
219
428
 
220
- `before_agent_start` exposes both the current prompt and its structured `systemPromptOptions`. `event.messageType` says what started the run: `"user"` for a prompt or `pi.sendUserMessage()`, with `prompt` and `images`; `"custom"` for `pi.sendMessage(..., { triggerTurn: true })`, with the starting `message` and no `prompt`. A returned `message` is added to either kind of run; check `messageType` to skip runs started by custom messages. Prefer changing prompt sections, selected tools, or guidelines so draht can append a transcript delta. Returning `systemPrompt`, or setting `forceSystemPrompt`, replaces the whole prompt for that run while the transcript continues recording the structured sections. Providers receive the forced text as their leading system prompt.
429
+ ### Startup Events
221
430
 
222
- `message_end` can replace a finalized message while preserving its role. `tool_call` can mutate input or block execution. `tool_result` handlers compose, with each handler seeing prior changes.
431
+ #### project_trust
223
432
 
224
- <a id="provider_stream_event"></a>
433
+ Fired before draht decides whether to trust a project with dynamic configs (`.draht` or `.agents/skills`). It runs during startup and when session replacement (for example `/resume`) enters a cwd whose trust has not been resolved in the current process. Only user/global extensions and CLI `-e` extensions participate; project-local extensions are not loaded until after trust is resolved.
225
434
 
226
- `provider_stream_event` fires for each parsed provider stream event before draht normalizes it. The event identifies the provider, API, and model; `event.data` is the earliest structured value available to draht, not necessarily the original HTTP bytes or SSE frame. Treat it as read-only because mutation can affect normalization. The event is notification-only and is not persisted.
435
+ ```typescript
436
+ pi.on("project_trust", async (event, ctx) => {
437
+ // event.cwd - current working directory
438
+ // ctx has a limited trust context: cwd, mode, hasUI, and select/confirm/input/notify UI helpers
439
+ if (await ctx.ui.confirm("Trust project?", event.cwd)) {
440
+ return { trusted: "yes", remember: true };
441
+ }
442
+ return { trusted: "undecided" };
443
+ });
444
+ ```
227
445
 
228
- Handlers are awaited in stream order, so slow handlers delay stream consumption. Handler errors are reported without changing the provider response. See [`debug-provider.ts`](../examples/extensions/debug-provider.ts) for an opt-in viewer that groups raw events by assistant message.
446
+ A `project_trust` handler must return `{ trusted: "yes" | "no" | "undecided" }`. A user/global or CLI extension that returns `"yes"` or `"no"` owns the decision; the first yes/no decision wins and suppresses the built-in trust prompt. Use `remember: true` to persist a yes/no decision; otherwise it applies only to the current process. Return `"undecided"` to let later handlers or the built-in trust flow decide. Check `ctx.hasUI` before prompting. If no handler returns yes/no, normal trust resolution continues: saved `trust.json` decisions apply first, then `defaultProjectTrust` controls whether draht asks, trusts, or declines by default.
229
447
 
230
- <a id="context_with_system"></a>
448
+ ### Resource Events
231
449
 
232
- `context` transforms conversation messages without prompt and tool system messages; draht restores that state afterward. Use `context_with_system` only when a request-local transformation must own the complete transcript, and keep a system message at index zero.
450
+ #### resources_discover
233
451
 
234
- `turn_end` and `agent_before_settle` are actionable boundaries. Their handlers can chain proposed `custom`, `custom_message`, `context_edit`, or `compaction` entries and return `continue: true` for one next model request. Guard continuation conditions because an unconditional continuation can loop. Use the exported event declarations for the complete validation and ordering contract.
452
+ Fired after `session_start` so extensions can contribute additional skill, prompt, and theme paths.
453
+ The startup path uses `reason: "startup"`. Reload uses `reason: "reload"`.
235
454
 
236
- <a id="cache_warming_decision"></a>
455
+ ```typescript
456
+ pi.on("resources_discover", async (event, _ctx) => {
457
+ // event.cwd - current working directory
458
+ // event.reason - "startup" | "reload"
459
+ return {
460
+ skillPaths: ["/path/to/skills"],
461
+ promptPaths: ["/path/to/prompts"],
462
+ themePaths: ["/path/to/themes"],
463
+ };
464
+ });
465
+ ```
237
466
 
238
- `cache_warming_decision` can override an idle prompt-cache refresh with `{ action: "warm" }` or `{ action: "stop" }`. The last handler that returns an action wins.
467
+ #### mcp_servers_change
239
468
 
240
- Tool calls from one assistant message can run in parallel.
241
- Do not assume a sibling call or result exists when another tool event runs.
242
- Use `ctx.signal` for nested work owned by an active turn; commands and idle session events often have no operation signal.
469
+ Fired when an extension registers or unregisters an MCP server after extensions are bound. `event.servers` lists every registered server after the change. Handling this event marks the extension as the one that connects registered servers; see [MCP Servers](#mcp-servers).
243
470
 
244
- A `user_bash` handler that returns `undefined` passes the command to the next handler and then to local execution if no handler handles it. Returning `operations` or `result` stops propagation. A handler failure blocks the command rather than falling through to local execution.
471
+ ### Session Events
245
472
 
246
- <a id="custom-tools"></a>
247
- <a id="register-tools"></a>
473
+ See [Session Format](session-format.md) for session storage internals and the SessionManager API.
248
474
 
249
- ### Tools
475
+ #### session_start
250
476
 
251
- A custom tool defines a name, model-facing description, TypeBox parameter schema, and `execute()` function.
252
- Its result requires model-facing `content` and a `details` field for rendering or state reconstruction.
253
- Use `details: undefined` when there are no structured details. If the tool makes nested model calls, include their `usage` in the result so session totals remain accurate. For model-attributed usage that happens outside any tool result — a host-side run reported only through a later custom message, for example — call `pi.appendUsage(kind, provider, model, usage, note?)` instead; it records a usage entry directly in the session's totals and cost breakdown. Record each unit of usage exactly once, and never for usage already reported through a tool result, and treat a throw (a stale ctx after the session ended) as a safe no-op.
477
+ Fired when a session is started, loaded, or reloaded.
254
478
 
255
- Throw from `execute()` to produce a failed tool result.
256
- Returning an object does not mark it as an error.
257
- Return `terminate: true` only when the agent should skip its automatic follow-up after every completed tool in that batch agrees to terminate.
479
+ ```typescript
480
+ pi.on("session_start", async (event, ctx) => {
481
+ // event.reason - "startup" | "reload" | "new" | "resume" | "fork"
482
+ // event.previousSessionFile - present for "new", "resume", and "fork"
483
+ ctx.ui.notify(`Session: ${ctx.sessionManager.getSessionFile() ?? "ephemeral"}`, "info");
484
+ });
485
+ ```
258
486
 
259
- Use sequential execution when tools share mutable in-memory state.
260
- File-mutating tools should wrap the complete read-modify-write operation with `withFileMutationQueue()`.
261
- Truncate large model-facing results and tell the model where to read the complete output.
487
+ #### session_info_changed
262
488
 
263
- Declare `outputSchema` and return a matching `structuredContent` when the result is data. The model still receives `content`; programmatic callers such as codemode scripts receive `structuredContent` instead of the text. Tools without `outputSchema` are passed to scripts as their text content. To report a failure that still carries data, return the result with `isError: true` instead of throwing: the model sees an error, and scripts still receive `structuredContent`.
489
+ Fired when the current session display name is set via `/name`, RPC, or `pi.setSessionName()`.
264
490
 
265
- A tool can run other tools with `ctx.executeTool(name, args, { signal, onUpdate })`. Nested calls go through argument validation and the `tool_call` and `tool_result` handlers like model-issued calls, and emit `tool_execution_start`, `tool_execution_update`, and `tool_execution_end`; all of these events carry `parentToolCallId`, and their `toolCallId` is assigned by draht as `<parent id>/<n>`. These ids do not appear as tool calls or tool results in the transcript. Nested calls do not add transcript entries: their results only reach the calling tool, which reports them itself, for example through `onUpdate` and `details`. The session keeps a bounded record of them (name, arguments, status, duration, error; never results) as `nestedCalls` on the calling tool's result message. It is used for compaction file lists and shown in HTML exports. Arguments over 8 KiB per call or 32 KiB per tool result are omitted, at most 256 calls are kept, and `complete: false` marks a record that lost anything. The `usage` of nested results, at every depth, is added to the calling tool's result `usage`, so a tool reports only its own usage, not that of the tools it called. `ctx.tools` lists the tools `ctx.executeTool()` can call. `tool_result` handlers that redact `content` should also replace `structuredContent`; replacing only `content` drops it.
491
+ ```typescript
492
+ pi.on("session_info_changed", async (event, ctx) => {
493
+ // event.name - current normalized name, or undefined if cleared
494
+ ctx.ui.notify(`Session renamed: ${event.name ?? "(none)"}`, "info");
495
+ });
496
+ ```
266
497
 
267
- See [`hello.ts`](../examples/extensions/hello.ts), [`todo.ts`](../examples/extensions/todo.ts), [`dynamic-tools.ts`](../examples/extensions/dynamic-tools.ts), and [`truncated-tool.ts`](../examples/extensions/truncated-tool.ts).
498
+ #### session_before_switch
268
499
 
269
- ### Tool exposure
500
+ Fired before starting a new session (`/new`) or switching sessions (`/resume`).
270
501
 
271
- `exposure` controls how the model reaches a tool. "Callable" means callable from other tools through `ctx.executeTool()` (`ctx.tools`), as the `codemode` tool's scripts do:
502
+ ```typescript
503
+ pi.on("session_before_switch", async (event, ctx) => {
504
+ // event.reason - "new" or "resume"
505
+ // event.targetSessionFile - session we're switching to (only for "resume")
272
506
 
273
- - `direct` (default): declared to the model while active, and callable while active.
274
- - `model-only`: declared to the model while active, never callable. Use it for tools that orchestrate other tools or ask the user.
275
- - `codemode`: callable whenever registered, and listed by the `codemode` tool. Not declared to the model unless activated explicitly.
276
- - `deferred`: like `codemode`, but codemode tools do not list it; `tool_search` can find and activate it.
277
- - `hidden`: registered but unreachable. Re-register a tool with `exposure: "hidden"` to withdraw it, since tools cannot be unregistered.
507
+ if (event.reason === "new") {
508
+ const ok = await ctx.ui.confirm("Clear?", "Delete all messages?");
509
+ if (!ok) return { cancel: true };
510
+ }
511
+ });
512
+ ```
278
513
 
279
- `namespace: { name, aliases, description, instructions }` groups related tools, as MCP servers do. Codemode tools list a namespace under one heading with its `description`. `instructions` holds longer usage guidance; it is not listed, and codemode scripts read it with `describeNamespace(name)`. `aliases` are other names scripts may look the namespace up by, for example the server name `docs` for `mcp__docs`; a name and the same name as a script identifier (`my-docs`, `my_docs`) match alike.
514
+ After a successful switch or new-session action, draht emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "new" | "resume"` and `previousSessionFile`.
515
+ Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
280
516
 
281
- Registering a `direct` or `model-only` tool activates it; the other exposures are not activated on registration. The active set (`pi.getActiveTools()`, `pi.setActiveTools()`) is the set of tools declared to the model. `pi.getAllTools()` reports each tool's `exposure`, `namespace`, `annotations`, and `reachesTools`.
517
+ #### session_before_fork
282
518
 
283
- `annotations` are hints about what a tool does, with the meaning of MCP tool annotations: `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint`. MCP tools carry the hints their server declares. Missing hints take the MCP defaults: a tool is not read-only, and may be destructive and reach an open world. The hints are not verified, but a permission extension can use them to decide which calls to confirm. This confirms the calls Codex asks approval for:
519
+ Fired when forking via `/fork` or cloning via `/clone`.
284
520
 
285
521
  ```typescript
286
- pi.on("tool_call", async (event, ctx) => {
287
- const hints = pi.getAllTools().find((tool) => tool.name === event.toolName)?.annotations;
288
- const needsApproval =
289
- hints?.destructiveHint === true ||
290
- (!hints?.readOnlyHint && ((hints?.destructiveHint ?? true) || (hints?.openWorldHint ?? true)));
291
- if (needsApproval && !(await ctx.ui.confirm("Allow tool call?", event.toolName))) {
292
- return { block: true, reason: `${event.toolName} was not approved` };
293
- }
522
+ pi.on("session_before_fork", async (event, ctx) => {
523
+ // event.entryId - ID of the selected entry
524
+ // event.position - "before" for /fork, "at" for /clone
525
+ return { cancel: true }; // Cancel fork/clone
526
+ // OR
527
+ return { skipConversationRestore: true }; // Reserved for future conversation restore control
294
528
  });
295
529
  ```
296
530
 
297
- draht's own permission gate runs a call to a tool with `readOnlyHint: true` without asking (in the `ask` and `supervised` modes, only one that also declares `openWorldHint: false`, since a tool that reaches the web can carry what it read out), when no rule in `permissions.yml` matches it, no argument of the call names a path outside the project, and the hint comes from outside the project: from a built-in tool, or from an extension loaded with `-e`, by the SDK, or from the user's own extensions and packages. Tools of a project's extensions still ask, and so does a tool that also declares `destructiveHint: true`. An extension that relays another source's hints, as the MCP support relays a server's, sets `annotationsScope` to that source's scope: `"user"`, `"project"`, or `"temporary"`. The gate ignores the hints when `annotationsScope` is `"project"`, so the field can lower trust but never raise it. `pi.getAllTools()` reports `annotationsScope` with the annotations.
531
+ After a successful fork or clone, draht emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "fork"` and `previousSessionFile`.
532
+ Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
298
533
 
299
- A tool that orchestrates other tools can adjust what the model sees while it is active with `prepareLoadout(loadout)`. It runs whenever the active tools change and receives the declared tools, the callable tools, and every registered tool with its exposure, namespace, and prompt guidelines. It returns replacement `descriptions` for declared tools (including its own) and `hiddenDeclarations`: active tools whose declarations requests leave out while they stay active and callable. The default system prompt leaves hidden tools out of its tool list and rules, and names no tool in the skills hint when the file reader is hidden, so the orchestrating tool should present their guidelines itself. `codemode` uses only this hook, `exposure`, `reachesTools`, and `ctx.executeTool()`, so another tool can implement the same behavior under a different name.
534
+ <a id="session_before_compact--session_compact"></a>
300
535
 
301
- A tool that reaches other tools declares which ones a call may reach with `reachesTools(input)`: `"all"`, or the words of the input that may name them, where a word refers to every tool or namespace whose name it contains. `codemode` returns `"all"` for scripts that search or list tools and the words of the script otherwise; `tool_search` always returns `"all"`. Extensions that register tools late use it from their `tool_call` handler to finish registering the tools a call needs before it runs, as the MCP extension does for servers that are still connecting. The MCP extension also activates `codemode` or `tool_search` for MCP tools only when the tool of that name declares `reachesTools`.
536
+ #### session_before_compact / session_compact / session_compact_failed
302
537
 
303
- ### Activate tools dynamically
538
+ Fired on compaction. See [compaction.md](compaction.md) for details.
304
539
 
305
- Register every tool first, keep optional tools inactive, and use `pi.setActiveTools()` from a loader tool to select the desired active tools. Names must already be registered; unknown names are ignored.
540
+ ```typescript
541
+ pi.on("session_before_compact", async (event, ctx) => {
542
+ const { preparation, branchEntries, customInstructions, reason, willRetry, signal } = event;
543
+
544
+ // reason - "manual" (/compact), "threshold", or "overflow"
545
+ // willRetry - whether the aborted turn is retried after compaction (overflow recovery)
546
+
547
+ // Cancel:
548
+ return { cancel: true };
549
+
550
+ // Custom summary:
551
+ return {
552
+ compaction: {
553
+ summary: "...",
554
+ firstKeptEntryId: preparation.firstKeptEntryId,
555
+ tokensBefore: preparation.tokensBefore,
556
+ // usage: summaryResponse.usage, // Optional; included in session totals
557
+ }
558
+ };
559
+ });
306
560
 
307
- draht records the initial prompt and tool set in the transcript's first system message, then appends tool and prompt changes before the next model request. Providers that cannot represent the transition receive a complete transcript checkpoint, which can invalidate the cached prefix.
561
+ pi.on("session_compact", async (event, ctx) => {
562
+ // event.compactionEntry - the saved compaction
563
+ // event.fromExtension - whether extension provided it
564
+ // event.reason - "manual" (/compact), "threshold", or "overflow"
565
+ // event.willRetry - whether the aborted turn is retried after compaction (overflow recovery)
566
+ });
308
567
 
309
- ### Checkpoints and rewind
568
+ pi.on("session_compact_failed", async (event, ctx) => {
569
+ // event.reason - "manual" (/compact), "threshold", or "overflow"
570
+ // event.errorMessage - present for non-abort failures
571
+ // event.aborted - true for cancelled/aborted compactions
572
+ // event.willRetry - whether the aborted turn would have retried after compaction
573
+ // event.fromExtension - whether extension-provided compaction content was being used
574
+ });
575
+ ```
310
576
 
311
- draht snapshots the working tree per session so `/rewind` can restore conversation and files. `pi.checkpoints` exposes that store: `list()` and `get(entryId)` read recorded checkpoints, `restore()` restores an entry's checkpoint after taking a safety snapshot, and `capture(entryId)` records a new one. The calls never throw and degrade quietly when checkpoints are unavailable, such as before the session has a file or outside a git repository.
577
+ #### session_before_tree / session_tree
312
578
 
313
- `checkpoint_created` fires after every capture. `session_before_rewind` reports the target entry and scope (`conversation-and-files`, `conversation-only`, or `files-only`) and can return `{ cancel: true }`. Retention is configured in [Settings](settings.md).
579
+ Fired on `/tree` navigation. See [Sessions](sessions.md) for tree navigation concepts.
314
580
 
315
- ### Tool rendering
581
+ ```typescript
582
+ pi.on("session_before_tree", async (event, ctx) => {
583
+ const { preparation, signal } = event;
584
+ // preparation.targetId, oldLeafId, commonAncestorId, entriesToSummarize,
585
+ // userWantsSummary, customInstructions, replaceInstructions, label
586
+ return { cancel: true };
587
+ // OR provide custom summary (used only when preparation.userWantsSummary is true):
588
+ return {
589
+ summary: {
590
+ summary: "...",
591
+ // usage: summaryResponse.usage, // Optional; included in session totals
592
+ details: {},
593
+ },
594
+ };
595
+ // OR override summarization options: customInstructions, replaceInstructions, label
596
+ });
316
597
 
317
- A tool's `renderCall` and `renderResult` draw its calls in the interactive transcript and in HTML exports. `draht.registerToolRenderer((toolName, next) => renderers)` chooses renderers for calls to any tool, including tools that are not registered yet, such as MCP tools in a resumed session before their server connected. `next()` returns what the remaining resolvers (in extension load order), then the registered tool, would use, so `next() ?? mine` only fills in.
598
+ pi.on("session_tree", async (event, ctx) => {
599
+ // event.newLeafId, oldLeafId, summaryEntry, fromExtension
600
+ });
601
+ ```
318
602
 
319
- ### MCP servers
603
+ #### session_shutdown
320
604
 
321
- `pi.registerMcpServer(name, config)` adds an MCP server for the current session. `config` has the shape of an `mcpServers` entry in [`mcp.json`](mcp.md): `command`, `args`, `env`, and `cwd` for stdio servers, `url`, `headers`, and `oauth` for HTTP servers, plus `exposure`, `toolExposure`, `description`, `enabled`, and `timeout`.
605
+ Fired before a started session runtime is torn down. Use this to clean up resources opened from `session_start` or other session-scoped hooks.
322
606
 
323
607
  ```typescript
324
- pi.registerMcpServer("jira", { url: "https://mcp.example.com/jira", exposure: "codemode" });
325
- pi.unregisterMcpServer("jira");
608
+ pi.on("session_shutdown", async (event, ctx) => {
609
+ // event.reason - "quit" | "reload" | "new" | "resume" | "fork"
610
+ // event.targetSessionFile - destination session for session replacement flows
611
+ // Cleanup, save state, etc.
612
+ });
326
613
  ```
327
614
 
328
- Servers registered while the extension loads connect when the session starts, together with the `mcp.json` servers; servers registered later connect right away, and `pi.unregisterMcpServer()` closes the connection and makes the server's tools unreachable. Registrations are not saved: register again on every load, for example based on the extension's own settings. A server in `mcp.json` with the same name takes precedence, and `/mcp` shows the override. Registering the same name again replaces the extension's earlier registration; names registered by another extension, invalid names, and invalid configs throw.
615
+ ### Agent Events
329
616
 
330
- The built-in MCP support connects registered servers. When nothing does, because another extension replaced it (see [MCP](mcp.md#other-mcp-extensions)), each registration is reported as an extension error. Other MCP extensions can connect registered servers too: read them with `pi.getMcpServers()` on `session_start` and handle the `mcp_servers_change` event for later changes. Each registered server carries the `extensionScope` of the extension that registered it, which its tools' `annotationsScope` takes, so the permission gate trusts a registered server's read-only hints as far as it trusts the extension.
617
+ #### before_agent_start
331
618
 
332
- <a id="extensioncontext"></a>
333
- <a id="extensioncommandcontext"></a>
334
- <a id="use-extension-context"></a>
619
+ Fired before a run starts, after input handling and expansion. Can inject a message and/or modify the system prompt.
335
620
 
336
- ### Context and session changes
621
+ `event.messageType` says what started the run: `"user"` for a prompt or `pi.sendUserMessage()`, with `prompt` and `images`; `"custom"` for `pi.sendMessage(..., { triggerTurn: true })` while idle, with the starting `message` and no `prompt`.
622
+
623
+ ```typescript
624
+ pi.on("before_agent_start", async (event, ctx) => {
625
+ // event.messageType - "user" | "custom"
626
+ // event.prompt, event.images - user's prompt text and images (messageType "user")
627
+ // event.message - the custom message that starts the run (messageType "custom")
628
+ // event.systemPrompt - current chained system prompt for this handler
629
+ // (includes changes from earlier before_agent_start handlers)
630
+ // event.systemPromptOptions - structured options used to build the system prompt
631
+ // .customPrompt - exact prompt prefix from --system-prompt, SYSTEM.md, or custom templates
632
+ // .forceSystemPrompt - optional exact replacement for the complete prompt
633
+ // .selectedTools - tools currently active in the prompt
634
+ // .hiddenTools - selected tools whose declarations requests leave out
635
+ // .toolSnippets - one-line descriptions for each tool
636
+ // .toolGuidelines - rule bullets keyed by tool name
637
+ // .promptGuidelines - additional custom rule bullets
638
+ // .sections - custom XML-wrapped sections keyed by tag name
639
+ // .appendSystemPrompt - text from --append-system-prompt flags
640
+ // .cwd - working directory
641
+ // .contextFiles - AGENTS.md files and other loaded context files
642
+ // .skills - loaded skills
643
+
644
+ return {
645
+ // Inject a persistent message (stored in session, sent to LLM)
646
+ message: {
647
+ customType: "my-extension",
648
+ content: "Additional context for the LLM",
649
+ display: true,
650
+ },
651
+ // Replace the system prompt for this turn (chained across extensions)
652
+ systemPrompt: event.systemPrompt + "\n\nExtra instructions for this turn...",
653
+ };
654
+ });
655
+ ```
337
656
 
338
- `ExtensionContext` provides the working directory, mode, UI, session manager, model runtime, abort signal, context usage, and controls for compaction and shutdown.
339
- Use `ctx.modelRegistry.streamSimple()` for provider-neutral nested model calls.
657
+ A returned `message` is added to either kind of run; check `messageType` to skip runs started by custom messages.
340
658
 
341
- Command handlers receive `ExtensionCommandContext`, which adds operations for waiting until idle, reloading, tree navigation, and session replacement.
342
- These operations are command-only because calling them from lifecycle handlers can deadlock the runtime.
659
+ The `systemPromptOptions` field gives extensions access to the same structured data draht uses to build the system prompt. Collections are mutable. Prefer changing `sections`, `selectedTools`, or `promptGuidelines`: draht diffs the resulting prompt sections against what the model already has and appends one system message patching only the changed sections. Returning `systemPrompt`, or setting `forceSystemPrompt`, replaces the whole prompt for the run: every provider receives the forced text as its leading system prompt (a cache miss when it changes), and the session transcript keeps recording the structured sections. Tool selection changes update both the prompt contributions and executable provider tools; calling `pi.setActiveTools()` inside the handler has the same effect as editing `selectedTools`. Models that accept system messages mid-conversation receive the patch in place and keep their cached prefix; other models get the replayed prompt as their system prompt, which is a cache miss once per change.
343
660
 
344
- Session replacement invalidates the old context. Capture only plain data before switching, then use the fresh context supplied to `withSession` for session-bound work.
661
+ Inside `before_agent_start`, `event.systemPrompt` and `ctx.getSystemPrompt()` both reflect the chained system prompt as of the current handler. Later `before_agent_start` handlers can still modify it again.
345
662
 
346
- <a id="state-management"></a>
347
- <a id="persist-state"></a>
663
+ <a id="agent_start--agent_end--agent_settled"></a>
348
664
 
349
- ### State
665
+ #### agent_start / agent_end / agent_before_settle / agent_settled
350
666
 
351
- Choose storage based on how state participates in the conversation:
667
+ `agent_start` fires when a low-level agent run begins. `agent_end` fires when that run ends, but draht may still auto-retry, auto-compact and retry, or continue with queued follow-up messages. `agent_before_settle` is the final actionable boundary: it can append session entries and request one continuation. `agent_settled` is final and notification-only; use it for status integrations that need to know draht will not continue running automatically.
352
668
 
353
- | State | Storage |
354
- |---|---|
355
- | Tool state that follows the active branch | Tool-result `details` |
356
- | Durable data excluded from model context | `pi.appendEntry()` |
357
- | Custom content stored and sent to the model | `pi.sendMessage()` |
358
- | Data outside one session | External storage |
669
+ ```typescript
670
+ pi.on("agent_start", async (_event, ctx) => {});
359
671
 
360
- Reconstruct branch-sensitive state from `ctx.sessionManager.getBranch()` during `session_start`.
361
- Do not rebuild it from every file entry because abandoned branches represent alternative histories.
362
- Register an entry or message renderer when custom stored content should appear in the transcript.
672
+ pi.on("agent_end", async (event, ctx) => {
673
+ // event.messages - messages from this low-level run
674
+ });
363
675
 
364
- <a id="custom-ui"></a>
365
- <a id="mode-behavior"></a>
366
- <a id="interact-with-the-user"></a>
367
- <a id="account-for-each-mode"></a>
676
+ let addedReviewReminder = false;
677
+ pi.on("agent_before_settle", async (event, ctx) => {
678
+ if (addedReviewReminder) return;
679
+ addedReviewReminder = true;
680
+ return {
681
+ entries: [...event.entries, {
682
+ type: "custom_message",
683
+ customType: "review-reminder",
684
+ content: "Review the final diff before replying.",
685
+ display: false,
686
+ }],
687
+ continue: true,
688
+ };
689
+ });
368
690
 
369
- ### UI and modes
691
+ pi.on("agent_settled", async (event, ctx) => {
692
+ // event.aborted - true when the run ended because it was aborted, for example with Escape
693
+ // ctx.isIdle() is true; runs requested here start after all settled handlers finish.
694
+ });
695
+ ```
370
696
 
371
- `ctx.ui` provides dialogs, notifications, status text, widgets, titles, editor access, and custom components.
372
- Use `ctx.ui.custom()` only when the interaction needs its own rendering and input.
373
- See [Terminal UI](tui.md) for component, focus, overlay, theme, and performance guidance.
697
+ If the run is aborted while `agent_before_settle` handlers are running, valid returned entries are still committed, but requested continuation is suppressed. Work requested from `agent_settled` is deferred until every settled handler completes, so notification dispatch is non-reentrant.
374
698
 
375
- Extensions load in interactive, RPC, JSON, and print modes.
376
- Interactive mode provides the complete terminal UI.
377
- RPC can forward supported dialogs and notifications through the [RPC Extension UI protocol](rpc-extension-ui.md), but not custom terminal components; JSON and print modes have no UI.
378
- Guard terminal-only behavior with `ctx.mode === "tui"` and use `ctx.hasUI` for interactions supported by interactive and RPC clients.
699
+ #### ui_prompt_start / ui_prompt_end
379
700
 
380
- Keep tool and event behavior independent from rendering so non-interactive modes remain functional.
701
+ Notification-only lifecycle events for blocking user-facing extension UI prompts. They fire around `ctx.ui.select()`, `ctx.ui.confirm()`, `ctx.ui.input()`, `ctx.ui.editor()`, and `ctx.ui.custom()` so host/status integrations can report "waiting for user" instead of just "running".
381
702
 
382
- <a id="error-handling"></a>
383
- <a id="handle-errors-and-shutdown"></a>
703
+ Nested or overlapping prompts are coalesced into one outer waiting span. Handlers are invoked best-effort and are not awaited before showing or closing the prompt.
384
704
 
385
- ### Errors and cleanup
705
+ ```typescript
706
+ pi.on("ui_prompt_start", async (event, ctx) => {
707
+ // event.reason === "ui_prompt"
708
+ // event.kind: "select" | "confirm" | "input" | "editor" | "custom"
709
+ // event.title: prompt title when available
710
+ });
386
711
 
387
- draht reports handler errors and continues where possible. A `tool_call` handler failure blocks the tool as a fail-safe; a tool execution failure becomes an error result for the model.
712
+ pi.on("ui_prompt_end", async (event, ctx) => {
713
+ // draht is no longer waiting on that UI prompt span.
714
+ });
715
+ ```
388
716
 
389
- Release resources in `session_shutdown` even when normal operation attempted cleanup.
390
- Keep cleanup idempotent because cancellation, reload, session replacement, and process exit can converge on the same path.
391
- Use `ctx.shutdown()` to request an orderly process shutdown.
717
+ #### turn_start / turn_end
392
718
 
393
- <a id="examples-reference"></a>
394
- <a id="use-examples-as-the-implementation-reference"></a>
719
+ Fired for each turn (one LLM response + tool calls).
720
+
721
+ ```typescript
722
+ pi.on("turn_start", async (event, ctx) => {
723
+ // event.turnIndex, event.timestamp
724
+ });
725
+
726
+ let replacedResponse = false;
727
+ pi.on("turn_end", async (event, ctx) => {
728
+ // event.turnIndex, event.message, event.toolResults
729
+ // event.entries contains the structural entries proposed so far.
730
+ if (replacedResponse || event.outcome !== "completed" || event.toolResults.length > 0) return;
731
+ replacedResponse = true;
732
+ return {
733
+ entries: [
734
+ ...event.entries,
735
+ { type: "context_edit", targetId: event.messageEntryId, replacement: null },
736
+ {
737
+ type: "custom_message",
738
+ customType: "replacement-instruction",
739
+ content: "Answer again using the persisted user request.",
740
+ display: false,
741
+ },
742
+ ],
743
+ continue: true,
744
+ };
745
+ });
746
+ ```
747
+
748
+ `turn_end` runs after the assistant and tool-result messages have been persisted and before the low-level `turn_end` event. Retry backoff and final-attempt recovery still happen after `agent_end`, preserving their existing lifecycle and queue ordering; `agent_before_settle` sees the repaired projection after that work completes. Boundary handlers run in extension load and registration order. Each handler sees prior proposals in `event.entries` and sees `event.context` rebuilt from them. Returning `entries` or `continue` replaces only that field; omitted fields preserve the current proposal. Allowed draft entry types are `custom`, `custom_message`, `context_edit`, and `compaction`. The complete proposal is validated before it is appended in list order after all handlers finish; a handler error is reported and later handlers still run. Validation prevents partially applied semantic errors, but persistence is not transactional.
749
+
750
+ `continue: true` ensures one next provider request for that boundary invocation. If tool results, steering, or a follow-up already cause that request, they satisfy the decision and no additional request is made; otherwise draht makes one context-only request. Error and aborted responses remain hard exits. `continue: false` never suppresses natural work. Guard continuation conditions: an unconditional `continue: true` is evaluated again after the next response and can create an endless loop. A `custom_message` draft contributes a user-role model message but is extension-authored: it does not run human input hooks, slash commands, skills, or prompt templates.
751
+
752
+ Host integrations that construct `TurnEndEvent` values must provide `messageEntryId`, `toolResultEntryIds`, `outcome`, `entries`, `continue`, and `context`. `ExtensionEvent` exhaustive switches must also handle `agent_before_settle`. `ExtensionRunner.emit()` excludes actionable turn boundaries; dispatch `turn_end` and `agent_before_settle` through `emitBoundary(baseEvent, buildContext)` so handlers receive chained previews. Other dedicated runner methods still return results for events such as `session_before_*`.
753
+
754
+ #### message_start / message_update / message_end
755
+
756
+ Fired for message lifecycle updates.
757
+
758
+ - `message_start` and `message_end` fire for every message, including user, assistant, tool-result, and custom messages.
759
+ - `message_update` fires for assistant streaming updates.
760
+ - `message_end` handlers can return `{ message }` to replace the finalized message. The replacement must keep the same `role`.
761
+
762
+ ```typescript
763
+ pi.on("message_start", async (event, ctx) => {
764
+ // event.message
765
+ });
766
+
767
+ pi.on("message_update", async (event, ctx) => {
768
+ // event.message
769
+ // event.assistantMessageEvent (token-by-token stream event)
770
+ });
771
+
772
+ pi.on("message_end", async (event, ctx) => {
773
+ if (event.message.role !== "assistant") return;
774
+
775
+ return {
776
+ message: {
777
+ ...event.message,
778
+ usage: {
779
+ ...event.message.usage,
780
+ cost: {
781
+ ...event.message.usage.cost,
782
+ total: 0.123,
783
+ },
784
+ },
785
+ },
786
+ };
787
+ });
788
+ ```
789
+
790
+ #### tool_execution_start / tool_execution_update / tool_execution_end
791
+
792
+ Fired for tool execution lifecycle updates.
793
+
794
+ In parallel tool mode:
795
+ - `tool_execution_start` is emitted in assistant source order during the preflight phase
796
+ - `tool_execution_update` events may interleave across tools
797
+ - `tool_execution_end` is emitted in tool completion order after each tool is finalized
798
+ - final `toolResult` message events are still emitted later in assistant source order
799
+
800
+ ```typescript
801
+ pi.on("tool_execution_start", async (event, ctx) => {
802
+ // event.toolCallId, event.toolName, event.args
803
+ });
804
+
805
+ pi.on("tool_execution_update", async (event, ctx) => {
806
+ // event.toolCallId, event.toolName, event.args, event.partialResult
807
+ });
808
+
809
+ pi.on("tool_execution_end", async (event, ctx) => {
810
+ // event.toolCallId, event.toolName, event.result, event.isError
811
+ // event.durationMs - milliseconds execute() took; absent when the tool did not run
812
+ });
813
+ ```
395
814
 
396
- ## Examples and reference
815
+ All three events, `tool_call`, and `tool_result` carry `parentToolCallId` when another tool made the call; see [Calling Other Tools](#calling-other-tools).
397
816
 
398
- The checked [extension examples](../examples/extensions/) are the implementation reference. Start with the smallest example matching the behavior you need:
817
+ #### context
399
818
 
400
- | Goal | Start with | Why |
401
- |---|---|---|
402
- | Confirm or block tool calls | [`permission-gate.ts`](../examples/extensions/permission-gate.ts) | Combines `tool_call`, mode-aware UI, and fail-closed behavior. |
403
- | Modify prompt sections for a run | [`prompt-customizer.ts`](../examples/extensions/prompt-customizer.ts) | Uses structured prompt options instead of replacing the complete prompt. |
404
- | Keep branch-aware tool state | [`todo.ts`](../examples/extensions/todo.ts) | Reconstructs state from persisted entries and renders it in the TUI. |
405
- | Register tools after startup | [`dynamic-tools.ts`](../examples/extensions/dynamic-tools.ts) | Shares registration logic between lifecycle and command handlers. |
406
- | Run cancellable model work from a command | [`qna.ts`](../examples/extensions/qna.ts) | Combines nested model calls, cancellation, and custom UI. |
407
- | Replace the main editor | [`modal-editor.ts`](../examples/extensions/modal-editor.ts) | Extends `CustomEditor` while preserving application controls. |
408
- | Run finalization at shutdown | [`auto-commit-on-exit.ts`](../examples/extensions/auto-commit-on-exit.ts) | Uses the session shutdown hook for finalization work. |
409
- | Route built-in tools to another machine | [`ssh.ts`](../examples/extensions/ssh.ts) | Reuses tool operation interfaces instead of recreating tool contracts. |
410
- | Add OAuth and provider-specific streaming | [`custom-provider-gitlab-duo/`](../examples/extensions/custom-provider-gitlab-duo/) | Shows a complete provider integration while delegating supported protocols. |
819
+ Fired before each LLM call. Modify messages non-destructively. See [Session Format](session-format.md) for message types.
820
+
821
+ ```typescript
822
+ pi.on("context", async (event, ctx) => {
823
+ // event.messages - deep copy without system messages, safe to modify
824
+ const filtered = event.messages.filter(m => !shouldPrune(m));
825
+ return { messages: filtered };
826
+ });
827
+ ```
828
+
829
+ `event.messages` holds the conversation without system messages. The prompt and tool declarations belong to draht and are not part of this hook: when the handler returns a changed list, draht replays the current prompt sections and tool declarations into one leading system message ahead of the returned messages. Filtering, windowing, or slicing from a compaction summary therefore cannot drop the prompt or the tools. An unchanged list keeps mid-conversation system messages in place, so models that accept them retain their cached prefix. System messages a handler adds are kept after draht's head. To change the prompt or the tool set durably, use [`before_agent_start`](#before_agent_start) or `pi.setActiveTools()`; to edit system messages for one request, use [`context_with_system`](#context_with_system).
830
+
831
+ #### context_with_system
832
+
833
+ Fired before each LLM call, after every `context` handler has run and draht has restored the prompt and tool state. `event.messages` is the full transcript, including the leading system message and any mid-conversation prompt or tool patches (see [Session Format](session-format.md#sessionmessageentry)). The returned messages are sent as they are: this hook owns the prompt and tool declarations for the request.
834
+
835
+ ```typescript
836
+ import { getCurrentSystemMessage } from "@draht/ai";
837
+
838
+ pi.on("context_with_system", async (event, ctx) => {
839
+ const cut = findCutIndex(event.messages);
840
+ // Fold the dropped prefix so its prompt and tool state survives as the new head.
841
+ const head = getCurrentSystemMessage(event.messages.slice(0, cut));
842
+ return { messages: head ? [head, ...event.messages.slice(cut)] : event.messages.slice(cut) };
843
+ });
844
+ ```
845
+
846
+ Rules: keep a system message at index 0 (providers read the prompt and initial tool declarations there; draht reports an error if a handler drops it). Removing a system message removes the tool declarations and section patches it carries. Check your output with `getCurrentSystemPrompt()` and `getCurrentTools()` from `@draht/ai`. Handlers run in extension load order; a `systemPrompt` forced from `before_agent_start` is still projected onto the request afterwards.
847
+
848
+ #### before_provider_headers
849
+
850
+ Fired after the outgoing HTTP headers are assembled. Use it to add, override, or remove request headers.
851
+
852
+ Handlers mutate `event.headers` in place. Set a key to a string to add or override it, or to `null` to delete it.
853
+
854
+ ```typescript
855
+ pi.on("before_provider_headers", (event, ctx) => {
856
+ // Add or override — e.g. a session id for gateway tracing/attribution
857
+ event.headers["x-session-id"] = ctx.sessionManager.getSessionId();
858
+
859
+ // Drop a tracking header draht adds for this call
860
+ event.headers["X-OpenRouter-Title"] = null;
861
+ });
862
+ ```
863
+
864
+ Runs once per provider request; retries reuse the same headers rather than re-firing the hook.
865
+
866
+ #### before_provider_request
867
+
868
+ Fired after the provider-specific payload is built, right before the request is sent. Handlers run in extension load order. Returning `undefined` keeps the payload unchanged. Returning any other value replaces the payload for later handlers and for the actual request.
869
+
870
+ This hook can rewrite provider-level system instructions or remove them entirely. Those payload-level changes are not reflected by `ctx.getSystemPrompt()`, which reports draht's system prompt string rather than the final serialized provider payload.
871
+
872
+ ```typescript
873
+ pi.on("before_provider_request", (event, ctx) => {
874
+ console.log(JSON.stringify(event.payload, null, 2));
875
+
876
+ // Optional: replace payload
877
+ // return { ...event.payload, temperature: 0 };
878
+ });
879
+ ```
880
+
881
+ This is mainly useful for debugging provider serialization and cache behavior.
882
+
883
+ The payload is the full request. Providers that continue from a previous response (OpenAI Codex over WebSocket, Anthropic message threads) may send only the part that is new since the previous request.
884
+
885
+ #### after_provider_response
886
+
887
+ Fired after an HTTP response is received and before its stream body is consumed. Handlers run in extension load order.
888
+
889
+ ```typescript
890
+ pi.on("after_provider_response", (event, ctx) => {
891
+ // event.status - HTTP status code
892
+ // event.headers - normalized response headers
893
+ if (event.status === 429) {
894
+ console.log("rate limited", event.headers["retry-after"]);
895
+ }
896
+ });
897
+ ```
898
+
899
+ Header availability depends on provider and transport. Providers that abstract HTTP responses may not expose headers.
900
+
901
+ #### provider_stream_event
902
+
903
+ Fired for each parsed provider stream event before draht normalizes it. Notification-only and not persisted.
904
+
905
+ ```typescript
906
+ pi.on("provider_stream_event", (event, ctx) => {
907
+ // event.provider, event.api, event.model
908
+ // event.data - earliest structured value available to draht (read-only)
909
+ });
910
+ ```
911
+
912
+ `event.data` is not necessarily the original HTTP bytes or SSE frame. Treat it as read-only because mutation can affect normalization. Handlers are awaited in stream order, so slow handlers delay stream consumption. Handler errors are reported without changing the provider response. See [`debug-provider.ts`](../examples/extensions/debug-provider.ts) for an opt-in viewer that groups raw events by assistant message.
913
+
914
+ #### cache_warming_decision
915
+
916
+ Fired before each prompt-cache refresh with draht's decision filled in. The event carries only draht's cost estimates; use `ctx.model`, `ctx.isIdle()`, and `ctx.getContextUsage()` for everything else.
917
+
918
+ ```typescript
919
+ pi.on("cache_warming_decision", (event, ctx) => {
920
+ // event.warmCost: price of this refresh
921
+ // event.missCost: extra price of the next request if the entry is lost
922
+ // event.continuationProbability: draht's estimate that a request arrives in time
923
+ // event.action: "warm" | "stop", draht's decision
924
+
925
+ if (ctx.model?.provider === "my-provider") {
926
+ return { action: "stop" };
927
+ }
928
+ });
929
+ ```
930
+
931
+ Return `{ action: "warm" }` or `{ action: "stop" }` to override; the last handler that returns an action wins. `"stop"` ends warming until the next real request.
932
+
933
+ ### Model Events
934
+
935
+ #### model_select
936
+
937
+ Fired when the model changes via `/model` command, model cycling (`Ctrl+P`), or `pi.setModel()`. Restoring a session does not fire it; read `ctx.model` in `session_start` to initialize model-dependent state.
938
+
939
+ ```typescript
940
+ pi.on("model_select", async (event, ctx) => {
941
+ // event.model - newly selected model
942
+ // event.previousModel - previous model (undefined if first selection)
943
+ // event.source - "set" | "cycle"
944
+
945
+ const prev = event.previousModel
946
+ ? `${event.previousModel.provider}/${event.previousModel.id}`
947
+ : "none";
948
+ const next = `${event.model.provider}/${event.model.id}`;
949
+
950
+ ctx.ui.notify(`Model changed (${event.source}): ${prev} -> ${next}`, "info");
951
+ });
952
+ ```
953
+
954
+ Use this to update UI elements (status bars, footers) or perform model-specific initialization when the active model changes.
955
+
956
+ #### thinking_level_select
957
+
958
+ Fired when the thinking level changes. This is notification-only; handler return values are ignored.
959
+
960
+ ```typescript
961
+ pi.on("thinking_level_select", async (event, ctx) => {
962
+ // event.level - newly selected thinking level
963
+ // event.previousLevel - previous thinking level
964
+
965
+ ctx.ui.setStatus("thinking", `thinking: ${event.level}`);
966
+ });
967
+ ```
968
+
969
+ Use this to update extension UI when `pi.setThinkingLevel()`, model changes, or built-in thinking-level controls change the active thinking level.
970
+
971
+ <a id="tool-call-events"></a>
972
+
973
+ ### Tool Events
974
+
975
+ #### tool_call
976
+
977
+ Fired after `tool_execution_start`, before the tool executes. **Can block.** Use `isToolCallEventType` to narrow and get typed inputs.
978
+
979
+ Before `tool_call` runs, draht waits for previously emitted Agent events to finish draining through `AgentSession`. This means `ctx.sessionManager` is up to date through the current assistant tool-calling message.
980
+
981
+ In the default parallel tool execution mode, sibling tool calls from the same assistant message are preflighted sequentially, then executed concurrently. `tool_call` is not guaranteed to see sibling tool results from that same assistant message in `ctx.sessionManager`.
982
+
983
+ `event.input` is mutable. Mutate it in place to patch tool arguments before execution.
984
+
985
+ Behavior guarantees:
986
+ - Mutations to `event.input` affect the actual tool execution
987
+ - Later `tool_call` handlers see mutations made by earlier handlers
988
+ - No re-validation is performed after your mutation
989
+ - Return values from `tool_call` control blocking via `{ block: true, reason?: string, terminate?: boolean }`
990
+ - `terminate` only applies to a blocked call; the agent stops early only when every finalized result in the batch is terminating
991
+
992
+ ```typescript
993
+ import { isToolCallEventType } from "@draht/coding-agent";
994
+
995
+ pi.on("tool_call", async (event, ctx) => {
996
+ // event.toolName - "bash", "read", "write", "edit", etc.
997
+ // event.toolCallId
998
+ // event.input - tool parameters (mutable)
999
+
1000
+ // Built-in tools: no type params needed
1001
+ if (isToolCallEventType("bash", event)) {
1002
+ // event.input is { command: string; timeout?: number }
1003
+ event.input.command = `source ~/.profile\n${event.input.command}`;
1004
+
1005
+ if (event.input.command.includes("rm -rf")) {
1006
+ return { block: true, reason: "Dangerous command", terminate: true };
1007
+ }
1008
+ }
1009
+
1010
+ if (isToolCallEventType("read", event)) {
1011
+ // event.input is { path: string; offset?: number; limit?: number }
1012
+ console.log(`Reading: ${event.input.path}`);
1013
+ }
1014
+ });
1015
+ ```
1016
+
1017
+ #### Typing custom tool input
1018
+
1019
+ Custom tools should export their input type:
1020
+
1021
+ ```typescript
1022
+ // my-tool.ts
1023
+ import { type Static, Type } from "typebox";
1024
+
1025
+ export const myToolSchema = Type.Object({ action: Type.String() });
1026
+ export type MyToolInput = Static<typeof myToolSchema>;
1027
+ ```
1028
+
1029
+ Use `isToolCallEventType` with explicit type parameters:
1030
+
1031
+ ```typescript
1032
+ import { isToolCallEventType } from "@draht/coding-agent";
1033
+ import type { MyToolInput } from "./my-tool.ts";
1034
+
1035
+ pi.on("tool_call", (event) => {
1036
+ if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) {
1037
+ event.input.action; // typed
1038
+ }
1039
+ });
1040
+ ```
1041
+
1042
+ #### tool_result
1043
+
1044
+ Fired after tool execution finishes and before `tool_execution_end` plus the final tool result message events are emitted. **Can modify result.**
1045
+
1046
+ In parallel tool mode, `tool_result` and `tool_execution_end` may interleave in tool completion order, while final `toolResult` message events are still emitted later in assistant source order.
1047
+
1048
+ `tool_result` handlers chain like middleware:
1049
+ - Handlers run in extension load order
1050
+ - Each handler sees the latest result after previous handler changes
1051
+ - Handlers can return partial patches (`content`, `details`, `structuredContent`, `isError`, or `usage`); omitted fields keep their current values
1052
+ - Replacing `content` without returning `structuredContent` drops the structured content, because it may no longer match
1053
+
1054
+ Use `ctx.signal` for nested async work inside the handler. This lets Esc cancel model calls, `fetch()`, and other abort-aware operations started by the extension.
1055
+
1056
+ ```typescript
1057
+ import { isBashToolResult } from "@draht/coding-agent";
1058
+
1059
+ pi.on("tool_result", async (event, ctx) => {
1060
+ // event.toolName, event.toolCallId, event.input, event.parentToolCallId
1061
+ // event.content, event.details, event.structuredContent, event.isError, event.usage
1062
+
1063
+ if (isBashToolResult(event)) {
1064
+ // event.details is typed as BashToolDetails
1065
+ }
1066
+
1067
+ const response = await fetch("https://example.com/summarize", {
1068
+ method: "POST",
1069
+ body: JSON.stringify({ content: event.content }),
1070
+ signal: ctx.signal,
1071
+ });
1072
+
1073
+ // Modify result:
1074
+ return { content: [...], details: {...}, isError: false, usage: nestedModelUsage };
1075
+ });
1076
+ ```
1077
+
1078
+ ### User Bash Events
1079
+
1080
+ #### user_bash
1081
+
1082
+ Fired when user executes `!` or `!!` commands. **Can intercept.**
1083
+
1084
+ ```typescript
1085
+ import { createLocalBashOperations } from "@draht/coding-agent";
1086
+
1087
+ pi.on("user_bash", (event, ctx) => {
1088
+ // event.command - the bash command
1089
+ // event.excludeFromContext - true if !! prefix
1090
+ // event.cwd - working directory
1091
+
1092
+ // Option 1: Provide custom operations (e.g., SSH)
1093
+ return { operations: remoteBashOps };
1094
+
1095
+ // Option 2: Wrap draht's built-in local bash backend
1096
+ const local = createLocalBashOperations();
1097
+ return {
1098
+ operations: {
1099
+ exec(command, cwd, options) {
1100
+ return local.exec(`source ~/.profile\n${command}`, cwd, options);
1101
+ }
1102
+ }
1103
+ };
1104
+
1105
+ // Option 3: Full replacement - return result directly
1106
+ return { result: { output: "...", exitCode: 0, cancelled: false, truncated: false } };
1107
+ });
1108
+ ```
1109
+
1110
+ Returning `undefined` continues to the next handler, then local execution if none handles the event. A valid result stops propagation: `operations` executes the command through the supplied backend, while `result` records the completed command without executing it.
1111
+
1112
+ ### Input Events
1113
+
1114
+ #### input
1115
+
1116
+ Fired when user input is received, after extension commands are checked but before skill and template expansion. The event sees the raw input text, so `/skill:foo` and `/template` are not yet expanded.
1117
+
1118
+ **Processing order:**
1119
+ 1. Extension commands (`/cmd`) checked first - if found, handler runs and input event is skipped. Messages from `pi.sendUserMessage()` are checked only with `expandPromptTemplates: true`.
1120
+ 2. `input` event fires - can intercept, transform, or handle
1121
+ 3. If not handled: skill commands (`/skill:name`) expanded to skill content
1122
+ 4. If not handled: prompt templates (`/template`) expanded to template content
1123
+ 5. Agent processing begins (`before_agent_start`, etc.)
1124
+
1125
+ ```typescript
1126
+ pi.on("input", async (event, ctx) => {
1127
+ // event.text - raw input (before skill/template expansion)
1128
+ // event.images - attached images, if any
1129
+ // event.source - "interactive" (typed), "rpc" (API), or "extension" (via sendUserMessage)
1130
+ // event.streamingBehavior - "steer" | "followUp" | undefined
1131
+ // undefined when idle, "steer" for mid-stream interrupts,
1132
+ // "followUp" for messages queued until the agent finishes
1133
+
1134
+ // Transform: rewrite input before expansion
1135
+ if (event.text.startsWith("?quick "))
1136
+ return { action: "transform", text: `Respond briefly: ${event.text.slice(7)}` };
1137
+
1138
+ // Handle: respond without LLM (extension shows its own feedback)
1139
+ if (event.text === "ping") {
1140
+ ctx.ui.notify("pong", "info");
1141
+ return { action: "handled" };
1142
+ }
1143
+
1144
+ // Route by source: skip processing for extension-injected messages
1145
+ if (event.source === "extension") return { action: "continue" };
1146
+
1147
+ // Intercept skill commands before expansion
1148
+ if (event.text.startsWith("/skill:")) {
1149
+ // Could transform, block, or let pass through
1150
+ }
1151
+
1152
+ return { action: "continue" }; // Default: pass through to expansion
1153
+ });
1154
+ ```
1155
+
1156
+ **Results:**
1157
+ - `continue` - pass through unchanged (default if handler returns nothing)
1158
+ - `transform` - modify text/images, then continue to expansion
1159
+ - `handled` - skip agent entirely (first handler to return this wins)
1160
+
1161
+ Transforms chain across handlers. See [input-transform.ts](../examples/extensions/input-transform.ts) and [input-transform-streaming.ts](../examples/extensions/input-transform-streaming.ts) for `streamingBehavior`-aware routing.
1162
+
1163
+ <a id="use-extension-context"></a>
1164
+
1165
+ ## ExtensionContext
1166
+
1167
+ All handlers receive `ctx: ExtensionContext`. Tool `execute()` receives `ExtensionToolContext`, which adds `ctx.tools` and `ctx.executeTool()` (see [Calling Other Tools](#calling-other-tools)). Command handlers receive [`ExtensionCommandContext`](#extensioncommandcontext).
1168
+
1169
+ ### ctx.ui
1170
+
1171
+ UI methods for user interaction. See [Custom UI](#custom-ui) for full details.
1172
+
1173
+ ### ctx.mode
1174
+
1175
+ Current run mode: `"tui"`, `"rpc"`, `"json"`, or `"print"`. Use `ctx.mode === "tui"` to guard terminal-only features such as `custom()`, component factories, terminal input, and direct TUI rendering.
1176
+
1177
+ ### ctx.hasUI
1178
+
1179
+ `true` in TUI and RPC modes. `false` in print mode (`-p`) and JSON mode. Use this to guard dialog methods (`select`, `confirm`, `input`, `editor`) and fire-and-forget methods (`notify`, `setStatus`, `setWidget`, `setTitle`, `setEditorText`) that work in both TUI and RPC modes. In RPC mode, some TUI-specific methods are no-ops or return defaults (see [RPC Extension UI](rpc-extension-ui.md)).
1180
+
1181
+ ### ctx.cwd
1182
+
1183
+ Current working directory.
1184
+
1185
+ Use `CONFIG_DIR_NAME` instead of hardcoding `.draht` when constructing project-local config paths. Rebranded distributions can use a different config directory name.
1186
+
1187
+ ```typescript
1188
+ import { CONFIG_DIR_NAME, type ExtensionAPI } from "@draht/coding-agent";
1189
+ import { join } from "node:path";
1190
+
1191
+ export default function (pi: ExtensionAPI) {
1192
+ pi.on("session_start", (_event, ctx) => {
1193
+ const projectConfigPath = join(ctx.cwd, CONFIG_DIR_NAME, "my-extension.json");
1194
+ // ...
1195
+ });
1196
+ }
1197
+ ```
1198
+
1199
+ ### ctx.isProjectTrusted()
1200
+
1201
+ Returns whether project-local trust is active for the current session context. This includes temporary trust decisions and CLI trust overrides, not just saved decisions in the global trust store.
1202
+
1203
+ Use this before reading project-local extension configuration that should only be honored for trusted projects.
1204
+
1205
+ ### ctx.sessionManager
1206
+
1207
+ Read-only access to session state: `getCwd()`, `getSessionDir()`, `getSessionId()`, `getSessionFile()`, `getSessionName()`, `getHeader()`, `getEntries()`, `getEntry()`, `getBranch()`, `getTree()`, `getLeafId()`, `getLeafEntry()`, `getLabel()`, `buildContextEntries()`, and `buildSessionProjection()`. See [Session Format](session-format.md) for entry types.
1208
+
1209
+ For `tool_call`, this state is synchronized through the current assistant message before handlers run. In parallel tool execution mode it is still not guaranteed to include sibling tool results from the same assistant message.
1210
+
1211
+ ```typescript
1212
+ ctx.sessionManager.getEntries() // All entries
1213
+ ctx.sessionManager.getBranch() // Current branch
1214
+ ctx.sessionManager.buildContextEntries() // Active branch entries with compaction applied
1215
+ ctx.sessionManager.getLeafId() // Current leaf entry ID
1216
+ ```
1217
+
1218
+ ### ctx.modelRegistry / ctx.model / ctx.thinkingLevel / ctx.scopedModels
1219
+
1220
+ Access to models, providers, and resolved authentication. `ctx.modelRegistry.getProvider(id)` returns the effective @draht/ai provider, while `getProviderAuth(id)` resolves its current API key, headers, base URL, and provider-scoped environment without requiring a loaded model. `ctx.model` is the active model, and `ctx.thinkingLevel` is its current effective thinking level.
1221
+
1222
+ `ctx.scopedModels` is the read-only list of models scoped to the current session — the same set the `/scoped-models` command shows. It is resolved at session start from the `--models` CLI flag and the `enabledModels` setting (matched against the available catalogue with minimatch on `provider/modelId` or a bare `modelId`). It is empty when no scoping is configured, meaning every available model is usable. Each entry is `{ model, thinkingLevel? }`, where `thinkingLevel` is set only when a pattern pinned it (e.g. `anthropic/*:high`). Use it to populate a model picker that mirrors the built-in one instead of enumerating the whole catalogue via `ctx.modelRegistry.getAvailable()`.
1223
+
1224
+ #### Streaming model calls
1225
+
1226
+ Use `ctx.modelRegistry.streamSimple(model, context, options)` for provider-neutral options such as `reasoning`, or `complete(model, context, options)` to await the final assistant message with API-specific options. Both use configured providers and resolve authentication, including for providers registered with `pi.registerProvider()`. Use these instead of `@draht/ai/compat` streaming functions, which cannot see extension provider registrations.
1227
+
1228
+ `streamSimple()` returns an `AssistantMessageEventStream`. Iterate it for response events and await `.result()` for the final message. Setup failures produce error events and error results.
1229
+
1230
+ For non-chat models, `findOfType()`, `getModelsOfType()`, `getAvailableOfType()`, and `getModelOfType()` look up image and classifier models, and `classify()` and `generateImages()` call them. See [Use classifier models](models.md#use-classifier-models) and [Use image models](models.md#use-image-models).
1231
+
1232
+ ### ctx.signal
1233
+
1234
+ The current agent abort signal, or `undefined` when no agent turn is active.
1235
+
1236
+ Use this for abort-aware nested work started by extension handlers, for example:
1237
+ - `fetch(..., { signal: ctx.signal })`
1238
+ - model calls that accept `signal`
1239
+ - file or process helpers that accept `AbortSignal`
1240
+
1241
+ `ctx.signal` is typically defined during active turn events such as `tool_call`, `tool_result`, `message_update`, and `turn_end`.
1242
+ It is usually `undefined` in idle or non-turn contexts such as session events, extension commands, and shortcuts fired while draht is idle.
1243
+
1244
+ ```typescript
1245
+ pi.on("tool_result", async (event, ctx) => {
1246
+ const response = await fetch("https://example.com/api", {
1247
+ method: "POST",
1248
+ body: JSON.stringify(event),
1249
+ signal: ctx.signal,
1250
+ });
1251
+
1252
+ const data = await response.json();
1253
+ return { details: data };
1254
+ });
1255
+ ```
1256
+
1257
+ ### ctx.isIdle() / ctx.abort() / ctx.hasPendingMessages()
1258
+
1259
+ Control flow helpers. `ctx.isIdle()` is false while draht is processing an agent run, automatic retry, auto-compaction retry, or queued continuation.
1260
+
1261
+ ### ctx.shutdown()
1262
+
1263
+ Request a graceful shutdown of draht.
1264
+
1265
+ - **Interactive mode:** Deferred until the agent becomes idle (after processing all queued steering and follow-up messages).
1266
+ - **RPC mode:** Runs right away when the session is idle and no command is being handled. Otherwise deferred until the current command finishes (including its response) or the active run settles. (A request made while an extension-started compaction is running waits for the next command or run to finish.)
1267
+ - **Print mode:** No-op. The process exits automatically when all prompts are processed.
1268
+
1269
+ Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands, shortcuts).
1270
+
1271
+ ```typescript
1272
+ pi.on("tool_call", (event, ctx) => {
1273
+ if (isFatal(event.input)) {
1274
+ ctx.shutdown();
1275
+ }
1276
+ });
1277
+ ```
1278
+
1279
+ ### ctx.getContextUsage()
1280
+
1281
+ Returns current context usage for the active model. Uses last assistant usage when available, then estimates tokens for trailing messages.
1282
+
1283
+ ```typescript
1284
+ const usage = ctx.getContextUsage();
1285
+ if (usage?.tokens != null && usage.tokens > 100_000) {
1286
+ // ...
1287
+ }
1288
+ ```
1289
+
1290
+ ### ctx.compact()
1291
+
1292
+ Trigger compaction without awaiting completion. Use `onComplete` and `onError` for follow-up actions.
1293
+
1294
+ ```typescript
1295
+ ctx.compact({
1296
+ customInstructions: "Focus on recent changes",
1297
+ onComplete: (result) => {
1298
+ ctx.ui.notify("Compaction completed", "info");
1299
+ },
1300
+ onError: (error) => {
1301
+ ctx.ui.notify(`Compaction failed: ${error.message}`, "error");
1302
+ },
1303
+ });
1304
+ ```
1305
+
1306
+ ### ctx.getSystemPrompt()
1307
+
1308
+ Returns draht's current system prompt string.
1309
+
1310
+ - During `before_agent_start`, this reflects chained system-prompt changes made so far for the current turn.
1311
+ - It does not include later `context` message mutations.
1312
+ - It does not include `before_provider_request` payload rewrites.
1313
+ - If later-loaded extensions run after yours, they can still change what is ultimately sent.
1314
+
1315
+ ```typescript
1316
+ pi.on("before_agent_start", (event, ctx) => {
1317
+ const prompt = ctx.getSystemPrompt();
1318
+ console.log(`System prompt length: ${prompt.length}`);
1319
+ });
1320
+ ```
1321
+
1322
+ ## ExtensionCommandContext
1323
+
1324
+ Command handlers receive `ExtensionCommandContext`, which extends `ExtensionContext` with session control methods. These are only available in commands because they can deadlock if called from event handlers.
1325
+
1326
+ ### ctx.getSystemPromptOptions()
1327
+
1328
+ Returns the base inputs draht currently uses to build the system prompt.
1329
+
1330
+ ```typescript
1331
+ const options = ctx.getSystemPromptOptions();
1332
+ const contextPaths = options.contextFiles?.map((file) => file.path) ?? [];
1333
+ ```
1334
+
1335
+ This has the same shape and mutability as `before_agent_start` `event.systemPromptOptions`: custom or forced prompt, active tools, tool snippets, per-tool and custom rules, custom sections, appended prompt text, cwd, loaded context files, and loaded skills. It may include full context file contents, so treat it as sensitive extension-local data and avoid exposing it through command lists, logs, or autocomplete metadata.
1336
+
1337
+ This reports the current base prompt inputs. It does not include per-turn `before_agent_start` chained system-prompt changes, later `context` event message mutations, or `before_provider_request` payload rewrites.
1338
+
1339
+ ### ctx.waitForIdle()
1340
+
1341
+ Wait for the agent to fully settle, including automatic retries, auto-compaction retries, and queued continuations:
1342
+
1343
+ ```typescript
1344
+ pi.registerCommand("my-cmd", {
1345
+ handler: async (args, ctx) => {
1346
+ await ctx.waitForIdle();
1347
+ // Agent is now idle, safe to modify session
1348
+ },
1349
+ });
1350
+ ```
1351
+
1352
+ ### ctx.newSession(options?)
1353
+
1354
+ Create a new session:
1355
+
1356
+ ```typescript
1357
+ const parentSession = ctx.sessionManager.getSessionFile();
1358
+ const kickoff = "Continue in the replacement session";
1359
+
1360
+ const result = await ctx.newSession({
1361
+ parentSession,
1362
+ setup: async (sm) => {
1363
+ sm.appendMessage({
1364
+ role: "user",
1365
+ content: [{ type: "text", text: "Context from previous session..." }],
1366
+ timestamp: Date.now(),
1367
+ });
1368
+ },
1369
+ withSession: async (ctx) => {
1370
+ // Use only the replacement-session ctx here.
1371
+ await ctx.sendUserMessage(kickoff);
1372
+ },
1373
+ });
1374
+
1375
+ if (result.cancelled) {
1376
+ // An extension cancelled the new session
1377
+ }
1378
+ ```
1379
+
1380
+ Options:
1381
+ - `parentSession`: parent session file to record in the new session header
1382
+ - `setup`: mutate the new session's `SessionManager` before `withSession` runs
1383
+ - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `draht` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1384
+
1385
+ ### ctx.fork(entryId, options?)
1386
+
1387
+ Fork from a specific entry, creating a new session file:
1388
+
1389
+ ```typescript
1390
+ const result = await ctx.fork("entry-id-123", {
1391
+ withSession: async (ctx) => {
1392
+ // Use only the replacement-session ctx here.
1393
+ ctx.ui.notify("Now in the forked session", "info");
1394
+ },
1395
+ });
1396
+ if (result.cancelled) {
1397
+ // An extension cancelled the fork
1398
+ }
1399
+
1400
+ const cloneResult = await ctx.fork("entry-id-456", { position: "at" });
1401
+ if (cloneResult.cancelled) {
1402
+ // An extension cancelled the clone
1403
+ }
1404
+ ```
1405
+
1406
+ Options:
1407
+ - `position`: `"before"` (default) forks before the selected user message, restoring that prompt into the editor
1408
+ - `position`: `"at"` duplicates the active path through the selected entry without restoring editor text
1409
+ - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `draht` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1410
+
1411
+ ### ctx.navigateTree(targetId, options?)
1412
+
1413
+ Navigate to a different point in the session tree. Rejects while an agent response, manual or automatic compaction, or another tree navigation is active, even with `summarize: false`. These conflicts leave the active branch unchanged and reject the promise rather than returning `{ cancelled: true }`. Wait for the active operation to finish (for example, with `await ctx.waitForIdle()` in a command handler) and retry. It also rejects when `summarize` is set without an available model, or when the target entry does not exist:
1414
+
1415
+ ```typescript
1416
+ const result = await ctx.navigateTree("entry-id-456", {
1417
+ summarize: true,
1418
+ customInstructions: "Focus on error handling changes",
1419
+ replaceInstructions: false, // true = replace default prompt entirely
1420
+ label: "review-checkpoint",
1421
+ });
1422
+ ```
1423
+
1424
+ Options:
1425
+ - `summarize`: Whether to generate a summary of the abandoned branch
1426
+ - `customInstructions`: Custom instructions for the summarizer
1427
+ - `replaceInstructions`: If true, `customInstructions` replaces the default prompt instead of being appended
1428
+ - `label`: Label to attach to the branch summary entry (or target entry if not summarizing)
1429
+
1430
+ ### ctx.switchSession(sessionPath, options?)
1431
+
1432
+ Switch to a different session file:
1433
+
1434
+ ```typescript
1435
+ const result = await ctx.switchSession("/path/to/session.jsonl", {
1436
+ withSession: async (ctx) => {
1437
+ await ctx.sendUserMessage("Resume work in the replacement session");
1438
+ },
1439
+ });
1440
+ if (result.cancelled) {
1441
+ // An extension cancelled the switch via session_before_switch
1442
+ }
1443
+ ```
1444
+
1445
+ Options:
1446
+ - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `draht` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1447
+
1448
+ To discover available sessions, use the static `SessionManager.list()` or `SessionManager.listAll()` methods:
1449
+
1450
+ ```typescript
1451
+ import { SessionManager } from "@draht/coding-agent";
1452
+
1453
+ pi.registerCommand("switch", {
1454
+ description: "Switch to another session",
1455
+ handler: async (args, ctx) => {
1456
+ const sessions = await SessionManager.list(ctx.cwd);
1457
+ if (sessions.length === 0) return;
1458
+ const choice = await ctx.ui.select(
1459
+ "Pick session:",
1460
+ sessions.map((s) => s.path),
1461
+ );
1462
+ if (choice) {
1463
+ await ctx.switchSession(choice, {
1464
+ withSession: async (ctx) => {
1465
+ ctx.ui.notify("Switched session", "info");
1466
+ },
1467
+ });
1468
+ }
1469
+ },
1470
+ });
1471
+ ```
1472
+
1473
+ ### Session replacement lifecycle and footguns
1474
+
1475
+ `withSession` receives a fresh `ReplacedSessionContext`, which extends `ExtensionCommandContext` with async `sendMessage()` and `sendUserMessage()` helpers bound to the replacement session.
1476
+
1477
+ Lifecycle and footguns:
1478
+ - `withSession` runs only after the old session has emitted `session_shutdown`, the old runtime has been torn down, the replacement session has been rebound, and the new extension instance has already received `session_start`.
1479
+ - The callback still executes in the original closure, not inside the new extension instance. That means your old extension instance may already have run its shutdown cleanup before `withSession` starts.
1480
+ - Captured old `draht` / old command `ctx` session-bound objects are stale after replacement and will throw if used. Use only the `ctx` passed to `withSession` for session-bound work.
1481
+ - Previously extracted raw objects are still your responsibility. For example, if you capture `const sm = ctx.sessionManager` before replacement, `sm` is still the old `SessionManager` object. Do not reuse it after replacement.
1482
+ - Code in `withSession` should assume any state invalidated by your `session_shutdown` handler is already gone. Only capture plain data that survives shutdown cleanly, such as strings, ids, and serialized config.
1483
+
1484
+ Safe pattern:
1485
+
1486
+ ```typescript
1487
+ pi.registerCommand("handoff", {
1488
+ handler: async (_args, ctx) => {
1489
+ const kickoff = "Continue from the replacement session";
1490
+ await ctx.newSession({
1491
+ withSession: async (ctx) => {
1492
+ await ctx.sendUserMessage(kickoff);
1493
+ },
1494
+ });
1495
+ },
1496
+ });
1497
+ ```
1498
+
1499
+ Unsafe pattern:
1500
+
1501
+ ```typescript
1502
+ pi.registerCommand("handoff", {
1503
+ handler: async (_args, ctx) => {
1504
+ const oldSessionManager = ctx.sessionManager;
1505
+ await ctx.newSession({
1506
+ withSession: async (_ctx) => {
1507
+ // stale old objects: do not do this
1508
+ oldSessionManager.getSessionFile();
1509
+ pi.sendUserMessage("wrong");
1510
+ },
1511
+ });
1512
+ },
1513
+ });
1514
+ ```
1515
+
1516
+ ### ctx.reload()
1517
+
1518
+ Run the same reload flow as `/reload`.
1519
+
1520
+ ```typescript
1521
+ pi.registerCommand("reload-runtime", {
1522
+ description: "Reload extensions, skills, prompts, themes, and context files",
1523
+ handler: async (_args, ctx) => {
1524
+ await ctx.reload();
1525
+ return;
1526
+ },
1527
+ });
1528
+ ```
1529
+
1530
+ Important behavior:
1531
+ - `await ctx.reload()` emits `session_shutdown` for the current extension runtime
1532
+ - It then reloads resources and emits `session_start` with `reason: "reload"` and `resources_discover` with reason `"reload"`
1533
+ - The currently running command handler still continues in the old call frame
1534
+ - Code after `await ctx.reload()` still runs from the pre-reload version
1535
+ - Code after `await ctx.reload()` must not assume old in-memory extension state is still valid
1536
+ - After the handler returns, future commands/events/tool calls use the new extension version
1537
+
1538
+ For predictable behavior, treat reload as terminal for that handler (`await ctx.reload(); return;`).
1539
+
1540
+ Tools run with `ExtensionToolContext`, not `ExtensionCommandContext`, so they cannot call `ctx.reload()`, and draht cannot reload while the agent is running. To let the LLM trigger a reload, have the tool record the request and run the command from `agent_settled`, where messages sent by handlers are processed after all settled handlers finish:
1541
+
1542
+ ```typescript
1543
+ let reloadRequested = false;
1544
+
1545
+ pi.registerTool({
1546
+ name: "reload_runtime",
1547
+ label: "Reload Runtime",
1548
+ description: "Reload extensions, skills, prompts, themes, and context files",
1549
+ parameters: Type.Object({}),
1550
+ async execute() {
1551
+ reloadRequested = true;
1552
+ return {
1553
+ content: [{ type: "text", text: "Reload requested. draht reloads after this response." }],
1554
+ details: {},
1555
+ terminate: true,
1556
+ };
1557
+ },
1558
+ });
1559
+
1560
+ pi.on("agent_settled", () => {
1561
+ if (!reloadRequested) return;
1562
+ reloadRequested = false;
1563
+ pi.sendUserMessage("/reload-runtime", { expandPromptTemplates: true });
1564
+ });
1565
+ ```
1566
+
1567
+ `expandPromptTemplates: true` dispatches the text as a command. Without it, or when queued with `deliverAs`, the text reaches the model as a plain user message. See [reload-runtime.ts](../examples/extensions/reload-runtime.ts).
1568
+
1569
+ ## ExtensionAPI Methods
1570
+
1571
+ ### pi.on(event, handler)
1572
+
1573
+ Subscribe to events. Returns an unsubscribe function that removes only that registration. See [Events](#events) for event types and return values.
1574
+
1575
+ ```typescript
1576
+ const unsubscribe = pi.on("agent_end", async (event) => {
1577
+ unsubscribe();
1578
+ await updateIntegration(event.messages);
1579
+ });
1580
+ ```
1581
+
1582
+ Handlers run in extension load order, then registration order within each extension. Adding or removing a handler does not affect a dispatch already in progress.
1583
+
1584
+ ### pi.registerTool(definition)
1585
+
1586
+ Register a custom tool callable by the LLM. See [Custom Tools](#custom-tools) for full details.
1587
+
1588
+ `pi.registerTool()` works both during extension load and after startup. You can call it inside `session_start`, command handlers, or other event handlers. New tools are refreshed immediately in the same session, so they appear in `pi.getAllTools()` without `/reload`. Registering a tool activates it unless it sets `defaultActive: false` or an [exposure](#tool-exposure) other than `direct` or `model-only`.
1589
+
1590
+ Use `pi.setActiveTools()` to enable or disable tools (including dynamically added tools) at runtime.
1591
+
1592
+ Use `promptSnippet` to opt a custom tool into a one-line entry in the `<tools>` section of the default system prompt, and `promptGuidelines` to append tool-specific bullets to its `<rules>` section when the tool is active.
1593
+
1594
+ **Important:** `promptGuidelines` bullets are appended flat to the `<rules>` section with no tool name prefix. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead.
1595
+
1596
+ See [dynamic-tools.ts](../examples/extensions/dynamic-tools.ts) for a full example.
1597
+
1598
+ ```typescript
1599
+ import { Type } from "typebox";
1600
+ import { StringEnum } from "@draht/ai";
1601
+
1602
+ pi.registerTool({
1603
+ name: "my_tool",
1604
+ label: "My Tool",
1605
+ description: "What this tool does",
1606
+ promptSnippet: "Summarize or transform text according to action",
1607
+ promptGuidelines: ["Use my_tool when the user asks to summarize previously generated text."],
1608
+ parameters: Type.Object({
1609
+ action: StringEnum(["list", "add"] as const),
1610
+ text: Type.Optional(Type.String()),
1611
+ }),
1612
+
1613
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
1614
+ // Stream progress; partial results also need details
1615
+ onUpdate?.({ content: [{ type: "text", text: "Working..." }], details: { result: "pending" } });
1616
+
1617
+ return {
1618
+ content: [{ type: "text", text: "Done" }],
1619
+ details: { result: "..." },
1620
+ };
1621
+ },
1622
+
1623
+ // Optional: Custom rendering
1624
+ renderCall(args, theme, context) { ... },
1625
+ renderResult(result, options, theme, context) { ... },
1626
+ });
1627
+ ```
1628
+
1629
+ ### pi.sendMessage(message, options?)
1630
+
1631
+ Inject a custom message into the session. Custom messages participate in LLM context. For durable TUI-only content that should not be sent to the LLM, use [`pi.appendEntry()`](#piappendentrycustomtype-data) with [`pi.registerEntryRenderer()`](#piregisterentryrenderercustomtype-renderer).
1632
+
1633
+ ```typescript
1634
+ pi.sendMessage({
1635
+ customType: "my-extension",
1636
+ content: "Message text",
1637
+ display: true,
1638
+ details: { ... },
1639
+ }, {
1640
+ triggerTurn: true,
1641
+ deliverAs: "steer",
1642
+ });
1643
+ ```
1644
+
1645
+ **Options:**
1646
+ - `deliverAs` - Delivery mode:
1647
+ - `"steer"` (default) - Queues the message while streaming. Delivered after the current assistant turn finishes executing its tool calls, before the next LLM call.
1648
+ - `"followUp"` - Waits for agent to finish. Delivered only when agent has no more tool calls.
1649
+ - `"nextTurn"` - Queued for next user prompt. Does not interrupt or trigger anything.
1650
+ - `triggerTurn: true` - If agent is idle, trigger an LLM response immediately. Only applies to `"steer"` and `"followUp"` modes (ignored for `"nextTurn"`). Without it, an idle session stores the message without starting a turn.
1651
+ - `triggerTurn: false` while streaming - The message is not steered or queued as a follow-up; it is appended after the current turn ends.
1652
+
1653
+ ### pi.sendUserMessage(content, options?)
1654
+
1655
+ Send a user message to the agent. Unlike `sendMessage()` which sends custom messages, this sends an actual user message that appears as if typed by the user. It starts or queues a turn unless an `input` handler handles it or, with `expandPromptTemplates: true`, it runs an extension command.
1656
+
1657
+ ```typescript
1658
+ // Simple text message
1659
+ pi.sendUserMessage("What is 2+2?");
1660
+
1661
+ // With content array (text + images)
1662
+ pi.sendUserMessage([
1663
+ { type: "text", text: "Describe this image:" },
1664
+ { type: "image", data: "...", mimeType: "image/png" },
1665
+ ]);
1666
+
1667
+ // During streaming - must specify delivery mode
1668
+ pi.sendUserMessage("Focus on error handling", { deliverAs: "steer" });
1669
+ pi.sendUserMessage("And then summarize", { deliverAs: "followUp" });
1670
+
1671
+ // Opt in to extension command dispatch and skill/prompt template expansion
1672
+ pi.sendUserMessage("/review src/index.ts", { expandPromptTemplates: true });
1673
+ ```
1674
+
1675
+ **Options:**
1676
+ - `deliverAs` - Required when agent is streaming:
1677
+ - `"steer"` - Queues the message for delivery after the current assistant turn finishes executing its tool calls
1678
+ - `"followUp"` - Waits for agent to finish all tools
1679
+ - `expandPromptTemplates` - Dispatch extension commands and expand skill commands and prompt templates. Defaults to `false`.
1680
+
1681
+ When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, the message is rejected and draht reports an extension error.
1682
+
1683
+ See [send-user-message.ts](../examples/extensions/send-user-message.ts) for a complete example.
1684
+
1685
+ ### pi.appendEntry(customType, data?)
1686
+
1687
+ Persist extension data. Custom entries do NOT participate in LLM context. In interactive mode, they can also render inside the chat transcript when paired with `pi.registerEntryRenderer()`.
1688
+
1689
+ ```typescript
1690
+ pi.appendEntry("my-state", { count: 42 });
1691
+ pi.appendEntry("status-card", { title: "Indexed files", count: 17 });
1692
+
1693
+ // Restore on reload
1694
+ pi.on("session_start", async (_event, ctx) => {
1695
+ for (const entry of ctx.sessionManager.getEntries()) {
1696
+ if (entry.type === "custom" && entry.customType === "my-state") {
1697
+ // Reconstruct from entry.data
1698
+ }
1699
+ }
1700
+ });
1701
+ ```
1702
+
1703
+ ### pi.appendUsage(kind, provider, model, usage, note?)
1704
+
1705
+ For model-attributed usage that happens outside any tool result — a host-side run reported only through a later custom message, for example — call `pi.appendUsage(kind, provider, model, usage, note?)` instead; it records a usage entry directly in the session's totals and cost breakdown. Record each unit of usage exactly once, and never for usage already reported through a tool result, and treat a throw (a stale ctx after the session ended) as a safe no-op.
1706
+
1707
+ ### pi.checkpoints
1708
+
1709
+ draht snapshots the working tree per session so `/rewind` can restore conversation and files. `pi.checkpoints` exposes that store: `list()` and `get(entryId)` read recorded checkpoints, `restore()` restores an entry's checkpoint after taking a safety snapshot, and `capture(entryId)` records a new one. The calls never throw and degrade quietly when checkpoints are unavailable, such as before the session has a file or outside a git repository.
1710
+
1711
+ `checkpoint_created` fires after every capture. `session_before_rewind` reports the target entry and scope (`conversation-and-files`, `conversation-only`, or `files-only`) and can return `{ cancel: true }`. Retention is configured in [Settings](settings.md).
1712
+
1713
+ ### pi.setSessionName(name)
1714
+
1715
+ Set the session display name (shown in session selector instead of first message).
1716
+
1717
+ ```typescript
1718
+ pi.setSessionName("Refactor auth module");
1719
+ ```
1720
+
1721
+ ### pi.getSessionName()
1722
+
1723
+ Get the current session name, if set.
1724
+
1725
+ ```typescript
1726
+ const name = pi.getSessionName();
1727
+ if (name) {
1728
+ console.log(`Session: ${name}`);
1729
+ }
1730
+ ```
1731
+
1732
+ ### pi.setLabel(entryId, label)
1733
+
1734
+ Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation (shown in `/tree` selector).
1735
+
1736
+ ```typescript
1737
+ // Set a label
1738
+ pi.setLabel(entryId, "checkpoint-before-refactor");
1739
+
1740
+ // Clear a label
1741
+ pi.setLabel(entryId, undefined);
1742
+
1743
+ // Read labels via sessionManager
1744
+ const label = ctx.sessionManager.getLabel(entryId);
1745
+ ```
1746
+
1747
+ Labels persist in the session and survive restarts. Use them to mark important points (turns, checkpoints) in the conversation tree.
1748
+
1749
+ ### pi.registerCommand(name, options)
1750
+
1751
+ Register a command.
1752
+
1753
+ If multiple extensions register the same command name, draht keeps them all and assigns numeric invocation suffixes in load order, for example `/review:1` and `/review:2`.
1754
+
1755
+ ```typescript
1756
+ pi.registerCommand("stats", {
1757
+ description: "Show session statistics",
1758
+ handler: async (args, ctx) => {
1759
+ const count = ctx.sessionManager.getEntries().length;
1760
+ ctx.ui.notify(`${count} entries`, "info");
1761
+ }
1762
+ });
1763
+ ```
1764
+
1765
+ Optional: add argument auto-completion for `/command ...`. `getArgumentCompletions` can also return a `Promise`:
1766
+
1767
+ ```typescript
1768
+ import type { AutocompleteItem } from "@draht/tui";
1769
+
1770
+ pi.registerCommand("deploy", {
1771
+ description: "Deploy to an environment",
1772
+ getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => {
1773
+ const envs = ["dev", "staging", "prod"];
1774
+ const items = envs.map((e) => ({ value: e, label: e }));
1775
+ const filtered = items.filter((i) => i.value.startsWith(prefix));
1776
+ return filtered.length > 0 ? filtered : null;
1777
+ },
1778
+ handler: async (args, ctx) => {
1779
+ ctx.ui.notify(`Deploying: ${args}`, "info");
1780
+ },
1781
+ });
1782
+ ```
1783
+
1784
+ ### pi.getCommands()
1785
+
1786
+ Get the slash commands available for invocation via `prompt` in the current session. Includes extension commands, prompt templates, and skill commands.
1787
+ The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills. Skill commands are named `skill:<name>`.
1788
+
1789
+ ```typescript
1790
+ const commands = pi.getCommands();
1791
+ const bySource = commands.filter((command) => command.source === "extension");
1792
+ const userScoped = commands.filter((command) => command.sourceInfo.scope === "user");
1793
+ ```
1794
+
1795
+ Each entry has this shape:
1796
+
1797
+ ```typescript
1798
+ {
1799
+ name: string; // Invokable command name without the leading slash. May be suffixed like "review:1"
1800
+ description?: string;
1801
+ source: "extension" | "prompt" | "skill";
1802
+ sourceInfo: {
1803
+ path: string;
1804
+ source: string;
1805
+ scope: "user" | "project" | "temporary";
1806
+ origin: "package" | "top-level";
1807
+ baseDir?: string;
1808
+ };
1809
+ }
1810
+ ```
1811
+
1812
+ Use `sourceInfo` as the canonical provenance field. Do not infer ownership from command names or from ad hoc path parsing.
1813
+
1814
+ Built-in interactive commands (like `/model` and `/settings`) are not included here. They are handled only in interactive
1815
+ mode and would not execute if sent via `prompt`.
1816
+
1817
+ ### pi.registerMessageRenderer(customType, renderer)
1818
+
1819
+ Register a custom TUI renderer for custom messages with your `customType`. Custom messages are created with `pi.sendMessage()` and participate in LLM context. See [Custom UI](#custom-ui).
1820
+
1821
+ ### pi.registerMarkdownTransformer(transformer, options?)
1822
+
1823
+ Register a transformer for Markdown before draht renders it in interactive mode. Transformers run in extension load order, and each transformer receives the Markdown returned by the previous transformer. After the chain finishes, draht renders the transformed content with its built-in renderer.
1824
+
1825
+ By default a transformer runs on normal user text, assistant text, and thinking blocks. `options.messageTypes` lists the surfaces it runs on instead:
1826
+
1827
+ | `messageType` | Surface |
1828
+ |---------------|---------|
1829
+ | `"user"`, `"assistant"`, `"assistant-thinking"` | Transcript messages (default) |
1830
+ | `"custom"` | Custom messages from `pi.sendMessage()` without a registered message renderer, and expanded skill blocks (their content, without draht's header) |
1831
+ | `"summary"` | Expanded branch and compaction summaries (the summary, without draht's header) |
1832
+ | `"changelog"` | draht's changelog ("What's New" at startup and `/changelog`) and the startup "Extension Updates" notice |
1833
+
1834
+ The transformer receives the Markdown string and a context with:
1835
+
1836
+ - `messageType` — one of the surfaces above
1837
+ - `isStreaming` — `true` for partial assistant updates; `false` otherwise
1838
+ - `availableWidth` — exact terminal columns available for the transformed Markdown content
1839
+ - `messageId`, `timestamp` — session-entry ID and ISO timestamp when rendering from persisted session entries; `undefined` for live messages and notices
1840
+
1841
+ Return the transformed Markdown:
1842
+
1843
+ ```typescript
1844
+ pi.registerMarkdownTransformer((markdown, { messageType, isStreaming }) => {
1845
+ if (isStreaming || messageType === "assistant-thinking") return markdown;
1846
+ return markdown.replaceAll("-->", "→");
1847
+ });
1848
+
1849
+ // Show :warning: shortcodes in changelogs as a symbol.
1850
+ pi.registerMarkdownTransformer((markdown) => markdown.replaceAll(":warning:", "⚠"), {
1851
+ messageTypes: ["changelog"],
1852
+ });
1853
+ ```
1854
+
1855
+ If a transformer throws, draht keeps the Markdown produced so far and continues with the next transformer. The hook is display-only: the original message remains unchanged in the session and model context. It runs for new messages, assistant streaming updates, restored session messages, and terminal width changes, so transformers should remain synchronous and inexpensive. An extension has one transformer; registering again replaces it.
1856
+
1857
+ ### pi.registerEntryRenderer(customType, renderer)
1858
+
1859
+ Register a custom TUI renderer for custom entries with your `customType`. Custom entries are created with `pi.appendEntry()` and do not participate in LLM context.
1860
+
1861
+ ```typescript
1862
+ import { Box, Text } from "@draht/tui";
1863
+
1864
+ pi.registerEntryRenderer("status-card", (entry, { expanded }, theme) => {
1865
+ const data = entry.data as { title: string; count: number };
1866
+ const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text));
1867
+ box.addChild(new Text(`${theme.bold(data.title)}: ${data.count}`));
1868
+ if (expanded) {
1869
+ box.addChild(new Text(theme.fg("dim", JSON.stringify(data, null, 2))));
1870
+ }
1871
+ return box;
1872
+ });
1873
+
1874
+ pi.appendEntry("status-card", { title: "Indexed files", count: 17 });
1875
+ ```
1876
+
1877
+ ### pi.registerShortcut(shortcut, options)
1878
+
1879
+ Register a keyboard shortcut. See [keybindings.md](keybindings.md) for the shortcut format and built-in keybindings.
1880
+
1881
+ ```typescript
1882
+ pi.registerShortcut("ctrl+shift+p", {
1883
+ description: "Toggle plan mode",
1884
+ handler: async (ctx) => {
1885
+ ctx.ui.notify("Toggled!");
1886
+ },
1887
+ });
1888
+ ```
1889
+
1890
+ ### pi.registerFlag(name, options)
1891
+
1892
+ Register a CLI flag.
1893
+
1894
+ ```typescript
1895
+ pi.registerFlag("plan", {
1896
+ description: "Start in plan mode",
1897
+ type: "boolean",
1898
+ default: false,
1899
+ });
1900
+
1901
+ // Check the value after loading; in the factory, getFlag() returns the default
1902
+ pi.on("session_start", () => {
1903
+ if (pi.getFlag("plan")) {
1904
+ // Plan mode enabled
1905
+ }
1906
+ });
1907
+ ```
1908
+
1909
+ ### pi.exec(command, args, options?)
1910
+
1911
+ Execute a command without a shell.
1912
+
1913
+ ```typescript
1914
+ const result = await pi.exec("git", ["status"], { signal, timeout: 5000 });
1915
+ // result.stdout, result.stderr, result.code, result.killed, result.truncated
1916
+ ```
1917
+
1918
+ Options: `signal` and `timeout` terminate the command, `cwd` sets the working directory, and `maxBuffer` limits stdout and stderr combined (default 256 MiB). When output exceeds `maxBuffer`, draht terminates the command and returns the output up to the limit with `truncated: true`, `killed: true`, and a nonzero `code`. `killed` is true whenever draht terminated the command: timeout, abort, or `maxBuffer`. A command that ignores SIGTERM gets SIGKILL after 5 seconds.
1919
+
1920
+ ### pi.getActiveTools() / pi.getAllTools() / pi.setActiveTools(names)
1921
+
1922
+ Manage active tools. This works for both built-in tools and dynamically registered tools. `pi.getActiveTools()` returns the active tool names as `string[]`; `pi.getAllTools()` returns metadata for all configured tools.
1923
+
1924
+ ```typescript
1925
+ const active = pi.getActiveTools(); // ["read", "bash", ...]
1926
+ const all = pi.getAllTools();
1927
+ // all = [{
1928
+ // name: "read",
1929
+ // description: "Read file contents...",
1930
+ // parameters: ...,
1931
+ // promptGuidelines: ["Use read to examine files instead of cat or sed."],
1932
+ // exposure: "direct",
1933
+ // sourceInfo: { path: "builtin:read", source: "builtin", scope: "temporary", origin: "top-level" }
1934
+ // }, ...]
1935
+ // Tools shipped with draht: core tools and tools from built-in extensions such as builtin:mcp
1936
+ const shippedTools = all.filter((t) => t.sourceInfo.source === "builtin");
1937
+ // Tools from installed or local extensions
1938
+ const extensionTools = all.filter((t) => t.sourceInfo.source !== "builtin" && t.sourceInfo.source !== "sdk");
1939
+ pi.setActiveTools([...new Set([...active, "my_custom_tool"])]); // Keep current tools and enable my_custom_tool
1940
+ pi.setActiveTools(["read", "bash"]); // Only read and bash
1941
+ ```
1942
+
1943
+ `pi.getAllTools()` returns `name`, `description`, `parameters`, `promptGuidelines`, `exposure`, `sourceInfo`, and, when set, `namespace`, `annotations`, and `reachesTools`.
1944
+
1945
+ Typical `sourceInfo` values:
1946
+ - `source: "builtin"` for tools shipped with draht: core tools (`path: "builtin:<tool>"`) and tools registered by built-in extensions such as `builtin:mcp` (`path: "builtin:<extension>"`)
1947
+ - `source: "sdk"` for tools passed via `createAgentSession({ customTools })`
1948
+ - extension source metadata for tools registered by extensions
1949
+
1950
+ `pi.setActiveTools()` ignores unknown and `hidden` tools. Tools with `codemode` or `deferred` exposure stay callable from codemode scripts whether active or not.
1951
+
1952
+ ### pi.setModel(model)
1953
+
1954
+ Set the model for the current session. The change is recorded in session history and restored when that session is resumed, but it does not change the configured `defaultProvider` or `defaultModel` used by new sessions unless you pass `{ persist: true }`, which also updates the user's global default. Returns `false` if authentication is not configured for the model's provider. See [models.md](models.md) for configuring custom models.
1955
+
1956
+ ```typescript
1957
+ const model = ctx.modelRegistry.find("anthropic", "claude-sonnet-4-5");
1958
+ if (model) {
1959
+ const success = await pi.setModel(model);
1960
+ if (!success) {
1961
+ ctx.ui.notify("No API key for this model", "error");
1962
+ }
1963
+ }
1964
+ ```
1965
+
1966
+ ### pi.getThinkingLevel() / pi.setThinkingLevel(level)
1967
+
1968
+ Get the current thinking level. Level is clamped to model capabilities (non-reasoning models always use "off"). Changes emit `thinking_level_select`.
1969
+
1970
+ `pi.setThinkingLevel()` changes the thinking level for the current session. The change is recorded in session history and restored when that session is resumed, but it does not change the configured default used by new sessions unless you pass `{ persist: true }`.
1971
+
1972
+ ```typescript
1973
+ const current = pi.getThinkingLevel(); // "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"
1974
+ pi.setThinkingLevel("high");
1975
+ ```
1976
+
1977
+ ### pi.events
1978
+
1979
+ Shared event bus for communication between extensions:
1980
+
1981
+ ```typescript
1982
+ pi.events.on("my:event", (data) => { ... });
1983
+ pi.events.emit("my:event", { ... });
1984
+ ```
1985
+
1986
+ ### pi.registerProvider(name, config)
1987
+
1988
+ Register or override a model provider dynamically. Useful for proxies, custom endpoints, or team-wide model configurations.
1989
+
1990
+ Calls made during the extension factory function are queued and applied once the runner initialises. Calls made after that — for example from a command handler following a user setup flow — take effect immediately without requiring a `/reload`.
1991
+
1992
+ Dynamic providers can implement `refreshModels`. draht calls it during model refresh, publishes the returned list synchronously through the provider, and passes the canonical credential/stored-catalog/network/signal context. The extension decides whether to persist catalog metadata through generation-checked `context.publish({ persist: entry })`; live servers such as llama.cpp can return models without persisting them.
1993
+
1994
+ `context.signal` is always a concrete signal and provider callbacks must pass it to blocking I/O. Public `ModelRuntime.refresh()` and `ModelRegistry.refresh()` calls accept an optional signal and are unbounded when it is omitted; extensions and applications choose their own deadlines. Cancellation stops the caller waiting even if a provider ignores the signal, but cooperation is still required to stop the underlying work.
1995
+
1996
+ Extensions that need native provider auth, filtering, refresh, or stream behavior can register a complete `Provider` from `@draht/ai`. The provider becomes the composition base and `models.json` overrides still apply above it.
1997
+
1998
+ ```typescript
1999
+ import { createProvider, openAICompletionsApi } from "@draht/ai/compat";
2000
+
2001
+ const provider = createProvider({
2002
+ id: "local-server",
2003
+ name: "Local Server",
2004
+ baseUrl: "http://localhost:8080/v1",
2005
+ auth: {
2006
+ apiKey: {
2007
+ name: "Local server setup",
2008
+ async login(interaction) {
2009
+ return {
2010
+ type: "api_key",
2011
+ key: await interaction.prompt({ type: "secret", message: "API key" }),
2012
+ };
2013
+ },
2014
+ async resolve({ credential }) {
2015
+ return credential?.key
2016
+ ? { auth: { apiKey: credential.key }, source: "stored API key" }
2017
+ : undefined;
2018
+ },
2019
+ },
2020
+ },
2021
+ models: [],
2022
+ api: openAICompletionsApi(),
2023
+ });
2024
+
2025
+ pi.registerProvider(provider);
2026
+
2027
+ // Register a new provider with custom models
2028
+ pi.registerProvider("my-proxy", {
2029
+ name: "My Proxy",
2030
+ baseUrl: "https://proxy.example.com",
2031
+ apiKey: "$PROXY_API_KEY", // env var reference
2032
+ api: "anthropic-messages",
2033
+ models: [
2034
+ {
2035
+ id: "claude-sonnet-4-20250514",
2036
+ name: "Claude 4 Sonnet (proxy)",
2037
+ reasoning: false,
2038
+ input: ["text", "image"],
2039
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
2040
+ contextWindow: 200000,
2041
+ maxTokens: 16384
2042
+ }
2043
+ ]
2044
+ });
2045
+
2046
+ // Register a live llama.cpp catalog without persisting discovered models
2047
+ pi.registerProvider("llama.cpp", {
2048
+ baseUrl: "http://localhost:8080/v1",
2049
+ apiKey: "local",
2050
+ api: "openai-completions",
2051
+ async refreshModels({ signal }) {
2052
+ const response = await fetch("http://localhost:8080/v1/models", { signal });
2053
+ const { data } = (await response.json()) as { data: Array<{ id: string }> };
2054
+ return data.map(({ id }) => ({
2055
+ id,
2056
+ name: id,
2057
+ reasoning: false,
2058
+ input: ["text"],
2059
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
2060
+ contextWindow: 128000,
2061
+ maxTokens: 16384
2062
+ }));
2063
+ }
2064
+ });
2065
+
2066
+ // Override baseUrl for an existing provider (keeps all models)
2067
+ pi.registerProvider("anthropic", {
2068
+ baseUrl: "https://proxy.example.com"
2069
+ });
2070
+
2071
+ // Register provider with OAuth support for /login
2072
+ pi.registerProvider("corporate-ai", {
2073
+ baseUrl: "https://ai.corp.com",
2074
+ api: "openai-responses",
2075
+ models: [...],
2076
+ oauth: {
2077
+ name: "Corporate AI (SSO)",
2078
+ async login(callbacks) {
2079
+ // Custom OAuth flow
2080
+ callbacks.onAuth({ url: "https://sso.corp.com/..." });
2081
+ const code = await callbacks.onPrompt({ message: "Enter code:" });
2082
+ return { refresh: code, access: code, expires: Date.now() + 3600000 };
2083
+ },
2084
+ async refreshToken(credentials, signal) {
2085
+ signal.throwIfAborted();
2086
+ // Refresh logic
2087
+ return credentials;
2088
+ },
2089
+ getApiKey(credentials) {
2090
+ return credentials.access;
2091
+ }
2092
+ }
2093
+ });
2094
+ ```
2095
+
2096
+ The object form accepts a complete @draht/ai `Provider`, including native `auth`, `getModels`, `refreshModels`, `filterModels`, `stream`, and `streamSimple` behavior.
2097
+
2098
+ **Legacy config options:**
2099
+ - `name` - Display name for the provider in UI such as `/login`.
2100
+ - `baseUrl` - API endpoint URL. Each defined model needs one, from the model definition or the provider.
2101
+ - `apiKey` - API key literal, environment interpolation (`$ENV_VAR` or `${ENV_VAR}`), or leading `!command`. Optional: without it, users store a key with `/login`. `$$` escapes `$`, and `$!` escapes a literal `!` without triggering command execution.
2102
+ - `api` - API type: `"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc.
2103
+ - `headers` - Custom headers to include in requests.
2104
+ - `authHeader` - If true, adds `Authorization: Bearer` header automatically.
2105
+ - `models` - Array of model definitions. If provided, replaces all existing models for this provider. Model definitions can set `baseUrl` to override the provider endpoint for that model.
2106
+ - `refreshModels` - Async dynamic discovery callback. Its returned models replace extension-provided models. `context.stored` contains the persisted provider snapshot; use generation-checked `context.publish({ persist: entry })` only when updated catalog data should persist. Use `persist: null` to delete that snapshot.
2107
+ - `oauth` - OAuth provider config for `/login` support. When provided, the provider appears in the login menu.
2108
+ - `streamSimple` - Custom streaming implementation for non-standard APIs.
2109
+
2110
+ See [custom-provider.md](custom-provider.md) for advanced topics: custom streaming APIs, OAuth details, model definition reference.
2111
+
2112
+ ### pi.unregisterProvider(name)
2113
+
2114
+ Remove a previously registered provider and its models. Built-in models that were overridden by the provider are restored. Has no effect if the provider was not registered.
2115
+
2116
+ Like `registerProvider`, this takes effect immediately when called after the initial load phase, so a `/reload` is not required.
2117
+
2118
+ ```typescript
2119
+ pi.registerCommand("my-setup-teardown", {
2120
+ description: "Remove the custom proxy provider",
2121
+ handler: async (_args, _ctx) => {
2122
+ pi.unregisterProvider("my-proxy");
2123
+ },
2124
+ });
2125
+ ```
2126
+
2127
+ ### pi.registerVirtualModel(model) / pi.unregisterVirtualModel(provider, id)
2128
+
2129
+ Register a selectable catalog entry that routes each request to a physical model. `ctx.model` and the session's model selection name the virtual model; assistant messages record the physical model and thinking level the router picked. Registering the same provider and ID again replaces the virtual model. See [Virtual Models](virtual-models.md).
2130
+
2131
+ ### pi.registerMcpServer(name, config) / pi.unregisterMcpServer(name) / pi.getMcpServers()
2132
+
2133
+ Register an MCP server for the current session. See [MCP Servers](#mcp-servers).
2134
+
2135
+ ### pi.registerToolRenderer(resolver)
2136
+
2137
+ Choose how calls to any tool are drawn, including tools that are not registered yet, such as MCP tools in a resumed session before their server connected. The resolver receives the tool name and `next()`, which returns what the remaining resolvers (in extension load order), then the registered tool, would use, so `next() ?? mine` only fills in.
2138
+
2139
+ ```typescript
2140
+ pi.registerToolRenderer((toolName, next) => {
2141
+ if (!toolName.startsWith("mcp__")) return next();
2142
+ return next() ?? { renderCall: (args, theme) => new Text(theme.fg("toolTitle", toolName), 0, 0) };
2143
+ });
2144
+ ```
2145
+
2146
+ ### pi.getSettings()
2147
+
2148
+ Return a copy of the effective settings, with global and project settings merged and overrides applied.
2149
+
2150
+ <a id="persist-state"></a>
2151
+
2152
+ ## State Management
2153
+
2154
+ Extensions with state should store it in tool result `details` for proper branching support:
2155
+
2156
+ ```typescript
2157
+ export default function (pi: ExtensionAPI) {
2158
+ let items: string[] = [];
2159
+
2160
+ // Reconstruct state from the active branch
2161
+ const reconstruct = (ctx: ExtensionContext) => {
2162
+ items = [];
2163
+ for (const entry of ctx.sessionManager.getBranch()) {
2164
+ if (entry.type === "message" && entry.message.role === "toolResult") {
2165
+ if (entry.message.toolName === "my_tool") {
2166
+ items = (entry.message.details as { items?: string[] } | undefined)?.items ?? [];
2167
+ }
2168
+ }
2169
+ }
2170
+ };
2171
+ pi.on("session_start", async (_event, ctx) => reconstruct(ctx));
2172
+ pi.on("session_tree", async (_event, ctx) => reconstruct(ctx)); // /tree changes the branch
2173
+
2174
+ pi.registerTool({
2175
+ name: "my_tool",
2176
+ // ...
2177
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
2178
+ items.push("new item");
2179
+ return {
2180
+ content: [{ type: "text", text: "Added" }],
2181
+ details: { items: [...items] }, // Store for reconstruction
2182
+ };
2183
+ },
2184
+ });
2185
+ }
2186
+ ```
2187
+
2188
+ Rebuild from `getBranch()`, not from every entry: abandoned branches represent alternative histories. Use [`pi.appendEntry()`](#piappendentrycustomtype-data) for durable data that should not reach the model.
2189
+
2190
+ <a id="register-tools"></a>
2191
+
2192
+ ## Custom Tools
2193
+
2194
+ Register tools the LLM can call via `pi.registerTool()`. Tools appear in the system prompt and can have custom rendering.
2195
+
2196
+ Use `promptSnippet` for a short one-line entry in the `<tools>` section of the default system prompt. If omitted, custom tools are left out of that section.
2197
+
2198
+ Use `promptGuidelines` to add tool-specific bullets to the `<rules>` section of the default system prompt. These bullets are included only while the tool is active (for example, after `pi.setActiveTools([...])`).
2199
+
2200
+ **Important:** `promptGuidelines` bullets are appended flat to the `<rules>` section with no tool name prefix or grouping. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead.
2201
+
2202
+ Note: Some models include the @ prefix in tool path arguments. Built-in tools strip a leading @ before resolving paths. If your custom tool accepts a path, normalize a leading @ as well.
2203
+
2204
+ If your custom tool mutates files, use `withFileMutationQueue()` so it participates in the same per-file queue as built-in `edit` and `write`. This matters because tool calls run in parallel by default. Without the queue, two tools can read the same old file contents, compute different updates, and then whichever write lands last overwrites the other.
2205
+
2206
+ Example failure case: your custom tool edits `foo.ts` while built-in `edit` also changes `foo.ts` in the same assistant turn. If your tool does not participate in the queue, both can read the original `foo.ts`, apply separate changes, and one of those changes is lost.
2207
+
2208
+ Pass the real target file path to `withFileMutationQueue()`, not the raw user argument. Resolve it to an absolute path first, relative to `ctx.cwd` or your tool's working directory. For existing files, the helper canonicalizes through `realpath()`, so symlink aliases for the same file share one queue. For new files, it falls back to the resolved absolute path because there is nothing to `realpath()` yet.
2209
+
2210
+ Queue the entire mutation window on that target path. That includes read-modify-write logic, not just the final write.
2211
+
2212
+ ```typescript
2213
+ import { withFileMutationQueue } from "@draht/coding-agent";
2214
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2215
+ import { dirname, resolve } from "node:path";
2216
+
2217
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2218
+ const absolutePath = resolve(ctx.cwd, params.path);
2219
+
2220
+ return withFileMutationQueue(absolutePath, async () => {
2221
+ await mkdir(dirname(absolutePath), { recursive: true });
2222
+ const current = await readFile(absolutePath, "utf8");
2223
+ const next = current.replace(params.oldText, params.newText);
2224
+ await writeFile(absolutePath, next, "utf8");
2225
+
2226
+ return {
2227
+ content: [{ type: "text", text: `Updated ${params.path}` }],
2228
+ details: {},
2229
+ };
2230
+ });
2231
+ }
2232
+ ```
2233
+
2234
+ ### Tool Definition
2235
+
2236
+ ```typescript
2237
+ import { type Static, Type } from "typebox";
2238
+ import { StringEnum } from "@draht/ai";
2239
+
2240
+ const myToolSchema = Type.Object({
2241
+ action: StringEnum(["list", "add"] as const),
2242
+ text: Type.Optional(Type.String()),
2243
+ });
2244
+
2245
+ pi.registerTool({
2246
+ name: "my_tool",
2247
+ label: "My Tool",
2248
+ description: "What this tool does (shown to LLM)",
2249
+ promptSnippet: "List or add items in the project todo list",
2250
+ promptGuidelines: [
2251
+ "Use my_tool for todo planning instead of direct file edits when the user asks for a task list."
2252
+ ],
2253
+ parameters: myToolSchema,
2254
+ prepareArguments(args) {
2255
+ // Fold a legacy `oldAction` field into `action`. Schema validation still runs afterwards.
2256
+ const input = (args ?? {}) as { action?: unknown; oldAction?: unknown };
2257
+ if (input.action === undefined && input.oldAction !== undefined) {
2258
+ return { ...input, action: input.oldAction } as Static<typeof myToolSchema>;
2259
+ }
2260
+ return args as Static<typeof myToolSchema>;
2261
+ },
2262
+
2263
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
2264
+ // Check for cancellation
2265
+ if (signal?.aborted) {
2266
+ return { content: [{ type: "text", text: "Cancelled" }], details: {} };
2267
+ }
2268
+
2269
+ // Stream progress updates; partial results also need details
2270
+ onUpdate?.({
2271
+ content: [{ type: "text", text: "Working..." }],
2272
+ details: {},
2273
+ });
2274
+
2275
+ // Run commands via pi.exec (captured from extension closure)
2276
+ const result = await pi.exec("some-command", [], { signal });
2277
+
2278
+ // Return result
2279
+ return {
2280
+ content: [{ type: "text", text: "Done" }], // Sent to LLM
2281
+ details: { data: result }, // For rendering & state
2282
+ // usage: nestedModelResponse.usage, // Optional nested LLM usage
2283
+ // Optional: stop after this tool batch when every finalized tool result
2284
+ // in the batch also returns terminate: true.
2285
+ terminate: true,
2286
+ };
2287
+ },
2288
+
2289
+ // Optional: Custom rendering
2290
+ renderCall(args, theme, context) { ... },
2291
+ renderResult(result, options, theme, context) { ... },
2292
+ });
2293
+ ```
2294
+
2295
+ **Result fields:** Every result, including partial results passed to `onUpdate`, needs model-facing `content` and a `details` value. Use `details: undefined` when there is nothing to store; the type of `details` must match across all results of the tool.
2296
+
2297
+ **Usage accounting:** If a tool makes nested LLM calls, return their combined `Usage` as `usage`. draht persists it on the tool result and includes it in footer, `/session`, and RPC session totals. `tool_result` handlers can inspect or replace this value.
2298
+
2299
+ **Signaling errors:** To mark a tool execution as failed, throw an error from `execute`, or return a result with `isError: true`. Both report an error result to the LLM; a returned result also keeps `details` and `structuredContent` for rendering and scripts. Other returned values never set the error flag.
2300
+
2301
+ **Early termination:** Return `terminate: true` from `execute()` to hint that the automatic follow-up LLM call should be skipped after the current tool batch. This only takes effect when every finalized tool result in that batch is terminating. See [examples/extensions/structured-output.ts](../examples/extensions/structured-output.ts) for a minimal example where the agent ends on a final structured-output tool call.
2302
+
2303
+ ```typescript
2304
+ // Correct: throw to signal an error
2305
+ async execute(toolCallId, params) {
2306
+ if (!isValid(params.input)) {
2307
+ throw new Error(`Invalid input: ${params.input}`);
2308
+ }
2309
+ return { content: [{ type: "text", text: "OK" }], details: {} };
2310
+ }
2311
+ ```
2312
+
2313
+ **String enums:** Prefer `StringEnum` from `@draht/ai`. It produces a plain `enum` schema that every provider accepts.
2314
+
2315
+ **Structured output:** Declare `outputSchema` and return a matching `structuredContent` when the result is data. The model still receives `content`; programmatic callers such as codemode scripts receive `structuredContent` instead of the text. Tools without `outputSchema` are passed to scripts as their text content. To report a failure that still carries data, return the result with `isError: true` instead of throwing: the model sees an error, and scripts still receive `structuredContent`.
2316
+
2317
+ **Execution mode:** Tool calls from one assistant message run in parallel by default. Set `executionMode: "sequential"` when a tool must not run concurrently with other calls, for example because it shares mutable in-memory state.
2318
+
2319
+ **Other definition fields:**
2320
+
2321
+ | Field | Purpose |
2322
+ |---|---|
2323
+ | `defaultActive` | Set `false` to register the tool inactive; `--tools`, the `defaultTools` setting, or `pi.setActiveTools()` activates it |
2324
+ | `exposure`, `namespace`, `annotations`, `reachesTools`, `prepareLoadout` | Control how the model and other tools reach the tool; see [Tool Exposure](#tool-exposure) |
2325
+ | `renderShell`, `renderCall`, `renderResult` | Custom rendering; see [Custom Rendering](#custom-rendering) |
2326
+ | `constrainedSampling` | Optional provider-side constrained sampling request for the tool's arguments |
2327
+
2328
+ Use `defineTool()` to keep parameter type inference when you assign a tool definition to a variable before registering it.
2329
+
2330
+ **Argument preparation:** `prepareArguments(args)` is optional. If defined, it runs before schema validation and before `execute()`. Use it to mimic an older accepted input shape when draht resumes an older session whose stored tool call arguments no longer match the current schema. Return the object you want validated against `parameters`. Keep the public schema strict. Do not add deprecated compatibility fields to `parameters` just to keep old resumed sessions working.
2331
+
2332
+ Example: an older session may contain an `edit` tool call with top-level `oldText` and `newText`, while the current schema only accepts `edits: [{ oldText, newText }]`.
2333
+
2334
+ ```typescript
2335
+ const editSchema = Type.Object({
2336
+ path: Type.String(),
2337
+ edits: Type.Array(
2338
+ Type.Object({
2339
+ oldText: Type.String(),
2340
+ newText: Type.String(),
2341
+ }),
2342
+ ),
2343
+ });
2344
+ type EditInput = Static<typeof editSchema>;
2345
+
2346
+ pi.registerTool({
2347
+ name: "edit",
2348
+ label: "Edit",
2349
+ description: "Edit a single file using exact text replacement",
2350
+ parameters: editSchema,
2351
+ prepareArguments(args) {
2352
+ const input = (args ?? {}) as Partial<EditInput> & { oldText?: unknown; newText?: unknown };
2353
+ if (typeof input.oldText !== "string" || typeof input.newText !== "string") {
2354
+ return args as EditInput; // validation reports anything still invalid
2355
+ }
2356
+
2357
+ const { oldText, newText, ...rest } = input;
2358
+ return { ...rest, edits: [...(input.edits ?? []), { oldText, newText }] } as EditInput;
2359
+ },
2360
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
2361
+ // params now matches the current schema
2362
+ return {
2363
+ content: [{ type: "text", text: `Applying ${params.edits.length} edit block(s)` }],
2364
+ details: {},
2365
+ };
2366
+ },
2367
+ });
2368
+ ```
2369
+
2370
+ ### Overriding Built-in Tools
2371
+
2372
+ Extensions can override built-in tools (`read`, `bash`, `powershell`, `edit`, `write`, `grep`, `find`, `ls`) by registering a tool with the same name. The extension tool replaces the built-in without a warning.
2373
+
2374
+ ```bash
2375
+ # Extension's read tool replaces built-in read
2376
+ draht -e ./tool-override.ts
2377
+ ```
2378
+
2379
+ Alternatively, use `--no-builtin-tools` to start without any built-in tools while keeping extension tools enabled:
2380
+ ```bash
2381
+ # No built-in tools, only extension tools
2382
+ draht --no-builtin-tools -e ./my-extension.ts
2383
+ ```
2384
+
2385
+ See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.ts) for a complete example that overrides `read` with logging and access control.
2386
+
2387
+ **Rendering:** Built-in renderer inheritance is resolved per slot. Execution override and rendering override are independent. If your override omits `renderCall`, the built-in `renderCall` is used. If your override omits `renderResult`, the built-in `renderResult` is used. If your override omits both, the built-in renderer is used automatically (syntax highlighting, diffs, etc.). This lets you wrap built-in tools for logging or access control without reimplementing the UI.
2388
+
2389
+ **Prompt metadata:** `promptSnippet` and `promptGuidelines` are not inherited from the built-in tool. If your override should keep those prompt instructions, define them on the override explicitly.
2390
+
2391
+ **Your implementation must match the exact result shape**, including the `details` type. The UI and session logic depend on these shapes for rendering and state tracking.
2392
+
2393
+ Built-in tool implementations:
2394
+ - [read.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/read.ts) - `ReadToolDetails`
2395
+ - [bash.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/bash.ts) - `BashToolDetails`
2396
+ - [powershell.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/powershell.ts) - `PowerShellToolDetails`
2397
+ - [edit.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/edit.ts)
2398
+ - [write.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/write.ts)
2399
+ - [grep.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/grep.ts) - `GrepToolDetails`
2400
+ - [find.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/find.ts) - `FindToolDetails`
2401
+ - [ls.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/ls.ts) - `LsToolDetails`
2402
+
2403
+ ### Remote Execution
2404
+
2405
+ Built-in tools support pluggable operations for delegating to remote systems (SSH, containers, etc.):
2406
+
2407
+ ```typescript
2408
+ import { createReadTool, type ReadOperations } from "@draht/coding-agent";
2409
+
2410
+ const localRead = createReadTool(cwd);
2411
+
2412
+ // Register, checking the remote configuration at execution time
2413
+ pi.registerTool({
2414
+ ...localRead,
2415
+ async execute(id, params, signal, onUpdate, _ctx) {
2416
+ const ssh = getSshConfig();
2417
+ if (ssh) {
2418
+ const operations: ReadOperations = {
2419
+ readFile: (path) => sshReadBuffer(ssh, path), // must resolve to a Buffer
2420
+ access: (path) => sshExec(ssh, `test -r ${path}`).then(() => {}),
2421
+ };
2422
+ return createReadTool(cwd, { operations }).execute(id, params, signal, onUpdate);
2423
+ }
2424
+ return localRead.execute(id, params, signal, onUpdate);
2425
+ },
2426
+ });
2427
+ ```
2428
+
2429
+ The `create*ToolDefinition()` factories, such as `createReadToolDefinition()`, return complete tool definitions, including the built-in prompt snippet and guidelines, for the same purpose. Rendering does not need copying: a tool registered under a built-in name inherits the built-in renderer for each slot it leaves out (see [Overriding Built-in Tools](#overriding-built-in-tools)).
2430
+
2431
+ **Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `PowerShellOperations`, `LsOperations`, `GrepOperations`, `FindOperations`
2432
+
2433
+ `GrepOperations` covers the directory check and, through the optional `spawn`, where `rg` runs (for example over SSH). Context lines come from `rg` itself; grep never reads matched files. Alternatively, override grep's `execute()`, as the [Gondolin example](../examples/extensions/gondolin/index.ts) does.
2434
+
2435
+ For `user_bash`, extensions can reuse draht's local shell backend via `createLocalBashOperations()` (or `createLocalPowerShellOperations()`) instead of reimplementing local process spawning, shell resolution, and process-tree termination.
2436
+
2437
+ The `bash` and `powershell` tools also support a spawn hook to adjust the command, cwd, or env before execution:
2438
+
2439
+ ```typescript
2440
+ import { createBashTool } from "@draht/coding-agent";
2441
+
2442
+ const bashTool = createBashTool(cwd, {
2443
+ spawnHook: ({ command, cwd, env }) => ({
2444
+ command: `source ~/.profile\n${command}`,
2445
+ cwd: `/mnt/sandbox${cwd}`,
2446
+ env: { ...env, CI: "1" },
2447
+ }),
2448
+ });
2449
+ ```
2450
+
2451
+ `createBashTool()` and `createPowerShellTool()` expose the current session to commands through `DRAHT_SESSION_ID`, `DRAHT_SESSION_FILE`, `DRAHT_PROVIDER`, `DRAHT_MODEL`, and `DRAHT_REASONING_LEVEL`. Injection happens before `spawnHook`, so hooks receive these values in `env` and preserve them when they spread the existing environment as above. Set `exposeSessionEnvironment: false` to disable them:
2452
+
2453
+ ```typescript
2454
+ const bashTool = createBashTool(cwd, {
2455
+ exposeSessionEnvironment: false,
2456
+ });
2457
+ ```
2458
+
2459
+ See [Shell tool session environment](environment-variables.md#shell-tool-session-environment) for variable semantics. See [examples/extensions/ssh.ts](../examples/extensions/ssh.ts) for a complete SSH example with `--ssh` flag.
2460
+
2461
+ ### Output Truncation
2462
+
2463
+ **Tools MUST truncate their output** to avoid overwhelming the LLM context. Large outputs can cause:
2464
+ - Context overflow errors (prompt too long)
2465
+ - Compaction failures
2466
+ - Degraded model performance
2467
+
2468
+ The built-in limit is **50KB** (~10k tokens) and **2000 lines**, whichever is hit first. Use the exported truncation utilities:
2469
+
2470
+ ```typescript
2471
+ import {
2472
+ truncateHead, // Keep first N lines/bytes (good for file reads, search results)
2473
+ truncateTail, // Keep last N lines/bytes (good for logs, command output)
2474
+ truncateLine, // Truncate a single line to a character count; returns { text, wasTruncated }
2475
+ formatSize, // Human-readable size (e.g., "50KB", "1.5MB")
2476
+ DEFAULT_MAX_BYTES, // 50KB
2477
+ DEFAULT_MAX_LINES, // 2000
2478
+ } from "@draht/coding-agent";
2479
+
2480
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
2481
+ const output = await runCommand();
2482
+
2483
+ // Apply truncation
2484
+ const truncation = truncateHead(output, {
2485
+ maxLines: DEFAULT_MAX_LINES,
2486
+ maxBytes: DEFAULT_MAX_BYTES,
2487
+ });
2488
+
2489
+ let result = truncation.content;
2490
+
2491
+ if (truncation.truncated) {
2492
+ // Write full output to temp file
2493
+ const tempFile = writeTempFile(output);
2494
+
2495
+ // Inform the LLM where to find complete output
2496
+ result += `\n\n[Output truncated: ${truncation.outputLines} of ${truncation.totalLines} lines`;
2497
+ result += ` (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).`;
2498
+ result += ` Full output saved to: ${tempFile}]`;
2499
+ }
2500
+
2501
+ return { content: [{ type: "text", text: result }], details: { truncation } };
2502
+ }
2503
+ ```
2504
+
2505
+ **Key points:**
2506
+ - Use `truncateHead` for content where the beginning matters (search results, file reads)
2507
+ - Use `truncateTail` for content where the end matters (logs, command output)
2508
+ - Always inform the LLM when output is truncated and where to find the full version
2509
+ - Document the truncation limits in your tool's description
2510
+
2511
+ See [examples/extensions/truncated-tool.ts](../examples/extensions/truncated-tool.ts) for a complete example wrapping `rg` (ripgrep) with proper truncation.
2512
+
2513
+ ### Multiple Tools
2514
+
2515
+ One extension can register multiple tools with shared state:
2516
+
2517
+ ```typescript
2518
+ export default function (pi: ExtensionAPI) {
2519
+ let connection = null;
2520
+
2521
+ pi.registerTool({ name: "db_connect", ... });
2522
+ pi.registerTool({ name: "db_query", ... });
2523
+ pi.registerTool({ name: "db_close", ... });
2524
+
2525
+ pi.on("session_shutdown", async () => {
2526
+ connection?.close();
2527
+ });
2528
+ }
2529
+ ```
2530
+
2531
+ <a id="tool-rendering"></a>
2532
+
2533
+ ### Custom Rendering
2534
+
2535
+ Tools can provide `renderCall` and `renderResult` for custom TUI display. See [tui.md](tui.md) for the full component API and [tool-execution.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/modes/interactive/components/tool-execution.ts) for how tool rows are composed.
2536
+
2537
+ By default, tool output is wrapped in a `Box` that handles background and horizontal padding from the `outputPad` setting. Tool renderers are also used in HTML exports. A defined `renderCall` or `renderResult` must return a `Component`. If a slot renderer is not defined, `tool-execution.ts` uses fallback rendering for that slot.
2538
+
2539
+ Set `renderShell: "self"` when the tool should render its own shell instead of using the default `Box`. This is useful for tools that need complete control over framing or background behavior, for example large previews that must stay visually stable after the tool settles.
2540
+
2541
+ ```typescript
2542
+ pi.registerTool({
2543
+ name: "my_tool",
2544
+ label: "My Tool",
2545
+ description: "Custom shell example",
2546
+ parameters: Type.Object({}),
2547
+ renderShell: "self",
2548
+ async execute() {
2549
+ return { content: [{ type: "text", text: "ok" }], details: undefined };
2550
+ },
2551
+ renderCall(args, theme, context) {
2552
+ return new Text(theme.fg("accent", "my custom shell"), 0, 0);
2553
+ },
2554
+ });
2555
+ ```
2556
+
2557
+ `renderCall` and `renderResult` each receive a `context` object with:
2558
+ - `args` - the current tool call arguments
2559
+ - `state` - shared row-local state across `renderCall` and `renderResult`
2560
+ - `lastComponent` - the previously returned component for that slot, if any
2561
+ - `invalidate()` - request a rerender of this tool row
2562
+ - `toolCallId`, `cwd`, `executionStarted`, `argsComplete`, `isPartial`, `expanded`, `showImages`, `isError`
2563
+ - `durationMs` - how long execution took, from the final result; `undefined` while running
2564
+ - `outputPad` - horizontal padding from the `outputPad` setting; renderers with `renderShell: "self"` apply it themselves
2565
+ - `keyText()`, `keyHint()` - format the user's configured keybindings, see [Keybinding Hints](#keybinding-hints)
2566
+
2567
+ Use `context.state` for cross-slot shared state. Keep slot-local caches on the returned component instance when you want to reuse and mutate the same component across renders.
2568
+
2569
+ #### renderCall
2570
+
2571
+ Renders the tool call or header:
2572
+
2573
+ ```typescript
2574
+ import { Text } from "@draht/tui";
2575
+
2576
+ renderCall(args, theme, context) {
2577
+ const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
2578
+ let content = theme.fg("toolTitle", theme.bold("my_tool "));
2579
+ content += theme.fg("muted", args.action);
2580
+ if (args.text) {
2581
+ content += " " + theme.fg("dim", `"${args.text}"`);
2582
+ }
2583
+ text.setText(content);
2584
+ return text;
2585
+ }
2586
+ ```
2587
+
2588
+ #### renderResult
2589
+
2590
+ Renders the tool result or output:
2591
+
2592
+ ```typescript
2593
+ renderResult(result, { expanded, isPartial }, theme, context) {
2594
+ if (isPartial) {
2595
+ return new Text(theme.fg("warning", "Processing..."), 0, 0);
2596
+ }
2597
+
2598
+ if (result.details?.error) {
2599
+ return new Text(theme.fg("error", `Error: ${result.details.error}`), 0, 0);
2600
+ }
2601
+
2602
+ let text = theme.fg("success", "✓ Done");
2603
+ if (expanded && result.details?.items) {
2604
+ for (const item of result.details.items) {
2605
+ text += "\n " + theme.fg("dim", item);
2606
+ }
2607
+ }
2608
+ return new Text(text, 0, 0);
2609
+ }
2610
+ ```
2611
+
2612
+ If a slot intentionally has no visible content, return an empty `Component` such as an empty `Container`.
2613
+
2614
+ #### Keybinding Hints
2615
+
2616
+ Use `keyHint()` and `keyText()` from the render context to display keybinding hints that respect the user's keybinding configuration:
2617
+
2618
+ ```typescript
2619
+ renderResult(result, { expanded }, theme, context) {
2620
+ let text = theme.fg("success", "✓ Done");
2621
+ if (!expanded) {
2622
+ text += ` (${context.keyHint("app.tools.expand", "to expand")})`;
2623
+ }
2624
+ return new Text(text, 0, 0);
2625
+ }
2626
+ ```
2627
+
2628
+ The same functions are available as `options.keyHint()`/`options.keyText()` in message and entry renderers:
2629
+
2630
+ - `keyHint(keybinding, description)` - Formats a configured keybinding id such as `"app.tools.expand"` or `"tui.select.confirm"`, followed by the description
2631
+ - `keyText(keybinding)` - Returns the raw configured key text for a keybinding id, or `""` if the id has no keys
2632
+
2633
+ In renderers, use these instead of importing `keyHint()` or `keyText()` from `@draht/coding-agent`. An extension can resolve its own copy of the package, for example from its own `node_modules`, and that copy does not see draht's configured keybindings: `app.*` ids then format as `""`. `rawKeyHint(key, description)` formats a literal key string and is safe to import.
2634
+
2635
+ Use namespaced keybinding ids:
2636
+ - Coding-agent ids use the `app.*` namespace, for example `app.tools.expand`, `app.editor.external`, `app.session.rename`
2637
+ - Shared TUI ids use the `tui.*` namespace, for example `tui.select.confirm`, `tui.select.cancel`, `tui.input.tab`
2638
+
2639
+ For the exhaustive list of keybinding ids and defaults, see [keybindings.md](keybindings.md). `keybindings.json` uses those same namespaced ids.
2640
+
2641
+ Custom editors and `ctx.ui.custom()` components receive `keybindings: KeybindingsManager` as an injected argument. They should use that injected manager directly instead of calling `getKeybindings()` or `setKeybindings()`.
2642
+
2643
+ #### Best Practices
2644
+
2645
+ - Use `Text` with padding `(0, 0)`. The default Box handles padding.
2646
+ - Use `\n` for multi-line content.
2647
+ - Handle `isPartial` for streaming progress.
2648
+ - Support `expanded` for detail on demand.
2649
+ - Keep default view compact.
2650
+ - Read `context.args` in `renderResult` instead of copying args into `context.state`.
2651
+ - Use `context.state` only for data that must be shared across call and result slots.
2652
+ - Reuse `context.lastComponent` when the same component instance can be updated in place.
2653
+ - Use `renderShell: "self"` only when the default boxed shell gets in the way. In self-shell mode the tool is responsible for its own framing, padding, and background.
2654
+
2655
+ #### Fallback
2656
+
2657
+ If a slot renderer is not defined or throws:
2658
+ - `renderCall`: Shows the tool name
2659
+ - `renderResult`: Shows raw text from `content`
2660
+
2661
+ ### Dynamic Tool Loading
2662
+
2663
+ Extensions can register many tools while keeping only a small initial set active. A tool can then change the active set with `pi.setActiveTools()` during execution. draht stores the initial prompt and tool loadout in the transcript's first system message, then appends tool and prompt deltas before the next model request. Providers that cannot represent a transition receive a complete transcript checkpoint, which may invalidate the cached prefix.
2664
+
2665
+ The lifecycle is:
2666
+
2667
+ 1. Register every tool with `pi.registerTool()` so it appears in `pi.getAllTools()`. Register searchable tools with `defaultActive: false` so they start inactive.
2668
+ 2. Keep loader tools, such as `search_tools`, active.
2669
+ 3. During loader execution, call `pi.setActiveTools()` with the desired active tool names. Names must already be registered; unknown and `hidden` names are ignored.
2670
+
2671
+ draht also ships a built-in `tool_search` tool. Register tools with `exposure: "deferred"` to make them findable by it instead of writing your own loader; see [Tool Exposure](#tool-exposure).
2672
+
2673
+ #### Search tool example
2674
+
2675
+ The following extension registers two inactive searchable tools and keeps `search_tools` active as their loader. The example uses simple keyword matching, but the search implementation could use BM25, embeddings, a remote catalog, or project-specific routing.
2676
+
2677
+ ```typescript
2678
+ import type { ExtensionAPI } from "@draht/coding-agent";
2679
+ import { Type } from "typebox";
2680
+
2681
+ const SEARCHABLE_TOOL_NAMES = new Set(["lookup_weather", "search_issues"]);
2682
+
2683
+ export default function (pi: ExtensionAPI) {
2684
+ pi.registerTool({
2685
+ name: "lookup_weather",
2686
+ label: "Lookup Weather",
2687
+ defaultActive: false,
2688
+ description: "Look up the current weather for a city",
2689
+ parameters: Type.Object({ city: Type.String() }),
2690
+ async execute(_toolCallId, params) {
2691
+ return {
2692
+ content: [{ type: "text", text: `Weather for ${params.city}: sunny` }],
2693
+ details: {},
2694
+ };
2695
+ },
2696
+ });
2697
+
2698
+ pi.registerTool({
2699
+ name: "search_issues",
2700
+ label: "Search Issues",
2701
+ defaultActive: false,
2702
+ description: "Search project issues by keyword",
2703
+ parameters: Type.Object({ query: Type.String() }),
2704
+ async execute(_toolCallId, params) {
2705
+ return {
2706
+ content: [{ type: "text", text: `No open issues matching ${params.query}` }],
2707
+ details: {},
2708
+ };
2709
+ },
2710
+ });
2711
+
2712
+ pi.registerTool({
2713
+ name: "search_tools",
2714
+ label: "Search Tools",
2715
+ description: "Search for and enable tools relevant to a task",
2716
+ promptSnippet: "Search for additional tools when the active tools cannot perform the task",
2717
+ promptGuidelines: [
2718
+ "Use search_tools when a task requires a capability that is not currently available.",
2719
+ ],
2720
+ parameters: Type.Object({
2721
+ query: Type.String({ description: "Capability or task to search for" }),
2722
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 10 })),
2723
+ }),
2724
+ async execute(_toolCallId, params) {
2725
+ const terms = params.query.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
2726
+ const matches = pi.getAllTools()
2727
+ .filter((tool) => SEARCHABLE_TOOL_NAMES.has(tool.name))
2728
+ .map((tool) => ({
2729
+ tool,
2730
+ score: terms.reduce(
2731
+ (score, term) =>
2732
+ score + (`${tool.name} ${tool.description}`.toLowerCase().includes(term) ? 1 : 0),
2733
+ 0,
2734
+ ),
2735
+ }))
2736
+ .filter((match) => match.score > 0)
2737
+ .sort((a, b) => b.score - a.score)
2738
+ .slice(0, params.limit ?? 3)
2739
+ .map((match) => match.tool.name);
2740
+
2741
+ if (matches.length === 0) {
2742
+ return {
2743
+ content: [{ type: "text", text: `No tools found for: ${params.query}` }],
2744
+ details: { matches: [] as string[], added: [] as string[] },
2745
+ };
2746
+ }
2747
+
2748
+ const active = pi.getActiveTools();
2749
+ const added = matches.filter((name) => !active.includes(name));
2750
+ pi.setActiveTools([...new Set([...active, ...added])]);
2751
+
2752
+ return {
2753
+ content: [{
2754
+ type: "text",
2755
+ text: added.length > 0
2756
+ ? `Loaded tools: ${added.join(", ")}`
2757
+ : `Matching tools already active: ${matches.join(", ")}`,
2758
+ }],
2759
+ details: { matches, added },
2760
+ };
2761
+ },
2762
+ });
2763
+ }
2764
+ ```
2765
+
2766
+ When `search_tools` adds a match, the model receives the complete updated tool list on the immediately following request.
2767
+
2768
+ ### Tool Exposure
2769
+
2770
+ `exposure` controls how the model reaches a tool. "Callable" means callable from other tools through `ctx.executeTool()` (`ctx.tools`), as the `codemode` tool's scripts do:
2771
+
2772
+ - `direct` (default): declared to the model while active, and callable while active.
2773
+ - `model-only`: declared to the model while active, never callable. Use it for tools that orchestrate other tools or ask the user.
2774
+ - `codemode`: callable whenever registered, and listed by the `codemode` tool. Not declared to the model unless activated explicitly.
2775
+ - `deferred`: like `codemode`, but codemode tools do not list it; `tool_search` can find and activate it.
2776
+ - `hidden`: registered but unreachable. Re-register a tool with `exposure: "hidden"` to withdraw it, since tools cannot be unregistered.
2777
+
2778
+ `namespace: { name, aliases, description, instructions }` groups related tools, as MCP servers do. Codemode tools list a namespace under one heading with its `description`. `instructions` holds longer usage guidance; it is not listed, and codemode scripts read it with `describeNamespace(name)`. `aliases` are other names scripts may look the namespace up by, for example the server name `docs` for `mcp__docs`; a name and the same name as a script identifier (`my-docs`, `my_docs`) match alike.
2779
+
2780
+ Registering a `direct` or `model-only` tool activates it unless it sets `defaultActive: false`; the other exposures are not activated on registration. The active set (`pi.getActiveTools()`, `pi.setActiveTools()`) is the set of tools declared to the model, except active tools whose declarations `prepareLoadout` hides. `pi.getAllTools()` reports each tool's `exposure`, `namespace`, `annotations`, and `reachesTools`.
2781
+
2782
+ `annotations` are hints about what a tool does, with the meaning of MCP tool annotations: `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint`. MCP tools carry the hints their server declares. Missing hints take the MCP defaults: a tool is not read-only, and may be destructive and reach an open world. The hints are not verified, but a permission extension can use them to decide which calls to confirm. This confirms the calls Codex asks approval for:
2783
+
2784
+ ```typescript
2785
+ pi.on("tool_call", async (event, ctx) => {
2786
+ const hints = pi.getAllTools().find((tool) => tool.name === event.toolName)?.annotations;
2787
+ const needsApproval =
2788
+ hints?.destructiveHint === true ||
2789
+ (!hints?.readOnlyHint && ((hints?.destructiveHint ?? true) || (hints?.openWorldHint ?? true)));
2790
+ if (needsApproval && !(await ctx.ui.confirm("Allow tool call?", event.toolName))) {
2791
+ return { block: true, reason: `${event.toolName} was not approved` };
2792
+ }
2793
+ });
2794
+ ```
2795
+
2796
+ draht's own permission gate runs a call to a tool with `readOnlyHint: true` without asking (in the `ask` and `supervised` modes, only one that also declares `openWorldHint: false`, since a tool that reaches the web can carry what it read out), when no rule in `permissions.yml` matches it, no argument of the call names a path outside the project, and the hint comes from outside the project: from a built-in tool, or from an extension loaded with `-e`, by the SDK, or from the user's own extensions and packages. Tools of a project's extensions still ask, and so does a tool that also declares `destructiveHint: true`. An extension that relays another source's hints, as the MCP support relays a server's, sets `annotationsScope` to that source's scope: `"user"`, `"project"`, or `"temporary"`. The gate ignores the hints when `annotationsScope` is `"project"`, so the field can lower trust but never raise it. `pi.getAllTools()` reports `annotationsScope` with the annotations.
2797
+
2798
+ A tool that orchestrates other tools can adjust what the model sees while it is active with `prepareLoadout(loadout)`. It runs whenever the active tools change and receives the declared tools, the callable tools, and every registered tool with its exposure, namespace, and prompt guidelines. It returns replacement `descriptions` for declared tools (including its own) and `hiddenDeclarations`: active tools whose declarations requests leave out while they stay active and callable. The default system prompt leaves hidden tools out of its tool list and rules, and names no tool in the skills hint when the file reader is hidden, so the orchestrating tool should present their guidelines itself. `codemode` uses only this hook, `exposure`, `reachesTools`, and `ctx.executeTool()`, so another tool can implement the same behavior under a different name.
2799
+
2800
+ A tool that reaches other tools declares which ones a call may reach with `reachesTools(input)`: `"all"`, or the words of the input that may name them, where a word refers to every tool or namespace whose name it contains. `codemode` returns `"all"` for scripts that search or list tools and the words of the script otherwise; `tool_search` always returns `"all"`. Extensions that register tools late use it from their `tool_call` handler to finish registering the tools a call needs before it runs, as the MCP extension does for servers that are still connecting. The MCP extension also activates `codemode` or `tool_search` for MCP tools only when the tool of that name declares `reachesTools`.
2801
+
2802
+ ### Calling Other Tools
2803
+
2804
+ A tool can run other tools with `ctx.executeTool(name, args, { signal, onUpdate })`. `ctx.tools` lists the tools it can call. The call never rejects for tool failures: unknown tools, validation errors, blocked calls, and thrown errors come back as results with `isError: true`.
2805
+
2806
+ Nested calls go through argument validation and the `tool_call` and `tool_result` handlers like model-issued calls, and emit `tool_execution_start`, `tool_execution_update`, and `tool_execution_end`. All of these events carry `parentToolCallId`, and their `toolCallId` is assigned by draht as `<parent id>/<n>`. These IDs do not appear as tool calls or tool results in the transcript.
2807
+
2808
+ Nested calls do not add transcript entries: their results only reach the calling tool, which reports them itself, for example through `onUpdate` and `details`. The session keeps a bounded record of them (name, arguments, status, duration, error; never results) as `nestedCalls` on the calling tool's result message. It is used for compaction file lists and shown in HTML exports. Arguments over 8 KiB per call or 32 KiB per tool result are omitted, at most 256 calls are kept, and `complete: false` marks a record that lost anything.
2809
+
2810
+ The `usage` of nested results, at every depth, is added to the calling tool's result `usage`, so a tool reports only its own usage, not that of the tools it called. `tool_result` handlers that redact `content` should also replace `structuredContent`; replacing only `content` drops it.
2811
+
2812
+ ## MCP Servers
2813
+
2814
+ `pi.registerMcpServer(name, config)` adds an MCP server for the current session. `config` has the shape of an `mcpServers` entry in [`mcp.json`](mcp.md): `command`, `args`, `env`, and `cwd` for stdio servers, `url`, `headers`, and `oauth` for HTTP servers, plus `exposure`, `toolExposure`, `description`, `enabled`, and `timeout`.
2815
+
2816
+ ```typescript
2817
+ pi.registerMcpServer("jira", { url: "https://mcp.example.com/jira", exposure: "codemode" });
2818
+ pi.unregisterMcpServer("jira");
2819
+ ```
2820
+
2821
+ Servers registered while the extension loads connect when the session starts, together with the `mcp.json` servers; servers registered later connect right away, and `pi.unregisterMcpServer()` closes the connection and makes the server's tools unreachable. Registrations are not saved: register again on every load, for example based on the extension's own settings. A server in `mcp.json` with the same name takes precedence, and `/mcp` shows the override. Registering the same name again replaces the extension's earlier registration; names registered by another extension, invalid names, and invalid configs throw.
2822
+
2823
+ The built-in MCP support connects registered servers. When nothing does, because another extension replaced it (see [MCP](mcp.md#replace-the-built-in-mcp-support)), each registration is reported as an extension error. Other MCP extensions can connect registered servers too: read them with `pi.getMcpServers()` on `session_start` and handle the `mcp_servers_change` event for later changes. Each registered server carries the `extensionScope` of the extension that registered it, which its tools' `annotationsScope` takes, so the permission gate trusts a registered server's read-only hints as far as it trusts the extension.
2824
+
2825
+ <a id="interact-with-the-user"></a>
2826
+
2827
+ ## Custom UI
2828
+
2829
+ Extensions can interact with users via `ctx.ui` methods and customize how messages/tools render.
2830
+
2831
+ For custom components, focus, overlays, themes, and rendering performance, see [Terminal UI](tui.md). The examples it lists show selection lists, settings toggles, cancellable loaders, footers, and widgets.
2832
+
2833
+ ### Dialogs
2834
+
2835
+ ```typescript
2836
+ // Select from options
2837
+ const choice = await ctx.ui.select("Pick one:", ["A", "B", "C"]);
2838
+
2839
+ // Confirm dialog
2840
+ const ok = await ctx.ui.confirm("Delete?", "This cannot be undone");
2841
+
2842
+ // Text input
2843
+ const name = await ctx.ui.input("Name:", "placeholder");
2844
+
2845
+ // Multi-line editor
2846
+ const text = await ctx.ui.editor("Edit:", "prefilled text");
2847
+
2848
+ // Notification (non-blocking)
2849
+ ctx.ui.notify("Done!", "info"); // "info" | "warning" | "error"
2850
+ ```
2851
+
2852
+ #### Timed Dialogs with Countdown
2853
+
2854
+ Dialogs support a `timeout` option that auto-dismisses with a live countdown display:
2855
+
2856
+ ```typescript
2857
+ // Dialog shows "Title (5s)" → "Title (4s)" → ... → auto-dismisses at 0
2858
+ const confirmed = await ctx.ui.confirm(
2859
+ "Timed Confirmation",
2860
+ "This dialog will auto-cancel in 5 seconds. Confirm?",
2861
+ { timeout: 5000 }
2862
+ );
2863
+
2864
+ if (confirmed) {
2865
+ // User confirmed
2866
+ } else {
2867
+ // User cancelled or timed out
2868
+ }
2869
+ ```
2870
+
2871
+ **Return values on timeout:**
2872
+ - `select()` returns `undefined`
2873
+ - `confirm()` returns `false`
2874
+ - `input()` returns `undefined`
2875
+
2876
+ #### Manual Dismissal with AbortSignal
2877
+
2878
+ For more control (e.g., to distinguish timeout from user cancel), use `AbortSignal`:
2879
+
2880
+ ```typescript
2881
+ const controller = new AbortController();
2882
+ const timeoutId = setTimeout(() => controller.abort(), 5000);
2883
+
2884
+ const confirmed = await ctx.ui.confirm(
2885
+ "Timed Confirmation",
2886
+ "This dialog will auto-cancel in 5 seconds. Confirm?",
2887
+ { signal: controller.signal }
2888
+ );
2889
+
2890
+ clearTimeout(timeoutId);
2891
+
2892
+ if (confirmed) {
2893
+ // User confirmed
2894
+ } else if (controller.signal.aborted) {
2895
+ // Dialog timed out
2896
+ } else {
2897
+ // User cancelled (pressed Escape or selected "No")
2898
+ }
2899
+ ```
2900
+
2901
+ See [examples/extensions/timed-confirm.ts](../examples/extensions/timed-confirm.ts) for complete examples.
2902
+
2903
+ ### Widgets, Status, and Footer
2904
+
2905
+ ```typescript
2906
+ // Status in footer (persistent until cleared)
2907
+ ctx.ui.setStatus("my-ext", "Processing...");
2908
+ ctx.ui.setStatus("my-ext", undefined); // Clear
2909
+
2910
+ // Working loader (shown during streaming)
2911
+ ctx.ui.setWorkingMessage("Thinking deeply...");
2912
+ ctx.ui.setWorkingMessage(); // Restore default
2913
+ ctx.ui.setWorkingVisible(false); // Hide the built-in working loader row entirely
2914
+ ctx.ui.setWorkingVisible(true); // Show the built-in working loader row
2915
+
2916
+ // Working indicator (shown during streaming)
2917
+ ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg("accent", "●")] }); // Static dot
2918
+ ctx.ui.setWorkingIndicator({
2919
+ frames: [
2920
+ ctx.ui.theme.fg("dim", "·"),
2921
+ ctx.ui.theme.fg("muted", "•"),
2922
+ ctx.ui.theme.fg("accent", "●"),
2923
+ ctx.ui.theme.fg("muted", "•"),
2924
+ ],
2925
+ intervalMs: 120,
2926
+ });
2927
+ ctx.ui.setWorkingIndicator({ frames: [] }); // Hide indicator
2928
+ ctx.ui.setWorkingIndicator(); // Restore default spinner
2929
+
2930
+ // Widget above editor (default)
2931
+ ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]);
2932
+ // Widget below editor
2933
+ ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" });
2934
+ ctx.ui.setWidget("my-widget", (tui, theme) => new Text(theme.fg("accent", "Custom"), 0, 0));
2935
+ ctx.ui.setWidget("my-widget", undefined); // Clear
2936
+
2937
+ // Custom footer (replaces built-in footer entirely)
2938
+ // footerData provides the git branch and extension statuses from setStatus()
2939
+ ctx.ui.setFooter((tui, theme, footerData) => ({
2940
+ render(width) { return [theme.fg("dim", "Custom footer")]; },
2941
+ invalidate() {},
2942
+ }));
2943
+ ctx.ui.setFooter(undefined); // Restore built-in footer
2944
+
2945
+ // Custom header shown at startup above the chat
2946
+ ctx.ui.setHeader((tui, theme) => new Text(theme.fg("accent", "my-project"), 0, 0));
2947
+ ctx.ui.setHeader(undefined); // Restore built-in header
2948
+
2949
+ // Label shown for hidden thinking blocks
2950
+ ctx.ui.setHiddenThinkingLabel("Reasoning...");
2951
+ ctx.ui.setHiddenThinkingLabel(); // Restore default
2952
+
2953
+ // Raw terminal input (interactive mode only); return { consume: true } to swallow it
2954
+ const unsubscribe = ctx.ui.onTerminalInput((data) => undefined);
2955
+
2956
+ // Terminal title
2957
+ ctx.ui.setTitle("draht - my-project");
2958
+
2959
+ // Editor text
2960
+ ctx.ui.setEditorText("Prefill text");
2961
+ const current = ctx.ui.getEditorText();
2962
+
2963
+ // Paste into editor (triggers paste handling, including collapse for large content)
2964
+ ctx.ui.pasteToEditor("pasted content");
2965
+
2966
+ // Stack custom autocomplete behavior on top of the built-in provider
2967
+ ctx.ui.addAutocompleteProvider((current) => ({
2968
+ triggerCharacters: ["#"],
2969
+ async getSuggestions(lines, line, col, options) {
2970
+ const beforeCursor = (lines[line] ?? "").slice(0, col);
2971
+ const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/);
2972
+ if (!match) {
2973
+ return current.getSuggestions(lines, line, col, options);
2974
+ }
2975
+
2976
+ return {
2977
+ prefix: `#${match[1] ?? ""}`,
2978
+ items: [{ value: "#2983", label: "#2983", description: "Extension API for autocomplete" }],
2979
+ };
2980
+ },
2981
+ applyCompletion(lines, line, col, item, prefix) {
2982
+ return current.applyCompletion(lines, line, col, item, prefix);
2983
+ },
2984
+ shouldTriggerFileCompletion(lines, line, col) {
2985
+ return current.shouldTriggerFileCompletion?.(lines, line, col) ?? true;
2986
+ },
2987
+ }));
2988
+
2989
+ // Tool output expansion
2990
+ const wasExpanded = ctx.ui.getToolsExpanded();
2991
+ ctx.ui.setToolsExpanded(true);
2992
+ ctx.ui.setToolsExpanded(wasExpanded);
2993
+
2994
+ // Custom editor (vim mode, emacs mode, etc.)
2995
+ ctx.ui.setEditorComponent((tui, theme, keybindings) => new VimEditor(tui, theme, keybindings));
2996
+ const currentEditor = ctx.ui.getEditorComponent();
2997
+ ctx.ui.setEditorComponent((tui, theme, keybindings) =>
2998
+ new WrappedEditor(tui, theme, keybindings, currentEditor?.(tui, theme, keybindings))
2999
+ );
3000
+ ctx.ui.setEditorComponent(undefined); // Restore default editor
3001
+
3002
+ // Theme management (see themes.md for creating themes)
3003
+ const themes = ctx.ui.getAllThemes(); // [{ name: "dark", path: "/..." | undefined }, ...]
3004
+ const lightTheme = ctx.ui.getTheme("light"); // Load without switching
3005
+ const result = ctx.ui.setTheme("light"); // Switch by name
3006
+ if (!result.success) {
3007
+ ctx.ui.notify(`Failed: ${result.error}`, "error");
3008
+ }
3009
+ ctx.ui.setTheme(lightTheme!); // Or switch by Theme object
3010
+ ctx.ui.theme.fg("accent", "styled text"); // Access current theme
3011
+ ```
3012
+
3013
+ Custom working-indicator frames are rendered verbatim. If you want colors, add them to the frame strings yourself, for example with `ctx.ui.theme.fg(...)`.
3014
+
3015
+ ### Autocomplete Providers
3016
+
3017
+ Use `ctx.ui.addAutocompleteProvider()` to stack custom autocomplete logic on top of the built-in slash-command and path provider. Set `triggerCharacters` for custom natural triggers such as `$`.
3018
+
3019
+ Typical pattern:
3020
+
3021
+ - inspect the text before the cursor
3022
+ - return your own suggestions when your extension-specific syntax matches
3023
+ - otherwise delegate to `current.getSuggestions(...)`
3024
+ - delegate `applyCompletion(...)` unless you need custom insertion behavior
3025
+
3026
+ ```typescript
3027
+ pi.on("session_start", (_event, ctx) => {
3028
+ ctx.ui.addAutocompleteProvider((current) => ({
3029
+ triggerCharacters: ["#"],
3030
+ async getSuggestions(lines, cursorLine, cursorCol, options) {
3031
+ const line = lines[cursorLine] ?? "";
3032
+ const beforeCursor = line.slice(0, cursorCol);
3033
+ const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/);
3034
+ if (!match) {
3035
+ return current.getSuggestions(lines, cursorLine, cursorCol, options);
3036
+ }
3037
+
3038
+ return {
3039
+ prefix: `#${match[1] ?? ""}`,
3040
+ items: [
3041
+ { value: "#2983", label: "#2983", description: "Extension API for registering custom @ autocomplete providers" },
3042
+ { value: "#2753", label: "#2753", description: "Reload stale resource settings" },
3043
+ ],
3044
+ };
3045
+ },
3046
+
3047
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
3048
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
3049
+ },
3050
+
3051
+ shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
3052
+ return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
3053
+ },
3054
+ }));
3055
+ });
3056
+ ```
3057
+
3058
+ See [github-issue-autocomplete.ts](../examples/extensions/github-issue-autocomplete.ts) for a complete example that preloads the latest open GitHub issues with `gh issue list` and filters them locally for fast `#...` completion. It requires GitHub CLI (`gh`) and a GitHub repository checkout.
3059
+
3060
+ ### Custom Components
3061
+
3062
+ For complex UI, use `ctx.ui.custom()`. This temporarily replaces the editor with your component until `done()` is called:
3063
+
3064
+ ```typescript
3065
+ import { truncateToWidth } from "@draht/tui";
3066
+
3067
+ const result = await ctx.ui.custom<boolean>((tui, theme, keybindings, done) => ({
3068
+ render(width: number): string[] {
3069
+ return [truncateToWidth(theme.fg("accent", "Press Enter to confirm, Escape to cancel"), width)];
3070
+ },
3071
+ handleInput(data: string): void {
3072
+ if (keybindings.matches(data, "tui.select.confirm")) done(true);
3073
+ else if (keybindings.matches(data, "tui.select.cancel")) done(false);
3074
+ },
3075
+ invalidate() {},
3076
+ }));
3077
+
3078
+ if (result) {
3079
+ // User pressed Enter
3080
+ }
3081
+ ```
3082
+
3083
+ The callback receives:
3084
+ - `tui` - TUI instance (for screen dimensions, focus management)
3085
+ - `theme` - Current theme for styling
3086
+ - `keybindings` - App keybinding manager (for checking shortcuts)
3087
+ - `done(value)` - Call to close component and return value
3088
+
3089
+ The factory can also return a `Promise` of a component. See [Terminal UI](tui.md#build-a-minimal-custom-screen) for a complete custom screen with cached rendering.
3090
+
3091
+ #### Overlay Mode (Experimental)
3092
+
3093
+ Pass `{ overlay: true }` to render the component as a floating modal on top of existing content, without clearing the screen:
3094
+
3095
+ ```typescript
3096
+ const result = await ctx.ui.custom<string | null>(
3097
+ (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
3098
+ { overlay: true }
3099
+ );
3100
+ ```
3101
+
3102
+ For advanced positioning (anchors, margins, percentages, responsive visibility), pass `overlayOptions`. Use `onHandle` to control focus or visibility programmatically:
3103
+
3104
+ ```typescript
3105
+ const result = await ctx.ui.custom<string | null>(
3106
+ (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
3107
+ {
3108
+ overlay: true,
3109
+ overlayOptions: { anchor: "top-right", width: "50%", margin: 2 },
3110
+ onHandle: (handle) => {
3111
+ handle.focus(); // focus this overlay and bring it to the visual front
3112
+ // handle.unfocus({ target: editorComponent }); // release input to a specific component
3113
+ // handle.setHidden(true/false); // toggle visibility
3114
+ // handle.isHidden(), handle.isFocused(), handle.getBounds()
3115
+ }
3116
+ }
3117
+ );
3118
+ ```
3119
+
3120
+ `overlayOptions` can also be a function, re-evaluated for dynamic positioning. Finish the interaction with `done()`; do not call `handle.hide()` on an overlay created by `ctx.ui.custom()`.
3121
+
3122
+ A focused visible overlay can reclaim input after temporary non-overlay custom UI closes. If you intentionally want another component to keep input while the overlay stays visible, call `handle.unfocus({ target })`. Passing `{ target: null }` releases the overlay without focusing another component.
3123
+
3124
+ See [`OverlayOptions` and `OverlayHandle`](https://github.com/draht-dev/draht/blob/main/packages/tui/src/tui.ts) for the full API and [overlay-qa-tests.ts](../examples/extensions/overlay-qa-tests.ts) for examples.
3125
+
3126
+ ### Custom Editor
3127
+
3128
+ Replace the main input editor with a custom implementation (vim mode, emacs mode, etc.):
3129
+
3130
+ ```typescript
3131
+ import { CustomEditor, type ExtensionAPI } from "@draht/coding-agent";
3132
+ import { matchesKey } from "@draht/tui";
3133
+
3134
+ class VimEditor extends CustomEditor {
3135
+ private mode: "normal" | "insert" = "insert";
3136
+
3137
+ handleInput(data: string): void {
3138
+ if (matchesKey(data, "escape") && this.mode === "insert") {
3139
+ this.mode = "normal";
3140
+ return;
3141
+ }
3142
+ if (this.mode === "normal" && data === "i") {
3143
+ this.mode = "insert";
3144
+ return;
3145
+ }
3146
+ super.handleInput(data); // App keybindings + text editing
3147
+ }
3148
+ }
3149
+
3150
+ export default function (pi: ExtensionAPI) {
3151
+ pi.on("session_start", (_event, ctx) => {
3152
+ ctx.ui.setEditorComponent((tui, theme, keybindings) =>
3153
+ new VimEditor(tui, theme, keybindings)
3154
+ );
3155
+ });
3156
+ }
3157
+ ```
3158
+
3159
+ **Key points:**
3160
+ - Extend `CustomEditor` (not base `Editor`) to get app keybindings (escape to abort, ctrl+d, model switching)
3161
+ - Call `super.handleInput(data)` for keys you don't handle
3162
+ - Custom editors keep the standalone working row by default. Pass `{ embedWorkingStatus: true }` as the fourth `CustomEditor` constructor argument to use the built-in editor-border spinner instead.
3163
+ - Factory receives `tui`, `theme`, and `keybindings` from the app
3164
+ - Use `ctx.ui.getEditorComponent()` before `setEditorComponent()` to wrap the previously configured custom editor
3165
+ - Pass `undefined` to restore default: `ctx.ui.setEditorComponent(undefined)`
3166
+
3167
+ To compose with another extension that already replaced the editor, capture the previous factory before setting yours:
3168
+
3169
+ ```typescript
3170
+ const previous = ctx.ui.getEditorComponent();
3171
+ ctx.ui.setEditorComponent((tui, theme, keybindings) =>
3172
+ new MyEditor(tui, theme, keybindings, { base: previous?.(tui, theme, keybindings) })
3173
+ );
3174
+ ```
3175
+
3176
+ See [modal-editor.ts](../examples/extensions/modal-editor.ts) for a complete example with a mode indicator.
3177
+
3178
+ ### Message and Entry Rendering
3179
+
3180
+ Register a custom renderer for messages with your `customType`. Use message renderers for content that should participate in LLM context:
3181
+
3182
+ ```typescript
3183
+ import { Text } from "@draht/tui";
3184
+
3185
+ pi.registerMessageRenderer("my-extension", (message, options, theme) => {
3186
+ const { expanded, outputPad } = options;
3187
+ let text = theme.fg("accent", `[${message.customType}] `);
3188
+ text += message.content;
3189
+
3190
+ if (expanded && message.details) {
3191
+ text += "\n" + theme.fg("dim", JSON.stringify(message.details, null, 2));
3192
+ } else if (message.details) {
3193
+ text += ` (${options.keyHint("app.tools.expand", "to expand")})`;
3194
+ }
3195
+
3196
+ return new Text(text, outputPad, 0);
3197
+ });
3198
+ ```
3199
+
3200
+ Messages are sent via `pi.sendMessage()`:
3201
+
3202
+ ```typescript
3203
+ pi.sendMessage({
3204
+ customType: "my-extension", // Matches registerMessageRenderer
3205
+ content: "Status update",
3206
+ display: true, // Show in TUI
3207
+ details: { ... }, // Available in renderer
3208
+ });
3209
+ ```
3210
+
3211
+ For TUI-only content that should not be sent to the LLM, render custom entries instead:
3212
+
3213
+ ```typescript
3214
+ pi.registerEntryRenderer("my-card", (entry, options, theme) => {
3215
+ return new Text(theme.fg("accent", JSON.stringify(entry.data)));
3216
+ });
3217
+
3218
+ pi.appendEntry("my-card", { status: "done" });
3219
+ ```
3220
+
3221
+ ### Theme Colors
3222
+
3223
+ All render functions receive a `theme` object. See [themes.md](themes.md) for creating custom themes and the full color palette.
3224
+
3225
+ ```typescript
3226
+ // Foreground colors
3227
+ theme.fg("toolTitle", text) // Tool names
3228
+ theme.fg("accent", text) // Highlights
3229
+ theme.fg("success", text) // Success (green)
3230
+ theme.fg("error", text) // Errors (red)
3231
+ theme.fg("warning", text) // Warnings (yellow)
3232
+ theme.fg("muted", text) // Secondary text
3233
+ theme.fg("dim", text) // Tertiary text
3234
+
3235
+ // Text styles
3236
+ theme.bold(text)
3237
+ theme.italic(text)
3238
+ theme.underline(text)
3239
+ theme.strikethrough(text)
3240
+
3241
+ // Combined foreground, background, and attributes
3242
+ theme.style(text, { fg: "success", bg: "toolSuccessBg", bold: true })
3243
+ ```
3244
+
3245
+ `theme.colors` exposes concrete colors and `theme.appearance` is `"dark"` or `"light"`. See [Apply themes correctly](tui.md#apply-themes-correctly).
3246
+
3247
+ For syntax highlighting in custom tool renderers:
3248
+
3249
+ ```typescript
3250
+ import { highlightCode, getLanguageFromPath } from "@draht/coding-agent";
3251
+
3252
+ // Highlight code with an explicit language; returns one string per line
3253
+ const lines = highlightCode("const x = 1;", "typescript");
3254
+
3255
+ // Auto-detect language from file path
3256
+ const lang = getLanguageFromPath("/path/to/file.rs"); // "rust", or undefined
3257
+ const highlighted = highlightCode(code, lang);
3258
+ ```
3259
+
3260
+ <a id="handle-errors-and-shutdown"></a>
3261
+
3262
+ ## Error Handling
3263
+
3264
+ - Extension errors are logged, agent continues
3265
+ - `tool_call` errors block the tool (fail-safe)
3266
+ - `user_bash` errors block the command instead of falling through to local execution
3267
+ - Tool `execute` errors are signaled by throwing or by returning `isError: true`; a thrown error is caught, reported to the LLM as an error result, and execution continues
3268
+
3269
+ <a id="ui-and-modes"></a>
3270
+ <a id="account-for-each-mode"></a>
3271
+
3272
+ ## Mode Behavior
3273
+
3274
+ | Mode | `ctx.mode` | `ctx.hasUI` | Notes |
3275
+ |------|------------|-------------|-------|
3276
+ | Interactive | `"tui"` | `true` | Full TUI with terminal rendering |
3277
+ | RPC (`--mode rpc`) | `"rpc"` | `true` | Dialogs and notifications via JSON protocol; `custom()` returns `undefined`, component factories are ignored. See [RPC Extension UI](rpc-extension-ui.md) |
3278
+ | JSON (`--mode json`) | `"json"` | `false` | Event stream to stdout; UI methods are no-ops |
3279
+ | Print (`-p`) | `"print"` | `false` | Extensions run but can't prompt |
3280
+
3281
+ Use `ctx.mode === "tui"` before TUI-specific features (`custom()`, component factories, terminal input). Use `ctx.hasUI` before dialog and notification methods that work in both TUI and RPC modes.
3282
+
3283
+ <a id="use-examples-as-the-implementation-reference"></a>
411
3284
 
412
- Use [Custom Providers](custom-provider.md) for model-service integrations, [Terminal UI](tui.md) for custom components, and [draht Packages](packages.md) to install or distribute extensions with other resources. Use the exported declarations for exact signatures, payloads, and result schemas; this guide focuses on lifecycle choices, composition, and durable implementation patterns.
3285
+ ## Examples Reference
3286
+
3287
+ All examples in [examples/extensions/](../examples/extensions/).
3288
+
3289
+ | Example | Description | Key APIs |
3290
+ |---------|-------------|----------|
3291
+ | **Tools** |||
3292
+ | `hello.ts` | Minimal tool registration | `registerTool` |
3293
+ | `question.ts` | Tool with user interaction | `registerTool`, `ui.custom`, `renderResult` |
3294
+ | `questionnaire.ts` | Multi-step wizard tool | `registerTool`, `ui.custom` |
3295
+ | `todo.ts` | Stateful tool with branch-aware state in `details` | `registerTool`, `renderResult`, `registerCommand`, `on("session_start")`, `on("session_tree")` |
3296
+ | `dynamic-tools.ts` | Register tools after startup and during commands | `registerTool`, `session_start`, `registerCommand` |
3297
+ | `structured-output.ts` | Final structured-output tool with `terminate: true` | `registerTool`, terminating tool results |
3298
+ | `truncated-tool.ts` | Output truncation example | `registerTool`, `truncateHead` |
3299
+ | `tic-tac-toe.ts` | Tool that must run sequentially | `registerTool`, `executionMode: "sequential"`, `ui.custom` |
3300
+ | `tool-override.ts` | Override built-in read tool | `registerTool` (same name as built-in) |
3301
+ | `built-in-tool-renderer.ts` | Custom rendering for built-in tools | `create*ToolDefinition`, `renderCall`, `renderResult`, `renderShell` |
3302
+ | `minimal-mode.ts` | Collapsed display for built-in tools | Built-in tool overrides, `renderResult` |
3303
+ | **Commands** |||
3304
+ | `pirate.ts` | Modify system prompt per-turn | `registerCommand`, `before_agent_start` |
3305
+ | `summarize.ts` | Conversation summary command | `registerCommand`, `ui.custom` |
3306
+ | `handoff.ts` | Cross-provider model handoff | `registerCommand`, `ui.editor`, `ui.custom` |
3307
+ | `qna.ts` | Q&A with custom UI | `registerCommand`, `ui.custom`, `setEditorText` |
3308
+ | `send-user-message.ts` | Inject user messages | `registerCommand`, `sendUserMessage` |
3309
+ | `reload-runtime.ts` | Reload command and LLM tool handoff | `registerCommand`, `ctx.reload()`, `on("agent_settled")`, `sendUserMessage` |
3310
+ | `shutdown-command.ts` | Graceful shutdown command | `registerCommand`, `shutdown()` |
3311
+ | **Events & Gates** |||
3312
+ | `permission-gate.ts` | Block dangerous commands | `on("tool_call")`, `ui.select` |
3313
+ | `project-trust.ts` | Decide or defer project trust from a user/global or CLI extension | `on("project_trust")`, trust UI, required trust result |
3314
+ | `protected-paths.ts` | Block writes to specific paths | `on("tool_call")` |
3315
+ | `confirm-destructive.ts` | Confirm session changes | `on("session_before_switch")`, `on("session_before_fork")` |
3316
+ | `dirty-repo-guard.ts` | Warn on dirty git repo | `on("session_before_*")`, `exec` |
3317
+ | `input-transform.ts` | Transform user input | `on("input")` |
3318
+ | `input-transform-streaming.ts` | Streaming-aware input transform | `on("input")`, `streamingBehavior` |
3319
+ | `model-status.ts` | React to model changes | `on("model_select")`, `setStatus` |
3320
+ | `provider-payload.ts` | Inspect payloads and provider response headers | `on("before_provider_request")`, `on("after_provider_response")` |
3321
+ | `debug-provider.ts` | View raw provider stream events | `on("provider_stream_event")`, `appendEntry`, `registerEntryRenderer` |
3322
+ | `system-prompt-header.ts` | Display system prompt info | `on("agent_start")`, `getSystemPrompt` |
3323
+ | `claude-rules.ts` | Load rules from files | `on("session_start")`, `on("before_agent_start")` |
3324
+ | `prompt-customizer.ts` | Add context-aware tool guidance using `systemPromptOptions` | `on("before_agent_start")`, `BuildSystemPromptOptions` |
3325
+ | `file-trigger.ts` | File watcher triggers messages | `sendMessage` |
3326
+ | **Compaction & Sessions** |||
3327
+ | `custom-compaction.ts` | Custom compaction summary | `on("session_before_compact")` |
3328
+ | `trigger-compact.ts` | Trigger compaction manually | `compact()` |
3329
+ | `git-checkpoint.ts` | Git stash on turns | `on("turn_start")`, `on("tool_result")`, `on("agent_settled")`, `on("session_before_fork")`, `exec` |
3330
+ | `git-merge-and-resolve.ts` | Fetch, merge, and resolve conflicts | `on("agent_end")`, `exec`, `sendUserMessage` |
3331
+ | `auto-commit-on-exit.ts` | Commit on shutdown | `on("session_shutdown")`, `exec` |
3332
+ | **UI Components** |||
3333
+ | `status-line.ts` | Footer status indicator | `setStatus`, session events |
3334
+ | `working-indicator.ts` | Customize the streaming working indicator | `setWorkingIndicator`, `registerCommand` |
3335
+ | `github-issue-autocomplete.ts` | Add `#1234` issue completions on top of built-in autocomplete by preloading recent open issues from `gh issue list` | `addAutocompleteProvider`, `on("session_start")`, `exec` |
3336
+ | `custom-footer.ts` | Replace footer entirely | `registerCommand`, `setFooter` |
3337
+ | `custom-header.ts` | Replace startup header | `on("session_start")`, `setHeader` |
3338
+ | `modal-editor.ts` | Vim-style modal editor | `setEditorComponent`, `CustomEditor` |
3339
+ | `rainbow-editor.ts` | Custom editor styling | `setEditorComponent` |
3340
+ | `widget-placement.ts` | Widget above/below editor | `setWidget` |
3341
+ | `overlay-test.ts` | Overlay components | `ui.custom` with overlay options |
3342
+ | `overlay-qa-tests.ts` | Comprehensive overlay tests | `ui.custom`, all overlay options |
3343
+ | `notify.ts` | Native terminal notification when the agent is done | `on("agent_settled")` |
3344
+ | `titlebar-spinner.ts` | Spinner in the terminal title while working | `setTitle` |
3345
+ | `hidden-thinking-label.ts` | Label for hidden thinking blocks | `setHiddenThinkingLabel` |
3346
+ | `border-status-editor.ts` | Status in the editor border | `setEditorComponent`, `CustomEditor` |
3347
+ | `rpc-demo.ts` | Every RPC-supported UI method | `ui.*` in RPC mode |
3348
+ | `timed-confirm.ts` | Dialogs with timeout | `ui.confirm` with timeout/signal |
3349
+ | `mac-system-theme.ts` | Auto-switch theme | `setTheme`, `exec` |
3350
+ | **Complex Extensions** |||
3351
+ | `plan-mode/` | Full plan mode implementation | All event types, `registerCommand`, `registerShortcut`, `registerFlag`, `setStatus`, `setWidget`, `sendMessage`, `setActiveTools` |
3352
+ | `preset.ts` | Saveable presets (model, tools, thinking) | `registerCommand`, `registerShortcut`, `registerFlag`, `setModel`, `setActiveTools`, `setThinkingLevel`, `appendEntry` |
3353
+ | `tools.ts` | Toggle tools on/off UI | `registerCommand`, `setActiveTools`, `SettingsList`, session events |
3354
+ | **Remote & Sandbox** |||
3355
+ | `ssh.ts` | SSH remote execution | `registerFlag`, `on("user_bash")`, `on("before_agent_start")`, tool operations |
3356
+ | `interactive-shell.ts` | Persistent shell session | `on("user_bash")` |
3357
+ | `sandbox/` | Sandboxed tool execution | Tool operations |
3358
+ | `gondolin/` | Route built-in tools and `!` commands into a Gondolin micro-VM | Tool operations, built-in tool overrides, `on("user_bash")` |
3359
+ | `subagent/` | Spawn sub-agents | `registerTool`, `exec` |
3360
+ | **Games** |||
3361
+ | `snake.ts` | Snake game | `registerCommand`, `ui.custom`, keyboard handling |
3362
+ | `space-invaders.ts` | Space Invaders game | `registerCommand`, `ui.custom` |
3363
+ | `doom-overlay/` | Doom in overlay | `ui.custom` with overlay |
3364
+ | **Providers** |||
3365
+ | `custom-provider-anthropic/` | Custom Anthropic proxy | `registerProvider` |
3366
+ | `custom-provider-gitlab-duo/` | GitLab Duo integration | `registerProvider` with OAuth |
3367
+ | `jev-router.ts` | Virtual model that routes planning and implementation to different models | `registerVirtualModel` |
3368
+ | **Messages & Communication** |||
3369
+ | `message-renderer.ts` | Custom message rendering | `registerMessageRenderer`, `sendMessage` |
3370
+ | `entry-renderer.ts` | TUI-only custom entry rendering | `registerEntryRenderer`, `appendEntry` |
3371
+ | `event-bus.ts` | Inter-extension events | `pi.events` |
3372
+ | **Session Metadata** |||
3373
+ | `session-name.ts` | Name sessions for selector | `setSessionName`, `getSessionName` |
3374
+ | `bookmark.ts` | Bookmark entries for /tree | `setLabel` |
3375
+ | **Misc** |||
3376
+ | `commands.ts` | List available slash commands | `getCommands` |
3377
+ | `dynamic-resources/` | Add skills, prompts, and themes at runtime | `on("resources_discover")` |
3378
+ | `inline-bash.ts` | Expand inline `!{command}` in user prompts | `on("input")`, `exec` |
3379
+ | `bash-spawn-hook.ts` | Adjust bash command, cwd, and env before execution | `createBashTool`, `spawnHook` |
3380
+ | `with-deps/` | Extension with npm dependencies | Package structure with `package.json` |