@punch-bot/cli 1.5.0 → 1.5.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 (505) hide show
  1. package/CHANGELOG.md +168 -1
  2. package/README.md +6 -8
  3. package/dist/bundle/chunks/anthropic-messages-WIBS5YKY.js +6 -0
  4. package/dist/bundle/chunks/azure-openai-responses-GP5GDEGO.js +2 -0
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +7 -4
  6. package/dist/bundle/chunks/chunk-35EHANXE.js +2 -0
  7. package/dist/bundle/chunks/chunk-3IMHRFLG.js +6 -0
  8. package/dist/bundle/chunks/chunk-77CRE5SV.js +9 -0
  9. package/dist/bundle/chunks/chunk-CE33JMCE.js +861 -0
  10. package/dist/bundle/chunks/{chunk-MYNHUMKE.js → chunk-CXY7BILM.js} +2 -44
  11. package/dist/bundle/chunks/chunk-EISXNXOQ.js +41 -0
  12. package/dist/bundle/chunks/chunk-ENMVUQHE.js +26 -0
  13. package/dist/bundle/chunks/chunk-FFMDRXC4.js +10 -0
  14. package/dist/bundle/chunks/chunk-GFUN2N5K.js +2 -0
  15. package/dist/bundle/chunks/chunk-HQH636GU.js +361 -0
  16. package/dist/bundle/chunks/chunk-IEBK4HQA.js +2 -0
  17. package/dist/bundle/chunks/chunk-JAJLG57O.js +4 -0
  18. package/dist/bundle/chunks/{chunk-RFVYQ7ZX.js → chunk-LOHGXPCL.js} +2 -2
  19. package/dist/bundle/chunks/{chunk-NO2FNWW3.js → chunk-OV2VGRRS.js} +1 -1
  20. package/dist/bundle/chunks/chunk-P7FPUEYA.js +2 -0
  21. package/dist/bundle/chunks/chunk-PDENR63J.js +16 -0
  22. package/dist/bundle/chunks/chunk-RHOWRSGK.js +2 -0
  23. package/dist/bundle/chunks/{chunk-BRECMFDT.js → chunk-UZ3LUZDC.js} +1 -1
  24. package/dist/bundle/chunks/chunk-WN2D4UD4.js +2 -0
  25. package/dist/bundle/chunks/chunk-X4T5TGM4.js +82 -0
  26. package/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
  27. package/dist/bundle/chunks/cli-OQNR6ESL.js +53 -0
  28. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-FDCKYGTP.js → cloudflare-workers-ai-system-one-36EDUVVN.js} +1 -1
  29. package/dist/bundle/chunks/codemode-worker.js +2 -0
  30. package/dist/bundle/chunks/{execute-HXULRBCI.js → execute-EHT55MW7.js} +5 -3
  31. package/dist/bundle/chunks/github-copilot.js +1 -1
  32. package/dist/bundle/chunks/{google-generative-ai-2ESDEFYR.js → google-generative-ai-KA6FZCHM.js} +1 -1
  33. package/dist/bundle/chunks/{google-vertex-YERBWL2T.js → google-vertex-DXKQ4IYR.js} +1 -1
  34. package/dist/bundle/chunks/image-resize-worker.js +1 -1
  35. package/dist/bundle/chunks/kimi-coding.js +1 -1
  36. package/dist/bundle/chunks/{llama-cpp-classify-M4KMJHPS.js → llama-cpp-classify-676UCBOD.js} +1 -1
  37. package/dist/bundle/chunks/meta.js +1 -1
  38. package/dist/bundle/chunks/mistral-conversations-PJ56UMXO.js +5 -0
  39. package/dist/bundle/chunks/openai-codex-responses-DWVG7MAQ.js +10 -0
  40. package/dist/bundle/chunks/openai-completions-OKI6KBNP.js +7 -0
  41. package/dist/bundle/chunks/{openai-decisions-PPJMQ3W4.js → openai-decisions-SO57QA6O.js} +1 -1
  42. package/dist/bundle/chunks/openai-responses-3HV234HB.js +4 -0
  43. package/dist/bundle/chunks/{openrouter-images-WWPCCAPX.js → openrouter-images-5X6D7HFS.js} +1 -1
  44. package/dist/bundle/chunks/pi-messages-BS5Z34RE.js +8 -0
  45. package/dist/bundle/chunks/radius.js +1 -1
  46. package/dist/bundle/chunks/{runtime-R5GXO4CV.js → runtime-74PFKASL.js} +1 -1
  47. package/dist/bundle/chunks/{typesafe-system-one-NLWRPIRL.js → typesafe-system-one-IPNULX2M.js} +1 -1
  48. package/dist/bundle/chunks/virtual-modules-2Y422I6U.js +2 -0
  49. package/dist/bundle/cli-runtime.js +1 -1
  50. package/dist/bundle/index.js +1 -1
  51. package/dist/bundle/rpc-entry.js +1 -1
  52. package/dist/cli/args.d.ts +0 -1
  53. package/dist/cli/args.d.ts.map +1 -1
  54. package/dist/cli/args.js +8 -12
  55. package/dist/cli/args.js.map +1 -1
  56. package/dist/cli/auth-command.d.ts.map +1 -1
  57. package/dist/cli/auth-command.js +26 -2
  58. package/dist/cli/auth-command.js.map +1 -1
  59. package/dist/cli/auth-login.d.ts +15 -0
  60. package/dist/cli/auth-login.d.ts.map +1 -0
  61. package/dist/cli/auth-login.js +232 -0
  62. package/dist/cli/auth-login.js.map +1 -0
  63. package/dist/cli/auth-logout.d.ts +14 -0
  64. package/dist/cli/auth-logout.d.ts.map +1 -0
  65. package/dist/cli/auth-logout.js +63 -0
  66. package/dist/cli/auth-logout.js.map +1 -0
  67. package/dist/cli/auth-terminal.d.ts +17 -0
  68. package/dist/cli/auth-terminal.d.ts.map +1 -0
  69. package/dist/cli/auth-terminal.js +63 -0
  70. package/dist/cli/auth-terminal.js.map +1 -0
  71. package/dist/cli/project-trust.js +1 -1
  72. package/dist/cli/project-trust.js.map +1 -1
  73. package/dist/config.d.ts +10 -2
  74. package/dist/config.d.ts.map +1 -1
  75. package/dist/config.js +24 -11
  76. package/dist/config.js.map +1 -1
  77. package/dist/core/agent-session-runtime.d.ts +5 -0
  78. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  79. package/dist/core/agent-session-runtime.js +20 -5
  80. package/dist/core/agent-session-runtime.js.map +1 -1
  81. package/dist/core/agent-session.d.ts +31 -15
  82. package/dist/core/agent-session.d.ts.map +1 -1
  83. package/dist/core/agent-session.js +158 -71
  84. package/dist/core/agent-session.js.map +1 -1
  85. package/dist/core/auth-storage.d.ts.map +1 -1
  86. package/dist/core/auth-storage.js +3 -2
  87. package/dist/core/auth-storage.js.map +1 -1
  88. package/dist/core/bash-executor.d.ts.map +1 -1
  89. package/dist/core/bash-executor.js +3 -1
  90. package/dist/core/bash-executor.js.map +1 -1
  91. package/dist/core/cache-warmer.d.ts +4 -37
  92. package/dist/core/cache-warmer.d.ts.map +1 -1
  93. package/dist/core/cache-warmer.js +11 -89
  94. package/dist/core/cache-warmer.js.map +1 -1
  95. package/dist/core/compaction/branch-summarization.d.ts +4 -2
  96. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  97. package/dist/core/compaction/branch-summarization.js +16 -4
  98. package/dist/core/compaction/branch-summarization.js.map +1 -1
  99. package/dist/core/compaction/utils.d.ts.map +1 -1
  100. package/dist/core/compaction/utils.js +2 -1
  101. package/dist/core/compaction/utils.js.map +1 -1
  102. package/dist/core/exec.d.ts +9 -1
  103. package/dist/core/exec.d.ts.map +1 -1
  104. package/dist/core/exec.js +104 -60
  105. package/dist/core/exec.js.map +1 -1
  106. package/dist/core/export-html/template.css +9 -0
  107. package/dist/core/export-html/template.js +165 -45
  108. package/dist/core/extensions/index.d.ts +1 -1
  109. package/dist/core/extensions/index.d.ts.map +1 -1
  110. package/dist/core/extensions/index.js.map +1 -1
  111. package/dist/core/extensions/loader.d.ts.map +1 -1
  112. package/dist/core/extensions/loader.js +10 -13
  113. package/dist/core/extensions/loader.js.map +1 -1
  114. package/dist/core/extensions/pi-ai-extension-view.d.ts +19 -0
  115. package/dist/core/extensions/pi-ai-extension-view.d.ts.map +1 -0
  116. package/dist/core/extensions/pi-ai-extension-view.js +22 -0
  117. package/dist/core/extensions/pi-ai-extension-view.js.map +1 -0
  118. package/dist/core/extensions/runner.d.ts +1 -4
  119. package/dist/core/extensions/runner.d.ts.map +1 -1
  120. package/dist/core/extensions/runner.js +0 -14
  121. package/dist/core/extensions/runner.js.map +1 -1
  122. package/dist/core/extensions/types.d.ts +5 -18
  123. package/dist/core/extensions/types.d.ts.map +1 -1
  124. package/dist/core/extensions/types.js +1 -1
  125. package/dist/core/extensions/types.js.map +1 -1
  126. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  127. package/dist/core/extensions/virtual-modules.js +8 -7
  128. package/dist/core/extensions/virtual-modules.js.map +1 -1
  129. package/dist/core/index.d.ts +1 -1
  130. package/dist/core/index.d.ts.map +1 -1
  131. package/dist/core/index.js.map +1 -1
  132. package/dist/core/mcp-servers.d.ts +23 -41
  133. package/dist/core/mcp-servers.d.ts.map +1 -1
  134. package/dist/core/mcp-servers.js +51 -120
  135. package/dist/core/mcp-servers.js.map +1 -1
  136. package/dist/core/model-config.d.ts +1730 -2029
  137. package/dist/core/model-config.d.ts.map +1 -1
  138. package/dist/core/model-config.js +2 -3
  139. package/dist/core/model-config.js.map +1 -1
  140. package/dist/core/model-resolver.d.ts.map +1 -1
  141. package/dist/core/model-resolver.js +36 -29
  142. package/dist/core/model-resolver.js.map +1 -1
  143. package/dist/core/model-runtime.d.ts +5 -0
  144. package/dist/core/model-runtime.d.ts.map +1 -1
  145. package/dist/core/model-runtime.js +11 -4
  146. package/dist/core/model-runtime.js.map +1 -1
  147. package/dist/core/package-manager.d.ts +24 -1
  148. package/dist/core/package-manager.d.ts.map +1 -1
  149. package/dist/core/package-manager.js +210 -51
  150. package/dist/core/package-manager.js.map +1 -1
  151. package/dist/core/pi-ai-schemas.d.ts +167 -0
  152. package/dist/core/pi-ai-schemas.d.ts.map +1 -0
  153. package/dist/core/pi-ai-schemas.js +21 -0
  154. package/dist/core/pi-ai-schemas.js.map +1 -0
  155. package/dist/core/pi-manifest.d.ts +1 -0
  156. package/dist/core/pi-manifest.d.ts.map +1 -1
  157. package/dist/core/pi-manifest.js +4 -0
  158. package/dist/core/pi-manifest.js.map +1 -1
  159. package/dist/core/preferred-providers.d.ts +17 -0
  160. package/dist/core/preferred-providers.d.ts.map +1 -0
  161. package/dist/core/preferred-providers.js +24 -0
  162. package/dist/core/preferred-providers.js.map +1 -0
  163. package/dist/core/project-trust.d.ts +1 -1
  164. package/dist/core/project-trust.d.ts.map +1 -1
  165. package/dist/core/project-trust.js +1 -1
  166. package/dist/core/project-trust.js.map +1 -1
  167. package/dist/core/prompt-templates.d.ts.map +1 -1
  168. package/dist/core/prompt-templates.js +18 -2
  169. package/dist/core/prompt-templates.js.map +1 -1
  170. package/dist/core/provider-composer.d.ts.map +1 -1
  171. package/dist/core/provider-composer.js +3 -1
  172. package/dist/core/provider-composer.js.map +1 -1
  173. package/dist/core/provider-matching.d.ts +11 -0
  174. package/dist/core/provider-matching.d.ts.map +1 -0
  175. package/dist/core/provider-matching.js +14 -0
  176. package/dist/core/provider-matching.js.map +1 -0
  177. package/dist/core/radius-mcp.d.ts +13 -0
  178. package/dist/core/radius-mcp.d.ts.map +1 -0
  179. package/dist/core/radius-mcp.js +29 -0
  180. package/dist/core/radius-mcp.js.map +1 -0
  181. package/dist/core/radius.d.ts +0 -3
  182. package/dist/core/radius.d.ts.map +1 -1
  183. package/dist/core/radius.js +0 -5
  184. package/dist/core/radius.js.map +1 -1
  185. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  186. package/dist/core/remote-catalog-provider.js +2 -0
  187. package/dist/core/remote-catalog-provider.js.map +1 -1
  188. package/dist/core/resource-loader.d.ts +4 -1
  189. package/dist/core/resource-loader.d.ts.map +1 -1
  190. package/dist/core/resource-loader.js +40 -25
  191. package/dist/core/resource-loader.js.map +1 -1
  192. package/dist/core/runtime-credentials.d.ts +8 -0
  193. package/dist/core/runtime-credentials.d.ts.map +1 -1
  194. package/dist/core/runtime-credentials.js +15 -1
  195. package/dist/core/runtime-credentials.js.map +1 -1
  196. package/dist/core/sdk.d.ts.map +1 -1
  197. package/dist/core/sdk.js +3 -1
  198. package/dist/core/sdk.js.map +1 -1
  199. package/dist/core/session-cwd.d.ts +0 -1
  200. package/dist/core/session-cwd.d.ts.map +1 -1
  201. package/dist/core/session-cwd.js +0 -3
  202. package/dist/core/session-cwd.js.map +1 -1
  203. package/dist/core/session-manager.d.ts +7 -0
  204. package/dist/core/session-manager.d.ts.map +1 -1
  205. package/dist/core/session-manager.js +32 -13
  206. package/dist/core/session-manager.js.map +1 -1
  207. package/dist/core/settings-defaults.d.ts +1 -31
  208. package/dist/core/settings-defaults.d.ts.map +1 -1
  209. package/dist/core/settings-defaults.js +1 -31
  210. package/dist/core/settings-defaults.js.map +1 -1
  211. package/dist/core/settings-manager.d.ts +4 -56
  212. package/dist/core/settings-manager.d.ts.map +1 -1
  213. package/dist/core/settings-manager.js +11 -247
  214. package/dist/core/settings-manager.js.map +1 -1
  215. package/dist/core/settings-schema.d.ts +4 -54
  216. package/dist/core/settings-schema.d.ts.map +1 -1
  217. package/dist/core/settings-schema.js +7 -101
  218. package/dist/core/settings-schema.js.map +1 -1
  219. package/dist/core/skills.d.ts.map +1 -1
  220. package/dist/core/skills.js +6 -14
  221. package/dist/core/skills.js.map +1 -1
  222. package/dist/core/slash-commands.d.ts +0 -6
  223. package/dist/core/slash-commands.d.ts.map +1 -1
  224. package/dist/core/slash-commands.js +1 -27
  225. package/dist/core/slash-commands.js.map +1 -1
  226. package/dist/core/source-info.d.ts +9 -0
  227. package/dist/core/source-info.d.ts.map +1 -1
  228. package/dist/core/source-info.js +13 -0
  229. package/dist/core/source-info.js.map +1 -1
  230. package/dist/core/system-prompt.d.ts.map +1 -1
  231. package/dist/core/system-prompt.js +5 -6
  232. package/dist/core/system-prompt.js.map +1 -1
  233. package/dist/core/telemetry.js +1 -1
  234. package/dist/core/telemetry.js.map +1 -1
  235. package/dist/core/theme/theme.d.ts.map +1 -1
  236. package/dist/core/theme/theme.js +5 -1
  237. package/dist/core/theme/theme.js.map +1 -1
  238. package/dist/core/tools/bash.d.ts +2 -2
  239. package/dist/core/tools/bash.d.ts.map +1 -1
  240. package/dist/core/tools/bash.js +35 -5
  241. package/dist/core/tools/bash.js.map +1 -1
  242. package/dist/core/tools/edit-diff.d.ts +23 -14
  243. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  244. package/dist/core/tools/edit-diff.js +182 -41
  245. package/dist/core/tools/edit-diff.js.map +1 -1
  246. package/dist/core/tools/edit.d.ts +3 -3
  247. package/dist/core/tools/edit.d.ts.map +1 -1
  248. package/dist/core/tools/edit.js +10 -11
  249. package/dist/core/tools/edit.js.map +1 -1
  250. package/dist/core/tools/find.d.ts +2 -2
  251. package/dist/core/tools/find.d.ts.map +1 -1
  252. package/dist/core/tools/find.js +82 -36
  253. package/dist/core/tools/find.js.map +1 -1
  254. package/dist/core/tools/grep.d.ts +7 -5
  255. package/dist/core/tools/grep.d.ts.map +1 -1
  256. package/dist/core/tools/grep.js +87 -75
  257. package/dist/core/tools/grep.js.map +1 -1
  258. package/dist/core/tools/ls.d.ts +2 -2
  259. package/dist/core/tools/ls.d.ts.map +1 -1
  260. package/dist/core/tools/ls.js +2 -1
  261. package/dist/core/tools/ls.js.map +1 -1
  262. package/dist/core/tools/powershell.d.ts.map +1 -1
  263. package/dist/core/tools/powershell.js +15 -2
  264. package/dist/core/tools/powershell.js.map +1 -1
  265. package/dist/core/tools/read.d.ts +10 -2
  266. package/dist/core/tools/read.d.ts.map +1 -1
  267. package/dist/core/tools/read.js +141 -25
  268. package/dist/core/tools/read.js.map +1 -1
  269. package/dist/core/tools/tool-definition-wrapper.d.ts +11 -1
  270. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  271. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  272. package/dist/core/tools/truncate.d.ts +4 -14
  273. package/dist/core/tools/truncate.d.ts.map +1 -1
  274. package/dist/core/tools/truncate.js +23 -29
  275. package/dist/core/tools/truncate.js.map +1 -1
  276. package/dist/core/tools/write.d.ts +2 -2
  277. package/dist/core/tools/write.d.ts.map +1 -1
  278. package/dist/core/tools/write.js.map +1 -1
  279. package/dist/core/trust-manager.d.ts.map +1 -1
  280. package/dist/core/trust-manager.js +14 -8
  281. package/dist/core/trust-manager.js.map +1 -1
  282. package/dist/core/usage-totals.d.ts.map +1 -1
  283. package/dist/core/usage-totals.js +2 -0
  284. package/dist/core/usage-totals.js.map +1 -1
  285. package/dist/extensions/codemode/execute.js +4 -4
  286. package/dist/extensions/codemode/execute.js.map +1 -1
  287. package/dist/extensions/codemode/tool.d.ts +2 -1
  288. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  289. package/dist/extensions/codemode/tool.js +59 -12
  290. package/dist/extensions/codemode/tool.js.map +1 -1
  291. package/dist/extensions/llama/client.d.ts +2 -0
  292. package/dist/extensions/llama/client.d.ts.map +1 -1
  293. package/dist/extensions/llama/client.js +23 -2
  294. package/dist/extensions/llama/client.js.map +1 -1
  295. package/dist/extensions/llama/index.d.ts.map +1 -1
  296. package/dist/extensions/llama/index.js +1 -1
  297. package/dist/extensions/llama/index.js.map +1 -1
  298. package/dist/extensions/mcp/cli.d.ts +2 -0
  299. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  300. package/dist/extensions/mcp/cli.js +83 -22
  301. package/dist/extensions/mcp/cli.js.map +1 -1
  302. package/dist/extensions/mcp/config.d.ts.map +1 -1
  303. package/dist/extensions/mcp/config.js +4 -7
  304. package/dist/extensions/mcp/config.js.map +1 -1
  305. package/dist/extensions/mcp/index.d.ts.map +1 -1
  306. package/dist/extensions/mcp/index.js +5 -4
  307. package/dist/extensions/mcp/index.js.map +1 -1
  308. package/dist/extensions/mcp/oauth.d.ts +11 -49
  309. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  310. package/dist/extensions/mcp/oauth.js +56 -296
  311. package/dist/extensions/mcp/oauth.js.map +1 -1
  312. package/dist/extensions/mcp/resources.d.ts +1 -1
  313. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  314. package/dist/extensions/mcp/resources.js +4 -3
  315. package/dist/extensions/mcp/resources.js.map +1 -1
  316. package/dist/extensions/mcp/runtime.d.ts +4 -3
  317. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  318. package/dist/extensions/mcp/runtime.js +7 -5
  319. package/dist/extensions/mcp/runtime.js.map +1 -1
  320. package/dist/extensions/mcp/tools.d.ts +2 -23
  321. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  322. package/dist/extensions/mcp/tools.js +6 -58
  323. package/dist/extensions/mcp/tools.js.map +1 -1
  324. package/dist/extensions/punch/index.d.ts.map +1 -1
  325. package/dist/extensions/punch/index.js +1 -1
  326. package/dist/extensions/punch/index.js.map +1 -1
  327. package/dist/extensions/punch/todos.js +1 -1
  328. package/dist/extensions/punch/todos.js.map +1 -1
  329. package/dist/extensions/subagent/index.d.ts.map +1 -1
  330. package/dist/extensions/subagent/index.js +278 -129
  331. package/dist/extensions/subagent/index.js.map +1 -1
  332. package/dist/extensions/tool-search/tool.d.ts +21 -6
  333. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  334. package/dist/extensions/tool-search/tool.js +122 -42
  335. package/dist/extensions/tool-search/tool.js.map +1 -1
  336. package/dist/index.d.ts +4 -4
  337. package/dist/index.d.ts.map +1 -1
  338. package/dist/index.js +2 -0
  339. package/dist/index.js.map +1 -1
  340. package/dist/main.d.ts.map +1 -1
  341. package/dist/main.js +106 -14
  342. package/dist/main.js.map +1 -1
  343. package/dist/modes/print-mode.d.ts.map +1 -1
  344. package/dist/modes/print-mode.js +19 -10
  345. package/dist/modes/print-mode.js.map +1 -1
  346. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  347. package/dist/modes/rpc/rpc-mode.js +53 -23
  348. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  349. package/dist/package-manager-cli.d.ts.map +1 -1
  350. package/dist/package-manager-cli.js +94 -12
  351. package/dist/package-manager-cli.js.map +1 -1
  352. package/dist/utils/ansi.d.ts.map +1 -1
  353. package/dist/utils/ansi.js +5 -2
  354. package/dist/utils/ansi.js.map +1 -1
  355. package/dist/utils/changelog.d.ts +2 -2
  356. package/dist/utils/changelog.d.ts.map +1 -1
  357. package/dist/utils/changelog.js +12 -9
  358. package/dist/utils/changelog.js.map +1 -1
  359. package/dist/utils/clipboard-command.d.ts.map +1 -1
  360. package/dist/utils/clipboard-command.js +4 -0
  361. package/dist/utils/clipboard-command.js.map +1 -1
  362. package/dist/utils/fuzzy.d.ts.map +1 -1
  363. package/dist/utils/fuzzy.js +59 -44
  364. package/dist/utils/fuzzy.js.map +1 -1
  365. package/dist/utils/git.d.ts +11 -1
  366. package/dist/utils/git.d.ts.map +1 -1
  367. package/dist/utils/git.js +44 -0
  368. package/dist/utils/git.js.map +1 -1
  369. package/dist/utils/image-resize-core.d.ts.map +1 -1
  370. package/dist/utils/image-resize-core.js +5 -3
  371. package/dist/utils/image-resize-core.js.map +1 -1
  372. package/dist/utils/image-resize.d.ts.map +1 -1
  373. package/dist/utils/image-resize.js +3 -1
  374. package/dist/utils/image-resize.js.map +1 -1
  375. package/dist/utils/open-browser.d.ts.map +1 -1
  376. package/dist/utils/open-browser.js +4 -1
  377. package/dist/utils/open-browser.js.map +1 -1
  378. package/dist/utils/paths.d.ts +17 -0
  379. package/dist/utils/paths.d.ts.map +1 -1
  380. package/dist/utils/paths.js +42 -1
  381. package/dist/utils/paths.js.map +1 -1
  382. package/dist/utils/shell.d.ts.map +1 -1
  383. package/dist/utils/shell.js +14 -0
  384. package/dist/utils/shell.js.map +1 -1
  385. package/dist/utils/terminal-question.d.ts +8 -0
  386. package/dist/utils/terminal-question.d.ts.map +1 -0
  387. package/dist/utils/terminal-question.js +24 -0
  388. package/dist/utils/terminal-question.js.map +1 -0
  389. package/dist/utils/text.d.ts +2 -0
  390. package/dist/utils/text.d.ts.map +1 -1
  391. package/dist/utils/text.js +5 -0
  392. package/dist/utils/text.js.map +1 -1
  393. package/dist/utils/tools-manager.d.ts.map +1 -1
  394. package/dist/utils/tools-manager.js +30 -35
  395. package/dist/utils/tools-manager.js.map +1 -1
  396. package/dist/utils/web-url.d.ts +12 -0
  397. package/dist/utils/web-url.d.ts.map +1 -0
  398. package/dist/utils/web-url.js +20 -0
  399. package/dist/utils/web-url.js.map +1 -0
  400. package/docs/cli-integration.md +3 -5
  401. package/docs/cli.md +45 -26
  402. package/docs/compaction.md +9 -9
  403. package/docs/configuration.md +1 -2
  404. package/docs/containerization.md +16 -14
  405. package/docs/custom-provider.md +5 -3
  406. package/docs/docs.json +9 -9
  407. package/docs/environment-variables.md +5 -12
  408. package/docs/extensions.md +683 -757
  409. package/docs/how-pi-works.md +5 -5
  410. package/docs/index.md +5 -5
  411. package/docs/llama-cpp.md +41 -39
  412. package/docs/mcp.md +12 -10
  413. package/docs/message-types.md +1 -1
  414. package/docs/models-configuration.md +6 -1
  415. package/docs/models.md +18 -19
  416. package/docs/nvidia-rtx-llama-cpp.md +1 -1
  417. package/docs/packages.md +21 -1
  418. package/docs/prompt-templates.md +11 -9
  419. package/docs/providers.md +8 -8
  420. package/docs/quickstart.md +28 -52
  421. package/docs/rpc-commands.md +2 -2
  422. package/docs/rpc-extension-ui.md +5 -7
  423. package/docs/rpc.md +4 -2
  424. package/docs/sdk.md +1 -1
  425. package/docs/security.md +9 -5
  426. package/docs/session-format.md +7 -9
  427. package/docs/sessions.md +26 -26
  428. package/docs/settings.md +36 -67
  429. package/docs/shell-aliases.md +7 -7
  430. package/docs/skills.md +4 -4
  431. package/docs/slash-commands.md +50 -58
  432. package/docs/termux.md +8 -9
  433. package/docs/themes.md +21 -41
  434. package/docs/usage.md +59 -177
  435. package/docs/virtual-models.md +4 -4
  436. package/docs/windows.md +8 -10
  437. package/examples/extensions/README.md +3 -2
  438. package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  439. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  440. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  441. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  442. package/examples/extensions/gondolin/package-lock.json +19 -29
  443. package/examples/extensions/gondolin/package.json +2 -2
  444. package/examples/extensions/reload-runtime.ts +17 -5
  445. package/examples/extensions/rpc-demo.ts +2 -2
  446. package/examples/extensions/subagent/README.md +14 -11
  447. package/examples/extensions/with-deps/package-lock.json +2 -2
  448. package/examples/extensions/with-deps/package.json +1 -1
  449. package/examples/tsconfig.json +208 -0
  450. package/npm-shrinkwrap.json +58 -53
  451. package/package.json +15 -17
  452. package/schemas/models.schema.json +65 -36
  453. package/schemas/settings.schema.json +17 -243
  454. package/dist/bundle/chunks/anthropic-messages-WCANLUXE.js +0 -6
  455. package/dist/bundle/chunks/azure-openai-responses-46GRAI5B.js +0 -2
  456. package/dist/bundle/chunks/chunk-37OLNCAX.js +0 -16
  457. package/dist/bundle/chunks/chunk-3V45WARH.js +0 -7
  458. package/dist/bundle/chunks/chunk-4LBJE4YM.js +0 -14
  459. package/dist/bundle/chunks/chunk-4NE64BTO.js +0 -82
  460. package/dist/bundle/chunks/chunk-5NXXRYVM.js +0 -2
  461. package/dist/bundle/chunks/chunk-7BOHO7TR.js +0 -1190
  462. package/dist/bundle/chunks/chunk-7XECPCHN.js +0 -2
  463. package/dist/bundle/chunks/chunk-NJK3U3WK.js +0 -8
  464. package/dist/bundle/chunks/chunk-PLK2QSUR.js +0 -2
  465. package/dist/bundle/chunks/chunk-TEPMHNKQ.js +0 -2
  466. package/dist/bundle/chunks/chunk-UE7JCDFW.js +0 -2
  467. package/dist/bundle/chunks/chunk-UKVNB6C4.js +0 -2
  468. package/dist/bundle/chunks/chunk-USJZMAIR.js +0 -2
  469. package/dist/bundle/chunks/chunk-WZONBDPY.js +0 -11
  470. package/dist/bundle/chunks/cli-W5KJM7YB.js +0 -51
  471. package/dist/bundle/chunks/mistral-conversations-D6VQXE7C.js +0 -5
  472. package/dist/bundle/chunks/openai-codex-responses-QSNSWBYG.js +0 -10
  473. package/dist/bundle/chunks/openai-completions-72VXSFHQ.js +0 -7
  474. package/dist/bundle/chunks/openai-responses-PMTL72CY.js +0 -4
  475. package/dist/bundle/chunks/pi-messages-WVCFUCBL.js +0 -8
  476. package/dist/bundle/chunks/virtual-modules-7Y5QW4VK.js +0 -2
  477. package/dist/core/bug-report-upload.d.ts +0 -12
  478. package/dist/core/bug-report-upload.d.ts.map +0 -1
  479. package/dist/core/bug-report-upload.js +0 -22
  480. package/dist/core/bug-report-upload.js.map +0 -1
  481. package/dist/core/bug-report.d.ts +0 -184
  482. package/dist/core/bug-report.d.ts.map +0 -1
  483. package/dist/core/bug-report.js +0 -292
  484. package/dist/core/bug-report.js.map +0 -1
  485. package/dist/core/crash-log.d.ts +0 -27
  486. package/dist/core/crash-log.d.ts.map +0 -1
  487. package/dist/core/crash-log.js +0 -140
  488. package/dist/core/crash-log.js.map +0 -1
  489. package/dist/core/footer-data-provider.d.ts +0 -64
  490. package/dist/core/footer-data-provider.d.ts.map +0 -1
  491. package/dist/core/footer-data-provider.js +0 -338
  492. package/dist/core/footer-data-provider.js.map +0 -1
  493. package/dist/utils/zip.d.ts +0 -7
  494. package/dist/utils/zip.d.ts.map +0 -1
  495. package/dist/utils/zip.js +0 -60
  496. package/dist/utils/zip.js.map +0 -1
  497. package/docs/images/interactive-mode.png +0 -0
  498. package/docs/images/tree-view.png +0 -0
  499. package/docs/keybindings.md +0 -194
  500. package/docs/terminal-setup.md +0 -17
  501. package/docs/tmux.md +0 -55
  502. package/docs/tui.md +0 -125
  503. package/examples/extensions/sandbox/index.ts +0 -321
  504. package/examples/extensions/sandbox/package-lock.json +0 -92
  505. package/examples/extensions/sandbox/package.json +0 -19
