@punch-bot/cli 1.4.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +1 -1
  3. package/dist/bundle/chunks/anthropic-messages-WAYXCPZL.js +6 -0
  4. package/dist/bundle/chunks/azure-openai-responses-LUIPKPFC.js +2 -0
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +8 -8
  6. package/dist/bundle/chunks/chunk-275CIYA5.js +16 -0
  7. package/dist/bundle/chunks/chunk-2W2ATKZM.js +2 -0
  8. package/dist/bundle/chunks/{chunk-PYGXRV27.js → chunk-3V45WARH.js} +1 -1
  9. package/dist/bundle/chunks/chunk-4LBJE4YM.js +14 -0
  10. package/dist/bundle/chunks/{chunk-J7I2NFJ7.js → chunk-4NE64BTO.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-S3GGRYIO.js → chunk-5AGIVGSV.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-F5ZABL6Z.js → chunk-7CBJINYJ.js} +2 -2
  13. package/dist/bundle/chunks/{chunk-DRQDKNXA.js → chunk-7DDKXS2Q.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-MCGQGCDS.js → chunk-7SFLP7ZK.js} +102 -93
  15. package/dist/bundle/chunks/{chunk-OO6DJ3CL.js → chunk-A3Y7H47A.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-LP6WVVUV.js → chunk-BQU3RKDL.js} +1 -1
  17. package/dist/bundle/chunks/chunk-CRILLKNU.js +2 -0
  18. package/dist/bundle/chunks/chunk-HMPP4ECW.js +2 -0
  19. package/dist/bundle/chunks/chunk-HS7GCDEX.js +6 -0
  20. package/dist/bundle/chunks/{chunk-4L3WN2XY.js → chunk-JXWJOIH4.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-6CYCI3EJ.js → chunk-LVVZS2NO.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-6C5VKHGV.js → chunk-MYNHUMKE.js} +2 -2
  23. package/dist/bundle/chunks/{chunk-2M76JOVH.js → chunk-NJK3U3WK.js} +2 -2
  24. package/dist/bundle/chunks/chunk-NQWQE4BR.js +11 -0
  25. package/dist/bundle/chunks/{chunk-YGGF2ZM6.js → chunk-RROECCMX.js} +3 -3
  26. package/dist/bundle/chunks/{chunk-ZBURYEWF.js → chunk-TMTOQ7H7.js} +1 -1
  27. package/dist/bundle/chunks/chunk-TRN3ET6M.js +2 -0
  28. package/dist/bundle/chunks/{chunk-YWHGLBPB.js → chunk-UE7JCDFW.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-22CYIUS4.js → chunk-UKVNB6C4.js} +1 -1
  30. package/dist/bundle/chunks/{cli-QAQLORRY.js → cli-W5KJM7YB.js} +1 -1
  31. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-JWAAZATQ.js +2 -0
  32. package/dist/bundle/chunks/{execute-2Z6BN5R3.js → execute-HXULRBCI.js} +9 -3
  33. package/dist/bundle/chunks/github-copilot.js +1 -1
  34. package/dist/bundle/chunks/google-generative-ai-EHUU7JII.js +2 -0
  35. package/dist/bundle/chunks/google-vertex-AFMVUS5C.js +2 -0
  36. package/dist/bundle/chunks/{https-proxy-agent-US7JVRJG.js → https-proxy-agent-VTEOYAYG.js} +1 -1
  37. package/dist/bundle/chunks/{jiti-loader-C3NU2SDH.js → jiti-loader-GL4HJFAD.js} +1 -1
  38. package/dist/bundle/chunks/{jiti-static-loader-E6ANQD5T.js → jiti-static-loader-2RCDI6B4.js} +1 -1
  39. package/dist/bundle/chunks/{lib-TEDK3E5I.js → lib-4AVRLBHM.js} +1 -1
  40. package/dist/bundle/chunks/{llama-cpp-classify-FYN623RH.js → llama-cpp-classify-YVA2UOJG.js} +2 -2
  41. package/dist/bundle/chunks/{mistral-conversations-VNJYBSRF.js → mistral-conversations-FEBYNTL2.js} +1 -1
  42. package/dist/bundle/chunks/{multipart-parser-SQ6GDJL7.js → multipart-parser-FMGQ7342.js} +1 -1
  43. package/dist/bundle/chunks/{node-TWVVAGPO.js → node-AUOGOBCN.js} +1 -1
  44. package/dist/bundle/chunks/{node-N5BSDOA5.js → node-KCMANYC2.js} +1 -1
  45. package/dist/bundle/chunks/openai-codex-responses-MI7TTP3C.js +10 -0
  46. package/dist/bundle/chunks/openai-completions-BVORSTAM.js +7 -0
  47. package/dist/bundle/chunks/{openai-decisions-WVPMQ4JD.js → openai-decisions-GNOLFL74.js} +1 -1
  48. package/dist/bundle/chunks/openai-responses-TLIV5OQA.js +4 -0
  49. package/dist/bundle/chunks/openrouter-images-ZTNVFSL2.js +2 -0
  50. package/dist/bundle/chunks/pi-messages-4MVQCGGY.js +8 -0
  51. package/dist/bundle/chunks/{runtime-R6O72Q4R.js → runtime-R5GXO4CV.js} +1 -1
  52. package/dist/bundle/chunks/{src-UK77SYZE.js → src-QKGKDFSU.js} +1 -1
  53. package/dist/bundle/chunks/typesafe-system-one-I5AHLF6T.js +2 -0
  54. package/dist/bundle/chunks/virtual-modules-QK7S56IZ.js +2 -0
  55. package/dist/bundle/cli-runtime.js +1 -1
  56. package/dist/bundle/index.js +1 -1
  57. package/dist/bundle/rpc-entry.js +1 -1
  58. package/dist/core/agent-session.d.ts +5 -1
  59. package/dist/core/agent-session.d.ts.map +1 -1
  60. package/dist/core/agent-session.js +41 -12
  61. package/dist/core/agent-session.js.map +1 -1
  62. package/dist/core/client-identity.d.ts +8 -0
  63. package/dist/core/client-identity.d.ts.map +1 -0
  64. package/dist/core/client-identity.js +15 -0
  65. package/dist/core/client-identity.js.map +1 -0
  66. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  67. package/dist/core/compaction/branch-summarization.js +1 -2
  68. package/dist/core/compaction/branch-summarization.js.map +1 -1
  69. package/dist/core/compaction/compaction.d.ts +2 -2
  70. package/dist/core/compaction/compaction.d.ts.map +1 -1
  71. package/dist/core/compaction/compaction.js +20 -15
  72. package/dist/core/compaction/compaction.js.map +1 -1
  73. package/dist/core/export-html/index.d.ts.map +1 -1
  74. package/dist/core/export-html/index.js +2 -0
  75. package/dist/core/export-html/index.js.map +1 -1
  76. package/dist/core/export-html/template.html +1 -0
  77. package/dist/core/export-html/template.js +2 -1
  78. package/dist/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
  79. package/dist/core/export-html/vendor/marked.min.js +30 -29
  80. package/dist/core/extensions/loader.d.ts.map +1 -1
  81. package/dist/core/extensions/loader.js +3 -0
  82. package/dist/core/extensions/loader.js.map +1 -1
  83. package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
  84. package/dist/core/extensions/virtual-modules.js +3 -0
  85. package/dist/core/extensions/virtual-modules.js.map +1 -1
  86. package/dist/core/model-config.d.ts +915 -0
  87. package/dist/core/model-config.d.ts.map +1 -1
  88. package/dist/core/model-config.js +48 -24
  89. package/dist/core/model-config.js.map +1 -1
  90. package/dist/core/model-resolver.js +2 -2
  91. package/dist/core/model-resolver.js.map +1 -1
  92. package/dist/core/model-runtime.d.ts.map +1 -1
  93. package/dist/core/model-runtime.js +6 -3
  94. package/dist/core/model-runtime.js.map +1 -1
  95. package/dist/core/provider-composer.d.ts +2 -1
  96. package/dist/core/provider-composer.d.ts.map +1 -1
  97. package/dist/core/provider-composer.js +7 -3
  98. package/dist/core/provider-composer.js.map +1 -1
  99. package/dist/core/sdk.d.ts.map +1 -1
  100. package/dist/core/sdk.js +8 -9
  101. package/dist/core/sdk.js.map +1 -1
  102. package/dist/core/tools/grep.d.ts.map +1 -1
  103. package/dist/core/tools/grep.js +3 -1
  104. package/dist/core/tools/grep.js.map +1 -1
  105. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  106. package/dist/extensions/codemode/execute.js +99 -24
  107. package/dist/extensions/codemode/execute.js.map +1 -1
  108. package/dist/extensions/mcp/config.d.ts.map +1 -1
  109. package/dist/extensions/mcp/config.js +3 -2
  110. package/dist/extensions/mcp/config.js.map +1 -1
  111. package/dist/extensions/punch/a2a-listen.d.ts.map +1 -1
  112. package/dist/extensions/punch/a2a-listen.js +1 -0
  113. package/dist/extensions/punch/a2a-listen.js.map +1 -1
  114. package/dist/extensions/punch/a2a.d.ts.map +1 -1
  115. package/dist/extensions/punch/a2a.js +12 -5
  116. package/dist/extensions/punch/a2a.js.map +1 -1
  117. package/dist/extensions/punch/auth.d.ts +4 -1
  118. package/dist/extensions/punch/auth.d.ts.map +1 -1
  119. package/dist/extensions/punch/auth.js +17 -2
  120. package/dist/extensions/punch/auth.js.map +1 -1
  121. package/dist/extensions/punch/collabs.d.ts.map +1 -1
  122. package/dist/extensions/punch/collabs.js +46 -40
  123. package/dist/extensions/punch/collabs.js.map +1 -1
  124. package/dist/extensions/punch/index.d.ts.map +1 -1
  125. package/dist/extensions/punch/index.js +2 -0
  126. package/dist/extensions/punch/index.js.map +1 -1
  127. package/dist/extensions/punch/plan-gate.d.ts +34 -0
  128. package/dist/extensions/punch/plan-gate.d.ts.map +1 -0
  129. package/dist/extensions/punch/plan-gate.js +149 -0
  130. package/dist/extensions/punch/plan-gate.js.map +1 -0
  131. package/dist/extensions/webfetch/index.d.ts.map +1 -1
  132. package/dist/extensions/webfetch/index.js +2 -1
  133. package/dist/extensions/webfetch/index.js.map +1 -1
  134. package/dist/package-manager-cli.d.ts.map +1 -1
  135. package/dist/package-manager-cli.js +2 -1
  136. package/dist/package-manager-cli.js.map +1 -1
  137. package/dist/server/a2a/run-server.d.ts +2 -0
  138. package/dist/server/a2a/run-server.d.ts.map +1 -1
  139. package/dist/server/a2a/run-server.js +2 -0
  140. package/dist/server/a2a/run-server.js.map +1 -1
  141. package/dist/utils/clipboard-command.d.ts.map +1 -1
  142. package/dist/utils/clipboard-command.js +3 -0
  143. package/dist/utils/clipboard-command.js.map +1 -1
  144. package/dist/utils/pi-user-agent.d.ts +1 -0
  145. package/dist/utils/pi-user-agent.d.ts.map +1 -1
  146. package/dist/utils/pi-user-agent.js +3 -2
  147. package/dist/utils/pi-user-agent.js.map +1 -1
  148. package/dist/utils/shell.d.ts.map +1 -1
  149. package/dist/utils/shell.js +45 -13
  150. package/dist/utils/shell.js.map +1 -1
  151. package/dist/utils/tools-manager.d.ts.map +1 -1
  152. package/dist/utils/tools-manager.js +4 -3
  153. package/dist/utils/tools-manager.js.map +1 -1
  154. package/docs/codemode.md +2 -2
  155. package/docs/compaction.md +3 -3
  156. package/docs/custom-provider.md +53 -1
  157. package/docs/docs.json +4 -0
  158. package/docs/environment-variables.md +3 -0
  159. package/docs/extensions.md +129 -10
  160. package/docs/models-configuration.md +196 -0
  161. package/docs/models.md +21 -5
  162. package/docs/settings.md +1 -1
  163. package/docs/windows.md +16 -2
  164. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  165. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  166. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  167. package/examples/extensions/gondolin/package-lock.json +8 -8
  168. package/examples/extensions/gondolin/package.json +1 -1
  169. package/examples/extensions/sandbox/package-lock.json +18 -44
  170. package/examples/extensions/sandbox/package.json +5 -2
  171. package/examples/extensions/with-deps/package-lock.json +2 -2
  172. package/examples/extensions/with-deps/package.json +1 -1
  173. package/npm-shrinkwrap.json +54 -43
  174. package/package.json +12 -11
  175. package/schemas/models.schema.json +83 -29
  176. package/dist/bundle/chunks/anthropic-messages-BUUFZMRE.js +0 -6
  177. package/dist/bundle/chunks/azure-openai-responses-WZ4GZHD2.js +0 -2
  178. package/dist/bundle/chunks/chunk-BYHXHV4K.js +0 -11
  179. package/dist/bundle/chunks/chunk-HACVPRBJ.js +0 -11
  180. package/dist/bundle/chunks/chunk-ITZNWD4K.js +0 -2
  181. package/dist/bundle/chunks/chunk-OWCYH5W2.js +0 -2
  182. package/dist/bundle/chunks/chunk-QQO2NSV6.js +0 -6
  183. package/dist/bundle/chunks/chunk-WUIPA42N.js +0 -14
  184. package/dist/bundle/chunks/chunk-XIX7LUWI.js +0 -2
  185. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-UTBL2KOF.js +0 -2
  186. package/dist/bundle/chunks/google-generative-ai-S2KXX5PQ.js +0 -2
  187. package/dist/bundle/chunks/google-vertex-LQOUTFJN.js +0 -2
  188. package/dist/bundle/chunks/openai-codex-responses-E6BLZPYJ.js +0 -10
  189. package/dist/bundle/chunks/openai-completions-LUDIAWSG.js +0 -7
  190. package/dist/bundle/chunks/openai-responses-IOCBEIVC.js +0 -3
  191. package/dist/bundle/chunks/openrouter-images-YU24TD7D.js +0 -2
  192. package/dist/bundle/chunks/pi-messages-V27DSLVC.js +0 -8
  193. package/dist/bundle/chunks/typesafe-system-one-ZSK3RN4B.js +0 -2
  194. package/dist/bundle/chunks/virtual-modules-WOHWUS3S.js +0 -2
  195. package/dist/core/provider-attribution.d.ts +0 -4
  196. package/dist/core/provider-attribution.d.ts.map +0 -1
  197. package/dist/core/provider-attribution.js +0 -72
  198. package/dist/core/provider-attribution.js.map +0 -1
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@punch-bot/cli",
3
- "version": "1.4.0",
3
+ "version": "1.5.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@punch-bot/cli",
9
- "version": "1.4.0",
9
+ "version": "1.5.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
- "@punch-bot/a2a": "1.4.0",
13
- "@punch-bot/agent": "1.4.0",
14
- "@punch-bot/ai": "1.4.0",
12
+ "@punch-bot/a2a": "1.5.1",
13
+ "@punch-bot/agent": "1.5.1",
14
+ "@punch-bot/ai": "1.5.1",
15
15
  "@silvia-odwyer/photon-node": "0.3.4",
