@averyyy/pi-coding-agent 1.5.0-piclient.3 → 1.5.2-piclient.1

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 (359) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/dist/bundle/chunks/anthropic-messages-KT6DV7MK.js +6 -0
  3. package/dist/bundle/chunks/{azure-openai-responses-M725JFGO.js → azure-openai-responses-E2Z734ES.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +3 -3
  5. package/dist/bundle/chunks/chunk-27POX4KP.js +82 -0
  6. package/dist/bundle/chunks/{chunk-NWAB6VML.js → chunk-BWM3ZYWS.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-GJFZM2RZ.js → chunk-D2CMHQWH.js} +9 -9
  8. package/dist/bundle/chunks/chunk-DGLLW4Y4.js +1590 -0
  9. package/dist/bundle/chunks/{chunk-N4CTF6DK.js → chunk-ECEUFETK.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-3UW3IQIY.js → chunk-FA5D3PPT.js} +1 -1
  11. package/dist/bundle/chunks/chunk-GFUN2N5K.js +2 -0
  12. package/dist/bundle/chunks/{chunk-OW4KH7CI.js → chunk-H36DQSY7.js} +1 -1
  13. package/dist/bundle/chunks/chunk-IEBK4HQA.js +2 -0
  14. package/dist/bundle/chunks/chunk-IYMNLY6C.js +4 -0
  15. package/dist/bundle/chunks/chunk-M4NMEBFE.js +2 -0
  16. package/dist/bundle/chunks/chunk-P4REYYCM.js +55 -0
  17. package/dist/bundle/chunks/chunk-RRE46THK.js +35 -0
  18. package/dist/bundle/chunks/chunk-RZHIIJ2O.js +2 -0
  19. package/dist/bundle/chunks/chunk-SHIWNICN.js +8 -0
  20. package/dist/bundle/chunks/{chunk-WATJAG5U.js → chunk-TCESBBFS.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-GO33PKBT.js → chunk-V5KN6SNQ.js} +1 -1
  22. package/dist/bundle/chunks/chunk-V7WCKBVO.js +19 -0
  23. package/dist/bundle/chunks/{chunk-OXKIVFVM.js → chunk-VZFAYNKC.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-JM6XUN2B.js → chunk-YAD6BXOQ.js} +5 -1
  25. package/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
  26. package/dist/bundle/chunks/{cli-2Q4CKMZK.js → cli-OTDOMRGW.js} +7 -7
  27. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-JEJELFEJ.js → cloudflare-workers-ai-system-one-6TWKBBSR.js} +1 -1
  28. package/dist/bundle/chunks/codemode-worker.js +2 -0
  29. package/dist/bundle/chunks/{easter-egg-3d-UEH5CVEM.js → easter-egg-3d-FREKSIW6.js} +1 -1
  30. package/dist/bundle/chunks/{execute-BOGNP5CQ.js → execute-MJMW76MP.js} +5 -3
  31. package/dist/bundle/chunks/github-copilot.js +1 -1
  32. package/dist/bundle/chunks/google-antigravity-runtime.js +2 -2
  33. package/dist/bundle/chunks/{google-generative-ai-UTHMOBSC.js → google-generative-ai-YSOYXY5K.js} +1 -1
  34. package/dist/bundle/chunks/{google-vertex-MKY2BEE7.js → google-vertex-X3ELXR2J.js} +1 -1
  35. package/dist/bundle/chunks/{llama-cpp-classify-CYHVVBOQ.js → llama-cpp-classify-R6PVLK5I.js} +1 -1
  36. package/dist/bundle/chunks/{mistral-conversations-U2CRJEWX.js → mistral-conversations-J4IL2HMK.js} +1 -1
  37. package/dist/bundle/chunks/openai-codex-responses-GULSUKQ4.js +10 -0
  38. package/dist/bundle/chunks/{openai-completions-VPNLDI5K.js → openai-completions-ZGWBSKNR.js} +3 -3
  39. package/dist/bundle/chunks/{openai-decisions-UZ6HF7LF.js → openai-decisions-BU2ER6AQ.js} +1 -1
  40. package/dist/bundle/chunks/openai-responses-WDSDROXC.js +4 -0
  41. package/dist/bundle/chunks/{openrouter-images-P5CYCO4P.js → openrouter-images-MK6H7N26.js} +1 -1
  42. package/dist/bundle/chunks/{pi-messages-XPX326L5.js → pi-messages-7PPZFV3U.js} +1 -1
  43. package/dist/bundle/chunks/{runtime-2Z3FBQRD.js → runtime-X3ZHEI2F.js} +1 -1
  44. package/dist/bundle/chunks/{typesafe-system-one-NKVLMGFF.js → typesafe-system-one-LXDZKNJW.js} +1 -1
  45. package/dist/bundle/chunks/virtual-modules-J7Z5J7IR.js +2 -0
  46. package/dist/bundle/cli-runtime.js +1 -1
  47. package/dist/bundle/index.js +1 -1
  48. package/dist/bundle/rpc-entry.js +1 -1
  49. package/dist/cli/args.js +1 -1
  50. package/dist/cli/args.js.map +1 -1
  51. package/dist/cli/auth-command.d.ts.map +1 -1
  52. package/dist/cli/auth-command.js +26 -2
  53. package/dist/cli/auth-command.js.map +1 -1
  54. package/dist/cli/auth-login.d.ts +15 -0
  55. package/dist/cli/auth-login.d.ts.map +1 -0
  56. package/dist/cli/auth-login.js +234 -0
  57. package/dist/cli/auth-login.js.map +1 -0
  58. package/dist/cli/auth-logout.d.ts +14 -0
  59. package/dist/cli/auth-logout.d.ts.map +1 -0
  60. package/dist/cli/auth-logout.js +74 -0
  61. package/dist/cli/auth-logout.js.map +1 -0
  62. package/dist/cli/auth-terminal.d.ts +17 -0
  63. package/dist/cli/auth-terminal.d.ts.map +1 -0
  64. package/dist/cli/auth-terminal.js +63 -0
  65. package/dist/cli/auth-terminal.js.map +1 -0
  66. package/dist/cli/config-selector.d.ts.map +1 -1
  67. package/dist/cli/config-selector.js +3 -1
  68. package/dist/cli/config-selector.js.map +1 -1
  69. package/dist/core/agent-session-runtime.d.ts +5 -0
  70. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  71. package/dist/core/agent-session-runtime.js +17 -2
  72. package/dist/core/agent-session-runtime.js.map +1 -1
  73. package/dist/core/agent-session.d.ts +25 -6
  74. package/dist/core/agent-session.d.ts.map +1 -1
  75. package/dist/core/agent-session.js +137 -54
  76. package/dist/core/agent-session.js.map +1 -1
  77. package/dist/core/auth-storage.d.ts.map +1 -1
  78. package/dist/core/auth-storage.js +3 -2
  79. package/dist/core/auth-storage.js.map +1 -1
  80. package/dist/core/bash-executor.d.ts.map +1 -1
  81. package/dist/core/bash-executor.js +3 -1
  82. package/dist/core/bash-executor.js.map +1 -1
  83. package/dist/core/cache-warmer.d.ts +4 -37
  84. package/dist/core/cache-warmer.d.ts.map +1 -1
  85. package/dist/core/cache-warmer.js +11 -97
  86. package/dist/core/cache-warmer.js.map +1 -1
  87. package/dist/core/compaction/utils.d.ts.map +1 -1
  88. package/dist/core/compaction/utils.js +2 -1
  89. package/dist/core/compaction/utils.js.map +1 -1
  90. package/dist/core/extensions/index.d.ts +1 -1
  91. package/dist/core/extensions/index.d.ts.map +1 -1
  92. package/dist/core/extensions/index.js.map +1 -1
  93. package/dist/core/extensions/loader.d.ts.map +1 -1
  94. package/dist/core/extensions/loader.js +10 -5
  95. package/dist/core/extensions/loader.js.map +1 -1
  96. package/dist/core/extensions/runner.d.ts +1 -0
  97. package/dist/core/extensions/runner.d.ts.map +1 -1
  98. package/dist/core/extensions/runner.js +9 -1
  99. package/dist/core/extensions/runner.js.map +1 -1
  100. package/dist/core/extensions/types.d.ts +28 -6
  101. package/dist/core/extensions/types.d.ts.map +1 -1
  102. package/dist/core/extensions/types.js.map +1 -1
  103. package/dist/core/keybindings.d.ts +2 -2
  104. package/dist/core/keybindings.js +1 -1
  105. package/dist/core/keybindings.js.map +1 -1
  106. package/dist/core/mcp-servers.d.ts +12 -37
  107. package/dist/core/mcp-servers.d.ts.map +1 -1
  108. package/dist/core/mcp-servers.js +42 -121
  109. package/dist/core/mcp-servers.js.map +1 -1
  110. package/dist/core/model-config.d.ts +52 -0
  111. package/dist/core/model-config.d.ts.map +1 -1
  112. package/dist/core/model-resolver.d.ts.map +1 -1
  113. package/dist/core/model-resolver.js +20 -19
  114. package/dist/core/model-resolver.js.map +1 -1
  115. package/dist/core/model-runtime.d.ts +2 -0
  116. package/dist/core/model-runtime.d.ts.map +1 -1
  117. package/dist/core/model-runtime.js +8 -4
  118. package/dist/core/model-runtime.js.map +1 -1
  119. package/dist/core/package-manager.d.ts +10 -1
  120. package/dist/core/package-manager.d.ts.map +1 -1
  121. package/dist/core/package-manager.js +50 -5
  122. package/dist/core/package-manager.js.map +1 -1
  123. package/dist/core/pi-ai-schemas.d.ts +4 -0
  124. package/dist/core/pi-ai-schemas.d.ts.map +1 -1
  125. package/dist/core/pi-server-client.d.ts.map +1 -1
  126. package/dist/core/pi-server-client.js +1 -0
  127. package/dist/core/pi-server-client.js.map +1 -1
  128. package/dist/core/preferred-providers.d.ts +17 -0
  129. package/dist/core/preferred-providers.d.ts.map +1 -0
  130. package/dist/core/preferred-providers.js +24 -0
  131. package/dist/core/preferred-providers.js.map +1 -0
  132. package/dist/core/prompt-templates.d.ts.map +1 -1
  133. package/dist/core/prompt-templates.js +18 -2
  134. package/dist/core/prompt-templates.js.map +1 -1
  135. package/dist/core/provider-composer.d.ts.map +1 -1
  136. package/dist/core/provider-composer.js +3 -1
  137. package/dist/core/provider-composer.js.map +1 -1
  138. package/dist/core/provider-matching.d.ts +6 -0
  139. package/dist/core/provider-matching.d.ts.map +1 -0
  140. package/dist/core/provider-matching.js +8 -0
  141. package/dist/core/provider-matching.js.map +1 -0
  142. package/dist/core/radius-mcp.d.ts +13 -0
  143. package/dist/core/radius-mcp.d.ts.map +1 -0
  144. package/dist/core/radius-mcp.js +29 -0
  145. package/dist/core/radius-mcp.js.map +1 -0
  146. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  147. package/dist/core/remote-catalog-provider.js +2 -0
  148. package/dist/core/remote-catalog-provider.js.map +1 -1
  149. package/dist/core/runtime-credentials.d.ts +8 -0
  150. package/dist/core/runtime-credentials.d.ts.map +1 -1
  151. package/dist/core/runtime-credentials.js +15 -1
  152. package/dist/core/runtime-credentials.js.map +1 -1
  153. package/dist/core/session-cwd.d.ts +7 -0
  154. package/dist/core/session-cwd.d.ts.map +1 -1
  155. package/dist/core/session-cwd.js +9 -1
  156. package/dist/core/session-cwd.js.map +1 -1
  157. package/dist/core/settings-defaults.d.ts +1 -1
  158. package/dist/core/settings-defaults.d.ts.map +1 -1
  159. package/dist/core/settings-defaults.js +1 -1
  160. package/dist/core/settings-defaults.js.map +1 -1
  161. package/dist/core/tools/bash.d.ts +1 -6
  162. package/dist/core/tools/bash.d.ts.map +1 -1
  163. package/dist/core/tools/bash.js +34 -9
  164. package/dist/core/tools/bash.js.map +1 -1
  165. package/dist/core/tools/edit-diff.d.ts +23 -14
  166. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  167. package/dist/core/tools/edit-diff.js +182 -41
  168. package/dist/core/tools/edit-diff.js.map +1 -1
  169. package/dist/core/tools/edit.d.ts.map +1 -1
  170. package/dist/core/tools/edit.js +8 -7
  171. package/dist/core/tools/edit.js.map +1 -1
  172. package/dist/core/tools/find.d.ts.map +1 -1
  173. package/dist/core/tools/find.js +82 -36
  174. package/dist/core/tools/find.js.map +1 -1
  175. package/dist/core/tools/grep.d.ts +5 -3
  176. package/dist/core/tools/grep.d.ts.map +1 -1
  177. package/dist/core/tools/grep.js +87 -75
  178. package/dist/core/tools/grep.js.map +1 -1
  179. package/dist/core/tools/ls.d.ts.map +1 -1
  180. package/dist/core/tools/ls.js +2 -1
  181. package/dist/core/tools/ls.js.map +1 -1
  182. package/dist/core/tools/powershell.d.ts.map +1 -1
  183. package/dist/core/tools/powershell.js +15 -2
  184. package/dist/core/tools/powershell.js.map +1 -1
  185. package/dist/core/tools/read.d.ts +8 -0
  186. package/dist/core/tools/read.d.ts.map +1 -1
  187. package/dist/core/tools/read.js +141 -25
  188. package/dist/core/tools/read.js.map +1 -1
  189. package/dist/core/tools/truncate.d.ts +4 -14
  190. package/dist/core/tools/truncate.d.ts.map +1 -1
  191. package/dist/core/tools/truncate.js +23 -29
  192. package/dist/core/tools/truncate.js.map +1 -1
  193. package/dist/extensions/codemode/execute.js +4 -4
  194. package/dist/extensions/codemode/execute.js.map +1 -1
  195. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  196. package/dist/extensions/codemode/tool.js +34 -12
  197. package/dist/extensions/codemode/tool.js.map +1 -1
  198. package/dist/extensions/llama/client.d.ts +2 -0
  199. package/dist/extensions/llama/client.d.ts.map +1 -1
  200. package/dist/extensions/llama/client.js +23 -2
  201. package/dist/extensions/llama/client.js.map +1 -1
  202. package/dist/extensions/llama/ui.d.ts.map +1 -1
  203. package/dist/extensions/llama/ui.js +15 -3
  204. package/dist/extensions/llama/ui.js.map +1 -1
  205. package/dist/extensions/mcp/cli.d.ts +2 -0
  206. package/dist/extensions/mcp/cli.d.ts.map +1 -1
  207. package/dist/extensions/mcp/cli.js +49 -14
  208. package/dist/extensions/mcp/cli.js.map +1 -1
  209. package/dist/extensions/mcp/config.d.ts.map +1 -1
  210. package/dist/extensions/mcp/config.js +4 -7
  211. package/dist/extensions/mcp/config.js.map +1 -1
  212. package/dist/extensions/mcp/index.d.ts.map +1 -1
  213. package/dist/extensions/mcp/index.js +4 -3
  214. package/dist/extensions/mcp/index.js.map +1 -1
  215. package/dist/extensions/mcp/oauth.d.ts +11 -49
  216. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  217. package/dist/extensions/mcp/oauth.js +56 -319
  218. package/dist/extensions/mcp/oauth.js.map +1 -1
  219. package/dist/extensions/mcp/resources.d.ts +1 -1
  220. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  221. package/dist/extensions/mcp/resources.js +4 -3
  222. package/dist/extensions/mcp/resources.js.map +1 -1
  223. package/dist/extensions/mcp/runtime.d.ts +4 -3
  224. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  225. package/dist/extensions/mcp/runtime.js +7 -5
  226. package/dist/extensions/mcp/runtime.js.map +1 -1
  227. package/dist/extensions/mcp/tools.d.ts +2 -23
  228. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  229. package/dist/extensions/mcp/tools.js +6 -58
  230. package/dist/extensions/mcp/tools.js.map +1 -1
  231. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  232. package/dist/extensions/tool-search/tool.js +18 -6
  233. package/dist/extensions/tool-search/tool.js.map +1 -1
  234. package/dist/index.d.ts +1 -1
  235. package/dist/index.d.ts.map +1 -1
  236. package/dist/index.js.map +1 -1
  237. package/dist/main.d.ts.map +1 -1
  238. package/dist/main.js +63 -11
  239. package/dist/main.js.map +1 -1
  240. package/dist/modes/interactive/components/branch-summary-message.d.ts +5 -1
  241. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  242. package/dist/modes/interactive/components/branch-summary-message.js +12 -4
  243. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  244. package/dist/modes/interactive/components/compaction-summary-message.d.ts +5 -1
  245. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  246. package/dist/modes/interactive/components/compaction-summary-message.js +12 -4
  247. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  248. package/dist/modes/interactive/components/custom-message.d.ts +5 -2
  249. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  250. package/dist/modes/interactive/components/custom-message.js +10 -3
  251. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  252. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  253. package/dist/modes/interactive/components/diff.js +11 -5
  254. package/dist/modes/interactive/components/diff.js.map +1 -1
  255. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  256. package/dist/modes/interactive/components/extension-selector.js +9 -1
  257. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  258. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  259. package/dist/modes/interactive/components/login-dialog.js +1 -18
  260. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  261. package/dist/modes/interactive/components/mermaid.d.ts +2 -1
  262. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  263. package/dist/modes/interactive/components/mermaid.js +25 -20
  264. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  265. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  266. package/dist/modes/interactive/components/model-selector.js +14 -6
  267. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  268. package/dist/modes/interactive/components/oauth-selector.d.ts +10 -3
  269. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  270. package/dist/modes/interactive/components/oauth-selector.js +32 -5
  271. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  272. package/dist/modes/interactive/components/provider-brand.d.ts +14 -0
  273. package/dist/modes/interactive/components/provider-brand.d.ts.map +1 -0
  274. package/dist/modes/interactive/components/provider-brand.js +66 -0
  275. package/dist/modes/interactive/components/provider-brand.js.map +1 -0
  276. package/dist/modes/interactive/components/radius-login-selector.d.ts +1 -2
  277. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
  278. package/dist/modes/interactive/components/radius-login-selector.js +6 -37
  279. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
  280. package/dist/modes/interactive/components/skill-invocation-message.d.ts +5 -1
  281. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  282. package/dist/modes/interactive/components/skill-invocation-message.js +12 -4
  283. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  284. package/dist/modes/interactive/components/tree-selector.d.ts +1 -0
  285. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  286. package/dist/modes/interactive/components/tree-selector.js +19 -10
  287. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  288. package/dist/modes/interactive/interactive-mode.d.ts +13 -1
  289. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  290. package/dist/modes/interactive/interactive-mode.js +164 -91
  291. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  292. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  293. package/dist/modes/interactive/theme/theme.js +4 -0
  294. package/dist/modes/interactive/theme/theme.js.map +1 -1
  295. package/dist/modes/print-mode.d.ts.map +1 -1
  296. package/dist/modes/print-mode.js +19 -10
  297. package/dist/modes/print-mode.js.map +1 -1
  298. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  299. package/dist/modes/rpc/rpc-mode.js +53 -23
  300. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  301. package/dist/package-manager-cli.d.ts.map +1 -1
  302. package/dist/package-manager-cli.js +39 -8
  303. package/dist/package-manager-cli.js.map +1 -1
  304. package/dist/utils/changelog.d.ts +2 -2
  305. package/dist/utils/changelog.d.ts.map +1 -1
  306. package/dist/utils/changelog.js +12 -6
  307. package/dist/utils/changelog.js.map +1 -1
  308. package/dist/utils/image-resize.d.ts.map +1 -1
  309. package/dist/utils/image-resize.js +3 -1
  310. package/dist/utils/image-resize.js.map +1 -1
  311. package/dist/utils/terminal-question.d.ts +8 -0
  312. package/dist/utils/terminal-question.d.ts.map +1 -0
  313. package/dist/utils/terminal-question.js +24 -0
  314. package/dist/utils/terminal-question.js.map +1 -0
  315. package/dist/utils/web-url.d.ts +12 -0
  316. package/dist/utils/web-url.d.ts.map +1 -0
  317. package/dist/utils/web-url.js +20 -0
  318. package/dist/utils/web-url.js.map +1 -0
  319. package/docs/cli.md +14 -1
  320. package/docs/extensions.md +27 -7
  321. package/docs/keybindings.md +1 -1
  322. package/docs/llama-cpp.md +5 -8
  323. package/docs/models-configuration.md +6 -1
  324. package/docs/models.md +2 -1
  325. package/docs/prompt-templates.md +1 -1
  326. package/docs/providers.md +1 -1
  327. package/docs/rpc.md +4 -2
  328. package/docs/sessions.md +7 -1
  329. package/docs/settings.md +1 -1
  330. package/docs/tui.md +1 -1
  331. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  332. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  333. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  334. package/examples/extensions/gondolin/package-lock.json +2 -2
  335. package/examples/extensions/gondolin/package.json +1 -1
  336. package/examples/extensions/plan-mode/index.ts +23 -13
  337. package/examples/extensions/plan-mode/utils.ts +42 -16
  338. package/examples/extensions/subagent/README.md +14 -11
  339. package/examples/extensions/subagent/index.ts +392 -171
  340. package/examples/extensions/with-deps/package-lock.json +2 -2
  341. package/examples/extensions/with-deps/package.json +1 -1
  342. package/examples/tsconfig.json +63 -35
  343. package/package.json +7 -7
  344. package/schemas/models.schema.json +29 -0
  345. package/schemas/settings.schema.json +1 -1
  346. package/dist/bundle/chunks/anthropic-messages-WU4RRDFO.js +0 -6
  347. package/dist/bundle/chunks/chunk-4RKLODCT.js +0 -2
  348. package/dist/bundle/chunks/chunk-7FMRLQ6P.js +0 -1590
  349. package/dist/bundle/chunks/chunk-G23G7KNC.js +0 -4
  350. package/dist/bundle/chunks/chunk-LTLKVIE2.js +0 -65
  351. package/dist/bundle/chunks/chunk-O5CTLHDX.js +0 -82
  352. package/dist/bundle/chunks/chunk-OV4EHN3Q.js +0 -2
  353. package/dist/bundle/chunks/chunk-PWQUNMKT.js +0 -4
  354. package/dist/bundle/chunks/chunk-UKVNB6C4.js +0 -2
  355. package/dist/bundle/chunks/chunk-USJZMAIR.js +0 -2
  356. package/dist/bundle/chunks/chunk-YH5RGRHQ.js +0 -7
  357. package/dist/bundle/chunks/openai-codex-responses-DK2NKO47.js +0 -10
  358. package/dist/bundle/chunks/openai-responses-S5QT5K5D.js +0 -4
  359. package/dist/bundle/chunks/virtual-modules-CTTKTI6Z.js +0 -2
