gemi 0.204.2 → 0.205.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 (248) hide show
  1. package/dist/ai/AgentProvider.d.ts +83 -3
  2. package/dist/ai/AgentProvider.d.ts.map +1 -1
  3. package/dist/ai/client/index.js +12 -10
  4. package/dist/ai/client/index.js.map +1 -1
  5. package/dist/ai/index.d.ts +2 -2
  6. package/dist/ai/index.d.ts.map +1 -1
  7. package/dist/ai/index.js +4 -4
  8. package/dist/ai/index.js.map +3 -3
  9. package/dist/ai/providers/anthropicRequest.d.ts +142 -0
  10. package/dist/ai/providers/anthropicRequest.d.ts.map +1 -0
  11. package/dist/ai/providers/anthropicStream.d.ts +54 -0
  12. package/dist/ai/providers/anthropicStream.d.ts.map +1 -0
  13. package/dist/ai/providers/call.d.ts +14 -3
  14. package/dist/ai/providers/call.d.ts.map +1 -1
  15. package/dist/ai/providers/capabilities.d.ts +31 -0
  16. package/dist/ai/providers/capabilities.d.ts.map +1 -1
  17. package/dist/ai/providers/endpoints.d.ts +51 -0
  18. package/dist/ai/providers/endpoints.d.ts.map +1 -1
  19. package/dist/ai/providers/http.d.ts.map +1 -1
  20. package/dist/ai/providers/request.d.ts +43 -1
  21. package/dist/ai/providers/request.d.ts.map +1 -1
  22. package/dist/ai/runtime.d.ts +5 -1
  23. package/dist/ai/runtime.d.ts.map +1 -1
  24. package/dist/ai/testing/RecordingProvider.d.ts +5 -2
  25. package/dist/ai/testing/RecordingProvider.d.ts.map +1 -1
  26. package/dist/ai/testing/index.js +3 -3
  27. package/dist/ai/testing/index.js.map +3 -3
  28. package/dist/ai/types.d.ts +34 -0
  29. package/dist/ai/types.d.ts.map +1 -1
  30. package/dist/ai/usageMeter.d.ts +4 -1
  31. package/dist/ai/usageMeter.d.ts.map +1 -1
  32. package/dist/app/index.js +2 -2
  33. package/dist/app/index.js.map +1 -1
  34. package/dist/bun/plugin.js +2 -2
  35. package/dist/bun/plugin.js.map +1 -1
  36. package/dist/bun/preload.js +2 -2
  37. package/dist/bun/preload.js.map +1 -1
  38. package/dist/{chunk-2t1eyzvq.js → chunk-06w8hhnk.js} +2 -2
  39. package/dist/{chunk-2t1eyzvq.js.map → chunk-06w8hhnk.js.map} +1 -1
  40. package/dist/{chunk-0t1d9s34.js → chunk-09hzyf9g.js} +3 -3
  41. package/dist/{chunk-0t1d9s34.js.map → chunk-09hzyf9g.js.map} +1 -1
  42. package/dist/{chunk-bq4pgzcd.js → chunk-0cckwd91.js} +2 -2
  43. package/dist/{chunk-bq4pgzcd.js.map → chunk-0cckwd91.js.map} +1 -1
  44. package/dist/{chunk-9hqnecjt.js → chunk-0eq7am78.js} +2 -2
  45. package/dist/{chunk-9hqnecjt.js.map → chunk-0eq7am78.js.map} +1 -1
  46. package/dist/{chunk-jma5d7zd.js → chunk-1em8t2x1.js} +3 -3
  47. package/dist/{chunk-jma5d7zd.js.map → chunk-1em8t2x1.js.map} +1 -1
  48. package/dist/{chunk-ek0dvbck.js → chunk-1tc6j8bn.js} +3 -3
  49. package/dist/{chunk-ek0dvbck.js.map → chunk-1tc6j8bn.js.map} +1 -1
  50. package/dist/{chunk-dk1xxtgk.js → chunk-24tj4dzx.js} +2 -2
  51. package/dist/{chunk-dk1xxtgk.js.map → chunk-24tj4dzx.js.map} +1 -1
  52. package/dist/{chunk-s5hdrpam.js → chunk-34vvev4a.js} +3 -3
  53. package/dist/{chunk-s5hdrpam.js.map → chunk-34vvev4a.js.map} +1 -1
  54. package/dist/{chunk-f52maa9b.js → chunk-3830ee5d.js} +2 -2
  55. package/dist/{chunk-f52maa9b.js.map → chunk-3830ee5d.js.map} +1 -1
  56. package/dist/{chunk-yykrvrpt.js → chunk-39dz1abf.js} +1 -1
  57. package/dist/{chunk-yjvqq4hj.js → chunk-3ek0s8fx.js} +2 -2
  58. package/dist/{chunk-yjvqq4hj.js.map → chunk-3ek0s8fx.js.map} +1 -1
  59. package/dist/{chunk-vsd5h2d9.js → chunk-3z8d8v8q.js} +3 -3
  60. package/dist/{chunk-vsd5h2d9.js.map → chunk-3z8d8v8q.js.map} +1 -1
  61. package/dist/{chunk-f9c8bnzx.js → chunk-460c8k50.js} +3 -3
  62. package/dist/{chunk-f9c8bnzx.js.map → chunk-460c8k50.js.map} +1 -1
  63. package/dist/{chunk-wxyxnbh6.js → chunk-4ksnhx8x.js} +4 -4
  64. package/dist/{chunk-wxyxnbh6.js.map → chunk-4ksnhx8x.js.map} +1 -1
  65. package/dist/chunk-4q59y78y.js +5 -0
  66. package/dist/{chunk-cf7xc02m.js.map → chunk-4q59y78y.js.map} +1 -1
  67. package/dist/{chunk-4m8t67px.js → chunk-65btke6p.js} +2 -2
  68. package/dist/{chunk-4m8t67px.js.map → chunk-65btke6p.js.map} +1 -1
  69. package/dist/{chunk-efnerp0c.js → chunk-6cx6kh04.js} +2 -2
  70. package/dist/{chunk-efnerp0c.js.map → chunk-6cx6kh04.js.map} +1 -1
  71. package/dist/{chunk-jmsfkzav.js → chunk-6ge27ygx.js} +2 -2
  72. package/dist/{chunk-jmsfkzav.js.map → chunk-6ge27ygx.js.map} +1 -1
  73. package/dist/{chunk-x26jb60f.js → chunk-6x2zbh1q.js} +2 -2
  74. package/dist/{chunk-x26jb60f.js.map → chunk-6x2zbh1q.js.map} +1 -1
  75. package/dist/{chunk-0hfzzb3k.js → chunk-6zpf257t.js} +3 -3
  76. package/dist/{chunk-0hfzzb3k.js.map → chunk-6zpf257t.js.map} +1 -1
  77. package/dist/{chunk-cq7hk8v9.js → chunk-72e857nw.js} +2 -2
  78. package/dist/{chunk-cq7hk8v9.js.map → chunk-72e857nw.js.map} +1 -1
  79. package/dist/{chunk-4v5c4mes.js → chunk-77dt2tap.js} +2 -2
  80. package/dist/{chunk-4v5c4mes.js.map → chunk-77dt2tap.js.map} +1 -1
  81. package/dist/{chunk-ptpzh61m.js → chunk-78g1cngk.js} +2 -2
  82. package/dist/{chunk-ptpzh61m.js.map → chunk-78g1cngk.js.map} +1 -1
  83. package/dist/{chunk-d7kknkmq.js → chunk-7wzhdq1x.js} +3 -3
  84. package/dist/{chunk-d7kknkmq.js.map → chunk-7wzhdq1x.js.map} +1 -1
  85. package/dist/{chunk-cg009t41.js → chunk-8a5wngew.js} +2 -2
  86. package/dist/{chunk-cg009t41.js.map → chunk-8a5wngew.js.map} +1 -1
  87. package/dist/{chunk-6g1xac70.js → chunk-8ar7180x.js} +2 -2
  88. package/dist/{chunk-6g1xac70.js.map → chunk-8ar7180x.js.map} +1 -1
  89. package/dist/{chunk-d3k38gk1.js → chunk-8d2g78vc.js} +2 -2
  90. package/dist/{chunk-d3k38gk1.js.map → chunk-8d2g78vc.js.map} +1 -1
  91. package/dist/{chunk-yrbvfda9.js → chunk-8ncqxja2.js} +1 -1
  92. package/dist/{chunk-6w6q9mxe.js → chunk-8q5kxzxn.js} +3 -3
  93. package/dist/{chunk-6w6q9mxe.js.map → chunk-8q5kxzxn.js.map} +1 -1
  94. package/dist/{chunk-y45whafz.js → chunk-9m6mkaqb.js} +2 -2
  95. package/dist/{chunk-y45whafz.js.map → chunk-9m6mkaqb.js.map} +1 -1
  96. package/dist/{chunk-zk1vwwv6.js → chunk-9qyet3nb.js} +2 -2
  97. package/dist/{chunk-zk1vwwv6.js.map → chunk-9qyet3nb.js.map} +1 -1
  98. package/dist/{chunk-p2nqksdq.js → chunk-a7rgrcs0.js} +3 -3
  99. package/dist/{chunk-p2nqksdq.js.map → chunk-a7rgrcs0.js.map} +1 -1
  100. package/dist/{chunk-x244kqcc.js → chunk-a7zqp5m7.js} +2 -2
  101. package/dist/{chunk-x244kqcc.js.map → chunk-a7zqp5m7.js.map} +1 -1
  102. package/dist/{chunk-y5kfqq4f.js → chunk-aed0vv5g.js} +2 -2
  103. package/dist/{chunk-y5kfqq4f.js.map → chunk-aed0vv5g.js.map} +1 -1
  104. package/dist/{chunk-9m7c4mws.js → chunk-ba1h9pm6.js} +2 -2
  105. package/dist/{chunk-9m7c4mws.js.map → chunk-ba1h9pm6.js.map} +1 -1
  106. package/dist/chunk-bb74k64k.js +11 -0
  107. package/dist/chunk-bb74k64k.js.map +21 -0
  108. package/dist/{chunk-7gxmf9rg.js → chunk-bpqkzpkt.js} +2 -2
  109. package/dist/{chunk-7gxmf9rg.js.map → chunk-bpqkzpkt.js.map} +1 -1
  110. package/dist/{chunk-qcrj4t72.js → chunk-bxznwntw.js} +2 -2
  111. package/dist/{chunk-qcrj4t72.js.map → chunk-bxznwntw.js.map} +1 -1
  112. package/dist/{chunk-4c0rb2ng.js → chunk-c8bvpkr2.js} +2 -2
  113. package/dist/{chunk-4c0rb2ng.js.map → chunk-c8bvpkr2.js.map} +1 -1
  114. package/dist/{chunk-jeq8wvj6.js → chunk-cffx7wqp.js} +2 -2
  115. package/dist/{chunk-jeq8wvj6.js.map → chunk-cffx7wqp.js.map} +1 -1
  116. package/dist/{chunk-8jfnn7v6.js → chunk-djnn8vvp.js} +2 -2
  117. package/dist/{chunk-8jfnn7v6.js.map → chunk-djnn8vvp.js.map} +1 -1
  118. package/dist/{chunk-s6bq91cm.js → chunk-dwya9z8p.js} +2 -2
  119. package/dist/{chunk-s6bq91cm.js.map → chunk-dwya9z8p.js.map} +1 -1
  120. package/dist/chunk-e0scxs81.js +5 -0
  121. package/dist/{chunk-xwqdh388.js.map → chunk-e0scxs81.js.map} +4 -4
  122. package/dist/{chunk-0shq2d31.js → chunk-eeq9ty68.js} +2 -2
  123. package/dist/{chunk-0shq2d31.js.map → chunk-eeq9ty68.js.map} +1 -1
  124. package/dist/{chunk-77x9vxht.js → chunk-emt36pxm.js} +2 -2
  125. package/dist/{chunk-77x9vxht.js.map → chunk-emt36pxm.js.map} +1 -1
  126. package/dist/{chunk-k62338g2.js → chunk-etcds9w3.js} +2 -2
  127. package/dist/{chunk-k62338g2.js.map → chunk-etcds9w3.js.map} +1 -1
  128. package/dist/{chunk-kgjcszx0.js → chunk-fe2nkshn.js} +2 -2
  129. package/dist/{chunk-kgjcszx0.js.map → chunk-fe2nkshn.js.map} +1 -1
  130. package/dist/{chunk-d5d3a8bm.js → chunk-fhn92are.js} +2 -2
  131. package/dist/{chunk-d5d3a8bm.js.map → chunk-fhn92are.js.map} +1 -1
  132. package/dist/{chunk-crqbzfd5.js → chunk-g6tqje74.js} +2 -2
  133. package/dist/{chunk-crqbzfd5.js.map → chunk-g6tqje74.js.map} +1 -1
  134. package/dist/{chunk-p9pwskv6.js → chunk-hke4hzfm.js} +2 -2
  135. package/dist/{chunk-p9pwskv6.js.map → chunk-hke4hzfm.js.map} +1 -1
  136. package/dist/{chunk-3gkxnfef.js → chunk-hqg4dfca.js} +2 -2
  137. package/dist/{chunk-3gkxnfef.js.map → chunk-hqg4dfca.js.map} +1 -1
  138. package/dist/{chunk-39hed4yr.js → chunk-hthyn5pj.js} +3 -3
  139. package/dist/{chunk-39hed4yr.js.map → chunk-hthyn5pj.js.map} +1 -1
  140. package/dist/{chunk-w3mc696j.js → chunk-jn1h76sa.js} +2 -2
  141. package/dist/{chunk-w3mc696j.js.map → chunk-jn1h76sa.js.map} +1 -1
  142. package/dist/{chunk-ezvtkbp9.js → chunk-jy26hy7z.js} +2 -2
  143. package/dist/{chunk-ezvtkbp9.js.map → chunk-jy26hy7z.js.map} +1 -1
  144. package/dist/{chunk-5km0np8s.js → chunk-jy61580r.js} +2 -2
  145. package/dist/{chunk-5km0np8s.js.map → chunk-jy61580r.js.map} +1 -1
  146. package/dist/{chunk-phvvxv1a.js → chunk-k8peybx0.js} +3 -3
  147. package/dist/{chunk-phvvxv1a.js.map → chunk-k8peybx0.js.map} +1 -1
  148. package/dist/{chunk-3xzhbkya.js → chunk-m3v661b3.js} +3 -3
  149. package/dist/{chunk-3xzhbkya.js.map → chunk-m3v661b3.js.map} +1 -1
  150. package/dist/{chunk-js9rm7g0.js → chunk-ndcqbwsj.js} +2 -2
  151. package/dist/{chunk-js9rm7g0.js.map → chunk-ndcqbwsj.js.map} +1 -1
  152. package/dist/{chunk-cdgnwzwf.js → chunk-ne51fxg2.js} +2 -2
  153. package/dist/{chunk-cdgnwzwf.js.map → chunk-ne51fxg2.js.map} +1 -1
  154. package/dist/{chunk-b1mdan5a.js → chunk-nfher0gz.js} +2 -2
  155. package/dist/{chunk-b1mdan5a.js.map → chunk-nfher0gz.js.map} +1 -1
  156. package/dist/{chunk-e5mqjren.js → chunk-njnng5ew.js} +4 -4
  157. package/dist/{chunk-e5mqjren.js.map → chunk-njnng5ew.js.map} +1 -1
  158. package/dist/{chunk-e3ehv27z.js → chunk-p9c5rc1z.js} +3 -3
  159. package/dist/{chunk-e3ehv27z.js.map → chunk-p9c5rc1z.js.map} +1 -1
  160. package/dist/{chunk-rr8bzm6k.js → chunk-q1t9gvm1.js} +2 -2
  161. package/dist/{chunk-rr8bzm6k.js.map → chunk-q1t9gvm1.js.map} +1 -1
  162. package/dist/{chunk-xvk6aqd7.js → chunk-q751b0jx.js} +3 -3
  163. package/dist/{chunk-xvk6aqd7.js.map → chunk-q751b0jx.js.map} +1 -1
  164. package/dist/{chunk-1kehwa3s.js → chunk-qc0e278w.js} +1 -1
  165. package/dist/{chunk-re9ac4tc.js → chunk-rbkvkv2m.js} +4 -4
  166. package/dist/{chunk-re9ac4tc.js.map → chunk-rbkvkv2m.js.map} +1 -1
  167. package/dist/{chunk-k1gt7fgy.js → chunk-rjtge67x.js} +3 -3
  168. package/dist/{chunk-k1gt7fgy.js.map → chunk-rjtge67x.js.map} +1 -1
  169. package/dist/{chunk-ybcdxrqx.js → chunk-s1fa5f8b.js} +2 -2
  170. package/dist/{chunk-ybcdxrqx.js.map → chunk-s1fa5f8b.js.map} +1 -1
  171. package/dist/{chunk-8pw4zjnx.js → chunk-scw0vknj.js} +1 -1
  172. package/dist/{chunk-gc9g7c4p.js → chunk-sjve1yvv.js} +3 -3
  173. package/dist/{chunk-gc9g7c4p.js.map → chunk-sjve1yvv.js.map} +1 -1
  174. package/dist/{chunk-wn4j741t.js → chunk-te4vz0rw.js} +2 -2
  175. package/dist/{chunk-wn4j741t.js.map → chunk-te4vz0rw.js.map} +1 -1
  176. package/dist/{chunk-2ngdhbz7.js → chunk-tx5zrdmb.js} +2 -2
  177. package/dist/{chunk-2ngdhbz7.js.map → chunk-tx5zrdmb.js.map} +1 -1
  178. package/dist/{chunk-pq15dt8j.js → chunk-v1d7xya8.js} +15 -15
  179. package/dist/{chunk-pq15dt8j.js.map → chunk-v1d7xya8.js.map} +5 -5
  180. package/dist/{chunk-fq5b1k4n.js → chunk-v2fd69at.js} +2 -2
  181. package/dist/{chunk-fq5b1k4n.js.map → chunk-v2fd69at.js.map} +1 -1
  182. package/dist/{chunk-n5k42dh7.js → chunk-vebstesm.js} +3 -3
  183. package/dist/{chunk-n5k42dh7.js.map → chunk-vebstesm.js.map} +1 -1
  184. package/dist/{chunk-n3kg99yw.js → chunk-vyaedzr8.js} +3 -3
  185. package/dist/{chunk-n3kg99yw.js.map → chunk-vyaedzr8.js.map} +1 -1
  186. package/dist/{chunk-9bjggtdt.js → chunk-wdrmzjtq.js} +2 -2
  187. package/dist/{chunk-9bjggtdt.js.map → chunk-wdrmzjtq.js.map} +1 -1
  188. package/dist/{chunk-5gvc03cv.js → chunk-wfees83q.js} +3 -3
  189. package/dist/{chunk-5gvc03cv.js.map → chunk-wfees83q.js.map} +1 -1
  190. package/dist/{chunk-n26atakz.js → chunk-wpfempaj.js} +3 -3
  191. package/dist/{chunk-n26atakz.js.map → chunk-wpfempaj.js.map} +1 -1
  192. package/dist/{chunk-0pgk811s.js → chunk-wrfz0jsw.js} +2 -2
  193. package/dist/{chunk-0pgk811s.js.map → chunk-wrfz0jsw.js.map} +1 -1
  194. package/dist/{chunk-c7nbzryd.js → chunk-xgc5tj8k.js} +3 -3
  195. package/dist/{chunk-c7nbzryd.js.map → chunk-xgc5tj8k.js.map} +1 -1
  196. package/dist/{chunk-1e82gfk9.js → chunk-yj1h4rzn.js} +3 -3
  197. package/dist/{chunk-1e82gfk9.js.map → chunk-yj1h4rzn.js.map} +1 -1
  198. package/dist/{chunk-k9882kqg.js → chunk-zf1eqgzt.js} +2 -2
  199. package/dist/{chunk-k9882kqg.js.map → chunk-zf1eqgzt.js.map} +1 -1
  200. package/dist/{chunk-4ex4s616.js → chunk-znw55n6g.js} +2 -2
  201. package/dist/{chunk-4ex4s616.js.map → chunk-znw55n6g.js.map} +1 -1
  202. package/dist/{chunk-6bfj0mbp.js → chunk-zvk6dydb.js} +3 -3
  203. package/dist/{chunk-6bfj0mbp.js.map → chunk-zvk6dydb.js.map} +1 -1
  204. package/dist/config/index.js +1 -1
  205. package/dist/console/run.js +2 -2
  206. package/dist/console/run.js.map +1 -1
  207. package/dist/container/index.js +2 -2
  208. package/dist/container/index.js.map +1 -1
  209. package/dist/database/index.js +2 -2
  210. package/dist/database/index.js.map +1 -1
  211. package/dist/email/index.js +2 -2
  212. package/dist/email/index.js.map +1 -1
  213. package/dist/facades/index.js +2 -2
  214. package/dist/facades/index.js.map +1 -1
  215. package/dist/foundation/index.js +2 -2
  216. package/dist/foundation/index.js.map +1 -1
  217. package/dist/http/index.js +2 -2
  218. package/dist/http/index.js.map +1 -1
  219. package/dist/i18n/dictionaryRuntime.js +2 -2
  220. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  221. package/dist/i18n/index.js +2 -2
  222. package/dist/i18n/index.js.map +1 -1
  223. package/dist/kernel/index.js +2 -2
  224. package/dist/kernel/index.js.map +1 -1
  225. package/dist/orm/index.js +2 -2
  226. package/dist/orm/index.js.map +1 -1
  227. package/dist/probe/index.js +2 -2
  228. package/dist/probe/index.js.map +1 -1
  229. package/dist/server/index.js +2 -2
  230. package/dist/server/index.js.map +1 -1
  231. package/dist/services/index.js +2 -2
  232. package/dist/services/index.js.map +1 -1
  233. package/dist/services/queue/work.js +2 -2
  234. package/dist/services/queue/work.js.map +1 -1
  235. package/dist/stats/route-table.js +1 -1
  236. package/dist/support/index.js +2 -2
  237. package/dist/support/index.js.map +1 -1
  238. package/dist/vitest/index.js +2 -2
  239. package/dist/vitest/index.js.map +1 -1
  240. package/package.json +1 -1
  241. package/dist/chunk-1x60thpm.js +0 -8
  242. package/dist/chunk-1x60thpm.js.map +0 -19
  243. package/dist/chunk-cf7xc02m.js +0 -5
  244. package/dist/chunk-xwqdh388.js +0 -5
  245. /package/dist/{chunk-yykrvrpt.js.map → chunk-39dz1abf.js.map} +0 -0
  246. /package/dist/{chunk-yrbvfda9.js.map → chunk-8ncqxja2.js.map} +0 -0
  247. /package/dist/{chunk-1kehwa3s.js.map → chunk-qc0e278w.js.map} +0 -0
  248. /package/dist/{chunk-8pw4zjnx.js.map → chunk-scw0vknj.js.map} +0 -0
