@gatanot/orrery 0.1.0

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