16
16
  "brace-expansion": "5.0.12",
17
17
  "chalk": "6.0.0",
@@ -24,15 +24,15 @@
24
24
  "hosted-git-info": "9.0.3",
25
25
  "ignore": "7.0.8",
26
26
  "jiti": "2.7.0",
27
- "minimatch": "10.2.6",
27
+ "minimatch": "11.0.4",
28
28
  "playwright": "1.62.1",
29
29
  "proper-lockfile": "4.1.2",
30
30
  "semver": "7.8.5",
31
31
  "typebox": "1.3.27",
32
- "undici": "8.11.0",
32
+ "undici": "8.12.3",
33
33
  "yaml": "2.9.0",
34
- "@punch-bot/codemode": "1.4.0",
35
- "@punch-bot/mcp": "1.4.0",
34
+ "@punch-bot/codemode": "1.5.1",
35
+ "@punch-bot/mcp": "1.5.1",
36
36
  "quickjs-wasi": "3.6.2"
37
37
  },
38
38
  "bin": {
@@ -101,6 +101,12 @@
101
101
  "node": ">=6.9.0"
102
102
  }
103
103
  },
104
+ "node_modules/@isaacs/nonrecursive-glob-match": {
105
+ "version": "1.0.3",
106
+ "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.0.3.tgz",
107
+ "integrity": "sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA==",
108
+ "license": "BlueOak-1.0.0"
109
+ },
104
110
  "node_modules/@protobufjs/aspromise": {
105
111
  "version": "1.1.2",
106
112
  "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
@@ -159,8 +165,8 @@
159
165
  "license": "BSD-3-Clause"
160
166
  },
