@draht/coding-agent 2026.9.5-1 → 2026.10.4-2

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 (1012) hide show
  1. package/CHANGELOG.md +452 -0
  2. package/dist/bun/cli.d.ts +1 -1
  3. package/dist/bun/cli.d.ts.map +1 -1
  4. package/dist/bun/cli.js +6 -3
  5. package/dist/bun/cli.js.map +1 -1
  6. package/dist/bun/sandbox-env-setup.d.ts +2 -0
  7. package/dist/bun/sandbox-env-setup.d.ts.map +1 -0
  8. package/dist/bun/sandbox-env-setup.js +4 -0
  9. package/dist/bun/sandbox-env-setup.js.map +1 -0
  10. package/dist/bundle/chunks/anthropic-messages-GAKYXF65.js +6 -0
  11. package/dist/bundle/chunks/anthropic.js +75 -0
  12. package/dist/bundle/chunks/azure-openai-responses-ZIXMK6JO.js +2 -0
  13. package/dist/bundle/chunks/bedrock-converse-stream.js +79 -0
  14. package/dist/bundle/chunks/chunk-2E5VODES.js +2 -0
  15. package/dist/bundle/chunks/chunk-2FBJKY7F.js +2 -0
  16. package/dist/bundle/chunks/chunk-2N4I6WXC.js +2 -0
  17. package/dist/bundle/chunks/chunk-5VZWYVZB.js +82 -0
  18. package/dist/bundle/chunks/chunk-63BK6WK2.js +2 -0
  19. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +6 -0
  20. package/dist/bundle/chunks/chunk-6ZJKIMU7.js +2 -0
  21. package/dist/bundle/chunks/chunk-736QBNUZ.js +12 -0
  22. package/dist/bundle/chunks/chunk-BXSHCX3G.js +11 -0
  23. package/dist/bundle/chunks/chunk-CEJJ5XF2.js +170 -0
  24. package/dist/bundle/chunks/chunk-COF5JT7R.js +4 -0
  25. package/dist/bundle/chunks/chunk-D6TMD5Q2.js +44 -0
  26. package/dist/bundle/chunks/chunk-DPE4ALPU.js +146 -0
  27. package/dist/bundle/chunks/chunk-EBVYI75P.js +2 -0
  28. package/dist/bundle/chunks/chunk-GVXA72ZA.js +2 -0
  29. package/dist/bundle/chunks/chunk-H6FT43VC.js +137 -0
  30. package/dist/bundle/chunks/chunk-HJ72RANT.js +2 -0
  31. package/dist/bundle/chunks/chunk-HTJ3L72O.js +2 -0
  32. package/dist/bundle/chunks/chunk-HZ2UHMBT.js +2 -0
  33. package/dist/bundle/chunks/chunk-I5OKY6RH.js +11 -0
  34. package/dist/bundle/chunks/chunk-IWTUBX6V.js +4 -0
  35. package/dist/bundle/chunks/chunk-KPO5375S.js +2 -0
  36. package/dist/bundle/chunks/chunk-KVH4HR57.js +31 -0
  37. package/dist/bundle/chunks/chunk-LDAOC5RB.js +18 -0
  38. package/dist/bundle/chunks/chunk-ON6XU6AG.js +2 -0
  39. package/dist/bundle/chunks/chunk-QMN7OD6G.js +2 -0
  40. package/dist/bundle/chunks/chunk-RZKPFWMH.js +42 -0
  41. package/dist/bundle/chunks/chunk-SDRCE6OP.js +2 -0
  42. package/dist/bundle/chunks/chunk-SVNWI7EV.js +8 -0
  43. package/dist/bundle/chunks/chunk-TIA2T6EO.js +3 -0
  44. package/dist/bundle/chunks/chunk-VOFPZOUQ.js +1472 -0
  45. package/dist/bundle/chunks/chunk-XBUEMKIY.js +2 -0
  46. package/dist/bundle/chunks/chunk-XOGEYN4Q.js +2 -0
  47. package/dist/bundle/chunks/chunk-ZZD35WKM.js +2 -0
  48. package/dist/bundle/chunks/cli-SR5QBZH4.js +51 -0
  49. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-MJKOAE5S.js +2 -0
  50. package/dist/bundle/chunks/codemode-worker.js +315 -0
  51. package/dist/bundle/chunks/execute-VCYDHEYA.js +328 -0
  52. package/dist/bundle/chunks/github-copilot.js +2 -0
  53. package/dist/bundle/chunks/google-antigravity.js +75 -0
  54. package/dist/bundle/chunks/google-gemini-cli.js +75 -0
  55. package/dist/bundle/chunks/google-generative-ai-RPUPQ6PM.js +2 -0
  56. package/dist/bundle/chunks/google-vertex-EZES5QVQ.js +2 -0
  57. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +13 -0
  58. package/dist/bundle/chunks/image-resize-worker.js +2 -0
  59. package/dist/bundle/chunks/jiti-loader-RKXLMQV2.js +2 -0
  60. package/dist/bundle/chunks/kimi-coding.js +2 -0
  61. package/dist/bundle/chunks/lib-XOG5PI3Y.js +9 -0
  62. package/dist/bundle/chunks/llama-cpp-classify-EJ5XMSQL.js +22 -0
  63. package/dist/bundle/chunks/meta.js +2 -0
  64. package/dist/bundle/chunks/mistral-conversations-AOYGU43Y.js +5 -0
  65. package/dist/bundle/chunks/multipart-parser-AZP5BX2W.js +3 -0
  66. package/dist/bundle/chunks/node-C2JGH2OB.js +2 -0
  67. package/dist/bundle/chunks/node-LQ52KV6B.js +16 -0
  68. package/dist/bundle/chunks/openai-chatgpt.js +75 -0
  69. package/dist/bundle/chunks/openai-codex-responses-M2Y77JEQ.js +10 -0
  70. package/dist/bundle/chunks/openai-codex.js +75 -0
  71. package/dist/bundle/chunks/openai-completions-A4OKYOYV.js +7 -0
  72. package/dist/bundle/chunks/openai-responses-6IXV53T3.js +3 -0
  73. package/dist/bundle/chunks/opencode-go.js +2 -0
  74. package/dist/bundle/chunks/openrouter-images-LYV4NKFM.js +2 -0
  75. package/dist/bundle/chunks/openrouter.js +75 -0
  76. package/dist/bundle/chunks/pi-messages-KKMEUT3Z.js +8 -0
  77. package/dist/bundle/chunks/radius.js +75 -0
  78. package/dist/bundle/chunks/runtime-6YJPGSP7.js +2 -0
  79. package/dist/bundle/chunks/settings-manager-D2EG7WDO.js +2 -0
  80. package/dist/bundle/chunks/src-TIBHS42X.js +4 -0
  81. package/dist/bundle/chunks/typesafe-system-one-YBEEY5XU.js +2 -0
  82. package/dist/bundle/chunks/virtual-modules-CBOAFAFT.js +2 -0
  83. package/dist/bundle/chunks/xai.js +75 -0
  84. package/dist/bundle/cli-runtime.js +3 -0
  85. package/dist/bundle/cli.js +5 -0
  86. package/dist/bundle/index.js +2 -0
  87. package/dist/bundle/rpc-entry.js +3 -0
  88. package/dist/cli/args.d.ts +4 -0
  89. package/dist/cli/args.d.ts.map +1 -1
  90. package/dist/cli/args.js +72 -21
  91. package/dist/cli/args.js.map +1 -1
  92. package/dist/cli/auth-check.d.ts +19 -0
  93. package/dist/cli/auth-check.d.ts.map +1 -0
  94. package/dist/cli/auth-check.js +50 -0
  95. package/dist/cli/auth-check.js.map +1 -0
  96. package/dist/cli/auth-command.d.ts +24 -0
  97. package/dist/cli/auth-command.d.ts.map +1 -0
  98. package/dist/cli/auth-command.js +103 -0
  99. package/dist/cli/auth-command.js.map +1 -0
  100. package/dist/cli/config-selector.d.ts.map +1 -1
  101. package/dist/cli/config-selector.js +3 -2
  102. package/dist/cli/config-selector.js.map +1 -1
  103. package/dist/cli/credential-print.d.ts +5 -3
  104. package/dist/cli/credential-print.d.ts.map +1 -1
  105. package/dist/cli/credential-print.js +42 -30
  106. package/dist/cli/credential-print.js.map +1 -1
  107. package/dist/cli/file-processor.d.ts +1 -1
  108. package/dist/cli/file-processor.d.ts.map +1 -1
  109. package/dist/cli/file-processor.js +2 -1
  110. package/dist/cli/file-processor.js.map +1 -1
  111. package/dist/cli/list-models.d.ts +1 -1
  112. package/dist/cli/list-models.d.ts.map +1 -1
  113. package/dist/cli/list-models.js +2 -2
  114. package/dist/cli/list-models.js.map +1 -1
  115. package/dist/cli/session-picker.d.ts +1 -1
  116. package/dist/cli/session-picker.d.ts.map +1 -1
  117. package/dist/cli/session-picker.js.map +1 -1
  118. package/dist/cli/setup.d.ts +2 -0
  119. package/dist/cli/setup.d.ts.map +1 -0
  120. package/dist/cli/setup.js +12 -0
  121. package/dist/cli/setup.js.map +1 -0
  122. package/dist/cli/startup-ui.d.ts +2 -2
  123. package/dist/cli/startup-ui.d.ts.map +1 -1
  124. package/dist/cli/startup-ui.js +42 -33
  125. package/dist/cli/startup-ui.js.map +1 -1
  126. package/dist/cli.js +3 -12
  127. package/dist/cli.js.map +1 -1
  128. package/dist/config.d.ts +20 -4
  129. package/dist/config.d.ts.map +1 -1
  130. package/dist/config.js +42 -6
  131. package/dist/config.js.map +1 -1
  132. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  133. package/dist/core/agent-session-runtime.js +12 -3
  134. package/dist/core/agent-session-runtime.js.map +1 -1
  135. package/dist/core/agent-session-services.d.ts +1 -0
  136. package/dist/core/agent-session-services.d.ts.map +1 -1
  137. package/dist/core/agent-session-services.js +14 -0
  138. package/dist/core/agent-session-services.js.map +1 -1
  139. package/dist/core/agent-session.d.ts +237 -39
  140. package/dist/core/agent-session.d.ts.map +1 -1
  141. package/dist/core/agent-session.js +1386 -565
  142. package/dist/core/agent-session.js.map +1 -1
  143. package/dist/core/auth-storage.d.ts +20 -8
  144. package/dist/core/auth-storage.d.ts.map +1 -1
  145. package/dist/core/auth-storage.js +199 -56
  146. package/dist/core/auth-storage.js.map +1 -1
  147. package/dist/core/bug-report-upload.d.ts +11 -0
  148. package/dist/core/bug-report-upload.d.ts.map +1 -0
  149. package/dist/core/bug-report-upload.js +20 -0
  150. package/dist/core/bug-report-upload.js.map +1 -0
  151. package/dist/core/bug-report.d.ts +176 -0
  152. package/dist/core/bug-report.d.ts.map +1 -0
  153. package/dist/core/bug-report.js +292 -0
  154. package/dist/core/bug-report.js.map +1 -0
  155. package/dist/core/builtins/duet.js +2 -2
  156. package/dist/core/builtins/duet.js.map +1 -1
  157. package/dist/core/cache-stats.d.ts.map +1 -1
  158. package/dist/core/cache-stats.js +12 -1
  159. package/dist/core/cache-stats.js.map +1 -1
  160. package/dist/core/cache-warmer.d.ts +103 -0
  161. package/dist/core/cache-warmer.d.ts.map +1 -0
  162. package/dist/core/cache-warmer.js +356 -0
  163. package/dist/core/cache-warmer.js.map +1 -0
  164. package/dist/core/checkpoints/checkpoint-manager.d.ts +8 -4
  165. package/dist/core/checkpoints/checkpoint-manager.d.ts.map +1 -1
  166. package/dist/core/checkpoints/checkpoint-manager.js +46 -10
  167. package/dist/core/checkpoints/checkpoint-manager.js.map +1 -1
  168. package/dist/core/checkpoints/rewind.d.ts +4 -2
  169. package/dist/core/checkpoints/rewind.d.ts.map +1 -1
  170. package/dist/core/checkpoints/rewind.js +4 -3
  171. package/dist/core/checkpoints/rewind.js.map +1 -1
  172. package/dist/core/compaction/branch-summarization.js +2 -2
  173. package/dist/core/compaction/branch-summarization.js.map +1 -1
  174. package/dist/core/compaction/compaction.d.ts +9 -6
  175. package/dist/core/compaction/compaction.d.ts.map +1 -1
  176. package/dist/core/compaction/compaction.js +196 -118
  177. package/dist/core/compaction/compaction.js.map +1 -1
  178. package/dist/core/compaction/utils.d.ts +2 -1
  179. package/dist/core/compaction/utils.d.ts.map +1 -1
  180. package/dist/core/compaction/utils.js +25 -18
  181. package/dist/core/compaction/utils.js.map +1 -1
  182. package/dist/core/crash-log.d.ts +27 -0
  183. package/dist/core/crash-log.d.ts.map +1 -0
  184. package/dist/core/crash-log.js +140 -0
  185. package/dist/core/crash-log.js.map +1 -0
  186. package/dist/core/defaults.d.ts +1 -0
  187. package/dist/core/defaults.d.ts.map +1 -1
  188. package/dist/core/defaults.js +9 -0
  189. package/dist/core/defaults.js.map +1 -1
  190. package/dist/core/experimental.js +1 -1
  191. package/dist/core/experimental.js.map +1 -1
  192. package/dist/core/export-html/template.css +10 -0
  193. package/dist/core/export-html/template.js +72 -18
  194. package/dist/core/extensions/index.d.ts +2 -2
  195. package/dist/core/extensions/index.d.ts.map +1 -1
  196. package/dist/core/extensions/index.js +1 -1
  197. package/dist/core/extensions/index.js.map +1 -1
  198. package/dist/core/extensions/jiti-loader.d.ts +2 -0
  199. package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
  200. package/dist/core/extensions/jiti-loader.js +5 -0
  201. package/dist/core/extensions/jiti-loader.js.map +1 -0
  202. package/dist/core/extensions/loader.d.ts.map +1 -1
  203. package/dist/core/extensions/loader.js +228 -89
  204. package/dist/core/extensions/loader.js.map +1 -1
  205. package/dist/core/extensions/runner.d.ts +47 -8
  206. package/dist/core/extensions/runner.d.ts.map +1 -1
  207. package/dist/core/extensions/runner.js +376 -104
  208. package/dist/core/extensions/runner.js.map +1 -1
  209. package/dist/core/extensions/types.d.ts +521 -88
  210. package/dist/core/extensions/types.d.ts.map +1 -1
  211. package/dist/core/extensions/types.js +3 -0
  212. package/dist/core/extensions/types.js.map +1 -1
  213. package/dist/core/extensions/virtual-modules.d.ts +3 -0
  214. package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
  215. package/dist/core/extensions/virtual-modules.js +37 -0
  216. package/dist/core/extensions/virtual-modules.js.map +1 -0
  217. package/dist/core/extensions/wrapper.d.ts +2 -2
  218. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  219. package/dist/core/extensions/wrapper.js +3 -22
  220. package/dist/core/extensions/wrapper.js.map +1 -1
  221. package/dist/core/footer-data-provider.d.ts +1 -1
  222. package/dist/core/footer-data-provider.js +19 -18
  223. package/dist/core/footer-data-provider.js.map +1 -1
  224. package/dist/core/index.d.ts +2 -1
  225. package/dist/core/index.d.ts.map +1 -1
  226. package/dist/core/index.js.map +1 -1
  227. package/dist/core/keybindings.d.ts +83 -13
  228. package/dist/core/keybindings.d.ts.map +1 -1
  229. package/dist/core/keybindings.js +33 -7
  230. package/dist/core/keybindings.js.map +1 -1
  231. package/dist/core/mcp-servers.d.ts +119 -0
  232. package/dist/core/mcp-servers.d.ts.map +1 -0
  233. package/dist/core/mcp-servers.js +191 -0
  234. package/dist/core/mcp-servers.js.map +1 -0
  235. package/dist/core/messages.d.ts +1 -1
  236. package/dist/core/messages.d.ts.map +1 -1
  237. package/dist/core/messages.js +1 -0
  238. package/dist/core/messages.js.map +1 -1
  239. package/dist/core/model-config.d.ts +202 -20
  240. package/dist/core/model-config.d.ts.map +1 -1
  241. package/dist/core/model-config.js +53 -18
  242. package/dist/core/model-config.js.map +1 -1
  243. package/dist/core/model-registry.d.ts +19 -2
  244. package/dist/core/model-registry.d.ts.map +1 -1
  245. package/dist/core/model-registry.js +39 -2
  246. package/dist/core/model-registry.js.map +1 -1
  247. package/dist/core/model-resolver.d.ts +7 -5
  248. package/dist/core/model-resolver.d.ts.map +1 -1
  249. package/dist/core/model-resolver.js +29 -17
  250. package/dist/core/model-resolver.js.map +1 -1
  251. package/dist/core/model-runtime.d.ts +79 -20
  252. package/dist/core/model-runtime.d.ts.map +1 -1
  253. package/dist/core/model-runtime.js +460 -134
  254. package/dist/core/model-runtime.js.map +1 -1
  255. package/dist/core/models-store.d.ts +12 -7
  256. package/dist/core/models-store.d.ts.map +1 -1
  257. package/dist/core/models-store.js +87 -18
  258. package/dist/core/models-store.js.map +1 -1
  259. package/dist/core/multi-agent/fsm.js +8 -3
  260. package/dist/core/multi-agent/fsm.js.map +1 -1
  261. package/dist/core/multi-agent/mailbox.js +1 -3
  262. package/dist/core/multi-agent/mailbox.js.map +1 -1
  263. package/dist/core/multi-agent/permission-gate.d.ts +5 -2
  264. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  265. package/dist/core/multi-agent/permission-gate.js +597 -34
  266. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  267. package/dist/core/multi-agent/task-board.js +2 -4
  268. package/dist/core/multi-agent/task-board.js.map +1 -1
  269. package/dist/core/multi-agent/worktree.js +1 -3
  270. package/dist/core/multi-agent/worktree.js.map +1 -1
  271. package/dist/core/nested-tool-calls.d.ts +102 -0
  272. package/dist/core/nested-tool-calls.d.ts.map +1 -0
  273. package/dist/core/nested-tool-calls.js +178 -0
  274. package/dist/core/nested-tool-calls.js.map +1 -0
  275. package/dist/core/package-manager.d.ts +10 -0
  276. package/dist/core/package-manager.d.ts.map +1 -1
  277. package/dist/core/package-manager.js +149 -33
  278. package/dist/core/package-manager.js.map +1 -1
  279. package/dist/core/pi-manifest.d.ts.map +1 -1
  280. package/dist/core/pi-manifest.js +13 -12
  281. package/dist/core/pi-manifest.js.map +1 -1
  282. package/dist/core/prompt-templates.d.ts +6 -1
  283. package/dist/core/prompt-templates.d.ts.map +1 -1
  284. package/dist/core/prompt-templates.js +63 -37
  285. package/dist/core/prompt-templates.js.map +1 -1
  286. package/dist/core/provider-attribution.js +5 -5
  287. package/dist/core/provider-attribution.js.map +1 -1
  288. package/dist/core/provider-composer.d.ts +44 -20
  289. package/dist/core/provider-composer.d.ts.map +1 -1
  290. package/dist/core/provider-composer.js +151 -51
  291. package/dist/core/provider-composer.js.map +1 -1
  292. package/dist/core/radius.d.ts +13 -0
  293. package/dist/core/radius.d.ts.map +1 -1
  294. package/dist/core/radius.js +19 -0
  295. package/dist/core/radius.js.map +1 -1
  296. package/dist/core/remote-catalog-provider.d.ts +10 -3
  297. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  298. package/dist/core/remote-catalog-provider.js +105 -81
  299. package/dist/core/remote-catalog-provider.js.map +1 -1
  300. package/dist/core/resource-loader.d.ts +7 -1
  301. package/dist/core/resource-loader.d.ts.map +1 -1
  302. package/dist/core/resource-loader.js +219 -42
  303. package/dist/core/resource-loader.js.map +1 -1
  304. package/dist/core/runtime-credentials.d.ts +5 -5
  305. package/dist/core/runtime-credentials.d.ts.map +1 -1
  306. package/dist/core/runtime-credentials.js +13 -9
  307. package/dist/core/runtime-credentials.js.map +1 -1
  308. package/dist/core/sandbox/executor.js +1 -0
  309. package/dist/core/sandbox/executor.js.map +1 -1
  310. package/dist/core/sdk.d.ts +7 -5
  311. package/dist/core/sdk.d.ts.map +1 -1
  312. package/dist/core/sdk.js +100 -52
  313. package/dist/core/sdk.js.map +1 -1
  314. package/dist/core/session-cwd.js +1 -0
  315. package/dist/core/session-cwd.js.map +1 -1
  316. package/dist/core/session-export.d.ts +8 -0
  317. package/dist/core/session-export.d.ts.map +1 -0
  318. package/dist/core/session-export.js +33 -0
  319. package/dist/core/session-export.js.map +1 -0
  320. package/dist/core/session-manager.d.ts +75 -15
  321. package/dist/core/session-manager.d.ts.map +1 -1
  322. package/dist/core/session-manager.js +314 -144
  323. package/dist/core/session-manager.js.map +1 -1
  324. package/dist/core/settings-diagnostics.d.ts +9 -0
  325. package/dist/core/settings-diagnostics.d.ts.map +1 -0
  326. package/dist/core/settings-diagnostics.js +21 -0
  327. package/dist/core/settings-diagnostics.js.map +1 -0
  328. package/dist/core/settings-manager.d.ts +84 -4
  329. package/dist/core/settings-manager.d.ts.map +1 -1
  330. package/dist/core/settings-manager.js +239 -25
  331. package/dist/core/settings-manager.js.map +1 -1
  332. package/dist/core/skills.d.ts.map +1 -1
  333. package/dist/core/skills.js +51 -33
  334. package/dist/core/skills.js.map +1 -1
  335. package/dist/core/slash-commands.d.ts.map +1 -1
  336. package/dist/core/slash-commands.js +3 -1
  337. package/dist/core/slash-commands.js.map +1 -1
  338. package/dist/core/soak/soak-log.js +6 -0
  339. package/dist/core/soak/soak-log.js.map +1 -1
  340. package/dist/core/socket-server/socket-server.js +11 -0
  341. package/dist/core/socket-server/socket-server.js.map +1 -1
  342. package/dist/core/socket-server/types.d.ts +2 -1
  343. package/dist/core/socket-server/types.d.ts.map +1 -1
  344. package/dist/core/socket-server/types.js.map +1 -1
  345. package/dist/core/source-info.d.ts +8 -0
  346. package/dist/core/source-info.d.ts.map +1 -1
  347. package/dist/core/source-info.js +16 -0
  348. package/dist/core/source-info.js.map +1 -1
  349. package/dist/core/system-prompt.d.ts +49 -6
  350. package/dist/core/system-prompt.d.ts.map +1 -1
  351. package/dist/core/system-prompt.js +126 -89
  352. package/dist/core/system-prompt.js.map +1 -1
  353. package/dist/core/tools/bash.d.ts +32 -2
  354. package/dist/core/tools/bash.d.ts.map +1 -1
  355. package/dist/core/tools/bash.js +82 -143
  356. package/dist/core/tools/bash.js.map +1 -1
  357. package/dist/core/tools/edit-diff.d.ts +0 -5
  358. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  359. package/dist/core/tools/edit-diff.js +2 -5
  360. package/dist/core/tools/edit-diff.js.map +1 -1
  361. package/dist/core/tools/edit.d.ts +5 -12
  362. package/dist/core/tools/edit.d.ts.map +1 -1
  363. package/dist/core/tools/edit.js +19 -171
  364. package/dist/core/tools/edit.js.map +1 -1
  365. package/dist/core/tools/find.d.ts +4 -0
  366. package/dist/core/tools/find.d.ts.map +1 -1
  367. package/dist/core/tools/find.js +11 -58
  368. package/dist/core/tools/find.js.map +1 -1
  369. package/dist/core/tools/grep.d.ts +4 -0
  370. package/dist/core/tools/grep.d.ts.map +1 -1
  371. package/dist/core/tools/grep.js +10 -62
  372. package/dist/core/tools/grep.js.map +1 -1
  373. package/dist/core/tools/index.d.ts +4 -1
  374. package/dist/core/tools/index.d.ts.map +1 -1
  375. package/dist/core/tools/index.js +18 -1
  376. package/dist/core/tools/index.js.map +1 -1
  377. package/dist/core/tools/ls.d.ts +4 -0
  378. package/dist/core/tools/ls.d.ts.map +1 -1
  379. package/dist/core/tools/ls.js +9 -50
  380. package/dist/core/tools/ls.js.map +1 -1
  381. package/dist/core/tools/output-accumulator.d.ts +11 -0
  382. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  383. package/dist/core/tools/output-accumulator.js +54 -12
  384. package/dist/core/tools/output-accumulator.js.map +1 -1
  385. package/dist/core/tools/powershell.d.ts +16 -0
  386. package/dist/core/tools/powershell.d.ts.map +1 -0
  387. package/dist/core/tools/powershell.js +39 -0
  388. package/dist/core/tools/powershell.js.map +1 -0
  389. package/dist/core/tools/read.d.ts +8 -1
  390. package/dist/core/tools/read.d.ts.map +1 -1
  391. package/dist/core/tools/read.js +16 -123
  392. package/dist/core/tools/read.js.map +1 -1
  393. package/dist/core/tools/render-utils.d.ts +6 -0
  394. package/dist/core/tools/render-utils.d.ts.map +1 -1
  395. package/dist/core/tools/render-utils.js +26 -0
  396. package/dist/core/tools/render-utils.js.map +1 -1
  397. package/dist/core/tools/renderers/bash.d.ts +12 -0
  398. package/dist/core/tools/renderers/bash.d.ts.map +1 -0
  399. package/dist/core/tools/renderers/bash.js +117 -0
  400. package/dist/core/tools/renderers/bash.js.map +1 -0
  401. package/dist/core/tools/renderers/edit.d.ts +23 -0
  402. package/dist/core/tools/renderers/edit.d.ts.map +1 -0
  403. package/dist/core/tools/renderers/edit.js +167 -0
  404. package/dist/core/tools/renderers/edit.js.map +1 -0
  405. package/dist/core/tools/renderers/find.d.ts +10 -0
  406. package/dist/core/tools/renderers/find.d.ts.map +1 -0
  407. package/dist/core/tools/renderers/find.js +64 -0
  408. package/dist/core/tools/renderers/find.js.map +1 -0
  409. package/dist/core/tools/renderers/grep.d.ts +10 -0
  410. package/dist/core/tools/renderers/grep.d.ts.map +1 -0
  411. package/dist/core/tools/renderers/grep.js +69 -0
  412. package/dist/core/tools/renderers/grep.js.map +1 -0
  413. package/dist/core/tools/renderers/index.d.ts +28 -0
  414. package/dist/core/tools/renderers/index.d.ts.map +1 -0
  415. package/dist/core/tools/renderers/index.js +47 -0
  416. package/dist/core/tools/renderers/index.js.map +1 -0
  417. package/dist/core/tools/renderers/ls.d.ts +10 -0
  418. package/dist/core/tools/renderers/ls.d.ts.map +1 -0
  419. package/dist/core/tools/renderers/ls.js +58 -0
  420. package/dist/core/tools/renderers/ls.js.map +1 -0
  421. package/dist/core/tools/renderers/read.d.ts +11 -0
  422. package/dist/core/tools/renderers/read.d.ts.map +1 -0
  423. package/dist/core/tools/renderers/read.js +130 -0
  424. package/dist/core/tools/renderers/read.js.map +1 -0
  425. package/dist/core/tools/renderers/write.d.ts +10 -0
  426. package/dist/core/tools/renderers/write.d.ts.map +1 -0
  427. package/dist/core/tools/renderers/write.js +153 -0
  428. package/dist/core/tools/renderers/write.js.map +1 -0
  429. package/dist/core/tools/tool-definition-wrapper.d.ts +5 -3
  430. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  431. package/dist/core/tools/tool-definition-wrapper.js +3 -1
  432. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  433. package/dist/core/tools/truncate.d.ts +14 -0
  434. package/dist/core/tools/truncate.d.ts.map +1 -1
  435. package/dist/core/tools/truncate.js +29 -0
  436. package/dist/core/tools/truncate.js.map +1 -1
  437. package/dist/core/tools/write.d.ts +4 -0
  438. package/dist/core/tools/write.d.ts.map +1 -1
  439. package/dist/core/tools/write.js +12 -147
  440. package/dist/core/tools/write.js.map +1 -1
  441. package/dist/core/trust-manager.d.ts.map +1 -1
  442. package/dist/core/trust-manager.js +4 -1
  443. package/dist/core/trust-manager.js.map +1 -1
  444. package/dist/core/usage-totals.d.ts +3 -1
  445. package/dist/core/usage-totals.d.ts.map +1 -1
  446. package/dist/core/usage-totals.js +28 -1
  447. package/dist/core/usage-totals.js.map +1 -1
  448. package/dist/core/virtual-models.d.ts +117 -0
  449. package/dist/core/virtual-models.d.ts.map +1 -0
  450. package/dist/core/virtual-models.js +124 -0
  451. package/dist/core/virtual-models.js.map +1 -0
  452. package/dist/experimental/micro/api.d.ts +81 -0
  453. package/dist/experimental/micro/api.d.ts.map +1 -0
  454. package/dist/experimental/micro/api.js +2 -0
  455. package/dist/experimental/micro/api.js.map +1 -0
  456. package/dist/experimental/micro/main.d.ts +3 -0
  457. package/dist/experimental/micro/main.d.ts.map +1 -0
  458. package/dist/experimental/micro/main.js +21 -0
  459. package/dist/experimental/micro/main.js.map +1 -0
  460. package/dist/experimental/micro/models.d.ts +11 -0
  461. package/dist/experimental/micro/models.d.ts.map +1 -0
  462. package/dist/experimental/micro/models.js +95 -0
  463. package/dist/experimental/micro/models.js.map +1 -0
  464. package/dist/experimental/micro/runtime.d.ts +12 -0
  465. package/dist/experimental/micro/runtime.d.ts.map +1 -0
  466. package/dist/experimental/micro/runtime.js +465 -0
  467. package/dist/experimental/micro/runtime.js.map +1 -0
  468. package/dist/experimental/micro/sessions.d.ts +10 -0
  469. package/dist/experimental/micro/sessions.d.ts.map +1 -0
  470. package/dist/experimental/micro/sessions.js +41 -0
  471. package/dist/experimental/micro/sessions.js.map +1 -0
  472. package/dist/experimental/micro/tools.d.ts +10 -0
  473. package/dist/experimental/micro/tools.d.ts.map +1 -0
  474. package/dist/experimental/micro/tools.js +96 -0
  475. package/dist/experimental/micro/tools.js.map +1 -0
  476. package/dist/experimental/micro/tui.d.ts +3 -0
  477. package/dist/experimental/micro/tui.d.ts.map +1 -0
  478. package/dist/experimental/micro/tui.js +510 -0
  479. package/dist/experimental/micro/tui.js.map +1 -0
  480. package/dist/experimental/mini/main.d.ts +7 -0
  481. package/dist/experimental/mini/main.d.ts.map +1 -0
  482. package/dist/experimental/mini/main.js +21 -0
  483. package/dist/experimental/mini/main.js.map +1 -0
  484. package/dist/experimental/mini/server/entry.d.ts +3 -0
  485. package/dist/experimental/mini/server/entry.d.ts.map +1 -0
  486. package/dist/experimental/mini/server/entry.js +11 -0
  487. package/dist/experimental/mini/server/entry.js.map +1 -0
  488. package/dist/experimental/mini/server/run.d.ts +13 -0
  489. package/dist/experimental/mini/server/run.d.ts.map +1 -0
  490. package/dist/experimental/mini/server/run.js +150 -0
  491. package/dist/experimental/mini/server/run.js.map +1 -0
  492. package/dist/experimental/mini/shared/protocol.d.ts +127 -0
  493. package/dist/experimental/mini/shared/protocol.d.ts.map +1 -0
  494. package/dist/experimental/mini/shared/protocol.js +13 -0
  495. package/dist/experimental/mini/shared/protocol.js.map +1 -0
  496. package/dist/experimental/mini/shared/rpc.d.ts +49 -0
  497. package/dist/experimental/mini/shared/rpc.d.ts.map +1 -0
  498. package/dist/experimental/mini/shared/rpc.js +171 -0
  499. package/dist/experimental/mini/shared/rpc.js.map +1 -0
  500. package/dist/experimental/mini/shared/transport.d.ts +35 -0
  501. package/dist/experimental/mini/shared/transport.d.ts.map +1 -0
  502. package/dist/experimental/mini/shared/transport.js +94 -0
  503. package/dist/experimental/mini/shared/transport.js.map +1 -0
  504. package/dist/experimental/mini/tui/run.d.ts +9 -0
  505. package/dist/experimental/mini/tui/run.d.ts.map +1 -0
  506. package/dist/experimental/mini/tui/run.js +62 -0
  507. package/dist/experimental/mini/tui/run.js.map +1 -0
  508. package/dist/experimental/mini/tui/session.d.ts +26 -0
  509. package/dist/experimental/mini/tui/session.d.ts.map +1 -0
  510. package/dist/experimental/mini/tui/session.js +94 -0
  511. package/dist/experimental/mini/tui/session.js.map +1 -0
  512. package/dist/experimental/mini/tui/view.d.ts +10 -0
  513. package/dist/experimental/mini/tui/view.d.ts.map +1 -0
  514. package/dist/experimental/mini/tui/view.js +461 -0
  515. package/dist/experimental/mini/tui/view.js.map +1 -0
  516. package/dist/experimental/mini/worker/entry.d.ts +3 -0
  517. package/dist/experimental/mini/worker/entry.d.ts.map +1 -0
  518. package/dist/experimental/mini/worker/entry.js +10 -0
  519. package/dist/experimental/mini/worker/entry.js.map +1 -0
  520. package/dist/experimental/mini/worker/lane-service.d.ts +44 -0
  521. package/dist/experimental/mini/worker/lane-service.d.ts.map +1 -0
  522. package/dist/experimental/mini/worker/lane-service.js +97 -0
  523. package/dist/experimental/mini/worker/lane-service.js.map +1 -0
  524. package/dist/experimental/mini/worker/models-service.d.ts +19 -0
  525. package/dist/experimental/mini/worker/models-service.d.ts.map +1 -0
  526. package/dist/experimental/mini/worker/models-service.js +136 -0
  527. package/dist/experimental/mini/worker/models-service.js.map +1 -0
  528. package/dist/experimental/mini/worker/run.d.ts +14 -0
  529. package/dist/experimental/mini/worker/run.d.ts.map +1 -0
  530. package/dist/experimental/mini/worker/run.js +88 -0
  531. package/dist/experimental/mini/worker/run.js.map +1 -0
  532. package/dist/extensions/codemode/execute.d.ts +16 -0
  533. package/dist/extensions/codemode/execute.d.ts.map +1 -0
  534. package/dist/extensions/codemode/execute.js +429 -0
  535. package/dist/extensions/codemode/execute.js.map +1 -0
  536. package/dist/extensions/codemode/execute.lazy.d.ts +3 -0
  537. package/dist/extensions/codemode/execute.lazy.d.ts.map +1 -0
  538. package/dist/extensions/codemode/execute.lazy.js +3 -0
  539. package/dist/extensions/codemode/execute.lazy.js.map +1 -0
  540. package/dist/extensions/codemode/index.d.ts +21 -0
  541. package/dist/extensions/codemode/index.d.ts.map +1 -0
  542. package/dist/extensions/codemode/index.js +31 -0
  543. package/dist/extensions/codemode/index.js.map +1 -0
  544. package/dist/extensions/codemode/renderer.d.ts +12 -0
  545. package/dist/extensions/codemode/renderer.d.ts.map +1 -0
  546. package/dist/extensions/codemode/renderer.js +137 -0
  547. package/dist/extensions/codemode/renderer.js.map +1 -0
  548. package/dist/extensions/codemode/tool.d.ts +123 -0
  549. package/dist/extensions/codemode/tool.d.ts.map +1 -0
  550. package/dist/extensions/codemode/tool.js +315 -0
  551. package/dist/extensions/codemode/tool.js.map +1 -0
  552. package/dist/extensions/codemode/worker.d.ts +7 -0
  553. package/dist/extensions/codemode/worker.d.ts.map +1 -0
  554. package/dist/extensions/codemode/worker.js +7 -0
  555. package/dist/extensions/codemode/worker.js.map +1 -0
  556. package/dist/extensions/index.d.ts.map +1 -1
  557. package/dist/extensions/index.js +9 -1
  558. package/dist/extensions/index.js.map +1 -1
  559. package/dist/extensions/llama/client.d.ts +8 -0
  560. package/dist/extensions/llama/client.d.ts.map +1 -1
  561. package/dist/extensions/llama/client.js +13 -0
  562. package/dist/extensions/llama/client.js.map +1 -1
  563. package/dist/extensions/llama/huggingface.js +2 -0
  564. package/dist/extensions/llama/huggingface.js.map +1 -1
  565. package/dist/extensions/llama/index.d.ts.map +1 -1
  566. package/dist/extensions/llama/index.js +13 -2
  567. package/dist/extensions/llama/index.js.map +1 -1
  568. package/dist/extensions/llama/provider.d.ts +4 -2
  569. package/dist/extensions/llama/provider.d.ts.map +1 -1
  570. package/dist/extensions/llama/provider.js +119 -17
  571. package/dist/extensions/llama/provider.js.map +1 -1
  572. package/dist/extensions/llama/ui.js +28 -12
  573. package/dist/extensions/llama/ui.js.map +1 -1
  574. package/dist/extensions/mcp/cli.d.ts +21 -0
  575. package/dist/extensions/mcp/cli.d.ts.map +1 -0
  576. package/dist/extensions/mcp/cli.js +500 -0
  577. package/dist/extensions/mcp/cli.js.map +1 -0
  578. package/dist/extensions/mcp/cli.lazy.d.ts +3 -0
  579. package/dist/extensions/mcp/cli.lazy.d.ts.map +1 -0
  580. package/dist/extensions/mcp/cli.lazy.js +3 -0
  581. package/dist/extensions/mcp/cli.lazy.js.map +1 -0
  582. package/dist/extensions/mcp/config.d.ts +72 -0
  583. package/dist/extensions/mcp/config.d.ts.map +1 -0
  584. package/dist/extensions/mcp/config.js +158 -0
  585. package/dist/extensions/mcp/config.js.map +1 -0
  586. package/dist/extensions/mcp/index.d.ts +76 -0
  587. package/dist/extensions/mcp/index.d.ts.map +1 -0
  588. package/dist/extensions/mcp/index.js +1055 -0
  589. package/dist/extensions/mcp/index.js.map +1 -0
  590. package/dist/extensions/mcp/log.d.ts +16 -0
  591. package/dist/extensions/mcp/log.d.ts.map +1 -0
  592. package/dist/extensions/mcp/log.js +66 -0
  593. package/dist/extensions/mcp/log.js.map +1 -0
  594. package/dist/extensions/mcp/oauth.d.ts +96 -0
  595. package/dist/extensions/mcp/oauth.d.ts.map +1 -0
  596. package/dist/extensions/mcp/oauth.js +333 -0
  597. package/dist/extensions/mcp/oauth.js.map +1 -0
  598. package/dist/extensions/mcp/resources.d.ts +43 -0
  599. package/dist/extensions/mcp/resources.d.ts.map +1 -0
  600. package/dist/extensions/mcp/resources.js +262 -0
  601. package/dist/extensions/mcp/resources.js.map +1 -0
  602. package/dist/extensions/mcp/runtime.d.ts +98 -0
  603. package/dist/extensions/mcp/runtime.d.ts.map +1 -0
  604. package/dist/extensions/mcp/runtime.js +394 -0
  605. package/dist/extensions/mcp/runtime.js.map +1 -0
  606. package/dist/extensions/mcp/runtime.lazy.d.ts +3 -0
  607. package/dist/extensions/mcp/runtime.lazy.d.ts.map +1 -0
  608. package/dist/extensions/mcp/runtime.lazy.js +3 -0
  609. package/dist/extensions/mcp/runtime.lazy.js.map +1 -0
  610. package/dist/extensions/mcp/tools.d.ts +84 -0
  611. package/dist/extensions/mcp/tools.d.ts.map +1 -0
  612. package/dist/extensions/mcp/tools.js +251 -0
  613. package/dist/extensions/mcp/tools.js.map +1 -0
  614. package/dist/extensions/mcp/ui.d.ts +60 -0
  615. package/dist/extensions/mcp/ui.d.ts.map +1 -0
  616. package/dist/extensions/mcp/ui.js +174 -0
  617. package/dist/extensions/mcp/ui.js.map +1 -0
  618. package/dist/extensions/stub-provider/provider.d.ts +2 -2
  619. package/dist/extensions/stub-provider/provider.d.ts.map +1 -1
  620. package/dist/extensions/stub-provider/provider.js +2 -1
  621. package/dist/extensions/stub-provider/provider.js.map +1 -1
  622. package/dist/extensions/tool-search/index.d.ts +12 -0
  623. package/dist/extensions/tool-search/index.d.ts.map +1 -0
  624. package/dist/extensions/tool-search/index.js +15 -0
  625. package/dist/extensions/tool-search/index.js.map +1 -0
  626. package/dist/extensions/tool-search/tool.d.ts +73 -0
  627. package/dist/extensions/tool-search/tool.d.ts.map +1 -0
  628. package/dist/extensions/tool-search/tool.js +189 -0
  629. package/dist/extensions/tool-search/tool.js.map +1 -0
  630. package/dist/index.d.ts +20 -11
  631. package/dist/index.d.ts.map +1 -1
  632. package/dist/index.js +12 -6
  633. package/dist/index.js.map +1 -1
  634. package/dist/main.d.ts +4 -0
  635. package/dist/main.d.ts.map +1 -1
  636. package/dist/main.js +123 -51
  637. package/dist/main.js.map +1 -1
  638. package/dist/migrations.d.ts +1 -1
  639. package/dist/migrations.js +7 -6
  640. package/dist/migrations.js.map +1 -1
  641. package/dist/modes/index.d.ts +1 -0
  642. package/dist/modes/index.d.ts.map +1 -1
  643. package/dist/modes/index.js.map +1 -1
  644. package/dist/modes/interactive/bug-report.d.ts +19 -0
  645. package/dist/modes/interactive/bug-report.d.ts.map +1 -0
  646. package/dist/modes/interactive/bug-report.js +211 -0
  647. package/dist/modes/interactive/bug-report.js.map +1 -0
  648. package/dist/modes/interactive/chat-viewport.d.ts +20 -0
  649. package/dist/modes/interactive/chat-viewport.d.ts.map +1 -0
  650. package/dist/modes/interactive/chat-viewport.js +28 -0
  651. package/dist/modes/interactive/chat-viewport.js.map +1 -0
  652. package/dist/modes/interactive/components/armin.js +10 -6
  653. package/dist/modes/interactive/components/armin.js.map +1 -1
  654. package/dist/modes/interactive/components/assistant-message.d.ts +6 -2
  655. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  656. package/dist/modes/interactive/components/assistant-message.js +38 -15
  657. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  658. package/dist/modes/interactive/components/bash-execution.js +9 -4
  659. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  660. package/dist/modes/interactive/components/bordered-loader.js +3 -0
  661. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  662. package/dist/modes/interactive/components/branch-summary-message.d.ts +1 -1
  663. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  664. package/dist/modes/interactive/components/branch-summary-message.js +15 -6
  665. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  666. package/dist/modes/interactive/components/compaction-summary-message.d.ts +1 -1
  667. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  668. package/dist/modes/interactive/components/compaction-summary-message.js +15 -6
  669. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  670. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  671. package/dist/modes/interactive/components/config-selector.js +35 -8
  672. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  673. package/dist/modes/interactive/components/countdown-timer.js +5 -0
  674. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  675. package/dist/modes/interactive/components/custom-editor.d.ts +10 -1
  676. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  677. package/dist/modes/interactive/components/custom-editor.js +54 -2
  678. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  679. package/dist/modes/interactive/components/custom-entry.js +4 -1
  680. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  681. package/dist/modes/interactive/components/custom-message.js +7 -1
  682. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  683. package/dist/modes/interactive/components/daxnuts.js +8 -6
  684. package/dist/modes/interactive/components/daxnuts.js.map +1 -1
  685. package/dist/modes/interactive/components/dynamic-border.js +1 -0
  686. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  687. package/dist/modes/interactive/components/extension-editor.d.ts +4 -1
  688. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  689. package/dist/modes/interactive/components/extension-editor.js +14 -3
  690. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  691. package/dist/modes/interactive/components/extension-input.d.ts +2 -0
  692. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  693. package/dist/modes/interactive/components/extension-input.js +14 -2
  694. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  695. package/dist/modes/interactive/components/extension-selector.d.ts +1 -0
  696. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  697. package/dist/modes/interactive/components/extension-selector.js +16 -1
  698. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  699. package/dist/modes/interactive/components/first-time-setup.d.ts +4 -4
  700. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  701. package/dist/modes/interactive/components/first-time-setup.js +12 -4
  702. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  703. package/dist/modes/interactive/components/footer.d.ts +7 -0
  704. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  705. package/dist/modes/interactive/components/footer.js +51 -6
  706. package/dist/modes/interactive/components/footer.js.map +1 -1
  707. package/dist/modes/interactive/components/index.d.ts +1 -1
  708. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  709. package/dist/modes/interactive/components/index.js.map +1 -1
  710. package/dist/modes/interactive/components/login-dialog.js +9 -3
  711. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  712. package/dist/modes/interactive/components/markdown-transform.d.ts +3 -0
  713. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -0
  714. package/dist/modes/interactive/components/markdown-transform.js +19 -0
  715. package/dist/modes/interactive/components/markdown-transform.js.map +1 -0
  716. package/dist/modes/interactive/components/mermaid.d.ts +11 -0
  717. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -0
  718. package/dist/modes/interactive/components/mermaid.js +75 -0
  719. package/dist/modes/interactive/components/mermaid.js.map +1 -0
  720. package/dist/modes/interactive/components/model-selector.d.ts +10 -4
  721. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  722. package/dist/modes/interactive/components/model-selector.js +101 -40
  723. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  724. package/dist/modes/interactive/components/oauth-selector.js +11 -3
  725. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  726. package/dist/modes/interactive/components/scoped-models-selector.d.ts +4 -0
  727. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  728. package/dist/modes/interactive/components/scoped-models-selector.js +60 -32
  729. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  730. package/dist/modes/interactive/components/session-selector.d.ts +5 -5
  731. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  732. package/dist/modes/interactive/components/session-selector.js +128 -78
  733. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  734. package/dist/modes/interactive/components/settings-selector.d.ts +23 -4
  735. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  736. package/dist/modes/interactive/components/settings-selector.js +230 -67
  737. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  738. package/dist/modes/interactive/components/settings-submenu.d.ts +72 -0
  739. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -0
  740. package/dist/modes/interactive/components/settings-submenu.js +165 -0
  741. package/dist/modes/interactive/components/settings-submenu.js.map +1 -0
  742. package/dist/modes/interactive/components/show-images-selector.js +1 -0
  743. package/dist/modes/interactive/components/show-images-selector.js.map +1 -1
  744. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  745. package/dist/modes/interactive/components/skill-invocation-message.js +14 -5
  746. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  747. package/dist/modes/interactive/components/status-indicator.d.ts +3 -1
  748. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  749. package/dist/modes/interactive/components/status-indicator.js +12 -3
  750. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  751. package/dist/modes/interactive/components/theme-selector.js +2 -0
  752. package/dist/modes/interactive/components/theme-selector.js.map +1 -1
  753. package/dist/modes/interactive/components/themed-text.d.ts +17 -0
  754. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -0
  755. package/dist/modes/interactive/components/themed-text.js +29 -0
  756. package/dist/modes/interactive/components/themed-text.js.map +1 -0
  757. package/dist/modes/interactive/components/thinking-selector.d.ts +15 -3
  758. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  759. package/dist/modes/interactive/components/thinking-selector.js +76 -18
  760. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  761. package/dist/modes/interactive/components/tool-execution.d.ts +21 -4
  762. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  763. package/dist/modes/interactive/components/tool-execution.js +78 -52
  764. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  765. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  766. package/dist/modes/interactive/components/tree-selector.js +44 -18
  767. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  768. package/dist/modes/interactive/components/trust-selector.js +8 -2
  769. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  770. package/dist/modes/interactive/components/user-message-selector.js +6 -3
  771. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  772. package/dist/modes/interactive/components/user-message.d.ts +3 -1
  773. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  774. package/dist/modes/interactive/components/user-message.js +12 -2
  775. package/dist/modes/interactive/components/user-message.js.map +1 -1
  776. package/dist/modes/interactive/components/visual-truncate.d.ts +27 -3
  777. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  778. package/dist/modes/interactive/components/visual-truncate.js +39 -6
  779. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  780. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  781. package/dist/modes/interactive/external-editor.js +2 -1
  782. package/dist/modes/interactive/external-editor.js.map +1 -1
  783. package/dist/modes/interactive/interactive-mode.d.ts +69 -5
  784. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  785. package/dist/modes/interactive/interactive-mode.js +1314 -593
  786. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  787. package/dist/modes/interactive/model-catalog-refresh.d.ts +7 -0
  788. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -0
  789. package/dist/modes/interactive/model-catalog-refresh.js +34 -0
  790. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -0
  791. package/dist/modes/interactive/session-share.d.ts +23 -0
  792. package/dist/modes/interactive/session-share.d.ts.map +1 -0
  793. package/dist/modes/interactive/session-share.js +130 -0
  794. package/dist/modes/interactive/session-share.js.map +1 -0
  795. package/dist/modes/interactive/theme/dark.json +54 -63
  796. package/dist/modes/interactive/theme/light.json +52 -60
  797. package/dist/modes/interactive/theme/system-theme.d.ts +54 -0
  798. package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -0
  799. package/dist/modes/interactive/theme/system-theme.js +535 -0
  800. package/dist/modes/interactive/theme/system-theme.js.map +1 -0
  801. package/dist/modes/interactive/theme/theme-controller.d.ts +59 -7
  802. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  803. package/dist/modes/interactive/theme/theme-controller.js +164 -51
  804. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  805. package/dist/modes/interactive/theme/theme-json.d.ts +85 -0
  806. package/dist/modes/interactive/theme/theme-json.d.ts.map +1 -0
  807. package/dist/modes/interactive/theme/theme-json.js +132 -0
  808. package/dist/modes/interactive/theme/theme-json.js.map +1 -0
  809. package/dist/modes/interactive/theme/theme-schema.json +24 -3
  810. package/dist/modes/interactive/theme/theme.d.ts +80 -42
  811. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  812. package/dist/modes/interactive/theme/theme.js +274 -417
  813. package/dist/modes/interactive/theme/theme.js.map +1 -1
  814. package/dist/modes/interactive/tui-renderer.d.ts +22 -0
  815. package/dist/modes/interactive/tui-renderer.d.ts.map +1 -0
  816. package/dist/modes/interactive/tui-renderer.js +67 -0
  817. package/dist/modes/interactive/tui-renderer.js.map +1 -0
  818. package/dist/modes/json-event.d.ts +34 -0
  819. package/dist/modes/json-event.d.ts.map +1 -0
  820. package/dist/modes/json-event.js +29 -0
  821. package/dist/modes/json-event.js.map +1 -0
  822. package/dist/modes/print-mode.d.ts +1 -1
  823. package/dist/modes/print-mode.d.ts.map +1 -1
  824. package/dist/modes/print-mode.js +12 -2
  825. package/dist/modes/print-mode.js.map +1 -1
  826. package/dist/modes/rpc/rpc-client.d.ts +17 -9
  827. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  828. package/dist/modes/rpc/rpc-client.js +27 -15
  829. package/dist/modes/rpc/rpc-client.js.map +1 -1
  830. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  831. package/dist/modes/rpc/rpc-mode.js +14 -12
  832. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  833. package/dist/modes/rpc/rpc-types.d.ts +22 -1
  834. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  835. package/dist/modes/rpc/rpc-types.js.map +1 -1
  836. package/dist/package-manager-cli.d.ts +1 -0
  837. package/dist/package-manager-cli.d.ts.map +1 -1
  838. package/dist/package-manager-cli.js +217 -63
  839. package/dist/package-manager-cli.js.map +1 -1
  840. package/dist/prompts/commands/plan-phase.md +1 -0
  841. package/dist/prompts/commands/review.md +2 -0
  842. package/dist/prompts/commands/verify-work.md +1 -0
  843. package/dist/prompts/commands/why.md +4 -0
  844. package/dist/rpc-entry.js +1 -0
  845. package/dist/rpc-entry.js.map +1 -1
  846. package/dist/skills/blast-radius/SKILL.md +1 -0
  847. package/dist/skills/explainers/SKILL.md +65 -0
  848. package/dist/skills/unslop/SKILL.md +19 -1
  849. package/dist/utils/abort.d.ts +5 -0
  850. package/dist/utils/abort.d.ts.map +1 -0
  851. package/dist/utils/abort.js +48 -0
  852. package/dist/utils/abort.js.map +1 -0
  853. package/dist/utils/changelog.js +1 -1
  854. package/dist/utils/changelog.js.map +1 -1
  855. package/dist/utils/child-process.d.ts +1 -1
  856. package/dist/utils/child-process.js +1 -1
  857. package/dist/utils/child-process.js.map +1 -1
  858. package/dist/utils/clipboard-command.d.ts +7 -0
  859. package/dist/utils/clipboard-command.d.ts.map +1 -0
  860. package/dist/utils/clipboard-command.js +45 -0
  861. package/dist/utils/clipboard-command.js.map +1 -0
  862. package/dist/utils/clipboard-image.d.ts.map +1 -1
  863. package/dist/utils/clipboard-image.js +60 -91
  864. package/dist/utils/clipboard-image.js.map +1 -1
  865. package/dist/utils/clipboard.d.ts +2 -0
  866. package/dist/utils/clipboard.d.ts.map +1 -1
  867. package/dist/utils/clipboard.js +116 -121
  868. package/dist/utils/clipboard.js.map +1 -1
  869. package/dist/utils/draht-user-agent.d.ts +2 -0
  870. package/dist/utils/draht-user-agent.d.ts.map +1 -0
  871. package/dist/utils/draht-user-agent.js +5 -0
  872. package/dist/utils/draht-user-agent.js.map +1 -0
  873. package/dist/utils/exif-orientation.d.ts +2 -1
  874. package/dist/utils/exif-orientation.d.ts.map +1 -1
  875. package/dist/utils/exif-orientation.js.map +1 -1
  876. package/dist/utils/frontmatter.d.ts.map +1 -1
  877. package/dist/utils/frontmatter.js +2 -1
  878. package/dist/utils/frontmatter.js.map +1 -1
  879. package/dist/utils/management-http.d.ts +25 -0
  880. package/dist/utils/management-http.d.ts.map +1 -0
  881. package/dist/utils/management-http.js +54 -0
  882. package/dist/utils/management-http.js.map +1 -0
  883. package/dist/utils/mime.js +1 -1
  884. package/dist/utils/mime.js.map +1 -1
  885. package/dist/utils/paths.d.ts +4 -3
  886. package/dist/utils/paths.d.ts.map +1 -1
  887. package/dist/utils/paths.js +15 -4
  888. package/dist/utils/paths.js.map +1 -1
  889. package/dist/utils/photon.d.ts +2 -1
  890. package/dist/utils/photon.d.ts.map +1 -1
  891. package/dist/utils/photon.js.map +1 -1
  892. package/dist/utils/shell.d.ts +4 -3
  893. package/dist/utils/shell.d.ts.map +1 -1
  894. package/dist/utils/shell.js +20 -35
  895. package/dist/utils/shell.js.map +1 -1
  896. package/dist/utils/syntax-highlight.d.ts +1 -0
  897. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  898. package/dist/utils/syntax-highlight.js +62 -1
  899. package/dist/utils/syntax-highlight.js.map +1 -1
  900. package/dist/utils/text.d.ts +8 -0
  901. package/dist/utils/text.d.ts.map +1 -0
  902. package/dist/utils/text.js +9 -0
  903. package/dist/utils/text.js.map +1 -0
  904. package/dist/utils/tool-result-images.d.ts +21 -0
  905. package/dist/utils/tool-result-images.d.ts.map +1 -0
  906. package/dist/utils/tool-result-images.js +48 -0
  907. package/dist/utils/tool-result-images.js.map +1 -0
  908. package/dist/utils/tools-manager.d.ts +11 -1
  909. package/dist/utils/tools-manager.d.ts.map +1 -1
  910. package/dist/utils/tools-manager.js +53 -36
  911. package/dist/utils/tools-manager.js.map +1 -1
  912. package/dist/utils/version-check.d.ts +4 -1
  913. package/dist/utils/version-check.d.ts.map +1 -1
  914. package/dist/utils/version-check.js +30 -9
  915. package/dist/utils/version-check.js.map +1 -1
  916. package/dist/utils/wsl.d.ts +3 -0
  917. package/dist/utils/wsl.d.ts.map +1 -0
  918. package/dist/utils/wsl.js +15 -0
  919. package/dist/utils/wsl.js.map +1 -0
  920. package/dist/utils/zip.d.ts +7 -0
  921. package/dist/utils/zip.d.ts.map +1 -0
  922. package/dist/utils/zip.js +60 -0
  923. package/dist/utils/zip.js.map +1 -0
  924. package/docs/cli-integration.md +106 -0
  925. package/docs/cli.md +374 -0
  926. package/docs/compaction.md +91 -29
  927. package/docs/configuration.md +47 -0
  928. package/docs/containerization.md +100 -66
  929. package/docs/custom-provider.md +109 -707
  930. package/docs/docs.json +155 -99
  931. package/docs/environment-variables.md +30 -17
  932. package/docs/extensions.md +169 -2811
  933. package/docs/how-pi-works.md +53 -0
  934. package/docs/images/interactive-mode.png +0 -0
  935. package/docs/index.md +25 -69
  936. package/docs/json.md +197 -56
  937. package/docs/keybindings.md +89 -93
  938. package/docs/llama-cpp.md +18 -3
  939. package/docs/mcp.md +231 -0
  940. package/docs/message-types.md +261 -0
  941. package/docs/models.md +94 -478
  942. package/docs/packages.md +67 -163
  943. package/docs/prompt-templates.md +31 -68
  944. package/docs/providers.md +118 -215
  945. package/docs/quickstart.md +55 -108
  946. package/docs/rpc-commands.md +860 -0
  947. package/docs/rpc-extension-ui.md +200 -0
  948. package/docs/rpc.md +139 -1518
  949. package/docs/sdk.md +79 -1127
  950. package/docs/security.md +76 -32
  951. package/docs/session-format.md +73 -219
  952. package/docs/sessions.md +36 -116
  953. package/docs/settings.md +124 -257
  954. package/docs/shell-aliases.md +85 -5
  955. package/docs/skills.md +52 -189
  956. package/docs/slash-commands.md +61 -0
  957. package/docs/terminal-setup.md +132 -61
  958. package/docs/termux.md +74 -84
  959. package/docs/themes.md +91 -252
  960. package/docs/tmux.md +31 -39
  961. package/docs/tui.md +74 -891
  962. package/docs/usage.md +54 -255
  963. package/docs/virtual-models.md +114 -0
  964. package/docs/windows.md +57 -7
  965. package/examples/extensions/antigravity-image-gen.ts +9 -9
  966. package/examples/extensions/bash-spawn-hook.ts +1 -1
  967. package/examples/extensions/border-status-editor.ts +1 -1
  968. package/examples/extensions/built-in-tool-renderer.ts +16 -40
  969. package/examples/extensions/custom-compaction.ts +1 -16
  970. package/examples/extensions/custom-provider-anthropic/index.ts +20 -13
  971. package/examples/extensions/custom-provider-gitlab-duo/index.ts +4 -3
  972. package/examples/extensions/custom-provider-gitlab-duo/test.ts +5 -5
  973. package/examples/extensions/debug-provider.ts +90 -0
  974. package/examples/extensions/doom-overlay/wad-finder.ts +7 -3
  975. package/examples/extensions/dynamic-resources/dynamic.json +3 -1
  976. package/examples/extensions/git-checkpoint.ts +2 -2
  977. package/examples/extensions/handoff.ts +2 -11
  978. package/examples/extensions/jev-router.ts +113 -0
  979. package/examples/extensions/minimal-mode.ts +24 -96
  980. package/examples/extensions/notify.ts +3 -1
  981. package/examples/extensions/prompt-customizer.ts +19 -67
  982. package/examples/extensions/qna.ts +3 -7
  983. package/examples/extensions/subagent/agents.ts +40 -9
  984. package/examples/extensions/subagent/index.ts +27 -4
  985. package/examples/extensions/summarize.ts +7 -18
  986. package/examples/extensions/titlebar-spinner.ts +1 -1
  987. package/examples/rpc-client.ts +35 -0
  988. package/examples/rpc-extension-ui.ts +38 -9
  989. package/examples/sdk/02-custom-model.ts +1 -2
  990. package/examples/sdk/06-extensions.ts +1 -1
  991. package/examples/sdk/09-api-keys-and-oauth.ts +1 -1
  992. package/examples/sdk/12-full-control.ts +1 -1
  993. package/examples/sdk/14-codemode-mcp.ts +61 -0
  994. package/package.json +25 -30
  995. package/prompts/commands/plan-phase.md +1 -0
  996. package/prompts/commands/review.md +2 -0
  997. package/prompts/commands/verify-work.md +1 -0
  998. package/prompts/commands/why.md +4 -0
  999. package/skills/blast-radius/SKILL.md +1 -0
  1000. package/skills/explainers/SKILL.md +65 -0
  1001. package/skills/unslop/SKILL.md +19 -1
  1002. package/dist/utils/clipboard-native.d.ts +0 -11
  1003. package/dist/utils/clipboard-native.d.ts.map +0 -1
  1004. package/dist/utils/clipboard-native.js +0 -20
  1005. package/dist/utils/clipboard-native.js.map +0 -1
  1006. package/dist/utils/pi-user-agent.d.ts +0 -2
  1007. package/dist/utils/pi-user-agent.d.ts.map +0 -1
  1008. package/dist/utils/pi-user-agent.js +0 -5
  1009. package/dist/utils/pi-user-agent.js.map +0 -1
  1010. package/docs/development.md +0 -71
  1011. package/docs/tree.md +0 -231
  1012. package/examples/extensions/kimi-deferred-tools.ts +0 -61
