@avadisabelle/ava-pi-coding-agent 0.61.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (628) hide show
  1. package/CHANGELOG.md +3246 -0
  2. package/README.md +596 -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 +7 -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/cli/args.d.ts +49 -0
  12. package/dist/cli/args.d.ts.map +1 -0
  13. package/dist/cli/args.js +304 -0
  14. package/dist/cli/args.js.map +1 -0
  15. package/dist/cli/config-selector.d.ts +14 -0
  16. package/dist/cli/config-selector.d.ts.map +1 -0
  17. package/dist/cli/config-selector.js +31 -0
  18. package/dist/cli/config-selector.js.map +1 -0
  19. package/dist/cli/file-processor.d.ts +15 -0
  20. package/dist/cli/file-processor.d.ts.map +1 -0
  21. package/dist/cli/file-processor.js +79 -0
  22. package/dist/cli/file-processor.js.map +1 -0
  23. package/dist/cli/initial-message.d.ts +18 -0
  24. package/dist/cli/initial-message.d.ts.map +1 -0
  25. package/dist/cli/initial-message.js +22 -0
  26. package/dist/cli/initial-message.js.map +1 -0
  27. package/dist/cli/list-models.d.ts +9 -0
  28. package/dist/cli/list-models.d.ts.map +1 -0
  29. package/dist/cli/list-models.js +92 -0
  30. package/dist/cli/list-models.js.map +1 -0
  31. package/dist/cli/session-picker.d.ts +9 -0
  32. package/dist/cli/session-picker.d.ts.map +1 -0
  33. package/dist/cli/session-picker.js +35 -0
  34. package/dist/cli/session-picker.js.map +1 -0
  35. package/dist/cli.d.ts +3 -0
  36. package/dist/cli.d.ts.map +1 -0
  37. package/dist/cli.js +14 -0
  38. package/dist/cli.js.map +1 -0
  39. package/dist/config.d.ts +68 -0
  40. package/dist/config.d.ts.map +1 -0
  41. package/dist/config.js +203 -0
  42. package/dist/config.js.map +1 -0
  43. package/dist/core/agent-session.d.ts +607 -0
  44. package/dist/core/agent-session.d.ts.map +1 -0
  45. package/dist/core/agent-session.js +2617 -0
  46. package/dist/core/agent-session.js.map +1 -0
  47. package/dist/core/auth-storage.d.ts +130 -0
  48. package/dist/core/auth-storage.d.ts.map +1 -0
  49. package/dist/core/auth-storage.js +419 -0
  50. package/dist/core/auth-storage.js.map +1 -0
  51. package/dist/core/bash-executor.d.ts +46 -0
  52. package/dist/core/bash-executor.d.ts.map +1 -0
  53. package/dist/core/bash-executor.js +113 -0
  54. package/dist/core/bash-executor.js.map +1 -0
  55. package/dist/core/compaction/branch-summarization.d.ts +86 -0
  56. package/dist/core/compaction/branch-summarization.d.ts.map +1 -0
  57. package/dist/core/compaction/branch-summarization.js +243 -0
  58. package/dist/core/compaction/branch-summarization.js.map +1 -0
  59. package/dist/core/compaction/compaction.d.ts +121 -0
  60. package/dist/core/compaction/compaction.d.ts.map +1 -0
  61. package/dist/core/compaction/compaction.js +612 -0
  62. package/dist/core/compaction/compaction.js.map +1 -0
  63. package/dist/core/compaction/index.d.ts +7 -0
  64. package/dist/core/compaction/index.d.ts.map +1 -0
  65. package/dist/core/compaction/index.js +7 -0
  66. package/dist/core/compaction/index.js.map +1 -0
  67. package/dist/core/compaction/utils.d.ts +38 -0
  68. package/dist/core/compaction/utils.d.ts.map +1 -0
  69. package/dist/core/compaction/utils.js +153 -0
  70. package/dist/core/compaction/utils.js.map +1 -0
  71. package/dist/core/defaults.d.ts +3 -0
  72. package/dist/core/defaults.d.ts.map +1 -0
  73. package/dist/core/defaults.js +2 -0
  74. package/dist/core/defaults.js.map +1 -0
  75. package/dist/core/diagnostics.d.ts +15 -0
  76. package/dist/core/diagnostics.d.ts.map +1 -0
  77. package/dist/core/diagnostics.js +2 -0
  78. package/dist/core/diagnostics.js.map +1 -0
  79. package/dist/core/event-bus.d.ts +9 -0
  80. package/dist/core/event-bus.d.ts.map +1 -0
  81. package/dist/core/event-bus.js +25 -0
  82. package/dist/core/event-bus.js.map +1 -0
  83. package/dist/core/exec.d.ts +29 -0
  84. package/dist/core/exec.d.ts.map +1 -0
  85. package/dist/core/exec.js +75 -0
  86. package/dist/core/exec.js.map +1 -0
  87. package/dist/core/export-html/ansi-to-html.d.ts +22 -0
  88. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -0
  89. package/dist/core/export-html/ansi-to-html.js +249 -0
  90. package/dist/core/export-html/ansi-to-html.js.map +1 -0
  91. package/dist/core/export-html/index.d.ts +37 -0
  92. package/dist/core/export-html/index.d.ts.map +1 -0
  93. package/dist/core/export-html/index.js +223 -0
  94. package/dist/core/export-html/index.js.map +1 -0
  95. package/dist/core/export-html/template.css +1001 -0
  96. package/dist/core/export-html/template.html +55 -0
  97. package/dist/core/export-html/template.js +1690 -0
  98. package/dist/core/export-html/tool-renderer.d.ts +38 -0
  99. package/dist/core/export-html/tool-renderer.d.ts.map +1 -0
  100. package/dist/core/export-html/tool-renderer.js +70 -0
  101. package/dist/core/export-html/tool-renderer.js.map +1 -0
  102. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  103. package/dist/core/export-html/vendor/marked.min.js +6 -0
  104. package/dist/core/extensions/index.d.ts +11 -0
  105. package/dist/core/extensions/index.d.ts.map +1 -0
  106. package/dist/core/extensions/index.js +9 -0
  107. package/dist/core/extensions/index.js.map +1 -0
  108. package/dist/core/extensions/loader.d.ts +25 -0
  109. package/dist/core/extensions/loader.d.ts.map +1 -0
  110. package/dist/core/extensions/loader.js +426 -0
  111. package/dist/core/extensions/loader.js.map +1 -0
  112. package/dist/core/extensions/runner.d.ts +150 -0
  113. package/dist/core/extensions/runner.d.ts.map +1 -0
  114. package/dist/core/extensions/runner.js +707 -0
  115. package/dist/core/extensions/runner.js.map +1 -0
  116. package/dist/core/extensions/types.d.ts +1037 -0
  117. package/dist/core/extensions/types.d.ts.map +1 -0
  118. package/dist/core/extensions/types.js +35 -0
  119. package/dist/core/extensions/types.js.map +1 -0
  120. package/dist/core/extensions/wrapper.d.ts +20 -0
  121. package/dist/core/extensions/wrapper.d.ts.map +1 -0
  122. package/dist/core/extensions/wrapper.js +28 -0
  123. package/dist/core/extensions/wrapper.js.map +1 -0
  124. package/dist/core/footer-data-provider.d.ts +44 -0
  125. package/dist/core/footer-data-provider.d.ts.map +1 -0
  126. package/dist/core/footer-data-provider.js +252 -0
  127. package/dist/core/footer-data-provider.js.map +1 -0
  128. package/dist/core/index.d.ts +9 -0
  129. package/dist/core/index.d.ts.map +1 -0
  130. package/dist/core/index.js +9 -0
  131. package/dist/core/index.js.map +1 -0
  132. package/dist/core/keybindings.d.ts +275 -0
  133. package/dist/core/keybindings.d.ts.map +1 -0
  134. package/dist/core/keybindings.js +241 -0
  135. package/dist/core/keybindings.js.map +1 -0
  136. package/dist/core/messages.d.ts +77 -0
  137. package/dist/core/messages.d.ts.map +1 -0
  138. package/dist/core/messages.js +123 -0
  139. package/dist/core/messages.js.map +1 -0
  140. package/dist/core/model-registry.d.ts +114 -0
  141. package/dist/core/model-registry.d.ts.map +1 -0
  142. package/dist/core/model-registry.js +563 -0
  143. package/dist/core/model-registry.js.map +1 -0
  144. package/dist/core/model-resolver.d.ts +110 -0
  145. package/dist/core/model-resolver.d.ts.map +1 -0
  146. package/dist/core/model-resolver.js +486 -0
  147. package/dist/core/model-resolver.js.map +1 -0
  148. package/dist/core/package-manager.d.ts +171 -0
  149. package/dist/core/package-manager.d.ts.map +1 -0
  150. package/dist/core/package-manager.js +1700 -0
  151. package/dist/core/package-manager.js.map +1 -0
  152. package/dist/core/prompt-templates.d.ts +50 -0
  153. package/dist/core/prompt-templates.d.ts.map +1 -0
  154. package/dist/core/prompt-templates.js +251 -0
  155. package/dist/core/prompt-templates.js.map +1 -0
  156. package/dist/core/resolve-config-value.d.ts +17 -0
  157. package/dist/core/resolve-config-value.d.ts.map +1 -0
  158. package/dist/core/resolve-config-value.js +94 -0
  159. package/dist/core/resolve-config-value.js.map +1 -0
  160. package/dist/core/resource-loader.d.ts +184 -0
  161. package/dist/core/resource-loader.d.ts.map +1 -0
  162. package/dist/core/resource-loader.js +670 -0
  163. package/dist/core/resource-loader.js.map +1 -0
  164. package/dist/core/sdk.d.ts +90 -0
  165. package/dist/core/sdk.d.ts.map +1 -0
  166. package/dist/core/sdk.js +242 -0
  167. package/dist/core/sdk.js.map +1 -0
  168. package/dist/core/session-manager.d.ts +329 -0
  169. package/dist/core/session-manager.d.ts.map +1 -0
  170. package/dist/core/session-manager.js +1097 -0
  171. package/dist/core/session-manager.js.map +1 -0
  172. package/dist/core/settings-manager.d.ts +235 -0
  173. package/dist/core/settings-manager.d.ts.map +1 -0
  174. package/dist/core/settings-manager.js +699 -0
  175. package/dist/core/settings-manager.js.map +1 -0
  176. package/dist/core/skills.d.ts +59 -0
  177. package/dist/core/skills.d.ts.map +1 -0
  178. package/dist/core/skills.js +385 -0
  179. package/dist/core/skills.js.map +1 -0
  180. package/dist/core/slash-commands.d.ts +15 -0
  181. package/dist/core/slash-commands.d.ts.map +1 -0
  182. package/dist/core/slash-commands.js +23 -0
  183. package/dist/core/slash-commands.js.map +1 -0
  184. package/dist/core/system-prompt.d.ts +28 -0
  185. package/dist/core/system-prompt.d.ts.map +1 -0
  186. package/dist/core/system-prompt.js +151 -0
  187. package/dist/core/system-prompt.js.map +1 -0
  188. package/dist/core/timings.d.ts +7 -0
  189. package/dist/core/timings.d.ts.map +1 -0
  190. package/dist/core/timings.js +25 -0
  191. package/dist/core/timings.js.map +1 -0
  192. package/dist/core/tools/bash.d.ts +63 -0
  193. package/dist/core/tools/bash.d.ts.map +1 -0
  194. package/dist/core/tools/bash.js +250 -0
  195. package/dist/core/tools/bash.js.map +1 -0
  196. package/dist/core/tools/edit-diff.d.ts +63 -0
  197. package/dist/core/tools/edit-diff.d.ts.map +1 -0
  198. package/dist/core/tools/edit-diff.js +244 -0
  199. package/dist/core/tools/edit-diff.js.map +1 -0
  200. package/dist/core/tools/edit.d.ts +39 -0
  201. package/dist/core/tools/edit.d.ts.map +1 -0
  202. package/dist/core/tools/edit.js +147 -0
  203. package/dist/core/tools/edit.js.map +1 -0
  204. package/dist/core/tools/file-mutation-queue.d.ts +6 -0
  205. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -0
  206. package/dist/core/tools/file-mutation-queue.js +37 -0
  207. package/dist/core/tools/file-mutation-queue.js.map +1 -0
  208. package/dist/core/tools/find.d.ts +39 -0
  209. package/dist/core/tools/find.d.ts.map +1 -0
  210. package/dist/core/tools/find.js +209 -0
  211. package/dist/core/tools/find.js.map +1 -0
  212. package/dist/core/tools/grep.d.ts +45 -0
  213. package/dist/core/tools/grep.d.ts.map +1 -0
  214. package/dist/core/tools/grep.js +239 -0
  215. package/dist/core/tools/grep.js.map +1 -0
  216. package/dist/core/tools/index.d.ts +74 -0
  217. package/dist/core/tools/index.d.ts.map +1 -0
  218. package/dist/core/tools/index.js +62 -0
  219. package/dist/core/tools/index.js.map +1 -0
  220. package/dist/core/tools/ls.d.ts +40 -0
  221. package/dist/core/tools/ls.d.ts.map +1 -0
  222. package/dist/core/tools/ls.js +118 -0
  223. package/dist/core/tools/ls.js.map +1 -0
  224. package/dist/core/tools/path-utils.d.ts +8 -0
  225. package/dist/core/tools/path-utils.d.ts.map +1 -0
  226. package/dist/core/tools/path-utils.js +81 -0
  227. package/dist/core/tools/path-utils.js.map +1 -0
  228. package/dist/core/tools/read.d.ts +39 -0
  229. package/dist/core/tools/read.d.ts.map +1 -0
  230. package/dist/core/tools/read.js +166 -0
  231. package/dist/core/tools/read.js.map +1 -0
  232. package/dist/core/tools/truncate.d.ts +70 -0
  233. package/dist/core/tools/truncate.d.ts.map +1 -0
  234. package/dist/core/tools/truncate.js +205 -0
  235. package/dist/core/tools/truncate.js.map +1 -0
  236. package/dist/core/tools/write.d.ts +29 -0
  237. package/dist/core/tools/write.d.ts.map +1 -0
  238. package/dist/core/tools/write.js +81 -0
  239. package/dist/core/tools/write.js.map +1 -0
  240. package/dist/index.d.ts +27 -0
  241. package/dist/index.d.ts.map +1 -0
  242. package/dist/index.js +42 -0
  243. package/dist/index.js.map +1 -0
  244. package/dist/main.d.ts +8 -0
  245. package/dist/main.d.ts.map +1 -0
  246. package/dist/main.js +736 -0
  247. package/dist/main.js.map +1 -0
  248. package/dist/migrations.d.ts +33 -0
  249. package/dist/migrations.d.ts.map +1 -0
  250. package/dist/migrations.js +261 -0
  251. package/dist/migrations.js.map +1 -0
  252. package/dist/modes/index.d.ts +9 -0
  253. package/dist/modes/index.d.ts.map +1 -0
  254. package/dist/modes/index.js +8 -0
  255. package/dist/modes/index.js.map +1 -0
  256. package/dist/modes/interactive/components/armin.d.ts +34 -0
  257. package/dist/modes/interactive/components/armin.d.ts.map +1 -0
  258. package/dist/modes/interactive/components/armin.js +333 -0
  259. package/dist/modes/interactive/components/armin.js.map +1 -0
  260. package/dist/modes/interactive/components/assistant-message.d.ts +16 -0
  261. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -0
  262. package/dist/modes/interactive/components/assistant-message.js +96 -0
  263. package/dist/modes/interactive/components/assistant-message.js.map +1 -0
  264. package/dist/modes/interactive/components/bash-execution.d.ts +35 -0
  265. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -0
  266. package/dist/modes/interactive/components/bash-execution.js +162 -0
  267. package/dist/modes/interactive/components/bash-execution.js.map +1 -0
  268. package/dist/modes/interactive/components/bordered-loader.d.ts +16 -0
  269. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -0
  270. package/dist/modes/interactive/components/bordered-loader.js +51 -0
  271. package/dist/modes/interactive/components/bordered-loader.js.map +1 -0
  272. package/dist/modes/interactive/components/branch-summary-message.d.ts +16 -0
  273. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -0
  274. package/dist/modes/interactive/components/branch-summary-message.js +44 -0
  275. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -0
  276. package/dist/modes/interactive/components/compaction-summary-message.d.ts +16 -0
  277. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -0
  278. package/dist/modes/interactive/components/compaction-summary-message.js +45 -0
  279. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -0
  280. package/dist/modes/interactive/components/config-selector.d.ts +71 -0
  281. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -0
  282. package/dist/modes/interactive/components/config-selector.js +479 -0
  283. package/dist/modes/interactive/components/config-selector.js.map +1 -0
  284. package/dist/modes/interactive/components/countdown-timer.d.ts +14 -0
  285. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -0
  286. package/dist/modes/interactive/components/countdown-timer.js +33 -0
  287. package/dist/modes/interactive/components/countdown-timer.js.map +1 -0
  288. package/dist/modes/interactive/components/custom-editor.d.ts +21 -0
  289. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -0
  290. package/dist/modes/interactive/components/custom-editor.js +70 -0
  291. package/dist/modes/interactive/components/custom-editor.js.map +1 -0
  292. package/dist/modes/interactive/components/custom-message.d.ts +20 -0
  293. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -0
  294. package/dist/modes/interactive/components/custom-message.js +79 -0
  295. package/dist/modes/interactive/components/custom-message.js.map +1 -0
  296. package/dist/modes/interactive/components/daxnuts.d.ts +23 -0
  297. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -0
  298. package/dist/modes/interactive/components/daxnuts.js +140 -0
  299. package/dist/modes/interactive/components/daxnuts.js.map +1 -0
  300. package/dist/modes/interactive/components/diff.d.ts +12 -0
  301. package/dist/modes/interactive/components/diff.d.ts.map +1 -0
  302. package/dist/modes/interactive/components/diff.js +133 -0
  303. package/dist/modes/interactive/components/diff.js.map +1 -0
  304. package/dist/modes/interactive/components/dynamic-border.d.ts +15 -0
  305. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -0
  306. package/dist/modes/interactive/components/dynamic-border.js +21 -0
  307. package/dist/modes/interactive/components/dynamic-border.js.map +1 -0
  308. package/dist/modes/interactive/components/extension-editor.d.ts +20 -0
  309. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -0
  310. package/dist/modes/interactive/components/extension-editor.js +111 -0
  311. package/dist/modes/interactive/components/extension-editor.js.map +1 -0
  312. package/dist/modes/interactive/components/extension-input.d.ts +23 -0
  313. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -0
  314. package/dist/modes/interactive/components/extension-input.js +61 -0
  315. package/dist/modes/interactive/components/extension-input.js.map +1 -0
  316. package/dist/modes/interactive/components/extension-selector.d.ts +24 -0
  317. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -0
  318. package/dist/modes/interactive/components/extension-selector.js +78 -0
  319. package/dist/modes/interactive/components/extension-selector.js.map +1 -0
  320. package/dist/modes/interactive/components/footer.d.ts +26 -0
  321. package/dist/modes/interactive/components/footer.d.ts.map +1 -0
  322. package/dist/modes/interactive/components/footer.js +198 -0
  323. package/dist/modes/interactive/components/footer.js.map +1 -0
  324. package/dist/modes/interactive/components/index.d.ts +32 -0
  325. package/dist/modes/interactive/components/index.d.ts.map +1 -0
  326. package/dist/modes/interactive/components/index.js +33 -0
  327. package/dist/modes/interactive/components/index.js.map +1 -0
  328. package/dist/modes/interactive/components/keybinding-hints.d.ts +8 -0
  329. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -0
  330. package/dist/modes/interactive/components/keybinding-hints.js +22 -0
  331. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -0
  332. package/dist/modes/interactive/components/login-dialog.d.ts +42 -0
  333. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -0
  334. package/dist/modes/interactive/components/login-dialog.js +145 -0
  335. package/dist/modes/interactive/components/login-dialog.js.map +1 -0
  336. package/dist/modes/interactive/components/model-selector.d.ts +47 -0
  337. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -0
  338. package/dist/modes/interactive/components/model-selector.js +275 -0
  339. package/dist/modes/interactive/components/model-selector.js.map +1 -0
  340. package/dist/modes/interactive/components/oauth-selector.d.ts +19 -0
  341. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -0
  342. package/dist/modes/interactive/components/oauth-selector.js +97 -0
  343. package/dist/modes/interactive/components/oauth-selector.js.map +1 -0
  344. package/dist/modes/interactive/components/scoped-models-selector.d.ts +49 -0
  345. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -0
  346. package/dist/modes/interactive/components/scoped-models-selector.js +275 -0
  347. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -0
  348. package/dist/modes/interactive/components/session-selector-search.d.ts +23 -0
  349. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -0
  350. package/dist/modes/interactive/components/session-selector-search.js +155 -0
  351. package/dist/modes/interactive/components/session-selector-search.js.map +1 -0
  352. package/dist/modes/interactive/components/session-selector.d.ts +95 -0
  353. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -0
  354. package/dist/modes/interactive/components/session-selector.js +848 -0
  355. package/dist/modes/interactive/components/session-selector.js.map +1 -0
  356. package/dist/modes/interactive/components/settings-selector.d.ts +58 -0
  357. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -0
  358. package/dist/modes/interactive/components/settings-selector.js +301 -0
  359. package/dist/modes/interactive/components/settings-selector.js.map +1 -0
  360. package/dist/modes/interactive/components/show-images-selector.d.ts +10 -0
  361. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -0
  362. package/dist/modes/interactive/components/show-images-selector.js +39 -0
  363. package/dist/modes/interactive/components/show-images-selector.js.map +1 -0
  364. package/dist/modes/interactive/components/skill-invocation-message.d.ts +17 -0
  365. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -0
  366. package/dist/modes/interactive/components/skill-invocation-message.js +47 -0
  367. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -0
  368. package/dist/modes/interactive/components/theme-selector.d.ts +11 -0
  369. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -0
  370. package/dist/modes/interactive/components/theme-selector.js +50 -0
  371. package/dist/modes/interactive/components/theme-selector.js.map +1 -0
  372. package/dist/modes/interactive/components/thinking-selector.d.ts +11 -0
  373. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -0
  374. package/dist/modes/interactive/components/thinking-selector.js +51 -0
  375. package/dist/modes/interactive/components/thinking-selector.js.map +1 -0
  376. package/dist/modes/interactive/components/tool-execution.d.ts +84 -0
  377. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -0
  378. package/dist/modes/interactive/components/tool-execution.js +832 -0
  379. package/dist/modes/interactive/components/tool-execution.js.map +1 -0
  380. package/dist/modes/interactive/components/tree-selector.d.ts +87 -0
  381. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -0
  382. package/dist/modes/interactive/components/tree-selector.js +1051 -0
  383. package/dist/modes/interactive/components/tree-selector.js.map +1 -0
  384. package/dist/modes/interactive/components/user-message-selector.d.ts +30 -0
  385. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -0
  386. package/dist/modes/interactive/components/user-message-selector.js +113 -0
  387. package/dist/modes/interactive/components/user-message-selector.js.map +1 -0
  388. package/dist/modes/interactive/components/user-message.d.ts +9 -0
  389. package/dist/modes/interactive/components/user-message.d.ts.map +1 -0
  390. package/dist/modes/interactive/components/user-message.js +28 -0
  391. package/dist/modes/interactive/components/user-message.js.map +1 -0
  392. package/dist/modes/interactive/components/visual-truncate.d.ts +24 -0
  393. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -0
  394. package/dist/modes/interactive/components/visual-truncate.js +33 -0
  395. package/dist/modes/interactive/components/visual-truncate.js.map +1 -0
  396. package/dist/modes/interactive/interactive-mode.d.ts +319 -0
  397. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -0
  398. package/dist/modes/interactive/interactive-mode.js +3868 -0
  399. package/dist/modes/interactive/interactive-mode.js.map +1 -0
  400. package/dist/modes/interactive/theme/dark.json +85 -0
  401. package/dist/modes/interactive/theme/light.json +84 -0
  402. package/dist/modes/interactive/theme/theme-schema.json +335 -0
  403. package/dist/modes/interactive/theme/theme.d.ts +78 -0
  404. package/dist/modes/interactive/theme/theme.d.ts.map +1 -0
  405. package/dist/modes/interactive/theme/theme.js +961 -0
  406. package/dist/modes/interactive/theme/theme.js.map +1 -0
  407. package/dist/modes/print-mode.d.ts +28 -0
  408. package/dist/modes/print-mode.d.ts.map +1 -0
  409. package/dist/modes/print-mode.js +101 -0
  410. package/dist/modes/print-mode.js.map +1 -0
  411. package/dist/modes/rpc/jsonl.d.ts +17 -0
  412. package/dist/modes/rpc/jsonl.d.ts.map +1 -0
  413. package/dist/modes/rpc/jsonl.js +49 -0
  414. package/dist/modes/rpc/jsonl.js.map +1 -0
  415. package/dist/modes/rpc/rpc-client.d.ts +217 -0
  416. package/dist/modes/rpc/rpc-client.d.ts.map +1 -0
  417. package/dist/modes/rpc/rpc-client.js +401 -0
  418. package/dist/modes/rpc/rpc-client.js.map +1 -0
  419. package/dist/modes/rpc/rpc-mode.d.ts +20 -0
  420. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -0
  421. package/dist/modes/rpc/rpc-mode.js +512 -0
  422. package/dist/modes/rpc/rpc-mode.js.map +1 -0
  423. package/dist/modes/rpc/rpc-types.d.ts +409 -0
  424. package/dist/modes/rpc/rpc-types.d.ts.map +1 -0
  425. package/dist/modes/rpc/rpc-types.js +8 -0
  426. package/dist/modes/rpc/rpc-types.js.map +1 -0
  427. package/dist/utils/changelog.d.ts +21 -0
  428. package/dist/utils/changelog.d.ts.map +1 -0
  429. package/dist/utils/changelog.js +87 -0
  430. package/dist/utils/changelog.js.map +1 -0
  431. package/dist/utils/child-process.d.ts +11 -0
  432. package/dist/utils/child-process.d.ts.map +1 -0
  433. package/dist/utils/child-process.js +78 -0
  434. package/dist/utils/child-process.js.map +1 -0
  435. package/dist/utils/clipboard-image.d.ts +11 -0
  436. package/dist/utils/clipboard-image.d.ts.map +1 -0
  437. package/dist/utils/clipboard-image.js +245 -0
  438. package/dist/utils/clipboard-image.js.map +1 -0
  439. package/dist/utils/clipboard-native.d.ts +8 -0
  440. package/dist/utils/clipboard-native.d.ts.map +1 -0
  441. package/dist/utils/clipboard-native.js +14 -0
  442. package/dist/utils/clipboard-native.js.map +1 -0
  443. package/dist/utils/clipboard.d.ts +2 -0
  444. package/dist/utils/clipboard.d.ts.map +1 -0
  445. package/dist/utils/clipboard.js +78 -0
  446. package/dist/utils/clipboard.js.map +1 -0
  447. package/dist/utils/exif-orientation.d.ts +5 -0
  448. package/dist/utils/exif-orientation.d.ts.map +1 -0
  449. package/dist/utils/exif-orientation.js +158 -0
  450. package/dist/utils/exif-orientation.js.map +1 -0
  451. package/dist/utils/frontmatter.d.ts +8 -0
  452. package/dist/utils/frontmatter.d.ts.map +1 -0
  453. package/dist/utils/frontmatter.js +26 -0
  454. package/dist/utils/frontmatter.js.map +1 -0
  455. package/dist/utils/git.d.ts +26 -0
  456. package/dist/utils/git.d.ts.map +1 -0
  457. package/dist/utils/git.js +163 -0
  458. package/dist/utils/git.js.map +1 -0
  459. package/dist/utils/image-convert.d.ts +9 -0
  460. package/dist/utils/image-convert.d.ts.map +1 -0
  461. package/dist/utils/image-convert.js +39 -0
  462. package/dist/utils/image-convert.js.map +1 -0
  463. package/dist/utils/image-resize.d.ts +36 -0
  464. package/dist/utils/image-resize.d.ts.map +1 -0
  465. package/dist/utils/image-resize.js +186 -0
  466. package/dist/utils/image-resize.js.map +1 -0
  467. package/dist/utils/mime.d.ts +2 -0
  468. package/dist/utils/mime.d.ts.map +1 -0
  469. package/dist/utils/mime.js +26 -0
  470. package/dist/utils/mime.js.map +1 -0
  471. package/dist/utils/photon.d.ts +21 -0
  472. package/dist/utils/photon.d.ts.map +1 -0
  473. package/dist/utils/photon.js +121 -0
  474. package/dist/utils/photon.js.map +1 -0
  475. package/dist/utils/shell.d.ts +26 -0
  476. package/dist/utils/shell.d.ts.map +1 -0
  477. package/dist/utils/shell.js +186 -0
  478. package/dist/utils/shell.js.map +1 -0
  479. package/dist/utils/sleep.d.ts +5 -0
  480. package/dist/utils/sleep.d.ts.map +1 -0
  481. package/dist/utils/sleep.js +17 -0
  482. package/dist/utils/sleep.js.map +1 -0
  483. package/dist/utils/tools-manager.d.ts +3 -0
  484. package/dist/utils/tools-manager.d.ts.map +1 -0
  485. package/dist/utils/tools-manager.js +252 -0
  486. package/dist/utils/tools-manager.js.map +1 -0
  487. package/docs/compaction.md +392 -0
  488. package/docs/custom-provider.md +596 -0
  489. package/docs/development.md +69 -0
  490. package/docs/extensions.md +2085 -0
  491. package/docs/images/doom-extension.png +0 -0
  492. package/docs/images/exy.png +0 -0
  493. package/docs/images/interactive-mode.png +0 -0
  494. package/docs/images/tree-view.png +0 -0
  495. package/docs/json.md +79 -0
  496. package/docs/keybindings.md +173 -0
  497. package/docs/models.md +335 -0
  498. package/docs/packages.md +218 -0
  499. package/docs/prompt-templates.md +67 -0
  500. package/docs/providers.md +195 -0
  501. package/docs/rpc.md +1354 -0
  502. package/docs/sdk.md +968 -0
  503. package/docs/session.md +412 -0
  504. package/docs/settings.md +234 -0
  505. package/docs/shell-aliases.md +13 -0
  506. package/docs/skills.md +231 -0
  507. package/docs/terminal-setup.md +106 -0
  508. package/docs/termux.md +127 -0
  509. package/docs/themes.md +295 -0
  510. package/docs/tmux.md +61 -0
  511. package/docs/tree.md +228 -0
  512. package/docs/tui.md +887 -0
  513. package/docs/windows.md +17 -0
  514. package/examples/README.md +25 -0
  515. package/examples/extensions/README.md +205 -0
  516. package/examples/extensions/antigravity-image-gen.ts +418 -0
  517. package/examples/extensions/auto-commit-on-exit.ts +49 -0
  518. package/examples/extensions/bash-spawn-hook.ts +30 -0
  519. package/examples/extensions/bookmark.ts +50 -0
  520. package/examples/extensions/built-in-tool-renderer.ts +246 -0
  521. package/examples/extensions/claude-rules.ts +86 -0
  522. package/examples/extensions/commands.ts +72 -0
  523. package/examples/extensions/confirm-destructive.ts +59 -0
  524. package/examples/extensions/custom-compaction.ts +114 -0
  525. package/examples/extensions/custom-footer.ts +64 -0
  526. package/examples/extensions/custom-header.ts +73 -0
  527. package/examples/extensions/custom-provider-anthropic/index.ts +604 -0
  528. package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
  529. package/examples/extensions/custom-provider-anthropic/package.json +19 -0
  530. package/examples/extensions/custom-provider-gitlab-duo/index.ts +349 -0
  531. package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
  532. package/examples/extensions/custom-provider-gitlab-duo/test.ts +82 -0
  533. package/examples/extensions/custom-provider-qwen-cli/index.ts +345 -0
  534. package/examples/extensions/custom-provider-qwen-cli/package.json +16 -0
  535. package/examples/extensions/dirty-repo-guard.ts +56 -0
  536. package/examples/extensions/doom-overlay/README.md +46 -0
  537. package/examples/extensions/doom-overlay/doom/build/doom.js +21 -0
  538. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  539. package/examples/extensions/doom-overlay/doom/build.sh +152 -0
  540. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -0
  541. package/examples/extensions/doom-overlay/doom-component.ts +132 -0
  542. package/examples/extensions/doom-overlay/doom-engine.ts +173 -0
  543. package/examples/extensions/doom-overlay/doom-keys.ts +104 -0
  544. package/examples/extensions/doom-overlay/index.ts +74 -0
  545. package/examples/extensions/doom-overlay/wad-finder.ts +51 -0
  546. package/examples/extensions/dynamic-resources/SKILL.md +8 -0
  547. package/examples/extensions/dynamic-resources/dynamic.json +79 -0
  548. package/examples/extensions/dynamic-resources/dynamic.md +5 -0
  549. package/examples/extensions/dynamic-resources/index.ts +15 -0
  550. package/examples/extensions/dynamic-tools.ts +74 -0
  551. package/examples/extensions/event-bus.ts +43 -0
  552. package/examples/extensions/file-trigger.ts +41 -0
  553. package/examples/extensions/git-checkpoint.ts +53 -0
  554. package/examples/extensions/handoff.ts +150 -0
  555. package/examples/extensions/hello.ts +25 -0
  556. package/examples/extensions/inline-bash.ts +94 -0
  557. package/examples/extensions/input-transform.ts +43 -0
  558. package/examples/extensions/interactive-shell.ts +196 -0
  559. package/examples/extensions/mac-system-theme.ts +47 -0
  560. package/examples/extensions/message-renderer.ts +59 -0
  561. package/examples/extensions/minimal-mode.ts +426 -0
  562. package/examples/extensions/modal-editor.ts +85 -0
  563. package/examples/extensions/model-status.ts +31 -0
  564. package/examples/extensions/notify.ts +55 -0
  565. package/examples/extensions/overlay-qa-tests.ts +1348 -0
  566. package/examples/extensions/overlay-test.ts +150 -0
  567. package/examples/extensions/permission-gate.ts +34 -0
  568. package/examples/extensions/pirate.ts +47 -0
  569. package/examples/extensions/plan-mode/README.md +65 -0
  570. package/examples/extensions/plan-mode/index.ts +340 -0
  571. package/examples/extensions/plan-mode/utils.ts +168 -0
  572. package/examples/extensions/preset.ts +397 -0
  573. package/examples/extensions/protected-paths.ts +30 -0
  574. package/examples/extensions/provider-payload.ts +14 -0
  575. package/examples/extensions/qna.ts +119 -0
  576. package/examples/extensions/question.ts +264 -0
  577. package/examples/extensions/questionnaire.ts +427 -0
  578. package/examples/extensions/rainbow-editor.ts +88 -0
  579. package/examples/extensions/reload-runtime.ts +37 -0
  580. package/examples/extensions/rpc-demo.ts +124 -0
  581. package/examples/extensions/sandbox/index.ts +317 -0
  582. package/examples/extensions/sandbox/package-lock.json +92 -0
  583. package/examples/extensions/sandbox/package.json +19 -0
  584. package/examples/extensions/send-user-message.ts +97 -0
  585. package/examples/extensions/session-name.ts +27 -0
  586. package/examples/extensions/shutdown-command.ts +63 -0
  587. package/examples/extensions/snake.ts +343 -0
  588. package/examples/extensions/space-invaders.ts +560 -0
  589. package/examples/extensions/ssh.ts +220 -0
  590. package/examples/extensions/status-line.ts +40 -0
  591. package/examples/extensions/subagent/README.md +172 -0
  592. package/examples/extensions/subagent/agents/planner.md +37 -0
  593. package/examples/extensions/subagent/agents/reviewer.md +35 -0
  594. package/examples/extensions/subagent/agents/scout.md +50 -0
  595. package/examples/extensions/subagent/agents/worker.md +24 -0
  596. package/examples/extensions/subagent/agents.ts +126 -0
  597. package/examples/extensions/subagent/index.ts +986 -0
  598. package/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
  599. package/examples/extensions/subagent/prompts/implement.md +10 -0
  600. package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
  601. package/examples/extensions/summarize.ts +195 -0
  602. package/examples/extensions/system-prompt-header.ts +17 -0
  603. package/examples/extensions/timed-confirm.ts +70 -0
  604. package/examples/extensions/titlebar-spinner.ts +58 -0
  605. package/examples/extensions/todo.ts +299 -0
  606. package/examples/extensions/tool-override.ts +144 -0
  607. package/examples/extensions/tools.ts +146 -0
  608. package/examples/extensions/trigger-compact.ts +40 -0
  609. package/examples/extensions/truncated-tool.ts +195 -0
  610. package/examples/extensions/widget-placement.ts +17 -0
  611. package/examples/extensions/with-deps/index.ts +32 -0
  612. package/examples/extensions/with-deps/package-lock.json +31 -0
  613. package/examples/extensions/with-deps/package.json +22 -0
  614. package/examples/rpc-extension-ui.ts +632 -0
  615. package/examples/sdk/01-minimal.ts +22 -0
  616. package/examples/sdk/02-custom-model.ts +49 -0
  617. package/examples/sdk/03-custom-prompt.ts +55 -0
  618. package/examples/sdk/04-skills.ts +46 -0
  619. package/examples/sdk/05-tools.ts +56 -0
  620. package/examples/sdk/06-extensions.ts +88 -0
  621. package/examples/sdk/07-context-files.ts +40 -0
  622. package/examples/sdk/08-prompt-templates.ts +47 -0
  623. package/examples/sdk/09-api-keys-and-oauth.ts +48 -0
  624. package/examples/sdk/10-settings.ts +51 -0
  625. package/examples/sdk/11-sessions.ts +48 -0
  626. package/examples/sdk/12-full-control.ts +82 -0
  627. package/examples/sdk/README.md +144 -0
  628. package/package.json +99 -0
