@bkm016/basalt 0.1.5 → 0.1.7

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 (202) hide show
  1. package/README.md +12 -10
  2. package/{chunk-gw05p4g3.js → chunk-053vb71h.js} +1 -1
  3. package/{chunk-3c330qna.js → chunk-063vbmtp.js} +2 -2
  4. package/{chunk-bgkegf0k.js → chunk-0javrjcm.js} +4 -4
  5. package/{chunk-pjr91g6k.js → chunk-10p3mb40.js} +1 -1
  6. package/{chunk-mkp28k1x.js → chunk-39vwrg8n.js} +2 -2
  7. package/{chunk-dddsrff6.js → chunk-654cny9a.js} +123 -121
  8. package/{chunk-8xb636vr.js → chunk-6kdgk70p.js} +2 -2
  9. package/{chunk-9z7sdh5e.js → chunk-6ptv4g5e.js} +1 -1
  10. package/{chunk-zzwjt7fp.js → chunk-75434aay.js} +1 -1
  11. package/{chunk-ar3dbfp9.js → chunk-7hr6zw2m.js} +1 -1
  12. package/{chunk-h1rypb99.js → chunk-8gw5bvh3.js} +4 -4
  13. package/{chunk-a4b75ekk.js → chunk-8saewt61.js} +2 -2
  14. package/{chunk-sqaam5ak.js → chunk-8wj32837.js} +1 -1
  15. package/{chunk-539ekagy.js → chunk-8wv5t0w6.js} +5 -5
  16. package/{chunk-aw65h276.js → chunk-8x21n7y9.js} +1 -1
  17. package/{chunk-0n99m9m4.js → chunk-a0c989ky.js} +1 -1
  18. package/{chunk-srjgvdvs.js → chunk-a5apjjcn.js} +6 -6
  19. package/chunk-a81p46j7.js +2 -0
  20. package/chunk-agsfy9w7.js +2 -0
  21. package/{chunk-2qcpq99g.js → chunk-arcqjt91.js} +1 -1
  22. package/{chunk-rxj6tct8.js → chunk-bdy4jksd.js} +1 -1
  23. package/{chunk-zrkh5dw7.js → chunk-benrzwea.js} +1 -1
  24. package/chunk-bpw6q7g0.js +3 -0
  25. package/{chunk-36cqq0ga.js → chunk-c7rcw9fb.js} +5 -5
  26. package/{chunk-x89em726.js → chunk-ca982n62.js} +1 -1
  27. package/chunk-d20p02ny.js +2 -0
  28. package/{chunk-5v4g21rw.js → chunk-d6p2hgxh.js} +1 -1
  29. package/{chunk-t7sc0wwc.js → chunk-dnx91jrd.js} +2 -2
  30. package/{chunk-mat08ab1.js → chunk-dpz4hwqb.js} +2 -2
  31. package/{chunk-zn0g0859.js → chunk-ebpyvs1d.js} +2 -2
  32. package/{chunk-00gwse5r.js → chunk-ecf896fz.js} +1 -1
  33. package/{chunk-0stvywr8.js → chunk-ejsneb6f.js} +1 -1
  34. package/{chunk-7as47pcw.js → chunk-ey15ye2h.js} +1 -1
  35. package/{chunk-v4k3qmdm.js → chunk-f156y565.js} +1 -1
  36. package/{chunk-7tgqhveh.js → chunk-f544p9rh.js} +1 -1
  37. package/chunk-fmq3zwzk.js +2 -0
  38. package/{chunk-ebzkckyw.js → chunk-fx7f4m3c.js} +1 -1
  39. package/{chunk-3k7ejpkc.js → chunk-g0t9c3gv.js} +1 -1
  40. package/{chunk-7w0mefgk.js → chunk-gv7wqkey.js} +2 -2
  41. package/{chunk-1xa7d5mh.js → chunk-j7yvh0ae.js} +1 -1
  42. package/{chunk-0j0qggej.js → chunk-n85qs7cs.js} +1 -1
  43. package/{chunk-7qq99360.js → chunk-n981vx1t.js} +4 -4
  44. package/{chunk-0fwdxd45.js → chunk-peja51xv.js} +1 -1
  45. package/{chunk-6dsq0fns.js → chunk-pg5nkf1y.js} +1 -1
  46. package/{chunk-jyrwk08p.js → chunk-prgm07j4.js} +1 -1
  47. package/{chunk-jvwg4rn1.js → chunk-q9dd6fhj.js} +4 -4
  48. package/{chunk-nxkmd29x.js → chunk-r8vvcp6c.js} +1 -1
  49. package/{chunk-stj493dn.js → chunk-r9aatvwm.js} +2 -2
  50. package/chunk-rfb85nj7.js +2 -0
  51. package/{chunk-980drajf.js → chunk-rfdt992v.js} +12 -12
  52. package/{chunk-e63c1186.js → chunk-s6dejhfj.js} +1 -1
  53. package/{chunk-wfyrfvfn.js → chunk-s7skpgm2.js} +1 -1
  54. package/{chunk-2nkfxhef.js → chunk-sjjtxpg2.js} +247 -230
  55. package/{chunk-r0jc8e7t.js → chunk-w67dvqtb.js} +2 -2
  56. package/{chunk-b9fqretv.js → chunk-whj87h4r.js} +2 -2
  57. package/{chunk-vt1anydc.js → chunk-y8dkfpmj.js} +3 -3
  58. package/{chunk-nx3jnbv8.js → chunk-z02sj1je.js} +2 -2
  59. package/{chunk-hq5ke1yp.js → chunk-zxkq9m8e.js} +1 -1
  60. package/compiled.js +3 -3
  61. package/package.json +1 -1
  62. package/ui-test-worker.js +27 -27
  63. package/web/{chunk-7znyd1mj.js → chunk-079091ar.js} +1 -1
  64. package/web/{chunk-65nwc4cf.js → chunk-083r4f80.js} +1 -1
  65. package/web/{chunk-h2ag4kvz.js → chunk-0cng7r2x.js} +1 -1
  66. package/web/chunk-0k0ande6.js +1 -0
  67. package/web/{chunk-14bad871.js → chunk-14deqqhr.js} +1 -1
  68. package/web/{chunk-pyg1mr80.js → chunk-1s53190z.js} +20 -20
  69. package/web/{chunk-1pasbxwh.js → chunk-2b63adsj.js} +1 -1
  70. package/web/{chunk-zc1mk10n.js → chunk-2cem4sv7.js} +2 -2
  71. package/web/{chunk-y7jq61nv.js → chunk-30b33r2w.js} +2 -2
  72. package/web/{chunk-xsrvw7dt.js → chunk-3baypnwn.js} +3 -3
  73. package/web/{chunk-s24qs1bn.js → chunk-4067nwjp.js} +6 -6
  74. package/web/{chunk-paywgcf7.js → chunk-4fm55fgb.js} +2 -2
  75. package/web/{chunk-yvgs6bm3.js → chunk-4q7wf0wd.js} +1 -1
  76. package/web/{chunk-g5jxwkdh.js → chunk-4sve9xrj.js} +1 -1
  77. package/web/{chunk-56krfj3b.js → chunk-4vjnrz87.js} +1 -1
  78. package/web/chunk-59678wmg.js +1 -0
  79. package/web/chunk-5k8sv4f5.js +1 -0
  80. package/web/{chunk-tcp77cp2.js → chunk-5vjhvw1m.js} +1 -1
  81. package/web/{chunk-f9k3xrwb.js → chunk-5wbnjjhg.js} +1 -1
  82. package/web/chunk-6ft5pz3c.js +1 -0
  83. package/web/chunk-7c8rwqtx.js +1 -0
  84. package/web/chunk-7qzz025k.js +1 -0
  85. package/web/chunk-7xbaqqd7.css +1 -0
  86. package/web/chunk-80eyv2mk.js +1 -0
  87. package/web/chunk-89paytbk.js +4 -0
  88. package/web/chunk-8ceej2g7.js +1 -0
  89. package/web/chunk-8nyhy122.js +1 -0
  90. package/web/{chunk-01hcjafh.js → chunk-989jq2h8.js} +1 -1
  91. package/web/{chunk-bnb9xhgw.js → chunk-aangfjqc.js} +6 -6
  92. package/web/{chunk-1cfh0e2e.js → chunk-bdydzbqk.js} +7 -7
  93. package/web/chunk-cpwtt6ny.js +1 -0
  94. package/web/{chunk-dzg1pv80.js → chunk-czjk218p.js} +3 -3
  95. package/web/{chunk-m8knte9z.js → chunk-dg3p8db5.js} +1 -1
  96. package/web/chunk-dsw5t58p.js +1 -0
  97. package/web/{chunk-j34q5jn6.js → chunk-dv72fat3.js} +1 -1
  98. package/web/{chunk-affear07.js → chunk-dvvs1jjq.js} +1 -1
  99. package/web/{chunk-g9sqbafw.js → chunk-e131rg6p.js} +1 -1
  100. package/web/{chunk-4m3zdd41.js → chunk-e8yj05t1.js} +1 -1
  101. package/web/chunk-ekw54h1q.js +1 -0
  102. package/web/{chunk-0k9aec1s.js → chunk-femhej5w.js} +3 -3
  103. package/web/chunk-fmthkpff.js +1 -0
  104. package/web/{chunk-d60dpf69.js → chunk-geh05ghh.js} +1 -1
  105. package/web/{chunk-892nf39p.js → chunk-gksf7cek.js} +7 -7
  106. package/web/{chunk-abhad4zj.js → chunk-ht4mx2dt.js} +4 -4
  107. package/web/chunk-hwsvhst3.js +1 -0
  108. package/web/{chunk-d6ddkh6e.js → chunk-k02b36g1.js} +1 -1
  109. package/web/{chunk-2nht58dc.js → chunk-kjacapzd.js} +1 -1
  110. package/web/{chunk-zz397b0v.js → chunk-kkfrs7d1.js} +1 -1
  111. package/web/{chunk-aqt7kc3s.js → chunk-kkyn8yhj.js} +1 -1
  112. package/web/chunk-mh4rx5cf.js +1 -0
  113. package/web/{chunk-4a4j030b.js → chunk-n448vaba.js} +1 -1
  114. package/web/{chunk-k67v6dyg.js → chunk-n754s8xd.js} +2 -2
  115. package/web/chunk-n8j88qxy.js +1 -0
  116. package/web/{chunk-kza0t0gj.js → chunk-nfvqjzz5.js} +1 -1
  117. package/web/chunk-nmpbsvwb.js +2 -0
  118. package/web/chunk-nws1s56b.js +1 -0
  119. package/web/{chunk-12z7d0hp.js → chunk-p7126wwy.js} +2 -2
  120. package/web/chunk-phnqnhj9.js +1 -0
  121. package/web/{chunk-5shygfgb.js → chunk-pjz30xcp.js} +2 -2
  122. package/web/{chunk-vhzys0rr.js → chunk-q3jevm51.js} +1 -1
  123. package/web/{chunk-advfpyb9.js → chunk-q97hn4j5.js} +4 -4
  124. package/web/chunk-qg31p6cn.js +1 -0
  125. package/web/{chunk-jcdw85mv.js → chunk-qhm3cfq9.js} +1 -1
  126. package/web/chunk-qsd595b9.js +1 -0
  127. package/web/{chunk-9xgspn75.js → chunk-r7frwjqx.js} +2 -2
  128. package/web/chunk-rddft5ce.js +1139 -0
  129. package/web/{chunk-x7sb3bwf.js → chunk-rgbdf2m9.js} +22 -22
  130. package/web/{chunk-fnnrrzqa.js → chunk-rsbkbg6x.js} +1 -1
  131. package/web/chunk-s2bs5vxh.js +2 -0
  132. package/web/{chunk-sd22cnjy.js → chunk-sgwccs54.js} +1 -1
  133. package/web/{chunk-c53xmf48.js → chunk-sjh8gtm9.js} +1 -1
  134. package/web/{chunk-zqht0jzx.js → chunk-sn3tkwme.js} +1 -1
  135. package/web/{chunk-gcv91974.js → chunk-svh4n157.js} +1 -1
  136. package/web/{chunk-7a3c137d.js → chunk-sy7e4dmq.js} +1 -1
  137. package/web/{chunk-vttgyb5v.js → chunk-t3658ehb.js} +1 -1
  138. package/web/{chunk-h6gh63xj.js → chunk-t6sq85s6.js} +1 -1
  139. package/web/{chunk-z4aj066q.js → chunk-t81p4wqc.js} +1 -1
  140. package/web/{chunk-qq5gh5zr.js → chunk-tewmsd7t.js} +1 -1
  141. package/web/chunk-tf57s7ry.js +1 -0
  142. package/web/{chunk-gxqaa4sv.js → chunk-tfn0rqg9.js} +5 -5
  143. package/web/{chunk-0qr891eq.js → chunk-tmndcktk.js} +1 -1
  144. package/web/chunk-tqr80b5w.js +2 -0
  145. package/web/{chunk-mnzramhc.js → chunk-twdy2f67.js} +1 -1
  146. package/web/chunk-tz4twwmw.js +2 -0
  147. package/web/{chunk-crzseqbx.js → chunk-v282r683.js} +1 -1
  148. package/web/chunk-v4vjjtn7.js +1 -0
  149. package/web/chunk-vbwdwcdp.js +1 -0
  150. package/web/{chunk-6enn8p66.js → chunk-vjngfh0q.js} +1 -1
  151. package/web/{chunk-g8kkc6vz.js → chunk-wbgkwxrc.js} +1 -1
  152. package/web/{chunk-ybw6vgf6.js → chunk-wjbk50hn.js} +1 -1
  153. package/web/chunk-wjy848e2.js +1 -0
  154. package/web/{chunk-3hkgdw6f.js → chunk-wqsczy57.js} +3 -3
  155. package/web/chunk-wvfmmw1v.js +8 -0
  156. package/web/chunk-x1jm4zsg.js +1 -0
  157. package/web/{chunk-26bwh1sb.js → chunk-xbpc6x9m.js} +6 -6
  158. package/web/{chunk-xk1t58c4.js → chunk-xckxtfp8.js} +4 -4
  159. package/web/{chunk-qrdh9j62.js → chunk-xmsb2g71.js} +1 -1
  160. package/web/{chunk-ka7c5rhx.js → chunk-y99ed8rd.js} +6 -6
  161. package/web/{chunk-0p1nmj5n.js → chunk-z1geewdf.js} +1 -1
  162. package/web/index.html +1 -1
  163. package/worker.js +1 -1
  164. package/chunk-2nb3d92s.js +0 -2
  165. package/chunk-2pa1z37c.js +0 -2
  166. package/chunk-4g5f43ea.js +0 -3
  167. package/chunk-eegztdzb.js +0 -2
  168. package/chunk-wd3z74av.js +0 -2
  169. package/chunk-yna8bwqc.js +0 -2
  170. package/web/chunk-0ytga215.js +0 -1
  171. package/web/chunk-1amzv4ha.js +0 -1
  172. package/web/chunk-1s2hp6h1.js +0 -1
  173. package/web/chunk-2y0rc1fe.js +0 -1
  174. package/web/chunk-4w298aqs.js +0 -1
  175. package/web/chunk-6stt9d18.js +0 -1
  176. package/web/chunk-7e47b1sn.js +0 -1
  177. package/web/chunk-7pypx5h8.js +0 -2
  178. package/web/chunk-9dy7z3ej.js +0 -2
  179. package/web/chunk-9mq2cdtq.js +0 -1
  180. package/web/chunk-b5hah4mf.js +0 -1
  181. package/web/chunk-b8tfetd8.js +0 -1
  182. package/web/chunk-ckgpy4r4.js +0 -1
  183. package/web/chunk-dbnrfxt1.js +0 -8
  184. package/web/chunk-ddxf8e84.js +0 -1
  185. package/web/chunk-e8h45nyr.js +0 -1
  186. package/web/chunk-ej9vb61c.js +0 -1
  187. package/web/chunk-fjag6yg8.js +0 -2
  188. package/web/chunk-gxsb5tx3.js +0 -1
  189. package/web/chunk-jg6fmz2d.js +0 -1
  190. package/web/chunk-mpfgr049.js +0 -1
  191. package/web/chunk-mz1dabxh.js +0 -1
  192. package/web/chunk-p53n0hwr.js +0 -1
  193. package/web/chunk-pfcnr9tw.js +0 -1
  194. package/web/chunk-q7xkscc5.js +0 -1
  195. package/web/chunk-qmbgb79a.js +0 -1139
  196. package/web/chunk-sfq6cw45.js +0 -2
  197. package/web/chunk-svqj4az8.js +0 -1
  198. package/web/chunk-t7jwyvvr.js +0 -1
  199. package/web/chunk-tf18d2dk.css +0 -1
  200. package/web/chunk-v0g4cqc1.js +0 -4
  201. package/web/chunk-vqfz99ff.js +0 -1
  202. package/web/chunk-zazs8p6c.js +0 -1
@@ -18,7 +18,7 @@ ${a.map((y)=>y.error).join(`
18
18
  ${u}
19
19
  ${w}`)}return u},d=Qf(Ku);class Hr extends p{list(e,t={},n){return this._client.getAPIList(d`/chat/completions/${e}/messages`,O,{query:t,...n,__security:{bearerAuth:!0}})}}function at(e){return e!==void 0&&"function"in e&&e.function!==void 0}function ep(e){return e?.$brand==="auto-parseable-response-format"}function ct(e){return ep(e)||e?.type==="json_schema"}function Pt(e,t){if(!ct(e))return null;if(typeof e==="object"&&e!==null&&"$parseRaw"in e&&typeof e.$parseRaw==="function")return e.$parseRaw(t);try{return JSON.parse(t)}catch(n){if(n instanceof SyntaxError)throw SyntaxError("Error reading response: invalid structured output JSON.");throw n}}function Qe(e){return e?.$brand==="auto-parseable-tool"}function zu(e,t){if(!t||!Ta(t))return{...e,choices:e.choices.map((n)=>({...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))};return Zn(e,t)}function Zn(e,t){let n=e.choices.map((s)=>{if(s.finish_reason==="length")throw new tr;if(s.finish_reason==="content_filter")throw new rr;return{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map((o)=>rp(t,o))??void 0}:void 0,parsed:s.message.content!==null&&s.message.content!==void 0&&!s.message.refusal&&(s.message.content!==""||!s.message.tool_calls?.length&&!s.message.function_call)?tp(t,s.message.content):null}}});return{...e,choices:n}}function tp(e,t){return Pt(e.response_format,t)}function rp(e,t){if(t.type==="custom")return t;if(t.type!=="function"){let o=t.type;throw new m(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${o}\``)}let n=e.tools?.find((o)=>at(o)&&o.function?.name===t.function.name),s=null;if(Qe(n))s=n.$parseRaw(t.function.arguments);else if(n?.function.strict)s=Pt({type:"json_schema",$parseRaw:void 0},t.function.arguments);return{...t,function:{...t.function,parsed_arguments:s}}}function _i(e,t){if(!e||!("tools"in e)||!e.tools||t.type!=="function")return!1;let n=e.tools?.find((s)=>at(s)&&s.function?.name===t.function?.name);return at(n)&&(Qe(n)||n?.function.strict||!1)}function Ta(e){if(ct(e.response_format))return!0;return e.tools?.some((t)=>Qe(t)||t.type==="function"&&t.function.strict===!0)??!1}function Xu(e){for(let t of e??[]){if(t.type==="custom")continue;if(t.type!=="function"){let n=t.type;throw new m(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${n}\``)}if(t.function.strict!==!0)throw new m(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var It=(e)=>e?.role==="assistant",es=(e)=>e?.role==="tool";var Te,bi,wi,os,rs,Ai,is,qe,as,cs,ns,Jr,Tt,lr,Ii,xi,Vr,dr,Da,Zu,Na,el,Fa,Pi,tl,Hu=4096,ss=8388608,np=4096,us=256,{stringify:sp,parse:op}=JSON,$a=new WeakSet,ip=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"buffer")?.get,ap=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"length")?.get,cp=Object.getOwnPropertyDescriptor(DataView.prototype,"buffer")?.get,Ju=Object.getOwnPropertyDescriptor(Symbol.prototype,"description")?.get,up=Date.prototype.getTime,lp=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get,dp=typeof SharedArrayBuffer==="function"?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength")?.get:void 0,ts=Object.getOwnPropertyDescriptor(Error("native stack descriptor"),"stack"),ut=Function.prototype.toString,fp=Object.prototype.toString,yi=Object.getOwnPropertyDescriptor(Error,"isError"),Vu=yi&&"value"in yi&&typeof yi.value==="function"?yi.value:void 0,pp=ut.call(Error),hp=ut.call(Date),mp=ut.call(Function),Si=new Set([Ge.prototype,le.prototype,H.prototype,m.prototype,Z.prototype,Jt.prototype,mt.prototype,Yt.prototype,rr.prototype,er.prototype,Be.prototype,tr.prototype,Gt.prototype,Ye.prototype,Vt.prototype,Zt.prototype,Nr.prototype,Qt.prototype]),rl=new Set,nl=new Map,Gu=new WeakMap;function _p(){if(typeof process>"u")return;try{let e=Object.getOwnPropertyDescriptor(process,"getBuiltinModule");if(!e||!("value"in e)||typeof e.value!=="function")return;let t=Reflect.apply(e.value,process,["node:util"]);if(typeof t!=="object"||t===null)return;let n=Object.getOwnPropertyDescriptor(t,"types");if(!n||!("value"in n)||typeof n.value!=="object"||n.value===null)return;let s=Object.getOwnPropertyDescriptor(n.value,"isProxy");if(!s||!("value"in s)||typeof s.value!=="function")return;return s.value}catch{return}}var yp=_p();function Ri(e){if(typeof e!=="function")return;let t=Object.getOwnPropertyDescriptor(e,"prototype");if(!t||!("value"in t)||typeof t.value!=="object"&&typeof t.value!=="function")return;Si.add(t.value);let n=ut.call(e);if(/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(n)&&t.configurable===!1&&t.writable===!1){rl.add(n);let s=new Map;for(let o of Reflect.ownKeys(t.value)){let a=Object.getOwnPropertyDescriptor(t.value,o);if(a)s.set(o,a)}nl.set(n,s)}}for(let e of[Object,Function,Array,Date,Map,Set,ArrayBuffer,DataView,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,Int8Array,Int16Array,Int32Array,Float32Array,Float64Array])Ri(e);for(let e of["SharedArrayBuffer","AggregateError","Float16Array","BigInt64Array","BigUint64Array","Blob","File","Headers"]){let t=Object.getOwnPropertyDescriptor(globalThis,e);if(t&&"value"in t)Ri(t.value)}var ja=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"constructor");if(ja&&"value"in ja)Ri(ja.value);if(typeof Buffer==="function")Ri(Buffer);var gp=(()=>{if(typeof Blob!=="function")return;try{let e=new Blob([]);for(let t of Object.getOwnPropertySymbols(e)){let n=Object.getOwnPropertyDescriptor(e,t);if(n&&"value"in n&&typeof n.value==="object"&&n.value)return Object.getPrototypeOf(n.value)}}catch{return}return})(),bp=Map.prototype.entries,wp=Set.prototype.values,gi=typeof Headers==="function"?Object.getOwnPropertyDescriptor(Headers.prototype,"entries"):void 0,Yu=gi&&"value"in gi&&typeof gi.value==="function"?gi.value:void 0,Ap=new Set(["ArrayBuffer","SharedArrayBuffer","Blob","File","Map","Date","Set","Headers"]);function vi(e){let t=Object.getOwnPropertyDescriptor(e,"constructor");if(!t||!("value"in t)||typeof t.value!=="function")return;let n=t.value,s=ut.call(n),o=nl.get(s);if(!rl.has(s)||!o)return;let a=Object.getOwnPropertyDescriptor(n,"prototype");if(!a||!("value"in a)||a.value!==e||a.configurable!==!1||a.writable!==!1)return;return{constructor:n,descriptors:o,functionPrototype:Object.getPrototypeOf(n)}}function Pp(e){return Si.has(e)||vi(e)!==void 0}function La(e,t,n){if(t===void 0)return e===void 0;if(typeof e!=="function"||typeof t!=="function")return!1;let s=ut.call(t);if(ut.call(e)!==s)return!1;let o=Object.getPrototypeOf(e);if(o===n)return!0;if(!/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(s))return!1;let a=vi(o);return a!==void 0&&ut.call(a.constructor)===mp}function Ip(e,t,n){if(!t||e.configurable!==t.configurable||e.enumerable!==t.enumerable||"value"in e!=="value"in t)return!1;if("value"in e&&"value"in t){if(e.writable!==t.writable)return!1;if(typeof t.value==="function")return La(e.value,t.value,n);if(t.value!==null&&typeof t.value==="object")return!1;return Object.is(e.value,t.value)}return La(e.get,t.get,n)&&La(e.set,t.set,n)}function Qu(e){if(Vu)return Vu.call(Error,e);let t=e;for(let n=0;t!==null&&n<us;n+=1){if(Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))return!1;t=Object.getPrototypeOf(t)}return t===null&&fp.call(e)==="[object Error]"}function xp(e,t){if(typeof t.get!=="function"||typeof t.set!=="function")return;let n=Object.getPrototypeOf(e);for(let s=0;n!==null&&s<us;s+=1){let o=Object.getOwnPropertyDescriptor(n,"constructor");if(o&&"value"in o&&typeof o.value==="function"){let a=o.value;if(ut.call(a)===pp&&Pp(n)){let u=Object.getPrototypeOf(a);if(Object.getPrototypeOf(t.get)===u&&Object.getPrototypeOf(t.set)===u)return{constructor:a,prototype:n};return}}n=Object.getPrototypeOf(n)}return}function Sp(e,t){if(!Qu(e))return!1;if(ts&&!("value"in ts)&&typeof ts.get==="function"&&Object.prototype.isPrototypeOf.call(Error.prototype,e)&&t.get===ts.get&&t.set===ts.set)return!0;let n=xp(e,t);if(!n)return!1;let s=Gu.get(n.prototype);if(!s){let o=Reflect.construct(n.constructor,[]);if(typeof o!=="object"||o===null||!Qu(o)||Object.getPrototypeOf(o)!==n.prototype)return!1;if(s=Object.getOwnPropertyDescriptor(o,"stack"),!s||"value"in s||typeof s.get!=="function"||typeof s.set!=="function")return!1;Gu.set(n.prototype,s)}return t.get===s.get&&t.set===s.set}function Ma(){let e=[],t=0;return{get length(){return e.length-t},enqueue(n){e.push(n)},dequeue(){if(t===e.length)return;let n=e[t];if(e[t]=void 0,t+=1,t===e.length)e=[],t=0;else if(t>=1024&&t*2>=e.length)e=e.slice(t),t=0;return n},clear(){e=[],t=0}}}function Rp(e){let t=Object.getPrototypeOf(e);for(let n=0;t!==null&&n<us;n+=1){if(t===Date.prototype)return"Date";if(!Si.has(t)){let o=Object.getOwnPropertyDescriptor(t,"constructor");if(o&&"value"in o&&typeof o.value==="function"&&ut.call(o.value)===hp&&vi(t))return"Date"}let s=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag);if(s&&"value"in s&&typeof s.value==="string"&&Ap.has(s.value))return s.value;t=Object.getPrototypeOf(t)}return}function vp(e,t,n){if(ArrayBuffer.isView(e)){let l,f="typed-array";try{l=ip?.call(e)}catch{f="data-view",l=cp?.call(e)}if(typeof l!=="object"||l===null)return{bytes:Number.POSITIVE_INFINITY,kind:f};return t(l,n+1),{bytes:0,kind:f}}let s=Rp(e);if(!s)return;let o,a="buffer";switch(s){case"ArrayBuffer":{o=lp;break}case"SharedArrayBuffer":{o=dp;break}case"Blob":case"File":return{bytes:Number.POSITIVE_INFINITY,kind:"blob"};case"Map":return{bytes:0,kind:"map"};case"Date":return Reflect.apply(up,e,[]),{bytes:8,kind:"date"};case"Set":return{bytes:0,kind:"set"};case"Headers":return{bytes:0,kind:"headers"};default:return}let u=o?.call(e);return{bytes:typeof u==="number"&&Number.isSafeInteger(u)&&u>=0?u:Number.POSITIVE_INFINITY,kind:a}}function Ep(e,t,n){if(t==="map"){for(let[s,o]of bp.call(e))if(!n(s,8)||!n(o,8))return!1}if(t==="set"){for(let s of wp.call(e))if(!n(s,8))return!1}if(t==="headers"){if(!Yu)return!1;for(let[s,o]of Yu.call(e))if(!n(s,8)||!n(o,8))return!1}return!0}function Op(e,t,n){if(Array.isArray(e)){let o=Object.getOwnPropertyDescriptor(e,"length"),a=o&&"value"in o?o.value:void 0;if(typeof a!=="number"||!Number.isSafeInteger(a)||a<0||a>Math.floor(n/16))return}if(t!=="typed-array")return Reflect.ownKeys(e);let s=ap?.call(e);if(typeof s!=="number"||!Number.isSafeInteger(s)||s<0||s>np)return;return Reflect.ownKeys(e).filter((o)=>{if(typeof o!=="string")return!0;let a=Number(o);return!Number.isInteger(a)||a<0||a>=s||String(a)!==o})}function sl(e,t,n,s,o,a){let u=Op(e,t,s());if(u===void 0)return!1;for(let l of u){if(!o(typeof l==="string"?l.length*2+8:8))return!1;if(typeof l==="symbol")a(l,n+1);let f=Object.getOwnPropertyDescriptor(e,l);if(!f)return!1;if(!("value"in f)){if(l==="stack"&&Sp(e,f))continue;return!1}a(f.value,n+1,t==="blob")}return!0}function kp(e,t,n,s,o,a,u,l){let f=Object.getPrototypeOf(e);for(let h=t+1;f!==null;h+=1){if(h>=us)return!1;if(Si.has(f)||n&&f===gp)return!0;if(s.has(f))return u(f,h),o()>=0;s.add(f);let _=f;if(!l(_,()=>{if(!a(16))return!1;let y=vi(_);if(!y)return sl(_,void 0,h,o,a,u);for(let P of Reflect.ownKeys(_)){let I=Object.getOwnPropertyDescriptor(_,P);if(!I)return!1;if(Ip(I,y.descriptors.get(P),y.functionPrototype))continue;if(!a(typeof P==="string"?P.length*2+8:8)||!("value"in I))return!1;if(typeof P==="symbol")u(P,h+1);u(I.value,h+1)}return o()>=0}))return!1;f=Object.getPrototypeOf(_)}return!0}var Cp=32,Tp=32,ol=8,il=16,$p=131072;function Ba(e,t){let n=0,s=0,o=new WeakSet,a=new Set,u=new Set,l=new Map,f,h=()=>t-n,_=(x)=>{if(!Number.isSafeInteger(x)||x<0)return n=t+1,!1;if(n+=x,f)f.bytes+=x;else s+=x;return n<=t},w=(x)=>{if(f)f.edges.add(x);else u.add(x)},y=(x,v)=>{w(x);let C={bytes:0,edges:new Set};l.set(x,C);let E=f;f=C;try{return v()}finally{f=E}},P=(x)=>{if(a.has(x)){w(x),_(8);return}if(a.add(x),!y(x,()=>{if(!Ju)return!1;let v=Reflect.apply(Ju,x,[]);return _(8+(v?.length??0)*2)}))n=t+1},I=(x,v,C=!1)=>{if(n>t)return;if(typeof x==="string"){_(x.length*2);return}if(typeof x==="symbol"){P(x);return}if(typeof x==="function"){n=t+1;return}if(x===null||typeof x!=="object"){_(8);return}if(yp?.(x)){n=t+1;return}if(v>=us){n=t+1;return}if(o.has(x)){w(x),_(8);return}if(o.add(x),!y(x,()=>{if(!_(16))return!1;let E=vp(x,I,v);if(!kp(x,v,C,o,h,_,I,y))return!1;if(E!==void 0&&!_(E.bytes))return!1;if(!Ep(x,E?.kind,(S,j)=>{if(!_(j))return!1;return I(S,v+1),n<=t}))return!1;return sl(x,E?.kind,v,h,_,I)}))n=t+1};try{I(e,0)}catch{return}return n<=t?{scalarBytes:s,roots:u,nodes:l}:void 0}function jp(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Wa(e,t){return e.bytes+Tp+e.edges.size*ol+t*il}function Ua(e){return Cp+e.scalarBytes+e.roots.size*ol}function Lp(e,t,n,s){let o=new Set,a=[...e];while(a.length){if(s.remaining-=1,s.remaining<0)return;let u=a.pop();if(o.has(u))continue;let l=t.get(u)??n.get(u);if(!l)return;o.add(u);for(let f of l.edges)a.push(f)}return o}function qa(e,t,n,s,o){let a=s.get(e);if(a){if(o)a.node=o;return a}let u=o??t.nodes.get(e)??n.get(e);if(!u)return;let l={node:u,ownerDelta:0};return s.set(e,l),l}function Mp(e,t,n,s,o){let a=new Set([e]);for(let[u,l]of t.nodes){if(o.remaining-=1,o.remaining<0)return;let f=n.get(u);if(!f)continue;let h=!jp(f.edges,l.edges);if(f.bytes!==l.bytes||h)qa(u,t,n,s,l);if(!h)continue;for(let _ of f.owners){if(o.remaining-=1,o.remaining<0)return;a.add(_)}}return a}function Bp(e,t,n,s,o,a){for(let u of e.identities){if(a.remaining-=1,a.remaining<0)return!1;if(!t.has(u)){let l=qa(u,n,s,o);if(!l)return!1;l.ownerDelta-=1}}for(let u of t){if(a.remaining-=1,a.remaining<0)return!1;if(!e.identities.has(u)){let l=qa(u,n,s,o);if(!l)return!1;l.ownerDelta+=1}}return!0}function Dp(e,t,n,s,o,a){let u=new Map;for(let l of n){let f=l===e?t.roots:l.roots,h=Lp(f,t.nodes,s,a);if(!h||!Bp(l,h,t,s,o,a))return;u.set(l,h)}return u}function Np(e,t,n,s,o,a){let u=e-(s?0:Ua(t))+Ua(n);for(let[l,f]of o){let h=a.get(l),_=(h?.owners.size??0)+f.ownerDelta;if(_<0)return;if(h)u-=Wa(h,h.owners.size);if(_)u+=Wa(f.node,_)}return Number.isSafeInteger(u)&&u>=0&&u<=ss?u:void 0}function Fp(e,t,n){for(let[s,o]of t){let a=e.get(s);if(!((a?.owners.size??0)+o.ownerDelta))continue;if(a)a.bytes=o.node.bytes,a.edges=o.node.edges;else e.set(s,{bytes:o.node.bytes,edges:o.node.edges,owners:new Set})}for(let[s,o]of n){for(let a of s.identities)if(!o.has(a))e.get(a)?.owners.delete(s);for(let a of o)if(!s.identities.has(a))e.get(a).owners.add(s);s.identities=o}for(let s of t.keys())if(e.get(s)?.owners.size===0)e.delete(s)}function Wp(){let e=new Map,t=0,n=(o,a,u)=>{let l={remaining:$p},f=new Map,h=Mp(o,a,e,f,l);if(!h)return!1;let _=Dp(o,a,h,e,f,l);if(!_)return!1;let w=Np(t,o,a,u,f,e);if(w===void 0)return!1;return Fp(e,f,_),o.scalarBytes=a.scalarBytes,o.roots=a.roots,t=w,!0};return{retain(o){let a={scalarBytes:0,roots:new Set,identities:new Set};return n(a,o,!0)?a:void 0},refresh(o,a){return n(o,a,!1)},release:(o)=>{t-=Ua(o);for(let a of o.identities){let u=e.get(a);if(!u?.owners.delete(o))continue;if(t-=il,u.owners.size===0)t-=Wa(u,0),e.delete(a)}o.identities.clear()},clear(){e.clear(),t=0}}}class fr{constructor(){Te.add(this),this.controller=new AbortController,bi.set(this,void 0),wi.set(this,()=>{return}),os.set(this,()=>{return}),rs.set(this,void 0),Ai.set(this,()=>{return}),is.set(this,()=>{return}),qe.set(this,Object.create(null)),as.set(this,[]),cs.set(this,new WeakMap),ns.set(this,new Set),Jr.set(this,new Set),Tt.set(this,0),lr.set(this,!1),Ii.set(this,!1),xi.set(this,!1),Vr.set(this,!1),dr.set(this,void 0),A(this,bi,new Promise((e,t)=>{A(this,wi,e,"f"),A(this,os,t,"f")}),"f"),A(this,rs,new Promise((e,t)=>{A(this,Ai,e,"f"),A(this,is,t,"f")}),"f"),c(this,bi,"f").catch(()=>{return}),c(this,rs,"f").catch(()=>{return})}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch((n)=>{t=!0,c(this,Te,"m",Pi).call(this,n)}).then(()=>{if(t)return;try{this._emitFinal()}catch(n){c(this,Te,"m",Pi).call(this,n);return}this._emit("end")})},0)}_connected(){if(this.ended)return;c(this,wi,"f").call(this),this._emit("connect")}get ended(){return c(this,lr,"f")}get errored(){return c(this,Ii,"f")}get aborted(){return c(this,xi,"f")}abort(){this.controller.abort()}_userAbortError(){let e=new Z;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){c(this,Te,"m",Da).call(this,e);return}if(c(this,as,"f").some((n)=>n.signal===e))return;let t=()=>c(this,Te,"m",Da).call(this,e);e.addEventListener("abort",t,{once:!0}),c(this,as,"f").push({signal:e,listener:t})}on(e,t){var n;return((n=c(this,qe,"f"))[e]||(n[e]=[])).push({listener:t}),this}off(e,t){let n=c(this,qe,"f")[e];if(!n)return this;let s=c(this,cs,"f").get(t);if(s?.event===e&&!s.registration.removed&&!s.registration.detached)return c(this,Te,"m",el).call(this,e,s.registration),this;let o=n.findIndex((a)=>!a.removed&&a.listener===t);if(o!==-1)n.splice(o,1);return this}once(e,t){var n;return((n=c(this,qe,"f"))[e]||(n[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{A(this,Vr,!0,"f");let s=(a)=>{this.off(e,o),n(a)},o=(...a)=>{if(e!=="error")this.off("error",s);t(a.length>1?a:a[0])};if(e!=="error")c(this,Te,"m",Na).call(this,"error",s);c(this,Te,"m",Na).call(this,e,o)})}events(e){return this._createIterator((t)=>{let n=(...s)=>{$a.add(s);try{t(s)}finally{$a.delete(s)}};return this.on(e,n),()=>this.off(e,n)},{rejectOnError:e!=="error",rejectOnAbort:e!=="abort"})}_createIterator(e,{rejectOnError:t=!0,rejectOnAbort:n=!0,onReturn:s}={}){let o=Ma(),a=Ma(),u=Ma(),l=Wp(),f=this.ended,h,_=!1,w=()=>{return},y=()=>({value:void 0,done:!0}),P=()=>{while(u.length)u.dequeue().resolve(y())},I=()=>{if(!h||_||!u.length)return;_=!0,u.dequeue().reject(h)},x=()=>{if(w(),this.off("end",F),t)this.off("error",j);if(n)this.off("abort",j)},v=(k)=>{if(k.active=!1,k.check)c(this,Jr,"f").delete(k.check),k.check=void 0},C=(k=!1)=>{if(k){while(a.length)v(a.dequeue());o.clear(),l.clear()}let T=new m(`Event stream iterator buffer limit exceeded (${Hu} events or ${ss} bytes); consume events as they arrive.`);try{c(this,Te,"m",Pi).call(this,T)}finally{this.controller.abort()}return T},E=(k,T)=>{if(!T.active||c(this,lr,"f"))return;let L=Ba(k,ss);if(!L||!l.refresh(T.retention,L))C(!0)},S=(k)=>{if(f)return;let T=u.dequeue();if(T)T.resolve({value:k,done:!1});else{if(o.length>=Hu){C();return}let L=Ba(k,ss),D=L&&l.retain(L);if(!D){C();return}if(typeof k==="object"&&k!==null&&$a.has(k)){let W=k;for(let J=0;J<W.length;J+=1){let X=W[J];if(typeof X==="string")W[J]=op(sp(X))}}let K={retention:D,active:!0,check:void 0};o.enqueue(k),a.enqueue(K);let U=()=>{K.check=void 0,E(k,K)};K.check=U,c(this,Jr,"f").add(U)}},j=(k)=>{if(h=k,!o.length)I()},R=()=>{if(h)return;let k=c(this,dr,"f");if(!k)return;if(k.kind==="error"?t:n)h=k.error},F=()=>{if(f=!0,R(),x(),!o.length)I(),P()};if(!f){if(w=e(S),this.on("end",F),t)this.on("error",j);if(n)this.on("abort",j)}return{next:()=>{if(o.length){let k=o.dequeue(),T=a.dequeue();v(T);let L=Ba(k,ss);if(!L||!l.refresh(T.retention,L)){let D=C(!0);return _=!0,Promise.reject(D)}return l.release(T.retention),Promise.resolve({value:k,done:!1})}if(f||this.ended)R();if(h&&!_)return _=!0,Promise.reject(h);if(f)return Promise.resolve(y());return new Promise((k,T)=>{u.enqueue({resolve:k,reject:T})})},return:()=>{f=!0,_=!0;while(a.length)v(a.dequeue());if(o.clear(),l.clear(),x(),P(),s)this.done().catch(()=>{return}),s();return Promise.resolve(y())},[Symbol.asyncIterator](){return this}}}async done(){A(this,Vr,!0,"f"),await c(this,rs,"f")}_hasListeners(e){return Boolean(c(this,qe,"f")[e]?.some((t)=>!t.removed))}_emit(e,...t){if(c(this,lr,"f"))return;if(e==="end")c(this,Te,"m",Zu).call(this),A(this,lr,!0,"f"),c(this,Ai,"f").call(this);let n=c(this,qe,"f")[e],s,o=!1;try{if(n){c(this,qe,"f")[e]=n.filter((a)=>{if(a.once)a.detached=!0;return!a.once&&!a.removed}),A(this,Tt,c(this,Tt,"f")+1,"f");try{for(let a of n)if(!a.removed){let{listener:u}=a;u(...t)}}finally{if(A(this,Tt,c(this,Tt,"f")-1,"f"),c(this,Tt,"f")===0){c(this,Te,"m",Fa).call(this);for(let a of c(this,Jr,"f"))if(c(this,Jr,"f").delete(a),!c(this,lr,"f"))a()}}}}catch(a){s=a,o=!0}try{c(this,Te,"m",tl).call(this,e,t,Boolean(n?.length))}catch(a){if(!o)s=a,o=!0}if(o)throw s}_emitFinal(){}}bi=new WeakMap,wi=new WeakMap,os=new WeakMap,rs=new WeakMap,Ai=new WeakMap,is=new WeakMap,qe=new WeakMap,as=new WeakMap,cs=new WeakMap,ns=new WeakMap,Jr=new WeakMap,Tt=new WeakMap,lr=new WeakMap,Ii=new WeakMap,xi=new WeakMap,Vr=new WeakMap,dr=new WeakMap,Te=new WeakSet,Da=function(t){try{this.controller.abort(t.reason)}catch{this.controller.abort()}},Zu=function(){for(let{signal:t,listener:n}of c(this,as,"f").splice(0))t.removeEventListener("abort",n)},Na=function(t,n){let s=c(this,qe,"f")[t],o=s?.length??0;this.once(t,n);let a=c(this,qe,"f")[t],[u]=a?.slice(-1)??[];if((s===void 0||a===s)&&a?.length===o+1&&u?.listener===n&&u.once)c(this,cs,"f").set(n,{event:t,registration:u})},el=function(t,n){if(n.removed)return;if(n.removed=!0,c(this,cs,"f").delete(n.listener),c(this,ns,"f").add(t),c(this,Tt,"f")===0)c(this,Te,"m",Fa).call(this)},Fa=function(){for(let t of c(this,ns,"f")){let n=t,s=c(this,qe,"f")[n];if(s)c(this,qe,"f")[n]=s.filter((o)=>!o.removed)}c(this,ns,"f").clear()},Pi=function(t){if(A(this,Ii,!0,"f"),t instanceof Error&&t.name==="AbortError")t=this._userAbortError();if(t instanceof Z)return A(this,xi,!0,"f"),this._emit("abort",t);if(t instanceof m)return this._emit("error",t);if(t instanceof Error){let n=new m(t.message);return n.cause=t,this._emit("error",n)}return this._emit("error",new m(String(t)))},tl=function(t,n,s){if(t==="abort"){let o=n[0];if(A(this,dr,c(this,dr,"f")??{kind:"abort",error:o},"f"),!c(this,Vr,"f")&&!s)Promise.reject(o);c(this,os,"f").call(this,o),c(this,is,"f").call(this,o),this._emit("end");return}if(t==="error"){let o=n[0];if(A(this,dr,c(this,dr,"f")??{kind:"error",error:o},"f"),!c(this,Vr,"f")&&!s)Promise.reject(o);c(this,os,"f").call(this,o),c(this,is,"f").call(this,o),this._emit("end")}};function al(e){return typeof e.parse==="function"}var Re,pr,Ei,Oi,Ka,ki,za,Xa,Ha,Ja,cl,ul,Up=10;function qp(e){for(let t of e.choices)for(let n of t.message.tool_calls??[])if(!n.id)n.id=`call_${Ve()}`}function Kp(e){if(!It(e))return e;let t={role:"assistant"};if(e.audio!=null)t.audio={id:e.audio.id};if(e.content!==void 0)t.content=e.content;if(e.function_call!=null)t.function_call=e.function_call;if(e.name!==void 0)t.name=e.name;if(e.refusal!=null)t.refusal=e.refusal;if(e.tool_calls!==void 0)t.tool_calls=e.tool_calls.map((n)=>{if(n.type==="custom")return{id:n.id,type:n.type,custom:{input:n.custom.input,name:n.custom.name}};return{id:n.id,type:n.type,function:{arguments:n.function.arguments,name:n.function.name}}});return t}class Gr extends fr{constructor(){super(...arguments);Re.add(this),this._chatCompletions=[],Ei.set(this,!1),Oi.set(this,!1),this.messages=[]}_addChatCompletion(e){A(this,Ei,!this.controller.signal.aborted,"f"),qp(e),this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;if(t)this._addMessage(t);return e}_addMessage(e,t=!0,n=!0){if(n&&!("content"in e))e.content=null;if(this.messages.push(e),t){if(this._emit("message",e),es(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(It(e)&&e.tool_calls){for(let s of e.tool_calls)if(s.type==="function")this._emit("functionToolCall",s.function)}}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new m("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,Re,"m",Ka).call(this)}async finalMessage(){return await this.done(),c(this,Re,"m",ki).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,Re,"m",za).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,Re,"m",Xa).call(this)}async totalUsage(){return await this.done(),c(this,Re,"m",Ha).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){if(c(this,Oi,"f"))c(this,Re,"m",Ja).call(this);let e=this._chatCompletions[this._chatCompletions.length-1];if(e)this._emit("finalChatCompletion",e);let t=c(this,Re,"m",ki).call(this);if(t)this._emit("finalMessage",t);let n=c(this,Re,"m",Ka).call(this);if(n)this._emit("finalContent",n);let s=c(this,Re,"m",za).call(this);if(s)this._emit("finalFunctionToolCall",s);let o=c(this,Re,"m",Xa).call(this);if(o!=null)this._emit("finalFunctionToolCallResult",o);if(this._chatCompletions.some((a)=>a.usage))this._emit("totalUsage",c(this,Re,"m",Ha).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),c(pr,pr,"m",cl).call(pr,t);let s=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Zn(s,t))}async _runChatCompletion(e,t,n){for(let s of t.messages)this._addMessage(s,!1,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,s){let{tool_choice:a="auto",stream:u,toolContext:l,...f}=t,h=l,_=typeof a!=="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:w=Up,afterCompletion:y}=s||{},P=async(S)=>{if(y==null)return;A(this,Oi,!0,"f"),await y(S,n),c(this,Re,"m",Ja).call(this)},I=t.tools.map((S)=>{if(Qe(S)){if(!S.$callback)throw new m("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:S.$callback,name:S.function.name,description:S.function.description||"",parameters:S.function.parameters,parse:S.$parseRaw,strict:!0}}}return S}),x=Object.create(null);for(let S of I)if(S.type==="function")x[S.function.name||S.function.function.name]=S.function;let v="tools"in t?I.map((S)=>S.type==="function"?{type:"function",function:{name:S.function.name||S.function.function.name,parameters:S.function.parameters,description:S.function.description,strict:S.function.strict}}:S):void 0;for(let S of t.messages)this._addMessage(S,!1,!1);let C=!1,E=async(S)=>{let j=C;if(C=!1,S.type!=="function")return{message:void 0,functionCalled:!1};let R=S.id,{name:F,arguments:k}=S.function,T=x[F];if(!T){let K=`Invalid tool_call: ${JSON.stringify(F)}. Available options are: ${Object.keys(x).map((U)=>JSON.stringify(U)).join(", ")}. Please try again`;return{message:{role:"tool",tool_call_id:R,content:K},functionCalled:!1}}if(_&&_!==F){let K=`Invalid tool_call: ${JSON.stringify(F)}. ${JSON.stringify(_)} requested. Please try again`;return{message:{role:"tool",tool_call_id:R,content:K},functionCalled:!1}}let L;if(al(T)){let K;try{K=await T.parse(k)}catch(U){if(this.controller.signal.aborted)throw this._userAbortError();let W=U instanceof Error?U.message:String(U);return{message:{role:"tool",tool_call_id:R,content:W},functionCalled:!1}}if(this.controller.signal.aborted)throw this._userAbortError();try{L=await T.function(K,n,h)}catch(U){if(this.controller.signal.aborted&&Object.is(U,this.controller.signal.reason))throw this._userAbortError();throw U}}else{if(this.controller.signal.aborted&&!j)throw this._userAbortError();try{L=await T.function(k,n,h)}catch(K){if(this.controller.signal.aborted&&Object.is(K,this.controller.signal.reason))throw this._userAbortError();throw K}}let D=c(pr,pr,"m",ul).call(pr,L);return{message:{role:"tool",tool_call_id:R,content:D},functionCalled:!0}};for(let S=0;S<w;++S){let j=await this._createChatCompletion(e,{...f,tool_choice:a,tools:v,messages:this.messages.map(Kp)},s);C=this.controller.signal.aborted&&c(this,Ei,"f");let R=j.choices[0]?.message;if(!R)throw new m("missing message in ChatCompletion response");if(!R.tool_calls?.length){await P(j);return}if(_||t.parallel_tool_calls===!1)for(let F of R.tool_calls){let k=await E(F);if(k.message)this._addMessage(k.message);if(this.controller.signal.aborted)throw this._userAbortError();if(_&&k.functionCalled){await P(j);return}}else{let F=await Promise.allSettled(R.tool_calls.map(E));if(!this.controller.signal.aborted){for(let k of F)if(k.status==="rejected")throw k.reason}for(let k of F)if(k.status==="fulfilled"&&k.value.message)this._addMessage(k.value.message);if(this.controller.signal.aborted)throw this._userAbortError()}await P(j)}}}pr=Gr,Ei=new WeakMap,Oi=new WeakMap,Re=new WeakSet,Ka=function(){return c(this,Re,"m",ki).call(this).content??null},ki=function(){let t=this.messages.length;while(t-- >0){let n=this.messages[t];if(It(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new m("stream ended without producing a ChatCompletionMessage with role=assistant")},za=function(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(It(n)&&n?.tool_calls?.length)for(let s=n.tool_calls.length-1;s>=0;s--){let o=n.tool_calls[s];if(o?.type==="function")return o.function}}return},Xa=function(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(es(n)&&n.content!=null&&typeof n.content==="string"&&this.messages.some((s)=>s.role==="assistant"&&s.tool_calls?.some((o)=>o.type==="function"&&o.id===n.tool_call_id)))return n.content}return},Ha=function(){let t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:n}of this._chatCompletions)if(n)t.completion_tokens+=n.completion_tokens,t.prompt_tokens+=n.prompt_tokens,t.total_tokens+=n.total_tokens;return t},Ja=function(){if(this.controller.signal.aborted)throw this._userAbortError()},cl=function(t){if(t.n!=null&&t.n>1)throw new m("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ul=function(t){if(typeof t==="string")return t;if(t===void 0)return"undefined";return JSON.stringify(t)};class ls extends Gr{static runTools(e,t,n){let s=new ls,o={...n,__metadata:{...n?.__metadata,helperMethod:"runTools"}};return s._run(()=>s._runTools(e,t,s,o)),s}_addMessage(e,t=!0,n=!0){if(super._addMessage(e,t,n),t&&It(e)&&e.content)this._emit("content",e.content)}}var pe={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class ll extends Error{}class Ci extends Error{}function zp(e,t=pe.ALL){if(typeof e!=="string")throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return Xp(e.trim(),t)}var Xp=(e,t)=>{let n=e.length,s=0,o=(y)=>{throw new ll(`${y} at position ${s}`)},a=(y)=>{throw new Ci(`${y} at position ${s}`)},u=()=>{if(w(),s>=n)o("Unexpected end of input");if(e[s]==='"')return l();if(e[s]==="{")return f();if(e[s]==="[")return h();if(e.substring(s,s+4)==="null"||pe.NULL&t&&n-s<4&&"null".startsWith(e.substring(s)))return s+=4,null;if(e.substring(s,s+4)==="true"||pe.BOOL&t&&n-s<4&&"true".startsWith(e.substring(s)))return s+=4,!0;if(e.substring(s,s+5)==="false"||pe.BOOL&t&&n-s<5&&"false".startsWith(e.substring(s)))return s+=5,!1;if(e.substring(s,s+8)==="Infinity"||pe.INFINITY&t&&n-s<8&&"Infinity".startsWith(e.substring(s)))return s+=8,1/0;if(e.substring(s,s+9)==="-Infinity"||pe.MINUS_INFINITY&t&&n-s>1&&n-s<9&&"-Infinity".startsWith(e.substring(s)))return s+=9,-1/0;if(e.substring(s,s+3)==="NaN"||pe.NAN&t&&n-s<3&&"NaN".startsWith(e.substring(s)))return s+=3,Number.NaN;return _()},l=()=>{let y=s,P=!1;s++;while(s<n&&(e[s]!=='"'||P&&e[s-1]==="\\"))P=e[s]==="\\"?!P:!1,s++;if(e.charAt(s)==='"')try{return JSON.parse(e.substring(y,++s-Number(P)))}catch(I){a(String(I))}else if(pe.STR&t)try{return JSON.parse(e.substring(y,s-Number(P))+'"')}catch{return JSON.parse(e.substring(y,e.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},f=()=>{s++,w();let y={};try{while(e[s]!=="}"){if(w(),s>=n&&pe.OBJ&t)return y;let P=l();w(),s++;try{let I=u();Object.defineProperty(y,P,{value:I,writable:!0,enumerable:!0,configurable:!0})}catch(I){if(pe.OBJ&t)return y;throw I}if(w(),e[s]===",")s++}}catch{if(pe.OBJ&t)return y;o("Expected '}' at end of object")}return s++,y},h=()=>{s++;let y=[];try{while(e[s]!=="]")if(y.push(u()),w(),e[s]===",")s++}catch{if(pe.ARR&t)return y;o("Expected ']' at end of array")}return s++,y},_=()=>{if(s===0){if(e==="-"&&pe.NUM&t)o("Not sure what '-' is");try{return JSON.parse(e)}catch(I){if(pe.NUM&t)try{if(e[e.length-1]===".")return JSON.parse(e.substring(0,e.lastIndexOf(".")));return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(I))}}let y=s;if(e[s]==="-")s++;while(e[s]&&!",]}".includes(e[s]))s++;if(s===n&&!(pe.NUM&t))o("Unterminated number literal");let P=e.substring(y,s);try{return JSON.parse(P)}catch{if(P==="-"&&pe.NUM&t)o("Not sure what '-' is");try{return JSON.parse(P.substring(0,P.lastIndexOf("e")))}catch(I){a(String(I))}}},w=()=>{while(s<n&&`
20
20
  \r `.includes(e[s]))s++};return u()},dl=(e)=>zp(e,pe.ALL^pe.NUM);var G,ie,Ti,$t,hr,ve,Ke,De,Va,Yr,Ga,Ya,Qa,Qr,ds,fl;function pl(e){try{return dl(e)}catch(t){if(t instanceof Ci||t instanceof SyntaxError)return Pt({type:"json_schema",$parseRaw:void 0},e);throw t}}var uc="chat.completion.chunk.message:";function Al(e,t,n){let s={type:"message",message:t,...n?{tool_call_ids:n}:{}};return{id:e.id,choices:[],created:e.created,model:e.model,object:`${uc}${JSON.stringify(s)}`}}function Hp(e){return"type"in e&&e.type==="message"&&"message"in e||"object"in e&&typeof e.object==="string"&&e.object.startsWith(uc)}function Jp(e){if("type"in e)return e;return JSON.parse(e.object.slice(uc.length))}var $i=128,jt=128,Vp=16777216,Gp=65536,lc=128,Pl=67108864,hl=1024;function oc(){return{bytes:0,depth:0,fragments:0,work:0,escaped:!1,has_non_whitespace:!1,in_string:!1,last_parsed_bytes:0,pending_high_surrogate:!1}}function ic(e,t,n,s){if(t.fragments>=Gp)throw new m("Chat completion stream exceeded its structured JSON fragment limit");let o=0,{depth:a,escaped:u,has_non_whitespace:l,in_string:f}=e,h=!1,_=!0;for(let y of n){let P=o,I=y.codePointAt(0);if(_&&e.pending_high_surrogate&&I>=56320&&I<=57343)o+=1;else if(I<=127)o+=1;else if(I<=2047)o+=2;else if(I<=65535)o+=3;else o+=4;if(_=!1,t.bytes+o>Vp)throw new m("Chat completion stream exceeded its structured JSON byte limit");if(s&&s.work+o>Pl)throw s.work+=P,new m("Chat completion stream exceeded its structured JSON parse-work limit");if(y!==" "&&y!==`
21
- `&&y!=="\r"&&y!=="\t")l=!0;if(f){if(u)u=!1;else if(y==="\\")u=!0;else if(y==='"')f=!1,h||(h=a===0);continue}if(y==='"')f=!0;else if(y==="{"||y==="["){if(a+=1,a>lc)throw new m("Chat completion stream exceeded its structured JSON nesting depth limit")}else if((y==="}"||y==="]")&&a>0)a-=1,h||(h=a===0)}if(e.bytes+=o,e.fragments+=1,e.depth=a,e.escaped=u,e.has_non_whitespace=l,e.in_string=f,n.length>0){let y=n.codePointAt(n.length-1)??0;e.pending_high_surrogate=y>=55296&&y<=56319}if(t.bytes+=o,t.fragments+=1,s)s.work+=o;if(!l||o===0)return!1;let w=Math.max(hl,Math.floor(e.last_parsed_bytes/2));if(e.bytes>hl&&!h&&e.bytes-e.last_parsed_bytes<w)return!1;return!0}function ac(e,t){if(t.work+e.bytes>Pl)return!1;return t.work+=e.bytes,e.work+=e.bytes,e.last_parsed_bytes=e.bytes,!0}function ze(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n){let s=Object.getPrototypeOf(e);for(let o=0;s!==null;o+=1){if(o>=lc||Object.getOwnPropertyDescriptor(s,t))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");s=Object.getPrototypeOf(s)}return}if(!("value"in n)||typeof n.value!=="string"&&n.value!==null&&n.value!==void 0)throw new m("Chat completion stream contains an unsafe structured JSON snapshot");return n.value}function fs(e){let t=Object.getOwnPropertyDescriptor(e,"message");if(!t||!("value"in t)||typeof t.value!=="object"||t.value===null)throw new m("Chat completion stream contains an unsafe structured JSON snapshot");return t.value}function ml(e,t,n,s){let o=Object.getOwnPropertyDescriptor(e,t);if(!o){let u=Object.getPrototypeOf(e);for(let l=0;u!==null;l+=1){if(l>=lc||Object.getOwnPropertyDescriptor(u,t))throw new m(`Chat completion stream contains an unsafe snapshot ${s} collection`);u=Object.getPrototypeOf(u)}return}if(!("value"in o)||!Array.isArray(o.value))throw new m(`Chat completion stream contains an unsafe snapshot ${s} collection`);let a=Object.getOwnPropertyDescriptor(o.value,"length");if(!a||!("value"in a)||!Number.isSafeInteger(a.value)||a.value>n)throw new m(`Chat completion stream exceeded its snapshot ${s} limit`);return o.value}function Za(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n)return;if(!("value"in n))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");return n.value}function _l(e,t,n,s){let o=Object.getOwnPropertyDescriptor(e,"length"),a=o&&"value"in o?o.value:void 0;if(typeof a!=="number"||!Number.isSafeInteger(a)||a<0||a>t)throw new m(`Chat completion stream exceeded its snapshot ${n} limit`);let u=[];u.length=a;for(let l=0;l<a;l+=1){let f=Object.getOwnPropertyDescriptor(e,l);if(!f)continue;if(!("value"in f))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");u[l]=s(f.value,l)}return u}function mr(e,t,n){let s=oc(),o=t??{bytes:0,fragments:0,work:0};if(ic(s,o,e,n),!ac(s,o))throw new m("Chat completion stream exceeded its structured JSON parse-work limit");return e}function ji(e){let t=Object.getOwnPropertyDescriptor(e,"type"),n=Object.getOwnPropertyDescriptor(e,"function");if(!t||!("value"in t)||t.value!=="function"||!n||!("value"in n))return;if(typeof n.value!=="object"||n.value===null)return;let s=Object.getOwnPropertyDescriptor(n.value,"name");if(!s||!("value"in s)||typeof s.value!=="string"||s.value.length===0)return;return{type:"function",name:s.value}}function ec(e,t){let n=ji(e);if(!n||n.name!==t.name||n.type!==t.type)throw new m("Chat completion stream contains a changed tool call identity")}function ps(e,t){if(Object.prototype.propertyIsEnumerable.call(t,"__proto__")&&!M(e,"__proto__"))Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0});return Object.assign(e,t)}function hs(e,t=[]){let n=Object.getOwnPropertyDescriptors(e);for(let s of t){let o=n[s];if(!o&&!(s in e))continue;n[s]={value:o&&"value"in o?o.value:Reflect.get(e,s,e),enumerable:o?.enumerable??!1,configurable:o?.configurable??!0,writable:o&&"writable"in o?o.writable:!1}}return Object.create(Object.getPrototypeOf(e),n)}function Yp(e){let t=hs(e);if(e.tools){let n=[],s=Object.getOwnPropertyDescriptor(e.tools,"length"),o=s&&"value"in s?s.value:void 0,a=typeof o==="number"&&Number.isSafeInteger(o)&&o>=0?Math.min(o,jt):0;for(let u=0;u<a;u+=1){let l=Object.getOwnPropertyDescriptor(e.tools,String(u));if(!l||!("value"in l)){n.length=u+1;continue}let f=l.value,h=hs(f,["type","$brand","$parseRaw","$callback","function"]),_=Object.getOwnPropertyDescriptors(h);if(at(h)){let w=_.function;_.function={...w&&"value"in w?w:{configurable:!0,enumerable:!0,writable:!0},value:hs(h.function,["name","strict"])}}n[u]=Object.create(Object.getPrototypeOf(f),_)}t.tools=n}if(e.response_format)t.response_format=hs(e.response_format,["type","$brand","$parseRaw"]);return t}var tc=4096,rc=JSON.stringify,Qp=1048576,Zp=64,nc=Symbol("omitted serialized parser value"),he=Symbol("unsafe serialized parser value");function Il(e,t){let n=new WeakSet,s=(a)=>{if(!Number.isSafeInteger(a)||a<0||t.bytes+a>Qp)return!1;return t.bytes+=a,!0},o=(a,u)=>{if(u>Zp||t.nodes>=tc)return he;if(t.nodes+=1,a===void 0||typeof a==="function"||typeof a==="symbol")return nc;if(typeof a==="bigint")return he;if(a===null||typeof a==="boolean"||typeof a==="number"){let h=rc(a);return typeof h==="string"&&s(h.length)?h:he}if(typeof a==="string"){if(!s(a.length*6+2))return he;return rc(a)}if(typeof a!=="object"||n.has(a))return he;let l=Array.isArray(a),f=Object.getPrototypeOf(a);if(l&&f!==Array.prototype||!l&&f!==null&&f!==Object.prototype)return he;for(let h=a;h!==null;h=Object.getPrototypeOf(h)){let _=Object.getOwnPropertyDescriptor(h,"toJSON");if(!_)continue;if(!("value"in _)||typeof _.value==="function")return he;break}n.add(a);try{if(!s(2))return he;if(l){let y=Object.getOwnPropertyDescriptor(a,"length"),P=y&&"value"in y?y.value:void 0;if(typeof P!=="number"||!Number.isSafeInteger(P)||P<0||P>tc-t.nodes)return he;let I=[];for(let x=0;x<P;x+=1){let v=String(x),C=Object.getOwnPropertyDescriptor(a,v);if(!C){if(Object.getOwnPropertyDescriptor(Array.prototype,v)||Object.getOwnPropertyDescriptor(Object.prototype,v))return he;if(t.nodes+=1,!s(4))return he;I.push("null");continue}if(!("value"in C))return he;let E=o(C.value,u+1);if(E===he)return E;I.push(E===nc?"null":E)}return`[${I.join(",")}]`}let h=Reflect.ownKeys(a);if(h.length>tc-t.nodes)return he;let _=[];for(let y of h){if(typeof y!=="string")continue;let P=Object.getOwnPropertyDescriptor(a,y);if(!P)return he;if(!P.enumerable)continue;if(!("value"in P))return he;_.push([y,P.value])}_.sort(([y],[P])=>{if(y===P)return 0;return y<P?-1:1});let w=[];for(let[y,P]of _){let I=o(P,u+1);if(I===he)return I;if(I===nc)continue;if(!s(y.length*6+3))return he;w.push(`${rc(y)}:${I}`)}return`{${w.join(",")}}`}finally{n.delete(a)}};try{let a=o(e,0);return typeof a==="string"?a:void 0}catch{return}}function yl(e,t,n,s){let o=Object.getOwnPropertyDescriptor(t,"$parseRaw"),a=Object.getOwnPropertyDescriptor(n,s);if(!o||!("value"in o)||typeof o.value!=="function"||!a||!("value"in a))return;let u=Il(a.value,{nodes:0,bytes:0});if(u!==void 0)e.set(t,u)}function gl(e,t,n,s,o){let a=t&&e.get(t),u=Object.getOwnPropertyDescriptor(n,s);return a!==void 0&&u!==void 0&&"value"in u&&Il(o,{nodes:0,bytes:0})===a}function Zr(e,t){return e&&"value"in e?{...e,value:t}:{configurable:!0,enumerable:!0,writable:!0,value:t}}function cc(e,t,n){for(let s of n){let o=e[s];if(!o&&!(s in t))continue;e[s]=o&&"value"in o?{...o,value:void 0}:{configurable:o?.configurable??!0,enumerable:o?.enumerable??!1,writable:!1,value:void 0}}}function eh(e){let t=e.source??{type:e.type,...e.type==="function"?{function:{}}:{}},n=Object.getOwnPropertyDescriptors(t);if(n.type=Zr(n.type,e.type),e.type!=="function"||!e.function){if(n.function)n.function=Zr(n.function,void 0);return cc(n,t,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(t),n)}let s=n.function,o=s&&"value"in s&&typeof s.value==="object"&&s.value!==null?s.value:{},a=Object.getOwnPropertyDescriptors(o);if(a.name=Zr(a.name,e.function.name),a.strict=Zr(a.strict,e.function.strict),n.function=Zr(s,Object.create(Object.getPrototypeOf(o),a)),!e.function.schemaMatches)cc(n,t,["$brand","$parseRaw","$callback"]);return Object.create(Object.getPrototypeOf(t),n)}function th(e){let t=e.source??{type:e.type},n=Object.getOwnPropertyDescriptors(t);if(n.type=Zr(n.type,e.type),e.type!=="json_schema"||!e.source||!e.schemaMatches)cc(n,t,["$brand","$parseRaw"]);return Object.create(Object.getPrototypeOf(t),n)}function sc(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n||!("value"in n))return;let{value:s}=n;return typeof s==="object"&&s!==null?s:void 0}function rh(e,t,n){let s=new WeakMap,o=new WeakMap;if(e.tools)for(let P=0;P<e.tools.length&&P<jt;P+=1){let I=sc(e.tools,String(P)),x=t.tools?.[P];if(I&&x){s.set(I,x);let v=sc(x,"function");if(v)yl(o,x,v,"parameters")}}if(t.response_format)yl(o,t.response_format,t.response_format,"json_schema");let a,u,l,f,h=[],_=new WeakMap,w=new Map,y=new WeakMap;return Yc(e,{value(P,I,x){if(!a&&I===""&&typeof x==="object"&&x!==null){a=x,u=void 0,l=void 0,f=void 0,h=[],_=new WeakMap,w=new Map,y=new WeakMap;return}if(P===a&&I==="response_format"){if(typeof x==="object"&&x!==null)l=x,f={source:sc(P,I)===e.response_format?t.response_format:void 0,schemaMatches:!1};return}if(P===a&&I==="tools"){if(Array.isArray(x))return u=new Proxy(x,{get(E,S){let j=Reflect.get(E,S,E);if(typeof S==="string"){let R=Number(S);if(Number.isSafeInteger(R)&&R>=0&&R<jt&&String(R)===S)w.set(R,typeof j==="object"&&j!==null?j:void 0)}return j}}),u;return}if(P===u){let E=Number(I);if(!Number.isSafeInteger(E)||E<0||E>=jt||typeof x!=="object"||x===null)return;let S=w.get(E),R={source:S?s.get(S):void 0};h[E]=R,_.set(x,R);return}let v=_.get(P);if(v){if(I==="type"&&typeof x==="string")v.type=x;else if(I==="function"&&typeof x==="object"&&x!==null){let E={source:v.source,schemaMatches:!1};v.function=E,y.set(x,E)}return}if(P===l&&f){if(I==="type"&&typeof x==="string")f.type=x;else if(I==="json_schema")f.schemaMatches=gl(o,f.source,P,I,x);return}let C=y.get(P);if(C){if(I==="name"&&typeof x==="string")C.name=x;else if(I==="strict"&&typeof x==="boolean")C.strict=x;else if(I==="parameters")C.schemaMatches=gl(o,C.source,P,I,x)}return},complete(){if(!a)return;let P=hs(t);if(u){let I=[];for(let x=0;x<h.length;x+=1){let v=h[x];if(v)I[x]=eh(v)}P.tools=I}else delete P.tools;if(f)P.response_format=th(f);else delete P.response_format;n(P),a=void 0,u=void 0,l=void 0,f=void 0,h=[],_=new WeakMap,w=new Map,y=new WeakMap}})}class Lt extends Gr{constructor(e){super();G.add(this),ie.set(this,void 0),Ti.set(this,!1),$t.set(this,void 0),hr.set(this,void 0),ve.set(this,void 0),Ke.set(this,void 0),De.set(this,void 0),A(this,ie,e,"f"),A(this,$t,new Set,"f"),A(this,hr,[],"f"),A(this,Ke,!1,"f");let t=e?.tools,n=t&&Object.getOwnPropertyDescriptor(t,"length"),s=n&&"value"in n?n.value:void 0;if(t&&typeof s==="number"&&Number.isSafeInteger(s)&&s>=0)for(let o=0;o<Math.min(s,jt);o+=1){let a=Object.getOwnPropertyDescriptor(t,String(o));if(!a||!("value"in a))continue;let u=a.value;if(at(u)&&(Qe(u)||u.function.strict===!0)){A(this,Ke,!0,"f");break}}A(this,De,{bytes:0,fragments:0,work:0},"f")}get currentChatCompletionSnapshot(){return c(this,ve,"f")}static fromReadableStream(e){let t=new Lt(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){let s=new Lt(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}_runTools(e,t,n,s){return A(this,Ti,!0,"f"),super._runTools(e,t,n,s)}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal);let s={...t,stream:!0};A(this,ie,s,"f"),c(this,G,"m",Va).call(this);let o=Yp(s);A(this,ie,o,"f"),A(this,Ke,o.tools?.some((l)=>at(l)&&(Qe(l)||l.function.strict===!0))??!1,"f");let a=s.tools||s.response_format?rh(s,o,(l)=>{A(this,ie,l,"f"),A(this,Ke,l.tools?.some((f)=>at(f)&&(Qe(f)||f.function.strict===!0))??!1,"f")}):void 0,u=await e.chat.completions.create(s,{...n,signal:this.controller.signal}).finally(a);this._connected();for await(let l of u)c(this,G,"m",Ga).call(this,l);if(u.controller.signal?.aborted)throw this._userAbortError();return this._addChatCompletion(c(this,G,"m",ds).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,G,"m",Va).call(this),this._connected();let n=Ae.fromReadableStream(e,this.controller),s;for await(let a of n){if("error"in a&&M(a,"error")&&typeof a.error==="object"&&a.error!==null)throw new H(void 0,a.error,void 0,void 0);if(Hp(a)){let l=Jp(a);if(c(this,ve,"f")){let f=c(this,ve,"f").choices[0]?.message.tool_calls;for(let[h,_]of l.tool_call_ids?.entries()??[]){let w=f?.[h];if(w&&_)w.id=_}this._addChatCompletion(c(this,G,"m",ds).call(this)),s=void 0}this._addMessage(l.message);continue}let u=a;if(s&&u.id&&s!==u.id)this._addChatCompletion(c(this,G,"m",ds).call(this));if(c(this,G,"m",Ga).call(this,u),u.id)s=u.id}if(n.controller.signal?.aborted)throw this._userAbortError();if(c(this,ve,"f"))return this._addChatCompletion(c(this,G,"m",ds).call(this));let o=this._chatCompletions[this._chatCompletions.length-1];if(o)return o;throw new m("request ended without sending any chunks")}[(ie=new WeakMap,Ti=new WeakMap,$t=new WeakMap,hr=new WeakMap,ve=new WeakMap,Ke=new WeakMap,De=new WeakMap,G=new WeakSet,Va=function(){if(this.ended)return;A(this,$t,new Set,"f"),A(this,ve,void 0,"f"),A(this,De,{bytes:0,fragments:0,work:0},"f")},Yr=function(t){let n=c(this,hr,"f")[t.index];if(n)return n;return n={content_done:!1,content_parse_state:void 0,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null,tool_call_parse_states:new Map,tool_call_identities:new Map},c(this,hr,"f")[t.index]=n,n},Ga=function(t){if(this.ended)return;let n=new WeakMap,s=c(this,G,"m",fl).call(this,t,n);this._emit("chunk",t,s);for(let o of t.choices){let a=n.get(o),u=s.choices[a?.index??o.index],l=a?.tool_calls??[],{delta:f}=o,h=ct(c(this,ie,"f")?.response_format),_=h||c(this,Ke,"f"),w=_?fs(u):u.message,y=_?ze(w,"refusal"):w.refusal,I=!y&&h?ze(w,"content"):w.content;if(f?.content!=null&&w.role==="assistant"&&I)this._emit("content",f.content,I),this._emit("content.delta",{delta:f.content,snapshot:I,parsed:w.parsed});if(f?.refusal!=null&&w.role==="assistant"&&y)this._emit("refusal.delta",{delta:f.refusal,snapshot:y});if(o.logprobs?.content!=null&&w.role==="assistant")this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:u.logprobs?.content??[]});if(o.logprobs?.refusal!=null&&w.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:u.logprobs?.refusal??[]});let x=c(this,G,"m",Yr).call(this,u);if(u.finish_reason){if(c(this,G,"m",Qa).call(this,u),x.current_tool_call_index!=null)c(this,G,"m",Ya).call(this,u,x.current_tool_call_index)}for(let v of l){if(x.current_tool_call_index!==v.index){if(c(this,G,"m",Qa).call(this,u),x.current_tool_call_index!=null)c(this,G,"m",Ya).call(this,u,x.current_tool_call_index)}x.current_tool_call_index=v.index}for(let v of l){let C=w.tool_calls?.[v.index];if(!C?.type)continue;if(C.type==="function"){let E=x.tool_call_identities.get(v.index),S;if(E?.parseable){let j=ze(C.function,"arguments");if(typeof j!=="string")throw new m("Chat completion stream contains an unsafe structured JSON snapshot");S=j}else S=C.function.arguments;this._emit("tool_calls.function.arguments.delta",{name:C.function.name,index:v.index,arguments:S,parsed_arguments:C.function.parsed_arguments,arguments_delta:v.arguments_delta})}else if(C.type!=="custom")wl(C)}}},Ya=function(t,n){let s=c(this,G,"m",Yr).call(this,t);if(s.done_tool_calls.has(n))return;let a=(c(this,Ke,"f")?fs(t):t.message).tool_calls?.[n];if(!a)throw Error("no tool call snapshot");let u=s.tool_call_identities.get(n);if(u)ec(a,u);if(!a.type)throw Error("tool call snapshot missing `type`");if(a.type==="function"){let l=c(this,ie,"f")?.tools?.find((w)=>at(w)&&w.function.name===a.function.name),f=null,h=Qe(l)||l?.function.strict===!0,_;if(h){if(c(this,ve,"f"))c(this,G,"m",Qr).call(this,c(this,ve,"f"));let w=ze(a.function,"arguments");if(typeof w!=="string")throw new m("Chat completion stream contains an unsafe structured JSON snapshot");_=w}else _=a.function.arguments;if(Qe(l))f=l.$parseRaw(mr(_));else if(l?.function.strict)f=Pt({type:"json_schema",$parseRaw:void 0},mr(_));if(t.finish_reason)s.done_tool_calls.add(n);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:_,parsed_arguments:f})}else if(a.type!=="custom")wl(a)},Qa=function(t){let n=c(this,G,"m",Yr).call(this,t),s=ct(c(this,ie,"f")?.response_format),o=s||c(this,Ke,"f"),a=o?fs(t):t.message,u=o?ze(a,"refusal"):a.refusal,l=!u&&s,f=l?ze(a,"content"):a.content;if(f!=null&&(f!==""||!u&&!a.tool_calls?.length&&!a.function_call)&&!n.content_done){if(l&&c(this,ve,"f"))c(this,G,"m",Qr).call(this,c(this,ve,"f"));n.content_done=!0,this._emit("content.done",{content:f,parsed:u?null:Pt(c(this,ie,"f")?.response_format,l?mr(f):f)})}if(u&&!n.refusal_done)n.refusal_done=!0,this._emit("refusal.done",{refusal:u});if(t.logprobs?.content&&!n.logprobs_content_done)n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content});if(t.logprobs?.refusal&&!n.logprobs_refusal_done)n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal})},Qr=function(t){let n={bytes:0,fragments:0,work:0},s=ct(c(this,ie,"f")?.response_format),o=new WeakMap,a=ml(t,"choices",$i,"choice");if(!a)throw new m("Chat completion stream contains an unsafe snapshot choice collection");for(let u=0;u<a.length;u+=1){let l=Za(a,u);if(!l)continue;let f=fs(l),h=ze(f,"refusal"),_=ze(f,"content"),w=new Map,y=ml(f,"tool_calls",jt,"tool-call");o.set(l,Object.freeze({message:f,content:_,refusal:h,toolCallCollection:y,toolCalls:w}));let P=c(this,hr,"f")[l.index];if(s&&!h&&typeof _==="string")mr(_,n,c(this,De,"f"));for(let[I,x]of P?.tool_call_identities??[]){let v=y&&Za(y,I);if(!v)throw new m("Chat completion stream contains a changed tool call identity");ec(v,x)}if(!c(this,Ke,"f"))continue;for(let I=0;I<(y?.length??0);I+=1){let x=Za(y,I);if(!x)continue;let v=ji(x);if(!v){let j=Object.getOwnPropertyDescriptor(x,"type");if(j&&!("value"in j))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");if(j?.value!=="function")continue;let R=Object.getOwnPropertyDescriptor(x,"function");if(R&&!("value"in R))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");if(R&&typeof R.value==="object"&&R.value!==null){let F=Object.getOwnPropertyDescriptor(R.value,"name");if(F&&!("value"in F))throw new m("Chat completion stream contains an unsafe structured JSON snapshot")}continue}if(!_i(c(this,ie,"f"),{type:v.type,function:{name:v.name}}))continue;let C=Object.getOwnPropertyDescriptor(x,"function");if(!C||!("value"in C))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");let E=C.value,S=ze(E,"arguments");if(typeof S!=="string")throw new m("Chat completion stream contains an unsafe structured JSON snapshot");mr(S,n,c(this,De,"f")),w.set(I,Object.freeze({tool:x,function:E,type:v.type,name:v.name,arguments:S}))}}return o},ds=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=c(this,ve,"f");if(!t)throw new m("request ended without sending any chunks");let n=c(this,G,"m",Qr).call(this,t),s=c(this,$t,"f");return A(this,$t,new Set,"f"),A(this,ve,void 0,"f"),A(this,hr,[],"f"),nh(t,c(this,ie,"f"),s,n)},fl=function(t,n){var s,o,a,u,l;let f=c(this,ve,"f"),{choices:h,obfuscation:_,...w}=t;if(!f){let I={...w,choices:[]};A(this,ve,I,"f"),f=I}else if(t.id)ps(f,w);let y=c(this,ie,"f")?.n,P=typeof y==="number"&&Number.isSafeInteger(y)&&y>0?Math.min(y,$i):$i;for(let I of t.choices){let{delta:x,finish_reason:v,index:C,logprobs:E=null,...S}=I,j=[];if(n.set(I,Object.freeze({index:C,tool_calls:j})),!Number.isSafeInteger(C)||C<0||C>=P)throw new m(`Chat completion stream contains an invalid choice index: ${C}`);let R=f.choices[C];if(!R){let X={finish_reason:v,index:C,message:{},logprobs:null,...S};f.choices[C]=X,R=X}if(ct(c(this,ie,"f")?.response_format)||c(this,Ke,"f"))ze(fs(R),"refusal");if(E)if(R.logprobs){let{content:X,refusal:Le,...ne}=E;if(bl(ne),ps(R.logprobs,ne),X)(s=R.logprobs).content??(s.content=[]),R.logprobs.content.push(...X);if(Le)(o=R.logprobs).refusal??(o.refusal=[]),R.logprobs.refusal.push(...Le)}else{if(R.logprobs={...E},E.content)R.logprobs.content=[...E.content];if(E.refusal)R.logprobs.refusal=[...E.refusal]}if(v){if(R.finish_reason=v,c(this,ie,"f")&&(c(this,Ti,"f")||Ta(c(this,ie,"f")))){if(v==="length")throw new tr;if(v==="content_filter")throw new rr}}if(ps(R,S),!x){Object.freeze(j);continue}c(this,$t,"f").delete(C);let{audio:F,content:k,refusal:T,function_call:L,role:D,...K}=x,{tool_calls:U,...W}=K,J=M(K,"tool_calls")?U:x.tool_calls;if(bl(W),ps(R.message,W),F?.expires_at!=null&&F.id==null&&F.data==null&&F.transcript==null&&k==null&&T==null&&L==null&&D==null&&J==null&&Object.keys(W).length===0)c(this,$t,"f").add(C);if(T)R.message.refusal=(R.message.refusal||"")+T;if(D)R.message.role=D;if(F){let X=(a=R.message).audio??(a.audio={});if(F.id!=null)X.id=F.id;if(F.data!=null)X.data=(X.data??"")+F.data;if(F.transcript!=null)X.transcript=(X.transcript??"")+F.transcript;if(F.expires_at!=null)X.expires_at=F.expires_at}if(L)if(R.message.function_call){if(L.name)R.message.function_call.name=L.name;if(L.arguments)(u=R.message.function_call).arguments??(u.arguments=""),R.message.function_call.arguments+=L.arguments}else R.message.function_call=L;if(k!=null)if(!R.message.refusal&&ct(c(this,ie,"f")?.response_format)){let X=c(this,G,"m",Yr).call(this,R),Le=X.content_parse_state??(X.content_parse_state=oc()),ne=ic(Le,c(this,De,"f"),k);if(R.message.content=(ze(R.message,"content")||"")+k,!Le.has_non_whitespace)R.message.parsed=null;else if(ne&&ac(Le,c(this,De,"f")))c(this,G,"m",Qr).call(this,f),R.message.parsed=pl(mr(R.message.content));else if(k.length>0)R.message.parsed=null}else R.message.content=(R.message.content||"")+k;if(J){let X=(l=R.message).tool_calls??(l.tool_calls=[]);for(let Le of J){let{index:ne,id:zo,type:Dr,function:Ln,custom:ft,...Xo}=Le;if(!Number.isSafeInteger(ne)||ne<0||ne>=jt)throw new m(`Chat completion stream contains an invalid tool call index: ${ne}`);let Ho="",ue=X[ne]??(X[ne]={}),Ie=Ln?.name,ke=c(this,Ke,"f")?c(this,G,"m",Yr).call(this,R):void 0,Ne=ke?.tool_call_identities.get(ne);if(Ne){if(ec(ue,Ne),Dr!==void 0&&Dr!==Ne.type||Ie!==void 0&&Ie!==Ne.name)throw new m("Chat completion stream contains a changed tool call identity")}if(ps(ue,Xo),zo)ue.id=zo;if(Dr)ue.type=Dr;if(ft){let Me=ue.custom??(ue.custom={name:ft.name??"",input:""});if(ft.name)Me.name=ft.name;if(ft.input)Me.input+=ft.input}if(Ln){let Me=ue.function??(ue.function={name:Ie??"",arguments:""});if(Ie)Me.name=Ie;if(ke&&!Ne){let Ce=ji(ue),ea=Ce&&c(this,ie,"f")?.tools?.find((nt)=>at(nt)&&nt.function.name===Ce.name);if(Ce){if(Ne={...Ce,parseable:ea!==void 0&&_i(c(this,ie,"f"),{type:Ce.type,function:{name:Ce.name}})},ke.tool_call_identities.set(ne,Ne),!Ne.parseable){let nt=ke.tool_call_parse_states.get(ne);if(nt)c(this,De,"f").bytes-=nt.bytes,c(this,De,"f").fragments-=nt.fragments,c(this,De,"f").work-=nt.work,ke.tool_call_parse_states.delete(ne)}}}let pt=Ln.arguments;if(pt!=null)if(Ho=pt,ke&&Ne?.parseable!==!1){let Ce=ke.tool_call_parse_states.get(ne);if(!Ce)Ce=oc(),ke.tool_call_parse_states.set(ne,Ce);let ea=ic(Ce,c(this,De,"f"),pt),nt=ze(Me,"arguments");if(typeof nt!=="string")throw new m("Chat completion stream contains an unsafe structured JSON snapshot");if(Me.arguments=nt+pt,ea&&Ne?.parseable===!0&&ac(Ce,c(this,De,"f")))c(this,G,"m",Qr).call(this,f),Me.parsed_arguments=pl(mr(Me.arguments));else if(pt.length>0&&M(Me,"parsed_arguments"))Me.parsed_arguments=void 0}else Me.arguments+=pt}j.push(Object.freeze({index:ne,arguments_delta:Ho}))}}Object.freeze(j)}return f},Symbol.asyncIterator)](){return this._createIterator((e)=>{let t=(n)=>e(n);return this.on("chunk",t),()=>this.off("chunk",t)},{onReturn:()=>this.abort()})}toReadableStream(){return new Ae(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function nh(e,t,n,s){let{id:o,choices:a,created:u,model:l,system_fingerprint:f,...h}=e,_={...h,id:o,choices:_l(a,$i,"choice",(w)=>{let y=s.get(w);if(!y)throw new m("Chat completion stream contains an unsafe structured JSON snapshot");let P=new Proxy(w,{get(U,W,J){return W==="message"?y.message:Reflect.get(U,W,J)}}),{message:I,finish_reason:x,index:v,logprobs:C,...E}=P,S=new Proxy(I,{get(U,W,J){if(W==="content")return y.content;if(W==="refusal")return y.refusal;if(W==="tool_calls")return y.toolCallCollection;return Reflect.get(U,W,J)}}),{content:j=null,function_call:R,tool_calls:F,audio:k,...T}=S,L=x??(n.has(v)&&sh(k)?"stop":null);if(!L)throw new m(`missing finish_reason for choice ${v}`);let D=k?{audio:k}:{},K=S.role;if(!K)throw new m(`missing role for choice ${v}`);if(R){let{arguments:U,name:W}=R;if(U==null)throw new m(`missing function_call.arguments for choice ${v}`);if(!W)throw new m(`missing function_call.name for choice ${v}`);return{...E,message:{...D,content:j,function_call:{arguments:U,name:W},role:K,refusal:S.refusal??null},finish_reason:L,index:v,logprobs:C}}if(F)return{...E,index:v,finish_reason:L,logprobs:C,message:{...T,...D,role:K,content:j,refusal:S.refusal??null,tool_calls:_l(F,jt,"tool-call",(U,W)=>{let J=y.toolCalls.get(W);if(!J){let ue=ji(U);if(ue&&_i(t,{type:ue.type,function:{name:ue.name}}))throw new m("Chat completion stream contains an unsafe structured JSON snapshot")}if(J&&J.tool!==U)throw new m("Chat completion stream contains a changed tool call identity");let X=J&&new Proxy(J.function,{get(ue,Ie,ke){if(Ie==="arguments")return J.arguments;if(Ie==="name")return J.name;return Reflect.get(ue,Ie,ke)}}),Le=J&&X?new Proxy(U,{get(ue,Ie,ke){if(Ie==="type")return J.type;if(Ie==="function")return X;return Reflect.get(ue,Ie,ke)}}):U;if(Le.type==null)throw new m(`missing choices[${v}].tool_calls[${W}].type`);if(Le.type==="custom"){let{custom:ue,type:Ie,id:ke,...Ne}=Le,{input:Me="",name:pt,...Ce}=ue||{};if(pt==null)throw new m(`missing choices[${v}].tool_calls[${W}].custom.name`);return{...Ne,id:ke||`call_${Ve()}`,type:Ie,custom:{...Ce,name:pt,input:Me}}}let{function:ne,type:zo,id:Dr,...Ln}=Le,{arguments:ft,name:Xo,...Ho}=ne||{};if(Xo==null)throw new m(`missing choices[${v}].tool_calls[${W}].function.name`);if(ft==null)throw new m(`missing choices[${v}].tool_calls[${W}].function.arguments`);return{...Ln,id:Dr||`call_${Ve()}`,type:zo,function:{...Ho,name:Xo,arguments:ft}}})}};return{...E,message:{...T,...D,content:j,role:K,refusal:S.refusal??null},finish_reason:L,index:v,logprobs:C}}),created:u,model:l,object:"chat.completion",...f?{system_fingerprint:f}:{}};return zu(_,t)}function sh(e){return e?.id!=null&&e.data!=null&&e.transcript!=null&&e.expires_at!=null}function bl(e){}function wl(e){return e}class en extends Lt{static fromReadableStream(e){let t=new en(null);return t._run(()=>t._fromReadableStream(e)),t}toReadableStream(){let e,t,n=this._createIterator((o)=>{let a=(l)=>{e=l,o(l)},u=(l)=>{if(It(l)){t=l.tool_calls?.map((f)=>f.id);return}if(es(l)){if(!e)throw new m("cannot serialize a tool message before receiving any chunks");o(Al(e,l,t)),t=void 0}};return this.on("chunk",a),this.on("message",u),()=>{this.off("chunk",a),this.off("message",u)}},{onReturn:()=>this.abort()});return new Ae(()=>n,this.controller).toReadableStream()}static runTools(e,t,n){let s=new en(t),o={...n,__metadata:{...n?.__metadata,helperMethod:"runTools"}};return s._run(()=>s._runTools(e,t,s,o)),s}}class Mt extends p{constructor(){super(...arguments);this.messages=new Hr(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Xu(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:"chat.completions.parse"}})._thenUnwrap((n)=>Zn(n,e))}runTools(e,t){if(e.stream)return en.runTools(this._client,e,t);return ls.runTools(this._client,e,t)}stream(e,t){return Lt.createChatCompletion(this._client,e,t)}}Mt.Messages=Hr;class _r extends p{constructor(){super(...arguments);this.completions=new Mt(this._client)}}_r.Completions=Mt;class ms extends p{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}class _s extends p{list(e={},t){return this._client.getAPIList("/organization/audit_logs",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}class ys extends p{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(d`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",ye,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",ye,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}}class gs extends p{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/data_retention",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}}class bs extends p{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}class ws extends p{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",re,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}class As extends p{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}class Ps extends p{retrieve(e){return this._client.get("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/spend_limit",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}}class Is extends p{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get("/organization/usage/completions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get("/organization/costs",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get("/organization/usage/embeddings",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get("/organization/usage/images",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get("/organization/usage/moderations",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}class xs extends p{create(e,t,n){return this._client.post(d`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:s}=t;return this._client.get(d`/organization/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/groups/${e}/roles`,re,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:s}=t;return this._client.delete(d`/organization/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class Ss extends p{create(e,t,n){return this._client.post(d`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:s}=t;return this._client.get(d`/organization/groups/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/groups/${e}/users`,re,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:s}=t;return this._client.delete(d`/organization/groups/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class yr extends p{constructor(){super(...arguments);this.users=new Ss(this._client),this.roles=new xs(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",re,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}yr.Users=Ss;yr.Roles=xs;class Rs extends p{retrieve(e,t,n){let{project_id:s}=t;return this._client.get(d`/organization/projects/${s}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/api_keys`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/organization/projects/${s}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class vs extends p{list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/certificates`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(d`/organization/projects/${e}/certificates/activate`,ye,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(d`/organization/projects/${e}/certificates/deactivate`,ye,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}}class Es extends p{retrieve(e,t){return this._client.get(d`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}}class Os extends p{retrieve(e,t){return this._client.get(d`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}}class ks extends p{retrieve(e,t){return this._client.get(d`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}}class Cs extends p{listRateLimits(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/rate_limits`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/organization/projects/${s}/rate_limits/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}}class Ts extends p{create(e,t,n){return this._client.post(d`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(d`/projects/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/projects/${s}/roles/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/projects/${e}/roles`,re,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/projects/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class $s extends p{create(e,t,n){return this._client.post(d`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(d`/organization/projects/${s}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/organization/projects/${s}/spend_alerts/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/spend_alerts`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/organization/projects/${s}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class js extends p{retrieve(e,t){return this._client.get(d`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/projects/${e}/spend_limit`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}}class Ls extends p{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/projects/${s}/groups/${e}/roles`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,group_id:o}=t;return this._client.get(d`/projects/${s}/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:s,...o}=t;return this._client.getAPIList(d`/projects/${s}/groups/${e}/roles`,re,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s,group_id:o}=t;return this._client.delete(d`/projects/${s}/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class tn extends p{constructor(){super(...arguments);this.roles=new Ls(this._client)}create(e,t,n){return this._client.post(d`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,...o}=t;return this._client.get(d`/organization/projects/${s}/groups/${e}`,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/groups`,re,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/organization/projects/${s}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}tn.Roles=Ls;class Ms extends p{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/organization/projects/${s}/service_accounts/${e}/api_keys`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}}class rn extends p{constructor(){super(...arguments);this.apiKeys=new Ms(this._client)}create(e,t,n){return this._client.post(d`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(d`/organization/projects/${s}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/organization/projects/${s}/service_accounts/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/service_accounts`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/organization/projects/${s}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}rn.APIKeys=Ms;class Bs extends p{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/projects/${s}/users/${e}/roles`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,user_id:o}=t;return this._client.get(d`/projects/${s}/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:s,...o}=t;return this._client.getAPIList(d`/projects/${s}/users/${e}/roles`,re,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s,user_id:o}=t;return this._client.delete(d`/projects/${s}/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class nn extends p{constructor(){super(...arguments);this.roles=new Bs(this._client)}create(e,t,n){return this._client.post(d`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(d`/organization/projects/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/organization/projects/${s}/users/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/users`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/organization/projects/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}nn.Roles=Bs;class ge extends p{constructor(){super(...arguments);this.users=new nn(this._client),this.serviceAccounts=new rn(this._client),this.apiKeys=new Rs(this._client),this.rateLimits=new Cs(this._client),this.modelPermissions=new ks(this._client),this.hostedToolPermissions=new Os(this._client),this.groups=new tn(this._client),this.roles=new Ts(this._client),this.dataRetention=new Es(this._client),this.spendLimit=new js(this._client),this.spendAlerts=new $s(this._client),this.certificates=new vs(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(d`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}}ge.Users=nn;ge.ServiceAccounts=rn;ge.APIKeys=Rs;ge.RateLimits=Cs;ge.ModelPermissions=ks;ge.HostedToolPermissions=Os;ge.Groups=tn;ge.Roles=Ts;ge.DataRetention=Es;ge.SpendLimit=js;ge.SpendAlerts=$s;ge.Certificates=vs;class Ds extends p{create(e,t,n){return this._client.post(d`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:s}=t;return this._client.get(d`/organization/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/users/${e}/roles`,re,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:s}=t;return this._client.delete(d`/organization/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class sn extends p{constructor(){super(...arguments);this.roles=new Ds(this._client)}retrieve(e,t){return this._client.get(d`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}sn.Roles=Ds;class be extends p{constructor(){super(...arguments);this.auditLogs=new _s(this._client),this.adminAPIKeys=new ms(this._client),this.usage=new Is(this._client),this.invites=new bs(this._client),this.users=new sn(this._client),this.groups=new yr(this._client),this.roles=new ws(this._client),this.dataRetention=new gs(this._client),this.spendLimit=new Ps(this._client),this.spendAlerts=new As(this._client),this.certificates=new ys(this._client),this.projects=new ge(this._client)}}be.AuditLogs=_s;be.AdminAPIKeys=ms;be.Usage=Is;be.Invites=bs;be.Users=sn;be.Groups=yr;be.Roles=ws;be.DataRetention=gs;be.SpendLimit=Ps;be.SpendAlerts=As;be.Certificates=ys;be.Projects=ge;class gr extends p{constructor(){super(...arguments);this.organization=new be(this._client)}}gr.Organization=be;class Ns extends p{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:b([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class Fs extends p{create(e,t){return this._client.post("/audio/transcriptions",oe({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class Ws extends p{create(e,t){return this._client.post("/audio/translations",oe({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class xt extends p{constructor(){super(...arguments);this.transcriptions=new Fs(this._client),this.translations=new Ws(this._client),this.speech=new Ns(this._client)}}xt.Transcriptions=Fs;xt.Translations=Ws;xt.Speech=Ns;class on extends p{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",O,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(d`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}}class Us extends p{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/assistants/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/assistants/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",O,{query:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/assistants/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}}class qs extends p{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}}class Ks extends p{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}}class br extends p{constructor(){super(...arguments);this.sessions=new qs(this._client),this.transcriptionSessions=new Ks(this._client)}}br.Sessions=qs;br.TranscriptionSessions=Ks;class zs extends p{create(e,t,n){return this._client.post(d`/agents/environments/${e}/files`,{body:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/agents/environments/${e}/files`,Hn,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class Xs extends p{create(e={},t){return this._client.post("/agents/environments/templates",{body:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/agents/environments/templates/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(d`/agents/environments/templates/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents/environments/templates",O,{query:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/agents/environments/templates/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}class wr extends p{constructor(){super(...arguments);this.files=new zs(this._client),this.templates=new Xs(this._client)}retrieve(e,t){return this._client.get(d`/agents/environments/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}wr.Files=zs;wr.Templates=Xs;var an,Li,Ar,Mi;class dc{constructor(){an.set(this,void 0),Li.set(this,!1),Ar.set(this,new Set),Mi.set(this,new Set)}accept(e){if(c(this,Ar,"f").has(e.event_id))return!1;if(c(this,Ar,"f").size===1024){let t=c(this,Ar,"f").values().next();if(!t.done)c(this,Ar,"f").delete(t.value)}if(c(this,Ar,"f").add(e.event_id),e.type==="agent.session.turn.created"&&e.turn.subagent_id===null&&c(this,an,"f")===void 0)A(this,an,e.turn_id,"f");if((e.type==="agent.session.turn.completed"||e.type==="agent.session.turn.failed"||e.type==="agent.session.turn.cancelled")&&c(this,an,"f")!==void 0&&e.turn_id===c(this,an,"f"))A(this,Li,!0,"f");return!0}terminal(e){return e.type==="agent.session.failed"||e.type==="agent.session.idle"&&c(this,Li,"f")}call(e){if(e.type!=="agent.session.turn.item.added"||e.item.type!=="function_call")return;let t=e.item,n=JSON.stringify([t.turn_id,t.call_id]);if(c(this,Mi,"f").has(n))return;return c(this,Mi,"f").add(n),t}}an=new WeakMap,Li=new WeakMap,Ar=new WeakMap,Mi=new WeakMap;var ae,Bi,un,Di,Ni,Pr,Ir,Fi,Wi,ln,Hs,Rl,xl,Ze,fc,pc,Sl;function Hh(e){if(!me(e))return!1;let t=e,n;if(t.type==="input_text")n="text";else if(t.type==="input_image")n="image_url";else return!1;return M(t,"type")&&M(t,n)&&typeof t[n]==="string"}function Jh(e){if(e===null)return null;if(typeof e==="string"||Array.isArray(e)&&e.every(Hh))return e;throw new m("Tool output must be text, content, a JSON object, or null")}function Vh(e,t){let n=me(t)?JSON.stringify(t):t,s=JSON.stringify(n);if(s===void 0)throw new m("Tool output must be JSON serializable");return{type:"agent.session.input.tool_result",turn_id:e.turn_id,call_id:e.call_id,success:!0,output:Jh(typeof n==="string"?n:JSON.parse(s))}}async function Gh(e){try{await e?.body?.cancel()}catch{}}class hc{constructor(e,t,n,s){ae.add(this),this.controller=new AbortController,Bi.set(this,!1),un.set(this,void 0),Di.set(this,void 0),Ni.set(this,!1),Pr.set(this,void 0),Ir.set(this,void 0),Fi.set(this,void 0),Wi.set(this,void 0),ln.set(this,void 0),Hs.set(this,void 0);let o=typeof n.input==="string"?[{role:"user",content:[{type:"input_text",text:n.input}]}]:n.input;if(n.input.length===0)throw new m("input must not be empty");A(this,Pr,e,"f"),A(this,Ir,t,"f"),A(this,Fi,{type:"agent.session.input.message",input:o},"f"),A(this,Wi,new Map(Object.entries(n.toolHandlers??{})),"f");let a=b([s?.headers]);A(this,ln,a.nulls.has("idempotency-key")?void 0:a.values.get("idempotency-key")??n.idempotencyKey??s?.idempotencyKey??Ve(),"f"),a.values.delete("idempotency-key"),a.nulls.delete("idempotency-key");let{idempotencyKey:u,...l}=s??{};A(this,Hs,{...l,headers:a},"f")}abort(e){if(this.controller.abort(e),c(this,un,"f")?.controller.abort(this.controller.signal.reason),!c(this,Ni,"f"))Gh(c(this,Di,"f"))}[(Bi=new WeakMap,un=new WeakMap,Di=new WeakMap,Ni=new WeakMap,Pr=new WeakMap,Ir=new WeakMap,Fi=new WeakMap,Wi=new WeakMap,ln=new WeakMap,Hs=new WeakMap,ae=new WeakSet,Symbol.asyncIterator)](){if(c(this,Bi,"f"))throw new m("An AgentSessionStream can only be consumed once");return A(this,Bi,!0,"f"),c(this,ae,"m",Rl).call(this)}}Rl=async function*(){let t=c(this,Hs,"f").signal,n=()=>this.abort(t?.aborted?t.reason:this.controller.signal.reason);t?.addEventListener("abort",n,{once:!0}),this.controller.signal.addEventListener("abort",n,{once:!0});let s={...c(this,Hs,"f"),signal:this.controller.signal},o=new dc;try{if(t?.aborted)this.abort(t.reason);if(c(this,ae,"m",Ze).call(this),(await c(this,Pr,"f").retrieve(c(this,Ir,"f"),s)).status!=="idle")throw new m("sessions.stream requires an idle session; use sessions.events.stream for active sessions");let u=await c(this,Pr,"f").events.stream(c(this,Ir,"f"),s).withResponse();A(this,un,u.data,"f"),A(this,Di,u.response,"f"),c(this,ae,"m",Ze).call(this),await c(this,Pr,"f").events.create(c(this,Ir,"f"),{events:[c(this,Fi,"f")],...c(this,ln,"f")===void 0?{}:{"Idempotency-Key":c(this,ln,"f")}},{...s,headers:b([s.headers,{"Idempotency-Key":c(this,ln,"f")??null}])}),c(this,ae,"m",Ze).call(this),A(this,Ni,!0,"f");for await(let l of c(this,un,"f")){if(c(this,ae,"m",Ze).call(this),!o.accept(l))continue;let f=o.terminal(l),h=o.call(l),_=h&&c(this,Wi,"f").get(h.name),w=h&&_?structuredClone(h):void 0;if(f)c(this,un,"f").controller.abort();if(yield l,f)return;if(c(this,ae,"m",Ze).call(this),!w||!_)continue;let y=await c(this,ae,"m",xl).call(this,w,_);c(this,ae,"m",Ze).call(this),await c(this,ae,"m",Sl).call(this,y,s)}throw c(this,ae,"m",Ze).call(this),new m("Session event stream ended before the turn reached idle or failed")}finally{t?.removeEventListener("abort",n),this.controller.signal.removeEventListener("abort",n),this.abort()}},xl=async function(t,n){try{let s=typeof t.arguments==="string"?JSON.parse(t.arguments):t.arguments;if(!me(s))throw new m("Function arguments must be a JSON object");return Vh(t,await c(this,ae,"m",pc).call(this,()=>n(s)))}catch{return c(this,ae,"m",Ze).call(this),{type:"agent.session.input.tool_result",turn_id:t.turn_id,call_id:t.call_id,success:!1,error:"Tool handler failed."}}},Ze=function(){if(this.controller.signal.aborted)throw c(this,ae,"m",fc).call(this)},fc=function(){let t=new Z;return Object.defineProperty(t,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),t},pc=async function(t){let n,s=new Promise((o,a)=>{n=()=>a(c(this,ae,"m",fc).call(this)),this.controller.signal.addEventListener("abort",n,{once:!0})});try{c(this,ae,"m",Ze).call(this);let o=async()=>await t();return await Promise.race([o(),s])}finally{if(n)this.controller.signal.removeEventListener("abort",n)}},Sl=async function e(t,n,s=Ve(),o=0){c(this,ae,"m",Ze).call(this);try{await c(this,Pr,"f").events.create(c(this,Ir,"f"),{events:[t],"Idempotency-Key":s},n)}catch(a){let u=[100,300,600][o];if(u===void 0||!(a instanceof mt)||a.code!=="invalid_request_error"||!a.error||!("message"in a.error)||a.error.message!==`Unknown pending tool call: ${t.call_id}`)throw a;let l;try{await c(this,ae,"m",pc).call(this,()=>new Promise((f)=>{l=setTimeout(f,u)}))}finally{if(l!==void 0)clearTimeout(l)}await c(this,ae,"m",e).call(this,t,n,s,o+1)}};class Js extends p{retrieve(e,t,n){let{session_id:s}=t;return this._client.get(d`/agents/sessions/${s}/artifacts/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/agents/sessions/${e}/artifacts`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{session_id:s}=t;return this._client.delete(d`/agents/sessions/${s}/artifacts/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}content(e,t,n){let{session_id:s}=t;return this._client.get(d`/agents/sessions/${s}/artifacts/${e}/content`,{...n,headers:b([{"OpenAI-Beta":"agents=v1",Accept:"application/octet-stream"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class Vs extends p{create(e,t,n){let{"Idempotency-Key":s,...o}=t;return this._client.post(d`/agents/sessions/${e}/events`,{body:o,...n,headers:b([{"OpenAI-Beta":"agents=v1",Accept:"*/*",...s!=null?{"Idempotency-Key":s}:void 0},n?.headers]),__security:{bearerAuth:!0}})}stream(e,t){return this._client.get(d`/agents/sessions/${e}/events`,{...t,headers:b([{"OpenAI-Beta":"agents=v1",Accept:"text/event-stream"},t?.headers]),stream:!0,__security:{bearerAuth:!0}})}}class Gs extends p{list(e,t={},n){return this._client.getAPIList(d`/agents/sessions/${e}/items`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class Ys extends p{retrieve(e,t,n){let{session_id:s}=t;return this._client.get(d`/agents/sessions/${s}/turns/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/agents/sessions/${e}/turns`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class Qs extends p{list(e,t,n){let{session_id:s,...o}=t;return this._client.getAPIList(d`/agents/sessions/${s}/subagents/${e}/items`,O,{query:o,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class Zs extends p{list(e,t,n){let{session_id:s,subagent_id:o,...a}=t;return this._client.getAPIList(d`/agents/sessions/${s}/subagents/${o}/turns/${e}/items`,O,{query:a,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class dn extends p{constructor(){super(...arguments);this.items=new Zs(this._client)}retrieve(e,t,n){let{session_id:s,subagent_id:o}=t;return this._client.get(d`/agents/sessions/${s}/subagents/${o}/turns/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{session_id:s,...o}=t;return this._client.getAPIList(d`/agents/sessions/${s}/subagents/${e}/turns`,O,{query:o,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}dn.Items=Zs;class xr extends p{constructor(){super(...arguments);this.items=new Qs(this._client),this.turns=new dn(this._client)}retrieve(e,t,n){let{session_id:s}=t;return this._client.get(d`/agents/sessions/${s}/subagents/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/agents/sessions/${e}/subagents`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}xr.Items=Qs;xr.Turns=dn;class lt extends p{constructor(){super(...arguments);this.subagents=new xr(this._client),this.artifacts=new Js(this._client),this.items=new Gs(this._client),this.events=new Vs(this._client),this.turns=new Ys(this._client)}stream(e,t,n){return new hc(this,e,t,n)}create(e,t){return this._client.post("/agents/sessions",{body:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/agents/sessions/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(d`/agents/sessions/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents/sessions",O,{query:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/agents/sessions/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}lt.Subagents=xr;lt.Artifacts=Js;lt.Items=Gs;lt.Events=Vs;lt.Turns=Ys;class eo extends p{create(e,t,n){return this._client.post(d`/vaults/${e}/credentials`,{body:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vault_id:s}=t;return this._client.get(d`/vaults/${s}/credentials/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vault_id:s,...o}=t;return this._client.post(d`/vaults/${s}/credentials/${e}`,{body:o,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/vaults/${e}/credentials`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vault_id:s}=t;return this._client.delete(d`/vaults/${s}/credentials/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class fn extends p{constructor(){super(...arguments);this.credentials=new eo(this._client)}create(e={},t){return this._client.post("/vaults",{body:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/vaults/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vaults",O,{query:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/vaults/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}fn.Credentials=eo;class Bt extends p{constructor(){super(...arguments);this.environments=new wr(this._client),this.vaults=new fn(this._client),this.sessions=new lt(this._client)}create(e,t){return this._client.post("/agents",{body:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/agents/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(d`/agents/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents",O,{query:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/agents/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}Bt.Environments=wr;Bt.Vaults=fn;Bt.Sessions=lt;class to extends p{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(d`/chatkit/sessions/${e}/cancel`,{...t,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}}class ro extends p{retrieve(e,t){return this._client.get(d`/chatkit/threads/${e}`,{...t,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",q,{query:e,...t,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/chatkit/threads/${e}`,{...t,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(d`/chatkit/threads/${e}/items`,q,{query:t,...n,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class Sr extends p{constructor(){super(...arguments);this.sessions=new to(this._client),this.threads=new ro(this._client)}}Sr.Sessions=to;Sr.Threads=ro;class no extends p{list(e,t={},n){let{betas:s,...o}=t??{};return this._client.getAPIList(d`/responses/${e}/input_items?beta=true`,O,{query:o,...n,headers:b([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}}class so extends p{count(e={},t){let{betas:n,...s}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:s,...t,headers:b([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}}class Rr extends p{constructor(){super(...arguments);this.inputItems=new no(this._client),this.inputTokens=new so(this._client)}create(e,t){let{betas:n,...s}=e;return this._client.post("/responses?beta=true",{body:s,...t,headers:b([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},n){let{betas:s,...o}=t??{};return this._client.get(d`/responses/${e}?beta=true`,{query:o,...n,headers:b([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},n){let{betas:s}=t??{};return this._client.delete(d`/responses/${e}?beta=true`,{...n,headers:b([{Accept:"*/*",...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},n){let{betas:s}=t??{};return this._client.post(d`/responses/${e}/cancel?beta=true`,{...n,headers:b([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:n,...s}=e;return this._client.post("/responses/compact?beta=true",{body:s,...t,headers:b([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}}Rr.InputItems=no;Rr.InputTokens=so;class oo extends p{create(e,t,n){return this._client.post(d`/threads/${e}/messages`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/messages/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/messages/${e}`,{body:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/threads/${e}/messages`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:s}=t;return this._client.delete(d`/threads/${s}/messages/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}class io extends p{retrieve(e,t,n){let{thread_id:s,run_id:o,...a}=t;return this._client.get(d`/threads/${s}/runs/${o}/steps/${e}`,{query:a,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:s,...o}=t;return this._client.getAPIList(d`/threads/${s}/runs/${e}/steps`,O,{query:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}var Ui=(e)=>{if(typeof globalThis.Buffer<"u"){let t=globalThis.Buffer.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(typeof atob<"u"){let t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}throw new m("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},vl=(e)=>{if(typeof Buffer<"u"){let t=Buffer.from(e,"base64");if(t.length%Float32Array.BYTES_PER_ELEMENT!==0)throw RangeError("Invalid base64-encoded float32 array: byte length must be a multiple of 4");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,s=new Uint8Array(n);for(let o=0;o<n;o++)s[o]=t.charCodeAt(o);return Array.from(new Float32Array(s.buffer))}};var Ee=(e)=>{try{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0}catch{return}return};var Ol=1024,ym=65536;function gm(e){switch(e){case"value":case"arguments":case"input":case"text":case"content":case"annotations":case"metadata":case"name":case"role":case"status":case"tool_calls":case"step_details":return e;default:return"unknown"}}var ao=new WeakMap,Dt=new WeakSet;function kl(e){return{arrays:new Map,cacheArrays:e,records:new WeakMap}}function Cl(e){for(let[t,n]of e.arrays)if(n.cacheable&&!Dt.has(t))ao.set(t,{length:n.length,ownEntryCount:n.ownEntryCount});else ao.delete(t)}function El(e){return typeof e==="string"||typeof e==="number"}function Tl(e,t){return t.every(El)&&e.every(El)}function bm(e){let t=0;for(let n of Object.keys(e)){let s=Number(n);if(Number.isSafeInteger(s)&&s>=0&&s<e.length&&String(s)===n)t+=1}return t}function wm(e,t,n){if(!t)return 0;if(n?.length===e.length)return n.ownEntryCount;return bm(e)}function Am(e,t,n){let{index:s}=e;if(t==="array"&&(s===null||s===void 0))throw Error("Expected array delta entry to have an `index` property");if(t==="array"&&typeof s!=="number")throw TypeError("Expected array delta entry `index` property to be a number but got an invalid value");if(!Number.isSafeInteger(s)||s<0||s>=n+Ol||s>=ym)throw new m(`Assistant stream delta contains an invalid ${t} index: ${typeof s==="number"?s:"unknown"}`);return s}function $l(e,t,n,s,o){let a=s.arrays.get(e);if(!a){let u=s.cacheArrays&&!Dt.has(e),l=u?ao.get(e):void 0;a={baselineLength:e.length,cacheable:u,enforceSparseHoleBudget:u,entries:new Map,length:e.length,ownEntryCount:wm(e,u,l)},s.arrays.set(e,a)}for(let u of t){if(!me(u))throw Error("Expected array delta entry to be an object but got an invalid value");let l=Am(u,n,a.baselineLength),f;if(a.entries.has(l))f=a.entries.get(l);else if(M(e,l)){if(f=e[l],f===null||f===void 0)a.entries.set(l,u)}else a.entries.set(l,u),a.ownEntryCount+=1;let h=Math.max(a.length,l+1);if(a.enforceSparseHoleBudget&&h-a.ownEntryCount>Ol)throw new m(`Assistant stream delta contains an invalid ${n} index: ${l}`);if(me(f))o(f,u,s);a.length=h}}function qi(e,t,n){let s=n.records.get(e);for(let[o,a]of Object.entries(t)){if(o==="index"||o==="type")continue;let u;if(s?.has(o))u=s.get(o);else if(M(e,o))u=e[o];if(u===null||u===void 0){if(!s)s=new Map,n.records.set(e,s);s.set(o,a);continue}if(me(u)&&me(a))qi(u,a,n);else if(Array.isArray(u)&&Array.isArray(a)&&!Tl(u,a))$l(u,a,"array",n,qi)}}function Ki(e){return(me(e)||Array.isArray(e))&&Dt.has(e)}function et(e){if(!me(e)&&!Array.isArray(e)||Dt.has(e))return;if(Dt.add(e),Array.isArray(e))ao.delete(e);for(let t of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,t);if(n&&"value"in n)et(n.value)}}function _c(e,t,n){if(Dt.has(e))et(n);Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function Pm(e){let{index:t}=e;if(t===null||t===void 0)throw Error("Expected array delta entry to have an `index` property");if(typeof t!=="number")throw TypeError("Expected array delta entry `index` property to be a number but got an invalid value");return t}function Im(e,t,n){if(Tl(e,t)){e.push(...t),ao.delete(e);return}for(let s of t){if(!me(s))throw Error("Expected array delta entry to be an object but got an invalid value");let o=Pm(s);if(M(e,o)){let a=e[o];if(a===null||a===void 0){if(Dt.has(e))et(s);e[o]=s}else e[o]=n(a,s)}else _c(e,o,s)}}function mc(e,t){let n=Dt.has(e);for(let[s,o]of Object.entries(t)){if(s==="__proto__"||s==="constructor"||s==="prototype")throw new m(`Assistant stream delta contains an unsafe property: ${s}`);if(!M(e,s)){if(n)et(o);e[s]=o;continue}let a=e[s];if(a===null||a===void 0){if(n)et(o);e[s]=o;continue}if(s==="index"||s==="type"){e[s]=o;continue}if(typeof a==="string"&&typeof o==="string")a+=o;else if(typeof a==="number"&&typeof o==="number")a+=o;else if(me(a)&&me(o))a=mc(a,o);else if(Array.isArray(a)&&Array.isArray(o)){Im(a,o,mc);continue}else throw TypeError(`Unhandled record type: ${gm(s)}`);e[s]=a}return e}function co(e){if(!me(e)&&!Array.isArray(e))return;for(let[t,n]of Object.entries(e)){if(t==="__proto__"||t==="constructor"||t==="prototype")throw new m(`Assistant stream delta contains an unsafe property: ${t}`);co(n)}}function zi(e,t,n=!1){co(t);let s=e,o=t,a=kl(n&&!Ki(e));return qi(s,o,a),mc(s,o),Cl(a),e}function jl(e,t,n,s=!0){co(t);let o=kl(s&&!Ki(e));return $l(e,t,n,o,qi),()=>Cl(o)}var B,Oe,Nt,He,mn,hn,Pe,St,Er,Ft,Rt,vr,$e,lo,fo,Wt,po,ho,Ll,pn,Ml,uo,Bl,Dl,ce,Nl,Fl,Wl,Ul,ql;function xm(e){let t=Object.getOwnPropertyDescriptor(e,"event"),n=Object.getOwnPropertyDescriptor(e,"data"),s=Reflect.get(e,"event",e),o=Reflect.get(e,"data",e),a=o;if(s==="thread.message.created"||s==="thread.message.in_progress"||s==="thread.message.delta"||s==="thread.message.completed"||s==="thread.message.incomplete"||s==="thread.run.step.created"||s==="thread.run.step.in_progress"||s==="thread.run.step.delta"||s==="thread.run.step.completed"||s==="thread.run.step.failed"||s==="thread.run.step.cancelled"||s==="thread.run.step.expired"){let f=Object.getOwnPropertyDescriptor(o,"id");if(f&&"value"in f&&o.id!==f.value){let h=f.value;a=new Proxy(o,{get(_,w){return w==="id"?h:Reflect.get(_,w,_)}})}}let u=Object.freeze({event:s,data:a}),l=t!==void 0&&"value"in t&&t.value===s&&n!==void 0&&"value"in n&&n.value===o&&a===o;return{event:u,exposedEvent:l?e:{event:s,data:a}}}class tt extends fr{constructor(){super(...arguments);B.add(this),Oe.set(this,Object.create(null)),Nt.set(this,new Map),He.set(this,void 0),mn.set(this,Object.create(null)),hn.set(this,new Map),Pe.set(this,void 0),St.set(this,void 0),Er.set(this,void 0),Ft.set(this,void 0),Rt.set(this,void 0),vr.set(this,void 0),$e.set(this,void 0),lo.set(this,void 0),fo.set(this,void 0),Wt.set(this,void 0)}[(Oe=new WeakMap,Nt=new WeakMap,He=new WeakMap,mn=new WeakMap,hn=new WeakMap,Pe=new WeakMap,St=new WeakMap,Er=new WeakMap,Ft=new WeakMap,Rt=new WeakMap,vr=new WeakMap,$e=new WeakMap,lo=new WeakMap,fo=new WeakMap,Wt=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){return this._createIterator((e)=>{let t=(n)=>e(structuredClone(n));return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}static fromReadableStream(e){let t=new tt;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=Ae.fromReadableStream(e,this.controller);for await(let s of n)c(this,B,"m",po).call(this,s);if(n.controller.signal?.aborted)throw this._userAbortError();return this._addRun(c(this,B,"m",ho).call(this))}toReadableStream(){return new Ae(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s){let o=new tt;return o._run(()=>o._runToolAssistantStream(e,t,n,{...s,__metadata:{...s?.__metadata,helperMethod:"stream"}})),o}async _createToolAssistantStream(e,t,n,s){this._listenForAbort(s?.signal);let o={...n,stream:!0},a=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let u of a)c(this,B,"m",po).call(this,u);if(a.controller.signal?.aborted)throw this._userAbortError();return this._addRun(c(this,B,"m",ho).call(this))}static createThreadAssistantStream(e,t,n){let s=new tt;return s._run(()=>s._threadAssistantStream(e,t,{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}static createAssistantStream(e,t,n,s){let o=new tt;return o._run(()=>o._runAssistantStream(e,t,n,{...s,__metadata:{...s?.__metadata,helperMethod:"stream"}})),o}currentEvent(){return et(c(this,lo,"f")),c(this,lo,"f")}currentRun(){return et(c(this,fo,"f")),c(this,fo,"f")}currentMessageSnapshot(){return et(c(this,Pe,"f")),c(this,Pe,"f")}currentRunStepSnapshot(){return et(c(this,Wt,"f")),c(this,Wt,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,Oe,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,mn,"f"))}async finalRun(){if(await this.done(),!c(this,Er,"f"))throw Error("Final run was not received.");return c(this,Er,"f")}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let s={...t,stream:!0},o=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let a of o)c(this,B,"m",po).call(this,a);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(c(this,B,"m",ho).call(this))}async _createAssistantStream(e,t,n,s){this._listenForAbort(s?.signal);let o={...n,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let u of a)c(this,B,"m",po).call(this,u);if(a.controller.signal?.aborted)throw this._userAbortError();return this._addRun(c(this,B,"m",ho).call(this))}static accumulateDelta(e,t){return zi(e,t)}_addRun(e){return c(this,B,"m",ce).call(this,"run",e),e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s){return await this._createToolAssistantStream(t,e,n,s)}}po=function(t){if(this.ended)return;let{event:n,exposedEvent:s}=xm(t),o,a,u,l;switch(n.event){case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{o=c(this,B,"m",Ml).call(this,n),a=n.data;break}case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{u=c(this,B,"m",Ll).call(this,n),l=n.data;break}}if(A(this,lo,s,"f"),c(this,B,"m",Nl).call(this,s),o!==void 0&&a!==void 0)c(this,B,"m",uo).call(this,a,o);if(u!==void 0&&l!==void 0)c(this,B,"m",pn).call(this,l,u);if(u===void 0&&c(this,He,"f")!==void 0&&c(this,Wt,"f"))c(this,B,"m",pn).call(this,c(this,Wt,"f"),c(this,He,"f"));switch(n.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":{c(this,B,"m",ql).call(this,n);break}case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{if(u===void 0)throw new m("Received assistant run-step event without a canonical run-step ID");let f=c(this,Oe,"f")[u];if(f)c(this,B,"m",pn).call(this,f,u);c(this,B,"m",Dl).call(this,n,u),c(this,B,"m",pn).call(this,n.data,u);let h=c(this,Oe,"f")[u];if(h)c(this,B,"m",pn).call(this,h,u);break}case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{if(o!==void 0&&c(this,Pe,"f"))c(this,B,"m",uo).call(this,c(this,Pe,"f"),o);if(c(this,B,"m",Bl).call(this,n),o!==void 0){c(this,B,"m",uo).call(this,n.data,o);let f=c(this,mn,"f")[o];if(f)c(this,B,"m",uo).call(this,f,o)}break}case"error":throw new H(void 0,n.data,void 0,void 0);default:Sm(n)}},ho=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!c(this,Er,"f"))throw Error("Final run has not been received");return c(this,Er,"f")},Ll=function(t){let n=Object.getOwnPropertyDescriptor(t.data,"id"),s=n&&"value"in n?n.value:void 0;if(typeof s!=="string"||s.length===0)throw new m("Received assistant run-step event with an invalid run-step ID");if(t.event==="thread.run.step.delta"){let o=t.data.delta;if(o&&M(o,"id"))throw new m("Run-step deltas must not contain an id field")}if(t.event==="thread.run.step.created"){if(c(this,He,"f")!==void 0)throw new m(`Received run-step creation for "${s}" before the active run step "${c(this,He,"f")}" reached a terminal state`);if(M(c(this,Oe,"f"),s)||c(this,Nt,"f").has(s))throw new m(`Received run-step creation for run step "${s}", which has already been created`);return A(this,He,s,"f"),c(this,Nt,"f").set(s,s),s}if(c(this,He,"f")!==void 0){if(s!==c(this,He,"f"))throw new m(`Received ${t.event} for run step "${s}", which does not match the active run step "${c(this,He,"f")}"`);return s}if(t.event==="thread.run.step.delta"){if(!M(c(this,Oe,"f"),s))throw new m("Received a RunStepDelta before creation of a snapshot");throw new m(`Received run-step delta for "${s}" with no active run step`)}if(M(c(this,Oe,"f"),s)||c(this,Nt,"f").has(s))throw new m(`Received run-step event for run step "${s}", which has already been created`);if(c(this,Nt,"f").set(s,s),t.event==="thread.run.step.in_progress")A(this,He,s,"f");return s},pn=function(t,n){let s=Object.getOwnPropertyDescriptor(t,"id"),o=s&&"value"in s?s.value:void 0;if(typeof o!=="string"||o.length===0)throw new m("Received assistant run-step event with an invalid run-step ID");let a=c(this,Nt,"f").get(o);if(a!==void 0&&a!==n)throw new m(`Received run-step creation for run step "${o}", which has already been created`);c(this,Nt,"f").set(o,n)},Ml=function(t){let n=Object.getOwnPropertyDescriptor(t.data,"id"),s=n&&"value"in n?n.value:void 0;if(typeof s!=="string"||s.length===0)throw new m("Received assistant message event with an invalid message ID");if(t.event==="thread.message.created"){if(c(this,Pe,"f"))throw new m(`Received message creation for "${s}" before the active message "${c(this,St,"f")}" reached a terminal state`);if(M(c(this,mn,"f"),s)||c(this,hn,"f").has(s))throw new m(`Received message creation for message "${s}", which has already been created`);return A(this,St,s,"f"),c(this,hn,"f").set(s,s),s}if(!c(this,Pe,"f")){if(t.event==="thread.message.delta")throw new m("Received a delta with no existing snapshot (there should be one from message creation)");throw new m("Received thread message event with no existing snapshot")}if(s!==c(this,St,"f"))throw new m(`Received ${t.event} for message "${s}", which does not match the active message "${c(this,St,"f")}"`);return s},uo=function(t,n){let s=Object.getOwnPropertyDescriptor(t,"id"),o=s&&"value"in s?s.value:void 0;if(typeof o!=="string"||o.length===0)throw new m("Received assistant message event with an invalid message ID");let a=c(this,hn,"f").get(o);if(a!==void 0&&a!==n)throw new m(`Received message creation for message "${o}", which has already been created`);c(this,hn,"f").set(o,n)},Bl=function(t){let[n,s]=c(this,B,"m",Wl).call(this,t,c(this,Pe,"f"));if(A(this,Pe,n,"f"),!c(this,St,"f"))throw new m("Received thread message event with no active message ID");c(this,mn,"f")[c(this,St,"f")]=n;for(let o of s){let a=n.content[o.index];if(a?.type==="text")c(this,B,"m",ce).call(this,"textCreated",a.text)}switch(t.event){case"thread.message.created":{A(this,Ft,void 0,"f"),A(this,Rt,void 0,"f"),c(this,B,"m",ce).call(this,"messageCreated",t.data);break}case"thread.message.in_progress":break;case"thread.message.delta":{if(c(this,B,"m",ce).call(this,"messageDelta",t.data.delta,n),t.data.delta.content)for(let o of t.data.delta.content){if(o.type==="text"&&o.text){let a=o.text,u=n.content[o.index];if(u&&u.type==="text")c(this,B,"m",ce).call(this,"textDelta",a,u.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!==c(this,Ft,"f")){if(c(this,Rt,"f"))switch(c(this,Rt,"f").type){case"text":{c(this,B,"m",ce).call(this,"textDone",c(this,Rt,"f").text,c(this,Pe,"f"));break}case"image_file":{c(this,B,"m",ce).call(this,"imageFileDone",c(this,Rt,"f").image_file,c(this,Pe,"f"));break}}A(this,Ft,o.index,"f")}A(this,Rt,n.content[o.index],"f")}break}case"thread.message.completed":case"thread.message.incomplete":{if(c(this,Ft,"f")!==void 0){let o=t.data.content[c(this,Ft,"f")];if(o)switch(o.type){case"image_file":{c(this,B,"m",ce).call(this,"imageFileDone",o.image_file,c(this,Pe,"f"));break}case"text":{c(this,B,"m",ce).call(this,"textDone",o.text,c(this,Pe,"f"));break}}}if(c(this,Pe,"f"))c(this,B,"m",ce).call(this,"messageDone",t.data);A(this,Ft,void 0,"f"),A(this,Rt,void 0,"f"),A(this,Pe,void 0,"f"),A(this,St,void 0,"f")}}},Dl=function(t,n){let s=c(this,B,"m",Fl).call(this,t,n);switch(A(this,Wt,s,"f"),t.event){case"thread.run.step.created":{A(this,vr,void 0,"f"),A(this,$e,void 0,"f"),c(this,B,"m",ce).call(this,"runStepCreated",t.data);break}case"thread.run.step.delta":{let o=t.data.delta;if(o.step_details&&o.step_details.type==="tool_calls"&&o.step_details.tool_calls&&s.step_details.type==="tool_calls")for(let a of o.step_details.tool_calls)if(a.index===c(this,vr,"f"))c(this,B,"m",ce).call(this,"toolCallDelta",a,s.step_details.tool_calls[a.index]);else{if(c(this,$e,"f"))c(this,B,"m",ce).call(this,"toolCallDone",c(this,$e,"f"));if(A(this,vr,a.index,"f"),A(this,$e,s.step_details.tool_calls[a.index],"f"),c(this,$e,"f"))c(this,B,"m",ce).call(this,"toolCallCreated",c(this,$e,"f"))}c(this,B,"m",ce).call(this,"runStepDelta",t.data.delta,s);break}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{if(A(this,Wt,void 0,"f"),A(this,He,void 0,"f"),t.data.step_details.type==="tool_calls"&&c(this,$e,"f"))c(this,B,"m",ce).call(this,"toolCallDone",c(this,$e,"f"));c(this,B,"m",ce).call(this,"runStepDone",t.data,s),A(this,vr,void 0,"f"),A(this,$e,void 0,"f");break}case"thread.run.step.in_progress":break}},ce=function(t,...n){if(this._hasListeners(t))for(let s of n)et(s);this._emit(t,...n)},Nl=function(t){c(this,B,"m",ce).call(this,"event",t)},Fl=function(t,n){switch(t.event){case"thread.run.step.created":return c(this,Oe,"f")[n]=t.data,t.data;case"thread.run.step.delta":{let s=c(this,Oe,"f")[n];if(!s)throw Error("Received a RunStepDelta before creation of a snapshot");let o=t.data.delta;if(o){if(M(o,"id"))throw new m("Run-step deltas must not contain an id field");let a=zi(s,o,!0);c(this,Oe,"f")[n]=a}return c(this,Oe,"f")[n]}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":{c(this,Oe,"f")[n]=t.data;break}}if(c(this,Oe,"f")[n])return c(this,Oe,"f")[n];throw Error("No snapshot available")},Wl=function(t,n){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":{if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=t.data;if(o.delta.content){co(o.delta);let a=!Ki(n),u=jl(n.content,o.delta.content,"content",a);for(let l of o.delta.content)if(M(n.content,l.index)){let f=n.content[l.index];n.content[l.index]=c(this,B,"m",Ul).call(this,l,f,a)}else _c(n.content,l.index,l),s.push(l);u()}return[n,s]}case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":{if(n)return[t.event==="thread.message.in_progress"?n:t.data,s];throw Error("Received thread message event with no existing snapshot")}}throw Error("Tried to accumulate a non-message event")},Ul=function(t,n,s){return zi(n,t,s)},ql=function(t){switch(A(this,fo,t.data,"f"),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":{if(A(this,Er,t.data,"f"),c(this,$e,"f"))c(this,B,"m",ce).call(this,"toolCallDone",c(this,$e,"f"));A(this,vr,void 0,"f"),A(this,$e,void 0,"f");break}case"thread.run.cancelling":break}};function Sm(e){return e}function Rm(e,t){return new Promise((n,s)=>{let o,a,u=!1,l=(_)=>{try{t.removeEventListener("abort",_)}catch{}},f=()=>{if(o!==void 0)clearTimeout(o),o=void 0;if(a){let _=a;a=void 0,l(_)}},h=()=>{if(u)return;u=!0,f();try{let _=new Z;Object.defineProperty(_,"cause",{value:t.reason,writable:!0,configurable:!0}),s(_)}catch(_){s(_)}};if(t.aborted){h();return}o=setTimeout(()=>{if(u)return;u=!0,f(),n()},e),a=h;try{if(t.addEventListener("abort",h,{once:!0}),u)l(h);else if(t.aborted)h()}catch(_){if(u)l(h);else u=!0,f(),s(_)}})}async function mo(e,t,n,s){let o=b([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:a,response:u}=await e(o).withResponse(),{status:l}=a;if(t.includes(l)){let f=5000,h=s?.pollIntervalMs;if(h||h===0)f=h;else{let w=u.headers.get("openai-poll-after-ms");if(w){let y=Number.parseInt(w);if(!Number.isNaN(y))f=y}}let _=s&&Object.prototype.propertyIsEnumerable.call(s,"signal")?s.signal:void 0;await(_?Rm(f,_):Fr(f))}else if(n.includes(l))return a}}function Kl(e,t,n,s){return mo((o)=>e.retrieve(t,n,{...s,headers:{...s?.headers,...o}}),["queued","in_progress","cancelling"],["requires_action","incomplete","cancelled","completed","failed","expired"],s)}class _n extends p{constructor(){super(...arguments);this.steps=new io(this._client)}create(e,t,n){let{include:s,...o}=t;return this._client.post(d`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/runs/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}`,{body:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/threads/${e}/runs`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:s}=t;return this._client.post(d`/threads/${s}/runs/${e}/cancel`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,t,n){return tt.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){return await Kl(this,e,t,n)}stream(e,t,n){return tt.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let s=await this.submitToolOutputs(e,t,n);return await this.poll(s.id,t,n)}submitToolOutputsStream(e,t,n){return tt.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}}_n.Steps=io;class Or extends p{constructor(){super(...arguments);this.runs=new _n(this._client),this.messages=new oo(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/threads/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/threads/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/threads/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return tt.createThreadAssistantStream(e,this._client.beta.threads,t)}}Or.Runs=_n;Or.Messages=oo;class Je extends p{constructor(){super(...arguments);this.realtime=new br(this._client),this.agents=new Bt(this._client),this.responses=new Rr(this._client),this.chatkit=new Sr(this._client),this.assistants=new Us(this._client),this.threads=new Or(this._client)}}Je.Realtime=br;Je.Agents=Bt;Je.Responses=Rr;Je.ChatKit=Sr;Je.Assistants=Us;Je.Threads=Or;class yn extends p{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}class _o extends p{retrieve(e,t,n){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}/content`,{...n,headers:b([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class gn extends p{constructor(){super(...arguments);this.content=new _o(this._client)}create(e,t,n){return this._client.post(d`/containers/${e}/files`,Ct({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/containers/${e}/files`,O,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:s}=t;return this._client.delete(d`/containers/${s}/files/${e}`,{...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}}gn.Content=_o;class kr extends p{constructor(){super(...arguments);this.files=new gn(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/containers/${e}`,{...t,headers:b([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}}kr.Files=gn;class bn extends p{create(e,t){return this._client.post("/content_provenance_checks",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}}class yo extends p{create(e,t,n){let{include:s,...o}=t;return this._client.post(d`/conversations/${e}/items`,{query:{include:s},body:o,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:s,...o}=t;return this._client.get(d`/conversations/${s}/items/${e}`,{query:o,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/conversations/${e}/items`,q,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:s}=t;return this._client.delete(d`/conversations/${s}/items/${e}`,{...n,__security:{bearerAuth:!0}})}}class Cr extends p{constructor(){super(...arguments);this.items=new yo(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}}Cr.Items=yo;function zl(e,t,n){let s=!!t.encoding_format,o=s?t.encoding_format:"base64";if(s)te(e).debug("embeddings/user defined encoding_format:",t.encoding_format);let u={body:{...t,encoding_format:o},...n,__security:{bearerAuth:!0}},l=e.post("/embeddings",u);if(s)return l;return te(e).debug("embeddings/decoding base64 embeddings from base64"),l._thenUnwrap((f)=>{let h=f?.data;if(h!==void 0){if(!Array.isArray(h))throw TypeError("Expected embeddings response data to be an array");let{length:_}=h;for(let w=0;w<_;w+=1)if(w in h){let y=h[w],{embedding:P}=y;if(Array.isArray(P))continue;y.embedding=vl(P)}}return f})}class wn extends p{create(e,t){return zl(this._client,e,t)}}class go extends p{retrieve(e,t,n){let{eval_id:s,run_id:o}=t;return this._client.get(d`/evals/${s}/runs/${o}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:s,...o}=t;return this._client.getAPIList(d`/evals/${s}/runs/${e}/output_items`,O,{query:o,...n,__security:{bearerAuth:!0}})}}class An extends p{constructor(){super(...arguments);this.outputItems=new go(this._client)}create(e,t,n){return this._client.post(d`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:s}=t;return this._client.get(d`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/evals/${e}/runs`,O,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:s}=t;return this._client.delete(d`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:s}=t;return this._client.post(d`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}}An.OutputItems=go;class Tr extends p{constructor(){super(...arguments);this.runs=new An(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}}Tr.Runs=An;async function Xl(e,t,n,s){let o=new Set(["processed","error","deleted"]),a=performance.now(),u=await e.retrieve(t);while(!u.status||!o.has(u.status))if(await Fr(n),u=await e.retrieve(t),performance.now()-a>s)throw new le({message:`Giving up on waiting for file ${t} to finish processing after ${s} milliseconds.`});return u}class Pn extends p{create(e,t){return this._client.post("/files",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(d`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(d`/files/${e}/content`,{...t,headers:b([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5000,maxWait:n=1800000}={}){return await Xl(this,e,t,n)}}class bo extends p{}class wo extends p{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t,__security:{bearerAuth:!0}})}}class In extends p{constructor(){super(...arguments);this.graders=new wo(this._client)}}In.Graders=wo;class Ao extends p{create(e,t,n){return this._client.getAPIList(d`/fine_tuning/checkpoints/${e}/permissions`,ye,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(d`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/fine_tuning/checkpoints/${e}/permissions`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(d`/fine_tuning/checkpoints/${s}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class xn extends p{constructor(){super(...arguments);this.permissions=new Ao(this._client)}}xn.Permissions=Ao;class Po extends p{list(e,t={},n){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/checkpoints`,O,{query:t,...n,__security:{bearerAuth:!0}})}}class Sn extends p{constructor(){super(...arguments);this.checkpoints=new Po(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",O,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/events`,O,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}}Sn.Checkpoints=Po;class dt extends p{constructor(){super(...arguments);this.methods=new bo(this._client),this.jobs=new Sn(this._client),this.checkpoints=new xn(this._client),this.alpha=new In(this._client)}}dt.Methods=bo;dt.Jobs=Sn;dt.Checkpoints=xn;dt.Alpha=In;class Io extends p{}class $r extends p{constructor(){super(...arguments);this.graderModels=new Io(this._client)}}$r.GraderModels=Io;class Rn extends p{createVariation(e,t){return this._client.post("/images/variations",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",oe({body:e,...t,stream:e.stream??!1,__metadata:{...t?.__metadata,...e.model==null?{}:{model:e.model}},__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}class xo extends p{accept(e,t,n){return this._client.post(d`/live/sessions/${e}/accept`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}downloadRecording(e,t){return this._client.get(d`/live/sessions/${e}/content`,{...t,headers:b([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}fork(e,t,n){return this._client.post(d`/live/sessions/${e}/fork`,{body:t,...n,__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(d`/live/sessions/${e}/hangup`,{...t,headers:b([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(d`/live/sessions/${e}/refer`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t,n){return this._client.post(d`/live/sessions/${e}/reject`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}}class So extends p{}class Ro extends p{}class vt extends p{constructor(){super(...arguments);this.sideband=new Ro(this._client),this.forks=new So(this._client),this.sessions=new xo(this._client)}create(e,t){return this._client.post("/live/sessions",{body:e,...t,__security:{bearerAuth:!0}})}}vt.Sideband=Ro;vt.Forks=So;vt.Sessions=xo;class vn extends p{retrieve(e,t){return this._client.get(d`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",ye,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/models/${e}`,{...t,__security:{bearerAuth:!0}})}}class En extends p{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}}async function Hl(e,t,n,s=null){if(e.body===null||typeof e.body!=="object"||Array.isArray(e.body))throw TypeError("Multipart request body must be an object");let o=Object.fromEntries(Object.entries(e.body).filter(([,f])=>f!==void 0));if(s!==null&&Object.keys(o).length===1&&Object.prototype.hasOwnProperty.call(o,s)){let f=o[s];if(typeof f!=="string")throw TypeError("Raw multipart alternative must be a string");return{...e,body:f,headers:b([e.headers,{"content-type":n[s].content_type}])}}let a=[];for(let[f,h]of Object.entries(n)){if(!Object.prototype.hasOwnProperty.call(o,f))continue;let _=o[f],w=h.json?JSON.stringify(_):_;if(typeof w!=="string")throw TypeError(`Multipart field ${f} must encode as a string`);a.push([f,At([w],"",{type:h.content_type})]),delete o[f]}let l=(await oe({...e,body:o},t)).body;if(!(l instanceof FormData))throw await l.cancel(),TypeError("Unexpected streaming upload in typed multipart request body");for(let[f,h]of a)l.append(f,h,"");return{...e,body:l,headers:b([e.headers,{"content-type":null}])}}class vo extends p{create(e,t){return this._client.post("/realtime/calls",Hl({body:e,...t,headers:b([{Accept:"application/sdp"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0},this._client,{sdp:{content_type:"application/sdp",json:!1},session:{content_type:"application/json",json:!0}},"sdp"))}accept(e,t,n){return this._client.post(d`/realtime/calls/${e}/accept`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(d`/realtime/calls/${e}/hangup`,{...t,headers:b([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(d`/realtime/calls/${e}/refer`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(d`/realtime/calls/${e}/reject`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}}class Eo extends p{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}}class Ut extends p{constructor(){super(...arguments);this.clientSecrets=new Eo(this._client),this.calls=new vo(this._client)}}Ut.ClientSecrets=Eo;Ut.Calls=vo;function Jl(e,t){if(!t||!Jm(t)){let n={...e,output_parsed:null,output:e.output.map((s)=>{if(s.type==="function_call")return{...s,parsed_arguments:null};if(s.type==="message")return{...s,content:s.content.map((o)=>({...o,parsed:null}))};return s})};if(Vl(e,n))On(n);return n}return gc(e,t)}function gc(e,t){let n=!e.status||e.status==="completed",s=e.output.map((a)=>{if(a.type==="function_call")return n?Gm(t,a):{...a,parsed_arguments:null};if(a.type==="message"){let u=a.content.map((l)=>{if(l.type==="output_text")return{...l,parsed:n?Hm(t,l.text):null};return l});return{...a,content:u}}return a}),o={...e,output:s};if(Vl(e,o))On(o);return Object.defineProperty(o,"output_parsed",{enumerable:!0,get(){for(let a of o.output){if(a.type!=="message")continue;for(let u of a.content)if(u.type==="output_text"&&u.parsed!==null)return u.parsed}return null}}),o}function Hm(e,t){return Pt(e.text?.format,t)}function Jm(e){if(ct(e.text?.format))return!0;return Array.isArray(e.tools)&&e.tools.some((t)=>yc(t)||t.type==="function"&&t.strict===!0||t.type==="namespace"&&t.tools.some((n)=>n.type==="function"&&(yc(n)||n.strict===!0)))}function yc(e){return e?.$brand==="auto-parseable-tool"}function Vm(e,t,n){for(let s of e)if(n==null){if(s.type==="function"&&s.name===t)return s}else if(s.type==="namespace"&&s.name===n)return s.tools.find((o)=>o.type==="function"&&o.name===t);return}function Gm(e,t){let n=Vm(e.tools??[],t.name,t.namespace),s=null;if(yc(n))s=n.$parseRaw(t.arguments);else if(n?.strict)s=Pt({type:"json_schema",$parseRaw:void 0},t.arguments);return{...t,parsed_arguments:s}}function Vl(e,t){return!Object.getOwnPropertyDescriptor(e,"output_text")||t.output_text==null}function On(e){let t=[];for(let n of e.output){if(n.type!=="message")continue;for(let s of n.content)if(s.type==="output_text")t.push(s.text)}e.output_text=t.join("")}class Oo{constructor(){this.capacity=1,this.values=[0,0],this.size=0}get length(){return this.size}append(e){if(this.size===this.capacity)this.grow();let t=this.size;this.size+=1,this.update(t,e)}update(e,t){if(!Number.isSafeInteger(e)||e<0||e>=this.size)throw RangeError(`missing output at index ${e}`);let n=this.capacity+e,s=t-(this.values[n]??0);if(s===0)return;while(n>=1)this.values[n]=(this.values[n]??0)+s,n=Math.floor(n/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw RangeError(`missing output at index ${e}`);let t=this.capacity,n=this.capacity+e,s=0;while(t<n){if(t%2===1)s+=this.values[t]??0,t+=1;if(n%2===1)n-=1,s+=this.values[n]??0;t=Math.floor(t/2),n=Math.floor(n/2)}return s}grow(){let e=this.capacity;this.capacity*=2;let t=Array.from({length:this.capacity*2},()=>0);for(let n=0;n<this.size;n+=1)t[this.capacity+n]=this.values[e+n]??0;for(let n=this.capacity-1;n>0;n-=1)t[n]=(t[n*2]??0)+(t[n*2+1]??0);this.values=t}}function bc(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new Oo}}function kn(e,t){if(t.type!=="message")return"";let n="";for(let s of t.content)if(s.type==="output_text")n+=s.text;return e.outputTextLengths.set(t,n.length),n}function qt(e,t){if(e.canonicalSnapshot===t)return;let n=new Oo,s="";for(let o of t.output){let a=kn(e,o);s+=a,n.append(a.length)}t.output_text=s,e.outputTextIndex=n,e.canonicalSnapshot=t}function Yl(e,t){e.canonicalSnapshot=void 0,e.outputTextLengths=new WeakMap,e.outputTextIndex=new Oo;let n=structuredClone(t);if(!Object.getOwnPropertyDescriptor(n,"output_text")||n.output_text===null||n.output_text===void 0)qt(e,n);else if(n.output.length===0&&n.output_text==="")e.canonicalSnapshot=n;return n}function ko(e,t,n,s,o){let a=e.outputTextLengths.get(t);if(a!==void 0){let u=a-s.length+o.length;e.outputTextLengths.set(t,u),e.outputTextIndex.update(n,u)}}function Gl(e,t,n){if(t.length===0){e.output_text+=n;return}e.output_text=e.output_text.slice(0,e.output_text.length-t.length)+n}function Ym(e,t,n,s){if(n===void 0||t?.type!=="message")return 0;if(n<t.content.length-n-1){let u=0;for(let l=0;l<n;l+=1){let f=t.content[l];if(f?.type==="output_text")u+=f.text.length}return u}let o=0;for(let u=n+1;u<t.content.length;u+=1){let l=t.content[u];if(l?.type==="output_text")o+=l.text.length}return(e.outputTextLengths.get(t)??kn(e,t).length)-o-s.length}function Cn(e,t,n,s,o,a){if(s===o)return;let u=t.output[n];if(n===t.output.length-1&&(a===void 0||u?.type==="message"&&a===u.content.length-1)){Gl(t,s,o);return}let l=Ym(e,u,a,o),f=e.outputTextIndex.prefixSum(n)+l;if(f+s.length===t.output_text.length){Gl(t,s,o);return}t.output_text=t.output_text.slice(0,f)+o+t.output_text.slice(f+s.length)}var wc=new WeakMap;function Kt(e,t,n,s=!1){if(!Array.isArray(e)||!Number.isSafeInteger(t)||t<0||t>e.length||(t===e.length?!s||t in e:!M(e,t)))throw new m(`missing ${n} at index ${t}`)}function Hi(e,t,n){if(t!==e.length)throw new m(`missing ${n} at index ${t}`);Kt(e,t,n,!0)}function N(e,t){Kt(e.output,t,"output");let n=e.output[t];if(!n)throw new m(`missing output at index ${t}`);return n}function Ac(e){return e.type==="function_call"||e.type==="custom_tool_call"||e.type==="shell_call"||e.type==="shell_call_output"}function Ji(e,t){if(!M(e,"type")||typeof e.type!=="string")throw new m(`expected an own output item type for ${t}`);let n=e.type==="function_call"||e.type==="custom_tool_call",s=[];if(M(e,"id")){if(typeof e.id!=="string"||e.id.length===0)throw new m(`expected a non-empty output item id for ${t}`);s.push(`id:${e.id}`)}else if(!n)throw new m(`expected a non-empty output item id for ${t}`);if(Ac(e)){if(!M(e,"call_id")||typeof e.call_id!=="string"||e.call_id.length===0)throw new m(`expected a non-empty output item call_id for ${t}`);s.push(`call:${e.type}:${e.call_id}`)}return s}function ed(e,t){for(let n of t)if(e.has(n))throw new m(`duplicate output item identity '${n}'`)}function td(e,t){ed(e,t);for(let n of t)e.add(n)}function rd(e){let t={snapshot:e,output:e.output,length:e.output.length,identities:new Set};for(let n=0;n<e.output.length;n+=1){let s=N(e,n);td(t.identities,Ji(s,"response snapshot"))}return t}function Qm(e,t){let n=wc.get(e);if(n&&n.snapshot===t&&n.output===t.output&&n.length===t.output.length)return n;let s=rd(t);return wc.set(e,s),s}function Ql(e,t){let n=bc(),s=Yl(n,t),o=rd(s);return e.canonicalSnapshot=n.canonicalSnapshot,e.outputTextLengths=n.outputTextLengths,e.outputTextIndex=n.outputTextIndex,wc.set(e,o),s}var Pc={"response.output_text.delta":"message","response.output_text.done":"message","response.output_text.annotation.added":"message","response.refusal.delta":"message","response.refusal.done":"message","response.function_call_arguments.delta":"function_call","response.function_call_arguments.done":"function_call","response.custom_tool_call_input.delta":"custom_tool_call","response.custom_tool_call_input.done":"custom_tool_call","response.mcp_call_arguments.delta":"mcp_call","response.mcp_call_arguments.done":"mcp_call","response.mcp_call.in_progress":"mcp_call","response.mcp_call.completed":"mcp_call","response.mcp_call.failed":"mcp_call","response.shell_call_output_content.delta":"shell_call_output","response.shell_call_output_content.done":"shell_call_output","response.reasoning_text.delta":"reasoning","response.reasoning_text.done":"reasoning","response.reasoning_summary_part.added":"reasoning","response.reasoning_summary_part.done":"reasoning","response.reasoning_summary_text.delta":"reasoning","response.reasoning_summary_text.done":"reasoning","response.code_interpreter_call_code.delta":"code_interpreter_call","response.code_interpreter_call_code.done":"code_interpreter_call","response.code_interpreter_call.in_progress":"code_interpreter_call","response.code_interpreter_call.interpreting":"code_interpreter_call","response.code_interpreter_call.completed":"code_interpreter_call","response.file_search_call.in_progress":"file_search_call","response.file_search_call.searching":"file_search_call","response.file_search_call.completed":"file_search_call","response.web_search_call.in_progress":"web_search_call","response.web_search_call.searching":"web_search_call","response.web_search_call.completed":"web_search_call","response.image_generation_call.in_progress":"image_generation_call","response.image_generation_call.generating":"image_generation_call","response.image_generation_call.completed":"image_generation_call","response.image_generation_call.partial_image":"image_generation_call","response.mcp_list_tools.in_progress":"mcp_list_tools","response.mcp_list_tools.completed":"mcp_list_tools","response.mcp_list_tools.failed":"mcp_list_tools","response.compaction.compacting":"compaction"};function Zm(e){if(e.type==="response.content_part.added"||e.type==="response.content_part.done")return e.part.type==="reasoning_text"?"reasoning":"message";return Pc[e.type]}function e_(e,t){let n=N(t,e.output_index),s=e.item;if(Ji(n,e.type),Ji(s,e.type),!M(s,"type")||n.type!==s.type)throw new m(`expected output item type '${n.type}', got '${s.type}'`);let o=M(n,"id")?n.id:void 0,a=M(s,"id")?s.id:void 0;if(o!==a)throw new m(`expected output item id '${o}', got '${a}'`);if(Ac(n)&&Ac(s)&&n.call_id!==s.call_id)throw new m(`expected output item call_id '${n.call_id}', got '${s.call_id}'`)}function t_(e,t,n){if(e.type==="response.output_item.done"){e_(e,t);return}if(n&&(e.type==="response.shell_call_command.added"||e.type==="response.shell_call_command.delta"||e.type==="response.shell_call_command.done")){let l=N(t,e.output_index);if(!M(l,"type")||l.type!=="shell_call")throw new m(`expected output item type 'shell_call', got '${l.type}'`);return}if(e.type!=="response.content_part.added"&&e.type!=="response.content_part.done"&&!M(Pc,e.type))return;let s=e;if(!M(e,"item_id")||typeof s.item_id!=="string"||s.item_id.length===0)throw new m(`expected a non-empty item_id for ${e.type}`);let o=N(t,s.output_index),a=M(o,"id")?o.id:void 0;if(a!==s.item_id)throw new m(`expected item_id '${a}', got '${s.item_id}'`);let u=Zm(s);if(o.type!==u)throw new m(`expected output item type '${u}', got '${o.type}'`)}function je(e,t){Kt(e,t,"content");let n=e[t];if(!n)throw new m(`missing content at index ${t}`);return n}function Zl(e,t,n){let s=e.output.find((o)=>o.type==="shell_call"&&o.call_id===t.call_id);if(s)Kt(s.action.commands,n,"command");else Kt(t.output,n,"content",!0);while(t.output.length<=n)t.output.push({stdout:"",stderr:"",outcome:{type:"exit",exit_code:0}});return je(t.output,n)}function r_(e){return new Set(e)}var n_=r_(["response.output_item.added","response.output_item.done","response.content_part.added","response.content_part.done","response.output_text.delta","response.output_text.done","response.output_text.annotation.added","response.refusal.delta","response.refusal.done","response.function_call_arguments.delta","response.function_call_arguments.done","response.custom_tool_call_input.delta","response.custom_tool_call_input.done","response.mcp_call_arguments.delta","response.mcp_call_arguments.done","response.shell_call_command.added","response.shell_call_command.done","response.shell_call_command.delta","response.shell_call_output_content.delta","response.shell_call_output_content.done","response.reasoning_text.delta","response.reasoning_text.done","response.reasoning_summary_part.added","response.reasoning_summary_part.done","response.reasoning_summary_text.delta","response.reasoning_summary_text.done","response.code_interpreter_call_code.delta","response.code_interpreter_call_code.done","response.code_interpreter_call.in_progress","response.code_interpreter_call.interpreting","response.code_interpreter_call.completed","response.file_search_call.in_progress","response.file_search_call.searching","response.file_search_call.completed","response.web_search_call.in_progress","response.web_search_call.searching","response.web_search_call.completed","response.image_generation_call.in_progress","response.image_generation_call.generating","response.image_generation_call.completed","response.mcp_call.in_progress","response.mcp_call.completed","response.mcp_call.failed","response.created","response.queued","response.in_progress","response.completed","response.failed","response.incomplete","response.audio.delta","response.audio.done","response.audio.transcript.delta","response.audio.transcript.done","response.compaction.compacting","response.image_generation_call.partial_image","response.mcp_list_tools.in_progress","response.mcp_list_tools.completed","response.mcp_list_tools.failed","keepalive","error"]);function Xi(e){throw new m("Unhandled response stream event: unknown")}var s_=["item_id","output_index","content_index","annotation_index","command_index","summary_index"];function o_(e){let t;try{t=Object.getOwnPropertyDescriptor(e,"type")}catch{return Xi(e)}let n=t?.value;if(typeof n!=="string"||!n_.has(n))return Xi(e);let s=new Map([["type",n]]);if(n==="response.output_item.added"||n==="response.output_item.done"||n==="response.content_part.added"||n==="response.content_part.done"||n==="response.shell_call_command.added"||n==="response.shell_call_command.delta"||n==="response.shell_call_command.done"||M(Pc,n))try{for(let a of s_){let u=Object.getOwnPropertyDescriptor(e,a);s.set(a,u?e[a]:void 0)}if(n==="response.output_item.done")s.set("item",structuredClone(e.item));else if(n==="response.content_part.added"||n==="response.content_part.done")s.set("part",structuredClone(e.part))}catch{return Xi(e)}return new Proxy(e,{get(a,u){return s.has(u)?s.get(u):Reflect.get(a,u,a)}})}function i_(e,t,n){switch(e.type){case"response.output_item.added":{Hi(t.output,e.output_index,"output");let s=Qm(n,t),o=structuredClone(e.item),a=Ji(o,e.type);if(ed(s.identities,a),o.type==="message")qt(n,t);t.output.push(o),td(s.identities,a),s.length=t.output.length;let u=kn(n,o);if(n.canonicalSnapshot===t)n.outputTextIndex.append(u.length);if(u)t.output_text+=u;return!0}case"response.output_item.done":{let s=N(t,e.output_index),o=kn(n,s),a=e.item;if(s.type==="message"||a.type==="message")qt(n,t);t.output[e.output_index]=a;let u=kn(n,a);if(n.canonicalSnapshot===t)n.outputTextIndex.update(e.output_index,u.length);return Cn(n,t,e.output_index,o,u),!0}default:return!1}}function a_(e,t,n){switch(e.type){case"response.content_part.added":{let s=N(t,e.output_index),{type:o}=s,{part:a}=e;if(o==="message"&&a.type!=="reasoning_text"){Hi(s.content,e.content_index,"content");let u=a;if(u.type==="output_text")qt(n,t);if(s.content.push(u),u.type==="output_text")ko(n,s,e.output_index,"",u.text),Cn(n,t,e.output_index,"",u.text,e.content_index)}else if(o==="reasoning"&&a.type==="reasoning_text"){let u=s.content??[];if(Hi(u,e.content_index,"content"),!s.content)s.content=u;u.push(a)}return!0}default:return!1}}function c_(e,t,n){switch(e.type){case"response.content_part.done":{let s=N(t,e.output_index),{part:o}=e;if(s.type==="message"&&o.type!=="reasoning_text"){let a=je(s.content,e.content_index),u=a.type==="output_text"?a.text:"",l=o;if(a.type==="output_text"||l.type==="output_text")qt(n,t);s.content[e.content_index]=l;let f=l.type==="output_text"?l.text:"";ko(n,s,e.output_index,u,f),Cn(n,t,e.output_index,u,f,e.content_index)}else if(s.type==="reasoning"&&o.type==="reasoning_text"){let{content:a}=s;if(!a)throw new m(`missing content at index ${e.content_index}`);je(a,e.content_index),a[e.content_index]=o}return!0}default:return!1}}function u_(e,t,n){switch(e.type){case"response.output_text.delta":{let s=N(t,e.output_index);if(s.type==="message"){let o=je(s.content,e.content_index);if(o.type!=="output_text")throw new m(`expected content to be 'output_text', got ${o.type}`);let a=o.text;if(qt(n,t),o.text=a+e.delta,ko(n,s,e.output_index,a,o.text),e.output_index===t.output.length-1&&e.content_index===s.content.length-1)t.output_text+=e.delta;else Cn(n,t,e.output_index,a,o.text,e.content_index)}return!0}case"response.output_text.done":{let s=N(t,e.output_index);if(s.type==="message"){let o=je(s.content,e.content_index);if(o.type!=="output_text")throw new m(`expected content to be 'output_text', got ${o.type}`);let a=o.text;qt(n,t),o.text=e.text,ko(n,s,e.output_index,a,e.text),Cn(n,t,e.output_index,a,e.text,e.content_index)}return!0}case"response.output_text.annotation.added":{let s=N(t,e.output_index);if(s.type==="message"){let o=je(s.content,e.content_index);if(o.type!=="output_text")throw new m(`expected content to be 'output_text', got ${o.type}`);Kt(o.annotations,e.annotation_index,"annotation",!0),o.annotations[e.annotation_index]=structuredClone(e.annotation)}return!0}default:return!1}}function l_(e,t){switch(e.type){case"response.refusal.delta":{let n=N(t,e.output_index);if(n.type==="message"){let s=je(n.content,e.content_index);if(s.type!=="refusal")throw new m(`expected content to be 'refusal', got ${s.type}`);s.refusal+=e.delta}return!0}case"response.refusal.done":{let n=N(t,e.output_index);if(n.type==="message"){let s=je(n.content,e.content_index);if(s.type!=="refusal")throw new m(`expected content to be 'refusal', got ${s.type}`);s.refusal=e.refusal}return!0}case"response.function_call_arguments.delta":{let n=N(t,e.output_index);if(n.type==="function_call")n.arguments+=e.delta;return!0}case"response.function_call_arguments.done":{let n=N(t,e.output_index);if(n.type==="function_call")n.arguments=e.arguments;return!0}case"response.custom_tool_call_input.delta":{let n=N(t,e.output_index);if(n.type==="custom_tool_call")n.input+=e.delta;return!0}case"response.custom_tool_call_input.done":{let n=N(t,e.output_index);if(n.type==="custom_tool_call")n.input=e.input;return!0}case"response.mcp_call_arguments.delta":{let n=N(t,e.output_index);if(n.type==="mcp_call")n.arguments+=e.delta;return!0}case"response.mcp_call_arguments.done":{let n=N(t,e.output_index);if(n.type==="mcp_call")n.arguments=e.arguments;return!0}default:return!1}}function d_(e,t){switch(e.type){case"response.shell_call_command.added":case"response.shell_call_command.done":{let n=N(t,e.output_index);if(n.type==="shell_call"){let s=e.type==="response.shell_call_command.added";Kt(n.action.commands,e.command_index,"command",s),n.action.commands[e.command_index]=e.command}return!0}case"response.shell_call_command.delta":{let n=N(t,e.output_index);if(n.type==="shell_call")Kt(n.action.commands,e.command_index,"command"),n.action.commands[e.command_index]+=e.delta;return!0}case"response.shell_call_output_content.delta":{let n=N(t,e.output_index);if(n.type==="shell_call_output"){let s=Zl(t,n,e.command_index);s.stdout+=e.delta.stdout??"",s.stderr+=e.delta.stderr??""}return!0}case"response.shell_call_output_content.done":{let n=N(t,e.output_index);if(n.type==="shell_call_output"){let s=je(e.output,0);Zl(t,n,e.command_index),n.output[e.command_index]=structuredClone(s)}return!0}default:return!1}}function f_(e,t){switch(e.type){case"response.reasoning_text.delta":{let n=N(t,e.output_index);if(n.type==="reasoning"){if(!n.content)throw new m(`missing content at index ${e.content_index}`);let s=je(n.content,e.content_index);if(s.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=e.delta}return!0}case"response.reasoning_text.done":{let n=N(t,e.output_index);if(n.type==="reasoning"){if(!n.content)throw new m(`missing content at index ${e.content_index}`);let s=je(n.content,e.content_index);if(s.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${s.type}`);s.text=e.text}return!0}case"response.reasoning_summary_part.added":{let n=N(t,e.output_index);if(n.type==="reasoning")Hi(n.summary,e.summary_index,"content"),n.summary.push(structuredClone(e.part));return!0}case"response.reasoning_summary_part.done":{let n=N(t,e.output_index);if(n.type==="reasoning")je(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part);return!0}case"response.reasoning_summary_text.delta":{let n=N(t,e.output_index);if(n.type==="reasoning"){let s=je(n.summary,e.summary_index);s.text+=e.delta}return!0}case"response.reasoning_summary_text.done":{let n=N(t,e.output_index);if(n.type==="reasoning"){let s=je(n.summary,e.summary_index);s.text=e.text}return!0}default:return!1}}function p_(e,t){switch(e.type){case"response.code_interpreter_call_code.delta":{let n=N(t,e.output_index);if(n.type==="code_interpreter_call")n.code=(n.code??"")+e.delta;return!0}case"response.code_interpreter_call_code.done":{let n=N(t,e.output_index);if(n.type==="code_interpreter_call")n.code=e.code;return!0}case"response.code_interpreter_call.in_progress":{let n=N(t,e.output_index);if(n.type==="code_interpreter_call")n.status="in_progress";return!0}case"response.code_interpreter_call.interpreting":{let n=N(t,e.output_index);if(n.type==="code_interpreter_call")n.status="interpreting";return!0}case"response.code_interpreter_call.completed":{let n=N(t,e.output_index);if(n.type==="code_interpreter_call")n.status="completed";return!0}default:return!1}}function h_(e,t){switch(e.type){case"response.file_search_call.in_progress":{let n=N(t,e.output_index);if(n.type==="file_search_call")n.status="in_progress";return!0}case"response.file_search_call.searching":{let n=N(t,e.output_index);if(n.type==="file_search_call")n.status="searching";return!0}case"response.file_search_call.completed":{let n=N(t,e.output_index);if(n.type==="file_search_call")n.status="completed";return!0}case"response.web_search_call.in_progress":{let n=N(t,e.output_index);if(n.type==="web_search_call")n.status="in_progress";return!0}case"response.web_search_call.searching":{let n=N(t,e.output_index);if(n.type==="web_search_call")n.status="searching";return!0}case"response.web_search_call.completed":{let n=N(t,e.output_index);if(n.type==="web_search_call")n.status="completed";return!0}default:return!1}}function m_(e,t){switch(e.type){case"response.image_generation_call.in_progress":{let n=N(t,e.output_index);if(n.type==="image_generation_call")n.status="in_progress";return!0}case"response.image_generation_call.generating":{let n=N(t,e.output_index);if(n.type==="image_generation_call")n.status="generating";return!0}case"response.image_generation_call.completed":{let n=N(t,e.output_index);if(n.type==="image_generation_call")n.status="completed";return!0}case"response.mcp_call.in_progress":{let n=N(t,e.output_index);if(n.type==="mcp_call")n.status="in_progress";return!0}case"response.mcp_call.completed":{let n=N(t,e.output_index);if(n.type==="mcp_call")n.status="completed";return!0}case"response.mcp_call.failed":{let n=N(t,e.output_index);if(n.type==="mcp_call")n.status="failed";return!0}default:return!1}}function __(e){switch(e.type){case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":return!0;default:return!1}}function y_(e){switch(e.type){case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.compaction.compacting":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":return!0;default:return!1}}function Vi(){return bc()}function nd(e,t,n,s=!1,o){let a=o_(e);if(o&&a.type!=="keepalive")o(a);if(!t){if(a.type!=="response.created")throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${a.type}`);return Ql(n,a.response)}if(t_(a,t,s),i_(a,t,n))return t;if(a_(a,t,n))return t;if(c_(a,t,n))return t;if(u_(a,t,n))return t;if(l_(a,t))return t;if(d_(a,t))return t;if(f_(a,t))return t;if(p_(a,t))return t;if(h_(a,t))return t;if(m_(a,t))return t;if(__(a))return Ql(n,a.response);if(y_(a))return t;return Xi(a)}var zt,Gi,jr,Yi,Co,Ic,xc,Sc;class To extends fr{constructor(e){super();zt.add(this),Gi.set(this,void 0),jr.set(this,void 0),Yi.set(this,void 0),Co.set(this,Vi()),A(this,Gi,e,"f")}static createResponse(e,t,n){let s=new To(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}static fromReadableStream(e){let t=new To(null);return t._run(()=>t._fromReadableStream(e)),t}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),c(this,zt,"m",Ic).call(this);let s,o=null;if("response_id"in t)s=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),o=t.starting_after??null;else s=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of s)c(this,zt,"m",xc).call(this,a,o);if(s.controller.signal?.aborted)throw this._userAbortError();return c(this,zt,"m",Sc).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,zt,"m",Ic).call(this),this._connected();let n=Ae.fromReadableStream(e,this.controller);for await(let s of n)c(this,zt,"m",xc).call(this,s,null);if(n.controller.signal?.aborted)throw this._userAbortError();return c(this,zt,"m",Sc).call(this)}[(Gi=new WeakMap,jr=new WeakMap,Yi=new WeakMap,Co=new WeakMap,zt=new WeakSet,Ic=function(){if(this.ended)return;A(this,jr,void 0,"f"),A(this,Co,Vi(),"f")},xc=function(t,n){if(this.ended)return;let s=(u,l)=>{if(n==null||l.sequence_number>n)this._emit(u,l)};if(t.type==="error"){let u="error"in t&&typeof t.error==="object"&&t.error!==null?t.error:t;throw new H(void 0,u,t.message,void 0)}let o=t,a=nd(t,c(this,jr,"f"),c(this,Co,"f"),!0,(u)=>{o=u});switch(A(this,jr,a,"f"),s("event",t),o.type){case"response.output_text.delta":{let u=a.output[o.output_index];if(!u)throw new m(`missing output at index ${o.output_index}`);if(u.type==="message"){let l=u.content[o.content_index];if(!l)throw new m(`missing content at index ${o.content_index}`);if(l.type!=="output_text")throw new m(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...o,type:o.type,item_id:o.item_id,output_index:o.output_index,content_index:o.content_index,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let u=a.output[o.output_index];if(!u)throw new m(`missing output at index ${o.output_index}`);if(u.type==="function_call")s("response.function_call_arguments.delta",{...o,type:o.type,item_id:o.item_id,output_index:o.output_index,snapshot:u.arguments});break}default:{s(o.type,t);break}}},Sc=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=c(this,jr,"f");if(!t)throw new m("request ended without sending any events");A(this,jr,void 0,"f"),A(this,Co,Vi(),"f");let n=g_(t,c(this,Gi,"f"));return A(this,Yi,n,"f"),n},Symbol.asyncIterator)](){return this._createIterator((e)=>{let t=(n)=>e(n);return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let e=c(this,Yi,"f");if(!e)throw new m("stream ended without producing a Response");return e}}function g_(e,t){return Jl(e,t)}class $o extends p{list(e,t={},n){return this._client.getAPIList(d`/responses/${e}/input_items`,O,{query:t,...n,__security:{bearerAuth:!0}})}}class jo extends p{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}}class Et extends p{constructor(){super(...arguments);this.inputItems=new $o(this._client),this.inputTokens=new jo(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((n)=>{if("object"in n&&n.object==="response")On(n);return n})}retrieve(e,t={},n){return this._client.get(d`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((s)=>{if("object"in s&&s.object==="response")On(s);return s})}delete(e,t){return this._client.delete(d`/responses/${e}`,{...t,headers:b([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((n)=>gc(n,e))}stream(e,t){return To.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(d`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}}Et.InputItems=$o;Et.InputTokens=jo;class Lo extends p{retrieve(e,t){return this._client.get(d`/safety/alerts/${e}`,{...t,__security:{bearerAuth:!0}})}}class Lr extends p{constructor(){super(...arguments);this.alerts=new Lo(this._client)}}Lr.Alerts=Lo;class Mo extends p{retrieve(e,t){return this._client.get(d`/skills/${e}/content`,{...t,headers:b([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class Bo extends p{retrieve(e,t,n){let{skill_id:s}=t;return this._client.get(d`/skills/${s}/versions/${e}/content`,{...n,headers:b([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class Tn extends p{constructor(){super(...arguments);this.content=new Bo(this._client)}create(e,t={},n){return this._client.post(d`/skills/${e}/versions`,Ct({body:t,...n,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t,n){let{skill_id:s}=t;return this._client.get(d`/skills/${s}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/skills/${e}/versions`,O,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:s}=t;return this._client.delete(d`/skills/${s}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}}Tn.Content=Bo;class Xt extends p{constructor(){super(...arguments);this.content=new Mo(this._client),this.versions=new Tn(this._client)}create(e={},t){return this._client.post("/skills",Ct({body:e,...t,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t){return this._client.get(d`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}}Xt.Content=Mo;Xt.Versions=Tn;class Do extends p{create(e,t,n){return this._client.post(d`/uploads/${e}/parts`,oe({body:t,...n,__security:{bearerAuth:!0}},this._client))}}class Mr extends p{constructor(){super(...arguments);this.parts=new Do(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(d`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(d`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}}Mr.Parts=Do;function sd(e,t,n,s){return mo((o)=>e.retrieve(n,{vector_store_id:t},{...s,headers:o}),["in_progress"],["failed","cancelled","completed"],s)}function od(e,t,n,s){return mo((o)=>e.retrieve(n,{vector_store_id:t},{...s,headers:o}),["in_progress"],["failed","cancelled","completed"],s)}var id=async(e)=>{let t=await Promise.allSettled(e),n=t.filter((o)=>o.status==="rejected");if(n.length)throw Object.defineProperty(Error(`${n.length} promise(s) failed`),"rejections",{configurable:!0,value:n.map(({reason:o})=>o),writable:!0});let s=[];for(let o of t)if(o.status==="fulfilled")s.push(o.value);return s};async function ad(e,t,n,s,o,a){if(s===null||s===void 0||s.length===0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let u=a?.maxConcurrency??5,l=Math.min(u,s.length);if(l===0)throw RangeError("maxConcurrency must be greater than 0");let f=s.values(),h=[...o];async function _(y){for(let P of y){let I=await t.files.create({file:P,purpose:"assistants"},a);h.push(I.id)}}let w=[];w.length=l;for(let y=0;y<w.length;y+=1)w[y]=_(f);return await id(w),await e.createAndPoll(n,{file_ids:h},a)}class No extends p{create(e,t,n){return this._client.post(d`/vector_stores/${e}/file_batches`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/file_batches/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:s}=t;return this._client.post(d`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}listFiles(e,t,n){let{vector_store_id:s,...o}=t;return this._client.getAPIList(d`/vector_stores/${s}/file_batches/${e}/files`,O,{query:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){return await od(this,e,t,n)}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){return await ad(this,this._client,e,t,n,s)}}class Fo extends p{create(e,t,n){return this._client.post(d`/vector_stores/${e}/files`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/files/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:s,...o}=t;return this._client.post(d`/vector_stores/${s}/files/${e}`,{body:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/vector_stores/${e}/files`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:s}=t;return this._client.delete(d`/vector_stores/${s}/files/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){return await sd(this,e,t,n)}async upload(e,t,n){let s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){let s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){let{vector_store_id:s}=t;return this._client.getAPIList(d`/vector_stores/${s}/files/${e}/content`,ye,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}class Ht extends p{constructor(){super(...arguments);this.files=new Fo(this._client),this.fileBatches=new No(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/vector_stores/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/vector_stores/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",O,{query:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/vector_stores/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(d`/vector_stores/${e}/search`,ye,{body:t,method:"post",...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}Ht.Files=Fo;Ht.FileBatches=No;class $n extends p{create(e,t){return this._client.post("/videos",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(d`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",q,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(d`/videos/${e}/content`,{query:t,...n,headers:b([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(d`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(d`/videos/${e}/remix`,Ct({body:t,...n,__security:{bearerAuth:!0}},this._client))}}var cd=32,E_=32;function Rc(e){return e.split(" ",cd+1).length>cd}function*vc(e){let t=0;while(t<=e.length){let n=e.indexOf(" ",t),s=e.slice(t,n===-1?void 0:n);if(yield s.startsWith("v1,")?s.slice(3):s,n===-1)break;t=n+1}}function ud(e){try{let t=Ui(e);return t.byteLength===E_?t:void 0}catch{return}}function O_(e){for(let t of vc(e)){let n=ud(t);if(n)return n}return}function k_(e,t,n){let s=n;for(let o of vc(e)){let a=ud(o);if(!a)continue;let u=0;for(let[l,f]of a.entries())u|=f^(t[l]??0);if(u===0)s=a}return s}async function ld(e,t,n,s,o,a){let u=Number.parseInt(n,10);if(Number.isNaN(u))throw new Be("Invalid webhook timestamp format");let l=Math.floor(Date.now()/1000);if(l-u>a)throw new Be("Webhook timestamp is too old");if(u>l+a)throw new Be("Webhook timestamp is too new");let f=Rc(t),h=f?O_(t):void 0;if(f&&!h)throw new Be("The given webhook signature does not match the expected signature");let _=Uint8Array.from(o.startsWith("whsec_")?Ui(o.slice(6)):_e(o)),w=s?`${s}.${n}.${e}`:`${n}.${e}`,y=Uint8Array.from(_e(w)),P=await crypto.subtle.importKey("raw",_,{name:"HMAC",hash:"SHA-256"},!1,f?["sign","verify"]:["verify"]);if(f&&h){let I=new Uint8Array(await crypto.subtle.sign("HMAC",P,y)),x=k_(t,I,h);try{if(await crypto.subtle.verify("HMAC",P,Uint8Array.from(x),y))return}catch{}throw new Be("The given webhook signature does not match the expected signature")}for(let I of vc(t))try{let x=Uint8Array.from(Ui(I));if(await crypto.subtle.verify("HMAC",P,x,y))return}catch{}throw new Be("The given webhook signature does not match the expected signature")}class Wo extends p{list(e){return this._client.get("/webhook_event_types",{...e,__security:{bearerAuth:!0}})}}var jn,dd,Qi;class Br extends p{constructor(){super(...arguments);jn.add(this),this.eventTypes=new Wo(this._client)}create(e,t){return this._client.post("/webhook_endpoints",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/webhook_endpoints/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(d`/webhook_endpoints/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/webhook_endpoints",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/webhook_endpoints/${e}`,{...t,__security:{bearerAuth:!0}})}rotateSecret(e,t={},n){return this._client.post(d`/webhook_endpoints/${e}/rotate_secret`,{body:t,...n,__security:{bearerAuth:!0}})}test(e,t,n){return this._client.post(d`/webhook_endpoints/${e}/test`,{body:t,...n,__security:{bearerAuth:!0}})}async unwrap(e,t,n=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,n,s),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle?.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,jn,"m",dd).call(this,n);let o=b([t]).values,a=c(this,jn,"m",Qi).call(this,o,"webhook-signature"),u=c(this,jn,"m",Qi).call(this,o,"webhook-timestamp"),l=c(this,jn,"m",Qi).call(this,o,"webhook-id");if(Rc(a)&&typeof crypto.subtle.sign!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");return await ld(e,a,u,l,n,s)}}jn=new WeakSet,dd=function(t){if(typeof t!=="string"||t.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Qi=function(t,n){if(!t)throw Error("Headers are required");let s=t.get(n);if(s===null||s===void 0)throw Error(`Missing required header: ${n}`);return s};Br.EventTypes=Wo;async function Ec(e){let t,n=await e._callApiKey((s)=>{t=s});return{apiKey:t===void 0?e.apiKey:t,isProvider:n}}var pd=Symbol.for("openai.node.providerDefinitions.v1"),hd=globalThis,md=hd[pd],_d=md??new WeakMap;if(!md)Object.defineProperty(hd,pd,{value:_d});function yd(e){let t=_d.get(e);if(!t)throw Error("Invalid provider. Providers must be created with createProvider().");return t.configure()}var Oc,rt,Uo,Y,Zi,Ot,Ko,qo,Ad;function gd(){if(Vc())return!0;let e=globalThis;return typeof e.WorkerGlobalScope==="function"&&e instanceof e.WorkerGlobalScope&&typeof e.WorkerNavigator==="function"&&e.navigator instanceof e.WorkerNavigator&&typeof e.navigator?.userAgent==="string"&&e.navigator.userAgent!=="Cloudflare-Workers"&&e.process?.versions?.node===void 0&&e.Deno===void 0&&e.Bun===void 0&&e.EdgeRuntime===void 0&&e.WebSocketPair===void 0}var T_="workload-identity-auth",bd=Symbol("inheritedDataResidencySelection");class g{constructor(e={}){Oc.add(this),Uo.set(this,void 0),Y.set(this,void 0),Zi.set(this,void 0),Ot.set(this,void 0),Ko.set(this,!1),qo.set(this,new WeakMap),this.completions=new yn(this),this.chat=new _r(this),this.embeddings=new wn(this),this.files=new Pn(this),this.images=new Rn(this),this.contentProvenanceChecks=new bn(this),this.audio=new xt(this),this.moderations=new En(this),this.models=new vn(this),this.fineTuning=new dt(this),this.graders=new $r(this),this.vectorStores=new Ht(this),this.safety=new Lr(this),this.webhooks=new Br(this),this.beta=new Je(this),this.batches=new on(this),this.uploads=new Mr(this),this.admin=new gr(this),this.responses=new Et(this),this.live=new vt(this),this.realtime=new Ut(this),this.conversations=new Cr(this),this.evals=new Tr(this),this.containers=new kr(this),this.skills=new Xt(this),this.videos=new $n(this);let{credential:t,options:n}=$u(e);e=n;let s=ha(e),o=e.provider,{baseURL:a=o?null:Ee("OPENAI_BASE_URL"),dataResidency:u,[bd]:l=!1,apiKey:f=o?null:Ee("OPENAI_API_KEY")??null,adminAPIKey:h=o?null:Ee("OPENAI_ADMIN_KEY")??null,organization:_=o?null:Ee("OPENAI_ORG_ID")??null,project:w=o?null:Ee("OPENAI_PROJECT_ID")??null,webhookSecret:y=Ee("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:P,x509Transport:I,credential:x,...v}=e;if(o){let T=["apiKey","adminAPIKey","workloadIdentity","x509Transport","baseURL","dataResidency"].filter((L)=>(L==="workloadIdentity"?P:e[L])!=null);if(T.length)throw new m(`The \`provider\` option cannot be used with ${T.map((L)=>`\`${L}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let C=li(P)?{x509:P,legacy:void 0}:{x509:void 0,legacy:P},E=C.x509,S=E!==void 0,j=o?yd(o):void 0,R={apiKey:f,adminAPIKey:h,organization:_,project:w,webhookSecret:y,workloadIdentity:P,x509Transport:I,provider:o,...v,baseURL:j?.baseURL??s??(a||(S?du:"https://api.openai.com/v1"))};if(I&&!S)throw new m("An X.509 transport requires an X.509 workload identity.");if(S){if(s!==void 0||l)throw new m("X.509 workload identity does not support data residency selection.");if(e.fetch!==void 0)throw new m("X.509 workload identity does not support a custom fetch implementation.");if(Kr(R.baseURL),Vn(R.fetchOptions),this.fetchWithAuth!==rt.prototype.fetchWithAuth||this.fetchWithTimeout!==rt.prototype.fetchWithTimeout)throw new m("X.509 workload identity does not support overridden fetch dispatch hooks.")}if(f&&P)throw new m("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!j&&!f&&!h&&!P)throw new m("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!R.dangerouslyAllowBrowser&&gd())throw new m(`It looks like you're running in a browser-like environment.
21
+ `&&y!=="\r"&&y!=="\t")l=!0;if(f){if(u)u=!1;else if(y==="\\")u=!0;else if(y==='"')f=!1,h||(h=a===0);continue}if(y==='"')f=!0;else if(y==="{"||y==="["){if(a+=1,a>lc)throw new m("Chat completion stream exceeded its structured JSON nesting depth limit")}else if((y==="}"||y==="]")&&a>0)a-=1,h||(h=a===0)}if(e.bytes+=o,e.fragments+=1,e.depth=a,e.escaped=u,e.has_non_whitespace=l,e.in_string=f,n.length>0){let y=n.codePointAt(n.length-1)??0;e.pending_high_surrogate=y>=55296&&y<=56319}if(t.bytes+=o,t.fragments+=1,s)s.work+=o;if(!l||o===0)return!1;let w=Math.max(hl,Math.floor(e.last_parsed_bytes/2));if(e.bytes>hl&&!h&&e.bytes-e.last_parsed_bytes<w)return!1;return!0}function ac(e,t){if(t.work+e.bytes>Pl)return!1;return t.work+=e.bytes,e.work+=e.bytes,e.last_parsed_bytes=e.bytes,!0}function ze(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n){let s=Object.getPrototypeOf(e);for(let o=0;s!==null;o+=1){if(o>=lc||Object.getOwnPropertyDescriptor(s,t))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");s=Object.getPrototypeOf(s)}return}if(!("value"in n)||typeof n.value!=="string"&&n.value!==null&&n.value!==void 0)throw new m("Chat completion stream contains an unsafe structured JSON snapshot");return n.value}function fs(e){let t=Object.getOwnPropertyDescriptor(e,"message");if(!t||!("value"in t)||typeof t.value!=="object"||t.value===null)throw new m("Chat completion stream contains an unsafe structured JSON snapshot");return t.value}function ml(e,t,n,s){let o=Object.getOwnPropertyDescriptor(e,t);if(!o){let u=Object.getPrototypeOf(e);for(let l=0;u!==null;l+=1){if(l>=lc||Object.getOwnPropertyDescriptor(u,t))throw new m(`Chat completion stream contains an unsafe snapshot ${s} collection`);u=Object.getPrototypeOf(u)}return}if(!("value"in o)||!Array.isArray(o.value))throw new m(`Chat completion stream contains an unsafe snapshot ${s} collection`);let a=Object.getOwnPropertyDescriptor(o.value,"length");if(!a||!("value"in a)||!Number.isSafeInteger(a.value)||a.value>n)throw new m(`Chat completion stream exceeded its snapshot ${s} limit`);return o.value}function Za(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n)return;if(!("value"in n))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");return n.value}function _l(e,t,n,s){let o=Object.getOwnPropertyDescriptor(e,"length"),a=o&&"value"in o?o.value:void 0;if(typeof a!=="number"||!Number.isSafeInteger(a)||a<0||a>t)throw new m(`Chat completion stream exceeded its snapshot ${n} limit`);let u=[];u.length=a;for(let l=0;l<a;l+=1){let f=Object.getOwnPropertyDescriptor(e,l);if(!f)continue;if(!("value"in f))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");u[l]=s(f.value,l)}return u}function mr(e,t,n){let s=oc(),o=t??{bytes:0,fragments:0,work:0};if(ic(s,o,e,n),!ac(s,o))throw new m("Chat completion stream exceeded its structured JSON parse-work limit");return e}function ji(e){let t=Object.getOwnPropertyDescriptor(e,"type"),n=Object.getOwnPropertyDescriptor(e,"function");if(!t||!("value"in t)||t.value!=="function"||!n||!("value"in n))return;if(typeof n.value!=="object"||n.value===null)return;let s=Object.getOwnPropertyDescriptor(n.value,"name");if(!s||!("value"in s)||typeof s.value!=="string"||s.value.length===0)return;return{type:"function",name:s.value}}function ec(e,t){let n=ji(e);if(!n||n.name!==t.name||n.type!==t.type)throw new m("Chat completion stream contains a changed tool call identity")}function ps(e,t){if(Object.prototype.propertyIsEnumerable.call(t,"__proto__")&&!M(e,"__proto__"))Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0});return Object.assign(e,t)}function hs(e,t=[]){let n=Object.getOwnPropertyDescriptors(e);for(let s of t){let o=n[s];if(!o&&!(s in e))continue;n[s]={value:o&&"value"in o?o.value:Reflect.get(e,s,e),enumerable:o?.enumerable??!1,configurable:o?.configurable??!0,writable:o&&"writable"in o?o.writable:!1}}return Object.create(Object.getPrototypeOf(e),n)}function Yp(e){let t=hs(e);if(e.tools){let n=[],s=Object.getOwnPropertyDescriptor(e.tools,"length"),o=s&&"value"in s?s.value:void 0,a=typeof o==="number"&&Number.isSafeInteger(o)&&o>=0?Math.min(o,jt):0;for(let u=0;u<a;u+=1){let l=Object.getOwnPropertyDescriptor(e.tools,String(u));if(!l||!("value"in l)){n.length=u+1;continue}let f=l.value,h=hs(f,["type","$brand","$parseRaw","$callback","function"]),_=Object.getOwnPropertyDescriptors(h);if(at(h)){let w=_.function;_.function={...w&&"value"in w?w:{configurable:!0,enumerable:!0,writable:!0},value:hs(h.function,["name","strict"])}}n[u]=Object.create(Object.getPrototypeOf(f),_)}t.tools=n}if(e.response_format)t.response_format=hs(e.response_format,["type","$brand","$parseRaw"]);return t}var tc=4096,rc=JSON.stringify,Qp=1048576,Zp=64,nc=Symbol("omitted serialized parser value"),he=Symbol("unsafe serialized parser value");function Il(e,t){let n=new WeakSet,s=(a)=>{if(!Number.isSafeInteger(a)||a<0||t.bytes+a>Qp)return!1;return t.bytes+=a,!0},o=(a,u)=>{if(u>Zp||t.nodes>=tc)return he;if(t.nodes+=1,a===void 0||typeof a==="function"||typeof a==="symbol")return nc;if(typeof a==="bigint")return he;if(a===null||typeof a==="boolean"||typeof a==="number"){let h=rc(a);return typeof h==="string"&&s(h.length)?h:he}if(typeof a==="string"){if(!s(a.length*6+2))return he;return rc(a)}if(typeof a!=="object"||n.has(a))return he;let l=Array.isArray(a),f=Object.getPrototypeOf(a);if(l&&f!==Array.prototype||!l&&f!==null&&f!==Object.prototype)return he;for(let h=a;h!==null;h=Object.getPrototypeOf(h)){let _=Object.getOwnPropertyDescriptor(h,"toJSON");if(!_)continue;if(!("value"in _)||typeof _.value==="function")return he;break}n.add(a);try{if(!s(2))return he;if(l){let y=Object.getOwnPropertyDescriptor(a,"length"),P=y&&"value"in y?y.value:void 0;if(typeof P!=="number"||!Number.isSafeInteger(P)||P<0||P>tc-t.nodes)return he;let I=[];for(let x=0;x<P;x+=1){let v=String(x),C=Object.getOwnPropertyDescriptor(a,v);if(!C){if(Object.getOwnPropertyDescriptor(Array.prototype,v)||Object.getOwnPropertyDescriptor(Object.prototype,v))return he;if(t.nodes+=1,!s(4))return he;I.push("null");continue}if(!("value"in C))return he;let E=o(C.value,u+1);if(E===he)return E;I.push(E===nc?"null":E)}return`[${I.join(",")}]`}let h=Reflect.ownKeys(a);if(h.length>tc-t.nodes)return he;let _=[];for(let y of h){if(typeof y!=="string")continue;let P=Object.getOwnPropertyDescriptor(a,y);if(!P)return he;if(!P.enumerable)continue;if(!("value"in P))return he;_.push([y,P.value])}_.sort(([y],[P])=>{if(y===P)return 0;return y<P?-1:1});let w=[];for(let[y,P]of _){let I=o(P,u+1);if(I===he)return I;if(I===nc)continue;if(!s(y.length*6+3))return he;w.push(`${rc(y)}:${I}`)}return`{${w.join(",")}}`}finally{n.delete(a)}};try{let a=o(e,0);return typeof a==="string"?a:void 0}catch{return}}function yl(e,t,n,s){let o=Object.getOwnPropertyDescriptor(t,"$parseRaw"),a=Object.getOwnPropertyDescriptor(n,s);if(!o||!("value"in o)||typeof o.value!=="function"||!a||!("value"in a))return;let u=Il(a.value,{nodes:0,bytes:0});if(u!==void 0)e.set(t,u)}function gl(e,t,n,s,o){let a=t&&e.get(t),u=Object.getOwnPropertyDescriptor(n,s);return a!==void 0&&u!==void 0&&"value"in u&&Il(o,{nodes:0,bytes:0})===a}function Zr(e,t){return e&&"value"in e?{...e,value:t}:{configurable:!0,enumerable:!0,writable:!0,value:t}}function cc(e,t,n){for(let s of n){let o=e[s];if(!o&&!(s in t))continue;e[s]=o&&"value"in o?{...o,value:void 0}:{configurable:o?.configurable??!0,enumerable:o?.enumerable??!1,writable:!1,value:void 0}}}function eh(e){let t=e.source??{type:e.type,...e.type==="function"?{function:{}}:{}},n=Object.getOwnPropertyDescriptors(t);if(n.type=Zr(n.type,e.type),e.type!=="function"||!e.function){if(n.function)n.function=Zr(n.function,void 0);return cc(n,t,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(t),n)}let s=n.function,o=s&&"value"in s&&typeof s.value==="object"&&s.value!==null?s.value:{},a=Object.getOwnPropertyDescriptors(o);if(a.name=Zr(a.name,e.function.name),a.strict=Zr(a.strict,e.function.strict),n.function=Zr(s,Object.create(Object.getPrototypeOf(o),a)),!e.function.schemaMatches)cc(n,t,["$brand","$parseRaw","$callback"]);return Object.create(Object.getPrototypeOf(t),n)}function th(e){let t=e.source??{type:e.type},n=Object.getOwnPropertyDescriptors(t);if(n.type=Zr(n.type,e.type),e.type!=="json_schema"||!e.source||!e.schemaMatches)cc(n,t,["$brand","$parseRaw"]);return Object.create(Object.getPrototypeOf(t),n)}function sc(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n||!("value"in n))return;let{value:s}=n;return typeof s==="object"&&s!==null?s:void 0}function rh(e,t,n){let s=new WeakMap,o=new WeakMap;if(e.tools)for(let P=0;P<e.tools.length&&P<jt;P+=1){let I=sc(e.tools,String(P)),x=t.tools?.[P];if(I&&x){s.set(I,x);let v=sc(x,"function");if(v)yl(o,x,v,"parameters")}}if(t.response_format)yl(o,t.response_format,t.response_format,"json_schema");let a,u,l,f,h=[],_=new WeakMap,w=new Map,y=new WeakMap;return Yc(e,{value(P,I,x){if(!a&&I===""&&typeof x==="object"&&x!==null){a=x,u=void 0,l=void 0,f=void 0,h=[],_=new WeakMap,w=new Map,y=new WeakMap;return}if(P===a&&I==="response_format"){if(typeof x==="object"&&x!==null)l=x,f={source:sc(P,I)===e.response_format?t.response_format:void 0,schemaMatches:!1};return}if(P===a&&I==="tools"){if(Array.isArray(x))return u=new Proxy(x,{get(E,S){let j=Reflect.get(E,S,E);if(typeof S==="string"){let R=Number(S);if(Number.isSafeInteger(R)&&R>=0&&R<jt&&String(R)===S)w.set(R,typeof j==="object"&&j!==null?j:void 0)}return j}}),u;return}if(P===u){let E=Number(I);if(!Number.isSafeInteger(E)||E<0||E>=jt||typeof x!=="object"||x===null)return;let S=w.get(E),R={source:S?s.get(S):void 0};h[E]=R,_.set(x,R);return}let v=_.get(P);if(v){if(I==="type"&&typeof x==="string")v.type=x;else if(I==="function"&&typeof x==="object"&&x!==null){let E={source:v.source,schemaMatches:!1};v.function=E,y.set(x,E)}return}if(P===l&&f){if(I==="type"&&typeof x==="string")f.type=x;else if(I==="json_schema")f.schemaMatches=gl(o,f.source,P,I,x);return}let C=y.get(P);if(C){if(I==="name"&&typeof x==="string")C.name=x;else if(I==="strict"&&typeof x==="boolean")C.strict=x;else if(I==="parameters")C.schemaMatches=gl(o,C.source,P,I,x)}return},complete(){if(!a)return;let P=hs(t);if(u){let I=[];for(let x=0;x<h.length;x+=1){let v=h[x];if(v)I[x]=eh(v)}P.tools=I}else delete P.tools;if(f)P.response_format=th(f);else delete P.response_format;n(P),a=void 0,u=void 0,l=void 0,f=void 0,h=[],_=new WeakMap,w=new Map,y=new WeakMap}})}class Lt extends Gr{constructor(e){super();G.add(this),ie.set(this,void 0),Ti.set(this,!1),$t.set(this,void 0),hr.set(this,void 0),ve.set(this,void 0),Ke.set(this,void 0),De.set(this,void 0),A(this,ie,e,"f"),A(this,$t,new Set,"f"),A(this,hr,[],"f"),A(this,Ke,!1,"f");let t=e?.tools,n=t&&Object.getOwnPropertyDescriptor(t,"length"),s=n&&"value"in n?n.value:void 0;if(t&&typeof s==="number"&&Number.isSafeInteger(s)&&s>=0)for(let o=0;o<Math.min(s,jt);o+=1){let a=Object.getOwnPropertyDescriptor(t,String(o));if(!a||!("value"in a))continue;let u=a.value;if(at(u)&&(Qe(u)||u.function.strict===!0)){A(this,Ke,!0,"f");break}}A(this,De,{bytes:0,fragments:0,work:0},"f")}get currentChatCompletionSnapshot(){return c(this,ve,"f")}static fromReadableStream(e){let t=new Lt(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){let s=new Lt(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}_runTools(e,t,n,s){return A(this,Ti,!0,"f"),super._runTools(e,t,n,s)}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal);let s={...t,stream:!0};A(this,ie,s,"f"),c(this,G,"m",Va).call(this);let o=Yp(s);A(this,ie,o,"f"),A(this,Ke,o.tools?.some((l)=>at(l)&&(Qe(l)||l.function.strict===!0))??!1,"f");let a=s.tools||s.response_format?rh(s,o,(l)=>{A(this,ie,l,"f"),A(this,Ke,l.tools?.some((f)=>at(f)&&(Qe(f)||f.function.strict===!0))??!1,"f")}):void 0,u=await e.chat.completions.create(s,{...n,signal:this.controller.signal}).finally(a);this._connected();for await(let l of u)c(this,G,"m",Ga).call(this,l);if(u.controller.signal?.aborted)throw this._userAbortError();return this._addChatCompletion(c(this,G,"m",ds).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,G,"m",Va).call(this),this._connected();let n=Ae.fromReadableStream(e,this.controller),s;for await(let a of n){if("error"in a&&M(a,"error")&&typeof a.error==="object"&&a.error!==null)throw new H(void 0,a.error,void 0,void 0);if(Hp(a)){let l=Jp(a);if(c(this,ve,"f")){let f=c(this,ve,"f").choices[0]?.message.tool_calls;for(let[h,_]of l.tool_call_ids?.entries()??[]){let w=f?.[h];if(w&&_)w.id=_}this._addChatCompletion(c(this,G,"m",ds).call(this)),s=void 0}this._addMessage(l.message);continue}let u=a;if(s&&u.id&&s!==u.id)this._addChatCompletion(c(this,G,"m",ds).call(this));if(c(this,G,"m",Ga).call(this,u),u.id)s=u.id}if(n.controller.signal?.aborted)throw this._userAbortError();if(c(this,ve,"f"))return this._addChatCompletion(c(this,G,"m",ds).call(this));let o=this._chatCompletions[this._chatCompletions.length-1];if(o)return o;throw new m("request ended without sending any chunks")}[(ie=new WeakMap,Ti=new WeakMap,$t=new WeakMap,hr=new WeakMap,ve=new WeakMap,Ke=new WeakMap,De=new WeakMap,G=new WeakSet,Va=function(){if(this.ended)return;A(this,$t,new Set,"f"),A(this,ve,void 0,"f"),A(this,De,{bytes:0,fragments:0,work:0},"f")},Yr=function(t){let n=c(this,hr,"f")[t.index];if(n)return n;return n={content_done:!1,content_parse_state:void 0,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null,tool_call_parse_states:new Map,tool_call_identities:new Map},c(this,hr,"f")[t.index]=n,n},Ga=function(t){if(this.ended)return;let n=new WeakMap,s=c(this,G,"m",fl).call(this,t,n);this._emit("chunk",t,s);for(let o of t.choices){let a=n.get(o),u=s.choices[a?.index??o.index],l=a?.tool_calls??[],{delta:f}=o,h=ct(c(this,ie,"f")?.response_format),_=h||c(this,Ke,"f"),w=_?fs(u):u.message,y=_?ze(w,"refusal"):w.refusal,I=!y&&h?ze(w,"content"):w.content;if(f?.content!=null&&w.role==="assistant"&&I)this._emit("content",f.content,I),this._emit("content.delta",{delta:f.content,snapshot:I,parsed:w.parsed});if(f?.refusal!=null&&w.role==="assistant"&&y)this._emit("refusal.delta",{delta:f.refusal,snapshot:y});if(o.logprobs?.content!=null&&w.role==="assistant")this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:u.logprobs?.content??[]});if(o.logprobs?.refusal!=null&&w.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:u.logprobs?.refusal??[]});let x=c(this,G,"m",Yr).call(this,u);if(u.finish_reason){if(c(this,G,"m",Qa).call(this,u),x.current_tool_call_index!=null)c(this,G,"m",Ya).call(this,u,x.current_tool_call_index)}for(let v of l){if(x.current_tool_call_index!==v.index){if(c(this,G,"m",Qa).call(this,u),x.current_tool_call_index!=null)c(this,G,"m",Ya).call(this,u,x.current_tool_call_index)}x.current_tool_call_index=v.index}for(let v of l){let C=w.tool_calls?.[v.index];if(!C?.type)continue;if(C.type==="function"){let E=x.tool_call_identities.get(v.index),S;if(E?.parseable){let j=ze(C.function,"arguments");if(typeof j!=="string")throw new m("Chat completion stream contains an unsafe structured JSON snapshot");S=j}else S=C.function.arguments;this._emit("tool_calls.function.arguments.delta",{name:C.function.name,index:v.index,arguments:S,parsed_arguments:C.function.parsed_arguments,arguments_delta:v.arguments_delta})}else if(C.type!=="custom")wl(C)}}},Ya=function(t,n){let s=c(this,G,"m",Yr).call(this,t);if(s.done_tool_calls.has(n))return;let a=(c(this,Ke,"f")?fs(t):t.message).tool_calls?.[n];if(!a)throw Error("no tool call snapshot");let u=s.tool_call_identities.get(n);if(u)ec(a,u);if(!a.type)throw Error("tool call snapshot missing `type`");if(a.type==="function"){let l=c(this,ie,"f")?.tools?.find((w)=>at(w)&&w.function.name===a.function.name),f=null,h=Qe(l)||l?.function.strict===!0,_;if(h){if(c(this,ve,"f"))c(this,G,"m",Qr).call(this,c(this,ve,"f"));let w=ze(a.function,"arguments");if(typeof w!=="string")throw new m("Chat completion stream contains an unsafe structured JSON snapshot");_=w}else _=a.function.arguments;if(Qe(l))f=l.$parseRaw(mr(_));else if(l?.function.strict)f=Pt({type:"json_schema",$parseRaw:void 0},mr(_));if(t.finish_reason)s.done_tool_calls.add(n);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:_,parsed_arguments:f})}else if(a.type!=="custom")wl(a)},Qa=function(t){let n=c(this,G,"m",Yr).call(this,t),s=ct(c(this,ie,"f")?.response_format),o=s||c(this,Ke,"f"),a=o?fs(t):t.message,u=o?ze(a,"refusal"):a.refusal,l=!u&&s,f=l?ze(a,"content"):a.content;if(f!=null&&(f!==""||!u&&!a.tool_calls?.length&&!a.function_call)&&!n.content_done){if(l&&c(this,ve,"f"))c(this,G,"m",Qr).call(this,c(this,ve,"f"));n.content_done=!0,this._emit("content.done",{content:f,parsed:u?null:Pt(c(this,ie,"f")?.response_format,l?mr(f):f)})}if(u&&!n.refusal_done)n.refusal_done=!0,this._emit("refusal.done",{refusal:u});if(t.logprobs?.content&&!n.logprobs_content_done)n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content});if(t.logprobs?.refusal&&!n.logprobs_refusal_done)n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal})},Qr=function(t){let n={bytes:0,fragments:0,work:0},s=ct(c(this,ie,"f")?.response_format),o=new WeakMap,a=ml(t,"choices",$i,"choice");if(!a)throw new m("Chat completion stream contains an unsafe snapshot choice collection");for(let u=0;u<a.length;u+=1){let l=Za(a,u);if(!l)continue;let f=fs(l),h=ze(f,"refusal"),_=ze(f,"content"),w=new Map,y=ml(f,"tool_calls",jt,"tool-call");o.set(l,Object.freeze({message:f,content:_,refusal:h,toolCallCollection:y,toolCalls:w}));let P=c(this,hr,"f")[l.index];if(s&&!h&&typeof _==="string")mr(_,n,c(this,De,"f"));for(let[I,x]of P?.tool_call_identities??[]){let v=y&&Za(y,I);if(!v)throw new m("Chat completion stream contains a changed tool call identity");ec(v,x)}if(!c(this,Ke,"f"))continue;for(let I=0;I<(y?.length??0);I+=1){let x=Za(y,I);if(!x)continue;let v=ji(x);if(!v){let j=Object.getOwnPropertyDescriptor(x,"type");if(j&&!("value"in j))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");if(j?.value!=="function")continue;let R=Object.getOwnPropertyDescriptor(x,"function");if(R&&!("value"in R))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");if(R&&typeof R.value==="object"&&R.value!==null){let F=Object.getOwnPropertyDescriptor(R.value,"name");if(F&&!("value"in F))throw new m("Chat completion stream contains an unsafe structured JSON snapshot")}continue}if(!_i(c(this,ie,"f"),{type:v.type,function:{name:v.name}}))continue;let C=Object.getOwnPropertyDescriptor(x,"function");if(!C||!("value"in C))throw new m("Chat completion stream contains an unsafe structured JSON snapshot");let E=C.value,S=ze(E,"arguments");if(typeof S!=="string")throw new m("Chat completion stream contains an unsafe structured JSON snapshot");mr(S,n,c(this,De,"f")),w.set(I,Object.freeze({tool:x,function:E,type:v.type,name:v.name,arguments:S}))}}return o},ds=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=c(this,ve,"f");if(!t)throw new m("request ended without sending any chunks");let n=c(this,G,"m",Qr).call(this,t),s=c(this,$t,"f");return A(this,$t,new Set,"f"),A(this,ve,void 0,"f"),A(this,hr,[],"f"),nh(t,c(this,ie,"f"),s,n)},fl=function(t,n){var s,o,a,u,l;let f=c(this,ve,"f"),{choices:h,obfuscation:_,...w}=t;if(!f){let I={...w,choices:[]};A(this,ve,I,"f"),f=I}else if(t.id)ps(f,w);let y=c(this,ie,"f")?.n,P=typeof y==="number"&&Number.isSafeInteger(y)&&y>0?Math.min(y,$i):$i;for(let I of t.choices){let{delta:x,finish_reason:v,index:C,logprobs:E=null,...S}=I,j=[];if(n.set(I,Object.freeze({index:C,tool_calls:j})),!Number.isSafeInteger(C)||C<0||C>=P)throw new m(`Chat completion stream contains an invalid choice index: ${C}`);let R=f.choices[C];if(!R){let X={finish_reason:v,index:C,message:{},logprobs:null,...S};f.choices[C]=X,R=X}if(ct(c(this,ie,"f")?.response_format)||c(this,Ke,"f"))ze(fs(R),"refusal");if(E)if(R.logprobs){let{content:X,refusal:Le,...ne}=E;if(bl(ne),ps(R.logprobs,ne),X)(s=R.logprobs).content??(s.content=[]),R.logprobs.content.push(...X);if(Le)(o=R.logprobs).refusal??(o.refusal=[]),R.logprobs.refusal.push(...Le)}else{if(R.logprobs={...E},E.content)R.logprobs.content=[...E.content];if(E.refusal)R.logprobs.refusal=[...E.refusal]}if(v){if(R.finish_reason=v,c(this,ie,"f")&&(c(this,Ti,"f")||Ta(c(this,ie,"f")))){if(v==="length")throw new tr;if(v==="content_filter")throw new rr}}if(ps(R,S),!x){Object.freeze(j);continue}c(this,$t,"f").delete(C);let{audio:F,content:k,refusal:T,function_call:L,role:D,...K}=x,{tool_calls:U,...W}=K,J=M(K,"tool_calls")?U:x.tool_calls;if(bl(W),ps(R.message,W),F?.expires_at!=null&&F.id==null&&F.data==null&&F.transcript==null&&k==null&&T==null&&L==null&&D==null&&J==null&&Object.keys(W).length===0)c(this,$t,"f").add(C);if(T)R.message.refusal=(R.message.refusal||"")+T;if(D)R.message.role=D;if(F){let X=(a=R.message).audio??(a.audio={});if(F.id!=null)X.id=F.id;if(F.data!=null)X.data=(X.data??"")+F.data;if(F.transcript!=null)X.transcript=(X.transcript??"")+F.transcript;if(F.expires_at!=null)X.expires_at=F.expires_at}if(L)if(R.message.function_call){if(L.name)R.message.function_call.name=L.name;if(L.arguments)(u=R.message.function_call).arguments??(u.arguments=""),R.message.function_call.arguments+=L.arguments}else R.message.function_call=L;if(k!=null)if(!R.message.refusal&&ct(c(this,ie,"f")?.response_format)){let X=c(this,G,"m",Yr).call(this,R),Le=X.content_parse_state??(X.content_parse_state=oc()),ne=ic(Le,c(this,De,"f"),k);if(R.message.content=(ze(R.message,"content")||"")+k,!Le.has_non_whitespace)R.message.parsed=null;else if(ne&&ac(Le,c(this,De,"f")))c(this,G,"m",Qr).call(this,f),R.message.parsed=pl(mr(R.message.content));else if(k.length>0)R.message.parsed=null}else R.message.content=(R.message.content||"")+k;if(J){let X=(l=R.message).tool_calls??(l.tool_calls=[]);for(let Le of J){let{index:ne,id:zo,type:Dr,function:Ln,custom:ft,...Xo}=Le;if(!Number.isSafeInteger(ne)||ne<0||ne>=jt)throw new m(`Chat completion stream contains an invalid tool call index: ${ne}`);let Ho="",ue=X[ne]??(X[ne]={}),Ie=Ln?.name,ke=c(this,Ke,"f")?c(this,G,"m",Yr).call(this,R):void 0,Ne=ke?.tool_call_identities.get(ne);if(Ne){if(ec(ue,Ne),Dr!==void 0&&Dr!==Ne.type||Ie!==void 0&&Ie!==Ne.name)throw new m("Chat completion stream contains a changed tool call identity")}if(ps(ue,Xo),zo)ue.id=zo;if(Dr)ue.type=Dr;if(ft){let Me=ue.custom??(ue.custom={name:ft.name??"",input:""});if(ft.name)Me.name=ft.name;if(ft.input)Me.input+=ft.input}if(Ln){let Me=ue.function??(ue.function={name:Ie??"",arguments:""});if(Ie)Me.name=Ie;if(ke&&!Ne){let Ce=ji(ue),ea=Ce&&c(this,ie,"f")?.tools?.find((nt)=>at(nt)&&nt.function.name===Ce.name);if(Ce){if(Ne={...Ce,parseable:ea!==void 0&&_i(c(this,ie,"f"),{type:Ce.type,function:{name:Ce.name}})},ke.tool_call_identities.set(ne,Ne),!Ne.parseable){let nt=ke.tool_call_parse_states.get(ne);if(nt)c(this,De,"f").bytes-=nt.bytes,c(this,De,"f").fragments-=nt.fragments,c(this,De,"f").work-=nt.work,ke.tool_call_parse_states.delete(ne)}}}let pt=Ln.arguments;if(pt!=null)if(Ho=pt,ke&&Ne?.parseable!==!1){let Ce=ke.tool_call_parse_states.get(ne);if(!Ce)Ce=oc(),ke.tool_call_parse_states.set(ne,Ce);let ea=ic(Ce,c(this,De,"f"),pt),nt=ze(Me,"arguments");if(typeof nt!=="string")throw new m("Chat completion stream contains an unsafe structured JSON snapshot");if(Me.arguments=nt+pt,ea&&Ne?.parseable===!0&&ac(Ce,c(this,De,"f")))c(this,G,"m",Qr).call(this,f),Me.parsed_arguments=pl(mr(Me.arguments));else if(pt.length>0&&M(Me,"parsed_arguments"))Me.parsed_arguments=void 0}else Me.arguments+=pt}j.push(Object.freeze({index:ne,arguments_delta:Ho}))}}Object.freeze(j)}return f},Symbol.asyncIterator)](){return this._createIterator((e)=>{let t=(n)=>e(n);return this.on("chunk",t),()=>this.off("chunk",t)},{onReturn:()=>this.abort()})}toReadableStream(){return new Ae(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function nh(e,t,n,s){let{id:o,choices:a,created:u,model:l,system_fingerprint:f,...h}=e,_={...h,id:o,choices:_l(a,$i,"choice",(w)=>{let y=s.get(w);if(!y)throw new m("Chat completion stream contains an unsafe structured JSON snapshot");let P=new Proxy(w,{get(U,W,J){return W==="message"?y.message:Reflect.get(U,W,J)}}),{message:I,finish_reason:x,index:v,logprobs:C,...E}=P,S=new Proxy(I,{get(U,W,J){if(W==="content")return y.content;if(W==="refusal")return y.refusal;if(W==="tool_calls")return y.toolCallCollection;return Reflect.get(U,W,J)}}),{content:j=null,function_call:R,tool_calls:F,audio:k,...T}=S,L=x??(n.has(v)&&sh(k)?"stop":null);if(!L)throw new m(`missing finish_reason for choice ${v}`);let D=k?{audio:k}:{},K=S.role;if(!K)throw new m(`missing role for choice ${v}`);if(R){let{arguments:U,name:W}=R;if(U==null)throw new m(`missing function_call.arguments for choice ${v}`);if(!W)throw new m(`missing function_call.name for choice ${v}`);return{...E,message:{...D,content:j,function_call:{arguments:U,name:W},role:K,refusal:S.refusal??null},finish_reason:L,index:v,logprobs:C}}if(F)return{...E,index:v,finish_reason:L,logprobs:C,message:{...T,...D,role:K,content:j,refusal:S.refusal??null,tool_calls:_l(F,jt,"tool-call",(U,W)=>{let J=y.toolCalls.get(W);if(!J){let ue=ji(U);if(ue&&_i(t,{type:ue.type,function:{name:ue.name}}))throw new m("Chat completion stream contains an unsafe structured JSON snapshot")}if(J&&J.tool!==U)throw new m("Chat completion stream contains a changed tool call identity");let X=J&&new Proxy(J.function,{get(ue,Ie,ke){if(Ie==="arguments")return J.arguments;if(Ie==="name")return J.name;return Reflect.get(ue,Ie,ke)}}),Le=J&&X?new Proxy(U,{get(ue,Ie,ke){if(Ie==="type")return J.type;if(Ie==="function")return X;return Reflect.get(ue,Ie,ke)}}):U;if(Le.type==null)throw new m(`missing choices[${v}].tool_calls[${W}].type`);if(Le.type==="custom"){let{custom:ue,type:Ie,id:ke,...Ne}=Le,{input:Me="",name:pt,...Ce}=ue||{};if(pt==null)throw new m(`missing choices[${v}].tool_calls[${W}].custom.name`);return{...Ne,id:ke||`call_${Ve()}`,type:Ie,custom:{...Ce,name:pt,input:Me}}}let{function:ne,type:zo,id:Dr,...Ln}=Le,{arguments:ft,name:Xo,...Ho}=ne||{};if(Xo==null)throw new m(`missing choices[${v}].tool_calls[${W}].function.name`);if(ft==null)throw new m(`missing choices[${v}].tool_calls[${W}].function.arguments`);return{...Ln,id:Dr||`call_${Ve()}`,type:zo,function:{...Ho,name:Xo,arguments:ft}}})}};return{...E,message:{...T,...D,content:j,role:K,refusal:S.refusal??null},finish_reason:L,index:v,logprobs:C}}),created:u,model:l,object:"chat.completion",...f?{system_fingerprint:f}:{}};return zu(_,t)}function sh(e){return e?.id!=null&&e.data!=null&&e.transcript!=null&&e.expires_at!=null}function bl(e){}function wl(e){return e}class en extends Lt{static fromReadableStream(e){let t=new en(null);return t._run(()=>t._fromReadableStream(e)),t}toReadableStream(){let e,t,n=this._createIterator((o)=>{let a=(l)=>{e=l,o(l)},u=(l)=>{if(It(l)){t=l.tool_calls?.map((f)=>f.id);return}if(es(l)){if(!e)throw new m("cannot serialize a tool message before receiving any chunks");o(Al(e,l,t)),t=void 0}};return this.on("chunk",a),this.on("message",u),()=>{this.off("chunk",a),this.off("message",u)}},{onReturn:()=>this.abort()});return new Ae(()=>n,this.controller).toReadableStream()}static runTools(e,t,n){let s=new en(t),o={...n,__metadata:{...n?.__metadata,helperMethod:"runTools"}};return s._run(()=>s._runTools(e,t,s,o)),s}}class Mt extends p{constructor(){super(...arguments);this.messages=new Hr(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Xu(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:"chat.completions.parse"}})._thenUnwrap((n)=>Zn(n,e))}runTools(e,t){if(e.stream)return en.runTools(this._client,e,t);return ls.runTools(this._client,e,t)}stream(e,t){return Lt.createChatCompletion(this._client,e,t)}}Mt.Messages=Hr;class _r extends p{constructor(){super(...arguments);this.completions=new Mt(this._client)}}_r.Completions=Mt;class ms extends p{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",O,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}class _s extends p{list(e={},t){return this._client.getAPIList("/organization/audit_logs",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}class ys extends p{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(d`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",ye,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",ye,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}}class gs extends p{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/data_retention",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}}class bs extends p{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}class ws extends p{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",re,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}class As extends p{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}class Ps extends p{retrieve(e){return this._client.get("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/spend_limit",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}}class Is extends p{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get("/organization/usage/completions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get("/organization/costs",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get("/organization/usage/embeddings",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get("/organization/usage/images",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get("/organization/usage/moderations",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}class xs extends p{create(e,t,n){return this._client.post(d`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:s}=t;return this._client.get(d`/organization/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/groups/${e}/roles`,re,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:s}=t;return this._client.delete(d`/organization/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class Ss extends p{create(e,t,n){return this._client.post(d`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:s}=t;return this._client.get(d`/organization/groups/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/groups/${e}/users`,re,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:s}=t;return this._client.delete(d`/organization/groups/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class yr extends p{constructor(){super(...arguments);this.users=new Ss(this._client),this.roles=new xs(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",re,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}yr.Users=Ss;yr.Roles=xs;class Rs extends p{retrieve(e,t,n){let{project_id:s}=t;return this._client.get(d`/organization/projects/${s}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/api_keys`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/organization/projects/${s}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class vs extends p{list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/certificates`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(d`/organization/projects/${e}/certificates/activate`,ye,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(d`/organization/projects/${e}/certificates/deactivate`,ye,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}}class Es extends p{retrieve(e,t){return this._client.get(d`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}}class Os extends p{retrieve(e,t){return this._client.get(d`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}}class ks extends p{retrieve(e,t){return this._client.get(d`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}}class Cs extends p{listRateLimits(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/rate_limits`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/organization/projects/${s}/rate_limits/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}}class Ts extends p{create(e,t,n){return this._client.post(d`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(d`/projects/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/projects/${s}/roles/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/projects/${e}/roles`,re,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/projects/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class $s extends p{create(e,t,n){return this._client.post(d`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(d`/organization/projects/${s}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/organization/projects/${s}/spend_alerts/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/spend_alerts`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/organization/projects/${s}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class js extends p{retrieve(e,t){return this._client.get(d`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/projects/${e}/spend_limit`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}}class Ls extends p{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/projects/${s}/groups/${e}/roles`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,group_id:o}=t;return this._client.get(d`/projects/${s}/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:s,...o}=t;return this._client.getAPIList(d`/projects/${s}/groups/${e}/roles`,re,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s,group_id:o}=t;return this._client.delete(d`/projects/${s}/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class tn extends p{constructor(){super(...arguments);this.roles=new Ls(this._client)}create(e,t,n){return this._client.post(d`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,...o}=t;return this._client.get(d`/organization/projects/${s}/groups/${e}`,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/groups`,re,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/organization/projects/${s}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}tn.Roles=Ls;class Ms extends p{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/organization/projects/${s}/service_accounts/${e}/api_keys`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}}class rn extends p{constructor(){super(...arguments);this.apiKeys=new Ms(this._client)}create(e,t,n){return this._client.post(d`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(d`/organization/projects/${s}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/organization/projects/${s}/service_accounts/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/service_accounts`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/organization/projects/${s}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}rn.APIKeys=Ms;class Bs extends p{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/projects/${s}/users/${e}/roles`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,user_id:o}=t;return this._client.get(d`/projects/${s}/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:s,...o}=t;return this._client.getAPIList(d`/projects/${s}/users/${e}/roles`,re,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s,user_id:o}=t;return this._client.delete(d`/projects/${s}/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class nn extends p{constructor(){super(...arguments);this.roles=new Bs(this._client)}create(e,t,n){return this._client.post(d`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(d`/organization/projects/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(d`/organization/projects/${s}/users/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/projects/${e}/users`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(d`/organization/projects/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}nn.Roles=Bs;class ge extends p{constructor(){super(...arguments);this.users=new nn(this._client),this.serviceAccounts=new rn(this._client),this.apiKeys=new Rs(this._client),this.rateLimits=new Cs(this._client),this.modelPermissions=new ks(this._client),this.hostedToolPermissions=new Os(this._client),this.groups=new tn(this._client),this.roles=new Ts(this._client),this.dataRetention=new Es(this._client),this.spendLimit=new js(this._client),this.spendAlerts=new $s(this._client),this.certificates=new vs(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(d`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(d`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}}ge.Users=nn;ge.ServiceAccounts=rn;ge.APIKeys=Rs;ge.RateLimits=Cs;ge.ModelPermissions=ks;ge.HostedToolPermissions=Os;ge.Groups=tn;ge.Roles=Ts;ge.DataRetention=Es;ge.SpendLimit=js;ge.SpendAlerts=$s;ge.Certificates=vs;class Ds extends p{create(e,t,n){return this._client.post(d`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:s}=t;return this._client.get(d`/organization/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/organization/users/${e}/roles`,re,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:s}=t;return this._client.delete(d`/organization/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class sn extends p{constructor(){super(...arguments);this.roles=new Ds(this._client)}retrieve(e,t){return this._client.get(d`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(d`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(d`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}sn.Roles=Ds;class be extends p{constructor(){super(...arguments);this.auditLogs=new _s(this._client),this.adminAPIKeys=new ms(this._client),this.usage=new Is(this._client),this.invites=new bs(this._client),this.users=new sn(this._client),this.groups=new yr(this._client),this.roles=new ws(this._client),this.dataRetention=new gs(this._client),this.spendLimit=new Ps(this._client),this.spendAlerts=new As(this._client),this.certificates=new ys(this._client),this.projects=new ge(this._client)}}be.AuditLogs=_s;be.AdminAPIKeys=ms;be.Usage=Is;be.Invites=bs;be.Users=sn;be.Groups=yr;be.Roles=ws;be.DataRetention=gs;be.SpendLimit=Ps;be.SpendAlerts=As;be.Certificates=ys;be.Projects=ge;class gr extends p{constructor(){super(...arguments);this.organization=new be(this._client)}}gr.Organization=be;class Ns extends p{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:b([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class Fs extends p{create(e,t){return this._client.post("/audio/transcriptions",oe({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class Ws extends p{create(e,t){return this._client.post("/audio/translations",oe({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class xt extends p{constructor(){super(...arguments);this.transcriptions=new Fs(this._client),this.translations=new Ws(this._client),this.speech=new Ns(this._client)}}xt.Transcriptions=Fs;xt.Translations=Ws;xt.Speech=Ns;class on extends p{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",O,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(d`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}}class Us extends p{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/assistants/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/assistants/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",O,{query:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/assistants/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}}class qs extends p{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}}class Ks extends p{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}}class br extends p{constructor(){super(...arguments);this.sessions=new qs(this._client),this.transcriptionSessions=new Ks(this._client)}}br.Sessions=qs;br.TranscriptionSessions=Ks;class zs extends p{create(e,t,n){return this._client.post(d`/agents/environments/${e}/files`,{body:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/agents/environments/${e}/files`,Hn,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class Xs extends p{create(e={},t){return this._client.post("/agents/environments/templates",{body:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/agents/environments/templates/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(d`/agents/environments/templates/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents/environments/templates",O,{query:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/agents/environments/templates/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}class wr extends p{constructor(){super(...arguments);this.files=new zs(this._client),this.templates=new Xs(this._client)}retrieve(e,t){return this._client.get(d`/agents/environments/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}wr.Files=zs;wr.Templates=Xs;var an,Li,Ar,Mi;class dc{constructor(){an.set(this,void 0),Li.set(this,!1),Ar.set(this,new Set),Mi.set(this,new Set)}accept(e){if(c(this,Ar,"f").has(e.event_id))return!1;if(c(this,Ar,"f").size===1024){let t=c(this,Ar,"f").values().next();if(!t.done)c(this,Ar,"f").delete(t.value)}if(c(this,Ar,"f").add(e.event_id),e.type==="agent.session.turn.created"&&e.turn.subagent_id===null&&c(this,an,"f")===void 0)A(this,an,e.turn_id,"f");if((e.type==="agent.session.turn.completed"||e.type==="agent.session.turn.failed"||e.type==="agent.session.turn.cancelled")&&c(this,an,"f")!==void 0&&e.turn_id===c(this,an,"f"))A(this,Li,!0,"f");return!0}terminal(e){return e.type==="agent.session.failed"||e.type==="agent.session.idle"&&c(this,Li,"f")}call(e){if(e.type!=="agent.session.turn.item.added"||e.item.type!=="function_call")return;let t=e.item,n=JSON.stringify([t.turn_id,t.call_id]);if(c(this,Mi,"f").has(n))return;return c(this,Mi,"f").add(n),t}}an=new WeakMap,Li=new WeakMap,Ar=new WeakMap,Mi=new WeakMap;var ae,Bi,cn,Di,Ni,Pr,Ir,Fi,Wi,ln,Hs,Rl,xl,Ze,fc,pc,Sl;function Hh(e){if(!me(e))return!1;let t=e,n;if(t.type==="input_text")n="text";else if(t.type==="input_image")n="image_url";else return!1;return M(t,"type")&&M(t,n)&&typeof t[n]==="string"}function Jh(e){if(e===null)return null;if(typeof e==="string"||Array.isArray(e)&&e.every(Hh))return e;throw new m("Tool output must be text, content, a JSON object, or null")}function Vh(e,t){let n=me(t)?JSON.stringify(t):t,s=JSON.stringify(n);if(s===void 0)throw new m("Tool output must be JSON serializable");return{type:"agent.session.input.tool_result",turn_id:e.turn_id,call_id:e.call_id,success:!0,output:Jh(typeof n==="string"?n:JSON.parse(s))}}async function Gh(e){try{await e?.body?.cancel()}catch{}}class hc{constructor(e,t,n,s){ae.add(this),this.controller=new AbortController,Bi.set(this,!1),cn.set(this,void 0),Di.set(this,void 0),Ni.set(this,!1),Pr.set(this,void 0),Ir.set(this,void 0),Fi.set(this,void 0),Wi.set(this,void 0),ln.set(this,void 0),Hs.set(this,void 0);let o=typeof n.input==="string"?[{role:"user",content:[{type:"input_text",text:n.input}]}]:n.input;if(n.input.length===0)throw new m("input must not be empty");A(this,Pr,e,"f"),A(this,Ir,t,"f"),A(this,Fi,{type:"agent.session.input.message",input:o},"f"),A(this,Wi,new Map(Object.entries(n.toolHandlers??{})),"f");let a=b([s?.headers]);A(this,ln,a.nulls.has("idempotency-key")?void 0:a.values.get("idempotency-key")??n.idempotencyKey??s?.idempotencyKey??Ve(),"f"),a.values.delete("idempotency-key"),a.nulls.delete("idempotency-key");let{idempotencyKey:u,...l}=s??{};A(this,Hs,{...l,headers:a},"f")}abort(e){if(this.controller.abort(e),c(this,cn,"f")?.controller.abort(this.controller.signal.reason),!c(this,Ni,"f"))Gh(c(this,Di,"f"))}[(Bi=new WeakMap,cn=new WeakMap,Di=new WeakMap,Ni=new WeakMap,Pr=new WeakMap,Ir=new WeakMap,Fi=new WeakMap,Wi=new WeakMap,ln=new WeakMap,Hs=new WeakMap,ae=new WeakSet,Symbol.asyncIterator)](){if(c(this,Bi,"f"))throw new m("An AgentSessionStream can only be consumed once");return A(this,Bi,!0,"f"),c(this,ae,"m",Rl).call(this)}}Rl=async function*(){let t=c(this,Hs,"f").signal,n=()=>this.abort(t?.aborted?t.reason:this.controller.signal.reason);t?.addEventListener("abort",n,{once:!0}),this.controller.signal.addEventListener("abort",n,{once:!0});let s={...c(this,Hs,"f"),signal:this.controller.signal},o=new dc;try{if(t?.aborted)this.abort(t.reason);if(c(this,ae,"m",Ze).call(this),(await c(this,Pr,"f").retrieve(c(this,Ir,"f"),s)).status!=="idle")throw new m("sessions.stream requires an idle session; use sessions.events.stream for active sessions");let u=await c(this,Pr,"f").events.stream(c(this,Ir,"f"),s).withResponse();A(this,cn,u.data,"f"),A(this,Di,u.response,"f"),c(this,ae,"m",Ze).call(this),await c(this,Pr,"f").events.create(c(this,Ir,"f"),{events:[c(this,Fi,"f")],...c(this,ln,"f")===void 0?{}:{"Idempotency-Key":c(this,ln,"f")}},{...s,headers:b([s.headers,{"Idempotency-Key":c(this,ln,"f")??null}])}),c(this,ae,"m",Ze).call(this),A(this,Ni,!0,"f");for await(let l of c(this,cn,"f")){if(c(this,ae,"m",Ze).call(this),!o.accept(l))continue;let f=o.terminal(l),h=o.call(l),_=h&&c(this,Wi,"f").get(h.name),w=h&&_?structuredClone(h):void 0;if(f)c(this,cn,"f").controller.abort();if(yield l,f)return;if(c(this,ae,"m",Ze).call(this),!w||!_)continue;let y=await c(this,ae,"m",xl).call(this,w,_);c(this,ae,"m",Ze).call(this),await c(this,ae,"m",Sl).call(this,y,s)}throw c(this,ae,"m",Ze).call(this),new m("Session event stream ended before the turn reached idle or failed")}finally{t?.removeEventListener("abort",n),this.controller.signal.removeEventListener("abort",n),this.abort()}},xl=async function(t,n){try{let s=typeof t.arguments==="string"?JSON.parse(t.arguments):t.arguments;if(!me(s))throw new m("Function arguments must be a JSON object");return Vh(t,await c(this,ae,"m",pc).call(this,()=>n(s)))}catch{return c(this,ae,"m",Ze).call(this),{type:"agent.session.input.tool_result",turn_id:t.turn_id,call_id:t.call_id,success:!1,error:"Tool handler failed."}}},Ze=function(){if(this.controller.signal.aborted)throw c(this,ae,"m",fc).call(this)},fc=function(){let t=new Z;return Object.defineProperty(t,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),t},pc=async function(t){let n,s=new Promise((o,a)=>{n=()=>a(c(this,ae,"m",fc).call(this)),this.controller.signal.addEventListener("abort",n,{once:!0})});try{c(this,ae,"m",Ze).call(this);let o=async()=>await t();return await Promise.race([o(),s])}finally{if(n)this.controller.signal.removeEventListener("abort",n)}},Sl=async function e(t,n,s=Ve(),o=0){c(this,ae,"m",Ze).call(this);try{await c(this,Pr,"f").events.create(c(this,Ir,"f"),{events:[t],"Idempotency-Key":s},n)}catch(a){let u=[100,300,600][o];if(u===void 0||!(a instanceof mt)||a.code!=="invalid_request_error"||!a.error||!("message"in a.error)||a.error.message!==`Unknown pending tool call: ${t.call_id}`)throw a;let l;try{await c(this,ae,"m",pc).call(this,()=>new Promise((f)=>{l=setTimeout(f,u)}))}finally{if(l!==void 0)clearTimeout(l)}await c(this,ae,"m",e).call(this,t,n,s,o+1)}};class Js extends p{retrieve(e,t,n){let{session_id:s}=t;return this._client.get(d`/agents/sessions/${s}/artifacts/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/agents/sessions/${e}/artifacts`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{session_id:s}=t;return this._client.delete(d`/agents/sessions/${s}/artifacts/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}content(e,t,n){let{session_id:s}=t;return this._client.get(d`/agents/sessions/${s}/artifacts/${e}/content`,{...n,headers:b([{"OpenAI-Beta":"agents=v1",Accept:"application/octet-stream"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class Vs extends p{create(e,t,n){let{"Idempotency-Key":s,...o}=t;return this._client.post(d`/agents/sessions/${e}/events`,{body:o,...n,headers:b([{"OpenAI-Beta":"agents=v1",Accept:"*/*",...s!=null?{"Idempotency-Key":s}:void 0},n?.headers]),__security:{bearerAuth:!0}})}stream(e,t){return this._client.get(d`/agents/sessions/${e}/events`,{...t,headers:b([{"OpenAI-Beta":"agents=v1",Accept:"text/event-stream"},t?.headers]),stream:!0,__security:{bearerAuth:!0}})}}class Gs extends p{list(e,t={},n){return this._client.getAPIList(d`/agents/sessions/${e}/items`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class Ys extends p{retrieve(e,t,n){let{session_id:s}=t;return this._client.get(d`/agents/sessions/${s}/turns/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/agents/sessions/${e}/turns`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class Qs extends p{list(e,t,n){let{session_id:s,...o}=t;return this._client.getAPIList(d`/agents/sessions/${s}/subagents/${e}/items`,O,{query:o,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class Zs extends p{list(e,t,n){let{session_id:s,subagent_id:o,...a}=t;return this._client.getAPIList(d`/agents/sessions/${s}/subagents/${o}/turns/${e}/items`,O,{query:a,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class dn extends p{constructor(){super(...arguments);this.items=new Zs(this._client)}retrieve(e,t,n){let{session_id:s,subagent_id:o}=t;return this._client.get(d`/agents/sessions/${s}/subagents/${o}/turns/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{session_id:s,...o}=t;return this._client.getAPIList(d`/agents/sessions/${s}/subagents/${e}/turns`,O,{query:o,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}dn.Items=Zs;class xr extends p{constructor(){super(...arguments);this.items=new Qs(this._client),this.turns=new dn(this._client)}retrieve(e,t,n){let{session_id:s}=t;return this._client.get(d`/agents/sessions/${s}/subagents/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/agents/sessions/${e}/subagents`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}xr.Items=Qs;xr.Turns=dn;class lt extends p{constructor(){super(...arguments);this.subagents=new xr(this._client),this.artifacts=new Js(this._client),this.items=new Gs(this._client),this.events=new Vs(this._client),this.turns=new Ys(this._client)}stream(e,t,n){return new hc(this,e,t,n)}create(e,t){return this._client.post("/agents/sessions",{body:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/agents/sessions/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(d`/agents/sessions/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents/sessions",O,{query:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/agents/sessions/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}lt.Subagents=xr;lt.Artifacts=Js;lt.Items=Gs;lt.Events=Vs;lt.Turns=Ys;class eo extends p{create(e,t,n){return this._client.post(d`/vaults/${e}/credentials`,{body:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vault_id:s}=t;return this._client.get(d`/vaults/${s}/credentials/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vault_id:s,...o}=t;return this._client.post(d`/vaults/${s}/credentials/${e}`,{body:o,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/vaults/${e}/credentials`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vault_id:s}=t;return this._client.delete(d`/vaults/${s}/credentials/${e}`,{...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class fn extends p{constructor(){super(...arguments);this.credentials=new eo(this._client)}create(e={},t){return this._client.post("/vaults",{body:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/vaults/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vaults",O,{query:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/vaults/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}fn.Credentials=eo;class Bt extends p{constructor(){super(...arguments);this.environments=new wr(this._client),this.vaults=new fn(this._client),this.sessions=new lt(this._client)}create(e,t){return this._client.post("/agents",{body:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/agents/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(d`/agents/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents",O,{query:e,...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/agents/${e}`,{...t,headers:b([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}}Bt.Environments=wr;Bt.Vaults=fn;Bt.Sessions=lt;class to extends p{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(d`/chatkit/sessions/${e}/cancel`,{...t,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}}class ro extends p{retrieve(e,t){return this._client.get(d`/chatkit/threads/${e}`,{...t,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",q,{query:e,...t,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/chatkit/threads/${e}`,{...t,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(d`/chatkit/threads/${e}/items`,q,{query:t,...n,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}}class Sr extends p{constructor(){super(...arguments);this.sessions=new to(this._client),this.threads=new ro(this._client)}}Sr.Sessions=to;Sr.Threads=ro;class no extends p{list(e,t={},n){let{betas:s,...o}=t??{};return this._client.getAPIList(d`/responses/${e}/input_items?beta=true`,O,{query:o,...n,headers:b([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}}class so extends p{count(e={},t){let{betas:n,...s}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:s,...t,headers:b([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}}class Rr extends p{constructor(){super(...arguments);this.inputItems=new no(this._client),this.inputTokens=new so(this._client)}create(e,t){let{betas:n,...s}=e;return this._client.post("/responses?beta=true",{body:s,...t,headers:b([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},n){let{betas:s,...o}=t??{};return this._client.get(d`/responses/${e}?beta=true`,{query:o,...n,headers:b([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},n){let{betas:s}=t??{};return this._client.delete(d`/responses/${e}?beta=true`,{...n,headers:b([{Accept:"*/*",...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},n){let{betas:s}=t??{};return this._client.post(d`/responses/${e}/cancel?beta=true`,{...n,headers:b([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:n,...s}=e;return this._client.post("/responses/compact?beta=true",{body:s,...t,headers:b([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}}Rr.InputItems=no;Rr.InputTokens=so;class oo extends p{create(e,t,n){return this._client.post(d`/threads/${e}/messages`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/messages/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/messages/${e}`,{body:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/threads/${e}/messages`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:s}=t;return this._client.delete(d`/threads/${s}/messages/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}class io extends p{retrieve(e,t,n){let{thread_id:s,run_id:o,...a}=t;return this._client.get(d`/threads/${s}/runs/${o}/steps/${e}`,{query:a,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:s,...o}=t;return this._client.getAPIList(d`/threads/${s}/runs/${e}/steps`,O,{query:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}var Ui=(e)=>{if(typeof globalThis.Buffer<"u"){let t=globalThis.Buffer.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(typeof atob<"u"){let t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}throw new m("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},vl=(e)=>{if(typeof Buffer<"u"){let t=Buffer.from(e,"base64");if(t.length%Float32Array.BYTES_PER_ELEMENT!==0)throw RangeError("Invalid base64-encoded float32 array: byte length must be a multiple of 4");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,s=new Uint8Array(n);for(let o=0;o<n;o++)s[o]=t.charCodeAt(o);return Array.from(new Float32Array(s.buffer))}};var Ee=(e)=>{try{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0}catch{return}return};var Ol=1024,ym=65536;function gm(e){switch(e){case"value":case"arguments":case"input":case"text":case"content":case"annotations":case"metadata":case"name":case"role":case"status":case"tool_calls":case"step_details":return e;default:return"unknown"}}var ao=new WeakMap,Dt=new WeakSet;function kl(e){return{arrays:new Map,cacheArrays:e,records:new WeakMap}}function Cl(e){for(let[t,n]of e.arrays)if(n.cacheable&&!Dt.has(t))ao.set(t,{length:n.length,ownEntryCount:n.ownEntryCount});else ao.delete(t)}function El(e){return typeof e==="string"||typeof e==="number"}function Tl(e,t){return t.every(El)&&e.every(El)}function bm(e){let t=0;for(let n of Object.keys(e)){let s=Number(n);if(Number.isSafeInteger(s)&&s>=0&&s<e.length&&String(s)===n)t+=1}return t}function wm(e,t,n){if(!t)return 0;if(n?.length===e.length)return n.ownEntryCount;return bm(e)}function Am(e,t,n){let{index:s}=e;if(t==="array"&&(s===null||s===void 0))throw Error("Expected array delta entry to have an `index` property");if(t==="array"&&typeof s!=="number")throw TypeError("Expected array delta entry `index` property to be a number but got an invalid value");if(!Number.isSafeInteger(s)||s<0||s>=n+Ol||s>=ym)throw new m(`Assistant stream delta contains an invalid ${t} index: ${typeof s==="number"?s:"unknown"}`);return s}function $l(e,t,n,s,o){let a=s.arrays.get(e);if(!a){let u=s.cacheArrays&&!Dt.has(e),l=u?ao.get(e):void 0;a={baselineLength:e.length,cacheable:u,enforceSparseHoleBudget:u,entries:new Map,length:e.length,ownEntryCount:wm(e,u,l)},s.arrays.set(e,a)}for(let u of t){if(!me(u))throw Error("Expected array delta entry to be an object but got an invalid value");let l=Am(u,n,a.baselineLength),f;if(a.entries.has(l))f=a.entries.get(l);else if(M(e,l)){if(f=e[l],f===null||f===void 0)a.entries.set(l,u)}else a.entries.set(l,u),a.ownEntryCount+=1;let h=Math.max(a.length,l+1);if(a.enforceSparseHoleBudget&&h-a.ownEntryCount>Ol)throw new m(`Assistant stream delta contains an invalid ${n} index: ${l}`);if(me(f))o(f,u,s);a.length=h}}function qi(e,t,n){let s=n.records.get(e);for(let[o,a]of Object.entries(t)){if(o==="index"||o==="type")continue;let u;if(s?.has(o))u=s.get(o);else if(M(e,o))u=e[o];if(u===null||u===void 0){if(!s)s=new Map,n.records.set(e,s);s.set(o,a);continue}if(me(u)&&me(a))qi(u,a,n);else if(Array.isArray(u)&&Array.isArray(a)&&!Tl(u,a))$l(u,a,"array",n,qi)}}function Ki(e){return(me(e)||Array.isArray(e))&&Dt.has(e)}function et(e){if(!me(e)&&!Array.isArray(e)||Dt.has(e))return;if(Dt.add(e),Array.isArray(e))ao.delete(e);for(let t of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,t);if(n&&"value"in n)et(n.value)}}function _c(e,t,n){if(Dt.has(e))et(n);Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function Pm(e){let{index:t}=e;if(t===null||t===void 0)throw Error("Expected array delta entry to have an `index` property");if(typeof t!=="number")throw TypeError("Expected array delta entry `index` property to be a number but got an invalid value");return t}function Im(e,t,n){if(Tl(e,t)){e.push(...t),ao.delete(e);return}for(let s of t){if(!me(s))throw Error("Expected array delta entry to be an object but got an invalid value");let o=Pm(s);if(M(e,o)){let a=e[o];if(a===null||a===void 0){if(Dt.has(e))et(s);e[o]=s}else e[o]=n(a,s)}else _c(e,o,s)}}function mc(e,t){let n=Dt.has(e);for(let[s,o]of Object.entries(t)){if(s==="__proto__"||s==="constructor"||s==="prototype")throw new m(`Assistant stream delta contains an unsafe property: ${s}`);if(!M(e,s)){if(n)et(o);e[s]=o;continue}let a=e[s];if(a===null||a===void 0){if(n)et(o);e[s]=o;continue}if(s==="index"||s==="type"){e[s]=o;continue}if(typeof a==="string"&&typeof o==="string")a+=o;else if(typeof a==="number"&&typeof o==="number")a+=o;else if(me(a)&&me(o))a=mc(a,o);else if(Array.isArray(a)&&Array.isArray(o)){Im(a,o,mc);continue}else throw TypeError(`Unhandled record type: ${gm(s)}`);e[s]=a}return e}function co(e){if(!me(e)&&!Array.isArray(e))return;for(let[t,n]of Object.entries(e)){if(t==="__proto__"||t==="constructor"||t==="prototype")throw new m(`Assistant stream delta contains an unsafe property: ${t}`);co(n)}}function zi(e,t,n=!1){co(t);let s=e,o=t,a=kl(n&&!Ki(e));return qi(s,o,a),mc(s,o),Cl(a),e}function jl(e,t,n,s=!0){co(t);let o=kl(s&&!Ki(e));return $l(e,t,n,o,qi),()=>Cl(o)}var B,Oe,Nt,He,mn,hn,Pe,St,Er,Ft,Rt,vr,$e,lo,fo,Wt,po,ho,Ll,pn,Ml,uo,Bl,Dl,ce,Nl,Fl,Wl,Ul,ql;function xm(e){let t=Object.getOwnPropertyDescriptor(e,"event"),n=Object.getOwnPropertyDescriptor(e,"data"),s=Reflect.get(e,"event",e),o=Reflect.get(e,"data",e),a=o;if(s==="thread.message.created"||s==="thread.message.in_progress"||s==="thread.message.delta"||s==="thread.message.completed"||s==="thread.message.incomplete"||s==="thread.run.step.created"||s==="thread.run.step.in_progress"||s==="thread.run.step.delta"||s==="thread.run.step.completed"||s==="thread.run.step.failed"||s==="thread.run.step.cancelled"||s==="thread.run.step.expired"){let f=Object.getOwnPropertyDescriptor(o,"id");if(f&&"value"in f&&o.id!==f.value){let h=f.value;a=new Proxy(o,{get(_,w){return w==="id"?h:Reflect.get(_,w,_)}})}}let u=Object.freeze({event:s,data:a}),l=t!==void 0&&"value"in t&&t.value===s&&n!==void 0&&"value"in n&&n.value===o&&a===o;return{event:u,exposedEvent:l?e:{event:s,data:a}}}class tt extends fr{constructor(){super(...arguments);B.add(this),Oe.set(this,Object.create(null)),Nt.set(this,new Map),He.set(this,void 0),mn.set(this,Object.create(null)),hn.set(this,new Map),Pe.set(this,void 0),St.set(this,void 0),Er.set(this,void 0),Ft.set(this,void 0),Rt.set(this,void 0),vr.set(this,void 0),$e.set(this,void 0),lo.set(this,void 0),fo.set(this,void 0),Wt.set(this,void 0)}[(Oe=new WeakMap,Nt=new WeakMap,He=new WeakMap,mn=new WeakMap,hn=new WeakMap,Pe=new WeakMap,St=new WeakMap,Er=new WeakMap,Ft=new WeakMap,Rt=new WeakMap,vr=new WeakMap,$e=new WeakMap,lo=new WeakMap,fo=new WeakMap,Wt=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){return this._createIterator((e)=>{let t=(n)=>e(structuredClone(n));return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}static fromReadableStream(e){let t=new tt;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=Ae.fromReadableStream(e,this.controller);for await(let s of n)c(this,B,"m",po).call(this,s);if(n.controller.signal?.aborted)throw this._userAbortError();return this._addRun(c(this,B,"m",ho).call(this))}toReadableStream(){return new Ae(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s){let o=new tt;return o._run(()=>o._runToolAssistantStream(e,t,n,{...s,__metadata:{...s?.__metadata,helperMethod:"stream"}})),o}async _createToolAssistantStream(e,t,n,s){this._listenForAbort(s?.signal);let o={...n,stream:!0},a=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let u of a)c(this,B,"m",po).call(this,u);if(a.controller.signal?.aborted)throw this._userAbortError();return this._addRun(c(this,B,"m",ho).call(this))}static createThreadAssistantStream(e,t,n){let s=new tt;return s._run(()=>s._threadAssistantStream(e,t,{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}static createAssistantStream(e,t,n,s){let o=new tt;return o._run(()=>o._runAssistantStream(e,t,n,{...s,__metadata:{...s?.__metadata,helperMethod:"stream"}})),o}currentEvent(){return et(c(this,lo,"f")),c(this,lo,"f")}currentRun(){return et(c(this,fo,"f")),c(this,fo,"f")}currentMessageSnapshot(){return et(c(this,Pe,"f")),c(this,Pe,"f")}currentRunStepSnapshot(){return et(c(this,Wt,"f")),c(this,Wt,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,Oe,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,mn,"f"))}async finalRun(){if(await this.done(),!c(this,Er,"f"))throw Error("Final run was not received.");return c(this,Er,"f")}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let s={...t,stream:!0},o=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let a of o)c(this,B,"m",po).call(this,a);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(c(this,B,"m",ho).call(this))}async _createAssistantStream(e,t,n,s){this._listenForAbort(s?.signal);let o={...n,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let u of a)c(this,B,"m",po).call(this,u);if(a.controller.signal?.aborted)throw this._userAbortError();return this._addRun(c(this,B,"m",ho).call(this))}static accumulateDelta(e,t){return zi(e,t)}_addRun(e){return c(this,B,"m",ce).call(this,"run",e),e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s){return await this._createToolAssistantStream(t,e,n,s)}}po=function(t){if(this.ended)return;let{event:n,exposedEvent:s}=xm(t),o,a,u,l;switch(n.event){case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{o=c(this,B,"m",Ml).call(this,n),a=n.data;break}case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{u=c(this,B,"m",Ll).call(this,n),l=n.data;break}}if(A(this,lo,s,"f"),c(this,B,"m",Nl).call(this,s),o!==void 0&&a!==void 0)c(this,B,"m",uo).call(this,a,o);if(u!==void 0&&l!==void 0)c(this,B,"m",pn).call(this,l,u);if(u===void 0&&c(this,He,"f")!==void 0&&c(this,Wt,"f"))c(this,B,"m",pn).call(this,c(this,Wt,"f"),c(this,He,"f"));switch(n.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":{c(this,B,"m",ql).call(this,n);break}case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{if(u===void 0)throw new m("Received assistant run-step event without a canonical run-step ID");let f=c(this,Oe,"f")[u];if(f)c(this,B,"m",pn).call(this,f,u);c(this,B,"m",Dl).call(this,n,u),c(this,B,"m",pn).call(this,n.data,u);let h=c(this,Oe,"f")[u];if(h)c(this,B,"m",pn).call(this,h,u);break}case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{if(o!==void 0&&c(this,Pe,"f"))c(this,B,"m",uo).call(this,c(this,Pe,"f"),o);if(c(this,B,"m",Bl).call(this,n),o!==void 0){c(this,B,"m",uo).call(this,n.data,o);let f=c(this,mn,"f")[o];if(f)c(this,B,"m",uo).call(this,f,o)}break}case"error":throw new H(void 0,n.data,void 0,void 0);default:Sm(n)}},ho=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!c(this,Er,"f"))throw Error("Final run has not been received");return c(this,Er,"f")},Ll=function(t){let n=Object.getOwnPropertyDescriptor(t.data,"id"),s=n&&"value"in n?n.value:void 0;if(typeof s!=="string"||s.length===0)throw new m("Received assistant run-step event with an invalid run-step ID");if(t.event==="thread.run.step.delta"){let o=t.data.delta;if(o&&M(o,"id"))throw new m("Run-step deltas must not contain an id field")}if(t.event==="thread.run.step.created"){if(c(this,He,"f")!==void 0)throw new m(`Received run-step creation for "${s}" before the active run step "${c(this,He,"f")}" reached a terminal state`);if(M(c(this,Oe,"f"),s)||c(this,Nt,"f").has(s))throw new m(`Received run-step creation for run step "${s}", which has already been created`);return A(this,He,s,"f"),c(this,Nt,"f").set(s,s),s}if(c(this,He,"f")!==void 0){if(s!==c(this,He,"f"))throw new m(`Received ${t.event} for run step "${s}", which does not match the active run step "${c(this,He,"f")}"`);return s}if(t.event==="thread.run.step.delta"){if(!M(c(this,Oe,"f"),s))throw new m("Received a RunStepDelta before creation of a snapshot");throw new m(`Received run-step delta for "${s}" with no active run step`)}if(M(c(this,Oe,"f"),s)||c(this,Nt,"f").has(s))throw new m(`Received run-step event for run step "${s}", which has already been created`);if(c(this,Nt,"f").set(s,s),t.event==="thread.run.step.in_progress")A(this,He,s,"f");return s},pn=function(t,n){let s=Object.getOwnPropertyDescriptor(t,"id"),o=s&&"value"in s?s.value:void 0;if(typeof o!=="string"||o.length===0)throw new m("Received assistant run-step event with an invalid run-step ID");let a=c(this,Nt,"f").get(o);if(a!==void 0&&a!==n)throw new m(`Received run-step creation for run step "${o}", which has already been created`);c(this,Nt,"f").set(o,n)},Ml=function(t){let n=Object.getOwnPropertyDescriptor(t.data,"id"),s=n&&"value"in n?n.value:void 0;if(typeof s!=="string"||s.length===0)throw new m("Received assistant message event with an invalid message ID");if(t.event==="thread.message.created"){if(c(this,Pe,"f"))throw new m(`Received message creation for "${s}" before the active message "${c(this,St,"f")}" reached a terminal state`);if(M(c(this,mn,"f"),s)||c(this,hn,"f").has(s))throw new m(`Received message creation for message "${s}", which has already been created`);return A(this,St,s,"f"),c(this,hn,"f").set(s,s),s}if(!c(this,Pe,"f")){if(t.event==="thread.message.delta")throw new m("Received a delta with no existing snapshot (there should be one from message creation)");throw new m("Received thread message event with no existing snapshot")}if(s!==c(this,St,"f"))throw new m(`Received ${t.event} for message "${s}", which does not match the active message "${c(this,St,"f")}"`);return s},uo=function(t,n){let s=Object.getOwnPropertyDescriptor(t,"id"),o=s&&"value"in s?s.value:void 0;if(typeof o!=="string"||o.length===0)throw new m("Received assistant message event with an invalid message ID");let a=c(this,hn,"f").get(o);if(a!==void 0&&a!==n)throw new m(`Received message creation for message "${o}", which has already been created`);c(this,hn,"f").set(o,n)},Bl=function(t){let[n,s]=c(this,B,"m",Wl).call(this,t,c(this,Pe,"f"));if(A(this,Pe,n,"f"),!c(this,St,"f"))throw new m("Received thread message event with no active message ID");c(this,mn,"f")[c(this,St,"f")]=n;for(let o of s){let a=n.content[o.index];if(a?.type==="text")c(this,B,"m",ce).call(this,"textCreated",a.text)}switch(t.event){case"thread.message.created":{A(this,Ft,void 0,"f"),A(this,Rt,void 0,"f"),c(this,B,"m",ce).call(this,"messageCreated",t.data);break}case"thread.message.in_progress":break;case"thread.message.delta":{if(c(this,B,"m",ce).call(this,"messageDelta",t.data.delta,n),t.data.delta.content)for(let o of t.data.delta.content){if(o.type==="text"&&o.text){let a=o.text,u=n.content[o.index];if(u&&u.type==="text")c(this,B,"m",ce).call(this,"textDelta",a,u.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!==c(this,Ft,"f")){if(c(this,Rt,"f"))switch(c(this,Rt,"f").type){case"text":{c(this,B,"m",ce).call(this,"textDone",c(this,Rt,"f").text,c(this,Pe,"f"));break}case"image_file":{c(this,B,"m",ce).call(this,"imageFileDone",c(this,Rt,"f").image_file,c(this,Pe,"f"));break}}A(this,Ft,o.index,"f")}A(this,Rt,n.content[o.index],"f")}break}case"thread.message.completed":case"thread.message.incomplete":{if(c(this,Ft,"f")!==void 0){let o=t.data.content[c(this,Ft,"f")];if(o)switch(o.type){case"image_file":{c(this,B,"m",ce).call(this,"imageFileDone",o.image_file,c(this,Pe,"f"));break}case"text":{c(this,B,"m",ce).call(this,"textDone",o.text,c(this,Pe,"f"));break}}}if(c(this,Pe,"f"))c(this,B,"m",ce).call(this,"messageDone",t.data);A(this,Ft,void 0,"f"),A(this,Rt,void 0,"f"),A(this,Pe,void 0,"f"),A(this,St,void 0,"f")}}},Dl=function(t,n){let s=c(this,B,"m",Fl).call(this,t,n);switch(A(this,Wt,s,"f"),t.event){case"thread.run.step.created":{A(this,vr,void 0,"f"),A(this,$e,void 0,"f"),c(this,B,"m",ce).call(this,"runStepCreated",t.data);break}case"thread.run.step.delta":{let o=t.data.delta;if(o.step_details&&o.step_details.type==="tool_calls"&&o.step_details.tool_calls&&s.step_details.type==="tool_calls")for(let a of o.step_details.tool_calls)if(a.index===c(this,vr,"f"))c(this,B,"m",ce).call(this,"toolCallDelta",a,s.step_details.tool_calls[a.index]);else{if(c(this,$e,"f"))c(this,B,"m",ce).call(this,"toolCallDone",c(this,$e,"f"));if(A(this,vr,a.index,"f"),A(this,$e,s.step_details.tool_calls[a.index],"f"),c(this,$e,"f"))c(this,B,"m",ce).call(this,"toolCallCreated",c(this,$e,"f"))}c(this,B,"m",ce).call(this,"runStepDelta",t.data.delta,s);break}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{if(A(this,Wt,void 0,"f"),A(this,He,void 0,"f"),t.data.step_details.type==="tool_calls"&&c(this,$e,"f"))c(this,B,"m",ce).call(this,"toolCallDone",c(this,$e,"f"));c(this,B,"m",ce).call(this,"runStepDone",t.data,s),A(this,vr,void 0,"f"),A(this,$e,void 0,"f");break}case"thread.run.step.in_progress":break}},ce=function(t,...n){if(this._hasListeners(t))for(let s of n)et(s);this._emit(t,...n)},Nl=function(t){c(this,B,"m",ce).call(this,"event",t)},Fl=function(t,n){switch(t.event){case"thread.run.step.created":return c(this,Oe,"f")[n]=t.data,t.data;case"thread.run.step.delta":{let s=c(this,Oe,"f")[n];if(!s)throw Error("Received a RunStepDelta before creation of a snapshot");let o=t.data.delta;if(o){if(M(o,"id"))throw new m("Run-step deltas must not contain an id field");let a=zi(s,o,!0);c(this,Oe,"f")[n]=a}return c(this,Oe,"f")[n]}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":{c(this,Oe,"f")[n]=t.data;break}}if(c(this,Oe,"f")[n])return c(this,Oe,"f")[n];throw Error("No snapshot available")},Wl=function(t,n){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":{if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=t.data;if(o.delta.content){co(o.delta);let a=!Ki(n),u=jl(n.content,o.delta.content,"content",a);for(let l of o.delta.content)if(M(n.content,l.index)){let f=n.content[l.index];n.content[l.index]=c(this,B,"m",Ul).call(this,l,f,a)}else _c(n.content,l.index,l),s.push(l);u()}return[n,s]}case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":{if(n)return[t.event==="thread.message.in_progress"?n:t.data,s];throw Error("Received thread message event with no existing snapshot")}}throw Error("Tried to accumulate a non-message event")},Ul=function(t,n,s){return zi(n,t,s)},ql=function(t){switch(A(this,fo,t.data,"f"),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":{if(A(this,Er,t.data,"f"),c(this,$e,"f"))c(this,B,"m",ce).call(this,"toolCallDone",c(this,$e,"f"));A(this,vr,void 0,"f"),A(this,$e,void 0,"f");break}case"thread.run.cancelling":break}};function Sm(e){return e}function Rm(e,t){return new Promise((n,s)=>{let o,a,u=!1,l=(_)=>{try{t.removeEventListener("abort",_)}catch{}},f=()=>{if(o!==void 0)clearTimeout(o),o=void 0;if(a){let _=a;a=void 0,l(_)}},h=()=>{if(u)return;u=!0,f();try{let _=new Z;Object.defineProperty(_,"cause",{value:t.reason,writable:!0,configurable:!0}),s(_)}catch(_){s(_)}};if(t.aborted){h();return}o=setTimeout(()=>{if(u)return;u=!0,f(),n()},e),a=h;try{if(t.addEventListener("abort",h,{once:!0}),u)l(h);else if(t.aborted)h()}catch(_){if(u)l(h);else u=!0,f(),s(_)}})}async function mo(e,t,n,s){let o=b([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:a,response:u}=await e(o).withResponse(),{status:l}=a;if(t.includes(l)){let f=5000,h=s?.pollIntervalMs;if(h||h===0)f=h;else{let w=u.headers.get("openai-poll-after-ms");if(w){let y=Number.parseInt(w);if(!Number.isNaN(y))f=y}}let _=s&&Object.prototype.propertyIsEnumerable.call(s,"signal")?s.signal:void 0;await(_?Rm(f,_):Fr(f))}else if(n.includes(l))return a}}function Kl(e,t,n,s){return mo((o)=>e.retrieve(t,n,{...s,headers:{...s?.headers,...o}}),["queued","in_progress","cancelling"],["requires_action","incomplete","cancelled","completed","failed","expired"],s)}class _n extends p{constructor(){super(...arguments);this.steps=new io(this._client)}create(e,t,n){let{include:s,...o}=t;return this._client.post(d`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/runs/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}`,{body:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/threads/${e}/runs`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:s}=t;return this._client.post(d`/threads/${s}/runs/${e}/cancel`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,t,n){return tt.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){return await Kl(this,e,t,n)}stream(e,t,n){return tt.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let s=await this.submitToolOutputs(e,t,n);return await this.poll(s.id,t,n)}submitToolOutputsStream(e,t,n){return tt.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}}_n.Steps=io;class Or extends p{constructor(){super(...arguments);this.runs=new _n(this._client),this.messages=new oo(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/threads/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/threads/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/threads/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return tt.createThreadAssistantStream(e,this._client.beta.threads,t)}}Or.Runs=_n;Or.Messages=oo;class Je extends p{constructor(){super(...arguments);this.realtime=new br(this._client),this.agents=new Bt(this._client),this.responses=new Rr(this._client),this.chatkit=new Sr(this._client),this.assistants=new Us(this._client),this.threads=new Or(this._client)}}Je.Realtime=br;Je.Agents=Bt;Je.Responses=Rr;Je.ChatKit=Sr;Je.Assistants=Us;Je.Threads=Or;class yn extends p{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}class _o extends p{retrieve(e,t,n){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}/content`,{...n,headers:b([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class gn extends p{constructor(){super(...arguments);this.content=new _o(this._client)}create(e,t,n){return this._client.post(d`/containers/${e}/files`,Ct({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/containers/${e}/files`,O,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:s}=t;return this._client.delete(d`/containers/${s}/files/${e}`,{...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}}gn.Content=_o;class kr extends p{constructor(){super(...arguments);this.files=new gn(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/containers/${e}`,{...t,headers:b([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}}kr.Files=gn;class bn extends p{create(e,t){return this._client.post("/content_provenance_checks",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}}class yo extends p{create(e,t,n){let{include:s,...o}=t;return this._client.post(d`/conversations/${e}/items`,{query:{include:s},body:o,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:s,...o}=t;return this._client.get(d`/conversations/${s}/items/${e}`,{query:o,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/conversations/${e}/items`,q,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:s}=t;return this._client.delete(d`/conversations/${s}/items/${e}`,{...n,__security:{bearerAuth:!0}})}}class Cr extends p{constructor(){super(...arguments);this.items=new yo(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}}Cr.Items=yo;function zl(e,t,n){let s=!!t.encoding_format,o=s?t.encoding_format:"base64";if(s)te(e).debug("embeddings/user defined encoding_format:",t.encoding_format);let u={body:{...t,encoding_format:o},...n,__security:{bearerAuth:!0}},l=e.post("/embeddings",u);if(s)return l;return te(e).debug("embeddings/decoding base64 embeddings from base64"),l._thenUnwrap((f)=>{let h=f?.data;if(h!==void 0){if(!Array.isArray(h))throw TypeError("Expected embeddings response data to be an array");let{length:_}=h;for(let w=0;w<_;w+=1)if(w in h){let y=h[w],{embedding:P}=y;if(Array.isArray(P))continue;y.embedding=vl(P)}}return f})}class wn extends p{create(e,t){return zl(this._client,e,t)}}class go extends p{retrieve(e,t,n){let{eval_id:s,run_id:o}=t;return this._client.get(d`/evals/${s}/runs/${o}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:s,...o}=t;return this._client.getAPIList(d`/evals/${s}/runs/${e}/output_items`,O,{query:o,...n,__security:{bearerAuth:!0}})}}class An extends p{constructor(){super(...arguments);this.outputItems=new go(this._client)}create(e,t,n){return this._client.post(d`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:s}=t;return this._client.get(d`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/evals/${e}/runs`,O,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:s}=t;return this._client.delete(d`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:s}=t;return this._client.post(d`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}}An.OutputItems=go;class Tr extends p{constructor(){super(...arguments);this.runs=new An(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}}Tr.Runs=An;async function Xl(e,t,n,s){let o=new Set(["processed","error","deleted"]),a=performance.now(),u=await e.retrieve(t);while(!u.status||!o.has(u.status))if(await Fr(n),u=await e.retrieve(t),performance.now()-a>s)throw new le({message:`Giving up on waiting for file ${t} to finish processing after ${s} milliseconds.`});return u}class Pn extends p{create(e,t){return this._client.post("/files",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(d`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(d`/files/${e}/content`,{...t,headers:b([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5000,maxWait:n=1800000}={}){return await Xl(this,e,t,n)}}class bo extends p{}class wo extends p{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t,__security:{bearerAuth:!0}})}}class In extends p{constructor(){super(...arguments);this.graders=new wo(this._client)}}In.Graders=wo;class Ao extends p{create(e,t,n){return this._client.getAPIList(d`/fine_tuning/checkpoints/${e}/permissions`,ye,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(d`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/fine_tuning/checkpoints/${e}/permissions`,q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(d`/fine_tuning/checkpoints/${s}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class xn extends p{constructor(){super(...arguments);this.permissions=new Ao(this._client)}}xn.Permissions=Ao;class Po extends p{list(e,t={},n){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/checkpoints`,O,{query:t,...n,__security:{bearerAuth:!0}})}}class Sn extends p{constructor(){super(...arguments);this.checkpoints=new Po(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",O,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/events`,O,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}}Sn.Checkpoints=Po;class dt extends p{constructor(){super(...arguments);this.methods=new bo(this._client),this.jobs=new Sn(this._client),this.checkpoints=new xn(this._client),this.alpha=new In(this._client)}}dt.Methods=bo;dt.Jobs=Sn;dt.Checkpoints=xn;dt.Alpha=In;class Io extends p{}class $r extends p{constructor(){super(...arguments);this.graderModels=new Io(this._client)}}$r.GraderModels=Io;class Rn extends p{createVariation(e,t){return this._client.post("/images/variations",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",oe({body:e,...t,stream:e.stream??!1,__metadata:{...t?.__metadata,...e.model==null?{}:{model:e.model}},__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}class xo extends p{accept(e,t,n){return this._client.post(d`/live/sessions/${e}/accept`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}downloadRecording(e,t){return this._client.get(d`/live/sessions/${e}/content`,{...t,headers:b([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}fork(e,t,n){return this._client.post(d`/live/sessions/${e}/fork`,{body:t,...n,__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(d`/live/sessions/${e}/hangup`,{...t,headers:b([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(d`/live/sessions/${e}/refer`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t,n){return this._client.post(d`/live/sessions/${e}/reject`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}}class So extends p{}class Ro extends p{}class vt extends p{constructor(){super(...arguments);this.sideband=new Ro(this._client),this.forks=new So(this._client),this.sessions=new xo(this._client)}create(e,t){return this._client.post("/live/sessions",{body:e,...t,__security:{bearerAuth:!0}})}}vt.Sideband=Ro;vt.Forks=So;vt.Sessions=xo;class vn extends p{retrieve(e,t){return this._client.get(d`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",ye,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/models/${e}`,{...t,__security:{bearerAuth:!0}})}}class En extends p{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}}async function Hl(e,t,n,s=null){if(e.body===null||typeof e.body!=="object"||Array.isArray(e.body))throw TypeError("Multipart request body must be an object");let o=Object.fromEntries(Object.entries(e.body).filter(([,f])=>f!==void 0));if(s!==null&&Object.keys(o).length===1&&Object.prototype.hasOwnProperty.call(o,s)){let f=o[s];if(typeof f!=="string")throw TypeError("Raw multipart alternative must be a string");return{...e,body:f,headers:b([e.headers,{"content-type":n[s].content_type}])}}let a=[];for(let[f,h]of Object.entries(n)){if(!Object.prototype.hasOwnProperty.call(o,f))continue;let _=o[f],w=h.json?JSON.stringify(_):_;if(typeof w!=="string")throw TypeError(`Multipart field ${f} must encode as a string`);a.push([f,At([w],"",{type:h.content_type})]),delete o[f]}let l=(await oe({...e,body:o},t)).body;if(!(l instanceof FormData))throw await l.cancel(),TypeError("Unexpected streaming upload in typed multipart request body");for(let[f,h]of a)l.append(f,h,"");return{...e,body:l,headers:b([e.headers,{"content-type":null}])}}class vo extends p{create(e,t){return this._client.post("/realtime/calls",Hl({body:e,...t,headers:b([{Accept:"application/sdp"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0},this._client,{sdp:{content_type:"application/sdp",json:!1},session:{content_type:"application/json",json:!0}},"sdp"))}accept(e,t,n){return this._client.post(d`/realtime/calls/${e}/accept`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(d`/realtime/calls/${e}/hangup`,{...t,headers:b([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(d`/realtime/calls/${e}/refer`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(d`/realtime/calls/${e}/reject`,{body:t,...n,headers:b([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}}class Eo extends p{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}}class Ut extends p{constructor(){super(...arguments);this.clientSecrets=new Eo(this._client),this.calls=new vo(this._client)}}Ut.ClientSecrets=Eo;Ut.Calls=vo;function Jl(e,t){if(!t||!Jm(t)){let n={...e,output_parsed:null,output:e.output.map((s)=>{if(s.type==="function_call")return{...s,parsed_arguments:null};if(s.type==="message")return{...s,content:s.content.map((o)=>({...o,parsed:null}))};return s})};if(Vl(e,n))On(n);return n}return gc(e,t)}function gc(e,t){let n=!e.status||e.status==="completed",s=e.output.map((a)=>{if(a.type==="function_call")return n?Gm(t,a):{...a,parsed_arguments:null};if(a.type==="message"){let u=a.content.map((l)=>{if(l.type==="output_text")return{...l,parsed:n?Hm(t,l.text):null};return l});return{...a,content:u}}return a}),o={...e,output:s};if(Vl(e,o))On(o);return Object.defineProperty(o,"output_parsed",{enumerable:!0,get(){for(let a of o.output){if(a.type!=="message")continue;for(let u of a.content)if(u.type==="output_text"&&u.parsed!==null)return u.parsed}return null}}),o}function Hm(e,t){return Pt(e.text?.format,t)}function Jm(e){if(ct(e.text?.format))return!0;return Array.isArray(e.tools)&&e.tools.some((t)=>yc(t)||t.type==="function"&&t.strict===!0||t.type==="namespace"&&t.tools.some((n)=>n.type==="function"&&(yc(n)||n.strict===!0)))}function yc(e){return e?.$brand==="auto-parseable-tool"}function Vm(e,t,n){for(let s of e)if(n==null){if(s.type==="function"&&s.name===t)return s}else if(s.type==="namespace"&&s.name===n)return s.tools.find((o)=>o.type==="function"&&o.name===t);return}function Gm(e,t){let n=Vm(e.tools??[],t.name,t.namespace),s=null;if(yc(n))s=n.$parseRaw(t.arguments);else if(n?.strict)s=Pt({type:"json_schema",$parseRaw:void 0},t.arguments);return{...t,parsed_arguments:s}}function Vl(e,t){return!Object.getOwnPropertyDescriptor(e,"output_text")||t.output_text==null}function On(e){let t=[];for(let n of e.output){if(n.type!=="message")continue;for(let s of n.content)if(s.type==="output_text")t.push(s.text)}e.output_text=t.join("")}class Oo{constructor(){this.capacity=1,this.values=[0,0],this.size=0}get length(){return this.size}append(e){if(this.size===this.capacity)this.grow();let t=this.size;this.size+=1,this.update(t,e)}update(e,t){if(!Number.isSafeInteger(e)||e<0||e>=this.size)throw RangeError(`missing output at index ${e}`);let n=this.capacity+e,s=t-(this.values[n]??0);if(s===0)return;while(n>=1)this.values[n]=(this.values[n]??0)+s,n=Math.floor(n/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw RangeError(`missing output at index ${e}`);let t=this.capacity,n=this.capacity+e,s=0;while(t<n){if(t%2===1)s+=this.values[t]??0,t+=1;if(n%2===1)n-=1,s+=this.values[n]??0;t=Math.floor(t/2),n=Math.floor(n/2)}return s}grow(){let e=this.capacity;this.capacity*=2;let t=Array.from({length:this.capacity*2},()=>0);for(let n=0;n<this.size;n+=1)t[this.capacity+n]=this.values[e+n]??0;for(let n=this.capacity-1;n>0;n-=1)t[n]=(t[n*2]??0)+(t[n*2+1]??0);this.values=t}}function bc(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new Oo}}function kn(e,t){if(t.type!=="message")return"";let n="";for(let s of t.content)if(s.type==="output_text")n+=s.text;return e.outputTextLengths.set(t,n.length),n}function qt(e,t){if(e.canonicalSnapshot===t)return;let n=new Oo,s="";for(let o of t.output){let a=kn(e,o);s+=a,n.append(a.length)}t.output_text=s,e.outputTextIndex=n,e.canonicalSnapshot=t}function Yl(e,t){e.canonicalSnapshot=void 0,e.outputTextLengths=new WeakMap,e.outputTextIndex=new Oo;let n=structuredClone(t);if(!Object.getOwnPropertyDescriptor(n,"output_text")||n.output_text===null||n.output_text===void 0)qt(e,n);else if(n.output.length===0&&n.output_text==="")e.canonicalSnapshot=n;return n}function ko(e,t,n,s,o){let a=e.outputTextLengths.get(t);if(a!==void 0){let u=a-s.length+o.length;e.outputTextLengths.set(t,u),e.outputTextIndex.update(n,u)}}function Gl(e,t,n){if(t.length===0){e.output_text+=n;return}e.output_text=e.output_text.slice(0,e.output_text.length-t.length)+n}function Ym(e,t,n,s){if(n===void 0||t?.type!=="message")return 0;if(n<t.content.length-n-1){let u=0;for(let l=0;l<n;l+=1){let f=t.content[l];if(f?.type==="output_text")u+=f.text.length}return u}let o=0;for(let u=n+1;u<t.content.length;u+=1){let l=t.content[u];if(l?.type==="output_text")o+=l.text.length}return(e.outputTextLengths.get(t)??kn(e,t).length)-o-s.length}function Cn(e,t,n,s,o,a){if(s===o)return;let u=t.output[n];if(n===t.output.length-1&&(a===void 0||u?.type==="message"&&a===u.content.length-1)){Gl(t,s,o);return}let l=Ym(e,u,a,o),f=e.outputTextIndex.prefixSum(n)+l;if(f+s.length===t.output_text.length){Gl(t,s,o);return}t.output_text=t.output_text.slice(0,f)+o+t.output_text.slice(f+s.length)}var wc=new WeakMap;function Kt(e,t,n,s=!1){if(!Array.isArray(e)||!Number.isSafeInteger(t)||t<0||t>e.length||(t===e.length?!s||t in e:!M(e,t)))throw new m(`missing ${n} at index ${t}`)}function Hi(e,t,n){if(t!==e.length)throw new m(`missing ${n} at index ${t}`);Kt(e,t,n,!0)}function N(e,t){Kt(e.output,t,"output");let n=e.output[t];if(!n)throw new m(`missing output at index ${t}`);return n}function Ac(e){return e.type==="function_call"||e.type==="custom_tool_call"||e.type==="shell_call"||e.type==="shell_call_output"}function Ji(e,t){if(!M(e,"type")||typeof e.type!=="string")throw new m(`expected an own output item type for ${t}`);let n=e.type==="function_call"||e.type==="custom_tool_call",s=[];if(M(e,"id")){if(typeof e.id!=="string"||e.id.length===0)throw new m(`expected a non-empty output item id for ${t}`);s.push(`id:${e.id}`)}else if(!n)throw new m(`expected a non-empty output item id for ${t}`);if(Ac(e)){if(!M(e,"call_id")||typeof e.call_id!=="string"||e.call_id.length===0)throw new m(`expected a non-empty output item call_id for ${t}`);s.push(`call:${e.type}:${e.call_id}`)}return s}function ed(e,t){for(let n of t)if(e.has(n))throw new m(`duplicate output item identity '${n}'`)}function td(e,t){ed(e,t);for(let n of t)e.add(n)}function rd(e){let t={snapshot:e,output:e.output,length:e.output.length,identities:new Set};for(let n=0;n<e.output.length;n+=1){let s=N(e,n);td(t.identities,Ji(s,"response snapshot"))}return t}function Qm(e,t){let n=wc.get(e);if(n&&n.snapshot===t&&n.output===t.output&&n.length===t.output.length)return n;let s=rd(t);return wc.set(e,s),s}function Ql(e,t){let n=bc(),s=Yl(n,t),o=rd(s);return e.canonicalSnapshot=n.canonicalSnapshot,e.outputTextLengths=n.outputTextLengths,e.outputTextIndex=n.outputTextIndex,wc.set(e,o),s}var Pc={"response.output_text.delta":"message","response.output_text.done":"message","response.output_text.annotation.added":"message","response.refusal.delta":"message","response.refusal.done":"message","response.function_call_arguments.delta":"function_call","response.function_call_arguments.done":"function_call","response.custom_tool_call_input.delta":"custom_tool_call","response.custom_tool_call_input.done":"custom_tool_call","response.mcp_call_arguments.delta":"mcp_call","response.mcp_call_arguments.done":"mcp_call","response.mcp_call.in_progress":"mcp_call","response.mcp_call.completed":"mcp_call","response.mcp_call.failed":"mcp_call","response.shell_call_output_content.delta":"shell_call_output","response.shell_call_output_content.done":"shell_call_output","response.reasoning_text.delta":"reasoning","response.reasoning_text.done":"reasoning","response.reasoning_summary_part.added":"reasoning","response.reasoning_summary_part.done":"reasoning","response.reasoning_summary_text.delta":"reasoning","response.reasoning_summary_text.done":"reasoning","response.code_interpreter_call_code.delta":"code_interpreter_call","response.code_interpreter_call_code.done":"code_interpreter_call","response.code_interpreter_call.in_progress":"code_interpreter_call","response.code_interpreter_call.interpreting":"code_interpreter_call","response.code_interpreter_call.completed":"code_interpreter_call","response.file_search_call.in_progress":"file_search_call","response.file_search_call.searching":"file_search_call","response.file_search_call.completed":"file_search_call","response.web_search_call.in_progress":"web_search_call","response.web_search_call.searching":"web_search_call","response.web_search_call.completed":"web_search_call","response.image_generation_call.in_progress":"image_generation_call","response.image_generation_call.generating":"image_generation_call","response.image_generation_call.completed":"image_generation_call","response.image_generation_call.partial_image":"image_generation_call","response.mcp_list_tools.in_progress":"mcp_list_tools","response.mcp_list_tools.completed":"mcp_list_tools","response.mcp_list_tools.failed":"mcp_list_tools","response.compaction.compacting":"compaction"};function Zm(e){if(e.type==="response.content_part.added"||e.type==="response.content_part.done")return e.part.type==="reasoning_text"?"reasoning":"message";return Pc[e.type]}function e_(e,t){let n=N(t,e.output_index),s=e.item;if(Ji(n,e.type),Ji(s,e.type),!M(s,"type")||n.type!==s.type)throw new m(`expected output item type '${n.type}', got '${s.type}'`);let o=M(n,"id")?n.id:void 0,a=M(s,"id")?s.id:void 0;if(o!==a)throw new m(`expected output item id '${o}', got '${a}'`);if(Ac(n)&&Ac(s)&&n.call_id!==s.call_id)throw new m(`expected output item call_id '${n.call_id}', got '${s.call_id}'`)}function t_(e,t,n){if(e.type==="response.output_item.done"){e_(e,t);return}if(n&&(e.type==="response.shell_call_command.added"||e.type==="response.shell_call_command.delta"||e.type==="response.shell_call_command.done")){let l=N(t,e.output_index);if(!M(l,"type")||l.type!=="shell_call")throw new m(`expected output item type 'shell_call', got '${l.type}'`);return}if(e.type!=="response.content_part.added"&&e.type!=="response.content_part.done"&&!M(Pc,e.type))return;let s=e;if(!M(e,"item_id")||typeof s.item_id!=="string"||s.item_id.length===0)throw new m(`expected a non-empty item_id for ${e.type}`);let o=N(t,s.output_index),a=M(o,"id")?o.id:void 0;if(a!==s.item_id)throw new m(`expected item_id '${a}', got '${s.item_id}'`);let u=Zm(s);if(o.type!==u)throw new m(`expected output item type '${u}', got '${o.type}'`)}function je(e,t){Kt(e,t,"content");let n=e[t];if(!n)throw new m(`missing content at index ${t}`);return n}function Zl(e,t,n){let s=e.output.find((o)=>o.type==="shell_call"&&o.call_id===t.call_id);if(s)Kt(s.action.commands,n,"command");else Kt(t.output,n,"content",!0);while(t.output.length<=n)t.output.push({stdout:"",stderr:"",outcome:{type:"exit",exit_code:0}});return je(t.output,n)}function r_(e){return new Set(e)}var n_=r_(["response.output_item.added","response.output_item.done","response.content_part.added","response.content_part.done","response.output_text.delta","response.output_text.done","response.output_text.annotation.added","response.refusal.delta","response.refusal.done","response.function_call_arguments.delta","response.function_call_arguments.done","response.custom_tool_call_input.delta","response.custom_tool_call_input.done","response.mcp_call_arguments.delta","response.mcp_call_arguments.done","response.shell_call_command.added","response.shell_call_command.done","response.shell_call_command.delta","response.shell_call_output_content.delta","response.shell_call_output_content.done","response.reasoning_text.delta","response.reasoning_text.done","response.reasoning_summary_part.added","response.reasoning_summary_part.done","response.reasoning_summary_text.delta","response.reasoning_summary_text.done","response.code_interpreter_call_code.delta","response.code_interpreter_call_code.done","response.code_interpreter_call.in_progress","response.code_interpreter_call.interpreting","response.code_interpreter_call.completed","response.file_search_call.in_progress","response.file_search_call.searching","response.file_search_call.completed","response.web_search_call.in_progress","response.web_search_call.searching","response.web_search_call.completed","response.image_generation_call.in_progress","response.image_generation_call.generating","response.image_generation_call.completed","response.mcp_call.in_progress","response.mcp_call.completed","response.mcp_call.failed","response.created","response.queued","response.in_progress","response.completed","response.failed","response.incomplete","response.audio.delta","response.audio.done","response.audio.transcript.delta","response.audio.transcript.done","response.compaction.compacting","response.image_generation_call.partial_image","response.mcp_list_tools.in_progress","response.mcp_list_tools.completed","response.mcp_list_tools.failed","keepalive","error"]);function Xi(e){throw new m("Unhandled response stream event: unknown")}var s_=["item_id","output_index","content_index","annotation_index","command_index","summary_index"];function o_(e){let t;try{t=Object.getOwnPropertyDescriptor(e,"type")}catch{return Xi(e)}let n=t?.value;if(typeof n!=="string"||!n_.has(n))return Xi(e);let s=new Map([["type",n]]);if(n==="response.output_item.added"||n==="response.output_item.done"||n==="response.content_part.added"||n==="response.content_part.done"||n==="response.shell_call_command.added"||n==="response.shell_call_command.delta"||n==="response.shell_call_command.done"||M(Pc,n))try{for(let a of s_){let u=Object.getOwnPropertyDescriptor(e,a);s.set(a,u?e[a]:void 0)}if(n==="response.output_item.done")s.set("item",structuredClone(e.item));else if(n==="response.content_part.added"||n==="response.content_part.done")s.set("part",structuredClone(e.part))}catch{return Xi(e)}return new Proxy(e,{get(a,u){return s.has(u)?s.get(u):Reflect.get(a,u,a)}})}function i_(e,t,n){switch(e.type){case"response.output_item.added":{Hi(t.output,e.output_index,"output");let s=Qm(n,t),o=structuredClone(e.item),a=Ji(o,e.type);if(ed(s.identities,a),o.type==="message")qt(n,t);t.output.push(o),td(s.identities,a),s.length=t.output.length;let u=kn(n,o);if(n.canonicalSnapshot===t)n.outputTextIndex.append(u.length);if(u)t.output_text+=u;return!0}case"response.output_item.done":{let s=N(t,e.output_index),o=kn(n,s),a=e.item;if(s.type==="message"||a.type==="message")qt(n,t);t.output[e.output_index]=a;let u=kn(n,a);if(n.canonicalSnapshot===t)n.outputTextIndex.update(e.output_index,u.length);return Cn(n,t,e.output_index,o,u),!0}default:return!1}}function a_(e,t,n){switch(e.type){case"response.content_part.added":{let s=N(t,e.output_index),{type:o}=s,{part:a}=e;if(o==="message"&&a.type!=="reasoning_text"){Hi(s.content,e.content_index,"content");let u=a;if(u.type==="output_text")qt(n,t);if(s.content.push(u),u.type==="output_text")ko(n,s,e.output_index,"",u.text),Cn(n,t,e.output_index,"",u.text,e.content_index)}else if(o==="reasoning"&&a.type==="reasoning_text"){let u=s.content??[];if(Hi(u,e.content_index,"content"),!s.content)s.content=u;u.push(a)}return!0}default:return!1}}function c_(e,t,n){switch(e.type){case"response.content_part.done":{let s=N(t,e.output_index),{part:o}=e;if(s.type==="message"&&o.type!=="reasoning_text"){let a=je(s.content,e.content_index),u=a.type==="output_text"?a.text:"",l=o;if(a.type==="output_text"||l.type==="output_text")qt(n,t);s.content[e.content_index]=l;let f=l.type==="output_text"?l.text:"";ko(n,s,e.output_index,u,f),Cn(n,t,e.output_index,u,f,e.content_index)}else if(s.type==="reasoning"&&o.type==="reasoning_text"){let{content:a}=s;if(!a)throw new m(`missing content at index ${e.content_index}`);je(a,e.content_index),a[e.content_index]=o}return!0}default:return!1}}function u_(e,t,n){switch(e.type){case"response.output_text.delta":{let s=N(t,e.output_index);if(s.type==="message"){let o=je(s.content,e.content_index);if(o.type!=="output_text")throw new m(`expected content to be 'output_text', got ${o.type}`);let a=o.text;if(qt(n,t),o.text=a+e.delta,ko(n,s,e.output_index,a,o.text),e.output_index===t.output.length-1&&e.content_index===s.content.length-1)t.output_text+=e.delta;else Cn(n,t,e.output_index,a,o.text,e.content_index)}return!0}case"response.output_text.done":{let s=N(t,e.output_index);if(s.type==="message"){let o=je(s.content,e.content_index);if(o.type!=="output_text")throw new m(`expected content to be 'output_text', got ${o.type}`);let a=o.text;qt(n,t),o.text=e.text,ko(n,s,e.output_index,a,e.text),Cn(n,t,e.output_index,a,e.text,e.content_index)}return!0}case"response.output_text.annotation.added":{let s=N(t,e.output_index);if(s.type==="message"){let o=je(s.content,e.content_index);if(o.type!=="output_text")throw new m(`expected content to be 'output_text', got ${o.type}`);Kt(o.annotations,e.annotation_index,"annotation",!0),o.annotations[e.annotation_index]=structuredClone(e.annotation)}return!0}default:return!1}}function l_(e,t){switch(e.type){case"response.refusal.delta":{let n=N(t,e.output_index);if(n.type==="message"){let s=je(n.content,e.content_index);if(s.type!=="refusal")throw new m(`expected content to be 'refusal', got ${s.type}`);s.refusal+=e.delta}return!0}case"response.refusal.done":{let n=N(t,e.output_index);if(n.type==="message"){let s=je(n.content,e.content_index);if(s.type!=="refusal")throw new m(`expected content to be 'refusal', got ${s.type}`);s.refusal=e.refusal}return!0}case"response.function_call_arguments.delta":{let n=N(t,e.output_index);if(n.type==="function_call")n.arguments+=e.delta;return!0}case"response.function_call_arguments.done":{let n=N(t,e.output_index);if(n.type==="function_call")n.arguments=e.arguments;return!0}case"response.custom_tool_call_input.delta":{let n=N(t,e.output_index);if(n.type==="custom_tool_call")n.input+=e.delta;return!0}case"response.custom_tool_call_input.done":{let n=N(t,e.output_index);if(n.type==="custom_tool_call")n.input=e.input;return!0}case"response.mcp_call_arguments.delta":{let n=N(t,e.output_index);if(n.type==="mcp_call")n.arguments+=e.delta;return!0}case"response.mcp_call_arguments.done":{let n=N(t,e.output_index);if(n.type==="mcp_call")n.arguments=e.arguments;return!0}default:return!1}}function d_(e,t){switch(e.type){case"response.shell_call_command.added":case"response.shell_call_command.done":{let n=N(t,e.output_index);if(n.type==="shell_call"){let s=e.type==="response.shell_call_command.added";Kt(n.action.commands,e.command_index,"command",s),n.action.commands[e.command_index]=e.command}return!0}case"response.shell_call_command.delta":{let n=N(t,e.output_index);if(n.type==="shell_call")Kt(n.action.commands,e.command_index,"command"),n.action.commands[e.command_index]+=e.delta;return!0}case"response.shell_call_output_content.delta":{let n=N(t,e.output_index);if(n.type==="shell_call_output"){let s=Zl(t,n,e.command_index);s.stdout+=e.delta.stdout??"",s.stderr+=e.delta.stderr??""}return!0}case"response.shell_call_output_content.done":{let n=N(t,e.output_index);if(n.type==="shell_call_output"){let s=je(e.output,0);Zl(t,n,e.command_index),n.output[e.command_index]=structuredClone(s)}return!0}default:return!1}}function f_(e,t){switch(e.type){case"response.reasoning_text.delta":{let n=N(t,e.output_index);if(n.type==="reasoning"){if(!n.content)throw new m(`missing content at index ${e.content_index}`);let s=je(n.content,e.content_index);if(s.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=e.delta}return!0}case"response.reasoning_text.done":{let n=N(t,e.output_index);if(n.type==="reasoning"){if(!n.content)throw new m(`missing content at index ${e.content_index}`);let s=je(n.content,e.content_index);if(s.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${s.type}`);s.text=e.text}return!0}case"response.reasoning_summary_part.added":{let n=N(t,e.output_index);if(n.type==="reasoning")Hi(n.summary,e.summary_index,"content"),n.summary.push(structuredClone(e.part));return!0}case"response.reasoning_summary_part.done":{let n=N(t,e.output_index);if(n.type==="reasoning")je(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part);return!0}case"response.reasoning_summary_text.delta":{let n=N(t,e.output_index);if(n.type==="reasoning"){let s=je(n.summary,e.summary_index);s.text+=e.delta}return!0}case"response.reasoning_summary_text.done":{let n=N(t,e.output_index);if(n.type==="reasoning"){let s=je(n.summary,e.summary_index);s.text=e.text}return!0}default:return!1}}function p_(e,t){switch(e.type){case"response.code_interpreter_call_code.delta":{let n=N(t,e.output_index);if(n.type==="code_interpreter_call")n.code=(n.code??"")+e.delta;return!0}case"response.code_interpreter_call_code.done":{let n=N(t,e.output_index);if(n.type==="code_interpreter_call")n.code=e.code;return!0}case"response.code_interpreter_call.in_progress":{let n=N(t,e.output_index);if(n.type==="code_interpreter_call")n.status="in_progress";return!0}case"response.code_interpreter_call.interpreting":{let n=N(t,e.output_index);if(n.type==="code_interpreter_call")n.status="interpreting";return!0}case"response.code_interpreter_call.completed":{let n=N(t,e.output_index);if(n.type==="code_interpreter_call")n.status="completed";return!0}default:return!1}}function h_(e,t){switch(e.type){case"response.file_search_call.in_progress":{let n=N(t,e.output_index);if(n.type==="file_search_call")n.status="in_progress";return!0}case"response.file_search_call.searching":{let n=N(t,e.output_index);if(n.type==="file_search_call")n.status="searching";return!0}case"response.file_search_call.completed":{let n=N(t,e.output_index);if(n.type==="file_search_call")n.status="completed";return!0}case"response.web_search_call.in_progress":{let n=N(t,e.output_index);if(n.type==="web_search_call")n.status="in_progress";return!0}case"response.web_search_call.searching":{let n=N(t,e.output_index);if(n.type==="web_search_call")n.status="searching";return!0}case"response.web_search_call.completed":{let n=N(t,e.output_index);if(n.type==="web_search_call")n.status="completed";return!0}default:return!1}}function m_(e,t){switch(e.type){case"response.image_generation_call.in_progress":{let n=N(t,e.output_index);if(n.type==="image_generation_call")n.status="in_progress";return!0}case"response.image_generation_call.generating":{let n=N(t,e.output_index);if(n.type==="image_generation_call")n.status="generating";return!0}case"response.image_generation_call.completed":{let n=N(t,e.output_index);if(n.type==="image_generation_call")n.status="completed";return!0}case"response.mcp_call.in_progress":{let n=N(t,e.output_index);if(n.type==="mcp_call")n.status="in_progress";return!0}case"response.mcp_call.completed":{let n=N(t,e.output_index);if(n.type==="mcp_call")n.status="completed";return!0}case"response.mcp_call.failed":{let n=N(t,e.output_index);if(n.type==="mcp_call")n.status="failed";return!0}default:return!1}}function __(e){switch(e.type){case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":return!0;default:return!1}}function y_(e){switch(e.type){case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.compaction.compacting":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":return!0;default:return!1}}function Vi(){return bc()}function nd(e,t,n,s=!1,o){let a=o_(e);if(o&&a.type!=="keepalive")o(a);if(!t){if(a.type!=="response.created")throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${a.type}`);return Ql(n,a.response)}if(t_(a,t,s),i_(a,t,n))return t;if(a_(a,t,n))return t;if(c_(a,t,n))return t;if(u_(a,t,n))return t;if(l_(a,t))return t;if(d_(a,t))return t;if(f_(a,t))return t;if(p_(a,t))return t;if(h_(a,t))return t;if(m_(a,t))return t;if(__(a))return Ql(n,a.response);if(y_(a))return t;return Xi(a)}var zt,Gi,jr,Yi,Co,Ic,xc,Sc;class To extends fr{constructor(e){super();zt.add(this),Gi.set(this,void 0),jr.set(this,void 0),Yi.set(this,void 0),Co.set(this,Vi()),A(this,Gi,e,"f")}static createResponse(e,t,n){let s=new To(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}static fromReadableStream(e){let t=new To(null);return t._run(()=>t._fromReadableStream(e)),t}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),c(this,zt,"m",Ic).call(this);let s,o=null;if("response_id"in t)s=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),o=t.starting_after??null;else s=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of s)c(this,zt,"m",xc).call(this,a,o);if(s.controller.signal?.aborted)throw this._userAbortError();return c(this,zt,"m",Sc).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,zt,"m",Ic).call(this),this._connected();let n=Ae.fromReadableStream(e,this.controller);for await(let s of n)c(this,zt,"m",xc).call(this,s,null);if(n.controller.signal?.aborted)throw this._userAbortError();return c(this,zt,"m",Sc).call(this)}[(Gi=new WeakMap,jr=new WeakMap,Yi=new WeakMap,Co=new WeakMap,zt=new WeakSet,Ic=function(){if(this.ended)return;A(this,jr,void 0,"f"),A(this,Co,Vi(),"f")},xc=function(t,n){if(this.ended)return;let s=(u,l)=>{if(n==null||l.sequence_number>n)this._emit(u,l)};if(t.type==="error"){let u="error"in t&&typeof t.error==="object"&&t.error!==null?t.error:t;throw new H(void 0,u,t.message,void 0)}let o=t,a=nd(t,c(this,jr,"f"),c(this,Co,"f"),!0,(u)=>{o=u});switch(A(this,jr,a,"f"),s("event",t),o.type){case"response.output_text.delta":{let u=a.output[o.output_index];if(!u)throw new m(`missing output at index ${o.output_index}`);if(u.type==="message"){let l=u.content[o.content_index];if(!l)throw new m(`missing content at index ${o.content_index}`);if(l.type!=="output_text")throw new m(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...o,type:o.type,item_id:o.item_id,output_index:o.output_index,content_index:o.content_index,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let u=a.output[o.output_index];if(!u)throw new m(`missing output at index ${o.output_index}`);if(u.type==="function_call")s("response.function_call_arguments.delta",{...o,type:o.type,item_id:o.item_id,output_index:o.output_index,snapshot:u.arguments});break}default:{s(o.type,t);break}}},Sc=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=c(this,jr,"f");if(!t)throw new m("request ended without sending any events");A(this,jr,void 0,"f"),A(this,Co,Vi(),"f");let n=g_(t,c(this,Gi,"f"));return A(this,Yi,n,"f"),n},Symbol.asyncIterator)](){return this._createIterator((e)=>{let t=(n)=>e(n);return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let e=c(this,Yi,"f");if(!e)throw new m("stream ended without producing a Response");return e}}function g_(e,t){return Jl(e,t)}class $o extends p{list(e,t={},n){return this._client.getAPIList(d`/responses/${e}/input_items`,O,{query:t,...n,__security:{bearerAuth:!0}})}}class jo extends p{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}}class Et extends p{constructor(){super(...arguments);this.inputItems=new $o(this._client),this.inputTokens=new jo(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((n)=>{if("object"in n&&n.object==="response")On(n);return n})}retrieve(e,t={},n){return this._client.get(d`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap((s)=>{if("object"in s&&s.object==="response")On(s);return s})}delete(e,t){return this._client.delete(d`/responses/${e}`,{...t,headers:b([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((n)=>gc(n,e))}stream(e,t){return To.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(d`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}}Et.InputItems=$o;Et.InputTokens=jo;class Lo extends p{retrieve(e,t){return this._client.get(d`/safety/alerts/${e}`,{...t,__security:{bearerAuth:!0}})}}class Lr extends p{constructor(){super(...arguments);this.alerts=new Lo(this._client)}}Lr.Alerts=Lo;class Mo extends p{retrieve(e,t){return this._client.get(d`/skills/${e}/content`,{...t,headers:b([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class Bo extends p{retrieve(e,t,n){let{skill_id:s}=t;return this._client.get(d`/skills/${s}/versions/${e}/content`,{...n,headers:b([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class Tn extends p{constructor(){super(...arguments);this.content=new Bo(this._client)}create(e,t={},n){return this._client.post(d`/skills/${e}/versions`,Ct({body:t,...n,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t,n){let{skill_id:s}=t;return this._client.get(d`/skills/${s}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/skills/${e}/versions`,O,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:s}=t;return this._client.delete(d`/skills/${s}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}}Tn.Content=Bo;class Xt extends p{constructor(){super(...arguments);this.content=new Mo(this._client),this.versions=new Tn(this._client)}create(e={},t){return this._client.post("/skills",Ct({body:e,...t,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t){return this._client.get(d`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}}Xt.Content=Mo;Xt.Versions=Tn;class Do extends p{create(e,t,n){return this._client.post(d`/uploads/${e}/parts`,oe({body:t,...n,__security:{bearerAuth:!0}},this._client))}}class Mr extends p{constructor(){super(...arguments);this.parts=new Do(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(d`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(d`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}}Mr.Parts=Do;function sd(e,t,n,s){return mo((o)=>e.retrieve(n,{vector_store_id:t},{...s,headers:o}),["in_progress"],["failed","cancelled","completed"],s)}function od(e,t,n,s){return mo((o)=>e.retrieve(n,{vector_store_id:t},{...s,headers:o}),["in_progress"],["failed","cancelled","completed"],s)}var id=async(e)=>{let t=await Promise.allSettled(e),n=t.filter((o)=>o.status==="rejected");if(n.length)throw Object.defineProperty(Error(`${n.length} promise(s) failed`),"rejections",{configurable:!0,value:n.map(({reason:o})=>o),writable:!0});let s=[];for(let o of t)if(o.status==="fulfilled")s.push(o.value);return s};async function ad(e,t,n,s,o,a){if(s===null||s===void 0||s.length===0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let u=a?.maxConcurrency??5,l=Math.min(u,s.length);if(l===0)throw RangeError("maxConcurrency must be greater than 0");let f=s.values(),h=[...o];async function _(y){for(let P of y){let I=await t.files.create({file:P,purpose:"assistants"},a);h.push(I.id)}}let w=[];w.length=l;for(let y=0;y<w.length;y+=1)w[y]=_(f);return await id(w),await e.createAndPoll(n,{file_ids:h},a)}class No extends p{create(e,t,n){return this._client.post(d`/vector_stores/${e}/file_batches`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/file_batches/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:s}=t;return this._client.post(d`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}listFiles(e,t,n){let{vector_store_id:s,...o}=t;return this._client.getAPIList(d`/vector_stores/${s}/file_batches/${e}/files`,O,{query:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){return await od(this,e,t,n)}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){return await ad(this,this._client,e,t,n,s)}}class Fo extends p{create(e,t,n){return this._client.post(d`/vector_stores/${e}/files`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/files/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:s,...o}=t;return this._client.post(d`/vector_stores/${s}/files/${e}`,{body:o,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(d`/vector_stores/${e}/files`,O,{query:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:s}=t;return this._client.delete(d`/vector_stores/${s}/files/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){return await sd(this,e,t,n)}async upload(e,t,n){let s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){let s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){let{vector_store_id:s}=t;return this._client.getAPIList(d`/vector_stores/${s}/files/${e}/content`,ye,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}class Ht extends p{constructor(){super(...arguments);this.files=new Fo(this._client),this.fileBatches=new No(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/vector_stores/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(d`/vector_stores/${e}`,{body:t,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",O,{query:e,...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/vector_stores/${e}`,{...t,headers:b([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(d`/vector_stores/${e}/search`,ye,{body:t,method:"post",...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}Ht.Files=Fo;Ht.FileBatches=No;class $n extends p{create(e,t){return this._client.post("/videos",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(d`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",q,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(d`/videos/${e}/content`,{query:t,...n,headers:b([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(d`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(d`/videos/${e}/remix`,Ct({body:t,...n,__security:{bearerAuth:!0}},this._client))}}var cd=32,E_=32;function Rc(e){return e.split(" ",cd+1).length>cd}function*vc(e){let t=0;while(t<=e.length){let n=e.indexOf(" ",t),s=e.slice(t,n===-1?void 0:n);if(yield s.startsWith("v1,")?s.slice(3):s,n===-1)break;t=n+1}}function ud(e){try{let t=Ui(e);return t.byteLength===E_?t:void 0}catch{return}}function O_(e){for(let t of vc(e)){let n=ud(t);if(n)return n}return}function k_(e,t,n){let s=n;for(let o of vc(e)){let a=ud(o);if(!a)continue;let u=0;for(let[l,f]of a.entries())u|=f^(t[l]??0);if(u===0)s=a}return s}async function ld(e,t,n,s,o,a){let u=Number.parseInt(n,10);if(Number.isNaN(u))throw new Be("Invalid webhook timestamp format");let l=Math.floor(Date.now()/1000);if(l-u>a)throw new Be("Webhook timestamp is too old");if(u>l+a)throw new Be("Webhook timestamp is too new");let f=Rc(t),h=f?O_(t):void 0;if(f&&!h)throw new Be("The given webhook signature does not match the expected signature");let _=Uint8Array.from(o.startsWith("whsec_")?Ui(o.slice(6)):_e(o)),w=s?`${s}.${n}.${e}`:`${n}.${e}`,y=Uint8Array.from(_e(w)),P=await crypto.subtle.importKey("raw",_,{name:"HMAC",hash:"SHA-256"},!1,f?["sign","verify"]:["verify"]);if(f&&h){let I=new Uint8Array(await crypto.subtle.sign("HMAC",P,y)),x=k_(t,I,h);try{if(await crypto.subtle.verify("HMAC",P,Uint8Array.from(x),y))return}catch{}throw new Be("The given webhook signature does not match the expected signature")}for(let I of vc(t))try{let x=Uint8Array.from(Ui(I));if(await crypto.subtle.verify("HMAC",P,x,y))return}catch{}throw new Be("The given webhook signature does not match the expected signature")}class Wo extends p{list(e){return this._client.get("/webhook_event_types",{...e,__security:{bearerAuth:!0}})}}var jn,dd,Qi;class Br extends p{constructor(){super(...arguments);jn.add(this),this.eventTypes=new Wo(this._client)}create(e,t){return this._client.post("/webhook_endpoints",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(d`/webhook_endpoints/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(d`/webhook_endpoints/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/webhook_endpoints",O,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(d`/webhook_endpoints/${e}`,{...t,__security:{bearerAuth:!0}})}rotateSecret(e,t={},n){return this._client.post(d`/webhook_endpoints/${e}/rotate_secret`,{body:t,...n,__security:{bearerAuth:!0}})}test(e,t,n){return this._client.post(d`/webhook_endpoints/${e}/test`,{body:t,...n,__security:{bearerAuth:!0}})}async unwrap(e,t,n=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,n,s),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle?.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,jn,"m",dd).call(this,n);let o=b([t]).values,a=c(this,jn,"m",Qi).call(this,o,"webhook-signature"),u=c(this,jn,"m",Qi).call(this,o,"webhook-timestamp"),l=c(this,jn,"m",Qi).call(this,o,"webhook-id");if(Rc(a)&&typeof crypto.subtle.sign!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");return await ld(e,a,u,l,n,s)}}jn=new WeakSet,dd=function(t){if(typeof t!=="string"||t.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Qi=function(t,n){if(!t)throw Error("Headers are required");let s=t.get(n);if(s===null||s===void 0)throw Error(`Missing required header: ${n}`);return s};Br.EventTypes=Wo;async function Ec(e){let t,n=await e._callApiKey((s)=>{t=s});return{apiKey:t===void 0?e.apiKey:t,isProvider:n}}var pd=Symbol.for("openai.node.providerDefinitions.v1"),hd=globalThis,md=hd[pd],_d=md??new WeakMap;if(!md)Object.defineProperty(hd,pd,{value:_d});function yd(e){let t=_d.get(e);if(!t)throw Error("Invalid provider. Providers must be created with createProvider().");return t.configure()}var Oc,rt,Uo,Y,Zi,Ot,Ko,qo,Ad;function gd(){if(Vc())return!0;let e=globalThis;return typeof e.WorkerGlobalScope==="function"&&e instanceof e.WorkerGlobalScope&&typeof e.WorkerNavigator==="function"&&e.navigator instanceof e.WorkerNavigator&&typeof e.navigator?.userAgent==="string"&&e.navigator.userAgent!=="Cloudflare-Workers"&&e.process?.versions?.node===void 0&&e.Deno===void 0&&e.Bun===void 0&&e.EdgeRuntime===void 0&&e.WebSocketPair===void 0}var T_="workload-identity-auth",bd=Symbol("inheritedDataResidencySelection");class g{constructor(e={}){Oc.add(this),Uo.set(this,void 0),Y.set(this,void 0),Zi.set(this,void 0),Ot.set(this,void 0),Ko.set(this,!1),qo.set(this,new WeakMap),this.completions=new yn(this),this.chat=new _r(this),this.embeddings=new wn(this),this.files=new Pn(this),this.images=new Rn(this),this.contentProvenanceChecks=new bn(this),this.audio=new xt(this),this.moderations=new En(this),this.models=new vn(this),this.fineTuning=new dt(this),this.graders=new $r(this),this.vectorStores=new Ht(this),this.safety=new Lr(this),this.webhooks=new Br(this),this.beta=new Je(this),this.batches=new on(this),this.uploads=new Mr(this),this.admin=new gr(this),this.responses=new Et(this),this.live=new vt(this),this.realtime=new Ut(this),this.conversations=new Cr(this),this.evals=new Tr(this),this.containers=new kr(this),this.skills=new Xt(this),this.videos=new $n(this);let{credential:t,options:n}=$u(e);e=n;let s=ha(e),o=e.provider,{baseURL:a=o?null:Ee("OPENAI_BASE_URL"),dataResidency:u,[bd]:l=!1,apiKey:f=o?null:Ee("OPENAI_API_KEY")??null,adminAPIKey:h=o?null:Ee("OPENAI_ADMIN_KEY")??null,organization:_=o?null:Ee("OPENAI_ORG_ID")??null,project:w=o?null:Ee("OPENAI_PROJECT_ID")??null,webhookSecret:y=Ee("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:P,x509Transport:I,credential:x,...v}=e;if(o){let T=["apiKey","adminAPIKey","workloadIdentity","x509Transport","baseURL","dataResidency"].filter((L)=>(L==="workloadIdentity"?P:e[L])!=null);if(T.length)throw new m(`The \`provider\` option cannot be used with ${T.map((L)=>`\`${L}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let C=li(P)?{x509:P,legacy:void 0}:{x509:void 0,legacy:P},E=C.x509,S=E!==void 0,j=o?yd(o):void 0,R={apiKey:f,adminAPIKey:h,organization:_,project:w,webhookSecret:y,workloadIdentity:P,x509Transport:I,provider:o,...v,baseURL:j?.baseURL??s??(a||(S?du:"https://api.openai.com/v1"))};if(I&&!S)throw new m("An X.509 transport requires an X.509 workload identity.");if(S){if(s!==void 0||l)throw new m("X.509 workload identity does not support data residency selection.");if(e.fetch!==void 0)throw new m("X.509 workload identity does not support a custom fetch implementation.");if(Kr(R.baseURL),Vn(R.fetchOptions),this.fetchWithAuth!==rt.prototype.fetchWithAuth||this.fetchWithTimeout!==rt.prototype.fetchWithTimeout)throw new m("X.509 workload identity does not support overridden fetch dispatch hooks.")}if(f&&P)throw new m("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!j&&!f&&!h&&!P)throw new m("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!R.dangerouslyAllowBrowser&&gd())throw new m(`It looks like you're running in a browser-like environment.
22
22
 
23
23
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
24
24
  If you understand the risks and have appropriate mitigations in place,
@@ -28,4 +28,4 @@ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
28
28
 
29
29
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
30
30
  `);this.baseURL=R.baseURL,A(this,Ko,s!==void 0||l,"f"),this.timeout=R.timeout??rt.DEFAULT_TIMEOUT,this.logger=R.logger??console;let F="warn";this.logLevel=F,this.logLevel=ia(R.logLevel,"ClientOptions.logLevel",this)??ia(Ee("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??F,this.fetchOptions=R.fetchOptions,this.maxRetries=R.maxRetries??2,this.fetch=R.fetch??Nn(),A(this,Uo,Qc,"f");let k=o||t?void 0:Ee("OPENAI_CUSTOM_HEADERS");if(k){let T={};for(let L of k.split(`
31
- `)){let D=L.indexOf(":");if(D>=0)T[L.substring(0,D).trim()]=L.substring(D+1).trim()}R.defaultHeaders=b([T,R.defaultHeaders])}if(this._options=R,this._provider=j,E){let T=new Se(E,I,_,w);this._workloadIdentityAuth=T,A(this,Y,T,"f"),A(this,Zi,t,"f"),A(this,Ot,T.fetch(),"f"),this.fetch=c(this,Ot,"f"),Au(this)}else if(C.legacy)this._workloadIdentityAuth=new Jn(C.legacy,this.fetch);this.apiKey=typeof f==="string"?f:null,this.adminAPIKey=h,this.organization=_,this.project=w,this.webhookSecret=y}withOptions(e){let t=ha(e),n=c(this,Y,"f"),s={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:c(this,Y,"f")?void 0:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:n?.identitySnapshot()??this._options.workloadIdentity,x509Transport:this._options.x509Transport,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret},{credential:o,provider:a}=ju(s,e,c(this,Zi,"f"),n!==void 0);if(t!==void 0)delete s.baseURL;let u={...s,...e,credential:o,provider:a,[bd]:c(this,Ko,"f")&&t===void 0&&!M(e,"baseURL")&&e.credential===void 0&&!a},l=new this.constructor(u);if(a&&new URL(l.baseURL).origin!==new URL(this.baseURL).origin)Object.assign(l._options,{defaultHeaders:e.defaultHeaders,defaultQuery:e.defaultQuery,fetchOptions:e.fetchOptions,fetch:e.fetch}),l.fetchOptions=e.fetchOptions,l.fetch=e.fetch??Nn(),l.organization=e.organization??null,l.project=e.project??null;if(c(this,Y,"f")&&c(l,Y,"f")&&this.baseURL===l.baseURL&&c(this,Y,"f").matches(c(l,Y,"f")))l._workloadIdentityAuth=c(this,Y,"f"),A(l,Y,c(this,Y,"f"),"f"),A(l,Ot,c(this,Ot,"f"),"f");return l}defaultQuery(){return this._options.defaultQuery}_buildWebSocketHeaders(e){return Object.fromEntries(b([{"User-Agent":this.getUserAgent(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},e,this._options.defaultHeaders]).values)}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(e.get("authorization")||e.get("api-key"))return;if(t.has("authorization")||t.has("api-key"))return;if(this._workloadIdentityAuth&&n.bearerAuth)return;throw Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){if((c(this,Y,"f")??this._workloadIdentityAuth)instanceof Se&&t.adminAPIKeyAuth&&this.adminAPIKey!==null)return await this.adminAPIKeyAuth(e);return b([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){let t=c(this,Y,"f")??this._workloadIdentityAuth;if(t){if(t instanceof Se){if(t===this._workloadIdentityAuth&&(this.fetchWithAuth!==rt.prototype.fetchWithAuth||this.fetchWithTimeout!==rt.prototype.fetchWithTimeout))throw new m("X.509 workload identity does not support overridden fetch dispatch hooks.");let o=t.headerSnapshots();if(!Se.shouldAuthenticate(e,o.defaultHeaders,o.requestHeaders))return}let s=t instanceof Se?await t.getToken(e,{apiURL:t.requestAPIURL(),...t.headerSnapshots(),...t.requestSnapshot(),signal:t.effectiveSignal(),...t.tenantSnapshot()}):await t.getToken();return b([{Authorization:`Bearer ${s}`}])}let{apiKey:n}=await Ec(this);if(n==null)return;return b([{Authorization:`Bearer ${n}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey==null)return;return b([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return uu(e)}getUserAgent(){return`${this.constructor.name}/JS ${kt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ve()}`}makeStatusError(e,t,n,s){let o=t&&typeof t==="object"&&t.error==null?{error:t}:t;return H.generate(e,o,n,s)}_hasApiKeyProvider(){return typeof this._options.apiKey==="function"}async _callApiKey(e){if(this._provider)return e?.(this.apiKey),!1;let t=this._options.apiKey;if(typeof t!=="function")return e?.(this.apiKey),!1;let n;try{n=await t()}catch(s){if(s instanceof m)throw s;throw new m(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof n!=="string"||!n)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,e?.(this.apiKey),!0}buildURL(e,t,n){let s=!c(this,Oc,"m",Ad).call(this)&&n||this.baseURL,o=kc(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),u=Object.fromEntries(o.searchParams);if(!ta(a)||!ta(u))t={...u,...a,...t};if(typeof t==="object"&&t&&!Array.isArray(t))o.search=this.stringifyQuery(t);return o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then((s)=>({method:e,path:t,...s})))}request(e,t=null){let n=c(this,Y,"f")??this._workloadIdentityAuth,s=n instanceof Se?Promise.resolve(e).then((o)=>n.runRequest(()=>this.makeRequest(o,t,void 0),this)):this.makeRequest(e,t,void 0);return this.responsePromise(s)}responsePromise(e,t=(n,s)=>this.parseResponseWithTimeout(n,s)){let n=new or(this,e,(s,o)=>{let a=c(this,qo,"f").get(o.controller)?.continueRequest;return a?a(()=>t(s,o)):t(s,o)});return n.withResponse=async()=>{let s=await n,{response:o}=await e;return{data:s,response:o,request_id:o.headers.get("x-request-id")}},n._thenUnwrap=(s)=>this.responsePromise(e,async(o,a)=>Kn(s(await t(o,a),a),a.response)),n}async parseResponseWithTimeout(e,t){if(t.options.stream||t.options.__binaryResponse||t.response.status===204||t.response.headers.get("content-length")==="0")return sr(e,t);while(!0){let n=c(this,qo,"f").get(t.controller),s=n?.timeout??t.options.timeout??this.timeout,o=n?.authentication,a=o?t.controller.signal:t.options.signal,u=()=>o&&a?this._makeUserAbortError(a):new Z,l;try{l=o?.remainingTimeout(t.options,s)??Math.max(0,t.startTime+s-Date.now())}catch(w){let y=a?.aborted?u():void 0;throw t.controller.abort(),_t(t.response.body).catch(()=>{return}),y??w}let f,h,_=!1;try{if(a?.aborted&&n?.helperMethod!=="runTools")throw u();let w=new Promise((y,P)=>{if(f=setTimeout(()=>{_=!0,t.controller.abort(),P(new le)},l),a)h=()=>{if(!_)P(u())},a.addEventListener("abort",h,{once:!0})});return await Promise.race([sr(e,t),w])}catch(w){if(a?.aborted&&!_)throw u();if(!_){if(o&&w instanceof SyntaxError)throw SyntaxError("X.509 workload identity API response contains invalid JSON.");if(o&&!(w instanceof m))throw new Ge({message:"X.509 workload identity API response body could not be read."});throw w}let y=n?.retriesRemaining??0;if(!y||n?.hasStreamingBody||t.options.__metadata?.hasStreamingBody||globalThis.ReadableStream&&t.options.body instanceof globalThis.ReadableStream||typeof t.options.body==="object"&&t.options.body!==null&&((Symbol.asyncIterator in t.options.body)||(Symbol.iterator in t.options.body)&&("next"in t.options.body)&&typeof t.options.body.next==="function"))throw new le;if(f!==void 0)clearTimeout(f);if(h)a?.removeEventListener("abort",h);h=void 0;let P=await this.retryRequest(t.options,y,t.retryOfRequestLogID??t.requestLogID,void 0,t.requestSignal);Object.assign(t,P)}finally{if(f!==void 0)clearTimeout(f);if(h)a?.removeEventListener("abort",h)}}}async readX509ResponseError(e,t,n,s,o){let a=new AbortController,u=s.signal,l=!1,f=()=>a.abort(u.reason);if(u.addEventListener("abort",f,{once:!0}),u.aborted)f();try{let h=o.remainingTimeout(t,n),_=o.waitForRetry(h,a.signal).then(()=>{throw new le}),w=await Promise.race([e.text().catch(()=>"X.509 workload identity API response body could not be read."),_]);if(u.aborted)throw this._makeUserAbortError(u);return w}catch(h){if(h instanceof le)l=!u.aborted,s.abort(),_t(e.body).catch(()=>{return});if(u.aborted&&!l)throw this._makeUserAbortError(u);throw h}finally{u.removeEventListener("abort",f),a.abort()}}async makeRequest(e,t,n){let s=await e,o=s.maxRetries??this.maxRetries;if(t==null)t=o;let a=c(this,Y,"f");a?.beginRequestPreparation(),await this.prepareOptions(s),a?.beginRequestPlanning();let u;try{let T=await this.buildRequest(s,{retryCount:o-t});if(u={req:T.req,url:T.url,timeout:T.timeout},a){if(ra("timeout",u.timeout),a.authorizePlannedRequest(u.url,u.req,u.timeout),Se.isStreamingRequestBody(u.req.body))s.__metadata={...s.__metadata,hasStreamingBody:!0};if(await this.prepareRequest(u.req,{url:u.url,options:s}),await this._provider?.prepareRequest?.(u.req,{url:u.url,options:s}),a.beginRequestPlanning(),a.authorizePlannedRequest(u.url,u.req,u.timeout,!0),Se.isStreamingRequestBody(u.req.body))s.__metadata={...s.__metadata,hasStreamingBody:!0};let L=a.requestSnapshot().signal;if(L?.aborted||u.req.signal?.aborted)throw this._makeUserAbortError(L?.aborted?L:u.req.signal);a.setEffectiveSignal(u.req.signal||L?wd(u.req.signal??L,L).signal:void 0),a.beginRequestNetwork();let D=s.__security??{bearerAuth:!0},K=await this.authHeaders(s,D),U=a.headerSnapshots(),W=b([U.defaultHeaders,U.requestHeaders]);for(let[J,X]of K?.values??[])if(!W.nulls.has(J)&&!u.req.headers.has(J))u.req.headers.set(J,X);this.validateHeaders(b([W,u.req.headers]),D)}}catch(T){if(a?.retireRequestBody(),a&&t&&!s.__metadata?.hasStreamingBody&&Se.isRetryableFailure(T))return await this.retryRequest(s,t,n??"x509-token-exchange",Se.retryHeaders(T));throw T}let{req:l,url:f}=u,h=a?Math.min(u.timeout,a.requestSnapshot().timeout):u.timeout;a?.bindRequest(s,l,this.adminAPIKey);let _=s.__metadata?.hasStreamingBody===!0;if(!a)await this.prepareRequest(l,{url:f,options:s}),await this._provider?.prepareRequest?.(l,{url:f,options:s});if(a?.adoptRequestHeaders(l),a&&Se.isStreamingRequestBody(l.body))_=!0;let w="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),y=n===void 0?"":`, retryOf: ${n}`,P=a?.requestStartedAt(s)??Date.now();if(this.logLevel==="debug"){let T=typeof l.body==="string"?{type:"string",length:l.body.length}:l.body;te(this).debug(`[${w}] sending request`,yt({retryOfRequestLogID:n,method:s.method,url:f,options:a?{body:T,...a.requestSnapshot()}:{...s,body:T},headers:l.headers}))}let I=a?a.requestSnapshot().signal:s.signal;if(I?.aborted||l.signal?.aborted)throw this._makeUserAbortError(I?.aborted?I:l.signal);let x=s.__security??{bearerAuth:!0},v=a||this.fetchWithTimeout===rt.prototype.fetchWithTimeout?wd(l.signal??(a?I:void 0),a?I:void 0):new AbortController,C=a?.remainingTimeout(s,h)??h,E=a?rt.prototype.fetchWithAuth:this.fetchWithAuth;a?.releaseRequestBody(l.body);let S=await E.call(this,f,l,C,v,x).catch(Mn),j=Date.now();if(S instanceof globalThis.Error){let T=`retrying, ${t} attempts remaining`;if(I?.aborted||l.signal?.aborted)throw this._makeUserAbortError(I?.aborted?I:l.signal);let L=ht(S)||/timed? ?out/i.test(String(S)+("cause"in S?String(S.cause):""));if(t&&!_&&(!a||ai(S)))return te(this).info(`[${w}] connection ${L?"timed out":"failed"} - ${T}`),te(this).debug(`[${w}] connection ${L?"timed out":"failed"} (${T})`,yt({retryOfRequestLogID:n,url:f,durationMs:j-P,message:a?"X.509 workload identity API connection failed.":S.message})),this.retryRequest(s,t,n??w,void 0,l.signal);let D=_?"error; streaming body cannot be retried":"error; no more retries left";if(te(this).info(`[${w}] connection ${L?"timed out":"failed"} - ${D}`),te(this).debug(`[${w}] connection ${L?"timed out":"failed"} (${D})`,yt({retryOfRequestLogID:n,url:f,durationMs:j-P,message:a?"X.509 workload identity API connection failed.":S.message})),S instanceof Ye||S instanceof Nr)throw S;if(L){let K="cause"in S?S.cause:void 0,W=typeof K==="object"&&K!==null&&"code"in K&&K.code==="UND_ERR_HEADERS_TIMEOUT"?new le({message:"Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout."}):new le;if(a)throw new le;throw Object.assign(W,{cause:S})}if(a)throw new Ge({message:"X.509 workload identity API connection failed."});throw new Ge({message:$_(S),cause:S})}let R=[...S.headers.entries()].filter(([T])=>T==="x-request-id").map(([T,L])=>", "+T+": "+JSON.stringify(L)).join(""),F=`[${w}${y}${R}] ${l.method} ${Qo(f)} ${S.ok?"succeeded":"failed"} with status ${S.status} in ${j-P}ms`;if(!S.ok){let T=S.status===401&&a&&x.bearerAuth&&a.usedWorkloadToken(s);if(T)a.invalidateToken();if(S.status===401&&(a||this._workloadIdentityAuth)&&x.bearerAuth&&(!a||a.usedWorkloadToken(s))&&(!a||t>0)&&!_&&!s.__metadata?.workloadIdentityTokenRefreshed){if(a)_t(S.body).catch(()=>{return});else await _t(S.body),this._workloadIdentityAuth?.invalidateToken();let X={...s,__metadata:{...s.__metadata,workloadIdentityTokenRefreshed:!0}};return this.makeRequest(X,a?t-1:t,n??w)}let L=T&&s.__metadata?.workloadIdentityTokenRefreshed?!1:await this.shouldRetry(S);if(t&&L&&!_){let X=`retrying, ${t} attempts remaining`;if(a)_t(S.body).catch(()=>{return});else await _t(S.body);return te(this).info(`${F} - ${X}`),te(this).debug(`[${w}] response error (${X})`,yt({retryOfRequestLogID:n,url:S.url,status:S.status,headers:S.headers,durationMs:j-P})),this.retryRequest(s,t,n??w,S.headers,l.signal)}let D=L?_?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";te(this).info(`${F} - ${D}`);let K=a?await this.readX509ResponseError(S,s,h,v,a):await S.text().catch((X)=>Mn(X).message),U=Tc(K),W=U?void 0:K;throw te(this).debug(`[${w}] response error (${D})`,yt({retryOfRequestLogID:n,url:S.url,status:S.status,headers:S.headers,message:W,durationMs:Date.now()-P})),this.makeStatusError(S.status,U,W,S.headers)}te(this).info(F),te(this).debug(`[${w}] response start`,yt({retryOfRequestLogID:n,url:S.url,status:S.status,headers:S.headers,durationMs:j-P}));let k=a?.continuation();return a?.releaseRequestCredentials(),c(this,qo,"f").set(v,{timeout:h,retriesRemaining:t,hasStreamingBody:_,...a?{authentication:a}:{},helperMethod:s.__metadata?.helperMethod,...k?{continueRequest:k}:{}}),{response:S,options:s,controller:v,requestSignal:l.signal,requestLogID:w,retryOfRequestLogID:n,startTime:P}}getAPIList(e,t,n){return this.requestAPIList(t,n&&"then"in n?n.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...n})}requestAPIList(e,t){let n=c(this,Y,"f")??this._workloadIdentityAuth,s=n instanceof Se?Promise.resolve(t).then((u)=>n.runRequest(()=>this.makeRequest(u,null,void 0),this)):this.makeRequest(t,null,void 0),o=new si(this,s,e),a=this.responsePromise(s,async(u,l)=>{let f=await this.parseResponseWithTimeout(u,l);return new e(u,l.response,f,l.options)});return o.then=a.then.bind(a),o.catch=a.catch.bind(a),o.finally=a.finally.bind(a),o.withResponse=a.withResponse.bind(a),o._thenUnwrap=a._thenUnwrap.bind(a),o}async fetchWithAuth(e,t,n,s,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&!c(this,Ot,"f")&&o.bearerAuth){let l=t.headers;if(l.get("Authorization")===`Bearer ${T_}`){let h=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${h}`)}}return await(c(this,Ot,"f")?rt.prototype.fetchWithTimeout:this.fetchWithTimeout).call(this,e,t,n,s)}async fetchWithTimeout(e,t,n,s){let{signal:o,method:a,...u}=t||{},l=this._makeAbort(s),f=!!o&&Pd.get(s)===o,h=o&&!f?jc(o,l,s.signal):void 0,_=setTimeout(l,n),w=globalThis.ReadableStream&&u.body instanceof globalThis.ReadableStream||typeof u.body==="object"&&u.body!==null&&Symbol.asyncIterator in u.body,y={signal:s.signal,...w?{duplex:"half"}:{},method:"GET",...u};if(a)y.method=a.toUpperCase();try{let P=await(c(this,Ot,"f")??this.fetch).call(void 0,e,y);if(h)na(P.body??P,l,s.signal);return P}catch(P){throw h?.(),P}finally{clearTimeout(_)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,n,s,o=e.signal){let a,u=s?.get("retry-after-ms");if(u){let h=parseFloat(u);if(!Number.isNaN(h))a=h}let l=s?.get("retry-after");if(l&&a===void 0){let h=parseFloat(l);if(!Number.isNaN(h))a=h*1000;else a=Date.parse(l)-Date.now()}if(a===void 0||!Number.isFinite(a)||a<0||a>60000){let h=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,h)}let f=c(this,Y,"f");if(f){let h=f.remainingTimeout(e,f.requestSnapshot().timeout);if(a>=h)throw new le}if(f)await f.waitForRetry(a,f.effectiveSignal());else{let h=o===e.signal?[o]:[o,e.signal];try{await Fr(a,...h)}catch(_){let w=h.find((y)=>y?.aborted);if(w)throw this._makeUserAbortError(w);throw _}}return this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(0.5*Math.pow(2,o),8),u=1-Math.random()*0.25;return a*u*1000}async buildRequest(e,{retryCount:t=0}={}){if(c(this,Y,"f")&&!c(this,Y,"f").inRequest(this)){let j=c(this,Y,"f");return await j.runRequest(async()=>{let R=await rt.prototype.buildRequest.call(this,e,{retryCount:t});return j.releaseRequestBody(R.req.body),R},this)}let n={...e},s=c(this,Y,"f"),o=s?.snapshotTenant(this.organization,this.project),a=s?.snapshotHeaders(this._options.defaultHeaders,n.headers);if(a)n.headers=a.requestHeaders;let u=s?Pa(this.fetchOptions):void 0,l=s?Pa(n.fetchOptions):void 0,{method:f,path:h,query:_,defaultBaseURL:w}=n,y=this.buildURL(h,_,w);s?.snapshotAPIURL(y);let P="timeout"in n;if(P)ra("timeout",n.timeout);if(n.timeout=n.timeout??this.timeout,s&&l)s.snapshotRequest(n.signal,n.timeout,l);if(s){let j=s.requestSnapshot();if(n.timeout=j.timeout,j.signal===void 0)delete n.signal;else n.signal=j.signal}let I=this._provider||s?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),{bodyHeaders:x,body:v,isStreamingBody:C}=this.buildBody({options:n});if(C)e.__metadata={...e.__metadata,hasStreamingBody:!0},s?.ownRequestBody(v,n.body);let E=await this.buildHeaders({options:e,method:f,bodyHeaders:x,authenticationHeaders:I,retryCount:t,x509Headers:a,x509Timeout:P?n.timeout:void 0,x509Tenant:o});return{req:{method:f,headers:E,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&v instanceof globalThis.ReadableStream&&{duplex:"half"},...v&&{body:v},...(s?u:this.fetchOptions)??{},...(s?l:n.fetchOptions)??{}},url:y,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,authenticationHeaders:s,retryCount:o,x509Headers:a,x509Timeout:u,x509Tenant:l}){let f={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();f[this.idempotencyHeader]=e.idempotencyKey}let h=e.__metadata?.helperMethod,_=a?u:e.timeout,w=b([f,{Accept:"application/json",...!gd()?{"User-Agent":this.getUserAgent()}:void 0,"X-Stainless-Retry-Count":String(o),..._?{"X-Stainless-Timeout":String(Math.trunc(_/1000))}:{},...Gc(),...typeof h==="string"?{"X-Stainless-Helper-Method":h}:{},"OpenAI-Organization":l?l.organization:this.organization,"OpenAI-Project":l?l.project:this.project},c(this,Y,"f")&&!c(this,Y,"f").isPlanningRequest()?await this.authHeaders(e,e.__security??{bearerAuth:!0}):s,a?.defaultHeaders??this._options.defaultHeaders,n,a?.requestHeaders??e.headers]);if(!this._provider&&!c(this,Y,"f")?.isPlanningRequest())this.validateHeaders(w,e.__security??{bearerAuth:!0});return w.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){let t=new Z;return Object.defineProperty(t,"cause",{value:e.reason,writable:!0,configurable:!0}),t}buildBody({options:e}){let{body:t,headers:n}=e;if(!t){if(t===void 0&&"body"in e)return{...c(this,Uo,"f").call(this,{body:t,headers:b([n])}),isStreamingBody:!1};return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1}}let s=b([n]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,a=!o&&(typeof t==="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==="string"&&s.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||o)return{bodyHeaders:void 0,body:t,isStreamingBody:!a};else if(typeof t==="object"&&((Symbol.asyncIterator in t)||(Symbol.iterator in t)&&("next"in t)&&typeof t.next==="function"))return{bodyHeaders:void 0,body:Fn(t),isStreamingBody:!0};else if(typeof t==="object"&&s.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1};else return{...c(this,Uo,"f").call(this,{body:t,headers:s}),isStreamingBody:!1}}}rt=g,Uo=new WeakMap,Y=new WeakMap,Zi=new WeakMap,Ot=new WeakMap,Ko=new WeakMap,qo=new WeakMap,Oc=new WeakSet,Ad=function(){return c(this,Ko,"f")||this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};g.OpenAI=rt;g.DEFAULT_TIMEOUT=600000;g.OpenAIError=m;g.APIError=H;g.APIConnectionError=Ge;g.APIConnectionTimeoutError=le;g.APIUserAbortError=Z;g.NotFoundError=Gt;g.ConflictError=Yt;g.RateLimitError=Zt;g.BadRequestError=mt;g.AuthenticationError=Jt;g.InternalServerError=er;g.PermissionDeniedError=Vt;g.UnprocessableEntityError=Qt;g.InvalidWebhookSignatureError=Be;g.toFile=mi;g.toStreamingFile=fi;g.Completions=yn;g.Chat=_r;g.Embeddings=wn;g.Files=Pn;g.Images=Rn;g.ContentProvenanceChecks=bn;g.Audio=xt;g.Moderations=En;g.Models=vn;g.FineTuning=dt;g.Graders=$r;g.VectorStores=Ht;g.Safety=Lr;g.Webhooks=Br;g.Beta=Je;g.Batches=on;g.Uploads=Mr;g.Admin=gr;g.Responses=Et;g.Live=vt;g.Realtime=Ut;g.Conversations=Cr;g.Evals=Tr;g.Containers=kr;g.Skills=Xt;g.Videos=$n;g.ConversationCursorPage=q;g.CursorPage=O;g.NextCursorPage=re;g.Page=ye;g.TokenPage=Hn;var Pd=new WeakMap;function wd(e,t){let n=new AbortController;if(!e)return n;let s=globalThis.AbortSignal;if(typeof s?.any!=="function"||!(e instanceof s))return n;try{let o=[n.signal,e];if(t&&t!==e)o.push(t);let a=s.any(o);Object.defineProperty(n,"signal",{value:a,configurable:!0}),Pd.set(n,e)}catch{}return n}function $_(e){if(j_(e))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });";return}function j_(e){let t=e;for(let n=0;n<8&&t&&typeof t==="object";n++){let s=t;if(s.code==="UND_ERR_INVALID_ARG"&&typeof s.message==="string"&&s.message.includes("invalid onRequestStart method"))return!0;t=s.cause}return!1}class cn extends g{constructor({baseURL:e=Ee("OPENAI_BASE_URL"),apiKey:t=Ee("AZURE_OPENAI_API_KEY"),apiVersion:n=Ee("OPENAI_API_VERSION"),endpoint:s,deployment:o,azureADTokenProvider:a,dangerouslyAllowBrowser:u,dataResidency:l,...f}={}){if(ma(l,"AzureOpenAI"),!n)throw new m("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof a==="function")u??(u=!0);if(!a&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new m("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(f.defaultQuery={...f.defaultQuery,"api-version":n},!e){if(!s)s=process.env.AZURE_OPENAI_ENDPOINT;if(!s)throw new m("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let h=s.length;while(h>0&&s[h-1]==="/")h--;e=`${s.slice(0,h)}/openai`}else if(s)throw new m("baseURL and endpoint are mutually exclusive");super({apiKey:a??t,baseURL:e,...f,...u===void 0?{}:{dangerouslyAllowBrowser:u}});this.apiVersion="",this.apiVersion=n,this.deploymentName=o}withOptions(e){let t={apiVersion:this.apiVersion,deployment:this.deploymentName,...e};if(M(e,"endpoint")&&e.endpoint!==void 0&&!M(e,"baseURL"))t.baseURL=void 0;return super.withOptions(t)}async buildRequest(e,t={}){if(M_.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!me(e.body))throw Error("Expected request body to be an object");let s=this.deploymentName||e.body.model||e.__metadata?.model;if(s!==void 0&&!L_(this.baseURL))e.path=d`/deployments/${s}`+e.path}let n=await super.buildRequest(e,t);if(n.req.headers.has("api-key"))n.req.redirect="manual";return n}async fetchWithAuth(e,t,n,s,o){if(new Headers(t.headers).has("api-key"))t.redirect="manual";return super.fetchWithAuth(e,t,n,s,o)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};if(n.bearerAuth&&typeof this._options.apiKey==="string")return b([{"api-key":this.apiKey}]);return super.authHeaders(e,n)}}function L_(e){try{return new URL(e).pathname.split("/").includes("deployments")}catch{return!1}}var M_=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var Id=Symbol.for("openai.privateBedrockClient");var B_;B_=Id;export{g,cn};
31
+ `)){let D=L.indexOf(":");if(D>=0)T[L.substring(0,D).trim()]=L.substring(D+1).trim()}R.defaultHeaders=b([T,R.defaultHeaders])}if(this._options=R,this._provider=j,E){let T=new Se(E,I,_,w);this._workloadIdentityAuth=T,A(this,Y,T,"f"),A(this,Zi,t,"f"),A(this,Ot,T.fetch(),"f"),this.fetch=c(this,Ot,"f"),Au(this)}else if(C.legacy)this._workloadIdentityAuth=new Jn(C.legacy,this.fetch);this.apiKey=typeof f==="string"?f:null,this.adminAPIKey=h,this.organization=_,this.project=w,this.webhookSecret=y}withOptions(e){let t=ha(e),n=c(this,Y,"f"),s={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:c(this,Y,"f")?void 0:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:n?.identitySnapshot()??this._options.workloadIdentity,x509Transport:this._options.x509Transport,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret},{credential:o,provider:a}=ju(s,e,c(this,Zi,"f"),n!==void 0);if(t!==void 0)delete s.baseURL;let u={...s,...e,credential:o,provider:a,[bd]:c(this,Ko,"f")&&t===void 0&&!M(e,"baseURL")&&e.credential===void 0&&!a},l=new this.constructor(u);if(a&&new URL(l.baseURL).origin!==new URL(this.baseURL).origin)Object.assign(l._options,{defaultHeaders:e.defaultHeaders,defaultQuery:e.defaultQuery,fetchOptions:e.fetchOptions,fetch:e.fetch}),l.fetchOptions=e.fetchOptions,l.fetch=e.fetch??Nn(),l.organization=e.organization??null,l.project=e.project??null;if(c(this,Y,"f")&&c(l,Y,"f")&&this.baseURL===l.baseURL&&c(this,Y,"f").matches(c(l,Y,"f")))l._workloadIdentityAuth=c(this,Y,"f"),A(l,Y,c(this,Y,"f"),"f"),A(l,Ot,c(this,Ot,"f"),"f");return l}defaultQuery(){return this._options.defaultQuery}_buildWebSocketHeaders(e){return Object.fromEntries(b([{"User-Agent":this.getUserAgent(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},e,this._options.defaultHeaders]).values)}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(e.get("authorization")||e.get("api-key"))return;if(t.has("authorization")||t.has("api-key"))return;if(this._workloadIdentityAuth&&n.bearerAuth)return;throw Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){if((c(this,Y,"f")??this._workloadIdentityAuth)instanceof Se&&t.adminAPIKeyAuth&&this.adminAPIKey!==null)return await this.adminAPIKeyAuth(e);return b([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){let t=c(this,Y,"f")??this._workloadIdentityAuth;if(t){if(t instanceof Se){if(t===this._workloadIdentityAuth&&(this.fetchWithAuth!==rt.prototype.fetchWithAuth||this.fetchWithTimeout!==rt.prototype.fetchWithTimeout))throw new m("X.509 workload identity does not support overridden fetch dispatch hooks.");let o=t.headerSnapshots();if(!Se.shouldAuthenticate(e,o.defaultHeaders,o.requestHeaders))return}let s=t instanceof Se?await t.getToken(e,{apiURL:t.requestAPIURL(),...t.headerSnapshots(),...t.requestSnapshot(),signal:t.effectiveSignal(),...t.tenantSnapshot()}):await t.getToken();return b([{Authorization:`Bearer ${s}`}])}let{apiKey:n}=await Ec(this);if(n==null)return;return b([{Authorization:`Bearer ${n}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey==null)return;return b([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return uu(e)}getUserAgent(){return`${this.constructor.name}/JS ${kt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ve()}`}makeStatusError(e,t,n,s){let o=t&&typeof t==="object"&&t.error==null?{error:t}:t;return H.generate(e,o,n,s)}_hasApiKeyProvider(){return typeof this._options.apiKey==="function"}async _callApiKey(e){if(this._provider)return e?.(this.apiKey),!1;let t=this._options.apiKey;if(typeof t!=="function")return e?.(this.apiKey),!1;let n;try{n=await t()}catch(s){if(s instanceof m)throw s;throw new m(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof n!=="string"||!n)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,e?.(this.apiKey),!0}buildURL(e,t,n){let s=!c(this,Oc,"m",Ad).call(this)&&n||this.baseURL,o=kc(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),u=Object.fromEntries(o.searchParams);if(!ta(a)||!ta(u))t={...u,...a,...t};if(typeof t==="object"&&t&&!Array.isArray(t))o.search=this.stringifyQuery(t);return o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then((s)=>({method:e,path:t,...s})))}request(e,t=null){let n=c(this,Y,"f")??this._workloadIdentityAuth,s=n instanceof Se?Promise.resolve(e).then((o)=>n.runRequest(()=>this.makeRequest(o,t,void 0),this)):this.makeRequest(e,t,void 0);return this.responsePromise(s)}responsePromise(e,t=(n,s)=>this.parseResponseWithTimeout(n,s)){let n=new or(this,e,(s,o)=>{let a=c(this,qo,"f").get(o.controller)?.continueRequest;return a?a(()=>t(s,o)):t(s,o)});return n.withResponse=async()=>{let s=await n,{response:o}=await e;return{data:s,response:o,request_id:o.headers.get("x-request-id")}},n._thenUnwrap=(s)=>this.responsePromise(e,async(o,a)=>Kn(s(await t(o,a),a),a.response)),n}async parseResponseWithTimeout(e,t){if(t.options.stream||t.options.__binaryResponse||t.response.status===204||t.response.headers.get("content-length")==="0")return sr(e,t);while(!0){let n=c(this,qo,"f").get(t.controller),s=n?.timeout??t.options.timeout??this.timeout,o=n?.authentication,a=o?t.controller.signal:t.options.signal,u=()=>o&&a?this._makeUserAbortError(a):new Z,l;try{l=o?.remainingTimeout(t.options,s)??Math.max(0,t.startTime+s-Date.now())}catch(w){let y=a?.aborted?u():void 0;throw t.controller.abort(),_t(t.response.body).catch(()=>{return}),y??w}let f,h,_=!1;try{if(a?.aborted&&n?.helperMethod!=="runTools")throw u();let w=new Promise((y,P)=>{if(f=setTimeout(()=>{_=!0,t.controller.abort(),P(new le)},l),a)h=()=>{if(!_)P(u())},a.addEventListener("abort",h,{once:!0})});return await Promise.race([sr(e,t),w])}catch(w){if(a?.aborted&&!_)throw u();if(!_){if(o&&w instanceof SyntaxError)throw SyntaxError("X.509 workload identity API response contains invalid JSON.");if(o&&!(w instanceof m))throw new Ge({message:"X.509 workload identity API response body could not be read."});throw w}let y=n?.retriesRemaining??0;if(!y||n?.hasStreamingBody||t.options.__metadata?.hasStreamingBody||globalThis.ReadableStream&&t.options.body instanceof globalThis.ReadableStream||typeof t.options.body==="object"&&t.options.body!==null&&((Symbol.asyncIterator in t.options.body)||(Symbol.iterator in t.options.body)&&("next"in t.options.body)&&typeof t.options.body.next==="function"))throw new le;if(f!==void 0)clearTimeout(f);if(h)a?.removeEventListener("abort",h);h=void 0;let P=await this.retryRequest(t.options,y,t.retryOfRequestLogID??t.requestLogID,void 0,t.requestSignal);Object.assign(t,P)}finally{if(f!==void 0)clearTimeout(f);if(h)a?.removeEventListener("abort",h)}}}async readX509ResponseError(e,t,n,s,o){let a=new AbortController,u=s.signal,l=!1,f=()=>a.abort(u.reason);if(u.addEventListener("abort",f,{once:!0}),u.aborted)f();try{let h=o.remainingTimeout(t,n),_=o.waitForRetry(h,a.signal).then(()=>{throw new le}),w=await Promise.race([e.text().catch(()=>"X.509 workload identity API response body could not be read."),_]);if(u.aborted)throw this._makeUserAbortError(u);return w}catch(h){if(h instanceof le)l=!u.aborted,s.abort(),_t(e.body).catch(()=>{return});if(u.aborted&&!l)throw this._makeUserAbortError(u);throw h}finally{u.removeEventListener("abort",f),a.abort()}}async makeRequest(e,t,n){let s=await e,o=s.maxRetries??this.maxRetries;if(t==null)t=o;let a=c(this,Y,"f");a?.beginRequestPreparation(),await this.prepareOptions(s),a?.beginRequestPlanning();let u;try{let T=await this.buildRequest(s,{retryCount:o-t});if(u={req:T.req,url:T.url,timeout:T.timeout},a){if(ra("timeout",u.timeout),a.authorizePlannedRequest(u.url,u.req,u.timeout),Se.isStreamingRequestBody(u.req.body))s.__metadata={...s.__metadata,hasStreamingBody:!0};if(await this.prepareRequest(u.req,{url:u.url,options:s}),await this._provider?.prepareRequest?.(u.req,{url:u.url,options:s}),a.beginRequestPlanning(),a.authorizePlannedRequest(u.url,u.req,u.timeout,!0),Se.isStreamingRequestBody(u.req.body))s.__metadata={...s.__metadata,hasStreamingBody:!0};let L=a.requestSnapshot().signal;if(L?.aborted||u.req.signal?.aborted)throw this._makeUserAbortError(L?.aborted?L:u.req.signal);a.setEffectiveSignal(u.req.signal||L?wd(u.req.signal??L,L).signal:void 0),a.beginRequestNetwork();let D=s.__security??{bearerAuth:!0},K=await this.authHeaders(s,D),U=a.headerSnapshots(),W=b([U.defaultHeaders,U.requestHeaders]);for(let[J,X]of K?.values??[])if(!W.nulls.has(J)&&!u.req.headers.has(J))u.req.headers.set(J,X);this.validateHeaders(b([W,u.req.headers]),D)}}catch(T){if(a?.retireRequestBody(),a&&t&&!s.__metadata?.hasStreamingBody&&Se.isRetryableFailure(T))return await this.retryRequest(s,t,n??"x509-token-exchange",Se.retryHeaders(T));throw T}let{req:l,url:f}=u,h=a?Math.min(u.timeout,a.requestSnapshot().timeout):u.timeout;a?.bindRequest(s,l,this.adminAPIKey);let _=s.__metadata?.hasStreamingBody===!0;if(!a)await this.prepareRequest(l,{url:f,options:s}),await this._provider?.prepareRequest?.(l,{url:f,options:s});if(a?.adoptRequestHeaders(l),a&&Se.isStreamingRequestBody(l.body))_=!0;let w="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),y=n===void 0?"":`, retryOf: ${n}`,P=a?.requestStartedAt(s)??Date.now();if(this.logLevel==="debug"){let T=typeof l.body==="string"?{type:"string",length:l.body.length}:l.body;te(this).debug(`[${w}] sending request`,yt({retryOfRequestLogID:n,method:s.method,url:f,options:a?{body:T,...a.requestSnapshot()}:{...s,body:T},headers:l.headers}))}let I=a?a.requestSnapshot().signal:s.signal;if(I?.aborted||l.signal?.aborted)throw this._makeUserAbortError(I?.aborted?I:l.signal);let x=s.__security??{bearerAuth:!0},v=a||this.fetchWithTimeout===rt.prototype.fetchWithTimeout?wd(l.signal??(a?I:void 0),a?I:void 0):new AbortController,C=a?.remainingTimeout(s,h)??h,E=a?rt.prototype.fetchWithAuth:this.fetchWithAuth;a?.releaseRequestBody(l.body);let S=await E.call(this,f,l,C,v,x).catch(Mn),j=Date.now();if(S instanceof globalThis.Error){let T=`retrying, ${t} attempts remaining`;if(I?.aborted||l.signal?.aborted)throw this._makeUserAbortError(I?.aborted?I:l.signal);let L=ht(S)||/timed? ?out/i.test(String(S)+("cause"in S?String(S.cause):""));if(t&&!_&&(!a||ai(S)))return te(this).info(`[${w}] connection ${L?"timed out":"failed"} - ${T}`),te(this).debug(`[${w}] connection ${L?"timed out":"failed"} (${T})`,yt({retryOfRequestLogID:n,url:f,durationMs:j-P,message:a?"X.509 workload identity API connection failed.":S.message})),this.retryRequest(s,t,n??w,void 0,l.signal);let D=_?"error; streaming body cannot be retried":"error; no more retries left";if(te(this).info(`[${w}] connection ${L?"timed out":"failed"} - ${D}`),te(this).debug(`[${w}] connection ${L?"timed out":"failed"} (${D})`,yt({retryOfRequestLogID:n,url:f,durationMs:j-P,message:a?"X.509 workload identity API connection failed.":S.message})),S instanceof Ye||S instanceof Nr)throw S;if(L){let K="cause"in S?S.cause:void 0,W=typeof K==="object"&&K!==null&&"code"in K&&K.code==="UND_ERR_HEADERS_TIMEOUT"?new le({message:"Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout."}):new le;if(a)throw new le;throw Object.assign(W,{cause:S})}if(a)throw new Ge({message:"X.509 workload identity API connection failed."});throw new Ge({message:$_(S),cause:S})}let R=[...S.headers.entries()].filter(([T])=>T==="x-request-id").map(([T,L])=>", "+T+": "+JSON.stringify(L)).join(""),F=`[${w}${y}${R}] ${l.method} ${Qo(f)} ${S.ok?"succeeded":"failed"} with status ${S.status} in ${j-P}ms`;if(!S.ok){let T=S.status===401&&a&&x.bearerAuth&&a.usedWorkloadToken(s);if(T)a.invalidateToken();if(S.status===401&&(a||this._workloadIdentityAuth)&&x.bearerAuth&&(!a||a.usedWorkloadToken(s))&&(!a||t>0)&&!_&&!s.__metadata?.workloadIdentityTokenRefreshed){if(a)_t(S.body).catch(()=>{return});else await _t(S.body),this._workloadIdentityAuth?.invalidateToken();let X={...s,__metadata:{...s.__metadata,workloadIdentityTokenRefreshed:!0}};return this.makeRequest(X,a?t-1:t,n??w)}let L=T&&s.__metadata?.workloadIdentityTokenRefreshed?!1:await this.shouldRetry(S);if(t&&L&&!_){let X=`retrying, ${t} attempts remaining`;if(a)_t(S.body).catch(()=>{return});else await _t(S.body);return te(this).info(`${F} - ${X}`),te(this).debug(`[${w}] response error (${X})`,yt({retryOfRequestLogID:n,url:S.url,status:S.status,headers:S.headers,durationMs:j-P})),this.retryRequest(s,t,n??w,S.headers,l.signal)}let D=L?_?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";te(this).info(`${F} - ${D}`);let K=a?await this.readX509ResponseError(S,s,h,v,a):await S.text().catch((X)=>Mn(X).message),U=Tc(K),W=U?void 0:K;throw te(this).debug(`[${w}] response error (${D})`,yt({retryOfRequestLogID:n,url:S.url,status:S.status,headers:S.headers,message:W,durationMs:Date.now()-P})),this.makeStatusError(S.status,U,W,S.headers)}te(this).info(F),te(this).debug(`[${w}] response start`,yt({retryOfRequestLogID:n,url:S.url,status:S.status,headers:S.headers,durationMs:j-P}));let k=a?.continuation();return a?.releaseRequestCredentials(),c(this,qo,"f").set(v,{timeout:h,retriesRemaining:t,hasStreamingBody:_,...a?{authentication:a}:{},helperMethod:s.__metadata?.helperMethod,...k?{continueRequest:k}:{}}),{response:S,options:s,controller:v,requestSignal:l.signal,requestLogID:w,retryOfRequestLogID:n,startTime:P}}getAPIList(e,t,n){return this.requestAPIList(t,n&&"then"in n?n.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...n})}requestAPIList(e,t){let n=c(this,Y,"f")??this._workloadIdentityAuth,s=n instanceof Se?Promise.resolve(t).then((u)=>n.runRequest(()=>this.makeRequest(u,null,void 0),this)):this.makeRequest(t,null,void 0),o=new si(this,s,e),a=this.responsePromise(s,async(u,l)=>{let f=await this.parseResponseWithTimeout(u,l);return new e(u,l.response,f,l.options)});return o.then=a.then.bind(a),o.catch=a.catch.bind(a),o.finally=a.finally.bind(a),o.withResponse=a.withResponse.bind(a),o._thenUnwrap=a._thenUnwrap.bind(a),o}async fetchWithAuth(e,t,n,s,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&!c(this,Ot,"f")&&o.bearerAuth){let l=t.headers;if(l.get("Authorization")===`Bearer ${T_}`){let h=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${h}`)}}return await(c(this,Ot,"f")?rt.prototype.fetchWithTimeout:this.fetchWithTimeout).call(this,e,t,n,s)}async fetchWithTimeout(e,t,n,s){let{signal:o,method:a,...u}=t||{},l=this._makeAbort(s),f=!!o&&Pd.get(s)===o,h=o&&!f?jc(o,l,s.signal):void 0,_=setTimeout(l,n),w=globalThis.ReadableStream&&u.body instanceof globalThis.ReadableStream||typeof u.body==="object"&&u.body!==null&&Symbol.asyncIterator in u.body,y={signal:s.signal,...w?{duplex:"half"}:{},method:"GET",...u};if(a)y.method=a.toUpperCase();try{let P=await(c(this,Ot,"f")??this.fetch).call(void 0,e,y);if(h)na(P.body??P,l,s.signal);return P}catch(P){throw h?.(),P}finally{clearTimeout(_)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,n,s,o=e.signal){let a,u=s?.get("retry-after-ms");if(u){let h=parseFloat(u);if(!Number.isNaN(h))a=h}let l=s?.get("retry-after");if(l&&a===void 0){let h=parseFloat(l);if(!Number.isNaN(h))a=h*1000;else a=Date.parse(l)-Date.now()}if(a===void 0||!Number.isFinite(a)||a<0||a>60000){let h=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,h)}let f=c(this,Y,"f");if(f){let h=f.remainingTimeout(e,f.requestSnapshot().timeout);if(a>=h)throw new le}if(f)await f.waitForRetry(a,f.effectiveSignal());else{let h=o===e.signal?[o]:[o,e.signal];try{await Fr(a,...h)}catch(_){let w=h.find((y)=>y?.aborted);if(w)throw this._makeUserAbortError(w);throw _}}return this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(0.5*Math.pow(2,o),8),u=1-Math.random()*0.25;return a*u*1000}async buildRequest(e,{retryCount:t=0}={}){if(c(this,Y,"f")&&!c(this,Y,"f").inRequest(this)){let j=c(this,Y,"f");return await j.runRequest(async()=>{let R=await rt.prototype.buildRequest.call(this,e,{retryCount:t});return j.releaseRequestBody(R.req.body),R},this)}let n={...e},s=c(this,Y,"f"),o=s?.snapshotTenant(this.organization,this.project),a=s?.snapshotHeaders(this._options.defaultHeaders,n.headers);if(a)n.headers=a.requestHeaders;let u=s?Pa(this.fetchOptions):void 0,l=s?Pa(n.fetchOptions):void 0,{method:f,path:h,query:_,defaultBaseURL:w}=n,y=this.buildURL(h,_,w);s?.snapshotAPIURL(y);let P="timeout"in n;if(P)ra("timeout",n.timeout);if(n.timeout=n.timeout??this.timeout,s&&l)s.snapshotRequest(n.signal,n.timeout,l);if(s){let j=s.requestSnapshot();if(n.timeout=j.timeout,j.signal===void 0)delete n.signal;else n.signal=j.signal}let I=this._provider||s?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),{bodyHeaders:x,body:v,isStreamingBody:C}=this.buildBody({options:n});if(C)e.__metadata={...e.__metadata,hasStreamingBody:!0},s?.ownRequestBody(v,n.body);let E=await this.buildHeaders({options:e,method:f,bodyHeaders:x,authenticationHeaders:I,retryCount:t,x509Headers:a,x509Timeout:P?n.timeout:void 0,x509Tenant:o});return{req:{method:f,headers:E,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&v instanceof globalThis.ReadableStream&&{duplex:"half"},...v&&{body:v},...(s?u:this.fetchOptions)??{},...(s?l:n.fetchOptions)??{}},url:y,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,authenticationHeaders:s,retryCount:o,x509Headers:a,x509Timeout:u,x509Tenant:l}){let f={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();f[this.idempotencyHeader]=e.idempotencyKey}let h=e.__metadata?.helperMethod,_=a?u:e.timeout,w=b([f,{Accept:"application/json",...!gd()?{"User-Agent":this.getUserAgent()}:void 0,"X-Stainless-Retry-Count":String(o),..._?{"X-Stainless-Timeout":String(Math.trunc(_/1000))}:{},...Gc(),...typeof h==="string"?{"X-Stainless-Helper-Method":h}:{},"OpenAI-Organization":l?l.organization:this.organization,"OpenAI-Project":l?l.project:this.project},c(this,Y,"f")&&!c(this,Y,"f").isPlanningRequest()?await this.authHeaders(e,e.__security??{bearerAuth:!0}):s,a?.defaultHeaders??this._options.defaultHeaders,n,a?.requestHeaders??e.headers]);if(!this._provider&&!c(this,Y,"f")?.isPlanningRequest())this.validateHeaders(w,e.__security??{bearerAuth:!0});return w.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){let t=new Z;return Object.defineProperty(t,"cause",{value:e.reason,writable:!0,configurable:!0}),t}buildBody({options:e}){let{body:t,headers:n}=e;if(!t){if(t===void 0&&"body"in e)return{...c(this,Uo,"f").call(this,{body:t,headers:b([n])}),isStreamingBody:!1};return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1}}let s=b([n]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,a=!o&&(typeof t==="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);if(ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==="string"&&s.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||o)return{bodyHeaders:void 0,body:t,isStreamingBody:!a};else if(typeof t==="object"&&((Symbol.asyncIterator in t)||(Symbol.iterator in t)&&("next"in t)&&typeof t.next==="function"))return{bodyHeaders:void 0,body:Fn(t),isStreamingBody:!0};else if(typeof t==="object"&&s.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1};else return{...c(this,Uo,"f").call(this,{body:t,headers:s}),isStreamingBody:!1}}}rt=g,Uo=new WeakMap,Y=new WeakMap,Zi=new WeakMap,Ot=new WeakMap,Ko=new WeakMap,qo=new WeakMap,Oc=new WeakSet,Ad=function(){return c(this,Ko,"f")||this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};g.OpenAI=rt;g.DEFAULT_TIMEOUT=600000;g.OpenAIError=m;g.APIError=H;g.APIConnectionError=Ge;g.APIConnectionTimeoutError=le;g.APIUserAbortError=Z;g.NotFoundError=Gt;g.ConflictError=Yt;g.RateLimitError=Zt;g.BadRequestError=mt;g.AuthenticationError=Jt;g.InternalServerError=er;g.PermissionDeniedError=Vt;g.UnprocessableEntityError=Qt;g.InvalidWebhookSignatureError=Be;g.toFile=mi;g.toStreamingFile=fi;g.Completions=yn;g.Chat=_r;g.Embeddings=wn;g.Files=Pn;g.Images=Rn;g.ContentProvenanceChecks=bn;g.Audio=xt;g.Moderations=En;g.Models=vn;g.FineTuning=dt;g.Graders=$r;g.VectorStores=Ht;g.Safety=Lr;g.Webhooks=Br;g.Beta=Je;g.Batches=on;g.Uploads=Mr;g.Admin=gr;g.Responses=Et;g.Live=vt;g.Realtime=Ut;g.Conversations=Cr;g.Evals=Tr;g.Containers=kr;g.Skills=Xt;g.Videos=$n;g.ConversationCursorPage=q;g.CursorPage=O;g.NextCursorPage=re;g.Page=ye;g.TokenPage=Hn;var Pd=new WeakMap;function wd(e,t){let n=new AbortController;if(!e)return n;let s=globalThis.AbortSignal;if(typeof s?.any!=="function"||!(e instanceof s))return n;try{let o=[n.signal,e];if(t&&t!==e)o.push(t);let a=s.any(o);Object.defineProperty(n,"signal",{value:a,configurable:!0}),Pd.set(n,e)}catch{}return n}function $_(e){if(j_(e))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });";return}function j_(e){let t=e;for(let n=0;n<8&&t&&typeof t==="object";n++){let s=t;if(s.code==="UND_ERR_INVALID_ARG"&&typeof s.message==="string"&&s.message.includes("invalid onRequestStart method"))return!0;t=s.cause}return!1}class un extends g{constructor({baseURL:e=Ee("OPENAI_BASE_URL"),apiKey:t=Ee("AZURE_OPENAI_API_KEY"),apiVersion:n=Ee("OPENAI_API_VERSION"),endpoint:s,deployment:o,azureADTokenProvider:a,dangerouslyAllowBrowser:u,dataResidency:l,...f}={}){if(ma(l,"AzureOpenAI"),!n)throw new m("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof a==="function")u??(u=!0);if(!a&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new m("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(f.defaultQuery={...f.defaultQuery,"api-version":n},!e){if(!s)s=process.env.AZURE_OPENAI_ENDPOINT;if(!s)throw new m("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let h=s.length;while(h>0&&s[h-1]==="/")h--;e=`${s.slice(0,h)}/openai`}else if(s)throw new m("baseURL and endpoint are mutually exclusive");super({apiKey:a??t,baseURL:e,...f,...u===void 0?{}:{dangerouslyAllowBrowser:u}});this.apiVersion="",this.apiVersion=n,this.deploymentName=o}withOptions(e){let t={apiVersion:this.apiVersion,deployment:this.deploymentName,...e};if(M(e,"endpoint")&&e.endpoint!==void 0&&!M(e,"baseURL"))t.baseURL=void 0;return super.withOptions(t)}async buildRequest(e,t={}){if(M_.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!me(e.body))throw Error("Expected request body to be an object");let s=this.deploymentName||e.body.model||e.__metadata?.model;if(s!==void 0&&!L_(this.baseURL))e.path=d`/deployments/${s}`+e.path}let n=await super.buildRequest(e,t);if(n.req.headers.has("api-key"))n.req.redirect="manual";return n}async fetchWithAuth(e,t,n,s,o){if(new Headers(t.headers).has("api-key"))t.redirect="manual";return super.fetchWithAuth(e,t,n,s,o)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};if(n.bearerAuth&&typeof this._options.apiKey==="string")return b([{"api-key":this.apiKey}]);return super.authHeaders(e,n)}}function L_(e){try{return new URL(e).pathname.split("/").includes("deployments")}catch{return!1}}var M_=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var Id=Symbol.for("openai.privateBedrockClient");var B_;B_=Id;export{g,un};