@celljs/ta 0.0.0-stage → 4.5.1

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