@punch-bot/cli 1.5.0 → 1.5.3

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 (505) hide show
  1. package/CHANGELOG.md +168 -1
  2. package/README.md +6 -8
  3. package/dist/bundle/chunks/anthropic-messages-WIBS5YKY.js +6 -0
  4. package/dist/bundle/chunks/azure-openai-responses-GP5GDEGO.js +2 -0
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +7 -4
  6. package/dist/bundle/chunks/chunk-35EHANXE.js +2 -0
  7. package/dist/bundle/chunks/chunk-3IMHRFLG.js +6 -0
  8. package/dist/bundle/chunks/chunk-77CRE5SV.js +9 -0
  9. package/dist/bundle/chunks/chunk-CE33JMCE.js +861 -0
  10. package/dist/bundle/chunks/{chunk-MYNHUMKE.js → chunk-CXY7BILM.js} +2 -44
  11. package/dist/bundle/chunks/chunk-EISXNXOQ.js +41 -0
  12. package/dist/bundle/chunks/chunk-ENMVUQHE.js +26 -0
  13. package/dist/bundle/chunks/chunk-FFMDRXC4.js +10 -0
  14. package/dist/bundle/chunks/chunk-GFUN2N5K.js +2 -0
  15. package/dist/bundle/chunks/chunk-HQH636GU.js +361 -0
  16. package/dist/bundle/chunks/chunk-IEBK4HQA.js +2 -0
  17. package/dist/bundle/chunks/chunk-JAJLG57O.js +4 -0
  18. package/dist/bundle/chunks/{chunk-RFVYQ7ZX.js → chunk-LOHGXPCL.js} +2 -2
  19. package/dist/bundle/chunks/{chunk-NO2FNWW3.js → chunk-OV2VGRRS.js} +1 -1
  20. package/dist/bundle/chunks/chunk-P7FPUEYA.js +2 -0
  21. package/dist/bundle/chunks/chunk-PDENR63J.js +16 -0
  22. package/dist/bundle/chunks/chunk-RHOWRSGK.js +2 -0
  23. package/dist/bundle/chunks/{chunk-BRECMFDT.js → chunk-UZ3LUZDC.js} +1 -1
  24. package/dist/bundle/chunks/chunk-WN2D4UD4.js +2 -0
  25. package/dist/bundle/chunks/chunk-X4T5TGM4.js +82 -0
  26. package/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
  27. package/dist/bundle/chunks/cli-OQNR6ESL.js +53 -0
  28. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-FDCKYGTP.js → cloudflare-workers-ai-system-one-36EDUVVN.js} +1 -1
  29. package/dist/bundle/chunks/codemode-worker.js +2 -0
  30. package/dist/bundle/chunks/{execute-HXULRBCI.js → execute-EHT55MW7.js} +5 -3
  31. package/dist/bundle/chunks/github-copilot.js +1 -1
  32. package/dist/bundle/chunks/{google-generative-ai-2ESDEFYR.js → google-generative-ai-KA6FZCHM.js} +1 -1
  33. package/dist/bundle/chunks/{google-vertex-YERBWL2T.js → google-vertex-DXKQ4IYR.js} +1 -1
  34. package/dist/bundle/chunks/image-resize-worker.js +1 -1
  35. package/dist/bundle/chunks/kimi-coding.js +1 -1
  36. package/dist/bundle/chunks/{llama-cpp-classify-M4KMJHPS.js → llama-cpp-classify-676UCBOD.js} +1 -1
  37. package/dist/bundle/chunks/meta.js +1 -1
  38. package/dist/bundle/chunks/mistral-conversations-PJ56UMXO.js +5 -0
  39. package/dist/bundle/chunks/openai-codex-responses-DWVG7MAQ.js +10 -0
  40. package/dist/bundle/chunks/openai-completions-OKI6KBNP.js +7 -0
  41. package/dist/bundle/chunks/{openai-decisions-PPJMQ3W4.js → openai-decisions-SO57QA6O.js} +1 -1
  42. package/dist/bundle/chunks/openai-responses-3HV234HB.js +4 -0
  43. package/dist/bundle/chunks/{openrouter-images-WWPCCAPX.js → openrouter-images-5X6D7HFS.js} +1 -1
  44. package/dist/bundle/chunks/pi-messages-BS5Z34RE.js +8 -0
  45. package/dist/bundle/chunks/radius.js +1 -1
  46. package/dist/bundle/chunks/{runtime-R5GXO4CV.js → runtime-74PFKASL.js} +1 -1
  47. package/dist/bundle/chunks/{typesafe-system-one-NLWRPIRL.js → typesafe-system-one-IPNULX2M.js} +1 -1
  48. package/dist/bundle/chunks/virtual-modules-2Y422I6U.js +2 -0
  49. package/dist/bundle/cli-runtime.js +1 -1
  50. package/dist/bundle/index.js +1 -1
  51. package/dist/bundle/rpc-entry.js +1 -1
  52. package/dist/cli/args.d.ts +0 -1
  53. package/dist/cli/args.d.ts.map +1 -1
  54. package/dist/cli/args.js +8 -12
  55. package/dist/cli/args.js.map +1 -1
  56. package/dist/cli/auth-command.d.ts.map +1 -1
  57. package/dist/cli/auth-command.js +26 -2
  58. package/dist/cli/auth-command.js.map +1 -1
  59. package/dist/cli/auth-login.d.ts +15 -0
  60. package/dist/cli/auth-login.d.ts.map +1 -0
  61. package/dist/cli/auth-login.js +232 -0
  62. package/dist/cli/auth-login.js.map +1 -0
  63. package/dist/cli/auth-logout.d.ts +14 -0
  64. package/dist/cli/auth-logout.d.ts.map +1 -0
  65. package/dist/cli/auth-logout.js +63 -0
  66. package/dist/cli/auth-logout.js.map +1 -0
  67. package/dist/cli/auth-terminal.d.ts +17 -0
  68. package/dist/cli/auth-terminal.d.ts.map +1 -0
  69. package/dist/cli/auth-terminal.js +63 -0
  70. package/dist/cli/auth-terminal.js.map +1 -0
  71. package/dist/cli/project-trust.js +1 -1
  72. package/dist/cli/project-trust.js.map +1 -1
  73. package/dist/config.d.ts +10 -2
  74. package/dist/config.d.ts.map +1 -1
  75. package/dist/config.js +24 -11
  76. package/dist/config.js.map +1 -1
  77. package/dist/core/agent-session-runtime.d.ts +5 -0
  78. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  79. package/dist/core/agent-session-runtime.js +20 -5
  80. package/dist/core/agent-session-runtime.js.map +1 -1
  81. package/dist/core/agent-session.d.ts +31 -15
  82. package/dist/core/agent-session.d.ts.map +1 -1
  83. package/dist/core/agent-session.js +158 -71
  84. package/dist/core/agent-session.js.map +1 -1
  85. package/dist/core/auth-storage.d.ts.map +1 -1
  86. package/dist/core/auth-storage.js +3 -2
  87. package/dist/core/auth-storage.js.map +1 -1
  88. package/dist/core/bash-executor.d.ts.map +1 -1
  89. package/dist/core/bash-executor.js +3 -1
  90. package/dist/core/bash-executor.js.map +1 -1
  91. package/dist/core/cache-warmer.d.ts +4 -37
  92. package/dist/core/cache-warmer.d.ts.map +1 -1
  93. package/dist/core/cache-warmer.js +11 -89
  94. package/dist/core/cache-warmer.js.map +1 -1
  95. package/dist/core/compaction/branch-summarization.d.ts +4 -2
  96. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  97. package/dist/core/compaction/branch-summarization.js +16 -4
  98. package/dist/core/compaction/branch-summarization.js.map +1 -1
  99. package/dist/core/compaction/utils.d.ts.map +1 -1
  100. package/dist/core/compaction/utils.js +2 -1
  101. package/dist/core/compaction/utils.js.map +1 -1
  102. package/dist/core/exec.d.ts +9 -1
  103. package/dist/core/exec.d.ts.map +1 -1
  104. package/dist/core/exec.js +104 -60
  105. package/dist/core/exec.js.map +1 -1
  106. package/dist/core/export-html/template.css +9 -0
  107. package/dist/core/export-html/template.js +165 -45
  108. package/dist/core/extensions/index.d.ts +1 -1
  109. package/dist/core/extensions/index.d.ts.map +1 -1
  110. package/dist/core/extensions/index.js.map +1 -1
  111. package/dist/core/extensions/loader.d.ts.map +1 -1
  112. package/dist/core/extensions/loader.js +10 -13
  113. package/dist/core/extensions/loader.js.map +1 -1
  114. package/dist/core/extensions/pi-ai-extension-view.d.ts +19 -0
  115. package/dist/core/extensions/pi-ai-extension-view.d.ts.map +1 -0
  116. package/dist/core/extensions/pi-ai-extension-view.js +22 -0
  117. package/dist/core/extensions/pi-ai-extension-view.js.map +1 -0
  118. package/dist/core/extensions/runner.d.ts +1 -4
  119. package/dist/core/extensions/runner.d.ts.map +1 -1
  120. package/dist/core/extensions/runner.js +0 -14
  121. package/dist/core/extensions/runner.js.map +1 -1
  122. package/dist/core/extensions/types.d.ts +5 -18
  123. package/dist/core/extensions/types.d.ts.map +1 -1
  124. package/dist/core/extensions/types.js +1 -1
  125. package/dist/core/extensions/types.js.map +1 -1
  126. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  127. package/dist/core/extensions/virtual-modules.js +8 -7
  128. package/dist/core/extensions/virtual-modules.js.map +1 -1
  129. package/dist/core/index.d.ts +1 -1
  130. package/dist/core/index.d.ts.map +1 -1
  131. package/dist/core/index.js.map +1 -1
  132. package/dist/core/mcp-servers.d.ts +23 -41
  133. package/dist/core/mcp-servers.d.ts.map +1 -1
  134. package/dist/core/mcp-servers.js +51 -120
  135. package/dist/core/mcp-servers.js.map +1 -1
  136. package/dist/core/model-config.d.ts +1730 -2029
  137. package/dist/core/model-config.d.ts.map +1 -1
  138. package/dist/core/model-config.js +2 -3
  139. package/dist/core/model-config.js.map +1 -1
  140. package/dist/core/model-resolver.d.ts.map +1 -1
  141. package/dist/core/model-resolver.js +36 -29
  142. package/dist/core/model-resolver.js.map +1 -1
  143. package/dist/core/model-runtime.d.ts +5 -0
  144. package/dist/core/model-runtime.d.ts.map +1 -1
  145. package/dist/core/model-runtime.js +11 -4
  146. package/dist/core/model-runtime.js.map +1 -1
  147. package/dist/core/package-manager.d.ts +24 -1
  148. package/dist/core/package-manager.d.ts.map +1 -1
  149. package/dist/core/package-manager.js +210 -51
  150. package/dist/core/package-manager.js.map +1 -1
  151. package/dist/core/pi-ai-schemas.d.ts +167 -0
  152. package/dist/core/pi-ai-schemas.d.ts.map +1 -0
  153. package/dist/core/pi-ai-schemas.js +21 -0
  154. package/dist/core/pi-ai-schemas.js.map +1 -0
  155. package/dist/core/pi-manifest.d.ts +1 -0
  156. package/dist/core/pi-manifest.d.ts.map +1 -1
  157. package/dist/core/pi-manifest.js +4 -0
  158. package/dist/core/pi-manifest.js.map +1 -1
  159. package/dist/core/preferred-providers.d.ts +17 -0
  160. package/dist/core/preferred-providers.d.ts.map +1 -0
  161. package/dist/core/preferred-providers.js +24 -0
  162. package/dist/core/preferred-providers.js.map +1 -0
  163. package/dist/core/project-trust.d.ts +1 -1
  164. package/dist/core/project-trust.d.ts.map +1 -1
  165. package/dist/core/project-trust.js +1 -1
  166. package/dist/core/project-trust.js.map +1 -1
  167. package/dist/core/prompt-templates.d.ts.map +1 -1
  168. package/dist/core/prompt-templates.js +18 -2
  169. package/dist/core/prompt-templates.js.map +1 -1
  170. package/dist/core/provider-composer.d.ts.map +1 -1
  171. package/dist/core/provider-composer.js +3 -1
  172. package/dist/core/provider-composer.js.map +1 -1
  173. package/dist/core/provider-matching.d.ts +11 -0
  174. package/dist/core/provider-matching.d.ts.map +1 -0
  175. package/dist/core/provider-matching.js +14 -0
  176. package/dist/core/provider-matching.js.map +1 -0
  177. package/dist/core/radius-mcp.d.ts +13 -0
  178. package/dist/core/radius-mcp.d.ts.map +1 -0
  179. package/dist/core/radius-mcp.js +29 -0
  180. package/dist/core/radius-mcp.js.map +1 -0
  181. package/dist/core/radius.d.ts +0 -3
  182. package/dist/core/radius.d.ts.map +1 -1
  183. package/dist/core/radius.js +0 -5
  184. package/dist/core/radius.js.map +1 -1
  185. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  186. package/dist/core/remote-catalog-provider.js +2 -0
  187. package/dist/core/remote-catalog-provider.js.map +1 -1
  188. package/dist/core/resource-loader.d.ts +4 -1
  189. package/dist/core/resource-loader.d.ts.map +1 -1
  190. package/dist/core/resource-loader.js +40 -25
  191. package/dist/core/resource-loader.js.map +1 -1
  192. package/dist/core/runtime-credentials.d.ts +8 -0
  193. package/dist/core/runtime-credentials.d.ts.map +1 -1
  194. package/dist/core/runtime-credentials.js +15 -1
  195. package/dist/core/runtime-credentials.js.map +1 -1
  196. package/dist/core/sdk.d.ts.map +1 -1
  197. package/dist/core/sdk.js +3 -1
  198. package/dist/core/sdk.js.map +1 -1
  199. package/dist/core/session-cwd.d.ts +0 -1
  200. package/dist/core/session-cwd.d.ts.map +1 -1
  201. package/dist/core/session-cwd.js +0 -3
  202. package/dist/core/session-cwd.js.map +1 -1
  203. package/dist/core/session-manager.d.ts +7 -0
  204. package/dist/core/session-manager.d.ts.map +1 -1
  205. package/dist/core/session-manager.js +32 -13
  206. package/dist/core/session-manager.js.map +1 -1
  207. package/dist/core/settings-defaults.d.ts +1 -31
  208. package/dist/core/settings-defaults.d.ts.map +1 -1
  209. package/dist/core/settings-defaults.js +1 -31
  210. package/dist/core/settings-defaults.js.map +1 -1
  211. package/dist/core/settings-manager.d.ts +4 -56
  212. package/dist/core/settings-manager.d.ts.map +1 -1
  213. package/dist/core/settings-manager.js +11 -247
  214. package/dist/core/settings-manager.js.map +1 -1
  215. package/dist/core/settings-schema.d.ts +4 -54
  216. package/dist/core/settings-schema.d.ts.map +1 -1
  217. package/dist/core/settings-schema.js +7 -101
  218. package/dist/core/settings-schema.js.map +1 -1
  219. package/dist/core/skills.d.ts.map +1 -1
  220. package/dist/core/skills.js +6 -14
  221. package/dist/core/skills.js.map +1 -1
  222. package/dist/core/slash-commands.d.ts +0 -6
  223. package/dist/core/slash-commands.d.ts.map +1 -1
  224. package/dist/core/slash-commands.js +1 -27
  225. package/dist/core/slash-commands.js.map +1 -1
  226. package/dist/core/source-info.d.ts +9 -0
  227. package/dist/core/source-info.d.ts.map +1 -1
  228. package/dist/core/source-info.js +13 -0
  229. package/dist/core/source-info.js.map +1 -1
  230. package/dist/core/system-prompt.d.ts.map +1 -1
  231. package/dist/core/system-prompt.js +5 -6
  232. package/dist/core/system-prompt.js.map +1 -1
  233. package/dist/core/telemetry.js +1 -1
  234. package/dist/core/telemetry.js.map +1 -1
  235. package/dist/core/theme/theme.d.ts.map +1 -1
  236. package/dist/core/theme/theme.js +5 -1
  237. package/dist/core/theme/theme.js.map +1 -1
  238. package/dist/core/tools/bash.d.ts +2 -2
  239. package/dist/core/tools/bash.d.ts.map +1 -1
  240. package/dist/core/tools/bash.js +35 -5
  241. package/dist/core/tools/bash.js.map +1 -1
  242. package/dist/core/tools/edit-diff.d.ts +23 -14
  243. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  244. package/dist/core/tools/edit-diff.js +182 -41
  245. package/dist/core/tools/edit-diff.js.map +1 -1
  246. package/dist/core/tools/edit.d.ts +3 -3
  247. package/dist/core/tools/edit.d.ts.map +1 -1
  248. package/dist/core/tools/edit.js +10 -11
  249. package/dist/core/tools/edit.js.map +1 -1
  250. package/dist/core/tools/find.d.ts +2 -2
  251. package/dist/core/tools/find.d.ts.map +1 -1
  252. package/dist/core/tools/find.js +82 -36
  253. package/dist/core/tools/find.js.map +1 -1
  254. package/dist/core/tools/grep.d.ts +7 -5
  255. package/dist/core/tools/grep.d.ts.map +1 -1
  256. package/dist/core/tools/grep.js +87 -75
  257. package/dist/core/tools/grep.js.map +1 -1
  258. package/dist/core/tools/ls.d.ts +2 -2
  259. package/dist/core/tools/ls.d.ts.map +1 -1
  260. package/dist/core/tools/ls.js +2 -1
  261. package/dist/core/tools/ls.js.map +1 -1
  262. package/dist/core/tools/powershell.d.ts.map +1 -1
  263. package/dist/core/tools/powershell.js +15 -2
  264. package/dist/core/tools/powershell.js.map +1 -1
  265. package/dist/core/tools/read.d.ts +10 -2
  266. package/dist/core/tools/read.d.ts.map +1 -1
  267. package/dist/core/tools/read.js +141 -25
  268. package/dist/core/tools/read.js.map +1 -1
  269. package/dist/core/tools/tool-definition-wrapper.d.ts +11 -1
  270. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  271. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  272. package/dist/core/tools/truncate.d.ts +4 -14
  273. package/dist/core/tools/truncate.d.ts.map +1 -1
  274. package/dist/core/tools/truncate.js +23 -29
  275. package/dist/core/tools/truncate.js.map +1 -1
  276. package/dist/core/tools/write.d.ts +2 -2
  277. package/dist/core/tools/write.d.ts.map +1 -1
  278. package/dist/core/tools/write.js.map +1 -1
  279. package/dist/core/trust-manager.d.ts.map +1 -1
  280. package/dist/core/trust-manager.js +14 -8
  281. package/dist/core/trust-manager.js.map +1 -1
  282. package/dist/core/usage-totals.d.ts.map +1 -1
  283. package/dist/core/usage-totals.js +2 -0
  284. package/dist/core/usage-totals.js.map +1 -1
  285. package/dist/extensions/codemode/execute.js +4 -4
  286. package/dist/extensions/codemode/execute.js.map +1 -1
  287. package/dist/extensions/codemode/tool.d.ts +2 -1
  288. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  289. package/dist/extensions/codemode/tool.js +59 -12
  290. package/dist/extensions/codemode/tool.js.map +1 -1
  291. package/dist/extensions/llama/client.d.ts +2 -0
  292. package/dist/extensions/llama/client.d.ts.map +1 -1
  293. package/dist/extensions/llama/client.js +23 -2
  294. package/dist/extensions/llama/client.js.map +1 -1
  295. package/dist/extensions/llama/index.d.ts.map +1 -1
  296. package/dist/extensions/llama/index.js +1 -1
  297. package/dist/extensions/llama/index.js.map +1 -1
  298. package/dist/extensions/mcp/cli.d.ts +2 -0
  299. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  300. package/dist/extensions/mcp/cli.js +83 -22
  301. package/dist/extensions/mcp/cli.js.map +1 -1
  302. package/dist/extensions/mcp/config.d.ts.map +1 -1
  303. package/dist/extensions/mcp/config.js +4 -7
  304. package/dist/extensions/mcp/config.js.map +1 -1
  305. package/dist/extensions/mcp/index.d.ts.map +1 -1
  306. package/dist/extensions/mcp/index.js +5 -4
  307. package/dist/extensions/mcp/index.js.map +1 -1
  308. package/dist/extensions/mcp/oauth.d.ts +11 -49
  309. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  310. package/dist/extensions/mcp/oauth.js +56 -296
  311. package/dist/extensions/mcp/oauth.js.map +1 -1
  312. package/dist/extensions/mcp/resources.d.ts +1 -1
  313. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  314. package/dist/extensions/mcp/resources.js +4 -3
  315. package/dist/extensions/mcp/resources.js.map +1 -1
  316. package/dist/extensions/mcp/runtime.d.ts +4 -3
  317. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  318. package/dist/extensions/mcp/runtime.js +7 -5
  319. package/dist/extensions/mcp/runtime.js.map +1 -1
  320. package/dist/extensions/mcp/tools.d.ts +2 -23
  321. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  322. package/dist/extensions/mcp/tools.js +6 -58
  323. package/dist/extensions/mcp/tools.js.map +1 -1
  324. package/dist/extensions/punch/index.d.ts.map +1 -1
  325. package/dist/extensions/punch/index.js +1 -1
  326. package/dist/extensions/punch/index.js.map +1 -1
  327. package/dist/extensions/punch/todos.js +1 -1
  328. package/dist/extensions/punch/todos.js.map +1 -1
  329. package/dist/extensions/subagent/index.d.ts.map +1 -1
  330. package/dist/extensions/subagent/index.js +278 -129
  331. package/dist/extensions/subagent/index.js.map +1 -1
  332. package/dist/extensions/tool-search/tool.d.ts +21 -6
  333. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  334. package/dist/extensions/tool-search/tool.js +122 -42
  335. package/dist/extensions/tool-search/tool.js.map +1 -1
  336. package/dist/index.d.ts +4 -4
  337. package/dist/index.d.ts.map +1 -1
  338. package/dist/index.js +2 -0
  339. package/dist/index.js.map +1 -1
  340. package/dist/main.d.ts.map +1 -1
  341. package/dist/main.js +106 -14
  342. package/dist/main.js.map +1 -1
  343. package/dist/modes/print-mode.d.ts.map +1 -1
  344. package/dist/modes/print-mode.js +19 -10
  345. package/dist/modes/print-mode.js.map +1 -1
  346. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  347. package/dist/modes/rpc/rpc-mode.js +53 -23
  348. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  349. package/dist/package-manager-cli.d.ts.map +1 -1
  350. package/dist/package-manager-cli.js +94 -12
  351. package/dist/package-manager-cli.js.map +1 -1
  352. package/dist/utils/ansi.d.ts.map +1 -1
  353. package/dist/utils/ansi.js +5 -2
  354. package/dist/utils/ansi.js.map +1 -1
  355. package/dist/utils/changelog.d.ts +2 -2
  356. package/dist/utils/changelog.d.ts.map +1 -1
  357. package/dist/utils/changelog.js +12 -9
  358. package/dist/utils/changelog.js.map +1 -1
  359. package/dist/utils/clipboard-command.d.ts.map +1 -1
  360. package/dist/utils/clipboard-command.js +4 -0
  361. package/dist/utils/clipboard-command.js.map +1 -1
  362. package/dist/utils/fuzzy.d.ts.map +1 -1
  363. package/dist/utils/fuzzy.js +59 -44
  364. package/dist/utils/fuzzy.js.map +1 -1
  365. package/dist/utils/git.d.ts +11 -1
  366. package/dist/utils/git.d.ts.map +1 -1
  367. package/dist/utils/git.js +44 -0
  368. package/dist/utils/git.js.map +1 -1
  369. package/dist/utils/image-resize-core.d.ts.map +1 -1
  370. package/dist/utils/image-resize-core.js +5 -3
  371. package/dist/utils/image-resize-core.js.map +1 -1
  372. package/dist/utils/image-resize.d.ts.map +1 -1
  373. package/dist/utils/image-resize.js +3 -1
  374. package/dist/utils/image-resize.js.map +1 -1
  375. package/dist/utils/open-browser.d.ts.map +1 -1
  376. package/dist/utils/open-browser.js +4 -1
  377. package/dist/utils/open-browser.js.map +1 -1
  378. package/dist/utils/paths.d.ts +17 -0
  379. package/dist/utils/paths.d.ts.map +1 -1
  380. package/dist/utils/paths.js +42 -1
  381. package/dist/utils/paths.js.map +1 -1
  382. package/dist/utils/shell.d.ts.map +1 -1
  383. package/dist/utils/shell.js +14 -0
  384. package/dist/utils/shell.js.map +1 -1
  385. package/dist/utils/terminal-question.d.ts +8 -0
  386. package/dist/utils/terminal-question.d.ts.map +1 -0
  387. package/dist/utils/terminal-question.js +24 -0
  388. package/dist/utils/terminal-question.js.map +1 -0
  389. package/dist/utils/text.d.ts +2 -0
  390. package/dist/utils/text.d.ts.map +1 -1
  391. package/dist/utils/text.js +5 -0
  392. package/dist/utils/text.js.map +1 -1
  393. package/dist/utils/tools-manager.d.ts.map +1 -1
  394. package/dist/utils/tools-manager.js +30 -35
  395. package/dist/utils/tools-manager.js.map +1 -1
  396. package/dist/utils/web-url.d.ts +12 -0
  397. package/dist/utils/web-url.d.ts.map +1 -0
  398. package/dist/utils/web-url.js +20 -0
  399. package/dist/utils/web-url.js.map +1 -0
  400. package/docs/cli-integration.md +3 -5
  401. package/docs/cli.md +45 -26
  402. package/docs/compaction.md +9 -9
  403. package/docs/configuration.md +1 -2
  404. package/docs/containerization.md +16 -14
  405. package/docs/custom-provider.md +5 -3
  406. package/docs/docs.json +9 -9
  407. package/docs/environment-variables.md +5 -12
  408. package/docs/extensions.md +683 -757
  409. package/docs/how-pi-works.md +5 -5
  410. package/docs/index.md +5 -5
  411. package/docs/llama-cpp.md +41 -39
  412. package/docs/mcp.md +12 -10
  413. package/docs/message-types.md +1 -1
  414. package/docs/models-configuration.md +6 -1
  415. package/docs/models.md +18 -19
  416. package/docs/nvidia-rtx-llama-cpp.md +1 -1
  417. package/docs/packages.md +21 -1
  418. package/docs/prompt-templates.md +11 -9
  419. package/docs/providers.md +8 -8
  420. package/docs/quickstart.md +28 -52
  421. package/docs/rpc-commands.md +2 -2
  422. package/docs/rpc-extension-ui.md +5 -7
  423. package/docs/rpc.md +4 -2
  424. package/docs/sdk.md +1 -1
  425. package/docs/security.md +9 -5
  426. package/docs/session-format.md +7 -9
  427. package/docs/sessions.md +26 -26
  428. package/docs/settings.md +36 -67
  429. package/docs/shell-aliases.md +7 -7
  430. package/docs/skills.md +4 -4
  431. package/docs/slash-commands.md +50 -58
  432. package/docs/termux.md +8 -9
  433. package/docs/themes.md +21 -41
  434. package/docs/usage.md +59 -177
  435. package/docs/virtual-models.md +4 -4
  436. package/docs/windows.md +8 -10
  437. package/examples/extensions/README.md +3 -2
  438. package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  439. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  440. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  441. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  442. package/examples/extensions/gondolin/package-lock.json +19 -29
  443. package/examples/extensions/gondolin/package.json +2 -2
  444. package/examples/extensions/reload-runtime.ts +17 -5
  445. package/examples/extensions/rpc-demo.ts +2 -2
  446. package/examples/extensions/subagent/README.md +14 -11
  447. package/examples/extensions/with-deps/package-lock.json +2 -2
  448. package/examples/extensions/with-deps/package.json +1 -1
  449. package/examples/tsconfig.json +208 -0
  450. package/npm-shrinkwrap.json +58 -53
  451. package/package.json +15 -17
  452. package/schemas/models.schema.json +65 -36
  453. package/schemas/settings.schema.json +17 -243
  454. package/dist/bundle/chunks/anthropic-messages-WCANLUXE.js +0 -6
  455. package/dist/bundle/chunks/azure-openai-responses-46GRAI5B.js +0 -2
  456. package/dist/bundle/chunks/chunk-37OLNCAX.js +0 -16
  457. package/dist/bundle/chunks/chunk-3V45WARH.js +0 -7
  458. package/dist/bundle/chunks/chunk-4LBJE4YM.js +0 -14
  459. package/dist/bundle/chunks/chunk-4NE64BTO.js +0 -82
  460. package/dist/bundle/chunks/chunk-5NXXRYVM.js +0 -2
  461. package/dist/bundle/chunks/chunk-7BOHO7TR.js +0 -1190
  462. package/dist/bundle/chunks/chunk-7XECPCHN.js +0 -2
  463. package/dist/bundle/chunks/chunk-NJK3U3WK.js +0 -8
  464. package/dist/bundle/chunks/chunk-PLK2QSUR.js +0 -2
  465. package/dist/bundle/chunks/chunk-TEPMHNKQ.js +0 -2
  466. package/dist/bundle/chunks/chunk-UE7JCDFW.js +0 -2
  467. package/dist/bundle/chunks/chunk-UKVNB6C4.js +0 -2
  468. package/dist/bundle/chunks/chunk-USJZMAIR.js +0 -2
  469. package/dist/bundle/chunks/chunk-WZONBDPY.js +0 -11
  470. package/dist/bundle/chunks/cli-W5KJM7YB.js +0 -51
  471. package/dist/bundle/chunks/mistral-conversations-D6VQXE7C.js +0 -5
  472. package/dist/bundle/chunks/openai-codex-responses-QSNSWBYG.js +0 -10
  473. package/dist/bundle/chunks/openai-completions-72VXSFHQ.js +0 -7
  474. package/dist/bundle/chunks/openai-responses-PMTL72CY.js +0 -4
  475. package/dist/bundle/chunks/pi-messages-WVCFUCBL.js +0 -8
  476. package/dist/bundle/chunks/virtual-modules-7Y5QW4VK.js +0 -2
  477. package/dist/core/bug-report-upload.d.ts +0 -12
  478. package/dist/core/bug-report-upload.d.ts.map +0 -1
  479. package/dist/core/bug-report-upload.js +0 -22
  480. package/dist/core/bug-report-upload.js.map +0 -1
  481. package/dist/core/bug-report.d.ts +0 -184
  482. package/dist/core/bug-report.d.ts.map +0 -1
  483. package/dist/core/bug-report.js +0 -292
  484. package/dist/core/bug-report.js.map +0 -1
  485. package/dist/core/crash-log.d.ts +0 -27
  486. package/dist/core/crash-log.d.ts.map +0 -1
  487. package/dist/core/crash-log.js +0 -140
  488. package/dist/core/crash-log.js.map +0 -1
  489. package/dist/core/footer-data-provider.d.ts +0 -64
  490. package/dist/core/footer-data-provider.d.ts.map +0 -1
  491. package/dist/core/footer-data-provider.js +0 -338
  492. package/dist/core/footer-data-provider.js.map +0 -1
  493. package/dist/utils/zip.d.ts +0 -7
  494. package/dist/utils/zip.d.ts.map +0 -1
  495. package/dist/utils/zip.js +0 -60
  496. package/dist/utils/zip.js.map +0 -1
  497. package/docs/images/interactive-mode.png +0 -0
  498. package/docs/images/tree-view.png +0 -0
  499. package/docs/keybindings.md +0 -194
  500. package/docs/terminal-setup.md +0 -17
  501. package/docs/tmux.md +0 -55
  502. package/docs/tui.md +0 -125
  503. package/examples/extensions/sandbox/index.ts +0 -321
  504. package/examples/extensions/sandbox/package-lock.json +0 -92
  505. package/examples/extensions/sandbox/package.json +0 -19