@@ -1,2921 +1,279 @@
1
- > draht can create extensions. Ask it to build one for your use case.
2
-
3
1
  # Extensions
4
2
 
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.
6
-
7
- > **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`.
8
-
9
- **Key capabilities:**
10
- - **Custom tools** - Register tools the LLM can call via `pi.registerTool()`
11
- - **Event interception** - Block or modify tool calls, inject context, customize compaction
12
- - **User interaction** - Prompt users via `ctx.ui` (select, confirm, input, notify)
13
- - **Custom UI components** - Full TUI components with keyboard input via `ctx.ui.custom()` for complex interactions
14
- - **Custom commands** - Register commands like `/mycommand` via `pi.registerCommand()`
15
- - **Session persistence** - Store state that survives restarts via `pi.appendEntry()`
16
- - **Custom rendering** - Control how tool calls/results and messages appear in TUI
17
-
18
- **Example use cases:**
19
- - Permission gates (confirm before `rm -rf`, `sudo`, etc.)
20
- - Git checkpointing (stash at each turn, restore on branch)
21
- - Path protection (block writes to `.env`, `node_modules/`)
22
- - Custom compaction (summarize conversation your way)
23
- - Conversation summaries (see `summarize.ts` example)
24
- - Interactive tools (questions, wizards, custom dialogs)
25
- - Stateful tools (todo lists, connection pools)
26
- - External integrations (file watchers, webhooks, CI triggers)
27
- - Games while you wait (see `snake.ts` example)
28
-
29
- See [examples/extensions/](../examples/extensions/) for working implementations.
30
-
31
- ## Table of Contents
32
-
33
- - [Quick Start](#quick-start)
34
- - [Extension Locations](#extension-locations)
35
- - [Available Imports](#available-imports)
36
- - [Writing an Extension](#writing-an-extension)
37
- - [Extension Styles](#extension-styles)
38
- - [Events](#events)
39
- - [Lifecycle Overview](#lifecycle-overview)
40
- - [Resource Events](#resource-events)
41
- - [Session Events](#session-events)
42
- - [Agent Events](#agent-events)
43
- - [Model Events](#model-events)
44
- - [Tool Events](#tool-events)
45
- - [ExtensionContext](#extensioncontext)
46
- - [ExtensionCommandContext](#extensioncommandcontext)
47
- - [ExtensionAPI Methods](#extensionapi-methods)
48
- - [State Management](#state-management)
49
- - [Custom Tools](#custom-tools)
50
- - [Dynamic Tool Loading](#dynamic-tool-loading)
51
- - [Custom UI](#custom-ui)
52
- - [Error Handling](#error-handling)
53
- - [Mode Behavior](#mode-behavior)
54
- - [Examples Reference](#examples-reference)
55
-
56
- ## Quick Start
57
-
58
- Create `~/.draht/agent/extensions/my-extension.ts`:
59
-
60
- ```typescript
61
- import type { ExtensionAPI } from "@draht/coding-agent";
62
- import { Type } from "typebox";
63
-
64
- export default function (pi: ExtensionAPI) {
65
- // React to events
66
- pi.on("session_start", async (_event, ctx) => {
67
- ctx.ui.notify("Extension loaded!", "info");
68
- });
69
-
70
- pi.on("tool_call", async (event, ctx) => {
71
- if (event.toolName === "bash" && event.input.command?.includes("rm -rf")) {
72
- const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?");
73
- if (!ok) return { block: true, reason: "Blocked by user" };
74
- }
75
- });
76
-
77
- // Register a custom tool
78
- pi.registerTool({
79
- name: "greet",
80
- label: "Greet",
81
- description: "Greet someone by name",
82
- parameters: Type.Object({
83
- name: Type.String({ description: "Name to greet" }),
84
- }),
85
- async execute(toolCallId, params, signal, onUpdate, ctx) {
86
- return {
87
- content: [{ type: "text", text: `Hello, ${params.name}!` }],
88
- details: {},
89
- };
90
- },
91
- });
92
-
93
- // Register a command
94
- pi.registerCommand("hello", {
95
- description: "Say hello",
96
- handler: async (args, ctx) => {
97
- ctx.ui.notify(`Hello ${args || "world"}!`, "info");
98
- },
99
- });
100
- }
101
- ```
102
-
103
- Test with `--extension` (or `-e`) flag:
104
-
105
- ```bash
106
- draht -e ./my-extension.ts
107
- ```
108
-
109
- ## Extension Locations
110
-
111
- > **Security:** Extensions run with your full system permissions and can execute arbitrary code. Only install from sources you trust.
112
-
113
- Extensions are auto-discovered from trusted locations. Project-local `.draht/extensions` entries load only after the project is trusted.
114
-
115
- | Location | Scope |
116
- |----------|-------|
117
- | `~/.draht/agent/extensions/*.ts` | Global (all projects) |
118
- | `~/.draht/agent/extensions/*/index.ts` | Global (subdirectory) |
119
- | `.draht/extensions/*.ts` | Project-local |
120
- | `.draht/extensions/*/index.ts` | Project-local (subdirectory) |
121
-
122
- Additional paths via `settings.json`:
123
-
124
- ```json
125
- {
126
- "packages": [
127
- "npm:@foo/bar@1.0.0",
128
- "git:github.com/user/repo@v1"
129
- ],
130
- "extensions": [
131
- "/path/to/local/extension.ts",
132
- "/path/to/local/extension/dir"
133
- ]
134
- }
135
- ```
136
-
137
- To share extensions via npm or git as draht packages, see [packages.md](packages.md).
138
-
139
- ## Available Imports
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.
140
4
 
141
- | Package | Purpose |
142
- |---------|---------|
143
- | `@draht/coding-agent` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) |
144
- | `typebox` | Schema definitions for tool parameters |
145
- | `@draht/ai` | AI utilities (`StringEnum` for Google-compatible enums) |
146
- | `@draht/tui` | TUI components for custom rendering |
5
+ 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.
147
6
 
148
- 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.
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.
149
8
 
150
- For distributed draht packages installed with `draht install` (npm or git), runtime deps must be in `dependencies`. Package installation uses production installs (`npm install --omit=dev`) by default, so `devDependencies` are not available at runtime; when `npmCommand` is configured, git packages use plain `install` for compatibility with wrappers.
9
+ <a id="quick-start"></a>
10
+ <a id="writing-an-extension"></a>
11
+ <a id="create-an-extension"></a>
151
12
 
152
- Node.js built-ins (`node:fs`, `node:path`, etc.) are also available.
13
+ ## Create and load an extension
153
14
 
154
- ## Writing an Extension
15
+ An extension exports a default factory that receives `ExtensionAPI`. The factory registers capabilities for the current extension runtime.
155
16
 
156
- An extension exports a default factory function that receives `ExtensionAPI`. The factory can be synchronous or asynchronous:
17
+ Create `~/.draht/agent/extensions/hello.ts`:
157
18
 
158
19
  ```typescript
