@leanandmean/coding-agent 0.74.1-scramjet.6

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