@dyyz1993/pi-coding-agent 0.69.5

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