159
20
  import type { ExtensionAPI } from "@draht/coding-agent";
160
21
 
161
22
  export default function (pi: ExtensionAPI) {
162
- // Subscribe to events
163
- pi.on("event_name", async (event, ctx) => {
164
- // ctx.ui for user interaction
165
- const ok = await ctx.ui.confirm("Title", "Are you sure?");
166
- ctx.ui.notify("Done!", "info");
167
- ctx.ui.setStatus("my-ext", "Processing..."); // Footer status
168
- ctx.ui.setWidget("my-ext", ["Line 1", "Line 2"]); // Widget above editor (default)
169
- });
170
-
171
- // Register tools, commands, shortcuts, flags
172
- pi.registerTool({ ... });
173
- pi.registerCommand("name", { ... });
174
- pi.registerShortcut("ctrl+x", { ... });
175
- pi.registerFlag("my-flag", { ... });
176
- }
177
- ```
178
-
179
- Extensions are loaded via [jiti](https://github.com/unjs/jiti), so TypeScript works without compilation.
180
-
181
- 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.
182
-
183
- ### Async factory functions
184
-
185
- Use an async factory for one-time startup work such as fetching remote configuration or dynamically discovering available models.
186
-
187
- ```typescript
188
- import type { ExtensionAPI } from "@draht/coding-agent";
189
-
190
- export default async function (pi: ExtensionAPI) {
191
- const response = await fetch("http://localhost:1234/v1/models");
192
- const payload = (await response.json()) as {
193
- data: Array<{
194
- id: string;
195
- name?: string;
196
- context_window?: number;
197
- max_tokens?: number;
198
- }>;
199
- };
200
-
201
- pi.registerProvider("local-openai", {
202
- baseUrl: "http://localhost:1234/v1",
203
- apiKey: "$LOCAL_OPENAI_API_KEY",
204
- api: "openai-completions",
205
- models: payload.data.map((model) => ({
206
- id: model.id,
207
- name: model.name ?? model.id,
208
- reasoning: false,
209
- input: ["text"],
210
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
211
- contextWindow: model.context_window ?? 128000,
212
- maxTokens: model.max_tokens ?? 4096,
213
- })),
23
+ pi.registerCommand("hello", {
24
+ description: "Show a greeting",
25
+ handler: async (name, ctx) => {
26
+ ctx.ui.notify(`Hello, ${name || "world"}!`, "info");
27
+ },
214
28
  });
215
29
  }
216
30
  ```
217
31
 
218
- This pattern makes the fetched models available during normal startup and to `draht --list-models`.
219
-
220
- ### Extension Styles
221
-
222
- **Single file** - simplest, for small extensions:
223
-
224
- ```
225
- ~/.draht/agent/extensions/
226
- └── my-extension.ts
227
- ```
228
-
229
- **Directory with index.ts** - for multi-file extensions:
230
-
231
- ```
232
- ~/.draht/agent/extensions/
233
- └── my-extension/
234
- ├── index.ts # Entry point (exports default function)
235
- ├── tools.ts # Helper module
236
- └── utils.ts # Helper module
237
- ```
238
-
239
- **Package with dependencies** - for extensions that need npm packages:
240
-
241
- ```
242
- ~/.draht/agent/extensions/
243
- └── my-extension/
244
- ├── package.json # Declares dependencies and entry points
245
- ├── package-lock.json
246
- ├── node_modules/ # After npm install
247
- └── src/
248
- └── index.ts
249
- ```
250
-
251
- ```json
252
- // package.json
253
- {
254
- "name": "my-extension",
255
- "dependencies": {
256
- "zod": "^3.0.0",
257
- "chalk": "^5.0.0"
258
- },
259
- "draht": {
260
- "extensions": ["./src/index.ts"]
261
- }
262
- }
263
- ```
264
-
265
- The manifest key is `draht`. Upstream's `pi` key is still read as a fallback, so extension packages written for pi work unchanged.
266
-
267
- Run `npm install` in the extension directory, then imports from `node_modules/` work automatically.
268
-
269
- ## Events
270
-
271
- ### Lifecycle Overview
272
-
273
- ```
274
- draht starts
275
- │
276
- ├─► project_trust (user/global and CLI extensions only, before project resources load)
277
- ├─► session_start { reason: "startup" }
278
- └─► resources_discover { reason: "startup" }
279
- │
280
- ▼
281
- user sends prompt ─────────────────────────────────────────┐
282
- │ │
283
- ├─► (extension commands checked first, bypass if found) │
284
- ├─► input (can intercept, transform, or handle) │
285
- ├─► (skill/template expansion if not handled) │
286
- ├─► before_agent_start (can inject message, modify system prompt)
287
- ├─► agent_start │
288
- ├─► message_start / message_update / message_end │
289
- │ │
290
- │ ┌─── turn (repeats while LLM calls tools) ───┐ │
291
- │ │ │ │
292
- │ ├─► turn_start │ │
293
- │ ├─► context (can modify messages) │ │
294
- │ ├─► before_provider_request (can inspect or replace payload)
295
- │ ├─► after_provider_response (status + headers, before stream consume)
296
- │ │ │ │
297
- │ │ LLM responds, may call tools: │ │
298
- │ │ ├─► tool_execution_start │ │
299
- │ │ ├─► tool_call (can block) │ │
300
- │ │ ├─► tool_execution_update │ │
301
- │ │ ├─► tool_result (can modify) │ │
302
- │ │ └─► tool_execution_end │ │
303
- │ │ │ │
304
- │ └─► turn_end │ │
305
- │ │
306
- ├─► agent_end │
307
- └─► agent_settled (no retry/compaction/follow-up left) │
308
- │
309
- user sends another prompt ◄────────────────────────────────┘
310
-
311
- /new (new session) or /resume (switch session)
312
- ├─► session_before_switch (can cancel)
313
- ├─► session_shutdown
314
- ├─► session_start { reason: "new" | "resume", previousSessionFile? }
315
- └─► resources_discover { reason: "startup" }
316
-
317
- /fork or /clone
318
- ├─► session_before_fork (can cancel)
319
- ├─► session_shutdown
320
- ├─► session_start { reason: "fork", previousSessionFile }
321
- └─► resources_discover { reason: "startup" }
322
-
323
- /name or pi.setSessionName()
324
- └─► session_info_changed
325
-
326
- /compact or auto-compaction
327
- ├─► session_before_compact (can cancel or customize)
328
- └─► session_compact
329
-
330
- /tree navigation
331
- ├─► session_before_tree (can cancel or customize)
332
- └─► session_tree
333
-
334
- /model or Ctrl+P (model selection/cycling)
335
- ├─► thinking_level_select (if model change changes/clamps thinking level)
336
- └─► model_select
337
-
338
- thinking level changes (settings, keybinding, pi.setThinkingLevel())
339
- └─► thinking_level_select
340
-
341
- exit (Ctrl+C, Ctrl+D, SIGHUP, SIGTERM)
342
- └─► session_shutdown
343
- ```
344
-
345
- ### Startup Events
346
-
347
- #### project_trust
348
-
349
- 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.
350
-
351
- ```typescript
352
- pi.on("project_trust", async (event, ctx) => {
353
- // event.cwd - current working directory
354
- // ctx has a limited trust context: cwd, mode, hasUI, and select/confirm/input/notify UI helpers
355
- if (await ctx.ui.confirm("Trust project?", event.cwd)) {
356
- return { trusted: "yes", remember: true };
357
- }
358
- return { trusted: "undecided" };
359
- });
360
- ```
361
-
362
- 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.
363
-
364
- ### Resource Events
365
-
366
- #### resources_discover
367
-
368
- Fired after `session_start` so extensions can contribute additional skill, prompt, and theme paths.
369
- The startup path uses `reason: "startup"`. Reload uses `reason: "reload"`.
370
-
371
- ```typescript
372
- pi.on("resources_discover", async (event, _ctx) => {
373
- // event.cwd - current working directory
374
- // event.reason - "startup" | "reload"
375
- return {
376
- skillPaths: ["/path/to/skills"],
377
- promptPaths: ["/path/to/prompts"],
378
- themePaths: ["/path/to/themes"],
379
- };
380
- });
381
- ```
382
-
383
- ### Session Events
384
-
385
- See [Session Format](session-format.md) for session storage internals and the SessionManager API.
386
-
387
- #### session_start
388
-
389
- Fired when a session is started, loaded, or reloaded.
390
-
391
- ```typescript
392
- pi.on("session_start", async (event, ctx) => {
393
- // event.reason - "startup" | "reload" | "new" | "resume" | "fork"
394
- // event.previousSessionFile - present for "new", "resume", and "fork"
395
- ctx.ui.notify(`Session: ${ctx.sessionManager.getSessionFile() ?? "ephemeral"}`, "info");
396
- });
397
- ```
398
-
399
- #### session_info_changed
400
-
401
- Fired when the current session display name is set via `/name`, RPC, or `pi.setSessionName()`.
402
-
403
- ```typescript
404
- pi.on("session_info_changed", async (event, ctx) => {
405
- // event.name - current normalized name, or undefined if cleared
406
- ctx.ui.notify(`Session renamed: ${event.name ?? "(none)"}`, "info");
407
- });
408
- ```
409
-
410
- #### session_before_switch
411
-
412
- Fired before starting a new session (`/new`) or switching sessions (`/resume`).
413
-
414
- ```typescript
415
- pi.on("session_before_switch", async (event, ctx) => {
416
- // event.reason - "new" or "resume"
417
- // event.targetSessionFile - session we're switching to (only for "resume")
418
-
419
- if (event.reason === "new") {
420
- const ok = await ctx.ui.confirm("Clear?", "Delete all messages?");
421
- if (!ok) return { cancel: true };
422
- }
423
- });
424
- ```
425
-
426
- 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`.
427
- Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
428
-
429
- #### session_before_fork
430
-
431
- Fired when forking via `/fork` or cloning via `/clone`.
432
-
433
- ```typescript
434
- pi.on("session_before_fork", async (event, ctx) => {
435
- // event.entryId - ID of the selected entry
436
- // event.position - "before" for /fork, "at" for /clone
437
- return { cancel: true }; // Cancel fork/clone
438
- // OR
439
- return { skipConversationRestore: true }; // Reserved for future conversation restore control
440
- });
441
- ```
442
-
443
- 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`.
444
- Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
445
-
446
- #### session_before_compact / session_compact
447
-
448
- Fired on compaction. See [compaction.md](compaction.md) for details.
449
-
450
- ```typescript
451
- pi.on("session_before_compact", async (event, ctx) => {
452
- const { preparation, branchEntries, customInstructions, signal } = event;
453
-
454
- // Cancel:
455
- return { cancel: true };
456
-
457
- // Custom summary:
458
- return {
459
- compaction: {
460
- summary: "...",
461
- firstKeptEntryId: preparation.firstKeptEntryId,
462
- tokensBefore: preparation.tokensBefore,
463
- // usage: summaryResponse.usage, // Optional; included in session totals
464
- }
465
- };
466
- });
467
-
468
- pi.on("session_compact", async (event, ctx) => {
469
- // event.compactionEntry - the saved compaction
470
- // event.fromExtension - whether extension provided it
471
- });
472
- ```
473
-
474
- #### session_before_tree / session_tree
475
-
476
- Fired on `/tree` navigation. See [Sessions](sessions.md) for tree navigation concepts.
477
-
478
- ```typescript
479
- pi.on("session_before_tree", async (event, ctx) => {
480
- const { preparation, signal } = event;
481
- return { cancel: true };
482
- // OR provide custom summary:
483
- return {
484
- summary: {
485
- summary: "...",
486
- // usage: summaryResponse.usage, // Optional; included in session totals
487
- details: {},
488
- },
489
- };
490
- });
491
-
492
- pi.on("session_tree", async (event, ctx) => {
493
- // event.newLeafId, oldLeafId, summaryEntry, fromExtension
494
- });
495
- ```
496
-
497
- #### session_shutdown
498
-
499
- Fired before an extension runtime is torn down.
500
-
501
- ```typescript
502
- pi.on("session_shutdown", async (event, ctx) => {
503
- // event.reason - "quit" | "reload" | "new" | "resume" | "fork"
504
- // event.targetSessionFile - destination session for session replacement flows
505
- // Cleanup, save state, etc.
506
- });
507
- ```
508
-
509
- ### Agent Events
510
-
511
- #### before_agent_start
512
-
513
- Fired after user submits prompt, before agent loop. Can inject a message and/or modify the system prompt.
514
-
515
- ```typescript
516
- pi.on("before_agent_start", async (event, ctx) => {
517
- // event.prompt - user's prompt text
518
- // event.images - attached images (if any)
519
- // event.systemPrompt - current chained system prompt for this handler
520
- // (includes changes from earlier before_agent_start handlers)
521
- // event.systemPromptOptions - structured options used to build the system prompt
522
- // .customPrompt - any custom system prompt (from --system-prompt, SYSTEM.md, or custom templates)
523
- // .selectedTools - tools currently active in the prompt
524
- // .toolSnippets - one-line descriptions for each tool
525
- // .promptGuidelines - custom guideline bullets
526
- // .appendSystemPrompt - text from --append-system-prompt flags
527
- // .cwd - working directory
528
- // .contextFiles - AGENTS.md files and other loaded context files
529
- // .skills - loaded skills
530
-
531
- return {
532
- // Inject a persistent message (stored in session, sent to LLM)
533
- message: {
534
- customType: "my-extension",
535
- content: "Additional context for the LLM",
536
- display: true,
537
- },
538
- // Replace the system prompt for this turn (chained across extensions)
539
- systemPrompt: event.systemPrompt + "\n\nExtra instructions for this turn...",
540
- };
541
- });
542
- ```
543
-
544
- The `systemPromptOptions` field gives extensions access to the same structured data draht uses to build the system prompt. This lets you inspect what draht has loaded — custom prompts, guidelines, tool snippets, context files, skills — without re-discovering resources or re-parsing flags. Use it when your extension needs to make deep, informed changes to the system prompt while respecting user-provided configuration.
545
-
546
- 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.
547
-
548
- #### agent_start / agent_end / agent_settled
549
-
550
- `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. Use `agent_settled` for status integrations that need to know draht will not continue running automatically.
551
-
552
- ```typescript
553
- pi.on("agent_start", async (_event, ctx) => {});
554
-
555
- pi.on("agent_end", async (event, ctx) => {
556
- // event.messages - messages from this low-level run
557
- });
32
+ Start draht and run `/hello`. During development, load a file directly:
558
33
 
559
- pi.on("agent_settled", async (_event, ctx) => {
560
- // ctx.isIdle() is true here unless another extension started a new run.
561
- });
34
+ ```bash
35
+ draht --extension ./hello.ts
562
36
  ```
563
37
 
564
- #### turn_start / turn_end
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.
565
39
 
566
- Fired for each turn (one LLM response + tool calls).
40
+ <a id="extension-locations"></a>
41
+ <a id="available-imports"></a>
42
+ <a id="choose-where-it-loads"></a>
567
43
 
568
- ```typescript
569
- pi.on("turn_start", async (event, ctx) => {
570
- // event.turnIndex, event.timestamp
571
- });
44
+ ## Add it to draht
572
45
 
573
- pi.on("turn_end", async (event, ctx) => {
574
- // event.turnIndex, event.message, event.toolResults
575
- });
576
- ```
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.
577
47
 
578
- #### message_start / message_update / message_end
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.
579
49
 
580
- Fired for message lifecycle updates.
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.
581
51
 
582
- - `message_start` and `message_end` fire for user, assistant, and toolResult messages.
583
- - `message_update` fires for assistant streaming updates.
584
- - `message_end` handlers can return `{ message }` to replace the finalized message. The replacement must keep the same `role`.
52
+ <a id="understand-the-lifecycle"></a>
585
53
 
586
- ```typescript
587
- pi.on("message_start", async (event, ctx) => {
588
- // event.message
589
- });
54
+ ## Respect the runtime lifecycle
590
55
 
591
- pi.on("message_update", async (event, ctx) => {
592
- // event.message
593
- // event.assistantMessageEvent (token-by-token stream event)
594
- });
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.
595
57
 
596
- pi.on("message_end", async (event, ctx) => {
597
- if (event.message.role !== "assistant") return;
598
-
599
- return {
600
- message: {
601
- ...event.message,
602
- usage: {
603
- ...event.message.usage,
604
- cost: {
605
- ...event.message.usage.cost,
606
- total: 0.123,
607
- },
608
- },
609
- },
610
- };
611
- });
612
- ```
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.
613
61
 
614
- #### tool_execution_start / tool_execution_update / tool_execution_end
62
+ A run proceeds from input and `before_agent_start`, through model, message, and tool events, to `agent_end`.
63
+ Automatic retries, recovery, compaction, or queued work can continue afterward.
64
+ <a id="agent_start--agent_end--agent_before_settle--agent_settled"></a>
615
65
 
616
- Fired for tool execution lifecycle updates.
66
+ `agent_before_settle` is the final actionable boundary: it can append entries and request one continuation.
67
+ `agent_settled` is final and notification-only; use it when an integration needs to know draht will not continue automatically.
617
68
 
618
- In parallel tool mode:
619
- - `tool_execution_start` is emitted in assistant source order during the preflight phase
620
- - `tool_execution_update` events may interleave across tools
621
- - `tool_execution_end` is emitted in tool completion order after each tool is finalized
622
- - final `toolResult` message events are still emitted later in assistant source order
69
+ <a id="extensionapi-methods"></a>
623
70
 
624
- ```typescript
625
- pi.on("tool_execution_start", async (event, ctx) => {
626
- // event.toolCallId, event.toolName, event.args
627
- });
71
+ ## Choose an integration point
628
72
 
629
- pi.on("tool_execution_update", async (event, ctx) => {
630
- // event.toolCallId, event.toolName, event.args, event.partialResult
631
- });
73
+ | Capability | Main API |
74
+ |---|---|
75
+ | Observe or modify lifecycle behavior | `pi.on()` |
76
+ | Add a model-callable operation | `pi.registerTool()` |
77
+ | Add a `/` command | `pi.registerCommand()` |
78
+ | Add a shortcut or CLI flag | `pi.registerShortcut()` or `pi.registerFlag()` |
79
+ | Send user or custom messages | `pi.sendUserMessage()` or `pi.sendMessage()` |
80
+ | Persist non-context session data | `pi.appendEntry()` |
81
+ | Change active tools, model, or thinking level | Session control methods on `pi` |
82
+ | Read or restore working-tree checkpoints | `pi.checkpoints` |
83
+ | Add a model provider | `pi.registerProvider()` |
84
+ | Add an MCP server | `pi.registerMcpServer()` |
85
+ | Route each request to a model | [`pi.registerVirtualModel()`](virtual-models.md) |
86
+ | Add terminal rendering | Renderer registration and `ctx.ui` |
87
+ | Communicate with another extension | `pi.events` |
632
88
 
633
- pi.on("tool_execution_end", async (event, ctx) => {
634
- // event.toolCallId, event.toolName, event.result, event.isError
635
- });
636
- ```
89
+ `pi.setModel()` and `pi.setThinkingLevel()` change only the current session by default; pass `{ persist: true }` to also update the user's global default.
637
90
 
638
- #### context
91
+ 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.
639
92
 
640
- Fired before each LLM call. Modify messages non-destructively. See [Session Format](session-format.md) for message types.
93
+ ## Follow the extension contracts
641
94
 
642
- ```typescript
643
- pi.on("context", async (event, ctx) => {
644
- // event.messages - deep copy, safe to modify
645
- const filtered = event.messages.filter(m => !shouldPrune(m));
646
- return { messages: filtered };
647
- });
648
- ```
95
+ <a id="events"></a>
96
+ <a id="work-with-events"></a>
649
97
 
650
- #### before_provider_request
98
+ ### Events and concurrency
651
99
 
652
- 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.
100
+ 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.
101
+ Some events notify; others transform data, replace results, or cancel an operation.
102
+ Use each event’s declared result type rather than assuming every return value has an effect.
653
103
 
654
- 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.
104
+ Events cover resource discovery, sessions, agent and message lifecycle, providers, tools, and raw input.
655
105
 
656
- ```typescript
657
- pi.on("before_provider_request", (event, ctx) => {
658
- console.log(JSON.stringify(event.payload, null, 2));
106
+ `before_agent_start` exposes both the current prompt and its structured `systemPromptOptions`. 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.
659
107
 
660
- // Optional: replace payload
661
- // return { ...event.payload, temperature: 0 };
662
- });
663
- ```
108
+ `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.
664
109
 
665
- This is mainly useful for debugging provider serialization and cache behavior.
110
+ <a id="provider_stream_event"></a>
666
111
 
667
- #### after_provider_response
112
+ `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.
668
113
 
669
- Fired after an HTTP response is received and before its stream body is consumed. Handlers run in extension load order.
114
+ 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.
670
115
 
671
- ```typescript
672
- pi.on("after_provider_response", (event, ctx) => {
673
- // event.status - HTTP status code
674
- // event.headers - normalized response headers
675
- if (event.status === 429) {
676
- console.log("rate limited", event.headers["retry-after"]);
677
- }
678
- });
679
- ```
116
+ <a id="context_with_system"></a>
680
117
 
681
- Header availability depends on provider and transport. Providers that abstract HTTP responses may not expose headers.
118
+ `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.
682
119
 
683
- ### Model Events
120
+ `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.
684
121
 
685
- #### model_select
122
+ <a id="cache_warming_decision"></a>
686
123
 
687
- Fired when the model changes via `/model` command, model cycling (`Ctrl+P`), or session restore.
124
+ `cache_warming_decision` can override an idle prompt-cache refresh with `{ action: "warm" }` or `{ action: "stop" }`. The last handler that returns an action wins.
688
125
 
689
- ```typescript
690
- pi.on("model_select", async (event, ctx) => {
691
- // event.model - newly selected model
692
- // event.previousModel - previous model (undefined if first selection)
693
- // event.source - "set" | "cycle" | "restore"
126
+ Tool calls from one assistant message can run in parallel.
127
+ Do not assume a sibling call or result exists when another tool event runs.
128
+ Use `ctx.signal` for nested work owned by an active turn; commands and idle session events often have no operation signal.
694
129
 
695
- const prev = event.previousModel
696
- ? `${event.previousModel.provider}/${event.previousModel.id}`
697
- : "none";
698
- const next = `${event.model.provider}/${event.model.id}`;
130
+ 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.
699
131
 
700
- ctx.ui.notify(`Model changed (${event.source}): ${prev} -> ${next}`, "info");
701
- });
702
- ```
132
+ <a id="custom-tools"></a>
133
+ <a id="register-tools"></a>
703
134
 
704
- Use this to update UI elements (status bars, footers) or perform model-specific initialization when the active model changes.
135
+ ### Tools
705
136
 
706
- #### thinking_level_select
137
+ A custom tool defines a name, model-facing description, TypeBox parameter schema, and `execute()` function.
138
+ Its result requires model-facing `content` and a `details` field for rendering or state reconstruction.
139
+ 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.
707
140
 
708
- Fired when the thinking level changes. This is notification-only; handler return values are ignored.
141
+ Throw from `execute()` to produce a failed tool result.
142
+ Returning an object does not mark it as an error.
143
+ Return `terminate: true` only when the agent should skip its automatic follow-up after every completed tool in that batch agrees to terminate.
709
144
 
710
- ```typescript
711
- pi.on("thinking_level_select", async (event, ctx) => {
712
- // event.level - newly selected thinking level
713
- // event.previousLevel - previous thinking level
145
+ Use sequential execution when tools share mutable in-memory state.
146
+ File-mutating tools should wrap the complete read-modify-write operation with `withFileMutationQueue()`.
147
+ Truncate large model-facing results and tell the model where to read the complete output.
714
148
 
715
- ctx.ui.setStatus("thinking", `thinking: ${event.level}`);
716
- });
717
- ```
149
+ 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`.
718
150
 
719
- Use this to update extension UI when `pi.setThinkingLevel()`, model changes, or built-in thinking-level controls change the active thinking level.
151
+ 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.
720
152
 
721
- ### Tool Events
153
+ 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).
722
154
 
723
- #### tool_call
155
+ ### Tool exposure
724
156
 
725
- Fired after `tool_execution_start`, before the tool executes. **Can block.** Use `isToolCallEventType` to narrow and get typed inputs.
157
+ `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:
726
158
 
727
- 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.
159
+ - `direct` (default): declared to the model while active, and callable while active.
160
+ - `model-only`: declared to the model while active, never callable. Use it for tools that orchestrate other tools or ask the user.
161
+ - `codemode`: callable whenever registered, and listed by the `codemode` tool. Not declared to the model unless activated explicitly.
162
+ - `deferred`: like `codemode`, but codemode tools do not list it; `tool_search` can find and activate it.
163
+ - `hidden`: registered but unreachable. Re-register a tool with `exposure: "hidden"` to withdraw it, since tools cannot be unregistered.
728
164
 
729
- 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`.
165
+ `namespace: { name, 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)`.
730
166
 
731
- `event.input` is mutable. Mutate it in place to patch tool arguments before execution.
167
+ 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`, and `annotations`.
732
168
 
733
- Behavior guarantees:
734
- - Mutations to `event.input` affect the actual tool execution
735
- - Later `tool_call` handlers see mutations made by earlier handlers
736
- - No re-validation is performed after your mutation
737
- - Return values from `tool_call` only control blocking via `{ block: true, reason?: string }`
169
+ `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:
738
170
 
739
171
  ```typescript
740
- import { isToolCallEventType } from "@draht/coding-agent";
741
-
742
172
  pi.on("tool_call", async (event, ctx) => {
743
- // event.toolName - "bash", "read", "write", "edit", etc.
744
- // event.toolCallId
745
- // event.input - tool parameters (mutable)
746
-
747
- // Built-in tools: no type params needed
748
- if (isToolCallEventType("bash", event)) {
749
- // event.input is { command: string; timeout?: number }
750
- event.input.command = `source ~/.profile\n${event.input.command}`;
751
-
752
- if (event.input.command.includes("rm -rf")) {
753
- return { block: true, reason: "Dangerous command" };
754
- }
755
- }
756
-
757
- if (isToolCallEventType("read", event)) {
758
- // event.input is { path: string; offset?: number; limit?: number }
759
- console.log(`Reading: ${event.input.path}`);
760
- }
761
- });
762
- ```
763
-
764
- #### Typing custom tool input
765
-
766
- Custom tools should export their input type:
767
-
768
- ```typescript
769
- // my-extension.ts
770
- export type MyToolInput = Static<typeof myToolSchema>;
771
- ```
772
-
773
- Use `isToolCallEventType` with explicit type parameters:
774
-
775
- ```typescript
776
- import { isToolCallEventType } from "@draht/coding-agent";
777
- import type { MyToolInput } from "my-extension";
778
-
779
- pi.on("tool_call", (event) => {
780
- if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) {
781
- event.input.action; // typed
173
+ const hints = pi.getAllTools().find((tool) => tool.name === event.toolName)?.annotations;
174
+ const needsApproval =
175
+ hints?.destructiveHint === true ||
176
+ (!hints?.readOnlyHint && ((hints?.destructiveHint ?? true) || (hints?.openWorldHint ?? true)));
177
+ if (needsApproval && !(await ctx.ui.confirm("Allow tool call?", event.toolName))) {
178
+ return { block: true, reason: `${event.toolName} was not approved` };
782
179
  }
783
180
  });
784
181
  ```
785
182
 
786
- #### tool_result
787
-
788
- Fired after tool execution finishes and before `tool_execution_end` plus the final tool result message events are emitted. **Can modify result.**
789
-
790
- 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.
791
-
792
- `tool_result` handlers chain like middleware:
793
- - Handlers run in extension load order
794
- - Each handler sees the latest result after previous handler changes
795
- - Handlers can return partial patches (`content`, `details`, `isError`, or `usage`); omitted fields keep their current values
796
-
797
- 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.
798
-
799
- ```typescript
800
- import { isBashToolResult } from "@draht/coding-agent";
801
-
802
- pi.on("tool_result", async (event, ctx) => {
803
- // event.toolName, event.toolCallId, event.input
804
- // event.content, event.details, event.isError, event.usage
805
-
806
- if (isBashToolResult(event)) {
807
- // event.details is typed as BashToolDetails
808
- }
809
-
810
- const response = await fetch("https://example.com/summarize", {
811
- method: "POST",
812
- body: JSON.stringify({ content: event.content }),
813
- signal: ctx.signal,
814
- });
815
-
816
- // Modify result:
817
- return { content: [...], details: {...}, isError: false, usage: nestedModelUsage };
818
- });
819
- ```
183
+ 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 and namespace. 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. `codemode` uses only this hook, `exposure`, and `ctx.executeTool()`, so another tool can implement the same behavior under a different name.
820
184
 
821
- ### User Bash Events
185
+ ### Activate tools dynamically
822
186
 
823
- #### user_bash
187
+ 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.
824
188
 
825
- Fired when user executes `!` or `!!` commands. **Can intercept.**
189
+ 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.
826
190
 
827
- ```typescript
828
- import { createLocalBashOperations } from "@draht/coding-agent";
829
-
830
- pi.on("user_bash", (event, ctx) => {
831
- // event.command - the bash command
832
- // event.excludeFromContext - true if !! prefix
833
- // event.cwd - working directory
834
-
835
- // Option 1: Provide custom operations (e.g., SSH)
836
- return { operations: remoteBashOps };
837
-
838
- // Option 2: Wrap draht's built-in local bash backend
839
- const local = createLocalBashOperations();
840
- return {
841
- operations: {
842
- exec(command, cwd, options) {
843
- return local.exec(`source ~/.profile\n${command}`, cwd, options);
844
- }
845
- }
846
- };
847
-
848
- // Option 3: Full replacement - return result directly
849
- return { result: { output: "...", exitCode: 0, cancelled: false, truncated: false } };
850
- });
851
- ```
191
+ ### Checkpoints and rewind
852
192
 
853
- ### Input Events
193
+ 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.
854
194
 
855
- #### input
195
+ `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).
856
196
 
857
- 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.
197
+ ### MCP servers
858
198
 
859
- **Processing order:**
860
- 1. Extension commands (`/cmd`) checked first - if found, handler runs and input event is skipped
861
- 2. `input` event fires - can intercept, transform, or handle
862
- 3. If not handled: skill commands (`/skill:name`) expanded to skill content
863
- 4. If not handled: prompt templates (`/template`) expanded to template content
864
- 5. Agent processing begins (`before_agent_start`, etc.)
199
+ `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`.
865
200
 
866
201
  ```typescript
867
- pi.on("input", async (event, ctx) => {
868
- // event.text - raw input (before skill/template expansion)
869
- // event.images - attached images, if any
870
- // event.source - "interactive" (typed), "rpc" (API), or "extension" (via sendUserMessage)
871
- // event.streamingBehavior - "steer" | "followUp" | undefined
872
- // undefined when idle, "steer" for mid-stream interrupts,
873
- // "followUp" for messages queued until the agent finishes
874
-
875
- // Transform: rewrite input before expansion
876
- if (event.text.startsWith("?quick "))
877
- return { action: "transform", text: `Respond briefly: ${event.text.slice(7)}` };
878
-
879
- // Handle: respond without LLM (extension shows its own feedback)
880
- if (event.text === "ping") {
881
- ctx.ui.notify("pong", "info");
882
- return { action: "handled" };
883
- }
884
-
885
- // Route by source: skip processing for extension-injected messages
886
- if (event.source === "extension") return { action: "continue" };
887
-
888
- // Intercept skill commands before expansion
889
- if (event.text.startsWith("/skill:")) {
890
- // Could transform, block, or let pass through
891
- }
892
-
893
- return { action: "continue" }; // Default: pass through to expansion
894
- });
202
+ pi.registerMcpServer("jira", { url: "https://mcp.example.com/jira", exposure: "codemode" });
203
+ pi.unregisterMcpServer("jira");
895
204
  ```
896
205
 
897
- **Results:**
898
- - `continue` - pass through unchanged (default if handler returns nothing)
899
- - `transform` - modify text/images, then continue to expansion
900
- - `handled` - skip agent entirely (first handler to return this wins)
901
-
902
- 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.
903
-
904
- ## ExtensionContext
905
-
906
- All handlers receive `ctx: ExtensionContext`.
907
-
908
- ### ctx.ui
909
-
910
- UI methods for user interaction. See [Custom UI](#custom-ui) for full details.
911
-
912
- ### ctx.mode
913
-
914
- 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.
915
-
916
- ### ctx.hasUI
917
-
918
- `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.md](rpc.md#extension-ui-protocol)).
919
-
920
- ### ctx.cwd
921
-
922
- Current working directory.
923
-
924
- ### ctx.isProjectTrusted()
925
-
926
- 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.
927
-
928
- Use this before reading project-local extension configuration that should only be honored for trusted projects.
206
+ 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.
929
207
 
930
- ### ctx.sessionManager
208
+ 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.
931
209
 
932
- Read-only access to session state. See [Session Format](session-format.md) for the full SessionManager API and entry types.
210
+ <a id="extensioncontext"></a>
211
+ <a id="extensioncommandcontext"></a>
212
+ <a id="use-extension-context"></a>
933
213
 
934
- 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.
214
+ ### Context and session changes
935
215
 
936
- ```typescript
937
- ctx.sessionManager.getEntries() // All entries
938
- ctx.sessionManager.getBranch() // Current branch
939
- ctx.sessionManager.buildContextEntries() // Active branch entries with compaction applied
940
- ctx.sessionManager.getLeafId() // Current leaf entry ID
941
- ```
942
-
943
- ### ctx.modelRegistry / ctx.model / ctx.thinkingLevel / ctx.scopedModels
944
-
945
- 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.
216
+ `ExtensionContext` provides the working directory, mode, UI, session manager, model runtime, abort signal, context usage, and controls for compaction and shutdown.
217
+ Use `ctx.modelRegistry.streamSimple()` for provider-neutral nested model calls.
946
218
 
947
- `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()`.
219
+ Command handlers receive `ExtensionCommandContext`, which adds operations for waiting until idle, reloading, tree navigation, and session replacement.
220
+ These operations are command-only because calling them from lifecycle handlers can deadlock the runtime.
948
221
 
949
- ### ctx.signal
222
+ Session replacement invalidates the old context. Capture only plain data before switching, then use the fresh context supplied to `withSession` for session-bound work.
950
223
 
951
- The current agent abort signal, or `undefined` when no agent turn is active.
224
+ <a id="state-management"></a>
225
+ <a id="persist-state"></a>
952
226
 
953
- Use this for abort-aware nested work started by extension handlers, for example:
954
- - `fetch(..., { signal: ctx.signal })`
955
- - model calls that accept `signal`
956
- - file or process helpers that accept `AbortSignal`
227
+ ### State
957
228
 
958
- `ctx.signal` is typically defined during active turn events such as `tool_call`, `tool_result`, `message_update`, and `turn_end`.
959
- It is usually `undefined` in idle or non-turn contexts such as session events, extension commands, and shortcuts fired while draht is idle.
229
+ Choose storage based on how state participates in the conversation:
960
230
 
961
- ```typescript
962
- pi.on("tool_result", async (event, ctx) => {
963
- const response = await fetch("https://example.com/api", {
964
- method: "POST",
965
- body: JSON.stringify(event),
966
- signal: ctx.signal,
967
- });
968
-
969
- const data = await response.json();
970
- return { details: data };
971
- });
972
- ```
231
+ | State | Storage |
232
+ |---|---|
233
+ | Tool state that follows the active branch | Tool-result `details` |
234
+ | Durable data excluded from model context | `pi.appendEntry()` |
235
+ | Custom content stored and sent to the model | `pi.sendMessage()` |
236
+ | Data outside one session | External storage |
973
237
 
974
- ### ctx.isIdle() / ctx.abort() / ctx.hasPendingMessages()
238
+ Reconstruct branch-sensitive state from `ctx.sessionManager.getBranch()` during `session_start`.
239
+ Do not rebuild it from every file entry because abandoned branches represent alternative histories.
240
+ Register an entry or message renderer when custom stored content should appear in the transcript.
975
241
 
976
- Control flow helpers. `ctx.isIdle()` is false while draht is processing an agent run, automatic retry, auto-compaction retry, or queued continuation.
242
+ <a id="custom-ui"></a>
243
+ <a id="mode-behavior"></a>
244
+ <a id="interact-with-the-user"></a>
245
+ <a id="account-for-each-mode"></a>
977
246
 
978
- ### ctx.shutdown()
247
+ ### UI and modes
979
248
 
980
- Request a graceful shutdown of draht.
249
+ `ctx.ui` provides dialogs, notifications, status text, widgets, titles, editor access, and custom components.
250
+ Use `ctx.ui.custom()` only when the interaction needs its own rendering and input.
251
+ See [Terminal UI](tui.md) for component, focus, overlay, theme, and performance guidance.
981
252
 
982
- - **Interactive mode:** Deferred until the agent becomes idle (after processing all queued steering and follow-up messages).
983
- - **RPC mode:** Deferred until the next idle state (after completing the current command response, when waiting for the next command).
984
- - **Print mode:** No-op. The process exits automatically when all prompts are processed.
253
+ Extensions load in interactive, RPC, JSON, and print modes.
254
+ Interactive mode provides the complete terminal UI.
255
+ 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.
256
+ Guard terminal-only behavior with `ctx.mode === "tui"` and use `ctx.hasUI` for interactions supported by interactive and RPC clients.
985
257
 
986
- Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands, shortcuts).
258
+ Keep tool and event behavior independent from rendering so non-interactive modes remain functional.
987
259
 