161
167
  "node_modules/@punch-bot/a2a": {
162
- "version": "1.4.0",
163
- "resolved": "https://registry.npmjs.org/@punch-bot/a2a/-/a2a-1.4.0.tgz",
168
+ "version": "1.5.1",
169
+ "resolved": "https://registry.npmjs.org/@punch-bot/a2a/-/a2a-1.5.1.tgz",
164
170
  "license": "MIT",
165
171
  "dependencies": {
166
172
  "@a2a-js/sdk": "1.0.1",
@@ -171,11 +177,11 @@
171
177
  }
172
178
  },
173
179
  "node_modules/@punch-bot/agent": {
174
- "version": "1.4.0",
175
- "resolved": "https://registry.npmjs.org/@punch-bot/agent/-/agent-1.4.0.tgz",
180
+ "version": "1.5.1",
181
+ "resolved": "https://registry.npmjs.org/@punch-bot/agent/-/agent-1.5.1.tgz",
176
182
  "license": "MIT",
177
183
  "dependencies": {
178
- "@punch-bot/ai": "1.4.0",
184
+ "@punch-bot/ai": "1.5.1",
179
185
  "typebox": "1.3.27"
180
186
  },
181
187
  "engines": {
@@ -183,13 +189,13 @@
183
189
  }
184
190
  },
185
191
  "node_modules/@punch-bot/ai": {
186
- "version": "1.4.0",
187
- "resolved": "https://registry.npmjs.org/@punch-bot/ai/-/ai-1.4.0.tgz",
192
+ "version": "1.5.1",
193
+ "resolved": "https://registry.npmjs.org/@punch-bot/ai/-/ai-1.5.1.tgz",
188
194
  "license": "MIT",
189
195
  "dependencies": {
190
196
  "@anthropic-ai/sdk": "0.129.0",
191
197
  "@aws-sdk/client-bedrock-runtime": "3.1127.0",
192
- "@punch-bot/telemetry": "1.4.0",
198
+ "@punch-bot/telemetry": "1.5.1",
193
199
  "@google/genai": "2.21.0",
194
200
  "@smithy/node-http-handler": "4.12.1",
195
201
  "http-proxy-agent": "9.1.0",
@@ -689,8 +695,8 @@
689
695
  }
690
696
  },
691
697
  "node_modules/@punch-bot/codemode": {
692
- "version": "1.4.0",
693
- "resolved": "https://registry.npmjs.org/@punch-bot/codemode/-/codemode-1.4.0.tgz",
698
+ "version": "1.5.1",
699
+ "resolved": "https://registry.npmjs.org/@punch-bot/codemode/-/codemode-1.5.1.tgz",
694
700
  "license": "MIT",
695
701
  "dependencies": {
696
702
  "quickjs-wasi": "3.6.2"
@@ -700,8 +706,8 @@
700
706
  }
701
707
  },
