@lenylvt/pi-coding-agent 0.64.0

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