988
- ```typescript
989
- pi.on("tool_call", (event, ctx) => {
990
- if (isFatal(event.input)) {
991
- ctx.shutdown();
992
- }
993
- });
994
- ```
260
+ <a id="error-handling"></a>
261
+ <a id="handle-errors-and-shutdown"></a>
995
262
 
996
- ### ctx.getContextUsage()
263
+ ### Errors and cleanup
997
264
 
998
- Returns current context usage for the active model. Uses last assistant usage when available, then estimates tokens for trailing messages.
265
+ 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.
999
266
 
1000
- ```typescript
1001
- const usage = ctx.getContextUsage();
1002
- if (usage && usage.tokens > 100_000) {
1003
- // ...
1004
- }
1005
- ```
267
+ Release resources in `session_shutdown` even when normal operation attempted cleanup.
268
+ Keep cleanup idempotent because cancellation, reload, session replacement, and process exit can converge on the same path.
269
+ Use `ctx.shutdown()` to request an orderly process shutdown.
1006
270
 
1007
- ### ctx.compact()
271
+ <a id="examples-reference"></a>
272
+ <a id="use-examples-as-the-implementation-reference"></a>
1008
273
 
1009
- Trigger compaction without awaiting completion. Use `onComplete` and `onError` for follow-up actions.
274
+ ## Examples and reference
1010
275
 