702
708
  "node_modules/@punch-bot/mcp": {
703
- "version": "1.4.0",
704
- "resolved": "https://registry.npmjs.org/@punch-bot/mcp/-/mcp-1.4.0.tgz",
709
+ "version": "1.5.1",
710
+ "resolved": "https://registry.npmjs.org/@punch-bot/mcp/-/mcp-1.5.1.tgz",
705
711
  "license": "MIT",
706
712
  "dependencies": {
707
713
  "cross-spawn": "7.0.6"
@@ -711,8 +717,8 @@
711
717
  }
712
718
  },
713
719
  "node_modules/@punch-bot/telemetry": {
714
- "version": "1.4.0",
715
- "resolved": "https://registry.npmjs.org/@punch-bot/telemetry/-/telemetry-1.4.0.tgz",
720
+ "version": "1.5.1",
721
+ "resolved": "https://registry.npmjs.org/@punch-bot/telemetry/-/telemetry-1.5.1.tgz",
716
722
  "license": "MIT",
717
723
  "engines": {
718
724
  "node": ">=22.19.0"
@@ -800,18 +806,18 @@
800
806
  }
801
807
  },
802
808
  "node_modules/body-parser": {
803
- "version": "2.3.0",
804
- "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
805
- "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
809
+ "version": "2.4.0",
810
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz",
811
+ "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==",
806
812
  "license": "MIT",
807
813
  "dependencies": {
808
814
  "bytes": "^3.1.2",
809
- "content-type": "^2.0.0",
815
+ "content-type": "^2.1.0",
810
816
  "debug": "^4.4.3",
811
817
  "http-errors": "^2.0.1",
812
- "iconv-lite": "^0.7.2",
818
+ "iconv-lite": "^0.7.3",
813
819
  "on-finished": "^2.4.1",
814
- "qs": "^6.15.2",
820
+ "qs": "^6.16.1",
815
821
  "raw-body": "^3.0.2",
816
822
  "type-is": "^2.1.0"
817
823
  },
@@ -1642,15 +1648,16 @@
1642
1648
  }
1643
1649
  },
1644
1650
  "node_modules/minimatch": {
1645
- "version": "10.2.6",
1646
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
1647
- "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
1651
+ "version": "11.0.4",
1652
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.4.tgz",
1653
+ "integrity": "sha512-/UJ1dEoVQTjPNDh6SGlUo+ueLMmoHTas4q+8yaAR/5t6nLAIiBDJtoYUh20IYleix7ehiQkgczb84PE3uzHkxg==",
1648
1654
  "license": "BlueOak-1.0.0",
1649
1655
  "dependencies": {
1650
- "brace-expansion": "^5.0.8"
1656
+ "@isaacs/nonrecursive-glob-match": "^1.0.3",
1657
+ "brace-expansion": "^5.0.12"
1651
1658
  },
1652
1659
  "engines": {
1653
- "node": "18 || 20 || >=22"
1660
+ "node": "20 || >=22"
1654
1661
  },
1655
1662
  "funding": {
1656
1663
  "url": "https://github.com/sponsors/isaacs"
@@ -1940,9 +1947,9 @@
1940
1947
  "hasInstallScript": true
1941
1948
  },
1942
1949
  "node_modules/proxy-addr": {
1943
- "version": "2.0.7",
1944
- "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
1945
- "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
1950
+ "version": "2.0.8",
1951
+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
1952
+ "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
1946
1953
  "license": "MIT",
1947
1954
  "dependencies": {
1948
1955
  "forwarded": "0.2.0",
@@ -1950,6 +1957,10 @@
1950
1957
  },
1951
1958
  "engines": {
1952
1959
  "node": ">= 0.10"
1960
+ },
1961
+ "funding": {
1962
+ "type": "opencollective",
1963
+ "url": "https://opencollective.com/express"
1953
1964
  }
1954
1965
  },
1955
1966
  "node_modules/proxy-agent-negotiate": {
@@ -1970,9 +1981,9 @@
1970
1981
  }
1971
1982
  },
