@schovest/pi-coding-agent 0.7.3

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