package/CHANGELOG.md CHANGED
@@ -16,6 +16,8 @@
16
16
 
17
17
  ### Fixed
18
18
 
19
+ - Preserved queued image resizing across provisional message selection and delivery retries.
20
+ - Preserved Anthropic message threads through pi-server cache warming and tool-result continuations, and released provider state when server sessions are deleted.
19
21
  - Shared execution lifecycle state between TUI working indicators and event-triggered pi-server observer reports, including preparation failures, asynchronous completion handlers, branch summaries, and cancellation acknowledgement.
20
22
  - Closed session observers before runtime command exits and drained Windows handle cleanup.
21
23
  - Fixed steering and follow-up messages queued during manual pi-server compaction failing to send when compaction completed.
@@ -64,6 +66,137 @@
64
66
  - Preserved oversized-session chunked summarization and pi-server compaction recovery while adopting upstream canonical context projection and extension boundaries.
65
67
  - Preserved eligible provider prompt prefixes during compaction summaries, with explicit reasons when the existing chunked path is required.
66
68
 
69
+ ## [1.5.2] - 2026-11-10
70
+
71
+ ### New Features
72
+
73
+ - **Fork sessions whose folder is gone**: when a session's original folder was moved or deleted, you can now fork it into the current folder instead of only continuing, so later resumes no longer ask. See [Continue or switch sessions](docs/sessions.md#continue-or-switch-sessions).
74
+
75
+ ### Changed
76
+
77
+ - When a session's working directory no longer exists, for example after the project folder was renamed, interactive mode now offers `Continue`, `Fork`, or `Cancel` instead of only continuing. `Continue` runs the session in the current directory without storing the choice, as before; `Fork` copies it into the current directory as a new session with a new ID, like `--fork`, so the next resume no longer asks. This applies at startup (`--session`, `--resume`), to `/resume`, to `/import`, and to `ctx.switchSession()` from extensions ([#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))
78
+
79
+ ### Fixed
80
+
81
+ - 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))
82
+ - Fixed Anthropic OAuth requests reporting an outdated Claude Code version
83
+
84
+ ## [1.5.1] - 2026-11-09
85
+
86
+ ### New Features
87
+
88
+ - **Shell login and logout**: use `pi auth login <provider>` and `pi auth logout <provider>` without starting a session, with API-key and no-browser sign-in options. See [Credential commands](docs/cli.md#credential-commands).
89
+ - **Idle prompt cache warming**: eligible caches now stay warm for up to 30 minutes between runs when a refresh is expected to pay for itself. See [`cacheWarming`](docs/settings.md#model-and-thinking).
90
+ - **Anthropic message threads**: requests send only new messages while the server continues the conversation, with full-request fallback when earlier context changes. See [Anthropic compatibility](docs/models-configuration.md#anthropic-messages).
91
+ - **Richer Mermaid diagrams**: pie charts, author-defined styles, clickable labels on supported terminals, and diagrams in expanded branch and compaction summaries. See [Display settings](docs/settings.md#terminal-and-display) and [Markdown transformers](docs/extensions.md#piregistermarkdowntransformertransformer-options).
92
+ - **GitHub Copilot classifiers**: call Microsoft-Decision-1 through codemode `models.classify()` for typed decisions and probabilities. See [Use classifier models](docs/models.md#use-classifier-models).
93
+ - **Package update summaries**: `pi update --extensions` reports each package's npm version or git commit change and distinguishes unchanged, skipped, and warned updates. See [Update Pi or packages](docs/cli.md#update-pi-or-packages).
94
+
95
+ ### Breaking Changes
96
+
97
+ - 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))
98
+ - 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))
99
+
100
+ ### Added
101
+
102
+ - `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))
103
+ - 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))
104
+ - `pi.registerMarkdownTransformer()` takes an optional `{ messageTypes }` that selects the Markdown surfaces a transformer runs on. Besides user, assistant, and thinking Markdown, transformers can now opt into `custom` (custom messages and skill blocks), `summary` (branch and compaction summaries), and `changelog` (What's New, `/changelog`, the Extension Updates notice, and the Update Available note). Without options a transformer runs on user, assistant, and thinking Markdown as before. The built-in Mermaid renderer now also draws diagrams in expanded branch and compaction summaries
105
+ - `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`
106
+ - `ctx.ui.custom()` overlays now honor the `blocked` option: pi reports blocked program status (OSC 7501) from when the overlay is shown until it calls `done()`, also while it is hidden with `setHidden()`. Closing one overlay keeps other open questions blocked ([#11816](https://github.com/earendil-works/pi/issues/11816))
107
+ - 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))
108
+ - 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))
109
+ - 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))
110
+ - 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))
111
+ - Added syntax highlighting for Dart, Nix, Groovy, and Gradle files in read and write views ([#11643](https://github.com/earendil-works/pi/issues/11643))
112
+ - Added GLM 5.3 to the Qwen Token Plan Individual model allowlist ([#11658](https://github.com/earendil-works/pi/issues/11658))
113
+ - 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
114
+
115
+ ### Changed
116
+
117
+ - The default model for the `anthropic` provider is now Claude Opus 5.5 (`claude-opus-5-5`) instead of Claude Opus 4.8
118
+ - 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`
119
+ - `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
120
+ - Consecutive cache warms now show as one `Cache warmed: $<total>` line with the cumulative cost instead of one line per warm
121
+ - The OpenAI Codex provider is shown as "OpenAI Codex" again instead of "OpenAI Codex (legacy)" in `/login` and the model selector
122
+ - The `/login` and `/logout` provider lists and `/login <provider>` completions now show the preferred partners Radius and OpenRouter first, then all other providers alphabetically. In the provider lists, partners are marked with `✦`, the selected Radius row shimmers in the Radius logo colors and the selected OpenRouter row glows in OpenRouter's brand color (lime on dark themes, violet on light themes)
123
+ - Upgraded terminal Mermaid rendering to support more diagram types, including pie charts, author-defined styles, and clickable labels on terminals with hyperlink support ([#8158](https://github.com/earendil-works/pi/pull/8158) by [@xl0](https://github.com/xl0))
124
+
125
+ ### Fixed
126
+
127
+ - 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))
128
+ - 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))
129
+ - 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))
130
+ - 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))
131
+ - 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.
132
+ - 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"
133
+ - 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))
134
+ - 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))
135
+ - 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))
136
+ - 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))
137
+ - 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))
138
+ - 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))
139
+ - 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))
140
+ - 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))
141
+ - 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))
142
+ - Fixed Ctrl+P not switching to the only model in scope (or the only available model) when the active model is a different one; it showed "Only one model in scope" instead. Cycling forward from a model outside the scope now also selects the first scoped model instead of skipping it ([#11806](https://github.com/earendil-works/pi/issues/11806))
143
+ - Fixed `/reload` and session switches leaving extension overlays on screen when an extension had more than one `ctx.ui.custom({ overlay: true })` open: only the topmost overlay was removed, and the others kept focus and input although the extension that opened them was gone. All extension overlays, including hidden ones, are now removed and disposed; pi's own overlays stay open
144
+ - Fixed `/mcp` sign-in staying on "Connecting…" for minutes after a successful browser sign-in, with Ctrl+C doing nothing: pi waited for the browser to drop an unused connection to the OAuth callback port. The callback server now closes remaining connections when it shuts down ([#11311](https://github.com/earendil-works/pi/issues/11311))
145
+ - 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))
146
+ - 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))
147
+ - 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))
148
+ - 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))
149
+ - Fixed `ctrl+o` not expanding or collapsing the output of `!` and `!!` commands run while the agent is working. New `!`/`!!` output now starts in the current expand state, the output no longer disappears when a steering or follow-up message is queued, and it moves into the chat when the agent finishes instead of on the next submitted message ([#11875](https://github.com/earendil-works/pi/issues/11875))
150
+ - 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))
151
+ - Fixed inline images in fullscreen mode showing only their first row in Orca, while regular mode showed them in full. Fullscreen now draws Kitty images after the rows they cover on every terminal, as it already did for WezTerm ([#11835](https://github.com/earendil-works/pi/issues/11835))
152
+ - 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))
153
+ - Fixed the Windows installer (`irm https://pi.dev/install.ps1 | iex`) aborting with `NativeCommandError` in Windows PowerShell 5.1 when npm or Node.js printed any warning, for example `npm warn Unknown user config` from an unknown `.npmrc` key. It failed before the action menu when migrating an npm installation, and during managed installs. An invalid `managed-install.json` also aborted the installer instead of being reported ([#11944](https://github.com/earendil-works/pi/issues/11944))
154
+ - 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
155
+ - 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))
156
+ - Fixed deleting a paste marker with Backspace corrupting later short markers such as `[paste #2]`, causing the marker text to be submitted instead of its pasted content ([#11923](https://github.com/earendil-works/pi/issues/11923))
157
+ - 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))
158
+ - 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))
159
+ - Fixed the model selector and llama.cpp Hugging Face search moving the selection when a background catalog refresh or search result arrives ([#9109](https://github.com/earendil-works/pi/issues/9109))
160
+ - Fixed internal cursor markers leaking into terminal output, including with multiple markers or horizontally clipped content ([#9441](https://github.com/earendil-works/pi/pull/9441) by [@muyiyr](https://github.com/muyiyr))
161
+ - 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))
162
+ - Fixed large pasted text being replaced by literal paste markers when switching editors, opening custom UI, or restoring queued messages ([#10146](https://github.com/earendil-works/pi/pull/10146) by [@w-winter](https://github.com/w-winter))
163
+ - 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))
164
+ - 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))
165
+ - 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))
166
+ - Fixed the plan-mode extension example missing completion markers in thinking blocks and common completion phrases, dropping formatted or long plan steps, and sending an extra model turn to acknowledge completion ([#7950](https://github.com/earendil-works/pi/pull/7950) by [@giannisCKS](https://github.com/giannisCKS))
167
+ - Fixed OpenAI Responses requests sending `session_id` instead of the documented `session-id` affinity header ([#11639](https://github.com/earendil-works/pi/issues/11639))
168
+ - 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))
169
+ - 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))
170
+ - 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))
171
+ - Fixed the session-tree search cursor not being shown or positioned for input methods ([#9157](https://github.com/earendil-works/pi/pull/9157) by [@Perlence](https://github.com/Perlence))
172
+ - 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))
173
+ - Fixed rendered edit diffs losing shared indentation when a change inserted text at the start of a line ([#9274](https://github.com/earendil-works/pi/pull/9274) by [@dannote](https://github.com/dannote))
174
+ - Fixed `!` and `!!` commands omitting the truncation notice and full-output file link when earlier output chunks had been discarded ([#10165](https://github.com/earendil-works/pi/pull/10165) by [@acmerfight](https://github.com/acmerfight))
175
+ - Fixed extension selection dialogs growing beyond the terminal height; they now show a scrolling window of up to ten options ([#11072](https://github.com/earendil-works/pi/pull/11072) by [@DivineDominion](https://github.com/DivineDominion))
176
+ - Fixed `pi config` ignoring custom keybindings from `keybindings.json` ([#11651](https://github.com/earendil-works/pi/issues/11651))
177
+ - 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))
178
+ - 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))
179
+ - Fixed Ctrl+V not pasting clipboard images or text on Windows and WSL; both Ctrl+V and Alt+V are now default paste shortcuts there ([#11765](https://github.com/earendil-works/pi/issues/11765))
180
+ - Fixed llama.cpp connection errors omitting the server URL and underlying network error ([#11745](https://github.com/earendil-works/pi/issues/11745))
181
+ - Fixed Alacritty hyperlinks not being enabled when `TERM_PROGRAM` is unset; detection now also uses `TERM` and `ALACRITTY_WINDOW_ID` ([#11767](https://github.com/earendil-works/pi/issues/11767))
182
+ - 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))
183
+ - 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))
184
+ - 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))
185
+ - 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.
186
+ - 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))
187
+ - 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))
188
+ - 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))
189
+ - 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))
190
+ - Fixed Markdown displaying HTML comments (`<!-- ... -->`) as visible text ([#11710](https://github.com/earendil-works/pi/issues/11710))
191
+ - 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))
192
+ - 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))
193
+ - 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))
194
+ - 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))
195
+ - 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))
196
+ - 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))
197
+ - 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))
198
+ - 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))
199
+
67
200
  ## [1.5.0] - 2026-11-02