1972
1983
  "node_modules/qs": {
1973
- "version": "6.16.0",
1974
- "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
1975
- "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==",
1984
+ "version": "6.17.1",
1985
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz",
1986
+ "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==",
1976
1987
  "license": "BSD-3-Clause",
1977
1988
  "dependencies": {
1978
1989
  "es-define-property": "^1.0.1",
@@ -2310,9 +2321,9 @@
2310
2321
  "license": "MIT"
2311
2322
  },
2312
2323
  "node_modules/undici": {
2313
- "version": "8.11.0",
2314
- "resolved": "https://registry.npmjs.org/undici/-/undici-8.11.0.tgz",
2315
- "integrity": "sha512-AdzuGcAkzhbha3GgCSoUBx2P0quwym6qdFNCQz/fDGZc8w9XJ741wHUbt2kTmfPz+ZIOMkySFkiY7RXmiDDC8w==",
2324
+ "version": "8.12.3",
2325
+ "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz",
2326
+ "integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==",
2316
2327
  "license": "MIT",
2317
2328
  "engines": {
2318
2329
  "node": ">=22.19.0"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@punch-bot/cli",
3
- "version": "1.4.0",
3
+ "version": "1.5.1",
4
4
  "description": "Headless coding agent SDK, RPC, and print modes with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "imports": {
@@ -48,13 +48,14 @@
48
48
  "copy-binary-assets": "shx cp package.json dist/ && shx cp README.md dist/ && shx cp CHANGELOG.md dist/ && shx mkdir -p dist/theme && shx cp src/core/theme/*.json dist/theme/ && shx mkdir -p dist/export-html/vendor && shx cp src/core/export-html/template.html dist/export-html/ && shx cp src/core/export-html/vendor/*.js dist/export-html/vendor/ && shx cp -r docs dist/ && shx cp -r examples dist/ && shx cp ../../node_modules/@silvia-odwyer/photon-node/photon_rs_bg.wasm dist/",
49
49
  "test": "vitest --run",
50
50
  "generate:schemas": "node --import ./src/experimental/source-resolver.ts scripts/generate-schemas.ts",
51
+ "generate:references": "node --import ./src/experimental/source-resolver.ts scripts/generate-references.ts",
51
52
  "shrinkwrap": "node ../../scripts/generate-coding-agent-shrinkwrap.mjs",
52
53
  "prepublishOnly": "npm run clean && npm run build && npm run shrinkwrap"
53
54
  },
54
55
  "dependencies": {
55
- "@punch-bot/a2a": "1.4.0",
56
- "@punch-bot/agent": "1.4.0",
57
- "@punch-bot/ai": "1.4.0",
56
+ "@punch-bot/a2a": "1.5.1",
57
+ "@punch-bot/agent": "1.5.1",
58
+ "@punch-bot/ai": "1.5.1",
58
59
  "@silvia-odwyer/photon-node": "0.3.4",
59
60
  "brace-expansion": "5.0.12",
60
61
  "chalk": "6.0.0",
@@ -67,15 +68,15 @@
67
68
  "hosted-git-info": "9.0.3",
68
69
  "ignore": "7.0.8",
69
70
  "jiti": "2.7.0",
70
- "minimatch": "10.2.6",
71
+ "minimatch": "11.0.4",
71
72
  "playwright": "1.62.1",
72
73
  "proper-lockfile": "4.1.2",
73
74
  "semver": "7.8.5",
74
75
  "typebox": "1.3.27",
75
- "undici": "8.11.0",
76
+ "undici": "8.12.3",
76
77
  "yaml": "2.9.0",
77
- "@punch-bot/codemode": "1.4.0",
78
- "@punch-bot/mcp": "1.4.0",
78
+ "@punch-bot/codemode": "1.5.1",
79
+ "@punch-bot/mcp": "1.5.1",
79
80
  "quickjs-wasi": "3.6.2"
80
81
  },
81
82
  "overrides": {
@@ -88,9 +89,9 @@
88
89
  "@types/proper-lockfile": "4.1.4",
89
90
  "@types/semver": "7.7.1",
90
91
  "marked": "18.0.11",
91
- "shx": "0.3.4",
92
- "vitest": "5.0.0",
93
- "@punch-bot/durable": "1.4.0"
92
+ "shx": "0.4.0",
93
+ "vitest": "5.0.5",
94
+ "@punch-bot/durable": "1.5.1"
94
95
  },
95
96
  "keywords": [
96
97
  "coding-agent",
@@ -18,23 +18,28 @@
18
18
  "properties": {
19
19
  "name": {
20
20
  "type": "string",
21
- "minLength": 1
21
+ "minLength": 1,
22
+ "description": "Display name."
22
23
  },
23
24
  "baseUrl": {
24
25
  "type": "string",
25
- "minLength": 1
26
+ "minLength": 1,
27
+ "description": "API base URL. Also applies to the provider's built-in models."
26
28
  },
27
29
  "apiKey": {
28
30
  "type": "string",
29
- "minLength": 1
31
+ "minLength": 1,
32
+ "description": "Literal key, \"$NAME\" environment interpolation, or \"!command\" output."
30
33
  },
31
34
  "api": {
32
35
  "type": "string",
33
- "minLength": 1
36
+ "minLength": 1,
37
+ "description": "API for the provider's models, such as \"openai-completions\", \"openai-responses\", \"anthropic-messages\", or \"google-generative-ai\"."
34
38
  },
35
39
  "oauth": {
36
40
  "type": "string",
37
- "const": "radius"
41
+ "const": "radius",
42
+ "description": "OAuth login flow. Requires baseUrl."
38
43
  },
39
44
  "headers": {
40
45
  "type": "object",
@@ -42,14 +47,17 @@
42
47
  "^.*$": {
43
48
  "type": "string"
44
49
  }
45
- }
50
+ },
51
+ "description": "Request headers. Values resolve like apiKey."
46
52
  },
47
53
  "compat": {
48
54
  "$ref": "#/$defs/ProviderCompat",
49
55
  "description": "Provider and model compatibility overrides."
50
56
  },
51
57
  "authHeader": {
52
- "type": "boolean"
58
+ "type": "boolean",
59
+ "default": false,
60
+ "description": "Whether to send the resolved API key as Authorization: Bearer."
53
61
  },
54
62
  "models": {
55
63
  "type": "array",
@@ -61,25 +69,32 @@
61
69
  "properties": {
62
70
  "id": {
63
71
  "type": "string",
64
- "minLength": 1
72
+ "minLength": 1,
73
+ "description": "Model ID sent to the API."
65
74
  },
66
75
  "name": {
67
76
  "type": "string",
68
- "minLength": 1
77
+ "minLength": 1,
78
+ "description": "Display name, also matched by --model patterns."
69
79
  },
70
80
  "api": {
71
81
  "type": "string",
72
- "minLength": 1
82
+ "minLength": 1,
83
+ "description": "Overrides the provider api."
73
84
  },
74
85
  "baseUrl": {
75
86
  "type": "string",
76
- "minLength": 1
87
+ "minLength": 1,
88
+ "description": "Overrides the provider baseUrl."
77
89
  },
78
90
  "reasoning": {
79
- "type": "boolean"
91
+ "type": "boolean",
92
+ "default": false,
93
+ "description": "Whether the model supports thinking."
80
94
  },
81
95
  "thinkingLevelMap": {
82
- "$ref": "#/$defs/ThinkingLevelMap"
96
+ "$ref": "#/$defs/ThinkingLevelMap",
97
+ "description": "Provider value sent for each thinking level. null marks a level unsupported. Levels the model does not map use the provider's default value through high; xhigh and max are unsupported."
83
98
  },
84
99
  "input": {
85
100
  "type": "array",
@@ -88,7 +103,10 @@
88
103
  "text",
89
104
  "image"
90
105
  ]
91
- }
106
+ },
107
+ "default": [
108
+ "text"
109
+ ]
92
110
  },
93
111
  "inputLimits": {
94
112
  "$ref": "#/$defs/ModelInputLimits"
@@ -98,21 +116,26 @@
98
116
  },
99
117
  "promptCache": {
100
118
  "$ref": "#/$defs/ModelPromptCache",
101
- "description": "Best-effort prompt cache lifetime in seconds for each retention tier. A missing tier means the lifetime is unknown, so Pi does not warm it."
119
+ "description": "Best-effort prompt cache lifetime in seconds for the short and long retention tiers. Pi warms only tiers with a known lifetime."
102
120
  },
103
121
  "contextWindow": {
104
122
  "type": "number",
105
- "exclusiveMinimum": 0
123
+ "exclusiveMinimum": 0,
124
+ "default": 128000,
125
+ "description": "Context window in tokens."
106
126
  },
107
127
  "maxTokens": {
108
128
  "type": "number",
109
- "exclusiveMinimum": 0
129
+ "exclusiveMinimum": 0,
130
+ "default": 16384,
131
+ "description": "Maximum output tokens."
110
132
  },
111
133
  "samplingParams": {
112
134
  "type": "object",
113
135
  "patternProperties": {
114
136
  "^.*$": {}
115
- }
137
+ },
138
+ "description": "Fields merged into every request body. Applies only to OpenAI-compatible APIs."
116
139
  },