@@ -0,0 +1,2085 @@
1
+ > pi can create extensions. Ask it to build one for your use case.
2
+
3
+ # Extensions
4
+
5
+ Extensions are TypeScript modules that extend pi'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 `~/.pi/agent/extensions/` (global) or `.pi/extensions/` (project-local) for auto-discovery. Use `pi -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
+ - [Session Events](#session-events)
41
+ - [Agent Events](#agent-events)
42
+ - [Tool Events](#tool-events)
43
+ - [ExtensionContext](#extensioncontext)
44
+ - [ExtensionCommandContext](#extensioncommandcontext)
45
+ - [ExtensionAPI Methods](#extensionapi-methods)
46
+ - [State Management](#state-management)
47
+ - [Custom Tools](#custom-tools)
48
+ - [Custom UI](#custom-ui)
49
+ - [Error Handling](#error-handling)
50
+ - [Mode Behavior](#mode-behavior)
51
+ - [Examples Reference](#examples-reference)
52
+
53
+ ## Quick Start
54
+
55
+ Create `~/.pi/agent/extensions/my-extension.ts`:
56
+
57
+ ```typescript
58
+ import type { ExtensionAPI } from "@avadisabelle/ava-pi-coding-agent";
59
+ import { Type } from "@sinclair/typebox";
60
+
61
+ export default function (pi: ExtensionAPI) {
62
+ // React to events
63
+ pi.on("session_start", async (_event, ctx) => {
64
+ ctx.ui.notify("Extension loaded!", "info");
65
+ });
66
+
67
+ pi.on("tool_call", async (event, ctx) => {
68
+ if (event.toolName === "bash" && event.input.command?.includes("rm -rf")) {
69
+ const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?");
70
+ if (!ok) return { block: true, reason: "Blocked by user" };
71
+ }
72
+ });
73
+
74
+ // Register a custom tool
75
+ pi.registerTool({
76
+ name: "greet",
77
+ label: "Greet",
78
+ description: "Greet someone by name",
79
+ parameters: Type.Object({
80
+ name: Type.String({ description: "Name to greet" }),
81
+ }),
82
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
83
+ return {
84
+ content: [{ type: "text", text: `Hello, ${params.name}!` }],
85
+ details: {},
86
+ };
87
+ },
88
+ });
89
+
90
+ // Register a command
91
+ pi.registerCommand("hello", {
92
+ description: "Say hello",
93
+ handler: async (args, ctx) => {
94
+ ctx.ui.notify(`Hello ${args || "world"}!`, "info");
95
+ },
96
+ });
97
+ }
98
+ ```
99
+
100
+ Test with `--extension` (or `-e`) flag:
101
+
102
+ ```bash
103
+ pi -e ./my-extension.ts
104
+ ```
105
+
106
+ ## Extension Locations
107
+
108
+ > **Security:** Extensions run with your full system permissions and can execute arbitrary code. Only install from sources you trust.
109
+
110
+ Extensions are auto-discovered from:
111
+
112
+ | Location | Scope |
113
+ |----------|-------|
114
+ | `~/.pi/agent/extensions/*.ts` | Global (all projects) |
115
+ | `~/.pi/agent/extensions/*/index.ts` | Global (subdirectory) |
116
+ | `.pi/extensions/*.ts` | Project-local |
117
+ | `.pi/extensions/*/index.ts` | Project-local (subdirectory) |
118
+
119
+ Additional paths via `settings.json`:
120
+
121
+ ```json
122
+ {
123
+ "packages": [
124
+ "npm:@foo/bar@1.0.0",
125
+ "git:github.com/user/repo@v1"
126
+ ],
127
+ "extensions": [
128
+ "/path/to/local/extension.ts",
129
+ "/path/to/local/extension/dir"
130
+ ]
131
+ }
132
+ ```
133
+
134
+ To share extensions via npm or git as pi packages, see [packages.md](packages.md).
135
+
136
+ ## Available Imports
137
+
138
+ | Package | Purpose |
139
+ |---------|---------|
140
+ | `@avadisabelle/ava-pi-coding-agent` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) |
141
+ | `@sinclair/typebox` | Schema definitions for tool parameters |
142
+ | `@avadisabelle/ava-pi-ai` | AI utilities (`StringEnum` for Google-compatible enums) |
143
+ | `@avadisabelle/ava-pi-tui` | TUI components for custom rendering |
144
+
145
+ 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.
146
+
147
+ Node.js built-ins (`node:fs`, `node:path`, etc.) are also available.
148
+
149
+ ## Writing an Extension
150
+
151
+ An extension exports a default function that receives `ExtensionAPI`:
152
+
153
+ ```typescript
154
+ import type { ExtensionAPI } from "@avadisabelle/ava-pi-coding-agent";
155
+
156
+ export default function (pi: ExtensionAPI) {
157
+ // Subscribe to events
158
+ pi.on("event_name", async (event, ctx) => {
159
+ // ctx.ui for user interaction
160
+ const ok = await ctx.ui.confirm("Title", "Are you sure?");
161
+ ctx.ui.notify("Done!", "success");
162
+ ctx.ui.setStatus("my-ext", "Processing..."); // Footer status
163
+ ctx.ui.setWidget("my-ext", ["Line 1", "Line 2"]); // Widget above editor (default)
164
+ });
165
+
166
+ // Register tools, commands, shortcuts, flags
167
+ pi.registerTool({ ... });
168
+ pi.registerCommand("name", { ... });
169
+ pi.registerShortcut("ctrl+x", { ... });
170
+ pi.registerFlag("my-flag", { ... });
171
+ }
172
+ ```
173
+
174
+ Extensions are loaded via [jiti](https://github.com/unjs/jiti), so TypeScript works without compilation.
175
+
176
+ ### Extension Styles
177
+
178
+ **Single file** - simplest, for small extensions:
179
+
180
+ ```
181
+ ~/.pi/agent/extensions/
182
+ └── my-extension.ts
183
+ ```
184
+
185
+ **Directory with index.ts** - for multi-file extensions:
186
+
187
+ ```
188
+ ~/.pi/agent/extensions/
189
+ └── my-extension/
190
+ ├── index.ts # Entry point (exports default function)
191
+ ├── tools.ts # Helper module
192
+ └── utils.ts # Helper module
193
+ ```
194
+
195
+ **Package with dependencies** - for extensions that need npm packages:
196
+
197
+ ```
198
+ ~/.pi/agent/extensions/
199
+ └── my-extension/
200
+ ├── package.json # Declares dependencies and entry points
201
+ ├── package-lock.json
202
+ ├── node_modules/ # After npm install
203
+ └── src/
204
+ └── index.ts
205
+ ```
206
+
207
+ ```json
208
+ // package.json
209
+ {
210
+ "name": "my-extension",
211
+ "dependencies": {
212
+ "zod": "^3.0.0",
213
+ "chalk": "^5.0.0"
214
+ },
215
+ "pi": {
216
+ "extensions": ["./src/index.ts"]
217
+ }
218
+ }
219
+ ```
220
+
221
+ Run `npm install` in the extension directory, then imports from `node_modules/` work automatically.
222
+
223
+ ## Events
224
+
225
+ ### Lifecycle Overview
226
+
227
+ ```
228
+ pi starts (CLI only)
229
+
230
+ ├─► session_directory (CLI startup only, no ctx)
231
+ └─► session_start
232
+
233
+
234
+ user sends prompt ─────────────────────────────────────────┐
235
+ │ │
236
+ ├─► (extension commands checked first, bypass if found) │
237
+ ├─► input (can intercept, transform, or handle) │
238
+ ├─► (skill/template expansion if not handled) │
239
+ ├─► before_agent_start (can inject message, modify system prompt)
240
+ ├─► agent_start │
241
+ ├─► message_start / message_update / message_end │
242
+ │ │
243
+ │ ┌─── turn (repeats while LLM calls tools) ───┐ │
244
+ │ │ │ │
245
+ │ ├─► turn_start │ │
246
+ │ ├─► context (can modify messages) │ │
247
+ │ ├─► before_provider_request (can inspect or replace payload)
248
+ │ │ │ │
249
+ │ │ LLM responds, may call tools: │ │
250
+ │ │ ├─► tool_execution_start │ │
251
+ │ │ ├─► tool_call (can block) │ │
252
+ │ │ ├─► tool_execution_update │ │
253
+ │ │ ├─► tool_result (can modify) │ │
254
+ │ │ └─► tool_execution_end │ │
255
+ │ │ │ │
256
+ │ └─► turn_end │ │
257
+ │ │
258
+ └─► agent_end │
259
+
260
+ user sends another prompt ◄────────────────────────────────┘
261
+
262
+ /new (new session) or /resume (switch session)
263
+ ├─► session_before_switch (can cancel)
264
+ └─► session_switch
265
+
266
+ /fork
267
+ ├─► session_before_fork (can cancel)
268
+ └─► session_fork
269
+
270
+ /compact or auto-compaction
271
+ ├─► session_before_compact (can cancel or customize)
272
+ └─► session_compact
273
+
274
+ /tree navigation
275
+ ├─► session_before_tree (can cancel or customize)
276
+ └─► session_tree
277
+
278
+ /model or Ctrl+P (model selection/cycling)
279
+ └─► model_select
280
+
281
+ exit (Ctrl+C, Ctrl+D)
282
+ └─► session_shutdown
283
+ ```
284
+
285
+ ### Session Events
286
+
287
+ See [session.md](session.md) for session storage internals and the SessionManager API.
288
+
289
+ #### session_directory
290
+
291
+ Fired by the `pi` CLI during startup session resolution, before the initial session manager is created.
292
+
293
+ This event is:
294
+ - CLI-only. It is not emitted in SDK mode.
295
+ - Startup-only. It is not emitted for later interactive `/new` or `/resume` actions.
296
+ - Bypassed when `--session-dir` is provided.
297
+ - Special-cased to receive no `ctx` argument.
298
+
299
+ If multiple extensions return `sessionDir`, the last one wins.
300
+
301
+ ```typescript
302
+ pi.on("session_directory", async (event) => {
303
+ return {
304
+ sessionDir: `/tmp/pi-sessions/${encodeURIComponent(event.cwd)}`,
305
+ };
306
+ });
307
+ ```
308
+
309
+ #### session_start
310
+
311
+ Fired on initial session load.
312
+
313
+ ```typescript
314
+ pi.on("session_start", async (_event, ctx) => {
315
+ ctx.ui.notify(`Session: ${ctx.sessionManager.getSessionFile() ?? "ephemeral"}`, "info");
316
+ });
317
+ ```
318
+
319
+ #### session_before_switch / session_switch
320
+
321
+ Fired when starting a new session (`/new`) or switching sessions (`/resume`).
322
+
323
+ ```typescript
324
+ pi.on("session_before_switch", async (event, ctx) => {
325
+ // event.reason - "new" or "resume"
326
+ // event.targetSessionFile - session we're switching to (only for "resume")
327
+
328
+ if (event.reason === "new") {
329
+ const ok = await ctx.ui.confirm("Clear?", "Delete all messages?");
330
+ if (!ok) return { cancel: true };
331
+ }
332
+ });
333
+
334
+ pi.on("session_switch", async (event, ctx) => {
335
+ // event.reason - "new" or "resume"
336
+ // event.previousSessionFile - session we came from
337
+ });
338
+ ```
339
+
340
+ #### session_before_fork / session_fork
341
+
342
+ Fired when forking via `/fork`.
343
+
344
+ ```typescript
345
+ pi.on("session_before_fork", async (event, ctx) => {
346
+ // event.entryId - ID of the entry being forked from
347
+ return { cancel: true }; // Cancel fork
348
+ // OR
349
+ return { skipConversationRestore: true }; // Fork but don't rewind messages
350
+ });
351
+
352
+ pi.on("session_fork", async (event, ctx) => {
353
+ // event.previousSessionFile - previous session file
354
+ });
355
+ ```
356
+
357
+ #### session_before_compact / session_compact
358
+
359
+ Fired on compaction. See [compaction.md](compaction.md) for details.
360
+
361
+ ```typescript
362
+ pi.on("session_before_compact", async (event, ctx) => {
363
+ const { preparation, branchEntries, customInstructions, signal } = event;
364
+
365
+ // Cancel:
366
+ return { cancel: true };
367
+
368
+ // Custom summary:
369
+ return {
370
+ compaction: {
371
+ summary: "...",
372
+ firstKeptEntryId: preparation.firstKeptEntryId,
373
+ tokensBefore: preparation.tokensBefore,
374
+ }
375
+ };
376
+ });
377
+
378
+ pi.on("session_compact", async (event, ctx) => {
379
+ // event.compactionEntry - the saved compaction
380
+ // event.fromExtension - whether extension provided it
381
+ });
382
+ ```
383
+
384
+ #### session_before_tree / session_tree
385
+
386
+ Fired on `/tree` navigation. See [tree.md](tree.md) for tree navigation concepts.
387
+
388
+ ```typescript
389
+ pi.on("session_before_tree", async (event, ctx) => {
390
+ const { preparation, signal } = event;
391
+ return { cancel: true };
392
+ // OR provide custom summary:
393
+ return { summary: { summary: "...", details: {} } };
394
+ });
395
+
396
+ pi.on("session_tree", async (event, ctx) => {
397
+ // event.newLeafId, oldLeafId, summaryEntry, fromExtension
398
+ });
399
+ ```
400
+
401
+ #### session_shutdown
402
+
403
+ Fired on exit (Ctrl+C, Ctrl+D, SIGTERM).
404
+
405
+ ```typescript
406
+ pi.on("session_shutdown", async (_event, ctx) => {
407
+ // Cleanup, save state, etc.
408
+ });
409
+ ```
410
+
411
+ ### Agent Events
412
+
413
+ #### before_agent_start
414
+
415
+ Fired after user submits prompt, before agent loop. Can inject a message and/or modify the system prompt.
416
+
417
+ ```typescript
418
+ pi.on("before_agent_start", async (event, ctx) => {
419
+ // event.prompt - user's prompt text
420
+ // event.images - attached images (if any)
421
+ // event.systemPrompt - current system prompt
422
+
423
+ return {
424
+ // Inject a persistent message (stored in session, sent to LLM)
425
+ message: {
426
+ customType: "my-extension",
427
+ content: "Additional context for the LLM",
428
+ display: true,
429
+ },
430
+ // Replace the system prompt for this turn (chained across extensions)
431
+ systemPrompt: event.systemPrompt + "\n\nExtra instructions for this turn...",
432
+ };
433
+ });
434
+ ```
435
+
436
+ #### agent_start / agent_end
437
+
438
+ Fired once per user prompt.
439
+
440
+ ```typescript
441
+ pi.on("agent_start", async (_event, ctx) => {});
442
+
443
+ pi.on("agent_end", async (event, ctx) => {
444
+ // event.messages - messages from this prompt
445
+ });
446
+ ```
447
+
448
+ #### turn_start / turn_end
449
+
450
+ Fired for each turn (one LLM response + tool calls).
451
+
452
+ ```typescript
453
+ pi.on("turn_start", async (event, ctx) => {
454
+ // event.turnIndex, event.timestamp
455
+ });
456
+
457
+ pi.on("turn_end", async (event, ctx) => {
458
+ // event.turnIndex, event.message, event.toolResults
459
+ });
460
+ ```
461
+
462
+ #### message_start / message_update / message_end
463
+
464
+ Fired for message lifecycle updates.
465
+
466
+ - `message_start` and `message_end` fire for user, assistant, and toolResult messages.
467
+ - `message_update` fires for assistant streaming updates.
468
+
469
+ ```typescript
470
+ pi.on("message_start", async (event, ctx) => {
471
+ // event.message
472
+ });
473
+
474
+ pi.on("message_update", async (event, ctx) => {
475
+ // event.message
476
+ // event.assistantMessageEvent (token-by-token stream event)
477
+ });
478
+
479
+ pi.on("message_end", async (event, ctx) => {
480
+ // event.message
481
+ });
482
+ ```
483
+
484
+ #### tool_execution_start / tool_execution_update / tool_execution_end
485
+
486
+ Fired for tool execution lifecycle updates.
487
+
488
+ In parallel tool mode:
489
+ - `tool_execution_start` is emitted in assistant source order during the preflight phase
490
+ - `tool_execution_update` events may interleave across tools
491
+ - `tool_execution_end` is emitted in assistant source order, matching final tool result message order
492
+
493
+ ```typescript
494
+ pi.on("tool_execution_start", async (event, ctx) => {
495
+ // event.toolCallId, event.toolName, event.args
496
+ });
497
+
498
+ pi.on("tool_execution_update", async (event, ctx) => {
499
+ // event.toolCallId, event.toolName, event.args, event.partialResult
500
+ });
501
+
502
+ pi.on("tool_execution_end", async (event, ctx) => {
503
+ // event.toolCallId, event.toolName, event.result, event.isError
504
+ });
505
+ ```
506
+
507
+ #### context
508
+
509
+ Fired before each LLM call. Modify messages non-destructively. See [session.md](session.md) for message types.
510
+
511
+ ```typescript
512
+ pi.on("context", async (event, ctx) => {
513
+ // event.messages - deep copy, safe to modify
514
+ const filtered = event.messages.filter(m => !shouldPrune(m));
515
+ return { messages: filtered };
516
+ });
517
+ ```
518
+
519
+ #### before_provider_request
520
+
521
+ 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.
522
+
523
+ ```typescript
524
+ pi.on("before_provider_request", (event, ctx) => {
525
+ console.log(JSON.stringify(event.payload, null, 2));
526
+
527
+ // Optional: replace payload
528
+ // return { ...event.payload, temperature: 0 };
529
+ });
530
+ ```
531
+
532
+ This is mainly useful for debugging provider serialization and cache behavior.
533
+
534
+ ### Model Events
535
+
536
+ #### model_select
537
+
538
+ Fired when the model changes via `/model` command, model cycling (`Ctrl+P`), or session restore.
539
+
540
+ ```typescript
541
+ pi.on("model_select", async (event, ctx) => {
542
+ // event.model - newly selected model
543
+ // event.previousModel - previous model (undefined if first selection)
544
+ // event.source - "set" | "cycle" | "restore"
545
+
546
+ const prev = event.previousModel
547
+ ? `${event.previousModel.provider}/${event.previousModel.id}`
548
+ : "none";
549
+ const next = `${event.model.provider}/${event.model.id}`;
550
+
551
+ ctx.ui.notify(`Model changed (${event.source}): ${prev} -> ${next}`, "info");
552
+ });
553
+ ```
554
+
555
+ Use this to update UI elements (status bars, footers) or perform model-specific initialization when the active model changes.
556
+
557
+ ### Tool Events
558
+
559
+ #### tool_call
560
+
561
+ Fired after `tool_execution_start`, before the tool executes. **Can block.** Use `isToolCallEventType` to narrow and get typed inputs.
562
+
563
+ Before `tool_call` runs, pi 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.
564
+
565
+ 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`.
566
+
567
+ ```typescript
568
+ import { isToolCallEventType } from "@avadisabelle/ava-pi-coding-agent";
569
+
570
+ pi.on("tool_call", async (event, ctx) => {
571
+ // event.toolName - "bash", "read", "write", "edit", etc.
572
+ // event.toolCallId
573
+ // event.input - tool parameters
574
+
575
+ // Built-in tools: no type params needed
576
+ if (isToolCallEventType("bash", event)) {
577
+ // event.input is { command: string; timeout?: number }
578
+ if (event.input.command.includes("rm -rf")) {
579
+ return { block: true, reason: "Dangerous command" };
580
+ }
581
+ }
582
+
583
+ if (isToolCallEventType("read", event)) {
584
+ // event.input is { path: string; offset?: number; limit?: number }
585
+ console.log(`Reading: ${event.input.path}`);
586
+ }
587
+ });
588
+ ```
589
+
590
+ #### Typing custom tool input
591
+
592
+ Custom tools should export their input type:
593
+
594
+ ```typescript
595
+ // my-extension.ts
596
+ export type MyToolInput = Static<typeof myToolSchema>;
597
+ ```
598
+
599
+ Use `isToolCallEventType` with explicit type parameters:
600
+
601
+ ```typescript
602
+ import { isToolCallEventType } from "@avadisabelle/ava-pi-coding-agent";
603
+ import type { MyToolInput } from "my-extension";
604
+
605
+ pi.on("tool_call", (event) => {
606
+ if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) {
607
+ event.input.action; // typed
608
+ }
609
+ });
610
+ ```
611
+
612
+ #### tool_result
613
+
614
+ Fired after tool execution finishes and before `tool_execution_end` plus the final tool result message events are emitted. **Can modify result.**
615
+
616
+ `tool_result` handlers chain like middleware:
617
+ - Handlers run in extension load order
618
+ - Each handler sees the latest result after previous handler changes
619
+ - Handlers can return partial patches (`content`, `details`, or `isError`); omitted fields keep their current values
620
+
621
+ ```typescript
622
+ import { isBashToolResult } from "@avadisabelle/ava-pi-coding-agent";
623
+
624
+ pi.on("tool_result", async (event, ctx) => {
625
+ // event.toolName, event.toolCallId, event.input
626
+ // event.content, event.details, event.isError
627
+
628
+ if (isBashToolResult(event)) {
629
+ // event.details is typed as BashToolDetails
630
+ }
631
+
632
+ // Modify result:
633
+ return { content: [...], details: {...}, isError: false };
634
+ });
635
+ ```
636
+
637
+ ### User Bash Events
638
+
639
+ #### user_bash
640
+
641
+ Fired when user executes `!` or `!!` commands. **Can intercept.**
642
+
643
+ ```typescript
644
+ import { createLocalBashOperations } from "@avadisabelle/ava-pi-coding-agent";
645
+
646
+ pi.on("user_bash", (event, ctx) => {
647
+ // event.command - the bash command
648
+ // event.excludeFromContext - true if !! prefix
649
+ // event.cwd - working directory
650
+
651
+ // Option 1: Provide custom operations (e.g., SSH)
652
+ return { operations: remoteBashOps };
653
+
654
+ // Option 2: Wrap pi's built-in local bash backend
655
+ const local = createLocalBashOperations();
656
+ return {
657
+ operations: {
658
+ exec(command, cwd, options) {
659
+ return local.exec(`source ~/.profile\n${command}`, cwd, options);
660
+ }
661
+ }
662
+ };
663
+
664
+ // Option 3: Full replacement - return result directly
665
+ return { result: { output: "...", exitCode: 0, cancelled: false, truncated: false } };
666
+ });
667
+ ```
668
+
669
+ ### Input Events
670
+
671
+ #### input
672
+
673
+ 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.
674
+
675
+ **Processing order:**
676
+ 1. Extension commands (`/cmd`) checked first - if found, handler runs and input event is skipped
677
+ 2. `input` event fires - can intercept, transform, or handle
678
+ 3. If not handled: skill commands (`/skill:name`) expanded to skill content
679
+ 4. If not handled: prompt templates (`/template`) expanded to template content
680
+ 5. Agent processing begins (`before_agent_start`, etc.)
681
+
682
+ ```typescript
683
+ pi.on("input", async (event, ctx) => {
684
+ // event.text - raw input (before skill/template expansion)
685
+ // event.images - attached images, if any
686
+ // event.source - "interactive" (typed), "rpc" (API), or "extension" (via sendUserMessage)
687
+
688
+ // Transform: rewrite input before expansion
689
+ if (event.text.startsWith("?quick "))
690
+ return { action: "transform", text: `Respond briefly: ${event.text.slice(7)}` };
691
+
692
+ // Handle: respond without LLM (extension shows its own feedback)
693
+ if (event.text === "ping") {
694
+ ctx.ui.notify("pong", "info");
695
+ return { action: "handled" };
696
+ }
697
+
698
+ // Route by source: skip processing for extension-injected messages
699
+ if (event.source === "extension") return { action: "continue" };
700
+
701
+ // Intercept skill commands before expansion
702
+ if (event.text.startsWith("/skill:")) {
703
+ // Could transform, block, or let pass through
704
+ }
705
+
706
+ return { action: "continue" }; // Default: pass through to expansion
707
+ });
708
+ ```
709
+
710
+ **Results:**
711
+ - `continue` - pass through unchanged (default if handler returns nothing)
712
+ - `transform` - modify text/images, then continue to expansion
713
+ - `handled` - skip agent entirely (first handler to return this wins)
714
+
715
+ Transforms chain across handlers. See [input-transform.ts](../examples/extensions/input-transform.ts).
716
+
717
+ ## ExtensionContext
718
+
719
+ All handlers except `session_directory` receive `ctx: ExtensionContext`.
720
+
721
+ `session_directory` is a CLI startup hook and receives only the event.
722
+
723
+ ### ctx.ui
724
+
725
+ UI methods for user interaction. See [Custom UI](#custom-ui) for full details.
726
+
727
+ ### ctx.hasUI
728
+
729
+ `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)).
730
+
731
+ ### ctx.cwd
732
+
733
+ Current working directory.
734
+
735
+ ### ctx.sessionManager
736
+
737
+ Read-only access to session state. See [session.md](session.md) for the full SessionManager API and entry types.
738
+
739
+ 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.
740
+
741
+ ```typescript
742
+ ctx.sessionManager.getEntries() // All entries
743
+ ctx.sessionManager.getBranch() // Current branch
744
+ ctx.sessionManager.getLeafId() // Current leaf entry ID
745
+ ```
746
+
747
+ ### ctx.modelRegistry / ctx.model
748
+
749
+ Access to models and API keys.
750
+
751
+ ### ctx.isIdle() / ctx.abort() / ctx.hasPendingMessages()
752
+
753
+ Control flow helpers.
754
+
755
+ ### ctx.shutdown()
756
+
757
+ Request a graceful shutdown of pi.
758
+
759
+ - **Interactive mode:** Deferred until the agent becomes idle (after processing all queued steering and follow-up messages).
760
+ - **RPC mode:** Deferred until the next idle state (after completing the current command response, when waiting for the next command).
761
+ - **Print mode:** No-op. The process exits automatically when all prompts are processed.
762
+
763
+ Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands, shortcuts).
764
+
765
+ ```typescript
766
+ pi.on("tool_call", (event, ctx) => {
767
+ if (isFatal(event.input)) {
768
+ ctx.shutdown();
769
+ }
770
+ });
771
+ ```
772
+
773
+ ### ctx.getContextUsage()
774
+
775
+ Returns current context usage for the active model. Uses last assistant usage when available, then estimates tokens for trailing messages.
776
+
777
+ ```typescript
778
+ const usage = ctx.getContextUsage();
779
+ if (usage && usage.tokens > 100_000) {
780
+ // ...
781
+ }
782
+ ```
783
+
784
+ ### ctx.compact()
785
+
786
+ Trigger compaction without awaiting completion. Use `onComplete` and `onError` for follow-up actions.
787
+
788
+ ```typescript
789
+ ctx.compact({
790
+ customInstructions: "Focus on recent changes",
791
+ onComplete: (result) => {
792
+ ctx.ui.notify("Compaction completed", "info");
793
+ },
794
+ onError: (error) => {
795
+ ctx.ui.notify(`Compaction failed: ${error.message}`, "error");
796
+ },
797
+ });
798
+ ```
799
+
800
+ ### ctx.getSystemPrompt()
801
+
802
+ Returns the current effective system prompt. This includes any modifications made by `before_agent_start` handlers for the current turn.
803
+
804
+ ```typescript
805
+ pi.on("before_agent_start", (event, ctx) => {
806
+ const prompt = ctx.getSystemPrompt();
807
+ console.log(`System prompt length: ${prompt.length}`);
808
+ });
809
+ ```
810
+
811
+ ## ExtensionCommandContext
812
+
813
+ Command handlers receive `ExtensionCommandContext`, which extends `ExtensionContext` with session control methods. These are only available in commands because they can deadlock if called from event handlers.
814
+
815
+ ### ctx.waitForIdle()
816
+
817
+ Wait for the agent to finish streaming:
818
+
819
+ ```typescript
820
+ pi.registerCommand("my-cmd", {
821
+ handler: async (args, ctx) => {
822
+ await ctx.waitForIdle();
823
+ // Agent is now idle, safe to modify session
824
+ },
825
+ });
826
+ ```
827
+
828
+ ### ctx.newSession(options?)
829
+
830
+ Create a new session:
831
+
832
+ ```typescript
833
+ const result = await ctx.newSession({
834
+ parentSession: ctx.sessionManager.getSessionFile(),
835
+ setup: async (sm) => {
836
+ sm.appendMessage({
837
+ role: "user",
838
+ content: [{ type: "text", text: "Context from previous session..." }],
839
+ timestamp: Date.now(),
840
+ });
841
+ },
842
+ });
843
+
844
+ if (result.cancelled) {
845
+ // An extension cancelled the new session
846
+ }
847
+ ```
848
+
849
+ ### ctx.fork(entryId)
850
+
851
+ Fork from a specific entry, creating a new session file:
852
+
853
+ ```typescript
854
+ const result = await ctx.fork("entry-id-123");
855
+ if (!result.cancelled) {
856
+ // Now in the forked session
857
+ }
858
+ ```
859
+
860
+ ### ctx.navigateTree(targetId, options?)
861
+
862
+ Navigate to a different point in the session tree:
863
+
864
+ ```typescript
865
+ const result = await ctx.navigateTree("entry-id-456", {
866
+ summarize: true,
867
+ customInstructions: "Focus on error handling changes",
868
+ replaceInstructions: false, // true = replace default prompt entirely
869
+ label: "review-checkpoint",
870
+ });
871
+ ```
872
+
873
+ Options:
874
+ - `summarize`: Whether to generate a summary of the abandoned branch
875
+ - `customInstructions`: Custom instructions for the summarizer
876
+ - `replaceInstructions`: If true, `customInstructions` replaces the default prompt instead of being appended
877
+ - `label`: Label to attach to the branch summary entry (or target entry if not summarizing)
878
+
879
+ ### ctx.reload()
880
+
881
+ Run the same reload flow as `/reload`.
882
+
883
+ ```typescript
884
+ pi.registerCommand("reload-runtime", {
885
+ description: "Reload extensions, skills, prompts, and themes",
886
+ handler: async (_args, ctx) => {
887
+ await ctx.reload();
888
+ return;
889
+ },
890
+ });
891
+ ```
892
+
893
+ Important behavior:
894
+ - `await ctx.reload()` emits `session_shutdown` for the current extension runtime
895
+ - It then reloads resources and emits `session_start` (and `resources_discover` with reason `"reload"`) for the new runtime
896
+ - The currently running command handler still continues in the old call frame
897
+ - Code after `await ctx.reload()` still runs from the pre-reload version
898
+ - Code after `await ctx.reload()` must not assume old in-memory extension state is still valid
899
+ - After the handler returns, future commands/events/tool calls use the new extension version
900
+
901
+ For predictable behavior, treat reload as terminal for that handler (`await ctx.reload(); return;`).
902
+
903
+ 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.
904
+
905
+ Example tool the LLM can call to trigger reload:
906
+
907
+ ```typescript
908
+ import type { ExtensionAPI } from "@avadisabelle/ava-pi-coding-agent";
909
+ import { Type } from "@sinclair/typebox";
910
+
911
+ export default function (pi: ExtensionAPI) {
912
+ pi.registerCommand("reload-runtime", {
913
+ description: "Reload extensions, skills, prompts, and themes",
914
+ handler: async (_args, ctx) => {
915
+ await ctx.reload();
916
+ return;
917
+ },
918
+ });
919
+
920
+ pi.registerTool({
921
+ name: "reload_runtime",
922
+ label: "Reload Runtime",
923
+ description: "Reload extensions, skills, prompts, and themes",
924
+ parameters: Type.Object({}),
925
+ async execute() {
926
+ pi.sendUserMessage("/reload-runtime", { deliverAs: "followUp" });
927
+ return {
928
+ content: [{ type: "text", text: "Queued /reload-runtime as a follow-up command." }],
929
+ };
930
+ },
931
+ });
932
+ }
933
+ ```
934
+
935
+ ## ExtensionAPI Methods
936
+
937
+ ### pi.on(event, handler)
938
+
939
+ Subscribe to events. See [Events](#events) for event types and return values.
940
+
941
+ ### pi.registerTool(definition)
942
+
943
+ Register a custom tool callable by the LLM. See [Custom Tools](#custom-tools) for full details.
944
+
945
+ `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`.
946
+
947
+ Use `pi.setActiveTools()` to enable or disable tools (including dynamically added tools) at runtime.
948
+
949
+ 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.
950
+
951
+ See [dynamic-tools.ts](../examples/extensions/dynamic-tools.ts) for a full example.
952
+
953
+ ```typescript
954
+ import { Type } from "@sinclair/typebox";
955
+ import { StringEnum } from "@avadisabelle/ava-pi-ai";
956
+
957
+ pi.registerTool({
958
+ name: "my_tool",
959
+ label: "My Tool",
960
+ description: "What this tool does",
961
+ promptSnippet: "Summarize or transform text according to action",
962
+ promptGuidelines: ["Use this tool when the user asks to summarize previously generated text."],
963
+ parameters: Type.Object({
964
+ action: StringEnum(["list", "add"] as const),
965
+ text: Type.Optional(Type.String()),
966
+ }),
967
+
968
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
969
+ // Stream progress
970
+ onUpdate?.({ content: [{ type: "text", text: "Working..." }] });
971
+
972
+ return {
973
+ content: [{ type: "text", text: "Done" }],
974
+ details: { result: "..." },
975
+ };
976
+ },
977
+
978
+ // Optional: Custom rendering
979
+ renderCall(args, theme) { ... },
980
+ renderResult(result, options, theme) { ... },
981
+ });
982
+ ```
983
+
984
+ ### pi.sendMessage(message, options?)
985
+
986
+ Inject a custom message into the session.
987
+
988
+ ```typescript
989
+ pi.sendMessage({
990
+ customType: "my-extension",
991
+ content: "Message text",
992
+ display: true,
993
+ details: { ... },
994
+ }, {
995
+ triggerTurn: true,
996
+ deliverAs: "steer",
997
+ });
998
+ ```
999
+
1000
+ **Options:**
1001
+ - `deliverAs` - Delivery mode:
1002
+ - `"steer"` (default) - Queues the message while streaming. Delivered after the current assistant turn finishes executing its tool calls, before the next LLM call.
1003
+ - `"followUp"` - Waits for agent to finish. Delivered only when agent has no more tool calls.
1004
+ - `"nextTurn"` - Queued for next user prompt. Does not interrupt or trigger anything.
1005
+ - `triggerTurn: true` - If agent is idle, trigger an LLM response immediately. Only applies to `"steer"` and `"followUp"` modes (ignored for `"nextTurn"`).
1006
+
1007
+ ### pi.sendUserMessage(content, options?)
1008
+
1009
+ 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.
1010
+
1011
+ ```typescript
1012
+ // Simple text message
1013
+ pi.sendUserMessage("What is 2+2?");
1014
+
1015
+ // With content array (text + images)
1016
+ pi.sendUserMessage([
1017
+ { type: "text", text: "Describe this image:" },
1018
+ { type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } },
1019
+ ]);
1020
+
1021
+ // During streaming - must specify delivery mode
1022
+ pi.sendUserMessage("Focus on error handling", { deliverAs: "steer" });
1023
+ pi.sendUserMessage("And then summarize", { deliverAs: "followUp" });
1024
+ ```
1025
+
1026
+ **Options:**
1027
+ - `deliverAs` - Required when agent is streaming:
1028
+ - `"steer"` - Queues the message for delivery after the current assistant turn finishes executing its tool calls
1029
+ - `"followUp"` - Waits for agent to finish all tools
1030
+
1031
+ When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, throws an error.
1032
+
1033
+ See [send-user-message.ts](../examples/extensions/send-user-message.ts) for a complete example.
1034
+
1035
+ ### pi.appendEntry(customType, data?)
1036
+
1037
+ Persist extension state (does NOT participate in LLM context).
1038
+
1039
+ ```typescript
1040
+ pi.appendEntry("my-state", { count: 42 });
1041
+
1042
+ // Restore on reload
1043
+ pi.on("session_start", async (_event, ctx) => {
1044
+ for (const entry of ctx.sessionManager.getEntries()) {
1045
+ if (entry.type === "custom" && entry.customType === "my-state") {
1046
+ // Reconstruct from entry.data
1047
+ }
1048
+ }
1049
+ });
1050
+ ```
1051
+
1052
+ ### pi.setSessionName(name)
1053
+
1054
+ Set the session display name (shown in session selector instead of first message).
1055
+
1056
+ ```typescript
1057
+ pi.setSessionName("Refactor auth module");
1058
+ ```
1059
+
1060
+ ### pi.getSessionName()
1061
+
1062
+ Get the current session name, if set.
1063
+
1064
+ ```typescript
1065
+ const name = pi.getSessionName();
1066
+ if (name) {
1067
+ console.log(`Session: ${name}`);
1068
+ }
1069
+ ```
1070
+
1071
+ ### pi.setLabel(entryId, label)
1072
+
1073
+ Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation (shown in `/tree` selector).
1074
+
1075
+ ```typescript
1076
+ // Set a label
1077
+ pi.setLabel(entryId, "checkpoint-before-refactor");
1078
+
1079
+ // Clear a label
1080
+ pi.setLabel(entryId, undefined);
1081
+
1082
+ // Read labels via sessionManager
1083
+ const label = ctx.sessionManager.getLabel(entryId);
1084
+ ```
1085
+
1086
+ Labels persist in the session and survive restarts. Use them to mark important points (turns, checkpoints) in the conversation tree.
1087
+
1088
+ ### pi.registerCommand(name, options)
1089
+
1090
+ Register a command.
1091
+
1092
+ ```typescript
1093
+ pi.registerCommand("stats", {
1094
+ description: "Show session statistics",
1095
+ handler: async (args, ctx) => {
1096
+ const count = ctx.sessionManager.getEntries().length;
1097
+ ctx.ui.notify(`${count} entries`, "info");
1098
+ }
1099
+ });
1100
+ ```
1101
+
1102
+ Optional: add argument auto-completion for `/command ...`:
1103
+
1104
+ ```typescript
1105
+ import type { AutocompleteItem } from "@avadisabelle/ava-pi-tui";
1106
+
1107
+ pi.registerCommand("deploy", {
1108
+ description: "Deploy to an environment",
1109
+ getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => {
1110
+ const envs = ["dev", "staging", "prod"];
1111
+ const items = envs.map((e) => ({ value: e, label: e }));
1112
+ const filtered = items.filter((i) => i.value.startsWith(prefix));
1113
+ return filtered.length > 0 ? filtered : null;
1114
+ },
1115
+ handler: async (args, ctx) => {
1116
+ ctx.ui.notify(`Deploying: ${args}`, "info");
1117
+ },
1118
+ });
1119
+ ```
1120
+
1121
+ ### pi.getCommands()
1122
+
1123
+ Get the slash commands available for invocation via `prompt` in the current session. Includes extension commands, prompt templates, and skill commands.
1124
+ The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills.
1125
+
1126
+ ```typescript
1127
+ const commands = pi.getCommands();
1128
+ const bySource = commands.filter((command) => command.source === "extension");
1129
+ ```
1130
+
1131
+ Each entry has this shape:
1132
+
1133
+ ```typescript
1134
+ {
1135
+ name: string; // Command name without the leading slash
1136
+ description?: string;
1137
+ source: "extension" | "prompt" | "skill";
1138
+ location?: "user" | "project" | "path"; // For templates and skills
1139
+ path?: string; // Files backing templates, skills, and extensions
1140
+ }
1141
+ ```
1142
+
1143
+ Built-in interactive commands (like `/model` and `/settings`) are not included here. They are handled only in interactive
1144
+ mode and would not execute if sent via `prompt`.
1145
+
1146
+ ### pi.registerMessageRenderer(customType, renderer)
1147
+
1148
+ Register a custom TUI renderer for messages with your `customType`. See [Custom UI](#custom-ui).
1149
+
1150
+ ### pi.registerShortcut(shortcut, options)
1151
+
1152
+ Register a keyboard shortcut. See [keybindings.md](keybindings.md) for the shortcut format and built-in keybindings.
1153
+
1154
+ ```typescript
1155
+ pi.registerShortcut("ctrl+shift+p", {
1156
+ description: "Toggle plan mode",
1157
+ handler: async (ctx) => {
1158
+ ctx.ui.notify("Toggled!");
1159
+ },
1160
+ });
1161
+ ```
1162
+
1163
+ ### pi.registerFlag(name, options)
1164
+
1165
+ Register a CLI flag.
1166
+
1167
+ ```typescript
1168
+ pi.registerFlag("plan", {
1169
+ description: "Start in plan mode",
1170
+ type: "boolean",
1171
+ default: false,
1172
+ });
1173
+
1174
+ // Check value
1175
+ if (pi.getFlag("--plan")) {
1176
+ // Plan mode enabled
1177
+ }
1178
+ ```
1179
+
1180
+ ### pi.exec(command, args, options?)
1181
+
1182
+ Execute a shell command.
1183
+
1184
+ ```typescript
1185
+ const result = await pi.exec("git", ["status"], { signal, timeout: 5000 });
1186
+ // result.stdout, result.stderr, result.code, result.killed
1187
+ ```
1188
+
1189
+ ### pi.getActiveTools() / pi.getAllTools() / pi.setActiveTools(names)
1190
+
1191
+ Manage active tools. This works for both built-in tools and dynamically registered tools.
1192
+
1193
+ ```typescript
1194
+ const active = pi.getActiveTools(); // ["read", "bash", "edit", "write"]
1195
+ const all = pi.getAllTools(); // [{ name: "read", description: "Read file contents..." }, ...]
1196
+ const names = all.map(t => t.name); // Just names if needed
1197
+ pi.setActiveTools(["read", "bash"]); // Switch to read-only
1198
+ ```
1199
+
1200
+ ### pi.setModel(model)
1201
+
1202
+ Set the current model. Returns `false` if no API key is available for the model. See [models.md](models.md) for configuring custom models.
1203
+
1204
+ ```typescript
1205
+ const model = ctx.modelRegistry.find("anthropic", "claude-sonnet-4-5");
1206
+ if (model) {
1207
+ const success = await pi.setModel(model);
1208
+ if (!success) {
1209
+ ctx.ui.notify("No API key for this model", "error");
1210
+ }
1211
+ }
1212
+ ```
1213
+
1214
+ ### pi.getThinkingLevel() / pi.setThinkingLevel(level)
1215
+
1216
+ Get or set the thinking level. Level is clamped to model capabilities (non-reasoning models always use "off").
1217
+
1218
+ ```typescript
1219
+ const current = pi.getThinkingLevel(); // "off" | "minimal" | "low" | "medium" | "high" | "xhigh"
1220
+ pi.setThinkingLevel("high");
1221
+ ```
1222
+
1223
+ ### pi.events
1224
+
1225
+ Shared event bus for communication between extensions:
1226
+
1227
+ ```typescript
1228
+ pi.events.on("my:event", (data) => { ... });
1229
+ pi.events.emit("my:event", { ... });
1230
+ ```
1231
+
1232
+ ### pi.registerProvider(name, config)
1233
+
1234
+ Register or override a model provider dynamically. Useful for proxies, custom endpoints, or team-wide model configurations.
1235
+
1236
+ 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`.
1237
+
1238
+ ```typescript
1239
+ // Register a new provider with custom models
1240
+ pi.registerProvider("my-proxy", {
1241
+ baseUrl: "https://proxy.example.com",
1242
+ apiKey: "PROXY_API_KEY", // env var name or literal
1243
+ api: "anthropic-messages",
1244
+ models: [
1245
+ {
1246
+ id: "claude-sonnet-4-20250514",
1247
+ name: "Claude 4 Sonnet (proxy)",
1248
+ reasoning: false,
1249
+ input: ["text", "image"],
1250
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
1251
+ contextWindow: 200000,
1252
+ maxTokens: 16384
1253
+ }
1254
+ ]
1255
+ });
1256
+
1257
+ // Override baseUrl for an existing provider (keeps all models)
1258
+ pi.registerProvider("anthropic", {
1259
+ baseUrl: "https://proxy.example.com"
1260
+ });
1261
+
1262
+ // Register provider with OAuth support for /login
1263
+ pi.registerProvider("corporate-ai", {
1264
+ baseUrl: "https://ai.corp.com",
1265
+ api: "openai-responses",
1266
+ models: [...],
1267
+ oauth: {
1268
+ name: "Corporate AI (SSO)",
1269
+ async login(callbacks) {
1270
+ // Custom OAuth flow
1271
+ callbacks.onAuth({ url: "https://sso.corp.com/..." });
1272
+ const code = await callbacks.onPrompt({ message: "Enter code:" });
1273
+ return { refresh: code, access: code, expires: Date.now() + 3600000 };
1274
+ },
1275
+ async refreshToken(credentials) {
1276
+ // Refresh logic
1277
+ return credentials;
1278
+ },
1279
+ getApiKey(credentials) {
1280
+ return credentials.access;
1281
+ }
1282
+ }
1283
+ });
1284
+ ```
1285
+
1286
+ **Config options:**
1287
+ - `baseUrl` - API endpoint URL. Required when defining models.
1288
+ - `apiKey` - API key or environment variable name. Required when defining models (unless `oauth` provided).
1289
+ - `api` - API type: `"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc.
1290
+ - `headers` - Custom headers to include in requests.
1291
+ - `authHeader` - If true, adds `Authorization: Bearer` header automatically.
1292
+ - `models` - Array of model definitions. If provided, replaces all existing models for this provider.
1293
+ - `oauth` - OAuth provider config for `/login` support. When provided, the provider appears in the login menu.
1294
+ - `streamSimple` - Custom streaming implementation for non-standard APIs.
1295
+
1296
+ See [custom-provider.md](custom-provider.md) for advanced topics: custom streaming APIs, OAuth details, model definition reference.
1297
+
1298
+ ### pi.unregisterProvider(name)
1299
+
1300
+ 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.
1301
+
1302
+ Like `registerProvider`, this takes effect immediately when called after the initial load phase, so a `/reload` is not required.
1303
+
1304
+ ```typescript
1305
+ pi.registerCommand("my-setup-teardown", {
1306
+ description: "Remove the custom proxy provider",
1307
+ handler: async (_args, _ctx) => {
1308
+ pi.unregisterProvider("my-proxy");
1309
+ },
1310
+ });
1311
+ ```
1312
+
1313
+ ## State Management
1314
+
1315
+ Extensions with state should store it in tool result `details` for proper branching support:
1316
+
1317
+ ```typescript
1318
+ export default function (pi: ExtensionAPI) {
1319
+ let items: string[] = [];
1320
+
1321
+ // Reconstruct state from session
1322
+ pi.on("session_start", async (_event, ctx) => {
1323
+ items = [];
1324
+ for (const entry of ctx.sessionManager.getBranch()) {
1325
+ if (entry.type === "message" && entry.message.role === "toolResult") {
1326
+ if (entry.message.toolName === "my_tool") {
1327
+ items = entry.message.details?.items ?? [];
1328
+ }
1329
+ }
1330
+ }
1331
+ });
1332
+
1333
+ pi.registerTool({
1334
+ name: "my_tool",
1335
+ // ...
1336
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
1337
+ items.push("new item");
1338
+ return {
1339
+ content: [{ type: "text", text: "Added" }],
1340
+ details: { items: [...items] }, // Store for reconstruction
1341
+ };
1342
+ },
1343
+ });
1344
+ }
1345
+ ```
1346
+
1347
+ ## Custom Tools
1348
+
1349
+ Register tools the LLM can call via `pi.registerTool()`. Tools appear in the system prompt and can have custom rendering.
1350
+
1351
+ 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.
1352
+
1353
+ 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([...])`).
1354
+
1355
+ 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.
1356
+
1357
+ 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.
1358
+
1359
+ 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.
1360
+
1361
+ 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.
1362
+
1363
+ Queue the entire mutation window on that target path. That includes read-modify-write logic, not just the final write.
1364
+
1365
+ ```typescript
1366
+ import { withFileMutationQueue } from "@avadisabelle/ava-pi-coding-agent";
1367
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
1368
+ import { dirname, resolve } from "node:path";
1369
+
1370
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1371
+ const absolutePath = resolve(ctx.cwd, params.path);
1372
+
1373
+ return withFileMutationQueue(absolutePath, async () => {
1374
+ await mkdir(dirname(absolutePath), { recursive: true });
1375
+ const current = await readFile(absolutePath, "utf8");
1376
+ const next = current.replace(params.oldText, params.newText);
1377
+ await writeFile(absolutePath, next, "utf8");
1378
+
1379
+ return {
1380
+ content: [{ type: "text", text: `Updated ${params.path}` }],
1381
+ details: {},
1382
+ };
1383
+ });
1384
+ }
1385
+ ```
1386
+
1387
+ ### Tool Definition
1388
+
1389
+ ```typescript
1390
+ import { Type } from "@sinclair/typebox";
1391
+ import { StringEnum } from "@avadisabelle/ava-pi-ai";
1392
+ import { Text } from "@avadisabelle/ava-pi-tui";
1393
+
1394
+ pi.registerTool({
1395
+ name: "my_tool",
1396
+ label: "My Tool",
1397
+ description: "What this tool does (shown to LLM)",
1398
+ promptSnippet: "List or add items in the project todo list",
1399
+ promptGuidelines: [
1400
+ "Use this tool for todo planning instead of direct file edits when the user asks for a task list."
1401
+ ],
1402
+ parameters: Type.Object({
1403
+ action: StringEnum(["list", "add"] as const), // Use StringEnum for Google compatibility
1404
+ text: Type.Optional(Type.String()),
1405
+ }),
1406
+
1407
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
1408
+ // Check for cancellation
1409
+ if (signal?.aborted) {
1410
+ return { content: [{ type: "text", text: "Cancelled" }] };
1411
+ }
1412
+
1413
+ // Stream progress updates
1414
+ onUpdate?.({
1415
+ content: [{ type: "text", text: "Working..." }],
1416
+ details: { progress: 50 },
1417
+ });
1418
+
1419
+ // Run commands via pi.exec (captured from extension closure)
1420
+ const result = await pi.exec("some-command", [], { signal });
1421
+
1422
+ // Return result
1423
+ return {
1424
+ content: [{ type: "text", text: "Done" }], // Sent to LLM
1425
+ details: { data: result }, // For rendering & state
1426
+ };
1427
+ },
1428
+
1429
+ // Optional: Custom rendering
1430
+ renderCall(args, theme) { ... },
1431
+ renderResult(result, options, theme) { ... },
1432
+ });
1433
+ ```
1434
+
1435
+ **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.
1436
+
1437
+ ```typescript
1438
+ // Correct: throw to signal an error
1439
+ async execute(toolCallId, params) {
1440
+ if (!isValid(params.input)) {
1441
+ throw new Error(`Invalid input: ${params.input}`);
1442
+ }
1443
+ return { content: [{ type: "text", text: "OK" }], details: {} };
1444
+ }
1445
+ ```
1446
+
1447
+ **Important:** Use `StringEnum` from `@avadisabelle/ava-pi-ai` for string enums. `Type.Union`/`Type.Literal` doesn't work with Google's API.
1448
+
1449
+ ### Overriding Built-in Tools
1450
+
1451
+ 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.
1452
+
1453
+ ```bash
1454
+ # Extension's read tool replaces built-in read
1455
+ pi -e ./tool-override.ts
1456
+ ```
1457
+
1458
+ Alternatively, use `--no-tools` to start without any built-in tools:
1459
+ ```bash
1460
+ # No built-in tools, only extension tools
1461
+ pi --no-tools -e ./my-extension.ts
1462
+ ```
1463
+
1464
+ See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.ts) for a complete example that overrides `read` with logging and access control.
1465
+
1466
+ **Rendering:** If your override doesn't provide custom `renderCall`/`renderResult` functions, 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.
1467
+
1468
+ **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.
1469
+
1470
+ Built-in tool implementations:
1471
+ - [read.ts](https://github.com/avadisabelle/ava-pi/blob/main/packages/coding-agent/src/core/tools/read.ts) - `ReadToolDetails`
1472
+ - [bash.ts](https://github.com/avadisabelle/ava-pi/blob/main/packages/coding-agent/src/core/tools/bash.ts) - `BashToolDetails`
1473
+ - [edit.ts](https://github.com/avadisabelle/ava-pi/blob/main/packages/coding-agent/src/core/tools/edit.ts)
1474
+ - [write.ts](https://github.com/avadisabelle/ava-pi/blob/main/packages/coding-agent/src/core/tools/write.ts)
1475
+ - [grep.ts](https://github.com/avadisabelle/ava-pi/blob/main/packages/coding-agent/src/core/tools/grep.ts) - `GrepToolDetails`
1476
+ - [find.ts](https://github.com/avadisabelle/ava-pi/blob/main/packages/coding-agent/src/core/tools/find.ts) - `FindToolDetails`
1477
+ - [ls.ts](https://github.com/avadisabelle/ava-pi/blob/main/packages/coding-agent/src/core/tools/ls.ts) - `LsToolDetails`
1478
+
1479
+ ### Remote Execution
1480
+
1481
+ Built-in tools support pluggable operations for delegating to remote systems (SSH, containers, etc.):
1482
+
1483
+ ```typescript
1484
+ import { createReadTool, createBashTool, type ReadOperations } from "@avadisabelle/ava-pi-coding-agent";
1485
+
1486
+ // Create tool with custom operations
1487
+ const remoteRead = createReadTool(cwd, {
1488
+ operations: {
1489
+ readFile: (path) => sshExec(remote, `cat ${path}`),
1490
+ access: (path) => sshExec(remote, `test -r ${path}`).then(() => {}),
1491
+ }
1492
+ });
1493
+
1494
+ // Register, checking flag at execution time
1495
+ pi.registerTool({
1496
+ ...remoteRead,
1497
+ async execute(id, params, signal, onUpdate, _ctx) {
1498
+ const ssh = getSshConfig();
1499
+ if (ssh) {
1500
+ const tool = createReadTool(cwd, { operations: createRemoteOps(ssh) });
1501
+ return tool.execute(id, params, signal, onUpdate);
1502
+ }
1503
+ return localRead.execute(id, params, signal, onUpdate);
1504
+ },
1505
+ });
1506
+ ```
1507
+
1508
+ **Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `LsOperations`, `GrepOperations`, `FindOperations`
1509
+
1510
+ For `user_bash`, extensions can reuse pi's local shell backend via `createLocalBashOperations()` instead of reimplementing local process spawning, shell resolution, and process-tree termination.
1511
+
1512
+ The bash tool also supports a spawn hook to adjust the command, cwd, or env before execution:
1513
+
1514
+ ```typescript
1515
+ import { createBashTool } from "@avadisabelle/ava-pi-coding-agent";
1516
+
1517
+ const bashTool = createBashTool(cwd, {
1518
+ spawnHook: ({ command, cwd, env }) => ({
1519
+ command: `source ~/.profile\n${command}`,
1520
+ cwd: `/mnt/sandbox${cwd}`,
1521
+ env: { ...env, CI: "1" },
1522
+ }),
1523
+ });
1524
+ ```
1525
+
1526
+ See [examples/extensions/ssh.ts](../examples/extensions/ssh.ts) for a complete SSH example with `--ssh` flag.
1527
+
1528
+ ### Output Truncation
1529
+
1530
+ **Tools MUST truncate their output** to avoid overwhelming the LLM context. Large outputs can cause:
1531
+ - Context overflow errors (prompt too long)
1532
+ - Compaction failures
1533
+ - Degraded model performance
1534
+
1535
+ The built-in limit is **50KB** (~10k tokens) and **2000 lines**, whichever is hit first. Use the exported truncation utilities:
1536
+
1537
+ ```typescript
1538
+ import {
1539
+ truncateHead, // Keep first N lines/bytes (good for file reads, search results)
1540
+ truncateTail, // Keep last N lines/bytes (good for logs, command output)
1541
+ truncateLine, // Truncate a single line to maxBytes with ellipsis
1542
+ formatSize, // Human-readable size (e.g., "50KB", "1.5MB")
1543
+ DEFAULT_MAX_BYTES, // 50KB
1544
+ DEFAULT_MAX_LINES, // 2000
1545
+ } from "@avadisabelle/ava-pi-coding-agent";
1546
+
1547
+ async execute(toolCallId, params, signal, onUpdate, ctx) {
1548
+ const output = await runCommand();
1549
+
1550
+ // Apply truncation
1551
+ const truncation = truncateHead(output, {
1552
+ maxLines: DEFAULT_MAX_LINES,
1553
+ maxBytes: DEFAULT_MAX_BYTES,
1554
+ });
1555
+
1556
+ let result = truncation.content;
1557
+
1558
+ if (truncation.truncated) {
1559
+ // Write full output to temp file
1560
+ const tempFile = writeTempFile(output);
1561
+
1562
+ // Inform the LLM where to find complete output
1563
+ result += `\n\n[Output truncated: ${truncation.outputLines} of ${truncation.totalLines} lines`;
1564
+ result += ` (${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}).`;
1565
+ result += ` Full output saved to: ${tempFile}]`;
1566
+ }
1567
+
1568
+ return { content: [{ type: "text", text: result }] };
1569
+ }
1570
+ ```
1571
+
1572
+ **Key points:**
1573
+ - Use `truncateHead` for content where the beginning matters (search results, file reads)
1574
+ - Use `truncateTail` for content where the end matters (logs, command output)
1575
+ - Always inform the LLM when output is truncated and where to find the full version
1576
+ - Document the truncation limits in your tool's description
1577
+
1578
+ See [examples/extensions/truncated-tool.ts](../examples/extensions/truncated-tool.ts) for a complete example wrapping `rg` (ripgrep) with proper truncation.
1579
+
1580
+ ### Multiple Tools
1581
+
1582
+ One extension can register multiple tools with shared state:
1583
+
1584
+ ```typescript
1585
+ export default function (pi: ExtensionAPI) {
1586
+ let connection = null;
1587
+
1588
+ pi.registerTool({ name: "db_connect", ... });
1589
+ pi.registerTool({ name: "db_query", ... });
1590
+ pi.registerTool({ name: "db_close", ... });
1591
+
1592
+ pi.on("session_shutdown", async () => {
1593
+ connection?.close();
1594
+ });
1595
+ }
1596
+ ```
1597
+
1598
+ ### Custom Rendering
1599
+
1600
+ 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/avadisabelle/ava-pi/blob/main/packages/coding-agent/src/modes/interactive/components/tool-execution.ts) for how built-in tools render.
1601
+
1602
+ Tool output is wrapped in a `Box` that handles padding and background. Your render methods return `Component` instances (typically `Text`).
1603
+
1604
+ #### renderCall
1605
+
1606
+ Renders the tool call (before/during execution):
1607
+
1608
+ ```typescript
1609
+ import { Text } from "@avadisabelle/ava-pi-tui";
1610
+
1611
+ renderCall(args, theme) {
1612
+ let text = theme.fg("toolTitle", theme.bold("my_tool "));
1613
+ text += theme.fg("muted", args.action);
1614
+ if (args.text) {
1615
+ text += " " + theme.fg("dim", `"${args.text}"`);
1616
+ }
1617
+ return new Text(text, 0, 0); // 0,0 padding - Box handles it
1618
+ }
1619
+ ```
1620
+
1621
+ #### renderResult
1622
+
1623
+ Renders the tool result:
1624
+
1625
+ ```typescript
1626
+ renderResult(result, { expanded, isPartial }, theme) {
1627
+ // Handle streaming
1628
+ if (isPartial) {
1629
+ return new Text(theme.fg("warning", "Processing..."), 0, 0);
1630
+ }
1631
+
1632
+ // Handle errors
1633
+ if (result.details?.error) {
1634
+ return new Text(theme.fg("error", `Error: ${result.details.error}`), 0, 0);
1635
+ }
1636
+
1637
+ // Normal result - support expanded view (Ctrl+O)
1638
+ let text = theme.fg("success", "✓ Done");
1639
+ if (expanded && result.details?.items) {
1640
+ for (const item of result.details.items) {
1641
+ text += "\n " + theme.fg("dim", item);
1642
+ }
1643
+ }
1644
+ return new Text(text, 0, 0);
1645
+ }
1646
+ ```
1647
+
1648
+ #### Keybinding Hints
1649
+
1650
+ Use `keyHint()` to display keybinding hints that respect the active keybinding configuration:
1651
+
1652
+ ```typescript
1653
+ import { keyHint } from "@avadisabelle/ava-pi-coding-agent";
1654
+
1655
+ renderResult(result, { expanded }, theme) {
1656
+ let text = theme.fg("success", "✓ Done");
1657
+ if (!expanded) {
1658
+ text += ` (${keyHint("app.tools.expand", "to expand")})`;
1659
+ }
1660
+ return new Text(text, 0, 0);
1661
+ }
1662
+ ```
1663
+
1664
+ Available functions:
1665
+ - `keyHint(keybinding, description)` - Formats a configured keybinding id such as `"app.tools.expand"` or `"tui.select.confirm"`
1666
+ - `keyText(keybinding)` - Returns the raw configured key text for a keybinding id
1667
+ - `rawKeyHint(key, description)` - Format a raw key string
1668
+
1669
+ Use namespaced keybinding ids:
1670
+ - Coding-agent ids use the `app.*` namespace, for example `app.tools.expand`, `app.editor.external`, `app.session.rename`
1671
+ - Shared TUI ids use the `tui.*` namespace, for example `tui.select.confirm`, `tui.select.cancel`, `tui.input.tab`
1672
+
1673
+ For the exhaustive list of keybinding ids and defaults, see [keybindings.md](keybindings.md). `keybindings.json` uses those same namespaced ids.
1674
+
1675
+ 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()`.
1676
+
1677
+ #### Best Practices
1678
+
1679
+ - Use `Text` with padding `(0, 0)` - the Box handles padding
1680
+ - Use `\n` for multi-line content
1681
+ - Handle `isPartial` for streaming progress
1682
+ - Support `expanded` for detail on demand
1683
+ - Keep default view compact
1684
+
1685
+ #### Fallback
1686
+
1687
+ If `renderCall`/`renderResult` is not defined or throws:
1688
+ - `renderCall`: Shows tool name
1689
+ - `renderResult`: Shows raw text from `content`
1690
+
1691
+ ## Custom UI
1692
+
1693
+ Extensions can interact with users via `ctx.ui` methods and customize how messages/tools render.
1694
+
1695
+ **For custom components, see [tui.md](tui.md)** which has copy-paste patterns for:
1696
+ - Selection dialogs (SelectList)
1697
+ - Async operations with cancel (BorderedLoader)
1698
+ - Settings toggles (SettingsList)
1699
+ - Status indicators (setStatus)
1700
+ - Working message during streaming (setWorkingMessage)
1701
+ - Widgets above/below editor (setWidget)
1702
+ - Custom footers (setFooter)
1703
+
1704
+ ### Dialogs
1705
+
1706
+ ```typescript
1707
+ // Select from options
1708
+ const choice = await ctx.ui.select("Pick one:", ["A", "B", "C"]);
1709
+
1710
+ // Confirm dialog
1711
+ const ok = await ctx.ui.confirm("Delete?", "This cannot be undone");
1712
+
1713
+ // Text input
1714
+ const name = await ctx.ui.input("Name:", "placeholder");
1715
+
1716
+ // Multi-line editor
1717
+ const text = await ctx.ui.editor("Edit:", "prefilled text");
1718
+
1719
+ // Notification (non-blocking)
1720
+ ctx.ui.notify("Done!", "info"); // "info" | "warning" | "error"
1721
+ ```
1722
+
1723
+ #### Timed Dialogs with Countdown
1724
+
1725
+ Dialogs support a `timeout` option that auto-dismisses with a live countdown display:
1726
+
1727
+ ```typescript
1728
+ // Dialog shows "Title (5s)" → "Title (4s)" → ... → auto-dismisses at 0
1729
+ const confirmed = await ctx.ui.confirm(
1730
+ "Timed Confirmation",
1731
+ "This dialog will auto-cancel in 5 seconds. Confirm?",
1732
+ { timeout: 5000 }
1733
+ );
1734
+
1735
+ if (confirmed) {
1736
+ // User confirmed
1737
+ } else {
1738
+ // User cancelled or timed out
1739
+ }
1740
+ ```
1741
+
1742
+ **Return values on timeout:**
1743
+ - `select()` returns `undefined`
1744
+ - `confirm()` returns `false`
1745
+ - `input()` returns `undefined`
1746
+
1747
+ #### Manual Dismissal with AbortSignal
1748
+
1749
+ For more control (e.g., to distinguish timeout from user cancel), use `AbortSignal`:
1750
+
1751
+ ```typescript
1752
+ const controller = new AbortController();
1753
+ const timeoutId = setTimeout(() => controller.abort(), 5000);
1754
+
1755
+ const confirmed = await ctx.ui.confirm(
1756
+ "Timed Confirmation",
1757
+ "This dialog will auto-cancel in 5 seconds. Confirm?",
1758
+ { signal: controller.signal }
1759
+ );
1760
+
1761
+ clearTimeout(timeoutId);
1762
+
1763
+ if (confirmed) {
1764
+ // User confirmed
1765
+ } else if (controller.signal.aborted) {
1766
+ // Dialog timed out
1767
+ } else {
1768
+ // User cancelled (pressed Escape or selected "No")
1769
+ }
1770
+ ```
1771
+
1772
+ See [examples/extensions/timed-confirm.ts](../examples/extensions/timed-confirm.ts) for complete examples.
1773
+
1774
+ ### Widgets, Status, and Footer
1775
+
1776
+ ```typescript
1777
+ // Status in footer (persistent until cleared)
1778
+ ctx.ui.setStatus("my-ext", "Processing...");
1779
+ ctx.ui.setStatus("my-ext", undefined); // Clear
1780
+
1781
+ // Working message (shown during streaming)
1782
+ ctx.ui.setWorkingMessage("Thinking deeply...");
1783
+ ctx.ui.setWorkingMessage(); // Restore default
1784
+
1785
+ // Widget above editor (default)
1786
+ ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]);
1787
+ // Widget below editor
1788
+ ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" });
1789
+ ctx.ui.setWidget("my-widget", (tui, theme) => new Text(theme.fg("accent", "Custom"), 0, 0));
1790
+ ctx.ui.setWidget("my-widget", undefined); // Clear
1791
+
1792
+ // Custom footer (replaces built-in footer entirely)
1793
+ ctx.ui.setFooter((tui, theme) => ({
1794
+ render(width) { return [theme.fg("dim", "Custom footer")]; },
1795
+ invalidate() {},
1796
+ }));
1797
+ ctx.ui.setFooter(undefined); // Restore built-in footer
1798
+
1799
+ // Terminal title
1800
+ ctx.ui.setTitle("pi - my-project");
1801
+
1802
+ // Editor text
1803
+ ctx.ui.setEditorText("Prefill text");
1804
+ const current = ctx.ui.getEditorText();
1805
+
1806
+ // Paste into editor (triggers paste handling, including collapse for large content)
1807
+ ctx.ui.pasteToEditor("pasted content");
1808
+
1809
+ // Tool output expansion
1810
+ const wasExpanded = ctx.ui.getToolsExpanded();
1811
+ ctx.ui.setToolsExpanded(true);
1812
+ ctx.ui.setToolsExpanded(wasExpanded);
1813
+
1814
+ // Custom editor (vim mode, emacs mode, etc.)
1815
+ ctx.ui.setEditorComponent((tui, theme, keybindings) => new VimEditor(tui, theme, keybindings));
1816
+ ctx.ui.setEditorComponent(undefined); // Restore default editor
1817
+
1818
+ // Theme management (see themes.md for creating themes)
1819
+ const themes = ctx.ui.getAllThemes(); // [{ name: "dark", path: "/..." | undefined }, ...]
1820
+ const lightTheme = ctx.ui.getTheme("light"); // Load without switching
1821
+ const result = ctx.ui.setTheme("light"); // Switch by name
1822
+ if (!result.success) {
1823
+ ctx.ui.notify(`Failed: ${result.error}`, "error");
1824
+ }
1825
+ ctx.ui.setTheme(lightTheme!); // Or switch by Theme object
1826
+ ctx.ui.theme.fg("accent", "styled text"); // Access current theme
1827
+ ```
1828
+
1829
+ ### Custom Components
1830
+
1831
+ For complex UI, use `ctx.ui.custom()`. This temporarily replaces the editor with your component until `done()` is called:
1832
+
1833
+ ```typescript
1834
+ import { Text, Component } from "@avadisabelle/ava-pi-tui";
1835
+
1836
+ const result = await ctx.ui.custom<boolean>((tui, theme, keybindings, done) => {
1837
+ const text = new Text("Press Enter to confirm, Escape to cancel", 1, 1);
1838
+
1839
+ text.onKey = (key) => {
1840
+ if (key === "return") done(true);
1841
+ if (key === "escape") done(false);
1842
+ return true;
1843
+ };
1844
+
1845
+ return text;
1846
+ });
1847
+
1848
+ if (result) {
1849
+ // User pressed Enter
1850
+ }
1851
+ ```
1852
+
1853
+ The callback receives:
1854
+ - `tui` - TUI instance (for screen dimensions, focus management)
1855
+ - `theme` - Current theme for styling
1856
+ - `keybindings` - App keybinding manager (for checking shortcuts)
1857
+ - `done(value)` - Call to close component and return value
1858
+
1859
+ See [tui.md](tui.md) for the full component API.
1860
+
1861
+ #### Overlay Mode (Experimental)
1862
+
1863
+ Pass `{ overlay: true }` to render the component as a floating modal on top of existing content, without clearing the screen:
1864
+
1865
+ ```typescript
1866
+ const result = await ctx.ui.custom<string | null>(
1867
+ (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
1868
+ { overlay: true }
1869
+ );
1870
+ ```
1871
+
1872
+ For advanced positioning (anchors, margins, percentages, responsive visibility), pass `overlayOptions`. Use `onHandle` to control visibility programmatically:
1873
+
1874
+ ```typescript
1875
+ const result = await ctx.ui.custom<string | null>(
1876
+ (tui, theme, keybindings, done) => new MyOverlayComponent({ onClose: done }),
1877
+ {
1878
+ overlay: true,
1879
+ overlayOptions: { anchor: "top-right", width: "50%", margin: 2 },
1880
+ onHandle: (handle) => { /* handle.setHidden(true/false) */ }
1881
+ }
1882
+ );
1883
+ ```
1884
+
1885
+ See [tui.md](tui.md) for the full `OverlayOptions` API and [overlay-qa-tests.ts](../examples/extensions/overlay-qa-tests.ts) for examples.
1886
+
1887
+ ### Custom Editor
1888
+
1889
+ Replace the main input editor with a custom implementation (vim mode, emacs mode, etc.):
1890
+
1891
+ ```typescript
1892
+ import { CustomEditor, type ExtensionAPI } from "@avadisabelle/ava-pi-coding-agent";
1893
+ import { matchesKey } from "@avadisabelle/ava-pi-tui";
1894
+
1895
+ class VimEditor extends CustomEditor {
1896
+ private mode: "normal" | "insert" = "insert";
1897
+
1898
+ handleInput(data: string): void {
1899
+ if (matchesKey(data, "escape") && this.mode === "insert") {
1900
+ this.mode = "normal";
1901
+ return;
1902
+ }
1903
+ if (this.mode === "normal" && data === "i") {
1904
+ this.mode = "insert";
1905
+ return;
1906
+ }
1907
+ super.handleInput(data); // App keybindings + text editing
1908
+ }
1909
+ }
1910
+
1911
+ export default function (pi: ExtensionAPI) {
1912
+ pi.on("session_start", (_event, ctx) => {
1913
+ ctx.ui.setEditorComponent((_tui, theme, keybindings) =>
1914
+ new VimEditor(theme, keybindings)
1915
+ );
1916
+ });
1917
+ }
1918
+ ```
1919
+
1920
+ **Key points:**
1921
+ - Extend `CustomEditor` (not base `Editor`) to get app keybindings (escape to abort, ctrl+d, model switching)
1922
+ - Call `super.handleInput(data)` for keys you don't handle
1923
+ - Factory receives `theme` and `keybindings` from the app
1924
+ - Pass `undefined` to restore default: `ctx.ui.setEditorComponent(undefined)`
1925
+
1926
+ See [tui.md](tui.md) Pattern 7 for a complete example with mode indicator.
1927
+
1928
+ ### Message Rendering
1929
+
1930
+ Register a custom renderer for messages with your `customType`:
1931
+
1932
+ ```typescript
1933
+ import { Text } from "@avadisabelle/ava-pi-tui";
1934
+
1935
+ pi.registerMessageRenderer("my-extension", (message, options, theme) => {
1936
+ const { expanded } = options;
1937
+ let text = theme.fg("accent", `[${message.customType}] `);
1938
+ text += message.content;
1939
+
1940
+ if (expanded && message.details) {
1941
+ text += "\n" + theme.fg("dim", JSON.stringify(message.details, null, 2));
1942
+ }
1943
+
1944
+ return new Text(text, 0, 0);
1945
+ });
1946
+ ```
1947
+
1948
+ Messages are sent via `pi.sendMessage()`:
1949
+
1950
+ ```typescript
1951
+ pi.sendMessage({
1952
+ customType: "my-extension", // Matches registerMessageRenderer
1953
+ content: "Status update",
1954
+ display: true, // Show in TUI
1955
+ details: { ... }, // Available in renderer
1956
+ });
1957
+ ```
1958
+
1959
+ ### Theme Colors
1960
+
1961
+ All render functions receive a `theme` object. See [themes.md](themes.md) for creating custom themes and the full color palette.
1962
+
1963
+ ```typescript
1964
+ // Foreground colors
1965
+ theme.fg("toolTitle", text) // Tool names
1966
+ theme.fg("accent", text) // Highlights
1967
+ theme.fg("success", text) // Success (green)
1968
+ theme.fg("error", text) // Errors (red)
1969
+ theme.fg("warning", text) // Warnings (yellow)
1970
+ theme.fg("muted", text) // Secondary text
1971
+ theme.fg("dim", text) // Tertiary text
1972
+
1973
+ // Text styles
1974
+ theme.bold(text)
1975
+ theme.italic(text)
1976
+ theme.strikethrough(text)
1977
+ ```
1978
+
1979
+ For syntax highlighting in custom tool renderers:
1980
+
1981
+ ```typescript
1982
+ import { highlightCode, getLanguageFromPath } from "@avadisabelle/ava-pi-coding-agent";
1983
+
1984
+ // Highlight code with explicit language
1985
+ const highlighted = highlightCode("const x = 1;", "typescript", theme);
1986
+
1987
+ // Auto-detect language from file path
1988
+ const lang = getLanguageFromPath("/path/to/file.rs"); // "rust"
1989
+ const highlighted = highlightCode(code, lang, theme);
1990
+ ```
1991
+
1992
+ ## Error Handling
1993
+
1994
+ - Extension errors are logged, agent continues
1995
+ - `tool_call` errors block the tool (fail-safe)
1996
+ - Tool `execute` errors must be signaled by throwing; the thrown error is caught, reported to the LLM with `isError: true`, and execution continues
1997
+
1998
+ ## Mode Behavior
1999
+
2000
+ | Mode | UI Methods | Notes |
2001
+ |------|-----------|-------|
2002
+ | Interactive | Full TUI | Normal operation |
2003
+ | RPC (`--mode rpc`) | JSON protocol | Host handles UI, see [rpc.md](rpc.md) |
2004
+ | JSON (`--mode json`) | No-op | Event stream to stdout, see [json.md](json.md) |
2005
+ | Print (`-p`) | No-op | Extensions run but can't prompt |
2006
+
2007
+ In non-interactive modes, check `ctx.hasUI` before using UI methods.
2008
+
2009
+ ## Examples Reference
2010
+
2011
+ All examples in [examples/extensions/](../examples/extensions/).
2012
+
2013
+ | Example | Description | Key APIs |
2014
+ |---------|-------------|----------|
2015
+ | **Tools** |||
2016
+ | `hello.ts` | Minimal tool registration | `registerTool` |
2017
+ | `question.ts` | Tool with user interaction | `registerTool`, `ui.select` |
2018
+ | `questionnaire.ts` | Multi-step wizard tool | `registerTool`, `ui.custom` |
2019
+ | `todo.ts` | Stateful tool with persistence | `registerTool`, `appendEntry`, `renderResult`, session events |
2020
+ | `dynamic-tools.ts` | Register tools after startup and during commands | `registerTool`, `session_start`, `registerCommand` |
2021
+ | `truncated-tool.ts` | Output truncation example | `registerTool`, `truncateHead` |
2022
+ | `tool-override.ts` | Override built-in read tool | `registerTool` (same name as built-in) |
2023
+ | **Commands** |||
2024
+ | `pirate.ts` | Modify system prompt per-turn | `registerCommand`, `before_agent_start` |
2025
+ | `summarize.ts` | Conversation summary command | `registerCommand`, `ui.custom` |
2026
+ | `handoff.ts` | Cross-provider model handoff | `registerCommand`, `ui.editor`, `ui.custom` |
2027
+ | `qna.ts` | Q&A with custom UI | `registerCommand`, `ui.custom`, `setEditorText` |
2028
+ | `send-user-message.ts` | Inject user messages | `registerCommand`, `sendUserMessage` |
2029
+ | `reload-runtime.ts` | Reload command and LLM tool handoff | `registerCommand`, `ctx.reload()`, `sendUserMessage` |
2030
+ | `shutdown-command.ts` | Graceful shutdown command | `registerCommand`, `shutdown()` |
2031
+ | **Events & Gates** |||
2032
+ | `permission-gate.ts` | Block dangerous commands | `on("tool_call")`, `ui.confirm` |
2033
+ | `protected-paths.ts` | Block writes to specific paths | `on("tool_call")` |
2034
+ | `confirm-destructive.ts` | Confirm session changes | `on("session_before_switch")`, `on("session_before_fork")` |
2035
+ | `dirty-repo-guard.ts` | Warn on dirty git repo | `on("session_before_*")`, `exec` |
2036
+ | `input-transform.ts` | Transform user input | `on("input")` |
2037
+ | `model-status.ts` | React to model changes | `on("model_select")`, `setStatus` |
2038
+ | `provider-payload.ts` | Inspect or patch provider payloads | `on("before_provider_request")` |
2039
+ | `system-prompt-header.ts` | Display system prompt info | `on("agent_start")`, `getSystemPrompt` |
2040
+ | `claude-rules.ts` | Load rules from files | `on("session_start")`, `on("before_agent_start")` |
2041
+ | `file-trigger.ts` | File watcher triggers messages | `sendMessage` |
2042
+ | **Compaction & Sessions** |||
2043
+ | `custom-compaction.ts` | Custom compaction summary | `on("session_before_compact")` |
2044
+ | `trigger-compact.ts` | Trigger compaction manually | `compact()` |
2045
+ | `git-checkpoint.ts` | Git stash on turns | `on("turn_end")`, `on("session_fork")`, `exec` |
2046
+ | `auto-commit-on-exit.ts` | Commit on shutdown | `on("session_shutdown")`, `exec` |
2047
+ | **UI Components** |||
2048
+ | `status-line.ts` | Footer status indicator | `setStatus`, session events |
2049
+ | `custom-footer.ts` | Replace footer entirely | `registerCommand`, `setFooter` |
2050
+ | `custom-header.ts` | Replace startup header | `on("session_start")`, `setHeader` |
2051
+ | `modal-editor.ts` | Vim-style modal editor | `setEditorComponent`, `CustomEditor` |
2052
+ | `rainbow-editor.ts` | Custom editor styling | `setEditorComponent` |
2053
+ | `widget-placement.ts` | Widget above/below editor | `setWidget` |
2054
+ | `overlay-test.ts` | Overlay components | `ui.custom` with overlay options |
2055
+ | `overlay-qa-tests.ts` | Comprehensive overlay tests | `ui.custom`, all overlay options |
2056
+ | `notify.ts` | Simple notifications | `ui.notify` |
2057
+ | `timed-confirm.ts` | Dialogs with timeout | `ui.confirm` with timeout/signal |
2058
+ | `mac-system-theme.ts` | Auto-switch theme | `setTheme`, `exec` |
2059
+ | **Complex Extensions** |||
2060
+ | `plan-mode/` | Full plan mode implementation | All event types, `registerCommand`, `registerShortcut`, `registerFlag`, `setStatus`, `setWidget`, `sendMessage`, `setActiveTools` |
2061
+ | `preset.ts` | Saveable presets (model, tools, thinking) | `registerCommand`, `registerShortcut`, `registerFlag`, `setModel`, `setActiveTools`, `setThinkingLevel`, `appendEntry` |
2062
+ | `tools.ts` | Toggle tools on/off UI | `registerCommand`, `setActiveTools`, `SettingsList`, session events |
2063
+ | **Remote & Sandbox** |||
2064
+ | `ssh.ts` | SSH remote execution | `registerFlag`, `on("user_bash")`, `on("before_agent_start")`, tool operations |
2065
+ | `interactive-shell.ts` | Persistent shell session | `on("user_bash")` |
2066
+ | `sandbox/` | Sandboxed tool execution | Tool operations |
2067
+ | `subagent/` | Spawn sub-agents | `registerTool`, `exec` |
2068
+ | **Games** |||
2069
+ | `snake.ts` | Snake game | `registerCommand`, `ui.custom`, keyboard handling |
2070
+ | `space-invaders.ts` | Space Invaders game | `registerCommand`, `ui.custom` |
2071
+ | `doom-overlay/` | Doom in overlay | `ui.custom` with overlay |
2072
+ | **Providers** |||
2073
+ | `custom-provider-anthropic/` | Custom Anthropic proxy | `registerProvider` |
2074
+ | `custom-provider-gitlab-duo/` | GitLab Duo integration | `registerProvider` with OAuth |
2075
+ | **Messages & Communication** |||
2076
+ | `message-renderer.ts` | Custom message rendering | `registerMessageRenderer`, `sendMessage` |
2077
+ | `event-bus.ts` | Inter-extension events | `pi.events` |
2078
+ | **Session Metadata** |||
2079
+ | `session-name.ts` | Name sessions for selector | `setSessionName`, `getSessionName` |
2080
+ | `bookmark.ts` | Bookmark entries for /tree | `setLabel` |
2081
+ | **Misc** |||
2082
+ | `antigravity-image-gen.ts` | Image generation tool | `registerTool`, Google Antigravity |
2083
+ | `inline-bash.ts` | Inline bash in tool calls | `on("tool_call")` |
2084
+ | `bash-spawn-hook.ts` | Adjust bash command, cwd, and env before execution | `createBashTool`, `spawnHook` |
2085
+ | `with-deps/` | Extension with npm dependencies | Package structure with `package.json` |