1011
- ```typescript
1012
- ctx.compact({
1013
- customInstructions: "Focus on recent changes",
1014
- onComplete: (result) => {
1015
- ctx.ui.notify("Compaction completed", "info");
1016
- },
1017
- onError: (error) => {
1018
- ctx.ui.notify(`Compaction failed: ${error.message}`, "error");
1019
- },
1020
- });
1021
- ```
1022
-
1023
- ### ctx.getSystemPrompt()
1024
-
1025
- Returns draht's current system prompt string.
1026
-
1027
- - During `before_agent_start`, this reflects chained system-prompt changes made so far for the current turn.
1028
- - It does not include later `context` message mutations.
1029
- - It does not include `before_provider_request` payload rewrites.
1030
- - If later-loaded extensions run after yours, they can still change what is ultimately sent.
1031
-
1032
- ```typescript
1033
- pi.on("before_agent_start", (event, ctx) => {
1034
- const prompt = ctx.getSystemPrompt();
1035
- console.log(`System prompt length: ${prompt.length}`);
1036
- });
1037
- ```
1038
-
1039
- ## ExtensionCommandContext
1040
-
1041
- 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.
1042
-
1043
- ### ctx.getSystemPromptOptions()
1044
-
1045
- Returns the base inputs draht currently uses to build the system prompt.
1046
-
1047
- ```typescript
1048
- const options = ctx.getSystemPromptOptions();
1049
- const contextPaths = options.contextFiles?.map((file) => file.path) ?? [];
1050
- ```
1051
-
1052
- This has the same shape and mutability as `before_agent_start` `event.systemPromptOptions`: custom prompt, active tools, tool snippets, prompt guidelines, appended system 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.
1053
-
1054
- 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.
1055
-
1056
- ### ctx.waitForIdle()
1057
-
1058
- Wait for the agent to fully settle, including automatic retries, auto-compaction retries, and queued continuations:
1059
-
1060
- ```typescript
1061
- pi.registerCommand("my-cmd", {
1062
- handler: async (args, ctx) => {
1063
- await ctx.waitForIdle();
1064
- // Agent is now idle, safe to modify session
1065
- },
1066
- });
1067
- ```
1068
-
1069
- ### ctx.newSession(options?)
1070
-
1071
- Create a new session:
1072
-
1073
- ```typescript
1074
- const parentSession = ctx.sessionManager.getSessionFile();
1075
- const kickoff = "Continue in the replacement session";
1076
-
1077
- const result = await ctx.newSession({
1078
- parentSession,
1079
- setup: async (sm) => {
1080
- sm.appendMessage({
1081
- role: "user",
1082
- content: [{ type: "text", text: "Context from previous session..." }],
1083
- timestamp: Date.now(),
1084
- });
1085
- },
1086
- withSession: async (ctx) => {
1087
- // Use only the replacement-session ctx here.
1088
- await ctx.sendUserMessage(kickoff);
1089
- },
1090
- });
1091
-
1092
- if (result.cancelled) {
1093
- // An extension cancelled the new session
1094
- }
1095
- ```
1096
-
1097
- Options:
1098
- - `parentSession`: parent session file to record in the new session header
1099
- - `setup`: mutate the new session's `SessionManager` before `withSession` runs
1100
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `pi` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1101
-
1102
- ### ctx.fork(entryId, options?)
1103
-
1104
- Fork from a specific entry, creating a new session file:
1105
-
1106
- ```typescript
1107
- const result = await ctx.fork("entry-id-123", {
1108
- withSession: async (ctx) => {
1109
- // Use only the replacement-session ctx here.
1110
- ctx.ui.notify("Now in the forked session", "info");
1111
- },
1112
- });
1113
- if (result.cancelled) {
1114
- // An extension cancelled the fork
1115
- }
1116
-
1117
- const cloneResult = await ctx.fork("entry-id-456", { position: "at" });
1118
- if (cloneResult.cancelled) {
1119
- // An extension cancelled the clone
1120
- }
1121
- ```
1122
-
1123
- Options:
1124
- - `position`: `"before"` (default) forks before the selected user message, restoring that prompt into the editor
1125
- - `position`: `"at"` duplicates the active path through the selected entry without restoring editor text
1126
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `pi` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1127
-
1128
- ### ctx.navigateTree(targetId, options?)
1129
-
1130
- Navigate to a different point in the session tree:
1131
-
1132
- ```typescript
1133
- const result = await ctx.navigateTree("entry-id-456", {
1134
- summarize: true,
1135
- customInstructions: "Focus on error handling changes",
1136
- replaceInstructions: false, // true = replace default prompt entirely
1137
- label: "review-checkpoint",
1138
- });
1139
- ```
1140
-
1141
- Options:
1142
- - `summarize`: Whether to generate a summary of the abandoned branch
1143
- - `customInstructions`: Custom instructions for the summarizer
1144
- - `replaceInstructions`: If true, `customInstructions` replaces the default prompt instead of being appended
1145
- - `label`: Label to attach to the branch summary entry (or target entry if not summarizing)
1146
-
1147
- ### ctx.switchSession(sessionPath, options?)
1148
-
1149
- Switch to a different session file:
1150
-
1151
- ```typescript
1152
- const result = await ctx.switchSession("/path/to/session.jsonl", {
1153
- withSession: async (ctx) => {
1154
- await ctx.sendUserMessage("Resume work in the replacement session");
1155
- },
1156
- });
1157
- if (result.cancelled) {
1158
- // An extension cancelled the switch via session_before_switch
1159
- }
1160
- ```
1161
-
1162
- Options:
1163
- - `withSession`: run post-switch work against a fresh replacement-session context. Do not use captured old `pi` / command `ctx`; see [Session replacement lifecycle and footguns](#session-replacement-lifecycle-and-footguns).
1164
-
1165
- To discover available sessions, use the static `SessionManager.list()` or `SessionManager.listAll()` methods:
1166
-
1167
- ```typescript
1168
- import { SessionManager } from "@draht/coding-agent";
1169
-
1170
- pi.registerCommand("switch", {
1171
- description: "Switch to another session",
1172
- handler: async (args, ctx) => {
1173
- const sessions = await SessionManager.list(ctx.cwd);
1174
- if (sessions.length === 0) return;
1175
- const choice = await ctx.ui.select(
1176
- "Pick session:",
1177
- sessions.map(s => s.file),
1178
- );
1179
- if (choice) {
1180
- await ctx.switchSession(choice, {
1181
- withSession: async (ctx) => {
1182
- ctx.ui.notify("Switched session", "info");
1183
- },
1184
- });
1185
- }
1186
- },
1187
- });
1188
- ```
1189
-
1190
- ### Session replacement lifecycle and footguns
1191
-
1192
- `withSession` receives a fresh `ReplacedSessionContext`, which extends `ExtensionCommandContext` with async `sendMessage()` and `sendUserMessage()` helpers bound to the replacement session.
1193
-
1194
- Lifecycle and footguns:
1195
- - `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`.
1196
- - 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.
1197
- - Captured old `pi` / 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.
1198
- - 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.
1199
- - 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.
1200
-
1201
- Safe pattern:
1202
-
1203
- ```typescript
1204
- pi.registerCommand("handoff", {
1205
- handler: async (_args, ctx) => {
1206
- const kickoff = "Continue from the replacement session";
1207
- await ctx.newSession({
1208
- withSession: async (ctx) => {
1209
- await ctx.sendUserMessage(kickoff);
1210
- },
1211
- });
1212
- },
1213
- });
1214
- ```
1215
-
1216
- Unsafe pattern:
1217
-
1218
- ```typescript
1219
- pi.registerCommand("handoff", {
1220
- handler: async (_args, ctx) => {
1221
- const oldSessionManager = ctx.sessionManager;
1222
- await ctx.newSession({
1223
- withSession: async (_ctx) => {
1224
- // stale old objects: do not do this
1225
- oldSessionManager.getSessionFile();
1226
- pi.sendUserMessage("wrong");
1227
- },
1228
- });
1229
- },
1230
- });
1231
- ```
1232
-
1233
- ### ctx.reload()
1234
-
1235
- Run the same reload flow as `/reload`.
1236
-
1237
- ```typescript
1238
- pi.registerCommand("reload-runtime", {
1239
- description: "Reload extensions, skills, prompts, themes, and context files",
1240
- handler: async (_args, ctx) => {
1241
- await ctx.reload();
1242
- return;
1243
- },
1244
- });
1245
- ```
1246
-
1247
- Important behavior:
1248
- - `await ctx.reload()` emits `session_shutdown` for the current extension runtime
1249
- - It then reloads resources and emits `session_start` with `reason: "reload"` and `resources_discover` with reason `"reload"`
1250
- - The currently running command handler still continues in the old call frame
1251
- - Code after `await ctx.reload()` still runs from the pre-reload version
1252
- - Code after `await ctx.reload()` must not assume old in-memory extension state is still valid
1253
- - After the handler returns, future commands/events/tool calls use the new extension version
1254
-
1255
- For predictable behavior, treat reload as terminal for that handler (`await ctx.reload(); return;`).
1256
-
1257
- Tools run with `ExtensionContext`, so they cannot call `ctx.reload()` directly. Use a command as the reload entrypoint, then expose a tool that queues that command as a follow-up user message.
1258
-
1259
- Example tool the LLM can call to trigger reload:
1260
-
1261
- ```typescript
1262
- import type { ExtensionAPI } from "@draht/coding-agent";
1263
- import { Type } from "typebox";
1264
-
1265
- export default function (pi: ExtensionAPI) {
1266
- pi.registerCommand("reload-runtime", {
1267
- description: "Reload extensions, skills, prompts, themes, and context files",
1268
- handler: async (_args, ctx) => {
1269
- await ctx.reload();
1270
- return;
1271
- },
1272
- });
1273
-
1274
- pi.registerTool({
1275
- name: "reload_runtime",
1276
- label: "Reload Runtime",
1277
- description: "Reload extensions, skills, prompts, themes, and context files",
1278
- parameters: Type.Object({}),
1279
- async execute() {
1280
- pi.sendUserMessage("/reload-runtime", { deliverAs: "followUp" });
1281
- return {
1282
- content: [{ type: "text", text: "Queued /reload-runtime as a follow-up command." }],
1283
- };
1284
- },
1285
- });
1286
- }
1287
- ```
1288
-
1289
- ## ExtensionAPI Methods
1290
-
1291
- ### pi.on(event, handler)
1292
-
1293
- Subscribe to events. See [Events](#events) for event types and return values.
1294
-
1295
- ### pi.registerTool(definition)
1296
-
1297
- Register a custom tool callable by the LLM. See [Custom Tools](#custom-tools) for full details.
1298
-
1299
- `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()` and are callable by the LLM without `/reload`.
1300
-
1301
- Use `pi.setActiveTools()` to enable or disable tools (including dynamically added tools) at runtime.
1302
-
1303
- Use `promptSnippet` to opt a custom tool into a one-line entry in `Available tools`, and `promptGuidelines` to append tool-specific bullets to the default `Guidelines` section when the tool is active.
1304
-
1305
- **Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` 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.
1306
-
1307
- See [dynamic-tools.ts](../examples/extensions/dynamic-tools.ts) for a full example.
1308
-
1309
- ```typescript
1310
- import { Type } from "typebox";
1311
- import { StringEnum } from "@draht/ai";
1312
-
1313
- pi.registerTool({
1314
- name: "my_tool",
1315
- label: "My Tool",
1316
- description: "What this tool does",
1317
- promptSnippet: "Summarize or transform text according to action",
1318
- promptGuidelines: ["Use my_tool when the user asks to summarize previously generated text."],
1319
- parameters: Type.Object({
1320
- action: StringEnum(["list", "add"] as const),
1321
- text: Type.Optional(Type.String()),
1322
- }),
1323
- prepareArguments(args) {
1324
- // Optional compatibility shim. Runs before schema validation.
1325
- // Return the current schema shape, for example to fold legacy fields
1326
- // into the modern parameter object.
1327
- return args;
1328
- },
1329
-
1330
- async execute(toolCallId, params, signal, onUpdate, ctx) {
1331
- // Stream progress
1332
- onUpdate?.({ content: [{ type: "text", text: "Working..." }] });
1333
-
1334
- return {
1335
- content: [{ type: "text", text: "Done" }],
1336
- details: { result: "..." },
1337
- };
1338
- },
1339
-
1340
- // Optional: Custom rendering
1341
- renderCall(args, theme, context) { ... },
1342
- renderResult(result, options, theme, context) { ... },
1343
- });
1344
- ```
1345
-
1346
- ### pi.sendMessage(message, options?)
1347
-
1348
- 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).
1349
-
1350
- ```typescript
1351
- pi.sendMessage({
1352
- customType: "my-extension",
1353
- content: "Message text",
1354
- display: true,
1355
- details: { ... },
1356
- }, {
1357
- triggerTurn: true,
1358
- deliverAs: "steer",
1359
- });
1360
- ```
1361
-
1362
- **Options:**
1363
- - `deliverAs` - Delivery mode:
1364
- - `"steer"` (default) - Queues the message while streaming. Delivered after the current assistant turn finishes executing its tool calls, before the next LLM call.
1365
- - `"followUp"` - Waits for agent to finish. Delivered only when agent has no more tool calls.
1366
- - `"nextTurn"` - Queued for next user prompt. Does not interrupt or trigger anything.
1367
- - `triggerTurn: true` - If agent is idle, trigger an LLM response immediately. Only applies to `"steer"` and `"followUp"` modes (ignored for `"nextTurn"`).
1368
-
1369
- ### pi.sendUserMessage(content, options?)
1370
-
1371
- 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. Always triggers a turn.
1372
-
1373
- ```typescript
1374
- // Simple text message
1375
- pi.sendUserMessage("What is 2+2?");
1376
-
1377
- // With content array (text + images)
1378
- pi.sendUserMessage([
1379
- { type: "text", text: "Describe this image:" },
1380
- { type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } },
1381
- ]);
1382
-
1383
- // During streaming - must specify delivery mode
1384
- pi.sendUserMessage("Focus on error handling", { deliverAs: "steer" });
1385
- pi.sendUserMessage("And then summarize", { deliverAs: "followUp" });
1386
- ```
1387
-
1388
- **Options:**
1389
- - `deliverAs` - Required when agent is streaming:
1390
- - `"steer"` - Queues the message for delivery after the current assistant turn finishes executing its tool calls
1391
- - `"followUp"` - Waits for agent to finish all tools
1392
-
1393
- When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, throws an error.
1394
-
1395
- See [send-user-message.ts](../examples/extensions/send-user-message.ts) for a complete example.
1396
-
1397
- ### pi.appendEntry(customType, data?)
1398
-
1399
- 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()`.
1400
-
1401
- ```typescript
1402
- pi.appendEntry("my-state", { count: 42 });
1403
- pi.appendEntry("status-card", { title: "Indexed files", count: 17 });
1404
-
1405
- // Restore on reload
1406
- pi.on("session_start", async (_event, ctx) => {
1407
- for (const entry of ctx.sessionManager.getEntries()) {
1408
- if (entry.type === "custom" && entry.customType === "my-state") {
1409
- // Reconstruct from entry.data
1410
- }
1411
- }
1412
- });
1413
- ```
1414
-
1415
- ### pi.setSessionName(name)
1416
-
1417
- Set the session display name (shown in session selector instead of first message).
1418
-
1419
- ```typescript
1420
- pi.setSessionName("Refactor auth module");
1421
- ```
1422
-
1423
- ### pi.getSessionName()
1424
-
1425
- Get the current session name, if set.
1426
-
1427
- ```typescript
1428
- const name = pi.getSessionName();
1429
- if (name) {
1430
- console.log(`Session: ${name}`);
1431
- }
1432
- ```
1433
-
1434
- ### pi.setLabel(entryId, label)
1435
-
1436
- Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation (shown in `/tree` selector).
1437
-
1438
- ```typescript
1439
- // Set a label
1440
- pi.setLabel(entryId, "checkpoint-before-refactor");
1441
-
1442
- // Clear a label
1443
- pi.setLabel(entryId, undefined);
1444
-
1445
- // Read labels via sessionManager
1446
- const label = ctx.sessionManager.getLabel(entryId);
1447
- ```
1448
-
1449
- Labels persist in the session and survive restarts. Use them to mark important points (turns, checkpoints) in the conversation tree.
1450
-
1451
- ### pi.registerCommand(name, options)
1452
-
1453
- Register a command.
1454
-
1455
- 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`.
1456
-
1457
- ```typescript
1458
- pi.registerCommand("stats", {
1459
- description: "Show session statistics",
1460
- handler: async (args, ctx) => {
1461
- const count = ctx.sessionManager.getEntries().length;
1462
- ctx.ui.notify(`${count} entries`, "info");
1463
- }
1464
- });
1465
- ```
1466
-
1467
- Optional: add argument auto-completion for `/command ...`:
1468
-
1469
- ```typescript
1470
- import type { AutocompleteItem } from "@draht/tui";
1471
-
1472
- pi.registerCommand("deploy", {
1473
- description: "Deploy to an environment",
1474
- getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => {
1475
- const envs = ["dev", "staging", "prod"];
1476
- const items = envs.map((e) => ({ value: e, label: e }));
1477
- const filtered = items.filter((i) => i.value.startsWith(prefix));
1478
- return filtered.length > 0 ? filtered : null;
1479
- },
1480
- handler: async (args, ctx) => {
1481
- ctx.ui.notify(`Deploying: ${args}`, "info");
1482
- },
1483
- });
1484
- ```
1485
-
1486
- ### pi.getCommands()
1487
-
1488
- Get the slash commands available for invocation via `prompt` in the current session. Includes extension commands, prompt templates, and skill commands.
1489
- The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills.
1490
-
1491
- ```typescript
1492
- const commands = pi.getCommands();
1493
- const bySource = commands.filter((command) => command.source === "extension");
1494
- const userScoped = commands.filter((command) => command.sourceInfo.scope === "user");
1495
- ```
1496
-
1497
- Each entry has this shape:
1498
-
1499
- ```typescript
1500
- {
1501
- name: string; // Invokable command name without the leading slash. May be suffixed like "review:1"
1502
- description?: string;
1503
- source: "extension" | "prompt" | "skill";
1504
- sourceInfo: {
1505
- path: string;
1506
- source: string;
1507
- scope: "user" | "project" | "temporary";
1508
- origin: "package" | "top-level";
1509
- baseDir?: string;
1510
- };
1511
- }
1512
- ```
1513
-
1514
- Use `sourceInfo` as the canonical provenance field. Do not infer ownership from command names or from ad hoc path parsing.
1515
-
1516
- Built-in interactive commands (like `/model` and `/settings`) are not included here. They are handled only in interactive
1517
- mode and would not execute if sent via `prompt`.
1518
-
1519
- ### pi.registerMessageRenderer(customType, renderer)
1520
-
1521
- 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).
1522
-
1523
- ### pi.registerEntryRenderer(customType, renderer)
1524
-
1525
- 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.
1526
-
1527
- ```typescript
1528
- import { Box, Text } from "@draht/tui";
1529
-
1530
- pi.registerEntryRenderer("status-card", (entry, { expanded }, theme) => {
1531
- const data = entry.data as { title: string; count: number };
1532
- const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text));
1533
- box.addChild(new Text(`${theme.bold(data.title)}: ${data.count}`));
1534
- if (expanded) {
1535
- box.addChild(new Text(theme.fg("dim", JSON.stringify(data, null, 2))));
1536
- }
1537
- return box;
1538
- });
1539
-
1540
- pi.appendEntry("status-card", { title: "Indexed files", count: 17 });
1541
- ```
1542
-
1543
- ### pi.registerShortcut(shortcut, options)
1544
-
1545
- Register a keyboard shortcut. See [keybindings.md](keybindings.md) for the shortcut format and built-in keybindings.
1546
-
1547
- ```typescript
1548
- pi.registerShortcut("ctrl+shift+p", {
1549
- description: "Toggle plan mode",
1550
- handler: async (ctx) => {
1551
- ctx.ui.notify("Toggled!");
1552
- },
1553
- });
1554
- ```
1555
-
1556
- ### pi.registerFlag(name, options)
1557
-
1558
- Register a CLI flag.
1559
-
1560
- ```typescript
1561
- pi.registerFlag("plan", {
1562
- description: "Start in plan mode",
1563
- type: "boolean",
1564
- default: false,
1565
- });
1566
-
1567
- // Check value
1568
- if (pi.getFlag("plan")) {
1569
- // Plan mode enabled
1570
- }
1571
- ```
1572
-
1573
- ### pi.exec(command, args, options?)
1574
-
1575
- Execute a shell command.
1576
-
1577
- ```typescript
1578
- const result = await pi.exec("git", ["status"], { signal, timeout: 5000 });
1579
- // result.stdout, result.stderr, result.code, result.killed
1580
- ```
1581
-
1582
- ### pi.getActiveTools() / pi.getAllTools() / pi.setActiveTools(names)
1583
-
1584
- Manage active tools. This works for both built-in tools and dynamically registered tools.
1585
-
1586
- ```typescript
1587
- const active = pi.getActiveTools();
1588
- const all = pi.getAllTools();
1589
- // [{
1590
- // name: "read",
1591
- // description: "Read file contents...",
1592
- // parameters: ...,
1593
- // promptGuidelines: ["Use read to examine files instead of cat or sed."],
1594
- // sourceInfo: { path: "<builtin:read>", source: "builtin", scope: "temporary", origin: "top-level" }
1595
- // }, ...]
1596
- const names = all.map(t => t.name);
1597
- const builtinTools = all.filter((t) => t.sourceInfo.source === "builtin");
1598
- const extensionTools = all.filter((t) => t.sourceInfo.source !== "builtin" && t.sourceInfo.source !== "sdk");
1599
- pi.setActiveTools(["read", "bash"]); // Switch to read-only
1600
- ```
1601
-
1602
- `pi.getAllTools()` returns `name`, `description`, `parameters`, `promptGuidelines`, and `sourceInfo`.
1603
-
1604
- Typical `sourceInfo.source` values:
1605
- - `builtin` for built-in tools
1606
- - `sdk` for tools passed via `createAgentSession({ customTools })`
1607
- - extension source metadata for tools registered by extensions
1608
-
1609
- ### pi.setModel(model, options?)
1610
-
1611
- Set the current model. Returns `false` if no API key is available for the model. See [models.md](models.md) for configuring custom models. Pass `{ persistDefault: false }` for session-scoped orchestration that must not replace the user's global default model.
1612
-
1613
- ```typescript
1614
- const model = ctx.modelRegistry.find("anthropic", "claude-sonnet-4-5");
1615
- if (model) {
1616
- const success = await pi.setModel(model);
1617
- if (!success) {
1618
- ctx.ui.notify("No API key for this model", "error");
1619
- }
1620
- }
1621
- ```
1622
-
1623
- ### pi.getThinkingLevel() / pi.setThinkingLevel(level, options?)
1624
-
1625
- Get or set the thinking level. Level is clamped to model capabilities (non-reasoning models always use "off"). Changes emit `thinking_level_select`. Pass `{ persistDefault: false }` when the change should remain session-scoped.
1626
-
1627
- ```typescript
1628
- const current = pi.getThinkingLevel(); // "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"
1629
- pi.setThinkingLevel("high");
1630
- ```
1631
-
1632
- ### pi.events
1633
-
1634
- Shared event bus for communication between extensions:
1635
-
1636
- ```typescript
1637
- pi.events.on("my:event", (data) => { ... });
1638
- pi.events.emit("my:event", { ... });
1639
- ```
1640
-
1641
- ### pi.registerProvider(name, config)
1642
-
1643
- Register or override a model provider dynamically. Useful for proxies, custom endpoints, or team-wide model configurations.
1644
-
1645
- 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`.
1646
-
1647
- Dynamic providers can implement `refreshModels`. draht calls it during model refresh, publishes the returned list synchronously through the provider, and passes the canonical credential/store/network/signal context. The extension decides whether to persist the catalog through `context.store`; live servers such as llama.cpp can ignore it.
1648
-
1649
- 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.
1650
-
1651
- ```typescript
1652
- import { createProvider, openAICompletionsApi } from "@draht/ai";
1653
-
1654
- const provider = createProvider({
1655
- id: "local-server",
1656
- name: "Local Server",
1657
- baseUrl: "http://localhost:8080/v1",
1658
- auth: {
1659
- apiKey: {
1660
- name: "Local server setup",
1661
- async login(interaction) {
1662
- return {
1663
- type: "api_key",
1664
- key: await interaction.prompt({ type: "secret", message: "API key" }),
1665
- };
1666
- },
1667
- async resolve({ credential }) {
1668
- return credential?.key
1669
- ? { auth: { apiKey: credential.key }, source: "stored API key" }
1670
- : undefined;
1671
- },
1672
- },
1673
- },
1674
- models: [],
1675
- api: openAICompletionsApi(),
1676
- });
1677
-
1678
- pi.registerProvider(provider);
1679
-
1680
- // Register a new provider with custom models
1681
- pi.registerProvider("my-proxy", {
1682
- name: "My Proxy",
1683
- baseUrl: "https://proxy.example.com",
1684
- apiKey: "$PROXY_API_KEY", // env var reference
1685
- api: "anthropic-messages",
1686
- models: [
1687
- {
1688
- id: "claude-sonnet-4-20250514",
1689
- name: "Claude 4 Sonnet (proxy)",
1690
- reasoning: false,
1691
- input: ["text", "image"],
1692
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1693
- contextWindow: 200000,
1694
- maxTokens: 16384
1695
- }
1696
- ]
1697
- });
1698
-
1699
- // Register a live llama.cpp catalog without persisting discovered models
1700
- pi.registerProvider("llama.cpp", {
1701
- baseUrl: "http://localhost:8080/v1",
1702
- apiKey: "local",
1703
- api: "openai-completions",
1704
- async refreshModels({ signal }) {
1705
- const response = await fetch("http://localhost:8080/v1/models", { signal });
1706
- const { data } = await response.json();
1707
- return data.map(({ id }) => ({
1708
- id,
1709
- name: id,
1710
- reasoning: false,
1711
- input: ["text"],
1712
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1713
- contextWindow: 128000,
1714
- maxTokens: 16384
1715
- }));
1716
- }
1717
- });
1718
-
1719
- // Override baseUrl for an existing provider (keeps all models)
1720
- pi.registerProvider("anthropic", {
1721
- baseUrl: "https://proxy.example.com"
1722
- });
1723
-
1724
- // Register provider with OAuth support for /login
1725
- pi.registerProvider("corporate-ai", {
1726
- baseUrl: "https://ai.corp.com",
1727
- api: "openai-responses",
1728
- models: [...],
1729
- oauth: {
1730
- name: "Corporate AI (SSO)",
1731
- async login(callbacks) {
1732
- // Custom OAuth flow
1733
- callbacks.onAuth({ url: "https://sso.corp.com/..." });
1734
- const code = await callbacks.onPrompt({ message: "Enter code:" });
1735
- return { refresh: code, access: code, expires: Date.now() + 3600000 };
1736
- },
1737
- async refreshToken(credentials) {
1738
- // Refresh logic
1739
- return credentials;
1740
- },
1741
- getApiKey(credentials) {
1742
- return credentials.access;
1743
- }
1744
- }
1745
- });
1746
- ```
1747
-
1748
- The object form accepts a complete `@draht/ai` `Provider`, including native `auth`, `getModels`, `refreshModels`, `filterModels`, `stream`, and `streamSimple` behavior.
1749
-
1750
- **Legacy config options:**
1751
- - `name` - Display name for the provider in UI such as `/login`.
1752
- - `baseUrl` - API endpoint URL. Required when defining models.
1753
- - `apiKey` - API key literal, environment interpolation (`$ENV_VAR` or `${ENV_VAR}`), or leading `!command`. Required when defining models (unless `oauth` provided). `$$` escapes `$`, and `$!` escapes a literal `!` without triggering command execution.
1754
- - `api` - API type: `"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc.
1755
- - `headers` - Custom headers to include in requests.
1756
- - `authHeader` - If true, adds `Authorization: Bearer` header automatically.
1757
- - `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.
1758
- - `refreshModels` - Async dynamic discovery callback. Its returned models replace extension-provided models. Use the scoped `context.store` only when results should persist.
1759
- - `oauth` - OAuth provider config for `/login` support. When provided, the provider appears in the login menu.
1760
- - `streamSimple` - Custom streaming implementation for non-standard APIs.
1761
-
1762
- See [custom-provider.md](custom-provider.md) for advanced topics: custom streaming APIs, OAuth details, model definition reference.
1763
-
1764
- ### pi.unregisterProvider(name)
1765
-
1766
- 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.
1767
-
1768
- Like `registerProvider`, this takes effect immediately when called after the initial load phase, so a `/reload` is not required.
1769
-
1770
- ```typescript
1771
- pi.registerCommand("my-setup-teardown", {
1772
- description: "Remove the custom proxy provider",
1773
- handler: async (_args, _ctx) => {
1774
- pi.unregisterProvider("my-proxy");
1775
- },
1776
- });
1777
- ```
1778
-
1779
- ## State Management
1780
-
1781
- Extensions with state should store it in tool result `details` for proper branching support:
1782
-
1783
- ```typescript
1784
- export default function (pi: ExtensionAPI) {
1785
- let items: string[] = [];
1786
-
1787
- // Reconstruct state from session
1788
- pi.on("session_start", async (_event, ctx) => {
1789
- items = [];
1790
- for (const entry of ctx.sessionManager.getBranch()) {
1791
- if (entry.type === "message" && entry.message.role === "toolResult") {
1792
- if (entry.message.toolName === "my_tool") {
1793
- items = entry.message.details?.items ?? [];
1794
- }
1795
- }
1796
- }
1797
- });
1798
-
1799
- pi.registerTool({
1800
- name: "my_tool",
1801
- // ...
1802
- async execute(toolCallId, params, signal, onUpdate, ctx) {
1803
- items.push("new item");
1804
- return {
1805
- content: [{ type: "text", text: "Added" }],
1806
- details: { items: [...items] }, // Store for reconstruction
1807
- };
1808
- },
1809
- });
1810
- }
1811
- ```
1812
-
1813
- ## Custom Tools
1814
-
1815
- Register tools the LLM can call via `pi.registerTool()`. Tools appear in the system prompt and can have custom rendering.
1816
-
1817
- Use `promptSnippet` for a short one-line entry in the `Available tools` section in the default system prompt. If omitted, custom tools are left out of that section.
1818
-
1819
- Use `promptGuidelines` to add tool-specific bullets to the default system prompt `Guidelines` section. These bullets are included only while the tool is active (for example, after `pi.setActiveTools([...])`).
1820
-
1821
- **Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` 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.
1822
-
1823
- Note: Some models are idiots and 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.
1824
-
1825
- 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.
1826
-
1827
- 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.
1828
-
1829
- 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.
1830
-
1831
- Queue the entire mutation window on that target path. That includes read-modify-write logic, not just the final write.
1832
-
1833
- ```typescript
1834
- import { withFileMutationQueue } from "@draht/coding-agent";
1835
- import { mkdir, readFile, writeFile } from "node:fs/promises";
1836
- import { dirname, resolve } from "node:path";
1837
-
1838
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1839
- const absolutePath = resolve(ctx.cwd, params.path);
1840
-
1841
- return withFileMutationQueue(absolutePath, async () => {
1842
- await mkdir(dirname(absolutePath), { recursive: true });
1843
- const current = await readFile(absolutePath, "utf8");
1844
- const next = current.replace(params.oldText, params.newText);
1845
- await writeFile(absolutePath, next, "utf8");
1846
-
1847
- return {
1848
- content: [{ type: "text", text: `Updated ${params.path}` }],
1849
- details: {},
1850
- };
1851
- });
1852
- }
1853
- ```
1854
-
1855
- ### Tool Definition
1856
-
1857
- ```typescript
1858
- import { Type } from "typebox";
1859
- import { StringEnum } from "@draht/ai";
1860
- import { Text } from "@draht/tui";
1861
-
1862
- pi.registerTool({
1863
- name: "my_tool",
1864
- label: "My Tool",
1865
- description: "What this tool does (shown to LLM)",
1866
- promptSnippet: "List or add items in the project todo list",
1867
- promptGuidelines: [
1868
- "Use my_tool for todo planning instead of direct file edits when the user asks for a task list."
1869
- ],
1870
- parameters: Type.Object({
1871
- action: StringEnum(["list", "add"] as const), // Use StringEnum for Google compatibility
1872
- text: Type.Optional(Type.String()),
1873
- }),
1874
- prepareArguments(args) {
1875
- if (!args || typeof args !== "object") return args;
1876
- const input = args as { action?: string; oldAction?: string };
1877
- if (typeof input.oldAction === "string" && input.action === undefined) {
1878
- return { ...input, action: input.oldAction };
1879
- }
1880
- return args;
1881
- },
1882
-
1883
- async execute(toolCallId, params, signal, onUpdate, ctx) {
1884
- // Check for cancellation
1885
- if (signal?.aborted) {
1886
- return { content: [{ type: "text", text: "Cancelled" }] };
1887
- }
1888
-
1889
- // Stream progress updates
1890
- onUpdate?.({
1891
- content: [{ type: "text", text: "Working..." }],
1892
- details: { progress: 50 },
1893
- });
1894
-
1895
- // Run commands via pi.exec (captured from extension closure)
1896
- const result = await pi.exec("some-command", [], { signal });
1897
-
1898
- // Return result
1899
- return {
1900
- content: [{ type: "text", text: "Done" }], // Sent to LLM
1901
- details: { data: result }, // For rendering & state
1902
- // usage: nestedModelResponse.usage, // Optional nested LLM usage
1903
- // Optional: stop after this tool batch when every finalized tool result
1904
- // in the batch also returns terminate: true.
1905
- terminate: true,
1906
- };
1907
- },
1908
-
1909
- // Optional: Custom rendering
1910
- renderCall(args, theme, context) { ... },
1911
- renderResult(result, options, theme, context) { ... },
1912
- });
1913
- ```
1914
-
1915
- **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.
1916
-
1917
- **Signaling errors:** To mark a tool execution as failed (sets `isError: true` on the result and reports it to the LLM), throw an error from `execute`. Returning a value never sets the error flag regardless of what properties you include in the return object.
1918
-
1919
- **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.
1920
-
1921
- ```typescript
1922
- // Correct: throw to signal an error
1923
- async execute(toolCallId, params) {
1924
- if (!isValid(params.input)) {
1925
- throw new Error(`Invalid input: ${params.input}`);
1926
- }
1927
- return { content: [{ type: "text", text: "OK" }], details: {} };
1928
- }
1929
- ```
1930
-
1931
- **Important:** Use `StringEnum` from `@draht/ai` for string enums. `Type.Union`/`Type.Literal` doesn't work with Google's API.
1932
-
1933
- **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.
1934
-
1935
- 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 }]`.
1936
-
1937
- ```typescript
1938
- pi.registerTool({
1939
- name: "edit",
1940
- label: "Edit",
1941
- description: "Edit a single file using exact text replacement",
1942
- parameters: Type.Object({
1943
- path: Type.String(),
1944
- edits: Type.Array(
1945
- Type.Object({
1946
- oldText: Type.String(),
1947
- newText: Type.String(),
1948
- }),
1949
- ),
1950
- }),
1951
- prepareArguments(args) {
1952
- if (!args || typeof args !== "object") return args;
1953
-
1954
- const input = args as {
1955
- path?: string;
1956
- edits?: Array<{ oldText: string; newText: string }>;
1957
- oldText?: unknown;
1958
- newText?: unknown;
1959
- };
1960
-
1961
- if (typeof input.oldText !== "string" || typeof input.newText !== "string") {
1962
- return args;
1963
- }
1964
-
1965
- return {
1966
- ...input,
1967
- edits: [...(input.edits ?? []), { oldText: input.oldText, newText: input.newText }],
1968
- };
1969
- },
1970
- async execute(toolCallId, params, signal, onUpdate, ctx) {
1971
- // params now matches the current schema
1972
- return {
1973
- content: [{ type: "text", text: `Applying ${params.edits.length} edit block(s)` }],
1974
- details: {},
1975
- };
1976
- },
1977
- });
1978
- ```
1979
-
1980
- ### Overriding Built-in Tools
1981
-
1982
- Extensions can override built-in tools (`read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`) by registering a tool with the same name. Interactive mode displays a warning when this happens.
1983
-
1984
- ```bash
1985
- # Extension's read tool replaces built-in read
1986
- draht -e ./tool-override.ts
1987
- ```
1988
-
1989
- Alternatively, use `--no-builtin-tools` to start without any built-in tools while keeping extension tools enabled:
1990
- ```bash
1991
- # No built-in tools, only extension tools
1992
- draht --no-builtin-tools -e ./my-extension.ts
1993
- ```
1994
-
1995
- See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.ts) for a complete example that overrides `read` with logging and access control.
1996
-
1997
- **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.
1998
-
1999
- **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.
2000
-
2001
- **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.
2002
-
2003
- Built-in tool implementations:
2004
- - [read.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/read.ts) - `ReadToolDetails`
2005
- - [bash.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/bash.ts) - `BashToolDetails`
2006
- - [edit.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/edit.ts)
2007
- - [write.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/write.ts)
2008
- - [grep.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/grep.ts) - `GrepToolDetails`
2009
- - [find.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/find.ts) - `FindToolDetails`
2010
- - [ls.ts](https://github.com/draht-dev/draht/blob/main/packages/coding-agent/src/core/tools/ls.ts) - `LsToolDetails`
2011
-
2012
- ### Remote Execution
2013
-
2014
- Built-in tools support pluggable operations for delegating to remote systems (SSH, containers, etc.):
2015
-
2016
- ```typescript
2017
- import { createReadTool, createBashTool, type ReadOperations } from "@draht/coding-agent";
2018
-
2019
- // Create tool with custom operations
2020
- const remoteRead = createReadTool(cwd, {
2021
- operations: {
2022
- readFile: (path) => sshExec(remote, `cat ${path}`),
2023
- access: (path) => sshExec(remote, `test -r ${path}`).then(() => {}),
2024
- }
2025
- });
2026
-
2027
- // Register, checking flag at execution time
2028
- pi.registerTool({
2029
- ...remoteRead,
2030
- async execute(id, params, signal, onUpdate, _ctx) {
2031
- const ssh = getSshConfig();
2032
- if (ssh) {
2033
- const tool = createReadTool(cwd, { operations: createRemoteOps(ssh) });
2034
- return tool.execute(id, params, signal, onUpdate);
2035
- }
2036
- return localRead.execute(id, params, signal, onUpdate);
2037
- },
2038
- });
2039
- ```
2040
-
2041
- **Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `LsOperations`, `GrepOperations`, `FindOperations`
2042
-
2043
- For `user_bash`, extensions can reuse draht's local shell backend via `createLocalBashOperations()` instead of reimplementing local process spawning, shell resolution, and process-tree termination.
2044
-
2045
- The bash tool also supports a spawn hook to adjust the command, cwd, or env before execution:
2046
-
2047
- ```typescript
2048
- import { createBashTool } from "@draht/coding-agent";
2049
-
2050
- const bashTool = createBashTool(cwd, {
2051
- spawnHook: ({ command, cwd, env }) => ({
2052
- command: `source ~/.profile\n${command}`,
2053
- cwd: `/mnt/sandbox${cwd}`,
2054
- env: { ...env, CI: "1" },
2055
- }),
2056
- });
2057
- ```
2058
-
2059
- `createBashTool()` exposes 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:
2060
-
2061
- ```typescript
2062
- const bashTool = createBashTool(cwd, {
2063
- exposeSessionEnvironment: false,
2064
- });
2065
- ```
2066
-
2067
- See [Bash tool session environment](environment-variables.md#bash-tool-session-environment) for variable semantics. See [examples/extensions/ssh.ts](../examples/extensions/ssh.ts) for a complete SSH example with `--ssh` flag.
2068
-
2069
- ### Output Truncation
2070
-
2071
- **Tools MUST truncate their output** to avoid overwhelming the LLM context. Large outputs can cause:
2072
- - Context overflow errors (prompt too long)
2073
- - Compaction failures
2074
- - Degraded model performance
2075
-
2076
- The built-in limit is **50KB** (~10k tokens) and **2000 lines**, whichever is hit first. Use the exported truncation utilities:
2077
-
2078
- ```typescript
2079
- import {
2080
- truncateHead, // Keep first N lines/bytes (good for file reads, search results)
2081
- truncateTail, // Keep last N lines/bytes (good for logs, command output)
2082
- truncateLine, // Truncate a single line to maxBytes with ellipsis
2083
- formatSize, // Human-readable size (e.g., "50KB", "1.5MB")
2084
- DEFAULT_MAX_BYTES, // 50KB
2085
- DEFAULT_MAX_LINES, // 2000
2086
- } from "@draht/coding-agent";
2087
-
2088
- async execute(toolCallId, params, signal, onUpdate, ctx) {
2089
- const output = await runCommand();
2090
-
2091
- // Apply truncation
2092
- const truncation = truncateHead(output, {
2093
- maxLines: DEFAULT_MAX_LINES,
2094
- maxBytes: DEFAULT_MAX_BYTES,
2095
- });
2096
-
2097
- let result = truncation.content;
2098
-
2099
- if (truncation.truncated) {
2100
- // Write full output to temp file
2101
- const tempFile = writeTempFile(output);
2102
-
2103
- // Inform the LLM where to find complete output
2104
- result += `\n\n[Output truncated: ${truncation.outputLines} of ${truncation.totalLines} lines`;
2105
- result += ` (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).`;
2106
- result += ` Full output saved to: ${tempFile}]`;
2107
- }
2108
-
2109
- return { content: [{ type: "text", text: result }] };
2110
- }
2111
- ```
2112
-
2113
- **Key points:**
2114
- - Use `truncateHead` for content where the beginning matters (search results, file reads)
2115
- - Use `truncateTail` for content where the end matters (logs, command output)
2116
- - Always inform the LLM when output is truncated and where to find the full version
2117
- - Document the truncation limits in your tool's description
2118
-
2119
- See [examples/extensions/truncated-tool.ts](../examples/extensions/truncated-tool.ts) for a complete example wrapping `rg` (ripgrep) with proper truncation.
2120
-
2121
- ### Multiple Tools
2122
-
2123
- One extension can register multiple tools with shared state:
2124
-
2125
- ```typescript
2126
- export default function (pi: ExtensionAPI) {
2127
- let connection = null;
2128
-
2129
- pi.registerTool({ name: "db_connect", ... });
2130
- pi.registerTool({ name: "db_query", ... });
2131
- pi.registerTool({ name: "db_close", ... });
2132
-
2133
- pi.on("session_shutdown", async () => {
2134
- connection?.close();
2135
- });
2136
- }
2137
- ```
2138
-
2139
- ### Custom Rendering
2140
-
2141
- 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.
2142
-
2143
- By default, tool output is wrapped in a `Box` that handles padding and background. 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.
2144
-
2145
- 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.
2146
-
2147
- ```typescript
2148
- pi.registerTool({
2149
- name: "my_tool",
2150
- label: "My Tool",
2151
- description: "Custom shell example",
2152
- parameters: Type.Object({}),
2153
- renderShell: "self",
2154
- async execute() {
2155
- return { content: [{ type: "text", text: "ok" }], details: undefined };
2156
- },
2157
- renderCall(args, theme, context) {
2158
- return new Text(theme.fg("accent", "my custom shell"), 0, 0);
2159
- },
2160
- });
2161
- ```
2162
-
2163
- `renderCall` and `renderResult` each receive a `context` object with:
2164
- - `args` - the current tool call arguments
2165
- - `state` - shared row-local state across `renderCall` and `renderResult`
2166
- - `lastComponent` - the previously returned component for that slot, if any
2167
- - `invalidate()` - request a rerender of this tool row
2168
- - `toolCallId`, `cwd`, `executionStarted`, `argsComplete`, `isPartial`, `expanded`, `showImages`, `isError`
2169
-
2170
- 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.
2171
-
2172
- #### renderCall
2173
-
2174
- Renders the tool call or header:
2175
-
2176
- ```typescript
2177
- import { Text } from "@draht/tui";
2178
-
2179
- renderCall(args, theme, context) {
2180
- const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
2181
- let content = theme.fg("toolTitle", theme.bold("my_tool "));
2182
- content += theme.fg("muted", args.action);
2183
- if (args.text) {
2184
- content += " " + theme.fg("dim", `"${args.text}"`);
2185
- }
2186
- text.setText(content);
2187
- return text;
2188
- }
2189
- ```
2190
-
2191
- #### renderResult
2192
-
2193
- Renders the tool result or output:
2194
-
2195
- ```typescript
2196
- renderResult(result, { expanded, isPartial }, theme, context) {
2197
- if (isPartial) {
2198
- return new Text(theme.fg("warning", "Processing..."), 0, 0);
2199
- }
2200
-
2201
- if (result.details?.error) {
2202
- return new Text(theme.fg("error", `Error: ${result.details.error}`), 0, 0);
2203
- }
2204
-
2205
- let text = theme.fg("success", "✓ Done");
2206
- if (expanded && result.details?.items) {
2207
- for (const item of result.details.items) {
2208
- text += "\n " + theme.fg("dim", item);
2209
- }
2210
- }
2211
- return new Text(text, 0, 0);
2212
- }
2213
- ```
2214
-
2215
- If a slot intentionally has no visible content, return an empty `Component` such as an empty `Container`.
2216
-
2217
- #### Keybinding Hints
2218
-
2219
- Use `keyHint()` to display keybinding hints that respect the active keybinding configuration:
2220
-
2221
- ```typescript
2222
- import { keyHint } from "@draht/coding-agent";
2223
-
2224
- renderResult(result, { expanded }, theme, context) {
2225
- let text = theme.fg("success", "✓ Done");
2226
- if (!expanded) {
2227
- text += ` (${keyHint("app.tools.expand", "to expand")})`;
2228
- }
2229
- return new Text(text, 0, 0);
2230
- }
2231
- ```
2232
-
2233
- Available functions:
2234
- - `keyHint(keybinding, description)` - Formats a configured keybinding id such as `"app.tools.expand"` or `"tui.select.confirm"`
2235
- - `keyText(keybinding)` - Returns the raw configured key text for a keybinding id
2236
- - `rawKeyHint(key, description)` - Format a raw key string
2237
-
2238
- Use namespaced keybinding ids:
2239
- - Coding-agent ids use the `app.*` namespace, for example `app.tools.expand`, `app.editor.external`, `app.session.rename`
2240
- - Shared TUI ids use the `tui.*` namespace, for example `tui.select.confirm`, `tui.select.cancel`, `tui.input.tab`
2241
-
2242
- For the exhaustive list of keybinding ids and defaults, see [keybindings.md](keybindings.md). `keybindings.json` uses those same namespaced ids.
2243
-
2244
- 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()`.
2245
-
2246
- #### Best Practices
2247
-
2248
- - Use `Text` with padding `(0, 0)`. The default Box handles padding.
2249
- - Use `\n` for multi-line content.
2250
- - Handle `isPartial` for streaming progress.
2251
- - Support `expanded` for detail on demand.
2252
- - Keep default view compact.
2253
- - Read `context.args` in `renderResult` instead of copying args into `context.state`.
2254
- - Use `context.state` only for data that must be shared across call and result slots.
2255
- - Reuse `context.lastComponent` when the same component instance can be updated in place.
2256
- - 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.
2257
-
2258
- #### Fallback
2259
-
2260
- If a slot renderer is not defined or throws:
2261
- - `renderCall`: Shows the tool name
2262
- - `renderResult`: Shows raw text from `content`
2263
-
2264
- ### Dynamic Tool Loading
2265
-
2266
- Extensions can register many tools while keeping only a small initial set active. A tool can then add more tools with `pi.setActiveTools()` during execution. draht detects purely additive changes, records the newly available tool names on that tool result, and applies the updated active set before the next model request.
2267
-
2268
- This works with every model. Models with native deferred-loading support preserve the stable prompt prefix and load the new definitions at the tool-result position. Other models use the fallback described below.
2269
-
2270
- The lifecycle is:
2271
-
2272
- 1. Register every tool with `pi.registerTool()` so it appears in `pi.getAllTools()`.
2273
- 2. Keep loader tools, such as `search_tools`, active and leave searchable tools inactive.
2274
- 3. During loader execution, call `pi.setActiveTools([...currentTools, ...matchingTools])`. The change must be additive: do not remove currently active tools in the same call.
2275
- 4. draht records which tools were added on the loader's tool result.
2276
- 5. Before the next model response, draht exposes the added definitions using native deferred loading when supported, or the normal active tool list otherwise.
2277
-
2278
- You do not need to return provider-specific tool references or mark the loader as a special search tool. The active-tool change is the signal. Names passed to `pi.setActiveTools()` must already be registered; unknown names are ignored.
2279
-
2280
- #### Models with native deferred loading
2281
-
2282
- - **Anthropic**
2283
- - **Models:** Sonnet, Opus, Fable version 4.5 or newer (without Haiku)
2284
- - **Native representation:** Deferred definitions use `defer_loading`; the load point uses `tool_reference` content.
2285
- - **OpenAI**
2286
- - **Models:** `gpt-5.4` and newer family
2287
- - **Native representation:** draht adds completed client `tool_search_call` and `tool_search_output` items at the load point.
2288
-
2289
- For a verified custom model or proxy, native handling can be enabled with `compat.supportsToolReferences: true` for `anthropic-messages`, or `compat.supportsToolSearch: true` for `openai-responses` and `openai-codex-responses`. Leave these disabled unless the endpoint and model accept the corresponding native protocol.
2290
-
2291
- #### Fallback behavior
2292
-
2293
- For all other models and providers, dynamic activation still works: draht sends the complete current active tool list normally on the next request. The model can call the newly activated tools, but adding their definitions may invalidate the provider's cached prompt prefix.
2294
-
2295
- draht also uses this safe fallback when the active set is not purely additive, such as replacing one group of tools with another. Tool removals therefore work, but they do not use deferred loading.
2296
-
2297
- For the best cache behavior, keep the loader tool active for the whole session and add tools instead of replacing the active set. Also note that activating a tool with `promptSnippet` or `promptGuidelines` rebuilds the system prompt; that system-prompt change can invalidate the prefix even when the provider supports deferred schemas. Lazily loaded tools should usually rely on their tool `description` and omit active-only prompt metadata.
2298
-
2299
- #### Search tool example
2300
-
2301
- The following extension registers two searchable tools, removes them from the initial active set, and keeps only `search_tools` as their loader. The example uses simple keyword matching, but the search implementation could use BM25, embeddings, a remote catalog, or project-specific routing.
2302
-
2303
- ```typescript
2304
- import type { ExtensionAPI } from "@draht/coding-agent";
2305
- import { Type } from "typebox";
2306
-
2307
- const SEARCHABLE_TOOL_NAMES = new Set(["lookup_weather", "search_issues"]);
2308
-
2309
- export default function (pi: ExtensionAPI) {
2310
- pi.registerTool({
2311
- name: "lookup_weather",
2312
- label: "Lookup Weather",
2313
- description: "Look up the current weather for a city",
2314
- parameters: Type.Object({ city: Type.String() }),
2315
- async execute(_toolCallId, params) {
2316
- return {
2317
- content: [{ type: "text", text: `Weather for ${params.city}: sunny` }],
2318
- details: {},
2319
- };
2320
- },
2321
- });
2322
-
2323
- pi.registerTool({
2324
- name: "search_issues",
2325
- label: "Search Issues",
2326
- description: "Search project issues by keyword",
2327
- parameters: Type.Object({ query: Type.String() }),
2328
- async execute(_toolCallId, params) {
2329
- return {
2330
- content: [{ type: "text", text: `No open issues matching ${params.query}` }],
2331
- details: {},
2332
- };
2333
- },
2334
- });
2335
-
2336
- pi.registerTool({
2337
- name: "search_tools",
2338
- label: "Search Tools",
2339
- description: "Search for and enable tools relevant to a task",
2340
- promptSnippet: "Search for additional tools when the active tools cannot perform the task",
2341
- promptGuidelines: [
2342
- "Use search_tools when a task requires a capability that is not currently available.",
2343
- ],
2344
- parameters: Type.Object({
2345
- query: Type.String({ description: "Capability or task to search for" }),
2346
- limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 10 })),
2347
- }),
2348
- async execute(_toolCallId, params) {
2349
- const terms = params.query.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
2350
- const matches = pi.getAllTools()
2351
- .filter((tool) => SEARCHABLE_TOOL_NAMES.has(tool.name))
2352
- .map((tool) => ({
2353
- tool,
2354
- score: terms.reduce(
2355
- (score, term) =>
2356
- score + (`${tool.name} ${tool.description}`.toLowerCase().includes(term) ? 1 : 0),
2357
- 0,
2358
- ),
2359
- }))
2360
- .filter((match) => match.score > 0)
2361
- .sort((a, b) => b.score - a.score)
2362
- .slice(0, params.limit ?? 3)
2363
- .map((match) => match.tool.name);
2364
-
2365
- if (matches.length === 0) {
2366
- return {
2367
- content: [{ type: "text", text: `No tools found for: ${params.query}` }],
2368
- details: { matches: [] },
2369
- };
2370
- }
2371
-
2372
- const active = pi.getActiveTools();
2373
- const added = matches.filter((name) => !active.includes(name));
2374
- pi.setActiveTools([...new Set([...active, ...added])]);
2375
-
2376
- return {
2377
- content: [{
2378
- type: "text",
2379
- text: added.length > 0
2380
- ? `Loaded tools: ${added.join(", ")}`
2381
- : `Matching tools already active: ${matches.join(", ")}`,
2382
- }],
2383
- details: { matches, added },
2384
- };
2385
- },
2386
- });
2387
-
2388
- pi.on("session_start", () => {
2389
- // Keep searchable tools registered but initially inactive. Preserve built-ins
2390
- // and tools owned by other extensions, and keep the loader itself active.
2391
- const initialTools = pi.getActiveTools().filter(
2392
- (name) => !SEARCHABLE_TOOL_NAMES.has(name),
2393
- );
2394
- pi.setActiveTools([...new Set([...initialTools, "search_tools"])]);
2395
- });
2396
- }
2397
- ```
2398
-
2399
- When `search_tools` adds a match, the model receives that definition on the immediately following request. On a native-capable model the definition is anchored after the search result without changing the initial tool-schema prefix. On other models it appears in the normal tool list on that same following request.
2400
-
2401
- ## Custom UI
2402
-
2403
- Extensions can interact with users via `ctx.ui` methods and customize how messages/tools render.
2404
-
2405
- **For custom components, see [tui.md](tui.md)** which has copy-paste patterns for:
2406
- - Selection dialogs (SelectList)
2407
- - Async operations with cancel (BorderedLoader)
2408
- - Settings toggles (SettingsList)
2409
- - Status indicators (setStatus)
2410
- - Working message, visibility, and indicator during streaming (`setWorkingMessage`, `setWorkingVisible`, `setWorkingIndicator`)
2411
- - Widgets above/below editor (setWidget)
2412
- - Autocomplete providers layered on top of built-in slash/path completion (addAutocompleteProvider)
2413
- - Custom footers (setFooter)
2414
-
2415
- ### Dialogs
2416
-
2417
- ```typescript
2418
- // Select from options
2419
- const choice = await ctx.ui.select("Pick one:", ["A", "B", "C"]);
2420
-
2421
- // Confirm dialog
2422
- const ok = await ctx.ui.confirm("Delete?", "This cannot be undone");
2423
-
2424
- // Text input
2425
- const name = await ctx.ui.input("Name:", "placeholder");
2426
-
2427
- // Multi-line editor
2428
- const text = await ctx.ui.editor("Edit:", "prefilled text");
2429
-
2430
- // Notification (non-blocking)
2431
- ctx.ui.notify("Done!", "info"); // "info" | "warning" | "error"
2432
- ```
2433
-
2434
- #### Timed Dialogs with Countdown
2435
-
2436
- Dialogs support a `timeout` option that auto-dismisses with a live countdown display:
2437
-
2438
- ```typescript
2439
- // Dialog shows "Title (5s)" → "Title (4s)" → ... → auto-dismisses at 0
2440
- const confirmed = await ctx.ui.confirm(
2441
- "Timed Confirmation",
2442
- "This dialog will auto-cancel in 5 seconds. Confirm?",
2443
- { timeout: 5000 }
2444
- );
2445
-
2446
- if (confirmed) {
2447
- // User confirmed
2448
- } else {
2449
- // User cancelled or timed out
2450
- }
2451
- ```
2452
-
2453
- **Return values on timeout:**
2454
- - `select()` returns `undefined`
2455
- - `confirm()` returns `false`
2456
- - `input()` returns `undefined`
2457
-
2458
- #### Manual Dismissal with AbortSignal
2459
-
2460
- For more control (e.g., to distinguish timeout from user cancel), use `AbortSignal`:
2461
-
2462
- ```typescript
2463
- const controller = new AbortController();
2464
- const timeoutId = setTimeout(() => controller.abort(), 5000);
2465
-
2466
- const confirmed = await ctx.ui.confirm(
2467
- "Timed Confirmation",
2468
- "This dialog will auto-cancel in 5 seconds. Confirm?",
2469
- { signal: controller.signal }
2470
- );
2471
-
2472
- clearTimeout(timeoutId);
2473
-
2474
- if (confirmed) {
2475
- // User confirmed
2476
- } else if (controller.signal.aborted) {
2477
- // Dialog timed out
2478
- } else {
2479
- // User cancelled (pressed Escape or selected "No")
2480
- }
2481
- ```
2482
-
2483
- See [examples/extensions/timed-confirm.ts](../examples/extensions/timed-confirm.ts) for complete examples.
2484
-
2485
- ### Widgets, Status, and Footer
2486
-
2487
- ```typescript
2488
- // Status in footer (persistent until cleared)
2489
- ctx.ui.setStatus("my-ext", "Processing...");
2490
- ctx.ui.setStatus("my-ext", undefined); // Clear
2491
-
2492
- // Working loader (shown during streaming)
2493
- ctx.ui.setWorkingMessage("Thinking deeply...");
2494
- ctx.ui.setWorkingMessage(); // Restore default
2495
- ctx.ui.setWorkingVisible(false); // Hide the built-in working loader row entirely
2496
- ctx.ui.setWorkingVisible(true); // Show the built-in working loader row
2497
-
2498
- // Working indicator (shown during streaming)
2499
- ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg("accent", "●")] }); // Static dot
2500
- ctx.ui.setWorkingIndicator({
2501
- frames: [
2502
- ctx.ui.theme.fg("dim", "·"),
2503
- ctx.ui.theme.fg("muted", "•"),
2504
- ctx.ui.theme.fg("accent", "●"),
2505
- ctx.ui.theme.fg("muted", "•"),
2506
- ],
2507
- intervalMs: 120,
2508
- });
2509
- ctx.ui.setWorkingIndicator({ frames: [] }); // Hide indicator
2510
- ctx.ui.setWorkingIndicator(); // Restore default spinner
2511
-
2512
- // Widget above editor (default)
2513
- ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]);
2514
- // Widget below editor
2515
- ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" });
2516
- ctx.ui.setWidget("my-widget", (tui, theme) => new Text(theme.fg("accent", "Custom"), 0, 0));
2517
- ctx.ui.setWidget("my-widget", undefined); // Clear
2518
-
2519
- // Custom footer (replaces built-in footer entirely)
2520
- ctx.ui.setFooter((tui, theme) => ({
2521
- render(width) { return [theme.fg("dim", "Custom footer")]; },
2522
- invalidate() {},
2523
- }));
2524
- ctx.ui.setFooter(undefined); // Restore built-in footer
2525
-
2526
- // Terminal title
2527
- ctx.ui.setTitle("draht - my-project");
2528
-
2529
- // Editor text
2530
- ctx.ui.setEditorText("Prefill text");
2531
- const current = ctx.ui.getEditorText();
2532
-
2533
- // Paste into editor (triggers paste handling, including collapse for large content)
2534
- ctx.ui.pasteToEditor("pasted content");
2535
-
2536
- // Stack custom autocomplete behavior on top of the built-in provider
2537
- ctx.ui.addAutocompleteProvider((current) => ({
2538
- triggerCharacters: ["#"],
2539
- async getSuggestions(lines, line, col, options) {
2540
- const beforeCursor = (lines[line] ?? "").slice(0, col);
2541
- const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/);
2542
- if (!match) {
2543
- return current.getSuggestions(lines, line, col, options);
2544
- }
2545
-
2546
- return {
2547
- prefix: `#${match[1] ?? ""}`,
2548
- items: [{ value: "#2983", label: "#2983", description: "Extension API for autocomplete" }],
2549
- };
2550
- },
2551
- applyCompletion(lines, line, col, item, prefix) {
2552
- return current.applyCompletion(lines, line, col, item, prefix);
2553
- },
2554
- shouldTriggerFileCompletion(lines, line, col) {
2555
- return current.shouldTriggerFileCompletion?.(lines, line, col) ?? true;
2556
- },
2557
- }));
2558
-
2559
- // Tool output expansion
2560
- const wasExpanded = ctx.ui.getToolsExpanded();
2561
- ctx.ui.setToolsExpanded(true);
2562
- ctx.ui.setToolsExpanded(wasExpanded);
2563
-
2564
- // Custom editor (vim mode, emacs mode, etc.)
2565
- ctx.ui.setEditorComponent((tui, theme, keybindings) => new VimEditor(tui, theme, keybindings));
2566
- const currentEditor = ctx.ui.getEditorComponent();
2567
- ctx.ui.setEditorComponent((tui, theme, keybindings) =>
2568
- new WrappedEditor(tui, theme, keybindings, currentEditor?.(tui, theme, keybindings))
2569
- );
2570
- ctx.ui.setEditorComponent(undefined); // Restore default editor
2571
-
2572
- // Theme management (see themes.md for creating themes)
2573
- const themes = ctx.ui.getAllThemes(); // [{ name: "dark", path: "/..." | undefined }, ...]
2574
- const lightTheme = ctx.ui.getTheme("light"); // Load without switching
2575
- const result = ctx.ui.setTheme("light"); // Switch by name
2576
- if (!result.success) {
2577
- ctx.ui.notify(`Failed: ${result.error}`, "error");
2578
- }
2579
- ctx.ui.setTheme(lightTheme!); // Or switch by Theme object
2580
- ctx.ui.theme.fg("accent", "styled text"); // Access current theme
2581
- ```
2582
-
2583
- 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(...)`.
2584
-
2585
- ### Autocomplete Providers
2586
-
2587
- 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 `$`.
2588
-
2589
- Typical pattern:
2590
-
2591
- - inspect the text before the cursor
2592
- - return your own suggestions when your extension-specific syntax matches
2593
- - otherwise delegate to `current.getSuggestions(...)`
2594
- - delegate `applyCompletion(...)` unless you need custom insertion behavior
2595
-
2596
- ```typescript
2597
- pi.on("session_start", (_event, ctx) => {
2598
- ctx.ui.addAutocompleteProvider((current) => ({
2599
- triggerCharacters: ["#"],
2600
- async getSuggestions(lines, cursorLine, cursorCol, options) {
2601
- const line = lines[cursorLine] ?? "";
2602
- const beforeCursor = line.slice(0, cursorCol);
2603
- const match = beforeCursor.match(/(?:^|[ \t])#([^\s#]*)$/);
2604
- if (!match) {
2605
- return current.getSuggestions(lines, cursorLine, cursorCol, options);
2606
- }
2607
-
2608
- return {
2609
- prefix: `#${match[1] ?? ""}`,
2610
- items: [
2611
- { value: "#2983", label: "#2983", description: "Extension API for registering custom @ autocomplete providers" },
2612
- { value: "#2753", label: "#2753", description: "Reload stale resource settings" },
2613
- ],
2614
- };
2615
- },
2616
-
2617
- applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
2618
- return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
2619
- },
2620
-
2621
- shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
2622
- return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
2623
- },
2624
- }));
2625
- });
2626
- ```
2627
-
2628
- 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.
2629
-
2630
- ### Custom Components
2631
-
2632
- For complex UI, use `ctx.ui.custom()`. This temporarily replaces the editor with your component until `done()` is called:
2633
-
2634
- ```typescript
2635
- import { Text, Component } from "@draht/tui";
2636
-
2637
- const result = await ctx.ui.custom<boolean>((tui, theme, keybindings, done) => {
2638
- const text = new Text("Press Enter to confirm, Escape to cancel", 1, 1);
2639
-
2640
- text.onKey = (key) => {
2641
- if (key === "return") done(true);
2642
- if (key === "escape") done(false);
2643
- return true;
2644
- };
2645
-
2646
- return text;
2647
- });
2648
-
2649
- if (result) {
2650
- // User pressed Enter
2651
- }
2652
- ```
2653
-
2654
- The callback receives:
2655
- - `tui` - TUI instance (for screen dimensions, focus management)
2656
- - `theme` - Current theme for styling
2657
- - `keybindings` - App keybinding manager (for checking shortcuts)
2658
- - `done(value)` - Call to close component and return value
2659
-
2660
- See [tui.md](tui.md) for the full component API.
2661
-
2662
- #### Overlay Mode (Experimental)
2663
-
2664
- Pass `{ overlay: true }` to render the component as a floating modal on top of existing content, without clearing the screen:
2665
-
2666
- ```typescript
2667
- const result = await ctx.ui.custom<string | null>(
2668
- (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
2669
- { overlay: true }
2670
- );
2671
- ```
2672
-
2673
- For advanced positioning (anchors, margins, percentages, responsive visibility), pass `overlayOptions`. Use `onHandle` to control focus or visibility programmatically:
2674
-
2675
- ```typescript
2676
- const result = await ctx.ui.custom<string | null>(
2677
- (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
2678
- {
2679
- overlay: true,
2680
- overlayOptions: { anchor: "top-right", width: "50%", margin: 2 },
2681
- onHandle: (handle) => {
2682
- handle.focus(); // focus this overlay and bring it to the visual front
2683
- // handle.unfocus({ target: editorComponent }); // release input to a specific component
2684
- // handle.setHidden(true/false); // toggle visibility
2685
- // handle.hide(); // permanently remove
2686
- }
2687
- }
2688
- );
2689
- ```
2690
-
2691
- 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.
2692
-
2693
- See [tui.md](tui.md) for the full `OverlayOptions` and `OverlayHandle` API and [overlay-qa-tests.ts](../examples/extensions/overlay-qa-tests.ts) for examples.
2694
-
2695
- ### Custom Editor
2696
-
2697
- Replace the main input editor with a custom implementation (vim mode, emacs mode, etc.):
2698
-
2699
- ```typescript
2700
- import { CustomEditor, type ExtensionAPI } from "@draht/coding-agent";
2701
- import { matchesKey } from "@draht/tui";
2702
-
2703
- class VimEditor extends CustomEditor {
2704
- private mode: "normal" | "insert" = "insert";
2705
-
2706
- handleInput(data: string): void {
2707
- if (matchesKey(data, "escape") && this.mode === "insert") {
2708
- this.mode = "normal";
2709
- return;
2710
- }
2711
- if (this.mode === "normal" && data === "i") {
2712
- this.mode = "insert";
2713
- return;
2714
- }
2715
- super.handleInput(data); // App keybindings + text editing
2716
- }
2717
- }
2718
-
2719
- export default function (pi: ExtensionAPI) {
2720
- pi.on("session_start", (_event, ctx) => {
2721
- ctx.ui.setEditorComponent((tui, theme, keybindings) =>
2722
- new VimEditor(tui, theme, keybindings)
2723
- );
2724
- });
2725
- }
2726
- ```
2727
-
2728
- **Key points:**
2729
- - Extend `CustomEditor` (not base `Editor`) to get app keybindings (escape to abort, ctrl+d, model switching)
2730
- - Call `super.handleInput(data)` for keys you don't handle
2731
- - Factory receives `tui`, `theme`, and `keybindings` from the app
2732
- - Use `ctx.ui.getEditorComponent()` before `setEditorComponent()` to wrap the previously configured custom editor
2733
- - Pass `undefined` to restore default: `ctx.ui.setEditorComponent(undefined)`
2734
-
2735
- To compose with another extension that already replaced the editor, capture the previous factory before setting yours:
2736
-
2737
- ```typescript
2738
- const previous = ctx.ui.getEditorComponent();
2739
- ctx.ui.setEditorComponent((tui, theme, keybindings) =>
2740
- new MyEditor(tui, theme, keybindings, { base: previous?.(tui, theme, keybindings) })
2741
- );
2742
- ```
2743
-
2744
- See [tui.md](tui.md) Pattern 7 for a complete example with mode indicator.
2745
-
2746
- ### Message and Entry Rendering
2747
-
2748
- Register a custom renderer for messages with your `customType`. Use message renderers for content that should participate in LLM context:
2749
-
2750
- ```typescript
2751
- import { Text } from "@draht/tui";
2752
-
2753
- pi.registerMessageRenderer("my-extension", (message, options, theme) => {
2754
- const { expanded, outputPad } = options;
2755
- let text = theme.fg("accent", `[${message.customType}] `);
2756
- text += message.content;
2757
-
2758
- if (expanded && message.details) {
2759
- text += "\n" + theme.fg("dim", JSON.stringify(message.details, null, 2));
2760
- }
2761
-
2762
- return new Text(text, outputPad, 0);
2763
- });
2764
- ```
2765
-
2766
- Messages are sent via `pi.sendMessage()`:
2767
-
2768
- ```typescript
2769
- pi.sendMessage({
2770
- customType: "my-extension", // Matches registerMessageRenderer
2771
- content: "Status update",
2772
- display: true, // Show in TUI
2773
- details: { ... }, // Available in renderer
2774
- });
2775
- ```
2776
-
2777
- For TUI-only content that should not be sent to the LLM, render custom entries instead:
2778
-
2779
- ```typescript
2780
- pi.registerEntryRenderer("my-card", (entry, options, theme) => {
2781
- return new Text(theme.fg("accent", JSON.stringify(entry.data)));
2782
- });
2783
-
2784
- pi.appendEntry("my-card", { status: "done" });
2785
- ```
2786
-
2787
- ### Theme Colors
2788
-
2789
- All render functions receive a `theme` object. See [themes.md](themes.md) for creating custom themes and the full color palette.
2790
-
2791
- ```typescript
2792
- // Foreground colors
2793
- theme.fg("toolTitle", text) // Tool names
2794
- theme.fg("accent", text) // Highlights
2795
- theme.fg("success", text) // Success (green)
2796
- theme.fg("error", text) // Errors (red)
2797
- theme.fg("warning", text) // Warnings (yellow)
2798
- theme.fg("muted", text) // Secondary text
2799
- theme.fg("dim", text) // Tertiary text
2800
-
2801
- // Text styles
2802
- theme.bold(text)
2803
- theme.italic(text)
2804
- theme.strikethrough(text)
2805
- ```
2806
-
2807
- For syntax highlighting in custom tool renderers:
2808
-
2809
- ```typescript
2810
- import { highlightCode, getLanguageFromPath } from "@draht/coding-agent";
2811
-
2812
- // Highlight code with explicit language
2813
- const highlighted = highlightCode("const x = 1;", "typescript", theme);
2814
-
2815
- // Auto-detect language from file path
2816
- const lang = getLanguageFromPath("/path/to/file.rs"); // "rust"
2817
- const highlighted = highlightCode(code, lang, theme);
2818
- ```
276
+ The checked [extension examples](../examples/extensions/) cover tools, lifecycle events, commands, flags, shortcuts, state, rendering, providers, OAuth, remote execution, and terminal components.
277
+ Start with the smallest example matching your integration point.
2819
278
 
2820
- ## Error Handling
2821
-
2822
- - Extension errors are logged, agent continues
2823
- - `tool_call` errors block the tool (fail-safe)
2824
- - Tool `execute` errors must be signaled by throwing; the thrown error is caught, reported to the LLM with `isError: true`, and execution continues
2825
-
2826
- ## Mode Behavior
2827
-
2828
- | Mode | `ctx.mode` | `ctx.hasUI` | Notes |
2829
- |------|------------|-------------|-------|
2830
- | Interactive | `"tui"` | `true` | Full TUI with terminal rendering |
2831
- | RPC (`--mode rpc`) | `"rpc"` | `true` | Dialogs and notifications via JSON protocol; `custom()` returns `undefined`. See [rpc.md](rpc.md) |
2832
- | JSON (`--mode json`) | `"json"` | `false` | Event stream to stdout; UI methods are no-ops |
2833
- | Print (`-p`) | `"print"` | `false` | Extensions run but can't prompt |
2834
-
2835
- 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.
2836
-
2837
- ## Examples Reference
2838
-
2839
- All examples in [examples/extensions/](../examples/extensions/).
2840
-
2841
- | Example | Description | Key APIs |
2842
- |---------|-------------|----------|
2843
- | **Tools** |||
2844
- | `hello.ts` | Minimal tool registration | `registerTool` |
2845
- | `question.ts` | Tool with user interaction | `registerTool`, `ui.select` |
2846
- | `questionnaire.ts` | Multi-step wizard tool | `registerTool`, `ui.custom` |
2847
- | `todo.ts` | Stateful tool with persistence | `registerTool`, `appendEntry`, `renderResult`, session events |
2848
- | `dynamic-tools.ts` | Register tools after startup and during commands | `registerTool`, `session_start`, `registerCommand` |
2849
- | `structured-output.ts` | Final structured-output tool with `terminate: true` | `registerTool`, terminating tool results |
2850
- | `truncated-tool.ts` | Output truncation example | `registerTool`, `truncateHead` |
2851
- | `tool-override.ts` | Override built-in read tool | `registerTool` (same name as built-in) |
2852
- | **Commands** |||
2853
- | `pirate.ts` | Modify system prompt per-turn | `registerCommand`, `before_agent_start` |
2854
- | `summarize.ts` | Conversation summary command | `registerCommand`, `ui.custom` |
2855
- | `handoff.ts` | Cross-provider model handoff | `registerCommand`, `ui.editor`, `ui.custom` |
2856
- | `qna.ts` | Q&A with custom UI | `registerCommand`, `ui.custom`, `setEditorText` |
2857
- | `send-user-message.ts` | Inject user messages | `registerCommand`, `sendUserMessage` |
2858
- | `reload-runtime.ts` | Reload command and LLM tool handoff | `registerCommand`, `ctx.reload()`, `sendUserMessage` |
2859
- | `shutdown-command.ts` | Graceful shutdown command | `registerCommand`, `shutdown()` |
2860
- | **Events & Gates** |||
2861
- | `permission-gate.ts` | Block dangerous commands | `on("tool_call")`, `ui.confirm` |
2862
- | `project-trust.ts` | Decide or defer project trust from a user/global or CLI extension | `on("project_trust")`, trust UI, required trust result |
2863
- | `protected-paths.ts` | Block writes to specific paths | `on("tool_call")` |
2864
- | `confirm-destructive.ts` | Confirm session changes | `on("session_before_switch")`, `on("session_before_fork")` |
2865
- | `dirty-repo-guard.ts` | Warn on dirty git repo | `on("session_before_*")`, `exec` |
2866
- | `input-transform.ts` | Transform user input | `on("input")` |
2867
- | `input-transform-streaming.ts` | Streaming-aware input transform | `on("input")`, `streamingBehavior` |
2868
- | `model-status.ts` | React to model changes | `on("model_select")`, `setStatus` |
2869
- | `provider-payload.ts` | Inspect payloads and provider response headers | `on("before_provider_request")`, `on("after_provider_response")` |
2870
- | `system-prompt-header.ts` | Display system prompt info | `on("agent_start")`, `getSystemPrompt` |
2871
- | `claude-rules.ts` | Load rules from files | `on("session_start")`, `on("before_agent_start")` |
2872
- | `prompt-customizer.ts` | Add context-aware tool guidance using `systemPromptOptions` | `on("before_agent_start")`, `BuildSystemPromptOptions` |
2873
- | `file-trigger.ts` | File watcher triggers messages | `sendMessage` |
2874
- | **Compaction & Sessions** |||
2875
- | `custom-compaction.ts` | Custom compaction summary | `on("session_before_compact")` |
2876
- | `trigger-compact.ts` | Trigger compaction manually | `compact()` |
2877
- | `git-checkpoint.ts` | Git stash on turns | `on("turn_start")`, `on("session_before_fork")`, `exec` |
2878
- | `git-merge-and-resolve.ts` | Fetch, merge, and resolve conflicts | `on("agent_end")`, `exec`, `sendUserMessage` |
2879
- | `auto-commit-on-exit.ts` | Commit on shutdown | `on("session_shutdown")`, `exec` |
2880
- | **UI Components** |||
2881
- | `status-line.ts` | Footer status indicator | `setStatus`, session events |
2882
- | `working-indicator.ts` | Customize the streaming working indicator | `setWorkingIndicator`, `registerCommand` |
2883
- | `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` |
2884
- | `custom-footer.ts` | Replace footer entirely | `registerCommand`, `setFooter` |
2885
- | `custom-header.ts` | Replace startup header | `on("session_start")`, `setHeader` |
2886
- | `modal-editor.ts` | Vim-style modal editor | `setEditorComponent`, `CustomEditor` |
2887
- | `rainbow-editor.ts` | Custom editor styling | `setEditorComponent` |
2888
- | `widget-placement.ts` | Widget above/below editor | `setWidget` |
2889
- | `overlay-test.ts` | Overlay components | `ui.custom` with overlay options |
2890
- | `overlay-qa-tests.ts` | Comprehensive overlay tests | `ui.custom`, all overlay options |
2891
- | `notify.ts` | Simple notifications | `ui.notify` |
2892
- | `timed-confirm.ts` | Dialogs with timeout | `ui.confirm` with timeout/signal |
2893
- | `mac-system-theme.ts` | Auto-switch theme | `setTheme`, `exec` |
2894
- | **Complex Extensions** |||
2895
- | `plan-mode/` | Full plan mode implementation | All event types, `registerCommand`, `registerShortcut`, `registerFlag`, `setStatus`, `setWidget`, `sendMessage`, `setActiveTools` |
2896
- | `preset.ts` | Saveable presets (model, tools, thinking) | `registerCommand`, `registerShortcut`, `registerFlag`, `setModel`, `setActiveTools`, `setThinkingLevel`, `appendEntry` |
2897
- | `tools.ts` | Toggle tools on/off UI | `registerCommand`, `setActiveTools`, `SettingsList`, session events |
2898
- | **Remote & Sandbox** |||
2899
- | `ssh.ts` | SSH remote execution | `registerFlag`, `on("user_bash")`, `on("before_agent_start")`, tool operations |
2900
- | `interactive-shell.ts` | Persistent shell session | `on("user_bash")` |
2901
- | `sandbox/` | Sandboxed tool execution | Tool operations |
2902
- | `gondolin/` | Route built-in tools and `!` commands into a Gondolin micro-VM | Tool operations, built-in tool overrides, `on("user_bash")` |
2903
- | `subagent/` | Spawn sub-agents | `registerTool`, `exec` |
2904
- | **Games** |||
2905
- | `snake.ts` | Snake game | `registerCommand`, `ui.custom`, keyboard handling |
2906
- | `space-invaders.ts` | Space Invaders game | `registerCommand`, `ui.custom` |
2907
- | `doom-overlay/` | Doom in overlay | `ui.custom` with overlay |
2908
- | **Providers** |||
2909
- | `custom-provider-anthropic/` | Custom Anthropic proxy | `registerProvider` |
2910
- | `custom-provider-gitlab-duo/` | GitLab Duo integration | `registerProvider` with OAuth |
2911
- | **Messages & Communication** |||
2912
- | `message-renderer.ts` | Custom message rendering | `registerMessageRenderer`, `sendMessage` |
2913
- | `entry-renderer.ts` | TUI-only custom entry rendering | `registerEntryRenderer`, `appendEntry` |
2914
- | `event-bus.ts` | Inter-extension events | `pi.events` |
2915
- | **Session Metadata** |||
2916
- | `session-name.ts` | Name sessions for selector | `setSessionName`, `getSessionName` |
2917
- | `bookmark.ts` | Bookmark entries for /tree | `setLabel` |
2918
- | **Misc** |||
2919
- | `inline-bash.ts` | Inline bash in tool calls | `on("tool_call")` |
2920
- | `bash-spawn-hook.ts` | Adjust bash command, cwd, and env before execution | `createBashTool`, `spawnHook` |
2921
- | `with-deps/` | Extension with npm dependencies | Package structure with `package.json` |
279
+ 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.