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