117
140
  "samplingParamsByThinkingLevel": {
118
141
  "type": "object",
@@ -159,7 +182,8 @@
159
182
  "^.*$": {}
160
183
  }
161
184
  }
162
- }
185
+ },
186
+ "description": "samplingParams per thinking level, merged over samplingParams."
163
187
  },
164
188
  "headers": {
165
189
  "type": "object",
@@ -167,7 +191,8 @@
167
191
  "^.*$": {
168
192
  "type": "string"
169
193
  }
170
- }
194
+ },
195
+ "description": "Request headers. Values resolve like apiKey."
171
196
  },
172
197
  "compat": {
173
198
  "$ref": "#/$defs/ProviderCompat",
@@ -184,13 +209,16 @@
184
209
  "properties": {
185
210
  "name": {
186
211
  "type": "string",
187
- "minLength": 1
212
+ "minLength": 1,
213
+ "description": "Display name, also matched by --model patterns."
188
214
  },
189
215
  "reasoning": {
190
- "type": "boolean"
216
+ "type": "boolean",
217
+ "description": "Whether the model supports thinking."
191
218
  },
192
219
  "thinkingLevelMap": {
193
- "$ref": "#/$defs/ThinkingLevelMap"
220
+ "$ref": "#/$defs/ThinkingLevelMap",
221
+ "description": "Provider value sent for each thinking level. null marks a level unsupported. Levels the model does not map use the provider's default value through high; xhigh and max are unsupported."
194
222
  },
195
223
  "input": {
196
224
  "type": "array",
@@ -263,21 +291,24 @@
263
291
  },
264
292
  "promptCache": {
265
293
  "$ref": "#/$defs/ModelPromptCache",
266
- "description": "Best-effort prompt cache lifetime in seconds for each retention tier. A missing tier means the lifetime is unknown, so Pi does not warm it."
294
+ "description": "Best-effort prompt cache lifetime in seconds for the short and long retention tiers. Pi warms only tiers with a known lifetime."
267
295
  },
268
296
  "contextWindow": {
269
297
  "type": "number",
270
- "exclusiveMinimum": 0
298
+ "exclusiveMinimum": 0,
299
+ "description": "Context window in tokens."
271
300
  },
272
301
  "maxTokens": {
273
302
  "type": "number",
274
- "exclusiveMinimum": 0
303
+ "exclusiveMinimum": 0,
304
+ "description": "Maximum output tokens."
275
305
  },
276
306
  "samplingParams": {
277
307
  "type": "object",
278
308
  "patternProperties": {
279
309
  "^.*$": {}
280
- }
310
+ },
311
+ "description": "Fields merged into every request body. Applies only to OpenAI-compatible APIs."
281
312
  },
282
313
  "samplingParamsByThinkingLevel": {
283
314
  "type": "object",
@@ -324,7 +355,8 @@
324
355
  "^.*$": {}
325
356
  }
326
357
  }
327
- }
358
+ },
359
+ "description": "samplingParams per thinking level, merged over samplingParams."
328
360
  },
329
361
  "headers": {
330
362
  "type": "object",
@@ -332,7 +364,8 @@
332
364
  "^.*$": {
333
365
  "type": "string"
334
366
  }
335
- }
367
+ },
368
+ "description": "Request headers. Values resolve like apiKey."
336
369
  },
337
370
  "compat": {
338
371
  "$ref": "#/$defs/ProviderCompat",
@@ -1074,6 +1107,27 @@
1074
1107
  },
1075
1108
  "maxItems": 3,
1076
1109
  "description": "Models Anthropic accepts for server-side refusal fallback, with local pricing metadata for returned fallback responses. When absent or empty, callers must omit fallbacks; Anthropic rejects the field for models with no permitted fallback targets."
1110
+ },
1111
+ "imageInput": {
1112
+ "anyOf": [
1113
+ {
1114
+ "type": "string",
1115
+ "const": "assets"
1116
+ },
1117
+ {
1118
+ "type": "string",
1119
+ "const": "images"
1120
+ },
1121
+ {
1122
+ "type": "string",
1123
+ "const": "state-image-urls"
1124
+ }
1125
+ ],
1126
+ "description": "How the service takes classifier images. \"assets\" sends TypeSafe's assets map (PNG and JPEG) and references the images from the state, as TypeSafe and Jev on Workers AI expect. \"images\" sends Clef's images list of data URLs (PNG, JPEG, and WebP, at most four), as Clef on Workers AI expects. \"state-image-urls\" places image_url parts before the state, as OpenRouter expects; OpenRouter drops assets without an error. Auto-detected from the provider, baseUrl, and model ID. Classifier models read it from the provider-level compat; models and modelOverrides entries apply to chat models only."
1127
+ },
1128
+ "sendImageOptInHeader": {
1129
+ "type": "boolean",
1130
+ "description": "Whether requests with images send the TypeSafe-Danger-Zone-Images: true header, which TypeSafe's own API requires for its experimental image input. Defaults to true for the typesafe-system-one API unless the model is detected as OpenRouter."
1077
1131
  }
1078
1132
  },
1079
1133
  "additionalProperties": true