@@ -4,27 +4,26 @@
4
4
 
5
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
6
 
7
- > **Placement for /reload:** Put extensions in `~/.pi/agent/extensions/` (global) or `.pi/extensions/` (project-local) for auto-discovery. Use `pi -e ./path.ts` only for quick tests. Extensions in auto-discovered locations can be hot-reloaded with `/reload`.
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 are reloaded by [`ctx.reload()`](#ctxreload) and in the next Pi process.
8
10
 
9
11
  **Key capabilities:**
10
12
  - **Custom tools** - Register tools the LLM can call via `pi.registerTool()`
11
13
  - **Event interception** - Block or modify tool calls, inject context, customize compaction
12
14
  - **User interaction** - Prompt users via `ctx.ui` (select, confirm, input, notify)
13
- - **Custom UI components** - Full TUI components with keyboard input via `ctx.ui.custom()` for complex interactions
14
15
  - **Custom commands** - Register commands like `/mycommand` via `pi.registerCommand()`
15
16
  - **Session persistence** - Store state that survives restarts via `pi.appendEntry()`
16
- - **Custom rendering** - Control how tool calls/results and messages appear in TUI
17
+ - **Providers and MCP servers** - Register model providers, virtual models, and MCP servers
17
18
 
18
19
  **Example use cases:**
19
20
  - Permission gates (confirm before `rm -rf`, `sudo`, etc.)
20
21
  - Git checkpointing (stash at each turn, restore on branch)
21
22
  - Path protection (block writes to `.env`, `node_modules/`)
22
23
  - Custom compaction (summarize conversation your way)
23
- - Conversation summaries (see `summarize.ts` example)
24
- - Interactive tools (questions, wizards, custom dialogs)
24
+ - Interactive tools (questions, confirmations, text input)
25
25
  - Stateful tools (todo lists, connection pools)
26
26
  - External integrations (file watchers, webhooks, CI triggers)
27
- - Games while you wait (see `snake.ts` example)
28
27
 
29
28
  See [examples/extensions/](../examples/extensions/) for working implementations.
30
29
 
@@ -37,28 +36,37 @@ See [examples/extensions/](../examples/extensions/) for working implementations.
37
36
  - [Extension Styles](#extension-styles)
38
37
  - [Events](#events)
39
38
  - [Lifecycle Overview](#lifecycle-overview)
39
+ - [Handler Composition](#handler-composition)
40
+ - [Startup Events](#startup-events)
40
41
  - [Resource Events](#resource-events)
41
42
  - [Session Events](#session-events)
42
43
  - [Agent Events](#agent-events)
43
44
  - [Model Events](#model-events)
44
45
  - [Tool Events](#tool-events)
46
+ - [User Bash Events](#user-bash-events)
47
+ - [Input Events](#input-events)
45
48
  - [ExtensionContext](#extensioncontext)
46
49
  - [ExtensionCommandContext](#extensioncommandcontext)
47
50
  - [ExtensionAPI Methods](#extensionapi-methods)
48
51
  - [State Management](#state-management)
49
52
  - [Custom Tools](#custom-tools)
53
+ - [Tool Exposure](#tool-exposure)
54
+ - [Calling Other Tools](#calling-other-tools)
50
55
  - [Dynamic Tool Loading](#dynamic-tool-loading)
56
+ - [MCP Servers](#mcp-servers)
51
57
  - [Custom UI](#custom-ui)
52
58
  - [Error Handling](#error-handling)
53
59
  - [Mode Behavior](#mode-behavior)
54
60
  - [Examples Reference](#examples-reference)
55
61
 
62
+ <a id="create-an-extension"></a>
63
+
56
64
  ## Quick Start
57
65
 
58
66
  Create `~/.pi/agent/extensions/my-extension.ts`:
59
67
 
60
68
  ```typescript
61
- import type { ExtensionAPI } from "@punch-bot/cli";
69
+ import { type ExtensionAPI, isToolCallEventType } from "@punch-bot/cli";
62
70
  import { Type } from "typebox";
63
71
 
64
72
  export default function (pi: ExtensionAPI) {
@@ -68,7 +76,7 @@ export default function (pi: ExtensionAPI) {
68
76
  });
69
77
 
70
78
  pi.on("tool_call", async (event, ctx) => {
71
- if (event.toolName === "bash" && event.input.command?.includes("rm -rf")) {
79
+ if (isToolCallEventType("bash", event) && event.input.command.includes("rm -rf")) {
72
80
  const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?");
73
81
  if (!ok) return { block: true, reason: "Blocked by user" };
74
82
  }
@@ -106,6 +114,8 @@ Test with `--extension` (or `-e`) flag:
106
114
  pi -e ./my-extension.ts
107
115
  ```
108
116
 
117
+ <a id="choose-where-it-loads"></a>
118
+
109
119
  ## Extension Locations
110
120
 
111
121
  > **Security:** Extensions run with your full system permissions and can execute arbitrary code. Only install from sources you trust.
@@ -114,10 +124,12 @@ Extensions are auto-discovered from trusted locations. Project-local `.pi/extens
114
124
 
115
125
  | Location | Scope |
116
126
  |----------|-------|
117
- | `~/.pi/agent/extensions/*.ts` | Global (all projects) |
118
- | `~/.pi/agent/extensions/*/index.ts` | Global (subdirectory) |
119
- | `.pi/extensions/*.ts` | Project-local |
120
- | `.pi/extensions/*/index.ts` | Project-local (subdirectory) |
127
+ | `~/.pi/agent/extensions/*.ts` or `*.js` | Global (all projects) |
128
+ | `~/.pi/agent/extensions/*/index.ts` or `index.js` | Global (subdirectory) |
129
+ | `~/.pi/agent/extensions/*/package.json` with a `pi.extensions` field | Global (subdirectory with manifest) |
130
+ | `.pi/extensions/...` | Project-local, same layouts |
131
+
132
+ Discovery goes one level deep. Larger packages declare their entry points in a `package.json` manifest.
121
133
 
122
134
  Additional paths via `settings.json`:
123
135
 
@@ -134,20 +146,35 @@ Additional paths via `settings.json`:
134
146
  }
135
147
  ```
136
148
 
137
- To share extensions via npm or git as pi packages, see [packages.md](packages.md).
149
+ 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).
138
150
 
139
151
  ## Available Imports
140
152
 
141
153
  | Package | Purpose |
142
154
  |---------|---------|
143
- | `@punch-bot/cli` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) |
144
- | `typebox` | Schema definitions for tool parameters |
145
- | `@punch-bot/ai` | AI utilities (`StringEnum` for Google-compatible enums) |
146
- | `@punch-bot/tui` | TUI components for custom rendering |
155
+ | `@punch-bot/cli` | Extension types (`ExtensionAPI`, `ExtensionContext`, events) and helpers, including `StringEnum` for string enums |
156
+ | `@punch-bot/agent` | Agent message and tool types |
157
+ | `typebox`, `typebox/compile`, `typebox/value` | Schema definitions for tool parameters |
158
+ | `@punch-bot/ai` | AI utilities (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 |
159
+ | `@punch-bot/ai/compat`, `/models`, `/oauth`, `/providers/all` | Provider construction, built-in APIs, and OAuth helpers |
160
+
161
+ 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.
147
162
 
148
163
  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.
149
164
 
150
- For distributed pi packages installed with `pi install` (npm or git), runtime deps must be in `dependencies`. Package installation uses production installs (`npm install --omit=dev`) by default, so `devDependencies` are not available at runtime; when `npmCommand` is configured, git packages use plain `install` for compatibility with wrappers.
165
+ 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).
166
+
167
+ ### Tool parameter schemas and TypeBox
168
+
169
+ pi validates tool arguments as JSON Schema with `@punch-bot/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:
170
+
171
+ - `Type.Refine()` refinements are not run. Check such constraints in `execute()`.
172
+ - `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.
173
+ - Formats registered with TypeBox's `Format.Set()` are not checked. The standard formats are, plus `url` and `json-pointer-uri-fragment`.
174
+ - Property names are matched as names, not as regular expressions, and `additionalProperties` applies only to properties the object does not declare.
175
+ - A `$ref` that names nothing rejects only arguments at its place.
176
+
177
+ Validation errors the model sees use `@punch-bot/schema`'s messages, such as `- path: missing` or `- limit: expected number, got string`.
151
178
 
152
179
  Node.js built-ins (`node:fs`, `node:path`, etc.) are also available.
153
180
 
@@ -168,10 +195,9 @@ export default function (pi: ExtensionAPI) {
168
195
  ctx.ui.setWidget("my-ext", ["Line 1", "Line 2"]); // Widget above editor (default)
169
196
  });
170
197
 
171
- // Register tools, commands, shortcuts, flags
198
+ // Register tools, commands, flags
172
199
  pi.registerTool({ ... });
173
200
  pi.registerCommand("name", { ... });
174
- pi.registerShortcut("ctrl+x", { ... });
175
201
  pi.registerFlag("my-flag", { ... });
176
202
  }
177
203
  ```
@@ -215,7 +241,7 @@ export default async function (pi: ExtensionAPI) {
215
241
  }
216
242
  ```
217
243
 
218
- This pattern makes the fetched models available during normal startup and to `pi --list-models`.
244
+ 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).
219
245
 
220
246
  ### Long-lived resources and shutdown
221
247
 
@@ -270,94 +296,133 @@ Defer background resource startup until `session_start` or the command/tool/even
270
296
 
271
297
  Run `npm install` in the extension directory, then imports from `node_modules/` work automatically.
272
298
 
299
+ <a id="extension-events"></a>
300
+
273
301
  ## Events
274
302
 
303
+ <a id="understand-the-lifecycle"></a>
304
+
275
305
  ### Lifecycle Overview
276
306
 
307
+ A prompt starts a run. Input handling comes first:
308
+
309
+ 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`.
310
+ 2. `input` handlers can intercept, transform, or handle the text.
311
+ 3. Skill commands (`/skill:name`) and prompt templates (`/template`) expand.
312
+ 4. `before_agent_start` runs, then the agent loop starts.
313
+
314
+ The run repeats turns, then checks whether more work starts another low-level agent run:
315
+
316
+ ```mermaid
317
+ flowchart TD
318
+ Input["input"] --> Before["before_agent_start"]
319
+ Before --> AgentStart["agent_start"]
320
+ AgentStart --> Turns[["turns"]]
321
+ Turns --> AgentEnd["agent_end"]
322
+ AgentEnd --> MoreRuns{"More work?"}
323
+ MoreRuns -->|yes| AgentStart
324
+ MoreRuns -->|no| BeforeSettle["agent_before_settle"]
325
+ BeforeSettle --> Continue{"Continuation requested?"}
326
+ Continue -->|yes| AgentStart
327
+ Continue -->|no| Settled["agent_settled"]
328
+ ```
329
+
330
+ 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.
331
+
332
+ Each turn sends one model request and executes the tool calls in the assistant response:
333
+
334
+ ```mermaid
335
+ flowchart TD
336
+ TurnStart["turn_start"] --> Request[["model request"]]
337
+ Request --> ToolDecision{"Tool calls?"}
338
+ ToolDecision -->|yes| Tools[["tool execution"]]
339
+ Tools --> TurnEnd["turn_end"]
340
+ ToolDecision -->|no| TurnEnd
341
+ TurnEnd --> MoreTurns{"Another turn?"}
342
+ MoreTurns -->|yes| TurnStart
343
+ MoreTurns -->|no| AgentEnd(["agent_end"])
277
344
  ```
278
- pi starts
279
- │
280
- ├─► project_trust (user/global and CLI extensions only, before project resources load)
281
- ├─► session_start { reason: "startup" }
282
- └─► resources_discover { reason: "startup" }
283
- │
284
- ▼
285
- user sends prompt ─────────────────────────────────────────┐
286
- │ │
287
- ├─► (extension commands checked first, bypass if found) │
288
- ├─► input (can intercept, transform, or handle) │
289
- ├─► (skill/template expansion if not handled) │
290
- ├─► before_agent_start (can inject message, modify system prompt)
291
- ├─► agent_start │
292
- ├─► message_start / message_update / message_end │
293
- │ │
294
- │ ┌─── turn (repeats while LLM calls tools) ───┐ │
295
- │ │ │ │
296
- │ ├─► turn_start │ │
297
- │ ├─► context (can modify conversation messages) │
298
- │ ├─► context_with_system (can modify the full transcript)
299
- │ ├─► before_provider_headers (can mutate headers) |
300
- │ ├─► before_provider_request (can inspect or replace payload)
301
- │ ├─► after_provider_response (status + headers, before stream consume)
302
- │ │ │ │
303
- │ │ LLM responds, may call tools: │ │
304
- │ │ ├─► tool_execution_start │ │
305
- │ │ ├─► tool_call (can block) │ │
306
- │ │ ├─► tool_execution_update │ │
307
- │ │ ├─► tool_result (can modify) │ │
308
- │ │ └─► tool_execution_end │ │
309
- │ │ │ │
310
- │ └─► turn_end │ │
311
- │ └─► threshold compaction before a naturally required next turn
312
- │ │
313
- ├─► agent_end │
314
- ├─► retry backoff or final-attempt recovery (when selected)
315
- │ └─► fresh agent_start on successful recovery │
316
- ├─► agent_before_settle (can append entries and continue)│
317
- └─► agent_settled (final, notification only) │
318
- │
319
- user sends another prompt ◄────────────────────────────────┘
320
-
321
- /new (new session) or /resume (switch session)
322
- ├─► session_before_switch (can cancel)
323
- ├─► session_shutdown
324
- ├─► session_start { reason: "new" | "resume", previousSessionFile? }
325
- └─► resources_discover { reason: "startup" }
326
-
327
- /fork or /clone
328
- ├─► session_before_fork (can cancel)
329
- ├─► session_shutdown
330
- ├─► session_start { reason: "fork", previousSessionFile }
331
- └─► resources_discover { reason: "startup" }
332
-
333
- /name or pi.setSessionName()
334
- └─► session_info_changed
335
-
336
- /compact or auto-compaction
337
- ├─► session_before_compact (can cancel or customize)
338
- ├─► session_compact (success)
339
- └─► session_compact_failed (failure or abort)
340
-
341
- /tree navigation
342
- ├─► session_before_tree (can cancel or customize)
343
- └─► session_tree
344
-
345
- /model or Ctrl+P (model selection/cycling)
346
- ├─► thinking_level_select (if model change changes/clamps thinking level)
347
- └─► model_select
348
-
349
- thinking level changes (settings, keybinding, pi.setThinkingLevel())
350
- └─► thinking_level_select
351
-
352
- exit (Ctrl+C, Ctrl+D, SIGHUP, SIGTERM)
353
- └─► session_shutdown
345
+
346
+ The model request runs these hooks in order:
347
+
348
+ 1. `context` (can modify conversation messages)
349
+ 2. `context_with_system` (can modify the full transcript)
350
+ 3. `before_provider_headers` (can mutate headers)
351
+ 4. `before_provider_request` (can inspect or replace the payload)
352
+ 5. `after_provider_response` (status and headers, before the stream is consumed)
353
+ 6. `provider_stream_event` (raw parsed stream events) and `message_start` / `message_update` / `message_end` for the assistant message
354
+
355
+ A tool call that executes runs these hooks in order:
356
+
357
+ 1. `tool_execution_start`
358
+ 2. `tool_call` (can block or mutate input)
359
+ 3. `tool_execution_update` while the tool executes
360
+ 4. `tool_result` (can modify the result)
361
+ 5. `tool_execution_end`
362
+
363
+ 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.
364
+
365
+ `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.
366
+
367
+ Session startup and replacement follow a separate lifecycle:
368
+
369
+ ```mermaid
370
+ flowchart TD
371
+ Startup["Process startup"] --> Trust["project_trust when needed"]
372
+ Trust --> SessionStart["session_start"]
373
+ Switch["new_session or switch_session"] --> BeforeSwitch["session_before_switch"]
374
+ Fork["fork or clone"] --> BeforeFork["session_before_fork"]
375
+ BeforeSwitch --> Shutdown["session_shutdown"]
376
+ BeforeFork --> Shutdown
377
+ Reload["ctx.reload()"] --> Shutdown
378
+ Exit["exit"] --> Shutdown
379
+ Shutdown --> Replacing{"Replacing the runtime?"}
380
+ Replacing -->|yes| ReplacementTrust["project_trust when the working directory is new"]
381
+ ReplacementTrust --> Replacement["load replacement extension runtime"]
382
+ Replacement --> SessionStart
383
+ Replacing -->|no| Stop["process exits"]
384
+ SessionStart --> Discover["resources_discover"]
354
385
  ```
355
386
 
387
+ `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 the end of a print-mode run, the RPC input closing, `ctx.shutdown()`, SIGHUP, and SIGTERM. `project_trust` runs before trusted project resources load and can run again when session replacement enters a new working directory.
388
+
389
+ Other operations change the current session without replacing the runtime:
390
+
391
+ | Operation | Events |
392
+ |---|---|
393
+ | RPC `compact`, `ctx.compact()`, or automatic compaction | `session_before_compact` (can cancel or customize), then `session_compact` or `session_compact_failed` |
394
+ | `ctx.navigateTree()` | `session_before_tree` (can cancel or customize), then `session_tree` |
395
+ | `--name`, RPC `set_session_name`, or `pi.setSessionName()` | `session_info_changed` |
396
+ | RPC `set_model`, model cycling (RPC `cycle_model`), or `pi.setModel()` | `thinking_level_select` if the level changes or is clamped, then `model_select` |
397
+ | Thinking-level change (settings, RPC `set_thinking_level` or `cycle_thinking_level`, `pi.setThinkingLevel()`) | `thinking_level_select` |
398
+ | RPC `bash` command | `user_bash` (can intercept) |
399
+ | Extension dialog waits for the user | `ui_prompt_start`, `ui_prompt_end` |
400
+ | Idle prompt-cache refresh | `cache_warming_decision` |
401
+ | Extension registers or removes an MCP server after startup | `mcp_servers_change` |
402
+
403
+ <a id="events-and-concurrency"></a>
404
+ <a id="work-with-events"></a>
405
+
406
+ ### Handler Composition
407
+
408
+ Handlers run in extension load order, then registration order. Some events notify; others transform data, replace results, or cancel an operation:
409
+
410
+ | Pattern | Behavior |
411
+ |---|---|
412
+ | Notification | Return values are ignored. Use the event for observation only. |
413
+ | In-place mutation | Later handlers see changes to values such as `before_provider_headers.headers`, `before_agent_start.systemPromptOptions`, and `tool_call.input`. |
414
+ | Chained transformation | Later handlers receive the value returned by earlier `input`, `context`, `context_with_system`, `message_end`, `tool_result`, and `before_provider_request` handlers. |
415
+ | Gate | A handled input, blocked tool call, cancelled session operation, or handled `user_bash` command stops that operation's normal fallback path. |
416
+ | Actionable boundary | Each `turn_end` or `agent_before_settle` handler sees the entries and continuation decision proposed so far. |
417
+ | Last override | The last `cache_warming_decision` handler that returns an action wins. |
418
+
419
+ 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.
420
+
356
421
  ### Startup Events
357
422
 
358
423
  #### project_trust
359
424
 
360
- 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.
425
+ 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 RPC `switch_session`) 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.
361
426
 
362
427
  ```typescript
363
428
  pi.on("project_trust", async (event, ctx) => {
@@ -391,6 +456,10 @@ pi.on("resources_discover", async (event, _ctx) => {
391
456
  });
392
457
  ```
393
458
 
459
+ #### mcp_servers_change
460
+
461
+ 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).
462
+
394
463
  ### Session Events
395
464
 
396
465
  See [Session Format](session-format.md) for session storage internals and the SessionManager API.
@@ -409,7 +478,7 @@ pi.on("session_start", async (event, ctx) => {
409
478
 
410
479
  #### session_info_changed
411
480
 
412
- Fired when the current session display name is set via `/name`, RPC, or `pi.setSessionName()`.
481
+ Fired when the current session display name is set via `--name`, RPC `set_session_name`, or `pi.setSessionName()`.
413
482
 
414
483
  ```typescript
415
484
  pi.on("session_info_changed", async (event, ctx) => {
@@ -420,7 +489,7 @@ pi.on("session_info_changed", async (event, ctx) => {
420
489
 
421
490
  #### session_before_switch
422
491
 
423
- Fired before starting a new session (`/new`) or switching sessions (`/resume`).
492
+ Fired before starting a new session (RPC `new_session`, `ctx.newSession()`) or switching sessions (RPC `switch_session`, `ctx.switchSession()`).
424
493
 
425
494
  ```typescript
426
495
  pi.on("session_before_switch", async (event, ctx) => {
@@ -439,12 +508,12 @@ Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `
439
508
 
440
509
  #### session_before_fork
441
510
 
442
- Fired when forking via `/fork` or cloning via `/clone`.
511
+ Fired when forking via RPC `fork` or cloning via RPC `clone`, or through `ctx.fork()`.
443
512
 
444
513
  ```typescript
445
514
  pi.on("session_before_fork", async (event, ctx) => {
446
515
  // event.entryId - ID of the selected entry
447
- // event.position - "before" for /fork, "at" for /clone
516
+ // event.position - "before" for fork, "at" for clone
448
517
  return { cancel: true }; // Cancel fork/clone
449
518
  // OR
450
519
  return { skipConversationRestore: true }; // Reserved for future conversation restore control
@@ -454,6 +523,8 @@ pi.on("session_before_fork", async (event, ctx) => {
454
523
  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`.
455
524
  Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
456
525
 
526
+ <a id="session_before_compact--session_compact"></a>
527
+
457
528
  #### session_before_compact / session_compact / session_compact_failed
458
529
 
459
530
  Fired on compaction. See [compaction.md](compaction.md) for details.
@@ -462,7 +533,7 @@ Fired on compaction. See [compaction.md](compaction.md) for details.
462
533
  pi.on("session_before_compact", async (event, ctx) => {
463
534
  const { preparation, branchEntries, customInstructions, reason, willRetry, signal } = event;
464
535
 
465
- // reason - "manual" (/compact), "threshold", or "overflow"
536
+ // reason - "manual" (RPC `compact` or `ctx.compact()`), "threshold", or "overflow"
466
537
  // willRetry - whether the aborted turn is retried after compaction (overflow recovery)
467
538
 
468
539
  // Cancel:
@@ -482,12 +553,12 @@ pi.on("session_before_compact", async (event, ctx) => {
482
553
  pi.on("session_compact", async (event, ctx) => {
483
554
  // event.compactionEntry - the saved compaction
484
555
  // event.fromExtension - whether extension provided it
485
- // event.reason - "manual" (/compact), "threshold", or "overflow"
556
+ // event.reason - "manual" (RPC `compact` or `ctx.compact()`), "threshold", or "overflow"
486
557
  // event.willRetry - whether the aborted turn is retried after compaction (overflow recovery)
487
558
  });
488
559
 
489
560
  pi.on("session_compact_failed", async (event, ctx) => {
490
- // event.reason - "manual" (/compact), "threshold", or "overflow"
561
+ // event.reason - "manual" (RPC `compact` or `ctx.compact()`), "threshold", or "overflow"
491
562
  // event.errorMessage - present for non-abort failures
492
563
  // event.aborted - true for cancelled/aborted compactions
493
564
  // event.willRetry - whether the aborted turn would have retried after compaction
@@ -497,13 +568,15 @@ pi.on("session_compact_failed", async (event, ctx) => {
497
568
 
498
569
  #### session_before_tree / session_tree
499
570
 
500
- Fired on `/tree` navigation. See [Sessions](sessions.md) for tree navigation concepts.
571
+ Fired on `ctx.navigateTree()`. See [Sessions](sessions.md) for tree navigation concepts.
501
572
 
502
573
  ```typescript
503
574
  pi.on("session_before_tree", async (event, ctx) => {
504
575
  const { preparation, signal } = event;
576
+ // preparation.targetId, oldLeafId, commonAncestorId, entriesToSummarize,
577
+ // userWantsSummary, customInstructions, replaceInstructions, label
505
578
  return { cancel: true };
506
- // OR provide custom summary:
579
+ // OR provide custom summary (used only when preparation.userWantsSummary is true):
507
580
  return {
508
581
  summary: {
509
582
  summary: "...",
@@ -511,6 +584,7 @@ pi.on("session_before_tree", async (event, ctx) => {
511
584
  details: {},
512
585
  },
513
586
  };
587
+ // OR override summarization options: customInstructions, replaceInstructions, label
514
588
  });
515
589
 
516
590
  pi.on("session_tree", async (event, ctx) => {
@@ -534,21 +608,25 @@ pi.on("session_shutdown", async (event, ctx) => {
534
608
 
535
609
  #### before_agent_start
536
610
 
537
- Fired after user submits prompt, before agent loop. Can inject a message and/or modify the system prompt.
611
+ Fired before a run starts, after input handling and expansion. Can inject a message and/or modify the system prompt.
612
+
613
+ `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`.
538
614
 
539
615
  ```typescript
540
616
  pi.on("before_agent_start", async (event, ctx) => {
541
- // event.prompt - user's prompt text
542
- // event.images - attached images (if any)
617
+ // event.messageType - "user" | "custom"
618
+ // event.prompt, event.images - user's prompt text and images (messageType "user")
619
+ // event.message - the custom message that starts the run (messageType "custom")
543
620
  // event.systemPrompt - current chained system prompt for this handler
544
621
  // (includes changes from earlier before_agent_start handlers)
545
622
  // event.systemPromptOptions - structured options used to build the system prompt
546
623
  // .customPrompt - exact prompt prefix from --system-prompt, SYSTEM.md, or custom templates
547
624
  // .forceSystemPrompt - optional exact replacement for the complete prompt
548
625
  // .selectedTools - tools currently active in the prompt
626
+ // .hiddenTools - selected tools whose declarations requests leave out
549
627
  // .toolSnippets - one-line descriptions for each tool
550
- // .toolGuidelines - guideline bullets keyed by tool name
551
- // .promptGuidelines - additional custom guideline bullets
628
+ // .toolGuidelines - rule bullets keyed by tool name
629
+ // .promptGuidelines - additional custom rule bullets
552
630
  // .sections - custom XML-wrapped sections keyed by tag name
553
631
  // .appendSystemPrompt - text from --append-system-prompt flags
554
632
  // .cwd - working directory
@@ -568,10 +646,14 @@ pi.on("before_agent_start", async (event, ctx) => {
568
646
  });
569
647
  ```
570
648
 
649
+ A returned `message` is added to either kind of run; check `messageType` to skip runs started by custom messages.
650
+
571
651
  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.
572
652
 
573
653
  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.
574
654
 
655
+ <a id="agent_start--agent_end--agent_settled"></a>
656
+
575
657
  #### agent_start / agent_end / agent_before_settle / agent_settled
576
658
 
577
659
  `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.
@@ -598,7 +680,8 @@ pi.on("agent_before_settle", async (event, ctx) => {
598
680
  };
599
681
  });
600
682
 
601
- pi.on("agent_settled", async (_event, ctx) => {
683
+ pi.on("agent_settled", async (event, ctx) => {
684
+ // event.aborted - true when the run ended because it was aborted, for example with ctx.abort()
602
685
  // ctx.isIdle() is true; runs requested here start after all settled handlers finish.
603
686
  });
604
687
  ```
@@ -607,14 +690,14 @@ If the run is aborted while `agent_before_settle` handlers are running, valid re
607
690
 
608
691
  #### ui_prompt_start / ui_prompt_end
609
692
 
610
- 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".
693
+ Notification-only lifecycle events for blocking user-facing extension UI prompts. They fire around `ctx.ui.select()`, `ctx.ui.confirm()`, `ctx.ui.input()`, and `ctx.ui.editor()` so host/status integrations can report "waiting for user" instead of just "running".
611
694
 
612
695
  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.
613
696
 
614
697
  ```typescript
615
698
  pi.on("ui_prompt_start", async (event, ctx) => {
616
699
  // event.reason === "ui_prompt"
617
- // event.kind: "select" | "confirm" | "input" | "editor" | "custom"
700
+ // event.kind: "select" | "confirm" | "input" | "editor"
618
701
  // event.title: prompt title when available
619
702
  });
620
703
 
@@ -658,13 +741,13 @@ pi.on("turn_end", async (event, ctx) => {
658
741
 
659
742
  `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.
660
743
 
661
- Host integrations that construct `TurnEndEvent` values must now 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_*`.
744
+ 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_*`.
662
745
 
663
746
  #### message_start / message_update / message_end
664
747
 
665
748
  Fired for message lifecycle updates.
666
749
 
667
- - `message_start` and `message_end` fire for user, assistant, and toolResult messages.
750
+ - `message_start` and `message_end` fire for every message, including user, assistant, tool-result, and custom messages.
668
751
  - `message_update` fires for assistant streaming updates.
669
752
  - `message_end` handlers can return `{ message }` to replace the finalized message. The replacement must keep the same `role`.
670
753
 
@@ -717,9 +800,12 @@ pi.on("tool_execution_update", async (event, ctx) => {
717
800
 
718
801
  pi.on("tool_execution_end", async (event, ctx) => {
719
802
  // event.toolCallId, event.toolName, event.result, event.isError
803
+ // event.durationMs - milliseconds execute() took; absent when the tool did not run
720
804
  });
721
805
  ```
722
806
 
807
+ All three events, `tool_call`, and `tool_result` carry `parentToolCallId` when another tool made the call; see [Calling Other Tools](#calling-other-tools).
808
+
723
809
  #### context
724
810
 
725
811
  Fired before each LLM call. Modify messages non-destructively. See [Session Format](session-format.md) for message types.
@@ -786,6 +872,8 @@ pi.on("before_provider_request", (event, ctx) => {
786
872
 
787
873
  This is mainly useful for debugging provider serialization and cache behavior.
788
874
 
875
+ The payload is the full request. Providers that continue from a previous response (OpenAI Codex over WebSocket, Anthropic message threads) may send only the part that is new since the previous request.
876
+
789
877
  #### after_provider_response
790
878
 
791
879
  Fired after an HTTP response is received and before its stream body is consumed. Handlers run in extension load order.
@@ -802,6 +890,19 @@ pi.on("after_provider_response", (event, ctx) => {
802
890
 
803
891
  Header availability depends on provider and transport. Providers that abstract HTTP responses may not expose headers.
804
892
 
893
+ #### provider_stream_event
894
+
895
+ Fired for each parsed provider stream event before pi normalizes it. Notification-only and not persisted.
896
+
897
+ ```typescript
898
+ pi.on("provider_stream_event", (event, ctx) => {
899
+ // event.provider, event.api, event.model
900
+ // event.data - earliest structured value available to Pi (read-only)
901
+ });
902
+ ```
903
+
904
+ `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 capture that stores raw events, grouped by assistant message, as custom entries.
905
+
805
906
  #### cache_warming_decision
806
907
 
807
908
  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.
@@ -825,13 +926,13 @@ Return `{ action: "warm" }` or `{ action: "stop" }` to override; the last handle
825
926
 
826
927
  #### model_select
827
928
 
828
- Fired when the model changes via `/model` command, model cycling (`Ctrl+P`), or session restore.
929
+ Fired when the model changes via RPC `set_model`, model cycling (RPC `cycle_model`), or `pi.setModel()`. Restoring a session does not fire it; read `ctx.model` in `session_start` to initialize model-dependent state.
829
930
 
830
931
  ```typescript
831
932
  pi.on("model_select", async (event, ctx) => {
832
933
  // event.model - newly selected model
833
934
  // event.previousModel - previous model (undefined if first selection)
834
- // event.source - "set" | "cycle" | "restore"
935
+ // event.source - "set" | "cycle"
835
936
 
836
937
  const prev = event.previousModel
837
938
  ? `${event.previousModel.provider}/${event.previousModel.id}`
@@ -842,7 +943,7 @@ pi.on("model_select", async (event, ctx) => {
842
943
  });
843
944
  ```
844
945
 
845
- Use this to update UI elements (status bars, footers) or perform model-specific initialization when the active model changes.
946
+ Use this to update UI elements such as status entries or perform model-specific initialization when the active model changes.
846
947
 
847
948
  #### thinking_level_select
848
949
 
@@ -859,6 +960,8 @@ pi.on("thinking_level_select", async (event, ctx) => {
859
960
 
860
961
  Use this to update extension UI when `pi.setThinkingLevel()`, model changes, or built-in thinking-level controls change the active thinking level.
861
962
 
963
+ <a id="tool-call-events"></a>
964
+
862
965
  ### Tool Events
863
966
 
864
967
  #### tool_call
@@ -908,7 +1011,10 @@ pi.on("tool_call", async (event, ctx) => {
908
1011
  Custom tools should export their input type:
909
1012
 
910
1013
  ```typescript
911
- // my-extension.ts
1014
+ // my-tool.ts
1015
+ import { type Static, Type } from "typebox";
1016
+
1017
+ export const myToolSchema = Type.Object({ action: Type.String() });
912
1018
  export type MyToolInput = Static<typeof myToolSchema>;
913
1019
  ```
914
1020
 
@@ -916,7 +1022,7 @@ Use `isToolCallEventType` with explicit type parameters:
916
1022
 
917
1023
  ```typescript
918
1024
  import { isToolCallEventType } from "@punch-bot/cli";
919
- import type { MyToolInput } from "my-extension";
1025
+ import type { MyToolInput } from "./my-tool.ts";
920
1026
 
921
1027
  pi.on("tool_call", (event) => {
922
1028
  if (isToolCallEventType<"my_tool", MyToolInput>("my_tool", event)) {
@@ -934,7 +1040,8 @@ In parallel tool mode, `tool_result` and `tool_execution_end` may interleave in
934
1040
  `tool_result` handlers chain like middleware:
935
1041
  - Handlers run in extension load order
936
1042
  - Each handler sees the latest result after previous handler changes
937
- - Handlers can return partial patches (`content`, `details`, `isError`, or `usage`); omitted fields keep their current values
1043
+ - Handlers can return partial patches (`content`, `details`, `structuredContent`, `isError`, or `usage`); omitted fields keep their current values
1044
+ - Replacing `content` without returning `structuredContent` drops the structured content, because it may no longer match
938
1045
 
939
1046
  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.
940
1047
 
@@ -942,8 +1049,8 @@ Use `ctx.signal` for nested async work inside the handler. This lets Esc cancel
942
1049
  import { isBashToolResult } from "@punch-bot/cli";
943
1050
 
944
1051
  pi.on("tool_result", async (event, ctx) => {
945
- // event.toolName, event.toolCallId, event.input
946
- // event.content, event.details, event.isError, event.usage
1052
+ // event.toolName, event.toolCallId, event.input, event.parentToolCallId
1053
+ // event.content, event.details, event.structuredContent, event.isError, event.usage
947
1054
 
948
1055
  if (isBashToolResult(event)) {
949
1056
  // event.details is typed as BashToolDetails
@@ -964,7 +1071,7 @@ pi.on("tool_result", async (event, ctx) => {
964
1071
 
965
1072
  #### user_bash
966
1073
 
967
- Fired when user executes `!` or `!!` commands. **Can intercept.**
1074
+ Fired when an RPC client runs the [`bash`](rpc-commands.md#bash) command. `excludeFromContext` is `true` when the output should stay out of model context. **Can intercept.**
968
1075
 
969
1076
  ```typescript
970
1077
  import { createLocalBashOperations } from "@punch-bot/cli";
@@ -1001,7 +1108,7 @@ Returning `undefined` continues to the next handler, then local execution if non
1001
1108
  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.
1002
1109
 
1003
1110
  **Processing order:**
1004
- 1. Extension commands (`/cmd`) checked first - if found, handler runs and input event is skipped
1111
+ 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`.
1005
1112
  2. `input` event fires - can intercept, transform, or handle
1006
1113
  3. If not handled: skill commands (`/skill:name`) expanded to skill content
1007
1114
  4. If not handled: prompt templates (`/template`) expanded to template content
@@ -1045,9 +1152,11 @@ pi.on("input", async (event, ctx) => {
1045
1152
 
1046
1153
  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.
1047
1154
 
1155
+ <a id="use-extension-context"></a>
1156
+
1048
1157
  ## ExtensionContext
1049
1158
 
1050
- All handlers receive `ctx: ExtensionContext`.
1159
+ 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).
1051
1160
 
1052
1161
  ### ctx.ui
1053
1162
 
@@ -1055,11 +1164,11 @@ UI methods for user interaction. See [Custom UI](#custom-ui) for full details.
1055
1164
 
1056
1165
  ### ctx.mode
1057
1166
 
1058
- 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.
1167
+ Current run mode: `"rpc"`, `"json"`, or `"print"`. See [Mode Behavior](#mode-behavior).
1059
1168
 
1060
1169
  ### ctx.hasUI
1061
1170
 
1062
- `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.md](rpc.md#extension-ui-protocol)).
1171
+ `true` in RPC mode. `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`). In RPC mode, some methods are no-ops or return defaults (see [RPC Extension UI](rpc-extension-ui.md)).
1063
1172
 
1064
1173
  ### ctx.cwd
1065
1174
 
@@ -1087,7 +1196,7 @@ Use this before reading project-local extension configuration that should only b
1087
1196
 
1088
1197
  ### ctx.sessionManager
1089
1198
 
1090
- Read-only access to session state. See [Session Format](session-format.md) for the full SessionManager API and entry types.
1199
+ 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.
1091
1200
 
1092
1201
  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.
1093
1202
 
@@ -1102,13 +1211,15 @@ ctx.sessionManager.getLeafId() // Current leaf entry ID
1102
1211
 
1103
1212
  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.
1104
1213
 
1105
- `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()`.
1214
+ `ctx.scopedModels` is the read-only list of models scoped to the current session — the same set RPC `cycle_model` cycles through. 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()`.
1106
1215
 
1107
1216
  #### Streaming model calls
1108
1217
 
1109
- Use `ctx.modelRegistry.streamSimple(model, context, options)` for provider-neutral options such as `reasoning`, or `stream()` for 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.
1218
+ 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.
1110
1219
 
1111
- Both return an `AssistantMessageEventStream`. Iterate it for response events and await `.result()` for the final message. Setup failures produce error events and error results.
1220
+ `streamSimple()` returns an `AssistantMessageEventStream`. Iterate it for response events and await `.result()` for the final message. Setup failures produce error events and error results.
1221
+
1222
+ 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).
1112
1223
 
1113
1224
  ### ctx.signal
1114
1225
 
@@ -1120,7 +1231,7 @@ Use this for abort-aware nested work started by extension handlers, for example:
1120
1231
  - file or process helpers that accept `AbortSignal`
1121
1232
 
1122
1233
  `ctx.signal` is typically defined during active turn events such as `tool_call`, `tool_result`, `message_update`, and `turn_end`.
1123
- It is usually `undefined` in idle or non-turn contexts such as session events, extension commands, and shortcuts fired while pi is idle.
1234
+ It is usually `undefined` in idle or non-turn contexts such as session events and extension commands run while pi is idle.
1124
1235
 
1125
1236
  ```typescript
1126
1237
  pi.on("tool_result", async (event, ctx) => {
@@ -1143,11 +1254,10 @@ Control flow helpers. `ctx.isIdle()` is false while Pi is processing an agent ru
1143
1254
 
1144
1255
  Request a graceful shutdown of pi.
1145
1256
 
1146
- - **Interactive mode:** Deferred until the agent becomes idle (after processing all queued steering and follow-up messages).
1147
- - **RPC mode:** Deferred until the next idle state (after completing the current command response, when waiting for the next command).
1257
+ - **RPC mode:** Runs right away when the session is idle and no command is being handled. Otherwise deferred until the current command finishes (including its response) or the active run settles. (A request made while an extension-started compaction is running waits for the next command or run to finish.)
1148
1258
  - **Print mode:** No-op. The process exits automatically when all prompts are processed.
1149
1259
 
1150
- Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands, shortcuts).
1260
+ Emits `session_shutdown` event to all extensions before exiting. Available in all contexts (event handlers, tools, commands).
1151
1261
 
1152
1262
  ```typescript
1153
1263
  pi.on("tool_call", (event, ctx) => {
@@ -1163,7 +1273,7 @@ Returns current context usage for the active model. Uses last assistant usage wh
1163
1273
 
1164
1274
  ```typescript
1165
1275
  const usage = ctx.getContextUsage();
1166
- if (usage && usage.tokens > 100_000) {
1276
+ if (usage?.tokens != null && usage.tokens > 100_000) {
1167
1277
  // ...
1168
1278
  }
1169
1279
  ```
@@ -1285,13 +1395,13 @@ if (cloneResult.cancelled) {
1285
1395
  ```
1286
1396
 
1287
1397
  Options:
1288
- - `position`: `"before"` (default) forks before the selected user message, restoring that prompt into the editor
1289
- - `position`: `"at"` duplicates the active path through the selected entry without restoring editor text
1398
+ - `position`: `"before"` (default) forks before the selected user message; RPC `fork` returns that prompt's text
1399
+ - `position`: `"at"` duplicates the active path through the selected entry
1290
1400
  - `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).
1291
1401
 
1292
1402
  ### ctx.navigateTree(targetId, options?)
1293
1403
 
1294
- 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:
1404
+ 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:
1295
1405
 
1296
1406
  ```typescript
1297
1407
  const result = await ctx.navigateTree("entry-id-456", {
@@ -1338,7 +1448,7 @@ pi.registerCommand("switch", {
1338
1448
  if (sessions.length === 0) return;
1339
1449
  const choice = await ctx.ui.select(
1340
1450
  "Pick session:",
1341
- sessions.map(s => s.file),
1451
+ sessions.map((s) => s.path),
1342
1452
  );
1343
1453
  if (choice) {
1344
1454
  await ctx.switchSession(choice, {
@@ -1396,7 +1506,7 @@ pi.registerCommand("handoff", {
1396
1506
 
1397
1507
  ### ctx.reload()
1398
1508
 
1399
- Run the same reload flow as `/reload`.
1509
+ Reload settings, extensions, skills, prompt templates, themes, and context files in the running session.
1400
1510
 
1401
1511
  ```typescript
1402
1512
  pi.registerCommand("reload-runtime", {
@@ -1418,38 +1528,35 @@ Important behavior:
1418
1528
 
1419
1529
  For predictable behavior, treat reload as terminal for that handler (`await ctx.reload(); return;`).
1420
1530
 
1421
- Tools run with `ExtensionContext`, so they cannot call `ctx.reload()` directly. Use a command as the reload entrypoint, then expose a tool that queues that command as a follow-up user message.
1422
-
1423
- Example tool the LLM can call to trigger reload:
1531
+ 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:
1424
1532
 
1425
1533
  ```typescript
1426
- import type { ExtensionAPI } from "@punch-bot/cli";
1427
- import { Type } from "typebox";
1534
+ let reloadRequested = false;
1428
1535
 
1429
- export default function (pi: ExtensionAPI) {
1430
- pi.registerCommand("reload-runtime", {
1431
- description: "Reload extensions, skills, prompts, themes, and context files",
1432
- handler: async (_args, ctx) => {
1433
- await ctx.reload();
1434
- return;
1435
- },
1436
- });
1536
+ pi.registerTool({
1537
+ name: "reload_runtime",
1538
+ label: "Reload Runtime",
1539
+ description: "Reload extensions, skills, prompts, themes, and context files",
1540
+ parameters: Type.Object({}),
1541
+ async execute() {
1542
+ reloadRequested = true;
1543
+ return {
1544
+ content: [{ type: "text", text: "Reload requested. Pi reloads after this response." }],
1545
+ details: {},
1546
+ terminate: true,
1547
+ };
1548
+ },
1549
+ });
1437
1550
 
1438
- pi.registerTool({
1439
- name: "reload_runtime",
1440
- label: "Reload Runtime",
1441
- description: "Reload extensions, skills, prompts, themes, and context files",
1442
- parameters: Type.Object({}),
1443
- async execute() {
1444
- pi.sendUserMessage("/reload-runtime", { deliverAs: "followUp" });
1445
- return {
1446
- content: [{ type: "text", text: "Queued /reload-runtime as a follow-up command." }],
1447
- };
1448
- },
1449
- });
1450
- }
1551
+ pi.on("agent_settled", () => {
1552
+ if (!reloadRequested) return;
1553
+ reloadRequested = false;
1554
+ pi.sendUserMessage("/reload-runtime", { expandPromptTemplates: true });
1555
+ });
1451
1556
  ```
1452
1557
 
1558
+ `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).
1559
+
1453
1560
  ## ExtensionAPI Methods
1454
1561
 
1455
1562
  ### pi.on(event, handler)
@@ -1469,19 +1576,19 @@ Handlers run in extension load order, then registration order within each extens
1469
1576
 
1470
1577
  Register a custom tool callable by the LLM. See [Custom Tools](#custom-tools) for full details.
1471
1578
 
1472
- `pi.registerTool()` works both during extension load and after startup. You can call it inside `session_start`, command handlers, or other event handlers. New tools are refreshed immediately in the same session, so they appear in `pi.getAllTools()` and are callable by the LLM without `/reload`.
1579
+ `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`.
1473
1580
 
1474
1581
  Use `pi.setActiveTools()` to enable or disable tools (including dynamically added tools) at runtime.
1475
1582
 
1476
- Use `promptSnippet` to opt a custom tool into a one-line entry in `Available tools`, and `promptGuidelines` to append tool-specific bullets to the default `Guidelines` section when the tool is active.
1583
+ 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.
1477
1584
 
1478
- **Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` section with no tool name prefix. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead.
1585
+ **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.
1479
1586
 
1480
1587
  See [dynamic-tools.ts](../examples/extensions/dynamic-tools.ts) for a full example.
1481
1588
 
1482
1589
  ```typescript
1590
+ import { StringEnum } from "@punch-bot/cli";
1483
1591
  import { Type } from "typebox";
1484
- import { StringEnum } from "@punch-bot/ai";
1485
1592
 
1486
1593
  pi.registerTool({
1487
1594
  name: "my_tool",
@@ -1493,32 +1600,22 @@ pi.registerTool({
1493
1600
  action: StringEnum(["list", "add"] as const),
1494
1601
  text: Type.Optional(Type.String()),
1495
1602
  }),
1496
- prepareArguments(args) {
1497
- // Optional compatibility shim. Runs before schema validation.
1498
- // Return the current schema shape, for example to fold legacy fields
1499
- // into the modern parameter object.
1500
- return args;
1501
- },
1502
1603
 
1503
1604
  async execute(toolCallId, params, signal, onUpdate, ctx) {
1504
- // Stream progress
1505
- onUpdate?.({ content: [{ type: "text", text: "Working..." }] });
1605
+ // Stream progress; partial results also need details
1606
+ onUpdate?.({ content: [{ type: "text", text: "Working..." }], details: { result: "pending" } });
1506
1607
 
1507
1608
  return {
1508
1609
  content: [{ type: "text", text: "Done" }],
1509
1610
  details: { result: "..." },
1510
1611
  };
1511
1612
  },
1512
-
1513
- // Optional: Custom rendering
1514
- renderCall(args, theme, context) { ... },
1515
- renderResult(result, options, theme, context) { ... },
1516
1613
  });
1517
1614
  ```
1518
1615
 
1519
1616
  ### pi.sendMessage(message, options?)
1520
1617
 
1521
- 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).
1618
+ Inject a custom message into the session. Custom messages participate in LLM context. For durable data that should not be sent to the LLM, use [`pi.appendEntry()`](#piappendentrycustomtype-data).
1522
1619
 
1523
1620
  ```typescript
1524
1621
  pi.sendMessage({
@@ -1537,11 +1634,12 @@ pi.sendMessage({
1537
1634
  - `"steer"` (default) - Queues the message while streaming. Delivered after the current assistant turn finishes executing its tool calls, before the next LLM call.
1538
1635
  - `"followUp"` - Waits for agent to finish. Delivered only when agent has no more tool calls.
1539
1636
  - `"nextTurn"` - Queued for next user prompt. Does not interrupt or trigger anything.
1540
- - `triggerTurn: true` - If agent is idle, trigger an LLM response immediately. Only applies to `"steer"` and `"followUp"` modes (ignored for `"nextTurn"`).
1637
+ - `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.
1638
+ - `triggerTurn: false` while streaming - The message is not steered or queued as a follow-up; it is appended after the current turn ends.
1541
1639
 
1542
1640
  ### pi.sendUserMessage(content, options?)
1543
1641
 
1544
- Send a user message to the agent. Unlike `sendMessage()` which sends custom messages, this sends an actual user message that appears as if typed by the user. Always triggers a turn.
1642
+ 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.
1545
1643
 
1546
1644
  ```typescript
1547
1645
  // Simple text message
@@ -1550,7 +1648,7 @@ pi.sendUserMessage("What is 2+2?");
1550
1648
  // With content array (text + images)
1551
1649
  pi.sendUserMessage([
1552
1650
  { type: "text", text: "Describe this image:" },
1553
- { type: "image", source: { type: "base64", mediaType: "image/png", data: "..." } },
1651
+ { type: "image", data: "...", mimeType: "image/png" },
1554
1652
  ]);
1555
1653
 
1556
1654
  // During streaming - must specify delivery mode
@@ -1567,17 +1665,16 @@ pi.sendUserMessage("/review src/index.ts", { expandPromptTemplates: true });
1567
1665
  - `"followUp"` - Waits for agent to finish all tools
1568
1666
  - `expandPromptTemplates` - Dispatch extension commands and expand skill commands and prompt templates. Defaults to `false`.
1569
1667
 
1570
- When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, throws an error.
1668
+ 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.
1571
1669
 
1572
1670
  See [send-user-message.ts](../examples/extensions/send-user-message.ts) for a complete example.
1573
1671
 
1574
1672
  ### pi.appendEntry(customType, data?)
1575
1673
 
1576
- 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()`.
1674
+ Persist extension data. Custom entries do NOT participate in LLM context.
1577
1675
 
1578
1676
  ```typescript
1579
1677
  pi.appendEntry("my-state", { count: 42 });
1580
- pi.appendEntry("status-card", { title: "Indexed files", count: 17 });
1581
1678
 
1582
1679
  // Restore on reload
1583
1680
  pi.on("session_start", async (_event, ctx) => {
@@ -1591,7 +1688,7 @@ pi.on("session_start", async (_event, ctx) => {
1591
1688
 
1592
1689
  ### pi.setSessionName(name)
1593
1690
 
1594
- Set the session display name (shown in session selector instead of first message).
1691
+ Set the session display name, returned by RPC `get_state` and stored as a `session_info` entry.
1595
1692
 
1596
1693
  ```typescript
1597
1694
  pi.setSessionName("Refactor auth module");
@@ -1610,7 +1707,7 @@ if (name) {
1610
1707
 
1611
1708
  ### pi.setLabel(entryId, label)
1612
1709
 
1613
- Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation (shown in `/tree` selector).
1710
+ Set or clear a label on an entry. Labels are user-defined markers for bookmarking and navigation, returned with RPC `get_tree` entries.
1614
1711
 
1615
1712
  ```typescript
1616
1713
  // Set a label
@@ -1641,10 +1738,10 @@ pi.registerCommand("stats", {
1641
1738
  });
1642
1739
  ```
1643
1740
 
1644
- Optional: add argument auto-completion for `/command ...`:
1741
+ Optional: add argument auto-completion for `/command ...`. `getArgumentCompletions` can also return a `Promise`:
1645
1742
 
1646
1743
  ```typescript
1647
- import type { AutocompleteItem } from "@punch-bot/tui";
1744
+ import type { AutocompleteItem } from "@punch-bot/cli";
1648
1745
 
1649
1746
  pi.registerCommand("deploy", {
1650
1747
  description: "Deploy to an environment",
@@ -1663,7 +1760,7 @@ pi.registerCommand("deploy", {
1663
1760
  ### pi.getCommands()
1664
1761
 
1665
1762
  Get the slash commands available for invocation via `prompt` in the current session. Includes extension commands, prompt templates, and skill commands.
1666
- The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills.
1763
+ The list matches the RPC `get_commands` ordering: extensions first, then templates, then skills. Skill commands are named `skill:<name>`.
1667
1764
 
1668
1765
  ```typescript
1669
1766
  const commands = pi.getCommands();
@@ -1690,45 +1787,7 @@ Each entry has this shape:
1690
1787
 
1691
1788
  Use `sourceInfo` as the canonical provenance field. Do not infer ownership from command names or from ad hoc path parsing.
1692
1789
 
1693
- Built-in interactive commands (like `/model` and `/settings`) are not included here. They are handled only in interactive
1694
- mode and would not execute if sent via `prompt`.
1695
-
1696
- ### pi.registerMessageRenderer(customType, renderer)
1697
-
1698
- 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).
1699
-
1700
- ### pi.registerEntryRenderer(customType, renderer)
1701
-
1702
- 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.
1703
-
1704
- ```typescript
1705
- import { Box, Text } from "@punch-bot/tui";
1706
-
1707
- pi.registerEntryRenderer("status-card", (entry, { expanded }, theme) => {
1708
- const data = entry.data as { title: string; count: number };
1709
- const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text));
1710
- box.addChild(new Text(`${theme.bold(data.title)}: ${data.count}`));
1711
- if (expanded) {
1712
- box.addChild(new Text(theme.fg("dim", JSON.stringify(data, null, 2))));
1713
- }
1714
- return box;
1715
- });
1716
-
1717
- pi.appendEntry("status-card", { title: "Indexed files", count: 17 });
1718
- ```
1719
-
1720
- ### pi.registerShortcut(shortcut, options)
1721
-
1722
- Register a keyboard shortcut. See [keybindings.md](keybindings.md) for the shortcut format and built-in keybindings.
1723
-
1724
- ```typescript
1725
- pi.registerShortcut("ctrl+shift+p", {
1726
- description: "Toggle plan mode",
1727
- handler: async (ctx) => {
1728
- ctx.ui.notify("Toggled!");
1729
- },
1730
- });
1731
- ```
1790
+ Pi has no other slash commands. A prompt such as `/model` that matches no extension command, prompt template, or skill is sent to the model as plain text. Use extension APIs such as `pi.setModel()` instead.
1732
1791
 
1733
1792
  ### pi.registerFlag(name, options)
1734
1793
 
@@ -1741,21 +1800,25 @@ pi.registerFlag("plan", {
1741
1800
  default: false,
1742
1801
  });
1743
1802
 
1744
- // Check value
1745
- if (pi.getFlag("plan")) {
1746
- // Plan mode enabled
1747
- }
1803
+ // Check the value after loading; in the factory, getFlag() returns the default
1804
+ pi.on("session_start", () => {
1805
+ if (pi.getFlag("plan")) {
1806
+ // Plan mode enabled
1807
+ }
1808
+ });
1748
1809
  ```
1749
1810
 
1750
1811
  ### pi.exec(command, args, options?)
1751
1812
 
1752
- Execute a shell command.
1813
+ Execute a command without a shell.
1753
1814
 
1754
1815
  ```typescript
1755
1816
  const result = await pi.exec("git", ["status"], { signal, timeout: 5000 });
1756
- // result.stdout, result.stderr, result.code, result.killed
1817
+ // result.stdout, result.stderr, result.code, result.killed, result.truncated
1757
1818
  ```
1758
1819
 
1820
+ 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.
1821
+
1759
1822
  ### pi.getActiveTools() / pi.getAllTools() / pi.setActiveTools(names)
1760
1823
 
1761
1824
  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.
@@ -1768,21 +1831,26 @@ const all = pi.getAllTools();
1768
1831
  // description: "Read file contents...",
1769
1832
  // parameters: ...,
1770
1833
  // promptGuidelines: ["Use read to examine files instead of cat or sed."],
1771
- // sourceInfo: { path: "<builtin:read>", source: "builtin", scope: "temporary", origin: "top-level" }
1834
+ // exposure: "direct",
1835
+ // sourceInfo: { path: "builtin:read", source: "builtin", scope: "temporary", origin: "top-level" }
1772
1836
  // }, ...]
1773
- const builtinTools = all.filter((t) => t.sourceInfo.source === "builtin");
1837
+ // Tools shipped with Pi: core tools and tools from built-in extensions such as builtin:mcp
1838
+ const shippedTools = all.filter((t) => t.sourceInfo.source === "builtin");
1839
+ // Tools from installed or local extensions
1774
1840
  const extensionTools = all.filter((t) => t.sourceInfo.source !== "builtin" && t.sourceInfo.source !== "sdk");
1775
1841
  pi.setActiveTools([...new Set([...active, "my_custom_tool"])]); // Keep current tools and enable my_custom_tool
1776
- pi.setActiveTools(["read", "bash"]); // Switch to read-only
1842
+ pi.setActiveTools(["read", "bash"]); // Only read and bash
1777
1843
  ```
1778
1844
 
1779
- `pi.getAllTools()` returns `name`, `description`, `parameters`, `promptGuidelines`, and `sourceInfo`.
1845
+ `pi.getAllTools()` returns `name`, `description`, `parameters`, `promptGuidelines`, `exposure`, `sourceInfo`, and, when set, `namespace`, `annotations`, and `reachesTools`.
1780
1846
 
1781
- Typical `sourceInfo.source` values:
1782
- - `builtin` for built-in tools
1783
- - `sdk` for tools passed via `createAgentSession({ customTools })`
1847
+ Typical `sourceInfo` values:
1848
+ - `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>"`)
1849
+ - `source: "sdk"` for tools passed via `createAgentSession({ customTools })`
1784
1850
  - extension source metadata for tools registered by extensions
1785
1851
 
1852
+ `pi.setActiveTools()` ignores unknown and `hidden` tools. Tools with `codemode` or `deferred` exposure stay callable from codemode scripts whether active or not.
1853
+
1786
1854
  ### pi.setModel(model)
1787
1855
 
1788
1856
  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.
@@ -1821,7 +1889,7 @@ pi.events.emit("my:event", { ... });
1821
1889
 
1822
1890
  Register or override a model provider dynamically. Useful for proxies, custom endpoints, or team-wide model configurations.
1823
1891
 
1824
- 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`.
1892
+ 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.
1825
1893
 
1826
1894
  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.
1827
1895
 
@@ -1830,7 +1898,7 @@ Dynamic providers can implement `refreshModels`. Pi calls it during model refres
1830
1898
  Extensions that need native provider auth, filtering, refresh, or stream behavior can register a complete `Provider` from `@punch-bot/ai`. The provider becomes the composition base and `models.json` overrides still apply above it.
1831
1899
 
1832
1900
  ```typescript
1833
- import { createProvider, openAICompletionsApi } from "@punch-bot/ai";
1901
+ import { createProvider, openAICompletionsApi } from "@punch-bot/ai/compat";
1834
1902
 
1835
1903
  const provider = createProvider({
1836
1904
  id: "local-server",
@@ -1884,7 +1952,7 @@ pi.registerProvider("llama.cpp", {
1884
1952
  api: "openai-completions",
1885
1953
  async refreshModels({ signal }) {
1886
1954
  const response = await fetch("http://localhost:8080/v1/models", { signal });
1887
- const { data } = await response.json();
1955
+ const { data } = (await response.json()) as { data: Array<{ id: string }> };
1888
1956
  return data.map(({ id }) => ({
1889
1957
  id,
1890
1958
  name: id,
@@ -1902,7 +1970,7 @@ pi.registerProvider("anthropic", {
1902
1970
  baseUrl: "https://proxy.example.com"
1903
1971
  });
1904
1972
 
1905
- // Register provider with OAuth support for /login
1973
+ // Register provider with OAuth support
1906
1974
  pi.registerProvider("corporate-ai", {
1907
1975
  baseUrl: "https://ai.corp.com",
1908
1976
  api: "openai-responses",
@@ -1930,15 +1998,15 @@ pi.registerProvider("corporate-ai", {
1930
1998
  The object form accepts a complete pi-ai `Provider`, including native `auth`, `getModels`, `refreshModels`, `filterModels`, `stream`, and `streamSimple` behavior.
1931
1999
 
1932
2000
  **Legacy config options:**
1933
- - `name` - Display name for the provider in UI such as `/login`.
1934
- - `baseUrl` - API endpoint URL. Required when defining models.
1935
- - `apiKey` - API key literal, environment interpolation (`$ENV_VAR` or `${ENV_VAR}`), or leading `!command`. Required when defining models (unless `oauth` provided). `$$` escapes `$`, and `$!` escapes a literal `!` without triggering command execution.
2001
+ - `name` - Display name for the provider.
2002
+ - `baseUrl` - API endpoint URL. Each defined model needs one, from the model definition or the provider.
2003
+ - `apiKey` - API key literal, environment interpolation (`$ENV_VAR` or `${ENV_VAR}`), or leading `!command`. Optional: without it, users store a key in `auth.json`. `$$` escapes `$`, and `$!` escapes a literal `!` without triggering command execution.
1936
2004
  - `api` - API type: `"anthropic-messages"`, `"openai-completions"`, `"openai-responses"`, etc.
1937
2005
  - `headers` - Custom headers to include in requests.
1938
2006
  - `authHeader` - If true, adds `Authorization: Bearer` header automatically.
1939
2007
  - `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.
1940
2008
  - `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.
1941
- - `oauth` - OAuth provider config for `/login` support. When provided, the provider appears in the login menu.
2009
+ - `oauth` - OAuth provider config. `pi auth login <provider>` runs this flow for providers that built-in or user extensions register, but not for those a project's own extensions register. SDK applications can also run it through `session.modelRuntime.login()`.
1942
2010
  - `streamSimple` - Custom streaming implementation for non-standard APIs.
1943
2011
 
1944
2012
  See [custom-provider.md](custom-provider.md) for advanced topics: custom streaming APIs, OAuth details, model definition reference.
@@ -1947,7 +2015,7 @@ See [custom-provider.md](custom-provider.md) for advanced topics: custom streami
1947
2015
 
1948
2016
  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.
1949
2017
 
1950
- Like `registerProvider`, this takes effect immediately when called after the initial load phase, so a `/reload` is not required.
2018
+ Like `registerProvider`, this takes effect immediately when called after the initial load phase, so no reload is required.
1951
2019
 
1952
2020
  ```typescript
1953
2021
  pi.registerCommand("my-setup-teardown", {
@@ -1958,6 +2026,20 @@ pi.registerCommand("my-setup-teardown", {
1958
2026
  });
1959
2027
  ```
1960
2028
 
2029
+ ### pi.registerVirtualModel(model) / pi.unregisterVirtualModel(provider, id)
2030
+
2031
+ 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).
2032
+
2033
+ ### pi.registerMcpServer(name, config) / pi.unregisterMcpServer(name) / pi.getMcpServers()
2034
+
2035
+ Register an MCP server for the current session. See [MCP Servers](#mcp-servers).
2036
+
2037
+ ### pi.getSettings()
2038
+
2039
+ Return a copy of the effective settings, with global and project settings merged and overrides applied.
2040
+
2041
+ <a id="persist-state"></a>
2042
+
1961
2043
  ## State Management
1962
2044
 
1963
2045
  Extensions with state should store it in tool result `details` for proper branching support:
@@ -1966,17 +2048,19 @@ Extensions with state should store it in tool result `details` for proper branch
1966
2048
  export default function (pi: ExtensionAPI) {
1967
2049
  let items: string[] = [];
1968
2050
 
1969
- // Reconstruct state from session
1970
- pi.on("session_start", async (_event, ctx) => {
2051
+ // Reconstruct state from the active branch
2052
+ const reconstruct = (ctx: ExtensionContext) => {
1971
2053
  items = [];
1972
2054
  for (const entry of ctx.sessionManager.getBranch()) {
1973
2055
  if (entry.type === "message" && entry.message.role === "toolResult") {
1974
2056
  if (entry.message.toolName === "my_tool") {
1975
- items = entry.message.details?.items ?? [];
2057
+ items = (entry.message.details as { items?: string[] } | undefined)?.items ?? [];
1976
2058
  }
1977
2059
  }
1978
2060
  }
1979
- });
2061
+ };
2062
+ pi.on("session_start", async (_event, ctx) => reconstruct(ctx));
2063
+ pi.on("session_tree", async (_event, ctx) => reconstruct(ctx)); // ctx.navigateTree() changes the branch
1980
2064
 
1981
2065
  pi.registerTool({
1982
2066
  name: "my_tool",
@@ -1992,17 +2076,21 @@ export default function (pi: ExtensionAPI) {
1992
2076
  }
1993
2077
  ```
1994
2078
 
2079
+ 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.
2080
+
2081
+ <a id="register-tools"></a>
2082
+
1995
2083
  ## Custom Tools
1996
2084
 
1997
- Register tools the LLM can call via `pi.registerTool()`. Tools appear in the system prompt and can have custom rendering.
2085
+ Register tools the LLM can call via `pi.registerTool()`. Tools appear in the system prompt.
1998
2086
 
1999
- Use `promptSnippet` for a short one-line entry in the `Available tools` section in the default system prompt. If omitted, custom tools are left out of that section.
2087
+ 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.
2000
2088
 
2001
- Use `promptGuidelines` to add tool-specific bullets to the default system prompt `Guidelines` section. These bullets are included only while the tool is active (for example, after `pi.setActiveTools([...])`).
2089
+ 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([...])`).
2002
2090
 
2003
- **Important:** `promptGuidelines` bullets are appended flat to the `Guidelines` section with no tool name prefix or grouping. Each guideline must name the tool it refers to — avoid "Use this tool when..." because the LLM cannot tell which tool "this" means. Write "Use my_tool when..." instead.
2091
+ **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.
2004
2092
 
2005
- Note: Some models are idiots and include the @ prefix in tool path arguments. Built-in tools strip a leading @ before resolving paths. If your custom tool accepts a path, normalize a leading @ as well.
2093
+ 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.
2006
2094
 
2007
2095
  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.
2008
2096
 
@@ -2037,9 +2125,13 @@ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2037
2125
  ### Tool Definition
2038
2126
 
2039
2127
  ```typescript
2040
- import { Type } from "typebox";
2041
- import { StringEnum } from "@punch-bot/ai";
2042
- import { Text } from "@punch-bot/tui";
2128
+ import { StringEnum } from "@punch-bot/cli";
2129
+ import { type Static, Type } from "typebox";
2130
+
2131
+ const myToolSchema = Type.Object({
2132
+ action: StringEnum(["list", "add"] as const),
2133
+ text: Type.Optional(Type.String()),
2134
+ });
2043
2135
 
2044
2136
  pi.registerTool({
2045
2137
  name: "my_tool",
@@ -2049,29 +2141,26 @@ pi.registerTool({
2049
2141
  promptGuidelines: [
2050
2142
  "Use my_tool for todo planning instead of direct file edits when the user asks for a task list."
2051
2143
  ],
2052
- parameters: Type.Object({
2053
- action: StringEnum(["list", "add"] as const), // Use StringEnum for Google compatibility
2054
- text: Type.Optional(Type.String()),
2055
- }),
2144
+ parameters: myToolSchema,
2056
2145
  prepareArguments(args) {
2057
- if (!args || typeof args !== "object") return args;
2058
- const input = args as { action?: string; oldAction?: string };
2059
- if (typeof input.oldAction === "string" && input.action === undefined) {
2060
- return { ...input, action: input.oldAction };
2146
+ // Fold a legacy `oldAction` field into `action`. Schema validation still runs afterwards.
2147
+ const input = (args ?? {}) as { action?: unknown; oldAction?: unknown };
2148
+ if (input.action === undefined && input.oldAction !== undefined) {
2149
+ return { ...input, action: input.oldAction } as Static<typeof myToolSchema>;
2061
2150
  }
2062
- return args;
2151
+ return args as Static<typeof myToolSchema>;
2063
2152
  },
2064
2153
 
2065
2154
  async execute(toolCallId, params, signal, onUpdate, ctx) {
2066
2155
  // Check for cancellation
2067
2156
  if (signal?.aborted) {
2068
- return { content: [{ type: "text", text: "Cancelled" }] };
2157
+ return { content: [{ type: "text", text: "Cancelled" }], details: {} };
2069
2158
  }
2070
2159
 
2071
- // Stream progress updates
2160
+ // Stream progress updates; partial results also need details
2072
2161
  onUpdate?.({
2073
2162
  content: [{ type: "text", text: "Working..." }],
2074
- details: { progress: 50 },
2163
+ details: {},
2075
2164
  });
2076
2165
 
2077
2166
  // Run commands via pi.exec (captured from extension closure)
@@ -2087,18 +2176,16 @@ pi.registerTool({
2087
2176
  terminate: true,
2088
2177
  };
2089
2178
  },
2090
-
2091
- // Optional: Custom rendering
2092
- renderCall(args, theme, context) { ... },
2093
- renderResult(result, options, theme, context) { ... },
2094
2179
  });
2095
2180
  ```
2096
2181
 
2097
- **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.
2182
+ **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.
2098
2183
 
2099
- **Signaling errors:** To mark a tool execution as failed (sets `isError: true` on the result and reports it to the LLM), throw an error from `execute`. Returning a value never sets the error flag regardless of what properties you include in the return object.
2184
+ **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 RPC `get_session_stats` and SDK session totals. `tool_result` handlers can inspect or replace this value.
2100
2185
 
2101
- **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.
2186
+ **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.
2187
+
2188
+ **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.
2102
2189
 
2103
2190
  ```typescript
2104
2191
  // Correct: throw to signal an error
@@ -2110,44 +2197,51 @@ async execute(toolCallId, params) {
2110
2197
  }
2111
2198
  ```
2112
2199
 
2113
- **Important:** Use `StringEnum` from `@punch-bot/ai` for string enums. `Type.Union`/`Type.Literal` doesn't work with Google's API.
2200
+ **String enums:** Prefer `StringEnum` from `@punch-bot/cli`. It produces a plain `enum` schema that every provider accepts, typed for TypeBox so `Type.Object` infers the literal union. `@punch-bot/ai` also exports a `StringEnum`, but it is typed for `@punch-bot/schema`, and inside `Type.Object` its field infers as `unknown`.
2201
+
2202
+ **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`.
2203
+
2204
+ **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.
2205
+
2206
+ **Other definition fields:**
2207
+
2208
+ | Field | Purpose |
2209
+ |---|---|
2210
+ | `defaultActive` | Set `false` to register the tool inactive; `--tools`, the `defaultTools` setting, or `pi.setActiveTools()` activates it |
2211
+ | `exposure`, `namespace`, `annotations`, `reachesTools`, `prepareLoadout` | Control how the model and other tools reach the tool; see [Tool Exposure](#tool-exposure) |
2212
+ | `constrainedSampling` | Optional provider-side constrained sampling request for the tool's arguments |
2213
+
2214
+ Use `defineTool()` to keep parameter type inference when you assign a tool definition to a variable before registering it.
2114
2215
 
2115
2216
  **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.
2116
2217
 
2117
2218
  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 }]`.
2118
2219
 
2119
2220
  ```typescript
2221
+ const editSchema = Type.Object({
2222
+ path: Type.String(),
2223
+ edits: Type.Array(
2224
+ Type.Object({
2225
+ oldText: Type.String(),
2226
+ newText: Type.String(),
2227
+ }),
2228
+ ),
2229
+ });
2230
+ type EditInput = Static<typeof editSchema>;
2231
+
2120
2232
  pi.registerTool({
2121
2233
  name: "edit",
2122
2234
  label: "Edit",
2123
2235
  description: "Edit a single file using exact text replacement",
2124
- parameters: Type.Object({
2125
- path: Type.String(),
2126
- edits: Type.Array(
2127
- Type.Object({
2128
- oldText: Type.String(),
2129
- newText: Type.String(),
2130
- }),
2131
- ),
2132
- }),
2236
+ parameters: editSchema,
2133
2237
  prepareArguments(args) {
2134
- if (!args || typeof args !== "object") return args;
2135
-
2136
- const input = args as {
2137
- path?: string;
2138
- edits?: Array<{ oldText: string; newText: string }>;
2139
- oldText?: unknown;
2140
- newText?: unknown;
2141
- };
2142
-
2238
+ const input = (args ?? {}) as Partial<EditInput> & { oldText?: unknown; newText?: unknown };
2143
2239
  if (typeof input.oldText !== "string" || typeof input.newText !== "string") {
2144
- return args;
2240
+ return args as EditInput; // validation reports anything still invalid
2145
2241
  }
2146
2242
 
2147
- return {
2148
- ...input,
2149
- edits: [...(input.edits ?? []), { oldText: input.oldText, newText: input.newText }],
2150
- };
2243
+ const { oldText, newText, ...rest } = input;
2244
+ return { ...rest, edits: [...(input.edits ?? []), { oldText, newText }] } as EditInput;
2151
2245
  },
2152
2246
  async execute(toolCallId, params, signal, onUpdate, ctx) {
2153
2247
  // params now matches the current schema
@@ -2161,7 +2255,7 @@ pi.registerTool({
2161
2255
 
2162
2256
  ### Overriding Built-in Tools
2163
2257
 
2164
- Extensions can override built-in tools (`read`, `bash`, `powershell`, `edit`, `write`, `grep`, `find`, `ls`) by registering a tool with the same name. Interactive mode displays a warning when this happens.
2258
+ 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.
2165
2259
 
2166
2260
  ```bash
2167
2261
  # Extension's read tool replaces built-in read
@@ -2176,8 +2270,6 @@ pi --no-builtin-tools -e ./my-extension.ts
2176
2270
 
2177
2271
  See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.ts) for a complete example that overrides `read` with logging and access control.
2178
2272
 
2179
- **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.
2180
-
2181
2273
  **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.
2182
2274
 
2183
2275
  **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.
@@ -2197,33 +2289,36 @@ Built-in tool implementations:
2197
2289
  Built-in tools support pluggable operations for delegating to remote systems (SSH, containers, etc.):
2198
2290
 
2199
2291
  ```typescript
2200
- import { createReadTool, createBashTool, type ReadOperations } from "@punch-bot/cli";
2292
+ import { createReadTool, type ReadOperations } from "@punch-bot/cli";
2201
2293
 
2202
- // Create tool with custom operations
2203
- const remoteRead = createReadTool(cwd, {
2204
- operations: {
2205
- readFile: (path) => sshExec(remote, `cat ${path}`),
2206
- access: (path) => sshExec(remote, `test -r ${path}`).then(() => {}),
2207
- }
2208
- });
2294
+ const localRead = createReadTool(cwd);
2209
2295
 
2210
- // Register, checking flag at execution time
2296
+ // Register, checking the remote configuration at execution time
2211
2297
  pi.registerTool({
2212
- ...remoteRead,
2298
+ ...localRead,
2213
2299
  async execute(id, params, signal, onUpdate, _ctx) {
2214
2300
  const ssh = getSshConfig();
2215
2301
  if (ssh) {
2216
- const tool = createReadTool(cwd, { operations: createRemoteOps(ssh) });
2217
- return tool.execute(id, params, signal, onUpdate);
2302
+ const operations: ReadOperations = {
2303
+ readFile: (path) => sshReadBuffer(ssh, path), // must resolve to a Buffer
2304
+ access: (path) => sshExec(ssh, `test -r ${path}`).then(() => {}),
2305
+ };
2306
+ return createReadTool(cwd, { operations }).execute(id, params, signal, onUpdate);
2218
2307
  }
2219
2308
  return localRead.execute(id, params, signal, onUpdate);
2220
2309
  },
2221
2310
  });
2222
2311
  ```
2223
2312
 
2313
+ `ReadOperations.createReadStream` is optional. When it returns the file as an async iterable of chunks (a Node `Readable` works), `read` keeps only the lines it shows in memory, so large files can be read with `offset`/`limit`; without it, `read` loads the whole file through `readFile`.
2314
+
2315
+ The `create*ToolDefinition()` factories, such as `createReadToolDefinition()`, return complete tool definitions, including the built-in prompt snippet and guidelines, for the same purpose.
2316
+
2224
2317
  **Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `PowerShellOperations`, `LsOperations`, `GrepOperations`, `FindOperations`
2225
2318
 
2226
- For `user_bash`, extensions can reuse pi's local shell backend via `createLocalBashOperations()` instead of reimplementing local process spawning, shell resolution, and process-tree termination.
2319
+ `GrepOperations` only covers the directory check: grep always runs the local `rg`. To search a remote system, override grep's `execute()` instead, as the [Gondolin example](../examples/extensions/gondolin/index.ts) does.
2320
+
2321
+ 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.
2227
2322
 
2228
2323
  The `bash` and `powershell` tools also support a spawn hook to adjust the command, cwd, or env before execution:
2229
2324
 
@@ -2262,7 +2357,7 @@ The built-in limit is **50KB** (~10k tokens) and **2000 lines**, whichever is hi
2262
2357
  import {
2263
2358
  truncateHead, // Keep first N lines/bytes (good for file reads, search results)
2264
2359
  truncateTail, // Keep last N lines/bytes (good for logs, command output)
2265
- truncateLine, // Truncate a single line to maxBytes with ellipsis
2360
+ truncateLine, // Truncate a single line to a character count; returns { text, wasTruncated }
2266
2361
  formatSize, // Human-readable size (e.g., "50KB", "1.5MB")
2267
2362
  DEFAULT_MAX_BYTES, // 50KB
2268
2363
  DEFAULT_MAX_LINES, // 2000
@@ -2289,7 +2384,7 @@ async execute(toolCallId, params, signal, onUpdate, ctx) {
2289
2384
  result += ` Full output saved to: ${tempFile}]`;
2290
2385
  }
2291
2386
 
2292
- return { content: [{ type: "text", text: result }] };
2387
+ return { content: [{ type: "text", text: result }], details: { truncation } };
2293
2388
  }
2294
2389
  ```
2295
2390
 
@@ -2299,8 +2394,6 @@ async execute(toolCallId, params, signal, onUpdate, ctx) {
2299
2394
  - Always inform the LLM when output is truncated and where to find the full version
2300
2395
  - Document the truncation limits in your tool's description
2301
2396
 
2302
- See [examples/extensions/truncated-tool.ts](../examples/extensions/truncated-tool.ts) for a complete example wrapping `rg` (ripgrep) with proper truncation.
2303
-
2304
2397
  ### Multiple Tools
2305
2398
 
2306
2399
  One extension can register multiple tools with shared state:
@@ -2319,389 +2412,114 @@ export default function (pi: ExtensionAPI) {
2319
2412
  }
2320
2413
  ```
2321
2414
 
2322
- ### Custom Rendering
2415
+ ### Dynamic Tool Loading
2323
2416
 
2324
- 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.
2417
+ 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.
2325
2418
 
2326
- By default, tool output is wrapped in a `Box` that handles padding and background. A defined `renderCall` or `renderResult` must return a `Component`. If a slot renderer is not defined, `tool-execution.ts` uses fallback rendering for that slot.
2419
+ The lifecycle is:
2327
2420
 
2328
- 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.
2421
+ 1. Register every tool with `pi.registerTool()` so it appears in `pi.getAllTools()`. Register searchable tools with `defaultActive: false` so they start inactive.
2422
+ 2. Keep loader tools, such as `search_tools`, active.
2423
+ 3. During loader execution, call `pi.setActiveTools()` with the desired active tool names. Names must already be registered; unknown and `hidden` names are ignored.
2329
2424
 
2330
- ```typescript
2331
- pi.registerTool({
2332
- name: "my_tool",
2333
- label: "My Tool",
2334
- description: "Custom shell example",
2335
- parameters: Type.Object({}),
2336
- renderShell: "self",
2337
- async execute() {
2338
- return { content: [{ type: "text", text: "ok" }], details: undefined };
2339
- },
2340
- renderCall(args, theme, context) {
2341
- return new Text(theme.fg("accent", "my custom shell"), 0, 0);
2342
- },
2343
- });
2344
- ```
2425
+ 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).
2345
2426
 
2346
- `renderCall` and `renderResult` each receive a `context` object with:
2347
- - `args` - the current tool call arguments
2348
- - `state` - shared row-local state across `renderCall` and `renderResult`
2349
- - `lastComponent` - the previously returned component for that slot, if any
2350
- - `invalidate()` - request a rerender of this tool row
2351
- - `toolCallId`, `cwd`, `executionStarted`, `argsComplete`, `isPartial`, `expanded`, `showImages`, `isError`
2427
+ #### Search tool example
2352
2428
 
2353
- 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.
2354
-
2355
- #### renderCall
2356
-
2357
- Renders the tool call or header:
2358
-
2359
- ```typescript
2360
- import { Text } from "@punch-bot/tui";
2361
-
2362
- renderCall(args, theme, context) {
2363
- const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
2364
- let content = theme.fg("toolTitle", theme.bold("my_tool "));
2365
- content += theme.fg("muted", args.action);
2366
- if (args.text) {
2367
- content += " " + theme.fg("dim", `"${args.text}"`);
2368
- }
2369
- text.setText(content);
2370
- return text;
2371
- }
2372
- ```
2373
-
2374
- #### renderResult
2375
-
2376
- Renders the tool result or output:
2377
-
2378
- ```typescript
2379
- renderResult(result, { expanded, isPartial }, theme, context) {
2380
- if (isPartial) {
2381
- return new Text(theme.fg("warning", "Processing..."), 0, 0);
2382
- }
2383
-
2384
- if (result.details?.error) {
2385
- return new Text(theme.fg("error", `Error: ${result.details.error}`), 0, 0);
2386
- }
2387
-
2388
- let text = theme.fg("success", "✓ Done");
2389
- if (expanded && result.details?.items) {
2390
- for (const item of result.details.items) {
2391
- text += "\n " + theme.fg("dim", item);
2392
- }
2393
- }
2394
- return new Text(text, 0, 0);
2395
- }
2396
- ```
2397
-
2398
- If a slot intentionally has no visible content, return an empty `Component` such as an empty `Container`.
2399
-
2400
- #### Keybinding Hints
2401
-
2402
- Use `keyHint()` to display keybinding hints that respect the active keybinding configuration:
2403
-
2404
- ```typescript
2405
- import { keyHint } from "@punch-bot/cli";
2406
-
2407
- renderResult(result, { expanded }, theme, context) {
2408
- let text = theme.fg("success", "✓ Done");
2409
- if (!expanded) {
2410
- text += ` (${keyHint("app.tools.expand", "to expand")})`;
2411
- }
2412
- return new Text(text, 0, 0);
2413
- }
2414
- ```
2415
-
2416
- Available functions:
2417
- - `keyHint(keybinding, description)` - Formats a configured keybinding id such as `"app.tools.expand"` or `"tui.select.confirm"`
2418
- - `keyText(keybinding)` - Returns the raw configured key text for a keybinding id
2419
- - `rawKeyHint(key, description)` - Format a raw key string
2420
-
2421
- Use namespaced keybinding ids:
2422
- - Coding-agent ids use the `app.*` namespace, for example `app.tools.expand`, `app.editor.external`, `app.session.rename`
2423
- - Shared TUI ids use the `tui.*` namespace, for example `tui.select.confirm`, `tui.select.cancel`, `tui.input.tab`
2424
-
2425
- For the exhaustive list of keybinding ids and defaults, see [keybindings.md](keybindings.md). `keybindings.json` uses those same namespaced ids.
2426
-
2427
- 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()`.
2428
-
2429
- #### Best Practices
2430
-
2431
- - Use `Text` with padding `(0, 0)`. The default Box handles padding.
2432
- - Use `\n` for multi-line content.
2433
- - Handle `isPartial` for streaming progress.
2434
- - Support `expanded` for detail on demand.
2435
- - Keep default view compact.
2436
- - Read `context.args` in `renderResult` instead of copying args into `context.state`.
2437
- - Use `context.state` only for data that must be shared across call and result slots.
2438
- - Reuse `context.lastComponent` when the same component instance can be updated in place.
2439
- - 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.
2440
-
2441
- #### Fallback
2442
-
2443
- Extensions are TypeScript modules that add executable behavior to Pi. Use one when a workflow needs tools, commands, event handlers, model providers, session state, or terminal UI rather than instructions alone.
2444
-
2445
- 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.
2446
-
2447
- Typical extensions add an agent tool, protect paths, confirm dangerous commands, react to session events, modify context, expose a command, or display persistent status.
2448
-
2449
- <a id="quick-start"></a>
2450
- <a id="writing-an-extension"></a>
2451
- <a id="create-an-extension"></a>
2452
-
2453
- ## Create and load an extension
2454
-
2455
- An extension exports a default factory that receives `ExtensionAPI`. The factory registers capabilities for the current extension runtime.
2456
-
2457
- Create `~/.pi/agent/extensions/hello.ts`:
2429
+ 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.
2458
2430
 
2459
2431
  ```typescript
2460
2432
  import type { ExtensionAPI } from "@punch-bot/cli";
2433
+ import { Type } from "typebox";
2434
+
2435
+ const SEARCHABLE_TOOL_NAMES = new Set(["lookup_weather", "search_issues"]);
2461
2436
 
2462
2437
  export default function (pi: ExtensionAPI) {
2463
- pi.registerCommand("hello", {
2464
- description: "Show a greeting",
2465
- handler: async (name, ctx) => {
2466
- ctx.ui.notify(`Hello, ${name || "world"}!`, "info");
2438
+ pi.registerTool({
2439
+ name: "lookup_weather",
2440
+ label: "Lookup Weather",
2441
+ defaultActive: false,
2442
+ description: "Look up the current weather for a city",
2443
+ parameters: Type.Object({ city: Type.String() }),
2444
+ async execute(_toolCallId, params) {
2445
+ return {
2446
+ content: [{ type: "text", text: `Weather for ${params.city}: sunny` }],
2447
+ details: {},
2448
+ };
2467
2449
  },
2468
2450
  });
2469
- }
2470
- ```
2471
-
2472
- Start Pi and run `/hello`. During development, load a file directly:
2473
-
2474
- ```bash
2475
- pi --extension ./hello.ts
2476
- ```
2477
2451
 
2478
- Pi uses `jiti`, so local TypeScript extensions do not need a separate compilation step. Use [Pi packages](packages.md) for distributed extensions and dependencies.
2479
-
2480
- <a id="extension-locations"></a>
2481
- <a id="available-imports"></a>
2482
- <a id="choose-where-it-loads"></a>
2483
-
2484
- ## Add it to Pi
2485
-
2486
- Place the extension in your user or project extensions directory. Pi loads direct TypeScript or JavaScript files and subdirectories containing an `index.ts` or `index.js` entry point.
2487
-
2488
- Use a single file for a small extension and a directory for a multi-file implementation. Put npm dependencies in a nearby `package.json`. See [Configuration](configuration.md) for conventional locations and [Settings](settings.md#resources) for additional paths.
2489
-
2490
- Reload replaces the extension runtime, so code after `await ctx.reload()` must not reuse state from the old runtime. Only personal and explicit command-line extensions can participate in the `project_trust` event that runs before project extensions load.
2491
-
2492
- <a id="understand-the-lifecycle"></a>
2493
-
2494
- ## Understand the runtime lifecycle
2495
-
2496
- The factory can be synchronous or asynchronous. Pi waits for an asynchronous factory before startup continues, allowing it to fetch configuration or register providers needed during startup.
2497
-
2498
- Do not start processes, sockets, watchers, or timers in the factory because some invocations load extensions without starting a session.
2499
- Start long-lived resources from `session_start` or from the command or tool that needs them.
2500
- Close session-scoped resources from an idempotent `session_shutdown` handler.
2501
-
2502
- A normal prompt starts a run. The run repeats turns, then checks whether more work starts another low-level agent run:
2503
-
2504
- ```mermaid
2505
- flowchart TD
2506
- Input["input"] --> Before["before_agent_start"]
2507
- Before --> AgentStart["agent_start"]
2508
- AgentStart --> Turns[["turns"]]
2509
- Turns --> AgentEnd["agent_end"]
2510
- AgentEnd --> MoreRuns{"More work?"}
2511
- MoreRuns -->|yes| AgentStart
2512
- MoreRuns -->|no| BeforeSettle["agent_before_settle"]
2513
- BeforeSettle --> Continue{"Continuation requested?"}
2514
- Continue -->|yes| AgentStart
2515
- Continue -->|no| Settled["agent_settled"]
2516
- ```
2517
-
2518
- More work means a retry, recovery, compaction retry, or queued work.
2519
-
2520
- Each turn sends one model request and executes the tool calls in the assistant response:
2521
-
2522
- ```mermaid
2523
- flowchart TD
2524
- TurnStart["turn_start"] --> Request[["model request"]]
2525
- Request --> ToolDecision{"Tool calls?"}
2526
- ToolDecision -->|yes| Tools[["tool execution"]]
2527
- Tools --> TurnEnd["turn_end"]
2528
- ToolDecision -->|no| TurnEnd
2529
- TurnEnd --> MoreTurns{"Another turn?"}
2530
- MoreTurns -->|yes| TurnStart
2531
- MoreTurns -->|no| AgentEnd(["agent_end"])
2532
- ```
2533
-
2534
- The model request runs these hooks in order:
2535
-
2536
- 1. `context`
2537
- 2. `context_with_system`
2538
- 3. `before_provider_headers`
2539
- 4. `before_provider_request`
2540
- 5. `after_provider_response`
2541
- 6. `provider_stream_event` and assistant message events
2542
-
2543
- Tool execution runs these hooks in order for each tool call:
2544
-
2545
- 1. `tool_execution_start`
2546
- 2. `tool_call`
2547
- 3. `tool_execution_update` while the tool executes
2548
- 4. `tool_result`
2549
- 5. `tool_execution_end`
2550
-
2551
- The lifecycle involves these event groups:
2552
-
2553
- | Area | Events |
2554
- |---|---|
2555
- | Input preparation | `input`, `before_agent_start` |
2556
- | Agent run | `agent_start`, `agent_end` |
2557
- | Model turn | `turn_start`, `context`, `context_with_system`, `turn_end` |
2558
- | Provider call | `before_provider_headers`, `before_provider_request`, `after_provider_response`, `provider_stream_event` |
2559
- | Message lifecycle | `message_start`, `message_update`, `message_end` |
2560
- | Tool execution | `tool_execution_start`, `tool_call`, `tool_execution_update`, `tool_result`, `tool_execution_end` |
2561
- | Settlement | `agent_before_settle`, `agent_settled` |
2562
-
2563
- 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. Message lifecycle events also cover user and tool-result messages; the model request list places only the assistant stream where it occurs in each turn.
2452
+ pi.registerTool({
2453
+ name: "search_issues",
2454
+ label: "Search Issues",
2455
+ defaultActive: false,
2456
+ description: "Search project issues by keyword",
2457
+ parameters: Type.Object({ query: Type.String() }),
2458
+ async execute(_toolCallId, params) {
2459
+ return {
2460
+ content: [{ type: "text", text: `No open issues matching ${params.query}` }],
2461
+ details: {},
2462
+ };
2463
+ },
2464
+ });
2564
2465
 
2565
- Tool hooks run for each tool call, and one assistant response can start another turn by returning tool calls. Provider hooks run only when that transport exposes the corresponding stage. See the exported declarations in [`extensions/types.ts`](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/src/core/extensions/types.ts) for exact event payloads and result types.
2466
+ pi.registerTool({
2467
+ name: "search_tools",
2468
+ label: "Search Tools",
2469
+ description: "Search for and enable tools relevant to a task",
2470
+ promptSnippet: "Search for additional tools when the active tools cannot perform the task",
2471
+ promptGuidelines: [
2472
+ "Use search_tools when a task requires a capability that is not currently available.",
2473
+ ],
2474
+ parameters: Type.Object({
2475
+ query: Type.String({ description: "Capability or task to search for" }),
2476
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 10 })),
2477
+ }),
2478
+ async execute(_toolCallId, params) {
2479
+ const terms = params.query.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
2480
+ const matches = pi.getAllTools()
2481
+ .filter((tool) => SEARCHABLE_TOOL_NAMES.has(tool.name))
2482
+ .map((tool) => ({
2483
+ tool,
2484
+ score: terms.reduce(
2485
+ (score, term) =>
2486
+ score + (`${tool.name} ${tool.description}`.toLowerCase().includes(term) ? 1 : 0),
2487
+ 0,
2488
+ ),
2489
+ }))
2490
+ .filter((match) => match.score > 0)
2491
+ .sort((a, b) => b.score - a.score)
2492
+ .slice(0, params.limit ?? 3)
2493
+ .map((match) => match.tool.name);
2494
+
2495
+ if (matches.length === 0) {
2496
+ return {
2497
+ content: [{ type: "text", text: `No tools found for: ${params.query}` }],
2498
+ details: { matches: [] as string[], added: [] as string[] },
2499
+ };
2500
+ }
2566
2501
 
2567
- Session startup and replacement follow a separate lifecycle:
2502
+ const active = pi.getActiveTools();
2503
+ const added = matches.filter((name) => !active.includes(name));
2504
+ pi.setActiveTools([...new Set([...active, ...added])]);
2568
2505
 
2569
- ```mermaid
2570
- flowchart TD
2571
- Startup["Process startup"] --> Trust["project_trust when needed"]
2572
- Trust --> SessionStart["session_start"]
2573
- Switch["/new or /resume"] --> BeforeSwitch["session_before_switch"]
2574
- Fork["/fork or /clone"] --> BeforeFork["session_before_fork"]
2575
- BeforeSwitch --> Shutdown["session_shutdown"]
2576
- BeforeFork --> Shutdown
2577
- Reload["reload"] --> Shutdown
2578
- Shutdown --> Replacing{"Replacing the runtime?"}
2579
- Replacing -->|yes| Replacement["load replacement extension runtime"]
2580
- Replacement --> SessionStart
2581
- Replacing -->|no| Stop["process exits"]
2582
- SessionStart --> Discover["resources_discover"]
2506
+ return {
2507
+ content: [{
2508
+ type: "text",
2509
+ text: added.length > 0
2510
+ ? `Loaded tools: ${added.join(", ")}`
2511
+ : `Matching tools already active: ${matches.join(", ")}`,
2512
+ }],
2513
+ details: { matches, added },
2514
+ };
2515
+ },
2516
+ });
2517
+ }
2583
2518
  ```
2584
2519
 
2585
- `project_trust` runs before trusted project resources load and can run again when session replacement enters a new working directory. Retries, recovery, compaction, and queued messages can start another agent run after `agent_end`, so `agent_end` is not a final-idle signal. Reload and session replacement invalidate the old runtime. Code after `await ctx.reload()` still belongs to the old runtime and must not reuse its session-bound state.
2586
-
2587
- ### Choose an event by intent
2588
-
2589
- | Goal | Event |
2590
- |---|---|
2591
- | Inspect, transform, or consume raw user input | `input` |
2592
- | Change prompt sections, active tools, or add context before a run | `before_agent_start` |
2593
- | Observe one low-level agent run | `agent_start`, `agent_end` |
2594
- | Act after one model response and its tool calls | `turn_end` |
2595
- | Filter conversation messages for one provider request | `context` |
2596
- | Transform the complete transcript, including system messages | `context_with_system` |
2597
- | Change request headers or the serialized provider payload | `before_provider_headers`, `before_provider_request` |
2598
- | Observe provider response metadata or parsed stream events | `after_provider_response`, `provider_stream_event` |
2599
- | Authorize or modify a tool call | `tool_call` |
2600
- | Redact, annotate, or replace a tool result | `tool_result` |
2601
- | Append final entries or request one last continuation | `agent_before_settle` |
2602
- | Run notification work after automatic processing has stopped | `agent_settled` |
2603
- | Initialize or release session-scoped resources | `session_start`, `session_shutdown` |
2604
-
2605
- <a id="agent_start--agent_end--agent_before_settle--agent_settled"></a>
2606
-
2607
- Use `agent_before_settle` when an extension must append entries or request one final continuation. Use `agent_settled` for notification-only work that should run after Pi has no automatic continuation remaining.
2608
-
2609
- <a id="extensionapi-methods"></a>
2610
-
2611
- ## Choose an integration point
2612
-
2613
- | Capability | Main API |
2614
- |---|---|
2615
- | Observe or modify lifecycle behavior | `pi.on()` |
2616
- | Add a model-callable operation | `pi.registerTool()` |
2617
- | Add a `/` command | `pi.registerCommand()` |
2618
- | Add a shortcut or CLI flag | `pi.registerShortcut()` or `pi.registerFlag()` |
2619
- | Send user or custom messages | `pi.sendUserMessage()` or `pi.sendMessage()` |
2620
- | Persist non-context session data | `pi.appendEntry()` |
2621
- | Change active tools, model, or thinking level | Session control methods on `pi` |
2622
- | Add a model provider | `pi.registerProvider()` |
2623
- | Add an MCP server | `pi.registerMcpServer()` |
2624
- | Route each request to a model | [`pi.registerVirtualModel()`](virtual-models.md) |
2625
- | Add terminal rendering | Renderer registration and `ctx.ui` |
2626
- | Communicate with another extension | `pi.events` |
2627
-
2628
- Use the exported declarations in [`extensions/types.ts`](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/src/core/extensions/types.ts) for exact event, context, tool, and result types.
2629
-
2630
- ## Follow the extension contracts
2631
-
2632
- <a id="events"></a>
2633
- <a id="work-with-events"></a>
2634
-
2635
- ### Events and concurrency
2636
-
2637
- Handlers run in extension load and registration order. `pi.on()` returns a function that unsubscribes that registration; changes do not affect a dispatch already in progress.
2638
- Some events notify; others transform data, replace results, or cancel an operation.
2639
- Use each event’s declared result type rather than assuming every return value has an effect.
2640
-
2641
- Events cover resource discovery, sessions, agent and message lifecycle, providers, tools, and raw input.
2642
-
2643
- #### Understand handler composition
2644
-
2645
- | Pattern | Behavior |
2646
- |---|---|
2647
- | Notification | Return values are ignored. Use the event for observation only. |
2648
- | In-place mutation | Later handlers see changes to values such as `before_provider_headers.headers`, `before_agent_start.systemPromptOptions`, and `tool_call.input`. |
2649
- | Chained transformation | Later handlers receive the value returned by earlier `input`, `context`, `context_with_system`, `message_end`, `tool_result`, and `before_provider_request` handlers. |
2650
- | Gate | A handled input, blocked tool call, cancelled session operation, or handled `user_bash` command stops that operation's normal fallback path. |
2651
- | Actionable boundary | Each `turn_end` or `agent_before_settle` handler sees the entries and continuation decision proposed so far. |
2652
- | Last override | The last `cache_warming_decision` handler that returns an action wins. |
2653
-
2654
- 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.
2655
-
2656
- `before_agent_start` exposes both the current prompt and its structured `systemPromptOptions`. `event.messageType` says what started the run: `"user"` for a prompt or `pi.sendUserMessage()`, with `prompt` and `images`; `"custom"` for `pi.sendMessage(..., { triggerTurn: true })`, with the starting `message` and no `prompt`. A returned `message` is added to either kind of run; check `messageType` to skip runs started by custom messages. Prefer changing prompt sections, selected tools, or guidelines so Pi can append a transcript delta. Returning `systemPrompt`, or setting `forceSystemPrompt`, replaces the whole prompt for that run while the transcript continues recording the structured sections. Providers receive the forced text as their leading system prompt.
2520
+ When `search_tools` adds a match, the model receives the complete updated tool list on the immediately following request.
2657
2521
 
2658
- `message_end` can replace a finalized message while preserving its role. `tool_call` can mutate input or block execution. `tool_result` handlers compose, with each handler seeing prior changes.
2659
-
2660
- <a id="provider_stream_event"></a>
2661
-
2662
- `provider_stream_event` fires for each parsed provider stream event before Pi normalizes it. The event identifies the provider, API, and model; `event.data` is the earliest structured value available to Pi, not necessarily the original HTTP bytes or SSE frame. Treat it as read-only because mutation can affect normalization. The event is notification-only and is not persisted.
2663
-
2664
- 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.
2665
-
2666
- <a id="context_with_system"></a>
2667
-
2668
- `context` transforms conversation messages without prompt and tool system messages; Pi restores that state afterward. Use `context_with_system` only when a request-local transformation must own the complete transcript, and keep a system message at index zero.
2669
-
2670
- `turn_end` and `agent_before_settle` are actionable boundaries. Their handlers can chain proposed `custom`, `custom_message`, `context_edit`, or `compaction` entries and return `continue: true` for one next model request. Guard continuation conditions because an unconditional continuation can loop. Use the exported event declarations for the complete validation and ordering contract.
2671
-
2672
- <a id="cache_warming_decision"></a>
2673
-
2674
- `cache_warming_decision` can override an idle prompt-cache refresh with `{ action: "warm" }` or `{ action: "stop" }`. The last handler that returns an action wins.
2675
-
2676
- Tool calls from one assistant message can run in parallel.
2677
- Do not assume a sibling call or result exists when another tool event runs.
2678
- Use `ctx.signal` for nested work owned by an active turn; commands and idle session events often have no operation signal.
2679
-
2680
- A `user_bash` handler that returns `undefined` passes the command to the next handler and then to local execution if no handler handles it. Returning `operations` or `result` stops propagation. A handler failure blocks the command rather than falling through to local execution.
2681
-
2682
- <a id="custom-tools"></a>
2683
- <a id="register-tools"></a>
2684
-
2685
- ### Tools
2686
-
2687
- A custom tool defines a name, model-facing description, TypeBox parameter schema, and `execute()` function.
2688
- Its result requires model-facing `content` and a `details` field for rendering or state reconstruction.
2689
- Use `details: undefined` when there are no structured details. If the tool makes nested model calls, include their `usage` in the result so session totals remain accurate.
2690
-
2691
- Throw from `execute()` to produce a failed tool result.
2692
- Returning an object does not mark it as an error.
2693
- Return `terminate: true` only when the agent should skip its automatic follow-up after every completed tool in that batch agrees to terminate.
2694
-
2695
- Use sequential execution when tools share mutable in-memory state.
2696
- File-mutating tools should wrap the complete read-modify-write operation with `withFileMutationQueue()`.
2697
- Truncate large model-facing results and tell the model where to read the complete output.
2698
-
2699
- 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`.
2700
-
2701
- A tool can run other tools with `ctx.executeTool(name, args, { signal, onUpdate })`. 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. 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. 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. `ctx.tools` lists the tools `ctx.executeTool()` can call. `tool_result` handlers that redact `content` should also replace `structuredContent`; replacing only `content` drops it.
2702
-
2703
-
2704
- ### Tool exposure
2522
+ ### Tool Exposure
2705
2523
 
2706
2524
  `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:
2707
2525
 
@@ -2713,7 +2531,7 @@ A tool can run other tools with `ctx.executeTool(name, args, { signal, onUpdate
2713
2531
 
2714
2532
  `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.
2715
2533
 
2716
- Registering a `direct` or `model-only` tool activates it; the other exposures are not activated on registration. The active set (`pi.getActiveTools()`, `pi.setActiveTools()`) is the set of tools declared to the model. `pi.getAllTools()` reports each tool's `exposure`, `namespace`, `annotations`, and `reachesTools`.
2534
+ 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`.
2717
2535
 
2718
2536
  `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:
2719
2537
 
@@ -2733,13 +2551,17 @@ A tool that orchestrates other tools can adjust what the model sees while it is
2733
2551
 
2734
2552
  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`.
2735
2553
 
2736
- ### Activate tools dynamically
2554
+ ### Calling Other Tools
2555
+
2556
+ 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`.
2737
2557
 
2738
- Register every tool first, keep optional tools inactive, and use `pi.setActiveTools()` from a loader tool to select the desired active tools. Names must already be registered; unknown names are ignored.
2558
+ 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.
2739
2559
 
2740
- Pi records the initial prompt and tool set in the transcript's first system message, then appends tool and prompt changes before the next model request. Providers that cannot represent the transition receive a complete transcript checkpoint, which can invalidate the cached prefix.
2560
+ 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.
2741
2561
 
2742
- ### MCP servers
2562
+ 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.
2563
+
2564
+ ## MCP Servers
2743
2565
 
2744
2566
  `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`.
2745
2567
 
@@ -2750,83 +2572,187 @@ pi.unregisterMcpServer("jira");
2750
2572
 
2751
2573
  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.
2752
2574
 
2753
- The built-in MCP support connects registered servers. When nothing does, because another extension replaced it (see [MCP](mcp.md#other-mcp-extensions)), 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.
2575
+ 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.
2754
2576
 
2755
- <a id="extensioncontext"></a>
2756
- <a id="extensioncommandcontext"></a>
2757
- <a id="use-extension-context"></a>
2577
+ <a id="interact-with-the-user"></a>
2758
2578
 
2759
- ### Context and session changes
2579
+ ## Custom UI
2760
2580
 
2761
- `ExtensionContext` provides the working directory, mode, UI, session manager, model runtime, abort signal, context usage, and controls for compaction and shutdown.
2762
- Use `ctx.modelRegistry.streamSimple()` for provider-neutral nested model calls.
2581
+ Extensions interact with users through `ctx.ui`. In RPC mode, dialogs and notifications are sent to the client as `extension_ui_request` messages; see [RPC Extension UI](rpc-extension-ui.md) for the protocol and the methods that are no-ops. In print and JSON modes, `ctx.hasUI` is `false` and dialogs return their default values.
2763
2582
 
2764
- Command handlers receive `ExtensionCommandContext`, which adds operations for waiting until idle, reloading, tree navigation, and session replacement.
2765
- These operations are command-only because calling them from lifecycle handlers can deadlock the runtime.
2583
+ ### Dialogs
2766
2584
 
2767
- Session replacement invalidates the old context. Capture only plain data before switching, then use the fresh context supplied to `withSession` for session-bound work.
2585
+ ```typescript
2586
+ // Select from options
2587
+ const choice = await ctx.ui.select("Pick one:", ["A", "B", "C"]);
2768
2588
 
2769
- <a id="state-management"></a>
2770
- <a id="persist-state"></a>
2589
+ // Confirm dialog
2590
+ const ok = await ctx.ui.confirm("Delete?", "This cannot be undone");
2771
2591
 
2772
- ### State
2592
+ // Text input
2593
+ const name = await ctx.ui.input("Name:", "placeholder");
2773
2594
 
2774
- Choose storage based on how state participates in the conversation:
2595
+ // Multi-line editor
2596
+ const text = await ctx.ui.editor("Edit:", "prefilled text");
2775
2597
 
2776
- | State | Storage |
2777
- |---|---|
2778
- | Tool state that follows the active branch | Tool-result `details` |
2779
- | Durable data excluded from model context | `pi.appendEntry()` |
2780
- | Custom content stored and sent to the model | `pi.sendMessage()` |
2781
- | Data outside one session | External storage |
2598
+ // Notification (non-blocking)
2599
+ ctx.ui.notify("Done!", "info"); // "info" | "warning" | "error"
2600
+ ```
2782
2601
 
2783
- Reconstruct branch-sensitive state from `ctx.sessionManager.getBranch()` during `session_start`.
2784
- Do not rebuild it from every file entry because abandoned branches represent alternative histories.
2785
- Register an entry or message renderer when custom stored content should appear in the transcript.
2602
+ #### Timed Dialogs
2786
2603
 
2787
- <a id="custom-ui"></a>
2788
- <a id="mode-behavior"></a>
2789
- <a id="interact-with-the-user"></a>
2790
- <a id="account-for-each-mode"></a>
2604
+ `select()`, `confirm()`, and `input()` accept a `timeout` option that dismisses the dialog when it expires. RPC requests carry the `timeout`, so clients can show a countdown:
2605
+
2606
+ ```typescript
2607
+ const confirmed = await ctx.ui.confirm(
2608
+ "Timed Confirmation",
2609
+ "This dialog will auto-cancel in 5 seconds. Confirm?",
2610
+ { timeout: 5000 }
2611
+ );
2612
+
2613
+ if (confirmed) {
2614
+ // User confirmed
2615
+ } else {
2616
+ // User cancelled or timed out
2617
+ }
2618
+ ```
2619
+
2620
+ **Return values on timeout:**
2621
+ - `select()` returns `undefined`
2622
+ - `confirm()` returns `false`
2623
+ - `input()` returns `undefined`
2624
+
2625
+ #### Manual Dismissal with AbortSignal
2626
+
2627
+ For more control (e.g., to distinguish timeout from user cancel), use `AbortSignal`:
2628
+
2629
+ ```typescript
2630
+ const controller = new AbortController();
2631
+ const timeoutId = setTimeout(() => controller.abort(), 5000);
2791
2632
 
2792
- ### UI and modes
2633
+ const confirmed = await ctx.ui.confirm(
2634
+ "Timed Confirmation",
2635
+ "This dialog will auto-cancel in 5 seconds. Confirm?",
2636
+ { signal: controller.signal }
2637
+ );
2793
2638
 
2794
- `ctx.ui` provides dialogs, notifications, status text, widgets, titles, editor access, and custom components.
2795
- Use `ctx.ui.custom()` only when the interaction needs its own rendering and input.
2796
- See [Terminal UI](tui.md) for component, focus, overlay, theme, and performance guidance.
2639
+ clearTimeout(timeoutId);
2797
2640
 
2798
- Extensions load in interactive, RPC, JSON, and print modes.
2799
- Interactive mode provides the complete terminal UI.
2800
- RPC can forward supported dialogs and notifications through the [RPC Extension UI protocol](rpc-extension-ui.md), but not custom terminal components; JSON and print modes have no UI.
2801
- Guard terminal-only behavior with `ctx.mode === "tui"` and use `ctx.hasUI` for interactions supported by interactive and RPC clients.
2641
+ if (confirmed) {
2642
+ // User confirmed
2643
+ } else if (controller.signal.aborted) {
2644
+ // Dialog timed out
2645
+ } else {
2646
+ // User cancelled
2647
+ }
2648
+ ```
2649
+
2650
+ See [examples/extensions/timed-confirm.ts](../examples/extensions/timed-confirm.ts) for complete examples.
2651
+
2652
+ ### Status, Widgets, Title, and Editor Text
2653
+
2654
+ These methods are fire-and-forget. RPC mode forwards them to the client:
2655
+
2656
+ ```typescript
2657
+ // Status entry (persistent until cleared)
2658
+ ctx.ui.setStatus("my-ext", "Processing...");
2659
+ ctx.ui.setStatus("my-ext", undefined); // Clear
2802
2660
 
2803
- Keep tool and event behavior independent from rendering so non-interactive modes remain functional.
2661
+ // Widget of text lines; placement tells the RPC client where to show it
2662
+ ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"]);
2663
+ ctx.ui.setWidget("my-widget", ["Line 1", "Line 2"], { placement: "belowEditor" });
2664
+ ctx.ui.setWidget("my-widget", undefined); // Clear
2665
+
2666
+ // Window or tab title
2667
+ ctx.ui.setTitle("pi - my-project");
2668
+
2669
+ // Prefill the client's input
2670
+ ctx.ui.setEditorText("Prefill text");
2671
+ ```
2804
2672
 
2805
- <a id="error-handling"></a>
2806
2673
  <a id="handle-errors-and-shutdown"></a>
2807
2674
 
2808
- ### Errors and cleanup
2675
+ ## Error Handling
2809
2676
 
2810
- Pi reports handler errors and continues where possible. A `tool_call` handler failure blocks the tool as a fail-safe; a tool execution failure becomes an error result for the model.
2677
+ - Extension errors are logged, agent continues
2678
+ - `tool_call` errors block the tool (fail-safe)
2679
+ - `user_bash` errors block the command instead of falling through to local execution
2680
+ - 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
2811
2681
 
2812
- Release resources in `session_shutdown` even when normal operation attempted cleanup.
2813
- Keep cleanup idempotent because cancellation, reload, session replacement, and process exit can converge on the same path.
2814
- Use `ctx.shutdown()` to request an orderly process shutdown.
2682
+ <a id="ui-and-modes"></a>
2683
+ <a id="account-for-each-mode"></a>
2815
2684
 
2816
- <a id="examples-reference"></a>
2817
- <a id="use-examples-as-the-implementation-reference"></a>
2685
+ ## Mode Behavior
2818
2686
 
2819
- ## Examples and reference
2687
+ | Mode | `ctx.mode` | `ctx.hasUI` | Notes |
2688
+ |------|------------|-------------|-------|
2689
+ | RPC (`--mode rpc`) | `"rpc"` | `true` | Dialogs and notifications via JSON protocol. See [RPC Extension UI](rpc-extension-ui.md) |
2690
+ | JSON (`--mode json`) | `"json"` | `false` | Event stream to stdout; UI methods are no-ops |
2691
+ | Print (`-p`) | `"print"` | `false` | Extensions run but can't prompt |
2820
2692
 
2821
- The checked [extension examples](../examples/extensions/) are the implementation reference. Start with the smallest example matching the behavior you need:
2693
+ Use `ctx.hasUI` before dialog and notification methods.
2822
2694
 
2823
- | Goal | Start with | Why |
2824
- |---|---|---|
2825
- | Confirm or block tool calls | [`permission-gate.ts`](../examples/extensions/permission-gate.ts) | Combines `tool_call`, mode-aware UI, and fail-closed behavior. |
2826
- | Modify prompt sections for a run | [`prompt-customizer.ts`](../examples/extensions/prompt-customizer.ts) | Uses structured prompt options instead of replacing the complete prompt. |
2827
- | Register tools after startup | [`dynamic-tools.ts`](../examples/extensions/dynamic-tools.ts) | Shares registration logic between lifecycle and command handlers. |
2828
- | Run finalization at shutdown | [`auto-commit-on-exit.ts`](../examples/extensions/auto-commit-on-exit.ts) | Uses the session shutdown hook for finalization work. |
2829
- | Route built-in tools to another machine | [`ssh.ts`](../examples/extensions/ssh.ts) | Reuses tool operation interfaces instead of recreating tool contracts. |
2830
- | Add OAuth and provider-specific streaming | [`custom-provider-gitlab-duo/`](../examples/extensions/custom-provider-gitlab-duo/) | Shows a complete provider integration while delegating supported protocols. |
2695
+ <a id="use-examples-as-the-implementation-reference"></a>
2831
2696
 
2832
- Use [Custom Providers](custom-provider.md) for model-service integrations, [Terminal UI](tui.md) for custom components, and [Pi Packages](packages.md) to install or distribute extensions with other resources. Use the exported declarations for exact signatures, payloads, and result schemas; this guide focuses on lifecycle choices, composition, and durable implementation patterns.
2697
+ ## Examples Reference
2698
+
2699
+ All examples in [examples/extensions/](../examples/extensions/).
2700
+
2701
+ | Example | Description | Key APIs |
2702
+ |---------|-------------|----------|
2703
+ | **Tools** |||
2704
+ | `hello.ts` | Minimal tool registration | `registerTool` |
2705
+ | `dynamic-tools.ts` | Register tools after startup and during commands | `registerTool`, `session_start`, `registerCommand` |
2706
+ | `tool-override.ts` | Override built-in read tool | `registerTool` (same name as built-in) |
2707
+ | **Commands** |||
2708
+ | `pirate.ts` | Modify system prompt per-turn | `registerCommand`, `before_agent_start` |
2709
+ | `send-user-message.ts` | Inject user messages | `registerCommand`, `sendUserMessage` |
2710
+ | `reload-runtime.ts` | Reload command and LLM tool handoff | `registerCommand`, `ctx.reload()`, `on("agent_settled")`, `sendUserMessage` |
2711
+ | `shutdown-command.ts` | Graceful shutdown command | `registerCommand`, `shutdown()` |
2712
+ | **Events & Gates** |||
2713
+ | `permission-gate.ts` | Block dangerous commands | `on("tool_call")`, `ui.select` |
2714
+ | `project-trust.ts` | Decide or defer project trust from a user/global or CLI extension | `on("project_trust")`, trust UI, required trust result |
2715
+ | `protected-paths.ts` | Block writes to specific paths | `on("tool_call")` |
2716
+ | `confirm-destructive.ts` | Confirm session changes | `on("session_before_switch")`, `on("session_before_fork")` |
2717
+ | `dirty-repo-guard.ts` | Warn on dirty git repo | `on("session_before_*")`, `exec` |
2718
+ | `input-transform.ts` | Transform user input | `on("input")` |
2719
+ | `input-transform-streaming.ts` | Streaming-aware input transform | `on("input")`, `streamingBehavior` |
2720
+ | `model-status.ts` | React to model changes | `on("model_select")`, `setStatus` |
2721
+ | `provider-payload.ts` | Inspect payloads and provider response headers | `on("before_provider_request")`, `on("after_provider_response")` |
2722
+ | `debug-provider.ts` | Capture raw provider stream events | `on("provider_stream_event")`, `appendEntry` |
2723
+ | `system-prompt-header.ts` | Display system prompt info | `on("agent_start")`, `getSystemPrompt` |
2724
+ | `claude-rules.ts` | Load rules from files | `on("session_start")`, `on("before_agent_start")` |
2725
+ | `prompt-customizer.ts` | Add context-aware tool guidance using `systemPromptOptions` | `on("before_agent_start")`, `BuildSystemPromptOptions` |
2726
+ | `file-trigger.ts` | File watcher triggers messages | `sendMessage` |
2727
+ | **Compaction & Sessions** |||
2728
+ | `custom-compaction.ts` | Custom compaction summary | `on("session_before_compact")` |
2729
+ | `trigger-compact.ts` | Trigger compaction manually | `compact()` |
2730
+ | `git-checkpoint.ts` | Git stash on turns | `on("turn_start")`, `on("tool_result")`, `on("agent_settled")`, `on("session_before_fork")`, `exec` |
2731
+ | `git-merge-and-resolve.ts` | Fetch, merge, and resolve conflicts | `on("agent_end")`, `exec`, `sendUserMessage` |
2732
+ | `auto-commit-on-exit.ts` | Commit on shutdown | `on("session_shutdown")`, `exec` |
2733
+ | **UI** |||
2734
+ | `status-line.ts` | Status indicator | `setStatus`, session events |
2735
+ | `widget-placement.ts` | Widget above/below editor | `setWidget` |
2736
+ | `notify.ts` | Native terminal notification when the agent is done | `on("agent_settled")` |
2737
+ | `titlebar-spinner.ts` | Spinner in the terminal title while working | `setTitle` |
2738
+ | `rpc-demo.ts` | Every RPC-supported UI method | `ui.*` in RPC mode |
2739
+ | `timed-confirm.ts` | Dialogs with timeout | `ui.confirm` with timeout/signal |
2740
+ | **Remote & Sandbox** |||
2741
+ | `ssh.ts` | SSH remote execution | `registerFlag`, `on("user_bash")`, `on("before_agent_start")`, tool operations |
2742
+ | `gondolin/` | Route built-in tools and user bash commands into a Gondolin micro-VM | Tool operations, built-in tool overrides, `on("user_bash")` |
2743
+ | `subagent/` | Spawn sub-agents | `registerTool`, `exec` |
2744
+ | **Providers** |||
2745
+ | `custom-provider-anthropic/` | Custom Anthropic proxy | `registerProvider` |
2746
+ | `custom-provider-gitlab-duo/` | GitLab Duo integration | `registerProvider` with OAuth |
2747
+ | `jev-router.ts` | Virtual model that routes planning and implementation to different models | `registerVirtualModel` |
2748
+ | **Messages & Communication** |||
2749
+ | `event-bus.ts` | Inter-extension events | `pi.events` |
2750
+ | **Session Metadata** |||
2751
+ | `session-name.ts` | Name sessions | `setSessionName`, `getSessionName` |
2752
+ | `bookmark.ts` | Bookmark entries for tree navigation | `setLabel` |
2753
+ | **Misc** |||
2754
+ | `commands.ts` | List available slash commands | `getCommands` |
2755
+ | `dynamic-resources/` | Add skills, prompts, and themes at runtime | `on("resources_discover")` |
2756
+ | `inline-bash.ts` | Expand inline `!{command}` in user prompts | `on("input")`, `exec` |
2757
+ | `bash-spawn-hook.ts` | Adjust bash command, cwd, and env before execution | `createBashTool`, `spawnHook` |
2758
+ | `with-deps/` | Extension with npm dependencies | Package structure with `package.json` |