@maxmo74/pi-coding-agent 1.5.2-max.15 → 1.7.0-max.17

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 (419) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/LICENSE +1 -1
  3. package/README.md +1 -1
  4. package/dist/bundle/chunks/anthropic-messages-VOAE66ME.js +3 -0
  5. package/dist/bundle/chunks/azure-openai-responses-FWQRNMCY.js +2 -0
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +6 -6
  7. package/dist/bundle/chunks/chunk-2BKJ4UF2.js +6 -0
  8. package/dist/bundle/chunks/{chunk-RKNK4Y6L.js → chunk-2HV66XRA.js} +1 -1
  9. package/dist/bundle/chunks/chunk-7TLS4DNZ.js +30 -0
  10. package/dist/bundle/chunks/{chunk-FMPAMX2W.js → chunk-AIIDHDL2.js} +1 -1
  11. package/dist/bundle/chunks/chunk-ARDROFM7.js +20 -0
  12. package/dist/bundle/chunks/{chunk-36QC74V4.js → chunk-D5E4JUBX.js} +1 -1
  13. package/dist/bundle/chunks/chunk-D5U74ZAG.js +2 -0
  14. package/dist/bundle/chunks/{chunk-BAC3QPNW.js → chunk-E3GEPN3H.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-4UNPP53I.js → chunk-G5K7SYL7.js} +2 -2
  16. package/dist/bundle/chunks/chunk-GBB3EUD7.js +16 -0
  17. package/dist/bundle/chunks/chunk-GMDZZCKH.js +2 -0
  18. package/dist/bundle/chunks/{chunk-AUUCDC7R.js → chunk-HFTJRRFR.js} +2 -2
  19. package/dist/bundle/chunks/chunk-INODY4DR.js +2 -0
  20. package/dist/bundle/chunks/{chunk-WL4TUXY7.js → chunk-IOF7AZCL.js} +1 -1
  21. package/dist/bundle/chunks/chunk-J35HXFD7.js +2 -0
  22. package/dist/bundle/chunks/{chunk-COKMCNCW.js → chunk-KPWXWGGJ.js} +1 -1
  23. package/dist/bundle/chunks/chunk-LWG2CUTI.js +31 -0
  24. package/dist/bundle/chunks/chunk-MDJ5LWZA.js +44 -0
  25. package/dist/bundle/chunks/{chunk-VKJQ6CME.js → chunk-O5MXS5TI.js} +1 -1
  26. package/dist/bundle/chunks/chunk-OVXT2WQH.js +2 -0
  27. package/dist/bundle/chunks/{chunk-M6TSYZBS.js → chunk-PADKDPJN.js} +128 -130
  28. package/dist/bundle/chunks/chunk-PST3NXKM.js +2 -0
  29. package/dist/bundle/chunks/chunk-S2GRKWHT.js +14 -0
  30. package/dist/bundle/chunks/{chunk-FF6XOTWB.js → chunk-V7D5E4XS.js} +17 -15
  31. package/dist/bundle/chunks/chunk-Z2XZSUHM.js +2 -0
  32. package/dist/bundle/chunks/{cli-2MK3TR7P.js → cli-OH5BEVHD.js} +1 -1
  33. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-Z73UPEZ7.js +2 -0
  34. package/dist/bundle/chunks/{easter-egg-3d-GEVPKQF6.js → easter-egg-3d-BOWYTYMI.js} +1 -1
  35. package/dist/bundle/chunks/{execute-L2EEDV3L.js → execute-UXTJZEKY.js} +3 -3
  36. package/dist/bundle/chunks/github-copilot.js +1 -1
  37. package/dist/bundle/chunks/google-generative-ai-VI7CGXA2.js +2 -0
  38. package/dist/bundle/chunks/google-vertex-UGCMSJWH.js +2 -0
  39. package/dist/bundle/chunks/{llama-cpp-classify-EJXCQRUQ.js → llama-cpp-classify-SKDW7RUG.js} +2 -2
  40. package/dist/bundle/chunks/mistral-conversations-F2GKIAZI.js +4 -0
  41. package/dist/bundle/chunks/openai-codex-responses-B54DADY4.js +2 -0
  42. package/dist/bundle/chunks/openai-completions-5UNXROMA.js +7 -0
  43. package/dist/bundle/chunks/{openai-decisions-F66BDLOM.js → openai-decisions-IN2F5D4R.js} +1 -1
  44. package/dist/bundle/chunks/openai-responses-2567WJBU.js +4 -0
  45. package/dist/bundle/chunks/openrouter-images-MPCL4RTO.js +2 -0
  46. package/dist/bundle/chunks/pi-decision-GZ2BG2JB.js +2 -0
  47. package/dist/bundle/chunks/pi-image-CXEQM6AW.js +2 -0
  48. package/dist/bundle/chunks/pi-messages-PDCTBGXV.js +2 -0
  49. package/dist/bundle/chunks/{runtime-J5ZSBGTX.js → runtime-JESTW74H.js} +1 -1
  50. package/dist/bundle/chunks/typesafe-system-one-6M47QHZX.js +2 -0
  51. package/dist/bundle/chunks/virtual-modules-QBVXFHBM.js +2 -0
  52. package/dist/bundle/cli-runtime.js +1 -1
  53. package/dist/bundle/index.js +1 -1
  54. package/dist/bundle/rpc-entry.js +1 -1
  55. package/dist/cli/agent-dir-arg.d.ts +20 -0
  56. package/dist/cli/agent-dir-arg.d.ts.map +1 -0
  57. package/dist/cli/agent-dir-arg.js +38 -0
  58. package/dist/cli/agent-dir-arg.js.map +1 -0
  59. package/dist/cli/args.d.ts +6 -0
  60. package/dist/cli/args.d.ts.map +1 -1
  61. package/dist/cli/args.js +49 -5
  62. package/dist/cli/args.js.map +1 -1
  63. package/dist/cli/config-selector.d.ts.map +1 -1
  64. package/dist/cli/config-selector.js +9 -6
  65. package/dist/cli/config-selector.js.map +1 -1
  66. package/dist/cli/list-models.d.ts.map +1 -1
  67. package/dist/cli/list-models.js +0 -5
  68. package/dist/cli/list-models.js.map +1 -1
  69. package/dist/cli/project-trust.d.ts.map +1 -1
  70. package/dist/cli/project-trust.js +6 -6
  71. package/dist/cli/project-trust.js.map +1 -1
  72. package/dist/cli/session-picker.d.ts.map +1 -1
  73. package/dist/cli/session-picker.js +9 -6
  74. package/dist/cli/session-picker.js.map +1 -1
  75. package/dist/cli/startup-ui.d.ts +3 -2
  76. package/dist/cli/startup-ui.d.ts.map +1 -1
  77. package/dist/cli/startup-ui.js +21 -23
  78. package/dist/cli/startup-ui.js.map +1 -1
  79. package/dist/config.d.ts +6 -1
  80. package/dist/config.d.ts.map +1 -1
  81. package/dist/config.js +16 -2
  82. package/dist/config.js.map +1 -1
  83. package/dist/core/agent-session-runtime.d.ts +11 -0
  84. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  85. package/dist/core/agent-session-runtime.js +19 -0
  86. package/dist/core/agent-session-runtime.js.map +1 -1
  87. package/dist/core/agent-session-services.d.ts.map +1 -1
  88. package/dist/core/agent-session-services.js +6 -0
  89. package/dist/core/agent-session-services.js.map +1 -1
  90. package/dist/core/agent-session.d.ts +6 -3
  91. package/dist/core/agent-session.d.ts.map +1 -1
  92. package/dist/core/agent-session.js +22 -13
  93. package/dist/core/agent-session.js.map +1 -1
  94. package/dist/core/auth-storage.d.ts.map +1 -1
  95. package/dist/core/auth-storage.js +7 -1
  96. package/dist/core/auth-storage.js.map +1 -1
  97. package/dist/core/bash-executor.d.ts +3 -1
  98. package/dist/core/bash-executor.d.ts.map +1 -1
  99. package/dist/core/bash-executor.js +24 -13
  100. package/dist/core/bash-executor.js.map +1 -1
  101. package/dist/core/client-identity.d.ts +2 -3
  102. package/dist/core/client-identity.d.ts.map +1 -1
  103. package/dist/core/client-identity.js +3 -4
  104. package/dist/core/client-identity.js.map +1 -1
  105. package/dist/core/compaction/compaction.d.ts.map +1 -1
  106. package/dist/core/compaction/compaction.js +3 -0
  107. package/dist/core/compaction/compaction.js.map +1 -1
  108. package/dist/core/exec.d.ts +1 -0
  109. package/dist/core/exec.d.ts.map +1 -1
  110. package/dist/core/exec.js +4 -1
  111. package/dist/core/exec.js.map +1 -1
  112. package/dist/core/export-html/ansi-to-html.d.ts +6 -1
  113. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  114. package/dist/core/export-html/ansi-to-html.js +57 -20
  115. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  116. package/dist/core/export-html/template.js +1 -1
  117. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  118. package/dist/core/export-html/tool-renderer.js +2 -3
  119. package/dist/core/export-html/tool-renderer.js.map +1 -1
  120. package/dist/core/extensions/loader.d.ts.map +1 -1
  121. package/dist/core/extensions/loader.js +18 -1
  122. package/dist/core/extensions/loader.js.map +1 -1
  123. package/dist/core/extensions/runner.d.ts.map +1 -1
  124. package/dist/core/extensions/runner.js +7 -1
  125. package/dist/core/extensions/runner.js.map +1 -1
  126. package/dist/core/extensions/types.d.ts +14 -1
  127. package/dist/core/extensions/types.d.ts.map +1 -1
  128. package/dist/core/extensions/types.js.map +1 -1
  129. package/dist/core/messages.d.ts +4 -0
  130. package/dist/core/messages.d.ts.map +1 -1
  131. package/dist/core/messages.js +10 -2
  132. package/dist/core/messages.js.map +1 -1
  133. package/dist/core/model-config.d.ts +36 -0
  134. package/dist/core/model-config.d.ts.map +1 -1
  135. package/dist/core/model-resolver.d.ts +0 -8
  136. package/dist/core/model-resolver.d.ts.map +1 -1
  137. package/dist/core/model-resolver.js +7 -71
  138. package/dist/core/model-resolver.js.map +1 -1
  139. package/dist/core/model-runtime.d.ts.map +1 -1
  140. package/dist/core/model-runtime.js +6 -2
  141. package/dist/core/model-runtime.js.map +1 -1
  142. package/dist/core/package-manager.d.ts +16 -0
  143. package/dist/core/package-manager.d.ts.map +1 -1
  144. package/dist/core/package-manager.js +45 -2
  145. package/dist/core/package-manager.js.map +1 -1
  146. package/dist/core/pi-ai-schemas.d.ts +4 -0
  147. package/dist/core/pi-ai-schemas.d.ts.map +1 -1
  148. package/dist/core/project-trust.d.ts.map +1 -1
  149. package/dist/core/project-trust.js +1 -1
  150. package/dist/core/project-trust.js.map +1 -1
  151. package/dist/core/provider-composer.d.ts +1 -0
  152. package/dist/core/provider-composer.d.ts.map +1 -1
  153. package/dist/core/provider-composer.js +1 -0
  154. package/dist/core/provider-composer.js.map +1 -1
  155. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  156. package/dist/core/remote-catalog-provider.js +7 -0
  157. package/dist/core/remote-catalog-provider.js.map +1 -1
  158. package/dist/core/resolve-config-value.d.ts +2 -0
  159. package/dist/core/resolve-config-value.d.ts.map +1 -1
  160. package/dist/core/resolve-config-value.js +4 -0
  161. package/dist/core/resolve-config-value.js.map +1 -1
  162. package/dist/core/resource-loader.d.ts +5 -1
  163. package/dist/core/resource-loader.d.ts.map +1 -1
  164. package/dist/core/resource-loader.js +2 -0
  165. package/dist/core/resource-loader.js.map +1 -1
  166. package/dist/core/sdk.js +2 -2
  167. package/dist/core/sdk.js.map +1 -1
  168. package/dist/core/session-manager.d.ts.map +1 -1
  169. package/dist/core/session-manager.js +55 -42
  170. package/dist/core/session-manager.js.map +1 -1
  171. package/dist/core/session-ownership.js +15 -1
  172. package/dist/core/session-ownership.js.map +1 -1
  173. package/dist/core/settings-defaults.d.ts +6 -2
  174. package/dist/core/settings-defaults.d.ts.map +1 -1
  175. package/dist/core/settings-defaults.js +6 -2
  176. package/dist/core/settings-defaults.js.map +1 -1
  177. package/dist/core/settings-manager.d.ts +6 -6
  178. package/dist/core/settings-manager.d.ts.map +1 -1
  179. package/dist/core/settings-manager.js +23 -16
  180. package/dist/core/settings-manager.js.map +1 -1
  181. package/dist/core/settings-schema.d.ts +16 -3
  182. package/dist/core/settings-schema.d.ts.map +1 -1
  183. package/dist/core/settings-schema.js +23 -8
  184. package/dist/core/settings-schema.js.map +1 -1
  185. package/dist/core/tools/bash.d.ts +3 -0
  186. package/dist/core/tools/bash.d.ts.map +1 -1
  187. package/dist/core/tools/bash.js +24 -9
  188. package/dist/core/tools/bash.js.map +1 -1
  189. package/dist/core/tools/find.d.ts.map +1 -1
  190. package/dist/core/tools/find.js +27 -16
  191. package/dist/core/tools/find.js.map +1 -1
  192. package/dist/core/tools/grep.js +1 -1
  193. package/dist/core/tools/grep.js.map +1 -1
  194. package/dist/core/tools/output-accumulator.d.ts +16 -4
  195. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  196. package/dist/core/tools/output-accumulator.js +47 -38
  197. package/dist/core/tools/output-accumulator.js.map +1 -1
  198. package/dist/core/tools/read.d.ts +5 -0
  199. package/dist/core/tools/read.d.ts.map +1 -1
  200. package/dist/core/tools/read.js +10 -15
  201. package/dist/core/tools/read.js.map +1 -1
  202. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  203. package/dist/core/tools/renderers/bash.js +9 -3
  204. package/dist/core/tools/renderers/bash.js.map +1 -1
  205. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  206. package/dist/core/tools/renderers/read.js +6 -2
  207. package/dist/core/tools/renderers/read.js.map +1 -1
  208. package/dist/core/tools/truncate.d.ts +1 -1
  209. package/dist/core/tools/truncate.d.ts.map +1 -1
  210. package/dist/core/tools/truncate.js +11 -5
  211. package/dist/core/tools/truncate.js.map +1 -1
  212. package/dist/core/usage-totals.d.ts.map +1 -1
  213. package/dist/core/usage-totals.js +3 -0
  214. package/dist/core/usage-totals.js.map +1 -1
  215. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  216. package/dist/extensions/codemode/execute.js +36 -5
  217. package/dist/extensions/codemode/execute.js.map +1 -1
  218. package/dist/extensions/llama/client.d.ts.map +1 -1
  219. package/dist/extensions/llama/client.js +3 -13
  220. package/dist/extensions/llama/client.js.map +1 -1
  221. package/dist/extensions/llama/provider.d.ts +1 -1
  222. package/dist/extensions/llama/provider.d.ts.map +1 -1
  223. package/dist/extensions/llama/provider.js +6 -4
  224. package/dist/extensions/llama/provider.js.map +1 -1
  225. package/dist/extensions/llama/ui.d.ts.map +1 -1
  226. package/dist/extensions/llama/ui.js +2 -1
  227. package/dist/extensions/llama/ui.js.map +1 -1
  228. package/dist/extensions/mcp/index.d.ts.map +1 -1
  229. package/dist/extensions/mcp/index.js +4 -7
  230. package/dist/extensions/mcp/index.js.map +1 -1
  231. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  232. package/dist/extensions/mcp/resources.js +3 -3
  233. package/dist/extensions/mcp/resources.js.map +1 -1
  234. package/dist/extensions/mcp/tools.d.ts +1 -9
  235. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  236. package/dist/extensions/mcp/tools.js +8 -124
  237. package/dist/extensions/mcp/tools.js.map +1 -1
  238. package/dist/main.d.ts +1 -1
  239. package/dist/main.d.ts.map +1 -1
  240. package/dist/main.js +57 -19
  241. package/dist/main.js.map +1 -1
  242. package/dist/modes/diagnostics-stderr.d.ts +4 -0
  243. package/dist/modes/diagnostics-stderr.d.ts.map +1 -0
  244. package/dist/modes/diagnostics-stderr.js +11 -0
  245. package/dist/modes/diagnostics-stderr.js.map +1 -0
  246. package/dist/modes/interactive/components/assistant-message.d.ts +2 -1
  247. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  248. package/dist/modes/interactive/components/assistant-message.js +9 -3
  249. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  250. package/dist/modes/interactive/components/bash-execution.d.ts +2 -1
  251. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  252. package/dist/modes/interactive/components/bash-execution.js +7 -4
  253. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  254. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  255. package/dist/modes/interactive/components/config-selector.js +6 -3
  256. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  257. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  258. package/dist/modes/interactive/components/custom-editor.js +13 -1
  259. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  260. package/dist/modes/interactive/components/extension-editor.d.ts +1 -1
  261. package/dist/modes/interactive/components/extension-editor.js +2 -2
  262. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  263. package/dist/modes/interactive/components/first-time-setup.d.ts +3 -5
  264. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  265. package/dist/modes/interactive/components/first-time-setup.js +15 -45
  266. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  267. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
  268. package/dist/modes/interactive/components/mermaid.js +13 -4
  269. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  270. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  271. package/dist/modes/interactive/components/model-selector.js +5 -2
  272. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  273. package/dist/modes/interactive/components/oauth-selector.d.ts +14 -2
  274. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  275. package/dist/modes/interactive/components/oauth-selector.js +17 -12
  276. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  277. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
  278. package/dist/modes/interactive/components/radius-login-selector.js +2 -1
  279. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
  280. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  281. package/dist/modes/interactive/components/scoped-models-selector.js +9 -1
  282. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  283. package/dist/modes/interactive/components/session-selector.d.ts +8 -1
  284. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  285. package/dist/modes/interactive/components/session-selector.js +44 -12
  286. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  287. package/dist/modes/interactive/components/settings-selector.d.ts +3 -5
  288. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  289. package/dist/modes/interactive/components/settings-selector.js +57 -46
  290. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  291. package/dist/modes/interactive/components/settings-submenu.d.ts +1 -1
  292. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  293. package/dist/modes/interactive/components/settings-submenu.js +8 -4
  294. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  295. package/dist/modes/interactive/components/themed-text.d.ts +1 -1
  296. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
  297. package/dist/modes/interactive/components/themed-text.js.map +1 -1
  298. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  299. package/dist/modes/interactive/components/thinking-selector.js +5 -1
  300. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  301. package/dist/modes/interactive/components/tool-execution.d.ts +1 -1
  302. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  303. package/dist/modes/interactive/components/tool-execution.js +3 -1
  304. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  305. package/dist/modes/interactive/components/user-message.d.ts +2 -1
  306. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  307. package/dist/modes/interactive/components/user-message.js +9 -3
  308. package/dist/modes/interactive/components/user-message.js.map +1 -1
  309. package/dist/modes/interactive/components/visual-truncate.d.ts +2 -2
  310. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  311. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  312. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  313. package/dist/modes/interactive/external-editor.js +13 -3
  314. package/dist/modes/interactive/external-editor.js.map +1 -1
  315. package/dist/modes/interactive/interactive-mode.d.ts +19 -2
  316. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  317. package/dist/modes/interactive/interactive-mode.js +176 -111
  318. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  319. package/dist/modes/interactive/program-resume-reporter.d.ts +32 -0
  320. package/dist/modes/interactive/program-resume-reporter.d.ts.map +1 -0
  321. package/dist/modes/interactive/program-resume-reporter.js +56 -0
  322. package/dist/modes/interactive/program-resume-reporter.js.map +1 -0
  323. package/dist/modes/interactive/program-status-reporter.d.ts +2 -0
  324. package/dist/modes/interactive/program-status-reporter.d.ts.map +1 -1
  325. package/dist/modes/interactive/program-status-reporter.js +4 -0
  326. package/dist/modes/interactive/program-status-reporter.js.map +1 -1
  327. package/dist/modes/interactive/session-share.d.ts.map +1 -1
  328. package/dist/modes/interactive/session-share.js +11 -1
  329. package/dist/modes/interactive/session-share.js.map +1 -1
  330. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  331. package/dist/modes/interactive/theme/theme.js +1 -0
  332. package/dist/modes/interactive/theme/theme.js.map +1 -1
  333. package/dist/modes/print-mode.d.ts.map +1 -1
  334. package/dist/modes/print-mode.js +17 -17
  335. package/dist/modes/print-mode.js.map +1 -1
  336. package/dist/modes/rpc/jsonl.d.ts.map +1 -1
  337. package/dist/modes/rpc/jsonl.js +13 -13
  338. package/dist/modes/rpc/jsonl.js.map +1 -1
  339. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  340. package/dist/modes/rpc/rpc-mode.js +19 -27
  341. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  342. package/dist/package-manager-cli.d.ts.map +1 -1
  343. package/dist/package-manager-cli.js +24 -2
  344. package/dist/package-manager-cli.js.map +1 -1
  345. package/dist/utils/changelog.d.ts.map +1 -1
  346. package/dist/utils/changelog.js +3 -2
  347. package/dist/utils/changelog.js.map +1 -1
  348. package/dist/utils/clipboard.js +1 -1
  349. package/dist/utils/clipboard.js.map +1 -1
  350. package/dist/utils/flush-stdout.d.ts +8 -0
  351. package/dist/utils/flush-stdout.d.ts.map +1 -0
  352. package/dist/utils/flush-stdout.js +23 -0
  353. package/dist/utils/flush-stdout.js.map +1 -0
  354. package/dist/utils/output-files.d.ts +20 -4
  355. package/dist/utils/output-files.d.ts.map +1 -1
  356. package/dist/utils/output-files.js +37 -2
  357. package/dist/utils/output-files.js.map +1 -1
  358. package/dist/utils/shell.d.ts +2 -1
  359. package/dist/utils/shell.d.ts.map +1 -1
  360. package/dist/utils/shell.js +56 -7
  361. package/dist/utils/shell.js.map +1 -1
  362. package/dist/utils/tools-manager.d.ts +1 -0
  363. package/dist/utils/tools-manager.d.ts.map +1 -1
  364. package/dist/utils/tools-manager.js +9 -8
  365. package/dist/utils/tools-manager.js.map +1 -1
  366. package/docs/cli.md +3 -1
  367. package/docs/codemode.md +16 -5
  368. package/docs/environment-variables.md +4 -4
  369. package/docs/extensions.md +18 -8
  370. package/docs/llama-cpp.md +3 -3
  371. package/docs/message-types.md +1 -0
  372. package/docs/models-configuration.md +18 -6
  373. package/docs/models.md +34 -14
  374. package/docs/nvidia-rtx-llama-cpp.md +5 -5
  375. package/docs/providers.md +7 -5
  376. package/docs/rpc-commands.md +2 -2
  377. package/docs/settings.md +5 -3
  378. package/docs/shell-aliases.md +1 -1
  379. package/docs/terminal-setup.md +53 -0
  380. package/docs/tui.md +2 -0
  381. package/docs/windows.md +2 -1
  382. package/examples/extensions/gondolin/index.ts +4 -7
  383. package/examples/extensions/subagent/index.ts +3 -2
  384. package/examples/rpc-extension-ui.ts +8 -7
  385. package/package.json +10 -10
  386. package/schemas/models.schema.json +22 -9
  387. package/schemas/settings.schema.json +30 -10
  388. package/dist/bundle/chunks/anthropic-messages-CA3HHOL3.js +0 -6
  389. package/dist/bundle/chunks/azure-openai-responses-76TWS6DT.js +0 -2
  390. package/dist/bundle/chunks/chunk-4KSTFUIK.js +0 -19
  391. package/dist/bundle/chunks/chunk-CF5GWZHW.js +0 -31
  392. package/dist/bundle/chunks/chunk-GFUN2N5K.js +0 -2
  393. package/dist/bundle/chunks/chunk-IQUU5XIT.js +0 -2
  394. package/dist/bundle/chunks/chunk-PMRZO46Y.js +0 -2
  395. package/dist/bundle/chunks/chunk-QN4TOIZN.js +0 -16
  396. package/dist/bundle/chunks/chunk-V7SLUK6A.js +0 -44
  397. package/dist/bundle/chunks/chunk-Y55SJART.js +0 -13
  398. package/dist/bundle/chunks/chunk-YTPJCXUB.js +0 -30
  399. package/dist/bundle/chunks/chunk-ZBIZYD6W.js +0 -2
  400. package/dist/bundle/chunks/chunk-ZGYS4UTC.js +0 -2
  401. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-U4J7D646.js +0 -2
  402. package/dist/bundle/chunks/google-generative-ai-D5B6W47J.js +0 -2
  403. package/dist/bundle/chunks/google-vertex-U4H5YDEW.js +0 -2
  404. package/dist/bundle/chunks/mistral-conversations-S277EKLB.js +0 -5
  405. package/dist/bundle/chunks/openai-codex-responses-TEQRB65N.js +0 -10
  406. package/dist/bundle/chunks/openai-completions-HRZOSLBO.js +0 -7
  407. package/dist/bundle/chunks/openai-responses-BAKFWTGE.js +0 -4
  408. package/dist/bundle/chunks/openrouter-images-VXF5TVIK.js +0 -2
  409. package/dist/bundle/chunks/pi-messages-UBJKNDRN.js +0 -8
  410. package/dist/bundle/chunks/typesafe-system-one-56TEMIHL.js +0 -2
  411. package/dist/bundle/chunks/virtual-modules-MRQHQVIQ.js +0 -2
  412. package/dist/core/telemetry.d.ts +0 -3
  413. package/dist/core/telemetry.d.ts.map +0 -1
  414. package/dist/core/telemetry.js +0 -9
  415. package/dist/core/telemetry.js.map +0 -1
  416. package/dist/utils/deprecation.d.ts +0 -4
  417. package/dist/utils/deprecation.d.ts.map +0 -1
  418. package/dist/utils/deprecation.js +0 -13
  419. package/dist/utils/deprecation.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,193 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.7.0] - 2026-11-27