@@ -1,6 +0,0 @@
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-22CYIUS4.js";import{buildCopilotDynamicHeaders,hasCopilotVisionInput}from"./chunk-PGXDEOVV.js";import{Anthropic}from"./chunk-F5ZABL6Z.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{adjustMaxTokensForThinking,buildBaseOptions,clampMaxTokensToContext,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,splitErrorToolResultImages,transformMessages}from"./chunk-OWCYH5W2.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import{parseJsonWithRepair,parseStreamingJson,parseToolCallArguments}from"./chunk-PYGXRV27.js";import{calculateCost,getCurrentTools,getInitialSystemMessage,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript}from"./chunk-HACVPRBJ.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic}from"./chunk-LPXNMA2W.js";import"./chunk-4L3WN2XY.js";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.280",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",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}}function mergeHeaders(...headerSources){let merged={};for(let headers of headerSources)headers&&Object.assign(merged,headers);return merged}function mergeClientHeaders(...headerSources){return mergeHeaders({"User-Agent":getPiUserAgent()},...headerSources)}function hasHeader(headers,name){if(!headers)return!1;let expected=name.toLowerCase();for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===expected&&value!==null&&value.trim().length>0)return!0;return!1}function hasRequestAuth(apiKey,headers){return!!apiKey||hasHeader(headers,"authorization")||hasHeader(headers,"x-api-key")||hasHeader(headers,"cf-aig-authorization")}function assertRequestAuth(provider,apiKey,headers){if(!hasRequestAuth(apiKey,headers))throw new Error(`No API key for provider: ${provider}`)}var PiAnthropic=class extends Anthropic{_shouldResolveDefaultCredentials(){return!1}};function getAnthropicFederation(model,apiKey,headers,env){if(model.provider!=="anthropic"||hasRequestAuth(apiKey,headers))return;let federationRuleId=getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV,env),organizationId=getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV,env),identityTokenFile=getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,env);if(!(!federationRuleId||!organizationId||!identityTokenFile))return{organization_id:organizationId,workspace_id:getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV,env),authentication:{type:"oidc_federation",federation_rule_id:federationRuleId,service_account_id:getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,env),identity_token:{source:"file",path:identityTokenFile}}}}var federationClient,ANTHROPIC_MESSAGE_EVENTS=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function flushSseEvent(state){if(!state.event&&state.data.length===0)return null;let event={event:state.event,data:state.data.join(`
4
- `),raw:[...state.raw]};return state.event=null,state.data=[],state.raw=[],event}function decodeSseLine(line,state){if(line==="")return flushSseEvent(state);if(state.raw.push(line),line.startsWith(":"))return null;let delimiterIndex=line.indexOf(":"),fieldName=delimiterIndex===-1?line:line.slice(0,delimiterIndex),value=delimiterIndex===-1?"":line.slice(delimiterIndex+1);return value.startsWith(" ")&&(value=value.slice(1)),fieldName==="event"?state.event=value:fieldName==="data"&&state.data.push(value),null}function nextLineBreakIndex(text){let carriageReturnIndex=text.indexOf("\r"),newlineIndex=text.indexOf(`
5
- `);return carriageReturnIndex===-1?newlineIndex:newlineIndex===-1?carriageReturnIndex:Math.min(carriageReturnIndex,newlineIndex)}function consumeLine(text){let lineBreakIndex=nextLineBreakIndex(text);if(lineBreakIndex===-1)return null;let nextIndex=lineBreakIndex+1;return text[lineBreakIndex]==="\r"&&text[nextIndex]===`
6
- `&&(nextIndex+=1),{line:text.slice(0,lineBreakIndex),rest:text.slice(nextIndex)}}async function*iterateSseMessages(body,signal){let reader=body.getReader(),decoder=new TextDecoder,state={event:null,data:[],raw:[]},buffer="";try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let consumed2=consumeLine(buffer);for(;consumed2;){buffer=consumed2.rest;let event=decodeSseLine(consumed2.line,state);event&&(yield event),consumed2=consumeLine(buffer)}}buffer+=decoder.decode();let consumed=consumeLine(buffer);for(;consumed;){buffer=consumed.rest;let event=decodeSseLine(consumed.line,state);event&&(yield event),consumed=consumeLine(buffer)}if(buffer.length>0){let event=decodeSseLine(buffer,state);event&&(yield event)}let trailingEvent=flushSseEvent(state);trailingEvent&&(yield trailingEvent)}finally{reader.releaseLock()}}async function*iterateAnthropicEvents(response,signal){if(!response.body)throw new Error("Attempted to iterate over an Anthropic response with no body");let sawMessageStart=!1,sawMessageEnd=!1;for await(let sse of iterateSseMessages(response.body,signal)){if(sse.event==="error")throw new Error(sse.data);if(ANTHROPIC_MESSAGE_EVENTS.has(sse.event??""))try{let event=parseJsonWithRepair(sse.data);event.type==="message_start"?sawMessageStart=!0:event.type==="message_stop"&&(sawMessageEnd=!0),yield event}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join("\\n")}`)}}if(sawMessageStart&&!sawMessageEnd)throw new Error("Anthropic stream ended before message_stop")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,getAnthropicCompat(model).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;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 cacheSessionId=resolveCacheRetention(options?.cacheRetention,options?.env)==="none"?void 0:options?.sessionId,created=createClient(model,apiKey,options?.headers,options?.fetch,copilotDynamicHeaders,cacheSessionId,federation);client=created.client,isOAuth=created.isOAuthToken}let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},disablePreferredStrictTools=!1,response;for(;;){options?.signal?.throwIfAborted();let built=buildParams(model,normalizedContext,isOAuth,options,disablePreferredStrictTools);built.providerThinkingLevel&&(output.providerThinkingLevel=built.providerThinkingLevel);let params=built.params,nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params={...nextParams,stream:!0});try{response=await retryProviderRequest(()=>client.beta.messages.create(params,requestOptions).asResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});break}catch(error){if(options?.signal?.aborted||disablePreferredStrictTools||!built.hasPreferredStrictTools||!(error instanceof Anthropic.APIError)||error.status!==400||error.type!=="invalid_request_error"||!["The compiled grammar is too large","Too many strict tools (","Schemas contains too many parameters with union types ("].some(message=>error.message.includes(message)))throw error;disablePreferredStrictTools=!0,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 blocks=output.content;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}if(event.content_block.type==="text"){let block={type:"text",text:event.content_block.text??"",index:event.index};output.content.push(block),stream2.push({type:"text_start",contentIndex:output.content.length-1,partial:output})}else if(event.content_block.type==="thinking"){let block={type:"thinking",thinking:event.content_block.thinking??"",thinkingSignature:event.content_block.signature??"",index:event.index};output.content.push(block),stream2.push({type:"thinking_start",contentIndex:output.content.length-1,partial:output})}else if(event.content_block.type==="redacted_thinking"){let block={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:event.content_block.data,redacted:!0,index:event.index};output.content.push(block),stream2.push({type:"thinking_start",contentIndex:output.content.length-1,partial:output})}else if(event.content_block.type==="tool_use"){let block={type:"toolCall",id:event.content_block.id,name:isOAuth?fromClaudeCodeName(event.content_block.name,currentTools):event.content_block.name,arguments:event.content_block.input??{},partialJson:"",index:event.index};output.content.push(block),stream2.push({type:"toolcall_start",contentIndex:output.content.length-1,partial:output})}}else if(event.type==="content_block_delta"){if(event.delta.type==="text_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="text"&&(block.text+=event.delta.text,stream2.push({type:"text_delta",contentIndex:index,delta:event.delta.text,partial:output}))}else if(event.delta.type==="thinking_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="thinking"&&(block.thinking+=event.delta.thinking,stream2.push({type:"thinking_delta",contentIndex:index,delta:event.delta.thinking,partial:output}))}else if(event.delta.type==="input_json_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="toolCall"&&(block.partialJson+=event.delta.partial_json,block.arguments=parseStreamingJson(block.partialJson),stream2.push({type:"toolcall_delta",contentIndex:index,delta:event.delta.partial_json,partial:output}))}else if(event.delta.type==="signature_delta"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&block.type==="thinking"&&(block.thinkingSignature=block.thinkingSignature||"",block.thinkingSignature+=event.delta.signature)}}else if(event.type==="content_block_stop"){let index=blocks.findIndex(b=>b.index===event.index),block=blocks[index];block&&(delete block.index,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"&&(Object.assign(block,parseToolCallArguments(block.partialJson)),delete block.partialJson,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)}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");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){for(let block of output.content)delete block.index,delete block.partialJson;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=error instanceof Error?error.message: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){if(model.provider==="github-copilot")return{client:new PiAnthropic({apiKey:null,authToken:apiKey??null,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:mergeClientHeaders({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:mergeClientHeaders({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=mergeClientHeaders({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,isOAuthToken2,nativeToolChanges,options){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),[...new Set(features)]}function buildParams(model,context,isOAuthToken2,options,disablePreferredStrictTools=!1){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,disablePreferredStrictTools);return definitions.some((definition,index)=>{let config=tools[index].constrainedSampling;return definition.strict===!0&&config&&config.type==="json_schema"&&config.strict==="prefer"})&&(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,isOAuthToken2,nativeToolChanges,options),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:"high"};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"){flushPendingSystemMessages();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;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 config=tool.constrainedSampling,strict=disablePreferredStrictTools&&config&&config.type==="json_schema"&&config.strict==="prefer"?void 0:resolveJsonSchemaStrictSampling(tool,supportsStrictTools,isAnthropicStrictUnsupportedKeyword),parameters=getJsonSchemaToolParameters(tool,strict),schema=parameters,legacyInputSchema={type:"object",properties:schema.properties??{},required:schema.required??[]},inputSchema=strict===!0?{...parameters,...legacyInputSchema}:legacyInputSchema;return{name:isOAuthToken2?toClaudeCodeName(tool.name):tool.name,description:tool.description,...supportsEagerToolInputStreaming?{eager_input_streaming:!0}:{},...strict===!0?{strict:!0}:{},input_schema:inputSchema,...cacheControl&&index===tools.length-1?{cache_control:cacheControl}:{}}}):[]}function mapStopReason(reason,stopDetails){switch(reason){case"end_turn":return{stopReason:"stop"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:stopDetails?.explanation||"The model refused to complete the request"};case"pause_turn":return{stopReason:"stop"};case"stop_sequence":return{stopReason:"stop"};case"sensitive":return{stopReason:"error",errorMessage:"Provider stopped with: sensitive"};default:throw new Error(`Unhandled stop reason: ${reason}`)}}export{stream,streamSimple};
@@ -1,2 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-BYHXHV4K.js";import{resolveAzureConfig,resolveDeploymentName}from"./chunk-ZBURYEWF.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{AzureOpenAI}from"./chunk-OO6DJ3CL.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-PJACZCIR.js";import{retryProviderRequest}from"./chunk-PMRZO46Y.js";import{buildBaseOptions,createGrammarToolInputProperties,getPiUserAgent,resolveSamplingParams}from"./chunk-OWCYH5W2.js";import"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import"./chunk-DRQDKNXA.js";import"./chunk-PYGXRV27.js";import{clampThinkingLevel,getDeclaredTools,resolveTranscript,resolveTranscriptTools}from"./chunk-HACVPRBJ.js";import{AssistantMessageEventStream}from"./chunk-LPXNMA2W.js";import"./chunk-4L3WN2XY.js";var AZURE_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode","azure"]),OPENAI_RESPONSES_MIN_OUTPUT_TOKENS=16;function formatAzureOpenAIError(error){return formatProviderError(normalizeProviderError(error),"Azure OpenAI API error")}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let deploymentName=resolveDeploymentName(model,options),output={role:"assistant",content:[],api:"azure-openai-responses",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options),grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages),model.compat?.supportsOpenAIGrammarTools??!1),params=buildParams(model,normalizedContext,options,deploymentName,grammarToolInputProperties),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:openaiStream,response}=await retryProviderRequest(()=>client.responses.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),stream2.push({type:"start",partial:output}),await processResponsesStream(openaiStream,output,stream2,model,{onProviderStreamEvent:options?.onProviderStreamEvent,grammarToolInputProperties}),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Azure OpenAI Responses stream ended without a stop reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.index,delete block.partialJson,delete block.customInput;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={"User-Agent":getPiUserAgent(),...model.headers};options?.headers&&Object.assign(headers,options.headers);let{baseUrl,apiVersion}=resolveAzureConfig(model,options);return new AzureOpenAI({apiKey,apiVersion,dangerouslyAllowBrowser:!0,fetch:options?.fetch,defaultHeaders:headers,baseURL:baseUrl})}function buildParams(model,context,options,deploymentName,grammarToolInputProperties=createGrammarToolInputProperties(getDeclaredTools(context.messages),model.compat?.supportsOpenAIGrammarTools??!1)){let supportsAdditionalTools=model.compat?.supportsAdditionalTools??!1,supportsToolSearch=model.compat?.supportsToolSearch??!1,transcriptTools=resolveTranscriptTools(context.messages,supportsAdditionalTools||supportsToolSearch),messages=convertResponsesMessages(model,context,AZURE_TOOL_CALL_PROVIDERS,{grammarToolInputProperties,supportsMidConvoSystemMessages:model.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools,supportsToolSearch,toolOptions:{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1}}),params={model:deploymentName,input:messages,stream:!0,prompt_cache_key:clampOpenAIPromptCacheKey(options?.sessionId),store:!1};options?.maxTokens&&(params.max_output_tokens=Math.max(options.maxTokens,OPENAI_RESPONSES_MIN_OUTPUT_TOKENS)),options?.temperature!==void 0&&(params.temperature=options?.temperature),transcriptTools.requestTools.length>0&&(params.tools=convertResponsesTools(transcriptTools.requestTools,{supportsStrictMode:model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools:model.compat?.supportsOpenAIGrammarTools??!1})),options?.toolChoice!==void 0&&(params.tool_choice=options.toolChoice);let reasoningEffort=options?.reasoningEffort??(options?.reasoningSummary?"medium":void 0);if(model.reasoning)if(reasoningEffort){let effort=options?.reasoningEffort?model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort:reasoningEffort;params.reasoning={effort,summary:options?.reasoningSummary||"auto"},params.include=["reasoning.encrypted_content"]}else model.thinkingLevelMap?.off!==null&&(params.reasoning={effort:model.thinkingLevelMap?.off??"none"});let samplingParams=resolveSamplingParams(model,reasoningEffort??"off",options?.samplingParams);return samplingParams&&Object.assign(params,samplingParams),params}export{stream,streamSimple};