package/CHANGELOG.md CHANGED
@@ -1,6 +1,173 @@
1
1
  # Changelog
2
2
 
3
- ## [Unreleased]
3
+ ## [1.5.3] - 2026-11-22
4
+
5
+ ## [1.5.2] - 2026-11-22
6
+
7
+ ### Breaking Changes
8
+
9
+ - Removed `pi.registerShortcut()` and the `ExtensionShortcut` type. Headless modes never ran extension shortcuts; register a command with `pi.registerCommand()` instead.
10
+ - Removed the `"tui"` value of `ExtensionContext.mode` and the `"custom"` UI prompt kind, which headless modes never produce.
11
+ - Removed `AgentSession.summarizeForBugReport()`. It belonged to the removed `/bug` command.
12
+ - Custom `GrepOperations.readFile` callbacks are no longer called for context lines. The field remains accepted as optional and deprecated so existing integrations still compile. The grep tool now takes context lines from ripgrep and no longer reads matched files itself. To search a remote system, override grep's `execute()`; see [Remote Execution](docs/extensions.md#remote-execution) ([#9276](https://github.com/earendil-works/pi/issues/9276))
13
+ - OpenAI-compatible models no longer send `"tools": []` when all tools are disabled in a session that has used tools; the field is omitted. This fixes 400 errors (`tools must not be an empty array`) from vLLM 0.20+, also behind LiteLLM. If your proxy requires `tools` once the history has tool calls, such as older LiteLLM versions in front of Anthropic, set `compat.requiresToolsWithToolHistory: true` for that model in `models.json` ([#11843](https://github.com/earendil-works/pi/issues/11843))
14
+ - Tool argument validation runs on `@punch-bot/schema`. TypeBox features outside JSON Schema (`Type.Refine()`, `Type.BigInt()`, `Type.Undefined()`, codecs, `Format.Set()` formats) no longer apply to tool arguments; see [Tool parameter schemas and TypeBox](docs/extensions.md#tool-parameter-schemas-and-typebox). Plain JSON Schema tools, including MCP tools, now get the same coercion as TypeBox tools, such as converting numeric strings and wrapping a single value into an array. Validation failures the model sees list pi-schema's messages (`- path: missing`, `- limit: expected number, got string`) instead of TypeBox's (`must have required properties path`, `must be number`).
15
+
16
+ ### Added
17
+
18
+ - `@punch-bot/cli` exports `StringEnum`, typed for TypeBox so it infers its literal union inside `Type.Object`. The `StringEnum` from `@punch-bot/ai` is typed for `@punch-bot/schema`, and its field infers as `unknown` there.
19
+ - `pi update` now lists each updated package with its npm version or git commit change, for example `npm:foo 1.2.0 -> 1.3.0`, and prints `Packages are already up to date` when nothing changed. When nothing changed but an update printed a warning, for example because npm left the old version installed after resolving stale registry metadata, it prints `No packages were updated, see the warnings above` instead; in offline mode it prints `Skipped package updates (offline mode)`. `PackageManager.update()` reports each changed package as a new `result` progress event whose `message` holds that line ([#11707](https://github.com/earendil-works/pi/pull/11707), [#11711](https://github.com/earendil-works/pi/pull/11711))
20
+ - Anthropic sessions now use message threads: each request sends only the new messages and the server continues from the previous reply, falling back to the full request when the conversation changed (for example after compaction or a tool list change). On by default for the `anthropic` provider on `api.anthropic.com`; set `compat.supportsMessageThreads` in `models.json` to enable it for gateways that forward the `thread` field, or to turn it off. Cache warming does not touch the session's thread ([#11545](https://github.com/earendil-works/pi/pull/11545))
21
+ - `pi auth login <provider>` logs in to a provider from the shell without starting a session, for example `pi auth login radius`. It signs in with an account in the browser and exits; `--api-key` saves an API key instead, and `--no-browser` uses device code or copy-code sign-in instead. Logging in to Radius also configures the Radius MCP server. `pi auth logout <provider>` removes the stored credentials, like `/logout`
22
+ - Added the `qwen-token-plan-individual-cn` provider for Qwen Token Plan Individual on the China endpoint, using `QWEN_TOKEN_PLAN_CN_API_KEY` ([#7989](https://github.com/earendil-works/pi/pull/7989) by [@bigoldcat123](https://github.com/bigoldcat123))
23
+ - Added Microsoft-Decision-1 classifier support through GitHub Copilot, including codemode `models.classify()` ([#11679](https://github.com/earendil-works/pi/pull/11679) by [@Marvae](https://github.com/Marvae))
24
+ - Added `compat.promptCacheKeyMode` (`"auto"`, `"enabled"`, or `"disabled"`) to enable prompt cache keys for compatible proxies or omit them for endpoints that reject them. Set it in `models.json` when using pi ([#9442](https://github.com/earendil-works/pi/pull/9442) by [@dannote](https://github.com/dannote))
25
+ - Added `compat.requiresNonNullAssistantContent` for OpenAI-compatible endpoints that require an empty string instead of `null` in assistant messages containing only tool calls. Set it in `models.json` when using pi ([#8118](https://github.com/earendil-works/pi/pull/8118) by [@gaoyk19](https://github.com/gaoyk19))
26
+ - Added GLM 5.3 to the Qwen Token Plan Individual model allowlist ([#11658](https://github.com/earendil-works/pi/issues/11658))
27
+ - Added Claude Fable 5.2 (`claude-fable-5-2`) to the `anthropic` provider ($8/$40 per million input/output tokens, 1M context, 128K output). Like Fable 5.1 it uses per-message effort and mid-conversation system messages; requests its safety classifiers refuse before any output are answered by Claude Opus 5 through server-side fallback and billed at Opus 5's price. Claude Fable 5.2 and Mythos 5.2 on other providers, such as OpenRouter's `anthropic/claude-fable-5.2`, get the same per-message effort support
28
+ - `pi.exec()` accepts a `maxBuffer` option that limits stdout and stderr combined, and its result has a `truncated` field that is true when output exceeded the limit ([#11360](https://github.com/earendil-works/pi/issues/11360))
29
+ - `pi update` can update Pi through a wrapper or another package manager. Set `PI_SELF_UPDATE_COMMAND` (for example `mise use -g npm:{packageName}@{version}`) or the global `selfUpdateCommand` setting; `pi update` runs it when pi.dev reports a newer release and fills `{packageName}`, `{version}`, and `{installSpec}` from that release. See [Custom update command](docs/cli.md#custom-update-command) ([#7756](https://github.com/earendil-works/pi/issues/7756), [#5607](https://github.com/earendil-works/pi/issues/5607))
30
+ - Added `Usage.cost.totalFromProvider` to distinguish billed totals from catalog estimates in SDK and extension usage data; combined usage is marked provider-reported only when every part is ([#11178](https://github.com/earendil-works/pi/pull/11178))
31
+ - Added concrete `responseModel` metadata to messages from pi-messages providers such as Radius, including when a virtual model is requested. See [AssistantMessage](docs/message-types.md#assistantmessage) ([#11265](https://github.com/earendil-works/pi/pull/11265))
32
+ - Added GPT-6.1 Terra for OpenAI, Azure OpenAI Responses, and OpenAI Codex, with tool search and mid-conversation thinking-level changes. It supports thinking `off`; Codex offers a 500K context window
33
+
34
+ ### Changed
35
+
36
+ - The default model for the `anthropic` provider is now Claude Opus 5.5 (`claude-opus-5-5`) instead of Claude Opus 4.8
37
+ - Default models moved to newer models at the same or a lower price: `amazon-bedrock` Claude Opus 5.5, `azure` GPT-6.1 Sol, `google` and `google-vertex` Gemini 4 Argon, `vercel-ai-gateway` GLM 5.3, `baseten` GLM 5.3, `minimax` and `minimax-cn` MiniMax-M3, `qwen-token-plan` and `qwen-token-plan-cn` Qwen3.8 Max, `opencode-go` Kimi K3.1 Pro, and Kimi K2.7 Code instead of Kimi K2.6 for `moonshotai`, `moonshotai-cn`, `huggingface`, `opencode`, `openrouter`, `cloudflare-workers-ai` and `cloudflare-ai-gateway`
38
+ - `cacheWarming` now defaults to `"idle"` instead of `"streaming"`: pi also keeps eligible prompt caches warm for up to 30 minutes between agent runs, but only when a refresh is expected to pay for itself. Set `"cacheWarming": "streaming"` in global settings for the previous behavior
39
+ - Extensions keep importing `Type`, `Static` and `TSchema` from `@punch-bot/ai`: Pi maps that import to pi-ai's compat entry plus the TypeBox it bundles, now that pi-ai itself no longer re-exports TypeBox, and its `StringEnum` there stays a TypeBox `TUnsafe<T>`. The built-in tool factories (`createReadTool()` and the others) return `TypeBoxAgentTool<typeof schema>`, which keeps `params` typed for TypeBox.
40
+ - Tightened system prompt
41
+ - `pi update` for installs from the pi.dev installer no longer passes `--min-release-age=0` to `npm ci`. The release lockfile pins every package, so the flag had no effect, and security scanners that block it stopped the update ([#11262](https://github.com/earendil-works/pi/issues/11262))
42
+ - MCP OAuth sign-in now uses pi's Client ID Metadata Document by default when the authorization server supports it for public clients, and registers a client dynamically otherwise, like Codex, Claude Code, and opencode. Clients registered before stay in use while their redirect URI matches. The new default `oauth.clientRegistration: "auto"` registers when `clientName` or a non-default `callbackUrl` is set; `"dcr"` always registers. `pi mcp add --oauth-client-registration` sets the mode ([#11426](https://github.com/earendil-works/pi/issues/11426))
43
+ - Changed the default OpenAI model from `gpt-5.5` to `gpt-6.1-sol`, including after ChatGPT sign-in when no model is selected ([#11442](https://github.com/earendil-works/pi/issues/11442))
44
+ - Updated the built-in model catalog to models.dev v2. Realtime and image-only models are no longer offered as chat models; newer OpenAI and Google chat models are included
45
+
46
+ ### Fixed
47
+
48
+ - Fixed `pi auth login` and `pi auth logout` not finding providers that extensions register, such as llama.cpp: they reported `Unknown provider "llama.cpp"`. Both now load the built-in and user extensions; a project's own extensions still do not load.
49
+ - Fixed `/import` of a session whose working directory no longer exists leaving a copy in the session directory, and continuing it leaving a second copy with the same ID (`s.jsonl` and `s-1.jsonl`); the failed copy is now removed ([#11975](https://github.com/earendil-works/pi/pull/11975) by [@petrroll](https://github.com/petrroll), fixes [#11060](https://github.com/earendil-works/pi/issues/11060))
50
+ - Fixed Anthropic OAuth requests reporting an outdated Claude Code version
51
+ - Fixed the grep tool's `glob` matching from the folder pi was started in instead of from `path`: with `path: "repo"`, `glob: "migrations/main/*.js"` returned `No matches found` even though `repo/migrations/main/a.js` exists. Globs are now relative to `path`, the same form grep prints its results in, also when `path` is a symlink. A leading `./` (`./src/*.ts`) is ignored instead of matching nothing ([#11807](https://github.com/earendil-works/pi/issues/11807), [#10998](https://github.com/earendil-works/pi/issues/10998))
52
+ - Fixed prompt template arguments dropping apostrophes and merging words: an apostrophe inside a word, as in `doesn't`, no longer opens a quote; a quote with no closing match is kept as text; and `\"` inside `"..."` (or `\'` inside `'...'`) gives a literal quote ([#11861](https://github.com/earendil-works/pi/issues/11861))
53
+ - Fixed the bash tool reporting only `Command timed out` when the command had already exited but a background process it started kept writing to its output until the timeout. The error now also reports the shell's exit code and when it exited ([#11613](https://github.com/earendil-works/pi/issues/11613))
54
+ - Images in steering and follow-up messages, including `prompt()` while streaming, are now resized like images in idle prompts instead of being sent and saved at full size ([#11738](https://github.com/earendil-works/pi/issues/11738))
55
+ - A failed token refresh of an MCP connection no longer registers an OAuth client or replaces the PKCE verifier of a sign-in in progress, which made that sign-in fail. MCP sign-in now refreshes the stored tokens with the stored client even when the loopback callback port changed, instead of registering a new client and opening the browser. Ctrl+C in `/mcp` and the `--timeout` of `pi mcp login` now also stop a sign-in while it waits up to 25 seconds for another pi process's token refresh, and a refresh lock that fails for another reason than that wait now fails the sign-in instead of opening the browser.
56
+ - Fixed `pi mcp list` reporting MCP servers with `"auth": { "provider": "<provider>" }`, such as Radius, as needing sign-in although the provider was signed in: the shell command sent no token. It now sends the provider's `/login` token and refreshes it when it expired. For these servers the sign-in hint names `/login <provider>` instead of `pi mcp login`, and `pi mcp login` and `pi mcp logout` point to `/login` and `/logout` instead of failing with "does not use OAuth"
57
+ - Fixed RPC mode ignoring an extension's `ctx.shutdown()` while idle, for example from a timer: the process kept running until the client sent another command. pi now shuts down right away when idle, and a shutdown requested by an extension command waits until the command's `prompt` response is written ([#11599](https://github.com/earendil-works/pi/issues/11599))
58
+ - Fixed changelog notes repeating on every fresh launch when the installed package version has a prerelease suffix, such as `0.1.5-20261020.7`: the saved version was read as `0.1.0`, so the `0.1.1` to `0.1.5` notes counted as new each time. A saved version without `major.minor.patch` now shows no notes and is replaced by the installed version, instead of showing the whole changelog ([#11703](https://github.com/earendil-works/pi/issues/11703))
59
+ - Fixed RPC mode cutting off shutdown cleanup, such as a pending MCP token refresh, when stdin closed and SIGTERM arrived together, which process managers like Paseo and systemd do. Pi lost the refreshed token and the MCP server revoked the sign-in. Once a shutdown has started, a stdin EOF or a single signal no longer interrupts it; a second signal still exits at once. Print mode likewise no longer dies from a signal that arrives during its final cleanup ([#11599](https://github.com/earendil-works/pi/issues/11599))
60
+ - Fixed the grep tool reading every matched file into memory when `context` was set, which ran out of memory on large files; context now comes from ripgrep, which also fixes UTF-16 files and lone CRs in matched lines, and the match limit notice no longer appears when exactly `limit` matches exist ([#9276](https://github.com/earendil-works/pi/issues/9276), [#11423](https://github.com/earendil-works/pi/issues/11423))
61
+ - Fixed the find tool reporting the result limit when exactly `limit` files match, and `limit: 0` in find and ls returning every result or an empty listing; limits below 1 now mean 1 ([#7121](https://github.com/earendil-works/pi/issues/7121))
62
+ - Fixed grep match lines, codemode output, compaction summaries of tool results, and MCP error and server summaries cutting an emoji or other non-BMP character in half when truncating, which left an invalid lone surrogate in the text ([#7121](https://github.com/earendil-works/pi/issues/7121))
63
+ - Fixed the find tool on Windows returning no results for patterns with Windows separators such as `src\**\*.ts`, and for every path pattern such as `src/**/*.ts` with fd 10.5.1, which pi now downloads. Windows path patterns now match the same way with every fd version: `src/**/*.ts` also finds files directly in `src/`, and `src/*.ts` no longer finds files in subdirectories ([#9262](https://github.com/earendil-works/pi/issues/9262))
64
+ - Fixed the read tool loading whole files into memory, which ran out of memory on large files even with `offset`/`limit`; it now streams the file and keeps only the shown lines. Custom `ReadOperations` can stream too by providing the new optional `createReadStream` ([#9654](https://github.com/earendil-works/pi/issues/9654))
65
+ - Fixed OAuth logins such as `openai` and `anthropic` failing with `invalid_grant` after pi was stopped while it refreshed an expired token, for example an RPC client that stops pi right after startup while the background catalog refresh runs. The token endpoint had already replaced the refresh token, but pi exited before saving the new one. On exit, pi now waits for a token refresh in progress to be saved ([#11692](https://github.com/earendil-works/pi/issues/11692))
66
+ - Fixed pi aborting (`zsh: abort`) after repeated image reads, reported on macOS arm64 with Node 24.16. Each image resize starts a worker thread, and pi did not wait for it to stop, so the next resize started a new worker while the previous one was still shutting down. The crash is most likely a Node bug that this overlap triggers and could not be reproduced on Linux; image resizes now wait for the previous worker to stop, which adds about 15 ms per image ([#10695](https://github.com/earendil-works/pi/issues/10695))
67
+ - Fixed `tool_search` and `searchTools()` not finding a tool by property names and descriptions behind a local `$ref`, as in MCP input schemas that put their models in `$defs`. Referenced definitions are read once, so recursive schemas do not loop, and definitions nothing references stay out of the search text ([#11803](https://github.com/earendil-works/pi/issues/11803))
68
+ - Fixed the codemode `resolves to` summary of a tool leaving out field names behind a local `$ref`, for example `structuredContent?` instead of `structuredContent?: { results }` for MCP output schemas that put their models in `$defs` ([#11803](https://github.com/earendil-works/pi/issues/11803))
69
+ - Fixed every codemode script failing with `URI malformed` when any callable tool, such as an MCP tool, had a `$ref` with a malformed percent escape (`#/$defs/%E0`) in its schema, even scripts that do not call that tool. The parameter now renders as `unknown` in the tool's declaration ([#11803](https://github.com/earendil-works/pi/issues/11803))
70
+ - Fixed resuming a session restoring an old thinking level after `/tree` navigated to before a `/thinking` change. Like the model, the live thinking level is now recorded on the new branch with the next prompt ([#11451](https://github.com/earendil-works/pi/issues/11451))
71
+ - Fixed the edit tool rewriting the line endings of untouched lines in files with mixed CRLF/LF or lone CR line endings, and running out of memory on large files after the file was already written; the diff now covers only the changed lines and their surroundings and is computed before writing ([#8544](https://github.com/earendil-works/pi/issues/8544))
72
+ - Fixed `pi update --models` failing with `Could not refresh model catalogs: openai: OAuth refresh failed for openai: ... invalid_grant` when a provider's login had gone stale. Built-in providers whose catalog comes from pi.dev, such as `openai`, no longer refresh their OAuth token for a catalog refresh at all. For providers that list models with the login, such as Radius and OpenRouter, a failed token refresh now prints a warning naming the provider and `pi auth login <provider>`, and the other catalogs still refresh; the command fails only for other errors, such as a network failure
73
+ - Fixed the powershell tool reporting `Command exited with code 1` under Windows PowerShell 5.1 when a native command succeeded but its stderr was redirected, as in `git push 2>&1 | Select-Object -Last 3`. Windows PowerShell 5.1 turns that stderr into error records; such commands now report the exit code PowerShell 7 reports ([#8842](https://github.com/earendil-works/pi/issues/8842))
74
+ - Fixed dropped provider streams reported as "cut short after the reply had begun" not triggering automatic retries ([#11879](https://github.com/earendil-works/pi/issues/11879))
75
+ - Fixed the subagent extension example passing Bun's Windows virtual entry path as part of the prompt when spawning a compiled pi binary ([#11865](https://github.com/earendil-works/pi/issues/11865))
76
+ - Fixed the subagent extension example showing running tasks as completed, losing subprocess failure diagnostics, and failing to stop child processes on abort. Agent discovery and trust checks now use each task's working directory, and single and chain results are truncated without losing the full tool details ([#8250](https://github.com/earendil-works/pi/pull/8250) by [@terrorobe](https://github.com/terrorobe))
77
+ - Fixed prompts and session-tree navigation overlapping during asynchronous input hooks, authentication, or branch summaries, which could install the wrong conversation context ([#9155](https://github.com/earendil-works/pi/pull/9155) by [@acmerfight](https://github.com/acmerfight))
78
+ - Fixed Claude Sonnet 5 requests sending an unsupported temperature parameter ([#7961](https://github.com/earendil-works/pi/pull/7961) by [@jingtao-wisdomgraph](https://github.com/jingtao-wisdomgraph))
79
+ - Fixed extensions loaded through symlinked paths failing to resolve their dependencies by resolving the entry file's real path before importing it ([#8112](https://github.com/earendil-works/pi/pull/8112) by [@cad0p](https://github.com/cad0p))
80
+ - Fixed OpenAI Responses requests sending `session_id` instead of the documented `session-id` affinity header ([#11639](https://github.com/earendil-works/pi/issues/11639))
81
+ - Fixed delivered image-only steering and follow-up messages remaining in the pending queue ([#8612](https://github.com/earendil-works/pi/pull/8612) by [@wutongyuonce](https://github.com/wutongyuonce))
82
+ - Fixed cancellation during lazy provider loading or authentication being reported as an error instead of an abort ([#8635](https://github.com/earendil-works/pi/pull/8635) by [@Mallikarjun-0](https://github.com/Mallikarjun-0))
83
+ - Fixed session runtime disposal tearing down extensions before active tools finished aborting and their results were recorded ([#9126](https://github.com/earendil-works/pi/pull/9126) by [@acmerfight](https://github.com/acmerfight))
84
+ - Fixed SDK and RPC reloads replacing extensions while a response or compaction was still running; reload now asks the caller to wait ([#9222](https://github.com/earendil-works/pi/pull/9222) by [@acmerfight](https://github.com/acmerfight))
85
+ - Fixed concurrent OAuth refreshes through symlinked paths to the same `auth.json` by sharing the lock on the resolved file ([#11655](https://github.com/earendil-works/pi/issues/11655))
86
+ - Fixed provider connection errors hiding their underlying cause, such as connection refusal or certificate errors, behind generic messages ([#11695](https://github.com/earendil-works/pi/issues/11695))
87
+ - Fixed llama.cpp connection errors omitting the server URL and underlying network error ([#11745](https://github.com/earendil-works/pi/issues/11745))
88
+ - Fixed OpenAI Codex SSE retries retaining abort listeners after each backoff, causing listener buildup on repeated retries ([#11708](https://github.com/earendil-works/pi/issues/11708))
89
+ - Azure OpenAI models now keep OpenAI's long-context price tier, so requests above 272K input tokens are costed at Azure's long-context rates ([#11948](https://github.com/earendil-works/pi/issues/11948))
90
+ - Fixed Anthropic and Bedrock sending `strict: "prefer"` tools strict again on every request after Claude rejected them for exceeding its strict tool limits, which cost a rejected request (400) per turn. Later requests with the same `sessionId` now send those tools non-strict right away, until `cleanupSessionResources(sessionId)` ([#11626](https://github.com/earendil-works/pi/issues/11626))
91
+ - Fixed tool arguments for `Type.BigInt()` and `Type.Undefined()` parameters being rejected: they convert as TypeBox converted them (`"42"` and `42` to `42n`, `null` to `undefined`), now that pi-schema supports both types. `Type.Void()` still rejects every JSON argument.
92
+ - Fixed Azure GPT-6 Astra, Luna, Sol, GPT-6.1 Sol, and GPT-6.1 Terra using a 272K context window instead of the 1,050,000 tokens Azure Foundry deploys them with ([#11742](https://github.com/earendil-works/pi/issues/11742))
93
+ - Fixed OpenRouter rejecting requests with a 400 (`This endpoint's maximum context length is ...`) for models whose output limit is close to the context window, such as DeepSeek flash. OpenRouter counts the input with its own tokenizer, which can be several percent higher than the provider's count, and pi left only 4,096 tokens spare. pi then treated the 400 as a context overflow and compacted the session, even at around 20% of the window. The default output limit now leaves 15% of the estimated input unused, and near a full window at most 32,768 output tokens are requested ([#10497](https://github.com/earendil-works/pi/issues/10497))
94
+ - Fixed Anthropic non-strict tool schemas dropping root `$defs` and `definitions`, which left property `$ref`s pointing at nothing. Claude then produced wrong arguments for such tools (common in MCP servers), for example a JSON string instead of an object, and some Anthropic-compatible gateways rejected the request outright ([#9557](https://github.com/earendil-works/pi/issues/9557))
95
+ - Fixed OpenCode Go Claude Haiku 5.5 failing with a 400 (`Invalid signature in thinking block ... bound to a different conversation`) after the tool list, system prompt, or earlier history changed, which left the session failing on every retry. OpenCode Go and Zen Claude 5.5 models, Opus 5, and Fable 5.1 now use per-message effort and send `thinking.block_binding: drop_block`, like the Anthropic provider ([#10954](https://github.com/earendil-works/pi/issues/10954))
96
+ - Fixed codemode `console.*` output and thrown non-Error values printing `NaN`, `Infinity`, and `-Infinity` as `null` ([#11901](https://github.com/earendil-works/pi/issues/11901))
97
+ - Fixed large MCP stdio messages being repeatedly copied and scanned as chunks arrived, causing slow tool responses ([#11761](https://github.com/earendil-works/pi/issues/11761))
98
+ - Fixed MCP Streamable HTTP SSE replies with CR-only line endings failing with "stream ended without a response" ([#11764](https://github.com/earendil-works/pi/issues/11764))
99
+ - Fixed oversized MCP SSE responses keeping their HTTP connections open after the message-size limit rejected them ([#11729](https://github.com/earendil-works/pi/issues/11729))
100
+ - Fixed MCP stdio server subprocesses surviving disconnect or pi exit on POSIX when the server's main process had already exited ([#11721](https://github.com/earendil-works/pi/issues/11721))
101
+ - Fixed MCP Streamable HTTP JSON replies bypassing message-size limits and HTTP errors buffering entire response bodies. Oversized replies and error-body content beyond the first 8 KiB are now cancelled ([#11335](https://github.com/earendil-works/pi/issues/11335))
102
+ - Fixed valid tool arguments being rejected when their schema combined local `$ref`s with a relative root `$id`, such as `schemas/tool.json` ([#11697](https://github.com/earendil-works/pi/issues/11697))
103
+ - Fixed the find tool starting an untracked `fd` process when cancelled during its parent-directory lookup ([#11974](https://github.com/earendil-works/pi/pull/11974) by [@petrroll](https://github.com/petrroll))
104
+ - Updated glob matching to prevent denial of service from amplified glob patterns.
105
+ - Fixed a saved "Do not trust" decision being ignored for projects without trust-requiring resources, for example a folder with only `AGENTS.md`. pi auto-trusted such projects, so `ctx.isProjectTrusted()` returned true and package commands treated them as trusted. A saved decision in `trust.json` now takes precedence; auto-trust applies only when no decision is saved ([#10947](https://github.com/earendil-works/pi/issues/10947))
106
+ - Fixed compaction, branch summaries, and bug-report summaries in SDK sessions passing the stored OAuth token back to the model runtime as an explicit API key. Provider auth that treats explicit keys differently from stored OAuth now sees the OAuth login, as normal prompts do ([#11520](https://github.com/earendil-works/pi/issues/11520))
107
+ - Fixed a redundant system prompt update (tools, rules) when an extension set the same active tools in a different order, for example a reversed `pi.setActiveTools()` list. Tools that stay active now keep their order and newly activated tools are appended ([#11495](https://github.com/earendil-works/pi/issues/11495))
108
+ - Fixed `pi.exec()` crashing pi with `RangeError: Invalid string length` when a command printed more output than fits in a string. The default output cap is the smaller of 256 MiB and the runtime string limit; past the cap, the command is terminated and the result has `truncated: true` and a nonzero exit code ([#11360](https://github.com/earendil-works/pi/issues/11360))
109
+ - Fixed `pi.exec()` never returning when a command ignored SIGTERM after a timeout or abort. pi now sends SIGKILL 5 seconds later, as intended
110
+ - Fixed `pi install` and `pi remove` adding ever deeper nested entries to the npm `package-lock.json` when the agent directory is reached through a symlink, such as `~/.pi` linked into a dotfiles repo. pi now passes the resolved real path to npm ([#11358](https://github.com/earendil-works/pi/issues/11358))
111
+ - MCP sign-in now rejects authorization endpoints and other OAuth metadata URLs that are not `http:` or `https:`. Before, a malicious MCP server could supply a `file:` or custom protocol URL, which pi passed to the platform URL handler.
112
+ - Automatic `fd` and `rg` downloads no longer fetch x86-64 binaries on ARM32 and other architectures without a prebuilt release. pi now warns and recommends installing the tool with the system package manager ([#11209](https://github.com/earendil-works/pi/issues/11209))
113
+ - Fixed HTML export showing a blank page for sessions with thousands of entries ([#11225](https://github.com/earendil-works/pi/issues/11225), [#11293](https://github.com/earendil-works/pi/pull/11293))
114
+ - Fixed HTML export not showing system messages: the system prompt and tools, and later section updates such as after `/reload`. `pi --export` now includes the system prompt and tools too ([#11261](https://github.com/earendil-works/pi/issues/11261), [#3464](https://github.com/earendil-works/pi/issues/3464), [#11290](https://github.com/earendil-works/pi/pull/11290))
115
+ - Fixed aborting a bash command on macOS sometimes running the next command of a list such as `long_step; next_step`. pi now stops the process group before killing it ([#11252](https://github.com/earendil-works/pi/issues/11252), [#11289](https://github.com/earendil-works/pi/pull/11289))
116
+ - Fixed large streamed tool calls taking excessive CPU time and memory because every delta re-parsed the accumulated arguments. Providers and agent proxy streams now parse each delta once, grammar tools no longer copy their entire input per delta, and interactive tool renderers run at most once per frame ([#9265](https://github.com/earendil-works/pi/issues/9265))
117
+ - Fixed `pi -e npm:<pkg>` staying on the version from the first download. On each start and `/reload`, pi now reinstalls an `-e` npm package without an exact version when the registry has a newer matching version. `pi -e git:<repo>@<branch>` likewise stayed on its first checkout and is now fetched and reset to the branch; a commit-hash ref that is already checked out is not fetched. Offline mode and failed checks keep the cached copy ([#11375](https://github.com/earendil-works/pi/issues/11375), [#11590](https://github.com/earendil-works/pi/pull/11590))
118
+ - Fixed Windows paths being compared case-sensitively. When the working directory and home directory differed only in drive-letter casing (`c:\Users\me` vs `C:\Users\me`), skills in `~/.agents/skills` loaded twice, as project and user skills, and were reported as name collisions. The same mismatch also re-asked for saved project trust, hid sessions in a custom session directory from `--continue` and `/resume`, and stopped `pi remove` from matching configured local packages ([#10488](https://github.com/earendil-works/pi/issues/10488))
119
+ - Fixed paths next to the home directory being shown with a broken `~` prefix, for example `/home/me2/project` shown as `~2/project` when home is `/home/me`
120
+ - Fixed `pi mcp login -l` and `pi mcp logout -l` failing with `Unknown option --local.` although `pi mcp add` and `pi mcp remove` accept `-l`. With `-l`, they now require the server to be a project server. Unknown options are now reported as typed, and a mistyped server name gets a suggestion, for example `Did you mean "gurker"?`
121
+ - Fixed `pi update` naming pnpm for installs that only live under `PNPM_HOME`, for example a wrapper under `$PNPM_HOME/global-nub/`. pi said "not managed by a global pnpm install"; it now names the package manager only when that manager owns the install ([#7756](https://github.com/earendil-works/pi/issues/7756))
122
+ - Fixed image paste, copy, and opening the browser for sign-in failing silently on WSL when the working directory is deep. Windows programs such as `powershell.exe` and `explorer.exe` cannot start from a directory whose `\\wsl.localhost\...` path exceeds 260 characters; pi now starts these helpers from `/` ([#11592](https://github.com/earendil-works/pi/issues/11592))
123
+ - Fixed `tool_search` and codemode `searchTools()` ranking a tool below tools that only mention its name in their descriptions, for example `peekaboo app` ranking `mcp__peekaboo__app` 14th. A tool matching more of the query's words now ranks above one matching fewer, a query word in a tool's name scores more than any number of mentions in its description, a tool whose whole name is in the query gets a large bonus, and long server instructions no longer lower the scores of that server's tools ([#11331](https://github.com/earendil-works/pi/issues/11331))
124
+ - Fixed `tool_search` and codemode `searchTools()` finding nothing for Chinese, Japanese, Thai, and other non-ASCII queries, because the tokenizer kept only ASCII letters and digits. Words in any script now match, text without spaces between words such as `搜索记录` is split into words, and canonically equivalent text such as `café` and `cafe\u0301` matches ([#10816](https://github.com/earendil-works/pi/issues/10816), [#11037](https://github.com/earendil-works/pi/pull/11037) by [@haoqixu](https://github.com/haoqixu))
125
+ - Fixed `pi update` stopping with `git clean -fdx failed with code 1` on Windows when another pi session had a git extension's native module or executable open. Windows cannot delete such files, so the update left the new code with the old dependencies. pi now warns, installs the dependencies anyway, and retries the clean on the next update ([#11597](https://github.com/earendil-works/pi/issues/11597))
126
+ - Fixed two pi processes refreshing OAuth credentials at the same time when they reach the same `auth.json` through different paths, such as a symlinked `auth.json` in a separate agent directory. The auth lock now uses the file's resolved path ([#11655](https://github.com/earendil-works/pi/issues/11655))
127
+ - Fixed resized photos being sent as multi-megabyte PNGs even when JPEG was much smaller, causing large requests to fail or time out. Image resizing now tries the smaller encoding first ([#11551](https://github.com/earendil-works/pi/issues/11551))
128
+ - Fixed `pi update --extensions` reporting success without warning when npm's stale registry metadata left a package at its old version. pi now reports the installed and expected versions ([#11536](https://github.com/earendil-works/pi/issues/11536))
129
+ - Fixed skill validation warnings being labeled `[Skill conflicts]` even when there was no name collision. They are now shown under `[Skill warnings]` ([#11521](https://github.com/earendil-works/pi/issues/11521))
130
+ - Fixed codemode tool descriptions including entire union and multi-line output types in every request. Object unions now summarize their fields and discriminators; other multi-line types point to `describeTool()` for the full declaration ([#11501](https://github.com/earendil-works/pi/issues/11501))
131
+ - Fixed startup from a deleted working directory crashing with an uncaught `uv_cwd` stack trace. pi now asks the user to change to an existing directory ([#11509](https://github.com/earendil-works/pi/issues/11509))
132
+ - Fixed failed session writes leaving entries in memory that were absent from disk, so later entries pointed to missing parents and resumed sessions lost earlier history and tools ([#11460](https://github.com/earendil-works/pi/issues/11460))
133
+ - Fixed `/tree` branch summaries ignoring the session's thinking level, which could make reasoning models reject summary requests with an unsupported `none` effort ([#11444](https://github.com/earendil-works/pi/issues/11444))
134
+ - Fixed package installation and removal printing npm audit and funding advice, including `npm audit fix` instructions that could install a second copy of pi into the package directory ([#11409](https://github.com/earendil-works/pi/issues/11409))
135
+ - Fixed `grep` context lines being offset from ripgrep's match line numbers when a file contains a lone carriage return ([#11398](https://github.com/earendil-works/pi/issues/11398))
136
+ - Fixed `--model <provider>/<id>` failing for provider IDs containing slashes, such as URL-derived llama.cpp provider IDs ([#11394](https://github.com/earendil-works/pi/issues/11394))
137
+ - Fixed slow session forking on filesystems where opening files is expensive by writing the fork through one file handle ([#11253](https://github.com/earendil-works/pi/issues/11253))
138
+ - Fixed `pi.exec()` corrupting UTF-8 characters split across stdout or stderr chunks ([#11312](https://github.com/earendil-works/pi/issues/11312))
139
+ - Fixed `pi.exec()` returning empty stderr when a command could not be spawned, such as a missing executable. It now preserves the spawn error message ([#11257](https://github.com/earendil-works/pi/pull/11257) by [@muyiyr](https://github.com/muyiyr))
140
+ - Fixed a configured package failing to install crashing startup. pi now skips the package, reports an extension warning, and retries on the next start or `/reload`; explicit install and update commands still fail with a nonzero exit ([#11304](https://github.com/earendil-works/pi/pull/11304) by [@Lincoln504](https://github.com/Lincoln504))
141
+ - Updated `undici` to 8.12.3 and the Gondolin extension example to 0.14.0 for security advisories
142
+ - Fixed OpenRouter cost totals using catalog estimates instead of reported billing for Chat Completions and Anthropic Messages. BYOK totals include both OpenRouter charges and reported upstream costs; component costs remain catalog estimates ([#9980](https://github.com/earendil-works/pi/issues/9980))
143
+ - Fixed OpenCode Zen and OpenCode Go requests using shared endpoints instead of their protocol-specific OpenAI, Anthropic, Google, and System One endpoints ([#11434](https://github.com/earendil-works/pi/pull/11434) by [@vimtor](https://github.com/vimtor))
144
+ - Fixed Zhipu/Z.ai usage-limit errors (code `1308`) being treated as transient HTTP 429 errors, causing automatic retries that cannot succeed until the usage cap resets ([#11537](https://github.com/earendil-works/pi/issues/11537))
145
+ - Fixed LiteLLM's `ContextWindowExceededError` not being recognized as context overflow ([#11492](https://github.com/earendil-works/pi/issues/11492))
146
+ - Fixed Gemini tool schemas sending unsupported `const` keywords. They are now converted to single-value `enum` schemas without rewriting literal data in defaults, examples, or enum values, or losing properties named `__proto__` ([#11308](https://github.com/earendil-works/pi/issues/11308))
147
+ - Fixed the faux provider counting simulated cache-write tokens as both input and cache writes
148
+ - Fixed Claude sessions failing with `role 'system' must precede an 'assistant' message` when a system update was followed by an empty or reasoning-only assistant reply ([#11091](https://github.com/earendil-works/pi/issues/11091))
149
+ - Fixed Claude mid-conversation thinking-level changes failing with `Invalid effort level` on accounts whose organization caps effort below `high` ([#10063](https://github.com/earendil-works/pi/issues/10063))
150
+ - Fixed Kimi K3.1 Pro models using Kimi K2 request settings on Kimi Coding, Moonshot, and OpenCode Go. They now send the correct reasoning effort, preserve earlier thinking, accept tools added mid-conversation, and use K3-family pricing
151
+ - Fixed OpenCode DeepSeek V4.1 Flash requests failing when long cache retention sent the unsupported `prompt_cache_retention` parameter
152
+ - Fixed GPT-5.4 and GPT-5.5 failing with `Missing namespace for function_call` after switching from a model that had called tools ([#11415](https://github.com/earendil-works/pi/issues/11415))
153
+ - Fixed Bedrock Claude requests failing when preferred strict tools exceed the provider's strict-tool limits. Requests now retry once with preferred tools non-strict while keeping required strict tools strict ([#11416](https://github.com/earendil-works/pi/issues/11416))
154
+ - Fixed OpenRouter's `~anthropic/claude-*-latest` aliases losing earlier thinking after tool calls by using the Anthropic Messages API ([#9534](https://github.com/earendil-works/pi/issues/9534))
155
+ - Fixed terminal titles containing control characters being able to inject terminal escape sequences, and pi-messages streams accepting invalid content-block indices
156
+ - Fixed `/tree` branch summaries including failed assistant replies and original content that context edits had hidden or replaced. Summaries now honor the same context edits as live requests and compaction ([#11602](https://github.com/earendil-works/pi/issues/11602))
157
+
158
+ ### Removed
159
+
160
+ - Removed the native OS `sandbox/` extension example and its dependency. Use the [Gondolin example](examples/extensions/gondolin/) or the [containerization guide](docs/containerization.md).
161
+ - Removed settings that only the removed terminal UI read, with their `SettingsManager` getters and setters: `tuiMode`, `fullscreenExitOutput`, `fullscreenScrollbar`, `fullscreenCopyOnSelect`, `fullscreenWheelScrollLines`, `editorPaddingX`, `outputPad`, `autocompleteMaxVisible`, `showHardwareCursor`, `externalEditor`, `doubleEscapeAction`, `treeFilterMode`, `hideThinkingBlock`, `quietStartup`, `terminal.showImages`, `terminal.imageWidthCells`, `terminal.clearOnShrink`, `terminal.showTerminalProgress`, `markdown`, `enableSkillCommands`, `branchSummary.skipPrompt`, `showCacheMissNotices`, `collapseChangelog`, `enableAnalytics`, `trackingId`, and `warnings`. Existing settings files that set them still load. The `FullscreenExitOutput`, `QuietStartup` and `TuiMode` type exports are gone.
162
+ - Removed the `--verbose` flag, which nothing read.
163
+ - Removed the `ReadonlyFooterDataProvider` type export and the footer data provider behind it, which only the removed terminal UI footer used.
164
+ - Removed the leftover `/share` and `/bug` code: bug-report bundling and upload, the unused crash log, and the `PI_SHARE_VIEWER_URL` and `PI_RADIUS_GATEWAY` environment variables, which only that code read.
165
+
166
+ ## [1.5.1] - 2026-11-04
167
+
168
+ ### Fixed
169
+
170
+ - Updated `undici` to 8.12.3 and `minimatch` to 11.0.4 for upstream security fixes (TLS certificate validation bypass, cross-origin redirect cache poisoning, and several denial-of-service issues in undici; glob pattern amplification in minimatch). The npm shrinkwrap and install lock also pick up `body-parser` 2.4.0 and `qs` 6.17.1.
4
171
 
5
172
  ## [1.5.0] - 2026-11-04
6
173
 
package/README.md CHANGED
@@ -82,7 +82,7 @@ To embed pi in your own app, use the SDK (`createAgentSession`). See [Programmat
82
82
 
83
83
  By default, pi gives the model four tools: `read`, `write`, `edit`, and `bash`. The model uses these to fulfill your requests. Add capabilities via [skills](#skills), [prompt templates](#prompt-templates), [extensions](#extensions), or [pi packages](#pi-packages).
84
84
 
85
- **Platform notes:** [Windows](docs/windows.md) | [Termux (Android)](docs/termux.md) | [tmux](docs/tmux.md) | [Terminal setup](docs/terminal-setup.md) | [Shell aliases](docs/shell-aliases.md)
85
+ **Platform notes:** [Windows](docs/windows.md) | [Termux (Android)](docs/termux.md) | [Shell aliases](docs/shell-aliases.md)
86
86
 
87
87
  ---
88
88
 
@@ -216,7 +216,7 @@ Non-interactive modes (`-p`, `--mode json`, and `--mode rpc`) do not show a trus
216
216
 
217
217
  If no extension or saved decision applies, `defaultProjectTrust` controls the fallback behavior. Set it to `"ask"`, `"always"`, or `"never"` in `~/.pi/agent/settings.json`.
218
218
 
219
- `pi config` and package commands use the same project trust flow, except `pi update` never prompts. Pass `--approve` to trust project-local settings for one command or `--no-approve` to ignore them.
219
+ `pi config` and package commands use the same project trust flow. Pass `--approve` to trust project-local settings for one command or `--no-approve` to ignore them.
220
220
 
221
221
  ### Telemetry and update checks
222
222
 
@@ -443,10 +443,10 @@ pi update --self # Update pi only
443
443
  pi update --self --force # Reinstall pi even if current
444
444
  pi update --extension <src> # Update one package
445
445
  pi list # List installed packages
446
- pi config # Enable/disable package resources
446
+ pi config # Print resolved package resources as JSON
447
447
  ```
448
448
 
449
- `pi config` and project package commands accept `--approve`/`--no-approve` to trust or ignore project-local settings for one command. `pi update` never prompts for project trust.
449
+ `pi config` and project package commands accept `--approve`/`--no-approve` to trust or ignore project-local settings for one command.
450
450
 
451
451
  ### Modes
452
452
 
@@ -519,8 +519,7 @@ Combine `--no-*` with explicit flags to load exactly what you need, ignoring set
519
519
  |--------|-------------|
520
520
  | `--system-prompt <text>` | Replace the default prompt's opening (tools, rules, context files, and skills still appended) |
521
521
  | `--append-system-prompt <text>` | Append to system prompt |
522
- | `--use-theme <name[/name]>` | Set the theme for this run without changing settings |
523
- | `--verbose` | Force verbose startup |
522
+ | `--use-theme <name>` | Set the theme for this run without changing settings |
524
523
  | `-a`, `--approve` | Trust project-local files for this run |
525
524
  | `-na`, `--no-approve` | Ignore project-local files for this run |
526
525
  | `--` | Stop option parsing; remaining arguments are prompts or `@file` inputs |
@@ -590,7 +589,6 @@ pi --thinking high "Solve this complex problem"
590
589
  | `PI_SKIP_VERSION_CHECK` | Skip the Pi version update check at startup. This prevents the `pi.dev` latest-version request |
591
590
  | `PI_TELEMETRY` | Override install/update telemetry and provider attribution headers. Use `1`/`true`/`yes` to enable or `0`/`false`/`no` to disable. This does not disable update checks |
592
591
  | `PI_CACHE_RETENTION` | Set to `long` for extended prompt cache (Anthropic: 1h, OpenAI: 24h) |
593
- | `VISUAL`, `EDITOR` | Fallback external editor for Ctrl+G when `externalEditor` is unset; defaults to Notepad on Windows and `nano` elsewhere |
594
592
 
595
593
  Commands run by the LLM-callable `bash` and `powershell` tools also receive current session metadata:
596
594
 
@@ -608,7 +606,7 @@ These values are resolved when each command starts. See [Environment Variables](
608
606
 
609
607
  ## Contributing & Development
610
608
 
611
- See [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines and [docs/development.md](docs/development.md) for setup, forking, and debugging.
609
+ See [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines.
612
610
 
613
611
  ## License
614
612
 
@@ -0,0 +1,6 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{ANTHROPIC_FEDERATION_RULE_ID_ENV,ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,ANTHROPIC_ORGANIZATION_ID_ENV,ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,ANTHROPIC_WORKSPACE_ID_ENV}from"./chunk-GFUN2N5K.js";import{registerSessionResourceCleanup}from"./chunk-ZG74NES2.js";import{applyOpenRouterReportedCost,isOpenRouterModel}from"./chunk-P7FPUEYA.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{Anthropic}from"./chunk-7CBJINYJ.js";import{shortHash}from"./chunk-PJACZCIR.js";import{adjustMaxTokensForThinking,buildBaseOptions,clampMaxTokensToContext,getJsonSchemaToolParameters,prefersJsonSchemaStrictSampling,resolveJsonSchemaStrictSampling,splitErrorToolResultImages,transformMessages}from"./chunk-35EHANXE.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{withCauseDetail}from"./chunk-WN2D4UD4.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{ToolCallArgumentsStream,parseJsonWithRepair}from"./chunk-FFMDRXC4.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{calculateCost,getCurrentTools,getInitialSystemMessage,resolveTranscript}from"./chunk-JAJLG57O.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders,getSystemMessageText,renderSystemMessageUpdate}from"./chunk-77CRE5SV.js";import"./chunk-JXWJOIH4.js";var STRICT_TOOL_LIMIT_ERROR_MESSAGES=["The compiled grammar is too large","Too many strict tools (","Schemas contains too many parameters with union types ("];function isStrictToolLimitErrorMessage(message){return STRICT_TOOL_LIMIT_ERROR_MESSAGES.some(limitMessage=>message.includes(limitMessage))}var sessionsOverStrictToolLimits=new Set,MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS=1e4;function markStrictToolLimitsExceeded(sessionId){if(sessionId!==void 0&&(sessionsOverStrictToolLimits.add(sessionId),sessionsOverStrictToolLimits.size>MAX_SESSIONS_OVER_STRICT_TOOL_LIMITS)){let oldest=sessionsOverStrictToolLimits.values().next().value;oldest!==void 0&&sessionsOverStrictToolLimits.delete(oldest)}}function hasExceededStrictToolLimits(sessionId){return sessionId!==void 0&&sessionsOverStrictToolLimits.has(sessionId)}registerSessionResourceCleanup(sessionId=>{sessionId?sessionsOverStrictToolLimits.delete(sessionId):sessionsOverStrictToolLimits.clear()});function resolveCacheRetention(cacheRetention,env){return cacheRetention||(getProviderEnvValue("PI_CACHE_RETENTION",env)==="long"?"long":"short")}function getCacheControl(model,cacheRetention,env){let retention=resolveCacheRetention(cacheRetention,env);if(retention==="none")return{retention};let ttl=retention==="long"&&getAnthropicCompat(model).supportsLongCacheRetention?"1h":void 0;return{retention,cacheControl:{type:"ephemeral",...ttl&&{ttl}}}}var claudeCodeVersion="2.1.322",claudeCodeTools=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],ccToolLookup=new Map(claudeCodeTools.map(t=>[t.toLowerCase(),t])),toClaudeCodeName=name=>ccToolLookup.get(name.toLowerCase())??name,fromClaudeCodeName=(name,tools)=>{if(tools&&tools.length>0){let lowerName=name.toLowerCase(),matchedTool=tools.find(tool=>tool.name.toLowerCase()===lowerName);if(matchedTool)return matchedTool.name}return name};function convertImageBlock(image){return{type:"image",source:{type:"base64",media_type:image.mimeType,data:image.data}}}function convertContentBlocks(content){if(!content.some(c=>c.type==="image"))return sanitizeSurrogates(content.map(c=>c.text).join(`
3
+ `));let blocks=content.map(block=>block.type==="text"?{type:"text",text:sanitizeSurrogates(block.text)}:convertImageBlock(block));return blocks.some(b=>b.type==="text")||blocks.unshift({type:"text",text:"(see attached image)"}),blocks}var FINE_GRAINED_TOOL_STREAMING_BETA="fine-grained-tool-streaming-2025-05-14",INTERLEAVED_THINKING_BETA="interleaved-thinking-2025-05-14",SERVER_SIDE_FALLBACK_BETA="server-side-fallback-2026-07-01",MID_CONVERSATION_OUTPUT_CONFIG_BETA="mid-conversation-output-config-2026-07-01",THINKING_BINDING_CONTROLS_BETA="thinking-binding-controls-2026-08-01",INLINE_TOOLS_BETA="inline-tools-2026-09-15",MESSAGE_THREADS_BETA="message-threads-2026-08-12",DEFERRED_TOOL_PLACEHOLDER={name:"__pi_deferred_placeholder__",description:"Reserved placeholder. Never available. Never call this.",input_schema:{type:"object",properties:{},required:[]},defer_loading:!0};function shouldUseServerSideFallbackBeta(model){return(model.compat?.allowedFallbackModels?.length??0)>0}function getAnthropicCompat(model){let isOpenRouter=model.provider==="openrouter"||model.baseUrl.includes("openrouter.ai");return{supportsEagerToolInputStreaming:model.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:model.compat?.supportsLongCacheRetention??!0,sendSessionAffinityHeaders:model.compat?.sendSessionAffinityHeaders??isOpenRouter,sessionAffinityFormat:model.compat?.sessionAffinityFormat??(isOpenRouter?"openrouter":void 0),supportsCacheControlOnTools:model.compat?.supportsCacheControlOnTools??!0,supportsTemperature:model.compat?.supportsTemperature??!0,allowEmptySignature:model.compat?.allowEmptySignature??!1,supportsStrictTools:model.compat?.supportsStrictTools??!1,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsMidConvoToolChanges:model.compat?.supportsMidConvoToolChanges??!1,supportsMessageThreads:model.compat?.supportsMessageThreads??(model.provider==="anthropic"&&model.baseUrl.includes("api.anthropic.com"))}}var threadState=new Map,MAX_THREAD_STATE_ENTRIES=1e4,NEW_THREAD_ERRORS=new Set(["thread_not_found","thread_already_continued","thread_continue_in_flight","thread_fingerprint_mismatch"]);function setThreadState(sessionId,value){if(threadState.delete(sessionId),threadState.set(sessionId,value),threadState.size>MAX_THREAD_STATE_ENTRIES){let oldest=threadState.keys().next().value;oldest!==void 0&&threadState.delete(oldest)}}registerSessionResourceCleanup(sessionId=>{sessionId?threadState.delete(sessionId):threadState.clear()});function hashThreadPrefix(model,params,messages){let{system,tools,thinking,output_config,tool_choice,betas,fallbacks}=params,settings=JSON.stringify([model.provider,model.baseUrl,params.model,system,tools,thinking,output_config,tool_choice,betas,fallbacks]),conversation=JSON.stringify(messages,(key,value)=>{if(key!=="cache_control")return key==="content"&&typeof value=="string"?[{type:"text",text:value}]:value});return shortHash(settings+conversation)}function createThreadRequest(sessionId,params){return{sessionId,body:{...params,thread:{type:"create"}}}}function prepareThreadRequest(model,sessionId,params){let state=threadState.get(sessionId);if(state!=="off"){if(state!==void 0&&params.messages.length>state.prefixCount&&hashThreadPrefix(model,params,params.messages.slice(0,state.prefixCount))===state.prefixHash){threadState.delete(sessionId);let{system:_system,tools:_tools,...rest}=params;return{body:{...rest,messages:params.messages.slice(state.prefixCount),thread:{type:"continue",previous_message_id:state.replyId}},sessionId}}return createThreadRequest(sessionId,params)}}function getThreadErrorCode(error){let code=error.error?.error?.details?.error_code;return typeof code=="string"?code:void 0}async function sendThreadRequest(thread,params,send,output,signal){try{return{response:await send(thread.body),thread}}catch(error){if(signal?.aborted||!(error instanceof Anthropic.APIError))throw error;let errorCode=getThreadErrorCode(error),startNewThread=errorCode!==void 0&&NEW_THREAD_ERRORS.has(errorCode),threadsUnsupported=errorCode==="thread_unsupported_request"||errorCode===void 0&&error.status===400&&error.message.includes("thread");if(!startNewThread&&!threadsUnsupported)throw error;if(appendAssistantMessageDiagnostic(output,{type:"anthropic_thread_fallback",timestamp:Date.now(),error:{message:error.message},details:{reason:errorCode??String(error.status)}}),startNewThread){let created=createThreadRequest(thread.sessionId,params);return{response:await send(created.body),thread:created}}let response=await send(params);return setThreadState(thread.sessionId,"off"),{response,thread:void 0}}}function recordThreadReply(model,thread,params,output,isOAuth,allowEmptySignature){if(output.responseId===void 0||output.responseModel!==void 0)return;let reply=convertMessages(transformMessages([output],model,normalizeToolCallId),isOAuth,void 0,allowEmptySignature).messages.filter(message=>message.role==="assistant"),prefix=[...params.messages,...reply];setThreadState(thread.sessionId,{prefixCount:prefix.length,prefixHash:hashThreadPrefix(model,params,prefix),replyId:output.responseId})}function mergeHeaders(...headerSources){let merged={};for(let headers of headerSources)headers&&Object.assign(merged,headers);return merged}function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function hasRequestAuth(apiKey,headers){return!!apiKey||hasHeader(headers,"authorization")||hasHeader(headers,"x-api-key")||hasHeader(headers,"cf-aig-authorization")}function assertRequestAuth(provider,apiKey,headers){if(!hasRequestAuth(apiKey,headers))throw new Error(`No API key for provider: ${provider}`)}var PiAnthropic=class extends Anthropic{_shouldResolveDefaultCredentials(){return!1}};function getAnthropicFederation(model,apiKey,headers,env){if(model.provider!=="anthropic"||hasRequestAuth(apiKey,headers))return;let federationRuleId=getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV,env),organizationId=getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV,env),identityTokenFile=getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,env);if(!(!federationRuleId||!organizationId||!identityTokenFile))return{organization_id:organizationId,workspace_id:getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV,env),authentication:{type:"oidc_federation",federation_rule_id:federationRuleId,service_account_id:getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,env),identity_token:{source:"file",path:identityTokenFile}}}}var federationClient,ANTHROPIC_MESSAGE_EVENTS=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function flushSseEvent(state){if(!state.event&&state.data.length===0)return null;let event={event:state.event,data:state.data.join(`
4
+ `),raw:[...state.raw]};return state.event=null,state.data=[],state.raw=[],event}function decodeSseLine(line,state){if(line==="")return flushSseEvent(state);if(state.raw.push(line),line.startsWith(":"))return null;let delimiterIndex=line.indexOf(":"),fieldName=delimiterIndex===-1?line:line.slice(0,delimiterIndex),value=delimiterIndex===-1?"":line.slice(delimiterIndex+1);return value.startsWith(" ")&&(value=value.slice(1)),fieldName==="event"?state.event=value:fieldName==="data"&&state.data.push(value),null}function nextLineBreakIndex(text){let carriageReturnIndex=text.indexOf("\r"),newlineIndex=text.indexOf(`
5
+ `);return carriageReturnIndex===-1?newlineIndex:newlineIndex===-1?carriageReturnIndex:Math.min(carriageReturnIndex,newlineIndex)}function consumeLine(text){let lineBreakIndex=nextLineBreakIndex(text);if(lineBreakIndex===-1)return null;let nextIndex=lineBreakIndex+1;return text[lineBreakIndex]==="\r"&&text[nextIndex]===`
6
+ `&&(nextIndex+=1),{line:text.slice(0,lineBreakIndex),rest:text.slice(nextIndex)}}async function*iterateSseMessages(body,signal){let reader=body.getReader(),decoder=new TextDecoder,state={event:null,data:[],raw:[]},buffer="";try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let consumed2=consumeLine(buffer);for(;consumed2;){buffer=consumed2.rest;let event=decodeSseLine(consumed2.line,state);event&&(yield event),consumed2=consumeLine(buffer)}}buffer+=decoder.decode();let consumed=consumeLine(buffer);for(;consumed;){buffer=consumed.rest;let event=decodeSseLine(consumed.line,state);event&&(yield event),consumed=consumeLine(buffer)}if(buffer.length>0){let event=decodeSseLine(buffer,state);event&&(yield event)}let trailingEvent=flushSseEvent(state);trailingEvent&&(yield trailingEvent)}finally{reader.releaseLock()}}async function*iterateAnthropicEvents(response,signal){if(!response.body)throw new Error("Attempted to iterate over an Anthropic response with no body");let sawMessageStart=!1,sawMessageEnd=!1;for await(let sse of iterateSseMessages(response.body,signal)){if(sse.event==="error")throw new Error(sse.data);if(ANTHROPIC_MESSAGE_EVENTS.has(sse.event??""))try{let event=parseJsonWithRepair(sse.data);event.type==="message_start"?sawMessageStart=!0:event.type==="message_stop"&&(sawMessageEnd=!0),yield event}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join("\\n")}`)}}if(sawMessageStart&&!sawMessageEnd)throw new Error("Anthropic stream ended before message_stop")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,compat=getAnthropicCompat(model),normalizedContext=resolveTranscript(context,compat.supportsMidConvoSystemMessages),currentTools=getCurrentTools(normalizedContext.messages);return(async()=>{let output={role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let client,isOAuth,usageModel=model,inputTransformations,cacheSessionId=resolveCacheRetention(options?.cacheRetention,options?.env)==="none"?void 0:options?.sessionId,threadSessionId=compat.supportsMessageThreads?cacheSessionId:void 0;if(options?.client)client=options.client,isOAuth=!1;else{let apiKey=options?.apiKey,federation=getAnthropicFederation(model,apiKey,options?.headers,options?.env);federation||assertRequestAuth(model.provider,apiKey,options?.headers);let copilotDynamicHeaders;if(model.provider==="github-copilot"){let hasImages=hasCopilotVisionInput(normalizedContext.messages);copilotDynamicHeaders=buildCopilotDynamicHeaders({messages:normalizedContext.messages,hasImages})}let created=createClient(model,apiKey,options?.headers,options?.fetch,copilotDynamicHeaders,cacheSessionId,federation,options?.identity);client=created.client,isOAuth=created.isOAuthToken}let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},send=body=>retryProviderRequest(()=>client.beta.messages.create(body,requestOptions).asResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal}),disablePreferredStrictTools=hasExceededStrictToolLimits(options?.sessionId),response,params,thread;for(;;){options?.signal?.throwIfAborted();let built=buildParams(model,normalizedContext,isOAuth,options,{disablePreferredStrictTools,messageThreads:threadSessionId!==void 0});built.providerThinkingLevel&&(output.providerThinkingLevel=built.providerThinkingLevel),params=built.params;let nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params={...nextParams,stream:!0});let prepared=threadSessionId!==void 0&&options?.disableContinuation!==!0?prepareThreadRequest(model,threadSessionId,params):void 0;try{let sent=prepared?await sendThreadRequest(prepared,params,send,output,options?.signal):{response:await send(params),thread:void 0};response=sent.response,thread=sent.thread;break}catch(error){if(options?.signal?.aborted||disablePreferredStrictTools||!built.hasPreferredStrictTools||!(error instanceof Anthropic.APIError)||error.status!==400||error.type!=="invalid_request_error"||!isStrictToolLimitErrorMessage(error.message))throw error;disablePreferredStrictTools=!0,markStrictToolLimitsExceeded(options?.sessionId),appendAssistantMessageDiagnostic(output,{type:"anthropic_strict_tools_fallback",timestamp:Date.now(),error:{message:error.message},details:{reason:"strict_tool_limits_exceeded"}})}}await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output});let openBlocks=new Map,openBlock=anthropicIndex=>{let open=openBlocks.get(anthropicIndex);return open===void 0?void 0:{...open,block:output.content[open.contentIndex]}};for await(let event of iterateAnthropicEvents(response,options?.signal))if(await options?.onProviderStreamEvent?.(event,model),event.type==="message_start"){output.responseId=event.message.id;let transformations=event.message.input_transformations;Array.isArray(transformations)&&(inputTransformations=transformations);let responseModel=event.message.model;responseModel!==model.id&&(output.responseModel=responseModel);let fallbackCost=responseModel===model.id?void 0:model.compat?.allowedFallbackModels?.find(fallback=>fallback.provider===model.provider&&fallback.model===responseModel)?.cost;usageModel=fallbackCost?{...model,id:responseModel,cost:fallbackCost}:model,output.usage.input=event.message.usage.input_tokens||0,output.usage.output=event.message.usage.output_tokens||0,output.usage.cacheRead=event.message.usage.cache_read_input_tokens||0,output.usage.cacheWrite=event.message.usage.cache_creation_input_tokens||0,output.usage.cacheWrite1h=event.message.usage.cache_creation?.ephemeral_1h_input_tokens||0,output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(usageModel,output.usage)}else if(event.type==="content_block_start"){if(event.content_block.type==="fallback"){if(output.content.length>0)throw new Error("Anthropic performed an unsupported mid-output model fallback");continue}event.content_block.type==="text"?(output.content.push({type:"text",text:event.content_block.text??""}),openBlocks.set(event.index,{contentIndex:output.content.length-1}),stream2.push({type:"text_start",contentIndex:output.content.length-1,partial:output})):event.content_block.type==="thinking"?(output.content.push({type:"thinking",thinking:event.content_block.thinking??"",thinkingSignature:event.content_block.signature??""}),openBlocks.set(event.index,{contentIndex:output.content.length-1}),stream2.push({type:"thinking_start",contentIndex:output.content.length-1,partial:output})):event.content_block.type==="redacted_thinking"?(output.content.push({type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:event.content_block.data,redacted:!0}),openBlocks.set(event.index,{contentIndex:output.content.length-1}),stream2.push({type:"thinking_start",contentIndex:output.content.length-1,partial:output})):event.content_block.type==="tool_use"&&(output.content.push({type:"toolCall",id:event.content_block.id,name:isOAuth?fromClaudeCodeName(event.content_block.name,currentTools):event.content_block.name,arguments:event.content_block.input??{}}),openBlocks.set(event.index,{contentIndex:output.content.length-1,arguments:new ToolCallArgumentsStream}),stream2.push({type:"toolcall_start",contentIndex:output.content.length-1,partial:output}))}else if(event.type==="content_block_delta"){let open=openBlock(event.index);event.delta.type==="text_delta"?open?.block.type==="text"&&(open.block.text+=event.delta.text,stream2.push({type:"text_delta",contentIndex:open.contentIndex,delta:event.delta.text,partial:output})):event.delta.type==="thinking_delta"?open?.block.type==="thinking"&&(open.block.thinking+=event.delta.thinking,stream2.push({type:"thinking_delta",contentIndex:open.contentIndex,delta:event.delta.thinking,partial:output})):event.delta.type==="input_json_delta"?open?.block.type==="toolCall"&&open.arguments!==void 0&&(open.block.arguments=open.arguments.append(event.delta.partial_json),stream2.push({type:"toolcall_delta",contentIndex:open.contentIndex,delta:event.delta.partial_json,partial:output})):event.delta.type==="signature_delta"&&open?.block.type==="thinking"&&(open.block.thinkingSignature=open.block.thinkingSignature||"",open.block.thinkingSignature+=event.delta.signature)}else if(event.type==="content_block_stop"){let open=openBlock(event.index);if(openBlocks.delete(event.index),open){let{block,contentIndex:index}=open;block.type==="text"?stream2.push({type:"text_end",contentIndex:index,content:block.text,partial:output}):block.type==="thinking"?stream2.push({type:"thinking_end",contentIndex:index,content:block.thinking,partial:output}):block.type==="toolCall"&&open.arguments!==void 0&&(Object.assign(block,open.arguments.finish()),stream2.push({type:"toolcall_end",contentIndex:index,toolCall:block,partial:output}))}}else if(event.type==="message_delta"){let transformations=event.input_transformations;if(Array.isArray(transformations)&&(inputTransformations=transformations),event.delta.stop_reason){output.rawStopReason=event.delta.stop_reason;let stopReasonResult=mapStopReason(event.delta.stop_reason,event.delta.stop_details);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}if(event.usage){event.usage.input_tokens!=null&&(output.usage.input=event.usage.input_tokens),event.usage.output_tokens!=null&&(output.usage.output=event.usage.output_tokens),event.usage.cache_read_input_tokens!=null&&(output.usage.cacheRead=event.usage.cache_read_input_tokens),event.usage.cache_creation_input_tokens!=null&&(output.usage.cacheWrite=event.usage.cache_creation_input_tokens);let cacheCreation=event.usage.cache_creation;cacheCreation?.ephemeral_1h_input_tokens!=null&&(output.usage.cacheWrite1h=cacheCreation.ephemeral_1h_input_tokens);let thinkingTokens=event.usage.output_tokens_details?.thinking_tokens;thinkingTokens!=null&&(output.usage.reasoning=thinkingTokens)}output.usage.totalTokens=output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(usageModel,output.usage),isOpenRouterModel(model)&&event.usage&&applyOpenRouterReportedCost(output.usage,event.usage)}if(options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Anthropic stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");thread&&recordThreadReply(model,thread,params,output,isOAuth,compat.allowEmptySignature),inputTransformations&&inputTransformations.length>0&&appendAssistantMessageDiagnostic(output,{type:"anthropic_input_transformations",timestamp:Date.now(),details:{transformations:inputTransformations.map(transformation=>({type:transformation.type??void 0,path:transformation.path??void 0,reason:transformation.reason??void 0}))}}),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=error instanceof Error?withCauseDetail(error):JSON.stringify(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2};function mapThinkingLevelToEffort(model,level){let mapped=level?model.thinkingLevelMap?.[level]:void 0;if(typeof mapped=="string")return mapped;switch(level){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}var streamSimple=(model,context,options)=>{getAnthropicFederation(model,options?.apiKey,options?.headers,options?.env)||assertRequestAuth(model.provider,options?.apiKey,options?.headers);let base={...buildBaseOptions(model,context,options,options?.apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinkingEnabled:!1});if(model.compat?.forceAdaptiveThinking===!0){let effort=mapThinkingLevelToEffort(model,options.reasoning);return stream(model,context,{...base,thinkingEnabled:!0,effort})}let adjusted=adjustMaxTokensForThinking(base.maxTokens,model.maxTokens,options.reasoning,options.thinkingBudgets),maxTokens=clampMaxTokensToContext(model,context,adjusted.maxTokens);return stream(model,context,{...base,maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:Math.min(adjusted.thinkingBudget,Math.max(0,maxTokens-1024))})};function isOAuthToken(apiKey){return apiKey.includes("sk-ant-oat")}function createClient(model,apiKey,optionsHeaders,fetch,dynamicHeaders,sessionId,federation,identity){if(model.provider==="github-copilot")return{client:new PiAnthropic({apiKey:null,authToken:apiKey??null,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:mergeHeaders(getIdentityHeaders(model,identity),{accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},model.headers,dynamicHeaders,optionsHeaders)}),isOAuthToken:!1};if(apiKey&&isOAuthToken(apiKey))return{client:new PiAnthropic({apiKey:null,authToken:apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:mergeHeaders({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","user-agent":`claude-cli/${claudeCodeVersion}`,"x-app":"cli"},model.headers,optionsHeaders)}),isOAuthToken:!0};let compat=getAnthropicCompat(model),sessionAffinityHeaders={};if(sessionId&&compat.sendSessionAffinityHeaders){let header=compat.sessionAffinityFormat==="openrouter"?"x-session-id":"x-session-affinity";sessionAffinityHeaders[header]=sessionId}let defaultHeaders=mergeHeaders(getIdentityHeaders(model,identity),{accept:"application/json","anthropic-dangerous-direct-browser-access":"true"},sessionAffinityHeaders,model.headers,optionsHeaders);if(federation){let key=JSON.stringify([model.baseUrl,federation]);if(federationClient?.key!==key||federationClient.fetch!==fetch){let client2=new PiAnthropic({apiKey:null,authToken:null,config:federation,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch});federationClient={key,fetch,client:client2}}return{client:federationClient.client.withOptions({defaultHeaders}),isOAuthToken:!1}}return{client:new PiAnthropic({apiKey:apiKey??null,authToken:null,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders}),isOAuthToken:!1}}function getBetaFeatures(model,context,options,{isOAuthToken:isOAuthToken2,nativeToolChanges,messageThreads}){let configuredFeatures;for(let headers of[model.headers,options?.headers])for(let[name,value]of Object.entries(headers??{}))name.toLowerCase()==="anthropic-beta"&&(configuredFeatures=value);if(configuredFeatures===null)return[];if(configuredFeatures!==void 0)return[...new Set(configuredFeatures.split(",").map(feature=>feature.trim()).filter(feature=>feature.length>0))];let features=[];return isOAuthToken2&&features.push("claude-code-20250219","oauth-2025-04-20"),shouldUseFineGrainedToolStreamingBeta(model,context)&&features.push(FINE_GRAINED_TOOL_STREAMING_BETA),model.reasoning&&options?.thinkingEnabled===!0&&(options.interleavedThinking??!0)&&model.compat?.forceAdaptiveThinking!==!0&&features.push(INTERLEAVED_THINKING_BETA),shouldUseServerSideFallbackBeta(model)&&features.push(SERVER_SIDE_FALLBACK_BETA),model.compat?.supportsMidConvoEffort===!0&&features.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA,THINKING_BINDING_CONTROLS_BETA),nativeToolChanges&&features.push(INLINE_TOOLS_BETA),messageThreads&&features.push(MESSAGE_THREADS_BETA),[...new Set(features)]}function buildParams(model,context,isOAuthToken2,options,flags){let{cacheControl}=getCacheControl(model,options?.cacheRetention,options?.env),compat=getAnthropicCompat(model),initialSystemMessage=getInitialSystemMessage(context.messages),initialSystemText=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",transformedMessages=transformMessages(context.messages,model,normalizeToolCallId),conversationMessages=initialSystemMessage?transformedMessages.slice(1):transformedMessages,hasPreferredStrictTools=!1,convertToolDefinitions=(tools,toolCacheControl2)=>{let definitions=convertTools(tools,isOAuthToken2,compat.supportsEagerToolInputStreaming,compat.supportsStrictTools,toolCacheControl2,flags.disablePreferredStrictTools);return definitions.some((definition,index)=>definition.strict===!0&&prefersJsonSchemaStrictSampling(tools[index]))&&(hasPreferredStrictTools=!0),definitions},initialTools=initialSystemMessage?.toolsAdded??[],nativeToolChanges=compat.supportsMidConvoSystemMessages&&compat.supportsMidConvoToolChanges&&initialTools.length>0,thinkingDisabled=model.reasoning&&options?.thinkingEnabled===!1&&model.thinkingLevelMap?.off!==null,effortMessages=model.compat?.supportsMidConvoEffort===!0&&!thinkingDisabled,converted=convertMessages(conversationMessages,isOAuthToken2,cacheControl,compat.allowEmptySignature,effortMessages?model.provider:void 0,nativeToolChanges?convertToolDefinitions:void 0),activeEffort=options?.effort??"high",betaFeatures=getBetaFeatures(model,context,options,{isOAuthToken:isOAuthToken2,nativeToolChanges,messageThreads:flags.messageThreads}),params={model:model.id,messages:effortMessages?insertThinkingLevelMessages(converted,activeEffort):converted.messages,max_tokens:options?.maxTokens??model.maxTokens,stream:!0,...betaFeatures.length>0?{betas:betaFeatures}:{}};isOAuthToken2?(params.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...cacheControl?{cache_control:cacheControl}:{}}],initialSystemText&&params.system.push({type:"text",text:sanitizeSurrogates(initialSystemText),...cacheControl?{cache_control:cacheControl}:{}})):initialSystemText&&(params.system=[{type:"text",text:sanitizeSurrogates(initialSystemText),...cacheControl?{cache_control:cacheControl}:{}}]),options?.temperature!==void 0&&!options?.thinkingEnabled&&model.compat?.supportsMidConvoEffort!==!0&&compat.supportsTemperature&&(params.temperature=options.temperature);let toolCacheControl=compat.supportsCacheControlOnTools?cacheControl:void 0;if(nativeToolChanges)params.tools=[...convertToolDefinitions(initialTools,toolCacheControl),DEFERRED_TOOL_PLACEHOLDER];else{let tools=getCurrentTools(context.messages);tools.length>0&&(params.tools=convertToolDefinitions(tools,toolCacheControl))}if(thinkingDisabled)params.thinking={type:"disabled"};else if(effortMessages)params.thinking={type:"adaptive",display:options?.thinkingDisplay??"summarized",block_binding:{prefix_mismatch_behavior:"drop_block"}},params.output_config={effort:"low"};else if(model.reasoning&&options?.thinkingEnabled){let display=options.thinkingDisplay??"summarized";model.compat?.forceAdaptiveThinking===!0?(params.thinking={type:"adaptive",display},options.effort&&(params.output_config={effort:options.effort})):params.thinking={type:"enabled",budget_tokens:options.thinkingBudgetTokens||1024,display}}if(options?.metadata){let userId=options.metadata.user_id;typeof userId=="string"&&(params.metadata={user_id:userId})}options?.toolChoice&&(typeof options.toolChoice=="string"?params.tool_choice={type:options.toolChoice}:params.tool_choice=options.toolChoice);let allowedFallbackModels=model.compat?.allowedFallbackModels;return allowedFallbackModels&&allowedFallbackModels.length>0&&(params.fallbacks=allowedFallbackModels.map(fallback=>({model:fallback.model}))),{params,hasPreferredStrictTools,providerThinkingLevel:effortMessages?activeEffort:void 0}}function normalizeToolCallId(id){return id.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function convertToolResult(msg,content=msg.content){return{type:"tool_result",tool_use_id:msg.toolCallId,content:convertContentBlocks(content),is_error:msg.isError}}function convertMessages(transformedMessages,isOAuthToken2,cacheControl,allowEmptySignature=!1,managedProvider,convertToolDefinitions){let params=[],assistantLevels=new Map,pendingSystemMessages=[],flushPendingSystemMessages=()=>{params.push(...pendingSystemMessages),pendingSystemMessages.length=0};for(let i=0;i<transformedMessages.length;i++){let msg=transformedMessages[i];if(msg.role==="system"){let text=renderSystemMessageUpdate(msg),blocks=[];if(text.length>0&&blocks.push({type:"text",text:sanitizeSurrogates(text)}),convertToolDefinitions){let added=msg.toolsAdded??[],redefined=new Set(added.map(tool=>tool.name));for(let tool of msg.toolsRemoved??[])redefined.has(tool.name)||blocks.push({type:"tool_removal",tool:{type:"tool_reference",name:isOAuthToken2?toClaudeCodeName(tool.name):tool.name}});for(let definition of convertToolDefinitions(added))blocks.push({type:"tool_addition",tool:{type:"tool_definition",definition}})}blocks.length>0&&pendingSystemMessages.push({role:"system",content:blocks})}else if(msg.role==="user")if(typeof msg.content=="string")msg.content.trim().length>0&&params.push({role:"user",content:sanitizeSurrogates(msg.content)});else{let filteredBlocks=msg.content.map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:convertImageBlock(item)).filter(b=>b.type==="text"?b.text.trim().length>0:!0);if(filteredBlocks.length===0)continue;params.push({role:"user",content:filteredBlocks})}else if(msg.role==="assistant"){let blocks=[];for(let block of msg.content)if(block.type==="text"){if(block.text.trim().length===0)continue;blocks.push({type:"text",text:sanitizeSurrogates(block.text)})}else if(block.type==="thinking"){if(block.redacted){blocks.push({type:"redacted_thinking",data:block.thinkingSignature});continue}let thinkingSignature=block.thinkingSignature,hasThinkingSignature=!!thinkingSignature&&thinkingSignature.trim().length>0;if(block.thinking.trim().length===0&&!hasThinkingSignature)continue;hasThinkingSignature?blocks.push({type:"thinking",thinking:sanitizeSurrogates(block.thinking),signature:thinkingSignature}):blocks.push(allowEmptySignature?{type:"thinking",thinking:sanitizeSurrogates(block.thinking),signature:""}:{type:"text",text:sanitizeSurrogates(block.thinking)})}else block.type==="toolCall"&&blocks.push({type:"tool_use",id:block.id,name:isOAuthToken2?toClaudeCodeName(block.name):block.name,input:block.arguments??{}});if(blocks.length===0)continue;flushPendingSystemMessages();let messageIndex=params.length;params.push({role:"assistant",content:blocks}),managedProvider!==void 0&&msg.api==="anthropic-messages"&&msg.provider===managedProvider&&isAnthropicEffort(msg.providerThinkingLevel)&&assistantLevels.set(messageIndex,msg.providerThinkingLevel)}else if(msg.role==="toolResult"){let toolResults=[],errorImages=[],j=i;for(;j<transformedMessages.length&&transformedMessages[j].role==="toolResult";){let toolMsg=transformedMessages[j],split=splitErrorToolResultImages(toolMsg);toolResults.push(convertToolResult(toolMsg,split?.content)),split&&errorImages.push({type:"text",text:split.caption},...split.images.map(convertImageBlock)),j++}i=j-1,params.push({role:"user",content:[...toolResults,...errorImages]})}}if(flushPendingSystemMessages(),cacheControl&&params.length>0){let lastMessage=params[params.length-1];if(lastMessage.role==="user"||lastMessage.role==="system")if(Array.isArray(lastMessage.content)){let lastBlock=lastMessage.content[lastMessage.content.length-1];lastBlock&&(lastBlock.type==="text"||lastBlock.type==="image"||lastBlock.type==="tool_result"||lastBlock.type==="tool_addition"||lastBlock.type==="tool_removal")&&(lastBlock.cache_control=cacheControl)}else typeof lastMessage.content=="string"&&(lastMessage.content=[{type:"text",text:lastMessage.content,cache_control:cacheControl}])}return{messages:params,assistantLevels}}function isAnthropicEffort(value){return value==="low"||value==="medium"||value==="high"||value==="xhigh"||value==="max"}function insertThinkingLevelMessages(converted,activeEffort){let messages=[];for(let index=0;index<converted.messages.length;index++){let historicalEffort=converted.assistantLevels.get(index);historicalEffort!==void 0&&messages.push({role:"system",content:[],output_config:{effort:historicalEffort}}),messages.push(converted.messages[index])}return messages.push({role:"system",content:[],output_config:{effort:activeEffort}}),messages}function shouldUseFineGrainedToolStreamingBeta(model,context){return getCurrentTools(context.messages).length>0&&!getAnthropicCompat(model).supportsEagerToolInputStreaming}var ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties"]),ANTHROPIC_STRICT_STRING_FORMATS=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),isAnthropicStrictUnsupportedKeyword=(key,value)=>ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS.has(key)?!0:key==="minItems"?value!==0&&value!==1:key==="format"?typeof value!="string"||!ANTHROPIC_STRICT_STRING_FORMATS.has(value):!1;function convertTools(tools,isOAuthToken2,supportsEagerToolInputStreaming,supportsStrictTools,cacheControl,disablePreferredStrictTools=!1){return tools?tools.map((tool,index)=>{let strict=disablePreferredStrictTools&&prefersJsonSchemaStrictSampling(tool)?void 0:resolveJsonSchemaStrictSampling(tool,supportsStrictTools,isAnthropicStrictUnsupportedKeyword),parameters=getJsonSchemaToolParameters(tool,strict),schema=parameters,legacyInputSchema={type:"object",properties:schema.properties??{},required:schema.required??[],...schema.$defs===void 0?{}:{$defs:schema.$defs},...schema.definitions===void 0?{}:{definitions:schema.definitions}},inputSchema=strict===!0?{...parameters,...legacyInputSchema}:legacyInputSchema;return{name:isOAuthToken2?toClaudeCodeName(tool.name):tool.name,description:tool.description,...supportsEagerToolInputStreaming?{eager_input_streaming:!0}:{},...strict===!0?{strict:!0}:{},input_schema:inputSchema,...cacheControl&&index===tools.length-1?{cache_control:cacheControl}:{}}}):[]}function mapStopReason(reason,stopDetails){switch(reason){case"end_turn":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:stopDetails?.explanation||"The model refused to complete the request"};case"pause_turn":return{stopReason:"stop"};case"stop_sequence":return{stopReason:"stop"};case"sensitive":return{stopReason:"error",errorMessage:"Provider stopped with: sensitive"};default:throw new Error(`Unhandled stop reason: ${reason}`)}}export{stream,streamSimple};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{convertResponsesMessages,convertResponsesTools,getResponsesToolSupport,processResponsesStream}from"./chunk-PDENR63J.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-TMTOQ7H7.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{AzureOpenAI}from"./chunk-A3Y7H47A.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,resolveSamplingParams}from"./chunk-35EHANXE.js";import"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-WN2D4UD4.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import"./chunk-FFMDRXC4.js";import"./chunk-7DDKXS2Q.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-JAJLG57O.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-77CRE5SV.js";import"./chunk-JXWJOIH4.js";var AZURE_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode","azure"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16;function formatAzureOpenAIError(error){return formatProviderError(normalizeProviderError(error),"Azure OpenAI API error")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let deploymentName=resolveDeploymentName(model,options),output={role:"assistant",content:[],api:"azure-openai-responses",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),params=buildParams(model,normalizedContext,options,deploymentName,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{onProviderStreamEvent:options?.onProviderStreamEvent,grammarToolInputProperties}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Azure OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatAzureOpenAIError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function createClient(model,apiKey,options){let headers={...getIdentityHeaders(model,options?.identity),...model.headers};options?.headers&&Object.assign(headers,options.headers);let{baseUrl,apiVersion}=resolveAzureConfig(model,options);return new AzureOpenAI({apiKey,apiVersion,dangerouslyAllowBrowser:!0,fetch:options?.fetch,defaultHeaders:headers,baseURL:baseUrl})}function buildParams(model,context,options,deploymentName,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,transcriptTools=resolveTranscriptTools(context.messages,getResponsesToolSupport({supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch})),messages=convertResponsesMessages(model,context,AZURE_TOOL_CALL_PROVIDERS,{grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1}}),params={model:deploymentName,input:messages,stream:!0,prompt_cache_key:model.compat?.promptCacheKeyMode==="disabled"?void 0:clampOpenAIPromptCacheKey(options?.sessionId),store:!1};options?.maxTokens&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&(params.temperature=options?.temperature),transcriptTools.requestTools.length>0&&(params.tools=convertResponsesTools(transcriptTools.requestTools,{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice);let reasoningEffort=options?.reasoningEffort??(options?.reasoningSummary?"medium":void 0);if(model.reasoning)if(reasoningEffort){let effort=options?.reasoningEffort?model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:reasoningEffort;params.reasoning={effort,summary:options?.reasoningSummary||"auto"},params.include=["reasoning.encrypted_content"]}else model.thinkingLevelMap?.off!==null&&(params.reasoning={effort:model.thinkingLevelMap?.off??"none"});let samplingParams=resolveSamplingParams(model,reasoningEffort??"off",options?.samplingParams);return samplingParams&&Object.assign(params,samplingParams),params}export{stream,streamSimple};