@earendil-works/pi-coding-agent 0.84.1 → 0.84.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (328) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/README.md +9 -4
  3. package/dist/bundle/chunks/anthropic-messages-JWX2WP65.js +45 -0
  4. package/dist/bundle/chunks/anthropic.js +75 -0
  5. package/dist/bundle/chunks/azure-openai-responses-5ENVCQ7U.js +2 -0
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +74 -0
  7. package/dist/bundle/chunks/chunk-4L3WN2XY.js +2 -0
  8. package/dist/bundle/chunks/chunk-6CYCI3EJ.js +12 -0
  9. package/dist/bundle/chunks/chunk-6R7UI4IY.js +2 -0
  10. package/dist/bundle/chunks/chunk-AXIIZGTV.js +2 -0
  11. package/dist/bundle/chunks/chunk-DRQDKNXA.js +2 -0
  12. package/dist/bundle/chunks/chunk-E5KXRMZK.js +1547 -0
  13. package/dist/bundle/chunks/chunk-GMWCTUPB.js +2 -0
  14. package/dist/bundle/chunks/chunk-GPPBJGBU.js +50 -0
  15. package/dist/bundle/chunks/chunk-JUUC5AZY.js +2 -0
  16. package/dist/bundle/chunks/chunk-L2ZPNLYD.js +2 -0
  17. package/dist/bundle/chunks/chunk-MNAIPA3J.js +2 -0
  18. package/dist/bundle/chunks/chunk-NBBFIJUL.js +11 -0
  19. package/dist/bundle/chunks/chunk-NUHFSC37.js +25 -0
  20. package/dist/bundle/chunks/chunk-PGXDEOVV.js +2 -0
  21. package/dist/bundle/chunks/chunk-PJACZCIR.js +2 -0
  22. package/dist/bundle/chunks/chunk-PRRNXB7S.js +2 -0
  23. package/dist/bundle/chunks/chunk-TEPMHNKQ.js +2 -0
  24. package/dist/bundle/chunks/chunk-TRDNDS6A.js +4 -0
  25. package/dist/bundle/chunks/chunk-UAQELI3K.js +2 -0
  26. package/dist/bundle/chunks/chunk-XDUWOHPL.js +6 -0
  27. package/dist/bundle/chunks/chunk-XNGRGP62.js +2 -0
  28. package/dist/bundle/chunks/dist-RDWOYWHR.js +13 -0
  29. package/dist/bundle/chunks/github-copilot.js +2 -0
  30. package/dist/bundle/chunks/google-generative-ai-XDKMGBCJ.js +2 -0
  31. package/dist/bundle/chunks/google-vertex-D5FGEO3Y.js +2 -0
  32. package/dist/bundle/chunks/image-resize-worker.js +2 -0
  33. package/dist/bundle/chunks/kimi-coding.js +2 -0
  34. package/dist/bundle/chunks/lib-HGQMNYVT.js +9 -0
  35. package/dist/bundle/chunks/mistral-conversations-YK73UAOZ.js +5 -0
  36. package/dist/bundle/chunks/multipart-parser-SQ6GDJL7.js +3 -0
  37. package/dist/bundle/chunks/openai-codex-responses-GJVBJXLB.js +8 -0
  38. package/dist/bundle/chunks/openai-codex.js +75 -0
  39. package/dist/bundle/chunks/openai-completions-JD4WAC3R.js +7 -0
  40. package/dist/bundle/chunks/openai-responses-BSOJMSEV.js +2 -0
  41. package/dist/bundle/chunks/openrouter-images-N4XVVFSD.js +2 -0
  42. package/dist/bundle/chunks/openrouter.js +75 -0
  43. package/dist/bundle/chunks/pi-messages-TPFH44NP.js +8 -0
  44. package/dist/bundle/chunks/radius.js +75 -0
  45. package/dist/bundle/chunks/src-UK77SYZE.js +4 -0
  46. package/dist/bundle/chunks/xai.js +2 -0
  47. package/dist/bundle/cli.js +3 -0
  48. package/dist/bundle/client.js +2 -0
  49. package/dist/bundle/index.js +2 -0
  50. package/dist/bundle/rpc-entry.js +3 -0
  51. package/dist/cli/args.d.ts +2 -0
  52. package/dist/cli/args.d.ts.map +1 -1
  53. package/dist/cli/args.js +40 -9
  54. package/dist/cli/args.js.map +1 -1
  55. package/dist/cli/auth-command.d.ts.map +1 -1
  56. package/dist/cli/auth-command.js +5 -4
  57. package/dist/cli/auth-command.js.map +1 -1
  58. package/dist/cli/file-processor.d.ts.map +1 -1
  59. package/dist/cli/file-processor.js +2 -1
  60. package/dist/cli/file-processor.js.map +1 -1
  61. package/dist/config.d.ts +4 -3
  62. package/dist/config.d.ts.map +1 -1
  63. package/dist/config.js +22 -14
  64. package/dist/config.js.map +1 -1
  65. package/dist/core/agent-session.d.ts +33 -9
  66. package/dist/core/agent-session.d.ts.map +1 -1
  67. package/dist/core/agent-session.js +169 -101
  68. package/dist/core/agent-session.js.map +1 -1
  69. package/dist/core/auth-storage.d.ts.map +1 -1
  70. package/dist/core/auth-storage.js +6 -7
  71. package/dist/core/auth-storage.js.map +1 -1
  72. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  73. package/dist/core/compaction/branch-summarization.js +3 -0
  74. package/dist/core/compaction/branch-summarization.js.map +1 -1
  75. package/dist/core/compaction/compaction.d.ts +4 -3
  76. package/dist/core/compaction/compaction.d.ts.map +1 -1
  77. package/dist/core/compaction/compaction.js +41 -32
  78. package/dist/core/compaction/compaction.js.map +1 -1
  79. package/dist/core/defaults.d.ts +1 -0
  80. package/dist/core/defaults.d.ts.map +1 -1
  81. package/dist/core/defaults.js +9 -0
  82. package/dist/core/defaults.js.map +1 -1
  83. package/dist/core/experimental.d.ts +4 -0
  84. package/dist/core/experimental.d.ts.map +1 -1
  85. package/dist/core/experimental.js +4 -0
  86. package/dist/core/experimental.js.map +1 -1
  87. package/dist/core/extensions/index.d.ts +2 -2
  88. package/dist/core/extensions/index.d.ts.map +1 -1
  89. package/dist/core/extensions/index.js +1 -1
  90. package/dist/core/extensions/index.js.map +1 -1
  91. package/dist/core/extensions/loader.d.ts.map +1 -1
  92. package/dist/core/extensions/loader.js +115 -48
  93. package/dist/core/extensions/loader.js.map +1 -1
  94. package/dist/core/extensions/types.d.ts +42 -9
  95. package/dist/core/extensions/types.d.ts.map +1 -1
  96. package/dist/core/extensions/types.js +3 -0
  97. package/dist/core/extensions/types.js.map +1 -1
  98. package/dist/core/footer-data-provider.d.ts +1 -1
  99. package/dist/core/footer-data-provider.d.ts.map +1 -1
  100. package/dist/core/footer-data-provider.js +1 -1
  101. package/dist/core/footer-data-provider.js.map +1 -1
  102. package/dist/core/keybindings.d.ts +38 -13
  103. package/dist/core/keybindings.d.ts.map +1 -1
  104. package/dist/core/keybindings.js +26 -5
  105. package/dist/core/keybindings.js.map +1 -1
  106. package/dist/core/model-config.d.ts +10 -0
  107. package/dist/core/model-config.d.ts.map +1 -1
  108. package/dist/core/model-config.js +4 -1
  109. package/dist/core/model-config.js.map +1 -1
  110. package/dist/core/model-resolver.d.ts +1 -0
  111. package/dist/core/model-resolver.d.ts.map +1 -1
  112. package/dist/core/model-resolver.js +14 -8
  113. package/dist/core/model-resolver.js.map +1 -1
  114. package/dist/core/models-store.d.ts.map +1 -1
  115. package/dist/core/models-store.js +2 -1
  116. package/dist/core/models-store.js.map +1 -1
  117. package/dist/core/package-manager.d.ts.map +1 -1
  118. package/dist/core/package-manager.js +22 -14
  119. package/dist/core/package-manager.js.map +1 -1
  120. package/dist/core/pi-manifest.d.ts.map +1 -1
  121. package/dist/core/pi-manifest.js +2 -1
  122. package/dist/core/pi-manifest.js.map +1 -1
  123. package/dist/core/project-trust.d.ts.map +1 -1
  124. package/dist/core/project-trust.js +2 -2
  125. package/dist/core/project-trust.js.map +1 -1
  126. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  127. package/dist/core/remote-catalog-provider.js +2 -1
  128. package/dist/core/remote-catalog-provider.js.map +1 -1
  129. package/dist/core/resource-loader.d.ts.map +1 -1
  130. package/dist/core/resource-loader.js +3 -2
  131. package/dist/core/resource-loader.js.map +1 -1
  132. package/dist/core/sdk.d.ts +7 -5
  133. package/dist/core/sdk.d.ts.map +1 -1
  134. package/dist/core/sdk.js +12 -4
  135. package/dist/core/sdk.js.map +1 -1
  136. package/dist/core/session-export.d.ts +4 -0
  137. package/dist/core/session-export.d.ts.map +1 -0
  138. package/dist/core/session-export.js +32 -0
  139. package/dist/core/session-export.js.map +1 -0
  140. package/dist/core/session-manager.d.ts.map +1 -1
  141. package/dist/core/session-manager.js +4 -3
  142. package/dist/core/session-manager.js.map +1 -1
  143. package/dist/core/settings-diagnostics.d.ts +9 -0
  144. package/dist/core/settings-diagnostics.d.ts.map +1 -0
  145. package/dist/core/settings-diagnostics.js +21 -0
  146. package/dist/core/settings-diagnostics.js.map +1 -0
  147. package/dist/core/settings-manager.d.ts +15 -0
  148. package/dist/core/settings-manager.d.ts.map +1 -1
  149. package/dist/core/settings-manager.js +64 -10
  150. package/dist/core/settings-manager.js.map +1 -1
  151. package/dist/core/skills.d.ts.map +1 -1
  152. package/dist/core/skills.js +51 -33
  153. package/dist/core/skills.js.map +1 -1
  154. package/dist/core/slash-commands.d.ts.map +1 -1
  155. package/dist/core/slash-commands.js +2 -1
  156. package/dist/core/slash-commands.js.map +1 -1
  157. package/dist/core/system-prompt.d.ts.map +1 -1
  158. package/dist/core/system-prompt.js +12 -3
  159. package/dist/core/system-prompt.js.map +1 -1
  160. package/dist/core/tools/bash.d.ts +14 -1
  161. package/dist/core/tools/bash.d.ts.map +1 -1
  162. package/dist/core/tools/bash.js +38 -20
  163. package/dist/core/tools/bash.js.map +1 -1
  164. package/dist/core/tools/edit-diff.d.ts +0 -5
  165. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  166. package/dist/core/tools/edit-diff.js +2 -5
  167. package/dist/core/tools/edit-diff.js.map +1 -1
  168. package/dist/core/tools/edit.d.ts.map +1 -1
  169. package/dist/core/tools/edit.js +22 -4
  170. package/dist/core/tools/edit.js.map +1 -1
  171. package/dist/core/tools/find.d.ts.map +1 -1
  172. package/dist/core/tools/find.js +1 -1
  173. package/dist/core/tools/find.js.map +1 -1
  174. package/dist/core/tools/grep.d.ts.map +1 -1
  175. package/dist/core/tools/grep.js +1 -1
  176. package/dist/core/tools/grep.js.map +1 -1
  177. package/dist/core/tools/index.d.ts +4 -1
  178. package/dist/core/tools/index.d.ts.map +1 -1
  179. package/dist/core/tools/index.js +18 -1
  180. package/dist/core/tools/index.js.map +1 -1
  181. package/dist/core/tools/powershell.d.ts +16 -0
  182. package/dist/core/tools/powershell.d.ts.map +1 -0
  183. package/dist/core/tools/powershell.js +39 -0
  184. package/dist/core/tools/powershell.js.map +1 -0
  185. package/dist/core/tools/read.d.ts.map +1 -1
  186. package/dist/core/tools/read.js +2 -0
  187. package/dist/core/tools/read.js.map +1 -1
  188. package/dist/core/tools/write.d.ts.map +1 -1
  189. package/dist/core/tools/write.js +2 -0
  190. package/dist/core/tools/write.js.map +1 -1
  191. package/dist/core/trust-manager.d.ts.map +1 -1
  192. package/dist/core/trust-manager.js +2 -1
  193. package/dist/core/trust-manager.js.map +1 -1
  194. package/dist/extensions/llama/index.d.ts.map +1 -1
  195. package/dist/extensions/llama/index.js +2 -0
  196. package/dist/extensions/llama/index.js.map +1 -1
  197. package/dist/extensions/llama/provider.d.ts.map +1 -1
  198. package/dist/extensions/llama/provider.js +6 -2
  199. package/dist/extensions/llama/provider.js.map +1 -1
  200. package/dist/index.d.ts +6 -6
  201. package/dist/index.d.ts.map +1 -1
  202. package/dist/index.js +4 -4
  203. package/dist/index.js.map +1 -1
  204. package/dist/main.d.ts +4 -0
  205. package/dist/main.d.ts.map +1 -1
  206. package/dist/main.js +23 -16
  207. package/dist/main.js.map +1 -1
  208. package/dist/migrations.d.ts.map +1 -1
  209. package/dist/migrations.js +4 -3
  210. package/dist/migrations.js.map +1 -1
  211. package/dist/modes/interactive/components/model-selector.d.ts +9 -3
  212. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  213. package/dist/modes/interactive/components/model-selector.js +58 -13
  214. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  215. package/dist/modes/interactive/components/settings-selector.d.ts +10 -3
  216. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  217. package/dist/modes/interactive/components/settings-selector.js +128 -56
  218. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  219. package/dist/modes/interactive/components/settings-submenu.d.ts +72 -0
  220. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -0
  221. package/dist/modes/interactive/components/settings-submenu.js +165 -0
  222. package/dist/modes/interactive/components/settings-submenu.js.map +1 -0
  223. package/dist/modes/interactive/components/thinking-selector.d.ts +15 -3
  224. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  225. package/dist/modes/interactive/components/thinking-selector.js +74 -17
  226. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  227. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  228. package/dist/modes/interactive/components/tool-execution.js +10 -1
  229. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  230. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  231. package/dist/modes/interactive/external-editor.js +2 -1
  232. package/dist/modes/interactive/external-editor.js.map +1 -1
  233. package/dist/modes/interactive/interactive-mode.d.ts +19 -2
  234. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  235. package/dist/modes/interactive/interactive-mode.js +250 -129
  236. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  237. package/dist/modes/interactive/model-catalog-refresh.d.ts +7 -0
  238. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -0
  239. package/dist/modes/interactive/model-catalog-refresh.js +34 -0
  240. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -0
  241. package/dist/modes/interactive/session-share.d.ts +16 -0
  242. package/dist/modes/interactive/session-share.d.ts.map +1 -0
  243. package/dist/modes/interactive/session-share.js +188 -0
  244. package/dist/modes/interactive/session-share.js.map +1 -0
  245. package/dist/modes/interactive/theme/dark.json +2 -0
  246. package/dist/modes/interactive/theme/light.json +2 -0
  247. package/dist/modes/interactive/theme/theme-controller.d.ts +10 -2
  248. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  249. package/dist/modes/interactive/theme/theme-controller.js +25 -11
  250. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  251. package/dist/modes/interactive/theme/theme-schema.json +9 -1
  252. package/dist/modes/interactive/theme/theme.d.ts +5 -3
  253. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  254. package/dist/modes/interactive/theme/theme.js +16 -5
  255. package/dist/modes/interactive/theme/theme.js.map +1 -1
  256. package/dist/modes/json-event.d.ts +18 -12
  257. package/dist/modes/json-event.d.ts.map +1 -1
  258. package/dist/modes/json-event.js +22 -5
  259. package/dist/modes/json-event.js.map +1 -1
  260. package/dist/package-manager-cli.d.ts +1 -0
  261. package/dist/package-manager-cli.d.ts.map +1 -1
  262. package/dist/package-manager-cli.js +187 -3
  263. package/dist/package-manager-cli.js.map +1 -1
  264. package/dist/server/create-harness.d.ts.map +1 -1
  265. package/dist/server/create-harness.js +2 -0
  266. package/dist/server/create-harness.js.map +1 -1
  267. package/dist/utils/frontmatter.d.ts.map +1 -1
  268. package/dist/utils/frontmatter.js +2 -1
  269. package/dist/utils/frontmatter.js.map +1 -1
  270. package/dist/utils/management-http.d.ts +5 -3
  271. package/dist/utils/management-http.d.ts.map +1 -1
  272. package/dist/utils/management-http.js +14 -10
  273. package/dist/utils/management-http.js.map +1 -1
  274. package/dist/utils/shell.d.ts +3 -0
  275. package/dist/utils/shell.d.ts.map +1 -1
  276. package/dist/utils/shell.js +17 -5
  277. package/dist/utils/shell.js.map +1 -1
  278. package/dist/utils/syntax-highlight.d.ts +1 -0
  279. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  280. package/dist/utils/syntax-highlight.js +60 -1
  281. package/dist/utils/syntax-highlight.js.map +1 -1
  282. package/dist/utils/text.d.ts +8 -0
  283. package/dist/utils/text.d.ts.map +1 -0
  284. package/dist/utils/text.js +9 -0
  285. package/dist/utils/text.js.map +1 -0
  286. package/dist/utils/tools-manager.d.ts +10 -1
  287. package/dist/utils/tools-manager.d.ts.map +1 -1
  288. package/dist/utils/tools-manager.js +14 -19
  289. package/dist/utils/tools-manager.js.map +1 -1
  290. package/docs/compaction.md +21 -6
  291. package/docs/custom-provider.md +6 -3
  292. package/docs/environment-variables.md +16 -10
  293. package/docs/extensions.md +21 -7
  294. package/docs/json.md +12 -5
  295. package/docs/keybindings.md +15 -9
  296. package/docs/llama-cpp.md +2 -0
  297. package/docs/models.md +8 -2
  298. package/docs/packages.md +2 -2
  299. package/docs/rpc.md +24 -7
  300. package/docs/sdk.md +16 -2
  301. package/docs/settings.md +41 -2
  302. package/docs/skills.md +4 -3
  303. package/docs/terminal-setup.md +34 -11
  304. package/docs/themes.md +24 -3
  305. package/docs/tui.md +2 -2
  306. package/docs/usage.md +9 -4
  307. package/docs/windows.md +24 -2
  308. package/examples/extensions/border-status-editor.ts +1 -1
  309. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  310. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  311. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  312. package/examples/extensions/git-checkpoint.ts +2 -2
  313. package/examples/extensions/gondolin/package-lock.json +2 -2
  314. package/examples/extensions/gondolin/package.json +1 -1
  315. package/examples/extensions/notify.ts +3 -1
  316. package/examples/extensions/sandbox/package-lock.json +2 -2
  317. package/examples/extensions/sandbox/package.json +1 -1
  318. package/examples/extensions/subagent/README.md +3 -1
  319. package/examples/extensions/subagent/agents.ts +40 -9
  320. package/examples/extensions/subagent/index.ts +27 -4
  321. package/examples/extensions/titlebar-spinner.ts +1 -1
  322. package/examples/extensions/with-deps/package-lock.json +2 -2
  323. package/examples/extensions/with-deps/package.json +1 -1
  324. package/examples/rpc-extension-ui.ts +1 -1
  325. package/examples/sdk/06-extensions.ts +1 -1
  326. package/examples/sdk/README.md +1 -1
  327. package/npm-shrinkwrap.json +28 -132
  328. package/package.json +12 -14