68
201
 
69
202
  ### New Features
@@ -132,6 +265,7 @@
132
265
  - 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))
133
266
  - 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))
134
267
  - 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))
268
+ - 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))
135
269
  - Fixed tool rows and streamed answers highlighting the same code again on every redraw. A running codemode row highlighted its whole script on every progress update and timer tick, a complete `write` row its whole file on every update and expand toggle, a streamed `write` its first 50 lines on every delta, and a streamed answer every earlier code block on every delta. Rows now reuse their last highlighting until the code, theme, or loaded grammars change, and assistant messages keep their rendered Markdown blocks while streaming ([#10971](https://github.com/earendil-works/pi/issues/10971))
136
270
  - 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))
137
271
  - 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))
@@ -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-M4NMEBFE.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{withCauseDetail}from"./chunk-RZHIIJ2O.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-IYMNLY6C.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders,getSystemMessageText,renderSystemMessageUpdate}from"./chunk-V5KN6SNQ.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};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{convertResponsesMessages,convertResponsesTools,getResponsesToolSupport,processResponsesStream}from"./chunk-3UW3IQIY.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{formatProviderError,normalizeProviderError}from"./chunk-OV4EHN3Q.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{buildBaseOptions,createGrammarToolInputProperties,resolveSamplingParams}from"./chunk-4RKLODCT.js";import"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import"./chunk-7DDKXS2Q.js";import"./chunk-FFMDRXC4.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-G23G7KNC.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-GO33PKBT.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: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};
2
+ import{convertResponsesMessages,convertResponsesTools,getResponsesToolSupport,processResponsesStream}from"./chunk-FA5D3PPT.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-M4NMEBFE.js";import"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{formatProviderError,normalizeProviderError}from"./chunk-RZHIIJ2O.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import"./chunk-FFMDRXC4.js";import"./chunk-7DDKXS2Q.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-IYMNLY6C.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-V5KN6SNQ.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};