@shumai-one/shumai 0.6.1 → 0.6.2

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 (225) hide show
  1. package/bin/chunk-01052ssf.js +32 -0
  2. package/bin/{chunk-w4ydfy9d.js → chunk-02fvcrej.js} +4 -4
  3. package/bin/chunk-0bj887zm.js +2 -0
  4. package/bin/chunk-167z646e.js +2 -0
  5. package/bin/chunk-1ktk6764.js +10 -0
  6. package/bin/{chunk-p1ed0pa6.js → chunk-1nvd90g2.js} +1 -1
  7. package/bin/{chunk-kywdke0y.js → chunk-1wfg56z3.js} +5 -5
  8. package/bin/{chunk-ahgq10a7.js → chunk-257dcd2f.js} +2 -2
  9. package/bin/chunk-26qn7fek.js +2 -0
  10. package/bin/chunk-2cdxm1cp.js +55 -0
  11. package/bin/chunk-2jj4j8cn.js +3 -0
  12. package/bin/chunk-2ne2b54t.js +2 -0
  13. package/bin/{chunk-qqj2m1b1.js → chunk-2nhgdqdg.js} +2 -2
  14. package/bin/chunk-2vbeqczj.js +1 -0
  15. package/bin/chunk-37p6bcx2.js +1 -0
  16. package/bin/chunk-3ckkwdjx.js +13 -0
  17. package/bin/chunk-3knfx6dm.js +1 -0
  18. package/bin/chunk-3z85zxkn.js +1 -0
  19. package/bin/chunk-4mws03es.js +5 -0
  20. package/bin/chunk-54tbfvya.js +2 -0
  21. package/bin/chunk-55h9ze53.js +2 -0
  22. package/bin/chunk-56kh5fxc.js +1 -0
  23. package/bin/chunk-576nj64j.js +2 -0
  24. package/bin/{chunk-dfecgpce.js → chunk-5wapd171.js} +13 -13
  25. package/bin/chunk-6cnqjngz.js +1 -0
  26. package/bin/chunk-73yncv54.js +2 -0
  27. package/bin/chunk-7g46e1wy.js +3 -0
  28. package/bin/{chunk-jq3pq545.js → chunk-7naa7tpn.js} +2 -2
  29. package/bin/{chunk-am6dg0a5.js → chunk-7sgrtxbt.js} +2 -2
  30. package/bin/{chunk-3me1v3z5.js → chunk-7v7mypc6.js} +2 -2
  31. package/bin/chunk-82tps5n1.js +2 -0
  32. package/bin/chunk-84x8p7v5.js +1 -0
  33. package/bin/{chunk-fxtzy5f5.js → chunk-88jg9dq5.js} +2 -2
  34. package/bin/chunk-8cjet7pp.js +12 -0
  35. package/bin/chunk-8fyg9dy4.js +2 -0
  36. package/bin/chunk-8gtfgkrn.js +2 -0
  37. package/bin/chunk-8mqbztj8.js +2 -0
  38. package/bin/chunk-8xb6yz11.js +2 -0
  39. package/bin/chunk-8yjsmr7g.js +2 -0
  40. package/bin/chunk-91rb0jpb.js +2 -0
  41. package/bin/chunk-96qpjght.js +2 -0
  42. package/bin/chunk-9f1xk1nt.js +1 -0
  43. package/bin/chunk-9mk9cvbk.js +1 -0
  44. package/bin/{chunk-r5g84kj4.js → chunk-9n1w5dw1.js} +3 -3
  45. package/bin/chunk-9nw5w8vh.js +1 -0
  46. package/bin/{chunk-3j82q2gj.js → chunk-9t3p4xp6.js} +1 -1
  47. package/bin/chunk-9xhjy897.js +11 -0
  48. package/bin/chunk-9zsv6d2f.js +1 -0
  49. package/bin/chunk-a411xhmm.js +7 -0
  50. package/bin/{chunk-s01p4w8d.js → chunk-a74g6h8a.js} +2 -2
  51. package/bin/chunk-ah8fjb6f.js +2 -0
  52. package/bin/chunk-atfz7g7e.js +2 -0
  53. package/bin/{chunk-swz6v48q.js → chunk-b5rhvzv9.js} +2 -2
  54. package/bin/{chunk-bg6waaf9.js → chunk-b7bnp021.js} +2 -2
  55. package/bin/chunk-cf5axr8c.js +1 -0
  56. package/bin/chunk-cgmebxx6.js +2 -0
  57. package/bin/chunk-cwat1jwx.js +3 -0
  58. package/bin/chunk-cz13a82m.js +3 -0
  59. package/bin/chunk-dk42gf7v.js +2 -0
  60. package/bin/chunk-e4f56spj.js +4 -0
  61. package/bin/chunk-e4yscwen.js +18 -0
  62. package/bin/chunk-eb7mzbfm.js +1 -0
  63. package/bin/chunk-er14d498.js +3 -0
  64. package/bin/{chunk-bs6saf4d.js → chunk-eyjfhdp9.js} +2 -2
  65. package/bin/chunk-f25fe9th.js +393 -0
  66. package/bin/chunk-f6avg5qe.js +129 -0
  67. package/bin/chunk-fatmqnp1.js +2 -0
  68. package/bin/chunk-fvx9k1dc.js +2 -0
  69. package/bin/{chunk-h6f2gyt5.js → chunk-g22wmpk1.js} +2 -2
  70. package/bin/chunk-g6sdezec.js +2 -0
  71. package/bin/chunk-gtf19jc1.js +2 -0
  72. package/bin/chunk-gxepkvt2.js +2 -0
  73. package/bin/chunk-h1n7jqnw.js +1 -0
  74. package/bin/chunk-hfm82066.js +2 -0
  75. package/bin/chunk-hnkcgvcj.js +3 -0
  76. package/bin/{chunk-agcnbjxk.js → chunk-hpbn0k9n.js} +2 -2
  77. package/bin/{chunk-d4hk62q2.js → chunk-hpwv4am3.js} +4 -4
  78. package/bin/{chunk-acmr8v0d.js → chunk-hw6czrya.js} +1 -1
  79. package/bin/{chunk-r9gp9yqw.js → chunk-hzkjgcre.js} +1 -1
  80. package/bin/chunk-j2s311yc.js +3 -0
  81. package/bin/{chunk-6hzktewz.js → chunk-jt02kpfc.js} +2 -2
  82. package/bin/{chunk-c60j1b4w.js → chunk-jt0ykktx.js} +1 -1
  83. package/bin/{chunk-sd6w0z6a.js → chunk-jzgbxqdg.js} +2 -2
  84. package/bin/chunk-kj6h5j5a.js +4 -0
  85. package/bin/chunk-km4gn6b6.js +1 -0
  86. package/bin/chunk-knj2s8mg.js +16 -0
  87. package/bin/{chunk-1eqw2dpx.js → chunk-kvhf12b4.js} +2 -2
  88. package/bin/chunk-m0q2cgfg.js +2 -0
  89. package/bin/chunk-m82tkhaa.js +11 -0
  90. package/bin/chunk-m9adtgzk.js +2 -0
  91. package/bin/{chunk-0tvnfy4k.js → chunk-mcj1xpcc.js} +2 -2
  92. package/bin/chunk-mcw198kg.js +13 -0
  93. package/bin/{chunk-9s0k533c.js → chunk-mwktrwtx.js} +1 -1
  94. package/bin/{chunk-wsprap60.js → chunk-mzsw9var.js} +2 -2
  95. package/bin/chunk-ns33grgx.js +2 -0
  96. package/bin/{chunk-xsfy8hz3.js → chunk-ny1kbmxt.js} +2 -2
  97. package/bin/{chunk-16n160h1.js → chunk-p3f5aevs.js} +1 -1
  98. package/bin/chunk-p3j6ydk1.js +1 -0
  99. package/bin/chunk-p4s95471.js +2 -0
  100. package/bin/chunk-pk406dgy.js +2 -0
  101. package/bin/chunk-q2bew2vc.js +2 -0
  102. package/bin/chunk-q5vkxee3.js +5 -0
  103. package/bin/{chunk-hzv1mhr5.js → chunk-q83h0hkx.js} +2 -2
  104. package/bin/{chunk-fre31bhw.js → chunk-q8w4mbw4.js} +2 -2
  105. package/bin/{chunk-b7qs7hxg.js → chunk-qwpkcp8d.js} +2 -2
  106. package/bin/chunk-r1xer8gn.js +5 -0
  107. package/bin/chunk-s1e4qy3q.js +14 -0
  108. package/bin/{chunk-b9d8xdhb.js → chunk-s9ksftq2.js} +1 -1
  109. package/bin/chunk-srxp5jav.js +42 -0
  110. package/bin/chunk-swtwaaqe.js +1 -0
  111. package/bin/chunk-tagdrg7p.js +1 -0
  112. package/bin/{chunk-d18v5vmp.js → chunk-tekwpkjf.js} +2 -2
  113. package/bin/chunk-twtxnzbv.js +2 -0
  114. package/bin/{chunk-c6f8x05m.js → chunk-v05rrxp5.js} +2 -2
  115. package/bin/{chunk-ht5rht98.js → chunk-v5cn90cf.js} +2 -2
  116. package/bin/chunk-v5mcjwxy.js +2 -0
  117. package/bin/{chunk-jb8vbeb0.js → chunk-vcrmjtcz.js} +2 -2
  118. package/bin/chunk-vkzasgxw.js +2 -0
  119. package/bin/chunk-vp3czaeh.js +7 -0
  120. package/bin/chunk-x03jwaga.js +8 -0
  121. package/bin/chunk-x342vzdx.js +2 -0
  122. package/bin/chunk-x8mjh387.js +5 -0
  123. package/bin/chunk-xc54vhfz.js +2 -0
  124. package/bin/chunk-xvkwbczx.js +3 -0
  125. package/bin/chunk-y241cxff.js +1 -0
  126. package/bin/chunk-yk12hydf.js +7 -0
  127. package/bin/chunk-ympbfzz4.js +2 -0
  128. package/bin/{chunk-n412a1hp.js → chunk-yq32evnn.js} +6 -6
  129. package/bin/chunk-z1p13dnc.js +2 -0
  130. package/bin/chunk-zarz3sqn.js +211 -0
  131. package/bin/chunk-zezje74z.js +4 -0
  132. package/bin/chunk-zrszykjf.js +3 -0
  133. package/bin/shumai-app.html +1 -1
  134. package/bin/shumai-app.js +942 -1015
  135. package/package.json +7 -7
  136. package/prisma/migrations/20261026024507_hash_api_tokens/migration.sql +28 -0
  137. package/prisma/migrations/20261026031904_add_audit_log_via/migration.sql +2 -0
  138. package/prisma/migrations/20261029024626_add_oauth_and_jwks/migration.sql +205 -0
  139. package/prisma/migrations/20261029030321_default_empty_arrays_oauth/migration.sql +25 -0
  140. package/prisma/schema.prisma +186 -1
  141. package/bin/chunk-0502p2k7.js +0 -3
  142. package/bin/chunk-0b0t6y8h.js +0 -11
  143. package/bin/chunk-1vt9ss7d.js +0 -2
  144. package/bin/chunk-23780yj6.js +0 -3
  145. package/bin/chunk-2cpsfc87.js +0 -1
  146. package/bin/chunk-2w0d9veg.js +0 -2
  147. package/bin/chunk-2xp9prpq.js +0 -1
  148. package/bin/chunk-3gqs15zq.js +0 -2
  149. package/bin/chunk-3pw7z25v.js +0 -3
  150. package/bin/chunk-3tx9v8kj.js +0 -2
  151. package/bin/chunk-3wdtp4ht.js +0 -1
  152. package/bin/chunk-57axjy7y.js +0 -1
  153. package/bin/chunk-5aqthcm6.js +0 -5
  154. package/bin/chunk-5gq4q1bb.js +0 -2
  155. package/bin/chunk-5r1br11d.js +0 -2
  156. package/bin/chunk-61hrdg0g.js +0 -1
  157. package/bin/chunk-6aa4xmnw.js +0 -2
  158. package/bin/chunk-6mrgtn78.js +0 -18
  159. package/bin/chunk-6s55r0z9.js +0 -1
  160. package/bin/chunk-6vkfzzvt.js +0 -5
  161. package/bin/chunk-7dprpnm6.js +0 -2
  162. package/bin/chunk-7rycq6wb.js +0 -129
  163. package/bin/chunk-895gzdtp.js +0 -7
  164. package/bin/chunk-8d1p8qpv.js +0 -1
  165. package/bin/chunk-8r3k84dh.js +0 -2
  166. package/bin/chunk-99sarrvt.js +0 -3
  167. package/bin/chunk-b21z62fj.js +0 -1
  168. package/bin/chunk-bv589v2m.js +0 -3
  169. package/bin/chunk-c8kjpmfe.js +0 -2
  170. package/bin/chunk-c9xyejnk.js +0 -2
  171. package/bin/chunk-cb9peqy5.js +0 -2
  172. package/bin/chunk-ckczqmrz.js +0 -5
  173. package/bin/chunk-cr33cs6j.js +0 -2
  174. package/bin/chunk-cxet91kt.js +0 -2
  175. package/bin/chunk-d7e351jd.js +0 -6
  176. package/bin/chunk-ebcfbn00.js +0 -2
  177. package/bin/chunk-f0b4a9y3.js +0 -2
  178. package/bin/chunk-fkn6f4qt.js +0 -4
  179. package/bin/chunk-g78vapcm.js +0 -2
  180. package/bin/chunk-gdpfwxea.js +0 -4
  181. package/bin/chunk-gwqqq0b1.js +0 -32
  182. package/bin/chunk-h3cwf9aw.js +0 -2
  183. package/bin/chunk-h4ty530v.js +0 -16
  184. package/bin/chunk-h58yfx7w.js +0 -2
  185. package/bin/chunk-h9ngpxyd.js +0 -1
  186. package/bin/chunk-hbr17jvr.js +0 -13
  187. package/bin/chunk-hc0xbmtt.js +0 -5
  188. package/bin/chunk-j9t7tvt5.js +0 -2
  189. package/bin/chunk-jvt8q0eg.js +0 -2
  190. package/bin/chunk-jzgtthsj.js +0 -3
  191. package/bin/chunk-jzjhg7ng.js +0 -1
  192. package/bin/chunk-k547syp2.js +0 -2
  193. package/bin/chunk-k7sjpke6.js +0 -2
  194. package/bin/chunk-k8ct1qgv.js +0 -3
  195. package/bin/chunk-k9q4nn8b.js +0 -11
  196. package/bin/chunk-keetdtxb.js +0 -2
  197. package/bin/chunk-kjjw8mbg.js +0 -1
  198. package/bin/chunk-mey80kv9.js +0 -54
  199. package/bin/chunk-nfncawpm.js +0 -12
  200. package/bin/chunk-nvwt8atc.js +0 -1
  201. package/bin/chunk-p1d500sf.js +0 -211
  202. package/bin/chunk-q0vs124k.js +0 -2
  203. package/bin/chunk-q5795f3s.js +0 -2
  204. package/bin/chunk-q5j3b0h5.js +0 -3
  205. package/bin/chunk-qd7pvaxb.js +0 -2
  206. package/bin/chunk-qhpt7170.js +0 -2
  207. package/bin/chunk-qt78vs3g.js +0 -2
  208. package/bin/chunk-ra6mdjr0.js +0 -1
  209. package/bin/chunk-ryfvaz6v.js +0 -3
  210. package/bin/chunk-s22eapcc.js +0 -2
  211. package/bin/chunk-sbg86tch.js +0 -2
  212. package/bin/chunk-sbqy6m8t.js +0 -1
  213. package/bin/chunk-sdp9w627.js +0 -14
  214. package/bin/chunk-sn0nypvd.js +0 -42
  215. package/bin/chunk-sv92vkyh.js +0 -2
  216. package/bin/chunk-t6cn018t.js +0 -3
  217. package/bin/chunk-ts4d1mxf.js +0 -2
  218. package/bin/chunk-wkdkc12e.js +0 -4
  219. package/bin/chunk-xgnvktq6.js +0 -10
  220. package/bin/chunk-xjw3mpvx.js +0 -1
  221. package/bin/chunk-xznq2axj.js +0 -1
  222. package/bin/chunk-y4v08wq7.js +0 -1
  223. package/bin/chunk-yncvy335.js +0 -3
  224. package/bin/chunk-ytzddcj2.js +0 -1
  225. package/bin/chunk-zxqasmvz.js +0 -2
@@ -1,7 +1,7 @@
1
1
  // @bun