@@ -0,0 +1,21 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../ai/providers/http.ts", "../ai/providers/realtime.ts", "../ai/providers/sideband.ts", "../ai/providers/fileRejection.ts", "../ai/providers/stream.ts", "../ai/providers/call.ts", "../ai/providers/request.ts", "../ai/providers/anthropicRequest.ts", "../ai/providers/anthropicStream.ts", "../ai/providers/capabilities.ts", "../ai/providers/endpoints.ts", "../ai/AgentProvider.ts"],
4
+ "sourcesContent": [
5
+ "import type { ProviderRetryInfo } from \"../AgentProvider\";\nimport {\n httpErrorDetail,\n normalizeProviderError,\n ProviderHttpError,\n ProviderTimeoutError,\n} from \"./errors\";\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\nexport type RequestOptions = {\n maxRetries: number;\n timeoutMs: number;\n signal?: AbortSignal;\n /** Injected by the tests. Nothing here should ever need a real socket to be\n * exercised, and a retry policy that is only tested against a live API is\n * one that gets tested during an outage. */\n fetchImpl?: FetchLike;\n /** Takes the caller's signal so the default can clear its timer rather than\n * hold the process open for a backoff nobody is waiting for any more. An\n * injected sleep may ignore it: the wait is raced against the abort either\n * way. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n random?: () => number;\n now?: () => number;\n /**\n * Whether a timeout is worth another attempt. Defaults to `true`.\n *\n * THE ANSWER DEPENDS ON WHAT THE TIMER BOUNDS, which is why this is a\n * parameter and not a policy. For a streamed call the timer covers getting a\n * response and is cleared once the headers land (see `requestWithRetry`), so a\n * timeout means the provider never started answering: nothing was generated,\n * nothing was billed, and retrying is both cheap and likely to work.\n *\n * For a call that returns its whole result in one body, the same timer bounds\n * the *work*. A timeout there means the work probably happened and we hung up\n * before hearing about it — so a retry pays for it a second time, at the same\n * latency, and most likely times out again.\n *\n * MEASURED, because the margin is what makes this urgent rather than\n * theoretical. One `gpt-image-2` render at `quality: \"high\"`, `1536x1024`,\n * against a real Azure deployment: **117.8 seconds**, against a\n * `DEFAULT_TIMEOUT_MS` of 120_000. Two seconds of headroom, about 2%. Any\n * variance crosses it, and with retries on, one such request becomes three\n * two-minute renders, six minutes of waiting, three images billed, and a\n * `ProviderTimeoutError` returned to the caller. (For scale: the same model at\n * `low`/1024² answers in 15s, and an edit in 14–20s.)\n *\n * So the image path passes `false` and the streaming path leaves it alone. A\n * 429 or a 5xx is still retried in both cases: those say the request did not\n * run, which is the opposite of what a timeout says here.\n */\n retryTimeouts?: boolean;\n /**\n * Called once per failed attempt that is about to be retried, before the\n * backoff wait (#1192). `elapsedMs` is measured from `startedAt` when given\n * (the call's first attempt, for a caller that retries around this too), or\n * from this function's first attempt. A hook that throws is ignored: it\n * must not turn a retry into a failure.\n */\n onRetry?: (info: Omit<ProviderRetryInfo, \"phase\">) => void;\n startedAt?: number;\n};\n\n/** The floor of the backoff. Doubling from here gives 0.5s, 1s, 2s, 4s — long\n * enough to outlast a rate-limit window, short enough that a user watching a\n * stream does not assume it died. */\nconst BASE_DELAY_MS = 500;\nexport const MAX_DELAY_MS = 20_000;\n\n/**\n * `Retry-After` in either of its two legal forms: seconds, or an HTTP date.\n *\n * Honoured rather than ignored because the server knows when its window\n * reopens and we are guessing. A value in the past clamps to zero; a garbage\n * value falls back to the computed backoff, since a header we cannot read is\n * not a reason to give up on the request.\n *\n * Parsed here, bounded at the call site: this returns what the server said.\n */\nexport function parseRetryAfter(value: string | null | undefined, now: number): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) return Math.max(0, Number(trimmed) * 1000);\n const date = Date.parse(trimmed);\n if (Number.isNaN(date)) return undefined;\n return Math.max(0, date - now);\n}\n\n/**\n * Exponential backoff with full jitter. The jitter is the point: without it,\n * every request that got rate limited at the same moment retries at the same\n * moment, and the second wave is the same size as the first.\n */\nexport function backoffDelayMs(attempt: number, random: () => number): number {\n const ceiling = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);\n return Math.round(ceiling * (0.5 + random() * 0.5));\n}\n\nfunction isRetryableStatus(status: number): boolean {\n // 429 and the 5xx range. 409 is in here because OpenAI answers it for a\n // request that raced with something on their side, and it succeeds on the\n // second try.\n return status === 429 || status === 408 || status === 409 || status >= 500;\n}\n\n/**\n * One retry policy, not two.\n *\n * The status table alone cannot answer this: a 429 from a spent quota is a 429\n * every time for the rest of the month, and retrying it turns one billing\n * problem into `maxRetries` of them and a much later error message. Only the\n * body says which 429 this is, and `normalizeProviderError` is where that is\n * already read — so it is asked here rather than left to disagree with a table\n * after the retries have happened.\n *\n * It is a veto, not a second opinion: the table decides which statuses are\n * worth another attempt and the normalized verdict can only take one away.\n * That way a future change to the error mapping cannot start retrying 400s.\n */\nfunction shouldRetry(status: number, error: ProviderHttpError): boolean {\n return isRetryableStatus(status) && normalizeProviderError(error).retryable;\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"The operation was aborted.\", \"AbortError\");\n}\n\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(abortReason(signal));\n },\n { once: true },\n );\n });\n}\n\n/**\n * A backoff nobody can interrupt is a `stop()` that does not stop.\n *\n * The wait is where a retrying request spends nearly all of its time — up to\n * 20 seconds of it — and noticing the abort only at the top of the next\n * iteration means the run holds its state, and the user watches a cancelled\n * stream, for the rest of the window. So the sleep loses a race with the\n * signal, and the abort propagates like any other.\n *\n * Shared by the request retry here and the stream retry in `call.ts`, so the\n * two cannot disagree on what an abort during a backoff does.\n */\nexport async function waitUnlessAborted(\n ms: number,\n signal: AbortSignal | undefined,\n sleep: (ms: number, signal?: AbortSignal) => Promise<void> = defaultSleep,\n): Promise<void> {\n if (!signal) return await sleep(ms);\n signal.throwIfAborted();\n let onAbort: (() => void) | undefined;\n try {\n await Promise.race([\n sleep(ms, signal),\n new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(abortReason(signal));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }),\n ]);\n } finally {\n if (onAbort) signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\n/**\n * One HTTP call, retried.\n *\n * The timeout covers getting a response, not consuming one. A streamed answer\n * legitimately takes minutes, and a timeout that kept running would cut off\n * long completions at exactly the point where they were most expensive to\n * abandon — so the timer is cleared once the headers land, and only the\n * caller's own signal or the stream limits (`boundedBody`: idle #1167,\n * duration #1169) can end the body.\n */\nexport async function requestWithRetry(\n url: string,\n init: RequestInit,\n options: RequestOptions,\n): Promise<Response> {\n const doFetch = options.fetchImpl ?? ((u: string, i: RequestInit) => fetch(u, i));\n const sleep = options.sleep ?? defaultSleep;\n const random = options.random ?? Math.random;\n const now = options.now ?? Date.now;\n const maxRetries = Math.max(0, options.maxRetries);\n\n const startedAt = options.startedAt ?? now();\n const wait = (ms: number, attempt: number, error: unknown, timedOut: boolean) => {\n try {\n options.onRetry?.({\n attempt: attempt + 1,\n maxRetries,\n error: normalizeProviderError(error),\n ...httpErrorDetail(error),\n timedOut,\n delayMs: ms,\n elapsedMs: now() - startedAt,\n });\n } catch {\n // See `onRetry`.\n }\n return waitUnlessAborted(ms, options.signal, sleep);\n };\n\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n options.signal?.throwIfAborted();\n\n const controller = new AbortController();\n const abortOuter = () => controller.abort(options.signal?.reason);\n options.signal?.addEventListener(\"abort\", abortOuter, { once: true });\n\n let timedOut = false;\n const timer =\n options.timeoutMs > 0\n ? setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, options.timeoutMs)\n : undefined;\n\n let response: Response;\n try {\n response = await doFetch(url, { ...init, signal: controller.signal });\n } catch (error) {\n if (timer !== undefined) clearTimeout(timer);\n options.signal?.removeEventListener(\"abort\", abortOuter);\n // The caller's abort wins outright — `stop()` means stop, not \"stop and\n // try three more times\".\n if (options.signal?.aborted) throw error;\n lastError = timedOut ? new ProviderTimeoutError(options.timeoutMs) : error;\n // Checked before the attempt count, because this is not \"no attempts\n // left\" — it is \"another attempt is the wrong thing to do\". See\n // `RequestOptions.retryTimeouts`.\n if (timedOut && options.retryTimeouts === false) throw lastError;\n if (attempt === maxRetries) throw lastError;\n await wait(backoffDelayMs(attempt, random), attempt, lastError, timedOut);\n continue;\n }\n\n if (timer !== undefined) clearTimeout(timer);\n\n if (response.ok) {\n // Deliberately left attached: the caller is about to read a stream, and\n // its own signal has to keep reaching it.\n return response;\n }\n\n options.signal?.removeEventListener(\"abort\", abortOuter);\n const body = await readErrorBody(response);\n const error = new ProviderHttpError(\n response.status,\n body,\n // `request-id` is Anthropic's spelling.\n response.headers.get(\"x-request-id\") ?? response.headers.get(\"request-id\") ?? undefined,\n parseRetryAfter(response.headers.get(\"retry-after\"), now()),\n );\n\n if (attempt === maxRetries || !shouldRetry(response.status, error)) throw error;\n\n // Bounded, because `Retry-After` is a number the server chooses and a daily\n // quota answers it in hours. Sleeping through that holds the run open for\n // the whole window; waking early costs one request that gets the same 429\n // and a longer, still-bounded backoff after it. Without the header, a 429\n // whose message names the wait (Azure: \"Please retry after 30 seconds\")\n // is believed too.\n const retryAfter =\n error.retryAfter ??\n (response.status === 429 ? normalizeProviderError(error).retryAfter : undefined);\n await wait(\n retryAfter === undefined\n ? backoffDelayMs(attempt, random)\n : Math.min(retryAfter, MAX_DELAY_MS),\n attempt,\n error,\n false,\n );\n lastError = error;\n }\n\n // Unreachable: the loop either returns or throws. Kept honest rather than\n // asserted away.\n throw lastError ?? new Error(\"Provider request failed with no response.\");\n}\n\nasync function readErrorBody(response: Response): Promise<unknown> {\n let text: string;\n try {\n text = await response.text();\n } catch {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/**\n * `body`, errored when a read waits longer than `idleMs` (`onIdle()`'s error,\n * #1167) or when it is still being read `maxMs` after this was called\n * (`onMax()`'s error, #1169). A limit `<= 0` is off; with both off, or no\n * body, `body` is returned as it is.\n *\n * `requestWithRetry`'s timer stops at the headers, so these are what bound the\n * stream after it started.\n *\n * IDLE. Every chunk resets the clock, so a slow but steady stream is never cut,\n * and a keepalive comment counts as a sign of life. The clock runs only while\n * the consumer is waiting on the source (the stream pulls on demand), so a\n * consumer that is busy between two events is not mistaken for a silent\n * provider.\n *\n * MAX. A wall clock from the moment the response started, which no chunk\n * resets: the one bound a stream that keeps trickling cannot get around. A\n * chunk that is already buffered when the deadline passes is still delivered\n * (the read wins the race against a zero-delay timer), so a stream that\n * finished just in time is not cut.\n *\n * Each callback is expected to abort the request, which releases the socket;\n * the source is cancelled here too, for a fetch that ignores its signal. The\n * same shape as `Storage.fetch()`'s `fetchIdleTimeoutMs`.\n */\nexport function boundedBody(\n body: ReadableStream<Uint8Array> | null,\n limits: { idleMs: number; maxMs: number },\n on: { idle: () => Error; max: () => Error },\n): ReadableStream<Uint8Array> | null {\n const idleMs = limits.idleMs > 0 ? limits.idleMs : 0;\n const maxMs = limits.maxMs > 0 ? limits.maxMs : 0;\n if (!body || (!idleMs && !maxMs)) return body;\n const deadline = maxMs ? performance.now() + maxMs : Infinity;\n const reader = body.getReader();\n return new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let timedOut: Error | undefined;\n const remaining = Math.max(0, deadline - performance.now());\n // Whichever comes first; on a tie the deadline, the limit really hit.\n const byDeadline = !idleMs || remaining <= idleMs;\n const wait = byDeadline ? remaining : idleMs;\n const limit = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n timedOut = byDeadline ? on.max() : on.idle();\n reject(timedOut);\n }, wait);\n });\n try {\n const chunk = await Promise.race([reader.read(), limit]);\n if (chunk.done) controller.close();\n else controller.enqueue(chunk.value);\n } catch (error) {\n // The abort in the callback can error the source first, with\n // whatever fetch throws on abort; the limit is the real cause.\n const reason = timedOut ?? error;\n controller.error(reason);\n reader.cancel(reason).catch(() => {});\n } finally {\n clearTimeout(timer);\n }\n },\n cancel(reason) {\n return reader.cancel(reason);\n },\n },\n { highWaterMark: 0 },\n );\n}\n",
6
+ "import { isSchema, type JSONSchema, type Schema } from \"../Schema\";\nimport type { AgentError, Usage } from \"../types\";\nimport type { ProviderTarget } from \"./endpoints\";\nimport { normalizeProviderError, ProviderHttpError } from \"./errors\";\nimport { requestWithRetry, type FetchLike } from \"./http\";\nimport { RealtimeSideband, type RealtimeSidebandOptions, type WebSocketFactory } from \"./sideband\";\n\n/**\n * Realtime (voice) calls on OpenAI's Realtime API and Azure OpenAI's GA\n * `/openai/v1/realtime` surface (#921).\n *\n * EXPERIMENTAL until a live call has run on Azure and on OpenAI: the request\n * shapes below follow the vendors' documentation and are tested against\n * fixtures only. Names and defaults may change in a minor release.\n *\n * THE SHAPE, and why the server holds every key. The browser makes a WebRTC\n * SDP offer and posts it to the app's own route. The route posts that offer,\n * together with the session config (model, instructions, tools, voice, turn\n * detection, transcription), to `/realtime/calls` with the **server's**\n * credential, and hands back the vendor's SDP answer. So no key or ephemeral\n * secret reaches the browser, and the browser does not choose the model or the\n * prompt when the call starts. It can still read the session (the data channel\n * delivers `session.created` with the instructions and tool schemas) and send\n * its own `session.update` / `response.create`, so instructions must hold no\n * secrets, and metering on the sideband, not the prompt, is what bounds a\n * misbehaving client. The server then opens the call's sideband —\n * `wss://…/realtime?call_id=…` — and that is where tool calls run and usage\n * arrives, which is why metering never has to trust the browser.\n *\n * WHAT THIS FILE IS VERIFIED AGAINST. The documented protocol only, through\n * recorded fixtures; there was no Azure realtime deployment to measure when it\n * was written, and no live key was used. `providers/__fixtures__/realtime-*`\n * hold the request and response shapes the tests assert. When a deployment\n * exists, the measurements belong in this comment, as they are on `azureBase`.\n *\n * POST {base}/realtime/calls multipart: sdp, session (JSON)\n * → 201, body: the SDP answer, `Location: …/realtime/calls/{call_id}`\n * (the \"unified\" flow: OpenAI's documented server-side shape)\n * POST {base}/realtime/calls application/sdp: the raw offer,\n * `Authorization: Bearer <ephemeral secret>` → 201 + `Location`\n * (the \"ephemeral\" flow: Azure's documented server-proxied shape; the\n * session goes into the client secret, minted server-side first)\n * POST {base}/realtime/client_secrets { expires_after, session }\n * → { value, expires_at, session }\n * POST {base}/realtime/calls/{call_id}/hangup\n * WSS {base}/realtime?call_id={call_id} the sideband (see `sideband.ts`)\n *\n * `{base}` is `https://api.openai.com/v1` or `https://<resource>/openai/v1`,\n * from `endpoints.ts` like every other call — this file appends paths and\n * nothing else.\n */\n\n/** Call creation is a handshake, not work: a vendor that has not answered an\n * SDP offer in this long has not started a call worth waiting for. */\nexport const DEFAULT_REALTIME_TIMEOUT_MS = 30_000;\n\n/** The vendor's documented bounds for an ephemeral secret, and its default. */\nexport const CLIENT_SECRET_MIN_SECONDS = 10;\nexport const CLIENT_SECRET_MAX_SECONDS = 7200;\nexport const CLIENT_SECRET_DEFAULT_SECONDS = 600;\n\n// --- session config --------------------------------------------------------\n\n/** A function the voice model may call. Its arguments arrive on the sideband\n * as `response.function_call_arguments.done`. */\nexport type RealtimeTool = {\n name: string;\n description?: string;\n /** A gemi schema (`s.object(...)`) or a plain JSON Schema object. */\n parameters?: Schema<unknown> | JSONSchema | Record<string, unknown>;\n};\n\nexport type RealtimeTurnDetection =\n | {\n type: \"semantic_vad\";\n eagerness?: \"low\" | \"medium\" | \"high\" | \"auto\";\n createResponse?: boolean;\n interruptResponse?: boolean;\n }\n | {\n type: \"server_vad\";\n threshold?: number;\n prefixPaddingMs?: number;\n silenceDurationMs?: number;\n idleTimeoutMs?: number;\n createResponse?: boolean;\n interruptResponse?: boolean;\n };\n\n/**\n * A realtime session, in gemi's names. Mapped onto the vendor's GA `session`\n * object (`type: \"realtime\"`, `audio.input`, `audio.output`, …) by\n * `toVendorSession`.\n *\n * Only the fields an app is likely to set are named. `vendor` is merged into\n * the vendor object last, for anything else the vendor adds, so a new field\n * does not need a gemi release.\n */\nexport type RealtimeSession = {\n /** A voice-agent session, the default. See `TranscriptionSession` for\n * speech-to-text only. */\n type?: \"realtime\";\n /** Defaults to the provider's model (the deployment, on Azure). */\n model?: string;\n instructions?: string;\n voice?: string;\n /** `[\"audio\"]` by default on the vendor's side. */\n outputModalities?: (\"audio\" | \"text\")[];\n tools?: RealtimeTool[];\n toolChoice?: \"auto\" | \"none\" | \"required\" | { name: string };\n /** `null` turns voice activity detection off, for push-to-talk: the client\n * then commits the input buffer itself. */\n turnDetection?: RealtimeTurnDetection | null;\n /** Transcribe what the user says, so captions and transcripts exist. */\n transcription?: { model: string; language?: string; prompt?: string } | null;\n noiseReduction?: \"near_field\" | \"far_field\" | null;\n speed?: number;\n maxOutputTokens?: number | \"inf\";\n /** e.g. `\"auto\"`, or the vendor's retention-ratio object. */\n truncation?: \"auto\" | \"disabled\" | Record<string, unknown>;\n /** Merged into the vendor's session object last. */\n vendor?: Record<string, unknown>;\n};\n\n// --- transcription sessions -------------------------------------------------\n\n/** OpenAI's recommended live speech-to-text model (realtime transcription\n * guide, 10-2026): partial deltas as speech arrives, the final transcript on\n * `input_audio_buffer.commit`. */\nexport const DEFAULT_TRANSCRIPTION_MODEL = \"gpt-live-transcribe\";\n\n/** How long the model waits before emitting text: lower gives earlier\n * partials, higher gives the model more audio and fewer errors. */\nexport type TranscriptionDelay = \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\n/**\n * A transcription session (`session.type: \"transcription\"`): the user's audio\n * in, transcript deltas and final transcripts out, no spoken or written\n * answer. Mapped by `toVendorSession` onto the vendor's\n * `RealtimeTranscriptionSessionCreateRequest`, which has no top-level `model`:\n * the model is the transcription's (`audio.input.transcription.model`).\n *\n * With `gpt-live-transcribe` there is no server-side turn detection (neither\n * `server_vad` nor `semantic_vad`), so `turnDetection` defaults to `null` and\n * the client commits each turn (`input_audio_buffer.commit`) when it hears the\n * user stop — what `useLiveTranscription` in `gemi/ai/voice` does.\n *\n * @experimental Follows OpenAI's realtime transcription guide; not yet run\n * against a live session, and not confirmed on Azure.\n */\nexport type TranscriptionSession = {\n type: \"transcription\";\n /** Default `gpt-live-transcribe`. On Azure, the transcription deployment. */\n model?: string;\n /** Expected input languages (ISO 639-1 such as `en`, `tr`, or the selected\n * ISO 639-3 / `zh-*` codes the vendor lists). `gpt-live-transcribe` and\n * `gpt-transcribe` read this one. */\n languages?: string[];\n /** The single-language hint older models (`gpt-4o-transcribe`,\n * `whisper-1`) read. Never together with `languages`. */\n language?: string;\n /** What the recording is about, in a sentence or two. */\n prompt?: string;\n /** Product names, acronyms and other literal terms likely to be said: hints,\n * not required output. One line each, without `<` or `>`. */\n keywords?: string[];\n /** Latency against accuracy. See `TranscriptionDelay`. */\n delay?: TranscriptionDelay;\n noiseReduction?: \"near_field\" | \"far_field\" | null;\n /** `null` by default (the client commits). Only for models that support\n * server-side detection; `gpt-live-transcribe` does not. */\n turnDetection?: RealtimeTurnDetection | null;\n /** Adds `item.input_audio_transcription.logprobs` to `include`, for models\n * that return them. */\n logprobs?: boolean;\n /** Merged into the vendor's session object last. */\n vendor?: Record<string, unknown>;\n};\n\n/** Either kind of session `createCall`, `clientSecret` and the sideband's\n * `updateSession` take. */\nexport type AnyRealtimeSession = RealtimeSession | TranscriptionSession;\n\nfunction isTranscriptionSession(session: AnyRealtimeSession): session is TranscriptionSession {\n return session.type === \"transcription\";\n}\n\n/** gemi's transcription session onto the vendor's. Refuses, before any\n * request, what the vendor documents it rejects. */\nexport function toVendorTranscriptionSession(\n session: TranscriptionSession,\n): Record<string, unknown> {\n if (session.language !== undefined && session.languages !== undefined) {\n throw new TypeError(\n \"A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).\",\n );\n }\n for (const keyword of session.keywords ?? []) {\n if (/[<>\\r\\n]/.test(keyword)) {\n throw new TypeError(\n `Transcription keywords must be one line without \"<\" or \">\", got ${JSON.stringify(keyword)}.`,\n );\n }\n }\n const transcription: Record<string, unknown> = {\n model: session.model ?? DEFAULT_TRANSCRIPTION_MODEL,\n };\n if (session.prompt !== undefined) transcription.prompt = session.prompt;\n if (session.keywords?.length) transcription.keywords = session.keywords;\n if (session.languages?.length) transcription.languages = session.languages;\n if (session.language !== undefined) transcription.language = session.language;\n if (session.delay !== undefined) transcription.delay = session.delay;\n\n const input: Record<string, unknown> = {\n transcription,\n turn_detection: session.turnDetection ? vendorTurnDetection(session.turnDetection) : null,\n };\n if (session.noiseReduction !== undefined) {\n input.noise_reduction = session.noiseReduction && { type: session.noiseReduction };\n }\n const out: Record<string, unknown> = { type: \"transcription\", audio: { input } };\n if (session.logprobs) out.include = [\"item.input_audio_transcription.logprobs\"];\n return { ...out, ...session.vendor };\n}\n\nfunction toolParameters(parameters: RealtimeTool[\"parameters\"]): unknown {\n if (!parameters) return { type: \"object\", properties: {} };\n return isSchema(parameters) ? parameters.toJSONSchema() : parameters;\n}\n\n/**\n * gemi's session onto the vendor's. A `TranscriptionSession` goes to\n * `toVendorTranscriptionSession` (its model is the transcription's, so the\n * provider's realtime model is not used).\n *\n * `model` is written only when there is one: a `session.update` on a live call\n * must not try to change the model, and `createCall` always passes the\n * provider's.\n */\nexport function toVendorSession(\n session: AnyRealtimeSession,\n model?: string,\n): Record<string, unknown> {\n if (isTranscriptionSession(session)) return toVendorTranscriptionSession(session);\n const out: Record<string, unknown> = { type: \"realtime\" };\n const resolvedModel = session.model ?? model;\n if (resolvedModel) out.model = resolvedModel;\n if (session.instructions !== undefined) out.instructions = session.instructions;\n if (session.outputModalities) out.output_modalities = session.outputModalities;\n if (session.maxOutputTokens !== undefined) out.max_output_tokens = session.maxOutputTokens;\n if (session.truncation !== undefined) out.truncation = session.truncation;\n\n if (session.tools) {\n out.tools = session.tools.map((tool) => ({\n type: \"function\",\n name: tool.name,\n ...(tool.description ? { description: tool.description } : {}),\n parameters: toolParameters(tool.parameters),\n }));\n }\n if (session.toolChoice !== undefined) {\n out.tool_choice =\n typeof session.toolChoice === \"string\"\n ? session.toolChoice\n : { type: \"function\", name: session.toolChoice.name };\n }\n\n const input: Record<string, unknown> = {};\n if (session.turnDetection !== undefined) {\n input.turn_detection = session.turnDetection && vendorTurnDetection(session.turnDetection);\n }\n if (session.transcription !== undefined) input.transcription = session.transcription;\n if (session.noiseReduction !== undefined) {\n input.noise_reduction = session.noiseReduction && { type: session.noiseReduction };\n }\n const output: Record<string, unknown> = {};\n if (session.voice !== undefined) output.voice = session.voice;\n if (session.speed !== undefined) output.speed = session.speed;\n if (Object.keys(input).length || Object.keys(output).length) {\n out.audio = {\n ...(Object.keys(input).length ? { input } : {}),\n ...(Object.keys(output).length ? { output } : {}),\n };\n }\n\n return { ...out, ...session.vendor };\n}\n\nfunction vendorTurnDetection(td: RealtimeTurnDetection): Record<string, unknown> {\n const out: Record<string, unknown> = { type: td.type };\n if (td.createResponse !== undefined) out.create_response = td.createResponse;\n if (td.interruptResponse !== undefined) out.interrupt_response = td.interruptResponse;\n if (td.type === \"semantic_vad\") {\n if (td.eagerness !== undefined) out.eagerness = td.eagerness;\n } else {\n if (td.threshold !== undefined) out.threshold = td.threshold;\n if (td.prefixPaddingMs !== undefined) out.prefix_padding_ms = td.prefixPaddingMs;\n if (td.silenceDurationMs !== undefined) out.silence_duration_ms = td.silenceDurationMs;\n if (td.idleTimeoutMs !== undefined) out.idle_timeout_ms = td.idleTimeoutMs;\n }\n return out;\n}\n\n// --- usage -----------------------------------------------------------------\n\n/**\n * A realtime `response.done`'s `usage` onto gemi's.\n *\n * Its own mapper for the reason `toImageUsage` is: the totals share names with\n * the Responses API's, the details do not. Realtime documents\n * `input_token_details` / `output_token_details` (no `s`), with `audio_tokens`,\n * `text_tokens`, `cached_tokens` and a `cached_tokens_details` split. Both\n * spellings are read, because the Responses API's `input_tokens_details` is one\n * typo away and a vendor normalizing later must not zero the audio share.\n */\nexport function toRealtimeUsage(raw: any): Usage {\n const inputTokens = Number(raw?.input_tokens ?? 0);\n const outputTokens = Number(raw?.output_tokens ?? 0);\n const usage: Usage = {\n inputTokens,\n outputTokens,\n totalTokens: Number(raw?.total_tokens ?? inputTokens + outputTokens),\n };\n const input = raw?.input_token_details ?? raw?.input_tokens_details;\n const output = raw?.output_token_details ?? raw?.output_tokens_details;\n if (typeof input?.cached_tokens === \"number\") usage.cachedInputTokens = input.cached_tokens;\n if (typeof input?.audio_tokens === \"number\") usage.audioInputTokens = input.audio_tokens;\n const cachedAudio = input?.cached_tokens_details?.audio_tokens;\n if (typeof cachedAudio === \"number\") usage.cachedAudioInputTokens = cachedAudio;\n if (typeof input?.image_tokens === \"number\" && input.image_tokens > 0) {\n usage.imageInputTokens = input.image_tokens;\n }\n if (typeof output?.audio_tokens === \"number\") usage.audioOutputTokens = output.audio_tokens;\n return usage;\n}\n\n// --- errors ----------------------------------------------------------------\n\n/**\n * What a realtime HTTP call failed with, as a normalized code. A promise has\n * nowhere else to put it — the same reasoning as `ImageRequestError`, and the\n * vendor's body is on `cause` rather than in `message` for the same reason.\n */\nexport class RealtimeRequestError extends Error {\n readonly code: AgentError[\"code\"];\n readonly retryable: boolean;\n /** The HTTP status, when the vendor answered one. */\n readonly status?: number;\n\n constructor(error: AgentError, options: { cause?: unknown; status?: number } = {}) {\n super(error.message, { cause: options.cause });\n this.name = \"RealtimeRequestError\";\n this.code = error.code;\n this.retryable = error.retryable;\n if (options.status !== undefined) this.status = options.status;\n }\n}\n\n// --- the client ------------------------------------------------------------\n\n/**\n * How `createCall` talks to the vendor. Both run server-side, and neither hands\n * the browser a credential.\n *\n * - `\"unified\"`: one multipart POST (`sdp` + `session`) with the server's key.\n * OpenAI documents this one.\n * - `\"ephemeral\"`: mint a short-lived client secret carrying the session, then\n * POST the raw SDP (`application/sdp`) with that secret as the Bearer. Azure\n * documents this one (\"Azure OpenAI expects application/sdp, not form\n * data\"), so it is Azure's default. The secret is used once, by the server,\n * and dropped.\n */\nexport type RealtimeCallFlow = \"unified\" | \"ephemeral\";\n\n/** How long the secret behind an `\"ephemeral\"` call lives: it only has to\n * outlast one POST. The vendor's minimum is 10 s. */\nconst EPHEMERAL_CALL_SECRET_SECONDS = 60;\n\nexport type CreateCallParams = {\n /** The browser's SDP offer, verbatim. */\n sdp: string;\n /** Overrides the client's flow for this call. */\n flow?: RealtimeCallFlow;\n /**\n * Azure only: `?webrtcfilter=on`, which limits what the browser's data\n * channel receives (no instructions, no function calls, no `response.done`).\n * Keeps the prompt private, but the browser then cannot show \"working\" from\n * the events alone.\n */\n webrtcFilter?: boolean;\n /** A voice-agent session, or `{ type: \"transcription\", … }` for\n * speech-to-text only. */\n session?: AnyRealtimeSession;\n /**\n * A stable, non-identifying id for the end user (e.g. a hash of their id),\n * sent as `OpenAI-Safety-Identifier` so abuse is attributed to a user and not\n * to the whole app.\n */\n safetyIdentifier?: string;\n signal?: AbortSignal;\n};\n\nexport type CreateCallResult = {\n /** Hand this back to the browser for `setRemoteDescription`. */\n sdpAnswer: string;\n /** The call's id, for the sideband and for `hangup`. */\n callId: string;\n};\n\nexport type ClientSecretParams = {\n /** A voice-agent session, or `{ type: \"transcription\", … }`. */\n session?: AnyRealtimeSession;\n /** 10–7200, default 600. */\n ttlSeconds?: number;\n /** Sent as `OpenAI-Safety-Identifier`. The vendor binds it to the secret,\n * so the browser need not send it when it connects. */\n safetyIdentifier?: string;\n signal?: AbortSignal;\n};\n\nexport type ClientSecret = {\n value: string;\n /** Unix seconds. */\n expiresAt: number;\n /** The session the vendor resolved, verbatim. */\n session: unknown;\n /** Where a browser holding this secret posts its SDP offer\n * (`Authorization: Bearer <value>`, `Content-Type: application/sdp`):\n * `…/realtime/calls` on this provider's host. */\n callsUrl: string;\n};\n\nexport type RealtimeClientOptions = {\n /** The model a call uses when its session names none. The deployment, on Azure. */\n model: string;\n /** `\"unified\"` by default; `AzureOpenAIProvider` passes `\"ephemeral\"`. See\n * `RealtimeCallFlow`. */\n callFlow?: RealtimeCallFlow;\n /** Injected by tests. Defaults to the global `fetch`. */\n fetchImpl?: FetchLike;\n /** Injected by tests. Defaults to the global `WebSocket` (Bun's, which takes\n * `headers`). */\n webSocket?: WebSocketFactory;\n};\n\n/**\n * The realtime surface of one provider. `OpenAIProvider#realtime` and\n * `AzureOpenAIProvider#realtime` return one of these, built on the provider's\n * resolved `ProviderTarget`, so the host, the credential and Azure's `/openai`\n * handling come from `endpoints.ts`.\n *\n * @experimental Not yet verified against a live Azure or OpenAI call.\n */\nexport class RealtimeClient {\n readonly model: string;\n private readonly target: ProviderTarget;\n private readonly options: RealtimeClientOptions;\n\n constructor(target: ProviderTarget, options: RealtimeClientOptions) {\n this.target = target;\n this.options = options;\n this.model = options.model;\n }\n\n /** `https://…/v1/realtime/calls` etc. Exposed for logs and tests. */\n url(path: string): string {\n return `${this.target.base}/realtime${path}${this.target.query}`;\n }\n\n /** The sideband's URL for a call: the HTTP base with a `wss` scheme. */\n sidebandUrl(callId: string): string {\n const base = this.target.base.replace(/^http(s?):/i, (_m, s) => `ws${s}:`);\n const query = this.target.query ? `${this.target.query}&` : \"?\";\n return `${base}/realtime${query}call_id=${encodeURIComponent(callId)}`;\n }\n\n /**\n * Starts a WebRTC call from the browser's SDP offer, server-side.\n *\n * Not retried on a timeout: a call the vendor created and we hung up on is\n * not one the browser can join, and a second offer starts a second call.\n * A 429 or 5xx is retried, since those say no call was made.\n */\n async createCall(params: CreateCallParams): Promise<CreateCallResult> {\n const flow = params.flow ?? this.options.callFlow ?? \"unified\";\n let headers: Record<string, string>;\n let body: BodyInit;\n if (flow === \"ephemeral\") {\n const secret = await this.clientSecret({\n session: params.session,\n ttlSeconds: EPHEMERAL_CALL_SECRET_SECONDS,\n signal: params.signal,\n });\n headers = { authorization: `Bearer ${secret.value}`, \"content-type\": \"application/sdp\" };\n body = params.sdp;\n } else {\n const form = new FormData();\n form.set(\"sdp\", params.sdp);\n form.set(\"session\", JSON.stringify(toVendorSession(params.session ?? {}, this.model)));\n headers = await this.target.headers();\n body = form;\n }\n if (params.safetyIdentifier) headers[\"OpenAI-Safety-Identifier\"] = params.safetyIdentifier;\n\n const url = this.url(\"/calls\");\n const response = await this.request(\n params.webrtcFilter ? `${url}${url.includes(\"?\") ? \"&\" : \"?\"}webrtcfilter=on` : url,\n { method: \"POST\", headers, body },\n params.signal,\n );\n const sdpAnswer = await response.text();\n const callId = callIdFrom(response);\n if (!callId) {\n throw new RealtimeRequestError({\n code: \"provider_error\",\n message: \"The provider started a realtime call but did not say which one (no Location).\",\n retryable: false,\n });\n }\n return { sdpAnswer, callId };\n }\n\n /**\n * An ephemeral secret for apps that let the browser connect on its own. The\n * browser then receives the function calls, and its reported usage is not\n * something to bill from — prefer `createCall` plus the sideband.\n */\n async clientSecret(params: ClientSecretParams = {}): Promise<ClientSecret> {\n const seconds = params.ttlSeconds ?? CLIENT_SECRET_DEFAULT_SECONDS;\n if (\n !Number.isInteger(seconds) ||\n seconds < CLIENT_SECRET_MIN_SECONDS ||\n seconds > CLIENT_SECRET_MAX_SECONDS\n ) {\n throw new RangeError(\n `ttlSeconds must be a whole number from ${CLIENT_SECRET_MIN_SECONDS} to ${CLIENT_SECRET_MAX_SECONDS}, got ${seconds}.`,\n );\n }\n const headers: Record<string, string> = {\n ...(await this.target.headers()),\n \"content-type\": \"application/json\",\n };\n if (params.safetyIdentifier) headers[\"OpenAI-Safety-Identifier\"] = params.safetyIdentifier;\n const response = await this.request(\n this.url(\"/client_secrets\"),\n {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n expires_after: { anchor: \"created_at\", seconds },\n session: toVendorSession(params.session ?? {}, this.model),\n }),\n },\n params.signal,\n );\n const json: any = await response.json();\n if (typeof json?.value !== \"string\") {\n throw new RealtimeRequestError({\n code: \"provider_error\",\n message: \"The provider answered a client secret request with no secret.\",\n retryable: false,\n });\n }\n return {\n value: json.value,\n expiresAt: Number(json.expires_at ?? 0),\n session: json.session,\n callsUrl: this.url(\"/calls\"),\n };\n }\n\n /**\n * Ends a call for everyone: the browser's peer connection closes and so does\n * any sideband.\n *\n * A 404 counts as \"already over\" only when its body says the *call* was not\n * found. Any other 404 — a route the vendor does not have (Azure does not\n * document `/hangup`), a wrong deployment — throws, because treating it as\n * success would let the caller drop the sideband, the only thing metering\n * the call, while the call goes on.\n */\n async hangup(callId: string, options: { signal?: AbortSignal } = {}): Promise<void> {\n try {\n await this.request(\n this.url(`/calls/${encodeURIComponent(callId)}/hangup`),\n { method: \"POST\", headers: await this.target.headers() },\n options.signal,\n );\n } catch (error) {\n if (isCallNotFound(error, callId)) return;\n throw error;\n }\n }\n\n /**\n * The call's server-side control channel. Opens at once; events sent before\n * it is open are queued. See `RealtimeSideband`.\n */\n sideband(callId: string, options: RealtimeSidebandOptions = {}): RealtimeSideband {\n return new RealtimeSideband({\n ...options,\n callId,\n url: this.sidebandUrl(callId),\n headers: this.target.headers,\n webSocket: options.webSocket ?? this.options.webSocket,\n hangup: () => this.hangup(callId),\n });\n }\n\n private async request(url: string, init: RequestInit, signal?: AbortSignal): Promise<Response> {\n try {\n return await requestWithRetry(url, init, {\n maxRetries: this.target.maxRetries,\n timeoutMs: this.target.timeoutMs,\n retryTimeouts: false,\n signal,\n fetchImpl: this.options.fetchImpl,\n });\n } catch (error) {\n if (signal?.aborted) throw error;\n throw new RealtimeRequestError(normalizeProviderError(error), {\n cause: error,\n ...(error instanceof ProviderHttpError ? { status: error.status } : {}),\n });\n }\n }\n}\n\n/**\n * A hangup's 404 that names the call, not the route: an error body whose code\n * or message is about the call (or its id). A bare 404, or \"Resource not\n * found\", is a route the vendor does not serve.\n */\nexport function isCallNotFound(error: unknown, callId: string): boolean {\n if (!(error instanceof RealtimeRequestError) || error.status !== 404) return false;\n const body: any = error.cause instanceof ProviderHttpError ? error.cause.body : undefined;\n const detail = body?.error ?? body;\n const code = String(detail?.code ?? \"\").toLowerCase();\n const message = String(detail?.message ?? \"\").toLowerCase();\n if (code.includes(\"call\")) return true;\n if (message.includes(callId.toLowerCase())) return true;\n return /\\bcall\\b/.test(message) && /not (be )?found|does not exist|no longer|ended/.test(message);\n}\n\n/** `Location: /v1/realtime/calls/rtc_123` → `rtc_123`. */\nfunction callIdFrom(response: Response): string | undefined {\n const location = response.headers.get(\"location\");\n if (!location) return undefined;\n const path = location.split(\"?\")[0]!.replace(/\\/+$/, \"\");\n const id = path.slice(path.lastIndexOf(\"/\") + 1);\n return id ? decodeURIComponent(id) : undefined;\n}\n",
7
+ "import type { Usage } from \"../types\";\nimport type { AnyRealtimeSession } from \"./realtime\";\nimport { toRealtimeUsage, toVendorSession } from \"./realtime\";\n\n/**\n * A realtime call's sideband: the server's own WebSocket to a call the browser\n * joined over WebRTC (`wss://…/realtime?call_id=…`).\n *\n * WHY IT EXISTS. The browser holds the audio; the server holds the authority.\n * Every function call the voice model makes arrives here, and so does every\n * `response.done` with its usage — so tools run with the server's checks and\n * metering does not depend on what a browser chooses to report. The server can\n * also end the call (`hangup`), which a browser-only design cannot.\n *\n * THE EVENTS ARE THE VENDOR'S, as documented for the GA Realtime API, with two\n * additions and one normalisation:\n *\n * - `response.done` gains `usage`, gemi's `Usage` (audio tokens included).\n * - `sideband.reconnected` and `sideband.closed` are gemi's own, so a consumer\n * iterating events learns about the connection in the same loop.\n * - The beta names for transcript and text deltas are renamed to the GA ones\n * (`response.audio_transcript.delta` → `response.output_audio_transcript.delta`),\n * so code written against one surface does not miss events on the other.\n *\n * Keeping the vendor's names — rather than mapping each event onto gemi's — is\n * a deliberate trade: the protocol has some forty server events, the vendor\n * adds more, and a mapping layer would drop every one it did not know. An\n * unknown event arrives as itself, with its own `type`.\n *\n * VERIFIED against the documented protocol through fixtures only; see\n * `realtime.ts`. Whether Azure accepts `call_id` on its sideband the way OpenAI\n * does is the open question #921 records.\n */\n\n// --- events ----------------------------------------------------------------\n\n/** The vendor's error envelope on an `error` event. */\nexport type RealtimeErrorDetail = {\n type?: string;\n code?: string;\n message: string;\n param?: string;\n event_id?: string;\n};\n\nexport type RealtimeServerEvent =\n | { type: \"session.created\" | \"session.updated\"; event_id?: string; session: Record<string, any> }\n | { type: \"error\"; event_id?: string; error: RealtimeErrorDetail }\n | { type: \"input_audio_buffer.speech_started\"; item_id: string; audio_start_ms?: number }\n | { type: \"input_audio_buffer.speech_stopped\"; item_id: string; audio_end_ms?: number }\n | { type: \"input_audio_buffer.committed\"; item_id: string; previous_item_id?: string | null }\n | { type: \"conversation.item.input_audio_transcription.delta\"; item_id: string; delta: string }\n | {\n type: \"conversation.item.input_audio_transcription.completed\";\n item_id: string;\n transcript: string;\n /** The vendor's, verbatim: `{ type: \"tokens\", … }` or `{ type: \"duration\", seconds }`. */\n usage?: Record<string, any>;\n /** gemi's: a token-billed transcription's usage, mapped (audio tokens in\n * `audioInputTokens`). Billed apart from `response.done`'s, at the\n * transcription model's rates. */\n transcriptionUsage?: Usage;\n /** gemi's: a duration-billed transcription's seconds. */\n transcriptionSeconds?: number;\n }\n | {\n type: \"conversation.item.input_audio_transcription.failed\";\n item_id: string;\n content_index?: number;\n error: RealtimeErrorDetail;\n }\n | { type: \"response.created\"; response: Record<string, any> }\n | {\n type: \"response.output_audio_transcript.delta\" | \"response.output_text.delta\";\n response_id: string;\n item_id: string;\n delta: string;\n }\n | {\n type: \"response.output_audio_transcript.done\";\n response_id: string;\n item_id: string;\n transcript: string;\n }\n | { type: \"response.output_text.done\"; response_id: string; item_id: string; text: string }\n | {\n type: \"response.function_call_arguments.done\";\n response_id: string;\n item_id: string;\n /** The id the `function_call_output` must answer. */\n call_id: string;\n name: string;\n /** JSON, as the model wrote it. Untrusted: parse and validate. */\n arguments: string;\n }\n | {\n type: \"response.done\";\n response: {\n id: string;\n status: \"completed\" | \"cancelled\" | \"failed\" | \"incomplete\" | (string & {});\n status_details?: Record<string, any> | null;\n output?: Record<string, any>[];\n usage?: Record<string, any>;\n [key: string]: unknown;\n };\n /** gemi's: the response's usage, mapped. Absent when the vendor sent none. */\n usage?: Usage;\n }\n | { type: \"output_audio_buffer.started\" | \"output_audio_buffer.stopped\"; response_id?: string }\n | { type: \"sideband.reconnected\"; attempt: number }\n | {\n type: \"sideband.closed\";\n code: number;\n reason: string;\n /** `true` when this side closed it (`close()` / `hangup()`). */\n byClient: boolean;\n };\n\n/** Any event, including ones gemi has no type for. Narrow on `type`. */\nexport type RealtimeEvent = RealtimeServerEvent | { type: string; [key: string]: unknown };\n\nconst RENAMED: Record<string, string> = {\n \"response.audio_transcript.delta\": \"response.output_audio_transcript.delta\",\n \"response.audio_transcript.done\": \"response.output_audio_transcript.done\",\n \"response.text.delta\": \"response.output_text.delta\",\n \"response.text.done\": \"response.output_text.done\",\n \"response.audio.delta\": \"response.output_audio.delta\",\n \"response.audio.done\": \"response.output_audio.done\",\n};\n\n/** One frame off the socket onto a `RealtimeEvent`. `undefined` for a frame\n * that is not a JSON object with a `type`. Exported for tests. */\nexport function parseRealtimeEvent(data: unknown): RealtimeEvent | undefined {\n if (typeof data !== \"string\") return undefined;\n let event: any;\n try {\n event = JSON.parse(data);\n } catch {\n return undefined;\n }\n if (!event || typeof event !== \"object\" || typeof event.type !== \"string\") return undefined;\n const renamed = RENAMED[event.type];\n if (renamed) event.type = renamed;\n if (event.type === \"response.done\" && event.response?.usage) {\n event.usage = toRealtimeUsage(event.response.usage);\n }\n if (event.type === \"conversation.item.input_audio_transcription.completed\" && event.usage) {\n if (event.usage.type === \"duration\") {\n const seconds = Number(event.usage.seconds);\n if (Number.isFinite(seconds)) event.transcriptionSeconds = seconds;\n } else {\n event.transcriptionUsage = toRealtimeUsage(event.usage);\n }\n }\n return event as RealtimeEvent;\n}\n\n// --- client events ---------------------------------------------------------\n\n/** A client event as the vendor documents it. `send` takes any of them. */\nexport type RealtimeClientEvent = { type: string; [key: string]: unknown };\n\nexport type RealtimeResponseOptions = {\n /** Instructions for this response only, e.g. \"Say this in one sentence.\" */\n instructions?: string;\n toolChoice?: \"auto\" | \"none\" | \"required\" | { name: string };\n outputModalities?: (\"audio\" | \"text\")[];\n /** `\"none\"` makes an out-of-band response that is not added to the\n * conversation. */\n conversation?: \"auto\" | \"none\";\n metadata?: Record<string, string>;\n /** Merged into the vendor's `response` object last. */\n vendor?: Record<string, unknown>;\n};\n\n// --- the socket ------------------------------------------------------------\n\n/** The part of the WHATWG `WebSocket` the sideband uses. */\nexport type WebSocketLike = {\n readonly readyState: number;\n send(data: string): void;\n close(code?: number, reason?: string): void;\n addEventListener(\n type: \"open\" | \"message\" | \"close\" | \"error\",\n listener: (event: any) => void,\n ): void;\n};\n\n/** Opens a socket with headers. Bun's `WebSocket` takes `{ headers }` as its\n * second argument, which is what the default uses. */\nexport type WebSocketFactory = (\n url: string,\n init: { headers: Record<string, string> },\n) => WebSocketLike;\n\nconst OPEN = 1;\n\n/** Events kept for an iterator that has not started yet. */\nconst BACKLOG_LIMIT = 500;\n\nfunction defaultWebSocket(url: string, init: { headers: Record<string, string> }): WebSocketLike {\n const Ctor = (globalThis as { WebSocket?: new (url: string, init?: unknown) => WebSocketLike })\n .WebSocket;\n if (!Ctor) throw new Error(\"No global WebSocket: the realtime sideband needs Bun or Node 22+.\");\n return new Ctor(url, { headers: init.headers });\n}\n\nexport type RealtimeSidebandOptions = {\n /**\n * Re-opening a dropped sideband by `callId`. The call itself survives a lost\n * control socket, but a call nobody is metering is the thing this exists to\n * prevent, so a consumer that gives up should `hangup()`.\n *\n * Only an abnormal close is retried. A normal close (1000) is the vendor\n * saying the call is over.\n */\n reconnect?: { attempts?: number; delayMs?: number };\n webSocket?: WebSocketFactory;\n};\n\ntype SidebandInit = RealtimeSidebandOptions & {\n callId: string;\n url: string;\n headers: () => Promise<Record<string, string>>;\n hangup: () => Promise<void>;\n};\n\ntype Subscriber = {\n queue: RealtimeEvent[];\n wake?: () => void;\n done: boolean;\n};\n\nexport class RealtimeSideband implements AsyncIterable<RealtimeEvent> {\n readonly callId: string;\n /** Resolves when the socket first opens; rejects when it never does. */\n readonly ready: Promise<void>;\n /** Resolves with the final `sideband.closed` event. */\n readonly closed: Promise<Extract<RealtimeServerEvent, { type: \"sideband.closed\" }>>;\n\n private readonly init: SidebandInit;\n private socket?: WebSocketLike;\n private finalEvent?: Extract<RealtimeServerEvent, { type: \"sideband.closed\" }>;\n private outbox: string[] = [];\n private subscribers = new Set<Subscriber>();\n private listeners = new Set<(event: RealtimeEvent) => void>();\n /** Events that arrived before anyone subscribed, handed to the first one. */\n private backlog: RealtimeEvent[] | undefined = [];\n private closing = false;\n private finished = false;\n private everOpened = false;\n private failures = 0;\n private resolveReady!: () => void;\n private rejectReady!: (error: Error) => void;\n private resolveClosed!: (\n event: Extract<RealtimeServerEvent, { type: \"sideband.closed\" }>,\n ) => void;\n\n constructor(init: SidebandInit) {\n this.init = init;\n this.callId = init.callId;\n this.ready = new Promise<void>((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n // A consumer that only iterates must not get an unhandled rejection for a\n // sideband that never opened: it learns from `sideband.closed`.\n this.ready.catch(() => {});\n this.closed = new Promise((resolve) => (this.resolveClosed = resolve));\n void this.open();\n }\n\n // --- sending -------------------------------------------------------------\n\n /** Sends a client event; queued while the socket is (re)connecting. */\n send(event: RealtimeClientEvent): void {\n if (this.finished || this.closing) return;\n const data = JSON.stringify(event);\n if (this.socket?.readyState === OPEN) this.socket.send(data);\n else this.outbox.push(data);\n }\n\n updateSession(session: AnyRealtimeSession): void {\n this.send({ type: \"session.update\", session: toVendorSession(session) });\n }\n\n /** Adds an item to the conversation without asking for a response. */\n addItem(item: Record<string, unknown>): void {\n this.send({ type: \"conversation.item.create\", item });\n }\n\n /**\n * A quiet note for the voice model (a `system` message): context it can use\n * on its next answer, without making it speak now.\n */\n addNote(text: string): void {\n this.addItem({ type: \"message\", role: \"system\", content: [{ type: \"input_text\", text }] });\n }\n\n /** Answers a function call. `output` is sent as-is when a string, as JSON\n * otherwise. Call `createResponse()` after it for the model to speak. */\n functionOutput(callId: string, output: unknown): void {\n this.addItem({\n type: \"function_call_output\",\n call_id: callId,\n output: typeof output === \"string\" ? output : JSON.stringify(output),\n });\n }\n\n createResponse(options: RealtimeResponseOptions = {}): void {\n const response: Record<string, unknown> = {};\n if (options.instructions !== undefined) response.instructions = options.instructions;\n if (options.toolChoice !== undefined) {\n response.tool_choice =\n typeof options.toolChoice === \"string\"\n ? options.toolChoice\n : { type: \"function\", name: options.toolChoice.name };\n }\n if (options.outputModalities) response.output_modalities = options.outputModalities;\n if (options.conversation) response.conversation = options.conversation;\n if (options.metadata) response.metadata = options.metadata;\n Object.assign(response, options.vendor);\n this.send(\n Object.keys(response).length\n ? { type: \"response.create\", response }\n : { type: \"response.create\" },\n );\n }\n\n cancelResponse(responseId?: string): void {\n this.send(\n responseId\n ? { type: \"response.cancel\", response_id: responseId }\n : { type: \"response.cancel\" },\n );\n }\n\n // --- receiving -----------------------------------------------------------\n\n /** Calls `listener` for every event from now on. Returns an unsubscribe. */\n on(listener: (event: RealtimeEvent) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Every event, in order, until the sideband closes for good (the last one is\n * `sideband.closed`). Each iterator gets the events from the moment it\n * starts; the first one also gets any that arrived before it.\n */\n [Symbol.asyncIterator](): AsyncIterator<RealtimeEvent> {\n const sub: Subscriber = { queue: this.backlog ?? [], done: this.finished };\n this.backlog = undefined;\n this.subscribers.add(sub);\n const next = async (): Promise<IteratorResult<RealtimeEvent>> => {\n for (;;) {\n const event = sub.queue.shift();\n if (event) return { value: event, done: false };\n if (sub.done) {\n this.subscribers.delete(sub);\n return { value: undefined, done: true };\n }\n await new Promise<void>((resolve) => (sub.wake = resolve));\n sub.wake = undefined;\n }\n };\n return {\n next,\n return: async () => {\n sub.done = true;\n sub.queue.length = 0;\n this.subscribers.delete(sub);\n return { value: undefined, done: true };\n },\n };\n }\n\n // --- ending --------------------------------------------------------------\n\n /** Closes this side's control socket. The call goes on; another process can\n * open its own sideband by `callId`. */\n close(code = 1000, reason = \"closed\"): void {\n if (this.finished || this.closing) return;\n this.closing = true;\n if (this.socket && this.socket.readyState <= OPEN) this.socket.close(code, reason);\n else this.finish(code, reason, true);\n }\n\n /**\n * Ends the call for everyone, then closes the socket.\n *\n * When the vendor refuses the hangup, the socket stays open and the error is\n * thrown: the call may still be running, and this socket is what meters it.\n * The caller decides whether to retry or to wait for the vendor to close it.\n * A sideband the vendor already closed normally (the call is over) needs no\n * hangup, so its failure is ignored.\n */\n async hangup(): Promise<void> {\n try {\n await this.init.hangup();\n } catch (error) {\n if (this.finalEvent && !this.finalEvent.byClient && this.finalEvent.code === 1000) return;\n throw error;\n }\n this.close(1000, \"hangup\");\n }\n\n // --- internals -----------------------------------------------------------\n\n private async open(): Promise<void> {\n let socket: WebSocketLike;\n try {\n const headers = await this.init.headers();\n if (this.closing) return this.finish(1000, \"closed\", true);\n socket = (this.init.webSocket ?? defaultWebSocket)(this.init.url, { headers });\n } catch (error) {\n return this.dropped(1006, error instanceof Error ? error.message : String(error), false);\n }\n this.socket = socket;\n let opened = false;\n\n socket.addEventListener(\"open\", () => {\n opened = true;\n const reconnected = this.everOpened;\n this.everOpened = true;\n const attempt = this.failures;\n this.failures = 0;\n for (const data of this.outbox.splice(0)) socket.send(data);\n this.resolveReady();\n if (reconnected) this.emit({ type: \"sideband.reconnected\", attempt });\n });\n socket.addEventListener(\"message\", (message: { data: unknown }) => {\n const event = parseRealtimeEvent(message.data);\n if (event) this.emit(event);\n });\n socket.addEventListener(\"close\", (event: { code?: number; reason?: string }) => {\n if (this.socket !== socket) return;\n this.dropped(event.code ?? 1006, event.reason ?? \"\", opened);\n });\n // `error` is always followed by `close`, which decides what happens.\n socket.addEventListener(\"error\", () => {});\n }\n\n private dropped(code: number, reason: string, wasOpen: boolean): void {\n this.socket = undefined;\n if (this.closing) return this.finish(code, reason, true);\n const attempts = this.init.reconnect?.attempts ?? 3;\n // 1000 is the vendor ending the call. Anything else, or a socket that never\n // opened, is worth another try by `callId`.\n const retry = (code !== 1000 || !wasOpen) && this.failures < attempts;\n if (!retry) return this.finish(code, reason, false);\n this.failures += 1;\n const delay = (this.init.reconnect?.delayMs ?? 500) * 2 ** (this.failures - 1);\n setTimeout(() => void this.open(), delay);\n }\n\n private finish(code: number, reason: string, byClient: boolean): void {\n if (this.finished) return;\n this.finished = true;\n this.outbox.length = 0;\n const event = { type: \"sideband.closed\" as const, code, reason, byClient };\n this.finalEvent = event;\n this.emit(event);\n for (const sub of this.subscribers) {\n sub.done = true;\n sub.wake?.();\n }\n if (!this.everOpened)\n this.rejectReady(new Error(`Realtime sideband did not open (${code} ${reason}).`));\n this.resolveClosed(event);\n }\n\n private emit(event: RealtimeEvent): void {\n if (this.backlog) {\n // Bounded: a consumer that only uses `on()` never drains it.\n this.backlog.push(event);\n if (this.backlog.length > BACKLOG_LIMIT) this.backlog.shift();\n }\n for (const sub of this.subscribers) {\n if (sub.done) continue;\n sub.queue.push(event);\n sub.wake?.();\n }\n for (const listener of this.listeners) {\n try {\n listener(event);\n } catch {\n // A listener's bug must not stop the others or the iterator.\n }\n }\n }\n}\n",
8
+ "import type { AgentMessage } from \"../types\";\nimport { ProviderHttpError } from \"./errors\";\nimport type { ResponsesInputItem, ResponsesRequest } from \"./request\";\n\n/**\n * A stored file the provider will not read, and what to do about it (#684).\n *\n * THE FAILURE. A `FilePart` lives in the thread's history and goes back up on\n * every request. If the provider refuses its `file_id` — an id from the wrong\n * upload purpose, a file that was deleted or expired, a resource that no longer\n * owns it — the turn that added it fails with a 400, and so does every turn\n * after it, because the history that holds the part is the history every turn\n * sends. The user's only way out was a new thread.\n *\n * THE FIX. When a 400 names a file block of the request, that block is swapped\n * for a line of text saying the attachment could not be read, and the request\n * is sent again. The model is told, so it can tell the user rather than answer\n * as though it had read the file. `Agent` is told too (a `file-rejected`\n * provider event), and marks the stored part `providerRejected` so later turns\n * send the note instead of the id and do not pay for a failed request first.\n *\n * WHAT A REFUSAL LOOKS LIKE, MEASURED against a live Azure resource (gpt-6-sol,\n * `/openai/v1`, `api-version=preview`, 2026-10-01). Each body is recorded in\n * `__fixtures__` and the tests read those files:\n *\n * A `user_data` id (`azure-error-file-id-prefix.json`): `param` points at the\n * block, `input[2].content[1].file_id`, and the message says `Expected an\n * ID that begins with 'assistant'`. With TWO such ids in one request only\n * the first is named, which is why more than one retry is allowed below.\n * An id that does not exist, or a file that was deleted\n * (`azure-error-files-not-found.json`, `azure-error-file-deleted.json`):\n * `param: null`, and the message lists every missing id at once —\n * `Files [assistant-…, assistant-…] were not found due to ownership\n * verification failure.` So the ids are read out of the message, by\n * matching the ids the request actually sent rather than by parsing the\n * sentence, which also covers OpenAI's wording without having measured it.\n * The right id in the wrong block (`azure-error-file-type.json`): `param:\n * \"input\"` and `… but got .png.`, naming neither the block nor the id. The\n * block is found by the extension and the block type the message names,\n * and only when that settles on exactly one file: guessing between two\n * would hide a file that was fine.\n *\n * Anything else is left alone and fails the turn as it did before. In\n * particular a refusal that names no file in this request is not retried: a\n * retry is only worth sending when something about the request has changed.\n */\n\n/** What the request builder knew about each file id it sent, for the note. */\nexport type SentFile = { name?: string; mimeType?: string };\n\n/**\n * How many times one call may be re-sent for a rejected file. Each retry has to\n * take out a file the previous ones did not, so this bounds requests, not\n * files: Azure names one bad block per 400 (`param` holds a single path), and\n * a thread that picked up several `user_data` ids before #682 would otherwise\n * clear one per turn and fail every turn until it ran out.\n */\nexport const MAX_FILE_REJECTION_RETRIES = 3;\n\n/** The file ids in a history, with the name each was attached under. */\nexport function sentFiles(messages: AgentMessage[]): Map<string, SentFile> {\n const files = new Map<string, SentFile>();\n for (const message of messages) {\n for (const part of message.content ?? []) {\n if (part.type !== \"file\" || !part.fileId || files.has(part.fileId)) continue;\n files.set(part.fileId, { name: part.name, mimeType: part.mimeType });\n }\n }\n return files;\n}\n\n/**\n * The file ids a provider error blames, among the ones `body` sent.\n *\n * Empty when the error is not a 400/404 from the API, or names nothing in this\n * request — which is the signal not to retry.\n */\nexport function rejectedFileIds(\n body: ResponsesRequest,\n error: unknown,\n files: Map<string, SentFile> = new Map(),\n): string[] {\n if (!(error instanceof ProviderHttpError)) return [];\n if (error.status !== 400 && error.status !== 404) return [];\n const detail = errorDetail(error.body);\n if (!detail) return [];\n\n const blocks = fileBlocks(body.input);\n if (blocks.length === 0) return [];\n\n // 1. The block, by its path. The most precise answer there is.\n const path = /^input\\[(\\d+)\\]\\.content\\[(\\d+)\\]\\.file_id$/.exec(detail.param ?? \"\");\n if (path) {\n const item = body.input[Number(path[1])];\n const block = contentOf(item)[Number(path[2])];\n const id = block && typeof block.file_id === \"string\" ? block.file_id : undefined;\n if (id) return [id];\n }\n\n // 2. The ids, by name. Matched against what was sent, so a message that\n // mentions an id this request never held cannot blame one that it did.\n const message = detail.message ?? \"\";\n const named = unique(blocks.map((block) => block.fileId).filter((id) => mentions(message, id)));\n if (named.length > 0) return named;\n\n // 3. The wrong block for the file's type. No id and no path, so it has to be\n // worked out, and it is only worth doing when the answer is unambiguous.\n const wrongType =\n /Expected (image type|context stuffing file type) to be a supported format:.*but got \\.([a-z0-9]+)\\.?\\s*$/is.exec(\n message,\n );\n if (wrongType) {\n const blockType = wrongType[1]!.toLowerCase() === \"image type\" ? \"input_image\" : \"input_file\";\n const extension = wrongType[2]!.toLowerCase();\n const candidates = unique(\n blocks.filter((block) => block.type === blockType).map((block) => block.fileId),\n );\n const byName = candidates.filter((id) =>\n (files.get(id)?.name ?? \"\").trim().toLowerCase().endsWith(`.${extension}`),\n );\n if (byName.length === 1) return byName;\n if (byName.length === 0 && candidates.length === 1) return candidates;\n }\n\n return [];\n}\n\n/**\n * `body` with every block holding one of `fileIds` replaced by a note.\n *\n * A copy: the caller's body is what was sent, and the next attempt is a\n * different request.\n */\nexport function withoutFiles(\n body: ResponsesRequest,\n fileIds: Set<string>,\n files: Map<string, SentFile> = new Map(),\n): ResponsesRequest {\n return {\n ...body,\n input: body.input.map((item) => {\n const content = contentOf(item);\n if (!content.some((block) => isRejected(block, fileIds))) return item;\n return {\n ...item,\n content: content.map((block) =>\n isRejected(block, fileIds)\n ? { type: \"input_text\", text: unreadableNote(files.get(String(block.file_id))?.name) }\n : block,\n ),\n };\n }),\n };\n}\n\n/**\n * What the model reads where the file would have been.\n *\n * It says the file was not read, so the model does not describe a document it\n * never saw, and it says the provider refused it, so \"please re-upload it\" is\n * the obvious next step rather than something the model has to guess at. The\n * name is JSON-quoted for the reason `attachmentLine` gives: it is the user's,\n * and can hold anything.\n */\nexport function unreadableNote(name: string | undefined): string {\n const label = name ? `attachment ${JSON.stringify(name)}` : \"an attachment\";\n return `[${label} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`;\n}\n\nfunction isRejected(block: Record<string, unknown>, fileIds: Set<string>): boolean {\n return typeof block.file_id === \"string\" && fileIds.has(block.file_id);\n}\n\nfunction contentOf(item: ResponsesInputItem | undefined): Record<string, unknown>[] {\n const content = item?.content;\n return Array.isArray(content) ? (content as Record<string, unknown>[]) : [];\n}\n\nfunction fileBlocks(input: ResponsesInputItem[]): { type: string; fileId: string }[] {\n const out: { type: string; fileId: string }[] = [];\n for (const item of input) {\n for (const block of contentOf(item)) {\n if (typeof block.file_id === \"string\" && block.file_id) {\n out.push({ type: String(block.type), fileId: block.file_id });\n }\n }\n }\n return out;\n}\n\nfunction errorDetail(body: unknown): { message?: string; param?: string } | null {\n if (!body || typeof body !== \"object\") return null;\n const wrapper = body as { error?: unknown };\n const inner = (wrapper.error && typeof wrapper.error === \"object\" ? wrapper.error : body) as {\n message?: unknown;\n param?: unknown;\n };\n return {\n message: typeof inner.message === \"string\" ? inner.message : undefined,\n param: typeof inner.param === \"string\" ? inner.param : undefined,\n };\n}\n\n/** `id` as a whole token in `message`, so `file-ab` is not blamed for `file-abc`. */\nfunction mentions(message: string, id: string): boolean {\n const escaped = id.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(^|[^A-Za-z0-9_-])${escaped}($|[^A-Za-z0-9_-])`).test(message);\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)];\n}\n",
9
+ "import type { ProviderEvent } from \"../AgentProvider\";\nimport type { FinishReason, Usage } from \"../types\";\n\n/**\n * The Responses SSE stream to `ProviderEvent`.\n *\n * Also a pure function over chunks, for the same reason the request builder is:\n * everything that breaks here breaks on a byte boundary or a malformed frame,\n * and neither needs a network to reproduce. The tests drive it with recorded\n * fixture strings, including one fed a byte at a time.\n */\n\nexport type SSEMessage = { event: string; data: string; id?: string };\n\n/**\n * Chunks to SSE messages.\n *\n * Written out rather than reached for as a one-liner because every shortcut\n * here is a bug that only shows up under load. A frame split across two chunks\n * is the normal case, not the edge case — TCP has no idea what an event is.\n * Multi-line `data:` is spec, comment lines beginning with `:` are what\n * keepalives look like, and a `\\r\\n` stream is what you get through some\n * proxies.\n */\nexport async function* sseMessages(\n chunks: AsyncIterable<string> | Iterable<string>,\n): AsyncGenerator<SSEMessage> {\n let buffer = \"\";\n let event = \"\";\n let data: string[] = [];\n let id: string | undefined;\n\n const dispatch = (): SSEMessage | null => {\n if (data.length === 0 && !event) return null;\n const message: SSEMessage = { event, data: data.join(\"\\n\"), id };\n event = \"\";\n data = [];\n id = undefined;\n // A frame with a name but no data is legal and carries nothing we want.\n return message.data ? message : null;\n };\n\n const handleLine = (rawLine: string): SSEMessage | null => {\n // Trailing CR from a `\\r\\n` stream. Stripping it here rather than\n // normalizing the whole buffer keeps a CR that lands on a chunk boundary\n // from being counted as a line ending of its own.\n const line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n if (line === \"\") return dispatch();\n // Keepalive. Servers send these so idle connections survive proxies, and a\n // parser that treats one as data corrupts the next real frame.\n if (line.startsWith(\":\")) return null;\n\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n\n if (field === \"event\") event = value;\n else if (field === \"data\") data.push(value);\n else if (field === \"id\") id = value;\n return null;\n };\n\n for await (const chunk of chunks as AsyncIterable<string>) {\n buffer += chunk;\n let newline = buffer.indexOf(\"\\n\");\n while (newline !== -1) {\n const line = buffer.slice(0, newline);\n buffer = buffer.slice(newline + 1);\n const message = handleLine(line);\n if (message) yield message;\n newline = buffer.indexOf(\"\\n\");\n }\n }\n\n // A stream that ends without its final blank line still has one frame in it.\n if (buffer.length > 0) {\n const message = handleLine(buffer);\n if (message) yield message;\n }\n const last = dispatch();\n if (last) yield last;\n}\n\ntype ParseOptions = {\n /**\n * Set when the agent declared an `output` schema. The same\n * `response.output_text.delta` carries prose in one case and the JSON of the\n * final answer in the other, and only the caller knows which it asked for.\n */\n structuredOutput?: boolean;\n};\n\ntype PendingCall = { callId: string; name: string; namespace?: string; done: boolean };\n\nexport async function* parseResponsesStream(\n chunks: AsyncIterable<string> | Iterable<string>,\n options: ParseOptions = {},\n): AsyncGenerator<ProviderEvent> {\n // Keyed by `item_id`, because the argument deltas name the item and not the\n // call, and the call id is what the rest of gemi pairs results on.\n const calls = new Map<string, PendingCall>();\n const searchesReported = new Set<string>();\n // The query of the last `tool_search_call`, held for the output that follows\n // it: the live API links the two by nothing but order (see below), and the\n // event is reported off the output, which does not carry the query.\n let searchArguments: unknown;\n let finished = false;\n // What the vendor says answered (#741): `response.model` on the lifecycle\n // frames. Kept from every frame that has it, so a stream that dies after\n // `response.created` still says who it was talking to.\n let responseModel: string | undefined;\n const ended = (reason: FinishReason, usage: Usage): ProviderEvent => ({\n type: \"finish\",\n reason,\n usage,\n ...(responseModel ? { model: responseModel } : {}),\n });\n\n for await (const message of sseMessages(chunks)) {\n if (message.data === \"[DONE]\") break;\n\n let payload: Record<string, any>;\n try {\n payload = JSON.parse(message.data);\n } catch {\n // A frame we cannot read is not a reason to abandon a stream that is\n // otherwise fine; the terminal event is what decides how this ended.\n continue;\n }\n\n // The event name is duplicated in the payload's own `type`. Preferring the\n // payload means a gateway that drops the `event:` line still parses, and\n // the two never disagree in practice.\n const type: string = typeof payload.type === \"string\" ? payload.type : message.event;\n\n const model = payload.response?.model;\n if (typeof model === \"string\" && model) responseModel = model;\n\n switch (type) {\n case \"response.output_text.delta\": {\n const delta = String(payload.delta ?? \"\");\n if (!delta) break;\n yield options.structuredOutput\n ? { type: \"output-delta\", delta }\n : { type: \"text-delta\", delta };\n break;\n }\n\n // Two names for the same thing across model generations: the summary\n // stream and, on models that expose it, the reasoning text itself.\n case \"response.reasoning_summary_text.delta\":\n case \"response.reasoning_text.delta\": {\n const delta = String(payload.delta ?? \"\");\n if (!delta) break;\n yield { type: \"reasoning-delta\", delta, id: payload.item_id };\n break;\n }\n\n case \"response.output_item.added\": {\n const item = payload.item as Record<string, any> | undefined;\n if (!item) break;\n if (item.type === \"function_call\") {\n const itemId = String(item.id ?? payload.item_id ?? item.call_id ?? \"\");\n calls.set(itemId, {\n callId: String(item.call_id ?? itemId),\n // FLAT, and pinned by a test against the recorded stream. A call to\n // a function inside a namespace comes back as\n // `{name:\"getOrder\", namespace:\"crm\"}` — not `\"crm.getOrder\"` — so\n // the name is already the registry key `Agent` looks tools up by,\n // and qualifying it here would break every lookup. The namespace is\n // carried alongside rather than folded in, because a name that is\n // sometimes qualified is a name nothing can match on.\n name: String(item.name ?? \"\"),\n namespace: typeof item.namespace === \"string\" && item.namespace\n ? item.namespace\n : undefined,\n done: false,\n });\n }\n break;\n }\n\n case \"response.function_call_arguments.delta\": {\n const call = calls.get(String(payload.item_id ?? \"\"));\n if (!call) break;\n const argsDelta = String(payload.delta ?? \"\");\n if (!argsDelta) break;\n yield {\n type: \"tool-call-delta\",\n toolCallId: call.callId,\n name: call.name,\n argsDelta,\n // Spread rather than `namespace: call.namespace`: a flat tool has no\n // namespace, and an explicit `undefined` is a key a consumer has to\n // remember to check for.\n ...(call.namespace ? { namespace: call.namespace } : {}),\n };\n break;\n }\n\n case \"response.function_call_arguments.done\": {\n const itemId = String(payload.item_id ?? \"\");\n const call = calls.get(itemId);\n if (!call) break;\n call.done = true;\n yield {\n type: \"tool-call\",\n toolCallId: call.callId,\n name: call.name,\n args: String(payload.arguments ?? \"\"),\n ...(call.namespace ? { namespace: call.namespace } : {}),\n };\n break;\n }\n\n case \"response.output_item.done\": {\n const item = payload.item as Record<string, any> | undefined;\n if (!item) break;\n\n if (item.type === \"function_call\") {\n const itemId = String(item.id ?? payload.item_id ?? item.call_id ?? \"\");\n const call = calls.get(itemId);\n // Belt and braces: a call whose arguments never got a `done` event\n // still has to reach the agent, or the loop waits for a step that\n // will not arrive.\n if (call?.done) break;\n const namespace =\n (typeof item.namespace === \"string\" ? item.namespace : \"\") || call?.namespace;\n yield {\n type: \"tool-call\",\n toolCallId: String(item.call_id ?? itemId),\n name: String(item.name ?? call?.name ?? \"\"),\n args: String(item.arguments ?? \"\"),\n ...(namespace ? { namespace } : {}),\n };\n if (call) call.done = true;\n break;\n }\n\n if (item.type === \"tool_search_call\" || item.type === \"tool_search_output\") {\n // The call and its output are one thing to a user — \"went looking,\n // found these\" — so they collapse into one event. Two mechanisms do\n // that, and which one fires depends on what the server sent:\n //\n // 1. THE PAIR IS LINKED. The documented shape puts\n // `tool_search_call_id` on the output item, naming the call item's\n // id, so both sides key the same and the second one is dropped.\n //\n // 2. THE PAIR IS NOT LINKED, which is what the live API actually\n // sends. In `__fixtures__/openai-tool-search.sse` the call is\n // `tsc_08945…`, the output is `tso_08945…`, `call_id` is null on\n // both and neither carries `tool_search_call_id` — so there is\n // nothing to pair them on. What collapses them there is the\n // `found` check below: only the OUTPUT item carries a `tools`\n // array, and the call item carries the query it ran\n // (`arguments.paths`), which is not a result and is not reported\n // as one.\n //\n // That second one used to be load-bearing and unwritten — the dedup\n // key was doing nothing and the length check was doing all the work\n // by accident. Both are tested now: \"the tool_search call and its\n // output collapse into one event\" in `stream.test.ts` covers (1), and\n // \"nothing in the recording links the search call to its output\"\n // plus \"reports one event from the real stream, despite that\" in\n // `recordings.test.ts` cover (2).\n if (item.type === \"tool_search_call\" && item.arguments !== undefined) {\n searchArguments = item.arguments;\n }\n const found = toolSearchReport(item);\n if (found.loaded.length === 0 && found.namespaces.length === 0) break;\n const key = String(item.tool_search_call_id ?? item.id ?? \"\");\n if (searchesReported.has(key)) break;\n searchesReported.add(key);\n // The query rides along so the search can be replayed (#776). Taken\n // and cleared, so a second search in the same response does not\n // report the first one's query.\n const query = searchArguments;\n searchArguments = undefined;\n yield {\n type: \"tool-search\",\n ...found,\n ...(query !== undefined && query !== null ? { arguments: query } : {}),\n };\n }\n break;\n }\n\n // A refusal is the model declining, and it arrives as its own item rather\n // than as an HTTP status. Reporting it as text would put the refusal in\n // the transcript as if it were an answer.\n case \"response.refusal.done\": {\n yield {\n type: \"error\",\n error: {\n code: \"content_filtered\",\n message: String(payload.refusal ?? \"The model refused to answer.\"),\n retryable: false,\n },\n };\n break;\n }\n\n case \"response.completed\": {\n finished = true;\n yield ended(\"stop\", toUsage(payload.response?.usage));\n break;\n }\n\n /**\n * Two very different endings share this frame, and the old code called\n * both of them \"stop\".\n *\n * `max_output_tokens` is a truncated answer. `content_filter` is Azure\n * blocking the request — verified against\n * `__fixtures__/azure-content-filtered.sse`, where a prompt that trips\n * the filter answers HTTP 200, streams a polite refusal, and ends\n * `response.incomplete` with `incomplete_details.reason` of\n * `content_filter`. Reporting that as a clean stop tells the agent the\n * model finished talking, which is exactly the mistake `content_filtered`\n * exists to prevent: the run reads as a normal answer, the loop takes\n * another step, and nothing anywhere says the content was blocked.\n *\n * The detail comes off Azure's `content_filters` array rather than off\n * the frame, because `incomplete_details` carries the word\n * `content_filter` and nothing else — no category, no severity.\n */\n case \"response.incomplete\": {\n finished = true;\n const usage = toUsage(payload.response?.usage);\n const reason = payload.response?.incomplete_details?.reason;\n if (reason === \"content_filter\") {\n yield {\n type: \"error\",\n error: {\n code: \"content_filtered\",\n message: describeContentFilters(payload.response?.content_filters),\n retryable: false,\n },\n };\n yield ended(\"error\", usage);\n break;\n }\n yield ended(reason === \"max_output_tokens\" ? \"length\" : \"stop\", usage);\n break;\n }\n\n case \"response.failed\":\n case \"error\": {\n finished = true;\n const raw = payload.response?.error ?? payload.error ?? payload;\n yield { type: \"error\", error: normalizeStreamError(raw) };\n yield ended(\"error\", toUsage(payload.response?.usage));\n break;\n }\n }\n\n if (finished) return;\n }\n\n // The connection closed with no terminal event: a dropped socket, a proxy\n // timing out, a process going away mid-answer. Reporting it as a clean stop\n // would tell the agent the model finished talking, and it did not — so this\n // is an error, and a retryable one, because the same request usually works.\n if (!finished) {\n yield {\n type: \"error\",\n error: {\n code: \"provider_error\",\n message: \"The provider stream ended without a terminal event.\",\n retryable: true,\n },\n };\n yield ended(\"error\", emptyUsage());\n }\n}\n\n/**\n * What a tool search actually pulled in.\n *\n * The entries of `tool_search_output.tools` are NAMESPACES, not functions:\n *\n * [{type:\"namespace\", name:\"crm\", tools:[{type:\"function\", name:\"listOrders\"},\n * {type:\"function\", name:\"getOrder\"}]}]\n *\n * — verified against `__fixtures__/openai-tool-search.sse`. Reading `name` off\n * the top level, which is what this did, reported `loaded: [\"crm\"]` for a\n * search that loaded `listOrders` and `getOrder`. The names it reported were\n * not names of tools, and nothing downstream could tell, because a namespace\n * name is a plausible tool name.\n *\n * BOTH HALVES ARE REPORTED. \"Searched crm, loaded getOrder\" is the sentence a\n * UI wants, and neither field can be recovered from the other: flattening to\n * `crm.getOrder` would invent a name the model never used (calls come back with\n * a flat `name` — see the `function_call` branch above), and dropping the\n * namespace throws away the only description of the *group*, which is the thing\n * the model actually chose between.\n *\n * The shape is read structurally rather than off `type === \"namespace\"`: an\n * entry with a `tools` array is a group whatever it calls itself, and the\n * hand-written fixtures that predate the recording use `results:[{name}]` with\n * no `type` at all.\n */\ntype ToolSearchReport = { loaded: string[]; namespaces: string[] };\n\nfunction toolSearchReport(item: Record<string, any>): ToolSearchReport {\n const loaded: string[] = [];\n const namespaces: string[] = [];\n collectToolNames(item.results ?? item.tools ?? item.loaded ?? item.output, loaded, namespaces, 0);\n return { loaded: unique(loaded), namespaces: unique(namespaces) };\n}\n\nfunction collectToolNames(\n raw: unknown,\n loaded: string[],\n namespaces: string[],\n depth: number,\n): void {\n // Nesting is one level deep today and a namespace of namespaces is not a\n // thing. The cap is here so a payload that disagrees costs a truncated event\n // rather than a blown stack in the middle of someone's stream.\n if (!Array.isArray(raw) || depth > 4) return;\n for (const entry of raw) {\n if (typeof entry === \"string\") {\n loaded.push(entry);\n continue;\n }\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Record<string, any>;\n const name =\n typeof e.name === \"string\" ? e.name : typeof e.tool_name === \"string\" ? e.tool_name : \"\";\n const children = e.tools ?? e.functions;\n if (Array.isArray(children)) {\n if (name) namespaces.push(name);\n collectToolNames(children, loaded, namespaces, depth + 1);\n continue;\n }\n if (name) loaded.push(name);\n }\n}\n\nfunction unique(names: string[]): string[] {\n return names.filter((name, index) => names.indexOf(name) === index);\n}\n\n/**\n * Azure's `content_filters`, read only where it means something.\n *\n * IT DOES NOT MAP ONTO `content_filtered` ON ITS OWN, and that is the decision\n * worth writing down: the array is on EVERY Azure response — `azure-text.sse`,\n * a recording of \"say hi\", carries it on `response.created`,\n * `response.in_progress` and `response.completed`, with `blocked:false` and\n * every category `severity:\"safe\"`. Treating its presence as a filter hit would\n * report every single Azure call as content-filtered, and treating any\n * `filtered:true` inside it as one would report a *warning* as a block. What is\n * authoritative about the outcome is `incomplete_details.reason`; this array is\n * authoritative only about the DETAIL, which is why it is read for a message\n * and for nothing else.\n *\n * OpenAI sends no such array. It signals a block by refusing in-band\n * (`response.refusal.done`, handled above) or by rejecting the request, so\n * nothing here needs a provider flag — an absent array just yields the generic\n * sentence.\n */\nfunction describeContentFilters(raw: unknown): string {\n const generic = \"The provider's content filter blocked this request.\";\n if (!Array.isArray(raw)) return generic;\n const hits: string[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Record<string, any>;\n const results = e.content_filter_results;\n if (!results || typeof results !== \"object\") continue;\n for (const [category, detail] of Object.entries(results as Record<string, any>)) {\n if (detail && typeof detail === \"object\" && detail.filtered === true) {\n // The source matters as much as the category: a `prompt` hit means the\n // user's own words were blocked and rewording works, a `completion` hit\n // means the model's answer was, and retrying the same prompt will not.\n hits.push(`${category} (${String(e.source_type ?? \"unknown\")})`);\n }\n }\n }\n return hits.length === 0 ? generic : `${generic} Categories: ${unique(hits).join(\", \")}.`;\n}\n\nfunction normalizeStreamError(raw: any) {\n const message = typeof raw?.message === \"string\" ? raw.message : \"The provider stream failed.\";\n const code = String(raw?.code ?? \"\").toLowerCase();\n if (code === \"rate_limit_exceeded\") {\n return { code: \"rate_limited\" as const, message, retryable: true };\n }\n if (code === \"context_length_exceeded\") {\n return { code: \"context_length_exceeded\" as const, message, retryable: false };\n }\n if (code.includes(\"content_filter\")) {\n return { code: \"content_filtered\" as const, message, retryable: false };\n }\n // Mid-stream failures are overwhelmingly transient — the request was accepted,\n // so it was not malformed.\n return { code: \"provider_error\" as const, message, retryable: true };\n}\n\nexport function emptyUsage(): Usage {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n}\n\nexport function toUsage(raw: any): Usage {\n if (!raw) return emptyUsage();\n const inputTokens = Number(raw.input_tokens ?? 0);\n const outputTokens = Number(raw.output_tokens ?? 0);\n const usage: Usage = {\n inputTokens,\n outputTokens,\n totalTokens: Number(raw.total_tokens ?? inputTokens + outputTokens),\n };\n const reasoning = raw.output_tokens_details?.reasoning_tokens;\n if (typeof reasoning === \"number\") usage.reasoningTokens = reasoning;\n const cached = raw.input_tokens_details?.cached_tokens;\n if (typeof cached === \"number\") usage.cachedInputTokens = cached;\n return usage;\n}\n\n/** A `ReadableStream` of bytes to the string chunks the parser wants. Split out\n * so the parser never has to know it came from a socket. */\nexport async function* decodeChunks(\n body: ReadableStream<Uint8Array> | null,\n): AsyncGenerator<string> {\n if (!body) return;\n const reader = body.getReader();\n const decoder = new TextDecoder();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n // `stream: true` matters: a multi-byte character can land across two\n // reads, and decoding each read on its own turns it into two U+FFFDs.\n if (value) yield decoder.decode(value, { stream: true });\n }\n const tail = decoder.decode();\n if (tail) yield tail;\n } finally {\n reader.releaseLock();\n }\n}\n",
10
+ "import type { ProviderEvent } from \"../AgentProvider\";\nimport type { ProviderTarget } from \"./endpoints\";\nimport {\n httpErrorDetail,\n normalizeProviderError,\n ProviderStreamDurationError,\n ProviderStreamIdleError,\n ProviderTimeoutError,\n ProviderToolArgumentsTooLongError,\n} from \"./errors\";\nimport {\n MAX_FILE_REJECTION_RETRIES,\n rejectedFileIds,\n withoutFiles,\n type SentFile,\n} from \"./fileRejection\";\nimport { addUsage, isContentEvent } from \"../runtime\";\nimport type { AgentError, Usage } from \"../types\";\nimport {\n backoffDelayMs,\n boundedBody,\n requestWithRetry,\n waitUnlessAborted,\n type FetchLike,\n type RequestOptions,\n} from \"./http\";\nimport type { ResponsesRequest } from \"./request\";\nimport { decodeChunks, emptyUsage, parseResponsesStream } from \"./stream\";\n\n/**\n * The parts of a call that differ between OpenAI and Azure, and nothing else.\n *\n * Two classes, one request path: the differences are a URL, a header and when\n * the credential is read, so those are what gets passed in. Everything below\n * this line — retries, decoding, event translation, what an error looks like —\n * is identical, and duplicating it into the Azure class is how the two would\n * start behaving differently by accident.\n */\nexport type ResponsesEndpoint = {\n responsesUrl: string;\n filesUrl: string;\n /** Async because Entra tokens expire mid-conversation, so the credential has\n * to be read per request rather than per provider. */\n headers: () => Promise<Record<string, string>>;\n timeoutMs: number;\n /** See `ProviderConfig.streamIdleTimeoutMs`. Absent or `0` is off. */\n streamIdleTimeoutMs?: number;\n /** See `ProviderConfig.streamMaxDurationMs`. Absent or `0` is off. */\n streamMaxDurationMs?: number;\n /** See `ProviderConfig.maxToolArgumentChars`. Absent or `0` is off. */\n maxToolArgumentChars?: number;\n maxRetries: number;\n fetchImpl?: FetchLike;\n /** Injected by the tests, with `random`, so a backoff can be asserted on\n * without waiting for it. See `RequestOptions`. */\n sleep?: RequestOptions[\"sleep\"];\n random?: () => number;\n now?: () => number;\n};\n\n/**\n * The Responses paths for a resolved vendor.\n *\n * The two URLs are all that distinguishes this from any other call to the same\n * host, which is why the host, the credential and the api-version are worked out\n * by `providers/endpoints.ts` and appended to here rather than resolved twice.\n * Files are resource-scoped rather than deployment-scoped on Azure — an upload\n * is not addressed to a model — and the deployment goes in the body's `model`,\n * which `buildResponsesRequest` already does.\n */\nexport function responsesEndpoint(target: ProviderTarget): ResponsesEndpoint {\n return {\n responsesUrl: `${target.base}/responses${target.query}`,\n filesUrl: `${target.base}/files${target.query}`,\n headers: target.headers,\n timeoutMs: target.timeoutMs,\n streamIdleTimeoutMs: target.streamIdleTimeoutMs,\n streamMaxDurationMs: target.streamMaxDurationMs,\n maxToolArgumentChars: target.maxToolArgumentChars,\n maxRetries: target.maxRetries,\n };\n}\n\n/**\n * Errors reach the consumer as events, not exceptions.\n *\n * A `ProviderStream` that threw would make every caller wrap its `for await`,\n * and would lose the deltas already yielded — the agent needs the text it got\n * before the socket died, because the user has already read it.\n *\n * A STREAM THAT DIES BEFORE ITS FIRST CONTENT EVENT IS ASKED AGAIN (#946).\n * `requestWithRetry` covers a request that fails before a response arrives;\n * this covers the one whose response started and then broke while its body was\n * being read: the socket closed, the stream ended with no terminal frame, or\n * the provider sent a `response.failed` / `error` frame that reads as\n * retryable. Measured in fager: one such drop on the first step lost a whole\n * build, and the same request a second later worked.\n *\n * Nothing the user could have seen is repeated. Until the first content event\n * (`isContentEvent`) the only things a Responses stream yields are an error and\n * a finish, and those are held back; from the first content event on, the call\n * is committed and a later failure ends it as before. The retries use the\n * endpoint's `maxRetries` and the same backoff as the request retry, and an\n * abort during the wait ends the call at once. The usage a dropped attempt\n * reported is added to the call's closing `finish`, because it was billed.\n *\n * A STREAM THAT GOES SILENT IS CUT (#1167). With `streamIdleTimeoutMs` set, a\n * body that sends nothing for that long errors with a `ProviderStreamIdleError`\n * and the attempt's request is aborted, which releases the socket. From there it\n * is a broken stream like any other: retryable, so asked again before the first\n * content event, and the call's error after it (nothing is repeated). The\n * caller's signal still wins: an abort while waiting ends the call as aborted.\n *\n * A STREAM THAT KEEPS TRICKLING IS CUT TOO (#1169). `streamMaxDurationMs`\n * bounds an attempt's stream by the wall clock, which no chunk resets, and\n * `maxToolArgumentChars` bounds the argument text of one unfinished tool call.\n * Both abort the attempt with a retryable error, like the idle limit.\n *\n * AN ATTEMPT THAT STREAMED ONLY UNFINISHED TOOL-CALL ARGUMENTS IS NOT\n * COMMITTED (#1169). `tool-call-delta` is yielded as it arrives, so a UI can\n * show a call filling in, but until a text, reasoning, output, tool-search or\n * completed `tool-call` event the attempt can still be asked again: the call\n * never completed and never ran, so nothing the model said has been acted on.\n * Before the retry a `tool-call-discard` event names the partial calls, so\n * the consumer drops them; the next attempt's calls get new ids. Any retryable\n * break counts, not only the limits above. Once retries are spent, the partial\n * calls stay and the call ends with the error, as before.\n */\nexport async function* streamResponses<Body extends object = ResponsesRequest>(\n endpoint: ResponsesEndpoint,\n body: Body,\n params: {\n signal?: AbortSignal;\n structuredOutput: boolean;\n /** The file ids `body` sends, with their names — for the note that\n * replaces a file the provider refuses. See `providers/fileRejection.ts`.\n * Responses bodies only: without it a refused file fails the call. */\n files?: Map<string, SentFile>;\n /**\n * The SSE parser. Defaults to the Responses one; the Anthropic provider\n * passes `parseMessagesStream`, and everything else here (retries, the\n * stream limits, holding back until the first content event) is shared.\n */\n parse?: (\n chunks: AsyncIterable<string>,\n options: { structuredOutput: boolean },\n ) => AsyncIterable<ProviderEvent>;\n },\n): AsyncGenerator<ProviderEvent> {\n const parse = params.parse ?? parseResponsesStream;\n let request = body;\n const rejected = new Set<string>();\n let fileAttempts = 0;\n const maxStreamRetries = Math.max(0, endpoint.maxRetries);\n const random = endpoint.random ?? Math.random;\n // What the attempts that were dropped before their first content event\n // reported as used. Folded into whichever `finish` closes the call.\n let dropped: Usage | undefined;\n const closing = (event: Extract<ProviderEvent, { type: \"finish\" }>): ProviderEvent => {\n if (!dropped) return event;\n const usage = addUsage(addUsage(emptyUsage(), dropped), event.usage);\n dropped = undefined;\n return { ...event, usage };\n };\n const aborted = (): ProviderEvent => closing({ type: \"finish\", reason: \"aborted\", usage: emptyUsage() });\n\n const idleMs = endpoint.streamIdleTimeoutMs ?? 0;\n const maxMs = endpoint.streamMaxDurationMs ?? 0;\n const maxArgs = endpoint.maxToolArgumentChars ?? 0;\n const now = endpoint.now ?? Date.now;\n const startedAt = now();\n\n for (let streamAttempt = 0; ; streamAttempt++) {\n // Per attempt, so an idle timeout can abort this attempt's request (and\n // release its socket) without touching the caller's signal.\n const attempt = new AbortController();\n const signal = params.signal ? AbortSignal.any([params.signal, attempt.signal]) : attempt.signal;\n let response: Response | undefined;\n while (response === undefined) {\n try {\n // The request retries inside `requestWithRetry`, and its `retry`\n // events are yielded as they happen, not after it settles: they exist\n // to say the call is waiting, while it is (#1192).\n const retries: ProviderEvent[] = [];\n let wake: () => void = () => {};\n const pending = requestWithRetry(\n endpoint.responsesUrl,\n {\n method: \"POST\",\n headers: { ...(await endpoint.headers()), \"content-type\": \"application/json\" },\n body: JSON.stringify(request),\n },\n {\n maxRetries: endpoint.maxRetries,\n timeoutMs: endpoint.timeoutMs,\n signal,\n fetchImpl: endpoint.fetchImpl,\n sleep: endpoint.sleep,\n random: endpoint.random,\n now: endpoint.now,\n startedAt,\n onRetry: (info) => {\n retries.push({ type: \"retry\", ...info, phase: \"request\" });\n wake();\n },\n },\n );\n const settled = pending.then(\n () => true,\n () => true,\n );\n for (;;) {\n const woken = new Promise<false>((resolve) => (wake = () => resolve(false)));\n const done = await Promise.race([settled, woken]);\n yield* retries.splice(0);\n if (done) break;\n }\n response = await pending;\n } catch (error) {\n // A stored file the provider will not read fails this request and, left\n // in, every later one in the thread (#684). Take it out and ask again,\n // as long as the error blames a file this attempt still sent.\n const responses = request as unknown as ResponsesRequest;\n const blamed =\n params.files && fileAttempts < MAX_FILE_REJECTION_RETRIES\n ? rejectedFileIds(responses, error, params.files).filter((id) => !rejected.has(id))\n : [];\n if (blamed.length > 0) {\n fileAttempts++;\n const reason = normalizeProviderError(error).message;\n for (const fileId of blamed) {\n rejected.add(fileId);\n yield { type: \"file-rejected\", fileId, message: reason, ...httpErrorDetail(error) };\n }\n request = withoutFiles(responses, new Set(blamed), params.files) as unknown as Body;\n continue;\n }\n const normalized = normalizeProviderError(error);\n // An abort is not a failure to report: the run was stopped on purpose, and\n // `Agent` is already writing the ending. Saying so twice would put an error\n // in a transcript the user closed themselves.\n if (normalized.code === \"aborted\") {\n yield aborted();\n return;\n }\n yield { type: \"error\", error: normalized, ...httpErrorDetail(error) };\n yield closing({ type: \"finish\", reason: \"error\", usage: emptyUsage() });\n return;\n }\n }\n\n const held: ProviderEvent[] = [];\n let committed = false;\n let failure: AgentError | undefined;\n let streamTimedOut = false;\n // The tool calls this attempt has yielded argument deltas for, with how\n // much text each has streamed. Before `committed`, these are the only\n // things the consumer has seen, and a retry discards them.\n const partial = new Map<string, number>();\n try {\n const body = boundedBody(\n response.body,\n { idleMs, maxMs },\n {\n idle: () => {\n const error = new ProviderStreamIdleError(idleMs);\n attempt.abort(error);\n return error;\n },\n max: () => {\n const error = new ProviderStreamDurationError(maxMs);\n attempt.abort(error);\n return error;\n },\n },\n );\n for await (const event of parse(decodeChunks(body), {\n structuredOutput: params.structuredOutput,\n })) {\n if (event.type === \"tool-call-delta\") {\n const chars = (partial.get(event.toolCallId) ?? 0) + event.argsDelta.length;\n partial.set(event.toolCallId, chars);\n if (maxArgs > 0 && chars > maxArgs) {\n const error = new ProviderToolArgumentsTooLongError(maxArgs, event.name);\n attempt.abort(error);\n throw error;\n }\n yield event;\n continue;\n }\n if (event.type === \"tool-call\") partial.delete(event.toolCallId);\n if (committed) {\n yield event.type === \"finish\" ? closing(event) : event;\n continue;\n }\n if (isContentEvent(event)) {\n committed = true;\n yield* held.splice(0);\n yield event;\n continue;\n }\n if (event.type === \"error\") failure = event.error;\n held.push(event);\n }\n } catch (error) {\n streamTimedOut = error instanceof ProviderTimeoutError;\n const normalized = normalizeProviderError(error);\n if (normalized.code === \"aborted\" || params.signal?.aborted) {\n yield aborted();\n return;\n }\n if (committed) {\n yield { type: \"error\", error: normalized };\n yield closing({ type: \"finish\", reason: \"error\", usage: emptyUsage() });\n return;\n }\n failure = normalized;\n held.push(\n { type: \"error\", error: normalized },\n { type: \"finish\", reason: \"error\", usage: emptyUsage() },\n );\n }\n if (committed) return;\n\n if (failure?.retryable && streamAttempt < maxStreamRetries && !params.signal?.aborted) {\n let detail: { status?: number; requestId?: string } = {};\n for (const event of held) {\n if (event.type === \"finish\") dropped = addUsage(dropped ?? emptyUsage(), event.usage);\n if (event.type === \"error\") detail = httpErrorDetail(event);\n }\n if (partial.size > 0) yield { type: \"tool-call-discard\", toolCallIds: [...partial.keys()] };\n const delayMs = backoffDelayMs(streamAttempt, random);\n yield {\n type: \"retry\",\n attempt: streamAttempt + 1,\n maxRetries: maxStreamRetries,\n error: failure,\n ...detail,\n phase: \"stream\",\n timedOut: streamTimedOut,\n delayMs,\n elapsedMs: now() - startedAt,\n };\n try {\n await waitUnlessAborted(delayMs, params.signal, endpoint.sleep);\n } catch {\n yield aborted();\n return;\n }\n continue;\n }\n\n for (const event of held) yield event.type === \"finish\" ? closing(event) : event;\n return;\n }\n}\n\n/**\n * What a file is uploaded *for*, which decides where its id is accepted.\n *\n * The two providers disagree, and each refuses the other's answer.\n *\n * OpenAI: `user_data`. This is a file a person attached to a message, not a\n * corpus for a retrieval store, and the purpose is what decides which of the\n * two the file can be used for.\n *\n * Azure: `assistants`. MEASURED (gpt-6-sol deployment, `/openai/v1`,\n * `api-version=preview`, 2026-10-01, #682): Azure accepts a `user_data` upload\n * and answers a `file-…` id, and then its Responses API refuses that id in both\n * `input_file` and `input_image` with `400 Invalid\n * 'input[0].content[0].file_id': 'file-…'. Expected an ID that begins with\n * 'assistant'.` The same files uploaded as `assistants` come back as\n * `assistant-…` ids (`expires_at: null`) and work: pdf, txt, md and csv as\n * `input_file`, png as `input_image` with real vision.\n */\nexport type UploadPurpose = \"user_data\" | \"assistants\";\n\n/**\n * Uploads an attachment and returns the id a `FilePart` carries.\n *\n * The purpose is the caller's because it is a property of the provider, not of\n * the file — see `UploadPurpose`.\n */\nexport async function uploadFile(\n endpoint: ResponsesEndpoint,\n file: File,\n /** `null` for Anthropic's Files API, which takes no purpose. */\n purpose: UploadPurpose | null = \"user_data\",\n): Promise<string> {\n const form = new FormData();\n if (purpose) form.set(\"purpose\", purpose);\n form.set(\"file\", file);\n\n const response = await requestWithRetry(\n endpoint.filesUrl,\n {\n method: \"POST\",\n // No content-type: the boundary is generated with the body, and setting\n // the header by hand is how multipart uploads fail with a parser error\n // that names nothing useful.\n headers: await endpoint.headers(),\n body: form,\n },\n {\n maxRetries: endpoint.maxRetries,\n timeoutMs: endpoint.timeoutMs,\n fetchImpl: endpoint.fetchImpl,\n },\n );\n\n const json = (await response.json()) as { id?: string };\n if (!json?.id) throw new Error(\"The provider accepted the upload but returned no file id.\");\n return json.id;\n}\n",
11
+ "import type {\n ProviderCapabilities,\n ProviderStreamParams,\n ProviderToolNamespace,\n ProviderToolSpec,\n} from \"../AgentProvider\";\nimport { ATTACHMENT_ID_PREFIX } from \"../store/Attachments\";\nimport { unreadableNote } from \"./fileRejection\";\nimport type { AgentMessage, FilePart, ToolResultPart, ToolSearchRecord } from \"../types\";\n\n/**\n * Building the request body is a pure function, on purpose.\n *\n * Everything hard about this provider is in here — item ordering, tool-call\n * pairing, what a denied call looks like on the wire — and none of it needs a\n * socket to be wrong. So it is separated from the class that posts it, and the\n * tests assert the object rather than mocking `fetch` and reading a string.\n */\n\n// The wire shapes, typed loosely on purpose: these mirror OpenAI's schema, and\n// a precise mirror is a second thing to keep in sync for no checking we would\n// actually get — the API is the authority and it answers in HTTP.\nexport type ResponsesInputItem = Record<string, unknown>;\nexport type ResponsesTool = Record<string, unknown>;\n\nexport type ResponsesRequest = {\n model: string;\n input: ResponsesInputItem[];\n stream: true;\n instructions?: string;\n tools?: ResponsesTool[];\n parallel_tool_calls?: boolean;\n tool_choice?: string | { type: \"function\"; name: string };\n text?: { format: Record<string, unknown> };\n reasoning?: { effort: string; summary?: \"auto\" };\n temperature?: number;\n max_output_tokens?: number;\n prompt_cache_key?: string;\n};\n\nexport function buildResponsesRequest(\n params: ProviderStreamParams,\n ctx: { model: string; capabilities: ProviderCapabilities },\n): ResponsesRequest {\n const { capabilities } = ctx;\n\n const body: ResponsesRequest = {\n model: ctx.model,\n input: toResponsesInput(params.messages, capabilities, params.tools),\n stream: true,\n };\n\n if (params.systemPrompt) body.instructions = params.systemPrompt;\n\n const tools = toResponsesTools(params.tools, capabilities);\n if (tools.length > 0) {\n body.tools = tools;\n if (!capabilities.parallelToolCalls) body.parallel_tool_calls = false;\n if (params.toolChoice !== undefined) {\n body.tool_choice =\n typeof params.toolChoice === \"string\"\n ? params.toolChoice\n : { type: \"function\", name: params.toolChoice.name };\n }\n }\n\n // Deliberately NOT gated on `capabilities.structuredOutput`. An agent that\n // declares `output` has a typed result its app is going to read, and dropping\n // the parameter does not degrade that gracefully — it produces prose, which\n // arrives as `text-delta`, so the app sees no output part, no error and\n // nothing to branch on. That is the silent-forever failure `capabilities.ts`\n // argues against: send it and let the API answer 400, which is loud, happens\n // once, and names the parameter it disliked. `reasoning` is dropped below\n // because it is an optimization; an output schema is the answer's shape.\n if (params.output) {\n body.text = {\n format: {\n type: \"json_schema\",\n name: params.output.name,\n schema: params.output.schema,\n strict: params.output.strict,\n },\n };\n }\n\n // Dropped rather than refused: a model that cannot reason should still answer\n // an agent that asked it to, because `reasoning` is the agent's preference\n // and the provider is where preferences meet reality.\n if (params.reasoning && capabilities.reasoning) {\n // `summary: \"auto\"` is not decoration — without it the stream carries no\n // reasoning text at all, and `ReasoningPart` would have nothing to hold.\n // Except at `\"none\"`, where there is no reasoning to summarize: the effort\n // is sent on its own, so turning reasoning off is not also a request for a\n // summary of it.\n body.reasoning =\n params.reasoning === \"none\"\n ? { effort: \"none\" }\n : { effort: params.reasoning, summary: \"auto\" };\n }\n\n if (typeof params.temperature === \"number\") body.temperature = params.temperature;\n if (typeof params.maxOutputTokens === \"number\") body.max_output_tokens = params.maxOutputTokens;\n if (params.promptCacheKey) body.prompt_cache_key = params.promptCacheKey;\n\n return body;\n}\n\n// --- messages ------------------------------------------------------------\n\n/**\n * `AgentMessage[]` to Responses input items.\n *\n * Order is preserved *within* a message, not just between messages: a message\n * that holds reasoning, then a tool call, then its result has to arrive in that\n * order, because the API validates the pairing positionally. So text and file\n * parts are buffered into one message item and that buffer is flushed the\n * moment a non-message item appears, rather than emitting all the text first\n * and all the calls after.\n */\nexport function toResponsesInput(\n messages: AgentMessage[],\n capabilities: ProviderCapabilities,\n tools?: (ProviderToolSpec | ProviderToolNamespace)[],\n): ResponsesInputItem[] {\n const items: ResponsesInputItem[] = [];\n // What this request's tools can resolve a namespaced call or a search\n // against. Empty without tool search: the tools are then sent flat (see\n // `toResponsesTools`), there is no namespace for a call to name, and a\n // search item would be one for a tool the request does not have.\n const namespaces = new Map<string, ProviderToolNamespace>();\n if (capabilities.toolSearch) {\n for (const entry of tools ?? []) if (isNamespace(entry)) namespaces.set(entry.name, entry);\n }\n\n for (const message of messages) {\n const role = message.role;\n let buffer: Record<string, unknown>[] = [];\n\n const flush = () => {\n if (buffer.length === 0) return;\n items.push({ type: \"message\", role, content: buffer });\n buffer = [];\n };\n\n for (const part of message.content ?? []) {\n switch (part.type) {\n case \"text\": {\n if (!part.text) break;\n buffer.push(textContent(role, part.text));\n break;\n }\n case \"output\": {\n // A structured answer is still the assistant's text as far as the\n // history is concerned; re-serializing it is what lets a follow-up\n // turn refer to what was decided.\n if (part.partial) break;\n buffer.push(textContent(role, JSON.stringify(part.value)));\n break;\n }\n case \"file\": {\n // Neither `input_file` nor `input_image` is legal on an output role.\n // An assistant message holding a file is a bug upstream, and sending\n // it anyway turns that bug into a 400 halfway through a conversation.\n // The attachment line goes with it: `output_text` saying \"here is a\n // file\" on the assistant's side would be the model told it produced\n // something it did not.\n if (role === \"assistant\") break;\n const attachmentId = attachmentIdOf(part);\n // A model that cannot read files still gets the line. The file is\n // gemi's either way, and a tool can take it by id even though the\n // model cannot look at it — dropping the line too would leave the\n // model unaware the user attached anything, which is the storage-only\n // failure this line exists to fix.\n if (!capabilities.fileInput) {\n if (attachmentId) buffer.push(textContent(role, attachmentLine(part, false)));\n break;\n }\n // NOT A PROVIDER FILE ID. There are two ids now — `POST /chat/files`\n // answers `fileId` (the provider's) and `attachmentId` (ours) — and\n // putting the wrong one here is the mistake the shapes invite. Left\n // alone it is an error from the vendor about a file it has never heard\n // of, arriving mid-conversation and naming nothing a reader can act\n // on. (Which error is NOT MEASURED: no request was made with a bogus\n // `file_id` to find out whether it is a 400 or a 404, or whether the\n // part is dropped and the rest of the turn proceeds. The guard does\n // not depend on the answer — it is worth having on the shapes alone —\n // so this comment names the failure rather than a status code nobody\n // checked.)\n assertFilePart(part, attachmentId);\n // Refused once already (#684): the id would be refused again, and the\n // request with it. The model is told the file is there and was not\n // read, and is given the attachment id when there is one, since the\n // stored copy is still readable by a tool.\n if (part.providerRejected) {\n if (attachmentId) buffer.push(textContent(role, attachmentLine(part, false)));\n buffer.push(textContent(role, unreadableNote(part.name)));\n break;\n }\n if (attachmentId) buffer.push(textContent(role, attachmentLine(part, !!part.fileId)));\n if (part.fileId) buffer.push(fileContent(part));\n break;\n }\n case \"reasoning\": {\n flush();\n const item = reasoningItem(part);\n if (item) items.push(item);\n break;\n }\n case \"tool-call\": {\n // A partial call is UI state — the arguments were still streaming\n // when this was written down, so what it holds is not what the model\n // asked for. Sending it would create the dangling call the API\n // rejects. If it did acquire a result (a stop landing mid-arguments\n // does exactly that), `reconcileToolPairs` drops that half too.\n if (part.partial) break;\n flush();\n // `Array.isArray` rather than truthiness: in stateless mode this\n // field came back from the browser, and a turn must not throw on it.\n if (capabilities.toolSearch && Array.isArray(part.toolSearches)) {\n for (const search of part.toolSearches) {\n items.push(...toolSearchItems(search, tools ?? []));\n }\n }\n const call: ResponsesInputItem = {\n type: \"function_call\",\n call_id: part.toolCallId,\n name: String(part.name),\n arguments: JSON.stringify(part.input ?? {}),\n };\n // Back the way the model made it (#776). Without the namespace this\n // is a call to a top-level function the tools do not list, and the\n // model, reading its own history, stopped making sense after one.\n // Dropped only when this request has no such namespace — a provider\n // without tool search, or an agent whose tools changed since — where\n // naming it would be a call into nothing.\n if (part.namespace && namespaces.has(part.namespace)) call.namespace = part.namespace;\n items.push(call);\n break;\n }\n case \"tool-result\": {\n flush();\n items.push({\n type: \"function_call_output\",\n call_id: part.toolCallId,\n output: toolResultOutput(part),\n });\n break;\n }\n }\n }\n\n flush();\n }\n\n return reconcileToolPairs(items);\n}\n\n/** What is sent for a call whose result never made it into the history. */\nconst NO_RESULT_RECORDED = \"No result was recorded for this tool call. Assume it did not complete.\";\n\n/**\n * Every `function_call` has exactly one `function_call_output`, and no output\n * stands alone.\n *\n * The loop above skips a `tool-call` marked `partial` — its arguments were\n * still streaming, so it is UI state rather than something the model did — but\n * a partial call can still acquire a result: `stop()` gives every call in\n * flight a `denied`/`stopped` result, and a call whose arguments were mid-flight\n * is exactly the one carrying `partial`. Emitting that result on its own is a\n * 400 (\"no tool call found for function call output\"), and because the history\n * is persisted it is a 400 on every subsequent turn — the thread is bricked,\n * which is the failure `denied` exists to prevent.\n *\n * So the invariant is enforced here rather than assumed part-by-part: an\n * unpartnered output is dropped, a repeated one is dropped, and a call left\n * dangling by a crash between the call and its result gets a synthetic output\n * saying so. Fabricating that line is the lesser evil — it is true, the model\n * can read it, and the alternative is a conversation that can never be\n * continued.\n *\n * A repeated *call* is dropped for the same reason in the other direction. The\n * API happens to accept two `function_call`s under one id, so this is not a\n * 400 — it is the model reading the same call twice, on every turn, for the\n * rest of the conversation. The way it arises is a store that appended the\n * amended copy of a message instead of replacing it; the store contract now\n * says upsert, and this is the guard for a store that did not read it.\n */\nfunction reconcileToolPairs(items: ResponsesInputItem[]): ResponsesInputItem[] {\n const called = new Set<string>();\n const answered = new Set<string>();\n const kept: ResponsesInputItem[] = [];\n\n for (const item of items) {\n if (item.type === \"function_call\") {\n const callId = String(item.call_id);\n if (called.has(callId)) continue;\n called.add(callId);\n } else if (item.type === \"function_call_output\") {\n const callId = String(item.call_id);\n // Positional: the output has to come *after* its call, which is what the\n // API checks, so a call seen later in the history does not rescue it.\n if (!called.has(callId) || answered.has(callId)) continue;\n answered.add(callId);\n }\n kept.push(item);\n }\n\n if (answered.size === called.size) return kept;\n\n const out: ResponsesInputItem[] = [];\n for (const item of kept) {\n out.push(item);\n if (item.type !== \"function_call\") continue;\n const callId = String(item.call_id);\n if (answered.has(callId)) continue;\n answered.add(callId);\n out.push({ type: \"function_call_output\", call_id: callId, output: NO_RESULT_RECORDED });\n }\n return out;\n}\n\nfunction textContent(role: AgentMessage[\"role\"], text: string): Record<string, unknown> {\n return { type: role === \"assistant\" ? \"output_text\" : \"input_text\", text };\n}\n\n/**\n * `FilePart.attachmentId`, if it is one.\n *\n * In stateless mode the history arrives from the browser and only the turn\n * itself is checked at the door (`toClientTurn`), so a part posted back as\n * history can hold anything here. A value that is not a gemi id is treated as\n * absent rather than refused: it names nothing a tool could resolve, and\n * refusing it would fail every later turn of a conversation over a field the\n * model could not have used.\n */\nexport function attachmentIdOf(part: FilePart): string | undefined {\n const id = part.attachmentId;\n return typeof id === \"string\" && id.startsWith(ATTACHMENT_ID_PREFIX) ? id : undefined;\n}\n\n/**\n * The line that tells the model an attachment's id, sent just before the file\n * block it labels (or alone, when there is no file block to send).\n *\n * WHY A LINE AT ALL. A model that has seen a user's image has no id to put in\n * a tool's arguments unless it is told one. Whatever it writes there instead\n * is answered by `ctx.attachments.file()` with `AttachmentNotFoundError` —\n * correctly, for an id that was never obtainable. For a storage-only upload\n * this line is all the model gets: without it, it does not know a file exists.\n *\n * WHY THIS FORMAT. `[attachment id=\"…\" name=\"…\" mimeType=\"…\"]`, each value\n * JSON-quoted. The filename is the user's and can hold spaces, quotes, `]` or\n * a newline; JSON quoting means none of them can end a field, end the bracket,\n * or start a second line that reads as another attachment, so the id a model\n * copies out is exactly the id. The unquoted form (`[attachment gemi_att_… my\n * photo.png image/png]`) looks tidier and is ambiguous as soon as a name has a\n * space. A key with no value is left out rather than written as `name=\"\"`.\n *\n * WHY IT SAYS WHEN THE FILE IS NOT SHOWN. A storage-only upload, or any file\n * sent to a model without `fileInput`, has no block beside the line. Left\n * unsaid, a line that names `photo.png` invites the model to describe a\n * picture it never saw.\n */\nexport function attachmentLine(part: FilePart, shown: boolean): string {\n const fields = [`id=${JSON.stringify(part.attachmentId)}`];\n if (part.name) fields.push(`name=${JSON.stringify(part.name)}`);\n if (part.mimeType) fields.push(`mimeType=${JSON.stringify(part.mimeType)}`);\n const line = `attachment ${fields.join(\" \")}`;\n return shown\n ? `[${line}]`\n : `[${line} — its contents are not shown to you; a tool can read the file by this id]`;\n}\n\n/**\n * An attachment onto the content block that can carry it.\n *\n * `input_file` is the document path and `input_image` is the vision one, and\n * they are not interchangeable in either direction — the API refuses the wrong\n * pairing with a 400 rather than degrading. So this branch is not a nicety\n * about how well an image is read; it decides whether the turn happens at all.\n * What was measured, on which models, with the verbatim rejections, is recorded\n * above `IMAGE_EXTENSIONS`.\n *\n * `file_id` is the same field on both blocks, so nothing about the upload\n * changes: `uploadFile` posts once (with the provider's purpose — see\n * `UploadPurpose`) and the id it returns is legal in either. `detail` is deliberately not sent on the image\n * block — it is optional, the API defaults it, and a `FilePart` carries no\n * signal that would justify choosing anything but that default.\n *\n * SVG is the case the `image/` prefix gets wrong. `image/svg+xml` is an image\n * MIME type, and .svg is on the API's *document* list and off its image list —\n * so a prefix test alone sends it to the one block that is guaranteed to refuse\n * it. It is routed by what the API calls it, not by what the MIME type calls\n * it.\n *\n * WHEN `mimeType` IS ABSENT OR EMPTY the file name decides, and if that settles\n * nothing the part is sent as `input_file`. Both halves matter.\n *\n * The name branch is NOT a rescue for un-typed legacy rows, and deleting it as\n * one would break a live upload. The browser path has always written the field:\n * `useChat.uploadFile` has stored `data.mimeType ?? file.type` since the module\n * landed (`git log -S mimeType -- ai/useChat.tsx` bottoms out at d940676e), so\n * there is no history of `undefined` MIME types to point at, and a backfill\n * would not make this branch dead. What it is actually for is the two cases\n * that still leave nothing to read. `File.type` is the EMPTY STRING, not\n * absent, for a file the browser cannot type — so `?? file.type` stores `\"\"`\n * and this branch fires on a perfectly current upload — and a `FilePart`\n * assembled by a server-side caller may set neither field, because the type\n * marks both optional.\n *\n * The name is also the right thing to fall back to rather than merely the last\n * thing left: the server classifies by the STORED FILE NAME'S EXTENSION, not by\n * the bytes and not by the upload's `Content-Type` (measured; the transcript is\n * below). And what it rescues is not a cosmetic degradation — an image part\n * that lands on `input_file` 400s, and because that part lives in stored\n * history and goes back up on every request, it 400s every remaining turn of\n * the thread. `useChat.uploadFile` fills `name` from the local `File` and the\n * file is uploaded under that same name, so such a part almost always still\n * says `.png`.\n *\n * Falling back to `input_file` past that is the conservative half — a part with\n * neither a MIME type nor a usable name is much more likely to be the document\n * it has always been sent as than an image, and this way a nameless document\n * keeps working instead of being newly broken to rescue a nameless image.\n *\n * PRECEDENCE, since two orderings are otherwise indistinguishable: the MIME\n * type classifies and the name is consulted only when there is none. A stated\n * type is a stated fact and a name is a convention, so a `.pdf` named\n * `image/png` goes to the image block. `request.test.ts` pins this with a case\n * where the two disagree, because a name-first `fileContent` passes every case\n * where they agree.\n */\nfunction fileContent(part: FilePart): Record<string, unknown> {\n return { type: isImageFile(part) ? \"input_image\" : \"input_file\", file_id: part.fileId };\n}\n\n/** Whether a file part goes to the image block. See `fileContent`. */\nexport function isImageFile(part: FilePart): boolean {\n const mimeType = part.mimeType?.trim().toLowerCase() ?? \"\";\n // `\"\"` rather than `undefined` is the shape to expect from a browser that\n // could not type the file: `useChat.uploadFile` writes `data.mimeType ??\n // file.type`, and `File.type` is the empty string, not absent. Both land on\n // the name.\n return mimeType\n ? mimeType.startsWith(\"image/\") && mimeType !== \"image/svg+xml\"\n : hasImageExtension(part.name);\n}\n\n/**\n * The two file parts no request can carry: a gemi attachment id in `fileId`,\n * and a part with neither id. See the `file` case in `toResponsesInput`.\n */\nexport function assertFilePart(part: FilePart, attachmentId: string | undefined): void {\n if (part.fileId?.startsWith(ATTACHMENT_ID_PREFIX)) {\n throw new Error(\n `FilePart.fileId holds a gemi attachment id (${part.fileId}). That field is the *provider's* file id, from \\`fileId\\` on the upload response; the \\`attachmentId\\` goes in \\`FilePart.attachmentId\\`, is shown to the model as text, and is resolved by a tool through \\`ctx.attachments\\`.`,\n );\n }\n // A storage-only upload has no provider id, and that is a legal part now:\n // the model is told the file exists and is not shown it. What is still\n // refused is a part with NEITHER id — nothing to show and nothing to name.\n // The emptiness check is `!part.fileId` rather than a prefix test because\n // `undefined?.startsWith` is `undefined`, and `file_id: undefined` reaches\n // the vendor as surely as a wrong string.\n if (!part.fileId && !attachmentId) {\n throw new Error(\n \"FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_…`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.\",\n );\n }\n}\n\nfunction hasImageExtension(name: string | undefined): boolean {\n const match = /\\.([a-z0-9]+)$/.exec(name?.trim().toLowerCase() ?? \"\");\n return match?.[1] !== undefined && IMAGE_EXTENSIONS.has(match[1]);\n}\n\n/**\n * Which block takes what, and whether the wrong one merely reads badly.\n *\n * MEASURED, not read off the API reference. Three attachments were uploaded to\n * `https://api.openai.com/v1/files` with `purpose: \"user_data\"` — a 64x64 PNG\n * of four solid quadrants (red, green, blue, yellow), a one-page PDF whose only\n * word is BANANA, and a 64x64 SVG — and each was then sent to\n * `https://api.openai.com/v1/responses` in both content blocks:\n *\n * PNG as `{type:\"input_image\", file_id}` — 200. Asked which quadrant was\n * red, gpt-5.4 answered `\"top-left\"` and gpt-4o `\"The red quadrant is the\n * top-left.\"` Both correct. SO AN UPLOADED IMAGE IS REAL VISION INPUT, and\n * `file_id` is all `input_image` needs; sending `detail:\"auto\"` alongside\n * it changed nothing, so it is left off.\n * PNG as `{type:\"input_file\", file_id}` — 400, verbatim: `Invalid input:\n * Expected context stuffing file type to be a supported format: .art, .bat,\n * … .pdf, … .svg, … .yml but got .png.` (~90 extensions, elided.) This is\n * the finding that mattered: what gemi shipped was not \"an image the model\n * reads poorly\", it was a request that never ran.\n * PDF as `{type:\"input_file\", file_id}` — 200, `\"BANANA\"` on gpt-5.4 and\n * gpt-4o both.\n * PDF as `{type:\"input_image\", file_id}` — 400, verbatim: `Invalid input:\n * Expected image type to be a supported format: .jpeg, .jpg, .png, .gif,\n * .webp but got .pdf.` So the refusal is symmetric: neither block tolerates\n * the other's content.\n * SVG as `{type:\"input_image\", file_id}` — 400, `… but got .svg.`\n * SVG as `{type:\"input_file\", file_id}` — 400, but a different one:\n * `You uploaded an invalid file. Please try again with a different file`,\n * with no format list. .svg is on the document list and off the image one,\n * so routing accepted it and the pipeline behind it did not. An SVG fails\n * both ways today; it is sent as `input_file` because that is where the API\n * says it belongs, which is the only branch that can start working without\n * another change here.\n *\n * AND THE DISCRIMINATOR IS THE FILE NAME, NOT THE BYTES AND NOT THE UPLOAD'S\n * `Content-Type`. The same PNG bytes uploaded under the name `quadrants.txt`\n * with `type: \"text/plain\"` were refused as `input_image` with `… but got\n * .txt.`, and as `input_file` with `The file you uploaded is badly formatted or\n * corrupted. Please fix the file and try again.` (code `invalid_file`) — routed\n * by the extension, then failed on the bytes. That is why the name is what a\n * part with no `mimeType` falls back to: it is what the server will judge by.\n *\n * The extensions below are transcribed from the image rejection above.\n *\n * A closed list is right *here* and wrong one line up. This set is only\n * consulted when there is no MIME type to read, which is a guess either way, so\n * it guesses the conservative direction: a format the API adds later goes on\n * being sent as `input_file`, exactly as it is today. The MIME branch stays\n * open (`image/` prefix) for the opposite reason — a declared `image/avif`\n * belongs in the image block the moment the API takes one, and being wrong\n * there is a 400 that names the format, which is loud and fixes itself.\n */\nconst IMAGE_EXTENSIONS = new Set([\"jpeg\", \"jpg\", \"png\", \"gif\", \"webp\"]);\n\n/**\n * Reasoning goes back exactly as it came.\n *\n * Reshaping it — flattening the summary into text, renaming the item, dropping\n * the id — costs two things that are hard to see and expensive to have lost:\n * the prompt cache, which keys on the literal item, and on a reasoning model\n * the thread of the model's own argument across turns.\n *\n * An item with no id is dropped instead. The id is the API's handle on stored\n * reasoning, and an item without one is not a reasoning item the API can\n * resolve — sending a summary under a fabricated id would be worse than\n * sending nothing, because it would look like continuity that is not there.\n */\nfunction reasoningItem(part: { id?: string; text?: string }): ResponsesInputItem | null {\n if (!part.id) return null;\n const item: ResponsesInputItem = { type: \"reasoning\", id: part.id };\n item.summary = part.text ? [{ type: \"summary_text\", text: part.text }] : [];\n return item;\n}\n\n/**\n * Every tool call gets an output, including the ones that never ran.\n *\n * The API rejects a history containing a `function_call` with no matching\n * `function_call_output`, so a denial cannot be expressed by omission — and a\n * conversation where the user said no has to stay continuable, which is the\n * whole reason `denied` exists in the first place.\n *\n * What is sent is prose rather than a status enum, because the reader is a\n * language model: it has to be able to tell \"the user refused this\" from \"this\n * blew up\", and those two lead to genuinely different next moves — apologize\n * and ask, versus try another way.\n *\n * STILL A STRING, AFTER #490, AND THAT IS THE DESIGN. A tool that produces a\n * file the model has to look at does not put it here: the run appends an\n * input-role message carrying a `FilePart` after the call settles, which is the\n * `input_file` shape a user's own upload already takes and which the branch\n * above already builds every day.\n *\n * The alternative was a `function_call_output` whose `output` is a content\n * array with an image block in it, and it was not chosen because NOBODY HAS\n * MEASURED WHETHER THE API ACCEPTS ONE. No request was made with an image block\n * in a `function_call_output`, so whether it is taken, ignored, or a 400 is\n * unknown, and the one thing that is certain is that finding out costs a\n * conversation each time it is wrong — a rejected history is rejected on every\n * subsequent turn, not just the one that built it. Going through a route that\n * is exercised on every vision request costs nothing to be sure of. If someone\n * does measure it and it works, the tool result becomes the tidier home for a\n * file and this comment is the place to say so.\n */\nexport function toolResultOutput(part: ToolResultPart): string {\n if (part.status === \"ok\") {\n // The tool's `toModel` projection when it has one (#1061): the client got\n // the whole output, the model reads what the tool chose to show it.\n const output = part.modelOutput !== undefined ? part.modelOutput : part.output;\n return typeof output === \"string\" ? output : JSON.stringify(output ?? null);\n }\n\n if (part.status === \"running\") {\n // The same text on every request until the job settles, so the prompt\n // cache holds: no age, no progress. The `<jobs>` block says how it is\n // going. \"Do not start it again\" is the line that matters; without a\n // result to read, a model repeats the call.\n const summary =\n part.job?.summary === undefined ? \"\" : ` Started with: ${JSON.stringify(part.job.summary)}.`;\n return `Started background job ${part.job?.id ?? \"(unknown)\"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${summary}`;\n }\n\n if (part.status === \"denied\") {\n const reason = part.reason ? ` Reason given: ${part.reason}` : \"\";\n if (part.cause === \"stopped\") {\n return `The run was stopped before this tool call could complete, so it did not run.${reason}`;\n }\n if (part.cause === \"interrupted\") {\n // Not \"it did not run\": the server went down while it was running, so it\n // may have done some or all of its work (saved a page, sent an email)\n // with nobody left to record the result. A model told it did not run\n // does it again.\n return `The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${reason}`;\n }\n return `The user declined this tool call, so it did not run.${reason}`;\n }\n\n return `The tool call failed and produced no result. Error (${part.error?.code ?? \"unknown\"}): ${\n part.error?.message ?? \"no message\"\n }`;\n}\n\n/**\n * A tool search the model ran, back onto the wire as the pair the API sent:\n * a `tool_search_call` with the query, then a `tool_search_output` with what\n * it loaded (#776).\n *\n * Why at all: the API's own guide for tool search without\n * `previous_response_id` is to pass every earlier item back, the search pair\n * included, and a deferred tool is loaded for the model by the output item\n * in its history. Without the pair the model reads calls to tools nothing in\n * its context ever loaded.\n *\n * The shape is the hosted one: `execution: \"server\"`, `call_id: null`, no\n * item ids. The ids are left out so the history does not depend on the\n * vendor's stored items, which a `FallbackProvider` leg on another resource\n * does not have. Measured on Azure (gpt-5.4): this pair, the pair with the\n * original ids, and the pair without `call_id` were all accepted.\n *\n * The output is rebuilt from this request's tools rather than stored, using\n * the same `functionTool` the `tools` array uses, so it matches what the API\n * returned for the same tools (`__fixtures__/openai-tool-search.sse`).\n * Namespaces and functions the agent no longer has are left out, and a search\n * that would load nothing is not replayed at all.\n */\nfunction toolSearchItems(\n search: ToolSearchRecord,\n tools: (ProviderToolSpec | ProviderToolNamespace)[],\n): ResponsesInputItem[] {\n const loaded = new Set(stringsOf(search?.loaded));\n const namespaces = stringsOf(search?.namespaces);\n const wanted = new Set(namespaces);\n const found: ResponsesTool[] = [];\n\n for (const entry of tools) {\n if (isNamespace(entry)) {\n if (!wanted.has(entry.name)) continue;\n // A search that named the group but listed no functions loaded all of\n // it; otherwise only the functions it listed.\n const inner = entry.tools.filter((tool) => loaded.size === 0 || loaded.has(tool.name));\n if (inner.length === 0) continue;\n found.push({\n type: \"namespace\",\n name: entry.name,\n description: entry.description,\n tools: inner.map((tool) => functionTool(tool, true)),\n });\n } else if (entry.deferred && loaded.has(entry.name)) {\n found.push(functionTool(entry, true));\n }\n }\n\n if (found.length === 0) return [];\n const query =\n search.arguments && typeof search.arguments === \"object\"\n ? search.arguments\n : { paths: namespaces.length > 0 ? namespaces : [...loaded] };\n return [\n {\n type: \"tool_search_call\",\n call_id: null,\n execution: \"server\",\n status: \"completed\",\n arguments: query,\n },\n {\n type: \"tool_search_output\",\n call_id: null,\n execution: \"server\",\n status: \"completed\",\n tools: found,\n },\n ];\n}\n\nfunction stringsOf(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === \"string\") : [];\n}\n\n// --- tools ---------------------------------------------------------------\n\nfunction isNamespace(\n entry: ProviderToolSpec | ProviderToolNamespace,\n): entry is ProviderToolNamespace {\n return Array.isArray((entry as ProviderToolNamespace).tools);\n}\n\n/**\n * Tools and namespaces onto the Responses `tools` array.\n *\n * Without tool search the grouping has nothing to do — a namespace exists to be\n * searched — so it is flattened away and every schema is sent inline with\n * `deferred` ignored. That is the promise `capabilities.toolSearch` makes:\n * deferral is a token optimization, and an optimization that changed which\n * tools the model can reach would not be one.\n */\nexport function toResponsesTools(\n tools: (ProviderToolSpec | ProviderToolNamespace)[] | undefined,\n capabilities: ProviderCapabilities,\n): ResponsesTool[] {\n if (!tools || tools.length === 0) return [];\n\n if (!capabilities.toolSearch) {\n const flat: ResponsesTool[] = [];\n for (const entry of tools) {\n if (isNamespace(entry)) {\n for (const tool of entry.tools) flat.push(functionTool(tool, false));\n } else {\n flat.push(functionTool(entry, false));\n }\n }\n return flat;\n }\n\n const out: ResponsesTool[] = [];\n let anyDeferred = false;\n\n for (const entry of tools) {\n if (isNamespace(entry)) {\n const inner = entry.tools.map((tool) => {\n if (tool.deferred) anyDeferred = true;\n return functionTool(tool, true);\n });\n out.push({\n type: \"namespace\",\n name: entry.name,\n description: entry.description,\n tools: inner,\n });\n } else {\n if (entry.deferred) anyDeferred = true;\n out.push(functionTool(entry, true));\n }\n }\n\n // Without this the deferred schemas are unreachable: the model is shown a\n // name and a description and given no way to ask for the rest, which is worse\n // than not deferring at all. Added only when something is actually deferred,\n // so an agent that defers nothing does not pay for a tool it cannot use.\n if (anyDeferred) out.push({ type: \"tool_search\" });\n\n return out;\n}\n\nfunction functionTool(tool: ProviderToolSpec, allowDeferred: boolean): ResponsesTool {\n const spec: ResponsesTool = {\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n strict: tool.strict,\n };\n if (allowDeferred && tool.deferred) spec.defer_loading = true;\n return spec;\n}\n",
12
+ "import type {\n ProviderCapabilities,\n ProviderStreamParams,\n ProviderToolNamespace,\n ProviderToolSpec,\n} from \"../AgentProvider\";\nimport type { JSONSchema } from \"../Schema\";\nimport type { AgentMessage, FilePart, ReasoningPart } from \"../types\";\nimport { unreadableNote } from \"./fileRejection\";\nimport {\n assertFilePart,\n attachmentIdOf,\n attachmentLine,\n isImageFile,\n toolResultOutput,\n} from \"./request\";\n\n/**\n * `ProviderStreamParams` to a Messages API body (`POST /v1/messages`), as a\n * pure function, for the reason `request.ts` gives: everything that can be\n * wrong here is wrong without a socket.\n *\n * The shapes follow Anthropic's API reference. What differs from the\n * Responses builder, and why:\n *\n * - Roles alternate and a tool result is a `user` block. gemi keeps a step's\n * calls and their results on one assistant message; here the calls stay in\n * the assistant turn and the results open the user turn right after it.\n * - `max_tokens` is required, so a call without `maxOutputTokens` sends\n * `DEFAULT_MAX_TOKENS`.\n * - `temperature` is never sent. On API version `2026-10-21` (see\n * `ANTHROPIC_VERSION`) it is a 400 on every model, whatever its value.\n * - `promptCacheKey` has no Anthropic counterpart: the cache keys on the\n * prefix itself, so it is not sent. Caching is asked for with `cache_control`\n * breakpoints instead; see `withCacheBreakpoints`.\n */\n\nexport type MessagesBlock = Record<string, unknown>;\nexport type MessagesMessage = { role: \"user\" | \"assistant\"; content: MessagesBlock[] };\nexport type MessagesTool = Record<string, unknown>;\n\nexport type MessagesRequest = {\n model: string;\n max_tokens: number;\n messages: MessagesMessage[];\n stream: true;\n system?: MessagesBlock[];\n tools?: MessagesTool[];\n tool_choice?: { type: \"auto\" | \"any\" | \"none\" | \"tool\"; name?: string; disable_parallel_tool_use?: boolean };\n thinking?:\n | {\n type: \"adaptive\";\n display?: \"summarized\";\n block_binding?: { prefix_mismatch_behavior: \"drop_block\" };\n }\n | { type: \"between_tools\" };\n output_config?: {\n effort?: string;\n format?: { type: \"json_schema\"; schema: JSONSchema };\n };\n};\n\n/**\n * Sent when the agent sets no `maxOutputTokens`. Every current Claude model\n * takes 64K or more (128K on the 4.6-and-later families, 64K on Haiku 4.5), and\n * the request is streamed, so a high cap costs nothing until it is used; a low\n * one cuts an answer off mid-thought.\n */\nexport const DEFAULT_MAX_TOKENS = 64_000;\n\nexport function buildMessagesRequest(\n params: ProviderStreamParams,\n ctx: {\n /** What the request names: the model id, or a Foundry deployment. */\n model: string;\n /** The model id, which the per-model rules below read. */\n modelId: string;\n capabilities: ProviderCapabilities;\n forcedToolChoice: boolean;\n /** Whether `thinking.block_binding` can be sent (it needs a beta header\n * that Anthropic's API takes and Foundry is not known to). */\n blockBinding: boolean;\n },\n): MessagesRequest {\n const body: MessagesRequest = {\n model: ctx.model,\n max_tokens: params.maxOutputTokens ?? DEFAULT_MAX_TOKENS,\n messages: toMessages(params.messages, ctx.capabilities),\n stream: true,\n };\n\n // A strict schema goes as `output_config.format`, unless it is over the\n // compiler's limits, in which case it is asked for like a loose one.\n const output = params.output;\n const strict = !!output?.strict && !overSchemaLimits(output.schema);\n\n const loose = output && !strict ? looseOutputInstruction(output.schema) : undefined;\n const system = [params.systemPrompt, loose].filter(Boolean);\n if (system.length > 0) body.system = [{ type: \"text\", text: system.join(\"\\n\\n\") }];\n\n const reasoning = ctx.capabilities.reasoning ? params.reasoning : undefined;\n if (reasoning === \"none\") {\n // Off where the model has a switch for it: Claude Sonnet 5.5 takes\n // `between_tools` at effort `high` or below. Claude Opus 5.5 and the\n // other 5.x models cannot turn thinking off (`disabled` is a 400), so\n // there `none` is the lowest effort and the model still thinks.\n if (/^claude-sonnet-5-5(?:-\\d{8})?$/.test(ctx.modelId)) body.thinking = { type: \"between_tools\" };\n body.output_config = { effort: \"low\" };\n } else if (reasoning) {\n body.thinking = { type: \"adaptive\", display: \"summarized\" };\n body.output_config = { effort: effortOf(reasoning, ctx.modelId) };\n } else if (ctx.capabilities.reasoning && repliesWithThinking(body.messages)) {\n // No effort was asked for, but the model thought anyway (adaptive\n // thinking is the default on the 5.x models) and its blocks are being sent\n // back. `thinking` is made explicit, which is what it already was, so\n // the binding below can be set on it.\n body.thinking = { type: \"adaptive\" };\n }\n\n // PRESERVED THINKING. A thinking block is bound to the conversation that\n // produced it, and `Agent` edits conversations: `contextWindow` and\n // compaction cut the start of the history, `activeTools` narrows the tools\n // and `prepareStep` the instructions from one step to the next. On the\n // models that check (Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable and Mythos 5.1\n // and 5.2), a block sent back after such an edit is a 400 for accounts\n // created from 2026-08-31 (on every account for Mythos 5.1 and the 5.2\n // models). `drop_block` has the API drop those blocks instead: the step\n // loses that reasoning and runs. Where the binding cannot be sent, the\n // provider strips the blocks and asks once more on that 400\n // (`thinkingMismatch`).\n if (body.thinking?.type === \"adaptive\" && ctx.blockBinding) {\n body.thinking.block_binding = { prefix_mismatch_behavior: \"drop_block\" };\n }\n\n if (output && strict) {\n body.output_config = {\n ...body.output_config,\n format: { type: \"json_schema\", schema: toClaudeSchema(output.schema) },\n };\n }\n\n const tools = toMessagesTools(params.tools);\n if (tools.length > 0) {\n body.tools = tools;\n // Forced choice works with adaptive thinking; only manual budgeted\n // thinking, which is never sent, refuses it.\n const choice = toolChoice(params.toolChoice, ctx.forcedToolChoice);\n if (!ctx.capabilities.parallelToolCalls) choice.disable_parallel_tool_use = true;\n if (params.toolChoice !== undefined || choice.disable_parallel_tool_use) body.tool_choice = choice;\n }\n\n return withCacheBreakpoints(body);\n}\n\nfunction repliesWithThinking(messages: MessagesMessage[]): boolean {\n return messages.some((message) =>\n message.content.some((block) => block.type === \"thinking\" || block.type === \"redacted_thinking\"),\n );\n}\n\n/** The beta header `thinking.block_binding` needs. */\nexport const THINKING_BINDING_BETA = \"thinking-binding-controls-2026-08-01\";\n\n/**\n * The request edits that answer a 400 once, with what to change.\n *\n * - `thinking`: a thinking block was bound to a different conversation (see\n * PRESERVED THINKING above) and the binding was not sent. The blocks are\n * stripped and the request asked again, which keeps the text and tool calls\n * and loses only the reasoning, as `drop_block` would.\n * - `schema`: `Schema is too complex for compilation.` The answer is asked for\n * in the system prompt instead, as for a loose schema.\n */\nexport function recoverableRequestError(message: string): \"thinking\" | \"schema\" | undefined {\n if (/bound to a different conversation|Invalid `signature` in `thinking` block/i.test(message)) {\n return \"thinking\";\n }\n if (/schema is too complex/i.test(message)) return \"schema\";\n return undefined;\n}\n\n/** The request without any thinking block, for the `thinking` retry. */\nexport function withoutThinkingBlocks(body: MessagesRequest): MessagesRequest {\n const messages: MessagesMessage[] = [];\n for (const message of body.messages) {\n const content = message.content.filter(\n (block) => block.type !== \"thinking\" && block.type !== \"redacted_thinking\",\n );\n if (content.length === 0) continue;\n const last = messages.at(-1);\n if (last?.role === message.role) last.content.push(...content);\n else messages.push({ role: message.role, content });\n }\n return { ...body, messages };\n}\n\n/**\n * gemi's effort onto `output_config.effort` (`low` … `max`). `minimal` and\n * `none` have no counterpart and are `low`. `xhigh` is `high` on the 4.6\n * models, which predate it. Anything else is sent as written, so a new level\n * works without a gemi release.\n */\nfunction effortOf(reasoning: string, modelId: string): string {\n if (reasoning === \"none\" || reasoning === \"minimal\") return \"low\";\n if (reasoning === \"xhigh\" && /^claude-(?:opus|sonnet)-4-6(?:-|$)/.test(modelId)) return \"high\";\n return reasoning;\n}\n\n/**\n * Prompt caching. The cache holds a prefix in render order (`tools`, then\n * `system`, then `messages`) up to a block marked `cache_control`, so three\n * breakpoints cover what an agent repeats: the last tool (the tool list), the\n * system prompt, and the last block of the last message, which the next step\n * extends, so it reads this step's prefix back. That is three of the four\n * allowed. A prefix under the model's minimum is not cached and costs nothing\n * extra: 512 tokens on Opus 5.5 and 5, Sonnet 5.5, Haiku 5.5 and Fable 5.x,\n * 1024 on Sonnet 5, Opus 4.8 and Sonnet 4.6, up to 4096 on Opus 4.6 and Haiku\n * 4.5. A cache write costs 1.25x input.\n *\n * Thinking blocks cannot carry `cache_control`, so the last message's\n * breakpoint goes on its last block that can.\n */\nfunction withCacheBreakpoints(body: MessagesRequest): MessagesRequest {\n const mark = (block: MessagesBlock | MessagesTool | undefined) => {\n if (block) block.cache_control = { type: \"ephemeral\" };\n };\n mark(body.tools?.at(-1));\n mark(body.system?.at(-1));\n const last = body.messages.at(-1)?.content ?? [];\n mark([...last].reverse().find((b) => b.type !== \"thinking\" && b.type !== \"redacted_thinking\"));\n return body;\n}\n\n// --- structured output ---------------------------------------------------\n\n/**\n * Keywords structured outputs refuse, per Anthropic's JSON schema limits:\n * numeric and string length constraints, and array constraints beyond\n * `minItems` 0 or 1.\n */\nconst UNSUPPORTED_KEYWORDS = new Set([\n \"minimum\",\n \"maximum\",\n \"exclusiveMinimum\",\n \"exclusiveMaximum\",\n \"multipleOf\",\n \"minLength\",\n \"maxLength\",\n \"maxItems\",\n \"uniqueItems\",\n]);\n\n/** The string formats structured outputs take. */\nconst SUPPORTED_FORMATS = new Set([\n \"date-time\",\n \"time\",\n \"date\",\n \"duration\",\n \"email\",\n \"hostname\",\n \"uri\",\n \"ipv4\",\n \"ipv6\",\n \"uuid\",\n]);\n\n/** Regex features structured outputs refuse: backreferences, lookaround and\n * word boundaries. */\nconst UNSUPPORTED_PATTERN = /\\\\[1-9]|\\(\\?<?[=!]|\\\\[bB]/;\n\nconst SCHEMA_MAPS = new Set([\"properties\", \"patternProperties\", \"$defs\", \"definitions\"]);\n\n/**\n * The agent's schema as structured outputs takes it, transformed the way\n * Anthropic's SDKs transform one: a constraint the API refuses (the keywords\n * above, a `minItems` over 1, a string `format` outside the supported list, a\n * `pattern` with backreferences, lookaround or `\\b`) is removed and written\n * into the node's `description` instead (`{minimum: 100}`), so the model still\n * reads it; and every object gets `additionalProperties: false`, which the API\n * requires. Nothing is lost: `Agent` validates the answer against the agent's\n * own schema, constraints included.\n */\nexport function toClaudeSchema(schema: JSONSchema): JSONSchema {\n const transform = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(transform);\n if (!isObject(node)) return node;\n const out: Record<string, unknown> = {};\n const moved: string[] = [];\n for (const [key, value] of Object.entries(node)) {\n const refused =\n UNSUPPORTED_KEYWORDS.has(key) ||\n (key === \"minItems\" && typeof value === \"number\" && value > 1) ||\n (key === \"format\" && typeof value === \"string\" && !SUPPORTED_FORMATS.has(value)) ||\n (key === \"pattern\" && typeof value === \"string\" && UNSUPPORTED_PATTERN.test(value));\n if (refused) {\n moved.push(`${key}: ${JSON.stringify(value)}`);\n continue;\n }\n // These map names to schemas; a property named `minimum` is kept.\n out[key] =\n SCHEMA_MAPS.has(key) && isObject(value)\n ? Object.fromEntries(Object.entries(value).map(([name, sub]) => [name, transform(sub)]))\n : transform(value);\n }\n if (moved.length > 0) {\n const note = `{${moved.join(\", \")}}`;\n out.description = typeof out.description === \"string\" ? `${out.description} ${note}` : note;\n }\n if (out.type === \"object\" || isObject(out.properties)) out.additionalProperties = false;\n return out;\n };\n return transform(schema) as JSONSchema;\n}\n\n/**\n * Whether a schema is over the structured-output compiler's limits: 24\n * optional properties and 16 union-typed ones (`anyOf` or a type array)\n * across the request. Tools are not sent strict, so the output schema is the\n * only one counted. Over either, the API answers `Schema is too complex for\n * compilation.`; the answer is asked for like a loose schema's instead.\n */\nfunction overSchemaLimits(schema: JSONSchema): boolean {\n let optional = 0;\n let unions = 0;\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) return node.forEach(visit);\n if (!isObject(node)) return;\n if (Array.isArray(node.anyOf) || Array.isArray(node.type)) unions++;\n if (isObject(node.properties)) {\n const required = new Set(Array.isArray(node.required) ? node.required : []);\n optional += Object.keys(node.properties).filter((name) => !required.has(name)).length;\n }\n for (const [key, value] of Object.entries(node)) {\n if (SCHEMA_MAPS.has(key) && isObject(value)) Object.values(value).forEach(visit);\n else visit(value);\n }\n };\n visit(schema);\n return optional > 24 || unions > 16;\n}\n\n/**\n * A schema that is not `strict` holds a free-form node (`s.json()`), which\n * structured outputs cannot express (every object needs `additionalProperties:\n * false`). It is not sent as `output_config.format`, which would be a 400;\n * the model is asked for the JSON in the system prompt instead, and `Agent`\n * validates what comes back. Schemas over the compiler's limits go the same\n * way (`overSchemaLimits`).\n */\nfunction looseOutputInstruction(schema: JSONSchema): string {\n return `Answer with only a JSON value (no prose, no code fence) that matches this JSON schema:\\n${JSON.stringify(schema)}`;\n}\n\n/**\n * gemi's `toolChoice` onto `tool_choice`.\n *\n * `\"required\"` is `any` and `{ name }` is `tool`, on the models that take them.\n * Claude Opus 5.5, Claude Sonnet 5.5 and Claude Fable 5.1 answer both with a\n * 400 (`tool_choice: type \"tool\" and \"any\" are not supported for this model.`),\n * so on those, and on any id `supportsForcedToolChoice` does not know, the\n * choice is sent as `auto`: the step still runs, and the prompt that asked for\n * the tool still asks for it. Failing the step instead would fail every step a\n * `prepareStep` forces, with no setting to turn it off.\n */\nfunction toolChoice(\n choice: ProviderStreamParams[\"toolChoice\"],\n forced: boolean,\n): NonNullable<MessagesRequest[\"tool_choice\"]> {\n if (choice === \"none\") return { type: \"none\" };\n if (choice === \"required\") return forced ? { type: \"any\" } : { type: \"auto\" };\n if (choice && typeof choice === \"object\") {\n return forced ? { type: \"tool\", name: choice.name } : { type: \"auto\" };\n }\n return { type: \"auto\" };\n}\n\n// --- messages ------------------------------------------------------------\n\n/**\n * `AgentMessage[]` to alternating `user` / `assistant` messages.\n *\n * Parts are laid out in order, each with the role it has on this API: the\n * assistant's text and tool calls are `assistant`, a tool result is `user`, and\n * the user's own words and files are `user`. Consecutive blocks of one role\n * are one message, which is what the API wants and what a step that called\n * three tools needs: three `tool_use` blocks in one turn, three `tool_result`\n * blocks in the next.\n *\n * Tool results are not placed where they sit in gemi's message but right after\n * the turn that made their calls, first in the user turn, in call order: the\n * API requires every `tool_use` to be answered in the very next message, with\n * the results before anything else in it. A step's calls are answered where\n * the step is known to be over: at the next message, or, when gemi kept the\n * next step on the same message, at the first block after a tool result. The\n * pairing rules are those of\n * `reconcileToolPairs` in `request.ts`, and for the same reasons: a repeated\n * call or result is dropped, a result for a call this history does not hold is\n * dropped, and a call left without a result gets one saying so.\n */\nexport function toMessages(\n messages: AgentMessage[],\n capabilities: ProviderCapabilities,\n): MessagesMessage[] {\n // `step-end` marks where a step's calls are known to be done: a new\n // message, or a tool result (the next step's blocks can share the message).\n const blocks: ({ role: \"user\" | \"assistant\"; block: MessagesBlock } | \"step-end\")[] = [];\n const results = new Map<string, MessagesBlock>();\n\n for (const message of messages) {\n // A system-role message in the history is the app's, not the user's, but\n // `messages` takes only two roles; it is sent as user text.\n const role = message.role === \"assistant\" ? \"assistant\" : \"user\";\n blocks.push(\"step-end\");\n for (const part of message.content ?? []) {\n switch (part.type) {\n case \"text\": {\n // The assistant's text goes back exactly as the model wrote it,\n // whitespace-only blocks included (the \"\\n\\n\" before a tool call):\n // anything else is an edit to the turn. Only an empty string, which\n // the API refuses, is left out. A user's blank text is noise.\n const keep = role === \"assistant\" ? !!part.text : !!part.text?.trim();\n if (keep) blocks.push({ role, block: { type: \"text\", text: part.text } });\n break;\n }\n case \"output\": {\n if (part.partial) break;\n // The model's own text when the part kept it; re-serializing the\n // value would change its whitespace and number formatting.\n const text = part.text ?? JSON.stringify(part.value);\n blocks.push({ role, block: { type: \"text\", text } });\n break;\n }\n case \"file\": {\n if (role === \"assistant\") break;\n for (const block of fileBlocks(part, capabilities)) blocks.push({ role, block });\n break;\n }\n case \"reasoning\": {\n // Claude's own thinking goes back as it came, signature and all,\n // empty ones included. Another provider's reasoning (a Responses\n // item id) means nothing here and is left out.\n const block = role === \"assistant\" ? thinkingBlock(part) : undefined;\n if (block) blocks.push({ role, block });\n break;\n }\n case \"tool-call\": {\n if (part.partial) break;\n blocks.push({\n role: \"assistant\",\n block: {\n type: \"tool_use\",\n id: part.toolCallId,\n name: String(part.name),\n input: isObject(part.input) ? part.input : {},\n },\n });\n break;\n }\n case \"tool-result\": {\n blocks.push(\"step-end\");\n if (results.has(part.toolCallId)) break;\n results.set(part.toolCallId, {\n type: \"tool_result\",\n tool_use_id: part.toolCallId,\n content: toolResultOutput(part),\n ...(part.status === \"error\" ? { is_error: true } : {}),\n });\n break;\n }\n }\n }\n }\n\n const out: MessagesMessage[] = [];\n const push = (role: \"user\" | \"assistant\", block: MessagesBlock) => {\n const last = out[out.length - 1];\n if (last && last.role === role) last.content.push(block);\n else out.push({ role, content: [block] });\n };\n const called = new Set<string>();\n // The calls of the assistant turn being written, answered when it ends.\n let open: string[] = [];\n let stepEnded = false;\n const answer = () => {\n for (const id of open) push(\"user\", results.get(id) ?? noResult(id));\n open = [];\n stepEnded = false;\n };\n\n for (const entry of blocks) {\n if (entry === \"step-end\") {\n stepEnded = true;\n continue;\n }\n const { role, block } = entry;\n // Anything after a finished step's calls, in either role, comes after\n // their results.\n if (stepEnded || role === \"user\") answer();\n if (block.type === \"tool_use\") {\n const id = String(block.id);\n if (called.has(id)) continue;\n called.add(id);\n open.push(id);\n }\n push(role, block);\n }\n answer();\n\n // The API wants a user turn first, and on the 4.6-and-later models it\n // refuses a history that ends on the assistant (that is a prefill). Both\n // happen when an app starts a run from a trimmed or assistant-authored\n // history. The turns added are fixed text, so the prefix stays the same\n // from one step to the next.\n if (out[0]?.role === \"assistant\") {\n out.unshift({ role: \"user\", content: [{ type: \"text\", text: HISTORY_STARTS_HERE }] });\n }\n if (out.at(-1)?.role === \"assistant\") {\n out.push({ role: \"user\", content: [{ type: \"text\", text: CONTINUE }] });\n }\n return out;\n}\n\nconst HISTORY_STARTS_HERE = \"(The conversation continues from an earlier point.)\";\nconst CONTINUE = \"Continue.\";\n\nconst NO_RESULT_RECORDED = \"No result was recorded for this tool call. Assume it did not complete.\";\n\nfunction noResult(toolUseId: string): MessagesBlock {\n return { type: \"tool_result\", tool_use_id: toolUseId, content: NO_RESULT_RECORDED };\n}\n\n/** A reasoning part this provider wrote, back as its block; else nothing. */\nfunction thinkingBlock(part: ReasoningPart): MessagesBlock | undefined {\n const meta = part.providerMetadata?.anthropic;\n if (!isObject(meta)) return undefined;\n if (meta.type === \"thinking\" && typeof meta.signature === \"string\") {\n return { type: \"thinking\", thinking: part.text ?? \"\", signature: meta.signature };\n }\n if (meta.type === \"redacted_thinking\" && typeof meta.data === \"string\") {\n return { type: \"redacted_thinking\", data: meta.data };\n }\n return undefined;\n}\n\n/**\n * A file part as the model is told about it, with the rules of the `file` case\n * in `toResponsesInput`: the attachment line when the part has an attachment\n * id, and the file itself when the model can read it.\n *\n * Files go by Files API id (`source: {type: \"file\"}`): an image as an `image`\n * block, a PDF or plain text as a `document`. Those are the types the API\n * reads; any other file is not shown (it would be a 400), and the model is told\n * so. Without `fileInput` it is the attachment line alone.\n */\nfunction fileBlocks(part: FilePart, capabilities: ProviderCapabilities): MessagesBlock[] {\n const attachmentId = attachmentIdOf(part);\n const line = (shown: boolean): MessagesBlock[] =>\n attachmentId ? [{ type: \"text\", text: attachmentLine(part, shown) }] : [];\n if (!capabilities.fileInput) return line(false);\n assertFilePart(part, attachmentId);\n if (!part.fileId) return line(false);\n const kind = part.providerRejected ? undefined : fileKind(part);\n if (!kind) return [...line(false), { type: \"text\", text: unreadableNote(part.name) }];\n return [...line(true), { type: kind, source: { type: \"file\", file_id: part.fileId } }];\n}\n\nconst IMAGE_TYPES = new Set([\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\"]);\n\nfunction fileKind(part: FilePart): \"image\" | \"document\" | undefined {\n const mimeType = part.mimeType?.trim().toLowerCase() ?? \"\";\n if (isImageFile(part)) return !mimeType || IMAGE_TYPES.has(mimeType) ? \"image\" : undefined;\n if (mimeType) return mimeType === \"application/pdf\" || mimeType === \"text/plain\" ? \"document\" : undefined;\n return /\\.(pdf|txt)$/i.test(part.name ?? \"\") ? \"document\" : undefined;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\n// --- tools ---------------------------------------------------------------\n\nfunction isNamespace(\n entry: ProviderToolSpec | ProviderToolNamespace,\n): entry is ProviderToolNamespace {\n return Array.isArray((entry as ProviderToolNamespace).tools);\n}\n\n/**\n * Tools onto the `tools` array, flat: this provider reports no tool search\n * (`capabilitiesForClaude`), so a namespace is flattened and a deferred tool\n * is sent whole, exactly as `toResponsesTools` does for a model without it.\n *\n * `strict` is not sent. Anthropic's strict tool use allows at most 20 strict\n * tools and 24 optional parameters across them per request, and refuses\n * numeric and length constraints, so passing gemi's flag through would turn an\n * agent with many tools into a 400. `Agent` validates every call's arguments\n * against the tool's schema either way.\n *\n * `eager_input_streaming` is on for every tool: the request is always\n * streamed, and without it the API buffers each argument until it is whole, so\n * a tool that writes a file sends nothing for as long as the model writes it.\n * It also gives up the API's own validation of the arguments, which `Agent`\n * does anyway.\n */\nexport function toMessagesTools(\n tools: (ProviderToolSpec | ProviderToolNamespace)[] | undefined,\n): MessagesTool[] {\n const out: MessagesTool[] = [];\n for (const entry of tools ?? []) {\n for (const tool of isNamespace(entry) ? entry.tools : [entry]) {\n out.push({\n name: tool.name,\n description: tool.description,\n input_schema: tool.parameters,\n eager_input_streaming: true,\n });\n }\n }\n return out;\n}\n",
13
+ "import type { ProviderEvent } from \"../AgentProvider\";\nimport type { AgentError, FinishReason, Usage } from \"../types\";\nimport { emptyUsage, sseMessages } from \"./stream\";\n\n/**\n * The Messages API SSE stream to `ProviderEvent`, a pure function over chunks\n * like `parseResponsesStream`, driven in the tests by the hand-written\n * fixtures in `__fixtures__/anthropic-*.sse`.\n *\n * The event flow, from Anthropic's streaming reference: `message_start` (the\n * model and the input usage), then per content block `content_block_start`,\n * its `content_block_delta`s and `content_block_stop`, then `message_delta`\n * (the stop reason, and usage that is CUMULATIVE, not an increment) and\n * `message_stop`. `ping` frames come at any time, an `error` frame can replace\n * the rest, and unknown event types are to be ignored.\n *\n * Thinking is `reasoning-delta`s with no id. A `thinking` block's text streams\n * as it comes, and at its stop one more, empty delta carries the signature as\n * `providerMetadata.anthropic`, which closes the part. A `redacted_thinking`\n * block is one empty delta carrying its `data`. `anthropicRequest.ts` turns\n * those parts back into the blocks, unchanged, as the API requires.\n */\n\ntype ParseOptions = {\n /** The agent asked for an `output` schema, so text is the answer's JSON. */\n structuredOutput?: boolean;\n};\n\ntype OpenBlock = { type: string; id?: string; name?: string; args: string; signature: string };\n\nexport async function* parseMessagesStream(\n chunks: AsyncIterable<string> | Iterable<string>,\n options: ParseOptions = {},\n): AsyncGenerator<ProviderEvent> {\n const blocks = new Map<number, OpenBlock>();\n // Calls whose arguments are not whole JSON, held until the stop reason says\n // whether they were cut off.\n const held: OpenBlock[] = [];\n let model: string | undefined;\n let usage: RawUsage = {};\n let stopReason: string | undefined;\n let stopDetails: Record<string, any> | undefined;\n let finished = false;\n\n const ended = (reason: FinishReason): ProviderEvent => ({\n type: \"finish\",\n reason,\n usage: toAnthropicUsage(usage),\n ...(model ? { model } : {}),\n });\n\n for await (const message of sseMessages(chunks)) {\n let payload: Record<string, any>;\n try {\n payload = JSON.parse(message.data);\n } catch {\n continue;\n }\n const type: string = typeof payload.type === \"string\" ? payload.type : message.event;\n\n switch (type) {\n case \"message_start\": {\n const start = payload.message ?? {};\n if (typeof start.model === \"string\" && start.model) model = start.model;\n usage = mergeUsage(usage, start.usage);\n break;\n }\n\n case \"content_block_start\": {\n const index = Number(payload.index);\n const block = payload.content_block ?? {};\n const open: OpenBlock = {\n type: String(block.type ?? \"\"),\n id: typeof block.id === \"string\" ? block.id : undefined,\n name: typeof block.name === \"string\" ? block.name : undefined,\n args: \"\",\n signature: typeof block.signature === \"string\" ? block.signature : \"\",\n };\n blocks.set(index, open);\n // Redacted thinking arrives whole: encrypted, nothing to show, and\n // sent back as it came.\n if (open.type === \"redacted_thinking\") {\n yield {\n type: \"reasoning-delta\",\n delta: \"\",\n providerMetadata: { anthropic: { type: \"redacted_thinking\", data: String(block.data ?? \"\") } },\n };\n }\n // A text block opens empty in every recorded shape, but the field is\n // there, so a gateway that sends it whole is read.\n if (open.type === \"text\" && typeof block.text === \"string\" && block.text) {\n yield textEvent(block.text, options);\n }\n break;\n }\n\n case \"content_block_delta\": {\n const block = blocks.get(Number(payload.index));\n const delta = payload.delta ?? {};\n if (!block) break;\n if (delta.type === \"text_delta\") {\n const text = String(delta.text ?? \"\");\n if (text) yield textEvent(text, options);\n } else if (delta.type === \"thinking_delta\") {\n const text = String(delta.thinking ?? \"\");\n if (text) yield { type: \"reasoning-delta\", delta: text };\n } else if (delta.type === \"signature_delta\") {\n block.signature += String(delta.signature ?? \"\");\n } else if (delta.type === \"input_json_delta\" && block.type === \"tool_use\") {\n const fragment = String(delta.partial_json ?? \"\");\n if (!fragment) break;\n block.args += fragment;\n yield {\n type: \"tool-call-delta\",\n toolCallId: block.id ?? \"\",\n name: block.name ?? \"\",\n argsDelta: fragment,\n };\n }\n break;\n }\n\n case \"content_block_stop\": {\n const index = Number(payload.index);\n const block = blocks.get(index);\n blocks.delete(index);\n // The signature closes the thinking part, and is what lets it be sent\n // back (see `ReasoningPart.providerMetadata`). A block with no text\n // (`display: \"omitted\"`) still becomes a part: it has to go back too.\n if (block?.type === \"thinking\") {\n yield {\n type: \"reasoning-delta\",\n delta: \"\",\n providerMetadata: { anthropic: { type: \"thinking\", signature: block.signature } },\n };\n }\n if (block?.type === \"tool_use\") {\n // A call with no arguments streams no delta at all; its input is\n // the empty object.\n block.args ||= \"{}\";\n // A block is stopped even when `max_tokens` cut it off, and then its\n // arguments are a prefix of the JSON. Such a call must not be\n // emitted whole, or it would run; it is held for `message_stop`.\n if (isJson(block.args)) yield toolCall(block);\n else held.push(block);\n }\n break;\n }\n\n case \"message_delta\": {\n if (typeof payload.delta?.stop_reason === \"string\") stopReason = payload.delta.stop_reason;\n if (payload.delta?.stop_details) stopDetails = payload.delta.stop_details;\n usage = mergeUsage(usage, payload.usage);\n break;\n }\n\n case \"message_stop\": {\n finished = true;\n // A refusal is the model's safety classifier declining, on HTTP 200.\n // Ending it `stop` would read as an answer, which is the mistake\n // `content_filtered` exists to prevent (as with OpenAI's refusal item).\n if (stopReason === \"refusal\") {\n yield { type: \"error\", error: refusalError(stopDetails) };\n yield ended(\"error\");\n break;\n }\n const reason = finishReasonOf(stopReason);\n // Cut off: the held calls never finished, so they are discarded (the\n // agent forgets them and the client removes their partial parts) and\n // the call ends `length`. Otherwise a held call is the model's own\n // malformed JSON, passed on for `Agent` to report against the tool.\n if (held.length > 0 && reason === \"length\") {\n yield { type: \"tool-call-discard\", toolCallIds: held.map((b) => b.id ?? \"\") };\n } else {\n for (const block of held) yield toolCall(block);\n }\n yield ended(reason);\n break;\n }\n\n case \"error\": {\n finished = true;\n yield { type: \"error\", error: anthropicStreamError(payload.error ?? payload) };\n yield ended(\"error\");\n break;\n }\n }\n\n if (finished) return;\n }\n\n // No `message_stop`: the connection closed under the answer. Retryable, as\n // in `parseResponsesStream`.\n yield {\n type: \"error\",\n error: {\n code: \"provider_error\",\n message: \"The provider stream ended without a terminal event.\",\n retryable: true,\n },\n };\n yield ended(\"error\");\n}\n\nfunction toolCall(block: OpenBlock): ProviderEvent {\n return { type: \"tool-call\", toolCallId: block.id ?? \"\", name: block.name ?? \"\", args: block.args };\n}\n\nfunction isJson(text: string): boolean {\n try {\n JSON.parse(text);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction textEvent(delta: string, options: ParseOptions): ProviderEvent {\n return options.structuredOutput ? { type: \"output-delta\", delta } : { type: \"text-delta\", delta };\n}\n\n/**\n * `stop_reason` onto gemi's finish reasons. `max_tokens` is a truncated answer,\n * and so is `model_context_window_exceeded` (the answer ran into the context\n * window rather than the cap). Everything else that ends a turn normally\n * (`end_turn`, `tool_use`, `stop_sequence`, and `pause_turn`, which only\n * server tools produce) is `stop`; `Agent` reads the tool calls themselves.\n */\nfunction finishReasonOf(stopReason: string | undefined): FinishReason {\n if (stopReason === \"max_tokens\" || stopReason === \"model_context_window_exceeded\") return \"length\";\n return \"stop\";\n}\n\nfunction refusalError(details: Record<string, any> | undefined): AgentError {\n const explanation = typeof details?.explanation === \"string\" ? details.explanation : \"\";\n const category = typeof details?.category === \"string\" ? ` (${details.category})` : \"\";\n return {\n code: \"content_filtered\",\n message: explanation || `The model declined to answer${category}.`,\n retryable: false,\n };\n}\n\n/**\n * An `error` frame, which arrives on a 200: the request was accepted and the\n * failure came later, so it is retryable unless its type says the request\n * itself is wrong. `overloaded_error` is the one seen most, the 529 of a\n * streamed call.\n */\nexport function anthropicStreamError(raw: any): AgentError {\n const type = String(raw?.type ?? \"\").toLowerCase();\n const message = typeof raw?.message === \"string\" ? raw.message : \"The provider stream failed.\";\n if (type === \"rate_limit_error\") return { code: \"rate_limited\", message, retryable: true };\n if (type === \"invalid_request_error\" || type === \"request_too_large\") {\n const tooLong = /prompt is too long|request_too_large/i.test(`${type} ${message}`);\n return {\n code: tooLong ? \"context_length_exceeded\" : \"provider_error\",\n message,\n retryable: false,\n };\n }\n if (\n type === \"authentication_error\" ||\n type === \"permission_error\" ||\n type === \"billing_error\" ||\n type === \"not_found_error\"\n ) {\n return { code: \"provider_error\", message, retryable: false };\n }\n return { code: \"provider_error\", message, retryable: true };\n}\n\ntype RawUsage = {\n input_tokens?: number;\n output_tokens?: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n /** From `output_tokens_details.thinking_tokens`, part of `output_tokens`. */\n thinking_tokens?: number;\n};\n\n/** The latest value of each field: `message_delta` usage is cumulative. */\nfunction mergeUsage(total: RawUsage, raw: any): RawUsage {\n if (!raw || typeof raw !== \"object\") return total;\n const next = { ...total };\n for (const key of [\n \"input_tokens\",\n \"output_tokens\",\n \"cache_creation_input_tokens\",\n \"cache_read_input_tokens\",\n ] as const) {\n if (typeof raw[key] === \"number\") next[key] = raw[key];\n }\n const thinking = raw.output_tokens_details?.thinking_tokens;\n if (typeof thinking === \"number\") next.thinking_tokens = thinking;\n return next;\n}\n\n/**\n * Anthropic usage onto `Usage`.\n *\n * Anthropic reports input in three disjoint parts: `input_tokens` (after the\n * last cache breakpoint), `cache_read_input_tokens` and\n * `cache_creation_input_tokens`. gemi's `inputTokens` is the whole prompt, as\n * OpenAI reports it, so it is their sum, and the two cache parts are its\n * breakdown (`cachedInputTokens`, `cacheWriteInputTokens`). Thinking tokens are part\n * of `output_tokens` and are its `reasoningTokens` breakdown. A field the\n * response did not carry stays absent rather than zero.\n */\nexport function toAnthropicUsage(raw: RawUsage | undefined): Usage {\n if (!raw) return emptyUsage();\n const read = raw.cache_read_input_tokens;\n const write = raw.cache_creation_input_tokens;\n const inputTokens = (raw.input_tokens ?? 0) + (read ?? 0) + (write ?? 0);\n const outputTokens = raw.output_tokens ?? 0;\n const usage: Usage = { inputTokens, outputTokens, totalTokens: inputTokens + outputTokens };\n if (typeof read === \"number\") usage.cachedInputTokens = read;\n if (typeof write === \"number\") usage.cacheWriteInputTokens = write;\n if (typeof raw.thinking_tokens === \"number\") usage.reasoningTokens = raw.thinking_tokens;\n return usage;\n}\n",
14
+ "import type { ProviderCapabilities } from \"../AgentProvider\";\n\n/**\n * What a model can do, read off its id.\n *\n * Hardcoding `true` was never an option — `reasoning: { effort }` is a 400 on\n * gpt-4o, and `defer_loading` is a 400 on anything that predates tool search —\n * but neither is a table lookup that only answers for ids we shipped knowing\n * about.\n *\n * SO AN UNKNOWN ID GETS EVERY CAPABILITY. That is the whole point: a model\n * released next Tuesday must be usable by writing its name, not by waiting for\n * a gemi release. The default is chosen for how it fails, not for how often it\n * is right. Guessing high fails loudly and once — the API rejects the request\n * and names the parameter it disliked, and the fix is one line of config.\n * Guessing low fails silently and forever: reasoning is dropped, every deferred\n * schema is inlined, and the only symptom is a bigger bill and a worse answer.\n * Unknown ids also skew new rather than old, because nobody invents the name of\n * a model that already shipped.\n *\n * The named families below exist to make the *known-old* cases right, which is\n * the only place a guess can be wrong in the quiet direction.\n *\n * Note what an answer of `false` does and does not buy. `reasoning: false` and\n * `toolSearch: false` change the request, because both are optimizations and\n * the run is identical without them. `structuredOutput: false` does not: it is\n * reported honestly for a caller that wants to branch on it, but the request\n * builder still sends the schema, because an agent that declared an `output`\n * has an app waiting on a typed result and dropping the parameter would answer\n * prose forever with nothing to branch on. See `request.ts`.\n *\n * `fileInput` IS DELIBERATELY STILL ONE FLAG, and this was reopened rather than\n * inherited. Splitting it into \"reads images\" and \"reads documents\" was the\n * obvious answer to #488, so it was measured before it was written: gpt-5.4 and\n * gpt-4o were each sent an uploaded PNG as `input_image` and an uploaded PDF as\n * `input_file`, and all four calls returned 200 with the right answer (the\n * transcript is in `request.ts`, above `IMAGE_EXTENSIONS`). The two abilities\n * did not come apart on either model, so there is nothing here for a second\n * flag to describe.\n *\n * Adding it anyway would be worse than none. Every guess in this file is a\n * guess about an id nobody has run yet, and the guess is high on purpose; a\n * second flag does not describe the world more finely, it doubles the number of\n * ways that guess can be wrong quietly, and the wrong-quiet direction is the\n * one with no error message. The split earns its place the day a model answers\n * 200 to one of those two calls and 400 to the other — and that call is cheap\n * to repeat, which is why the recipe is written down rather than the conclusion\n * alone.\n */\nexport function capabilitiesForModel(model: string): ProviderCapabilities {\n const id = normalizeModelId(model);\n\n // Everything before the tool-era models. Listed by prefix because these names\n // are closed sets now — nothing new will be called `gpt-3.5-*`.\n if (id.startsWith(\"gpt-3.5\") || id.startsWith(\"text-\") || id.startsWith(\"davinci\")) {\n return {\n reasoning: false,\n structuredOutput: false,\n fileInput: false,\n parallelToolCalls: true,\n toolSearch: false,\n };\n }\n\n const family = parseFamily(id);\n\n // o1 reasons but takes its tool calls one at a time; o3/o4 do not have that\n // restriction. Both predate tool search.\n if (family?.kind === \"o\") {\n return {\n reasoning: true,\n structuredOutput: true,\n fileInput: true,\n parallelToolCalls: family.major > 1,\n toolSearch: supportsToolSearch(family),\n };\n }\n\n if (family?.kind === \"gpt\") {\n return {\n // gpt-4 and gpt-4o are strong models with no reasoning parameter at all.\n reasoning: family.major >= 5,\n // Strict `json_schema` landed with gpt-4o; plain gpt-4 only has json_object.\n structuredOutput: family.major > 4 || id.startsWith(\"gpt-4o\") || id.startsWith(\"gpt-4.1\"),\n fileInput: family.major > 4 || id.startsWith(\"gpt-4o\") || id.startsWith(\"gpt-4.1\"),\n parallelToolCalls: true,\n toolSearch: supportsToolSearch(family),\n };\n }\n\n return {\n reasoning: true,\n structuredOutput: true,\n fileInput: true,\n parallelToolCalls: true,\n toolSearch: true,\n };\n}\n\n/**\n * Tool search, by generation.\n *\n * MEASURED, not read off a changelog. Every id below was sent a request\n * carrying `{type:\"tool_search\"}` plus one `namespace` of deferred functions,\n * against `https://api.openai.com/v1/responses`:\n *\n * accepted (200): gpt-5.6-terra, gpt-5.5, gpt-5.4, gpt-5.4-mini,\n * gpt-5.3-codex, gpt-5.2\n * rejected (400): gpt-5.1, gpt-5, gpt-5-mini, gpt-4.1, gpt-4o, o4-mini, o3\n *\n * with the rejection reading, verbatim,\n * `Tool 'tool_search' is not supported with gpt-5.1.` — recorded as\n * `__fixtures__/openai-error-tool-search-unsupported.json`.\n *\n * So the boundary is the *minor* number, and the whole-major rule this used to\n * carry (`major >= 5`) was wrong in the expensive direction for four shipped\n * models: gpt-5, gpt-5-mini and gpt-5.1 would have had `defer_loading` and a\n * `tool_search` tool put in every request and answered 400 on all of them.\n * Reading the minor is the only way to be right here, because gpt-5 and gpt-5.4\n * differ by a decimal point and by this capability.\n *\n * The o-series keeps its `major >= 5` guard rather than being hardcoded false:\n * o1 through o4 are all measured rejections above, and an o5 that does not\n * exist gets the same benefit-of-the-doubt an unknown id gets, for the reason\n * in the module comment.\n */\nfunction supportsToolSearch(family: Family): boolean {\n if (family.kind === \"o\") return family.major >= 5;\n return family.major > 5 || (family.major === 5 && family.minor >= 2);\n}\n\n/**\n * What a Claude model can do, read off its id, with the same bias as\n * `capabilitiesForModel`: an id this does not know gets every capability that\n * is safe to guess.\n *\n * - `reasoning`: adaptive thinking (`thinking: {type: \"adaptive\"}` with\n * `output_config.effort`), which the 4.6 models and everything after take.\n * The 4.5 generation and older only take a token budget and answer adaptive\n * thinking with a 400, so `reasoning` is dropped for them.\n * - `fileInput`: images (JPEG, PNG, GIF, WebP), PDFs and plain text, uploaded\n * through the Files API. Other types are not shown; see `fileBlocks`.\n * - `toolSearch`: false for now. Anthropic has a tool search tool, but\n * replaying its results in a history is not built yet, so deferred tools and\n * namespaces are sent flat and whole, which runs the agent the same.\n *\n * Forced tool choice is not a capability an agent can branch on; it decides\n * how the request is built. See `supportsForcedToolChoice`.\n */\nexport function capabilitiesForClaude(model: string): ProviderCapabilities {\n const id = normalizeModelId(model);\n // `claude-opus-4-1`, `claude-haiku-4-5`, `claude-sonnet-4-20250514` (minor\n // 0): the 4.x releases before 4.6.\n const four = /^claude-(?:opus|sonnet|haiku)-4(?:-(\\d{1,2}))?(?:-\\d{8})?$/.exec(id);\n const legacy = /^claude-(?:3|2|instant)/.test(id) || (!!four && Number(four[1] ?? 0) <= 5);\n return {\n reasoning: !legacy,\n structuredOutput: true,\n fileInput: true,\n parallelToolCalls: true,\n toolSearch: false,\n };\n}\n\n/**\n * Whether a Claude model takes `tool_choice` `any` and `tool`.\n *\n * Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.1 (and the Mythos and\n * 5.2 releases beside them) answer both with a 400, and every release since\n * Claude Opus 5 that did not keep them has dropped them. So this is a list of\n * the families known to take them, not of those known to refuse, and an id it\n * does not know is sent `auto`: a step that should have called a tool and\n * wrote text instead is a worse step, while a 400 is a failed one on every\n * forced step.\n */\nexport function supportsForcedToolChoice(model: string): boolean {\n const id = normalizeModelId(model);\n return (\n /^claude-(?:3|2|instant)/.test(id) ||\n /^claude-(?:opus|sonnet|haiku)-4(?:-|$)/.test(id) ||\n /^claude-(?:opus|sonnet|fable|mythos)-5(?:-\\d{8})?$/.test(id) ||\n /^claude-haiku-5-5(?:-\\d{8})?$/.test(id)\n );\n}\n\n/**\n * Azure deployment names are chosen by whoever ran the ARM template, so half of\n * them look nothing like a model id. That is not a special case here: an\n * unrecognizable deployment name lands on the same all-true default as an\n * unrecognized model, for the same reason.\n */\nfunction normalizeModelId(model: string): string {\n return model.trim().toLowerCase();\n}\n\nexport type Family = { kind: \"gpt\" | \"o\"; major: number; minor: number };\n\n/**\n * Reads the generation out of `gpt-5.4-mini-2025-01-01` or `o3-mini`.\n *\n * The minor number is read as well as the major, and it is load-bearing: tool\n * search arrived at gpt-5.2, so `gpt-5` and `gpt-5.4` are two different answers\n * to the same question and a major-only reading gets one of them wrong. An id\n * with no minor — `gpt-5`, `gpt-4o`, `o3` — is minor 0, which is what it is.\n *\n * Exported for its own test: the classification is what the guards below are\n * really about, and it is the only place they are observable — two ids can\n * classify differently and still land on the same capability answer today.\n */\nexport function parseFamily(id: string): Family | null {\n const gpt = /^gpt-(\\d+)(?:\\.(\\d+))?/.exec(id);\n if (gpt?.[1]) return { kind: \"gpt\", major: Number(gpt[1]), minor: Number(gpt[2] ?? 0) };\n // `o1`, `o3-mini`, `o4-mini`. The boundary is what keeps an id whose leading\n // digits are not a generation out of this family — `o200k-base` is a\n // tokenizer, not an o-series model, and `/^o(\\d+)/` alone reads it as\n // generation 200. (`omni-moderation` never gets this far: `m` is not a\n // digit.) Both land on the unknown default today, so the boundary is only\n // visible in the classification — which is where a future rule keyed on\n // `major` would read it.\n const o = /^o(\\d+)(?:[-.]|$)/.exec(id);\n // The o-series never had a minor: `o3-mini` is a size, not a point release.\n if (o?.[1]) return { kind: \"o\", major: Number(o[1]), minor: 0 };\n return null;\n}\n",
15
+ "/**\n * Where a vendor lives, and who we are to it — resolved once, for every kind of\n * call.\n *\n * WHY THIS IS ITS OWN MODULE. The Responses path and the images path differ only\n * in the last segment of the URL. Everything before it — which host, whether the\n * configured endpoint already carried `/openai`, whether the api-version is\n * dated and therefore routes to the older path, whether to send `authorization:\n * Bearer` or `api-key`, whether an Entra token has to be minted again because\n * the last one expired mid-conversation — is identical, and every line of it was\n * worked out by measuring a real resource rather than reading documentation (the\n * transcripts are on `azureBase` below).\n *\n * That is exactly the kind of knowledge that must not be copied. A second copy\n * in an image provider would be correct on the day it was written and would\n * drift on the first fix that only one of them got, and the symptom of the drift\n * is a 404 on every request for whichever apps configured the provider the\n * documented way — which is the bug `azureBase` exists because of.\n *\n * So a provider resolves a `ProviderTarget` and appends its own path. Nothing\n * here knows about Responses, files or images.\n */\n\nexport type ProviderConfig = {\n apiKey?: string;\n baseURL?: string;\n timeoutMs?: number;\n /**\n * The longest a streamed answer may go without sending anything (an event or\n * a keepalive) once its response has started. Every chunk resets it. When it\n * runs out the attempt is aborted with a retryable `ProviderTimeoutError`:\n * before the first content event it is asked again like any other dropped\n * stream, after it the call ends with an error. Default\n * `DEFAULT_STREAM_IDLE_TIMEOUT_MS` (120 s); `0` turns it off.\n */\n streamIdleTimeoutMs?: number;\n /**\n * The longest one attempt's stream may run, from its response headers to its\n * last event, however steadily it keeps sending (#1169). No chunk resets it.\n * When it runs out the attempt is aborted with a retryable `provider_error`.\n * Default `DEFAULT_STREAM_MAX_DURATION_MS` (300 s); `0` turns it off.\n */\n streamMaxDurationMs?: number;\n /**\n * The most argument text one tool call may stream without finishing (#1169),\n * in characters. Past it the attempt is aborted with a retryable\n * `provider_error`, as a runaway generation. Default `0`, off: how large a\n * legitimate call gets depends entirely on the app's tools.\n */\n maxToolArgumentChars?: number;\n maxRetries?: number;\n headers?: Record<string, string>;\n};\n\nexport type AzureConfig = ProviderConfig & {\n /**\n * The resource host, with or without a trailing `/openai`. Both spellings\n * work — `https://<resource>.cognitiveservices.azure.com` and\n * `https://<resource>.openai.azure.com` — and neither is rewritten, because\n * only one of them exists for a resource that was not created as\n * kind=OpenAI. See `azureBase` for what is done to it.\n */\n endpoint?: string;\n /**\n * Just the resource name, when there is no endpoint to hand. `<name>` is\n * expanded to `https://<name>.cognitiveservices.azure.com/openai`.\n */\n resourceName?: string;\n apiVersion?: string;\n /**\n * The deployment to call, when it is not named after the model. Azure lets\n * whoever ran the template call it anything, and plenty of them are called\n * `prod` — this is the override the class comment promises.\n */\n deployment?: string;\n /**\n * For Entra ID instead of a key. A function, not a token, because these\n * expire mid-conversation.\n */\n getToken?: () => Promise<string>;\n};\n\n/**\n * A resolved vendor, ready for a path to be appended.\n *\n * `base` and `query` are separate because Azure's api-version is a query\n * parameter and a caller appending `/images/generations` must not have to know\n * that it goes *before* the `?`. Every URL is `${base}${path}${query}`.\n */\nexport type ProviderTarget = {\n /** e.g. `https://api.openai.com/v1`, or `https://<host>/openai/v1`. */\n base: string;\n /** e.g. `` or `?api-version=preview`. Already encoded. */\n query: string;\n /** Called per request. See the Azure branch for why that is not an accident. */\n headers: () => Promise<Record<string, string>>;\n timeoutMs: number;\n /** See `ProviderConfig.streamIdleTimeoutMs`. `0` is off. */\n streamIdleTimeoutMs: number;\n /** See `ProviderConfig.streamMaxDurationMs`. `0` is off. */\n streamMaxDurationMs: number;\n /** See `ProviderConfig.maxToolArgumentChars`. `0` is off. */\n maxToolArgumentChars: number;\n maxRetries: number;\n};\n\n/** Long enough for a reasoning model to think before it says anything, short\n * enough that a hung connection is not mistaken for a slow one. For a streamed\n * call it only covers getting a response; the stream that follows is bounded\n * by `streamIdleTimeoutMs` instead. For a one-shot call it is the whole deadline — which is why the\n * images path sets its own, and why `retryTimeouts` exists. */\nexport const DEFAULT_TIMEOUT_MS = 120_000;\nexport const DEFAULT_MAX_RETRIES = 2;\n\n/**\n * How long a streamed answer may stay silent once it has started (#1167).\n *\n * `timeoutMs` stops at the response headers, and a Responses stream sends its\n * headers (and `response.created`) within a second or so, so before this\n * nothing bounded a stream that went quiet: a stalled step waited for the\n * run's `maxRunDurationMs`. Seen on an Azure deployment: completed steps took\n * 1–12 s with the first event after 1–5 s, and the one that stalled sent\n * nothing more for ten minutes.\n *\n * WHY NOT SHORTER. The cost of the two mistakes is not symmetric. Too long, and\n * a rare stall takes two minutes to notice instead of one. Too short, and a\n * reasoning model at a high effort, which can think for a long while between\n * two events, is cut off mid-thought on every hard request, retried (and billed)\n * up to `maxRetries` times, and fails anyway. So the default matches the\n * header timeout, which already had to be long enough for a model to think\n * before saying anything. An app on low effort can set it lower.\n */\nexport const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 120_000;\n\n/**\n * How long one attempt's stream may run in all, however steadily it sends\n * (#1169).\n *\n * `streamIdleTimeoutMs` cannot see a stream that keeps trickling: seen on an\n * Azure deployment, one function call whose argument deltas kept coming for\n * 500 s (1,228 deltas against 20–60 normally), each one resetting the idle\n * clock, until the run's `maxRunDurationMs` ended the whole run. Completed\n * calls of the same agent took 4 s at p50 and 43 s at most.\n *\n * WHY 300 S. The same asymmetry as the idle limit, sharper. A limit that cuts a\n * legitimate call does not just cost a retry: the retry is the same long call\n * and is cut again, so a request that used to work now always fails. Five\n * minutes leaves room for a reasoning model at a high effort that thinks for\n * minutes before writing, and for a long answer or a large tool call (about\n * 15–30k output tokens at common streaming rates). And it is half the default\n * `maxRunDurationMs` (ten minutes), so a run that hits a runaway early still\n * has the time to ask again and finish. An app whose calls are short (a low\n * reasoning effort, small tools) can set it much lower.\n */\nexport const DEFAULT_STREAM_MAX_DURATION_MS = 300_000;\n\nexport function env(name: string): string | undefined {\n return typeof process === \"undefined\" ? undefined : process.env?.[name];\n}\n\n/**\n * `preview` selects Azure's `/openai/v1` surface, which is the OpenAI-shaped\n * one — same request body, same SSE frames, same `model` field naming the\n * deployment — and it is the only surface the Responses API has that gemi's\n * request builder can talk to unchanged. It takes no dated version: sending\n * `api-version=2025-04-01-preview` to `/openai/v1/responses` answers\n * `400 {\"code\":\"BadRequest\",\"message\":\"API version not supported\"}`.\n *\n * A dated version is still honoured, and routes to the older\n * `/openai/responses` path instead — see `azurePath`. So an app that pinned\n * one keeps working, which is the promise the old comment here made and could\n * not keep once the paths diverged.\n */\nexport const AZURE_API_VERSION = \"preview\";\n\n/**\n * Where an Azure call goes, worked out live rather than from docs.\n *\n * THE PROBLEM THIS SOLVES. `AZURE_OPENAI_ENDPOINT` is conventionally written\n * with `/openai` already on the end, and the old code appended `/openai` again\n * and then a deployment path, producing\n * `…/openai/openai/deployments/<dep>/responses` — a 404 on every request, for\n * every app that configured the provider the documented way. Two separate\n * mistakes were stacked there, and only measuring told them apart.\n *\n * WHAT WAS MEASURED, against a real resource, POSTing a Responses body:\n *\n * 404 {endpoint}/openai/deployments/gpt-5.4/responses?api-version=2025-04-01-preview\n * 404 {host}/openai/deployments/gpt-5.4/responses?api-version=2025-04-01-preview\n * 404 {host}/openai/deployments/gpt-5.4/responses?api-version=preview\n * 400 {host}/openai/v1/responses?api-version=2025-04-01-preview (\"API version not supported\")\n * 200 {host}/openai/v1/responses?api-version=preview\n * 200 {host}/openai/v1/responses (no api-version at all)\n * 200 {host}/openai/responses?api-version=2025-04-01-preview\n *\n * for {host} in BOTH `https://<resource>.cognitiveservices.azure.com` and\n * `https://<resource>.openai.azure.com` — both spellings answered identically,\n * so the host was never the variable. The deployment-in-the-URL path is the\n * Chat Completions shape and the Responses API does not serve it at all; the\n * deployment goes in the body's `model`, which is what `buildResponsesRequest`\n * already puts there.\n *\n * `/openai/v1/files?api-version=preview` and\n * `/openai/files?api-version=2025-04-01-preview` were both checked too (200,\n * empty list), so uploads follow the same fork.\n *\n * And so do images, measured the same way against a `gpt-image-2` deployment:\n *\n * 200 {host}/openai/v1/images/generations?api-version=preview\n * 200 {host}/openai/v1/images/edits?api-version=preview\n *\n * which is the whole reason this function is shared rather than reimplemented.\n */\nexport function azureBase(raw: string): string {\n const trimmed = raw.trim().replace(/\\/+$/, \"\");\n if (!trimmed) return \"\";\n // A configured endpoint may or may not already carry `/openai`, and may even\n // carry `/openai/v1` if someone copied a full URL. Normalize down to the\n // resource base and put exactly one `/openai` back, rather than appending\n // blind — appending blind is the bug.\n const base = trimmed.replace(/\\/openai(?:\\/v1)?$/i, \"\");\n return `${base}/openai`;\n}\n\n/** Dated versions belong to the older path; `preview` (and anything that is not\n * a date) belongs to `/v1`. Both were verified above. */\nexport function azurePath(apiVersion: string): string {\n return /^\\d{4}-\\d{2}-\\d{2}/.test(apiVersion) ? \"\" : \"/v1\";\n}\n\n/** Overrides for a call whose deadline is not a streaming handshake's. */\nexport type TargetDefaults = { timeoutMs?: number };\n\nexport function openAITarget(\n config: ProviderConfig,\n defaults: TargetDefaults = {},\n): ProviderTarget {\n const base = (config.baseURL ?? env(\"OPENAI_BASE_URL\") ?? \"https://api.openai.com/v1\").replace(\n /\\/+$/,\n \"\",\n );\n\n return {\n base,\n query: \"\",\n headers: async () => {\n const apiKey = config.apiKey ?? env(\"OPENAI_API_KEY\");\n return {\n ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),\n ...config.headers,\n };\n },\n timeoutMs: config.timeoutMs ?? defaults.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n streamIdleTimeoutMs: config.streamIdleTimeoutMs ?? DEFAULT_STREAM_IDLE_TIMEOUT_MS,\n streamMaxDurationMs: config.streamMaxDurationMs ?? DEFAULT_STREAM_MAX_DURATION_MS,\n maxToolArgumentChars: config.maxToolArgumentChars ?? 0,\n maxRetries: config.maxRetries ?? DEFAULT_MAX_RETRIES,\n };\n}\n\n/**\n * The resource base, `<host>/openai`, from whichever of the three ways it was\n * configured. A bare resource name expands to the `cognitiveservices` host\n * rather than the `openai.azure.com` one: both answer for a resource created\n * as kind=OpenAI, only `cognitiveservices` answers for an AI Foundry or\n * multi-service resource, so it is the spelling that is right more often. An\n * app on the other one sets `endpoint` and nothing rewrites it.\n */\nexport function azureResourceBase(config: AzureConfig): string {\n const configured = config.baseURL ?? config.endpoint ?? env(\"AZURE_OPENAI_ENDPOINT\");\n if (configured) return azureBase(configured);\n const resource =\n config.resourceName ?? env(\"AZURE_OPENAI_RESOURCE_NAME\") ?? env(\"AZURE_RESOURCE_NAME\");\n return resource ? azureBase(`https://${resource.trim()}.cognitiveservices.azure.com`) : \"\";\n}\n\nexport function azureTarget(config: AzureConfig, defaults: TargetDefaults = {}): ProviderTarget {\n const apiVersion = config.apiVersion ?? env(\"AZURE_OPENAI_API_VERSION\") ?? AZURE_API_VERSION;\n\n return {\n base: `${azureResourceBase(config)}${azurePath(apiVersion)}`,\n query: `?api-version=${encodeURIComponent(apiVersion)}`,\n headers: async () => {\n // Called per request, not per provider: an Entra token minted when the\n // app booted is expired by the time a long conversation reaches step\n // nine, and that failure looks like a random 401 in the middle of a\n // working feature.\n if (config.getToken) {\n return { authorization: `Bearer ${await config.getToken()}`, ...config.headers };\n }\n const apiKey = config.apiKey ?? env(\"AZURE_OPENAI_API_KEY\");\n return { ...(apiKey ? { \"api-key\": apiKey } : {}), ...config.headers };\n },\n timeoutMs: config.timeoutMs ?? defaults.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n streamIdleTimeoutMs: config.streamIdleTimeoutMs ?? DEFAULT_STREAM_IDLE_TIMEOUT_MS,\n streamMaxDurationMs: config.streamMaxDurationMs ?? DEFAULT_STREAM_MAX_DURATION_MS,\n maxToolArgumentChars: config.maxToolArgumentChars ?? 0,\n maxRetries: config.maxRetries ?? DEFAULT_MAX_RETRIES,\n };\n}\n\n/**\n * The Messages API version sent as `anthropic-version`. `2026-10-21` is the\n * version the current SDKs send: on it `temperature`, `top_p` and `top_k` are a\n * 400 on every model, which is why `buildMessagesRequest` never sends them.\n */\nexport const ANTHROPIC_VERSION = \"2026-10-21\";\n\n/** `AnthropicProvider`'s config. */\nexport type AnthropicConfig = ProviderConfig & {\n /**\n * The workspace to bill and scope requests to, sent as\n * `anthropic-workspace-id` on every request (Messages and Files). Needed for\n * an API key that is not scoped to a workspace, which the API otherwise\n * answers with a 400. Else `ANTHROPIC_WORKSPACE_ID`; unset sends no header.\n */\n workspaceId?: string;\n};\n\n/**\n * Anthropic's API, `https://api.anthropic.com` unless `baseURL` (or\n * `ANTHROPIC_BASE_URL`) names a gateway in front of it. The base is the host,\n * as the SDKs take it; a trailing `/v1` is accepted too and not doubled.\n *\n * Authenticates with `x-api-key` (`apiKey`, else `ANTHROPIC_API_KEY`), or\n * with `ANTHROPIC_AUTH_TOKEN` as a bearer when there is no key (the SDKs'\n * order), read per request like the others. `workspaceId` (else\n * `ANTHROPIC_WORKSPACE_ID`) adds `anthropic-workspace-id`.\n */\nexport function anthropicTarget(config: AnthropicConfig, defaults: TargetDefaults = {}): ProviderTarget {\n const host = config.baseURL ?? env(\"ANTHROPIC_BASE_URL\") ?? \"https://api.anthropic.com\";\n return messagesTarget(host, config, defaults, async () => {\n const workspaceId = config.workspaceId ?? env(\"ANTHROPIC_WORKSPACE_ID\");\n const workspace = workspaceId ? { \"anthropic-workspace-id\": workspaceId } : {};\n const apiKey = config.apiKey ?? env(\"ANTHROPIC_API_KEY\");\n if (apiKey) return { \"x-api-key\": apiKey, ...workspace };\n const token = env(\"ANTHROPIC_AUTH_TOKEN\");\n return token ? { authorization: `Bearer ${token}`, ...workspace } : workspace;\n });\n}\n\n/** `AzureAnthropicProvider`'s config: the Azure OpenAI fields that apply. */\nexport type FoundryConfig = ProviderConfig & {\n /**\n * The resource's Anthropic base, `https://<resource>.services.ai.azure.com/anthropic`\n * (the deployment's Target URI without `/v1/messages`). `baseURL` works too.\n */\n endpoint?: string;\n /** Just the resource name; expanded to the base above. */\n resourceName?: string;\n /** The deployment to call, when it is not named after the model. */\n deployment?: string;\n /** For Entra ID instead of a key, called per request (tokens expire). */\n getToken?: () => Promise<string>;\n};\n\n/**\n * Claude on Azure AI Foundry: the same Messages API under the resource's\n * `/anthropic` path. The settings and their environment variables are the\n * ones Anthropic's Foundry SDK clients read: `endpoint`/`baseURL` or\n * `ANTHROPIC_FOUNDRY_BASE_URL`, else `resourceName` or\n * `ANTHROPIC_FOUNDRY_RESOURCE`; the key in `api-key` (`apiKey`, else\n * `ANTHROPIC_FOUNDRY_API_KEY`), or an Entra token from `getToken` as a bearer\n * (scope `https://ai.azure.com/.default`).\n */\nexport function foundryTarget(config: FoundryConfig, defaults: TargetDefaults = {}): ProviderTarget {\n const resource = config.resourceName ?? env(\"ANTHROPIC_FOUNDRY_RESOURCE\");\n const host =\n config.baseURL ??\n config.endpoint ??\n env(\"ANTHROPIC_FOUNDRY_BASE_URL\") ??\n (resource ? `https://${resource.trim()}.services.ai.azure.com/anthropic` : \"\");\n // Without one, every request would go to a relative `/v1/messages` and fail\n // as a network error that names nothing.\n if (!host.trim()) {\n throw new Error(\n \"AzureAnthropicProvider has no Foundry endpoint. Set `endpoint` (the deployment's Target URI without `/v1/messages`, e.g. `https://<resource>.services.ai.azure.com/anthropic`) or `resourceName`, or the ANTHROPIC_FOUNDRY_BASE_URL or ANTHROPIC_FOUNDRY_RESOURCE environment variable.\",\n );\n }\n return messagesTarget(host, config, defaults, async () => {\n if (config.getToken) return { authorization: `Bearer ${await config.getToken()}` };\n const apiKey = config.apiKey ?? env(\"ANTHROPIC_FOUNDRY_API_KEY\");\n return apiKey ? { \"api-key\": apiKey } : {};\n });\n}\n\n/** What Anthropic and Foundry share: `/v1` under the host, and the version. */\nfunction messagesTarget(\n host: string,\n config: ProviderConfig,\n defaults: TargetDefaults,\n auth: () => Promise<Record<string, string>>,\n): ProviderTarget {\n const base = host.trim().replace(/\\/+$/, \"\").replace(/\\/v1$/, \"\");\n return {\n base: `${base}/v1`,\n query: \"\",\n headers: async () => ({\n ...(await auth()),\n \"anthropic-version\": ANTHROPIC_VERSION,\n ...config.headers,\n }),\n timeoutMs: config.timeoutMs ?? defaults.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n streamIdleTimeoutMs: config.streamIdleTimeoutMs ?? DEFAULT_STREAM_IDLE_TIMEOUT_MS,\n streamMaxDurationMs: config.streamMaxDurationMs ?? DEFAULT_STREAM_MAX_DURATION_MS,\n maxToolArgumentChars: config.maxToolArgumentChars ?? 0,\n maxRetries: config.maxRetries ?? DEFAULT_MAX_RETRIES,\n };\n}\n\n/**\n * Azure's realtime surface, which is the GA `/openai/v1` one regardless of the\n * configured api-version.\n *\n * WHY NOT `azureTarget`. A dated api-version routes `azureTarget` to the older\n * `/openai/...` path (see `azurePath`), and that path has no `realtime/calls`:\n * the WebRTC \"unified interface\", the client secrets and the call's sideband\n * socket are documented on `/openai/v1/realtime/...` only, and the documented\n * URLs carry no `api-version` at all. An app that pinned a dated version for\n * its Responses calls must not lose voice for it, so this target ignores the\n * version and keeps everything else — the resource base and, above all, the\n * per-request credential — from the one place that resolves them.\n *\n * NOT YET MEASURED against a real Azure realtime deployment (there was none to\n * measure when this was written). The shape follows Azure's GA realtime\n * documentation; when a deployment exists, the transcripts belong here as they\n * do on `azureBase`.\n */\nexport function azureRealtimeTarget(\n config: AzureConfig,\n defaults: TargetDefaults = {},\n): ProviderTarget {\n const target = azureTarget(config, defaults);\n return { ...target, base: `${azureResourceBase(config)}/v1`, query: \"\" };\n}\n",
16
+ "import type { ReasoningEffort } from \"./Agent\";\nimport {\n responsesEndpoint,\n streamResponses,\n uploadFile,\n type ResponsesEndpoint,\n} from \"./providers/call\";\nimport {\n buildMessagesRequest,\n recoverableRequestError,\n THINKING_BINDING_BETA,\n withoutThinkingBlocks,\n type MessagesRequest,\n} from \"./providers/anthropicRequest\";\nimport { parseMessagesStream } from \"./providers/anthropicStream\";\nimport {\n capabilitiesForClaude,\n capabilitiesForModel,\n supportsForcedToolChoice,\n} from \"./providers/capabilities\";\nimport {\n anthropicTarget,\n azureRealtimeTarget,\n foundryTarget,\n type AnthropicConfig,\n type FoundryConfig,\n azureTarget,\n openAITarget,\n type AzureConfig,\n type ProviderConfig,\n type ProviderTarget,\n} from \"./providers/endpoints\";\nimport { normalizeProviderError } from \"./providers/errors\";\nimport { sentFiles } from \"./providers/fileRejection\";\nimport { RealtimeClient, DEFAULT_REALTIME_TIMEOUT_MS } from \"./providers/realtime\";\nimport { isContentEvent } from \"./runtime\";\nimport { buildResponsesRequest } from \"./providers/request\";\nimport type { JSONSchema } from \"./Schema\";\nimport type { AgentError, AgentMessage, FinishReason, Usage } from \"./types\";\n\n/**\n * A provider makes one model call. It does not run the tool loop.\n *\n * The split matters: approvals, `maxSteps`, deferred tools, skill loading and\n * persistence are all provider-independent, and putting them in the provider\n * would mean writing them again for the second provider. So the provider's\n * whole job is to translate gemi's messages into a request, and the response\n * stream back into `ProviderEvent`s. Everything above that lives in `Agent`.\n *\n * v1 targets OpenAI's Responses API — native reasoning items and strict\n * structured output without reassembling them by hand. The interface is kept\n * free of anything Responses-specific so a Chat Completions provider (for older\n * Azure deployments and OpenAI-compatible gateways) can be added later without\n * touching Agent, Controller or the client.\n */\n\n/** What a provider will actually honour, so `Agent` can drop the rest rather\n * than have a request rejected at runtime. */\nexport type ProviderCapabilities = {\n reasoning: boolean;\n structuredOutput: boolean;\n fileInput: boolean;\n parallelToolCalls: boolean;\n /**\n * Tool search, and with it deferred loading. Only recent models have it, so a\n * provider that answers `false` is sent every schema inline and the agent\n * runs identically — deferral is a token optimization, and an optimization\n * that changed behaviour when unavailable would not be one.\n */\n toolSearch: boolean;\n};\n\n/** A tool as the model is shown it: schema only, no implementation. */\nexport type ProviderToolSpec = {\n name: string;\n description: string;\n parameters: JSONSchema;\n strict: boolean;\n /** `defer_loading`: send the name and description, withhold the schema until\n * the model searches for it. Ignored when `capabilities.toolSearch` is\n * false. */\n deferred?: boolean;\n};\n\n/** Tools grouped for search. Flattened back to a list by a provider without\n * tool search, since the grouping exists to be searched. */\nexport type ProviderToolNamespace = {\n name: string;\n description: string;\n tools: ProviderToolSpec[];\n};\n\n/** See `ProviderStreamParams.toolChoice`. */\nexport type ProviderToolChoice = \"auto\" | \"required\" | \"none\" | { name: string };\n\nexport interface ProviderStreamParams {\n messages: AgentMessage[];\n systemPrompt?: string;\n tools?: (ProviderToolSpec | ProviderToolNamespace)[];\n /**\n * Whether the model must call a tool on this call (#1010): `\"auto\"` (it\n * chooses, the provider's default), `\"required\"` (some tool), `\"none\"` (no\n * tool, though `tools` is still sent so the prompt prefix stays the same),\n * or `{ name }` (that tool). Unset: the provider's default. Set by\n * `PrepareStepResult.toolChoice`.\n */\n toolChoice?: ProviderToolChoice;\n /**\n * Sent as `prompt_cache_key` (#1223): requests with the same key and prefix\n * share a prompt cache. Set by `Agent` from `promptCacheKey`.\n */\n promptCacheKey?: string;\n /** Set when the agent declares an `output` schema; the provider turns it into\n * whatever its own strict-JSON parameter is. `strict` comes from the schema —\n * false when it contains an `s.json()` node, which strict mode cannot\n * express — and is required rather than defaulted so that a new caller has to\n * answer it instead of inheriting a 400. */\n output?: { name: string; schema: JSONSchema; strict: boolean };\n /** Optional: silently dropped by a provider whose `capabilities.reasoning`\n * is false, since a model that cannot reason should not fail a request. */\n reasoning?: ReasoningEffort;\n temperature?: number;\n maxOutputTokens?: number;\n signal?: AbortSignal;\n}\n\n/**\n * The events of a single model call. Deliberately smaller than\n * `AgentStreamEvent`: no run, message, tool-result or approval events, because\n * a provider knows about none of those.\n */\nexport type ProviderEvent =\n | { type: \"text-delta\"; delta: string }\n /**\n * `providerMetadata` is what the provider needs to send the part back, kept\n * on `ReasoningPart.providerMetadata` (#477). Sent once, on the part's last\n * delta, which closes the part: the next reasoning delta starts a new one.\n */\n | {\n type: \"reasoning-delta\";\n delta: string;\n id?: string;\n providerMetadata?: Record<string, unknown>;\n }\n /** Arguments arrive as JSON fragments; the provider passes them through and\n * `Agent` assembles and validates against the tool's schema. */\n | {\n type: \"tool-call-delta\";\n toolCallId: string;\n name: string;\n argsDelta: string;\n namespace?: string;\n }\n /**\n * `name` IS FLAT AND STAYS FLAT. This was an open question and the API has\n * answered it: a call to a function that lives inside a namespace comes back\n * as `{name: \"getOrder\", namespace: \"crm\"}`, not as `\"crm.getOrder\"` —\n * recorded in `providers/__fixtures__/openai-tool-search.sse` and pinned by\n * a test that reads that file. So `name` is already the key `Agent`'s tool\n * registry is built on, which is what makes tool names having to be globally\n * unique within an agent (see `ToolNamespace`) the right rule rather than an\n * inconvenience.\n *\n * `namespace` is carried beside it, absent for a tool that was listed bare.\n * It is provenance, not identity: it says which group the model chose to\n * look in, which is worth recording next to the call and is worthless for\n * finding the tool. Folding it into `name` would make a name that is\n * sometimes qualified and sometimes not, and nothing could match on that.\n */\n | { type: \"tool-call\"; toolCallId: string; name: string; args: string; namespace?: string }\n /**\n * The provider is asking the model again, and the calls named here, which\n * only ever streamed `tool-call-delta` and never completed, are void (#1169).\n * A stream that broke (or was cut as a runaway) before anything but argument\n * deltas had been sent is retried like one that broke before its first\n * content event, and this is how the deltas already passed on are taken\n * back: `Agent` forgets the calls and tells the client to drop them, so the\n * retried answer does not sit beside a half-written call that will never\n * run. A provider that never retries after a delta need not send this.\n */\n | { type: \"tool-call-discard\"; toolCallIds: string[] }\n /**\n * The model went looking for a deferred tool and pulled its schema in. Worth\n * surfacing rather than swallowing: it is a step the user paid for, and the\n * pause before it is otherwise unexplained.\n *\n * TWO FIELDS, not one. `loaded` is the function names — `[\"listOrders\",\n * \"getOrder\"]` — and `namespaces` is the groups they came out of —\n * `[\"crm\"]`. Search results arrive as a tree of namespaces containing\n * functions, so a single flat list has to pick one level and throw the other\n * away, and both levels are worth saying: \"searched crm, loaded getOrder\"\n * reads better than either half, and the group is the thing the model\n * actually chose between.\n *\n * `namespaces` is required rather than optional because the parser always\n * knows the answer, and an optional field would let a future provider forget\n * to fill it in silently. Empty means the search returned bare functions.\n */\n /**\n * `arguments` is the query the model searched with, as the provider sent it\n * (`{paths: [\"crm\"]}` on the Responses API), when it said. Kept so the\n * search can be replayed on later requests (#776); see `ToolSearchRecord`.\n */\n | { type: \"tool-search\"; loaded: string[]; namespaces: string[]; arguments?: unknown }\n | { type: \"output-delta\"; delta: string }\n /**\n * `model` is the model the vendor says produced the response (`response.model`\n * on the Responses API), which is not always the one asked for: an Azure\n * deployment name answers with the model behind it, and an alias like\n * `gpt-5.4` with a dated snapshot. Absent when the vendor did not say — a\n * request that failed before any response, or a provider that does not know.\n * Optional so a custom provider need not fill it in (#741).\n */\n | { type: \"finish\"; reason: FinishReason; usage: Usage; model?: string }\n /**\n * `status` and `requestId` describe the HTTP response the error came from,\n * when there was one. They are for the server's record of the run\n * (`AgentRunResult.error`) and are never written to a client frame; leave\n * them out for an error that was not a response.\n */\n /**\n * The provider refused a stored file (`fileId` is the provider's id) and the\n * call was sent again with a note in the file's place, so the turn goes on.\n * `Agent` marks the stored `FilePart` `providerRejected`, which makes later\n * requests send the note instead of the id — otherwise the same refusal\n * costs a failed request on every turn of the thread (#684). `message` is\n * the provider's, for the log. A provider that never retries need not send\n * this; `Agent` treats its absence as nothing having been rejected.\n */\n | { type: \"file-rejected\"; fileId: string; message: string; status?: number; requestId?: string }\n /**\n * An attempt failed and the provider is about to ask again (#1192), sent\n * before the backoff wait, so it arrives while the call is still waiting\n * rather than after. Informational only: it is not content, it commits\n * nothing, and a consumer that ignores it loses nothing. See\n * `ProviderRetryInfo` for the fields. A provider that never retries need not\n * send it.\n */\n | ({ type: \"retry\" } & ProviderRetryInfo)\n | { type: \"error\"; error: AgentError; status?: number; requestId?: string };\n\n/**\n * One failed attempt of a provider call that is about to be asked again.\n *\n * - `attempt`: the attempt that failed, from 1. The next one is `attempt + 1`.\n * - `maxRetries`: the provider's `maxRetries`, so `attempt <= maxRetries`.\n * - `error`: the failure, normalized; `status` and `requestId` describe the\n * HTTP response it came from, when there was one.\n * - `phase`: `\"request\"` when no response arrived (or an error status did),\n * `\"stream\"` when the response started and its body broke before the first\n * content event.\n * - `timedOut`: the attempt was cut by `timeoutMs`, `streamIdleTimeoutMs` or\n * `streamMaxDurationMs`.\n * - `delayMs`: how long the provider waits before the next attempt.\n * - `elapsedMs`: since the call's first attempt started.\n */\nexport type ProviderRetryInfo = {\n attempt: number;\n maxRetries: number;\n error: AgentError;\n status?: number;\n requestId?: string;\n phase: \"request\" | \"stream\";\n timedOut: boolean;\n delayMs: number;\n elapsedMs: number;\n};\n\nexport type ProviderStream = AsyncIterable<ProviderEvent>;\n\n/**\n * Re-exported rather than declared here. What these configure is the *vendor*,\n * not the Responses API, and the images path resolves the same host, credential\n * and api-version from the same fields — see `providers/endpoints.ts` for why\n * that resolution lives in one place and what happens when it does not.\n */\nexport type { AnthropicConfig, AzureConfig, FoundryConfig, ProviderConfig } from \"./providers/endpoints\";\n\nexport abstract class AgentProvider {\n abstract readonly model: string;\n abstract readonly capabilities: ProviderCapabilities;\n\n /** The model ids this provider knows about — for autocomplete only; any\n * string is still accepted, because a new model must not require a gemi\n * release to use. */\n static models(): readonly string[] {\n return [];\n }\n\n abstract stream(params: ProviderStreamParams): ProviderStream;\n\n /**\n * Uploads a file and returns the id a `FilePart` carries. Message history\n * therefore holds provider file ids, which is the trade for getting vision\n * and PDF input without gemi owning a storage story in v1.\n */\n abstract upload(file: File): Promise<string>;\n\n /**\n * Maps a provider's error body onto the normalized codes, so an app can\n * branch on `rate_limited` without knowing whose rate limit it was.\n *\n * Shared rather than abstract-in-practice: Azure answers the same error\n * envelope as OpenAI, and the one place it differs — the content filter's\n * code, buried in `innererror` — is handled by reading both.\n */\n normalizeError(error: unknown): AgentError {\n return normalizeProviderError(error);\n }\n}\n\n/**\n * Autocomplete, not a gate. Every id here was confirmed present in\n * `GET https://api.openai.com/v1/models`; any other string is still accepted,\n * because a model released next Tuesday must not need a gemi release to use —\n * see `capabilitiesForModel` for what an unrecognized id is assumed to do.\n *\n * Ordered newest first, and deliberately short. `/v1/models` answers with\n * ninety-odd chat ids once the dated snapshots and the `-codex`, `-pro`,\n * `-chat-latest`, `-search-api` and `-nano` variants are counted; a list that\n * tried to be complete would be stale within the month and would bury the\n * handful of names anyone actually types. Snapshot-pinned ids\n * (`gpt-5.4-2026-03-05`) are left out for the same reason and work identically.\n *\n * The Azure provider returns this same list, which is a small lie it has always\n * told: a resource serves the deployments someone created, not the catalogue.\n * `AzureConfig.deployment` is the escape hatch, and an unrecognized deployment\n * name lands on the same capable default as an unrecognized model.\n */\nconst OPENAI_MODELS = [\n \"gpt-5.5\",\n \"gpt-5.4\",\n \"gpt-5.4-mini\",\n \"gpt-5.4-nano\",\n \"gpt-5.2\",\n \"gpt-5.1\",\n \"gpt-5\",\n \"gpt-5-mini\",\n \"gpt-5-nano\",\n \"gpt-4.1\",\n \"gpt-4.1-mini\",\n \"gpt-4.1-nano\",\n \"gpt-4o\",\n \"gpt-4o-mini\",\n \"o4-mini\",\n \"o3\",\n \"o3-mini\",\n] as const;\n\nexport class OpenAIProvider extends AgentProvider {\n readonly model: string;\n readonly capabilities: ProviderCapabilities;\n protected readonly config: ProviderConfig;\n\n constructor(model: string, config: ProviderConfig = {}) {\n super();\n this.model = model;\n this.capabilities = capabilitiesForModel(model);\n this.config = config;\n }\n\n /** Config defaults come from gemi's config (`ai.openai`), so an app that has\n * set `OPENAI_API_KEY` writes only the model name. */\n static model(model: string, config?: ProviderConfig): OpenAIProvider {\n return new OpenAIProvider(model, config);\n }\n\n static models(): readonly string[] {\n return OPENAI_MODELS;\n }\n\n stream(params: ProviderStreamParams): ProviderStream {\n const body = buildResponsesRequest(params, {\n model: this.model,\n capabilities: this.capabilities,\n });\n return streamResponses(this.endpoint(), body, {\n signal: params.signal,\n // The request carries the schema whenever the agent declared one, so the\n // parser has to read the answer as one too — a model that ignored the\n // parameter answers 400, not prose.\n structuredOutput: Boolean(params.output),\n files: sentFiles(params.messages),\n });\n }\n\n upload(file: File): Promise<string> {\n return uploadFile(this.endpoint(), file);\n }\n\n protected endpoint(): ResponsesEndpoint {\n return responsesEndpoint(openAITarget(this.config));\n }\n\n /**\n * Realtime (voice) calls on this provider's account: `createCall`,\n * `clientSecret`, `sideband` and `hangup`. The provider's model is the call's\n * default model, so build it with a realtime one\n * (`OpenAIProvider.model(\"gpt-realtime-mini\").realtime`). See\n * `providers/realtime.ts`.\n *\n * @experimental Not yet verified against a live call.\n */\n get realtime(): RealtimeClient {\n return new RealtimeClient(\n openAITarget(this.config, { timeoutMs: DEFAULT_REALTIME_TIMEOUT_MS }),\n { model: this.model },\n );\n }\n}\n\n/**\n * The current Claude models, newest family first. Autocomplete, not a gate,\n * like `OPENAI_MODELS`: any id is accepted, and `capabilitiesForClaude` says\n * what an unknown one is assumed to do.\n */\nconst CLAUDE_MODELS = [\n \"claude-opus-5-5\",\n \"claude-sonnet-5-5\",\n \"claude-haiku-5-5\",\n \"claude-fable-5-2\",\n \"claude-fable-5-1\",\n \"claude-opus-5\",\n \"claude-sonnet-5\",\n \"claude-fable-5\",\n \"claude-opus-4-8\",\n \"claude-sonnet-4-6\",\n \"claude-haiku-4-5\",\n] as const;\n\n/**\n * Claude on Anthropic's Messages API (`POST /v1/messages`), with an API key.\n *\n * The same request path as the OpenAI providers below the request body:\n * `streamResponses` does the retries, the stream limits and the holding back\n * until the first content event, and `parseMessagesStream` reads the stream.\n * `baseURL` (or `ANTHROPIC_BASE_URL`) points it at a gateway; see\n * `anthropicTarget`. `AzureAnthropicProvider` is the Azure AI Foundry\n * variant; Bedrock and Vertex are not covered.\n */\nexport class AnthropicProvider extends AgentProvider {\n readonly model: string;\n readonly capabilities: ProviderCapabilities;\n protected readonly config: AnthropicConfig;\n\n constructor(model: string, config: AnthropicConfig = {}) {\n super();\n this.model = model;\n this.capabilities = capabilitiesForClaude(model);\n this.config = config;\n }\n\n /**\n * `ANTHROPIC_API_KEY` (and `ANTHROPIC_WORKSPACE_ID`) from the environment\n * unless `config.apiKey` (`config.workspaceId`) is set.\n */\n static model(model: string, config?: AnthropicConfig): AnthropicProvider {\n return new AnthropicProvider(model, config);\n }\n\n static models(): readonly string[] {\n return CLAUDE_MODELS;\n }\n\n stream(params: ProviderStreamParams): ProviderStream {\n return this.send(params);\n }\n\n /**\n * One call, asked again at most once per kind of 400 that a changed request\n * answers (`recoverableRequestError`): a thinking block bound to another\n * conversation, with the thinking blocks stripped, and a schema too complex\n * to compile, with the answer asked for in the prompt. Only before anything\n * was yielded, which a 400 always is.\n */\n private async *send(params: ProviderStreamParams): ProviderStream {\n let request = params;\n let stripThinking = false;\n const tried = new Set<string>();\n for (;;) {\n let body = this.request(request);\n if (stripThinking) body = withoutThinkingBlocks(body);\n let recover: \"thinking\" | \"schema\" | undefined;\n let yielded = false;\n for await (const event of streamResponses(this.endpointFor(body), body, {\n signal: params.signal,\n structuredOutput: Boolean(params.output),\n parse: parseMessagesStream,\n })) {\n if (recover) continue;\n if (!yielded && event.type === \"error\" && event.status === 400) {\n const kind = recoverableRequestError(event.error.message);\n if (kind && !tried.has(kind)) {\n tried.add(kind);\n recover = kind;\n continue;\n }\n }\n if (isContentEvent(event)) yielded = true;\n yield event;\n }\n if (!recover) return;\n if (recover === \"thinking\") stripThinking = true;\n else if (request.output) request = { ...request, output: { ...request.output, strict: false } };\n }\n }\n\n private request(params: ProviderStreamParams): MessagesRequest {\n return buildMessagesRequest(params, {\n model: this.deployment(),\n modelId: this.model,\n capabilities: this.capabilities,\n forcedToolChoice: supportsForcedToolChoice(this.model),\n blockBinding: this.bindsThinking(),\n });\n }\n\n /** The beta header goes with the body that needs it. */\n private endpointFor(body: MessagesRequest): ResponsesEndpoint {\n const endpoint = this.endpoint();\n const binding = body.thinking?.type === \"adaptive\" && body.thinking.block_binding;\n if (!binding) return endpoint;\n return {\n ...endpoint,\n headers: async () => {\n const headers = await endpoint.headers();\n const beta = headers[\"anthropic-beta\"];\n return { ...headers, \"anthropic-beta\": beta ? `${beta},${THINKING_BINDING_BETA}` : THINKING_BINDING_BETA };\n },\n };\n }\n\n /** Whether `thinking.block_binding` and its beta header can be sent. */\n protected bindsThinking(): boolean {\n return true;\n }\n\n /** The `model` the request names. */\n protected deployment(): string {\n return this.model;\n }\n\n /** Through the Files API (`POST /v1/files`), which takes no `purpose`. */\n upload(file: File): Promise<string> {\n return uploadFile(this.endpoint(), file, null);\n }\n\n protected endpoint(): ResponsesEndpoint {\n return messagesEndpoint(anthropicTarget(this.config));\n }\n}\n\nfunction messagesEndpoint(target: ProviderTarget): ResponsesEndpoint {\n return { ...responsesEndpoint(target), responsesUrl: `${target.base}/messages` };\n}\n\n/**\n * Claude on Azure AI Foundry, which serves the same Messages API under the\n * resource's `/anthropic` path, so this is `AnthropicProvider` with another\n * endpoint and auth (see `foundryTarget`) and, as with `AzureOpenAIProvider`,\n * a deployment name that can differ from the model id. Capabilities are read\n * off the model, as there.\n *\n * NO FILES. The Files API is a 400 on deployments hosted on Azure (the\n * default hosting) and a beta on the ones hosted on Anthropic, so\n * `fileInput` is false and `upload()` refuses: a file a user attaches is\n * stored by gemi and named to the model by its attachment id, for a tool to\n * read. Everything else the agent uses (streaming, tools, thinking, structured\n * output, prompt caching) is supported on both hostings. Thinking is not\n * bound (`bindsThinking`).\n */\nexport class AzureAnthropicProvider extends AnthropicProvider {\n declare readonly capabilities: ProviderCapabilities;\n protected declare readonly config: FoundryConfig;\n\n constructor(model: string, config: FoundryConfig = {}) {\n super(model, config);\n this.capabilities = { ...capabilitiesForClaude(model), fileInput: false };\n }\n\n /** `ANTHROPIC_FOUNDRY_*` from the environment for what `config` leaves out. */\n static override model(model: string, config?: FoundryConfig): AzureAnthropicProvider {\n return new AzureAnthropicProvider(model, config);\n }\n\n override upload(_file: File): Promise<string> {\n return Promise.reject(\n new Error(\n \"AzureAnthropicProvider does not upload files: the Files API is not available on Azure-hosted Foundry deployments. The file is still stored by gemi and named to the model by its attachment id.\",\n ),\n );\n }\n\n protected override deployment(): string {\n return this.config.deployment ?? this.model;\n }\n\n /**\n * Thinking block-binding controls are unconfirmed on Foundry, and sending\n * the field where the beta is not taken is a 400 on every request. Without\n * it, a thinking block invalidated by an edit to the history is handled by\n * stripping the blocks and asking once more (see `AnthropicProvider.send`).\n */\n protected override bindsThinking(): boolean {\n return false;\n }\n\n protected override endpoint(): ResponsesEndpoint {\n return messagesEndpoint(foundryTarget(this.config));\n }\n}\n\n/**\n * Its own class rather than a flag on `OpenAIProvider`: Azure names the\n * deployment rather than the model, pins an api-version, authenticates with an\n * `api-key` header or an Entra token, and puts the resource in the host. One\n * class carrying both shapes means every field is conditionally meaningful.\n *\n * (It used to put the deployment in the URL as well. It does not: the Responses\n * API serves no such path — see `azureBase` for the measurements.)\n *\n * The API stays symmetrical — `.model()`, not `.deployment()`. Apps name a\n * model; mapping that onto a deployment is this class's problem, and an app\n * that named its deployment differently overrides it in config.\n */\nexport class AzureOpenAIProvider extends AgentProvider {\n readonly model: string;\n readonly capabilities: ProviderCapabilities;\n protected readonly config: AzureConfig;\n\n constructor(model: string, config: AzureConfig = {}) {\n super();\n this.model = model;\n // Read off the model, not the deployment: a deployment called `prod` says\n // nothing, and an unrecognized name lands on the all-capabilities default\n // anyway. See `capabilitiesForModel`.\n this.capabilities = capabilitiesForModel(model);\n this.config = config;\n }\n\n /** Defaults from gemi's config (`ai.azure`). */\n static model(model: string, config?: AzureConfig): AzureOpenAIProvider {\n return new AzureOpenAIProvider(model, config);\n }\n\n static models(): readonly string[] {\n return OPENAI_MODELS;\n }\n\n stream(params: ProviderStreamParams): ProviderStream {\n const body = buildResponsesRequest(params, {\n model: this.deployment(),\n capabilities: this.capabilities,\n });\n return streamResponses(this.endpoint(), body, {\n signal: params.signal,\n // The request carries the schema whenever the agent declared one, so the\n // parser has to read the answer as one too — a model that ignored the\n // parameter answers 400, not prose.\n structuredOutput: Boolean(params.output),\n files: sentFiles(params.messages),\n });\n }\n\n /** `assistants`, not OpenAI's `user_data`: Azure's Responses API refuses a\n * `user_data` id outright (#682). See `UploadPurpose`. */\n upload(file: File): Promise<string> {\n return uploadFile(this.endpoint(), file, \"assistants\");\n }\n\n protected deployment(): string {\n return this.config.deployment ?? this.model;\n }\n\n protected endpoint(): ResponsesEndpoint {\n return responsesEndpoint(azureTarget(this.config));\n }\n\n /**\n * Realtime (voice) calls on this Azure resource, on its GA\n * `/openai/v1/realtime` surface whatever `apiVersion` says (see\n * `azureRealtimeTarget`). The deployment is the call's default model, as it\n * is a text call's.\n *\n * Calls use Azure's documented server-proxied flow by default: a client\n * secret minted with the resource's credential, then the raw SDP posted with\n * that secret (`callFlow: \"ephemeral\"`), all server-side. Pass\n * `createCall({ flow: \"unified\" })` to try the multipart shape instead.\n *\n * @experimental Not yet verified against a live Azure call.\n */\n get realtime(): RealtimeClient {\n return new RealtimeClient(\n azureRealtimeTarget(this.config, { timeoutMs: DEFAULT_REALTIME_TIMEOUT_MS }),\n { model: this.deployment(), callFlow: \"ephemeral\" },\n );\n }\n}\n"
17
+ ],
18
+ "mappings": ";qKAmEA,FAAM,GAAgB,IACT,GAAe,MAYrB,SAAS,EAAe,CAAC,EAAkC,EAAiC,CACjG,GAAI,CAAC,EAAO,OACZ,IAAM,EAAU,EAAM,KAAK,EAC3B,GAAI,gBAAgB,KAAK,CAAO,EAAG,OAAO,KAAK,IAAI,EAAG,OAAO,CAAO,EAAI,IAAI,EAC5E,IAAM,EAAO,KAAK,MAAM,CAAO,EAC/B,GAAI,OAAO,MAAM,CAAI,EAAG,OACxB,OAAO,KAAK,IAAI,EAAG,EAAO,CAAG,EAQxB,SAAS,CAAc,CAAC,EAAiB,EAA8B,CAC5E,IAAM,EAAU,KAAK,IAAI,GAAc,GAAgB,GAAK,CAAO,EACnE,OAAO,KAAK,MAAM,GAAW,IAAM,EAAO,EAAI,IAAI,EAGpD,SAAS,EAAiB,CAAC,EAAyB,CAIlD,OAAO,IAAW,KAAO,IAAW,KAAO,IAAW,KAAO,GAAU,IAi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