@m4ike1/ion-coding-agent 0.1.0

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