@@ -1 +1 @@
1
- {"version":3,"file":"tools-manager.js","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAyB,SAAS,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAC1G,OAAO,EAAE,IAAI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CAAC,CAAC,CAAC;QAC7F,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,+BAA+B;IAC/B,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,4BAA4B,CAAC,CAAC,CAAC;IACpE,CAAC;IAED,IAAI,CAAC;QACJ,MAAM,IAAI,GAAG,MAAM,YAAY,CAAC,IAAI,CAAC,CAAC;QACtC,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,iBAAiB,IAAI,EAAE,CAAC,CAAC,CAAC;QAC/D,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACZ,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,sBAAsB,MAAM,CAAC,IAAI,KAAK,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACvG,CAAC;QACD,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["import chalk from \"chalk\";\nimport { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { chmodSync, createWriteStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from \"fs\";\nimport { arch, platform } from \"os\";\nimport { join } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { APP_NAME, getBinDir } from \"../config.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.PI_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n\tgetAssetName: (version: string, plat: string, architecture: string) => string | null;\n}\n\nconst TOOLS: Record<string, ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-unknown-linux-gnu.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tif (architecture === \"arm64\") {\n\t\t\t\t\treturn `ripgrep-${version}-aarch64-unknown-linux-gnu.tar.gz`;\n\t\t\t\t}\n\t\t\t\treturn `ripgrep-${version}-x86_64-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n};\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\" });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\"): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n// Fetch latest release version from GitHub\nasync function getLatestVersion(repo: string): Promise<string> {\n\tconst response = await fetchWithRetry(\n\t\t`https://api.github.com/repos/${repo}/releases/latest`,\n\t\t{\n\t\t\theaders: { \"User-Agent\": `${APP_NAME}-coding-agent` },\n\t\t},\n\t\t{ timeoutMs: NETWORK_TIMEOUT_MS },\n\t);\n\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub API error: ${response.status}`);\n\t}\n\n\tconst data = (await response.json()) as { tag_name: string };\n\treturn data.tag_name.replace(/^v/, \"\");\n}\n\n// Download a file from URL\nasync function downloadFile(url: string, dest: string): Promise<void> {\n\tconst response = await fetchWithRetry(url, undefined, { timeoutMs: DOWNLOAD_TIMEOUT_MS });\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst fileStream = createWriteStream(dest);\n\tawait pipeline(Readable.fromWeb(response.body as any), fileStream);\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\" });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\n// Download and install a tool\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise<string> {\n\tconst config = TOOLS[tool];\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Get latest version\n\tlet version = await getLatestVersion(config.repo);\n\tif (tool === \"fd\" && plat === \"darwin\" && architecture === \"x64\") {\n\t\tversion = \"10.3.0\";\n\t}\n\n\t// Get asset name for this platform\n\tconst assetName = config.getAssetName(version, plat, architecture);\n\tif (!assetName) {\n\t\tthrow new Error(`Unsupported platform: ${plat}/${architecture}`);\n\t}\n\n\t// Create tools directory\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\tconst downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`;\n\tconst archivePath = join(TOOLS_DIR, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// Download\n\tawait downloadFile(downloadUrl, archivePath);\n\n\t// Extract into a unique temp directory. fd and rg downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tTOOLS_DIR,\n\t\t`extract_tmp_${config.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(extractDir, { recursive: true });\n\n\ttry {\n\t\tif (assetName.endsWith(\".tar.gz\")) {\n\t\t\textractTarGzArchive(archivePath, extractDir, assetName);\n\t\t} else if (assetName.endsWith(\".zip\")) {\n\t\t\textractZipArchive(archivePath, extractDir, assetName);\n\t\t} else {\n\t\t\tthrow new Error(`Unsupported archive format: ${assetName}`);\n\t\t}\n\n\t\t// Find the binary in extracted files. Some archives contain files directly\n\t\t// at root, others nest under a versioned subdirectory.\n\t\tconst binaryFileName = config.binaryName + binaryExt;\n\t\tconst extractedDir = join(extractDir, assetName.replace(/\\.(tar\\.gz|zip)$/, \"\"));\n\t\tconst extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)];\n\t\tlet extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate));\n\n\t\tif (!extractedBinary) {\n\t\t\textractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined;\n\t\t}\n\n\t\tif (extractedBinary) {\n\t\t\trenameSync(extractedBinary, binaryPath);\n\t\t} else {\n\t\t\tthrow new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);\n\t\t}\n\n\t\t// Make executable (Unix only)\n\t\tif (plat !== \"win32\") {\n\t\t\tchmodSync(binaryPath, 0o755);\n\t\t}\n\t} finally {\n\t\t// Cleanup\n\t\trmSync(archivePath, { force: true });\n\t\trmSync(extractDir, { recursive: true, force: true });\n\t}\n\n\treturn binaryPath;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<string, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\n// Ensure a tool is available, downloading if necessary\n// Returns the path to the tool, or null if unavailable\nexport async function ensureTool(tool: \"fd\" | \"rg\", silent: boolean = false): Promise<string | undefined> {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${pkgName}`));\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Tool not found - download it\n\tif (!silent) {\n\t\tconsole.log(chalk.dim(`${config.name} not found. Downloading...`));\n\t}\n\n\ttry {\n\t\tconst path = await downloadTool(tool);\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.dim(`${config.name} installed to ${path}`));\n\t\t}\n\t\treturn path;\n\t} catch (e) {\n\t\tif (!silent) {\n\t\t\tconsole.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));\n\t\t}\n\t\treturn undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"tools-manager.js","sourceRoot":"","sources":["../../src/utils/tools-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyB,SAAS,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAC1G,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,MAAM,SAAS,GAAG,SAAS,EAAE,CAAC;AAC9B,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,mBAAmB,GAAG,OAAO,CAAC;AAEpC,SAAS,oBAAoB,GAAY;IACxC,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;IACrC,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC;IACzB,OAAO,KAAK,KAAK,GAAG,IAAI,KAAK,CAAC,WAAW,EAAE,KAAK,MAAM,IAAI,KAAK,CAAC,WAAW,EAAE,KAAK,KAAK,CAAC;AAAA,CACxF;AAWD,MAAM,KAAK,GAA+B;IACzC,EAAE,EAAE;QACH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AC5B,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,IAAI,sDAAsD,EAAE,CAAC,CAAC;QAC/G,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,mFAAmF;IACnF,8BAA8B;IAC9B,IAAI,QAAQ,EAAE,KAAK,SAAS,EAAE,CAAC;QAC9B,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC;QAC9C,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,IAAI,yCAAyC,OAAO,EAAE,EAAE,CAAC,CAAC;QAC3G,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,+BAA+B;IAC/B,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,IAAI,4BAA4B,EAAE,CAAC,CAAC;IAElF,IAAI,CAAC;QACJ,MAAM,IAAI,GAAG,MAAM,YAAY,CAAC,IAAI,CAAC,CAAC;QACtC,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,IAAI,iBAAiB,IAAI,EAAE,EAAE,CAAC,CAAC;QAC7E,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACZ,QAAQ,EAAE,CAAC;YACV,IAAI,EAAE,SAAS;YACf,OAAO,EAAE,sBAAsB,MAAM,CAAC,IAAI,KAAK,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;SACnF,CAAC,CAAC;QACH,OAAO,SAAS,CAAC;IAClB,CAAC;AAAA,CACD","sourcesContent":["import { type SpawnSyncReturns, spawnSync } from \"child_process\";\nimport { chmodSync, createWriteStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from \"fs\";\nimport { arch, platform } from \"os\";\nimport { join } from \"path\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport { APP_NAME, getBinDir } from \"../config.ts\";\nimport { fetchWithRetry } from \"./management-http.ts\";\n\nconst TOOLS_DIR = getBinDir();\nconst NETWORK_TIMEOUT_MS = 10_000;\nconst DOWNLOAD_TIMEOUT_MS = 120_000;\n\nfunction isOfflineModeEnabled(): boolean {\n\tconst value = process.env.PI_OFFLINE;\n\tif (!value) return false;\n\treturn value === \"1\" || value.toLowerCase() === \"true\" || value.toLowerCase() === \"yes\";\n}\n\ninterface ToolConfig {\n\tname: string;\n\trepo: string; // GitHub repo (e.g., \"sharkdp/fd\")\n\tbinaryName: string; // Name of the binary inside the archive\n\tsystemBinaryNames?: string[]; // Alternative system command names to try before downloading\n\ttagPrefix: string; // Prefix for tags (e.g., \"v\" for v1.0.0, \"\" for 1.0.0)\n\tgetAssetName: (version: string, plat: string, architecture: string) => string | null;\n}\n\nconst TOOLS: Record<string, ToolConfig> = {\n\tfd: {\n\t\tname: \"fd\",\n\t\trepo: \"sharkdp/fd\",\n\t\tbinaryName: \"fd\",\n\t\tsystemBinaryNames: [\"fd\", \"fdfind\"],\n\t\ttagPrefix: \"v\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-unknown-linux-gnu.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `fd-v${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n\trg: {\n\t\tname: \"ripgrep\",\n\t\trepo: \"BurntSushi/ripgrep\",\n\t\tbinaryName: \"rg\",\n\t\ttagPrefix: \"\",\n\t\tgetAssetName: (version, plat, architecture) => {\n\t\t\tif (plat === \"darwin\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`;\n\t\t\t} else if (plat === \"linux\") {\n\t\t\t\tif (architecture === \"arm64\") {\n\t\t\t\t\treturn `ripgrep-${version}-aarch64-unknown-linux-gnu.tar.gz`;\n\t\t\t\t}\n\t\t\t\treturn `ripgrep-${version}-x86_64-unknown-linux-musl.tar.gz`;\n\t\t\t} else if (plat === \"win32\") {\n\t\t\t\tconst archStr = architecture === \"arm64\" ? \"aarch64\" : \"x86_64\";\n\t\t\t\treturn `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t},\n};\n\n// Check if a command exists in PATH by trying to run it\nfunction commandExists(cmd: string): boolean {\n\ttry {\n\t\tconst result = spawnSync(cmd, [\"--version\"], { stdio: \"pipe\" });\n\t\t// Check for ENOENT error (command not found)\n\t\treturn result.error === undefined || result.error === null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// Get the path to a tool (system-wide or in our tools dir)\nexport function getToolPath(tool: \"fd\" | \"rg\"): string | null {\n\tconst config = TOOLS[tool];\n\tif (!config) return null;\n\n\t// Check our tools directory first\n\tconst localPath = join(TOOLS_DIR, config.binaryName + (platform() === \"win32\" ? \".exe\" : \"\"));\n\tif (existsSync(localPath)) {\n\t\treturn localPath;\n\t}\n\n\t// Check system PATH - if found, just return the command name (it's in PATH)\n\tconst systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];\n\tfor (const systemBinaryName of systemBinaryNames) {\n\t\tif (commandExists(systemBinaryName)) {\n\t\t\treturn systemBinaryName;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n// Fetch latest release version from GitHub\nasync function getLatestVersion(repo: string): Promise<string> {\n\tconst response = await fetchWithRetry(\n\t\t`https://api.github.com/repos/${repo}/releases/latest`,\n\t\t{\n\t\t\theaders: { \"User-Agent\": `${APP_NAME}-coding-agent` },\n\t\t},\n\t\t{ timeoutMs: NETWORK_TIMEOUT_MS },\n\t);\n\n\tif (!response.ok) {\n\t\tthrow new Error(`GitHub API error: ${response.status}`);\n\t}\n\n\tconst data = (await response.json()) as { tag_name: string };\n\treturn data.tag_name.replace(/^v/, \"\");\n}\n\n// Download a file from URL\nasync function downloadFile(url: string, dest: string): Promise<void> {\n\tconst response = await fetchWithRetry(url, undefined, { timeoutMs: DOWNLOAD_TIMEOUT_MS });\n\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to download: ${response.status}`);\n\t}\n\n\tif (!response.body) {\n\t\tthrow new Error(\"No response body\");\n\t}\n\n\tconst fileStream = createWriteStream(dest);\n\tawait pipeline(Readable.fromWeb(response.body as any), fileStream);\n}\n\nfunction findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {\n\tconst stack: string[] = [rootDir];\n\n\twhile (stack.length > 0) {\n\t\tconst currentDir = stack.pop();\n\t\tif (!currentDir) continue;\n\n\t\tconst entries = readdirSync(currentDir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst fullPath = join(currentDir, entry.name);\n\t\t\tif (entry.isFile() && entry.name === binaryFileName) {\n\t\t\t\treturn fullPath;\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tstack.push(fullPath);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {\n\tif (result.error?.message) {\n\t\treturn result.error.message;\n\t}\n\tconst stderr = result.stderr?.toString().trim();\n\tif (stderr) {\n\t\treturn stderr;\n\t}\n\tconst stdout = result.stdout?.toString().trim();\n\tif (stdout) {\n\t\treturn stdout;\n\t}\n\treturn `exit status ${result.status ?? \"unknown\"}`;\n}\n\nfunction runExtractionCommand(command: string, args: string[]): string | null {\n\tconst result = spawnSync(command, args, { stdio: \"pipe\" });\n\tif (!result.error && result.status === 0) {\n\t\treturn null;\n\t}\n\treturn `${command}: ${formatSpawnFailure(result)}`;\n}\n\nfunction extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failure = runExtractionCommand(\"tar\", [\"xzf\", archivePath, \"-C\", extractDir]);\n\tif (failure) {\n\t\tthrow new Error(`Failed to extract ${assetName}: ${failure}`);\n\t}\n}\n\nfunction getWindowsTarCommand(): string {\n\tconst systemRoot = process.env.SystemRoot ?? process.env.WINDIR;\n\tif (systemRoot) {\n\t\tconst systemTar = join(systemRoot, \"System32\", \"tar.exe\");\n\t\tif (existsSync(systemTar)) {\n\t\t\treturn systemTar;\n\t\t}\n\t}\n\treturn \"tar.exe\";\n}\n\nfunction extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {\n\tconst failures: string[] = [];\n\n\tif (platform() === \"win32\") {\n\t\t// Windows ships bsdtar as tar.exe, which supports zip files. Prefer the\n\t\t// System32 binary over Git Bash's GNU tar, which does not handle zip archives.\n\t\tconst tarFailure = runExtractionCommand(getWindowsTarCommand(), [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\n\t\tconst script =\n\t\t\t\"& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }\";\n\t\tconst powershellFailure = runExtractionCommand(\"powershell.exe\", [\n\t\t\t\"-NoLogo\",\n\t\t\t\"-NoProfile\",\n\t\t\t\"-NonInteractive\",\n\t\t\t\"-ExecutionPolicy\",\n\t\t\t\"Bypass\",\n\t\t\t\"-Command\",\n\t\t\tscript,\n\t\t\tarchivePath,\n\t\t\textractDir,\n\t\t]);\n\t\tif (!powershellFailure) return;\n\t\tfailures.push(powershellFailure);\n\t} else {\n\t\tconst unzipFailure = runExtractionCommand(\"unzip\", [\"-q\", archivePath, \"-d\", extractDir]);\n\t\tif (!unzipFailure) return;\n\t\tfailures.push(unzipFailure);\n\n\t\tconst tarFailure = runExtractionCommand(\"tar\", [\"xf\", archivePath, \"-C\", extractDir]);\n\t\tif (!tarFailure) return;\n\t\tfailures.push(tarFailure);\n\t}\n\n\tthrow new Error(`Failed to extract ${assetName}: ${failures.join(\"; \")}`);\n}\n\n// Download and install a tool\nasync function downloadTool(tool: \"fd\" | \"rg\"): Promise<string> {\n\tconst config = TOOLS[tool];\n\tif (!config) throw new Error(`Unknown tool: ${tool}`);\n\n\tconst plat = platform();\n\tconst architecture = arch();\n\n\t// Get latest version\n\tlet version = await getLatestVersion(config.repo);\n\tif (tool === \"fd\" && plat === \"darwin\" && architecture === \"x64\") {\n\t\tversion = \"10.3.0\";\n\t}\n\n\t// Get asset name for this platform\n\tconst assetName = config.getAssetName(version, plat, architecture);\n\tif (!assetName) {\n\t\tthrow new Error(`Unsupported platform: ${plat}/${architecture}`);\n\t}\n\n\t// Create tools directory\n\tmkdirSync(TOOLS_DIR, { recursive: true });\n\n\tconst downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`;\n\tconst archivePath = join(TOOLS_DIR, assetName);\n\tconst binaryExt = plat === \"win32\" ? \".exe\" : \"\";\n\tconst binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);\n\n\t// Download\n\tawait downloadFile(downloadUrl, archivePath);\n\n\t// Extract into a unique temp directory. fd and rg downloads can run concurrently\n\t// during startup, so sharing a fixed directory causes races.\n\tconst extractDir = join(\n\t\tTOOLS_DIR,\n\t\t`extract_tmp_${config.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,\n\t);\n\tmkdirSync(extractDir, { recursive: true });\n\n\ttry {\n\t\tif (assetName.endsWith(\".tar.gz\")) {\n\t\t\textractTarGzArchive(archivePath, extractDir, assetName);\n\t\t} else if (assetName.endsWith(\".zip\")) {\n\t\t\textractZipArchive(archivePath, extractDir, assetName);\n\t\t} else {\n\t\t\tthrow new Error(`Unsupported archive format: ${assetName}`);\n\t\t}\n\n\t\t// Find the binary in extracted files. Some archives contain files directly\n\t\t// at root, others nest under a versioned subdirectory.\n\t\tconst binaryFileName = config.binaryName + binaryExt;\n\t\tconst extractedDir = join(extractDir, assetName.replace(/\\.(tar\\.gz|zip)$/, \"\"));\n\t\tconst extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)];\n\t\tlet extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate));\n\n\t\tif (!extractedBinary) {\n\t\t\textractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined;\n\t\t}\n\n\t\tif (extractedBinary) {\n\t\t\trenameSync(extractedBinary, binaryPath);\n\t\t} else {\n\t\t\tthrow new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);\n\t\t}\n\n\t\t// Make executable (Unix only)\n\t\tif (plat !== \"win32\") {\n\t\t\tchmodSync(binaryPath, 0o755);\n\t\t}\n\t} finally {\n\t\t// Cleanup\n\t\trmSync(archivePath, { force: true });\n\t\trmSync(extractDir, { recursive: true, force: true });\n\t}\n\n\treturn binaryPath;\n}\n\n// Termux package names for tools\nconst TERMUX_PACKAGES: Record<string, string> = {\n\tfd: \"fd\",\n\trg: \"ripgrep\",\n};\n\nexport interface ToolStatus {\n\ttype: \"info\" | \"warning\";\n\tmessage: string;\n}\n\n/**\n * Ensure a tool is available, downloading if necessary.\n * Reports progress through `onStatus`; status messages are otherwise silent.\n * Returns the tool path, or undefined if unavailable.\n */\nexport async function ensureTool(\n\ttool: \"fd\" | \"rg\",\n\tonStatus?: (status: ToolStatus) => void,\n): Promise<string | undefined> {\n\tconst existingPath = getToolPath(tool);\n\tif (existingPath) {\n\t\treturn existingPath;\n\t}\n\n\tconst config = TOOLS[tool];\n\tif (!config) return undefined;\n\n\tif (isOfflineModeEnabled()) {\n\t\tonStatus?.({ type: \"warning\", message: `${config.name} not found. Offline mode enabled, skipping download.` });\n\t\treturn undefined;\n\t}\n\n\t// On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility.\n\t// Users must install via pkg.\n\tif (platform() === \"android\") {\n\t\tconst pkgName = TERMUX_PACKAGES[tool] ?? tool;\n\t\tonStatus?.({ type: \"warning\", message: `${config.name} not found. Install with: pkg install ${pkgName}` });\n\t\treturn undefined;\n\t}\n\n\t// Tool not found - download it\n\tonStatus?.({ type: \"info\", message: `${config.name} not found. Downloading...` });\n\n\ttry {\n\t\tconst path = await downloadTool(tool);\n\t\tonStatus?.({ type: \"info\", message: `${config.name} installed to ${path}` });\n\t\treturn path;\n\t} catch (e) {\n\t\tonStatus?.({\n\t\t\ttype: \"warning\",\n\t\t\tmessage: `Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`,\n\t\t});\n\t\treturn undefined;\n\t}\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  # Compaction & Branch Summarization
2
2
 
3
- LLMs have limited context windows. When conversations grow too long, pi uses compaction to summarize older content while preserving recent work. This page covers both auto-compaction and branch summarization.
3
+ LLMs have limited context windows. When conversations grow too long, Pi uses compaction to summarize older content while preserving recent work. This page covers both auto-compaction and branch summarization.
4
4
 
5
5
  **Source files** ([pi-mono](https://github.com/earendil-works/pi-mono)):
6
6
  - [`packages/coding-agent/src/core/compaction/compaction.ts`](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/compaction/compaction.ts) - Auto-compaction logic
@@ -42,13 +42,13 @@ You can also trigger manually with `/compact [instructions]`, where optional ins
42
42
  2. **Extract messages**: Collect messages from the previous kept boundary (or session start) up to the cut point
43
43
  3. **Generate summary**: Call LLM to summarize with structured format, passing the previous summary as iterative context when present
44
44
  4. **Append entry**: Save `CompactionEntry` with summary and `firstKeptEntryId`
45
- 5. **Reload**: Session reloads, using summary + messages from `firstKeptEntryId` onwards
45
+ 5. **Rebuilds context**: Session rebuilds the context for the next request, using summary + messages from `firstKeptEntryId` onwards
46
46
 
47
47
  ```
48
48
  Before compaction:
49
49
 
50
50
  entry: 0 1 2 3 4 5 6 7 8 9
51
- ┌─────┬─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┐
51
+ ┌─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬─────┐
52
52
  │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│
53
53
  └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┘
54
54
  └────────┬───────┘ └──────────────┬──────────────┘
@@ -59,7 +59,7 @@ Before compaction:
59
59
  After compaction (new entry appended):
60
60
 
61
61
  entry: 0 1 2 3 4 5 6 7 8 9 10
62
- ┌─────┬─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬─────┐
62
+ ┌─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬─────┬─────┐
63
63
  │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│ cmp │
64
64
  └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┴─────┘
65
65
  └──────────┬──────┘ └──────────────────────┬───────────────────┘
@@ -102,7 +102,7 @@ Split turn (one huge turn exceeds budget):
102
102
  turnPrefixMessages = [usr, ass, tool, ass, tool, tool]
103
103
  ```
104
104
 
105
- For split turns, pi generates two summaries and merges them:
105
+ For split turns, Pi generates two summaries and merges them:
106
106
  1. **History summary**: Previous context (if any)
107
107
  2. **Turn prefix summary**: The early part of the split turn
108
108
 
@@ -149,7 +149,7 @@ See [`prepareCompaction()`](https://github.com/earendil-works/pi-mono/blob/main/
149
149
 
150
150
  ### When It Triggers
151
151
 
152
- When you use `/tree` to navigate to a different branch, pi offers to summarize the work you're leaving. This injects context from the left branch into the new branch.
152
+ When you use `/tree` to navigate to a different branch, Pi offers to summarize the work you're leaving. This injects context from the left branch into the new branch.
153
153
 
154
154
  ### How It Works
155
155
 
@@ -346,6 +346,21 @@ pi.on("session_before_compact", async (event, ctx) => {
346
346
 
347
347
  See [custom-compaction.ts](../examples/extensions/custom-compaction.ts) for a complete example using a different model.
348
348
 
349
+ ### session_compact_failed
350
+
351
+ Fired when manual or automatic compaction fails or is aborted. This is useful for telemetry extensions that need to pair `session_before_compact` attempts with terminal outcomes.
352
+
353
+ ```typescript
354
+ pi.on("session_compact_failed", async (event, ctx) => {
355
+ const { reason, errorMessage, aborted, willRetry, fromExtension } = event;
356
+ // reason - "manual" (/compact), "threshold", or "overflow"
357
+ // errorMessage - present for non-abort failures
358
+ // aborted - true for cancelled/aborted compactions
359
+ // willRetry - whether the aborted turn would have retried after compaction
360
+ // fromExtension - whether extension-provided compaction content was being used
361
+ });
362
+ ```
363
+
349
364
  ### session_before_tree
350
365
 
351
366
  Fired before `/tree` navigation. Always fires regardless of whether user chose to summarize. Can cancel navigation or provide custom summary.
@@ -227,7 +227,7 @@ The `api` field determines which streaming implementation is used:
227
227
  | `openai-responses` | OpenAI Responses API |
228
228
  | `azure-openai-responses` | Azure OpenAI Responses API |
229
229
  | `openai-codex-responses` | OpenAI Codex Responses API |
230
- | `mistral-conversations` | Mistral SDK Conversations/Chat streaming |
230
+ | `mistral-conversations` | Native Mistral Chat Completions streaming |
231
231
  | `google-generative-ai` | Google Generative AI API |
232
232
  | `google-vertex` | Google Vertex AI API |
233
233
  | `bedrock-converse-stream` | Amazon Bedrock Converse API |
@@ -752,8 +752,10 @@ interface ProviderModelConfig {
752
752
  requiresThinkingAsText?: boolean;
753
753
  requiresReasoningContentOnAssistantMessages?: boolean;
754
754
  thinkingFormat?: "openai" | "openrouter" | "deepseek" | "together" | "baseten" | "zai" | "qwen" | "chat-template" | "qwen-chat-template" | "string-thinking" | "ant-ling";
755
- chatTemplateKwargs?: Record<string, string | number | boolean | null | { "$var": "thinking.enabled" | "thinking.effort"; omitWhenOff?: boolean }>;
756
- chatTemplateArgs?: Record<string, string | number | boolean | null | { "$var": "thinking.enabled" | "thinking.effort"; omitWhenOff?: boolean }>;
755
+ chatTemplateKwargs?: Record<string, string | number | boolean | null | { "$var": "thinking.enabled" | "thinking.effort" | "thinking.budget"; omitWhenOff?: boolean }>;
756
+ chatTemplateArgs?: Record<string, string | number | boolean | null | { "$var": "thinking.enabled" | "thinking.effort" | "thinking.budget"; omitWhenOff?: boolean }>;
757
+ thinkingTokenBudgetField?: "thinking_token_budget" | "thinking_budget" | "thinking_budget_tokens";
758
+ supportsThinkingTokenBudget?: boolean;
757
759
  cacheControlFormat?: "anthropic";
758
760
  sessionAffinityFormat?: "openai" | "openai-nosession" | "openrouter";
759
761
  sendSessionAffinityHeaders?: boolean;
@@ -771,4 +773,5 @@ interface ProviderModelConfig {
771
773
  ```
772
774
 
773
775
  `openrouter` sends `reasoning: { effort }`. `deepseek` sends `thinking: { type: "enabled" | "disabled" }` and `reasoning_effort` when enabled. `together` sends `reasoning: { enabled }` and also `reasoning_effort` when `supportsReasoningEffort` is enabled. `qwen` is for DashScope-style top-level `enable_thinking`. Use `qwen-chat-template` for local Qwen-compatible servers that read `chat_template_kwargs.enable_thinking` and need `preserve_thinking`. Use `chat-template` for configurable `chat_template_kwargs`, for example DeepSeek V3.x behind vLLM with `chatTemplateKwargs: { "thinking": { "$var": "thinking.enabled" } }`. Use `thinkingFormat: "baseten"` with `chatTemplateArgs` when the provider expects toggle values under `chat_template_args` and optionally supports top-level `reasoning_effort`.
776
+ `thinkingTokenBudgetField` sends a clamped per-level thinking budget as a top-level request field (`thinking_token_budget` on vLLM, `thinking_budget` on Qwen/SGLang, `thinking_budget_tokens` on llama.cpp). `supportsThinkingTokenBudget: true` is an alias for the vLLM field name. Do not combine it with `reasoning_effort` on DashScope Qwen models.
774
777
  `cacheControlFormat: "anthropic"` applies Anthropic-style `cache_control` markers to the system prompt, last tool definition, and last user, assistant, or tool-result text content.
@@ -3,18 +3,23 @@
3
3
  Pi uses environment variables in three ways:
4
4
 
5
5
  - Variables such as `PI_OFFLINE` configure the Pi process.
6
- - Pi sets `PI_CODING_AGENT` so child processes can detect that they run inside Pi.
7
- - Commands run by the LLM-callable bash tool receive `PI_*` variables describing the current session.
6
+ - Pi sets process markers so child processes can identify Pi as the launching agent.
7
+ - Commands run by the LLM-callable shell tools receive `PI_*` variables describing the current session.
8
8
 
9
9
  Provider API-key variables are documented separately in [Providers](providers.md#environment-variables-or-auth-file).
10
10
 
11
11
  ## Process Marker
12
12
 
13
- The CLI and RPC entry points set `PI_CODING_AGENT=true`. Child processes inherit it and can use it to detect that they run inside Pi. It is not session-specific and is not set automatically when Pi is embedded through the SDK.
13
+ The CLI and RPC entry points set two process markers:
14
14
 
15
- ## Bash Tool Session Environment
15
+ - `AI_AGENT=pi` is a generic marker that lets tooling identify Pi as the agent that launched the process.
16
+ - `PI_CODING_AGENT=true` is Pi-specific and lets child processes detect that they run inside Pi.
16
17
 
17
- Commands run by the bash tool receive the current Pi session state:
18
+ Child processes inherit both markers. They are not session-specific and are not set automatically when Pi is embedded through the SDK.
19
+
20
+ ## Shell Tool Session Environment
21
+
22
+ Commands run by the `bash` and `powershell` tools receive the current Pi session state:
18
23
 
19
24
  | Variable | Description |
20
25
  |----------|-------------|
@@ -24,7 +29,7 @@ Commands run by the bash tool receive the current Pi session state:
24
29
  | `PI_MODEL` | Currently selected model ID |
25
30
  | `PI_REASONING_LEVEL` | Current effective reasoning level: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` |
26
31
 
27
- The values are resolved when each command starts. Switching models or changing the reasoning level therefore affects the next bash command without restarting Pi. `PI_PROVIDER` and `PI_MODEL` identify the selected Pi model, not a different upstream model that a router may choose internally.
32
+ The values are resolved when each command starts. Switching models or changing the reasoning level therefore affects the next shell command without restarting Pi. `PI_PROVIDER` and `PI_MODEL` identify the selected Pi model, not a different upstream model that a router may choose internally.
28
33
 
29
34
  When asked which model or provider is running, inspect these variables instead of inferring the answer from the system prompt:
30
35
 
@@ -41,11 +46,11 @@ if [ -n "$PI_SESSION_FILE" ]; then
41
46
  fi
42
47
  ```
43
48
 
44
- These variables are injected into the LLM-callable bash tool. They are not injected into user-entered `!` or `!!` commands.
49
+ These variables are injected into the LLM-callable `bash` and `powershell` tools. They are not injected into user-entered `!` or `!!` commands.
45
50
 
46
- ### Custom Bash Tools
51
+ ### Custom Shell Tools
47
52
 
48
- Bash tools created with `createBashTool()` expose the session environment by default when registered with Pi. Injection happens before `spawnHook`, so a hook receives the variables in `ctx.env`:
53
+ Tools created with `createBashTool()` or `createPowerShellTool()` expose the session environment by default when registered with Pi. Injection happens before `spawnHook`, so a hook receives the variables in `ctx.env`:
49
54
 
50
55
  ```typescript
51
56
  const bashTool = createBashTool(cwd, {
@@ -59,7 +64,7 @@ const bashTool = createBashTool(cwd, {
59
64
  Disable session metadata independently of the spawn hook:
60
65
 
61
66
  ```typescript
62
- const bashTool = createBashTool(cwd, {
67
+ const powershellTool = createPowerShellTool(cwd, {
63
68
  exposeSessionEnvironment: false,
64
69
  spawnHook: (ctx) => ctx,
65
70
  });
@@ -82,6 +87,7 @@ These variables are read by Pi itself:
82
87
  | `PI_CACHE_RETENTION` | Set to `long` for extended provider prompt caching where supported |
83
88
  | `PI_SHARE_VIEWER_URL` | Override the base URL used by `/share` |
84
89
  | `PI_HARDWARE_CURSOR` | Set to `1` to show the hardware cursor; see [Terminal setup](terminal-setup.md) |
90
+ | `PI_TUI_ESC_TIMEOUT` | How long to wait after a lone ESC before treating it as Escape, in milliseconds; defaults to `100` over SSH and `10` otherwise. Increase if Alt-key input is misread as Escape |
85
91
  | `VISUAL`, `EDITOR` | External editor fallback when `externalEditor` is unset |
86
92
  | `HTTP_PROXY`, `HTTPS_PROXY` | Proxy outbound HTTP requests |
87
93
 
@@ -330,7 +330,8 @@ user sends another prompt ◄─────────────────
330
330
 
331
331
  /compact or auto-compaction
332
332
  ├─► session_before_compact (can cancel or customize)
333
- └─► session_compact
333
+ ├─► session_compact (success)
334
+ └─► session_compact_failed (failure or abort)
334
335
 
335
336
  /tree navigation
336
337
  ├─► session_before_tree (can cancel or customize)
@@ -448,7 +449,7 @@ pi.on("session_before_fork", async (event, ctx) => {
448
449
  After a successful fork or clone, pi emits `session_shutdown` for the old extension instance, reloads and rebinds extensions for the new session, then emits `session_start` with `reason: "fork"` and `previousSessionFile`.
449
450
  Do cleanup work in `session_shutdown`, then reestablish any in-memory state in `session_start`.
450
451
 
451
- #### session_before_compact / session_compact
452
+ #### session_before_compact / session_compact / session_compact_failed
452
453
 
453
454
  Fired on compaction. See [compaction.md](compaction.md) for details.
454
455
 
@@ -479,6 +480,14 @@ pi.on("session_compact", async (event, ctx) => {
479
480
  // event.reason - "manual" (/compact), "threshold", or "overflow"
480
481
  // event.willRetry - whether the aborted turn is retried after compaction (overflow recovery)
481
482
  });
483
+
484
+ pi.on("session_compact_failed", async (event, ctx) => {
485
+ // event.reason - "manual" (/compact), "threshold", or "overflow"
486
+ // event.errorMessage - present for non-abort failures
487
+ // event.aborted - true for cancelled/aborted compactions
488
+ // event.willRetry - whether the aborted turn would have retried after compaction
489
+ // event.fromExtension - whether extension-provided compaction content was being used
490
+ });
482
491
  ```
483
492
 
484
493
  #### session_before_tree / session_tree
@@ -1426,12 +1435,16 @@ pi.sendUserMessage([
1426
1435
  // During streaming - must specify delivery mode
1427
1436
  pi.sendUserMessage("Focus on error handling", { deliverAs: "steer" });
1428
1437
  pi.sendUserMessage("And then summarize", { deliverAs: "followUp" });
1438
+
1439
+ // Opt in to extension command dispatch and skill/prompt template expansion
1440
+ pi.sendUserMessage("/review src/index.ts", { expandPromptTemplates: true });
1429
1441
  ```
1430
1442
 
1431
1443
  **Options:**
1432
1444
  - `deliverAs` - Required when agent is streaming:
1433
1445
  - `"steer"` - Queues the message for delivery after the current assistant turn finishes executing its tool calls
1434
1446
  - `"followUp"` - Waits for agent to finish all tools
1447
+ - `expandPromptTemplates` - Dispatch extension commands and expand skill commands and prompt templates. Defaults to `false`.
1435
1448
 
1436
1449
  When not streaming, the message is sent immediately and triggers a new turn. When streaming without `deliverAs`, throws an error.
1437
1450
 
@@ -2046,7 +2059,7 @@ pi.registerTool({
2046
2059
 
2047
2060
  ### Overriding Built-in Tools
2048
2061
 
2049
- 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.
2062
+ Extensions can override built-in tools (`read`, `bash`, `powershell`, `edit`, `write`, `grep`, `find`, `ls`) by registering a tool with the same name. Interactive mode displays a warning when this happens.
2050
2063
 
2051
2064
  ```bash
2052
2065
  # Extension's read tool replaces built-in read
@@ -2070,6 +2083,7 @@ See [examples/extensions/tool-override.ts](../examples/extensions/tool-override.
2070
2083
  Built-in tool implementations:
2071
2084
  - [read.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/read.ts) - `ReadToolDetails`
2072
2085
  - [bash.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/bash.ts) - `BashToolDetails`
2086
+ - [powershell.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/powershell.ts) - `PowerShellToolDetails`
2073
2087
  - [edit.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/edit.ts)
2074
2088
  - [write.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/write.ts)
2075
2089
  - [grep.ts](https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/src/core/tools/grep.ts) - `GrepToolDetails`
@@ -2105,11 +2119,11 @@ pi.registerTool({
2105
2119
  });
2106
2120
  ```
2107
2121
 
2108
- **Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `LsOperations`, `GrepOperations`, `FindOperations`
2122
+ **Operations interfaces:** `ReadOperations`, `WriteOperations`, `EditOperations`, `BashOperations`, `PowerShellOperations`, `LsOperations`, `GrepOperations`, `FindOperations`
2109
2123
 
2110
2124
  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.
2111
2125
 
2112
- The bash tool also supports a spawn hook to adjust the command, cwd, or env before execution:
2126
+ The `bash` and `powershell` tools also support a spawn hook to adjust the command, cwd, or env before execution:
2113
2127
 
2114
2128
  ```typescript
2115
2129
  import { createBashTool } from "@earendil-works/pi-coding-agent";
@@ -2123,7 +2137,7 @@ const bashTool = createBashTool(cwd, {
2123
2137
  });
2124
2138
  ```
2125
2139
 
2126
- `createBashTool()` exposes the current session to commands through `PI_SESSION_ID`, `PI_SESSION_FILE`, `PI_PROVIDER`, `PI_MODEL`, and `PI_REASONING_LEVEL`. Injection happens before `spawnHook`, so hooks receive these values in `env` and preserve them when they spread the existing environment as above. Set `exposeSessionEnvironment: false` to disable them:
2140
+ `createBashTool()` and `createPowerShellTool()` expose the current session to commands through `PI_SESSION_ID`, `PI_SESSION_FILE`, `PI_PROVIDER`, `PI_MODEL`, and `PI_REASONING_LEVEL`. Injection happens before `spawnHook`, so hooks receive these values in `env` and preserve them when they spread the existing environment as above. Set `exposeSessionEnvironment: false` to disable them:
2127
2141
 
2128
2142
  ```typescript
2129
2143
  const bashTool = createBashTool(cwd, {
@@ -2131,7 +2145,7 @@ const bashTool = createBashTool(cwd, {
2131
2145
  });
2132
2146
  ```
2133
2147
 
2134
- See [Bash tool session environment](environment-variables.md#bash-tool-session-environment) for variable semantics. See [examples/extensions/ssh.ts](../examples/extensions/ssh.ts) for a complete SSH example with `--ssh` flag.
2148
+ See [Shell tool session environment](environment-variables.md#shell-tool-session-environment) for variable semantics. See [examples/extensions/ssh.ts](../examples/extensions/ssh.ts) for a complete SSH example with `--ssh` flag.
2135
2149
 
2136
2150
  ### Output Truncation
2137
2151
 
package/docs/json.md CHANGED
@@ -15,11 +15,16 @@ except that streaming message updates omit cumulative snapshots:
15
15
  ```typescript
16
16
  type WithoutPartial<T> = T extends { partial: unknown } ? Omit<T, "partial"> : T;
17
17
 
18
+ type JsonAssistantMessageEvent<T> = T extends { type: "toolcall_start"; partial: unknown }
19
+ ? WithoutPartial<T> & { id: string; toolName: string }
20
+ : WithoutPartial<T>;
21
+
18
22
  type JsonAgentSessionEvent =
19
23
  | Exclude<AgentSessionEvent, { type: "message_update" }>
20
24
  | {
21
25
  type: "message_update";
22
- assistantMessageEvent: WithoutPartial<AssistantMessageEvent>;
26
+ usage: Usage;
27
+ assistantMessageEvent: JsonAssistantMessageEvent<AssistantMessageEvent>;
23
28
  };
24
29
  ```
25
30
 
@@ -73,16 +78,18 @@ Followed by events as they occur:
73
78
  {"type":"agent_start"}
74
79
  {"type":"turn_start"}
75
80
  {"type":"message_start","message":{"role":"assistant","content":[],...}}
76
- {"type":"message_update","assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"Hello"}}
81
+ {"type":"message_update","usage":{...},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"Hello"}}
77
82
  {"type":"message_end","message":{...}}
78
83
  {"type":"turn_end","message":{...},"toolResults":[]}
79
84
  {"type":"agent_end","messages":[...]}
80
85
  ```
81
86
 
82
87
  `message_update` records are delta-only. They omit both the cumulative `message` field and
83
- `assistantMessageEvent.partial` to keep stream size linear. Use `contentIndex` and `delta`
84
- to assemble live text, thinking, or tool-call arguments if needed. `message_end` contains
85
- the final authoritative message.
88
+ `assistantMessageEvent.partial` to keep stream size linear. The top-level `usage` field contains
89
+ the latest cumulative provider-reported usage and may remain zero when a provider only reports
90
+ usage at completion. Use `contentIndex` and `delta` to assemble live text, thinking, or tool-call
91
+ arguments if needed. A `toolcall_start` event also includes the constant-sized `id` and `toolName`
92
+ fields. `message_end` contains the final authoritative message.
86
93
 
87
94
  ## Example
88
95
 
@@ -70,7 +70,7 @@ The dedicated history actions always change history entries, regardless of the c
70
70
  |--------|---------|-------------|
71
71
  | `tui.editor.yank` | `ctrl+y` | Paste most recently deleted text |
72
72
  | `tui.editor.yankPop` | `alt+y` | Cycle through deleted text after yank |
73
- | `tui.editor.undo` | `ctrl+-` | Undo last edit |
73
+ | `tui.editor.undo` | `ctrl+-` (`ctrl+z` on Windows; `alt+z` on WSL) | Undo last edit |
74
74
 
75
75
  ### TUI Clipboard and Selection
76
76
 
@@ -86,7 +86,7 @@ The dedicated history actions always change history entries, regardless of the c
86
86
 
87
87
  ### TUI Fullscreen Viewport
88
88
 
89
- These actions apply when interactive mode uses `--tui-mode fullscreen` and target the primary transcript scroll region. Two-finger trackpad and mouse-wheel input scroll the region under the pointer, falling back to the transcript over the fixed editor/status/footer dock. Clicking an OSC 8 hyperlink opens it in the default handler. Dragging with the primary mouse button selects text and copies it to the clipboard; holding at the transcript's top or bottom edge auto-scrolls into off-screen content.
89
+ These actions apply when interactive mode uses `--tui-mode fullscreen` and target the primary transcript scroll region. Two-finger trackpad and mouse-wheel input scroll the region under the pointer, falling back to the transcript over the fixed editor/status/footer dock. Clicking an OSC 8 hyperlink opens it in the default handler. Dragging with the primary mouse button selects text and copies it to the clipboard; holding at the transcript's top or bottom edge auto-scrolls into off-screen content. See [Terminal setup](terminal-setup.md) for terminal-specific mouse and trackpad behavior.
90
90
 
91
91
  Fullscreen transcript bindings take precedence over editor bindings. The default unmodified navigation keys therefore control the transcript in fullscreen mode, while their `ctrl` variants continue to control the editor. Outside fullscreen mode, both variants control the editor.
92
92
 
@@ -97,7 +97,7 @@ Fullscreen transcript bindings take precedence over editor bindings. The default
97
97
  | `pageUp`, `pageDown` | Editor | Transcript |
98
98
  | `ctrl+pageUp`, `ctrl+pageDown` | Editor | Editor |
99
99
 
100
- This routing remains configurable through the ordinary action bindings. For example, `"tui.altScreen.pageUp": "ctrl+pageUp"` makes `pageUp` control the editor and `ctrl+pageUp` control the transcript in fullscreen mode. Bind `tui.altScreen.halfPageUp` and `tui.altScreen.halfPageDown` for smaller transcript steps while keeping the full-page bindings. Setting `"tui.altScreen.pageUp": []` disables that transcript shortcut entirely. User bindings replace the defaults for that action.
100
+ This routing remains configurable through the ordinary action bindings. For example, `"tui.altScreen.pageUp": "ctrl+pageUp"` makes `pageUp` control the editor and `ctrl+pageUp` control the transcript in fullscreen mode. Bind `tui.altScreen.halfPageUp` and `tui.altScreen.halfPageDown` for half-page steps, or bind `tui.altScreen.lineUp` and `tui.altScreen.lineDown` for single-line steps. Setting `"tui.altScreen.pageUp": []` disables that transcript shortcut entirely. User bindings replace the defaults for that action.
101
101
 
102
102
  | Keybinding id | Default | Description |
103
103
  |--------|---------|-------------|
@@ -105,8 +105,14 @@ This routing remains configurable through the ordinary action bindings. For exam
105
105
  | `tui.altScreen.pageDown` | `pageDown` | Scroll the transcript down by one page |
106
106
  | `tui.altScreen.halfPageUp` | *(none)* | Scroll the transcript up by half a page |
107
107
  | `tui.altScreen.halfPageDown` | *(none)* | Scroll the transcript down by half a page |
108
- | `tui.altScreen.previousPrompt` | `ctrl+shift+up` | Jump to the previous marked message |
109
- | `tui.altScreen.nextPrompt` | `ctrl+shift+down` | Jump to the next marked message |
108
+ | `tui.altScreen.lineUp` | *(none)* | Scroll the transcript up by one line |
109
+ | `tui.altScreen.lineDown` | *(none)* | Scroll the transcript down by one line |
110
+ | `tui.altScreen.previousPrompt` | `ctrl+shift+up`, `ctrl+up` (`ctrl+up` only on Windows and WSL) | Jump to the previous marked message |
111
+ | `tui.altScreen.nextPrompt` | `ctrl+shift+down`, `ctrl+down` (`ctrl+down` only on Windows and WSL) | Jump to the next marked message |
112
+ | `tui.altScreen.search` | `ctrl+shift+f` (`ctrl+f` on Windows and WSL) | Search the rendered transcript |
113
+ | `tui.altScreen.searchNext` | `enter`, `ctrl+g` | Select the next search match while searching |
114
+ | `tui.altScreen.searchPrevious` | `shift+enter`, `ctrl+shift+g` | Select the previous search match while searching |
115
+ | `tui.altScreen.searchClose` | `escape` | Close transcript search |
110
116
  | `tui.altScreen.top` | `home` | Scroll to the beginning of the transcript |
111
117
  | `tui.altScreen.bottom` | `end` | Scroll to the transcript end and follow new output |
112
118
 
@@ -119,7 +125,7 @@ This routing remains configurable through the ordinary action bindings. For exam
119
125
  | `app.exit` | `ctrl+d` | Exit (when editor empty) |
120
126
  | `app.suspend` | `ctrl+z` (none on Windows) | Suspend to background |
121
127
  | `app.editor.external` | `ctrl+g` | Open in external editor (`externalEditor`, `$VISUAL`, `$EDITOR`, Notepad on Windows, or `nano` elsewhere) |
122
- | `app.clipboard.pasteImage` | `ctrl+v` (`alt+v` on Windows) | Paste image or text from clipboard |
128
+ | `app.clipboard.pasteImage` | `ctrl+v` (`alt+v` on Windows and WSL) | Paste image or text from clipboard |
123
129
 
124
130
  ### Sessions
125
131
 
@@ -142,7 +148,7 @@ This routing remains configurable through the ordinary action bindings. For exam
142
148
  |--------|---------|-------------|
143
149
  | `app.model.select` | `ctrl+l` | Open model selector |
144
150
  | `app.model.cycleForward` | `ctrl+p` | Cycle to next model |
145
- | `app.model.cycleBackward` | `shift+ctrl+p` | Cycle to previous model |
151
+ | `app.model.cycleBackward` | `shift+ctrl+p` (`alt+p` on Windows and WSL) | Cycle to previous model |
146
152
  | `app.thinking.cycle` | `shift+tab` | Cycle thinking level |
147
153
  | `app.thinking.toggle` | `ctrl+t` | Collapse or expand thinking blocks |
148
154
 
@@ -152,8 +158,8 @@ This routing remains configurable through the ordinary action bindings. For exam
152
158
  |--------|---------|-------------|
153
159
  | `app.tools.expand` | `ctrl+o` | Collapse or expand tool output |
154
160
  | `app.message.copy` | `ctrl+x` | Copy the last assistant message, or the selected message in `/tree` |
155
- | `app.message.followUp` | `alt+enter` | Queue follow-up message |
156
- | `app.message.dequeue` | `alt+up` | Restore queued messages to editor |
161
+ | `app.message.followUp` | `alt+enter` (`ctrl+q` on Windows and WSL) | Queue follow-up message |
162
+ | `app.message.dequeue` | `alt+up` (`alt+q` on Windows and WSL) | Restore queued messages to editor |
157
163
 
158
164
  ### Tree Navigation
159
165
 
package/docs/llama-cpp.md CHANGED
@@ -53,6 +53,8 @@ Start Pi and configure the provider:
53
53
 
54
54
  Enter the router URL and optional API key. The default URL is `http://127.0.0.1:8080`.
55
55
 
56
+ If you start the router with `--no-models-autoload`, `/login llama.cpp` only stores the connection. Run `/llama` to load a model, then `/model` to select the loaded model for the current session.
57
+
56
58
  Environment variables can configure the same values without `/login`:
57
59
 
58
60
  ```bash
package/docs/models.md CHANGED
@@ -254,6 +254,8 @@ Current behavior:
254
254
 
255
255
  Only OpenAI-compatible APIs apply it (`openai-completions`, `openai-responses`, `azure-openai-responses`); other APIs ignore it. Keys override pi's named request fields (for example a `temperature` key here beats the request-level temperature), so prefer it as the single source of sampling truth for a model. In `modelOverrides`, `samplingParams` merges per key with the base model's value.
256
256
 
257
+ A constant thinking-token cap can go here too, but it will not follow `thinkingBudgets` or leave room for the answer. Prefer `compat.thinkingTokenBudgetField` (or the `supportsThinkingTokenBudget` alias) for that.
258
+
257
259
  ### Thinking Level Map
258
260
 
259
261
  Use `thinkingLevelMap` on a model to describe model-specific thinking controls. Keys are pi thinking levels: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. Maps may contain holes; for example, a model can expose `high` and `max` without exposing `xhigh`.
@@ -467,8 +469,10 @@ For providers with partial OpenAI compatibility, use the `compat` field.
467
469
  | `requiresThinkingAsText` | Convert thinking blocks to plain text |
468
470
  | `requiresReasoningContentOnAssistantMessages` | Include empty `reasoning_content` on all replayed assistant messages when reasoning is enabled |
469
471
  | `thinkingFormat` | Use `reasoning_effort`, `openrouter`, `deepseek`, `together`, `baseten`, `zai`, `qwen`, `chat-template`, or `qwen-chat-template` thinking parameters |
470
- | `chatTemplateKwargs` | `chat_template_kwargs` values for `thinkingFormat: "chat-template"`; use `{ "$var": "thinking.enabled" }` or `{ "$var": "thinking.effort" }` for pi-controlled thinking values |
471
- | `chatTemplateArgs` | `chat_template_args` values for `thinkingFormat: "baseten"`; use `{ "$var": "thinking.enabled" }` or `{ "$var": "thinking.effort" }` for pi-controlled thinking values |
472
+ | `chatTemplateKwargs` | `chat_template_kwargs` values for `thinkingFormat: "chat-template"`; use `{ "$var": "thinking.enabled" }`, `{ "$var": "thinking.effort" }`, or `{ "$var": "thinking.budget" }` for pi-controlled thinking values |
473
+ | `chatTemplateArgs` | `chat_template_args` values for `thinkingFormat: "baseten"`; use `{ "$var": "thinking.enabled" }`, `{ "$var": "thinking.effort" }`, or `{ "$var": "thinking.budget" }` for pi-controlled thinking values |
474
+ | `thinkingTokenBudgetField` | Top-level request field used to cap reasoning tokens from `thinkingBudgets`, clamped so at least 1024 tokens remain for the answer. `"thinking_token_budget"` (vLLM), `"thinking_budget"` (Qwen/DashScope/SGLang), `"thinking_budget_tokens"` (llama.cpp). Off by default; not set on the generated catalog. |
475
+ | `supportsThinkingTokenBudget` | Alias for `thinkingTokenBudgetField: "thinking_token_budget"` (vLLM). Prefer `thinkingTokenBudgetField`. Default: `false`. |
472
476
  | `cacheControlFormat` | Use Anthropic-style `cache_control` markers on the system prompt, last tool definition, and last user, assistant, or tool-result text content. Currently only `anthropic` is supported. |
473
477
  | `sendSessionAffinityHeaders` | For `openai-completions`, send session-affinity headers from the session id when caching is enabled. Default: `false`. |
474
478
  | `sessionAffinityFormat` | For `openai-completions` and `openai-responses`, the session-affinity header format: `openai` sends `session_id`/`x-client-request-id` (completions also `x-session-affinity`), `openai-nosession` omits the underscore-containing `session_id` header, `openrouter` sends `x-session-id`. Does not affect the `prompt_cache_key` body param. Default: auto-detected. |
@@ -481,6 +485,8 @@ For providers with partial OpenAI compatibility, use the `compat` field.
481
485
 
482
486
  `openrouter` uses `reasoning: { effort }`. `together` uses `reasoning: { enabled }` and also `reasoning_effort` when `supportsReasoningEffort` is enabled. `qwen` uses top-level `enable_thinking`. Use `qwen-chat-template` for local Qwen-compatible servers that require `chat_template_kwargs.enable_thinking` and `preserve_thinking`. Use `chat-template` for vLLM/Hugging Face chat templates that need configurable `chat_template_kwargs`, such as `chatTemplateKwargs: { "thinking": { "$var": "thinking.enabled" } }` for DeepSeek V3.x templates. Use `thinkingFormat: "baseten"` with `chatTemplateArgs` for providers that expose toggle controls through `chat_template_args` and optionally support top-level `reasoning_effort`.
483
487
 
488
+ `thinkingTokenBudgetField` is independent of `thinkingFormat`. Do not enable it on the generated Qwen catalog: those models already send `reasoning_effort`, and DashScope rejects `thinking_budget` together with `reasoning_effort`.
489
+
484
490
  `cacheControlFormat: "anthropic"` is for OpenAI-compatible providers that expose Anthropic-style prompt caching through `cache_control` markers on text content and tool definitions.
485
491
 
486
492
  Example:
package/docs/packages.md CHANGED
@@ -38,7 +38,7 @@ pi update npm:@foo/bar # update one package
38
38
  pi update --extension npm:@foo/bar
39
39
  ```
40
40
 
41
- These commands manage pi packages and `pi update` can update the pi CLI installation. To uninstall pi itself, see [Quickstart](quickstart.md#uninstall).
41
+ These commands manage pi packages and `pi update` can update the pi CLI installation. For experimental installer-managed installations, `pi update` installs the exact checked version into a staged, lockfile-backed release and activates it only after verification, leaving the current release intact if the update fails. Managed installations do not support `--force`; rerun the installer to repair one. To uninstall pi itself, see [Quickstart](quickstart.md#uninstall).
42
42
 
43
43
  By default, `install` and `remove` write to user settings (`~/.pi/agent/settings.json`). Use `-l` to write to project settings (`.pi/settings.json`) instead. Project settings can be shared with your team, and pi installs any missing packages automatically on startup after the project is trusted.
44
44
 
@@ -130,7 +130,7 @@ Add a `pi` manifest to `package.json` or use conventional directories. Include t
130
130
  }
131
131
  ```
132
132
 
133
- Paths are relative to the package root. Arrays support glob patterns and `!exclusions`.
133
+ Paths are relative to the package root. Arrays support glob patterns and `!exclusions`. Positive manifest globs discover visible paths in lexical order. List dot-prefixed paths directly. If a glob would need to continue through a symlink, list the symlinked resource root directly.
134
134
 
135
135
  ### Gallery Metadata
136
136