2
- function b(e,t,r,s,n){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!n)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r}function i(e,t,r,s){if(r==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(e):s?s.value:t.get(e)}var Hr=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Hr=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(s)=>(+s^r()&15>>+s/4).toString(16))};function dt(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var pt=(e)=>{if(e instanceof Error)return e;if(typeof e==="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=Error(e.message,e.cause?{cause:e.cause}:{});if(e.stack)t.stack=e.stack;if(e.cause&&!t.cause)t.cause=e.cause;if(e.name)t.name=e.name;return t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class m extends Error{}class O extends m{constructor(e,t,r,s){super(`${O.makeMessage(e,t,r)}`);this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let n=t;this.code=n?.code,this.param=n?.param,this.type=n?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message==="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;if(e&&s)return`${e} ${s}`;if(e)return`${e} status code (no body)`;if(s)return s;return"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new xe({message:r,cause:pt(t)});let n=t?.error;if(e===400)return new mt(e,n,r,s);if(e===401)return new _t(e,n,r,s);if(e===403)return new gt(e,n,r,s);if(e===404)return new yt(e,n,r,s);if(e===409)return new bt(e,n,r,s);if(e===422)return new wt(e,n,r,s);if(e===429)return new xt(e,n,r,s);if(e>=500)return new At(e,n,r,s);return new O(e,n,r,s)}}class F extends O{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class xe extends O{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class Ae extends xe{constructor({message:e}={}){super({message:e??"Request timed out."})}}class mt extends O{}class _t extends O{}class gt extends O{}class yt extends O{}class bt extends O{}class wt extends O{}class xt extends O{}class At extends O{}class It extends m{constructor(){super("Could not parse response content as the length limit was reached")}}class Pt extends m{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class se extends Error{constructor(e){super(e)}}var jn=/^[a-z][a-z0-9+.-]*:/i,Cs=(e)=>jn.test(e),U=(e)=>(U=Array.isArray,U(e)),Jr=U;function Xr(e){if(typeof e!=="object")return{};return e??{}}function Es(e){if(!e)return!0;for(let t in e)return!1;return!0}function vs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Be(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}var $s=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new m(`${e} must be an integer`);if(t<0)throw new m(`${e} must be a positive integer`);return t};var ks=(e)=>{try{return JSON.parse(e)}catch(t){return}};var z=(e)=>new Promise((t)=>setTimeout(t,e));var fe="6.26.0";var Ns=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Dn(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var Wn=()=>{let e=Dn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":Ts(Deno.build.os),"X-Stainless-Arch":Os(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":Ts(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Os(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=qn();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function qn(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:r}of e){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,a=s[3]||0;return{browser:t,version:`${n}.${o}.${a}`}}}return null}var Os=(e)=>{if(e==="x32")return"x32";if(e==="x86_64"||e==="x64")return"x64";if(e==="arm")return"arm";if(e==="aarch64"||e==="arm64")return"arm64";if(e)return`other:${e}`;return"unknown"},Ts=(e)=>{if(e=e.toLowerCase(),e.includes("ios"))return"iOS";if(e==="android")return"Android";if(e==="darwin")return"MacOS";if(e==="win32")return"Windows";if(e==="freebsd")return"FreeBSD";if(e==="openbsd")return"OpenBSD";if(e==="linux")return"Linux";if(e)return`Other:${e}`;return"Unknown"},Fs,Ms=()=>Fs??(Fs=Wn());function Ls(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Vr(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function pr(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Vr({start(){},async pull(r){let{done:s,value:n}=await t.next();if(s)r.close();else r.enqueue(n)},async cancel(){await t.return?.()}})}function Kr(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();if(r?.done)t.releaseLock();return r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Bs(e){if(e===null||typeof e!=="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var Us=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var Gr="RFC3986",zr=(e)=>String(e),Qr={RFC1738:(e)=>String(e).replace(/%20/g,"+"),RFC3986:zr},js="RFC1738";var mr=(e,t)=>(mr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),mr(e,t)),Q=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var Yr=1024,Ds=(e,t,r,s,n)=>{if(e.length===0)return e;let o=e;if(typeof e==="symbol")o=Symbol.prototype.toString.call(e);else if(typeof e!=="string")o=String(e);if(r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(f){return"%26%23"+parseInt(f.slice(2),16)+"%3B"});let a="";for(let f=0;f<o.length;f+=Yr){let d=o.length>=Yr?o.slice(f,f+Yr):o,_=[];for(let y=0;y<d.length;++y){let p=d.charCodeAt(y);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===js&&(p===40||p===41)){_[_.length]=d.charAt(y);continue}if(p<128){_[_.length]=Q[p];continue}if(p<2048){_[_.length]=Q[192|p>>6]+Q[128|p&63];continue}if(p<55296||p>=57344){_[_.length]=Q[224|p>>12]+Q[128|p>>6&63]+Q[128|p&63];continue}y+=1,p=65536+((p&1023)<<10|d.charCodeAt(y)&1023),_[_.length]=Q[240|p>>18]+Q[128|p>>12&63]+Q[128|p>>6&63]+Q[128|p&63]}a+=_.join("")}return a};function Ws(e){if(!e||typeof e!=="object")return!1;return!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Zr(e,t){if(U(e)){let r=[];for(let s=0;s<e.length;s+=1)r.push(t(e[s]));return r}return t(e)}var Hs={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Js=function(e,t){Array.prototype.push.apply(e,U(t)?t:[t])},qs,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ds,encodeValuesOnly:!1,format:Gr,formatter:zr,indices:!1,serializeDate(e){return(qs??(qs=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Xn(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="symbol"||typeof e==="bigint"}var es={};function Xs(e,t,r,s,n,o,a,f,d,_,y,p,u,w,g,R,S,I){let A=e,k=I,E=0,W=!1;while((k=k.get(es))!==void 0&&!W){let P=k.get(e);if(E+=1,typeof P<"u")if(P===E)throw RangeError("Cyclic object value");else W=!0;if(typeof k.get(es)>"u")E=0}if(typeof _==="function")A=_(t,A);else if(A instanceof Date)A=u?.(A);else if(r==="comma"&&U(A))A=Zr(A,function(P){if(P instanceof Date)return u?.(P);return P});if(A===null){if(o)return d&&!R?d(t,N.encoder,S,"key",w):t;A=""}if(Xn(A)||Ws(A)){if(d){let P=R?t:d(t,N.encoder,S,"key",w);return[g?.(P)+"="+g?.(d(A,N.encoder,S,"value",w))]}return[g?.(t)+"="+g?.(String(A))]}let T=[];if(typeof A>"u")return T;let C;if(r==="comma"&&U(A)){if(R&&d)A=Zr(A,d);C=[{value:A.length>0?A.join(",")||null:void 0}]}else if(U(_))C=_;else{let P=Object.keys(A);C=y?P.sort(y):P}let j=f?String(t).replace(/\./g,"%2E"):String(t),re=s&&U(A)&&A.length===1?j+"[]":j;if(n&&U(A)&&A.length===0)return re+"[]";for(let P=0;P<C.length;++P){let ue=C[P],Ss=typeof ue==="object"&&typeof ue.value<"u"?ue.value:A[ue];if(a&&Ss===null)continue;let qr=p&&f?ue.replace(/\./g,"%2E"):ue,Bn=U(A)?typeof r==="function"?r(re,qr):re:re+(p?"."+qr:"["+qr+"]");I.set(e,E);let Rs=new WeakMap;Rs.set(es,I),Js(T,Xs(Ss,Bn,r,s,n,o,a,f,r==="comma"&&R&&U(A)?null:d,_,y,p,u,w,g,R,S,Rs))}return T}function Vn(e=N){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!=="function")throw TypeError("Encoder has to be a function.");let t=e.charset||N.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Gr;if(typeof e.format<"u"){if(!mr(Qr,e.format))throw TypeError("Unknown format option provided.");r=e.format}let s=Qr[r],n=N.filter;if(typeof e.filter==="function"||U(e.filter))n=e.filter;let o;if(e.arrayFormat&&e.arrayFormat in Hs)o=e.arrayFormat;else if("indices"in e)o=e.indices?"indices":"repeat";else o=N.arrayFormat;if("commaRoundTrip"in e&&typeof e.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof e.allowDots>"u"?!!e.encodeDotInKeys===!0?!0:N.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==="boolean"?e.addQueryPrefix:N.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof e.allowEmptyArrays==="boolean"?!!e.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel==="boolean"?e.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?N.delimiter:e.delimiter,encode:typeof e.encode==="boolean"?e.encode:N.encode,encodeDotInKeys:typeof e.encodeDotInKeys==="boolean"?e.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof e.encoder==="function"?e.encoder:N.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==="boolean"?e.encodeValuesOnly:N.encodeValuesOnly,filter:n,format:r,formatter:s,serializeDate:typeof e.serializeDate==="function"?e.serializeDate:N.serializeDate,skipNulls:typeof e.skipNulls==="boolean"?e.skipNulls:N.skipNulls,sort:typeof e.sort==="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling==="boolean"?e.strictNullHandling:N.strictNullHandling}}function Vs(e,t={}){let r=e,s=Vn(t),n,o;if(typeof s.filter==="function")o=s.filter,r=o("",r);else if(U(s.filter))o=s.filter,n=o;let a=[];if(typeof r!=="object"||r===null)return"";let f=Hs[s.arrayFormat],d=f==="comma"&&s.commaRoundTrip;if(!n)n=Object.keys(r);if(s.sort)n.sort(s.sort);let _=new WeakMap;for(let u=0;u<n.length;++u){let w=n[u];if(s.skipNulls&&r[w]===null)continue;Js(a,Xs(r[w],w,f,d,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,_))}let y=a.join(s.delimiter),p=s.addQueryPrefix===!0?"?":"";if(s.charsetSentinel)if(s.charset==="iso-8859-1")p+="utf8=%26%2310003%3B&";else p+="utf8=%E2%9C%93&";return y.length>0?p+y:""}function Ks(e){return Vs(e,{arrayFormat:"brackets"})}function Qs(e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t),s=0;for(let n of e)r.set(n,s),s+=n.length;return r}var Gs;function Ue(e){let t;return(Gs??(t=new globalThis.TextEncoder,Gs=t.encode.bind(t)))(e)}var zs;function ts(e){let t;return(zs??(t=new globalThis.TextDecoder,zs=t.decode.bind(t)))(e)}var q,H;class je{constructor(){q.set(this,void 0),H.set(this,void 0),b(this,q,new Uint8Array,"f"),b(this,H,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?Ue(e):e;b(this,q,Qs([i(this,q,"f"),t]),"f");let r=[],s;while((s=Gn(i(this,q,"f"),i(this,H,"f")))!=null){if(s.carriage&&i(this,H,"f")==null){b(this,H,s.index,"f");continue}if(i(this,H,"f")!=null&&(s.index!==i(this,H,"f")+1||s.carriage)){r.push(ts(i(this,q,"f").subarray(0,i(this,H,"f")-1))),b(this,q,i(this,q,"f").subarray(i(this,H,"f")),"f"),b(this,H,null,"f");continue}let n=i(this,H,"f")!==null?s.preceding-1:s.preceding,o=ts(i(this,q,"f").subarray(0,n));r.push(o),b(this,q,i(this,q,"f").subarray(s.index),"f"),b(this,H,null,"f")}return r}flush(){if(!i(this,q,"f").length)return[];return this.decode(`
2
+ function b(e,t,r,s,n){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!n)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r}function i(e,t,r,s){if(r==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(e):s?s.value:t.get(e)}var Hr=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Hr=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(s)=>(+s^r()&15>>+s/4).toString(16))};function ht(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var dt=(e)=>{if(e instanceof Error)return e;if(typeof e==="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=Error(e.message,e.cause?{cause:e.cause}:{});if(e.stack)t.stack=e.stack;if(e.cause&&!t.cause)t.cause=e.cause;if(e.name)t.name=e.name;return t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class m extends Error{}class O extends m{constructor(e,t,r,s){super(`${O.makeMessage(e,t,r)}`);this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let n=t;this.code=n?.code,this.param=n?.param,this.type=n?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message==="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;if(e&&s)return`${e} ${s}`;if(e)return`${e} status code (no body)`;if(s)return s;return"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new xe({message:r,cause:dt(t)});let n=t?.error;if(e===400)return new pt(e,n,r,s);if(e===401)return new mt(e,n,r,s);if(e===403)return new _t(e,n,r,s);if(e===404)return new gt(e,n,r,s);if(e===409)return new yt(e,n,r,s);if(e===422)return new bt(e,n,r,s);if(e===429)return new wt(e,n,r,s);if(e>=500)return new xt(e,n,r,s);return new O(e,n,r,s)}}class F extends O{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class xe extends O{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class Ae extends xe{constructor({message:e}={}){super({message:e??"Request timed out."})}}class pt extends O{}class mt extends O{}class _t extends O{}class gt extends O{}class yt extends O{}class bt extends O{}class wt extends O{}class xt extends O{}class It extends m{constructor(){super("Could not parse response content as the length limit was reached")}}class Pt extends m{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class se extends Error{constructor(e){super(e)}}var jn=/^[a-z][a-z0-9+.-]*:/i,Cs=(e)=>jn.test(e),U=(e)=>(U=Array.isArray,U(e)),Jr=U;function Xr(e){if(typeof e!=="object")return{};return e??{}}function Es(e){if(!e)return!0;for(let t in e)return!1;return!0}function vs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Be(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}var $s=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new m(`${e} must be an integer`);if(t<0)throw new m(`${e} must be a positive integer`);return t};var ks=(e)=>{try{return JSON.parse(e)}catch(t){return}};var z=(e)=>new Promise((t)=>setTimeout(t,e));var fe="6.26.0";var Ns=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Dn(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var Wn=()=>{let e=Dn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":Ts(Deno.build.os),"X-Stainless-Arch":Os(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":Ts(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Os(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=qn();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":fe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function qn(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:r}of e){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,a=s[3]||0;return{browser:t,version:`${n}.${o}.${a}`}}}return null}var Os=(e)=>{if(e==="x32")return"x32";if(e==="x86_64"||e==="x64")return"x64";if(e==="arm")return"arm";if(e==="aarch64"||e==="arm64")return"arm64";if(e)return`other:${e}`;return"unknown"},Ts=(e)=>{if(e=e.toLowerCase(),e.includes("ios"))return"iOS";if(e==="android")return"Android";if(e==="darwin")return"MacOS";if(e==="win32")return"Windows";if(e==="freebsd")return"FreeBSD";if(e==="openbsd")return"OpenBSD";if(e==="linux")return"Linux";if(e)return`Other:${e}`;return"Unknown"},Fs,Ms=()=>Fs??(Fs=Wn());function Ls(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Vr(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function pr(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Vr({start(){},async pull(r){let{done:s,value:n}=await t.next();if(s)r.close();else r.enqueue(n)},async cancel(){await t.return?.()}})}function Kr(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();if(r?.done)t.releaseLock();return r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Bs(e){if(e===null||typeof e!=="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var Us=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var Gr="RFC3986",zr=(e)=>String(e),Qr={RFC1738:(e)=>String(e).replace(/%20/g,"+"),RFC3986:zr},js="RFC1738";var mr=(e,t)=>(mr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),mr(e,t)),Q=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var Yr=1024,Ds=(e,t,r,s,n)=>{if(e.length===0)return e;let o=e;if(typeof e==="symbol")o=Symbol.prototype.toString.call(e);else if(typeof e!=="string")o=String(e);if(r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(f){return"%26%23"+parseInt(f.slice(2),16)+"%3B"});let a="";for(let f=0;f<o.length;f+=Yr){let d=o.length>=Yr?o.slice(f,f+Yr):o,_=[];for(let y=0;y<d.length;++y){let p=d.charCodeAt(y);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===js&&(p===40||p===41)){_[_.length]=d.charAt(y);continue}if(p<128){_[_.length]=Q[p];continue}if(p<2048){_[_.length]=Q[192|p>>6]+Q[128|p&63];continue}if(p<55296||p>=57344){_[_.length]=Q[224|p>>12]+Q[128|p>>6&63]+Q[128|p&63];continue}y+=1,p=65536+((p&1023)<<10|d.charCodeAt(y)&1023),_[_.length]=Q[240|p>>18]+Q[128|p>>12&63]+Q[128|p>>6&63]+Q[128|p&63]}a+=_.join("")}return a};function Ws(e){if(!e||typeof e!=="object")return!1;return!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Zr(e,t){if(U(e)){let r=[];for(let s=0;s<e.length;s+=1)r.push(t(e[s]));return r}return t(e)}var Hs={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Js=function(e,t){Array.prototype.push.apply(e,U(t)?t:[t])},qs,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ds,encodeValuesOnly:!1,format:Gr,formatter:zr,indices:!1,serializeDate(e){return(qs??(qs=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Xn(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="symbol"||typeof e==="bigint"}var es={};function Xs(e,t,r,s,n,o,a,f,d,_,y,p,u,w,g,R,S,I){let A=e,k=I,E=0,W=!1;while((k=k.get(es))!==void 0&&!W){let P=k.get(e);if(E+=1,typeof P<"u")if(P===E)throw RangeError("Cyclic object value");else W=!0;if(typeof k.get(es)>"u")E=0}if(typeof _==="function")A=_(t,A);else if(A instanceof Date)A=u?.(A);else if(r==="comma"&&U(A))A=Zr(A,function(P){if(P instanceof Date)return u?.(P);return P});if(A===null){if(o)return d&&!R?d(t,N.encoder,S,"key",w):t;A=""}if(Xn(A)||Ws(A)){if(d){let P=R?t:d(t,N.encoder,S,"key",w);return[g?.(P)+"="+g?.(d(A,N.encoder,S,"value",w))]}return[g?.(t)+"="+g?.(String(A))]}let T=[];if(typeof A>"u")return T;let C;if(r==="comma"&&U(A)){if(R&&d)A=Zr(A,d);C=[{value:A.length>0?A.join(",")||null:void 0}]}else if(U(_))C=_;else{let P=Object.keys(A);C=y?P.sort(y):P}let j=f?String(t).replace(/\./g,"%2E"):String(t),re=s&&U(A)&&A.length===1?j+"[]":j;if(n&&U(A)&&A.length===0)return re+"[]";for(let P=0;P<C.length;++P){let ue=C[P],Ss=typeof ue==="object"&&typeof ue.value<"u"?ue.value:A[ue];if(a&&Ss===null)continue;let qr=p&&f?ue.replace(/\./g,"%2E"):ue,Bn=U(A)?typeof r==="function"?r(re,qr):re:re+(p?"."+qr:"["+qr+"]");I.set(e,E);let Rs=new WeakMap;Rs.set(es,I),Js(T,Xs(Ss,Bn,r,s,n,o,a,f,r==="comma"&&R&&U(A)?null:d,_,y,p,u,w,g,R,S,Rs))}return T}function Vn(e=N){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!=="function")throw TypeError("Encoder has to be a function.");let t=e.charset||N.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Gr;if(typeof e.format<"u"){if(!mr(Qr,e.format))throw TypeError("Unknown format option provided.");r=e.format}let s=Qr[r],n=N.filter;if(typeof e.filter==="function"||U(e.filter))n=e.filter;let o;if(e.arrayFormat&&e.arrayFormat in Hs)o=e.arrayFormat;else if("indices"in e)o=e.indices?"indices":"repeat";else o=N.arrayFormat;if("commaRoundTrip"in e&&typeof e.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof e.allowDots>"u"?!!e.encodeDotInKeys===!0?!0:N.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==="boolean"?e.addQueryPrefix:N.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof e.allowEmptyArrays==="boolean"?!!e.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel==="boolean"?e.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?N.delimiter:e.delimiter,encode:typeof e.encode==="boolean"?e.encode:N.encode,encodeDotInKeys:typeof e.encodeDotInKeys==="boolean"?e.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof e.encoder==="function"?e.encoder:N.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==="boolean"?e.encodeValuesOnly:N.encodeValuesOnly,filter:n,format:r,formatter:s,serializeDate:typeof e.serializeDate==="function"?e.serializeDate:N.serializeDate,skipNulls:typeof e.skipNulls==="boolean"?e.skipNulls:N.skipNulls,sort:typeof e.sort==="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling==="boolean"?e.strictNullHandling:N.strictNullHandling}}function Vs(e,t={}){let r=e,s=Vn(t),n,o;if(typeof s.filter==="function")o=s.filter,r=o("",r);else if(U(s.filter))o=s.filter,n=o;let a=[];if(typeof r!=="object"||r===null)return"";let f=Hs[s.arrayFormat],d=f==="comma"&&s.commaRoundTrip;if(!n)n=Object.keys(r);if(s.sort)n.sort(s.sort);let _=new WeakMap;for(let u=0;u<n.length;++u){let w=n[u];if(s.skipNulls&&r[w]===null)continue;Js(a,Xs(r[w],w,f,d,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,_))}let y=a.join(s.delimiter),p=s.addQueryPrefix===!0?"?":"";if(s.charsetSentinel)if(s.charset==="iso-8859-1")p+="utf8=%26%2310003%3B&";else p+="utf8=%E2%9C%93&";return y.length>0?p+y:""}function Ks(e){return Vs(e,{arrayFormat:"brackets"})}function Qs(e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t),s=0;for(let n of e)r.set(n,s),s+=n.length;return r}var Gs;function Ue(e){let t;return(Gs??(t=new globalThis.TextEncoder,Gs=t.encode.bind(t)))(e)}var zs;function ts(e){let t;return(zs??(t=new globalThis.TextDecoder,zs=t.decode.bind(t)))(e)}var q,H;class je{constructor(){q.set(this,void 0),H.set(this,void 0),b(this,q,new Uint8Array,"f"),b(this,H,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?Ue(e):e;b(this,q,Qs([i(this,q,"f"),t]),"f");let r=[],s;while((s=Gn(i(this,q,"f"),i(this,H,"f")))!=null){if(s.carriage&&i(this,H,"f")==null){b(this,H,s.index,"f");continue}if(i(this,H,"f")!=null&&(s.index!==i(this,H,"f")+1||s.carriage)){r.push(ts(i(this,q,"f").subarray(0,i(this,H,"f")-1))),b(this,q,i(this,q,"f").subarray(i(this,H,"f")),"f"),b(this,H,null,"f");continue}let n=i(this,H,"f")!==null?s.preceding-1:s.preceding,o=ts(i(this,q,"f").subarray(0,n));r.push(o),b(this,q,i(this,q,"f").subarray(s.index),"f"),b(this,H,null,"f")}return r}flush(){if(!i(this,q,"f").length)return[];return this.decode(`
3
3
  `)}}q=new WeakMap,H=new WeakMap;je.NEWLINE_CHARS=new Set([`
4
- `,"\r"]);je.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Gn(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ys(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10)return s+2;if(e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}var gr={off:0,error:200,warn:300,info:400,debug:500},rs=(e,t,r)=>{if(!e)return;if(vs(gr,e))return e;v(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(gr))}`);return};function St(){}function _r(e,t,r){if(!t||gr[e]>gr[r])return St;else return t[e].bind(t)}var zn={error:St,warn:St,info:St,debug:St},Zs=new WeakMap;function v(e){let t=e.logger,r=e.logLevel??"off";if(!t)return zn;let s=Zs.get(t);if(s&&s[0]===r)return s[1];let n={error:_r("error",t,r),warn:_r("warn",t,r),info:_r("info",t,r),debug:_r("debug",t,r)};return Zs.set(t,[r,n]),n}var ne=(e)=>{if(e.options)e.options={...e.options},delete e.options.headers;if(e.headers)e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]));if("retryOfRequestLogID"in e){if(e.retryOfRequestLogID)e.retryOf=e.retryOfRequestLogID;delete e.retryOfRequestLogID}return e};var Rt;class J{constructor(e,t,r){this.iterator=e,Rt.set(this,void 0),this.controller=t,b(this,Rt,r,"f")}static fromSSEResponse(e,t,r,s){let n=!1,o=r?v(r):console;async function*a(){if(n)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let f=!1;try{for await(let d of Qn(e,t)){if(f)continue;if(d.data.startsWith("[DONE]")){f=!0;continue}if(d.event===null||!d.event.startsWith("thread.")){let _;try{_=JSON.parse(d.data)}catch(y){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),y}if(_&&_.error)throw new O(void 0,_.error,void 0,e.headers);yield s?{event:d.event,data:_}:_}else{let _;try{_=JSON.parse(d.data)}catch(y){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),y}if(d.event=="error")throw new O(void 0,_.error,_.message,void 0);yield{event:d.event,data:_}}}f=!0}catch(d){if(dt(d))return;throw d}finally{if(!f)t.abort()}}return new J(a,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let a=new je,f=Kr(e);for await(let d of f)for(let _ of a.decode(d))yield _;for(let d of a.flush())yield d}async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let f of n()){if(a)continue;if(f)yield JSON.parse(f)}a=!0}catch(f){if(dt(f))return;throw f}finally{if(!a)t.abort()}}return new J(o,t,r)}[(Rt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=(n)=>({next:()=>{if(n.length===0){let o=r.next();e.push(o),t.push(o)}return n.shift()}});return[new J(()=>s(e),this.controller,i(this,Rt,"f")),new J(()=>s(t),this.controller,i(this,Rt,"f"))]}toReadableStream(){let e=this,t;return Vr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:n}=await t.next();if(n)return r.close();let o=Ue(JSON.stringify(s)+`
4
+ `,"\r"]);je.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Gn(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ys(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10)return s+2;if(e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}var gr={off:0,error:200,warn:300,info:400,debug:500},rs=(e,t,r)=>{if(!e)return;if(vs(gr,e))return e;v(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(gr))}`);return};function St(){}function _r(e,t,r){if(!t||gr[e]>gr[r])return St;else return t[e].bind(t)}var zn={error:St,warn:St,info:St,debug:St},Zs=new WeakMap;function v(e){let t=e.logger,r=e.logLevel??"off";if(!t)return zn;let s=Zs.get(t);if(s&&s[0]===r)return s[1];let n={error:_r("error",t,r),warn:_r("warn",t,r),info:_r("info",t,r),debug:_r("debug",t,r)};return Zs.set(t,[r,n]),n}var ne=(e)=>{if(e.options)e.options={...e.options},delete e.options.headers;if(e.headers)e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]));if("retryOfRequestLogID"in e){if(e.retryOfRequestLogID)e.retryOf=e.retryOfRequestLogID;delete e.retryOfRequestLogID}return e};var Rt;class J{constructor(e,t,r){this.iterator=e,Rt.set(this,void 0),this.controller=t,b(this,Rt,r,"f")}static fromSSEResponse(e,t,r,s){let n=!1,o=r?v(r):console;async function*a(){if(n)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let f=!1;try{for await(let d of Qn(e,t)){if(f)continue;if(d.data.startsWith("[DONE]")){f=!0;continue}if(d.event===null||!d.event.startsWith("thread.")){let _;try{_=JSON.parse(d.data)}catch(y){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),y}if(_&&_.error)throw new O(void 0,_.error,void 0,e.headers);yield s?{event:d.event,data:_}:_}else{let _;try{_=JSON.parse(d.data)}catch(y){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),y}if(d.event=="error")throw new O(void 0,_.error,_.message,void 0);yield{event:d.event,data:_}}}f=!0}catch(d){if(ht(d))return;throw d}finally{if(!f)t.abort()}}return new J(a,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let a=new je,f=Kr(e);for await(let d of f)for(let _ of a.decode(d))yield _;for(let d of a.flush())yield d}async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let f of n()){if(a)continue;if(f)yield JSON.parse(f)}a=!0}catch(f){if(ht(f))return;throw f}finally{if(!a)t.abort()}}return new J(o,t,r)}[(Rt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=(n)=>({next:()=>{if(n.length===0){let o=r.next();e.push(o),t.push(o)}return n.shift()}});return[new J(()=>s(e),this.controller,i(this,Rt,"f")),new J(()=>s(t),this.controller,i(this,Rt,"f"))]}toReadableStream(){let e=this,t;return Vr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:n}=await t.next();if(n)return r.close();let o=Ue(JSON.stringify(s)+`
5
5
  `);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Qn(e,t){if(!e.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new m("Attempted to iterate over a response with no body")}let r=new en,s=new je,n=Kr(e.body);for await(let o of Yn(n))for(let a of s.decode(o)){let f=r.decode(a);if(f)yield f}for(let o of s.flush()){let a=r.decode(o);if(a)yield a}}async function*Yn(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r==="string"?Ue(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=Ys(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class en{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r"))e=e.substring(0,e.length-1);if(!e){if(!this.event&&!this.data.length)return null;let n={event:this.event,data:this.data.join(`
6
6
  `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=Zn(e,":");if(s.startsWith(" "))s=s.substring(1);if(t==="event")this.event=s;else if(t==="data")this.data.push(s);return null}}function Zn(e,t){let r=e.indexOf(t);if(r!==-1)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}async function yr(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,a=await(async()=>{if(t.options.stream){if(v(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)return t.options.__streamClass.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData);return J.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData)}if(r.status===204)return null;if(t.options.__binaryResponse)return r;let d=r.headers.get("content-type")?.split(";")[0]?.trim();if(d?.includes("application/json")||d?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let u=await r.json();return ss(u,r)}return await r.text()})();return v(e).debug(`[${s}] response parsed`,ne({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}function ss(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return e;return Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Ct;class Ie extends Promise{constructor(e,t,r=yr){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,Ct.set(this,void 0),b(this,Ct,e,"f")}_thenUnwrap(e){return new Ie(i(this,Ct,"f"),this.responsePromise,async(t,r)=>ss(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then((e)=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((e)=>this.parseResponse(i(this,Ct,"f"),e));return this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Ct=new WeakMap;var br;class wr{constructor(e,t,r,s){br.set(this,void 0),b(this,br,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await i(this,br,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(br=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class xr extends Ie{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await yr(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class oe extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class x extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;if(!t)return null;return{...this.options,query:{...Xr(this.options.query),after:t}}}}class Y extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;if(!e)return null;return{...this.options,query:{...Xr(this.options.query),after:e}}}}var is=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node==="string"&&parseInt(e.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function De(e,t,r){return is(),new File(e,t??"unknown_file",r)}function Et(e){return(typeof e==="object"&&e!==null&&(("name"in e)&&e.name&&String(e.name)||("url"in e)&&e.url&&String(e.url)||("filename"in e)&&e.filename&&String(e.filename)||("path"in e)&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var Ar=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function",ie=async(e,t)=>{if(!ns(e.body))return e;return{...e,body:await rn(e.body,t)}},V=async(e,t)=>({...e,body:await rn(e.body,t)}),tn=new WeakMap;function to(e){let t=typeof e==="function"?e:e.fetch,r=tn.get(t);if(r)return r;let s=(async()=>{try{let n="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;if(o.toString()===await new n(o).text())return!1;return!0}catch{return!0}})();return tn.set(t,s),s}var rn=async(e,t)=>{if(!await to(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([s,n])=>os(r,s,n))),r},sn=(e)=>e instanceof Blob&&("name"in e),ro=(e)=>typeof e==="object"&&e!==null&&(e instanceof Response||Ar(e)||sn(e)),ns=(e)=>{if(ro(e))return!0;if(Array.isArray(e))return e.some(ns);if(e&&typeof e==="object"){for(let t in e)if(ns(e[t]))return!0}return!1},os=async(e,t,r)=>{if(r===void 0)return;if(r==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r==="string"||typeof r==="number"||typeof r==="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,De([await r.blob()],Et(r)));else if(Ar(r))e.append(t,De([await new Response(pr(r)).blob()],Et(r)));else if(sn(r))e.append(t,r,Et(r));else if(Array.isArray(r))await Promise.all(r.map((s)=>os(e,t+"[]",s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([s,n])=>os(e,`${t}[${s}]`,n)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)};var nn=(e)=>e!=null&&typeof e==="object"&&typeof e.size==="number"&&typeof e.type==="string"&&typeof e.text==="function"&&typeof e.slice==="function"&&typeof e.arrayBuffer==="function",so=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&nn(e),no=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function Ir(e,t,r){if(is(),e=await e,so(e)){if(e instanceof File)return e;return De([await e.arrayBuffer()],e.name)}if(no(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),De(await as(n),t,r)}let s=await as(e);if(t||(t=Et(e)),!r?.type){let n=s.find((o)=>typeof o==="object"&&("type"in o)&&o.type);if(typeof n==="string")r={...r,type:n}}return De(s,t,r)}async function as(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(nn(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ar(e))for await(let r of e)t.push(...await as(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${oo(e)}`)}return t}function oo(e){if(typeof e!=="object"||e===null)return"";return`; props: [${Object.getOwnPropertyNames(e).map((r)=>`"${r}"`).join(", ")}]`}class c{constructor(e){this._client=e}}function an(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var on=Object.freeze(Object.create(null)),ao=(e=an)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],a=r.reduce((y,p,u)=>{if(/[?#]/.test(p))n=!0;let w=s[u],g=(n?encodeURIComponent:e)(""+w);if(u!==s.length&&(w==null||typeof w==="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??on)??on)?.toString))g=w+"",o.push({start:y.length+p.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`});return y+p+(u===s.length?"":g)},""),f=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,_;while((_=d.exec(f))!==null)o.push({start:_.index,length:_[0].length,error:`Value "${_[0]}" can't be safely passed as a path parameter`});if(o.sort((y,p)=>y.start-p.start),o.length>0){let y=0,p=o.reduce((u,w)=>{let g=" ".repeat(w.start-y),R="^".repeat(w.length);return y=w.start+w.length,u+g+R},"");throw new m(`Path parameters result in path with invalid segments:
7
7
  ${o.map((u)=>u.error).join(`
@@ -12,7 +12,7 @@ ${p}`)}return a},l=ao(an);class We extends c{list(e,t={},r){return this._client.
12
12
  ${Or(e)}`);if(T==null)throw new m(`missing choices[${p}].tool_calls[${E}].type
13
13
  ${Or(e)}`);if(P==null)throw new m(`missing choices[${p}].tool_calls[${E}].function.name
14
14
  ${Or(e)}`);if(re==null)throw new m(`missing choices[${p}].tool_calls[${E}].function.arguments
15
- ${Or(e)}`);return{...j,id:C,type:T,function:{...ue,name:P,arguments:re}}})}};return{...w,message:{...I,content:g,role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}),created:n,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return ln(d,t)}function Or(e){return JSON.stringify(e)}function bn(e){return}function wn(e){}class Xe extends de{static fromReadableStream(e){let t=new Xe(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new Xe(t),n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}}class pe extends c{constructor(){super(...arguments);this.messages=new We(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(l`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(l`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,t)}parse(e,t){return fn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((r)=>kt(r,e))}runTools(e,t){if(e.stream)return Xe.runTools(this._client,e,t);return Lt.runTools(this._client,e,t)}stream(e,t){return de.createChatCompletion(this._client,e,t)}}pe.Messages=We;class Re extends c{constructor(){super(...arguments);this.completions=new pe(this._client)}}Re.Completions=pe;var xn=Symbol("brand.privateNullableHeaders");function*yo(e){if(!e)return;if(xn in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(Jr(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=Jr(s[1])?s[1]:[s[1]],a=!1;for(let f of o){if(f===void 0)continue;if(t&&!a)a=!0,yield[n,null];yield[n,f]}}}var h=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,a]of yo(s)){let f=o.toLowerCase();if(!n.has(f))t.delete(o),n.add(f);if(a===null)t.delete(o),r.add(f);else t.append(o,a),r.delete(f)}}return{[xn]:!0,values:t,nulls:r}};class Bt extends c{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Ut extends c{create(e,t){return this._client.post("/audio/transcriptions",V({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class jt extends c{create(e,t){return this._client.post("/audio/translations",V({body:e,...t,__metadata:{model:e.model}},this._client))}}class ce extends c{constructor(){super(...arguments);this.transcriptions=new Ut(this._client),this.translations=new jt(this._client),this.speech=new Bt(this._client)}}ce.Transcriptions=Ut;ce.Translations=jt;ce.Speech=Bt;class Ve extends c{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(l`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,t)}}class Dt extends c{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Wt extends c{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class qt extends c{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ce extends c{constructor(){super(...arguments);this.sessions=new Wt(this._client),this.transcriptionSessions=new qt(this._client)}}Ce.Sessions=Wt;Ce.TranscriptionSessions=qt;class Ht extends c{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}class Jt extends c{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Y,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,Y,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}}class Ee extends c{constructor(){super(...arguments);this.sessions=new Ht(this._client),this.threads=new Jt(this._client)}}Ee.Sessions=Ht;Ee.Threads=Jt;class Xt extends c{create(e,t,r){return this._client.post(l`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/messages/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/messages`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class Vt extends c{retrieve(e,t,r){let{thread_id:s,run_id:n,...o}=t;return this._client.get(l`/threads/${s}/runs/${n}/steps/${e}`,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...n}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}var An=(e)=>{if(typeof Buffer<"u"){let t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),r=t.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=t.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var K=(e)=>{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();return};var B,$e,xs,Z,Tr,G,ke,Ke,ve,Mr,X,Fr,Nr,zt,Kt,Gt,In,Pn,Sn,Rn,Cn,En,vn;class me extends Se{constructor(){super(...arguments);B.add(this),xs.set(this,[]),Z.set(this,{}),Tr.set(this,{}),G.set(this,void 0),ke.set(this,void 0),Ke.set(this,void 0),ve.set(this,void 0),Mr.set(this,void 0),X.set(this,void 0),Fr.set(this,void 0),Nr.set(this,void 0),zt.set(this,void 0)}[(xs=new WeakMap,Z=new WeakMap,Tr=new WeakMap,G=new WeakMap,ke=new WeakMap,Ke=new WeakMap,ve=new WeakMap,Mr=new WeakMap,X=new WeakMap,Fr=new WeakMap,Nr=new WeakMap,zt=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new $e;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}this._connected();let s=J.fromReadableStream(e,this.controller);for await(let n of s)i(this,B,"m",Kt).call(this,n);if(s.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let n=new $e;return n._run(()=>n._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createToolAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}static createThreadAssistantStream(e,t,r){let s=new $e;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let n=new $e;return n._run(()=>n._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}currentEvent(){return i(this,Fr,"f")}currentRun(){return i(this,Nr,"f")}currentMessageSnapshot(){return i(this,G,"f")}currentRunStepSnapshot(){return i(this,zt,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,Z,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,Tr,"f"))}async finalRun(){if(await this.done(),!i(this,ke,"f"))throw Error("Final run was not received.");return i(this,ke,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)i(this,B,"m",Kt).call(this,a);if(o.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}async _createAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let n=e[r];if(n===null||n===void 0){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof n==="string"&&typeof s==="string")n+=s;else if(typeof n==="number"&&typeof s==="number")n+=s;else if(Be(n)&&Be(s))n=this.accumulateDelta(n,s);else if(Array.isArray(n)&&Array.isArray(s)){if(n.every((o)=>typeof o==="string"||typeof o==="number")){n.push(...s);continue}for(let o of s){if(!Be(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),Error("Expected array delta entry to have an `index` property");if(typeof a!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let f=n[a];if(f==null)n.push(o);else n[a]=this.accumulateDelta(f,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${n}`);e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}$e=me,Kt=function(t){if(this.ended)return;switch(b(this,Fr,t,"f"),i(this,B,"m",Sn).call(this,t),t.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":i(this,B,"m",vn).call(this,t);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":i(this,B,"m",Pn).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":i(this,B,"m",In).call(this,t);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:ko(t)}},Gt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!i(this,ke,"f"))throw Error("Final run has not been received");return i(this,ke,"f")},In=function(t){let[r,s]=i(this,B,"m",Cn).call(this,t,i(this,G,"f"));b(this,G,r,"f"),i(this,Tr,"f")[r.id]=r;for(let n of s){let o=r.content[n.index];if(o?.type=="text")this._emit("textCreated",o.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,r),t.data.delta.content)for(let n of t.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=r.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=i(this,Ke,"f")){if(i(this,ve,"f"))switch(i(this,ve,"f").type){case"text":this._emit("textDone",i(this,ve,"f").text,i(this,G,"f"));break;case"image_file":this._emit("imageFileDone",i(this,ve,"f").image_file,i(this,G,"f"));break}b(this,Ke,n.index,"f")}b(this,ve,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,Ke,"f")!==void 0){let n=t.data.content[i(this,Ke,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,i(this,G,"f"));break;case"text":this._emit("textDone",n.text,i(this,G,"f"));break}}if(i(this,G,"f"))this._emit("messageDone",t.data);b(this,G,void 0,"f")}},Pn=function(t){let r=i(this,B,"m",Rn).call(this,t);switch(b(this,zt,r,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":let s=t.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)if(o.index==i(this,Mr,"f"))this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]);else{if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f"));if(b(this,Mr,o.index,"f"),b(this,X,r.step_details.tool_calls[o.index],"f"),i(this,X,"f"))this._emit("toolCallCreated",i(this,X,"f"))}this._emit("runStepDelta",t.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(b(this,zt,void 0,"f"),t.data.step_details.type=="tool_calls"){if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f")}this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},Sn=function(t){i(this,xs,"f").push(t),this._emit("event",t)},Rn=function(t){switch(t.event){case"thread.run.step.created":return i(this,Z,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=i(this,Z,"f")[t.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let s=t.data;if(s.delta){let n=$e.accumulateDelta(r,s.delta);i(this,Z,"f")[t.data.id]=n}return i(this,Z,"f")[t.data.id];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":i(this,Z,"f")[t.data.id]=t.data;break}if(i(this,Z,"f")[t.data.id])return i(this,Z,"f")[t.data.id];throw Error("No snapshot available")},Cn=function(t,r){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=t.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in r.content){let a=r.content[o.index];r.content[o.index]=i(this,B,"m",En).call(this,o,a)}else r.content[o.index]=o,s.push(o);return[r,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,s];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},En=function(t,r){return $e.accumulateDelta(r,t)},vn=function(t){switch(b(this,Nr,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(b(this,ke,t.data,"f"),i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f");break;case"thread.run.cancelling":break}};function ko(e){}class Ge extends c{constructor(){super(...arguments);this.steps=new Vt(this._client)}create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/threads/${e}/runs`,{query:{include:s},body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/runs`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(l`/threads/${s}/runs/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return me.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(n.status){case"queued":case"in_progress":case"cancelling":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return n}}}stream(e,t,r){return me.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return me.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}Ge.Steps=Vt;class Oe extends c{constructor(){super(...arguments);this.runs=new Ge(this._client),this.messages=new Xt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return me.createThreadAssistantStream(e,this._client.beta.threads,t)}}Oe.Runs=Ge;Oe.Messages=Xt;class ee extends c{constructor(){super(...arguments);this.realtime=new Ce(this._client),this.chatkit=new Ee(this._client),this.assistants=new Dt(this._client),this.threads=new Oe(this._client)}}ee.Realtime=Ce;ee.ChatKit=Ee;ee.Assistants=Dt;ee.Threads=Oe;class ze extends c{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Qt extends c{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class Qe extends c{constructor(){super(...arguments);this.content=new Qt(this._client)}create(e,t,r){return this._client.post(l`/containers/${e}/files`,ie({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/containers/${e}/files`,x,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(l`/containers/${s}/files/${e}`,{...r,headers:h([{Accept:"*/*"},r?.headers])})}}Qe.Content=Qt;class Te extends c{constructor(){super(...arguments);this.files=new Qe(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(l`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}}Te.Files=Qe;class Yt extends c{create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/conversations/${e}/items`,{query:{include:s},body:n,...r})}retrieve(e,t,r){let{conversation_id:s,...n}=t;return this._client.get(l`/conversations/${s}/items/${e}`,{query:n,...r})}list(e,t={},r){return this._client.getAPIList(l`/conversations/${e}/items`,Y,{query:t,...r})}delete(e,t,r){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,r)}}class Fe extends c{constructor(){super(...arguments);this.items=new Yt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(l`/conversations/${e}`,t)}update(e,t,r){return this._client.post(l`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(l`/conversations/${e}`,t)}}Fe.Items=Yt;class Ye extends c{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";if(r)v(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let n=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});if(r)return n;return v(this._client).debug("embeddings/decoding base64 embeddings from base64"),n._thenUnwrap((o)=>{if(o&&o.data)o.data.forEach((a)=>{let f=a.embedding;a.embedding=An(f)});return o})}}class Zt extends c{retrieve(e,t,r){let{eval_id:s,run_id:n}=t;return this._client.get(l`/evals/${s}/runs/${n}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...n}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,x,{query:n,...r})}}class Ze extends c{constructor(){super(...arguments);this.outputItems=new Zt(this._client)}create(e,t,r){return this._client.post(l`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/evals/${e}/runs`,x,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(l`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(l`/evals/${s}/runs/${e}`,r)}}Ze.OutputItems=Zt;class Ne extends c{constructor(){super(...arguments);this.runs=new Ze(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(l`/evals/${e}`,t)}update(e,t,r){return this._client.post(l`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/evals/${e}`,t)}}Ne.Runs=Ze;class et extends c{create(e,t){return this._client.post("/files",V({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/files/${e}`,t)}content(e,t){return this._client.get(l`/files/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5000,maxWait:r=1800000}={}){let s=new Set(["processed","error","deleted"]),n=Date.now(),o=await this.retrieve(e);while(!o.status||!s.has(o.status))if(await z(t),o=await this.retrieve(e),Date.now()-n>r)throw new Ae({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}}class er extends c{}class tr extends c{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}}class tt extends c{constructor(){super(...arguments);this.graders=new tr(this._client)}}tt.Graders=tr;class rr extends c{create(e,t,r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,oe,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Y,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(l`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}class st extends c{constructor(){super(...arguments);this.permissions=new rr(this._client)}}st.Permissions=rr;class sr extends c{list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,x,{query:t,...r})}}class nt extends c{constructor(){super(...arguments);this.checkpoints=new sr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,x,{query:t,...r})}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,t)}}nt.Checkpoints=sr;class te extends c{constructor(){super(...arguments);this.methods=new er(this._client),this.jobs=new nt(this._client),this.checkpoints=new st(this._client),this.alpha=new tt(this._client)}}te.Methods=er;te.Jobs=nt;te.Checkpoints=st;te.Alpha=tt;class nr extends c{}class Me extends c{constructor(){super(...arguments);this.graderModels=new nr(this._client)}}Me.GraderModels=nr;class ot extends c{createVariation(e,t){return this._client.post("/images/variations",V({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",V({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class it extends c{retrieve(e,t){return this._client.get(l`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",oe,e)}delete(e,t){return this._client.delete(l`/models/${e}`,t)}}class at extends c{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class or extends c{accept(e,t,r){return this._client.post(l`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(l`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(l`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}}class ir extends c{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class _e extends c{constructor(){super(...arguments);this.clientSecrets=new ir(this._client),this.calls=new or(this._client)}}_e.ClientSecrets=ir;_e.Calls=or;function $n(e,t){if(!t||!zo(t))return{...e,output_parsed:null,output:e.output.map((r)=>{if(r.type==="function_call")return{...r,parsed_arguments:null};if(r.type==="message")return{...r,content:r.content.map((s)=>({...s,parsed:null}))};else return r})};return As(e,t)}function As(e,t){let r=e.output.map((n)=>{if(n.type==="function_call")return{...n,parsed_arguments:Zo(t,n)};if(n.type==="message"){let o=n.content.map((a)=>{if(a.type==="output_text")return{...a,parsed:Go(t,a.text)};return a});return{...n,content:o}}return n}),s=Object.assign({},e,{output:r});if(!Object.getOwnPropertyDescriptor(e,"output_text"))Lr(s);return Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let n of s.output){if(n.type!=="message")continue;for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),s}function Go(e,t){if(e.text?.format?.type!=="json_schema")return null;if("$parseRaw"in e.text?.format)return(e.text?.format).$parseRaw(t);return JSON.parse(t)}function zo(e){if($t(e.text?.format))return!0;return!1}function Qo(e){return e?.$brand==="auto-parseable-tool"}function Yo(e,t){return e.find((r)=>r.type==="function"&&r.name===t)}function Zo(e,t){let r=Yo(e.tools??[],t.name);return{...t,...t,parsed_arguments:Qo(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function Lr(e){let t=[];for(let r of e.output){if(r.type!=="message")continue;for(let s of r.content)if(s.type==="output_text")t.push(s.text)}e.output_text=t.join("")}var lt,Br,ge,Ur,kn,On,Tn,Fn;class jr extends Se{constructor(e){super();lt.add(this),Br.set(this,void 0),ge.set(this,void 0),Ur.set(this,void 0),b(this,Br,e,"f")}static createResponse(e,t,r){let s=new jr(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,lt,"m",kn).call(this);let n,o=null;if("response_id"in t)n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null;else n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let a of n)i(this,lt,"m",On).call(this,a,o);if(n.controller.signal?.aborted)throw new F;return i(this,lt,"m",Tn).call(this)}[(Br=new WeakMap,ge=new WeakMap,Ur=new WeakMap,lt=new WeakSet,kn=function(){if(this.ended)return;b(this,ge,void 0,"f")},On=function(t,r){if(this.ended)return;let s=(o,a)=>{if(r==null||a.sequence_number>r)this._emit(o,a)},n=i(this,lt,"m",Fn).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="message"){let a=o.content[t.content_index];if(!a)throw new m(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new m(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="function_call")s("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:s(t.type,t);break}},Tn=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,ge,"f");if(!t)throw new m("request ended without sending any events");b(this,ge,void 0,"f");let r=ei(t,i(this,Br,"f"));return b(this,Ur,r,"f"),r},Fn=function(t){let r=i(this,ge,"f");if(!r){if(t.type!=="response.created")throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=b(this,ge,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);let n=s.type,o=t.part;if(n==="message"&&o.type!=="reasoning_text")s.content.push(o);else if(n==="reasoning"&&o.type==="reasoning_text"){if(!s.content)s.content=[];s.content.push(o)}break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="message"){let n=s.content[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="output_text")throw new m(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="function_call")s.arguments+=t.delta;break}case"response.reasoning_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="reasoning"){let n=s.content?.[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.completed":{b(this,ge,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=i(this,Ur,"f");if(!e)throw new m("stream ended without producing a ChatCompletion");return e}}function ei(e,t){return $n(e,t)}class ar extends c{list(e,t={},r){return this._client.getAPIList(l`/responses/${e}/input_items`,x,{query:t,...r})}}class lr extends c{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class ye extends c{constructor(){super(...arguments);this.inputItems=new ar(this._client),this.inputTokens=new lr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((r)=>{if("object"in r&&r.object==="response")Lr(r);return r})}retrieve(e,t={},r){return this._client.get(l`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap((s)=>{if("object"in s&&s.object==="response")Lr(s);return s})}delete(e,t){return this._client.delete(l`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((r)=>As(r,e))}stream(e,t){return jr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}ye.InputItems=ar;ye.InputTokens=lr;class cr extends c{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}}class ur extends c{retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class ct extends c{constructor(){super(...arguments);this.content=new ur(this._client)}create(e,t={},r){return this._client.post(l`/skills/${e}/versions`,ie({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/skills/${e}/versions`,x,{query:t,...r})}delete(e,t,r){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,r)}}ct.Content=ur;class be extends c{constructor(){super(...arguments);this.content=new cr(this._client),this.versions=new ct(this._client)}create(e={},t){return this._client.post("/skills",ie({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/skills/${e}`,t)}update(e,t,r){return this._client.post(l`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/skills/${e}`,t)}}be.Content=cr;be.Versions=ct;class fr extends c{create(e,t,r){return this._client.post(l`/uploads/${e}/parts`,V({body:t,...r},this._client))}}class Le extends c{constructor(){super(...arguments);this.parts=new fr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(l`/uploads/${e}/complete`,{body:t,...r})}}Le.Parts=fr;var Nn=async(e)=>{let t=await Promise.allSettled(e),r=t.filter((n)=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw Error(`${r.length} promise(s) failed - see the above errors`)}let s=[];for(let n of t)if(n.status==="fulfilled")s.push(n.value);return s};class hr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(l`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...n}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(n.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"failed":case"cancelled":case"completed":return n}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let n=s?.maxConcurrency??5,o=Math.min(n,t.length),a=this._client,f=t.values(),d=[...r];async function _(p){for(let u of p){let w=await a.files.create({file:u,purpose:"assistants"},s);d.push(w.id)}}let y=Array(o).fill(f).map(_);return await Nn(y),await this.createAndPoll(e,{file_ids:d})}}class dr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...n}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/vector_stores/${e}/files`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let n=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),o=n.data;switch(o.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=n.response.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"failed":case"completed":return o}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(l`/vector_stores/${s}/files/${e}/content`,oe,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class we extends c{constructor(){super(...arguments);this.files=new dr(this._client),this.fileBatches=new hr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(l`/vector_stores/${e}/search`,oe,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}we.Files=dr;we.FileBatches=hr;class ut extends c{create(e,t){return this._client.post("/videos",ie({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Y,{query:e,...t})}delete(e,t){return this._client.delete(l`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(l`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(l`/videos/${e}/remix`,ie({body:t,...r},this._client))}}var ft,Mn,Dr;class ht extends c{constructor(){super(...arguments);ft.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=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");i(this,ft,"m",Mn).call(this,r);let n=h([t]).values,o=i(this,ft,"m",Dr).call(this,n,"webhook-signature"),a=i(this,ft,"m",Dr).call(this,n,"webhook-timestamp"),f=i(this,ft,"m",Dr).call(this,n,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new se("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1000);if(_-d>s)throw new se("Webhook timestamp is too old");if(d>_+s)throw new se("Webhook timestamp is too new");let y=o.split(" ").map((g)=>g.startsWith("v1,")?g.substring(3):g),p=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),u=f?`${f}.${a}.${e}`:`${a}.${e}`,w=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let g of y)try{let R=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",w,R,new TextEncoder().encode(u)))return}catch{continue}throw new se("The given webhook signature does not match the expected signature")}}ft=new WeakSet,Mn=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")},Dr=function(t,r){if(!t)throw Error("Headers are required");let s=t.get(r);if(s===null||s===void 0)throw Error(`Missing required header: ${r}`);return s};var Is,Ps,Wr,Ln;class rt{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("OPENAI_API_KEY"),organization:r=K("OPENAI_ORG_ID")??null,project:s=K("OPENAI_PROJECT_ID")??null,webhookSecret:n=K("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(Is.add(this),Wr.set(this,void 0),this.completions=new ze(this),this.chat=new Re(this),this.embeddings=new Ye(this),this.files=new et(this),this.images=new ot(this),this.audio=new ce(this),this.moderations=new at(this),this.models=new it(this),this.fineTuning=new te(this),this.graders=new Me(this),this.vectorStores=new we(this),this.webhooks=new ht(this),this.beta=new ee(this),this.batches=new Ve(this),this.uploads=new Le(this),this.responses=new ye(this),this.realtime=new _e(this),this.conversations=new Fe(this),this.evals=new Ne(this),this.containers=new Te(this),this.skills=new be(this),this.videos=new ut(this),t===void 0)throw new m("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:s,webhookSecret:n,...o,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Ns())throw new m(`It looks like you're running in a browser-like environment.
15
+ ${Or(e)}`);return{...j,id:C,type:T,function:{...ue,name:P,arguments:re}}})}};return{...w,message:{...I,content:g,role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}),created:n,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return ln(d,t)}function Or(e){return JSON.stringify(e)}function bn(e){return}function wn(e){}class Xe extends de{static fromReadableStream(e){let t=new Xe(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new Xe(t),n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}}class pe extends c{constructor(){super(...arguments);this.messages=new We(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(l`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(l`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,t)}parse(e,t){return fn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((r)=>kt(r,e))}runTools(e,t){if(e.stream)return Xe.runTools(this._client,e,t);return Lt.runTools(this._client,e,t)}stream(e,t){return de.createChatCompletion(this._client,e,t)}}pe.Messages=We;class Re extends c{constructor(){super(...arguments);this.completions=new pe(this._client)}}Re.Completions=pe;var xn=Symbol("brand.privateNullableHeaders");function*yo(e){if(!e)return;if(xn in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(Jr(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=Jr(s[1])?s[1]:[s[1]],a=!1;for(let f of o){if(f===void 0)continue;if(t&&!a)a=!0,yield[n,null];yield[n,f]}}}var h=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,a]of yo(s)){let f=o.toLowerCase();if(!n.has(f))t.delete(o),n.add(f);if(a===null)t.delete(o),r.add(f);else t.append(o,a),r.delete(f)}}return{[xn]:!0,values:t,nulls:r}};class Bt extends c{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Ut extends c{create(e,t){return this._client.post("/audio/transcriptions",V({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class jt extends c{create(e,t){return this._client.post("/audio/translations",V({body:e,...t,__metadata:{model:e.model}},this._client))}}class ce extends c{constructor(){super(...arguments);this.transcriptions=new Ut(this._client),this.translations=new jt(this._client),this.speech=new Bt(this._client)}}ce.Transcriptions=Ut;ce.Translations=jt;ce.Speech=Bt;class Ve extends c{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(l`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,t)}}class Dt extends c{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Wt extends c{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class qt extends c{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ce extends c{constructor(){super(...arguments);this.sessions=new Wt(this._client),this.transcriptionSessions=new qt(this._client)}}Ce.Sessions=Wt;Ce.TranscriptionSessions=qt;class Ht extends c{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}class Jt extends c{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Y,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,Y,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}}class Ee extends c{constructor(){super(...arguments);this.sessions=new Ht(this._client),this.threads=new Jt(this._client)}}Ee.Sessions=Ht;Ee.Threads=Jt;class Xt extends c{create(e,t,r){return this._client.post(l`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/messages/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/messages`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class Vt extends c{retrieve(e,t,r){let{thread_id:s,run_id:n,...o}=t;return this._client.get(l`/threads/${s}/runs/${n}/steps/${e}`,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...n}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}var An=(e)=>{if(typeof Buffer<"u"){let t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),r=t.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=t.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var K=(e)=>{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();return};var B,$e,xs,Z,Tr,G,ke,Ke,ve,Mr,X,Fr,Nr,zt,Kt,Gt,In,Pn,Sn,Rn,Cn,En,vn;class me extends Se{constructor(){super(...arguments);B.add(this),xs.set(this,[]),Z.set(this,{}),Tr.set(this,{}),G.set(this,void 0),ke.set(this,void 0),Ke.set(this,void 0),ve.set(this,void 0),Mr.set(this,void 0),X.set(this,void 0),Fr.set(this,void 0),Nr.set(this,void 0),zt.set(this,void 0)}[(xs=new WeakMap,Z=new WeakMap,Tr=new WeakMap,G=new WeakMap,ke=new WeakMap,Ke=new WeakMap,ve=new WeakMap,Mr=new WeakMap,X=new WeakMap,Fr=new WeakMap,Nr=new WeakMap,zt=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new $e;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}this._connected();let s=J.fromReadableStream(e,this.controller);for await(let n of s)i(this,B,"m",Kt).call(this,n);if(s.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}toReadableStream(){return new J(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let n=new $e;return n._run(()=>n._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createToolAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}static createThreadAssistantStream(e,t,r){let s=new $e;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let n=new $e;return n._run(()=>n._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}currentEvent(){return i(this,Fr,"f")}currentRun(){return i(this,Nr,"f")}currentMessageSnapshot(){return i(this,G,"f")}currentRunStepSnapshot(){return i(this,zt,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,Z,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,Tr,"f"))}async finalRun(){if(await this.done(),!i(this,ke,"f"))throw Error("Final run was not received.");return i(this,ke,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)i(this,B,"m",Kt).call(this,a);if(o.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}async _createAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,B,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new F;return this._addRun(i(this,B,"m",Gt).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let n=e[r];if(n===null||n===void 0){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof n==="string"&&typeof s==="string")n+=s;else if(typeof n==="number"&&typeof s==="number")n+=s;else if(Be(n)&&Be(s))n=this.accumulateDelta(n,s);else if(Array.isArray(n)&&Array.isArray(s)){if(n.every((o)=>typeof o==="string"||typeof o==="number")){n.push(...s);continue}for(let o of s){if(!Be(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),Error("Expected array delta entry to have an `index` property");if(typeof a!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let f=n[a];if(f==null)n.push(o);else n[a]=this.accumulateDelta(f,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${n}`);e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}$e=me,Kt=function(t){if(this.ended)return;switch(b(this,Fr,t,"f"),i(this,B,"m",Sn).call(this,t),t.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":i(this,B,"m",vn).call(this,t);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":i(this,B,"m",Pn).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":i(this,B,"m",In).call(this,t);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:ko(t)}},Gt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!i(this,ke,"f"))throw Error("Final run has not been received");return i(this,ke,"f")},In=function(t){let[r,s]=i(this,B,"m",Cn).call(this,t,i(this,G,"f"));b(this,G,r,"f"),i(this,Tr,"f")[r.id]=r;for(let n of s){let o=r.content[n.index];if(o?.type=="text")this._emit("textCreated",o.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,r),t.data.delta.content)for(let n of t.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=r.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=i(this,Ke,"f")){if(i(this,ve,"f"))switch(i(this,ve,"f").type){case"text":this._emit("textDone",i(this,ve,"f").text,i(this,G,"f"));break;case"image_file":this._emit("imageFileDone",i(this,ve,"f").image_file,i(this,G,"f"));break}b(this,Ke,n.index,"f")}b(this,ve,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,Ke,"f")!==void 0){let n=t.data.content[i(this,Ke,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,i(this,G,"f"));break;case"text":this._emit("textDone",n.text,i(this,G,"f"));break}}if(i(this,G,"f"))this._emit("messageDone",t.data);b(this,G,void 0,"f")}},Pn=function(t){let r=i(this,B,"m",Rn).call(this,t);switch(b(this,zt,r,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":let s=t.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)if(o.index==i(this,Mr,"f"))this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]);else{if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f"));if(b(this,Mr,o.index,"f"),b(this,X,r.step_details.tool_calls[o.index],"f"),i(this,X,"f"))this._emit("toolCallCreated",i(this,X,"f"))}this._emit("runStepDelta",t.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(b(this,zt,void 0,"f"),t.data.step_details.type=="tool_calls"){if(i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f")}this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},Sn=function(t){i(this,xs,"f").push(t),this._emit("event",t)},Rn=function(t){switch(t.event){case"thread.run.step.created":return i(this,Z,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=i(this,Z,"f")[t.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let s=t.data;if(s.delta){let n=$e.accumulateDelta(r,s.delta);i(this,Z,"f")[t.data.id]=n}return i(this,Z,"f")[t.data.id];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":i(this,Z,"f")[t.data.id]=t.data;break}if(i(this,Z,"f")[t.data.id])return i(this,Z,"f")[t.data.id];throw Error("No snapshot available")},Cn=function(t,r){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=t.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in r.content){let a=r.content[o.index];r.content[o.index]=i(this,B,"m",En).call(this,o,a)}else r.content[o.index]=o,s.push(o);return[r,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,s];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},En=function(t,r){return $e.accumulateDelta(r,t)},vn=function(t){switch(b(this,Nr,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(b(this,ke,t.data,"f"),i(this,X,"f"))this._emit("toolCallDone",i(this,X,"f")),b(this,X,void 0,"f");break;case"thread.run.cancelling":break}};function ko(e){}class Ge extends c{constructor(){super(...arguments);this.steps=new Vt(this._client)}create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/threads/${e}/runs`,{query:{include:s},body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/runs`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(l`/threads/${s}/runs/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return me.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(n.status){case"queued":case"in_progress":case"cancelling":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return n}}}stream(e,t,r){return me.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return me.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}Ge.Steps=Vt;class Oe extends c{constructor(){super(...arguments);this.runs=new Ge(this._client),this.messages=new Xt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return me.createThreadAssistantStream(e,this._client.beta.threads,t)}}Oe.Runs=Ge;Oe.Messages=Xt;class ee extends c{constructor(){super(...arguments);this.realtime=new Ce(this._client),this.chatkit=new Ee(this._client),this.assistants=new Dt(this._client),this.threads=new Oe(this._client)}}ee.Realtime=Ce;ee.ChatKit=Ee;ee.Assistants=Dt;ee.Threads=Oe;class ze extends c{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Qt extends c{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class Qe extends c{constructor(){super(...arguments);this.content=new Qt(this._client)}create(e,t,r){return this._client.post(l`/containers/${e}/files`,ie({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/containers/${e}/files`,x,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(l`/containers/${s}/files/${e}`,{...r,headers:h([{Accept:"*/*"},r?.headers])})}}Qe.Content=Qt;class Te extends c{constructor(){super(...arguments);this.files=new Qe(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(l`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}}Te.Files=Qe;class Yt extends c{create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/conversations/${e}/items`,{query:{include:s},body:n,...r})}retrieve(e,t,r){let{conversation_id:s,...n}=t;return this._client.get(l`/conversations/${s}/items/${e}`,{query:n,...r})}list(e,t={},r){return this._client.getAPIList(l`/conversations/${e}/items`,Y,{query:t,...r})}delete(e,t,r){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,r)}}class Fe extends c{constructor(){super(...arguments);this.items=new Yt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(l`/conversations/${e}`,t)}update(e,t,r){return this._client.post(l`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(l`/conversations/${e}`,t)}}Fe.Items=Yt;class Ye extends c{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";if(r)v(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let n=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});if(r)return n;return v(this._client).debug("embeddings/decoding base64 embeddings from base64"),n._thenUnwrap((o)=>{if(o&&o.data)o.data.forEach((a)=>{let f=a.embedding;a.embedding=An(f)});return o})}}class Zt extends c{retrieve(e,t,r){let{eval_id:s,run_id:n}=t;return this._client.get(l`/evals/${s}/runs/${n}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...n}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,x,{query:n,...r})}}class Ze extends c{constructor(){super(...arguments);this.outputItems=new Zt(this._client)}create(e,t,r){return this._client.post(l`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/evals/${e}/runs`,x,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(l`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(l`/evals/${s}/runs/${e}`,r)}}Ze.OutputItems=Zt;class Ne extends c{constructor(){super(...arguments);this.runs=new Ze(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(l`/evals/${e}`,t)}update(e,t,r){return this._client.post(l`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/evals/${e}`,t)}}Ne.Runs=Ze;class et extends c{create(e,t){return this._client.post("/files",V({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/files/${e}`,t)}content(e,t){return this._client.get(l`/files/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5000,maxWait:r=1800000}={}){let s=new Set(["processed","error","deleted"]),n=Date.now(),o=await this.retrieve(e);while(!o.status||!s.has(o.status))if(await z(t),o=await this.retrieve(e),Date.now()-n>r)throw new Ae({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}}class er extends c{}class tr extends c{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}}class tt extends c{constructor(){super(...arguments);this.graders=new tr(this._client)}}tt.Graders=tr;class rr extends c{create(e,t,r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,oe,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Y,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(l`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}class rt extends c{constructor(){super(...arguments);this.permissions=new rr(this._client)}}rt.Permissions=rr;class sr extends c{list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,x,{query:t,...r})}}class st extends c{constructor(){super(...arguments);this.checkpoints=new sr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,x,{query:t,...r})}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,t)}}st.Checkpoints=sr;class te extends c{constructor(){super(...arguments);this.methods=new er(this._client),this.jobs=new st(this._client),this.checkpoints=new rt(this._client),this.alpha=new tt(this._client)}}te.Methods=er;te.Jobs=st;te.Checkpoints=rt;te.Alpha=tt;class nr extends c{}class Me extends c{constructor(){super(...arguments);this.graderModels=new nr(this._client)}}Me.GraderModels=nr;class nt extends c{createVariation(e,t){return this._client.post("/images/variations",V({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",V({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class ot extends c{retrieve(e,t){return this._client.get(l`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",oe,e)}delete(e,t){return this._client.delete(l`/models/${e}`,t)}}class it extends c{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class or extends c{accept(e,t,r){return this._client.post(l`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(l`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(l`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}}class ir extends c{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class _e extends c{constructor(){super(...arguments);this.clientSecrets=new ir(this._client),this.calls=new or(this._client)}}_e.ClientSecrets=ir;_e.Calls=or;function $n(e,t){if(!t||!zo(t))return{...e,output_parsed:null,output:e.output.map((r)=>{if(r.type==="function_call")return{...r,parsed_arguments:null};if(r.type==="message")return{...r,content:r.content.map((s)=>({...s,parsed:null}))};else return r})};return As(e,t)}function As(e,t){let r=e.output.map((n)=>{if(n.type==="function_call")return{...n,parsed_arguments:Zo(t,n)};if(n.type==="message"){let o=n.content.map((a)=>{if(a.type==="output_text")return{...a,parsed:Go(t,a.text)};return a});return{...n,content:o}}return n}),s=Object.assign({},e,{output:r});if(!Object.getOwnPropertyDescriptor(e,"output_text"))Lr(s);return Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let n of s.output){if(n.type!=="message")continue;for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),s}function Go(e,t){if(e.text?.format?.type!=="json_schema")return null;if("$parseRaw"in e.text?.format)return(e.text?.format).$parseRaw(t);return JSON.parse(t)}function zo(e){if($t(e.text?.format))return!0;return!1}function Qo(e){return e?.$brand==="auto-parseable-tool"}function Yo(e,t){return e.find((r)=>r.type==="function"&&r.name===t)}function Zo(e,t){let r=Yo(e.tools??[],t.name);return{...t,...t,parsed_arguments:Qo(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function Lr(e){let t=[];for(let r of e.output){if(r.type!=="message")continue;for(let s of r.content)if(s.type==="output_text")t.push(s.text)}e.output_text=t.join("")}var at,Br,ge,Ur,kn,On,Tn,Fn;class jr extends Se{constructor(e){super();at.add(this),Br.set(this,void 0),ge.set(this,void 0),Ur.set(this,void 0),b(this,Br,e,"f")}static createResponse(e,t,r){let s=new jr(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,at,"m",kn).call(this);let n,o=null;if("response_id"in t)n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null;else n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let a of n)i(this,at,"m",On).call(this,a,o);if(n.controller.signal?.aborted)throw new F;return i(this,at,"m",Tn).call(this)}[(Br=new WeakMap,ge=new WeakMap,Ur=new WeakMap,at=new WeakSet,kn=function(){if(this.ended)return;b(this,ge,void 0,"f")},On=function(t,r){if(this.ended)return;let s=(o,a)=>{if(r==null||a.sequence_number>r)this._emit(o,a)},n=i(this,at,"m",Fn).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="message"){let a=o.content[t.content_index];if(!a)throw new m(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new m(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="function_call")s("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:s(t.type,t);break}},Tn=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,ge,"f");if(!t)throw new m("request ended without sending any events");b(this,ge,void 0,"f");let r=ei(t,i(this,Br,"f"));return b(this,Ur,r,"f"),r},Fn=function(t){let r=i(this,ge,"f");if(!r){if(t.type!=="response.created")throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=b(this,ge,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);let n=s.type,o=t.part;if(n==="message"&&o.type!=="reasoning_text")s.content.push(o);else if(n==="reasoning"&&o.type==="reasoning_text"){if(!s.content)s.content=[];s.content.push(o)}break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="message"){let n=s.content[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="output_text")throw new m(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="function_call")s.arguments+=t.delta;break}case"response.reasoning_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="reasoning"){let n=s.content?.[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.completed":{b(this,ge,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=i(this,Ur,"f");if(!e)throw new m("stream ended without producing a ChatCompletion");return e}}function ei(e,t){return $n(e,t)}class ar extends c{list(e,t={},r){return this._client.getAPIList(l`/responses/${e}/input_items`,x,{query:t,...r})}}class lr extends c{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class ye extends c{constructor(){super(...arguments);this.inputItems=new ar(this._client),this.inputTokens=new lr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((r)=>{if("object"in r&&r.object==="response")Lr(r);return r})}retrieve(e,t={},r){return this._client.get(l`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap((s)=>{if("object"in s&&s.object==="response")Lr(s);return s})}delete(e,t){return this._client.delete(l`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((r)=>As(r,e))}stream(e,t){return jr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}ye.InputItems=ar;ye.InputTokens=lr;class cr extends c{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}}class ur extends c{retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class lt extends c{constructor(){super(...arguments);this.content=new ur(this._client)}create(e,t={},r){return this._client.post(l`/skills/${e}/versions`,ie({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/skills/${e}/versions`,x,{query:t,...r})}delete(e,t,r){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,r)}}lt.Content=ur;class be extends c{constructor(){super(...arguments);this.content=new cr(this._client),this.versions=new lt(this._client)}create(e={},t){return this._client.post("/skills",ie({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/skills/${e}`,t)}update(e,t,r){return this._client.post(l`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/skills/${e}`,t)}}be.Content=cr;be.Versions=lt;class fr extends c{create(e,t,r){return this._client.post(l`/uploads/${e}/parts`,V({body:t,...r},this._client))}}class Le extends c{constructor(){super(...arguments);this.parts=new fr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(l`/uploads/${e}/complete`,{body:t,...r})}}Le.Parts=fr;var Nn=async(e)=>{let t=await Promise.allSettled(e),r=t.filter((n)=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw Error(`${r.length} promise(s) failed - see the above errors`)}let s=[];for(let n of t)if(n.status==="fulfilled")s.push(n.value);return s};class hr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(l`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...n}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(n.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"failed":case"cancelled":case"completed":return n}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let n=s?.maxConcurrency??5,o=Math.min(n,t.length),a=this._client,f=t.values(),d=[...r];async function _(p){for(let u of p){let w=await a.files.create({file:u,purpose:"assistants"},s);d.push(w.id)}}let y=Array(o).fill(f).map(_);return await Nn(y),await this.createAndPoll(e,{file_ids:d})}}class dr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...n}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/vector_stores/${e}/files`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let n=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),o=n.data;switch(o.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=n.response.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await z(a);break;case"failed":case"completed":return o}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(l`/vector_stores/${s}/files/${e}/content`,oe,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class we extends c{constructor(){super(...arguments);this.files=new dr(this._client),this.fileBatches=new hr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(l`/vector_stores/${e}/search`,oe,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}we.Files=dr;we.FileBatches=hr;class ct extends c{create(e,t){return this._client.post("/videos",ie({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Y,{query:e,...t})}delete(e,t){return this._client.delete(l`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(l`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(l`/videos/${e}/remix`,ie({body:t,...r},this._client))}}var ut,Mn,Dr;class ft extends c{constructor(){super(...arguments);ut.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=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");i(this,ut,"m",Mn).call(this,r);let n=h([t]).values,o=i(this,ut,"m",Dr).call(this,n,"webhook-signature"),a=i(this,ut,"m",Dr).call(this,n,"webhook-timestamp"),f=i(this,ut,"m",Dr).call(this,n,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new se("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1000);if(_-d>s)throw new se("Webhook timestamp is too old");if(d>_+s)throw new se("Webhook timestamp is too new");let y=o.split(" ").map((g)=>g.startsWith("v1,")?g.substring(3):g),p=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),u=f?`${f}.${a}.${e}`:`${a}.${e}`,w=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let g of y)try{let R=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",w,R,new TextEncoder().encode(u)))return}catch{continue}throw new se("The given webhook signature does not match the expected signature")}}ut=new WeakSet,Mn=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")},Dr=function(t,r){if(!t)throw Error("Headers are required");let s=t.get(r);if(s===null||s===void 0)throw Error(`Missing required header: ${r}`);return s};var Is,Ps,Wr,Ln;class At{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("OPENAI_API_KEY"),organization:r=K("OPENAI_ORG_ID")??null,project:s=K("OPENAI_PROJECT_ID")??null,webhookSecret:n=K("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(Is.add(this),Wr.set(this,void 0),this.completions=new ze(this),this.chat=new Re(this),this.embeddings=new Ye(this),this.files=new et(this),this.images=new nt(this),this.audio=new ce(this),this.moderations=new it(this),this.models=new ot(this),this.fineTuning=new te(this),this.graders=new Me(this),this.vectorStores=new we(this),this.webhooks=new ft(this),this.beta=new ee(this),this.batches=new Ve(this),this.uploads=new Le(this),this.responses=new ye(this),this.realtime=new _e(this),this.conversations=new Fe(this),this.evals=new Ne(this),this.containers=new Te(this),this.skills=new be(this),this.videos=new ct(this),t===void 0)throw new m("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:s,webhookSecret:n,...o,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Ns())throw new m(`It looks like you're running in a browser-like environment.
16
16
 
17
17
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
18
18
  If you understand the risks and have appropriate mitigations in place,
@@ -21,4 +21,4 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
21
21
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
22
22
 
23
23
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
24
- `);this.baseURL=a.baseURL,this.timeout=a.timeout??Ps.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=rs(a.logLevel,"ClientOptions.logLevel",this)??rs(K("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Ls(),b(this,Wr,Us,"f"),this._options=a,this.apiKey=typeof t==="string"?t:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){return}async authHeaders(e){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ks(e)}getUserAgent(){return`${this.constructor.name}/JS ${fe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hr()}`}makeStatusError(e,t,r,s){return O.generate(e,t,r,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=="function")return!1;let t;try{t=await e()}catch(r){if(r instanceof m)throw r;throw new m(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!=="string"||!t)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let s=!i(this,Is,"m",Ln).call(this)&&r||this.baseURL,n=Cs(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!Es(o))t={...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Ie(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:a,timeout:f}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:a,options:s});let d="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),_=r===void 0?"":`, retryOf: ${r}`,y=Date.now();if(v(this).debug(`[${d}] sending request`,ne({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new F;let p=new AbortController,u=await this.fetchWithTimeout(a,o,f,p).catch(pt),w=Date.now();if(u instanceof globalThis.Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new F;let I=dt(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return v(this).info(`[${d}] connection ${I?"timed out":"failed"} - ${S}`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (${S})`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),this.retryRequest(s,t,r??d);if(v(this).info(`[${d}] connection ${I?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (error; no more retries left)`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),I)throw new Ae;throw new xe({cause:u})}let g=[...u.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,I])=>", "+S+": "+JSON.stringify(I)).join(""),R=`[${d}${_}${g}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${w-y}ms`;if(!u.ok){let S=await this.shouldRetry(u);if(t&&S){let T=`retrying, ${t} attempts remaining`;return await Bs(u.body),v(this).info(`${R} - ${T}`),v(this).debug(`[${d}] response error (${T})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),this.retryRequest(s,t,r??d,u.headers)}let I=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${I}`);let A=await u.text().catch((T)=>pt(T).message),k=ks(A),E=k?void 0:A;throw v(this).debug(`[${d}] response error (${I})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:E,durationMs:Date.now()-y})),this.makeStatusError(u.status,k,E,u.headers)}return v(this).info(R),v(this).debug(`[${d}] response start`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),{response:u,options:s,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:y}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new xr(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...a}=t||{},f=this._makeAbort(s);if(n)n.addEventListener("abort",f,{once:!0});let d=setTimeout(f,r),_=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body==="object"&&a.body!==null&&Symbol.asyncIterator in a.body,y={signal:s.signal,..._?{duplex:"half"}:{},method:"GET",...a};if(o)y.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,y)}finally{clearTimeout(d)}}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,r,s){let n,o=s?.get("retry-after-ms");if(o){let f=parseFloat(o);if(!Number.isNaN(f))n=f}let a=s?.get("retry-after");if(a&&!n){let f=parseFloat(a);if(!Number.isNaN(f))n=f*1000;else n=Date.parse(a)-Date.now()}if(n===void 0){let f=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,f)}return await z(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),a=1-Math.random()*0.25;return o*a*1000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:a}=r,f=this.buildURL(n,o,a);if("timeout"in r)$s("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:_}=this.buildBody({options:r}),y=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:y,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=h([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Ms(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=h([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:pr(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return i(this,Wr,"f").call(this,{body:e,headers:r})}}Ps=rt,Wr=new WeakMap,Is=new WeakSet,Ln=function(){return this.baseURL!=="https://api.openai.com/v1"};rt.OpenAI=Ps;rt.DEFAULT_TIMEOUT=600000;rt.OpenAIError=m;rt.APIError=O;rt.APIConnectionError=xe;rt.APIConnectionTimeoutError=Ae;rt.APIUserAbortError=F;rt.NotFoundError=yt;rt.ConflictError=bt;rt.RateLimitError=xt;rt.BadRequestError=mt;rt.AuthenticationError=_t;rt.InternalServerError=At;rt.PermissionDeniedError=gt;rt.UnprocessableEntityError=wt;rt.InvalidWebhookSignatureError=se;rt.toFile=Ir;rt.Completions=ze;rt.Chat=Re;rt.Embeddings=Ye;rt.Files=et;rt.Images=ot;rt.Audio=ce;rt.Moderations=at;rt.Models=it;rt.FineTuning=te;rt.Graders=Me;rt.VectorStores=we;rt.Webhooks=ht;rt.Beta=ee;rt.Batches=Ve;rt.Uploads=Le;rt.Responses=ye;rt.Realtime=_e;rt.Conversations=Fe;rt.Evals=Ne;rt.Containers=Te;rt.Skills=be;rt.Videos=ut;class Tu extends rt{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("AZURE_OPENAI_API_KEY"),apiVersion:r=K("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)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 o==="function")a=!0;if(!o&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&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":r},!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");e=`${s}/openai`}else if(s)throw new m("baseURL and endpoint are mutually exclusive");super({apiKey:o??t,baseURL:e,...f,...a!==void 0?{dangerouslyAllowBrowser:a}:{}});this.apiVersion="",this.apiVersion=r,this.deploymentName=n}async buildRequest(e,t={}){if(ui.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Be(e.body))throw Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;if(r!==void 0&&!this.baseURL.includes("/deployments"))e.path=`/deployments/${r}${e.path}`}return super.buildRequest(e,t)}async authHeaders(e){if(typeof this._options.apiKey==="string")return h([{"api-key":this.apiKey}]);return super.authHeaders(e)}}var ui=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{rt,Tu};
24
+ `);this.baseURL=a.baseURL,this.timeout=a.timeout??Ps.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=rs(a.logLevel,"ClientOptions.logLevel",this)??rs(K("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Ls(),b(this,Wr,Us,"f"),this._options=a,this.apiKey=typeof t==="string"?t:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){return}async authHeaders(e){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ks(e)}getUserAgent(){return`${this.constructor.name}/JS ${fe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hr()}`}makeStatusError(e,t,r,s){return O.generate(e,t,r,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=="function")return!1;let t;try{t=await e()}catch(r){if(r instanceof m)throw r;throw new m(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!=="string"||!t)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let s=!i(this,Is,"m",Ln).call(this)&&r||this.baseURL,n=Cs(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!Es(o))t={...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Ie(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:a,timeout:f}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:a,options:s});let d="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),_=r===void 0?"":`, retryOf: ${r}`,y=Date.now();if(v(this).debug(`[${d}] sending request`,ne({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new F;let p=new AbortController,u=await this.fetchWithTimeout(a,o,f,p).catch(dt),w=Date.now();if(u instanceof globalThis.Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new F;let I=ht(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return v(this).info(`[${d}] connection ${I?"timed out":"failed"} - ${S}`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (${S})`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),this.retryRequest(s,t,r??d);if(v(this).info(`[${d}] connection ${I?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (error; no more retries left)`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),I)throw new Ae;throw new xe({cause:u})}let g=[...u.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,I])=>", "+S+": "+JSON.stringify(I)).join(""),R=`[${d}${_}${g}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${w-y}ms`;if(!u.ok){let S=await this.shouldRetry(u);if(t&&S){let T=`retrying, ${t} attempts remaining`;return await Bs(u.body),v(this).info(`${R} - ${T}`),v(this).debug(`[${d}] response error (${T})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),this.retryRequest(s,t,r??d,u.headers)}let I=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${I}`);let A=await u.text().catch((T)=>dt(T).message),k=ks(A),E=k?void 0:A;throw v(this).debug(`[${d}] response error (${I})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:E,durationMs:Date.now()-y})),this.makeStatusError(u.status,k,E,u.headers)}return v(this).info(R),v(this).debug(`[${d}] response start`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),{response:u,options:s,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:y}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new xr(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...a}=t||{},f=this._makeAbort(s);if(n)n.addEventListener("abort",f,{once:!0});let d=setTimeout(f,r),_=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body==="object"&&a.body!==null&&Symbol.asyncIterator in a.body,y={signal:s.signal,..._?{duplex:"half"}:{},method:"GET",...a};if(o)y.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,y)}finally{clearTimeout(d)}}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,r,s){let n,o=s?.get("retry-after-ms");if(o){let f=parseFloat(o);if(!Number.isNaN(f))n=f}let a=s?.get("retry-after");if(a&&!n){let f=parseFloat(a);if(!Number.isNaN(f))n=f*1000;else n=Date.parse(a)-Date.now()}if(n===void 0){let f=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,f)}return await z(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),a=1-Math.random()*0.25;return o*a*1000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:a}=r,f=this.buildURL(n,o,a);if("timeout"in r)$s("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:_}=this.buildBody({options:r}),y=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:y,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=h([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Ms(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=h([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:pr(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return i(this,Wr,"f").call(this,{body:e,headers:r})}}Ps=At,Wr=new WeakMap,Is=new WeakSet,Ln=function(){return this.baseURL!=="https://api.openai.com/v1"};At.OpenAI=Ps;At.DEFAULT_TIMEOUT=600000;At.OpenAIError=m;At.APIError=O;At.APIConnectionError=xe;At.APIConnectionTimeoutError=Ae;At.APIUserAbortError=F;At.NotFoundError=gt;At.ConflictError=yt;At.RateLimitError=wt;At.BadRequestError=pt;At.AuthenticationError=mt;At.InternalServerError=xt;At.PermissionDeniedError=_t;At.UnprocessableEntityError=bt;At.InvalidWebhookSignatureError=se;At.toFile=Ir;At.Completions=ze;At.Chat=Re;At.Embeddings=Ye;At.Files=et;At.Images=nt;At.Audio=ce;At.Moderations=it;At.Models=ot;At.FineTuning=te;At.Graders=Me;At.VectorStores=we;At.Webhooks=ft;At.Beta=ee;At.Batches=Ve;At.Uploads=Le;At.Responses=ye;At.Realtime=_e;At.Conversations=Fe;At.Evals=Ne;At.Containers=Te;At.Skills=be;At.Videos=ct;class Yd extends At{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("AZURE_OPENAI_API_KEY"),apiVersion:r=K("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)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 o==="function")a=!0;if(!o&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&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":r},!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");e=`${s}/openai`}else if(s)throw new m("baseURL and endpoint are mutually exclusive");super({apiKey:o??t,baseURL:e,...f,...a!==void 0?{dangerouslyAllowBrowser:a}:{}});this.apiVersion="",this.apiVersion=r,this.deploymentName=n}async buildRequest(e,t={}){if(ui.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Be(e.body))throw Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;if(r!==void 0&&!this.baseURL.includes("/deployments"))e.path=`/deployments/${r}${e.path}`}return super.buildRequest(e,t)}async authHeaders(e){if(typeof this._options.apiKey==="string")return h([{"api-key":this.apiKey}]);return super.authHeaders(e)}}var ui=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{At,Yd};
@@ -0,0 +1,2 @@
1
+ import{S,G,M,w,Z,Y,a,g,X,Tt,We,R,K,Pn,F,t1,re,Zn,hs,tm,lt,Nt,Ft,St}from"./chunk-zarz3sqn.js";import{wa}from"./chunk-s1e4qy3q.js";import{gu,Ns}from"./chunk-f6avg5qe.js";import{hu}from"./chunk-gtf19jc1.js";import{Ea}from"./chunk-r1xer8gn.js";import{pu,mu}from"./chunk-z1p13dnc.js";import{Jr}from"./chunk-q5vkxee3.js";import{_r}from"./chunk-ny1kbmxt.js";Z();function ba({shareId:r,initialFolderId:ve,initialFileId:W,startTime:O,versionId:x,compare:ye,compareLeftId:C,compareRightId:k,compareActiveSide:Q="left"}){let c=We(),A=hs(),p=!!ye&&!!C&&!!k,[d,J]=w(()=>localStorage.getItem(`share_pwd_${r}`)||""),[q,xe]=w(""),{data:s,error:b,isLoading:Se}=X({queryKey:["share-info",r,d],queryFn:async()=>{let e=await R.api.shares[":shareId"].info.$get({param:{shareId:r}},{headers:{"x-share-password":d}});if(e.status===401)throw Error("Unauthorized");if(e.status===403){let t=await e.json();throw Error(t.error||"Forbidden")}if(!e.ok)throw Error("Failed to fetch share info");return await e.json()},retry:!1}),o=ve||s?.rootFolderId,l=W||null,z=x||l,[V,ee]=w([]),{data:j}=X({queryKey:["public-share-folder",r,o,d],queryFn:async()=>{let e=await R.api.shares[":shareId"].files[":fileId"].$get({param:{shareId:r,fileId:o}},{headers:{"x-share-password":d}});if(e.status===401)throw Error("Unauthorized");return await e.json()},enabled:!!s&&!!o});S(()=>{if(j?.ancestorFolders&&s){let e=j.ancestorFolders.findIndex((t)=>t.id===s.rootFolderId);if(e!==-1)ee(j.ancestorFolders.slice(0,e));else if(o===s.rootFolderId)ee([])}},[j,s,o]);let[D,u]=w(null),[I,f]=w(new Set),[be,Pe]=w(360),[U,Ne]=w(()=>!W),P=M(null),[te,E]=w([]),[Ce,se]=w(0),[ke,_]=w(null),[oe,Ae]=w(null),[je,De]=w(void 0),{data:T,fetchNextPage:ae,hasNextPage:ne,isFetchingNextPage:ie,isLoading:le,error:de}=Tt({queryKey:["public-share-children",r,o,"folder",d],queryFn:async({pageParam:e})=>{let t=await R.api.shares[":shareId"].folders[":folderId"].children.$get({param:{shareId:r,folderId:o},query:{assetType:"folder",after:e}},{headers:{"x-share-password":d}});if(t.status===401)throw Error("Unauthorized");if(t.status===403)throw Error("Expired");return await t.json()},enabled:!!s&&!!o,initialPageParam:"",getNextPageParam:(e)=>e.pageInfo?.cursor||void 0,retry:!1}),{data:L,fetchNextPage:ce,hasNextPage:fe,isFetchingNextPage:ue,isLoading:me}=Tt({queryKey:["public-share-children",r,o,"file",d],queryFn:async({pageParam:e})=>{let t=await R.api.shares[":shareId"].folders[":folderId"].children.$get({param:{shareId:r,folderId:o},query:{assetType:"file",after:e}},{headers:{"x-share-password":d}});if(t.status===401)throw Error("Unauthorized");if(t.status===403)throw Error("Expired");return await t.json()},enabled:!!s&&!!o,initialPageParam:"",getNextPageParam:(e)=>e.pageInfo?.cursor||void 0,retry:!1}),{data:pe}=X({queryKey:["public-share-fields",r,d],queryFn:async()=>{let e=await R.api.shares[":shareId"].fields.$get({param:{shareId:r}},{headers:{"x-share-password":d}});if(e.status===401)throw Error("Unauthorized");return await e.json()},enabled:!!s}),{data:m,isLoading:$e}=X({queryKey:["public-share-file",r,l,d],queryFn:async()=>{let e=await R.api.shares[":shareId"].files[":fileId"].$get({param:{shareId:r,fileId:l}},{headers:{"x-share-password":d}});if(e.status===401)throw Error("Unauthorized");return await e.json()},enabled:!!l&&!!s}),{data:Ee,isLoading:Te}=X({queryKey:["public-share-file",r,x,d],queryFn:async()=>{let e=await R.api.shares[":shareId"].files[":fileId"].$get({param:{shareId:r,fileId:x}},{headers:{"x-share-password":d}});if(e.status===401)throw Error("Unauthorized");return await e.json()},enabled:!!x&&!!s}),n=x?Ee:m,Le=$e||!!x&&Te;S(()=>{if(de?.message==="Unauthorized")J(""),localStorage.removeItem(`share_pwd_${r}`)},[de,r]);let h=G(()=>T?.pages.flatMap((e)=>e.data??[])??[],[T]),v=G(()=>L?.pages.flatMap((e)=>e.data??[])??[],[L]),Re=T?.pages[0]?.pageInfo?.total,qe=L?.pages[0]?.pageInfo?.total,ze=T?.pages[0]?.pageInfo?.totalSize,Me=L?.pages[0]?.pageInfo?.totalSize,ge=G(()=>{if(n)return n;if(I.size!==1)return null;let e=Array.from(I)[0];return[...h,...v].find((t)=>t.id===e)||null},[I,h,v,n]),Ke=(e)=>{e.preventDefault(),J(q),localStorage.setItem(`share_pwd_${r}`,q)},he=(e)=>{if(e.type==="folder"||e.targetType==="folder")c({to:"/share/$shareId/folders/$folderId",params:{shareId:r,folderId:e.id}});else c({to:"/share/$shareId/files/$fileId",params:{shareId:r,fileId:e.versionStack?e.versionStack.id:e.id}});f(new Set)},Ve=(e)=>{if(!s)return;let t=e==="root"?s.rootFolderId:e;if(t===s.rootFolderId)c({to:"/share/$shareId",params:{shareId:r}});else c({to:"/share/$shareId/folders/$folderId",params:{shareId:r,folderId:t}});f(new Set),u(null)},Ue=(e)=>{_(e.id||null);let t=e.annotations;if(t&&t.length>0)E(t);else E([]);if(p){if(e.second!==null&&e.second!==void 0)De({second:e.second,nonce:Date.now()});return}if(e.second!==null&&e.second!==void 0)P.current?.seekTo(e.second),P.current?.pause();else if(t&&t.length>0)P.current?.pause()},we=()=>{E([]),_(null)},_e=()=>{E([]),_(null)},B=(e)=>{if(!l)return;c({to:"/share/$shareId/files/$fileId",params:{shareId:r,fileId:l},search:(t)=>({...t,...e})})},Be=()=>{B({compare:void 0,cmpLeft:void 0,cmpRight:void 0,cmpActive:void 0,version:Q==="left"?C:k})},{setProjectState:Ie,clearProjectState:Fe}=Zn();S(()=>{if(s&&o){let e=o===s.rootFolderId?s.name:h.find((t)=>t.id===o)?.name||s.name;Ie({teamId:"",projectId:s.projectId,projectName:s.name,ancestorFolders:V,currentAsset:{name:n?.name||e,type:l?"file":"folder",version:m?.versionStack?m.versionStack.versions.find((t)=>t.id===z)?.version??m.versionStack.versions.length:void 0,proxyType:n?.proxyType||null},isRootFolder:o===s.rootFolderId&&!l,isPublic:!0,shareId:r,fileId:l||void 0,allowDownload:s.allowDownload,downloadInfo:n?{originalKey:n.media?.original?.key,videoTranscodes:n.media?.videoTranscodes?.map((t)=>({key:t.key,width:t.width,height:t.height,resolution:t.resolution,hdr:t.hdr}))}:void 0,onFolderClick:Ve,isRightSidebarCollapsed:U,onRightSidebarToggle:()=>Ne((t)=>!t),versions:m?.versionStack?.versions,compareMode:p,canCompareVersions:(m?.versionStack?.versions?.length??0)>=2,onCompareVersions:()=>{let t=gu(m?.versionStack?.versions);if(!t||!l)return;c({to:"/share/$shareId/files/$fileId",params:{shareId:r,fileId:l},search:(i)=>({...i,compare:!0,cmpLeft:t.left.id,cmpRight:t.right.id,cmpActive:"left"})})}})}return()=>Fe()},[s,o,h,n,m,z,l,V,Ie,Fe,U,p,c,r]);let y;if(Se&&!b)y=a("div",{className:"flex flex-1 items-center justify-center bg-background",children:a(K,{className:"h-8 w-8 animate-spin text-foreground"})});else if(b)if(b.message==="Unauthorized"){let e=d!=="";y=a("div",{className:"flex flex-1 items-center justify-center p-4",children:g(lt,{className:"w-full max-w-md",children:[g(Nt,{className:"text-center",children:[a("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:a(Pn,{className:"h-6 w-6 text-primary"})}),a(Ft,{children:t1()})]}),a(St,{children:g("form",{onSubmit:Ke,className:"space-y-4",children:[g("div",{className:"space-y-2",children:[a(re,{type:"password",placeholder:"Enter password",value:q,onChange:(t)=>xe(t.target.value),autoFocus:!0}),e&&a("p",{className:"text-sm font-medium text-destructive",children:"Incorrect password. Please try again."})]}),a(F,{type:"submit",className:"w-full",children:"Access Share"})]})})]})})}else{let e=b.message.includes("expired"),t=b.message.includes("disabled");y=a("div",{className:"flex flex-1 items-center justify-center p-4",children:g(lt,{className:"w-full max-w-md",children:[g(Nt,{className:"text-center",children:[a("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-destructive/10",children:a(_r,{className:"h-6 w-6 text-destructive"})}),a(Ft,{children:e?"Share Expired":t?"Share Disabled":"Error"})]}),a(St,{className:"text-center text-muted-foreground",children:b.message})]})})}else if(!s)y=a("div",{className:"flex flex-1 items-center justify-center bg-background",children:a(K,{className:"h-8 w-8 animate-spin text-foreground"})});else if(A&&l&&!p&&n){let e=n?.ancestorFolders?.[0]?.id||(o!==s.rootFolderId?o:void 0),t=n?.ancestorFolders&&n.ancestorFolders.length>0?n.ancestorFolders:V;y=a(pu,{projectId:s.projectId,fileId:l,file:n,projectInfo:{name:s.name,rootFolder:s.rootFolderId},ancestorFolders:t,versions:m?.versionStack?.versions??n?.versionStack?.versions,activeFileId:z||l,startTime:O,isPublic:!0,shareId:r,allowDownload:s.allowDownload,publicFields:pe,siblingFiles:v,onNavigateToFile:(i)=>{c({to:"/share/$shareId/files/$fileId",params:{shareId:r,fileId:i}})},onNavigateBack:()=>{if(e&&e!==s.rootFolderId)c({to:"/share/$shareId/folders/$folderId",params:{shareId:r,folderId:e}});else c({to:"/share/$shareId",params:{shareId:r}})},onSelectVersion:(i)=>{c({to:"/share/$shareId/files/$fileId",params:{shareId:r,fileId:l},search:(N)=>({...N,version:i})})},onSaveField:()=>{}})}else y=g("div",{className:"flex flex-1 overflow-hidden relative",children:[l?g("div",{className:"flex-1 relative bg-muted/30",children:[Le&&!p&&a("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/50",children:a(K,{className:"h-8 w-8 animate-spin text-foreground"})}),p&&C&&k?a(mu,{isPublic:!0,shareId:r,versions:n?.versionStack?.versions??[],leftId:C,rightId:k,activeSide:Q,annotations:te,seekRequest:je,allowDownload:s.allowDownload,onActiveSideChange:(e)=>B({cmpActive:e}),onSwitchVersion:(e,t)=>B(e==="left"?{cmpLeft:t}:{cmpRight:t}),onExit:Be,onActiveAssetChange:Ae,onPlay:we,onTimeUpdate:se}):n&&a(Ns,{file:n,mediaControllerRef:P,onPlay:we,onTimeUpdate:se,onSeek:_e,annotations:te,startTime:O,shareId:r,allowDownload:s.allowDownload})]}):o&&(A?a(hu,{teamId:"",projectId:s.projectId,assetId:o,folders:h,files:v,totalFolders:Re,totalFiles:qe,totalFoldersSize:ze,totalFilesSize:Me,selectedItem:D,selectedIds:I,onItemSelect:(e,t)=>{if(t.metaKey||t.ctrlKey){let i=new Set(I);if(i.has(e.id)){if(i.delete(e.id),f(i),D?.id===e.id){let N=[...h,...v].find((H)=>i.has(H.id));u(N||null)}}else i.add(e.id),f(i),u(e)}else f(new Set([e.id])),u(e)},onItemDoubleClick:he,onClearSelection:()=>{f(new Set),u(null)},fetchNextFoldersPage:ae,hasNextFoldersPage:ne,isFetchingNextFoldersPage:ie,fetchNextFilesPage:ce,hasNextFilesPage:fe,isFetchingNextFilesPage:ue,isLoading:le||me,isShareView:!0,isPublic:!0,shareId:r,allowDownload:s.allowDownload}):a(wa,{teamId:"",projectId:s.projectId,assetId:o,folders:h,files:v,selectedItem:D,selectedIds:I,onItemSelect:(e,t)=>{if(t.metaKey||t.ctrlKey){let i=new Set(I);if(i.has(e.id)){if(i.delete(e.id),f(i),D?.id===e.id){let N=[...h,...v].find((H)=>i.has(H.id));u(N||null)}}else i.add(e.id),f(i),u(e)}else f(new Set([e.id])),u(e)},onItemDoubleClick:he,onSaveField:()=>{},displayStyle:s.viewMode??"card",onClearSelection:()=>{f(new Set),u(null)},fetchNextFoldersPage:ae,hasNextFoldersPage:ne,isFetchingNextFoldersPage:ie,fetchNextFilesPage:ce,hasNextFilesPage:fe,isFetchingNextFilesPage:ue,isLoading:le||me,isShareView:!0,isPublic:!0,shareId:r,sharePassword:d,allowDownload:s.allowDownload})),!U&&!A&&g(Y,{children:[a(Jr,{onResize:(e)=>Pe((t)=>Math.max(240,Math.min(600,t-e)))}),a("div",{style:{width:be},className:"flex-shrink-0 border-l",children:a(Ea,{teamId:"",projectId:s.projectId,file:p?oe:ge,onSaveField:()=>{},members:[],readOnly:!0,publicFields:pe,onCommentSelect:Ue,isPublic:!0,shareId:r,currentTime:Ce,onTyping:()=>{P.current?.pause()},selectedCommentId:ke,hideAnnotationControl:(p?oe:ge)?.proxyType==="audio"})})]})]});return g("div",{className:"flex h-[100dvh] flex-col bg-background",children:[(!A||!l)&&a(tm,{}),y]})}
2
+ export{ba};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{cc,uc}from"./chunk-mzsw9var.js";import{gm,Am,_m,af}from"./chunk-a411xhmm.js";function p(e){return`'${e.replaceAll("'","''")}'`}function f(e){return async(t)=>{if(t.length===0)return[];let n=(await e.batch(t.map((r)=>e.prepare(`PRAGMA index_list(${p(r)})`)))).flatMap((r,o)=>{let i=t[o];if(!i)return[];return r.results.map((u)=>({...u,tableName:i}))});if(n.length===0)return[];let l=await e.batch(n.map((r)=>e.prepare(`PRAGMA index_info(${p(r.name)})`)));return n.map((r,o)=>({columns:(l[o]?.results??[]).map((i)=>({fullLength:i.name!==null,name:i.name,position:i.seqno})),name:r.name,partial:r.partial!==0,table:r.tableName,unique:r.unique!==0,valid:!0}))}}var h=class extends uc{get supportsMultipleConnections(){return!0}},m=class{#e;#t;constructor(e){this.#e={...e}}async init(){if(this.#t=new w(this.#e.database),this.#e.onCreateConnection)await this.#e.onCreateConnection(this.#t)}async acquireConnection(){return this.#t}async beginTransaction(){throw Error("D1 does not support interactive transactions. Use the D1 batch() API instead.")}async commitTransaction(){throw Error("D1 does not support interactive transactions. Use the D1 batch() API instead.")}async rollbackTransaction(){throw Error("D1 does not support interactive transactions. Use the D1 batch() API instead.")}async releaseConnection(){}async destroy(){}},w=class{#e;constructor(e){this.#e=e}async executeQuery(e){let t=await this.#e.prepare(e.sql).bind(...e.parameters).all(),n=t.meta.changes!=null?BigInt(t.meta.changes):void 0;return{insertId:t.meta.last_row_id===void 0||t.meta.last_row_id===null?void 0:BigInt(t.meta.last_row_id),rows:t?.results||[],numAffectedRows:n}}async*streamQuery(){throw Error("D1 does not support streaming queries.")}},d=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").where("name","not like","_cf_%").select(["name","type"]).$castTo();if(!e.withInternalKyselyTables)t=t.where("name","!=",gm).where("name","!=",Am);let n=await t.execute();if(n.length===0)return[];let l=n.map((a)=>this.#t.prepare("SELECT * FROM pragma_table_info(?)").bind(a.name)),r=await this.#t.batch(l),o=n.flatMap((a,s)=>{let c=_m(r[s]?.results??[]);return c?[{index:s,tableName:a.name,column:c}]:[]}),i=o.length?await this.#t.batch(o.map(({tableName:a})=>this.#t.prepare(`PRAGMA index_list(${p(a)})`))):[],u=new Map(o.filter((a,s)=>!i[s]?.results?.some((c)=>c.origin==="pk")).map(({index:a,column:s})=>[a,s]));return n.map((a,s)=>af(a,r[s]?.results??[],u.get(s)))}async getMetadata(e){return{tables:await this.getTables(e)}}},y=class extends cc{},q=class{#e;constructor(e){this.#e={...e}}createDriver(){return new m(this.#e)}createQueryCompiler(){return new y}createAdapter(){return new h}createIntrospector(e){return new d(e,this.#e.database)}};export{q as D1SqliteDialect,f as createD1IndexIntrospector};
@@ -0,0 +1,10 @@
1
+ import{J,Q,S,G,M,w,Z,Y,a,g,ee,R,z,Ka,Be,cr,Er,Ol,Ue,Ge,F,Dn,Nn,Fn,Ln,$e,He,Qe,Gb,VE,mx,yh,EI,bk,Ik,Tk,YM,Pt,ha,pt,mt,ht,Fi,An,ar,Te}from"./chunk-zarz3sqn.js";import{ss,ro,un,dl}from"./chunk-55h9ze53.js";import{yu}from"./chunk-91rb0jpb.js";var Mt=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Gd=z("arrow-left",Mt);var At=[["path",{d:"m11 10 3 3",key:"fzmg1i"}],["path",{d:"M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z",key:"p4q2r7"}],["path",{d:"M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031",key:"wy6l02"}]],Le=z("brush",At);var Et=[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]],Se=z("redo",Et);var It=[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]],Pe=z("undo",It);Z();var Rt=["#ef4444","#f97316","#eab308","#22c55e","#3b82f6","#a855f7","#ec4899","#000000","#ffffff"],Bi=J(({projectId:h,onSendMessage:Fe,replyingTo:c,onCancelReply:ne,placeholder:_e,initialText:B="",value:A,onChangeText:E,disabled:pe=!1,allowMentions:ze,disableMentions:je=!1,allowAttachments:Oe=!0,workspaceAssets:x,onRemoveWorkspaceAsset:fe,allowMarkup:qe,hideAnnotationControl:We=!1,canMarkup:Ke=!0,markupDisabledTooltip:Ve,allowTimestamp:Xe=!0,currentTime:u,frameRate:m,startTimecode:ge,formatTimestamp:v,bottomLeftExtra:Je,isStreaming:oe=!1,onAbort:Ye,onTyping:I},Ze)=>{let[p,D]=w([]),[re,H]=w(null),[f,et]=w(!0),L=ze??!je,tt=qe??!We,T=Xe,{videoTimeDisplayMode:O}=ar(),nt=G(()=>{if(u===void 0)return"";if(v)return v(u);if(!m)return"";let e=Math.round(u*m);return ro(e,m,O,ge)},[u,m,O,ge,v]),{teamId:q,ensureTeamIdForProject:be}=Pt(),{members:he,loading:xe,fetchMembers:ot,fetchProjectMembers:rt}=An();S(()=>{if(h&&!q)be(h)},[h,q,be]);let{isDrawing:at,setIsDrawing:P,currentTool:W,setTool:K,currentColor:ve,setColor:st,undo:lt,redo:it,history:ct,historyIndex:ye,annotations:ae,reset:we}=un(),[se,y]=w(!1),[le,dt]=w(""),[U,_]=w(0),[b,Ne]=w({bots:!1,users:!1}),[ie,N]=w(!1),ut=G(()=>{if(!f||!T||u===void 0||!v&&!m||ie)return"";if(O==="timecode")return"pl-[120px]";return"pl-[85px]"},[f,T,u,m,ie,O,v]),r=M(null),V=M(null),k=M(null),ke=M(null),C=M(!1),{mutateAsync:Ce}=ee({mutationFn:async({projectId:e,data:t})=>{let n=await R.api.projects[":projectId"].attachments.$post({param:{projectId:e},json:t});if(!n.ok)throw Error("Failed to create attachment");return await n.json()}});S(()=>{if(A!==void 0&&r.current){if(C.current){C.current=!1;return}if(r.current.innerText!==A)r.current.innerText=A,N(!!A.trim())}else if(B&&r.current){r.current.innerText=B,N(!!B.trim()),r.current.focus();let e=document.createRange(),t=window.getSelection();e.selectNodeContents(r.current),e.collapse(!1),t?.removeAllRanges(),t?.addRange(e)}},[A,B]);let ce=M(null),Me=Q((e)=>{if(!r.current)return;let t=document.createElement("span");t.contentEditable="false",t.dataset.type="mention",t.dataset.id=e.id,t.className="inline-block bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-sm font-medium align-middle select-none mx-0.5",t.innerText=`@${e.name}`;let n=document.createTextNode(" ");r.current.appendChild(t),r.current.appendChild(n);let s=document.createRange(),l=window.getSelection();s.setStartAfter(n),s.collapse(!0),l?.removeAllRanges(),l?.addRange(s),N(!0);let o=r.current.innerText||"";C.current=!0,E?.(o),I?.(),r.current.focus()},[E,I]);S(()=>{if(c&&r.current){if(c.id!==ce.current){if(ce.current=c.id,L&&c.creator?.id&&c.creator?.name){let n=r.current.querySelectorAll('span[data-type="mention"]');if(!Array.from(n).some((l)=>l.dataset.id===c.creator.id)){Me({id:c.creator.id,name:c.creator.name});return}}}r.current.focus();let e=document.createRange(),t=window.getSelection();e.selectNodeContents(r.current),e.collapse(!1),t?.removeAllRanges(),t?.addRange(e)}else if(!c)ce.current=null},[c,L,Me]),S(()=>()=>{P(!1)},[P]);let j=he.filter((e)=>e.type==="agent"&&e.name?.toLowerCase().startsWith(le.toLowerCase())).map((e)=>({type:"user",data:e})),X=he.filter((e)=>e.type!=="agent"&&e.name?.toLowerCase().startsWith(le.toLowerCase())).map((e)=>({type:"user",data:e})),te=[...b.bots?[]:j,...b.users?[]:X];S(()=>{_(0)},[le,se,b]),S(()=>{ke.current?.querySelector(`[data-index="${U}"]`)?.scrollIntoView({block:"nearest"})},[U]);let Ae=(e)=>e.split(" ").map((t)=>t[0]).slice(0,2).join("").toUpperCase(),Ee=()=>{if(!r.current)return;let e=r.current.innerText||"";if(N(!!e.trim()),C.current=!0,E?.(e),I?.(),!L){y(!1),k.current=null;return}let t=window.getSelection();if(!t||t.rangeCount===0)return;let n=t.getRangeAt(0),{startContainer:s,startOffset:l}=n;if(s.nodeType===Node.TEXT_NODE){let i=(s.textContent||"").slice(0,l),d=i.lastIndexOf("@");if(d!==-1){let kt=d===0,Ct=i[d-1];if(kt||/\s/.test(Ct)){let De=i.slice(d+1);if(!/\s/.test(De)){if(dt(De),y(!0),h)rt(h,!0,!0);else if(q)ot(q,!0,!0);let me=document.createRange();me.setStart(s,d),me.setEnd(s,l),k.current=me;return}}}}y(!1),k.current=null},de=(e)=>{if(!k.current||!r.current)return;let t=k.current;t.deleteContents();let n=document.createElement("span");n.contentEditable="false",n.dataset.type="mention",n.dataset.id=e.data.id,n.className="inline-block bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-sm font-medium align-middle select-none mx-0.5",n.innerText=`@${e.data.name}`,t.insertNode(n);let s=document.createTextNode(" ");n.after(s);let l=document.createRange(),o=window.getSelection();l.setStartAfter(s),l.collapse(!0),o?.removeAllRanges(),o?.addRange(l),y(!1),k.current=null,N(!0);let i=r.current.innerText||"";C.current=!0,E?.(i),I?.(),r.current.focus()},ft=(e)=>{e.preventDefault();let t=e.clipboardData.getData("text/plain");if(!t)return;let n=window.getSelection();if(!n||n.rangeCount===0||!r.current?.contains(n.anchorNode)){if(r.current){r.current.focus();let l=document.createRange();l.selectNodeContents(r.current),l.collapse(!1),n=window.getSelection(),n?.removeAllRanges(),n?.addRange(l)}}if(!(typeof document.execCommand==="function"&&document.queryCommandSupported?.("insertText")&&document.execCommand("insertText",!1,t))){let l=window.getSelection();if(l&&l.rangeCount>0){let o=l.getRangeAt(0);o.deleteContents();let i=document.createTextNode(t);o.insertNode(i),o.setStartAfter(i),o.collapse(!0),l.removeAllRanges(),l.addRange(o)}else if(r.current)r.current.innerText+=t}Ee()},gt=(e)=>{if(e.nativeEvent.isComposing)return;if(se&&L&&te.length>0){if(e.key==="ArrowUp"){e.preventDefault(),_((t)=>t>0?t-1:te.length-1);return}if(e.key==="ArrowDown"){e.preventDefault(),_((t)=>t<te.length-1?t+1:0);return}if(e.key==="Enter"||e.key==="Tab"){e.preventDefault(),de(te[U]);return}if(e.key==="Escape"){e.preventDefault(),y(!1);return}}if(e.key==="Enter"&&!e.shiftKey)e.preventDefault(),Ie()},bt=Q(async(e)=>{if(!e.target.files)return;let t=Array.from(e.target.files);for(let n of t){let s=`${Date.now()}-${n.name}`,l={id:s,file:n,progress:0};D((o)=>[...o,l]);try{let o=await Ce({projectId:h,data:{fileName:n.name,contentType:n.type,size:n.size}});if(o.uploadUrl&&o.id)await fetch(o.uploadUrl,{method:"PUT",body:n,headers:{"Content-Type":n.type}}),D((i)=>i.map((d)=>d.id===s?{...d,progress:100,attachmentId:o.id}:d))}catch(o){D((i)=>i.map((d)=>d.id===s?{...d,error:o instanceof Error?o.message:"Upload failed"}:d))}}if(V.current)V.current.value=""},[h,Ce]),xt=(e)=>{D((t)=>t.filter((n)=>n.id!==e))},Ie=()=>{if(!r.current)return;if(p.some((o)=>!o.attachmentId&&!o.error))return;let t=p.map((o)=>o.attachmentId).filter((o)=>!!o),n=p.filter((o)=>!o.error&&!!o.attachmentId).map((o)=>({id:o.attachmentId,name:o.file.name,type:o.file.type,url:o.file.type.startsWith("image/")||Fi(o.file.name)?URL.createObjectURL(o.file):void 0})),s="";r.current.childNodes.forEach((o)=>{if(o.nodeType===Node.TEXT_NODE)s+=o.textContent;else if(o.nodeType===Node.ELEMENT_NODE){let i=o;if(i.dataset.type==="mention")s+=`<@${i.dataset.id}>`;else if(i.tagName==="BR")s+=`
2
+ `;else if(i.tagName==="DIV"||i.tagName==="P")s+=`
3
+ `+i.innerText;else s+=i.innerText}}),s=s.trim();let l=(x?.length??0)>0;if(!s&&t.length===0&&ae.length===0&&!l)return;if(Fe(s,t,ae,c?.id,T&&f?u:void 0,n),r.current.innerHTML="",N(!1),C.current=!0,E?.(""),D([]),H(null),P(!1),we(),y(!1),ne)ne()},ue=p.some((e)=>!e.attachmentId&&!e.error),vt=p.some((e)=>!!e.attachmentId),yt=(x?.length??0)>0,wt=pe||oe,Re=(ie||vt||ae.length>0||yt)&&!wt,Nt=x&&x.length>0||p.length>0||!!c;return g("div",{ref:Ze,className:"relative flex flex-col w-full border border-foreground/35 rounded-3xl shadow-sm transition-all duration-200 bg-background",children:[a("style",{children:`
4
+ [contenteditable]:empty:before {
5
+ content: attr(data-placeholder);
6
+ color: #9ca3af;
7
+ cursor: text;
8
+ }
9
+ `}),se&&L&&(xe||j.length>0||X.length>0)&&a("div",{onMouseDown:(e)=>e.preventDefault(),className:"absolute bottom-full left-4 mb-2 w-64 rounded-xl shadow-lg border border-border overflow-hidden z-20 bg-popover text-popover-foreground animate-in fade-in slide-in-from-bottom-2 duration-200",children:a("div",{ref:ke,className:"h-64 overflow-y-auto",children:xe?g("div",{className:"p-2 space-y-4 animate-pulse",children:[g("div",{className:"space-y-2",children:[a("div",{className:"px-3 py-1.5 bg-muted/50 border-b border-border",children:a(Te,{className:"h-3 w-16"})}),g("div",{className:"flex items-center gap-2 px-3 py-2",children:[a(Te,{className:"w-6 h-6 rounded-full"}),a(Te,{className:"h-4 w-28"})]}),g("div",{className:"flex items-center gap-2 px-3 py-2",children:[a(Te,{className:"w-6 h-6 rounded-full"}),a(Te,{className:"h-4 w-20"})]})]}),g("div",{className:"space-y-2",children:[a("div",{className:"px-3 py-1.5 bg-muted/50 border-b border-border",children:a(Te,{className:"h-3 w-16"})}),g("div",{className:"flex items-center gap-2 px-3 py-2",children:[a(Te,{className:"w-6 h-6 rounded-full"}),a(Te,{className:"h-4 w-32"})]}),g("div",{className:"flex items-center gap-2 px-3 py-2",children:[a(Te,{className:"w-6 h-6 rounded-full"}),a(Te,{className:"h-4 w-24"})]})]})]}):g(Y,{children:[j.length>0&&g(Y,{children:[g("button",{type:"button",onMouseDown:(e)=>e.preventDefault(),onClick:(e)=>{e.preventDefault(),e.stopPropagation(),Ne((t)=>({...t,bots:!t.bots})),r.current?.focus()},className:"w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border flex items-center justify-between hover:bg-muted transition-colors cursor-pointer select-none",children:[a("span",{children:"Agents"}),a(Be,{className:`w-3 h-3 transition-transform ${b.bots?"-rotate-90":""}`})]}),!b.bots&&j.map((e,t)=>{let n=t;return g("button",{type:"button","data-index":n,onMouseDown:(s)=>s.preventDefault(),onClick:()=>de(e),onMouseEnter:()=>_(n),className:`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left cursor-pointer ${n===U?"bg-accent text-accent-foreground":"hover:bg-accent/50"}`,children:[g($e,{className:"w-6 h-6",children:[e.type==="user"&&e.data.image&&a(He,{src:e.data.image,alt:e.data.name,className:"object-cover"}),a(Qe,{className:"text-[10px] bg-purple-400 text-black font-semibold",children:Ae(e.data.name)})]}),a("span",{className:"text-sm",children:e.data.name})]},e.data.id)})]}),X.length>0&&g(Y,{children:[g("button",{type:"button",onMouseDown:(e)=>e.preventDefault(),onClick:(e)=>{e.preventDefault(),e.stopPropagation(),Ne((t)=>({...t,users:!t.users})),r.current?.focus()},className:"w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border flex items-center justify-between hover:bg-muted transition-colors cursor-pointer select-none",children:[a("span",{children:"Members"}),a(Be,{className:`w-3 h-3 transition-transform ${b.users?"-rotate-90":""}`})]}),!b.users&&X.map((e,t)=>{let n=b.bots?0:j.length,s=t+n;return g("button",{type:"button","data-index":s,onMouseDown:(l)=>l.preventDefault(),onClick:()=>de(e),onMouseEnter:()=>_(s),className:`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left cursor-pointer ${s===U?"bg-accent text-accent-foreground":"hover:bg-accent/50"}`,children:[g($e,{className:"w-6 h-6",children:[e.type==="user"&&e.data.image&&a(He,{src:e.data.image,alt:e.data.name,className:"object-cover"}),a(Qe,{className:"text-[10px] bg-purple-400 text-black font-semibold",children:Ae(e.data.name)})]}),a("span",{className:"text-sm",children:e.data.name})]},e.data.id)})]})]})})}),Nt&&g("div",{className:"flex flex-col gap-2 p-3 pb-0 animate-in fade-in slide-in-from-bottom-2 duration-200",children:[x&&x.length>0&&a("div",{className:"flex flex-col gap-1.5 min-h-0 max-h-[160px] overflow-y-auto border border-border/60 rounded-lg bg-muted/20 p-2.5 divide-y divide-border/50",children:x.map((e)=>g("div",{className:"flex items-center justify-between py-1 text-xs group",children:[g("div",{className:"flex items-baseline gap-1.5 min-w-0 pr-2",children:[a("span",{className:"truncate font-medium text-foreground",children:e.name}),a("span",{className:"text-[9px] text-muted-foreground uppercase flex-shrink-0",children:e.type})]}),fe&&a("button",{onClick:()=>fe(e.id),className:"text-muted-foreground hover:text-destructive transition-colors p-0.5 cursor-pointer",title:bk?.()||"Remove from context",children:a(Ue,{className:"h-3.5 w-3.5"})})]},e.id))}),c&&g("div",{className:"flex items-center justify-between bg-muted p-2 px-3 rounded-lg border border-border",children:[a("div",{className:"text-xs text-muted-foreground truncate mr-2",children:Tk({message:c.message||""})}),a("button",{onClick:ne,className:"text-muted-foreground hover:text-foreground p-1 rounded-full hover:bg-muted-foreground/10 shrink-0",children:a(Ge,{className:"w-3.5 h-3.5"})})]}),p.length>0&&a("div",{className:"flex gap-3 overflow-x-auto py-2 px-1 scrollbar-hide",children:p.map((e)=>g("div",{className:"relative group flex-shrink-0",children:[g("div",{className:"w-16 h-16 rounded-lg border border-gray-200 overflow-hidden bg-gray-50 flex items-center justify-center",children:[e.file.type.startsWith("image/")?a("img",{src:URL.createObjectURL(e.file),alt:"preview",onClick:()=>H(e.file),className:`w-full h-full object-cover ${!e.attachmentId?"opacity-50":""}`}):a(Er,{className:"w-8 h-8 text-gray-400"}),ue&&!e.attachmentId&&!e.error&&a("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:a(dl,{progress:e.progress,className:"w-10 h-10"})})]}),a("button",{onClick:()=>xt(e.id),className:"absolute -top-1.5 -right-1.5 bg-gray-500 text-white rounded-full p-0.5 shadow-md opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-500 z-10 cursor-pointer",children:a(Ge,{className:"w-3 h-3"})}),a("span",{className:"text-[10px] text-gray-500 mt-1 block max-w-[4rem] truncate text-center",children:e.file.name})]},e.id))})]}),g("div",{onClick:()=>r.current?.focus(),className:"w-full px-4 pt-1 pb-1 cursor-text flow-root max-h-60 overflow-y-auto",children:[T&&f&&u!==void 0&&(m!==void 0||v!==void 0)&&a("div",{onClick:(e)=>{e.stopPropagation(),r.current?.focus()},className:"float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-2.5 py-0.5 mt-3 mr-2 rounded-sm text-xs font-mono font-bold flex items-center gap-1 cursor-text",children:nt}),a("div",{ref:r,contentEditable:!pe&&!oe,suppressContentEditableWarning:!0,onInput:Ee,onKeyDown:gt,onPaste:ft,"data-placeholder":_e||(c?Ik():EI()),className:`bg-transparent border-none focus:ring-0 resize-none min-h-[40px] leading-relaxed py-2 focus:outline-none block whitespace-pre-wrap break-words ${ut}`})]}),g("div",{className:"flex justify-between items-center px-2 pb-2",children:[at?g("div",{className:"flex items-center gap-2 overflow-x-auto scrollbar-hide w-full mr-2",children:[a(F,{onClick:()=>{P(!1),we()},variant:"ghost",size:"icon",className:"p-2 rounded-full cursor-pointer text-gray-500 hover:text-gray-700 hover:bg-gray-100 mr-2",title:"Back",children:a(Gd,{className:"w-4 h-4"})}),a("div",{className:"h-4 w-px bg-gray-300 mx-1"}),a("button",{onClick:()=>K("arrow"),className:`p-1.5 rounded hover:bg-gray-100 ${W==="arrow"?"text-blue-500 bg-blue-50":"text-gray-500"}`,title:"Arrow",children:a(Ka,{size:16,className:"rotate-45"})}),a("button",{onClick:()=>K("line"),className:`p-1.5 rounded hover:bg-gray-100 ${W==="line"?"text-blue-500 bg-blue-50":"text-gray-500"}`,title:"Line",children:a(ss,{size:16,className:"-rotate-45"})}),a("button",{onClick:()=>K("box"),className:`p-1.5 rounded hover:bg-gray-100 ${W==="box"?"text-blue-500 bg-blue-50":"text-gray-500"}`,title:"Box",children:a(yu,{size:16})}),a("button",{onClick:()=>K("freehand"),className:`p-1.5 rounded hover:bg-gray-100 ${W==="freehand"?"text-blue-500 bg-blue-50":"text-gray-500"}`,title:"Freehand",children:a(Le,{size:16})}),a("div",{className:"h-4 w-px bg-gray-300 mx-1"}),g(pt,{children:[a(mt,{asChild:!0,children:g("button",{className:"flex items-center gap-1 p-1 rounded hover:bg-gray-100",children:[a("div",{className:"w-4 h-4 rounded-full border border-gray-200",style:{backgroundColor:ve}}),a(Be,{size:12,className:"text-gray-500"})]})}),a(ht,{className:"w-auto p-2",align:"center",side:"top",children:a("div",{className:"flex items-center gap-1",children:Rt.map((e)=>a("button",{onClick:()=>st(e),className:`w-6 h-6 rounded-full border border-gray-200 transition-transform hover:scale-110 ${ve===e?"ring-2 ring-blue-500 ring-offset-1":""}`,style:{backgroundColor:e}},e))})})]}),a("div",{className:"h-4 w-px bg-gray-300 mx-1"}),a("button",{onClick:lt,disabled:ye<=0,className:"p-1.5 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed text-gray-500",children:a(Pe,{size:16})}),a("button",{onClick:it,disabled:ye>=ct.length-1,className:"p-1.5 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed text-gray-500",children:a(Se,{size:16})})]}):g("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[80%]",children:[Je,Oe&&g(Y,{children:[a("input",{type:"file",ref:V,className:"hidden",multiple:!0,onChange:bt}),a(F,{onClick:()=>V.current?.click(),className:"p-2 rounded-full cursor-pointer shrink-0",variant:"ghost",size:"icon",title:Gb(),children:a(Ol,{className:"w-4 h-4"})})]}),T&&u!==void 0&&(m!==void 0||v!==void 0)&&a(F,{onClick:()=>et(!f),variant:f?"secondary":"ghost",size:"icon",className:`p-2 rounded-full cursor-pointer shrink-0 ${f?"text-blue-600 bg-blue-50 dark:bg-blue-900/20":""}`,title:f?VE():mx(),children:a(cr,{className:"w-4 h-4"})}),tt&&(Ke?a(F,{onClick:()=>{I?.(),P(!0)},variant:"ghost",size:"icon",className:"p-2 rounded-full cursor-pointer shrink-0",title:YM(),children:a(ha,{className:"w-4 h-4"})}):a(Dn,{children:g(Nn,{children:[a(Fn,{asChild:!0,children:a("span",{className:"inline-block cursor-not-allowed shrink-0",children:a(F,{disabled:!0,variant:"ghost",size:"icon",className:"p-2 rounded-full opacity-40 cursor-not-allowed pointer-events-none",children:a(ha,{className:"w-4 h-4"})})})}),a(Ln,{side:"top",children:a("p",{className:"text-xs",children:Ve||yh()})})]})}))]}),oe?a("button",{onClick:Ye,className:"p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 shadow-sm bg-destructive text-destructive-foreground hover:bg-destructive/90 transform hover:-translate-y-0.5 cursor-pointer",title:"Stop generation",children:a("div",{className:"h-4 w-4 flex items-center justify-center",children:a("div",{className:"h-3 w-3 rounded-[2px] bg-white"})})}):a("button",{onClick:Ie,disabled:!Re||ue,className:`p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 ${Re&&!ue?"bg-blue-600 text-white shadow-md hover:bg-blue-700 hover:shadow-lg transform hover:-translate-y-0.5 cursor-pointer":"bg-gray-400 cursor-not-allowed opacity-50"}`,children:a(Ka,{className:"w-4 h-4"})})]}),re&&g("div",{className:"fixed inset-0 z-[100] bg-black/95 flex flex-col items-center justify-center p-4 animate-in fade-in duration-200",onClick:()=>H(null),children:[a("button",{className:"absolute top-4 right-4 text-white/70 hover:text-white hover:bg-white/20 rounded-full p-2 transition-colors z-50",children:a(Ge,{className:"w-8 h-8"})}),a("div",{className:"w-full h-full flex items-center justify-center p-2",children:a("img",{src:URL.createObjectURL(re),alt:"Enlarged view",className:"max-w-full max-h-[85vh] object-contain rounded shadow-2xl cursor-zoom-out",onClick:(e)=>{e.stopPropagation(),H(null)}})}),a("div",{className:"absolute bottom-6 text-white text-sm font-medium bg-black/50 px-4 py-2 rounded-full backdrop-blur-sm",children:re.name})]})]})});Bi.displayName="ChatInput";
10
+ export{Gd,Bi};