4
+
5
+ ### New Features
6
+
7
+ - **[Terminal session resume](docs/terminal-setup.md#program-resume):** Compatible terminals can reopen the current pi session after a restart with its original profile, tool restrictions, and instructions.
8
+ - **[Image generation in codemode](docs/codemode.md#generate-images):** Generate images with Radius, or set the aspect ratio and size when using OpenRouter image models.
9
+ - **GitHub Copilot prompt caching:** Changing the thinking level preserves the prompt cache on supported Claude 5.x and GPT-6 models. Supported Claude 5.x models also keep the cache when tools change, and Copilot Claude models support [cache warming](docs/settings.md#model-and-thinking).
10
+
11
+ ### Breaking Changes
12
+
13
+ - Removed telemetry reporting from pi for new installs and updates (`/api/report-install`), the `enableInstallTelemetry` setting (`SettingsManager.getEnableInstallTelemetry()` / `setEnableInstallTelemetry()`), and `PI_TELEMETRY`
14
+
15
+ ### Added
16
+
17
+ - Added program resume through the [Program Resume Protocol (OSC 7577)](https://www.superlogical.com/rex/docs/build/program-resume): in terminals that set `OSC7577_TOKEN`, interactive mode reports `pi --session <id>` for the current session, so the terminal can bring it back after it restarts. Pi removes the token from the environment of every process it starts. See [Terminal setup](docs/terminal-setup.md#program-resume)
18
+ - Added optional `{ aspectRatio, size }` as the third argument to codemode `models.generateImages()`
19
+ - Added `--agent-dir <dir>`, the command-line form of `PI_CODING_AGENT_DIR`. The resume command pi prints on exit and reports through OSC 7577 now includes it when the config directory is not `~/.pi/agent`. Without it, a session started with `PI_CODING_AGENT_DIR` came back with the default directory's settings and auth: a terminal resumes the command without the environment pi was started in. This is for setups that keep a separate pi profile per project, for example a shell function that sets `PI_CODING_AGENT_DIR` for one directory tree. Terminals that resume programs, such as Rex, need a rule that trusts the longer command; see [Terminal setup](docs/terminal-setup.md#program-resume)
20
+ - The OSC 7577 resume command now repeats the restriction and resource flags pi was started with (`--tools`, `--no-extensions`, `-e`, `--skill`, `--system-prompt`, and similar), as typed, so a terminal cannot resume a session with other tools or instructions, possibly more access, than it had. The command printed on exit is unchanged. A terminal rule must trust each flag combination; see [Terminal setup](docs/terminal-setup.md#program-resume)
21
+ - Added Radius image generation to [codemode](docs/codemode.md#generate-images). Radius image and classifier models are now listed in the built-in catalog as well as through provider discovery
22
+
23
+ ### Changed
24
+
25
+ - The default model for `cloudflare-workers-ai` and `cloudflare-ai-gateway` is now `@cf/zai-org/glm-5.3`, because Cloudflare deprecated Workers AI Kimi K2.6 and K2.7 Code
26
+ - Changed the `ant-ling` default model from the retired `Ring-2.6-1T` to `Ling-3.1-flash`. Existing `models.json` files can keep `thinkingFormat: "ant-ling"` as a deprecated alias for `"deepseek"` ([#11800](https://github.com/earendil-works/pi/pull/11800) by [@lvisei](https://github.com/lvisei))
27
+ - Replaced the retired `qwen4-max-preview` with `qwen4-max` on Qwen Token Plan Individual
28
+ - Preserved the GitHub Copilot prompt cache when changing thinking levels on supported Claude 5.x and GPT-6 models or changing tools on supported Claude 5.x models. Copilot Claude models now support cache warming, and GPT-5.3 Codex and MAI-Code receive mid-conversation system messages where they take effect ([#12316](https://github.com/earendil-works/pi/issues/12316))
29
+
30
+ ### Fixed
31
+
32
+ - Fixed `/llama` "Download model" downloading the typed text instead of the highlighted result when the query looked like `owner/repository` and the user had moved the selection with the arrow keys ([#12465](https://github.com/earendil-works/pi/issues/12465))
33
+ - Fixed key hints that named the wrong keybinding or a hardcoded key: the extension editor and session rename now name `tui.input.submit`, `/hotkeys` names `tui.select.cancel` for cancelling autocomplete, and the settings submenu, `/config` selector, session selector and fullscreen copy setting follow remapped keys
34
+ - Fixed a console Ctrl+Break on Windows ending pi without restoring the terminal, which left the shell in the alternate screen with mouse reports typed into the prompt. A child process in the same console can send Ctrl+Break too. pi now shuts down normally on it ([#12133](https://github.com/earendil-works/pi/issues/12133))
35
+ - Fixed print, JSON, and RPC modes not reporting an invalid `models.json`, so a typo such as `"contextWindow": "32000"` showed up only as `Model "..." not found` or `No API key found`. `createAgentSessionServices()` now returns the error as a warning in `diagnostics`, so every mode and SDK runtimes report it; interactive mode shows it as a warning instead of an error, as reported in [#12522](https://github.com/earendil-works/pi/issues/12522) ([#12523](https://github.com/earendil-works/pi/pull/12523) by [@acmerfight](https://github.com/acmerfight))
36
+ - Fixed `app.message.followUp` (Alt+Enter) ignoring an open autocomplete menu and queuing the half-typed text. It now applies the selected suggestion like Enter: a completed command name is queued, and other completions are inserted without queuing
37
+ - Fixed running `!` commands showing the wrong cancel shortcut. The hint now names the configured `app.interrupt` key ([#12518](https://github.com/earendil-works/pi/pull/12518) by [@acmerfight](https://github.com/acmerfight))
38
+ - Fixed `!!` commands counting toward the context estimate even though the model never sees them. Large outputs no longer trigger early compaction or crowd out recent history ([#12513](https://github.com/earendil-works/pi/issues/12513))
39
+ - Fixed Kitty images disappearing in Konsole and regular mode clearing the screen and scrollback when an appended image extended past the bottom of the screen ([#12548](https://github.com/earendil-works/pi/issues/12548))
40
+ - Fixed Amazon Bedrock Kimi K3.1 and GLM 5.3 ignoring the selected thinking level ([#12462](https://github.com/earendil-works/pi/issues/12462)). Kimi K3 and K3.1 also no longer send earlier reasoning back to Bedrock, which could make later turns fail
41
+ - Fixed GitHub Copilot models using `openai-completions` losing their reasoning state between turns ([#12418](https://github.com/earendil-works/pi/issues/12418))
42
+ - Fixed codemode image generation reporting success for failed OpenRouter responses. Image and classifier usage now includes reasoning tokens when reported; image usage distinguishes image output tokens, and OpenRouter costs use the reported total or the model's image output rate when estimating
43
+
44
+ ## [1.6.1] - 2026-11-25
45
+
46
+ ### New Features
47
+
48
+ - **Decision models in codemode**: GitHub Copilot's `gpt-6-luna-decisions` and Radius decision models can be called from codemode `models.classify()`, and results include the provider's `responseId`. See [Classify](docs/codemode.md#classify).
49
+ - **One setting per transcript notice**: cache misses, cache warming, compaction costs, and reasoning drops each have their own setting under Notices in `/settings`. See [Model and thinking](docs/settings.md#model-and-thinking).
50
+ - **Dialog status kind for extensions**: `ctx.ui.select()`, `ctx.ui.confirm()`, and `ctx.ui.input()` accept `blockedKind`, so terminals with program status can show a dialog as a permission request, question, or login. See [Program Status Kind](docs/extensions.md#program-status-kind).
51
+
52
+ ### Breaking Changes
53
+
54
+ - Replaced the `showCacheMissNotices` setting with one setting per transcript notice: `notices.cacheMisses`, `notices.cacheWarming`, `notices.compactionCosts`, and `notices.reasoningDrops`, configured under Notices in `/settings`. An existing `showCacheMissNotices` value is migrated to all four. `SettingsManager.getShowCacheMissNotices()` and `setShowCacheMissNotices()` are removed; use `getNotices()` and `setNotice()` instead
55
+
56
+ ### Added
57
+
58
+ - Added `compat.supportsStrictMode` for `google-generative-ai` and `google-vertex` models in `models.json`, so Gemini 3+ models served under IDs without the version can use strict tools ([#12321](https://github.com/earendil-works/pi/issues/12321))
59
+ - Added a `blockedKind` option to `ctx.ui.select()`, `ctx.ui.confirm()` and `ctx.ui.input()` that sets the kind of blocked program status (OSC 7501) the dialog reports, for example `"permission"` for a select that approves an action. See [Dialogs](docs/extensions.md#program-status-kind)
60
+ - Added `full_output_error` to the bash tool's structured output and `fullOutputError` to its details, `BashResult` and `BashExecutionMessage`, giving the reason when truncated output could not be saved to a temp file. User bash output that was truncated without a saved file now says so in the model context and the TUI ([#10585](https://github.com/earendil-works/pi/issues/10585))
61
+ - Added the `gpt-6-luna-decisions` decision model for GitHub Copilot, callable from codemode `models.classify()` with text and images ([#12395](https://github.com/earendil-works/pi/issues/12395))
62
+ - Added decision models on the Radius provider, callable from codemode `models.classify()`
63
+ - Added `responseId` to codemode `models.classify()` results. OpenRouter's System One fills it with its generation ID, and its billed cost replaces the catalog estimate. See [codemode](docs/codemode.md)
64
+
65
+ ### Changed
66
+
67
+ - Changed the default Mistral model from `devstral-medium-latest` to `mistral-medium-latest`, because Mistral retired Devstral and the model catalog no longer lists it
68
+ - Changed `after_provider_response` to also fire for HTTP error responses (4xx/5xx) and for each retried attempt on OpenAI, Azure OpenAI, Anthropic, and Google models, as it already did for OpenAI Codex, Mistral, Radius, and Amazon Bedrock, so extensions can read the status and `retry-after` of rate-limited requests ([#12376](https://github.com/earendil-works/pi/issues/12376))
69
+ - Changed first-time setup to show the colored pi logo and only ask about analytics; the theme defaults to the system theme, which follows the terminal's colors
70
+
71
+ ### Fixed
72
+
73
+ - Fixed selecting the `xhigh` thinking level for Gemini 4 Hydrogen and Neon on the `google` and `google-vertex` providers failing with `Unsupported Google thinking level mapping ... xhigh -> xhigh` ([#12184](https://github.com/earendil-works/pi/issues/12184))
74
+ - Fixed sessions with very many entries after the last compaction (about 120k or more) failing to load with `RangeError: Maximum call stack size exceeded` when building the context ([#12154](https://github.com/earendil-works/pi/issues/12154))
75
+ - Fixed `ctx.ui.pasteToEditor()` and `ctx.ui.setEditorText()` not repainting the editor when called outside terminal input handling, such as after an `await` in a command handler ([#12295](https://github.com/earendil-works/pi/issues/12295))
76
+ - Fixed the bash tool returning `(no output)` when the output ended with a line over 50KB followed by an empty line; it now shows the end of that line ([#12350](https://github.com/earendil-works/pi/issues/12350))
77
+ - Fixed `/tree` navigation adding the branch's prompts to Up-arrow history again on every navigation; prompts already in history now move to the most recent position instead of repeating ([#12279](https://github.com/earendil-works/pi/issues/12279))
78
+ - Fixed closing the console window or terminal tab on Windows skipping `session_shutdown` and leaving commands started by the bash tool running, for example `sleep 300` from `bash -c "sleep 300"`. pi now handles SIGHUP on Windows like on POSIX and waits for `taskkill` to finish before it exits. Quitting with Ctrl+D or `/quit` while a `!` command runs, or ending RPC mode while a `bash` command runs, no longer leaves that command running on Windows either
79
+ - Fixed the `AuthStorage` coalesced-reload test failing intermittently on systems with coarse file timestamps ([#12190](https://github.com/earendil-works/pi/issues/12190))
80
+ - Fixed the `thinkingLevelMap` reference in the models.json schema and docs suggesting pi does not support the `xhigh` and `max` thinking levels; it now says they are opt-in and only offered when mapped, and the model guide explains how to map thinking levels ([#12281](https://github.com/earendil-works/pi/issues/12281))
81
+ - Fixed Mermaid diagrams wider than the terminal falling back to their source without explanation; a note now says how many columns the diagram needs ([#12324](https://github.com/earendil-works/pi/issues/12324))
82
+ - Fixed copies on Wayland silently failing when `wl-copy` guessed a non-text MIME type from the copied text, for example `application/x-ruby` for text starting with `def`, which clipboard managers such as Klipper discard; pi now copies as `text/plain` ([#12446](https://github.com/earendil-works/pi/pull/12446) by [@ttempaa](https://github.com/ttempaa))
83
+ - Fixed pi crashing when the bash tool or a `!` command could not write its full-output temp file, for example when `/tmp` was full, over a per-user quota or not writable; both now keep the truncated output and say why the full output could not be saved. Opening the external editor and `/share` now report such failures instead of crashing ([#10585](https://github.com/earendil-works/pi/issues/10585))
84
+ - Fixed `/login` showing a provider as configured when its stored `auth.json` key is a `!command` that fails, while requests failed with `No API key found`. `/login` now shows `stored key did not resolve`, `getProviderAuthStatus()` returns `{ configured: false, source: "stored" }`, and entering the same `!command` again in `/login` runs it again instead of reusing the cached failure ([#12164](https://github.com/earendil-works/pi/issues/12164))
85
+ - Fixed `pi update` run from WSL through the Windows installation of pi rebuilding that installation with Linux npm; it now stops and says that running the Windows installation from WSL is unsupported ([#12172](https://github.com/earendil-works/pi/issues/12172))
86
+ - Fixed right-click paste inserting the clipboard twice in Tabby on Windows, which pastes on right-click itself ([#12406](https://github.com/earendil-works/pi/issues/12406))
87
+ - Fixed dialogs shown before interactive mode starts, such as the project trust prompt, the missing session folder prompt and first-time setup, reporting no `blocked` program status (OSC 7501). Blocked messages of multi-line dialog titles are now the first line only, for example `Trust project folder?` instead of the folder path and explanation. The project trust prompt and first-time setup report `kind=permission` ([#12439](https://github.com/earendil-works/pi/issues/12439))
88
+ - Fixed GitHub Copilot listing decision models the account cannot use, such as `microsoft-decision-1` on accounts whose plan does not include it, where every call failed with HTTP 400. After `/login` or the next token refresh, only the decision models in the account's Copilot model catalog are listed ([#12395](https://github.com/earendil-works/pi/issues/12395))
89
+ - Fixed the bash tool on Windows not finding Git for Windows installed outside Program Files and running commands through the WSL launcher `System32\bash.exe` instead. pi now asks the `git.exe` on `PATH` for its installation (`git var GIT_SHELL_PATH`, Git 2.47+) and uses its Git Bash before other `bash.exe` on `PATH` ([#12408](https://github.com/earendil-works/pi/issues/12408))
90
+ - Fixed RPC mode, session loading, and llama.cpp model events rescanning an incomplete line on every chunk, which made large lines, such as messages with images, take time quadratic in their size. llama.cpp model events also accept lone CR line endings and CRLF split across chunks ([#12224](https://github.com/earendil-works/pi/issues/12224))
91
+ - Fixed `!` command output coming back collapsed after compaction, `/reload`, `/resume` or `/tree` while ctrl+o was set to expanded ([#12426](https://github.com/earendil-works/pi/issues/12426), [#12427](https://github.com/earendil-works/pi/pull/12427) by [@acmerfight](https://github.com/acmerfight))
92
+ - Fixed more temporary provider failures not being retried automatically: Cloudflare HTTP 525, gateway "provider is temporarily unavailable" and partial-response errors, Anthropic `api_error` events during streaming, OpenRouter empty responses and stops without output, streams ending with `finish_reason: "error"`, and "request rate increased too quickly" throttling ([#12206](https://github.com/earendil-works/pi/issues/12206), [#12227](https://github.com/earendil-works/pi/issues/12227), [#12240](https://github.com/earendil-works/pi/issues/12240), [#12407](https://github.com/earendil-works/pi/issues/12407))
93
+ - Fixed unrelated request errors whose code contains `request_too_large` inside a longer identifier, such as `plugin_request_too_large`, triggering compact-and-retry as if the context overflowed ([#12343](https://github.com/earendil-works/pi/issues/12343), [#12438](https://github.com/earendil-works/pi/pull/12438) by [@muyiyr](https://github.com/muyiyr))
94
+ - Fixed HTTP 400 with thinking `off` on Claude Sonnet 5.5 through GitHub Copilot, and on Claude Opus 5.5 and Sonnet 5.5 through Cloudflare AI Gateway and Vercel AI Gateway; selecting `off` on those models now uses the lowest supported level ([#12429](https://github.com/earendil-works/pi/issues/12429))
95
+ - Fixed Gemini 3+ models whose IDs carry a prefix, such as `vendor-gemini-4-argon`, being treated as older Gemini models: they now get strict tools, tool-call IDs, and images inside function responses ([#12321](https://github.com/earendil-works/pi/issues/12321))
96
+ - Fixed Google prompt blocks being reported and retried as incomplete streams; the error now includes the block reason and safety ratings ([#12330](https://github.com/earendil-works/pi/issues/12330))
97
+ - Fixed `openai-codex` starting GPT-6 requests at `medium` regardless of the selected thinking level ([#12361](https://github.com/earendil-works/pi/issues/12361))
98
+ - Fixed GPT-6.2 dropping earlier reasoning as `prefix_mismatch` after the OpenAI Codex WebSocket connection expired ([#12367](https://github.com/earendil-works/pi/issues/12367))
99
+ - Fixed Amazon Bedrock requests hanging behind `HTTPS_PROXY` with AWS SSO profiles ([#12353](https://github.com/earendil-works/pi/issues/12353))
100
+ - Fixed HTTP 400 after tool calls without text on Cloudflare Workers AI's GPT-OSS 120B and 20B, Granite 4.0 H Micro, and Llama 3.3 70B Instruct FP8 Fast ([#12194](https://github.com/earendil-works/pi/issues/12194))
101
+ - Fixed HTTP 400 for non-strict Anthropic tools with Draft 7 tuples ([#12212](https://github.com/earendil-works/pi/issues/12212))
102
+ - Fixed OpenAI Decisions usage dropping cache read and write tokens ([#12264](https://github.com/earendil-works/pi/issues/12264))
103
+ - Fixed extension providers with `fetchModels` making model lookups quadratic in catalog size, which blocked pi for about a second with ~10k models ([#12311](https://github.com/earendil-works/pi/issues/12311))
104
+ - Fixed the model list still offering models their providers shut down: `gpt-5-chat-latest` on `openai` and `azure`, Groq's `llama-3.1-8b-instant`, `llama-3.3-70b-versatile` and `qwen/qwen3.6-27b`, and the undocumented `mistral-medium-3.5` ([#12202](https://github.com/earendil-works/pi/issues/12202))
105
+ - Fixed Markdown after an unclosed `$` before a number, such as `+$50`, rendering as raw text for the rest of the paragraph ([#12389](https://github.com/earendil-works/pi/issues/12389) by [@wuhaoyujerry](https://github.com/wuhaoyujerry))
106
+ - Fixed rendering a bare URL that runs into a multi-megabyte line exhausting the heap in terminals with OSC 8 hyperlinks ([#12416](https://github.com/earendil-works/pi/issues/12416))
107
+ - Fixed MCP requests to servers that echo request IDs as strings timing out, and large MCP Streamable HTTP events blocking pi for seconds ([#12205](https://github.com/earendil-works/pi/issues/12205), [#12224](https://github.com/earendil-works/pi/issues/12224))
108
+
109
+ ## [1.6.0] - 2026-11-20
110
+
111
+ ### New Features
112
+
113
+ - **GPT-6.2 Astra and GPT-6.2 Sol**: both models are available on the `openai`, `azure`, and `openai-codex` providers, and GPT-6.2 Sol is now the default model for all three. See [Providers](docs/providers.md).
114
+
115
+ ### Breaking Changes
116
+
117
+ - Extension components: `render()` now returns `readonly string[]`, and `Container` returns the same cached array while its children are unchanged. Extensions that modify render output in place, including `super.render()` in a `Container` subclass or an embedded component's output, must copy it first ([#9549](https://github.com/earendil-works/pi/issues/9549))
118
+
119
+ ### Added
120
+
121
+ - Added GPT-6.2 Astra and GPT-6.2 Sol to the `openai`, `azure`, and `openai-codex` providers. Both reject reasoning effort `none` and `minimal`, so thinking level `off` is unavailable. Azure serves them with a 1.05M context window; Codex serves GPT-6.2 Sol with 500K and GPT-6.2 Astra with 272K
122
+ - Added `qwen4-max-preview` to the Qwen Token Plan Individual providers ([#12259](https://github.com/earendil-works/pi/issues/12259))
123
+ - Added `deepseek-v4.1-flash` and `deepseek-v4.1-flash-1017` to the Qwen Token Plan Individual providers, and per-plan key variables `QWEN_TOKEN_PLAN_TEAM_API_KEY`, `QWEN_TOKEN_PLAN_TEAM_CN_API_KEY`, `QWEN_TOKEN_PLAN_INDIVIDUAL_API_KEY`, and `QWEN_TOKEN_PLAN_INDIVIDUAL_CN_API_KEY`; the shared `QWEN_TOKEN_PLAN_API_KEY` and `QWEN_TOKEN_PLAN_CN_API_KEY` still work ([#11773](https://github.com/earendil-works/pi/issues/11773))
124
+ - Added a transcript notice when OpenAI drops reasoning items from a request, such as `OpenAI dropped 2 reasoning items: prefix_mismatch (details in session)` after compaction on GPT-6.2. Like the Anthropic thinking notice, it is shown when `showCacheMissNotices` is on and only when more items are dropped than in the previous response. Both notices now name the reasons
125
+
126
+ ### Changed
127
+
128
+ - Qwen Token Plan providers now use the current gateways (`token-plan.maas.qwencloudapi.com` international, `token-plan.maas.qianwenaiapi.com` China), and `qwen-token-plan` and `qwen-token-plan-cn` are named "Qwen Token Plan Team" and "Qwen Token Plan Team CN". Provider IDs are unchanged, and the old `aliyuncs.com` hosts still work ([#11773](https://github.com/earendil-works/pi/issues/11773))
129
+ - Updated `undici` to 8.12.4 for security advisories GHSA-mqg3-3v4r-cm32, GHSA-7xg3-fphp-28hg, GHSA-5rm8-gv32-r954, GHSA-9v6h-8rgp-m69f, GHSA-3g9m-rv3r-w5w2, and GHSA-r4pc-4jcp-7pqc ([#12200](https://github.com/earendil-works/pi/issues/12200))
130
+ - The default model for the `openai`, `azure`, and `openai-codex` providers is now GPT-6.2 Sol (`gpt-6.2-sol`) instead of GPT-6.1 Sol, at the same price
131
+ - The find tool's path patterns are now relative to the search directory, like grep's `glob`: `src/*.ts` finds `src/a.ts` but no longer `pkg/src/a.ts`; use `**/src/*.ts` to match at any depth. Patterns without `/` still match file names at any depth ([#12066](https://github.com/earendil-works/pi/issues/12066))
132
+ - The llama.cpp extension now connects to `http://127.0.0.1:9931` by default, the current llama-server default port, instead of port 8080 ([#12001](https://github.com/earendil-works/pi/pull/12001) by [@julien-c](https://github.com/julien-c))
133
+ - Anthropic message threads are now on by default for any provider whose baseUrl is on api.anthropic.com, not only the `anthropic` provider ([#11987](https://github.com/earendil-works/pi/issues/11987))
134
+ - The resume command printed on exit is now on its own line after `To resume this session:`, so it can be selected with a triple-click ([#12237](https://github.com/earendil-works/pi/issues/12237))
135
+
136
+ ### Fixed
137
+
138
+ - Fixed `read` storing a note that the current model does not support images, which was replayed to the model as stale text after switching to a vision model. The image is still replaced with a placeholder per request for models without image input, and the read result now shows the warning in the TUI only, also when collapsed ([#12131](https://github.com/earendil-works/pi/issues/12131))
139
+ - Fixed MCP tools loaded by `tool_search` being dropped on resume and `/reload` when an extension deactivates only its own tool at `session_start`, as pi-web-access and pi-subagents do in `toolActivation: "auto"` mode ([#11996](https://github.com/earendil-works/pi/issues/11996))
140
+ - Fixed the standalone binary failing to resolve extension npm dependencies whose entry point is declared in `package.json` `main` or `exports` (for example `shiki`, `yaml`, `graceful-fs`), including imports made from inside other dependencies ([#12012](https://github.com/earendil-works/pi/issues/12012))
141
+ - Fixed the find tool returning no results for patterns starting with `./`, such as `./src/*.ts` ([#12020](https://github.com/earendil-works/pi/issues/12020))
142
+ - Fixed pi exiting with an uncaught `AbortError` when a `read` tool call is cancelled while the file is being opened ([#11956](https://github.com/earendil-works/pi/issues/11956))
143
+ - Fixed pi exiting with an uncaught `AbortError` when the session picker cancels loading after skipping a `.jsonl` file that is not a session, and fixed such files staying open ([#11956](https://github.com/earendil-works/pi/issues/11956))
144
+ - Fixed `/share` crashing pi when the GitHub CLI fails to start
145
+ - Fixed `pi update` on Windows managed installs failing with "Could not verify managed Pi" when an older system Node.js comes before the installer's standalone Node.js on PATH ([#12048](https://github.com/earendil-works/pi/issues/12048))
146
+ - Fixed `/export` HTML showing raw terminal hyperlink escape codes around links in custom tool output; links are now clickable ([#12003](https://github.com/earendil-works/pi/issues/12003))
147
+ - Fixed the bash tool returning no output, with a footer like `[Showing lines 3-2 of 2]`, when the output ends in one line longer than about 100KB, such as a `grep` match in a minified file; it now shows the end of that line ([#12062](https://github.com/earendil-works/pi/issues/12062))
148
+ - Fixed provider errors reading "Connection closed." not triggering automatic retries ([#12064](https://github.com/earendil-works/pi/issues/12064))
149
+ - Fixed `/resume` sometimes selecting an unrelated session while the list reloads after deleting or renaming a session ([#12106](https://github.com/earendil-works/pi/issues/12106))
150
+ - Fixed Groq Qwen models failing with `400 Unexpected message role`; OpenAI-compatible providers other than OpenAI now receive system messages (the system prompt and mid-conversation system messages) with the `system` role ([#10741](https://github.com/earendil-works/pi/issues/10741))
151
+ - Fixed `enabledModels`/`--models` warnings such as `No models match pattern "github-copilot/nope"` being written over the interactive TUI on every `/new`, `/resume` and `/fork`, which left stale lines in fullscreen mode. The warnings are now shown once at startup, in the chat in interactive mode and on stderr in other modes; RPC mode no longer repeats them on stderr for each `new_session`, `switch_session` or `fork` ([#11264](https://github.com/earendil-works/pi/issues/11264))
152
+ - Fixed the find tool matching path patterns through folders above the search path: with the project in `~/src/app`, `src/**/*.ts` returned every `.ts` file in the project ([#12066](https://github.com/earendil-works/pi/issues/12066))
153
+ - Fixed pi crashing with `RangeError: Maximum call stack size exceeded` when rendering a very large edit diff, for example after editing a file with a multi-megabyte line, and again on every resume of that session ([#8036](https://github.com/earendil-works/pi/issues/8036))
154
+ - Fixed pressing Esc during a batch of tool calls leaving the calls that had not started yet without a result in the session; they now get an "Operation aborted" result ([#9986](https://github.com/earendil-works/pi/issues/9986))
155
+ - Fixed an unreadable `CHANGELOG.md` (pi's own or an extension package's) printing `Warning: Could not parse changelog` over the interactive TUI; it now shows no changelog notes ([#11264](https://github.com/earendil-works/pi/issues/11264))
156
+ - Fixed problems found when replacing the session with `/new`, `/resume`, `/fork` or RPC `new_session`, `switch_session` and `fork` never being shown, for example a project extension that fails to load after `/resume` into another project, or an `enabledModels` pattern that matches nothing after a settings change. Interactive mode now shows them in the chat and print, JSON and RPC modes write them to stderr; a problem already reported is not repeated. SDK hosts can call the new `AgentSessionRuntime.takeUnreportedDiagnostics()` at startup and after each replacement to get each diagnostic once
157
+ - Fixed RPC `new_session`, `switch_session`, `fork` and `clone` running extension `session_start` and `resources_discover` handlers twice for the new session. RPC clients now also receive events emitted by `session_start` handlers, such as `entry_appended` for entries they append ([#10470](https://github.com/earendil-works/pi/issues/10470))
158
+ - Fixed an exception thrown by an extension's `pi.events` handler being printed with `console.error` over the interactive TUI. It is now reported like other extension errors: in the chat in interactive mode, as `extension_error` in RPC mode and as `Extension error (...)` in print mode. Errors from a handler that fails after its session was replaced are dropped ([#11264](https://github.com/earendil-works/pi/issues/11264))
159
+ - Fixed `AgentSession.reload()` not emitting `session_start` to extensions when the SDK host bound them with `bindExtensions({})`, after it had already emitted `session_shutdown`. Extensions that start work in `session_start`, such as the MCP extension connecting its servers, stayed stopped after a reload
160
+ - Fixed `--mode json` dropping events emitted by extension `session_start` handlers, such as `entry_appended` for entries they append, at startup and after an extension replaces the session
161
+ - Fixed `Could not restore model <provider>/<model>. Using <fallback>` being shown only at interactive startup. Resuming or forking into a session whose model no longer exists or has no login switched to another model without notice, and print, JSON and RPC modes never showed it. It is now reported in every mode, at startup and after `/resume`, `/fork` and RPC `switch_session` or `fork`
162
+ - Fixed git and npm output, such as `Cloning into ...` or `added 12 packages`, being drawn over the interactive TUI when pi installed or refreshed packages during `/reload`, `/new`, `/resume` and `/fork`, including temporary `-e git:` and `-e npm:` packages. In interactive mode their output is now captured, and a failed install reports the end of it. Until the TUI starts, each install is announced as `Installing <source>...` on stderr instead of showing git and npm output. git and ssh can no longer prompt in interactive mode: a package that needs a typed password or passphrase fails with a hint to set up a credential helper or ssh agent, or to run `pi install <source>` once from the shell. `pi install` and `pi update` keep live output ([#11264](https://github.com/earendil-works/pi/issues/11264))
163
+ - Fixed fullscreen scrolling in long sessions saturating a CPU core by re-rendering the whole transcript on every wheel event ([#9549](https://github.com/earendil-works/pi/issues/9549))
164
+ - Fixed search in `/login`, `/logout`, `/scoped-models` and `/resume` keeping the highlight on the row scrolled to before typing, so Enter picked whichever entry landed there instead of the best match; a query now highlights the top match, as `/model` does ([#12245](https://github.com/earendil-works/pi/issues/12245), [#12246](https://github.com/earendil-works/pi/pull/12246) by [@acmerfight](https://github.com/acmerfight))
165
+ - Fixed exiting pi, `pi config` and the `--resume` and other startup pickers dropping terminal output still queued in stdout, such as the resets that turn off mouse tracking and Kitty keyboard reporting; the shell could then print mouse and key reports as text. pi now waits up to one second for queued output before exiting or continuing ([#12133](https://github.com/earendil-works/pi/issues/12133))
166
+ - Fixed moving the cursor in a search field with Left, Right, Home or End moving the highlight back to the first entry in `/login`, `/logout`, `/model`, `/scoped-models`, `/resume`, `/settings`, the per-model settings model picker and `pi config` ([#12245](https://github.com/earendil-works/pi/issues/12245))
167
+ - Fixed llama.cpp decision classifiers ignoring the image input that llama.cpp reports, such as Clef with its `mmproj`; `models.classify()` now sends their images to `/v1/systemone` ([#12282](https://github.com/earendil-works/pi/issues/12282))
168
+ - Fixed `kill -TSTP` from outside pi stopping it without restoring the terminal, which left mouse tracking and the Kitty keyboard protocol on at the shell prompt and turned mouse movement into garbage input. pi now suspends as with Ctrl+Z and redraws on `fg` ([#12283](https://github.com/earendil-works/pi/pull/12283) by [@haoqixu](https://github.com/haoqixu))
169
+ - Fixed changing the thinking level on the `openai-codex` provider invalidating the prompt cache on GPT-6 models ([#12269](https://github.com/earendil-works/pi/issues/12269))
170
+ - Fixed unscoped syntax-highlighted text inheriting the terminal foreground and becoming unreadable on contrasting tool cards ([#11092](https://github.com/earendil-works/pi/issues/11092))
171
+ - Fixed `/copy` saying "No agent messages to copy yet." after Esc during a tool call or after a provider error; it now copies the previous answer. RPC `get_last_assistant_text` skips the same messages ([#12119](https://github.com/earendil-works/pi/issues/12119), [#12121](https://github.com/earendil-works/pi/pull/12121) by [@acmerfight](https://github.com/acmerfight))
172
+ - Fixed `pi.exec` reporting exit code 0 for commands ended by a signal, such as a timeout, an abort or a crash; it now reports 128 + the signal number, like a shell (143 for SIGTERM, 137 for SIGKILL) ([#12088](https://github.com/earendil-works/pi/issues/12088), [#12089](https://github.com/earendil-works/pi/pull/12089) by [@acmerfight](https://github.com/acmerfight))
173
+ - Fixed GitHub Copilot Gemini and Kimi models (`gemini-4-argon`, `gemini-4-carbon`, `gemini-3.8-flash`, `kimi-k3`) ignoring the thinking level, and Copilot usage always reporting 0 reasoning tokens ([#12110](https://github.com/earendil-works/pi/pull/12110) by [@DenielC1](https://github.com/DenielC1))
174
+ - Fixed provider errors that report only a Node socket error code, such as `read ECONNRESET`, `write EPIPE`, or `connect ETIMEDOUT`, not triggering automatic retries ([#12128](https://github.com/earendil-works/pi/issues/12128))
175
+ - Fixed OpenAI rejecting requests with a 400 error when a tool's schema contains a node without a `type` (such as `items: {}` or `Type.Unknown()`); such tools are now sent in non-strict mode ([#12049](https://github.com/earendil-works/pi/issues/12049))
176
+ - Fixed Mistral Large 4 tool calls stalling for minutes; Mistral models no longer receive strict tools unless `compat.supportsStrictMode` is set ([#12148](https://github.com/earendil-works/pi/issues/12148))
177
+ - Fixed non-strict Anthropic tool schemas not telling the model that extra arguments are forbidden ([#12067](https://github.com/earendil-works/pi/issues/12067))
178
+ - Fixed GitHub Copilot models on the Responses API (GPT, Grok, MAI-Code) filling omitted optional tool arguments with empty strings or invented values ([#12286](https://github.com/earendil-works/pi/issues/12286))
179
+ - Fixed the OpenAI Codex WebSocket 60-minute connection limit failing the turn when it hit mid-stream, for example during long thinking; the request is now retried on a fresh connection ([#12124](https://github.com/earendil-works/pi/issues/12124))
180
+ - Fixed the `openai-codex` provider getting almost no prompt cache hits for the system prompt on GPT-6.2 models ([#12273](https://github.com/earendil-works/pi/issues/12273))
181
+ - Fixed the `openai-codex` provider ignoring a model's `maxTokens`
182
+ - Fixed fullscreen Kitty images disappearing after a full redraw such as a window resize ([#12010](https://github.com/earendil-works/pi/issues/12010))
183
+ - Fixed text after a multi-row inline image in Markdown drawing over the image ([#12017](https://github.com/earendil-works/pi/issues/12017))
184
+ - Fixed Kitty and iTerm2 images covering overlays drawn over them ([#11584](https://github.com/earendil-works/pi/issues/11584))
185
+ - Fixed Enter on a Tab path menu for an absolute path (`look at /tmp/fi`) or a slash command argument menu (`/open /tm`) submitting the prompt instead of accepting the completion ([#12309](https://github.com/earendil-works/pi/issues/12309), [#12312](https://github.com/earendil-works/pi/pull/12312) by [@acmerfight](https://github.com/acmerfight))
186
+
187
+ ### Removed
188
+
189
+ - Removed the retired `deepseek-v3.2` and `deepseek-v4-flash` from the Qwen Token Plan Team providers; use `deepseek-v4-flash-0731` or `deepseek-v4.1-flash` ([#11773](https://github.com/earendil-works/pi/issues/11773))
190
+
3
191
  ## [1.5.2] - 2026-11-10
4
192
 
5
193
  ### New Features
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Mario Zechner
3
+ Copyright (c) 2026 Earendil Inc.
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -17,7 +17,7 @@ back. Do not run pi.dev's installer on a machine that should keep this build: it
17
17
  Pi over it.
18
18
 
19
19
  Everything else is upstream. The full list of changes, and why they live here rather than upstream:
20
- [FORK.md](https://github.com/maxmo74/pi/blob/release/v1.5.0/FORK.md).
20
+ [FORK.md](https://github.com/maxmo74/pi/blob/HEAD/FORK.md).
21
21
 
22
22
  <p align="center">
23
23
  <a href="https://pi.dev">
@@ -0,0 +1,3 @@
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-INODY4DR.js";import{registerSessionResourceCleanup}from"./chunk-ZG74NES2.js";import{SseDecoder}from"./chunk-2BKJ4UF2.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{applyOpenRouterReportedCost,isOpenRouterModel}from"./chunk-P7FPUEYA.js";import{Anthropic}from"./chunk-7CBJINYJ.js";import{shortHash}from"./chunk-PJACZCIR.js";import{adjustMaxTokensForThinking,buildBaseOptions,clampMaxTokensToContext,getJsonSchemaToolParameters,prefersJsonSchemaStrictSampling,resolveJsonSchemaStrictSampling,splitErrorToolResultImages,transformMessages}from"./chunk-D5U74ZAG.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-OVXT2WQH.js";import{withCauseDetail}from"./chunk-2HV66XRA.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import{ToolCallArgumentsStream,parseJsonWithRepair}from"./chunk-FFMDRXC4.js";import{calculateCost,getCurrentTools,getInitialSystemMessage,resolveTranscript}from"./chunk-HFTJRRFR.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders,getSystemMessageText,renderSystemMessageUpdate}from"./chunk-E3GEPN3H.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.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"]);async function*iterateSseMessages(body,signal){let reader=body.getReader(),sse=new SseDecoder;try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{value,done}=await reader.read();if(done)break;yield*sse.push(value)}yield*sse.end()}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,onErrorResponse:errorResponse=>options?.onResponse?.(errorResponse,model)}),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.additionalProperties===void 0?{}:{additionalProperties:schema.additionalProperties},...schema.$schema===void 0?{}:{$schema:schema.$schema},...schema.$defs===void 0?{}:{$defs:schema.$defs},...schema.definitions===void 0?{}:{definitions:schema.definitions}},inputSchema=strict===!0?{...parameters,...legacyInputSchema}:legacyInputSchema;return{name:isOAuthToken2?toClaudeCodeName(tool.name):tool.name,description:tool.description,...supportsEagerToolInputStreaming?{eager_input_streaming:!0}:{},...strict===!0?{strict:!0}:{},input_schema:inputSchema,...cacheControl&&index===tools.length-1?{cache_control:cacheControl}:{}}}):[]}function mapStopReason(reason,stopDetails){switch(reason){case"end_turn":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:stopDetails?.explanation||"The model refused to complete the request"};case"pause_turn":return{stopReason:"stop"};case"stop_sequence":return{stopReason:"stop"};case"sensitive":return{stopReason:"error",errorMessage:"Provider stopped with: sensitive"};default:throw new Error(`Unhandled stop reason: ${reason}`)}}export{stream,streamSimple};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{prepareResponsesPrompt,processResponsesStream}from"./chunk-GBB3EUD7.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-TMTOQ7H7.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{AzureOpenAI}from"./chunk-LWG2CUTI.js";import"./chunk-PJACZCIR.js";import{buildBaseOptions,createGrammarToolInputProperties,resolveSamplingParams}from"./chunk-D5U74ZAG.js";import"./chunk-L2ZPNLYD.js";import{retryProviderRequest}from"./chunk-OVXT2WQH.js";import{formatProviderError,normalizeProviderError}from"./chunk-2HV66XRA.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import"./chunk-7DDKXS2Q.js";import"./chunk-FFMDRXC4.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript}from"./chunk-HFTJRRFR.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import{getIdentityHeaders}from"./chunk-E3GEPN3H.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,onErrorResponse:errorResponse=>options?.onResponse?.(errorResponse,model)});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,{input,requestTools}=prepareResponsesPrompt(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,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),requestTools.length>0&&(params.tools=requestTools),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};