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